Repository: rongcloud/websdk-demo Branch: master Commit: a4c6aeb29599 Files: 578 Total size: 27.0 MB Directory structure: gitextract_ajuhcao0/ ├── .gitignore ├── LICENSE ├── README.md ├── api-test/ │ ├── .gitignore │ ├── README.md │ ├── config.js │ ├── index.html │ ├── js/ │ │ ├── common/ │ │ │ ├── api-list.js │ │ │ ├── service.js │ │ │ └── utils.js │ │ ├── components/ │ │ │ ├── button.js │ │ │ ├── json-alert.js │ │ │ └── msg-expansion.js │ │ ├── login.js │ │ └── main.js │ ├── lib/ │ │ ├── js/ │ │ │ ├── RongIMLib-3.0.0.js │ │ │ ├── RongIMLib-3.0.3.js │ │ │ ├── RongIMLib-3.0.5-mentioned.js │ │ │ ├── RongIMLib-3.0.6.js │ │ │ ├── es6-promise.js │ │ │ ├── vue-2.6.10.js │ │ │ └── vue-json-pretty.js │ │ └── styles/ │ │ ├── dragula-3.7.2.css │ │ └── iview.css │ └── styles/ │ ├── main.css │ └── main.scss ├── api-test-v2/ │ ├── .gitignore │ ├── README.md │ ├── config.js │ ├── debug.html │ ├── index.html │ ├── js/ │ │ ├── common/ │ │ │ ├── api-list.js │ │ │ ├── service.js │ │ │ └── utils.js │ │ ├── components/ │ │ │ ├── button.js │ │ │ └── json-alert.js │ │ ├── login.js │ │ └── main.js │ ├── lib/ │ │ ├── js/ │ │ │ ├── RongIMLib-2.3.1-revise-20200311-222.js │ │ │ ├── RongIMLib-2.3.1-revise-20200311.js │ │ │ ├── RongIMLib-2.3.5-bugfix-zhiyuan-20190408.js │ │ │ ├── RongIMLib-2.5.1.js │ │ │ ├── RongIMLib-2.5.3.js │ │ │ ├── RongIMLib-2.5.4.js │ │ │ ├── RongIMLib-2.5.5-private.js │ │ │ ├── RongIMLib-2.5.5.js │ │ │ ├── RongIMLib-2.5.6.js │ │ │ ├── RongIMLib-2.5.9-release.js │ │ │ ├── RongIMLib-2.5.9-silent.js │ │ │ ├── RongIMLib.js │ │ │ ├── es6-promise.js │ │ │ ├── vue-2.6.10.js │ │ │ └── vue-json-pretty.js │ │ └── styles/ │ │ ├── dragula-3.7.2.css │ │ └── iview.css │ └── styles/ │ ├── main.css │ └── main.scss ├── api-test-v4/ │ ├── README.md │ ├── config.js │ ├── index.html │ ├── js/ │ │ ├── common/ │ │ │ ├── api-list.js │ │ │ ├── service.js │ │ │ └── utils.js │ │ ├── components/ │ │ │ ├── button.js │ │ │ ├── json-alert.js │ │ │ └── msg-expansion.js │ │ ├── login.js │ │ └── main.js │ ├── lib/ │ │ ├── js/ │ │ │ ├── RongIMLib-4.1.0.js │ │ │ ├── RongIMLib-4.2.0.js │ │ │ ├── es6-promise.js │ │ │ ├── vue-2.6.10.js │ │ │ └── vue-json-pretty.js │ │ └── styles/ │ │ ├── dragula-3.7.2.css │ │ └── iview.css │ └── styles/ │ ├── main.css │ └── main.scss ├── api-test.html ├── calllib-v2/ │ ├── README.md │ ├── demo.js │ ├── group.html │ ├── init.js │ ├── private.html │ ├── style/ │ │ └── main.css │ └── user-media.html ├── calllib-v3/ │ ├── README.md │ ├── docs/ │ │ ├── ready.md │ │ ├── server.md │ │ ├── show.md │ │ └── web.md │ ├── private.html │ ├── server/ │ │ ├── index.js │ │ ├── package.json │ │ └── setting.js │ ├── web/ │ │ ├── css/ │ │ │ ├── main.css │ │ │ └── main.scss │ │ ├── index.html │ │ ├── js/ │ │ │ ├── call.js │ │ │ ├── common/ │ │ │ │ ├── init.js │ │ │ │ └── utils.js │ │ │ ├── dialog.js │ │ │ ├── login.js │ │ │ └── main.js │ │ ├── lib/ │ │ │ ├── vue-2.6.7.js │ │ │ └── vue-router-3.0.2.js │ │ └── setting.js │ ├── web-ie/ │ │ ├── README.md │ │ ├── css/ │ │ │ ├── main.css │ │ │ └── main.scss │ │ ├── index.html │ │ ├── js/ │ │ │ ├── call.js │ │ │ ├── common/ │ │ │ │ ├── init.js │ │ │ │ └── utils.js │ │ │ ├── dialog.js │ │ │ ├── login.js │ │ │ └── main.js │ │ ├── lib/ │ │ │ ├── RongCallLib.3.1.5.js │ │ │ ├── RongIMLib-2.5.1.js │ │ │ ├── RongRTC-IE-3.0.4.js │ │ │ ├── promise.js │ │ │ ├── vue-2.6.7.js │ │ │ └── vue-router-3.0.2.js │ │ └── setting.js │ └── web-im-v3/ │ ├── css/ │ │ ├── main.css │ │ └── main.scss │ ├── index.html │ ├── js/ │ │ ├── call.js │ │ ├── common/ │ │ │ ├── init.js │ │ │ └── utils.js │ │ ├── dialog.js │ │ ├── login.js │ │ └── main.js │ ├── lib/ │ │ ├── vue-2.6.7.js │ │ └── vue-router-3.0.2.js │ └── setting.js ├── chameleon/ │ ├── README.md │ ├── chameleon.config.js │ ├── dist/ │ │ └── wx/ │ │ ├── app.js │ │ ├── app.json │ │ ├── app.wxss │ │ ├── pages/ │ │ │ └── index/ │ │ │ ├── index.js │ │ │ ├── index.json │ │ │ └── index.wxml │ │ └── static/ │ │ └── js/ │ │ ├── app.js │ │ ├── common.js │ │ ├── manifest.js │ │ └── pages/ │ │ └── index/ │ │ └── index.js │ ├── mock/ │ │ ├── api/ │ │ │ └── index.js │ │ └── template/ │ │ └── index.php │ ├── npm-shrinkwrap.json │ ├── package.json │ └── src/ │ ├── app/ │ │ └── app.cml │ ├── assets/ │ │ └── js/ │ │ └── RongIMLib-2.4.0.js │ ├── components/ │ │ └── demo-com/ │ │ └── demo-com.cml │ ├── pages/ │ │ └── index/ │ │ └── index.cml │ ├── router.config.json │ └── store/ │ ├── actions.js │ ├── getters.js │ ├── index.js │ ├── mutations.js │ └── state.js ├── chatroom/ │ ├── chatroom.html │ ├── chatroom.js │ ├── chatroom.sdk.js │ └── demo.html ├── chatroom-h5/ │ ├── README.md │ ├── demo.html │ ├── js/ │ │ ├── RongIMLib-2.5.12.js │ │ ├── chatroom.js │ │ ├── demo.js │ │ ├── like.js │ │ ├── mock.js │ │ └── render.js │ └── style/ │ └── chatroom.css ├── chatroom-h5-gif/ │ ├── README.md │ ├── demo.html │ ├── js/ │ │ ├── RongIMLib-2.5.12.js │ │ ├── chatroom.js │ │ ├── demo.js │ │ ├── like.js │ │ ├── mock.js │ │ └── render.js │ └── style/ │ └── chatroom.css ├── chrm-kv-demo/ │ ├── README.md │ ├── css/ │ │ ├── main.css │ │ └── main.scss │ ├── index.html │ ├── js/ │ │ ├── init.js │ │ ├── main.js │ │ └── utils.js │ └── setting.js ├── common-im/ │ ├── css/ │ │ ├── common.css │ │ └── main.css │ ├── index.html │ └── js/ │ └── service.js ├── connect-check.html ├── cs/ │ ├── jx/ │ │ ├── .gitignore │ │ ├── .project │ │ ├── Gruntfile.js │ │ ├── README.md │ │ ├── RongIMemoji.js │ │ ├── cs.css │ │ ├── cs.html │ │ ├── cs.js │ │ ├── dist/ │ │ │ └── cs.html │ │ ├── emoji.js │ │ ├── package.json │ │ ├── phiz.js │ │ ├── qiniu-upload.js │ │ ├── template.js │ │ ├── templates/ │ │ │ ├── button.html │ │ │ ├── chat.html │ │ │ ├── closebefore.html │ │ │ ├── conversation.html │ │ │ ├── endconversation.html │ │ │ ├── evaluate.html │ │ │ ├── imageView.html │ │ │ ├── import.html │ │ │ ├── leaveword.html │ │ │ ├── main.html │ │ │ ├── message.html │ │ │ ├── messageTemplate.html │ │ │ └── userInfo.html │ │ ├── ui.html │ │ └── utils.js │ └── sobot/ │ ├── .gitignore │ ├── Gruntfile.js │ ├── README.md │ ├── RongIMEmoji.js │ ├── cs.css │ ├── cs.html │ ├── cs.js │ ├── dist/ │ │ └── cs.html │ ├── emoji.js │ ├── package.json │ ├── qiniu.js │ ├── template.js │ ├── templates/ │ │ ├── button.html │ │ ├── chat.html │ │ ├── closebefore.html │ │ ├── conversation.html │ │ ├── endconversation.html │ │ ├── evaluate.html │ │ ├── evaluateItem.html │ │ ├── imageView.html │ │ ├── import.html │ │ ├── leaveword.html │ │ ├── main.html │ │ ├── message.html │ │ ├── messageTemplate.html │ │ └── userInfo.html │ ├── test.html │ ├── ui.html │ ├── upload.js │ └── utils.js ├── desktop/ │ ├── downloadExtra.html │ ├── file.html │ ├── index.html │ ├── screenshot.html │ ├── system.html │ └── window.html ├── electron/ │ ├── desktop_share.html │ ├── init.js │ ├── main.js │ ├── normal.html │ ├── package.json │ ├── requirejs-in-node.html │ ├── sdk/ │ │ ├── RongIMLib-2.3.3.js │ │ ├── RongIMLib-2.5.1.js │ │ └── init.js │ └── user_media.html ├── electron-vue/ │ ├── .babelrc │ ├── .electron-vue/ │ │ ├── build.js │ │ ├── dev-client.js │ │ ├── dev-runner.js │ │ ├── webpack.main.config.js │ │ ├── webpack.renderer.config.js │ │ └── webpack.web.config.js │ ├── .eslintignore │ ├── .eslintrc.js │ ├── .gitignore │ ├── .travis.yml │ ├── README.md │ ├── appveyor.yml │ ├── package.json │ ├── src/ │ │ ├── index.ejs │ │ ├── main/ │ │ │ ├── index.dev.js │ │ │ └── index.js │ │ └── renderer/ │ │ ├── App.vue │ │ ├── assets/ │ │ │ └── .gitkeep │ │ ├── components/ │ │ │ └── Init.vue │ │ ├── main.js │ │ ├── router/ │ │ │ └── index.js │ │ └── store/ │ │ ├── index.js │ │ └── modules/ │ │ ├── Counter.js │ │ └── index.js │ ├── static/ │ │ ├── .gitkeep │ │ └── js/ │ │ ├── RongEmoji-2.2.7.js │ │ └── RongIMLib-2.5.1.js │ └── test/ │ ├── .eslintrc │ ├── e2e/ │ │ ├── index.js │ │ ├── specs/ │ │ │ └── Launch.spec.js │ │ └── utils.js │ └── unit/ │ ├── index.js │ ├── karma.conf.js │ └── specs/ │ └── LandingPage.spec.js ├── electron-vue-sdk-v3/ │ ├── .babelrc │ ├── .electron-vue/ │ │ ├── build.js │ │ ├── dev-client.js │ │ ├── dev-runner.js │ │ ├── webpack.main.config.js │ │ ├── webpack.renderer.config.js │ │ └── webpack.web.config.js │ ├── .eslintignore │ ├── .eslintrc.js │ ├── .gitignore │ ├── .travis.yml │ ├── README.md │ ├── appveyor.yml │ ├── package.json │ ├── src/ │ │ ├── index.ejs │ │ ├── main/ │ │ │ ├── index.dev.js │ │ │ └── index.js │ │ └── renderer/ │ │ ├── App.vue │ │ ├── assets/ │ │ │ └── .gitkeep │ │ ├── components/ │ │ │ └── Init.vue │ │ ├── main.js │ │ ├── router/ │ │ │ └── index.js │ │ └── store/ │ │ ├── index.js │ │ └── modules/ │ │ ├── Counter.js │ │ └── index.js │ ├── static/ │ │ ├── .gitkeep │ │ └── js/ │ │ ├── RongEmoji-2.2.7.js │ │ ├── RongIMLib-2.5.1.js │ │ └── RongIMLib-3.0.1-dev.es.js │ └── test/ │ ├── .eslintrc │ ├── e2e/ │ │ ├── index.js │ │ ├── specs/ │ │ │ └── Launch.spec.js │ │ └── utils.js │ └── unit/ │ ├── index.js │ ├── karma.conf.js │ └── specs/ │ └── LandingPage.spec.js ├── emoji.html ├── faq.md ├── histroy-messages.html ├── im/ │ ├── .gitignore │ ├── Gruntfile.js │ ├── README.md │ ├── emoji.js │ ├── im.css │ ├── im.html │ ├── im.js │ ├── libs/ │ │ ├── RongEmoji.js │ │ ├── qiniu-upload.js │ │ └── utils.js │ ├── package.json │ ├── template.js │ └── templates/ │ ├── button.html │ ├── chat.html │ ├── closebefore.html │ ├── conversation.html │ ├── endconversation.html │ ├── evaluate.html │ ├── imMain.html │ ├── imMessage.html │ ├── imMessageTemplate.html │ ├── imageView.html │ ├── import.html │ ├── leaveword.html │ ├── main.html │ ├── message.html │ ├── messageTemplate.html │ └── userInfo.html ├── im-ui-mod/ │ ├── component-ui.css │ ├── reset.css │ └── ui.html ├── init-muti.html ├── init-muti.js ├── init.js ├── integrate/ │ ├── chat/ │ │ ├── chat-guide.html │ │ ├── chat.css │ │ ├── chat.html │ │ ├── chat.js │ │ └── chat.json │ ├── conversation-list/ │ │ ├── conversation-list-guide.html │ │ ├── conversation-list.css │ │ ├── conversation-list.html │ │ ├── conversation-list.js │ │ └── conversation-list.json │ ├── guide.html │ ├── init.html │ ├── init.js │ ├── integrate.css │ ├── lib/ │ │ ├── jquery-3.1.1.js │ │ └── vue-2.1.4.js │ ├── login/ │ │ ├── login.css │ │ ├── login.html │ │ ├── login.js │ │ └── login.json │ ├── message/ │ │ ├── message-guide.html │ │ ├── message.css │ │ ├── message.html │ │ ├── message.js │ │ ├── message.json │ │ └── upload/ │ │ ├── qiniu.js │ │ ├── upload.js │ │ └── uploadInit.js │ ├── public/ │ │ ├── js/ │ │ │ ├── public-article.js │ │ │ ├── public-chat.js │ │ │ ├── public-common.js │ │ │ ├── public-info.js │ │ │ ├── public-list.js │ │ │ └── public-search.js │ │ ├── public-guide.html │ │ ├── public-mock-data.json │ │ ├── public.css │ │ ├── public.html │ │ └── template/ │ │ ├── public-article.html │ │ ├── public-chat.html │ │ ├── public-info.html │ │ ├── public-list.html │ │ └── public-search.html │ ├── reset.css │ └── server-api.md ├── js/ │ ├── message-output.js │ └── pre-check.js ├── json-view/ │ ├── jquery.jsonview.js │ └── jsonview.css ├── lib/ │ ├── RongCallLib.js │ ├── RongEmoji-dev.js │ ├── RongIMVoice-2.2.6.js │ ├── jquery-3.1.1.js │ ├── require.js │ ├── seajs-2.1.1.js │ └── vue-2.1.4.js ├── local-sdks/ │ ├── README.md │ ├── emoji.html │ ├── im.html │ ├── sdk/ │ │ ├── RongIMLib-2.3.4.js │ │ ├── RongIMLib-2.3.5.js │ │ ├── RongIMLib-2.4.0.js │ │ ├── RongIMLib-2.5.0.js │ │ ├── RongIMLib-2.5.1.js │ │ └── RongIMLib-2.5.3.js │ ├── voice-amr-base64.json │ └── voice.html ├── miniprogram-upload/ │ ├── README.md │ ├── app.js │ ├── app.json │ ├── app.wxss │ ├── pages/ │ │ ├── index/ │ │ │ ├── index.js │ │ │ ├── index.json │ │ │ ├── index.wxml │ │ │ └── index.wxss │ │ ├── lib/ │ │ │ └── RongIMLib-3.0.4-dev.js │ │ └── services.js │ ├── project.config.json │ ├── sitemap.json │ └── utils/ │ └── util.js ├── nav/ │ ├── README.md │ ├── css/ │ │ ├── iconfont.css │ │ └── style.css │ ├── index.html │ └── js/ │ ├── config.js │ └── index.js ├── react/ │ ├── im.html │ ├── react-16.2.js │ └── react-dom-16.2.js ├── require.html ├── res/ │ ├── rongcloud.css │ └── voice-amr-base64.json ├── rongrtc/ │ ├── README.md │ ├── api/ │ │ └── api.html │ ├── im.js │ ├── mock.js │ ├── screenshare/ │ │ ├── screenshare.html │ │ └── screenshare.js │ └── utils.js ├── rtc/ │ ├── README.md │ ├── app/ │ │ ├── README.md │ │ ├── config.js │ │ ├── css/ │ │ │ ├── common.css │ │ │ └── main.css │ │ ├── index.html │ │ ├── js/ │ │ │ ├── core.js │ │ │ └── utils.js │ │ └── lib/ │ │ ├── RongRTCEngine.js │ │ └── adapter.js │ └── whiteboard/ │ └── src/ │ ├── blink-wb.html │ ├── config.js │ ├── css/ │ │ ├── app.css │ │ ├── enyo.css │ │ ├── main.css │ │ ├── style.css │ │ ├── sweetalert.css │ │ ├── upload.css │ │ └── uploadfile.css │ ├── js/ │ │ ├── Queue.src.js │ │ ├── blink/ │ │ │ └── blinkEwb.js │ │ ├── common.js │ │ ├── core.js │ │ ├── ewb/ │ │ │ ├── App.js │ │ │ ├── Connection.js │ │ │ ├── Svg.js │ │ │ └── WhiteBoardApi.js │ │ ├── lib/ │ │ │ ├── enyo-ilib/ │ │ │ │ └── ilib/ │ │ │ │ └── locale/ │ │ │ │ ├── ilibmanifest.json │ │ │ │ ├── scripts.json │ │ │ │ └── und/ │ │ │ │ └── CN/ │ │ │ │ └── localeinfo.json │ │ │ ├── enyo-ilib.js │ │ │ ├── enyo.js │ │ │ ├── layout.js │ │ │ └── onyx.js │ │ ├── raphael-min.js │ │ └── raphael.inline_text_editing.js │ └── resources/ │ ├── localeinfo.json │ └── strings.json ├── sdk-unitest/ │ ├── emoji/ │ │ ├── emoji.js │ │ ├── run.html │ │ └── testcase.js │ ├── im/ │ │ ├── RongIMLib-2.2.7.js │ │ ├── run.html │ │ └── testcase/ │ │ ├── 1-staticCheck.js │ │ ├── 2-connect.js │ │ └── 3-sendMessage.js │ ├── index.html │ ├── jasmine/ │ │ ├── 1.2.0/ │ │ │ ├── jasmine-html.js │ │ │ ├── jasmine.css │ │ │ └── jasmine.js │ │ └── guide.js │ └── libs/ │ ├── ua.js │ └── underscore.js ├── seajs.html ├── sticker/ │ ├── README.md │ ├── extend-stickers/ │ │ └── extend-sticker.js │ ├── init.js │ ├── message.html │ ├── require.html │ └── sticker.html ├── switch-users.html ├── unreadcount/ │ └── unreadcount.js ├── user-group.js ├── video/ │ ├── flowplayer/ │ │ ├── flowplayer-3.2.13.js │ │ ├── flowplayer-3.2.18.swf │ │ └── flowplayer.controls-3.2.16.swf │ └── player.html ├── voice-autoplay.html ├── voice.html ├── vue/ │ ├── im/ │ │ ├── config.js │ │ ├── conversation-list.js │ │ ├── css/ │ │ │ ├── common.css │ │ │ └── main.css │ │ ├── im.html │ │ ├── im.js │ │ ├── js/ │ │ │ └── service.js │ │ ├── lib/ │ │ │ ├── vue-2.1.4.js │ │ │ └── vue-router-2.1.1.js │ │ ├── message-list.js │ │ └── routes.js │ ├── normal.html │ ├── require.html │ └── vue-2.1.4.js ├── vue-cli/ │ ├── .eslintignore │ ├── .gitignore │ ├── README.md │ ├── babel.config.js │ ├── package.json │ ├── public/ │ │ └── index.html │ └── src/ │ ├── App.vue │ ├── components/ │ │ └── Init.vue │ └── main.js └── vue-cli-4/ ├── .gitignore ├── README.md ├── babel.config.js ├── package.json ├── public/ │ └── index.html └── src/ ├── App.vue ├── components/ │ └── Init.vue └── main.js ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ node_modules .DS_Store electron-vue/node_modules electron-vue/dist electron-vue/build calllib-v3/server/node_modules calllib-v3/server/package-lock.json calllib-v3/web/node_modules ================================================ FILE: LICENSE ================================================ MIT License Copyright (c) 2017 融云 RongCloud Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ================================================ FILE: README.md ================================================ # 引导说明 写给前端新手的工程管理建议: [https://support.rongcloud.cn/kb/NzUx](https://support.rongcloud.cn/kb/NzUx) 开发 IM 的基本思路: [https://support.rongcloud.cn/kb/NzQ4](https://support.rongcloud.cn/kb/NzQ4) 消息类型与文件格式: [http://support.rongcloud.cn/kb/NjE0](http://support.rongcloud.cn/kb/NjE0) 用信息处理: [http://support.rongcloud.cn/kb/NjQ5](http://support.rongcloud.cn/kb/NjQ5) # WebSDK demo WebSDK API 示例(基于 IM SDK V4): [https://rongcloud.github.io/websdk-demo/api-test-v4](https://rongcloud.github.io/websdk-demo/api-test-v4/) WebSDK API 示例(基于 IM SDK V3): [https://rongcloud.github.io/websdk-demo/api-test](https://rongcloud.github.io/websdk-demo/api-test/) SDK源码: [https://github.com/rongcloud/rongcloud-web-im-sdk-v2](https://github.com/rongcloud/rongcloud-web-im-sdk-v2) 常见问题: [https://github.com/rongcloud/websdk-demo/blob/master/faq.md](https://github.com/rongcloud/websdk-demo/blob/master/faq.md) Require SDK: [https://rongcloud.github.io/websdk-demo/require.html](https://rongcloud.github.io/websdk-demo/require.html) Require SDK in Electron: [https://github.com/rongcloud/websdk-demo/tree/master/electron/requirejs-in-node.html](https://github.com/rongcloud/websdk-demo/tree/master/electron/requirejs-in-node.html) Normal SDK in Electron: [https://github.com/rongcloud/websdk-demo/tree/master/electron/normal.html](https://github.com/rongcloud/websdk-demo/tree/master/electron/normal.html) WebSDK in electron-vue: [https://github.com/rongcloud/websdk-demo/tree/master/electron-vue](https://github.com/rongcloud/websdk-demo/tree/master/electron-vue) 引用本地 SDK: 将 [WebSDK](https://cdn.ronghub.com/RongIMLib-2.3.0.js) 下载至本地引用即可,[初始化示例](https://github.com/rongcloud/websdk-demo/tree/master/local-sdks) 初始化、消息监听: [https://rongcloud.github.io/websdk-demo/connect-check.html](https://rongcloud.github.io/websdk-demo/connect-check.html) 消息监听回调队列: [https://rongcloud.github.io/websdk-demo/init-muti.html](https://rongcloud.github.io/websdk-demo/init-muti.html) 获取历史消息: [https://rongcloud.github.io/websdk-demo/histroy-messages.html](https://rongcloud.github.io/websdk-demo/histroy-messages.html) 聊天室自定义属性: [https://github.com/rongcloud/websdk-demo/tree/master/chrm-kv-demo](https://github.com/rongcloud/websdk-demo/tree/master/chrm-kv-demo) WebSDK Vue Require 示例: [https://rongcloud.github.io/websdk-demo/vue/require.html](https://rongcloud.github.io/websdk-demo/vue/require.html) WebSDK Vue Normal 示例: [https://rongcloud.github.io/websdk-demo/vue/normal.html](https://rongcloud.github.io/websdk-demo/vue/normal.html) WebSDK Vue CLI 3.x 示例: [https://github.com/rongcloud/websdk-demo/tree/master/vue-cli](https://github.com/rongcloud/websdk-demo/tree/master/vue-cli) WebSDK Vue CLI 4.x 示例: [https://github.com/rongcloud/websdk-demo/tree/master/vue-cli-4](https://github.com/rongcloud/websdk-demo/tree/master/vue-cli-4) WebSDK React 示例: [https://rongcloud.github.io/websdk-demo/react/im.html](https://rongcloud.github.io/websdk-demo/react/im.html) WebSDK SeaJS 示例: [https://rongcloud.github.io/websdk-demo/seajs.html](https://rongcloud.github.io/websdk-demo/seajs.html) # 扩展组件 Component Emoji: [https://rongcloud.github.io/websdk-demo/emoji.html](https://rongcloud.github.io/websdk-demo/emoji.html) 视频播放(Video + Flash): [https://rongcloud.github.io/websdk-demo/video/player.html](https://rongcloud.github.io/websdk-demo/video/player.html) 声音播放: [https://rongcloud.github.io/websdk-demo/voice.html](https://rongcloud.github.io/websdk-demo/voice.html) 上传组件: [https://github.com/rongcloud/rongcloud-web-im-upload](https://github.com/rongcloud/rongcloud-web-im-upload) # 集成项目 集成指南: [https://rongcloud.github.io/websdk-demo/integrate/guide.html](https://rongcloud.github.io/websdk-demo/integrate/guide.html) Web 聊天室 (弹幕效果):[https://rongcloud.github.io/websdk-demo/chatroom/chatroom.html](https://rongcloud.github.io/websdk-demo/chatroom/chatroom.html) Web IM(无框架依赖): [https://rongcloud.github.io/websdk-demo/im/im.html](https://rongcloud.github.io/websdk-demo/im/im.html) Web IM(Angular): [https://github.com/rongcloud/rongcloud-web-im-widget](https://github.com/rongcloud/rongcloud-web-im-widget) Web IM H5(Angular): [https://github.com/rongcloud/rongcloud-web-im-widget-h5](https://github.com/rongcloud/rongcloud-web-im-widget-h5) Web 对接佳信客服(无框架依赖): [https://rongcloud.github.io/websdk-demo/cs/jx/cs.html](https://rongcloud.github.io/websdk-demo/cs/jx/cs.html) Web 对接智齿客服(无框架依赖): [https://rongcloud.github.io/websdk-demo/cs/sobot/cs.html](https://rongcloud.github.io/websdk-demo/cs/sobot/cs.html) # SealTalk 项目源码 SealTalk Server: [https://github.com/sealtalk/sealtalk-server](https://github.com/sealtalk/sealtalk-server) SealTalk Web: [https://github.com/sealtalk/sealtalk-web](https://github.com/sealtalk/sealtalk-web) SealTalk Desktop: [https://github.com/sealtalk/sealtalk-desktop](https://github.com/sealtalk/sealtalk-desktop) ================================================ FILE: api-test/.gitignore ================================================ .node_modules .sass-cache *.css.map ================================================ FILE: api-test/README.md ================================================ # api-test ================================================ FILE: api-test/config.js ================================================ (function (win) { var isDebug = false; var im = { appkey: 'n19jmcy59f1q9', token: 'Kn2p4uokgY5AZOFVsKTbKq+YsUIoF3ojin3K277sfOnEb+B6ZpahsTOCVisdS43pwz7SnsSF0xxiLfygEojZP7ywLi39+nOPq12llTIt1oc=', navi: '', targetId: 'api_test_target', // customCMP: '', isPolling: false, }; if (!isDebug) { delete im.cmpUrl; } var config = { im: im, isDebug: isDebug, debugConf: { autoRun: false, isShowMsg: false } }; win.RongIM = win.RongIM || {}; win.RongIM = { config: config, components: {} }; })(window); ================================================ FILE: api-test/index.html ================================================ Api Test v3

Web SDK Demo 示例源码

{{opt.name}}

提示: {{RunType[runType].prompt}}

运行
================================================ FILE: api-test/js/common/api-list.js ================================================ (function (win, dependencies) { var RongIMLib = win.RongIMLib, RongIMClient = RongIMLib.RongIMClient; var RongIM = dependencies.RongIM, utils = RongIM.Utils, Service = RongIM.Service, config = RongIM.config.im, urlQueryConfig = utils.getUrlQuery(); var MiniUnSupportEventList = [ 'sendRecallMessage', 'deleteRemoteMessages', 'clearRemoteHistoryMessages' ]; var disconnect = { name: '断开链接', event: Service.disconnect, eventName: 'disconnect', desc: '断开链接', doc: 'https://docs.rongcloud.cn/v3/views/im/noui/guide/private/connection/disconnect/web3.html', params: [] }; var reconnect = { name: '重新链接', event: Service.reconnect, eventName: 'reconnect', desc: '重新链接', doc: 'https://docs.rongcloud.cn/v3/views/im/noui/guide/private/connection/reconnect/web3.html', params: [ // { name: '是否嗅探', type: 'boolean', value: true }, // { name: '嗅探 url', type: 'string', value: 'https://cdn.ronghub.com/RongIMLib-2.2.6.min.js?d=' + Date.now() }, // { name: '嗅探频率', type: 'string', value: '100,1000,3000,3000,3000' } ] }; var changeUser = { name: '切换用户', evnet: utils.noop, eventName: 'logout', desc: '切换用户', doc: 'https://docs.rongcloud.cn/v3/views/im/noui/guide/private/connection/disconnect/web3.html#logout', params: [ { name: 'Token', type: 'string', value: '5JQlp5czM31GNl99DOZyI3xpRjANxKgfakOnYLFljI+TMvOF0hGaVtR1n9Qp4baLgKBGsyl3w5j4gAWBbNZ3nOKrvnVo8Ldl' } ] }; var registerMessage = { name: '注册自定义消息', event: Service.registerMessage, eventName: 'registerMessageType', desc: '注册自定义消息', doc: 'https://docs.rongcloud.cn/im/imlib/web/message-send/#custom-register', params: [ { name: 'messageType', type: 'string', value: 'PersonMessage' }, { name: 'objectName', type: 'string', value: 's:person' }, { name: '是否计数', type: 'boolean', value: true }, { name: '是否存储', type: 'boolean', value: true }, { name: '属性', type: 'string', value: 'name,age' }, ] }; var getConversationList = { name: '获取会话列表', event: Service.getConversationList, eventName: 'getConversationList', desc: '获取会话列表', doc: 'https://docs.rongcloud.cn/v3/views/im/noui/guide/private/conversation/getall/web3.html', params: [ { name: '数量', type: 'number', value: 1000 } ] }; var removeConversation = { name: '删除会话列表', event: Service.removeConversation, eventName: 'removeConversation', desc: '删除会话列表', doc: 'https://docs.rongcloud.cn/v3/views/im/noui/guide/private/conversation/clear/web3.html', params: [ { name: '会话类型', type: 'number', value: 1 }, { name: '对方 id', type: 'string', value: config.targetId } ] }; var getHistoryMessages = { name: '获取历史消息', event: Service.getHistoryMessages, eventName: 'getHistoryMessages', desc: '获取历史消息', doc: 'https://docs.rongcloud.cn/v3/views/im/noui/guide/private/msgmanage/storage/web3.html', params: [ { name: '时间戳', type: 'number', value: 0 }, { name: '数量', type: 'number', value: 20 }, { name: '会话类型', type: 'number', value: 1 }, { name: '对方 id', type: 'string', value: config.targetId } ] }; var setConversationStatus = { name: '设置会话状态', event: Service.setConversationStatus, eventName: 'setConversationStatus', desc: '设置会话状态', doc: 'https://docs.rongcloud.cn/v3/views/im/noui/guide/private/conversation/notify/web3.html', params: [ { name: '免打扰', type: 'number', value: 1 }, { name: '置顶', type: 'boolean', value: true }, { name: '会话类型', type: 'number', value: 1 }, { name: '对方 id', type: 'string', value: config.targetId } ] }; var deleteRemoteMessages = { name: '删除历史消息(按消息)', event: Service.deleteRemoteMessages, eventName: 'deleteRemoteMessages', desc: '按消息删除指定历史消息', doc: 'https://docs.rongcloud.cn/v3/views/im/noui/guide/private/msgmanage/delete/web3.html#deletebyid', params: [ { name: '消息 Uid', type: 'string', value: '', event: Service.getLastCacheMsgUId }, { name: '发送时间', type: 'number', value: 0, event: Service.getLastCacheMsgSentTime }, { name: '消息方向', type: 'number', value: 1, event: Service.getLastCacheMsgDirection }, { name: '会话类型', type: 'number', value: 1 }, { name: '对方 id', type: 'string', value: config.targetId } ] }; var clearHistoryMessages = { name: '删除历史消息(按时间)', event: Service.clearHistoryMessages, eventName: 'clearRemoteHistoryMessages', desc: '按时间删除历史消息', doc: 'https://docs.rongcloud.cn/v3/views/im/noui/guide/private/msgmanage/delete/web3.html#deletebyid', params: [ { name: '删除时间戳', type: 'number', value: Date.now() }, { name: '会话类型', type: 'number', value: 1 }, { name: '对方 id', type: 'string', value: config.targetId } ] }; var sendTextMessage = { name: '发送文字消息', event: Service.sendTextMessage, eventName: 'sendMessage', desc: '发送文字消息(TextMessage)', doc: 'https://docs.rongcloud.cn/v3/views/im/noui/guide/private/msgmanage/msgsend/web3.html#TxtMsg', params: [ { name: '文字内容', type: 'string', value: '我是一条文字消息' }, { name: '会话类型', type: 'number', value: 1 }, { name: '对方 id', type: 'string', value: config.targetId }, { name: '状态消息', type: 'boolean', value: false }, { name: '静默消息', type: 'boolean', value: false }, ] }; var sendImageMessage = { name: '发送图片消息', event: Service.sendImageMessage, eventName: 'sendMessage', desc: '发送图片消息(ImageMessage)', doc: 'https://docs.rongcloud.cn/v3/views/im/noui/guide/private/msgmanage/msgsend/web3.html#ImgTextMsg', params: [ { name: '缩略图', type: 'string', value: '/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDABALDA4MChAODQ4SERATGCgaGBYWGDEjJR0oOjM9PDkzODdASFxOQERXRTc4UG1RV19iZ2hnPk1xeXBkeFxlZ2P/2wBDARESEhgVGC8aGi9jQjhCY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2P/wAARCABkAPADASIAAhEBAxEB/8QAGwABAAIDAQEAAAAAAAAAAAAAAAECAwQGBwX/xAA7EAABAwEHAQYDBQcFAQAAAAABAAIDEQQFEiExUZETFiJBVGHRI3GTBhSBobEVM1Ji4fDxJEJDU3LB/8QAFwEBAQEBAAAAAAAAAAAAAAAAAAEDAv/EABwRAQEBAQACAwAAAAAAAAAAAAABEwIRMQNRYf/aAAwDAQACEQMRAD8ArBct7wBwbZWkOoc5G5EaHVSLnvoRCIQgNAoO+2ozrrVdY9tpNoqx7BDQZeNc/TTMceqwMivFrm4p43NqcVRmR4Uy11/Jb638ZZxzxu6/nPL3QtJJqQSyhOeo08StR/2dvV7sX3YVJqfiN912NLYZ8TSwREjuu1A/DxOfj4D1Wdgko3GW1/3UGvyU2s+jOVxTbivhgAbCQ2tadVtP1UTXBe81S6zguIp+8b7rsZ22rrNdA+PAKVa/x1r/APFEf3t9mlEmCObMRluY0yPj4qb9efRnHIw3HfEDsUdnaDUGpcw0/NQ+4b2eBis4y0+I33XUGG8uqCLVH0w5hphzIqMQ02r/AEWeZlqM7XQyNEWGjmkamvyXW3X4Zxhu2yPjueGy2hpa4No4A6Z7hbENlihdiZUHxO6iyNtLICLU8PlrkQcv0H6LXskF4iOMWq1MxtcC4xtBxCmmYyWNnm+Xb4l+XNb7Xess8EAdG4NocbRoBuVrfsi++/8ACpjbhdSRoqKU3XaItJ8tk8Ob8ct8uD7OXriB+7DT/sb7rajuu/Y8GGIdymGr2GlPmf7ouyRXbr6Mo4R32dvUkH7tXOp+I33WWO5b5iaAyGgDsQ+I3I8+i7ZE26Mo4WX7P3tIHE2epIP/ACN91qdl748qPqM916KibdGceddl748qPqM907L3x5UfUZ7r0VFNujOPOuy98eVH1Ge6dl748qPqM916KibdGceddl748qPqM907L3x5UfUZ7r0VE26M4867L3x5UfUZ7p2Xvjyo+oz3XoqJt0Zx512Xvjyo+oz3TsvfHlR9RnuvRUTbozjzrsvfHlR9RnunZe+PKj6jPdeiom3RnGV0UTRV2Q3Liqn7sK1ezLXv/P19DwrytbKzCXkA/wAJodKLAbFCS49SSrjUnH8+NSs2jJMLPBC+aU4Y4wXOcScgNVVr7I5xa2VhcDhID866U1V5YYp7NJZ5u/HI0tcCaVB10Wsy6bAy0/eBH8Tu5l5NS2tCc8zmcz7oMjJ7C9mNs8Zbv1P6qRLYnFwE0dWOLXfE0I1Gqwtue7mTGZkDWyurV7XkE1BGtdiomua7Z3h8sAe5shkDi91Q4nEaZ6Vzpog2OpZC9jBI0uecLQHE1NCf0B4UdSx4XO6rMLa4j1NKGh8d8lSz3XYbNKJIYg1weZK4ye8QRXX+Z3KC67CBJSL96AH/ABHZ0pTx9Px8UGQyWNpAMrAXEAfE1rSnj6hYHXhdjBMXWqL4BAk75OAkkUPrUFP2NdvUhk6Axw06Zxu7tKU8fQfnuU/Y120nHQAFofjlAe4YzUnPPcnJBW0Xnddm6vWtLWdJwa+pd3Sa0H5HhTJeF3RMe983djNHuAcQ3XWn/k8KZbnu+ZsrXxEiZ2N9JXCpz9ch3nZaZlXddtifHJGY+5IHB4xuzxYq+P8AO7n0CDHaLwu6yyOZPKWOa0OILX6EgA8kBS233a6EzC0MwBodUuIyJoMvmNFe13bY7aXG0Nc7FStJXN0II0O4Cwm4rrNKwVoMNeq7eu+Z9UFo7wuyQAstLHVoBRx8cgrMtl3vja8TDA4E4iSAKEg1rpmDqsYuK6w0tFnGEginUdTP8dchn4UCvFc9ggjayJj2taSRSd9RWtc6+p5QXbarC9jnslxsa0vLm4iKfMf3rskNpsU72sic9znad14/XRY3XNd7nRudG9zowQwumeSAdfFZIrssUNrbamNf1m1o4zPOuuRNP8DZBs9GPY8lOjHseSr4huExDcIKdGPY8lOjHseSr4huExDcIKdGPY8lOjHseSr4huExDcIKdGPY8lOjHseSr4huExDcIKdGPY8lOjHseSr4huExDcIKdGPY8lOjHseSr4huExDcIMi15rbZoOp1ZWt6YxOr4DdZzqFozXfd8tqklmaHTSt6bwZD3hTSlaaBQXlvOxQsc+S0Na1oBcTXKulVtNcHtDmmoIqCtEXZdtphdSJsrH4QTjLqhtKCtdMhkt5rQxoa3QCgQWREQEREBERAREQEREBERAREQEREBERAREQEREBERAREQQdQtK0ywtklbJG5+VXVc0DT1K3TqFpTtvA2z4Do2WfDSrhU13UqVe7HQvsgfA1zWOOKjnYjnnrUrbWGzdbpf6jDjrXu6D0/DT8FmSeiehERVRERAREQEREBERAREQEREBERAREQEREBERAREQEREEEE6GiijtxwpPgtG02W2yzSGK2GONwoG0zbpmDz+SDdo7ccJR244URtc2Noe7E4DN1KVVkEUduOEo7ccKUQRR244SjtxwpRBFHbjhKO3HClEEUduOEo7ccKUQRR244SjtxwpRBFHbjhKO3HClEEUduOEo7ccKUQRR244SjtxwpRBFHbjhKO3HClEEUduOEo7ccKUQRR244SjtxwpRBFHbjhKO3HClEEUduOEo7ccKUQD4Ii07VLbmOlFngY8BowEnU8oNxF8ya0XuC8RWSI4Wijia4jlWgqNM9f87mKfrMBADKd70OWn5oM6LFG6Qvo4CnzWVAREQEREBERAREQEREBERAREQEREBERAREQEREBERAOoUoiAiIgIiIC+VaLymiksrWtjImjxuqDkaeGaIgXfeU1qbZS9sY6wcXYQcqGmWazR22R0sTS1lHuAOR/gr+qIg30REBERAREQEREBERAREQEREBERAREQEREH//Z' }, { name: '原图 url', type: 'string', value: 'https://nfsprodrcx.cn.ronghub.com/v3/BGSPKH501EG0K6MI/base64.png?token=Um9uZ2Nsb3VkMTQyMDIwMDMxNzAzMzk1OTM2MDBtZXNzYWdlOzs7MjczMTk5NDg4OA==' }, { name: '会话类型', type: 'number', value: 1 }, { name: '对方 id', type: 'string', value: config.targetId }, { name: '静默消息', type: 'boolean', value: false }, ] }; var sendFileMessage = { name: '发送文件消息', event: Service.sendFileMessage, eventName: 'sendMessage', desc: '发送文件消息(FileMessage)', doc: 'https://docs.rongcloud.cn/v3/views/im/noui/guide/private/msgmanage/msgsend/web3.html#FileMsg', params: [ { name: '文件名', type: 'string', value: 'logo_wx' }, { name: '文件大小', type: 'number', value: 20000 }, { name: '文件类型', type: 'string', value: 'png' }, { name: '文件 url', type: 'string', value: 'http://rongcloud.cn/images/newVersion/log_wx.png' }, { name: '会话类型', type: 'number', value: 1 }, { name: '对方 id', type: 'string', value: config.targetId }, { name: '静默消息', type: 'boolean', value: false }, ] }; var sendVoiceMessage = { name: '发送语音消息', event: Service.sendVoiceMessage, eventName: 'sendMessage', desc: '发送语音消息(HQVoiceMessage)', doc: 'https://docs.rongcloud.cn/v3/views/im/noui/guide/private/msgmanage/msgsend/web3.html#HQVCMsg', params: [ { name: '语音 url', type: 'string', value: 'https://rongcloud-audio.cn.ronghub.com/audio_amr__RC-2020-03-17_42_1584413950049.aac?e=1599965952&token=CddrKW5AbOMQaDRwc3ReDNvo3-sL_SO1fSUBKV3H:CDngyWj7ZApNmAfoecng7L_3SaU=' }, { name: '语音类型', type: 'string', value: 'aac' }, { name: '语音时长', type: 'number', value: 6 }, { name: '会话类型', type: 'number', value: 1 }, { name: '对方 id', type: 'string', value: config.targetId }, { name: '静默消息', type: 'boolean', value: false }, ] }; var sendRecallMessage = { name: '发送撤回消息', event: Service.sendRecallMessage, eventName: 'sendRecallMessage', desc: '发送撤回消息', doc: 'https://docs.rongcloud.cn/v3/views/im/noui/guide/private/msgmanage/msgrecall/web3.html', params: [ { name: '消息 Uid', type: 'string', value: '', event: Service.getLastCacheMsgUId }, { name: '发送时间', type: 'number', value: 0, event: Service.getLastCacheMsgSentTime }, { name: '会话类型', type: 'number', value: 1 }, { name: '对方 id', type: 'string', value: config.targetId }, { name: '静默消息', type: 'boolean', value: false }, ] }; var sendAtMessage = { name: '发送 @ 消息', event: Service.sendAtMessage, eventName: 'sendMessage', desc: '发送 @ 消息', doc: 'https://docs.rongcloud.cn/v3/views/im/noui/guide/group/msgmanage/msgsend/web3.html#at', params: [ { name: '文字内容', type: 'string', value: '我是一条文本消息, 我 @ 了其他人' }, { name: '@ 对象 id', type: 'string', value: config.targetId }, { name: '会话类型', type: 'number', value: 3 }, { name: '群组 id', type: 'string', value: config.targetId }, { name: '静默消息', type: 'boolean', value: false }, ] }; var sendAtMessageByErrorParamField = { name: '发送 @ 消息 ErrorParams', event: Service.sendAtMessageByErrorParamField, eventName: 'sendMessage', desc: '发送 @ 消息', doc: 'https://docs.rongcloud.cn/v3/views/im/noui/guide/group/msgmanage/msgsend/web3.html#at', params: [ { name: '文字内容', type: 'string', value: '我是一条文本消息, 我 @ 了其他人' }, { name: '@ 对象 id', type: 'string', value: config.targetId }, { name: '会话类型', type: 'number', value: 3 }, { name: '群组 id', type: 'string', value: config.targetId }, { name: '静默消息', type: 'boolean', value: false }, ] }; var sendRegisterMessage = { name: '发送自定义消息', event: Service.sendRegisterMessage, eventName: 'sendMessage', desc: '发送自定义消息(RegisterMessage)', doc: 'https://docs.rongcloud.cn/im/imlib/web/message-send/#custom-send', params: [ { name: '消息类型', type: 'string', value: 'PersonMessage' }, { name: '属性值', type: 'string', value: 'name,age' }, { name: '会话类型', type: 'number', value: 1 }, { name: '对方 id', type: 'string', value: config.targetId }, { name: '静默消息', type: 'boolean', value: false }, ] }; var sendLocationMessage = { name: '发送位置消息', event: Service.sendLocationMessage, eventName: 'sendMessage', desc: '发送位置消息(sendLocationMessage)', doc: 'https://docs.rongcloud.cn/v3/views/im/noui/guide/group/msgmanage/msgsend/web3.html#LBSMsg', params: [ { name: '位置缩略图', type: 'string', value: '/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDABsSFBcUERsXFhceHBsgKEIrKCUlKFE6PTBCYFVlZF9VXVtqeJmBanGQc1tdhbWGkJ6jq62rZ4C8ybqmx5moq6T/2wBDARweHigjKE4rK06kbl1upKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKT/wAARCADwAZgDASIAAhEBAxEB/8QAGQAAAwEBAQAAAAAAAAAAAAAAAAIDAQQF/8QAQRAAAgIBAwEFBQQIBAUFAQAAAQIAAxEEEiExEzJBUXEUImGBkQVSobEVIzNCU2LB0TRykuEkVXOi8ENjZJOkZf/EABgBAQEBAQEAAAAAAAAAAAAAAAABAgME/8QAHxEBAQEBAQACAwEBAAAAAAAAAAERAjEhQQMTcRIy/9oADAMBAAIRAxEAPwD3YQhKohCEAhCEAhCEAhCbtbyP0gZCNtb7phsbygLCaVI6iZAIQm9TiBkYIx8MesYKEG5jFZyenAgN2YHVofqx8ZOECm5B0X8IdqPBZOEYKdr/AC/jN9x/gZKEYGZCvxEWOLCOvIjYVxxwYCMLRUDTs3k/v5xj5TnX7RCUhr1O7cVIQeI9Z2rwoE8rU0sbLqzXdtNm9WRNw5HM3xJfii/6W0/3LPoP7zpWxb6FtUEA8jPWeR7J/Lqf/o/3nsVKE0iKAQAgHIwZe+eZ4EhCE5ghCEAl5CWHSSjG7p9I8WancHpIjB4j4xLn7Opn8QOPWMSAxyfjAtwdpBOOBmFjmyXoZAVKL7u9j1OOfzhTZvVHLuzYHCr/AF/3hWMUEMVJCn3scA+vnEV2XvBxXncCAeT5emZt0d0IiPlFLYDEcjym7l85hzavfPpNfoD8YoILjHlGfuH6wghCEKJJuplZJu8ZYzWQhCVGQhNAJ6CG2Qj9m3wikEdRAyEJoGTgdYGR1rJ68RjtrHTJiF2br0gPlE4HJi9o3wiQgP2jfCBsbziQgUVw3usIrLtOIucc+UpaMlQPGAnU4lABWMnkwwKxnqZMkk5MALFjkzIQgEIQgEIQgEIQgEIDkkAgkdQDyJu0+R+kBkswcN084g02dZ7SLD0xt8JuDnGJinoyMCPgeDHngbV0e0U7C5TnOZhPuqgJIUYyepjNsfOGG4DJGecRI34wEIEgYyQMnAycZMIBCEIBLDoJGWXuj0ko2CdPmYRGfs0dsZxziRFIYBGCBFY52kHAMMH7xlGlVOMgcdOJz6E4WxCclXIl8H7xnHV7v2jauTgjP5GWNT5ld0IuPifrDb8T9TMsmgRkYiEYBIJ4+MeUKvKibMXxHkZsiiSbvGVkm78sSjb8YRoRphAMkCJrdWNJUAmDYegP5mVq7/ynN9pLVX2eosrNhB27c4B6nmb5y9fKuX9Laj7lf0P953aLVDV1EOALB1A/MTy/1XZ9p7Hbszndv49M4nofZq1WdpqK6zWSdu3OQOh4nXvnnPCrkYJEk2rSm0p2V1jYz7i5wJ0ON1uPhzODUEj7QfbqVo9xe8Ac/WcEbXq7CpN2m1BYsT7tXQeAlqLlvDbVdSpwQ4wZDc//ADOr/Qn94aRTYupXttxZ8dooHl4QA6u3fcyUiylOh3hcY6nzMd9Um+gLbWm/O8Eg7fd8fnItStlwpGw1Vd6wcYH3T5xrKl1FnbVVIVTke6B2pzz8pBZdQi0dpdbXwdpKHcCflJJ9o0G20PcNmRs90+XPh5yo1GlpqDqyVox6KuOfiAJCrXaddTexuwHK4O084HPhKGT7Ro7ewPcOzG3Z7p8ufCX1erupXtKqA9e3dvLY/DrOenX6ZNVqHNvusE2kqecA58In2iy2U9pXdad4yFDYXA6nEg6TqLK69+pQZLBVWrk8zF1al0Vqb03ttBdMDP1kMYFQL3FxegZbWzjr0nVrOun/AOuv5GBJ77u1sCtpkRG2g2kgniZ7Rf8Ax9B/rM0VvY2oCV0uwt/9UZGMTm7O2u+7NGlOCoI2EgZHhA7NPbbZc1dvZHChg1WcHM6Cp8JCldmtZSFUilchRgA5PSdMCcJRuknLFEPA4xnwzGUeM1uhOMkeHnJo8+ntrNZdXZ2BBCiwAtyMeH1kex0q6O6w1hmR2Ue8eOePGX09IW657uHXbYWB6Hkn+0VHOipS8g4sHvrnBzyR+eIRfT21JpVNO+5a8KdiknPoZypqwmhRf1lbAjBIxuG7nHnO3TL2NQaxhljvds8ZM4ltrs0SIASyMOdvAy3nKKJqbG1lj6ekvlAPf93HXmWFtr6NLUVd+AxXHUeImWpqDqrDSFG5ANzg48emPGU0hzp1VR+zJTPnjxkErrFtTSuhyrXKR+MobWOpFVeMLzYT4eQ9Zz2INQ+3TYVKSW3Dozzp07V2Vl61CknLr4hvHMopCEIUSq90SUqndElDSdoYq4UZJWUmfvj0MiJ0lmoQnHBwPylYP3D8OYQCcbjb9p1n7y/3nZOXVLi6iz+cLLG+fXVCEJGWTU5UQgnQjyMIz98/WbMbvD0mwCTbvykm3flhWwhCQIDggjwktdRdq1VazWKxzznOeZSAJByDibly7Fc3smr9k9mzRs88nPXMroaLtIrLYazWeeM5zxLdo/w+kFBdveOcS3u2YHHClz1M8+5LDrGf2QXgoOWIAH1nc5LNgcgQFbHrxMI4dr/8rq/1p/aPpEZRfvoNYZs7B5Y8MTs2IveMO0Ud0QORUur0aYqGcgtWF/dJ6To2WC7Bx2RXg9NpjGxj8InXrzKJpbbXSc6ffdu2kqAA383pNp7YFnts3M37q91fSPCMVKw6ity9ZNqE5NZ6j0P9Jmqq36e51RjY6AEdT6S0deklRHWVWW11rUcMtitnj3fjzJPp9SbKS2o7VVsDEbAuPjOyEg862l3uuDaI3LvyCbNngPrF9kH/ACv/APRPTPSEo49HW6ah92nNKhAFG7cOp8Z2QhIAjMUqY0IAvSbMHQQgQfTCyx2LnbZt3KB1AzxmaNMpsNlp7RugBHCjyAloQOYaOtFZDl6ichG5CmPZUllRqYYQ+A4xLNyDJzUVD2TjHtOq/wDt/wBo1mjU6eutXdah3lB72fMysoTmmESRVRQqAKo6ASVmnD2dojtVZ4svj6jxloQrZkIQCVTuiSla+7FDTD3l9ZsxunzEyGYZUj4RQcgGNEXuj4cQhpza/wDYBvusDOmQ1ozpbB8P6yz1rn2LwiVndWjeagx5EExe8Zsz98fSED+B8jNg/dMyBsm/eEpJv3hEK2EIQJwHPTmV2IvX8YGwAe6JrVKKyevEf3a1k9zMQCesa09BIgNvkIuXbxMEHOY0BCuJkpFYY9IlUsIQlBCEIBKDgRB1EeSghCEiA+EIeMIBCEIBA9DCB6QCE0AmNt+MBITSCJkAiHgx4rdZYFlFwaj8JOUq7pEtVOEIQCEIQCUr7snKV9DFDxW7p9I0yZDRR4j4zU7g9Jn7zfWEbJ3jNFg/lP5SkwjIwfGFS0rbtNWf5cS05tAc6VR5Ej8Z0y31evRMPgfIzZjcqZENEXuiODkZijqR8YRsR+8I8R+CDEKITN3whKEhCEqnqGWz5THOWJjJ7qFvOTA6CBRRgQhCZQQhCArDHpFlIjDEsqshCaAScASgXvCPBa2BzxNII6yVGQhCQHiYQEIBCEIBNAycTJq96Bz/AGk5TTqA+xXbaxxngg5nn6RhVepquyWsCY29Vz1nf9p5NVQVQx7UYB6HrPOzZV+salAEvySOCCP3fSd+P+WL692IRg4nBd9pXCxqFoCWjBJZshR8pzLq9SbmUaoPYg95GrAH4c/jPP1ZLldueLZsevMfwkdJqRqaydux1OHU+Blm6SxkkpV1MnHq7/ymqFIwSJk1uHPrMgEIQgEpX4ycevxiikIQmQJ3fmZh7/qIJ+96wbvD6QjYQhCubR4AuT7thnTObTjbqtQvxBnTLfV69EIQkQJ3R8OJh75+Ignj6wbvD0MI2JZ4R4lnhEKSEZekJdTCQhNUZOOflK0569WzO6Gu5k34RlT3cDjr6xa9Wz7LA+mVCOUa7nP04kNO4S9wfbFrTopHCjH7wlFsNI09deouKHgnsfDHh7v95EdCarfp7rAFzXuHDbgcDPXictX2ja9la7tO25gCqhs8n48SjJWdPentDYLh7CyEEA446fCciXICgbWMQCNw7RyCPLG3+sDrbWaoMzey4ROHXtBnPhL2vY1VaBTVbacYByVHic+n5zxm7HeuPZ8c5x2mPn4/SdlyaZdFQGCBnyFYFsKM8nnmBbWazFdbUvtHaEbmzg49Ooi6bW2X6hay1LqQSdgYEcfGZcKzUG0916pjC4Yqg/DJPpJ0otrVg36o3YIb38bPPw/CB6XXiLZqk077GrsxkDft93n4x074/rF+0U36KweIGfpNTNyqo2opUkNdWCOoLCA1FDEKLqyT0AYTxdRWbbmsRq8Phv2ijkjnxj6HTt7XWWNeAc8OpP4GdP1zN0x7BGDiZGfqIp6TggHSEIQCEAwJIDAkdQD0grBlDKQwPQg5EAgenHWbiGD5QJajTpq1UOzrt5wp6yP6Jo+/Z9R/adW3I5EMHzM1OrEyPGetdLqtRWAxxh1zyWGP7gzlprvreu8ovvE7wM5w3n6cT1/tKkGg3A7bK+6fP4fOcD35pRq+9ZwvwPx9Jx6l3+vTxZef46/s3B1OoZemFUn4jP8AcTvPIM4NOyU1itOg6nxJ8zOiu0HksAPMnE3Jkcert1SNWffERXRyQjoxHUBgYy94es2jbO+Yse3vD0iQCEIQCPX1MSPX1MUUhCZMgXvH5Qf931gO/wDKa/T5iEEIQhXMox9oP/MgP9J0zms419R+8hH9Z0y1b9CEISIxe80G6r6wHfPpNfoPWEESzoI8SzpEKxYTF6wloWPV3/lElKuplVx2U3tqNQQ1a12DHPJPu4+Ua2uweyisAsmRnBwDt8fhLk5JMcdJEcqJqK1usZVstswNtbbQAOOpnI+n1jIV2ajkY51KkflPVhA8ldPrlCgLeFAwQNQB9PKdrLqbUrO2uphkHf77D0M6YQOG6vUJljl8DmxFy5+Cjwi00v2TNUhrcWbq1fr0AOfWehJxAdOR1lWPaVMFAJIIw3TPxkoDIOQcGVSaTTfqf+Joq358EHSC0PXrty1VLSB1CgHp9ZXtH+H0mglu8Zb1RucnMD0hA9DMIJK+/scfqrbM/wANc4lYlt1dK7rXCj4+MDn0T9pfqX2MmWXhxgjiS0Wpc6Wqqio2Mo94nhV585XRWC2/UuAwBZcBhg9IaWwU/ZaWEZCoTj5yjNVSl+srV03gVsQucZMh7J//AC//ANErqK69VqQHXIWndjPQk8Tm9m06abT3umQf2g3HJHn8oHVpdIq27m0PYlRkN2u7n0lPtFqhpttpXk+7v3Yz8uZHR6RDcNQtIrrAygLEk/HrLmqyioppiPeYlmsbO3MDxn7IsoHs4Gclh2mPQ5nLcRuevNbKp9wDdjnnjx4wevnPXewaenUVrcr2MNwsU+8eehlhut1Vl+mepXHu7DyXx4nyg1B9Kg+zTZntCQuMcDqI3YbAT+i1wPO4GW1NXbNSLWtQ2HBRLPdBAz5RbdMVvpq9q1JWzduzZ5CA2lZiVZdEtSOO+HXp9MzpnKNOKrq6lv1OMEj9ZwMY4xidR5zKqlvhJyl3UScQEIQgEevvRI9Xf+UBrLEprL2NhR4yH6R0n8X/ALT/AGkftOmy2ysGxUp8SxAwf6zz/ZW/i09cftB9Z1445s+aPdqdLlFlbZU9DGfuGcH2ZTZVZYBYr0+BUg5P9J3tyCPhOfUkuRBCYORmbMK5tSduo07fzEfWdM5tcdqVv92wGdMt8W+QQhCRGDvj0M1+6frM/eX1mtyp9IQRLOkYciY/diFIvWEwdYS1IyUr4UmTlF/Yn5y1pOUk5SSghCEiCEIQCIepjxG6mWKyEISgmg4MyECkIqnwjEgTKAdBFaqtnV2QFl6EjpGXkQgJXVsuts3Z7Qg4x0wMTn/R1WNvaXdnnPZ7/d+k64QJLQqtawY7rep8hjHEXT6OqgDguwGNzc8fDyl4QIV6YU2BqrHSvxr6j/aVsRLUKOoZT1EaGIHLboQ/upYK6jjci1jn5yl2lpvO50w33l4Mt6wgT1FC3hcu6FTkFDgyJ0Clgx1OpJXoe06fhOqB4EDlr0wruFnbWvgEYsO7rLryw9ZkavviaVtp94D4RIznLmLAIQhAIyHDiLGXvCByfbNidktWff3BsY8OZx/8J7B/8j5+f06T2wSOvIm7x/4Jvn8mTB5/2NYnZNVn39xbGPDiegOcxWYkccCPM9df6uoRe6PSNFXp8zGmFc+uGdK/wwfxl1O5Qw8RmT1K7tPYP5TDTNu09Z/lEv0v0rCEJEYfA/GNEbp8xHhCKw2jkdJjkbeojbl8j9IblHgfpAlkecJTen/ghNamJSg/Yycov7I/OK0nKScoOgkoIQhIghCEAiv4RpjdICQhCaUQhCAQhA8AnygMp5xGkkYOodc4PPMqORJQQkjqqFJBs5HHQzPbNP8AxPwMZTFoQhIghCEAik4PEaIeplgYMPHiYzZ4EWEuKJSrxMnKLxUT5xQh5OfOZCEAi2OK13MGPBPCk/kOI0jqveCJsVy5IANYY5x4ZIxA1dTWaRa25QVBwVP0BxzGovV3RSGSwjJRlPH4TnoU1g1Csq1YXJStA3wOSxEmtlqO9w7Ut2orOQmMZHHr6cSI7L/tDT1F0Ng7RfDaesj+lKPZt29e22Z27TjdjpOjV3CunG3L2e6qE9SZlpWqqqg15Wz9WQD0GICV/aGmtVV7Ub2HI2nrMs+1tKqgo+85HGCP6S9V9TOaaiTsHJHIHwzOW46i9rNnZGmrAPaZ7w5J4gM32ppVI2vuy3PBGB59J0UaqjUEil9xHJ4InH2up1TVhUpyqrb7+4YPPkZ16S2y1H7UIGRyp2Zxx6wLMNylT4jEhoTnSp8Mj8Z0Tm0Q2pYv3bCI+mp46YQhIhW6fOPEbpNssWpNzZx8BCMXp8zB+6YtNi2oSucAkciYXdndFQELjJLY/pAyEViyldyDDMF4b/aE0mNjK+MJjvk8+XEWI7FXTC554itHjr0iDpzNBxFDwmbhNyD4zKCEIQCB6QhAnCaepmTSiEIQCY3db0M2DA7W9DA56XtFKAU5GODvAzOip2K++mw56ZzE04/UJ6QvJWlyMggdZb8qSm7YHXs7G988quR1hqL91Dr2VoyOpXiDI1YRhbafeHBbiMENt1v62xQCMBWx4R8ejoXoIhci9UwMFSYmnG+llclhuK8nwkzpKu3UCs7NpzyesmRHXMmIi1qFQYAmzKA9JOVAyYwUDwlghCdBAPUSTpt5HSVSSjjFYEQDJAj2n3gIE4QhAJDVJvs064U5c99cjofCXmgkdCYHJpxWH1B31iv3PerOxfHyP9YaeiuwO2XK9sWU7zggY5+M68nzMM88wjn1lIF1VxYsxuQDP7o8hJayuwtS2rtXszZgqowBx5z0HrSzbvGdrBh6ia6K67XUMPIjImRyG+tbKKNK9eGY7gmDgYkGrS6xaNIzAAbbXB4I8j5meglNVZzXUiHzVQI9YABwAOT0Eo4LsV610F66f9Uu1jjHBPnH0DAPbWri1R7zWDxYzqtqrscdpWj4HG5QZqIlYwiKo8lGIDTn0nW//qtOic2k79//AFDH01PK6YQhIhW7seI3dM2xO0TbuZfipwYRHTdLcfxGk3U9s29EbIB3dkW/rKU6cVtuFlh5OQW4Ms2dpxjPxGYHLtQMvCKdwwewYc/WEcqWK7mGAc4C45+sJRsesAk5AOOREj1H3vWVSnqfWNtHlMfhjGXoJKM2iGwec2EiF2kdDN94fGbCBm7zE0EHxh1mFfKUY/WLNIImSxRCEIAyhlKsMg9ZL2Wj+H+JlYS6Jey0fw/xM0UVBWVV27hg4MpCNpqQ01IIIUgg5zma2nqdyzLkn4yuD5GZG00Uota7FyBnPMpJzQSJmwPCYG85oOZEDVpbUUcZVuonm2M+j9probaFZWHGeD6/Keoh8Jw6xV9tVRbsa1QpBrDA8+OZ1/HfpY4v0jq/4v8A2j+09PQWWX6Tfa24knBxjic92jNNTWPdXtXy06zq0rj2NGDbhg4O0L4+Qmu7zefiBq++IWHLmbV3vlMfvH1nILCEIBCEIBCEIFpswdBNmQQTofWExOresIG749DNmN3h85sAnNpP2moH/uGdM5tJ+11H+eWeNTyumEISIV+6fSPEbun0jwhV6H1P5wgvj6mbCowgesJazGTQcEHymQlaUtHQzE6TQN1WPKKvWRDTnv1qUuyGu1tgBYquQM/OdE8/U/tdSD3Cat58l5zIOhtYAcDTalh5ivI/OZXrVe5auwvVj95MYHn16RLm1DW6g13italBC7Ac8Z6zamZtYrcFjpgefPMotXqEc2Bv1bVn3gx6Dz9IrayhbUQWVkMDlt4wuJz22WPptWty1h0UDKA8gjPjJO9HtFJGhsAw2V7Ee908PGB6JtU1M9WLceCsDk+UKrEvrFicg/hOXSFzRcdOio3bHC2AjAwPAR6qzq6KrTZZSSORU20dYFK37Q2AKRscr1zmJqNVVptgsPeP0Hiek5tHQlpu26q8EWHhbMEjzMrrx2OmpHbMNto/WN7xHXn4wNTXaey4Vq+crndg9fLGJg1qPxTVbb8QMD6yent7XUWt7R2+KT72zbjnpCnU3pTQnspO5QFPagZ4/CUehtEA9KPtaxA/kSMzE7y5GPMZkftKpfZ3tVALFIO4DmJNuVXZMZQ3UTw9XqLl1L7brApOQAxHB5jaG6+3V1qbrCM5ILE8Tp+q5umPWKYMUjHWVfqIs5aicI+0E8cTjXWo4ylGpYea15H5y6rq3Ecxt6MwZ0G4dCR0kmtVXqVgwNvQY6cZ5jQKsysCCNwPhiTbwAAAA4A8JJtTXXelJLb36YHEa61aq2tfO1RzgcwiiHDibYMN6yVVi3VLZWcqenwjC5LrHRQQayAc/GFEJzLrkZdy06gr94V8fnLVW13JurYMPygPCEIBCEIFl7omzF7omzIJi9WmzF7x9BCBuq+s2Y/7vrNgE5tL+21H+edM5tL+31H+eWeNTyumEISIVu6fSb2i9p2fjjMxu6fST2L7X0/d3dfHMIqPH1mzB1PrNhUm7xhB+8YS1ksIQlaPUfeI85hG1vSYDtIMe0cgwM3CcNxta/VJVUH3oqklsbeDOuGBknAyepxyYwcz6W0do3tS1Vsqq2VBzgY8ek2hqzrcJYrqmnClgeOs6CAQQQCD1BGQZtSVoCERUz12qBmRHn2Xo66rqouA7MsMBsDHWabbmsrsOo0OUBAG8+M9EorLtZQV8iOIns2n/gVf6BA5tJetddzW2VljYWxWc5zjGJOm4pp00pdaXUYdnIGPTznelVdedlaLnyUCD1V2ftK0fH3lBgclo03Zp2GoqrsrHuMHH0MXUtZetHZ2jtMg7a1DDI6nPwzOr2XT/wACr/QJRFVF2ooVfIDAgebqK9WlljNa1hKbFIrGGB8PhyZ02J2dmkTwUkfRZ1wgTBwQfKPeFfTuCCVKnu9flFZfETFYr05HlKrm0dAvoDi7U1gHAHaflxNq/V/aAp36h8DOWfKnjynX2w+6Yby3HSavfo1jlvSZCE5o0dZ5mgt1C6ULXpe0XJ97tAM8+U9MdZ5+l9r09Iq9k3YJOe1USimqH/F6TjHvN+U6PXic+pS9n01qU7mTJZN4GMgeMy5tXbTYg0uxiuAe1U/+cQOYtVdRfcbUWxm3ICwBAXp/WX1dgt+zHsHRlB/ESy6ahFC9jWdoxkoOZznTWjR6ihVBBbNfvDkZBxKNUeyagDpRd/2t/vLaIZ1WrH86/lGtqW2o1P0Ix6RPsym6pru3xuYjByDnHjIE+zf8GnqfzgRs+0ht47Sslh8QesTTjV6ekVeygkE+8bQPwlqKXWxrrmDWsMe70UeQlFoQhCiEIQKp3RGip3RGmQTB3z6TZg749IRr9B6wg/dhAJzaX/Ean/MP6zpnNpv8Tqf8w/rLPGp5XTCEJEY3dPpNCjdvx72MZ+Exu6fSMOkIUdT6zZg6t6zYVN+9CFnWEqEhKnbYgdCDkZBHjJSqJTvVfEScpUeSPOKJwmsMMRMgEdRgQUeJmyVBCEJAQhCAQhCAQhCARWXxEaECc0HBzNYYOYs0qkJiHwmzKCEIQCEIQMYZ5ESUisMGWKWMhwwiwlD2DD+sSWZd4BziL2X834QJwlOy/m/CHZfzfhGicJTsv5vwh2X834QNr7saYqFfHPym4Oeox6TKCZ+8JpB8CPpDb056QB+4fSE08gxR0EDZzaf/ABOp9VnTOej/ABWo9V/KWNTyuiEISIxu6fSMOkVu6fSMOkIUdW9ZswdW9ZsKSzwhCzpCVH//2Q==' }, { name: '维度', type: 'number', value: 40.03190424323978 }, { name: '经度', type: 'number', value: 116.41731465378871 }, { name: '位置信息', type: 'string', value: '奥运村街道麦当劳(上品奥运村店)上品+(奥运村店)' }, { name: '会话类型', type: 'number', value: 1 }, { name: '对方 id', type: 'string', value: config.targetId }, { name: '静默消息', type: 'boolean', value: false }, ] }; var sendRichContentMessage = { name: '发送富文本消息', event: Service.sendRichContentMessage, eventName: 'sendMessage', desc: '发送富文本(图文)消息(sendRichContentMessage)', doc: 'https://docs.rongcloud.cn/v3/views/im/noui/guide/group/msgmanage/msgsend/web3.html#ImgTextMsg', params: [ { name: '图文标题', type: 'string', value: '标题: 融云' }, { name: '图文内容', type: 'string', value: '为用户提供 IM 即时通讯和音视频通讯云服务' }, { name: '图片信息', type: 'string', value: 'https://www.rongcloud.cn/images/newVersion/log_wx.png' }, { name: '图文链接', type: 'string', value: 'https://developer.rongcloud.cn' }, { name: '会话类型', type: 'number', value: 1 }, { name: '对方 id', type: 'string', value: config.targetId }, { name: '静默消息', type: 'boolean', value: false }, ] }; var getUnreadCount = { name: '获取会话未读数', event: Service.getUnreadCount, eventName: 'getUnreadCount', desc: '获取指定会话未读数', doc: 'https://docs.rongcloud.cn/v3/views/im/noui/guide/group/conversation/unreadcount/web3.html#clear', params: [ { name: '会话类型', type: 'number', value: 1 }, { name: '对方 id', type: 'string', value: config.targetId } ] }; var getTotalUnreadCount = { name: '获取会话未读数总数', event: Service.getTotalUnreadCount, eventName: 'getTotalUnreadCount', desc: '获取会话未读总数', doc: 'https://docs.rongcloud.cn/v3/views/im/noui/guide/group/conversation/unreadcount/web3.html#total', params: [ ] }; var clearUnreadCount = { name: '清除会话未读数', event: Service.clearUnreadCount, eventName: 'clearUnreadCount', desc: '清除指定会话未读数', doc: 'https://docs.rongcloud.cn/v3/views/im/noui/guide/group/conversation/unreadcount/web3.html#clearcode', params: [ { name: '会话类型', type: 'number', value: 1 }, { name: '对方 id', type: 'string', value: config.targetId } ] }; var joinChatRoom = { name: '加入聊天室', event: Service.joinChatRoom, eventName: 'joinChatRoom', desc: '加入指定聊天室, 并拉取消息', doc: 'https://docs.rongcloud.cn/v3/views/im/noui/guide/chatroom/manage/basic/join/web3.html', params: [ { name: '聊天室 id', type: 'string', value: config.targetId }, { name: '拉取消息数', type: 'number', value: 2 } ] }; var joinExistChatRoom = { name: '加入已存在的聊天室', event: Service.joinExistChatRoom, eventName: 'joinExistChatRoom', desc: '加入已存在的聊天室,若聊天室不存在,则加入失败', doc: 'https://docs.rongcloud.cn/v3/views/im/noui/guide/chatroom/manage/basic/join/web3.html#jion-exist', params: [ { name: '聊天室 id', type: 'string', value: config.targetId }, { name: '拉取消息数', type: 'number', value: 2 } ] }; var quitChatRoom = { name: '退出聊天室', event: Service.quitChatRoom, eventName: 'quitChatRoom', desc: '退出聊天室', doc: 'https://docs.rongcloud.cn/v3/views/im/noui/guide/chatroom/manage/basic/quit/web3.html', params: [ { name: '聊天室 id', type: 'string', value: config.targetId } ] }; var getChatRoomInfo = { name: '获取聊天室信息', event: Service.getChatRoomInfo, eventName: 'getChatRoomInfo', desc: '获取聊天室信息', doc: 'https://docs.rongcloud.cn/v3/views/im/noui/guide/chatroom/manage/basic/info/web3.html', params: [ { name: '聊天室 id', type: 'string', value: config.targetId }, { name: '获取人数', type: 'number', value: 20 }, { name: '排序方式', type: 'number', value: 1 } ] }; var getChatRoomHistoryMessages = { name: '获取聊天室历史消息', event: Service.getChatRoomHistoryMessages, eventName: 'getChatRoomHistoryMessages', desc: '获取聊天室历史消息', doc: 'https://docs.rongcloud.cn/v3/views/im/noui/guide/chatroom/msgmanage/storage/web3.html', params: [ { name: '聊天室 id', type: 'string', value: config.targetId }, { name: '获取时间', type: 'number', value: 0 }, { name: '获取个数', type: 'number', value: 20 }, { name: '排序方式', type: 'number', value: 0 } ] }; var setChatRoomEntry = { name: '设置聊天室属性', event: Service.setChatRoomEntry, eventName: 'setChatRoomEntry', desc: '设置聊天室自定义属性', doc: 'https://docs.rongcloud.cn/v3/views/im/noui/guide/chatroom/manage/key/set/web3.html', params: [ { name: '属性 key', type: 'string', value: 'chrmKey1' }, { name: '属性 value', type: 'string', value: '我是一个聊天室 value' }, { name: '是否退出清除', type: 'boolean', value: true }, { name: '是否发送消息', type: 'boolean', value: true }, { name: '附加信息', type: 'string', value: '我是消息中的附加信息' }, { name: '聊天室 id', type: 'string', value: config.targetId } ] }; var forceSetChatRoomEntry = { name: '设置聊天室属性(强制)', event: Service.forceSetChatRoomEntry, eventName: 'forceSetChatRoomEntry', desc: '强制设置聊天室自定义属性', doc: 'https://docs.rongcloud.cn/v3/views/im/noui/guide/chatroom/manage/key/set/web3.html#force', params: [ { name: '属性 key', type: 'string', value: 'chrmKey2' }, { name: '属性 value', type: 'string', value: '我是一个聊天室 value' }, { name: '是否退出清除', type: 'boolean', value: true }, { name: '是否发送消息', type: 'boolean', value: true }, { name: '附加信息', type: 'string', value: '我是消息中的附加信息' }, { name: '聊天室 id', type: 'string', value: config.targetId } ] }; var removeChatRoomEntry = { name: '删除聊天室属性', event: Service.removeChatRoomEntry, eventName: 'removeChatRoomEntry', desc: '删除聊天室自定义属性', doc: 'https://docs.rongcloud.cn/v3/views/im/noui/guide/chatroom/manage/key/remove/web3.html#del', params: [ { name: '属性 key', type: 'string', value: 'chrmKey1' }, { name: '是否发送消息', type: 'boolean', value: true }, { name: '附加信息', type: 'string', value: '我是消息中的附加信息' }, { name: '聊天室 id', type: 'string', value: config.targetId } ] }; var forceRemoveChatRoomEntry = { name: '删除聊天室属性(强制)', event: Service.forceRemoveChatRoomEntry, eventName: 'forceRemoveChatRoomEntry', desc: '强制删除聊天室自定义属性', doc: 'https://docs.rongcloud.cn/v3/views/im/noui/guide/chatroom/manage/key/remove/web3.html#forcedel', params: [ { name: '属性 key', type: 'string', value: 'chrmKey2' }, { name: '是否发送消息', type: 'boolean', value: true }, { name: '附加信息', type: 'string', value: '我是消息中的附加信息' }, { name: '聊天室 id', type: 'string', value: config.targetId } ] }; var getChatRoomEntry = { name: '获取聊天室属性', event: Service.getChatRoomEntry, eventName: 'getChatRoomEntry', desc: '获取指定聊天室自定义属性', doc: 'https://docs.rongcloud.cn/v3/views/im/noui/guide/chatroom/manage/key/query/web3.html', params: [ { name: '属性 key', type: 'string', value: 'chrmKey1' }, { name: '聊天室 id', type: 'string', value: config.targetId } ] }; var getAllChatRoomEntries = { name: '获取聊天室属性(所有)', event: Service.getAllChatRoomEntries, eventName: 'getAllChatRoomEntries', desc: '获取所有聊天室自定义属性', doc: 'https://docs.rongcloud.cn/v3/views/im/noui/guide/chatroom/manage/key/query/web3.html#getall', params: [ { name: '聊天室 id', type: 'string', value: config.targetId } ] }; var sendChatRoomMessage = { name: '发送聊天室消息', event: Service.sendChatRoomMessage, eventName: 'sendMessage', desc: '发送聊天室消息, 以文本消息为例(TextMessage)', doc: 'https://docs.rongcloud.cn/im/imlib/web/message-send/#example', params: [ { name: '文字内容', type: 'string', value: '我是一条聊天室的文字消息' }, { name: '聊天室 id', type: 'string', value: config.targetId } ] }; var joinRTCRoom = { name: '加入 RTC 房间', event: Service.joinRTCRoom, eventName: 'rtc.join', desc: '', params: [ { name: '房间 id', type: 'string', value: config.targetId }, { name: '模式', type: 'number', value: 0 } ] }; var pingRTCRoom = { name: 'Ping RTC', event: Service.pingRTCRoom, eventName: 'rtc.ping', desc: '', params: [ { name: '房间 id', type: 'string', value: config.targetId } ] }; var setRTCData = { name: '设置 RTC 数据', event: Service.setRTCData, eventName: '', desc: '', params: [ { name: '房间 id', type: 'string', value: config.targetId }, { name: 'key', type: 'string', value: 'key' }, { name: 'value', type: 'string', value: 'value' }, { name: 'isInner', type: 'boolean', value: false }, { name: 'apiType', type: 'number', value: 1 } ] }; var getRTCData = { name: '获取 RTC 数据', event: Service.getRTCData, eventName: '', desc: '', params: [ { name: '房间 id', type: 'string', value: config.targetId }, { name: 'key', type: 'string', value: 'key' }, { name: 'isInner', type: 'boolean', value: false }, { name: 'apiType', type: 'number', value: 1 } ] }; var removeRTCData = { name: '删除 RTC 数据', event: Service.removeRTCData, eventName: '', desc: '', params: [ { name: '房间 id', type: 'string', value: config.targetId }, { name: 'key', type: 'string', value: 'key' }, { name: 'isInner', type: 'boolean', value: false }, { name: 'apiType', type: 'number', value: 1 } ] }; var getRTCToken = { name: '获取 RTC Token', event: Service.getRTCToken, eventName: '', desc: '', params: [ { name: '房间 id', type: 'string', value: config.targetId } ] }; var getRTCRoomInfo = { name: '获取 RTC 房间信息', event: Service.getRTCRoomInfo, eventName: '', desc: '', params: [ { name: '房间 id', type: 'string', value: config.targetId } ] }; var setRTCUserInfo = { name: '设置 RTC 人员信息', event: Service.setRTCUserInfo, eventName: 'rtc.getRTCUserInfoList', desc: '', params: [ { name: '房间 id', type: 'string', value: config.targetId } ] }; var getRTCUserInfoList = { name: '获取 RTC 人员列表', event: Service.getRTCUserInfoList, eventName: '', desc: '', params: [ { name: '房间 id', type: 'string', value: config.targetId } ] }; var removeRTCUserInfo = { name: '删除 RTC 人员信息', event: Service.removeRTCUserInfo, eventName: '', desc: '', params: [ { name: '房间 id', type: 'string', value: config.targetId } ] }; var quitRTCRoom = { name: '退出 RTC 房间', event: Service.quitRTCRoom, eventName: 'rtc.quit', desc: '', params: [ { name: '房间 id', type: 'string', value: config.targetId } ] }; win.RongIM = win.RongIM || {}; var DefailtReadyApiQueue = [ [disconnect, reconnect], [getConversationList, removeConversation, setConversationStatus, getUnreadCount, getTotalUnreadCount, clearUnreadCount], [sendTextMessage, sendImageMessage, sendRecallMessage, sendFileMessage, sendVoiceMessage, sendRegisterMessage, sendAtMessage, /*sendAtMessageByErrorParamField,*/ sendLocationMessage, sendRichContentMessage], [getHistoryMessages, deleteRemoteMessages, clearHistoryMessages], [joinChatRoom, joinExistChatRoom, getChatRoomInfo, sendChatRoomMessage, getChatRoomHistoryMessages], [setChatRoomEntry, getChatRoomEntry, forceSetChatRoomEntry, getAllChatRoomEntries, removeChatRoomEntry, forceRemoveChatRoomEntry], [quitChatRoom], [joinRTCRoom, pingRTCRoom, setRTCData, getRTCData, removeRTCData, getRTCToken, getRTCRoomInfo, getRTCUserInfoList, setRTCUserInfo, removeRTCUserInfo], [quitRTCRoom], ]; urlQueryConfig.isMini && utils.forEach(DefailtReadyApiQueue, function (list, i) { utils.forEach(list, function (item, j) { if (MiniUnSupportEventList.indexOf(item.eventName) !== -1) { list.splice(j, 1); } }, { isReverse: true }) }); win.RongIM.DefailtReadyApiQueue = DefailtReadyApiQueue; win.RongIM.ApiList = [ getConversationList ]; window.RongIM.Api = { changeUser: changeUser } })(window, { RongIM: RongIM }); ================================================ FILE: api-test/js/common/service.js ================================================ (function(win) { var RongIMLib = win.RongIMLib, RongIM = win.RongIM, RongIMClient = RongIMLib.RongIMClient, utils = RongIM.Utils; var im; // var sendMsgTimeout = RongIM.config.isDebug ? 300 : 0; var selfUserId; // 缓存消息, 用作撤回、删除等操作的参数 var CacheMsg = { eventEmitter: new utils.EventEmitter(), _list: [], set: function (msg) { this._list.push(msg); this.eventEmitter.emit('msgChanged'); }, remove: function (msg) { var list = this._list; utils.forEach(list, function(child, index) { if (child.messageUId === msg.messageUId) { list.splice(index, 1); } }, { isReverse: true }); this.eventEmitter.emit('msgChanged'); }, getLast: function () { var list = this._list, length = list.length; var msg = {}; if (length) { msg = list[length - 1]; } return msg; } }; /** * 初始化以及链接 * @param {object} config * @param {string} config.appkey 融云颁发的 appkey * @param {string} config.token 融云颁发的 token(代表某一个用户) * @param {Object} watcher * @param {Object} watcher.status 监听链接状态的变化 * @param {Object} watcher.message 监听消息的接收 */ function init(config, watcher) { watcher = watcher || {}; config = utils.clearUndefKey(config); config = utils.copy(config); var navi = config.navi; if (config.isPolling) { config.connectType = 'comet'; } if (navi) { var navigators; navi = navi.replace(/\s/g, ''); if (navi.indexOf(',') !== -1) { navigators = navi.split(','); } else { navigators = [navi]; } config.navigators = navigators; } // config.customCMP = ['120.92.13.84:80'] // config.isDebug = true; im = RongIMLib.init(config); im.watch({ conversation: function (event) { console.log('watch conversation', event); }, message: function (event) { var message = event.message; var hasMore = event.hasMore; watcher.message(message); console.warn('received messages', event); // message.xxx.xxx; }, status: function (event) { var status = event.status; console.log('status changed', event); // 不处理的状态码 var unHandleStatus = []; if (unHandleStatus.indexOf(status) === -1) { watcher.status(status); } }, chatroom: function (event) { console.warn('chatroom', event); var updatedEntries = event.updatedEntries; watcher.chatroom(updatedEntries); } }); if(!config.customCMP){ delete config.customCMP; } return im.connect(config); } /** * 断开链接 * 文档: https://docs.rongcloud.cn/im/imlib/web/connect/#disconnect */ function disconnect() { return im.disconnect(); } function changeUser(config) { return im.changeUser(config); } /** * 重新链接 * 文档: https://docs.rongcloud.cn/im/imlib/web/connect/#reconnect */ function reconnect() { return im.reconnect(); } /** * 获取会话列表 * 文档: https://docs.rongcloud.cn/im/imlib/web/conversation/get-list/ * * @param {number} count 获取会话的数量 */ function getConversationList(count) { return im.Conversation.getList({ count: count }); } /** * 删除会话列表 * 文档: https://docs.rongcloud.cn/im/imlib/web/conversation/remove/ */ function removeConversation(conversationType, targetId) { conversationType = Number(conversationType); return im.Conversation.remove({ type: conversationType, targetId: targetId }); } /** * 获取历史消息 * 文档: https://docs.rongcloud.cn/im/imlib/web/message-list/get-list/ * * @param {number} timestrap 时间戳 * @param {number} count 数量 */ function getHistoryMessages(timestrap, count, conversationType, targetId) { conversationType = Number(conversationType); count = Number(count); timestrap = Number(timestrap); var conversation = im.Conversation.get({ type: conversationType, targetId: targetId }); return conversation.getMessages({ timestrap: timestrap, count: count }); } /** * 按时间删除历史消息 * 文档: https://docs.rongcloud.cn/im/imlib/web/message-list/remove-list/#_1 * * @param {number} timestrap 时间戳 */ function clearHistoryMessages(timestamp, conversationType, targetId) { conversationType = Number(conversationType); timestamp = Number(timestamp); var conversation = im.Conversation.get({ type: conversationType, targetId: targetId }); return conversation.clearMessages({ timestrap: timestamp }); } /** * 按消息删除历史消息 * @param {string} messageUId 消息在 server 的唯一标识 * @param {number} sentTime 消息发送时间 * @param {number} messageDirection 消息方向 */ function deleteRemoteMessages(messageUId, sentTime, messageDirection, conversationType, targetId) { var lastMsg = CacheMsg.getLast() || {}; conversationType = Number(conversationType) || lastMsg.type; sentTime = Number(sentTime) || lastMsg.sentTime; messageDirection = Number(messageDirection) || lastMsg.direction; var deleteMsg = { messageUId: messageUId, sentTime: sentTime, messageDirection: messageDirection }; var messages = [ deleteMsg ]; var conversation = im.Conversation.get({ type: conversationType, targetId: targetId }); return conversation.deleteMessages(messages); } /** * 获取指定会话未读数 * 文档: https://docs.rongcloud.cn/im/imlib/web/conversation/unreadcount/#get-one * * @param {number} conversationType 会话类型 * @param {string} targetId 目标 id (对方 id、群组 id、聊天室 id 等) */ function getUnreadCount(conversationType, targetId) { conversationType = Number(conversationType); var conversation = im.Conversation.get({ type: conversationType, targetId: targetId }); return conversation.getUnreadCount() // console.log(conversationType, targetId); // return utils.Defer.resolve('TODO'); } /** * 获取所有会话未读数 * 文档: https://docs.rongcloud.cn/im/imlib/web/conversation/unreadcount/#get-all */ function getTotalUnreadCount() { return im.Conversation.getTotalUnreadCount(); } /** * 清除指定会话未读数 * 文档: https://docs.rongcloud.cn/im/imlib/web/conversation/unreadcount/#clear */ function clearUnreadCount(conversationType, targetId) { conversationType = Number(conversationType); var conversation = im.Conversation.get({ type: conversationType, targetId: targetId }); return conversation.read(); } function sendMessage(conversationType, targetId, msg) { conversationType = Number(conversationType); var conversation = im.Conversation.get({ type: conversationType, targetId: targetId }); return conversation.send(msg).then(function (msg) { CacheMsg.set(msg); return msg; }); } /** * 发送文本消息 * 文档: https://docs.rongcloud.cn/im/imlib/web/message-send/#text * 注意事项: * 1: 单条消息整体不得大于128K * 2: conversationType 类型是 number,targetId 类型是 string * * @param {string} text 文字内容 * @param {number} conversationType 会话类型 * @param {string} targetId 目标 id (对方 id、群组 id、聊天室 id 等) * @param {booleam} disableNotification 是否推送消息 */ function sendTextMessage(text, conversationType, targetId, isStatusMessage, disableNotification) { var content = { content: text // 文本内容 }; return sendMessage(conversationType, targetId, { content: content, messageType: 'RC:TxtMsg', isStatusMessage: isStatusMessage, disableNotification: disableNotification }); } /** * 发送图片消息 * 文档: https://docs.rongcloud.cn/im/imlib/web/message-send/#image * 注意事项: * 1. 略缩图(content 字段)必须是 base64 字符串, 类型必须为 jpg * 2. base64 略缩图必须不带前缀 * 3. base64 字符串大小不可超过 100 k * 4. 可通过 FileReader 或者 canvas 对图片进行压缩, 生成压缩后的 base64 字符串 * imageUri 为上传至服务器的原图 url, 用来展示高清图片 * 上传图片需开发者实现. 可参考上传插件: https://docs.rongcloud.cn/im/imlib/web/plugin/upload * * @param {string} base64 图片 base64 缩略图 * @param {string} imageUri 图片上传后的 url */ function sendImageMessage(base64, imageUri, conversationType, targetId, disableNotification) { var content = { content: base64, // 压缩后的 base64 略缩图, 用来快速展示图片 imageUri: imageUri // 上传到服务器的 url. 用来展示高清图片 }; return sendMessage(conversationType, targetId, { content: content, messageType: 'RC:ImgMsg', disableNotification }); } /** * 发送文件消息 * 文档:https://docs.rongcloud.cn/im/imlib/web/message-send/#file * * @param {string} fileName 文件名 * @param {string} fileSize 文件大小 * @param {string} fileType 文件类型 * @param {string} fileUrl 文件上传后的 url */ function sendFileMessage(fileName, fileSize, fileType, fileUrl, conversationType, targetId, disableNotification) { var content = { name: fileName, // 文件名 size: fileSize, // 文件大小 type: fileType, // 文件类型 fileUrl: fileUrl // 文件地址 }; return sendMessage(conversationType, targetId, { content: content, messageType: 'RC:FileMsg', disableNotification }); } /** * 高质量语音消息: https://docs.rongcloud.cn/im/introduction/message_structure/#hqvoice_message * 注意事项: * 融云不提供声音录制的方法. remoteUrl 的生成需开发者实现 * * @param {string} remoteUrl 语音上传后的 url * @param {number} duration 语音时长 */ function sendVoiceMessage(remoteUrl, type, duration, conversationType, targetId, disableNotification) { var content = { remoteUrl: remoteUrl, // 音频 url, 建议格式: aac duration: duration, // 音频时长 type: type }; return sendMessage(conversationType, targetId, { content: content, messageType: 'RC:HQVCMsg', disableNotification }); } /** * 撤回消息: https://docs.rongcloud.cn/im/imlib/web/message-send/#recall * 注意事项: * 消息撤回操作服务器端没有撤回时间范围的限制,由客户端决定 * * @param {string} messageUId 撤回的消息 Uid * @param {number} sentTime 撤回的消息 sentTime */ function sendRecallMessage(messageUId, sentTime, conversationType, targetId, disableNotification) { var recallMsg; if (messageUId && sentTime && conversationType && targetId) { recallMsg = { messageUId: messageUId, sentTime: sentTime, disableNotification: disableNotification }; } else { var lastMsg = CacheMsg.getLast() || {}; recallMsg = lastMsg; recallMsg.disableNotification = disableNotification; } return im.Conversation.get({ type: conversationType, targetId: targetId, }).recall(recallMsg); } /** * 发送 @ 消息(此处以文本消息举例) * 文档: https://docs.rongcloud.cn/im/imlib/web/message-send/#example * * @param {string} text 文字内容 * @param {string} methiondId @ 对象的 id */ function sendAtMessage(text, methiondId, conversationType, targetId, disableNotification) { conversationType = Number(conversationType); var isMentioned = true; var content = { content: text }; return im.Conversation.get({ type: conversationType, targetId: targetId }).send({ content: content, messageType: 'RC:TxtMsg', isMentioned: isMentioned, mentionedUserIdList: [methiondId], // @ 人 id 列表 mentionedType: 2, disableNotification }); } //测试错误参数下发送 @ 消息 function sendAtMessageByErrorParamField(text, methiondId, conversationType, targetId, disableNotification) { conversationType = Number(conversationType); var isMentioned = true; var content = { content: text }; return im.Conversation.get({ type: conversationType, targetId: targetId }).send({ content: content, messageType: 'RC:TxtMsg', isMentiond: isMentioned, mentiondUserIdList: [methiondId], // @ 人 id 列表 mentiondType: 1, disableNotification }); } /** * 注册自定义消息 * 文档: https://docs.rongcloud.cn/im/imlib/web/message-send/#custom * * @param {string} messageName 注册消息的 Web 端类型名 * @param {string} messageType 注册消息的唯一名称. 注: 此名称需多端一致 * @param {boolean} isCounted 是否计数 * @param {boolean} isPersited 是否存储 * @param {Array} props 消息包含的字段集合 */ function registerMessage(/* messageName, messageType, isCounted, isPersited, props */) { // var mesasgeTag = new RongIMLib.MessageTag(isCounted, isPersited); //true true 保存且计数,false false 不保存不计数。 // props = props.split(','); // 将字符串截取为数组. 此处为 Demo 逻辑, 与融云无关 // RongIMClient.registerMessageType(messageName, messageType, mesasgeTag, props); // 废弃此概念 return utils.Defer.resolve(); } /** * 发送自定义消息 * 文档: https://docs.rongcloud.cn/im/imlib/web/message-send/#custom * * @param {string} messageType 注册消息的 Web 端类型名 * @param {*} props 消息包含的字段集合 */ function sendRegisterMessage(messageType, props, conversationType, targetId, disableNotification) { var content = props.split(','); return im.Conversation.get({ type: conversationType, targetId: targetId }).send({ messageType: messageType, content: { content: content }, disableNotification }); } /** * 发送位置消息 * 文档: https://docs.rongcloud.cn/im/imlib/web/message-send/#location * 注意事项: * 1. 缩略图必须是base64码的jpg图, 而且不带前缀"data:image/jpeg;base64,", 不得超过100K * 2. 需要开发者做显示效果, 一般显示逻辑: 图片加链接, 传入经纬度并跳转进入地图网站 * * @param {string} base64 位置缩略图 * @param {number} latitude 维度 * @param {number} longitude 经度 * @param {string} poi 位置信息 */ function sendLocationMessage(base64, latitude, longitude, poi, conversationType, targetId, disableNotification) { var content = { latitude: latitude, longitude: longitude, poi: poi, content: base64 }; return im.Conversation.get({ type: conversationType, targetId: targetId }).send({ messageType: 'RC:LBSMsg', content: content, disableNotification }); } /** * 发送富文本(图文)消息 * 文档: https://docs.rongcloud.cn/im/imlib/web/message-send/#rich-content * * @param {string} title 图文标题 * @param {number} content 图文内容 * @param {number} imageUri 显示图片的 url(图片信息) * @param {string} url 点击图文后打开的 url */ function sendRichContentMessage(title, content, imageUri, url, conversationType, targetId, disableNotification) { content = { title: title, content: content, imageUri: imageUri, url: url }; return im.Conversation.get({ type: conversationType, targetId: targetId }).send({ messageType: 'RC:ImgTextMsg', content: content, disableNotification }); } /** * 加入聊天室 * 文档: https://docs.rongcloud.cn/im/imlib/web/chatroom/#join * * @param {string} chatRoomId 聊天室 id * @param {number} count 拉取消息数量 */ function joinChatRoom(chatRoomId, count) { return im.ChatRoom.get({ id: chatRoomId }).join({ count: count }); } /** * 加入已存在的聊天室 * 文档: https://docs.rongcloud.cn/im/imlib/web/chatroom/#join * * @param {string} chatRoomId 聊天室 id * @param {number} count 拉取消息数量 */ function joinExistChatRoom(chatRoomId, count) { return im.ChatRoom.get({ id: chatRoomId }).joinExist({ count: count }); } /** * 退出聊天室 * 文档: https://docs.rongcloud.cn/im/imlib/web/chatroom/#quit * * @param {string} chatRoomId 聊天室 id */ function quitChatRoom(chatRoomId) { return im.ChatRoom.get({ id: chatRoomId }).quit(); } /** * 获取聊天室信息 * 文档: https://docs.rongcloud.cn/im/imlib/web/chatroom/#get * * @param {string} chatRoomId 聊天室 id * @param {string} count 获取人数 * @param {string} order 排序方式 */ function getChatRoomInfo(chatRoomId, count, order) { return im.ChatRoom.get({ id: chatRoomId }).getInfo({ count: count, order: order }); } function getChatRoomHistoryMessages(chatRoomId, timestrap, count, order) { return im.ChatRoom.get({ id: chatRoomId }).getMessages({ timestrap: timestrap, count: count, order: order }); } /** * 发送聊天室消息(以文本消息为例) * 文档: https://docs.rongcloud.cn/im/imlib/web/message-send/#text * * @param {string} text 文字内容 */ function sendChatRoomMessage(text, targetId) { var content = { content: text // 文本内容 }; return im.ChatRoom.get({ id: targetId }).send({ messageType: 'RC:TxtMsg', content: content }) } function setChatRoomEntry(key, value, isAutoDelete, isSendNotification, extra, chatRoomId) { var entry = { key: key, value: value, notificationExtra: extra, isAutoDelete: isAutoDelete, isSendNotification: isSendNotification }; return im.ChatRoom.get({ id: chatRoomId }).setEntry(entry); } function forceSetChatRoomEntry(key, value, isAutoDelete, isSendNotification, extra, chatRoomId) { var entry = { key: key, value: value, notificationExtra: extra, isAutoDelete: isAutoDelete, isSendNotification: isSendNotification }; return im.ChatRoom.get({ id: chatRoomId }).forceSetEntry(entry); } function removeChatRoomEntry(key, isSendNotification, extra, chatRoomId) { var entry = { key: key, notificationExtra: extra, isSendNotification: isSendNotification }; return im.ChatRoom.get({ id: chatRoomId }).removeEntry(entry); } function forceRemoveChatRoomEntry(key, isSendNotification, extra, chatRoomId) { var entry = { key: key, notificationExtra: extra, isSendNotification: isSendNotification }; return im.ChatRoom.get({ id: chatRoomId }).forceRemoveEntry(entry); } function getChatRoomEntry(key, chatRoomId) { return im.ChatRoom.get({ id: chatRoomId }).getEntry(key); } function getAllChatRoomEntries(chatRoomId) { return im.ChatRoom.get({ id: chatRoomId }).getAllEntries(); } function joinRTCRoom(roomId, mode) { return im.RTC.get({ roomId: roomId, mode: mode }).join(); } function pingRTCRoom(roomId, mode) { return im.RTC.get({ roomId: roomId }).ping(); } function setRTCData(roomId, key, value, isInner, apiType, message) { return im.RTC.get({ roomId: roomId }).setData(key, value, isInner, apiType, message); } function getRTCData(roomId, key, isInner, apiType) { return im.RTC.get({ roomId: roomId }).getData([key], isInner, apiType); } function removeRTCData(roomId, key, isInner, apiType) { return im.RTC.get({ roomId: roomId }).removeData([key], isInner, apiType); } function getRTCToken(roomId) { return im.RTC.get({ roomId: roomId }).getToken(); } function getRTCRoomInfo(roomId) { return im.RTC.get({ roomId: roomId }).getRoomInfo(); } function getRTCUserInfoList(roomId) { return im.RTC.get({ roomId: roomId }).getUserInfoList(); } function setRTCUserInfo(roomId) { return im.RTC.get({ roomId: roomId }).setUserInfo({ key: 'test', value: 'test hahahah' }); } function removeRTCUserInfo(roomId) { return im.RTC.get({ roomId: roomId }).removeUserInfo({ key: 'test' }); } function quitRTCRoom(roomId, mode) { return im.RTC.get({ roomId: roomId, mode: mode }).quit(); } function setConversationStatus(isNotification, isTop, conversationType, targetId) { return im.Conversation.get({ type: conversationType, targetId: targetId }).setStatus({ notificationStatus: isNotification, isTop: isTop }); } function getLastCacheMsgUId() { return CacheMsg.getLast().messageUId; } function getLastCacheMsgSentTime() { return CacheMsg.getLast().sentTime; } function getLastCacheMsgDirection() { return CacheMsg.getLast().direction; } win.RongIM = win.RongIM || {}; win.RongIM.Service = { init: init, disconnect: disconnect, reconnect: reconnect, registerMessage: registerMessage, sendRegisterMessage: sendRegisterMessage, getConversationList: getConversationList, removeConversation: removeConversation, getHistoryMessages: getHistoryMessages, clearHistoryMessages: clearHistoryMessages, deleteRemoteMessages: deleteRemoteMessages, sendTextMessage: sendTextMessage, sendImageMessage: sendImageMessage, sendFileMessage: sendFileMessage, sendVoiceMessage: sendVoiceMessage, sendAtMessage: sendAtMessage, sendAtMessageByErrorParamField: sendAtMessageByErrorParamField, sendLocationMessage: sendLocationMessage, sendRichContentMessage: sendRichContentMessage, sendRecallMessage: sendRecallMessage, getUnreadCount: getUnreadCount, getTotalUnreadCount: getTotalUnreadCount, clearUnreadCount: clearUnreadCount, joinChatRoom: joinChatRoom, joinExistChatRoom: joinExistChatRoom, quitChatRoom: quitChatRoom, getChatRoomInfo: getChatRoomInfo, getChatRoomHistoryMessages: getChatRoomHistoryMessages, sendChatRoomMessage: sendChatRoomMessage, setChatRoomEntry: setChatRoomEntry, forceSetChatRoomEntry: forceSetChatRoomEntry, removeChatRoomEntry: removeChatRoomEntry, forceRemoveChatRoomEntry: forceRemoveChatRoomEntry, getChatRoomEntry: getChatRoomEntry, getAllChatRoomEntries: getAllChatRoomEntries, getLastCacheMsgSentTime: getLastCacheMsgSentTime, getLastCacheMsgUId: getLastCacheMsgUId, getLastCacheMsgDirection: getLastCacheMsgDirection, msgEmitter: CacheMsg.eventEmitter, changeUser: changeUser, joinRTCRoom: joinRTCRoom, quitRTCRoom: quitRTCRoom, pingRTCRoom: pingRTCRoom, setRTCData: setRTCData, getRTCData: getRTCData, removeRTCData: removeRTCData, getRTCToken: getRTCToken, getRTCRoomInfo: getRTCRoomInfo, getRTCUserInfoList: getRTCUserInfoList, setRTCUserInfo: setRTCUserInfo, removeRTCUserInfo: removeRTCUserInfo, setConversationStatus: setConversationStatus }; })(window); ================================================ FILE: api-test/js/common/utils.js ================================================ (function (win) { var Defer = win.Promise || ES6Promise; var Vue = win.Vue; var TypeColor = { FAILED: '#ed4014', MSG: '#2db7f5', STATUS: '#ff9900' }; var ConversationName = { 1: '单聊', 3: '群聊', 4: '聊天室', 5: '客服', 6: '系统', 7: '公众号', 8: '公众号' }; var StatusName = { 0: '已连接', 1: '正在链接', 2: '主动断开链接', 3: '网络不可用', 4: '链接关闭', 5: 'Socket Error', 6: '其他设备登录, 被踢', 12: '被封禁', 20: 'AppKey 错误', 201: '正在请求 Navi', 202: '请求 Navi 成功', 203: '请求 Navi 错误', 204: '请求 Navi 超时' }; var SuccessStatus = [0, 1, 2, 4, 201, 202, 203, 204]; var noop = function () {}; function isObject(obj) { return Object.prototype.toString.call(obj) === '[object Object]'; } function isArray(arr) { return Object.prototype.toString.call(arr) === '[object Array]'; } function isNodeList(arr) { return Object.prototype.toString.call(arr) === '[object NodeList]' || Object.prototype.toString.call(arr) === '[object HTMLCollection]'; } function isFunction(arr) { return Object.prototype.toString.call(arr) === '[object Function]'; } function isString(str) { return Object.prototype.toString.call(str) === '[object String]'; } function isBoolean(str) { return Object.prototype.toString.call(str) === '[object Boolean]'; } function isUndefined(str) { return Object.prototype.toString.call(str) === '[object Undefined]'; } function isNull(str) { return Object.prototype.toString.call(str) === '[object Null]'; } function isNumber(str) { return Object.prototype.toString.call(str) === '[object Number]'; } function defered(callback) { return new Defer(callback); } function tplEngine(temp, data, regexp) { var replaceAction = function (object) { return temp.replace(regexp || (/{([^}]+)}/g), function (match, name) { if (match.charAt(0) === '\\') return match.slice(1); return (object[name] !== undefined) ? object[name] : '{' + name + '}'; }); }; if (!(Object.prototype.toString.call(data) === '[object Array]')) data = [data]; var ret = []; for (var i = 0, j = data.length; i < j; i++) { ret.push(replaceAction(data[i])); } return ret.join(''); } function forEach(obj, callback, options) { options = options || {}; callback = callback || noop; var isReverse = options.isReverse; var loopObj = function() { for (var key in obj) { callback(obj[key], key, obj); } }; var loopArr = function() { if (isReverse) { for (var i = obj.length - 1; i >= 0; i--) { callback(obj[i], i); } } else { for (var j = 0, len = obj.length; j < len; j++) { callback(obj[j], j); } } }; if (isObject(obj)) { loopObj(); } if (isArray(obj) || isNodeList(obj)) { loopArr(); } }; function clearUndefKey(obj) { forEach(obj, function (key, val) { if (isUndefined(val)) { delete obj[key]; } }); return obj; } function map(arr, event) { forEach(arr, function(item, index) { arr[index] = event(item, index); }); return arr; } function deepMap(arr, event) { forEach(arr, function (item, index) { if (isArray(item) || isObject(item)) { arr[index] = deepMap(item, event); } else { arr[index] = event(item, index); } }); return arr; } function isEqual(obj1, obj2) { if (isObject(obj1) && isObject(obj2)) { var isEq = true; forEach(obj1, function (val, key) { if (obj2[key] !== val) { isEq = false; } }); return isEq; } else { return obj1 == obj2; } } function getDom(id) { return document.getElementById(id); } function queryAllDom(sel) { return document.querySelectorAll(sel); } function queryDom(sel) { return document.querySelector(sel); } function removeDom(dom) { var parent = dom.parentNode || dom.parentElement; parent.removeChild(dom); } function getParent(dom) { return dom.parentNode || dom.parentElement; } function getChildren(dom) { return dom.children; } function getTemp(id) { var dom = getDom(id); return dom.innerHTML; } function getDomIndex(dom) { var parent = getParent(dom); var children = parent.children; for (var i = 0, max = children.length; i < max; i++) { var child = children[i]; if (dom === child) { return i; } } return -1; } function toJSON(obj) { return JSON.stringify(obj); } function parseJSON(str) { var val; try { val = JSON.parse(str); } catch(e) {} return val; } function copy(obj) { var copyObj = parseJSON(toJSON(obj)); return copyObj; } function hasClass(el, className) { if (!el) { return false; } var classList = el.classList; for (var i = 0, max = classList.length; i < max; i++) { if (classList[i] === className) { return true; } } return false; } function timestampToString(timestamp) { var date = timestamp ? new Date(timestamp) : new Date(); Y = date.getFullYear() + '-'; M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'; D = date.getDate() + ' '; h = date.getHours() + ':'; m = date.getMinutes() + ':'; s = date.getSeconds(); return Y + M + D + h + m + s; } function extend(destination, sources) { for (var key in sources) { var value = sources[key]; if (!isUndefined(value)) { destination[key] = value; } } return destination; }; /** * 封装弹框组件 * @param {object} options */ function mountDialog(options, instance) { options.parent = instance; var Dialog = Vue.extend(options); var instance = new Dialog({ el: document.createElement('div') }); var wrap = document.getElementsByTagName('body')[0]; wrap.appendChild(instance.$el); return instance; } function reverse(obj) { var newObj = copy(obj); return newObj.reverse(); } function openUrl(url) { window.open(url); } function getBase64Image() { var canvas = document.createElement('canvas'); canvas.width = 100; canvas.height = 100; var context = canvas.getContext('2d'); context.font = '20pt Arial'; context.fillStyle = 'blue'; context.fillText('RongCloud.cn', 10, 20); var content = canvas.toDataURL('image/jpeg'); content = content.replace('data:image/jpeg;base64,', ''); return content; } var increaseNumber = 0; function getIncreasNumber() { return ++increaseNumber; } var EventEmitter = function () { this._events = {}; this.on = function (name, event) { var _events = this._events[name] || []; _events.push(event); this._events[name] = _events; }; this.emit = function (name, data) { var _events = this._events[name]; forEach(_events, function(event) { event(data); }); }; }; var Storage = { ConfigKey: 'config', get: function (key) { var str = localStorage.getItem(key); return parseJSON(str); }, set: function (key, val) { var str = toJSON(val); localStorage.setItem(key, str); } }; function getUrlQuery() { var url = location.search; //获取url中"?"符后的字串 var theRequest = new Object(); if (url.indexOf('?') != -1) { var str = url.substr(1); strs = str.split('&'); for (var i = 0; i < strs.length; i++) { theRequest[strs[i].split('=')[0]] = unescape(strs[i].split('=')[1]); } } return theRequest; } function getRCUrlQuery() { var theRequest = getUrlQuery(); var transMap = { 'true': true, 'false': false }; map(theRequest, function (val, key) { var transVal = transMap[val]; if (!isUndefined(transVal)) { val = transVal; } return val; }); forEach(theRequest, function (val, key) { if (key === 'encodeToken') { theRequest.token = decodeURIComponent(val); delete theRequest.encodeToken; } if (key === 'isMini') { delete theRequest.isMini; } }); return theRequest; } function deferNoop() { return Defer.resolve(); } win.RongIM = win.RongIM || {}; win.RongIM.Utils = { Storage: Storage, TypeColor: TypeColor, ConversationName: ConversationName, StatusName: StatusName, SuccessStatus: SuccessStatus, EventEmitter: EventEmitter, noop: noop, isNumber: isNumber, isFunction: isFunction, map: map, deepMap: deepMap, isEqual: isEqual, clearUndefKey: clearUndefKey, Defer: Defer, defered: defered, tplEngine: tplEngine, forEach: forEach, toJSON: toJSON, parseJSON: parseJSON, copy: copy, removeDom: removeDom, getParent: getParent, getChildren: getChildren, hasClass: hasClass, getDomIndex: getDomIndex, timestampToString: timestampToString, extend: extend, reverse: reverse, openUrl: openUrl, getBase64Image: getBase64Image, getIncreasNumber: getIncreasNumber, getDom: getDom, queryDom: queryDom, queryAllDom: queryAllDom, getTemp: getTemp, mountDialog: mountDialog, getUrlQuery: getUrlQuery, getRCUrlQuery: getRCUrlQuery, deferNoop: deferNoop }; })(window); ================================================ FILE: api-test/js/components/button.js ================================================ (function (win, dependencies, components) { var Vue = dependencies.Vue, RongIM = dependencies.RongIM, utils = RongIM.Utils, Service = RongIM.Service; var OutputMark = { SUCCESS: '成功', FAILED: '失败' }; var copyApi = function (api) { var params = api.params || []; var copyParams = utils.copy(params); utils.forEach(params, function (item, index) { utils.forEach(item, function (val, key) { if (utils.isFunction(val)) { copyParams[index][key] = val; } }); }); api.params = copyParams; return api; }; components.apiBtn = Vue.component('api-btn', { template: utils.getTemp('rong-tpl-apibtn'), props: ['api', 'isdragging'], data: function() { return { isShowEditDialog: false, selfApi: copyApi(this.api) } }, watch: { markMessage: function (newMsg) { console.log(newMsg); } }, computed: { tip: function() { var api = this.selfApi; return utils.tplEngine(TipTpl, api); }, apiValue: function() { var api = this.selfApi; return utils.toJSON(api); }, paramList: function () { var paramList = this.selfApi.params; return paramList; }, hasParams: function () { var params = this.selfApi.params; return params && params.length; } }, methods: { openUrl: utils.openUrl, showEditDialog: function() { this.isShowEditDialog = true; }, hideEditDialog: function() { this.isShowEditDialog = false; }, change: function() { }, run: function() { var self = this; var params = []; var startTime = +new Date(); utils.forEach(self.selfApi.params, function(item) { if (item.type === 'number') { item.value = Number(item.value); } params.push(item.value); }); var imInstance = RongIM.vueInstance; var addOutput = function(data, isSuccess) { var currentTime = +new Date(); var consumedTime = currentTime - startTime; var title = self.api.name + (isSuccess ? OutputMark.SUCCESS : OutputMark.FAILED); var config = {}; if (!isSuccess) { config.color = utils.TypeColor.FAILED; } self.hideEditDialog(); return imInstance.addOutput(title, data, consumedTime, params, config); }; return self.api.event.apply(void 0, params).then(function(data) { data = addOutput(data, true); return { isSuccess: true, data: data }; }).catch(function(errorInfo) { // TODO 报警 // error = utils.isNumber(error) ? error : error.toString(); var data = addOutput(errorInfo, false); return { isSuccess: false, data: data }; }); } }, mounted: function() { var self = this; var setParams = function () { var paramList = self.selfApi.params; utils.forEach(paramList, function (item) { if (item.event) { item.value = item.value || item.event(); } }); }; setParams(); Service.msgEmitter.on('msgChanged', setParams); } }); })(window, { Vue: Vue, iview: iview, RongIM: RongIM }, window.RongIM.components); ================================================ FILE: api-test/js/components/json-alert.js ================================================ (function (win, dependencies) { var RongIM = dependencies.RongIM; var utils = RongIM.Utils; RongIM.dialog = RongIM.dialog || {}; RongIM.dialog.jsonAlert = function(options) { var vueInstance = RongIM.vueInstance; options = options || {}; utils.mountDialog({ name: 'json-alert', template: '#rong-json-alert', data: function () { return { isShow: true, data: options.data }; }, watch: { isShow: function(isShow) { if (!isShow) { utils.removeDom(this.$el); } } }, methods: { hide: function() { this.isShow = false; } } }, vueInstance); }; })(window, { RongIM: RongIM }); ================================================ FILE: api-test/js/components/msg-expansion.js ================================================ (function (win, dependencies, components) { var Vue = dependencies.Vue, RongIM = dependencies.RongIM, utils = RongIM.Utils, Service = RongIM.Service; components.apiExpansion = Vue.component('api-expansion', { template: utils.getTemp('rong-tpl-expansion'), props: ['isOpen'], data: function() { return { isOpen: true, } }, watch: { isOpen: function (val, newval) { console.warn(val, newval); } }, computed: { }, methods: { }, mounted: function() { console.warn('msg-expansion'); } }); })(window, { Vue: Vue, iview: iview, RongIM: RongIM }, window.RongIM.components); ================================================ FILE: api-test/js/login.js ================================================ (function (win, dependencies, components) { var Vue = dependencies.Vue, RongIM = dependencies.RongIM, utils = RongIM.Utils, isDebug = RongIM.config.isDebug, debugConf = RongIM.config.debugConf; var ConfigPlacehoder = { appkey: '开发者的融云 AppKey', token: '开发者的用户 Token', targetId: '对方 id. 发消息、获取历史消息等都默认对此用户操作. 默认聊天室、群组、个人 id 都为此 id', navi: '导航地址. 注: 国内数据中心可不填', customCMP: '链接地址(开发者忽略此项)', isPolling: '若使用长轮训链接方式, 可选择此项(开发者可忽略)' }; components.login = Vue.component('login', { template: utils.getTemp('rong-global-config'), props: ['config', 'login'], computed: { configList: function() { var items = []; utils.forEach(this.config, function(val, key) { items.push({ type: typeof val, name: key }); }); return items; }, prompt: function() { return ConfigPlacehoder; } }, methods: { clearStorage: function () { window.localStorage.clear(); this.$Message.success({ background: true, content: '清空本地缓存成功' }); } }, mounted: function () { if (isDebug && debugConf.autoRun) { var self = this; Vue.nextTick(function () { self.login(self.config); }); } } }); })(window, { Vue: Vue, iview: iview, RongIM: RongIM }, window.RongIM.components); ================================================ FILE: api-test/js/main.js ================================================ (function (win, dependencies, components) { var Vue = dependencies.Vue, iview = dependencies.iview, VueJsonPretty = dependencies.VueJsonPretty, RongIM = dependencies.RongIM, Service = RongIM.Service, utils = RongIM.Utils, ApiList = RongIM.ApiList, DefailtReadyApiQueue = RongIM.DefailtReadyApiQueue, DefaultConfig = RongIM.config.im, Config = utils.copy(DefaultConfig), Storage = utils.Storage, StorageConfig = Storage.get(Storage.ConfigKey), DefaultTargetId = Config.targetId, isDebug = RongIM.config.isDebug, debugConf = RongIM.config.debugConf; DefailtReadyApiQueue.push([]); var ValidStatus = [0, 1, 2, 6, 201, 202]; var ValidErrorCode = [23424, 23427, 23426, 23423]; var isStop = false; var isStorageConfig = false; if (StorageConfig && !isDebug) { isStorageConfig = true; Config = utils.copy(StorageConfig); } var urlQueryConfig = utils.getRCUrlQuery(); Config = utils.extend(Config, urlQueryConfig); var ReceiveMsgTextTpl = '监听到{typeName} ({conversationType})消息. 发送者: {senderUserId}'; var StatusTextTpl = '链接状态: {statusName} ({status})'; var OptBoxClass = 'rong-ready-box'; var ApiBoxClass = 'rong-api-list'; var ApiSourceClass = 'rong-api-source'; var RunType = { OneByOne: { name: '逐个运行', prompt: 'Api 逐个执行' }, LineByLine: { name: '逐行运行', prompt: '每行 Api 并行. 执行完一行后执行下一行' } }; var vueInstance; function runAllApi(allRefs, currentIndex, finishCallback) { var total = allRefs.length; var isFinished = total === currentIndex || isStop; if (isFinished) { return finishCallback && finishCallback(); } var refList = allRefs[currentIndex]; var deferArr = []; utils.forEach(refList, function (instance) { deferArr.push(instance.run()); }); return utils.Defer.all(deferArr).then(function (result) { result = result[0]; var isSuccess = result.isSuccess || ValidErrorCode.indexOf(result.data.result) !== -1; if (isSuccess) { vueInstance.runInfo.successApiCount++; } else { vueInstance.runInfo.failApiList.push(result.data); } currentIndex++; runAllApi(allRefs, currentIndex, finishCallback); }); } function runOneByOne(finishCallback) { var refs = vueInstance.$refs; var allRefs = []; utils.forEach(refs, function (subRefList) { utils.forEach(subRefList, function (ref) { allRefs.push([ ref ]); }); }); runAllApi(allRefs, 0, finishCallback); } function runLineByLine(finishCallback) { var refs = vueInstance.$refs; var allRefs = []; utils.forEach(refs, function (ins) { allRefs.push(ins); }); runAllApi(allRefs, 0, finishCallback); } function setConfig(config) { var currentTargetId = config.targetId; vueInstance.globalConfig = config; vueInstance.readyApiQueue = utils.deepMap(vueInstance.readyApiQueue, function (item) { if (item === DefaultTargetId) { item = currentTargetId; } return item; }); } function watchStatus(status) { var title = utils.tplEngine(StatusTextTpl, { status: status, statusName: utils.StatusName[status] }); var output = vueInstance.addOutput(title, status, 0, [], { color: utils.TypeColor.STATUS }); if (ValidStatus.indexOf(status) === -1) { vueInstance.runInfo.failApiList.push(output); } var isSuccess = utils.SuccessStatus.indexOf(status) !== -1; var event = isSuccess ? vueInstance.$Message.success : vueInstance.$Message.error; event.call(vueInstance.$Message, { background: true, content: title }); } function watchMessage(message) { if (RongIM.config.isDebug && !RongIM.config.debugConf.isShowMsg) { return; } var title = utils.tplEngine(ReceiveMsgTextTpl, { typeName: utils.ConversationName[message.type], conversationType: message.type, senderUserId: message.senderUserId }); vueInstance.addOutput(title, message, 0, [], { color: utils.TypeColor.MSG }); console.log('Reveice Msg', utils.toJSON(message)); } function watchChatroom(entries) { vueInstance.addOutput('监听到聊天室 KV 更新', entries, 0, [], { color: utils.TypeColor.MSG }); } function autoRun() { Vue.nextTick(function () { runOneByOne(function () { vueInstance.runInfo.runCount++; localStorage.removeItem('rong_servers'); localStorage.removeItem('rong_fullnavi'); vueInstance.outputList = []; vueInstance.allOutputList = []; !isStop && autoRun(); }); }); } function loginSuccessEvent(userId, config) { vueInstance.$Message.success({ background: true, content: '链接成功 ' + userId }); vueInstance.currentUserId = userId; vueInstance.isLogged = true; if (isDebug && debugConf.autoRun) { Vue.nextTick(autoRun); } } function login(config) { setConfig(config); return Service.init(config, { status: watchStatus, message: watchMessage, chatroom: watchChatroom }).then(function ({ id }) { Storage.set(Storage.ConfigKey, config); loginSuccessEvent(id, config); }).catch(function (error) { console.log(error); vueInstance.$Message.error({ background: true, content: '链接失败 ' + JSON.stringify(error) }); return utils.Defer.reject(); }); } function getApiListMethods() { return { addOutput: function (title, result, consumedTime, params, config) { config = config || {}; var output = { id: utils.getIncreasNumber(), title: title, result: result, consumedTime: consumedTime, params: params, config: config }; output.time = utils.timestampToString(); vueInstance.allOutputList.push(output); vueInstance.outputList.push(output); return output; }, clearOutput: function () { vueInstance.outputList = []; }, showAllOutput: function () { vueInstance.outputList = vueInstance.allOutputList; }, toJSON: function (data) { return utils.toJSON(data); }, showJSONAlert: function(data) { RongIM.dialog.jsonAlert({ data: data }); }, runAllApi: function() { if (vueInstance.runType === 'OneByOne') { runOneByOne(); } else { runLineByLine(); } }, startDragging: function () { setTimeout(function() { vueInstance.isDragging = true; }, 100); } }; } function getServiceMethods() { return { openUrl: utils.openUrl, reverse: utils.reverse, login: function(config) { var isEqualStorage = utils.isEqual(config, StorageConfig); var isEqualDefault = utils.isEqual(config, DefaultConfig); if (isStorageConfig && isEqualStorage && !isEqualDefault && !isDebug) { vueInstance.$Modal.confirm({ title: '注意', content: '您目前使用的为上一次链接配置, 请确定配置是否可用 ?', onOk: function () { login(config); } }); } else { return login(config); } }, alarm: function () { if (!this.isAlarmMuted) { vueInstance.$refs.alarm.play(); } }, mute: function () { vueInstance.$refs.alarm.pause(); } }; } Vue.use(iview); vueInstance = new Vue({ el: '#app', data: function() { return { currentUserId: '', isLogged: false, readyApiQueue: DefailtReadyApiQueue, allOutputList: [], outputList: [], globalConfig: Config, RunType: RunType, runType: 'OneByOne', alertJSON: null, isDragging: false, isShowRunType: false, isShowOutList: false, isDebug: RongIM.config.isDebug, runInfo: { runCount: 0, successApiCount: 0, failApiList: [] }, isAlarmMuted: false }; }, computed: { apiList: function() { return ApiList; }, changeUserApi: function () { var self = this; var changeUserApi = RongIM.Api.changeUser; var changeUserEvent = changeUserApi.event; changeUserApi.event = function (token) { var globalConfig = self.globalConfig globalConfig.token = token; return Service.changeUser(globalConfig, { status: watchStatus, message: watchMessage }).then(function (userId) { loginSuccessEvent(userId, globalConfig); }).catch(function () { vueInstance.$Message.error({ background: true, content: '切换用户失败 ' + error }); }); }; return changeUserApi; }, currentOutput: function() { var outputList = this.outputList; if (outputList.length) { return outputList[outputList.length - 1]; } }, displayedOutputList: function () { if (isDebug) { return this.runInfo.failApiList; } else { return this.outputList; } } }, watch: { 'runInfo.failApiList': function (newList) { if (newList.length > 20) { this.alarm(); } }, isAlarmMuted: function (isMuted) { if (isMuted) { this.mute(); } } }, components: { apiBtn: components.apiBtn, login: components.login, prettyjson: Vue.component('prettyjson', VueJsonPretty.default) }, mounted: function() { this.isPageLoaded = true; }, methods: utils.extend(getApiListMethods(), getServiceMethods()) }); RongIM.vueInstance = vueInstance; (function () { function start() { isStop = false; if (vueInstance.isLogged) { autoRun(); } else { vueInstance.login(vueInstance.globalConfig).then(autoRun); } } window.addEventListener("message", function (event) { var type = event.data; if (type === 'start') { start(); } else if (type === 'pause') { isStop = true; } }, false); })(); })(window, { Vue: Vue, iview: iview, VueJsonPretty: VueJsonPretty, RongIM: RongIM }, window.RongIM.components); ================================================ FILE: api-test/lib/js/RongIMLib-3.0.0.js ================================================ /* * RongIMLib.js v3.0.0 * Release Date: Fri Mar 27 2020 09:51:18 GMT+0800 (China Standard Time) * Copyright 2020 RongCloud * Released under the MIT License. */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global.RongIMLib = factory()); }(this, (function () { 'use strict'; console.log('----------------------'); console.log(window); var version = "3.0.0"; var SDK_VERSION = version; var ERROR_INFO = { TIMEOUT: { code: -1, msg: 'Network timeout' }, SDK_INTERNAL_ERROR: { code: -2, msg: 'SDK internal error' }, PARAMETER_ERROR: { code: -3, msg: 'Please check the parameters, the {param} expected a value of {expect} but received {current}' }, REJECTED_BY_BLACKLIST: { code: 405, msg: 'Blacklisted by the other party' }, SEND_TOO_FAST: { code: 20604, msg: 'Sending messages too quickly' }, NOT_IN_GROUP: { code: 22406, msg: 'Not in group' }, FORBIDDEN_IN_GROUP: { code: 22408, msg: 'Forbbiden from speaking in the group' }, NOT_IN_CHATROOM: { code: 23406, msg: 'Not in chatroom' }, FORBIDDEN_IN_CHATROOM: { code: 23408, msg: 'Forbbiden from speaking in the chatroom' }, KICKED_FROM_CHATROOM: { code: 23409, msg: 'Kicked out and forbbiden from joining the chatroom' }, CHATROOM_NOT_EXIST: { code: 23410, msg: 'ChatRoom does not exist' }, CHATROOM_IS_FULL: { code: 23411, msg: 'ChatRoom members exceeded' }, PARAMETER_INVALID_CHATROOM: { code: 23412, msg: 'Invalid chatroom parameters' }, ROAMING_SERVICE_UNAVAILABLE_CHATROOM: { code: 23414, msg: 'ChatRoom message roaming service is not open' }, RECALLMESSAGE_PARAMETER_INVALID: { code: 25101, msg: 'Invalid recall message parameter' }, PUSHSETTING_PARAMETER_INVALID: { code: 26001, msg: 'Invalid push parameter' }, OPERATION_BLOCKED: { code: 20605, msg: 'Operation is blocked' }, OPERATION_NOT_SUPPORT: { code: 20606, msg: 'Operation is not supported' }, MSG_BLOCKED_SENSITIVE_WORD: { code: 21501, msg: 'The sent message contains sensitive words' }, REPLACED_SENSITIVE_WORD: { code: 21502, msg: 'Sensitive words in the message have been replaced' }, NOT_CONNECTED: { code: 30001, msg: 'Please connect successfully first' }, NAVI_REQUEST_ERROR: { code: 30007, msg: 'Navigation http request failed' }, CMP_REQUEST_ERROR: { code: 30010, msg: 'CMP sniff http request failed' }, CONN_APPKEY_FAKE: { code: 31002, msg: 'Your appkey is fake' }, CONN_SERVER_UNAVAILABLE: { code: 31003, msg: 'The server is currently unavailable' }, CONN_TOKEN_INCORRECT: { code: 31004, msg: 'Your token is not valid or expired' }, CONN_NOT_AUTHRORIZED: { code: 31005, msg: 'AppKey and Token do not match' }, CONN_REDIRECTED: { code: 31006, msg: 'Connection redirection' }, CONN_APP_BLOCKED_OR_DELETED: { code: 31008, msg: 'AppKey is banned or deleted' }, CONN_USER_BLOCKED: { code: 31009, msg: 'User blocked' }, RC_CONNECTION_EXIST: { code: 34001, msg: 'Connection already exists' } }; var ERROR_CODE = {}; var ERROR_CODE_TO_INFO = {}; for (var name$1 in ERROR_INFO) { var info = ERROR_INFO[name$1]; var code = info.code; ERROR_CODE[name$1] = code; ERROR_CODE[code] = name$1; ERROR_CODE_TO_INFO[code] = info; } var _CONNECT_SERVER_STATU, _SERVER_DISCONNECT_ST, _TRANSPORTER_STATUS_T; var NAVI_ERROR_INFO = { '401': ERROR_INFO.CONN_TOKEN_INCORRECT, '403': ERROR_INFO.CONN_APPKEY_FAKE }; var CONNECTION_STATUS = { CONNECTED: 0, CONNECTING: 1, DISCONNECTED: 2, NETWORK_UNAVAILABLE: 3, SOCKET_CLOSE: 4, SOCKET_ERROR: 5, KICKED_OFFLINE_BY_OTHER_CLIENT: 6 }; var SERVER_DISCONNECT_STATUS = { KICKED_OFFLINE_BY_OTHER_CLIENT: 1 }; var CONNECT_SERVER_STATUS = { IDENTIFIER_REJECTED: 2, SERVER_UNAVAILABLE: 3, TOKEN_INCORRECT: 4, NOT_AUTHORIZED: 5, REDIRECT: 6, PACKAGE_ERROR: 7, APP_BLOCK_OR_DELETE: 8, BLOCK: 9, TOKEN_EXPIRE: 10, DEVICE_ERROR: 11 }; var CONNECT_SERVER_STATUS_MAP_ERROR_INFO = (_CONNECT_SERVER_STATU = {}, _CONNECT_SERVER_STATU[CONNECT_SERVER_STATUS.IDENTIFIER_REJECTED] = ERROR_INFO.CONN_APPKEY_FAKE, _CONNECT_SERVER_STATU[CONNECT_SERVER_STATUS.SERVER_UNAVAILABLE] = ERROR_INFO.CONN_SERVER_UNAVAILABLE, _CONNECT_SERVER_STATU[CONNECT_SERVER_STATUS.TOKEN_INCORRECT] = ERROR_INFO.CONN_TOKEN_INCORRECT, _CONNECT_SERVER_STATU[CONNECT_SERVER_STATUS.NOT_AUTHORIZED] = ERROR_INFO.CONN_NOT_AUTHRORIZED, _CONNECT_SERVER_STATU[CONNECT_SERVER_STATUS.REDIRECT] = ERROR_INFO.CONN_REDIRECTED, _CONNECT_SERVER_STATU[CONNECT_SERVER_STATUS.APP_BLOCK_OR_DELETE] = ERROR_INFO.CONN_APP_BLOCKED_OR_DELETED, _CONNECT_SERVER_STATU[CONNECT_SERVER_STATUS.BLOCK] = ERROR_INFO.CONN_USER_BLOCKED, _CONNECT_SERVER_STATU[CONNECT_SERVER_STATUS.TOKEN_EXPIRE] = ERROR_INFO.CONN_TOKEN_INCORRECT, _CONNECT_SERVER_STATU); var TRANSPORTER_STATUS = { CONNECTED: CONNECTION_STATUS.CONNECTED, KICKED_OFFLINE_BY_OTHER_CLIENT: CONNECTION_STATUS.KICKED_OFFLINE_BY_OTHER_CLIENT, CLOSE_GOING_AWAY: 1001, CLOSE_PROTOCOL_ERROR: 1002, CLOSE_UNSUPPORTED: 1003, CLOSE_NO_STATUS: 1005, CLOSE_ABNORMAL: 1006, UNSUPPORTED_DATA: 1007, POLICY_VIOLATION: 1008, CLOSE_TOO_LARGE: 1009, MISSING_EXTENSION: 1010, INTERNAL_ERROR: 1011, SERVICE_RESTART: 1012, TRY_AGAIN_LATER: 1013, TSL_HANDSHAKE: 1015, PING_FIRST_TIMEOUT: 2001, PING_TIMEOUT: 2002, DISCONNECT_TOO_FAST: 2003, EXCEED_MESSAGE_ID_LIMIT: 2004 }; var SERVER_DISCONNECT_STATUS_TO_TRANSPORTER_STATUS = (_SERVER_DISCONNECT_ST = {}, _SERVER_DISCONNECT_ST[SERVER_DISCONNECT_STATUS.KICKED_OFFLINE_BY_OTHER_CLIENT] = TRANSPORTER_STATUS.KICKED_OFFLINE_BY_OTHER_CLIENT, _SERVER_DISCONNECT_ST); var TRANSPORTER_STATUS_NEED_UPDATE_CMP = [TRANSPORTER_STATUS.CLOSE_GOING_AWAY, TRANSPORTER_STATUS.CLOSE_PROTOCOL_ERROR, TRANSPORTER_STATUS.CLOSE_UNSUPPORTED, TRANSPORTER_STATUS.UNSUPPORTED_DATA, TRANSPORTER_STATUS.POLICY_VIOLATION, TRANSPORTER_STATUS.MISSING_EXTENSION, TRANSPORTER_STATUS.INTERNAL_ERROR, TRANSPORTER_STATUS.SERVICE_RESTART, TRANSPORTER_STATUS.TRY_AGAIN_LATER, TRANSPORTER_STATUS.TSL_HANDSHAKE, TRANSPORTER_STATUS.PING_FIRST_TIMEOUT, TRANSPORTER_STATUS.DISCONNECT_TOO_FAST]; var TRANSPORTER_STATUS_NEED_RECONNECT = TRANSPORTER_STATUS_NEED_UPDATE_CMP.concat([TRANSPORTER_STATUS.PING_TIMEOUT, TRANSPORTER_STATUS.CLOSE_ABNORMAL, TRANSPORTER_STATUS.EXCEED_MESSAGE_ID_LIMIT]); var TRANSPORTER_STATUS_TO_CONNECTION_STATUS = (_TRANSPORTER_STATUS_T = {}, _TRANSPORTER_STATUS_T[TRANSPORTER_STATUS.CLOSE_GOING_AWAY] = CONNECTION_STATUS.SOCKET_ERROR, _TRANSPORTER_STATUS_T[TRANSPORTER_STATUS.CLOSE_PROTOCOL_ERROR] = CONNECTION_STATUS.SOCKET_ERROR, _TRANSPORTER_STATUS_T[TRANSPORTER_STATUS.CLOSE_UNSUPPORTED] = CONNECTION_STATUS.SOCKET_ERROR, _TRANSPORTER_STATUS_T[TRANSPORTER_STATUS.CLOSE_NO_STATUS] = CONNECTION_STATUS.DISCONNECTED, _TRANSPORTER_STATUS_T[TRANSPORTER_STATUS.CLOSE_ABNORMAL] = CONNECTION_STATUS.NETWORK_UNAVAILABLE, _TRANSPORTER_STATUS_T[TRANSPORTER_STATUS.DISCONNECT_TOO_FAST] = CONNECTION_STATUS.NETWORK_UNAVAILABLE, _TRANSPORTER_STATUS_T[TRANSPORTER_STATUS.UNSUPPORTED_DATA] = CONNECTION_STATUS.SOCKET_ERROR, _TRANSPORTER_STATUS_T[TRANSPORTER_STATUS.POLICY_VIOLATION] = CONNECTION_STATUS.SOCKET_ERROR, _TRANSPORTER_STATUS_T[TRANSPORTER_STATUS.CLOSE_TOO_LARGE] = CONNECTION_STATUS.SOCKET_ERROR, _TRANSPORTER_STATUS_T[TRANSPORTER_STATUS.MISSING_EXTENSION] = CONNECTION_STATUS.SOCKET_ERROR, _TRANSPORTER_STATUS_T[TRANSPORTER_STATUS.INTERNAL_ERROR] = CONNECTION_STATUS.SOCKET_ERROR, _TRANSPORTER_STATUS_T[TRANSPORTER_STATUS.SERVICE_RESTART] = CONNECTION_STATUS.SOCKET_ERROR, _TRANSPORTER_STATUS_T[TRANSPORTER_STATUS.TRY_AGAIN_LATER] = CONNECTION_STATUS.SOCKET_ERROR, _TRANSPORTER_STATUS_T[TRANSPORTER_STATUS.TSL_HANDSHAKE] = CONNECTION_STATUS.SOCKET_ERROR, _TRANSPORTER_STATUS_T[TRANSPORTER_STATUS.PING_FIRST_TIMEOUT] = CONNECTION_STATUS.NETWORK_UNAVAILABLE, _TRANSPORTER_STATUS_T[TRANSPORTER_STATUS.PING_TIMEOUT] = CONNECTION_STATUS.NETWORK_UNAVAILABLE, _TRANSPORTER_STATUS_T); var CONNECT_TYPE = { COMET: 'comet', WEBSOCKET: 'websocket' }; var CONVERSATION_TYPE = { PRIVATE: 1, GROUP: 3, CHATROOM: 4, CUSTOMER_SERVICE: 5, SYSTEM: 6 }; var MESSAGE_DIRECTION = { SEND: 1, RECEIVE: 2 }; var MESSAGS_TIME_ORDER = { DESC: 0, ASC: 1 }; var CHATROOM_ORDER = { ASC: 1, DESC: 2 }; var RECALL_OBJECT_NAME = 'RC:RcCmd'; var MENTIOND_TYPE = { ALL: 1, SINGAL: 2 }; var CONST = { CONNECT_TYPE: CONNECT_TYPE, CONNECTION_STATUS: CONNECTION_STATUS, CONVERSATION_TYPE: CONVERSATION_TYPE, MESSAGE_DIRECTION: MESSAGE_DIRECTION, MESSAGS_TIME_ORDER: MESSAGS_TIME_ORDER, CHATROOM_ORDER: CHATROOM_ORDER, RECALL_OBJECT_NAME: RECALL_OBJECT_NAME }; var IM_TIMEOUT = 30000; var IM_PING_INTERVAL_TIME = 30000; var IM_PING_MAX_TIMEOUT = 6000; var IM_PING_MIN_TIMEOUT = 2000; var HTTP_TIMEOUT = 60000; var PULL_MSG_TIME = 180000; var NAVI_EXPIRED_TIME = 10800000; var CMP_SNIFF_INTERNAL_TIME = 1000; var FIRST_PING_TIMEOUT = 100; var NAVI_REQUEST_SUCCESS_CODE = 200; var NAVI_SEPARATOR_IN_TOKEN = '@'; var DOMAIN_SEPARATOR_IN_NAVLIST = ';'; var DOMAIN_SEPARATOR_IN_CMPLIST = ','; var MAX_SINGAL_ID = 65535; var MINIMUM_CONNECT_DURATION = 5000; var TYPE_HAS_CONVERSATION = [CONVERSATION_TYPE.PRIVATE, CONVERSATION_TYPE.GROUP, CONVERSATION_TYPE.SYSTEM]; var PLATFORM = { WEB: 'web', WX: 'wx', ZFB: 'zfb', TT: 'tt', BAIDU: 'baidu', QUICK_APP: 'quick_app' }; var REQUEST_METHOD = { POST: 'post', GET: 'get' }; var STORAGE_ROOT_KEY = 'rc-'; var STORAGE_NAVI = { ROOT_KEY_TPL: 'nav-{appkey}-{UID}', SUB_KEY: { CONNECT_TYPE: 'connettype', TIME_WHEN_SAVED: 'time', RESPONSE: 'resp' } }; var STORAGE_SYNC_TIME = { ROOT_KEY_TPL: 'sync-{appkey}-{userId}', SUB_KEY: { SENDBOX: 'send', INBOX: 'in' } }; var STORAGE_CONVERSATION = { ROOT_KEY_TPL: 'con-{appkey}-{userId}', SUB_KEY: { ROOT_TPL: '{type}-{id}', UNREAD_COUNT: 'c', UNREAD_LAST_TIME: 't', HAS_MENTIOND: 'hm', MENTIOND_INFO: 'm' } }; var HTTP_PROTOCOL = { HTTP: 'http:', HTTPS: 'https:' }; var WS_PROTOCOL = { WSS: 'wss:', WS: 'ws:' }; var NAVI_CALLBACK_NAME = 'getServerEndpoint'; var NAVI_TYPE = { COMET: 'cometnavi', WEBSOCKET: 'navi' }; var NAVI_URL_TPL = '{url}/{type}.js?appId={appkey}&token={token}&callBack=' + NAVI_CALLBACK_NAME + '&r={random}&v=' + SDK_VERSION; var CMP_URL_TPL = '{protocol}//{domain}/websocket?appId={appkey}&token={token}&apiVer={apiVer}&sdkVer=' + SDK_VERSION; var COMET_REQ_HAS_TOPIC_URL_TPL = '{protocol}//{domain}/websocket?messageid={messageId}&header={headerCode}&sessionid={sessionId}&topic={topic}&targetid={targetId}&pid={pid}'; var COMET_REQ_NO_TOPIC_URL_TPL = '{protocol}//{domain}/websocket?messageid={messageId}&header={headerCode}&sessionid={sessionId}&pid={pid}'; var COMET_PULL_URL_TPL = '{protocol}//{domain}/pullmsg.js?sessionid={sessionId}×tamp={timestamp}&pid={pid}'; var TIMER_TYPE = { INTERVAL: 'interval', TIMEOUT: 'timeout' }; var TIMER_STATUS = { PENNDING: 'pendding', BUSY: 'busy', ENDING: 'ending' }; var UnKown = 'UnKown'; var isMiniEnv = function isMiniEnv(global) { return global !== window; }; var getEnvInfo = function getEnvInfo() { if (typeof wx !== 'undefined') { return { platform: PLATFORM.WX, global: wx }; } else if (typeof swan !== 'undefined') { return { platform: PLATFORM.BAIDU, global: swan }; } else if (typeof tt !== 'undefined') { return { platform: PLATFORM.TT, global: tt }; } else if (typeof my !== 'undefined') { return { platform: PLATFORM.ZFB, global: my }; } else { return { platform: PLATFORM.WEB, global: window }; } }; var getWebSystemInfo = function getWebSystemInfo() { var userAgent = navigator.userAgent; var version, type; var condition = { IE: /rv:([\d.]+)\) like Gecko|MSIE ([\d.]+)/, Edge: /Edge\/([\d.]+)/, Firefox: /Firefox\/([\d.]+)/, Opera: /(?:OPERA|OPR).([\d.]+)/, WeiXin: /MicroMessenger\/([\d.]+)/, QQBrowser: /QQBrowser\/([\d.]+)/, Chrome: /Chrome\/([\d.]+)/, Safari: /Version\/([\d.]+).*Safari/ }; for (var key in condition) { if (!condition.hasOwnProperty(key)) continue; var browserContent = userAgent.match(condition[key]); if (browserContent) { type = key; version = browserContent[1] || browserContent[2]; break; } } return { model: type || UnKown, version: version || UnKown }; }; var getMiniSystemInfo = function getMiniSystemInfo(global) { var systemInfo = global.getSystemInfoSync() || {}; var model = systemInfo.model, brand = systemInfo.brand; if (model && brand) { model = model + ' ' + brand; } systemInfo.model = model; return systemInfo; }; var getProtocol = function getProtocol(global) { var protocol = { http: global.location.protocol || HTTP_PROTOCOL.HTTPS, ws: WS_PROTOCOL.WSS }; var isHttp = protocol.http === HTTP_PROTOCOL.HTTP; if (isHttp) { protocol.ws = WS_PROTOCOL.WS; } return protocol; }; var adaptGlobalObjectCreate = function adaptGlobalObjectCreate(global) { if (!global.Object.create) { global.Object.create = function (o, properties) { if (typeof o !== 'object' && typeof o !== 'function') throw new TypeError('Object prototype may only be an Object: ' + o);else if (o === null) throw new Error('This browser\'s implementation of Object.create is a shim and doesn\'t support \'null\' as the first argument.'); if (typeof properties !== 'undefined') throw new Error('This browser\'s implementation of Object.create is a shim and doesn\'t support a second argument.'); function F() {} F.prototype = o; return new F(); }; } }; var envInfo = getEnvInfo(); var platform = envInfo.platform, global$1 = envInfo.global; var isMini = isMiniEnv(global$1); var protocol = getProtocol(global$1); var system = isMini ? getMiniSystemInfo(global$1) : getWebSystemInfo(); system.name = platform; adaptGlobalObjectCreate(global$1); var env = { global: global$1, system: system, isMini: isMini, protocol: protocol }; var CacheStorage = function () { function CacheStorage(values) { this.caches = {}; if (values) { this.caches = values; } } var _proto = CacheStorage.prototype; _proto.set = function set(key, value) { this.caches[key] = value; }; _proto.remove = function remove(key) { var val = this.get(key); delete this.caches[key]; return val; }; _proto.get = function get(key) { return this.caches[key]; }; _proto.getKeys = function getKeys() { var keys = []; for (var key in this.caches) { keys.push(key); } return keys; }; return CacheStorage; }(); var global$2 = env.global, system$1 = env.system; var isZFB = system$1.name === PLATFORM.ZFB; var ZFBStorage = function () { function ZFBStorage() { this.cache = new CacheStorage(); } var _proto = ZFBStorage.prototype; _proto.set = function set(key, value) { this.cache.set(key, value); global$2.setStorageSync({ key: key, data: value }); }; _proto.get = function get(key) { return this.cache.get(key); }; _proto.remove = function remove(key) { global$2.removeStorageSync({ key: key }); return this.cache.remove(key); }; _proto.getKeys = function getKeys() { return this.cache.getKeys(); }; return ZFBStorage; }(); var MiniStorage = function () { function MiniStorage() { this.cache = new CacheStorage(); } var _proto2 = MiniStorage.prototype; _proto2.set = function set(key, value) { this.cache.set(key, value); global$2.setStorageSync(key, value); }; _proto2.get = function get(key) { return this.cache.get(key); }; _proto2.remove = function remove(key) { global$2.removeStorageSync(key); return this.cache.remove(key); }; _proto2.getKeys = function getKeys() { return this.cache.getKeys(); }; return MiniStorage; }(); var storage = isZFB ? ZFBStorage : MiniStorage; var JSON$1 = { parse: function parse(sJSON) { return new Function('', 'return (' + sJSON + ')')(); }, stringify: function stringify(value) { return JSON$1.str('', { '': value }); }, str: function str(key, holder) { var i, k, v, length, partial, value = holder[key], self = JSON$1; if (value && typeof value === 'object' && typeof value.toJSON === 'function') { value = value.toJSON(key); } switch (typeof value) { case 'string': return self.quote(value); case 'number': return isFinite(value) ? String(value) : 'null'; case 'boolean': return String(value); case 'object': if (!value) { return 'null'; } partial = []; if (Object.prototype.toString.apply(value) === '[object Array]') { length = value.length; for (i = 0; i < length; i += 1) { partial[i] = self.str(i, value) || 'null'; } v = partial.length === 0 ? '[]' : '[' + partial.join(',') + ']'; return v; } for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = self.str(k, value); if (v) { partial.push(self.quote(k) + ':' + v); } } } v = partial.length === 0 ? '{}' : '{' + partial.join(',') + '}'; return v; } }, quote: function quote(string) { var self = JSON$1; self.rx_escapable.lastIndex = 0; return self.rx_escapable.test(string) ? '"' + string.replace(self.rx_escapable, function (a) { var c = self.meta[a]; return typeof c === 'string' ? c : "\\u" + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }) + '"' : '"' + string + '"'; }, rx_escapable: new RegExp("[\\\"\\\\\"\0-\x1F\x7F-\x9F\xAD\u0600-\u0604\u070F\u17B4\u17B5\u200C-\u200F\u2028-\u202F\u2060-\u206F\uFEFF\uFFF0-\uFFFF]", 'g'), meta: { '\b': '\\b', ' ': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"': '\\"', '\'\'': '\\\'\'', '\\': '\\\\' } }; var global$3 = env.global; var TEST_KEY = 'RC_TEST_KEY'; var TEST_VALUE = 'RC_TEST_VALUE'; var isSupportLocalStorage = function isSupportLocalStorage() { var isSupport = false; var localStorage = global$3.localStorage; if (localStorage) { try { localStorage.setItem(TEST_KEY, TEST_VALUE); var testVal = localStorage.getItem(TEST_KEY); if (testVal === TEST_VALUE) { isSupport = true; } localStorage.removeItem(TEST_KEY); } catch (e) {} } return isSupport; }; var WebStorage = function () { function WebStorage() {} var _proto = WebStorage.prototype; _proto.set = function set(key, value) { global$3.localStorage.setItem(key, JSON$1.stringify({ d: value })); }; _proto.get = function get(key) { var value; var localValue = global$3.localStorage.getItem(key); try { localValue = JSON$1.parse(localValue); } catch (e) { localValue = {}; } if (localValue && localValue.d) { value = localValue.d; } return value; }; _proto.remove = function remove(key) { return global$3.localStorage.removeItem(key); }; _proto.getKeys = function getKeys() { var keyList = []; for (var key in global$3.localStorage) { keyList.push(key); } return keyList; }; return WebStorage; }(); var WebStorage$1 = isSupportLocalStorage() ? WebStorage : CacheStorage; var isMini$1 = env.isMini; var Storage = isMini$1 ? storage : WebStorage$1, storage$1 = new Storage(); var global$4 = env.global; var Socket = function () { function Socket(options) { this.socket = void 0; this.socket = global$4.connectSocket(options); } var _proto = Socket.prototype; _proto.send = function send(data) { this.socket.send(data); }; _proto.close = function close() { this.socket.close(); }; _proto.onOpen = function onOpen(callback) { this.socket.onOpen(callback); }; _proto.onMessage = function onMessage(callback) { this.socket.onMessage(callback); }; _proto.onError = function onError(callback) { this.socket.onError(callback); }; _proto.onClose = function onClose(callback) { this.socket.onClose(callback); }; return Socket; }(); var Socket$1 = function () { function Socket(options) { this.socket = void 0; var url = options.url; this.socket = new WebSocket(url); this.socket.binaryType = 'arraybuffer'; return this; } var _proto = Socket.prototype; _proto.send = function send(data) { return this.socket.send(data); }; _proto.close = function close() { this.socket.close(); }; _proto.onOpen = function onOpen(callback) { this.socket.addEventListener('open', callback); }; _proto.onMessage = function onMessage(callback) { this.socket.addEventListener('message', callback); }; _proto.onError = function onError(callback) { this.socket.addEventListener('error', callback); }; _proto.onClose = function onClose(callback) { this.socket.addEventListener('close', callback); }; return Socket; }(); var isMini$2 = env.isMini; var Socket$2 = isMini$2 ? Socket : Socket$1; /*! 基于 es6-promise * Github: https://github.com/stefanpenner/es6-promise * @overview es6-promise - a tiny implementation of Promises/A+. * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald) * @license Licensed under MIT license * See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE * @version v4.2.8+1e68dce6 */ var SparePromise = (function(){function a(a){var b=typeof a;return null!==a&&("object"===b||"function"===b)}function b(a){return "function"==typeof a}function c(a){P=a;}function d(a){Q=a;}function e(){return function(){return process.nextTick(j)}}function f(){return "undefined"!=typeof O?function(){O(j);}:i()}function g(){var a=0,b=new T(j),c=document.createTextNode("");return b.observe(c,{characterData:!0}),function(){c.data=a=++a%2;}}function h(){var a=new MessageChannel;return a.port1.onmessage=j,function(){return a.port2.postMessage(0)}}function i(){var a=setTimeout;return function(){return a(j,1)}}function j(){var a,b,c;for(a=0;N>a;a+=2)b=W[a],c=W[a+1],b(c),W[a]=void 0,W[a+1]=void 0;N=0;}function k(){try{var a=Function("return this")().require("vertx");return O=a.runOnLoop||a.runOnContext,f()}catch(b){return i()}}function l(a,b){var e,f,c=this,d=new this.constructor(n);return void 0===d[Y]&&D(d),e=c._state,e?(f=arguments[e-1],Q(function(){return A(e,d,f,c._result)})):y(c,d,a,b),d}function m(a){var c,b=this;return a&&"object"==typeof a&&a.constructor===b?a:(c=new b(n),u(c,a),c)}function n(){}function o(){return new TypeError("You cannot resolve a promise with itself")}function p(){return new TypeError("A promises callback cannot return that same promise.")}function q(a,b,c,d){try{a.call(b,c,d);}catch(e){return e}}function r(a,b,c){Q(function(a){var d=!1,e=q(c,b,function(c){d||(d=!0,b!==c?u(a,c):w(a,c));},function(b){d||(d=!0,x(a,b));},"Settle: "+(a._label||" unknown promise"));!d&&e&&(d=!0,x(a,e));},a);}function s(a,b){b._state===$?w(a,b._result):b._state===_?x(a,b._result):y(b,void 0,function(b){return u(a,b)},function(b){return x(a,b)});}function t(a,c,d){c.constructor===a.constructor&&d===l&&c.constructor.resolve===m?s(a,c):void 0===d?w(a,c):b(d)?r(a,c,d):w(a,c);}function u(b,c){if(b===c)x(b,o());else if(a(c)){var d=void 0;try{d=c.then;}catch(e){return void x(b,e)}t(b,c,d);}else w(b,c);}function v(a){a._onerror&&a._onerror(a._result),z(a);}function w(a,b){a._state===Z&&(a._result=b,a._state=$,0!==a._subscribers.length&&Q(z,a));}function x(a,b){a._state===Z&&(a._state=_,a._result=b,Q(v,a));}function y(a,b,c,d){var e=a._subscribers,f=e.length;a._onerror=null,e[f]=b,e[f+$]=c,e[f+_]=d,0===f&&a._state&&Q(z,a);}function z(a){var d,e,f,g,b=a._subscribers,c=a._state;if(0!==b.length){for(d=void 0,e=void 0,f=a._result,g=0;gf;f++)b.resolve(a[f]).then(c,d);}:function(a,b){return b(new TypeError("You must pass an array to race."))})}function H(a){var b=this,c=new b(n);return x(c,a),c}function I(){throw new TypeError("You must pass a resolver function as the first argument to the promise constructor")}function J(){throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.")}function K(){var c,d,a=void 0;if("undefined"!=typeof global)a=global;else if("undefined"!=typeof self)a=self;else try{a=Function("return this")();}catch(b){throw new Error("polyfill failed because global object is unavailable in this environment")}if(c=a.Promise){d=null;try{d=Object.prototype.toString.call(c.resolve());}catch(b){}if("[object Promise]"===d&&!c.cast)return}a.Promise=cb;}var M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,$,_,ab,bb,cb,L=void 0;return L=Array.isArray?Array.isArray:function(a){return "[object Array]"===Object.prototype.toString.call(a)},M=L,N=0,O=void 0,P=void 0,Q=function(a,b){W[N]=a,W[N+1]=b,N+=2,2===N&&(P?P(j):X());},R="undefined"!=typeof window?window:void 0,S=R||{},T=S.MutationObserver||S.WebKitMutationObserver,U="undefined"==typeof self&&"undefined"!=typeof process&&"[object process]"==={}.toString.call(process),V="undefined"!=typeof Uint8ClampedArray&&"undefined"!=typeof importScripts&&"undefined"!=typeof MessageChannel,W=new Array(1e3),X=void 0,X=U?e():T?g():V?h():void 0===R&&"function"==typeof require?k():i(),Y=Math.random().toString(36).substring(2),Z=void 0,$=1,_=2,ab=0,bb=function(){function a(a,b){this._instanceConstructor=a,this.promise=new a(n),this.promise[Y]||D(this.promise),M(b)?(this.length=b.length,this._remaining=b.length,this._result=new Array(this.length),0===this.length?w(this.promise,this._result):(this.length=this.length||0,this._enumerate(b),0===this._remaining&&w(this.promise,this._result))):x(this.promise,E());}return a.prototype._enumerate=function(a){for(var b=0;this._state===Z&&b>16)+(b>>16)+(c>>16);return d<<16|65535&c}function b(a,b){return a<>>32-b}function c(c,d,e,f,g,h){return a(b(a(a(d,c),a(f,h)),g),e)}function d(a,b,d,e,f,g,h){return c(b&d|~b&e,a,b,f,g,h)}function e(a,b,d,e,f,g,h){return c(b&e|d&~e,a,b,f,g,h)}function f(a,b,d,e,f,g,h){return c(b^d^e,a,b,f,g,h)}function g(a,b,d,e,f,g,h){return c(d^(b|~e),a,b,f,g,h)}function h(b,c){var h,i,j,k,l,m,n,o,p;for(b[c>>5]|=128<>>9<<4)+14]=c,m=1732584193,n=-271733879,o=-1732584194,p=271733878,h=0;hb;b+=8)c+=String.fromCharCode(255&a[b>>5]>>>b%32);return c}function j(a){var b,d,c=[];for(c[(a.length>>2)-1]=void 0,b=0;bb;b+=8)c[b>>5]|=(255&a.charCodeAt(b/8))<16&&(d=h(d,8*a.length)),c=0;16>c;c+=1)e[c]=909522486^d[c],f[c]=1549556828^d[c];return g=h(e.concat(j(b)),512+8*b.length),i(h(f.concat(g),640))}function m(a){var d,e,b="0123456789abcdef",c="";for(e=0;e>>4)+b.charAt(15&d);return c}function n(a){return unescape(encodeURIComponent(a))}function o(a){return k(n(a))}function p(a){return m(o(a))}function q(a,b){return l(n(a),n(b))}function r(a,b){return m(q(a,b))}function s(a,b,c){return b?c?q(b,a):r(b,a):c?o(a):p(a)}return s})(); var global$7 = env.global; var Promise$1 = global$7.Promise; var isSupportPromise = function isSupportPromise() { if (!global$7.Promise) return false; var defer = function () { return global$7.Promise.resolve(); }(); return defer.then && defer["catch"] && defer["finally"]; }; var Defer = isSupportPromise() ? global$7.Promise : SparePromise; var noop = function noop(data) { return data; }; var deferNoop = function deferNoop(data) { return Promise$1.resolve(data); }; var JSON$2 = JSON$1; var allowError = function allowError(event) { var result; try { for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } result = event.apply(void 0, args); } catch (e) { result = null; } return result; }; var toJSON = function toJSON(val) { return allowError(JSON$2.stringify, val); }; var parseJSON = function parseJSON(val) { return allowError(JSON$2.parse, val); }; var copy = function copy(val) { return parseJSON(toJSON(val)); }; var isObject = function isObject(val) { return Object.prototype.toString.call(val) === '[object Object]'; }; var isArray = function isArray(val) { return Object.prototype.toString.call(val).indexOf('Array') !== -1; }; var isFunction = function isFunction(val) { return Object.prototype.toString.call(val) === '[object Function]'; }; var isString = function isString(val) { return Object.prototype.toString.call(val) === '[object String]'; }; var isBoolean = function isBoolean(val) { return Object.prototype.toString.call(val) === '[object Boolean]'; }; var isUndefined = function isUndefined(val) { return val === undefined || Object.prototype.toString.call(val) === '[object Undefined]'; }; var isNull = function isNull(val) { return Object.prototype.toString.call(val) === '[object Null]'; }; var isNumber = function isNumber(val) { return Object.prototype.toString.call(val) === '[object Number]'; }; var isArrayBuffer = function isArrayBuffer(val) { return Object.prototype.toString.call(val) === '[object ArrayBuffer]'; }; var isPromise = function isPromise(val) { var isTrue = false; try { isTrue = Object.prototype.toString.call(val) === '[object Promise]' || val && val.then && val["catch"] && val["finally"]; } catch (e) { isTrue = false; } return isTrue; }; var getTypeName = function getTypeName(data) { var typeName = Object.prototype.toString.call(data); return typeName.substring(8, typeName.length - 1); }; var isEqual = function isEqual(source, target) { return source === target; }; var ArrayBufferToArray = function ArrayBufferToArray(data) { if (isArrayBuffer(data)) { return [].slice.call(new Int8Array(data)); } return data; }; var ArrayBufferToUint8Array = function ArrayBufferToUint8Array(data) { if (isArrayBuffer(data)) { return new Uint8Array(data); } return data; }; var forEach = function forEach(source, event, options) { options = options || {}; event = event || noop; var _options = options, isReverse = _options.isReverse; var loopObj = function loopObj() { for (var key in source) { event(source[key], key, source); } }; var loopArr = function loopArr() { if (isReverse) { for (var i = source.length - 1; i >= 0; i--) { event(source[i], i); } } else { for (var j = 0, len = source.length; j < len; j++) { event(source[j], j); } } }; if (isObject(source)) { loopObj(); } if (isArray(source) || isString(source)) { loopArr(); } }; var isEmpty = function isEmpty(val) { var result = true; if (isObject(val)) { forEach(val, function () { result = false; }); } if (isString(val) || isArray(val)) { result = val.length === 0; } if (isNumber(val)) { result = val === 0; } return result; }; var isNumberData = function isNumberData(val) { var isEmptyVal = isEmpty(val); val = Number(val); return isNumber(val) && !isEmptyVal; }; var getKeys = function getKeys(obj) { var keyList = []; forEach(obj, function (val, key) { keyList.push(key); }); return keyList; }; var getValues = function getValues(obj) { var valList = []; forEach(obj, function (val) { valList.push(val); }); return valList; }; var getTimestamp = function getTimestamp(time) { return new Date(time).getTime(); }; var getCurrentTimestamp = function getCurrentTimestamp() { return new Date().getTime(); }; var isValidJSON = function isValidJSON(jsonStr) { var isValid = false; try { var obj = JSON$2.parse(jsonStr); var str = JSON$2.stringify(obj); isValid = str === jsonStr; } catch (e) { isValid = false; } return isValid; }; var isSupportSocket = function isSupportSocket() { var isMini = env.isMini; if (isMini) { return true; } var Socket = global$7.WebSocket; if (isUndefined(Socket)) { return false; } var hasWS = typeof Socket === 'object' || typeof Socket === 'function'; var isIntegrity = typeof Socket.OPEN === 'number'; return hasWS && isIntegrity; }; var indexOf = function indexOf(source, searchVal) { if (source.indexOf) { return source.indexOf(searchVal); } var index = -1; forEach(source, function (sub, i) { if (searchVal === sub) { index = i; return; } }); return index; }; var lastIndexOf = function lastIndexOf(source, searchVal) { if (source.lastIndexOf) { return source.lastIndexOf(searchVal); } var index = -1; forEach(source, function (sub, i) { if (searchVal === sub) { index = i; return; } }, { isReverse: true }); return index; }; var isInclude = function isInclude(source, searchVal) { var index = indexOf(source, searchVal); return index !== -1; }; var substring = function substring(source, start, end) { return source.substring(start, end); }; var spliceByChild = function spliceByChild(arr, item) { forEach(arr, function (child, index) { if (isEqual(child, item)) { arr.splice(index, 1); } }, { isReverse: true }); }; var parse16To10 = function parse16To10(num) { return parseInt(num, 16); }; var isPlus = function isPlus(num) { return +num === num; }; var filter = function filter(source, event) { var newArr = []; for (var i = 0, max = source.length; i < max; i++) { var data = source[i]; if (event(data, i)) { newArr.push(data); } } return newArr; }; var map = function map(source, event) { forEach(source, function (item, index) { source[index] = event(item, index); }); return source; }; var extend = function extend(destination, sources) { destination = destination || {}; sources = sources || {}; for (var key in sources) { var value = sources[key]; if (!isUndefined(value)) { destination[key] = value; } } return destination; }; var extendInShallow = function extendInShallow(destination, sources) { destination = copy(destination); sources = copy(sources); return extend(destination, sources); }; var deferred = function deferred(callbacks) { return new Defer(callbacks); }; var deferTimeout = function deferTimeout(timeout) { return deferred(function (resolve) { var timeouter = setTimeout(function () { resolve(timeouter); }, timeout); }); }; var tplEngine = function tplEngine(temp, data, regexp) { var replaceAction = function replaceAction(obj) { return temp.replace(regexp || /{([^}]+)}/g, function (match, name) { if (match.charAt(0) === '\\') { return match.slice(1); } return obj[name] !== undefined ? obj[name] : '{' + name + '}'; }); }; if (!isArray(data)) { data = [data]; } var ret = []; forEach(data, function (item) { ret.push(replaceAction(item)); }); return ret.join(''); }; var getRandomNum = function getRandomNum(max, min) { min = min || 0; var range = max - min, random = Math.random(); return min + Math.round(random * range); }; var Timer = function () { function Timer(options) { this._timerId = void 0; this._timerEvent = void 0; this._timerClearEvent = void 0; this.timeout = 0; this.type = TIMER_TYPE.TIMEOUT; this.status = TIMER_STATUS.PENNDING; var self = this; extend(self, options); var type = self.type; var isTimeout = type === TIMER_TYPE.TIMEOUT; if (isTimeout) { self._timerEvent = global$7.setTimeout; self._timerClearEvent = clearTimeout; } else { self._timerEvent = global$7.setInterval; self._timerClearEvent = clearInterval; } return self; } var _proto = Timer.prototype; _proto.start = function start(event, options) { options = options || {}; var self = this, isTimeout = self.type === TIMER_TYPE.TIMEOUT; var _options2 = options, args = _options2.args, thisArg = _options2.thisArg; self.stop(); self._timerId = self._timerEvent.call(global$7, function () { isTimeout && self.stop(); event.apply(thisArg, args); }, self.timeout); self.status = TIMER_STATUS.BUSY; }; _proto.stop = function stop() { var self = this; if (self._timerId) { self._timerClearEvent.call(global$7, self._timerId); self.status = TIMER_STATUS.ENDING; } }; return Timer; }(); var DeferHandler = function () { function DeferHandler(options) { this._list = {}; this.timeout = IM_TIMEOUT; extend(this, options); } var _proto2 = DeferHandler.prototype; _proto2._isInvalid = function _isInvalid(id) { var handlers = this._list[id]; return !isArray(handlers) || isEmpty(handlers); }; _proto2._exec = function _exec(id, isError, data) { var self = this; if (self._isInvalid(id)) { return; } var handlers = self._list[id], handler = handlers[0]; isError ? handler.reject(data) : handler.resolve(data); handlers.splice(0, 1); }; _proto2.add = function add(id, defer, options) { options = options || {}; var self = this; var resolve = defer.resolve, reject = defer.reject; var timeout = options.timeout || self.timeout; if (self._isInvalid(id)) { self._list[id] = []; } var timer = new Timer({ timeout: timeout }); timer.start(function () { self.reject(id, ERROR_INFO.TIMEOUT.code); }); self._list[id].push({ resolve: resolve, reject: reject, timer: timer }); }; _proto2.resolve = function resolve(id, data) { this._exec(id, false, data); }; _proto2.reject = function reject(id, error) { this._exec(id, true, error); }; return DeferHandler; }(); var EventEmitter = function () { function EventEmitter() { this._events = void 0; this._events = {}; } var _proto3 = EventEmitter.prototype; _proto3.on = function on(name, event) { var _events = this._events[name] || []; _events.push(event); this._events[name] = _events; }; _proto3.off = function off(name, offEvent) { if (offEvent) { var _events = this._events[name] || []; spliceByChild(_events, offEvent); } else { delete this._events[name]; } }; _proto3.emit = function emit(name, data, error) { var _events = this._events[name]; forEach(_events, function (event) { event(data, error); }); }; _proto3.clear = function clear() { this._events = {}; }; return EventEmitter; }(); var decodeURI = function decodeURI(uri) { return global$7.decodeURIComponent(uri); }; var encodeURI = function encodeURI(uri) { return global$7.encodeURIComponent(uri); }; var int64ToTimestamp = function int64ToTimestamp(obj) { if (obj.low === undefined) { return obj; } var low = obj.low; if (low < 0) { low += 0xffffffff + 1; } low = low.toString(16); var timestamp = parseInt(obj.high.toString(16) + '00000000'.replace(new RegExp('0{' + low.length + '}$'), low), 16); return timestamp; }; var batchInt64ToTimestamp = function batchInt64ToTimestamp(data) { forEach(data, function (item, key) { if (isObject(item)) { data[key] = int64ToTimestamp(item); } }); return data; }; var Queue = function () { function Queue(defaultConfig) { this._isRunning = false; this._list = []; this._defaultConfig = void 0; this._defaultConfig = defaultConfig; } var _proto4 = Queue.prototype; _proto4.add = function add(params) { params = params || this._defaultConfig; this._list.push(params); this.run(); }; _proto4.run = function run() { var self = this; var _isRunning = self._isRunning, _list = self._list; var isFinished = isEmpty(_list); if (_isRunning || isFinished) { return; } var firstItem = _list.splice(0, 1)[0]; var event = firstItem.event, args = firstItem.args, thisArg = firstItem.thisArg; var next = function next() { self._isRunning = false; self.run(); }; if (!event) { return next(); } self._isRunning = true; event.apply(thisArg, args)["finally"](next); }; return Queue; }(); var secondsToMilliseconds = function secondsToMilliseconds(seconds) { return seconds * 1000; }; var request$3 = function request(url, options) { options = options || {}; return deferred(function (resolve, reject) { options = extend(options, { url: url, success: function success(responseText, xhr, status) { resolve({ responseText: responseText, xhr: xhr, status: status }); }, fail: function fail(result, xhr, status) { reject({ result: result, xhr: xhr, status: status }); } }); request$2(options); }); }; var requestByUrlList = function requestByUrlList(urlList, options) { if (isEmpty(urlList)) { return Defer.reject(); } var url = urlList[0]; return request$3(url, options).then(function (result) { result = result || {}; result.urlList = urlList; return result; })["catch"](function (error) { urlList.splice(0, 1); if (isEmpty(urlList)) { return Defer.reject(error); } else { return requestByUrlList(urlList, options); } }); }; var requestForFaster = function requestForFaster(urlList, option) { option = option || {}; var timeInterval = option.timeInterval || 0; var faildCount = 0, totalCount = urlList.length; var requestXhrs = []; var totalTimer = new Timer({ timeout: 15 * 1000 }); var reqCountdownTimers = []; var clearAll = function clearAll() { forEach(reqCountdownTimers, function (timer) { timer.stop(); }); forEach(requestXhrs, function (xhr) { xhr.abort(); }); reqCountdownTimers.length = 0; requestXhrs.length = 0; }; var isAllFaild = function isAllFaild() { return faildCount === totalCount; }; return deferred(function (resolve, reject) { var _success = function success(url, index) { clearAll(); resolve({ url: url, index: index }); }; var _fail = function fail() { clearAll(); reject(); }; forEach(urlList, function (url, index) { var timer = new Timer({ timeout: timeInterval * index }); timer.start(function () { var xhr; var opt = extend({ url: url, success: function success() { _success(url, index); }, fail: function fail() { faildCount++; isAllFaild() && _fail(); } }, option); xhr = request$2(opt); requestXhrs.push(xhr); }); reqCountdownTimers.push(timer); }); totalTimer.start(_fail); }); }; var NetworkDetecter = function () { function NetworkDetecter(option) { this._option = void 0; this._detectCount = 0; this._timeoutId = void 0; this._option = option; } var _proto5 = NetworkDetecter.prototype; _proto5._detect = function _detect() { var self = this; var _detectCount = self._detectCount, _option = self._option; var url = _option.url, timeout = _option.intervalTime, max = _option.max; _detectCount++; return request$3(url).then(function () { return; }, function (_ref) { var status = _ref.status; if (isEqual(status, 404)) { return; } var isAlreadyMax = max && isEqual(max, _detectCount); if (isAlreadyMax) { return Defer.reject(); } return deferTimeout(timeout).then(function (timeoutId) { self._detectCount = _detectCount; self._timeoutId = timeoutId; return self._detect(); }); }); }; _proto5.start = function start() { return this._detect(); }; _proto5.stop = function stop() { var timeoutId = this._timeoutId; if (timeoutId) { clearTimeout(timeoutId); } }; return NetworkDetecter; }(); var toUpperCase = function toUpperCase(str, startIndex, endIndex) { if (isUndefined(startIndex) || isUndefined(endIndex)) { return str.toUpperCase(); } var sliceStr = str.slice(startIndex, endIndex); str = str.replace(sliceStr, function (text) { return text.toUpperCase(); }); return str; }; var getDomainByUrl = function getDomainByUrl(url) { var StartMark = '://', EndMark = '/'; var urlProtocolIndex = indexOf(url, StartMark); var hasProtocol = urlProtocolIndex > -1; if (hasProtocol) { urlProtocolIndex = urlProtocolIndex + StartMark.length; url = substring(url, urlProtocolIndex, url.length); } var urlPathIndex = indexOf(url, EndMark); var hasPath = urlPathIndex > -1; if (hasPath) { url = substring(url, 0, urlPathIndex); } return url; }; var getValidUrl = function getValidUrl(url, option) { option = option || {}; var ProtocolMark = '://'; var hasProtocol = isInclude(url, ProtocolMark); var localProtocol = env.protocol.http; var _option2 = option, protocol = _option2.protocol; if (protocol) { var domain = getDomainByUrl(url); url = protocol + "//" + domain; } if (hasProtocol) { var urlProtocolIndex = indexOf(url, ProtocolMark) + 1; var urlProtocol = substring(url, 0, urlProtocolIndex); var isHttpUrl = urlProtocol === HTTP_PROTOCOL.HTTP; var isLocalHttps = localProtocol === HTTP_PROTOCOL.HTTPS; if (isHttpUrl && isLocalHttps) { var _domain = getDomainByUrl(url); return HTTP_PROTOCOL.HTTPS + "//" + _domain; } else { return url; } } else { return localProtocol + "//" + url; } }; var quickSort = function quickSort(arr, event) { var sort = function sort(array, left, right, event) { event = event || function (a, b) { return a <= b; }; if (left < right) { var x = array[right], i = left - 1, temp; for (var j = left; j <= right; j++) { if (event(array[j], x)) { i++; temp = array[i]; array[i] = array[j]; array[j] = temp; } } sort(array, left, i - 1, event); sort(array, i + 1, right, event); } return array; }; return sort(arr, 0, arr.length - 1, event); }; var unique = function unique(arr, event) { var keyEvent = event || function (data) { return data; }; var hashTable = {}; var newArr = []; forEach(arr, function (data) { var key = keyEvent(data); if (!hashTable[key]) { hashTable[key] = true; newArr.push(data); } }); return newArr; }; var utils = { Storage: storage$1, Socket: Socket$2, Cache: CacheStorage, JSON: JSON$2, Defer: Defer, httpRequest: request$2, request: request$3, requestByUrlList: requestByUrlList, requestForFaster: requestForFaster, md5: md5, DeferHandler: DeferHandler, EventEmitter: EventEmitter, Timer: Timer, Queue: Queue, noop: noop, deferNoop: deferNoop, toJSON: toJSON, parseJSON: parseJSON, copy: copy, isObject: isObject, isArray: isArray, isFunction: isFunction, isArrayBuffer: isArrayBuffer, isString: isString, isBoolean: isBoolean, isUndefined: isUndefined, isNull: isNull, isNumber: isNumber, isNumberData: isNumberData, isPromise: isPromise, getTypeName: getTypeName, isPlus: isPlus, isEmpty: isEmpty, isEqual: isEqual, isValidJSON: isValidJSON, isSupportSocket: isSupportSocket, ArrayBufferToArray: ArrayBufferToArray, ArrayBufferToUint8Array: ArrayBufferToUint8Array, indexOf: indexOf, lastIndexOf: lastIndexOf, isInclude: isInclude, substring: substring, getKeys: getKeys, getValues: getValues, getTimestamp: getTimestamp, getCurrentTimestamp: getCurrentTimestamp, parse16To10: parse16To10, forEach: forEach, map: map, filter: filter, extend: extend, extendInShallow: extendInShallow, deferred: deferred, tplEngine: tplEngine, getRandomNum: getRandomNum, int64ToTimestamp: int64ToTimestamp, batchInt64ToTimestamp: batchInt64ToTimestamp, encodeURI: encodeURI, decodeURI: decodeURI, secondsToMilliseconds: secondsToMilliseconds, NetworkDetecter: NetworkDetecter, toUpperCase: toUpperCase, getDomainByUrl: getDomainByUrl, getValidUrl: getValidUrl, quickSort: quickSort, unique: unique }; function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } var _PUBLISH_TOPIC_TO_CON, _CONVERSATION_TYPE_TO, _CONVERSATION_TYPE_TO2, _CONVERSATION_TYPE_TO3; var SUCCESS_CODE = 0; var PULL_MSG_TYPE = { NORMAL: 1, CHATROOM: 2 }; var MESSAGE_NAME = { CONN_ACK: 'ConnAckMessage', DISCONNECT: 'DisconnectMessage', PING_REQ: 'PingReqMessage', PING_RESP: 'PingRespMessage', PUBLISH: 'PublishMessage', PUB_ACK: 'PubAckMessage', QUERY: 'QueryMessage', QUERY_CON: 'QueryConMessage', QUERY_ACK: 'QueryAckMessage' }; var QOS = { AT_MOST_ONCE: 0, AT_LEAST_ONCE: 1, EXACTLY_ONCE: 2, DEFAULT: 3, '0': 'AT_MOST_ONCE', '1': 'AT_LEAST_ONCE', '2': 'EXACTLY_ONCE', '3': 'DEFAULT' }; var OPERATE_TYPE = { CONNECT: 1, '1': 'CONNECT', CONNACK: 2, '2': 'CONNACK', PUBLISH: 3, '3': 'PUBLISH', PUBACK: 4, '4': 'PUBACK', QUERY: 5, '5': 'QUERY', QUERYACK: 6, '6': 'QUERYACK', QUERYCON: 7, '7': 'QUERYCON', SUBSCRIBE: 8, '8': 'SUBSCRIBE', SUBACK: 9, '9': 'SUBACK', UNSUBSCRIBE: 10, '10': 'UNSUBSCRIBE', UNSUBACK: 11, '11': 'UNSUBACK', PINGREQ: 12, '12': 'PINGREQ', PINGRESP: 13, '13': 'PINGRESP', DISCONNECT: 14, '14': 'DISCONNECT' }; var MESSAGE_TAG = { NONE: 0, PERSIT_ONLY: 1, COUNT_ONLY: 2, PERSIT_AND_COUNT: 3 }; var PUBLISH_TOPIC = { PRIVATE: 'ppMsgP', GROUP: 'pgMsgP', CHATROOM: 'chatMsg', CUSTOMER_SERVICE: 'pcMsgP', RECALL: 'recallMsg', NOTIFY_PULL_MSG: 's_ntf', RECEIVE_MSG: 's_msg', SYNC_STATUS: 's_stat', SYNC_CHRM_KV: 's_cmd' }; var QUERY_TOPIC = { GET_SYNC_TIME: 'qrySessionsAtt', PULL_MSG: 'pullMsg', GET_CONVERSATION_LIST: 'qrySessions', REMOVE_CONVERSATION_LIST: 'delSessions', DELETE_MESSAGES: 'delMsg', CLEAR_UNREAD_COUNT: 'updRRTime', PULL_CHRM_MSG: 'chrmPull', JOIN_CHATROOM: 'joinChrm', QUIT_CHATROOM: 'exitChrm', GET_CHATROOM_INFO: 'queryChrmI', GET_OLD_CONVERSATION_LIST: 'qryRelation', REMOVE_OLD_CONVERSATION: 'delRelation', CLEAR_MESSAGES: { PRIVATE: 'cleanPMsg', GROUP: 'cleanGMsg', CUSTOMER_SERVICE: 'cleanCMsg', SYSTEM: 'cleanSMsg' } }; var QUERY_HISTORY_TOPIC = { PRIVATE: 'qryPMsg', GROUP: 'qryGMsg', CHATROOM: 'qryCHMsg', CUSTOMER_SERVICE: 'qryCMsg', SYSTEM: 'qrySMsg' }; var PUBLISH_TOPIC_TO_CONVERSATION_TYPE = (_PUBLISH_TOPIC_TO_CON = {}, _PUBLISH_TOPIC_TO_CON[PUBLISH_TOPIC.PRIVATE] = CONVERSATION_TYPE.PRIVATE, _PUBLISH_TOPIC_TO_CON[PUBLISH_TOPIC.GROUP] = CONVERSATION_TYPE.GROUP, _PUBLISH_TOPIC_TO_CON[PUBLISH_TOPIC.CHATROOM] = CONVERSATION_TYPE.CHATROOM, _PUBLISH_TOPIC_TO_CON[PUBLISH_TOPIC.CUSTOMER_SERVICE] = CONVERSATION_TYPE.CUSTOMER_SERVICE, _PUBLISH_TOPIC_TO_CON); var CONVERSATION_TYPE_TO_PUBLISH_TOPIC = (_CONVERSATION_TYPE_TO = {}, _CONVERSATION_TYPE_TO[CONVERSATION_TYPE.PRIVATE] = PUBLISH_TOPIC.PRIVATE, _CONVERSATION_TYPE_TO[CONVERSATION_TYPE.GROUP] = PUBLISH_TOPIC.GROUP, _CONVERSATION_TYPE_TO[CONVERSATION_TYPE.CHATROOM] = PUBLISH_TOPIC.CHATROOM, _CONVERSATION_TYPE_TO[CONVERSATION_TYPE.CUSTOMER_SERVICE] = PUBLISH_TOPIC.CUSTOMER_SERVICE, _CONVERSATION_TYPE_TO); var CONVERSATION_TYPE_TO_QUERY_HISTORY_TOPIC = (_CONVERSATION_TYPE_TO2 = {}, _CONVERSATION_TYPE_TO2[CONVERSATION_TYPE.PRIVATE] = QUERY_HISTORY_TOPIC.PRIVATE, _CONVERSATION_TYPE_TO2[CONVERSATION_TYPE.GROUP] = QUERY_HISTORY_TOPIC.GROUP, _CONVERSATION_TYPE_TO2[CONVERSATION_TYPE.CHATROOM] = QUERY_HISTORY_TOPIC.CHATROOM, _CONVERSATION_TYPE_TO2[CONVERSATION_TYPE.CUSTOMER_SERVICE] = QUERY_HISTORY_TOPIC.CUSTOMER_SERVICE, _CONVERSATION_TYPE_TO2[CONVERSATION_TYPE.SYSTEM] = QUERY_HISTORY_TOPIC.SYSTEM, _CONVERSATION_TYPE_TO2); var CONVERSATION_TYPE_TO_CLEAR_MESSAGE_TOPIC = (_CONVERSATION_TYPE_TO3 = {}, _CONVERSATION_TYPE_TO3[CONVERSATION_TYPE.PRIVATE] = QUERY_TOPIC.CLEAR_MESSAGES.PRIVATE, _CONVERSATION_TYPE_TO3[CONVERSATION_TYPE.GROUP] = QUERY_TOPIC.CLEAR_MESSAGES.GROUP, _CONVERSATION_TYPE_TO3[CONVERSATION_TYPE.CUSTOMER_SERVICE] = QUERY_TOPIC.CLEAR_MESSAGES.CUSTOMER_SERVICE, _CONVERSATION_TYPE_TO3[CONVERSATION_TYPE.SYSTEM] = QUERY_TOPIC.CLEAR_MESSAGES.SYSTEM, _CONVERSATION_TYPE_TO3); var Header = function () { function Header(_type, _retain, _qos, _dup) { this.type = void 0; this.retain = false; this.qos = QOS.AT_LEAST_ONCE; this.dup = false; this.syncMsg = false; var isPlusType = utils.isPlus(_type); if (_type && isPlusType && arguments.length === 1) { this.retain = (_type & 1) > 0; this.qos = (_type & 6) >> 1; this.dup = (_type & 8) > 0; this.type = _type >> 4 & 15; this.syncMsg = (_type & 8) === 8; } else { this.type = _type; this.retain = _retain === undefined ? false : _retain; this.qos = _qos === undefined ? QOS.AT_LEAST_ONCE : _qos; this.dup = _dup === undefined ? false : _dup; } } var _proto = Header.prototype; _proto.encode = function encode() { var self = this; var validQosList = [QOS.AT_MOST_ONCE, QOS.AT_LEAST_ONCE, QOS.EXACTLY_ONCE, QOS.DEFAULT]; utils.forEach(validQosList, function (qos) { if (self.qos === QOS[qos]) { self.qos = qos; } }); var _byte = self.type << 4; _byte |= self.retain ? 1 : 0; _byte |= self.qos << 1; _byte |= self.dup ? 8 : 0; return _byte; }; return Header; }(); var BinaryHelper = { writeUTF: function writeUTF(str, isGetBytes) { var back = [], byteSize = 0; utils.forEach(str, function (_char, i) { var code = str.charCodeAt(i); if (code >= 0 && code <= 127) { byteSize += 1; back.push(code); } else if (code >= 128 && code <= 2047) { byteSize += 2; back.push(192 | 31 & code >> 6); back.push(128 | 63 & code); } else if (code >= 2048 && code <= 65535) { byteSize += 3; back.push(224 | 15 & code >> 12); back.push(128 | 63 & code >> 6); back.push(128 | 63 & code); } }); utils.forEach(back, function (_char2, i) { if (_char2 > 255) { back[i] &= 255; } }); if (isGetBytes) { return back; } if (byteSize <= 255) { return [0, byteSize].concat(back); } else { return [byteSize >> 8, byteSize & 255].concat(back); } }, readUTF: function readUTF(arr) { var UTF = ''; for (var i = 0, len = arr.length; i < len; i++) { var _char3 = arr[i]; if (_char3 < 0) { arr[i] += 256; } var one = arr[i].toString(2), v = one.match(/^1+?(?=0)/); if (v && one.length === 8) { var bytesLength = v[0].length, store = ''; for (var st = 0; st < bytesLength; st++) { store += arr[st + i].toString(2).slice(2); } UTF += String.fromCharCode(parseInt(store, 2)); i += bytesLength - 1; } else { UTF += String.fromCharCode(arr[i]); } } return UTF; } }; var RongStreamReader = function () { function RongStreamReader(arr) { this.pool = void 0; this.position = 0; this.poolLen = 0; this.pool = arr; this.poolLen = arr.length; } var _proto2 = RongStreamReader.prototype; _proto2.check = function check() { return this.position >= this.pool.length; }; _proto2.readInt = function readInt() { var self = this; if (self.check()) { return -1; } var end = ''; for (var i = 0; i < 4; i++) { var t = self.pool[self.position++].toString(16); if (t.length === 1) { t = '0' + t; } end += t.toString(); } return utils.parse16To10(end); }; _proto2.readLong = function readLong() { var self = this; if (self.check()) { return -1; } var end = ''; for (var i = 0; i < 8; i++) { var t = self.pool[self.position++].toString(16); if (t.length === 1) { t = '0' + t; } end += t; } return utils.parse16To10(end); }; _proto2.readByte = function readByte() { if (this.check()) { return -1; } var val = this.pool[this.position++]; if (val > 255) { val &= 255; } return val; }; _proto2.readUTF = function readUTF() { if (this.check()) { return ''; } var big = this.readByte() << 8 | this.readByte(); var pool = this.pool.subarray(this.position, this.position += big); return BinaryHelper.readUTF(pool); }; _proto2.readAll = function readAll() { return this.pool.subarray(this.position, this.poolLen); }; return RongStreamReader; }(); var RongStreamWriter = function () { function RongStreamWriter() { this.pool = []; this.position = 0; this.writen = 0; } var _proto3 = RongStreamWriter.prototype; _proto3.write = function write(_byte2) { if (utils.isArray(_byte2)) { this.pool = this.pool.concat(_byte2); } else if (utils.isPlus(_byte2)) { if (_byte2 > 255) { _byte2 &= 255; } this.pool.push(_byte2); this.writen++; } return _byte2; }; _proto3.writeArr = function writeArr(_byte3) { this.pool = this.pool.concat(_byte3); return _byte3; }; _proto3.writeUTF = function writeUTF(str) { var val = BinaryHelper.writeUTF(str); this.pool = this.pool.concat(val); this.writen += val.length; }; _proto3.getBytesArray = function getBytesArray() { return this.pool; }; return RongStreamWriter; }(); var IDENTIFIER = { PUB: 'pub', QUERY: 'qry' }; var _getIdentifier = function getIdentifier(messageId, identifier) { if (messageId && identifier) { return identifier + '_' + messageId; } else if (messageId) { return messageId; } else { return utils.getCurrentTimestamp(); } }; var BaseReader = function () { function BaseReader(header) { this._name = void 0; this._header = void 0; this.lengthSize = 0; this.messageId = void 0; this.identifier = void 0; this._header = header; } var _proto = BaseReader.prototype; _proto.getIdentifier = function getIdentifier() { var messageId = this.messageId, identifier = this.identifier; return _getIdentifier(messageId, identifier); }; _proto.read = function read(stream, length) { this.readMessage(stream, length); }; _proto.readMessage = function readMessage(stream, length) { return { stream: stream, length: length }; }; return BaseReader; }(); var BaseWriter = function () { function BaseWriter(headerType) { this._header = void 0; this.lengthSize = 0; this.data = void 0; this.messageId = void 0; this.topic = void 0; this.targetId = void 0; this.identifier = void 0; this._header = new Header(headerType, false, QOS.AT_MOST_ONCE, false); } var _proto2 = BaseWriter.prototype; _proto2.getIdentifier = function getIdentifier() { var messageId = this.messageId, identifier = this.identifier; return _getIdentifier(messageId, identifier); }; _proto2.write = function write(stream) { var headerCode = this.getHeaderFlag(); stream.write(headerCode); this.writeMessage(stream); }; _proto2.writeMessage = function writeMessage(stream) { return stream; }; _proto2.setHeaderQos = function setHeaderQos(qos) { this._header.qos = qos; }; _proto2.getHeaderFlag = function getHeaderFlag() { return this._header.encode(); }; _proto2.getLengthSize = function getLengthSize() { return this.lengthSize; }; _proto2.getBufferData = function getBufferData() { var stream = new RongStreamWriter(); this.write(stream); var val = stream.getBytesArray(); var binary = new Int8Array(val); return binary; }; _proto2.getCometData = function getCometData() { var data = this.data || {}; return utils.toJSON(data); }; return BaseWriter; }(); var ConnAckReader = function (_BaseReader) { _inheritsLoose(ConnAckReader, _BaseReader); function ConnAckReader() { var _this; for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this = _BaseReader.call.apply(_BaseReader, [this].concat(args)) || this; _this._name = MESSAGE_NAME.CONN_ACK; _this.status = void 0; _this.userId = void 0; _this.timestamp = void 0; return _this; } var _proto3 = ConnAckReader.prototype; _proto3.readMessage = function readMessage(stream, msgLength) { stream.readByte(); this.status = +stream.readByte(); if (msgLength > ConnAckReader.MESSAGE_LENGTH) { this.userId = stream.readUTF(); stream.readUTF(); this.timestamp = stream.readLong(); } }; return ConnAckReader; }(BaseReader); ConnAckReader.MESSAGE_LENGTH = 2; var DisconnectReader = function (_BaseReader2) { _inheritsLoose(DisconnectReader, _BaseReader2); function DisconnectReader() { var _this2; for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } _this2 = _BaseReader2.call.apply(_BaseReader2, [this].concat(args)) || this; _this2._name = MESSAGE_NAME.DISCONNECT; _this2.status = void 0; return _this2; } var _proto4 = DisconnectReader.prototype; _proto4.readMessage = function readMessage(stream) { stream.readByte(); this.status = +stream.readByte(); }; return DisconnectReader; }(BaseReader); DisconnectReader.MESSAGE_LENGTH = 2; var PingReqWriter = function (_BaseWriter) { _inheritsLoose(PingReqWriter, _BaseWriter); function PingReqWriter() { var _this3; _this3 = _BaseWriter.call(this, OPERATE_TYPE.PINGREQ) || this; _this3._name = MESSAGE_NAME.PING_REQ; return _this3; } return PingReqWriter; }(BaseWriter); var PingRespReader = function (_BaseReader3) { _inheritsLoose(PingRespReader, _BaseReader3); function PingRespReader() { var _this4; for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { args[_key3] = arguments[_key3]; } _this4 = _BaseReader3.call.apply(_BaseReader3, [this].concat(args)) || this; _this4._name = MESSAGE_NAME.PING_RESP; return _this4; } return PingRespReader; }(BaseReader); var RetryableReader = function (_BaseReader4) { _inheritsLoose(RetryableReader, _BaseReader4); function RetryableReader() { var _this5; for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { args[_key4] = arguments[_key4]; } _this5 = _BaseReader4.call.apply(_BaseReader4, [this].concat(args)) || this; _this5.messageId = void 0; return _this5; } var _proto5 = RetryableReader.prototype; _proto5.readMessage = function readMessage(stream) { var msgId = stream.readByte() * 256 + stream.readByte(); this.messageId = parseInt(msgId, 10); }; return RetryableReader; }(BaseReader); var RetryableWriter = function (_BaseWriter2) { _inheritsLoose(RetryableWriter, _BaseWriter2); function RetryableWriter() { var _this6; for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) { args[_key5] = arguments[_key5]; } _this6 = _BaseWriter2.call.apply(_BaseWriter2, [this].concat(args)) || this; _this6.messageId = void 0; return _this6; } var _proto6 = RetryableWriter.prototype; _proto6.writeMessage = function writeMessage(stream) { var id = this.messageId; var lsb = id & 255; var msb = (id & 65280) >> 8; stream.write(msb); stream.write(lsb); }; return RetryableWriter; }(BaseWriter); var PublishReader = function (_RetryableReader) { _inheritsLoose(PublishReader, _RetryableReader); function PublishReader() { var _this7; for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) { args[_key6] = arguments[_key6]; } _this7 = _RetryableReader.call.apply(_RetryableReader, [this].concat(args)) || this; _this7._name = MESSAGE_NAME.PUBLISH; _this7.topic = void 0; _this7.data = void 0; _this7.targetId = void 0; _this7.date = void 0; _this7.syncMsg = false; _this7.identifier = IDENTIFIER.PUB; return _this7; } var _proto7 = PublishReader.prototype; _proto7.readMessage = function readMessage(stream) { this.date = stream.readInt(); this.topic = stream.readUTF(); this.targetId = stream.readUTF(); RetryableReader.prototype.readMessage.apply(this, arguments); this.data = stream.readAll(); }; return PublishReader; }(RetryableReader); var PublishWriter = function (_RetryableWriter) { _inheritsLoose(PublishWriter, _RetryableWriter); function PublishWriter(topic, data, targetId) { var _this8; _this8 = _RetryableWriter.call(this, OPERATE_TYPE.PUBLISH) || this; _this8._name = MESSAGE_NAME.PUBLISH; _this8.topic = void 0; _this8.data = void 0; _this8.targetId = void 0; _this8.date = void 0; _this8.syncMsg = false; _this8.identifier = IDENTIFIER.PUB; _this8.topic = topic; _this8.data = utils.isString(data) ? BinaryHelper.writeUTF(data) : data; _this8.targetId = targetId; return _this8; } var _proto8 = PublishWriter.prototype; _proto8.writeMessage = function writeMessage(stream) { stream.writeUTF(this.topic); stream.writeUTF(this.targetId); RetryableWriter.prototype.writeMessage.apply(this, arguments); stream.write(this.data); }; return PublishWriter; }(RetryableWriter); var PubAckReader = function (_RetryableReader2) { _inheritsLoose(PubAckReader, _RetryableReader2); function PubAckReader() { var _this9; for (var _len7 = arguments.length, args = new Array(_len7), _key7 = 0; _key7 < _len7; _key7++) { args[_key7] = arguments[_key7]; } _this9 = _RetryableReader2.call.apply(_RetryableReader2, [this].concat(args)) || this; _this9._name = MESSAGE_NAME.PUB_ACK; _this9.status = void 0; _this9.date = 0; _this9.data = void 0; _this9.millisecond = 0; _this9.messageUId = void 0; _this9.timestamp = 0; _this9.identifier = IDENTIFIER.PUB; return _this9; } var _proto9 = PubAckReader.prototype; _proto9.readMessage = function readMessage(stream) { RetryableReader.prototype.readMessage.call(this, stream); this.date = stream.readInt(); this.status = stream.readByte() * 256 + stream.readByte(); this.millisecond = stream.readByte() * 256 + stream.readByte(); this.timestamp = this.date * 1000 + this.millisecond; this.messageUId = stream.readUTF(); }; return PubAckReader; }(RetryableReader); var PubAckWriter = function (_RetryableWriter2) { _inheritsLoose(PubAckWriter, _RetryableWriter2); function PubAckWriter(messageId) { var _this10; _this10 = _RetryableWriter2.call(this, OPERATE_TYPE.PUBACK) || this; _this10._name = MESSAGE_NAME.PUB_ACK; _this10.status = void 0; _this10.date = 0; _this10.millisecond = 0; _this10.messageUId = void 0; _this10.timestamp = 0; _this10.messageId = messageId; return _this10; } var _proto10 = PubAckWriter.prototype; _proto10.writeMessage = function writeMessage(stream) { RetryableWriter.prototype.writeMessage.call(this, stream); }; return PubAckWriter; }(RetryableWriter); var QueryWriter = function (_RetryableWriter3) { _inheritsLoose(QueryWriter, _RetryableWriter3); function QueryWriter(topic, data, targetId) { var _this11; _this11 = _RetryableWriter3.call(this, OPERATE_TYPE.QUERY) || this; _this11._name = MESSAGE_NAME.QUERY; _this11.topic = void 0; _this11.data = void 0; _this11.targetId = void 0; _this11.identifier = IDENTIFIER.QUERY; _this11.topic = topic; _this11.data = utils.isString(data) ? BinaryHelper.writeUTF(data) : data; _this11.targetId = targetId; return _this11; } var _proto11 = QueryWriter.prototype; _proto11.writeMessage = function writeMessage(stream) { stream.writeUTF(this.topic); stream.writeUTF(this.targetId); RetryableWriter.prototype.writeMessage.call(this, stream); stream.write(this.data); }; return QueryWriter; }(RetryableWriter); var QueryConWriter = function (_RetryableWriter4) { _inheritsLoose(QueryConWriter, _RetryableWriter4); function QueryConWriter(messageId) { var _this12; _this12 = _RetryableWriter4.call(this, OPERATE_TYPE.QUERYCON) || this; _this12._name = MESSAGE_NAME.QUERY_CON; _this12.messageId = messageId; return _this12; } return QueryConWriter; }(RetryableWriter); var QueryAckReader = function (_RetryableReader3) { _inheritsLoose(QueryAckReader, _RetryableReader3); function QueryAckReader() { var _this13; for (var _len8 = arguments.length, args = new Array(_len8), _key8 = 0; _key8 < _len8; _key8++) { args[_key8] = arguments[_key8]; } _this13 = _RetryableReader3.call.apply(_RetryableReader3, [this].concat(args)) || this; _this13._name = MESSAGE_NAME.QUERY_ACK; _this13.data = void 0; _this13.status = void 0; _this13.date = void 0; _this13.identifier = IDENTIFIER.QUERY; return _this13; } var _proto12 = QueryAckReader.prototype; _proto12.readMessage = function readMessage(stream) { RetryableReader.prototype.readMessage.call(this, stream); this.date = stream.readInt(); this.status = stream.readByte() * 256 + stream.readByte(); this.data = stream.readAll(); }; return QueryAckReader; }(RetryableReader); var getReaderByHeader = function getReaderByHeader(header) { var type = header.type, msg = new BaseReader(header); switch (type) { case OPERATE_TYPE.CONNACK: msg = new ConnAckReader(header); break; case OPERATE_TYPE.PUBLISH: msg = new PublishReader(header); msg.syncMsg = header.syncMsg; break; case OPERATE_TYPE.PUBACK: msg = new PubAckReader(header); break; case OPERATE_TYPE.QUERYACK: msg = new QueryAckReader(header); break; case OPERATE_TYPE.SUBACK: case OPERATE_TYPE.UNSUBACK: case OPERATE_TYPE.PINGRESP: msg = new PingRespReader(header); break; case OPERATE_TYPE.DISCONNECT: msg = new DisconnectReader(header); break; default: throw new Error('No support for deserializing ' + type + ' messages'); } return msg; }; var readWSBuffer = function readWSBuffer(data) { var arr = new Uint8Array(data); var stream = new RongStreamReader(arr); var flags = stream.readByte(), header = new Header(flags); var msg = getReaderByHeader(header); msg.read(stream, arr.length - 1); return msg; }; var readCometData = function readCometData(data) { var flags = data.headerCode, header = new Header(flags); var msg = getReaderByHeader(header); utils.forEach(data, function (item, key) { if (key in msg) { msg[key] = item; } }); return msg; }; var _PUBLISH_TOPIC_MAP_SE; var ENGINE_EVENT = { WATCH: 'watch', CONNECT: 'connect', RECONNECT: 'reconnect', DISCONNECT: 'disconnect', CHANGE_USER: 'change_user', GET_CONVERSATION_LIST: 'get_conversation_list', REMOVE_CONVERSATION_LIST: 'remove_conversation_list', REMOVE_CONVERSATION: 'remove_conversation', GET_TOTAL_UNREAD_COUNT: 'get_total_unread_count', CLEAR_UNREAD_COUNT: 'clear_unread_count', SEND_MESSAGE: 'send_message', GET_HISTORY_MSGS: 'get_history_msgs', DELETE_MESSAGES: 'delete_history_msgs', CLEAR_MESSAGES: 'clear_history_msgs', RECALL_MESSAGE: 'recall_message', JOIN_CHATROOM: 'join_chatroom', QUIT_CHATROOM: 'quit_chatroom', GET_CHATROOM_INFO: 'get_chatroom_info', GET_CHATROOM_MSGS: 'get_chatroom_msgs' }; var ENGINE_EVENT_NEED_CONNECTED = [ENGINE_EVENT.GET_CONVERSATION_LIST, ENGINE_EVENT.REMOVE_CONVERSATION_LIST, ENGINE_EVENT.REMOVE_CONVERSATION, ENGINE_EVENT.GET_TOTAL_UNREAD_COUNT, ENGINE_EVENT.CLEAR_UNREAD_COUNT, ENGINE_EVENT.SEND_MESSAGE, ENGINE_EVENT.GET_HISTORY_MSGS, ENGINE_EVENT.DELETE_MESSAGES, ENGINE_EVENT.CLEAR_MESSAGES, ENGINE_EVENT.RECALL_MESSAGE, ENGINE_EVENT.JOIN_CHATROOM, ENGINE_EVENT.QUIT_CHATROOM, ENGINE_EVENT.GET_CHATROOM_INFO, ENGINE_EVENT.GET_CHATROOM_MSGS]; var ENGINE_EVENT_NEED_DISCONNECTED = [ENGINE_EVENT.CONNECT, ENGINE_EVENT.RECONNECT]; var IM_EVENT = { STATUS: 'status', MESSAGE: 'message', CONVERSATION: 'conversation' }; var TRANSPORT_EVENT = { SIGNAL: 'signal', STATUS: 'status' }; var SERVER_TASK = { DISCONNECTED: 'disconnected', SYNC_SELF_MSG: 'sync_self_other_client_msg', NOTIFY_PULL: 'notify_pull_msg', RECEIVE_MSG: 'receive_msg', SYNC_STATUS: 'sync_status', SYNC_CHRM_KV: 'sync_chrm_kv' }; var PUBLISH_TOPIC_MAP_SERVER_TASK = (_PUBLISH_TOPIC_MAP_SE = {}, _PUBLISH_TOPIC_MAP_SE[PUBLISH_TOPIC.NOTIFY_PULL_MSG] = SERVER_TASK.NOTIFY_PULL, _PUBLISH_TOPIC_MAP_SE[PUBLISH_TOPIC.RECEIVE_MSG] = SERVER_TASK.RECEIVE_MSG, _PUBLISH_TOPIC_MAP_SE[PUBLISH_TOPIC.SYNC_STATUS] = SERVER_TASK.SYNC_STATUS, _PUBLISH_TOPIC_MAP_SE[PUBLISH_TOPIC.SYNC_CHRM_KV] = SERVER_TASK.SYNC_CHRM_KV, _PUBLISH_TOPIC_MAP_SE); var isEmpty$1 = utils.isEmpty, tplEngine$1 = utils.tplEngine, getRandomNum$1 = utils.getRandomNum; var getTransporterUrl = function getTransporterUrl(option) { var domain = option.domain, appkey = option.appkey, token = option.token, connectType = option.connectType, protocol = option.protocol; var isComet = connectType === CONNECT_TYPE.COMET; if (isEmpty$1(protocol)) { protocol = isComet ? env.protocol.http : env.protocol.ws; } return tplEngine$1(CMP_URL_TPL, { domain: domain, appkey: appkey, protocol: protocol, apiVer: getRandomNum$1(1e6), token: utils.encodeURI(token) }); }; var isGroup = function isGroup(type) { return type === CONVERSATION_TYPE.GROUP; }; var isChatRoom = function isChatRoom(type) { return type === CONVERSATION_TYPE.CHATROOM; }; var getConversationTypeList = function getConversationTypeList() { return utils.getValues(CONVERSATION_TYPE); }; var isValidConversationType = function isValidConversationType(type) { var conversationTypeList = getConversationTypeList(); return utils.isNumber(type) && utils.isInclude(conversationTypeList, type); }; var getSessionId = function getSessionId(option) { var isPersited = option.isPersited, isCounted = option.isCounted, isMentiond = option.isMentiond; var sessionId = 0; if (isPersited) { sessionId = sessionId | 0x01; } if (isCounted) { sessionId = sessionId | 0x02; } if (isMentiond) { sessionId = sessionId | 0x04; } return sessionId; }; var getPersitedAndCountedBySessionId = function getPersitedAndCountedBySessionId(sessionId) { var isPersited, isCounted; switch (sessionId) { case MESSAGE_TAG.COUNT_ONLY: isPersited = false; isCounted = true; break; case MESSAGE_TAG.PERSIT_ONLY: isPersited = true; isCounted = false; break; case MESSAGE_TAG.NONE: isPersited = isCounted = false; break; case MESSAGE_TAG.PERSIT_AND_COUNT: default: isPersited = isCounted = true; break; } return { isPersited: isPersited, isCounted: isCounted }; }; var getMessageOptionByStatus = function getMessageOptionByStatus(status) { var isPersited = true, isCounted = true, isMentiond = false; isPersited = !!(status & 0x10); isCounted = !!(status & 0x20); isMentiond = !!(status & 0x40); return { isPersited: isPersited, isCounted: isCounted, isMentiond: isMentiond }; }; var SignalId = { ids: {}, temp: '{appkey}_{userId}', get: function get(option) { var key = utils.tplEngine(SignalId.temp, option); var id = SignalId.ids[key] || 0; id++; SignalId.ids[key] = id; return id; }, clear: function clear(option) { var key = utils.tplEngine(SignalId.temp, option); SignalId.ids[key] = 0; }, isExceedLimit: function isExceedLimit(id) { return id > MAX_SINGAL_ID; } }; var RCSocket = function () { function RCSocket(options) { this._socket = void 0; this.eventEmitter = new utils.EventEmitter(); this.KEY = { OPEN: 'open', MSG: 'msg', ERROR: 'error', CLOSE: 'close' }; var self = this; var KEY = self.KEY; self._socket = new utils.Socket(options); self._socket.onOpen(function (data) { self.eventEmitter.emit(KEY.OPEN, data); }); self._socket.onMessage(function (data) { self.eventEmitter.emit(KEY.MSG, data); }); self._socket.onError(function (data) { self.eventEmitter.emit(KEY.ERROR, data); }); self._socket.onClose(function (data) { self.eventEmitter.emit(KEY.CLOSE, data); }); } var _proto = RCSocket.prototype; _proto.send = function send(data) { return this._socket.send(data); }; _proto.close = function close() { this.eventEmitter.clear(); this._socket.close(); }; _proto.onOpen = function onOpen(event) { this.eventEmitter.on(this.KEY.OPEN, event); }; _proto.onMessage = function onMessage(event) { this.eventEmitter.on(this.KEY.MSG, event); }; _proto.onError = function onError(event) { this.eventEmitter.on(this.KEY.ERROR, event); }; _proto.onClose = function onClose(event) { this.eventEmitter.on(this.KEY.CLOSE, event); }; return RCSocket; }(); var RCStorage = function () { function RCStorage(suffix) { var _ref; this._cache = void 0; this.STORAGE_KEY = void 0; var storageKey = suffix ? STORAGE_ROOT_KEY + suffix : STORAGE_ROOT_KEY; var localCache = utils.Storage.get(storageKey) || {}; this._cache = new utils.Cache((_ref = {}, _ref[storageKey] = localCache, _ref)); this.STORAGE_KEY = storageKey; } var _proto2 = RCStorage.prototype; _proto2._get = function _get() { var KEY = this.STORAGE_KEY; return this._cache.get(KEY) || {}; }; _proto2._set = function _set(cache) { var KEY = this.STORAGE_KEY; cache = cache || {}; this._cache.set(KEY, cache); utils.Storage.set(KEY, cache); }; _proto2.set = function set(key, value) { var localValue = this._get(); localValue[key] = value; this._set(localValue); }; _proto2.remove = function remove(key) { var localValue = this._get(); delete localValue[key]; this._set(localValue); }; _proto2.clear = function clear() { var KEY = this.STORAGE_KEY; utils.Storage.remove(KEY); this._cache.remove(KEY); }; _proto2.get = function get(key) { var localValue = this._get(); return localValue[key]; }; _proto2.getKeys = function getKeys() { var localValue = this._get(); return utils.getKeys(localValue); }; _proto2.getValues = function getValues() { return this._get() || {}; }; return RCStorage; }(); var formatSyncTime = function formatSyncTime(_syncTime) { _syncTime = _syncTime || {}; _syncTime.inboxTime = _syncTime.inboxTime || 0; _syncTime.sendboxTime = _syncTime.sendboxTime || 0; return _syncTime; }; var MessageTimeSyner = function () { function MessageTimeSyner(option) { this._syncTime = void 0; this._storage = void 0; option = option || {}; var _option = option, startSyncTime = _option.startSyncTime; this._initStorage(option); if (startSyncTime) { this._syncTime = formatSyncTime(startSyncTime); } } var _proto3 = MessageTimeSyner.prototype; _proto3._initStorage = function _initStorage(option) { var appkey = option.appkey, userId = option.userId; var ROOT_KEY = utils.tplEngine(STORAGE_SYNC_TIME.ROOT_KEY_TPL, { appkey: appkey, userId: userId }); var storage = new RCStorage(ROOT_KEY); var syncTime = { sendboxTime: storage.get(STORAGE_SYNC_TIME.SUB_KEY.SENDBOX), inboxTime: storage.get(STORAGE_SYNC_TIME.SUB_KEY.INBOX) }; this._storage = storage; this._syncTime = formatSyncTime(syncTime); }; _proto3.setInbox = function setInbox(time) { this._syncTime.inboxTime = time; this._storage.set(STORAGE_SYNC_TIME.SUB_KEY.INBOX, time); }; _proto3.setSendbox = function setSendbox(time) { this._syncTime.sendboxTime = time; this._storage.set(STORAGE_SYNC_TIME.SUB_KEY.SENDBOX, time); }; _proto3.setByMessage = function setByMessage(msg) { var direction = msg.direction, sentTime = msg.sentTime; var isSelfSend = direction === MESSAGE_DIRECTION.SEND; isSelfSend ? this.setSendbox(sentTime) : this.setInbox(sentTime); }; _proto3.get = function get() { return formatSyncTime(this._syncTime); }; return MessageTimeSyner; }(); var ChatRoomMessageTimeSyner = function () { function ChatRoomMessageTimeSyner() { this._pullTimes = {}; } var _proto4 = ChatRoomMessageTimeSyner.prototype; _proto4.set = function set(chrmId, time) { this._pullTimes[chrmId] = time; }; _proto4.get = function get(chrmId) { return this._pullTimes[chrmId] || 0; }; _proto4.setByMessage = function setByMessage(msg) { var sentTime = msg.sentTime; var chrmId = msg.targetId; this.set(chrmId, sentTime); }; return ChatRoomMessageTimeSyner; }(); var getUIDByToken = function getUIDByToken(token) { return utils.md5(token).slice(8, 16); }; var isIncludeNavi = function isIncludeNavi(token) { return utils.isInclude(token, NAVI_SEPARATOR_IN_TOKEN); }; var getNaviListByToken = function getNaviListByToken(token) { var navDomainList = []; if (isIncludeNavi(token)) { var separatorIndex = utils.indexOf(token, NAVI_SEPARATOR_IN_TOKEN); var navsText = token.substring(separatorIndex + 1, token.length); var domainList = navsText.split(DOMAIN_SEPARATOR_IN_NAVLIST); utils.forEach(domainList, function (domain) { if (!isEmpty$1(domain)) { navDomainList.push(domain); } }); } return navDomainList; }; var getCMPDomainList = function getCMPDomainList(option) { var server = option.server, backupServer = option.backupServer; server = server || ''; backupServer = backupServer || ''; var backupCMPList = backupServer.split(DOMAIN_SEPARATOR_IN_CMPLIST); var cmpList = [server]; utils.forEach(backupCMPList, function (cmp) { if (!utils.isEmpty(cmp)) { cmpList.push(cmp); } }); return cmpList; }; var getValidToken = function getValidToken(token) { if (isIncludeNavi(token)) { var separatorIndex = utils.indexOf(token, NAVI_SEPARATOR_IN_TOKEN); token = token.substring(0, separatorIndex + 1); } return token; }; var getConnectType = function getConnectType(option) { var connectType = option.connectType; var isSpecifiedSocket = connectType === CONNECT_TYPE.WEBSOCKET; var isSocket = isSpecifiedSocket && utils.isSupportSocket(); return isSocket ? CONNECT_TYPE.WEBSOCKET : CONNECT_TYPE.COMET; }; var isConnected = function isConnected(status) { return utils.isEqual(status, CONNECTION_STATUS.CONNECTED); }; var isConnecting = function isConnecting(status) { return utils.isEqual(status, CONNECTION_STATUS.CONNECTING); }; var isDisconnected = function isDisconnected(status) { return !isConnected(status) && !isConnecting(status); }; var getNavReqOption = function getNavReqOption(option, user) { option = utils.copy(option); option.token = user.token; return option; }; var getPingTimeout = function getPingTimeout(timeSpentConnect) { var timeout = timeSpentConnect * 3; if (timeout < IM_PING_MIN_TIMEOUT) { return IM_PING_MIN_TIMEOUT; } if (timeout > IM_PING_MAX_TIMEOUT) { return IM_PING_MAX_TIMEOUT; } return timeout; }; var fixConversationData = function fixConversationData(conversation) { conversation = conversation || {}; conversation.latestMessage = conversation.latestMessage || {}; conversation.latestMessage.sentTime = conversation.latestMessage.sentTime || 0; return conversation; }; var sortConversationList = function sortConversationList(conversationList) { return utils.quickSort(conversationList, function (before, after) { before = fixConversationData(before); after = fixConversationData(after); return after.latestMessage.sentTime <= before.latestMessage.sentTime; }); }; var common = { isConnected: isConnected, isConnecting: isConnecting, isDisconnected: isDisconnected, getConnectType: getConnectType, getTransporterUrl: getTransporterUrl, isGroup: isGroup, isChatRoom: isChatRoom, getConversationTypeList: getConversationTypeList, isValidConversationType: isValidConversationType, getUIDByToken: getUIDByToken, getSessionId: getSessionId, getMessageOptionByStatus: getMessageOptionByStatus, getPersitedAndCountedBySessionId: getPersitedAndCountedBySessionId, SignalId: SignalId, MessageTimeSyner: MessageTimeSyner, ChatRoomMessageTimeSyner: ChatRoomMessageTimeSyner, getCMPDomainList: getCMPDomainList, getNaviListByToken: getNaviListByToken, getValidToken: getValidToken, RCSocket: RCSocket, RCStorage: RCStorage, getNavReqOption: getNavReqOption, getPingTimeout: getPingTimeout, fixConversationData: fixConversationData, sortConversationList: sortConversationList }; var EventEmitter$1 = utils.EventEmitter, DeferHandler$1 = utils.DeferHandler, Timer$1 = utils.Timer; var RCSocket$1 = common.RCSocket; var TransHandlerID = { CONNECT: 'connect', PING: 'ping' }; var Heartbeat = function () { function Heartbeat(transporter, option) { this._transporter = void 0; this._timer = void 0; option = option || {}; var timeout = option.timeout; this._transporter = transporter; this._timer = new Timer$1({ type: TIMER_TYPE.INTERVAL, timeout: timeout }); } var _proto = Heartbeat.prototype; _proto.check = function check(timeout) { var _transporter = this._transporter; var _deferHandler = _transporter._deferHandler; var pingReqSignal = new PingReqWriter(); _transporter.sendSignal(pingReqSignal); return utils.deferred(function (resolve, reject) { _deferHandler.add(TransHandlerID.PING, { resolve: resolve, reject: reject }, { timeout: timeout }); }); }; _proto.start = function start(timeout, onError) { var self = this; self._timer.start(function () { self.check(timeout).then(utils.noop)["catch"](onError); }); }; _proto.stop = function stop() { this._timer && this._timer.stop(); }; return Heartbeat; }(); var SocketTransporter = function () { function SocketTransporter(option) { this._socket = void 0; this._option = void 0; this._transporterEventEmiiter = new EventEmitter$1(); this._deferHandler = new DeferHandler$1(); this._heartbeat = new Heartbeat(this, { timeout: IM_PING_INTERVAL_TIME }); this._connectedTime = void 0; this._option = option; } var _proto2 = SocketTransporter.prototype; _proto2._createSocket = function _createSocket(url) { var self = this; var _transporterEventEmiiter = self._transporterEventEmiiter; var socket = new RCSocket$1({ url: url }); var onClose = function onClose(event) { event = event || {}; var code = event.code || TRANSPORTER_STATUS.CLOSE_ABNORMAL; _transporterEventEmiiter.emit(TRANSPORT_EVENT.STATUS, code); self.disconnect(); }; socket.onMessage(function (msg) { var data = msg.data; if (!utils.isArrayBuffer(data)) { throw new Error('Error socket signal'); } var signal = readWSBuffer(data); self.handleSignal(signal); }); socket.onError(onClose); socket.onClose(onClose); return socket; }; _proto2._startHeartbeat = function _startHeartbeat(timeSpentConnect) { var self = this; var _heartbeat = self._heartbeat, _transporterEventEmiiter = self._transporterEventEmiiter; _heartbeat.check(FIRST_PING_TIMEOUT).then(utils.noop)["catch"](function () { _transporterEventEmiiter.emit(TRANSPORT_EVENT.STATUS, TRANSPORTER_STATUS.PING_FIRST_TIMEOUT); self.disconnect(); }); var pingTimeout = common.getPingTimeout(timeSpentConnect); _heartbeat.start(pingTimeout, function () { _transporterEventEmiiter.emit(TRANSPORT_EVENT.STATUS, TRANSPORTER_STATUS.PING_TIMEOUT); self.disconnect(); }); }; _proto2._stopHeartbeat = function _stopHeartbeat() { this._heartbeat.stop(); }; _proto2.watchSignal = function watchSignal(watcher) { this._transporterEventEmiiter.on(TRANSPORT_EVENT.SIGNAL, watcher); }; _proto2.watchStatus = function watchStatus(watcher) { this._transporterEventEmiiter.on(TRANSPORT_EVENT.STATUS, watcher); }; _proto2.connect = function connect(user, option) { var self = this; var _self$_option = self._option, appkey = _self$_option.appkey, connectType = _self$_option.connectType, _deferHandler = self._deferHandler; var token = user.token; var domain = option.domain; var url = common.getTransporterUrl({ domain: domain, appkey: appkey, connectType: connectType, token: token }); var timeBeforeConnect = utils.getCurrentTimestamp(); self._socket = this._createSocket(url); return utils.deferred(function (resolve, reject) { _deferHandler.add(TransHandlerID.CONNECT, { resolve: resolve, reject: reject }); }).then(function (result) { var timeAfterConnect = utils.getCurrentTimestamp(); var timeSpentConnect = timeAfterConnect - timeBeforeConnect; self._startHeartbeat(timeSpentConnect); return result; }); }; _proto2.sendSignal = function sendSignal(writer) { var binary = writer.getBufferData(); this._socket.send(binary.buffer); }; _proto2.handleSignal = function handleSignal(signal) { var _transporterEventEmiiter = this._transporterEventEmiiter, _deferHandler = this._deferHandler; if (signal instanceof ConnAckReader) { this.handleConnAck(signal); } else if (signal instanceof PingRespReader) { _deferHandler.resolve(TransHandlerID.PING); } else { _transporterEventEmiiter.emit(TRANSPORT_EVENT.SIGNAL, signal); } }; _proto2.handleConnAck = function handleConnAck(signal) { var self = this; var _deferHandler = self._deferHandler, _transporterEventEmiiter = self._transporterEventEmiiter; var status = signal.status; var isConnected = status === SUCCESS_CODE; var event = isConnected ? _deferHandler.resolve : _deferHandler.reject; event.call(_deferHandler, TransHandlerID.CONNECT, signal); if (isConnected) { self._connectedTime = utils.getCurrentTimestamp(); } isConnected && _transporterEventEmiiter.emit(TRANSPORT_EVENT.STATUS, TRANSPORTER_STATUS.CONNECTED); }; _proto2.disconnect = function disconnect() { this._stopHeartbeat(); this._socket.close(); }; return SocketTransporter; }(); var EventEmitter$2 = utils.EventEmitter, DeferHandler$2 = utils.DeferHandler, httpRequest = utils.httpRequest, request$4 = utils.request, Defer$1 = utils.Defer; var CometTransporter = function () { function CometTransporter(option) { this._option = void 0; this._transporterEventEmiiter = new EventEmitter$2(); this._deferHandler = new DeferHandler$2(); this._pid = utils.getCurrentTimestamp() + Math.random() + ''; this._domain = void 0; this._sessionid = void 0; this._xhrCache = new utils.Cache(); this._isDisconnected = true; this._option = option; } var _proto = CometTransporter.prototype; _proto._startPullSignal = function _startPullSignal() { var self = this; var _domain = self._domain, _sessionid = self._sessionid, _pid = self._pid, _transporterEventEmiiter = self._transporterEventEmiiter; var timestamp = utils.getCurrentTimestamp(); var protocol = env.protocol.http; var url = utils.tplEngine(COMET_PULL_URL_TPL, { protocol: protocol, timestamp: timestamp, domain: _domain, sessionId: _sessionid, pid: _pid }); var xhr = httpRequest({ url: url, success: function success(responseText) { self.handleCometResponse(responseText); !self._isDisconnected && self._startPullSignal(); self._xhrCache.remove(url); }, fail: function fail() { if (!self._isDisconnected) { _transporterEventEmiiter.emit(TRANSPORT_EVENT.STATUS, CONNECTION_STATUS.NETWORK_UNAVAILABLE); } self._xhrCache.remove(url); } }); self._xhrCache.set(url, xhr); }; _proto.watchSignal = function watchSignal(event) { this._transporterEventEmiiter.on(TRANSPORT_EVENT.SIGNAL, event); }; _proto.watchStatus = function watchStatus(event) { this._transporterEventEmiiter.on(TRANSPORT_EVENT.STATUS, function (status) { event && event(status); }); }; _proto.connect = function connect(user, option) { var self = this; var _transporterEventEmiiter = self._transporterEventEmiiter, _self$_option = self._option, appkey = _self$_option.appkey, connectType = _self$_option.connectType; var token = user.token; var domain = option.domain; var url = common.getTransporterUrl({ domain: domain, appkey: appkey, token: token, connectType: connectType }); self._domain = domain; self._isDisconnected = false; var success = function success(_ref) { var responseText = _ref.responseText; if (!utils.isValidJSON(responseText)) { return Defer$1.reject(); } var response = utils.parseJSON(responseText); var isConnectSuccess = utils.isEqual(response.status, SUCCESS_CODE); return isConnectSuccess ? Defer$1.resolve(response) : Defer$1.reject(response); }; return request$4(url).then(success).then(function (response) { _transporterEventEmiiter.emit(TRANSPORT_EVENT.STATUS, CONNECTION_STATUS.CONNECTED); self._sessionid = response.sessionid; self._startPullSignal(); return response; }); }; _proto.sendSignal = function sendSignal(writer) { var self = this; var _domain = self._domain, _sessionid = self._sessionid, _pid = self._pid; var messageId = writer.messageId, topic = writer.topic, targetId = writer.targetId; var headerCode = writer.getHeaderFlag(); var protocol = env.protocol.http; var TPL = topic ? COMET_REQ_HAS_TOPIC_URL_TPL : COMET_REQ_NO_TOPIC_URL_TPL; var url = utils.tplEngine(TPL, { protocol: protocol, messageId: messageId, headerCode: headerCode, topic: topic, targetId: targetId, pid: _pid, sessionId: _sessionid, domain: _domain }); var currentTime = utils.getCurrentTimestamp() + ''; var xhr = httpRequest({ url: url, method: REQUEST_METHOD.POST, body: writer.getCometData(), success: function success(responseText) { var isSuccess = self.handleCometResponse(responseText); if (!isSuccess) { self.handleError(messageId); } self._xhrCache.remove(currentTime); }, fail: function fail(error) { console.log('comet error', error); self.handleError(messageId); self._xhrCache.remove(currentTime); } }); self._xhrCache.set(currentTime, xhr); }; _proto.handleCometResponse = function handleCometResponse(responseText) { var self = this; var _transporterEventEmiiter = self._transporterEventEmiiter; var response = utils.parseJSON(responseText); if (!response) { return false; } if (!response || !utils.isArray(response)) { return true; } utils.forEach(response, function (data) { var sessionid = data.sessionid; if (sessionid) { self._sessionid = sessionid; } var signal = readCometData(data); _transporterEventEmiiter.emit(TRANSPORT_EVENT.SIGNAL, signal); }); return true; }; _proto.handleError = function handleError(messageId, status) { var signal = { messageId: messageId, status: status || ERROR_CODE.TIMEOUT }; this._transporterEventEmiiter.emit(TRANSPORT_EVENT.SIGNAL, signal); }; _proto.disconnect = function disconnect() { var self = this; self._isDisconnected = true; var _xhrCache = self._xhrCache; var xhrKeys = _xhrCache.getKeys(); utils.forEach(xhrKeys, function (key) { var xhr = _xhrCache.get(key); xhr.abort(); _xhrCache.remove(key); }); }; return CometTransporter; }(); var Transporter = (function (option) { var connectType = option.connectType; var isSocket = connectType === CONNECT_TYPE.WEBSOCKET; var Transporter = isSocket ? SocketTransporter : CometTransporter; return new Transporter(option); }); var PBName = { UpStreamMessage: 'UpStreamMessage', DownStreamMessage: 'DownStreamMessage', DownStreamMessages: 'DownStreamMessages', SessionsAttQryInput: 'SessionsAttQryInput', SessionsAttOutput: 'SessionsAttOutput', SyncRequestMsg: 'SyncRequestMsg', ChrmPullMsg: 'ChrmPullMsg', NotifyMsg: 'NotifyMsg', HistoryMsgInput: 'HistoryMsgInput', HistoryMsgOuput: 'HistoryMsgOuput', RelationQryInput: 'RelationQryInput', RelationsOutput: 'RelationsOutput', DeleteSessionsInput: 'DeleteSessionsInput', SessionInfo: 'SessionInfo', DeleteSessionsOutput: 'DeleteSessionsOutput', RelationsInput: 'RelationsInput', DeleteMsgInput: 'DeleteMsgInput', CleanHisMsgInput: 'CleanHisMsgInput', SessionMsgReadInput: 'SessionMsgReadInput', ChrmInput: 'ChrmInput', QueryChatRoomInfoInput: 'QueryChatRoomInfoInput', QueryChatRoomInfoOutput: 'QueryChatRoomInfoOutput' }; var _SSMsg; var SSMsg = (_SSMsg = {}, _SSMsg[PBName.UpStreamMessage] = ['sessionId', 'classname', 'content', 'pushText', 'userId', 'configFlag', 'appData'], _SSMsg[PBName.DownStreamMessages] = ['fromUserId', 'type', 'groupId', 'classname', 'content', 'dataTime', 'status', 'msgId'], _SSMsg[PBName.SessionsAttQryInput] = ['nothing'], _SSMsg[PBName.SessionsAttOutput] = ['inboxTime', 'sendboxTime', 'totalUnreadCount'], _SSMsg[PBName.SyncRequestMsg] = ['syncTime', 'ispolling', 'isweb', 'isPullSend', 'isKeeping', 'sendBoxSyncTime'], _SSMsg[PBName.ChrmPullMsg] = ['syncTime', 'count'], _SSMsg[PBName.NotifyMsg] = ['type', 'time', 'chrmId'], _SSMsg[PBName.HistoryMsgInput] = ['targetId', 'time', 'count', 'order'], _SSMsg[PBName.HistoryMsgOuput] = ['list', 'syncTime', 'hasMsg'], _SSMsg[PBName.RelationQryInput] = ['type', 'count', 'startTime', 'order'], _SSMsg[PBName.RelationsOutput] = ['info'], _SSMsg[PBName.DeleteSessionsInput] = ['sessions'], _SSMsg[PBName.SessionInfo] = ['type', 'channelId'], _SSMsg[PBName.DeleteSessionsOutput] = ['nothing'], _SSMsg[PBName.RelationsInput] = ['type', 'msg', 'count', 'offset', 'startTime', 'endTime'], _SSMsg[PBName.DeleteMsgInput] = ['type', 'conversationId', 'msgs'], _SSMsg[PBName.CleanHisMsgInput] = ['targetId', 'dataTime', 'conversationType'], _SSMsg[PBName.SessionMsgReadInput] = ['type', 'msgTime', 'channelId'], _SSMsg[PBName.ChrmInput] = ['nothing'], _SSMsg[PBName.QueryChatRoomInfoInput] = ['count', 'order'], _SSMsg[PBName.QueryChatRoomInfoOutput] = ['userTotalNums', 'userInfos'], _SSMsg); var Codec = {}; utils.forEach(SSMsg, function (paramList, name) { Codec[name] = function () {}; Codec[name].prototype.data = {}; Codec[name].prototype.getData = function () { return this.data; }; utils.forEach(paramList, function (param) { var setEventName = 'set' + utils.toUpperCase(param, 0, 1); Codec[name].prototype[setEventName] = function (item) { this.data[param] = item; }; }); Codec[name].decode = function (data) { var decodeResult = {}; if (utils.isString(data)) { data = utils.parseJSON(data); } var _loop = function _loop(key) { var getEventName = 'get' + utils.toUpperCase(key, 0, 1); decodeResult[key] = data[key]; decodeResult[getEventName] = function () { return data[key]; }; }; for (var key in data) { _loop(key); } return decodeResult; }; }); Codec.getModule = function (pbName) { var modules = new Codec[pbName](); modules.getArrayData = function () { return modules.getData(); }; return modules; }; function protobuf(a){var b=void 0,c=function(){function a(a,b,c){this.low=0|a,this.high=0|b,this.unsigned=!!c;}function b(a){return (a&&a.__isLong__)===!0}function e(a,b){var e,f,h;return b?(a>>>=0,(h=a>=0&&256>a)&&(f=d[a])?f:(e=g(a,0>(0|a)?-1:0,!0),h&&(d[a]=e),e)):(a|=0,(h=a>=-128&&128>a)&&(f=c[a])?f:(e=g(a,0>a?-1:0,!1),h&&(c[a]=e),e))}function f(a,b){if(isNaN(a)||!isFinite(a))return b?r:q;if(b){if(0>a)return r;if(a>=n)return w}else{if(-o>=a)return x;if(a+1>=o)return v}return 0>a?f(-a,b).neg():g(0|a%m,0|a/m,b)}function g(b,c,d){return new a(b,c,d)}function i(a,b,c){var d,e,g,j,k,l,m;if(0===a.length)throw Error("empty string");if("NaN"===a||"Infinity"===a||"+Infinity"===a||"-Infinity"===a)return q;if("number"==typeof b?(c=b,b=!1):b=!!b,c=c||10,2>c||c>36)throw RangeError("radix");if((d=a.indexOf("-"))>0)throw Error("interior hyphen");if(0===d)return i(a.substring(1),b,c).neg();for(e=f(h(c,8)),g=q,j=0;jk?(m=f(h(c,k)),g=g.mul(m).add(f(l))):(g=g.mul(e),g=g.add(f(l)));return g.unsigned=b,g}function j(b){return b instanceof a?b:"number"==typeof b?f(b):"string"==typeof b?i(b):g(b.low,b.high,b.unsigned)}var c,d,h,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y;return Object.defineProperty(a.prototype,"__isLong__",{value:!0,enumerable:!1,configurable:!1}),a.isLong=b,c={},d={},a.fromInt=e,a.fromNumber=f,a.fromBits=g,h=Math.pow,a.fromString=i,a.fromValue=j,k=65536,l=1<<24,m=k*k,n=m*m,o=n/2,p=e(l),q=e(0),a.ZERO=q,r=e(0,!0),a.UZERO=r,s=e(1),a.ONE=s,t=e(1,!0),a.UONE=t,u=e(-1),a.NEG_ONE=u,v=g(-1,2147483647,!1),a.MAX_VALUE=v,w=g(-1,-1,!0),a.MAX_UNSIGNED_VALUE=w,x=g(0,-2147483648,!1),a.MIN_VALUE=x,y=a.prototype,y.toInt=function(){return this.unsigned?this.low>>>0:this.low},y.toNumber=function(){return this.unsigned?(this.high>>>0)*m+(this.low>>>0):this.high*m+(this.low>>>0)},y.toString=function(a){var b,c,d,e,g,i,j,k,l;if(a=a||10,2>a||a>36)throw RangeError("radix");if(this.isZero())return "0";if(this.isNegative())return this.eq(x)?(b=f(a),c=this.div(b),d=c.mul(b).sub(this),c.toString(a)+d.toInt().toString(a)):"-"+this.neg().toString(a);for(e=f(h(a,6),this.unsigned),g=this,i="";;){if(j=g.div(e),k=g.sub(j.mul(e)).toInt()>>>0,l=k.toString(a),g=j,g.isZero())return l+i;for(;l.length<6;)l="0"+l;i=""+l+i;}},y.getHighBits=function(){return this.high},y.getHighBitsUnsigned=function(){return this.high>>>0},y.getLowBits=function(){return this.low},y.getLowBitsUnsigned=function(){return this.low>>>0},y.getNumBitsAbs=function(){var a,b;if(this.isNegative())return this.eq(x)?64:this.neg().getNumBitsAbs();for(a=0!=this.high?this.high:this.low,b=31;b>0&&0==(a&1<=0},y.isOdd=function(){return 1===(1&this.low)},y.isEven=function(){return 0===(1&this.low)},y.equals=function(a){return b(a)||(a=j(a)),this.unsigned!==a.unsigned&&1===this.high>>>31&&1===a.high>>>31?!1:this.high===a.high&&this.low===a.low},y.eq=y.equals,y.notEquals=function(a){return !this.eq(a)},y.neq=y.notEquals,y.lessThan=function(a){return this.comp(a)<0},y.lt=y.lessThan,y.lessThanOrEqual=function(a){return this.comp(a)<=0},y.lte=y.lessThanOrEqual,y.greaterThan=function(a){return this.comp(a)>0},y.gt=y.greaterThan,y.greaterThanOrEqual=function(a){return this.comp(a)>=0},y.gte=y.greaterThanOrEqual,y.compare=function(a){if(b(a)||(a=j(a)),this.eq(a))return 0;var c=this.isNegative(),d=a.isNegative();return c&&!d?-1:!c&&d?1:this.unsigned?a.high>>>0>this.high>>>0||a.high===this.high&&a.low>>>0>this.low>>>0?-1:1:this.sub(a).isNegative()?-1:1},y.comp=y.compare,y.negate=function(){return !this.unsigned&&this.eq(x)?x:this.not().add(s)},y.neg=y.negate,y.add=function(a){var c,d,e,f,h,i,k,l,m,n,o,p;return b(a)||(a=j(a)),c=this.high>>>16,d=65535&this.high,e=this.low>>>16,f=65535&this.low,h=a.high>>>16,i=65535&a.high,k=a.low>>>16,l=65535&a.low,m=0,n=0,o=0,p=0,p+=f+l,o+=p>>>16,p&=65535,o+=e+k,n+=o>>>16,o&=65535,n+=d+i,m+=n>>>16,n&=65535,m+=c+h,m&=65535,g(o<<16|p,m<<16|n,this.unsigned)},y.subtract=function(a){return b(a)||(a=j(a)),this.add(a.neg())},y.sub=y.subtract,y.multiply=function(a){var c,d,e,h,i,k,l,m,n,o,r,s;return this.isZero()?q:(b(a)||(a=j(a)),a.isZero()?q:this.eq(x)?a.isOdd()?x:q:a.eq(x)?this.isOdd()?x:q:this.isNegative()?a.isNegative()?this.neg().mul(a.neg()):this.neg().mul(a).neg():a.isNegative()?this.mul(a.neg()).neg():this.lt(p)&&a.lt(p)?f(this.toNumber()*a.toNumber(),this.unsigned):(c=this.high>>>16,d=65535&this.high,e=this.low>>>16,h=65535&this.low,i=a.high>>>16,k=65535&a.high,l=a.low>>>16,m=65535&a.low,n=0,o=0,r=0,s=0,s+=h*m,r+=s>>>16,s&=65535,r+=e*m,o+=r>>>16,r&=65535,r+=h*l,o+=r>>>16,r&=65535,o+=d*m,n+=o>>>16,o&=65535,o+=e*l,n+=o>>>16,o&=65535,o+=h*k,n+=o>>>16,o&=65535,n+=c*m+d*l+e*k+h*i,n&=65535,g(r<<16|s,n<<16|o,this.unsigned)))},y.mul=y.multiply,y.divide=function(a){var c,d,e,g,i,k,l,m;if(b(a)||(a=j(a)),a.isZero())throw Error("division by zero");if(this.isZero())return this.unsigned?r:q;if(this.unsigned){if(a.unsigned||(a=a.toUnsigned()),a.gt(this))return r;if(a.gt(this.shru(1)))return t;e=r;}else{if(this.eq(x))return a.eq(s)||a.eq(u)?x:a.eq(x)?s:(g=this.shr(1),c=g.div(a).shl(1),c.eq(q)?a.isNegative()?s:u:(d=this.sub(a.mul(c)),e=c.add(d.div(a))));if(a.eq(x))return this.unsigned?r:q;if(this.isNegative())return a.isNegative()?this.neg().div(a.neg()):this.neg().div(a).neg();if(a.isNegative())return this.div(a.neg()).neg();e=q;}for(d=this;d.gte(a);){for(c=Math.max(1,Math.floor(d.toNumber()/a.toNumber())),i=Math.ceil(Math.log(c)/Math.LN2),k=48>=i?1:h(2,i-48),l=f(c),m=l.mul(a);m.isNegative()||m.gt(d);)c-=k,l=f(c,this.unsigned),m=l.mul(a);l.isZero()&&(l=s),e=e.add(l),d=d.sub(m);}return e},y.div=y.divide,y.modulo=function(a){return b(a)||(a=j(a)),this.sub(this.div(a).mul(a))},y.mod=y.modulo,y.not=function(){return g(~this.low,~this.high,this.unsigned)},y.and=function(a){return b(a)||(a=j(a)),g(this.low&a.low,this.high&a.high,this.unsigned)},y.or=function(a){return b(a)||(a=j(a)),g(this.low|a.low,this.high|a.high,this.unsigned)},y.xor=function(a){return b(a)||(a=j(a)),g(this.low^a.low,this.high^a.high,this.unsigned)},y.shiftLeft=function(a){return b(a)&&(a=a.toInt()),0===(a&=63)?this:32>a?g(this.low<>>32-a,this.unsigned):g(0,this.low<a?g(this.low>>>a|this.high<<32-a,this.high>>a,this.unsigned):g(this.high>>a-32,this.high>=0?0:-1,this.unsigned)},y.shr=y.shiftRight,y.shiftRightUnsigned=function(a){var c,d;return b(a)&&(a=a.toInt()),a&=63,0===a?this:(c=this.high,32>a?(d=this.low,g(d>>>a|c<<32-a,c>>>a,this.unsigned)):32===a?g(c,0,this.unsigned):g(c>>>a-32,0,this.unsigned))},y.shru=y.shiftRightUnsigned,y.toSigned=function(){return this.unsigned?g(this.low,this.high,!1):this},y.toUnsigned=function(){return this.unsigned?this:g(this.low,this.high,!0)},y.toBytes=function(a){return a?this.toBytesLE():this.toBytesBE()},y.toBytesLE=function(){var a=this.high,b=this.low;return [255&b,255&b>>>8,255&b>>>16,255&b>>>24,255&a,255&a>>>8,255&a>>>16,255&a>>>24]},y.toBytesBE=function(){var a=this.high,b=this.low;return [255&a>>>24,255&a>>>16,255&a>>>8,255&a,255&b>>>24,255&b>>>16,255&b>>>8,255&b]},a}(),d=function(a){function f(a){var b=0;return function(){return b1024&&(b.push(e.apply(String,a)),a.length=0),Array.prototype.push.apply(a,arguments),void 0)}}function h(a,b,c,d,e){var f,g,h=8*e-d-1,i=(1<>1,k=-7,l=c?e-1:0,m=c?-1:1,n=a[b+l];for(l+=m,f=n&(1<<-k)-1,n>>=-k,k+=h;k>0;f=256*f+a[b+l],l+=m,k-=8);for(g=f&(1<<-k)-1,f>>=-k,k+=d;k>0;g=256*g+a[b+l],l+=m,k-=8);if(0===f)f=1-j;else{if(f===i)return g?0/0:1/0*(n?-1:1);g+=Math.pow(2,d),f-=j;}return (n?-1:1)*g*Math.pow(2,f-d)}function i(a,b,c,d,e,f){var g,h,i,j=8*f-e-1,k=(1<>1,m=23===e?Math.pow(2,-24)-Math.pow(2,-77):0,n=d?0:f-1,o=d?1:-1,p=0>b||0===b&&0>1/b?1:0;for(b=Math.abs(b),isNaN(b)||1/0===b?(h=isNaN(b)?1:0,g=k):(g=Math.floor(Math.log(b)/Math.LN2),b*(i=Math.pow(2,-g))<1&&(g--,i*=2),b+=g+l>=1?m/i:m*Math.pow(2,1-l),b*i>=2&&(g++,i/=2),g+l>=k?(h=0,g=k):g+l>=1?(h=(b*i-1)*Math.pow(2,e),g+=l):(h=b*Math.pow(2,l-1)*Math.pow(2,e),g=0));e>=8;a[c+n]=255&h,n+=o,h/=256,e-=8);for(g=g<0;a[c+n]=255&g,n+=o,g/=256,j-=8);a[c+n-o]|=128*p;}var c,d,e,j,k,b=function(a,c,e){if("undefined"==typeof a&&(a=b.DEFAULT_CAPACITY),"undefined"==typeof c&&(c=b.DEFAULT_ENDIAN),"undefined"==typeof e&&(e=b.DEFAULT_NOASSERT),!e){if(a=0|a,0>a)throw RangeError("Illegal capacity");c=!!c,e=!!e;}this.buffer=0===a?d:new ArrayBuffer(a),this.view=0===a?null:new Uint8Array(this.buffer),this.offset=0,this.markedOffset=-1,this.limit=a,this.littleEndian=c,this.noAssert=e;};return b.VERSION="5.0.1",b.LITTLE_ENDIAN=!0,b.BIG_ENDIAN=!1,b.DEFAULT_CAPACITY=16,b.DEFAULT_ENDIAN=b.BIG_ENDIAN,b.DEFAULT_NOASSERT=!1,b.Long=a||null,c=b.prototype,c.__isByteBuffer__,Object.defineProperty(c,"__isByteBuffer__",{value:!0,enumerable:!1,configurable:!1}),d=new ArrayBuffer(0),e=String.fromCharCode,b.accessor=function(){return Uint8Array},b.allocate=function(a,c,d){return new b(a,c,d)},b.concat=function(a,c,d,e){var f,i,g,h,k,j;for(("boolean"==typeof c||"string"!=typeof c)&&(e=d,d=c,c=void 0),f=0,g=0,h=a.length;h>g;++g)b.isByteBuffer(a[g])||(a[g]=b.wrap(a[g],c)),i=a[g].limit-a[g].offset,i>0&&(f+=i);if(0===f)return new b(0,d,e);for(j=new b(f,d,e),g=0;h>g;)k=a[g++],i=k.limit-k.offset,0>=i||(j.view.set(k.view.subarray(k.offset,k.limit),j.offset),j.offset+=i);return j.limit=j.offset,j.offset=0,j},b.isByteBuffer=function(a){return (a&&a.__isByteBuffer__)===!0},b.type=function(){return ArrayBuffer},b.wrap=function(a,d,e,f){var g,h;if("string"!=typeof d&&(f=e,e=d,d=void 0),"string"==typeof a)switch("undefined"==typeof d&&(d="utf8"),d){case"base64":return b.fromBase64(a,e);case"hex":return b.fromHex(a,e);case"binary":return b.fromBinary(a,e);case"utf8":return b.fromUTF8(a,e);case"debug":return b.fromDebug(a,e);default:throw Error("Unsupported encoding: "+d)}if(null===a||"object"!=typeof a)throw TypeError("Illegal buffer");if(b.isByteBuffer(a))return g=c.clone.call(a),g.markedOffset=-1,g;if(a instanceof Uint8Array)g=new b(0,e,f),a.length>0&&(g.buffer=a.buffer,g.offset=a.byteOffset,g.limit=a.byteOffset+a.byteLength,g.view=new Uint8Array(a.buffer));else if(a instanceof ArrayBuffer)g=new b(0,e,f),a.byteLength>0&&(g.buffer=a,g.offset=0,g.limit=a.byteLength,g.view=a.byteLength>0?new Uint8Array(a):null);else{if("[object Array]"!==Object.prototype.toString.call(a))throw TypeError("Illegal buffer");for(g=new b(a.length,e,f),g.limit=a.length,h=0;h>>=0,0>b||b+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+b+" (+"+0+") <= "+this.buffer.byteLength)}for(d=b,e=a.length,f=e>>3,g=0,b+=this.writeVarint32(e,b);f--;)h=1&!!a[g++]|(1&!!a[g++])<<1|(1&!!a[g++])<<2|(1&!!a[g++])<<3|(1&!!a[g++])<<4|(1&!!a[g++])<<5|(1&!!a[g++])<<6|(1&!!a[g++])<<7,this.writeByte(h,b++);if(e>g){for(i=0,h=0;e>g;)h|=(1&!!a[g++])<>3,f=0,g=[],a+=c.length;e--;)h=this.readByte(a++),g[f++]=!!(1&h),g[f++]=!!(2&h),g[f++]=!!(4&h),g[f++]=!!(8&h),g[f++]=!!(16&h),g[f++]=!!(32&h),g[f++]=!!(64&h),g[f++]=!!(128&h);if(d>f)for(i=0,h=this.readByte(a++);d>f;)g[f++]=!!(1&h>>i++);return b&&(this.offset=a),g},c.readBytes=function(a,b){var d,c="undefined"==typeof b;if(c&&(b=this.offset),!this.noAssert){if("number"!=typeof b||0!==b%1)throw TypeError("Illegal offset: "+b+" (not an integer)");if(b>>>=0,0>b||b+a>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+b+" (+"+a+") <= "+this.buffer.byteLength)}return d=this.slice(b,b+a),c&&(this.offset+=a),d},c.writeBytes=c.append,c.writeInt8=function(a,b){var d,c="undefined"==typeof b;if(c&&(b=this.offset),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal value: "+a+" (not an integer)");if(a|=0,"number"!=typeof b||0!==b%1)throw TypeError("Illegal offset: "+b+" (not an integer)");if(b>>>=0,0>b||b+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+b+" (+"+0+") <= "+this.buffer.byteLength)}return b+=1,d=this.buffer.byteLength,b>d&&this.resize((d*=2)>b?d:b),b-=1,this.view[b]=a,c&&(this.offset+=1),this},c.writeByte=c.writeInt8,c.readInt8=function(a){var c,b="undefined"==typeof a;if(b&&(a=this.offset),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal offset: "+a+" (not an integer)");if(a>>>=0,0>a||a+1>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+a+" (+"+1+") <= "+this.buffer.byteLength)}return c=this.view[a],128===(128&c)&&(c=-(255-c+1)),b&&(this.offset+=1),c},c.readByte=c.readInt8,c.writeUint8=function(a,b){var d,c="undefined"==typeof b;if(c&&(b=this.offset),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal value: "+a+" (not an integer)");if(a>>>=0,"number"!=typeof b||0!==b%1)throw TypeError("Illegal offset: "+b+" (not an integer)");if(b>>>=0,0>b||b+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+b+" (+"+0+") <= "+this.buffer.byteLength)}return b+=1,d=this.buffer.byteLength,b>d&&this.resize((d*=2)>b?d:b),b-=1,this.view[b]=a,c&&(this.offset+=1),this},c.writeUInt8=c.writeUint8,c.readUint8=function(a){var c,b="undefined"==typeof a;if(b&&(a=this.offset),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal offset: "+a+" (not an integer)");if(a>>>=0,0>a||a+1>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+a+" (+"+1+") <= "+this.buffer.byteLength)}return c=this.view[a],b&&(this.offset+=1),c},c.readUInt8=c.readUint8,c.writeInt16=function(a,b){var d,c="undefined"==typeof b;if(c&&(b=this.offset),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal value: "+a+" (not an integer)");if(a|=0,"number"!=typeof b||0!==b%1)throw TypeError("Illegal offset: "+b+" (not an integer)");if(b>>>=0,0>b||b+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+b+" (+"+0+") <= "+this.buffer.byteLength)}return b+=2,d=this.buffer.byteLength,b>d&&this.resize((d*=2)>b?d:b),b-=2,this.littleEndian?(this.view[b+1]=(65280&a)>>>8,this.view[b]=255&a):(this.view[b]=(65280&a)>>>8,this.view[b+1]=255&a),c&&(this.offset+=2),this},c.writeShort=c.writeInt16,c.readInt16=function(a){var c,b="undefined"==typeof a;if(b&&(a=this.offset),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal offset: "+a+" (not an integer)");if(a>>>=0,0>a||a+2>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+a+" (+"+2+") <= "+this.buffer.byteLength)}return c=0,this.littleEndian?(c=this.view[a],c|=this.view[a+1]<<8):(c=this.view[a]<<8,c|=this.view[a+1]),32768===(32768&c)&&(c=-(65535-c+1)),b&&(this.offset+=2),c},c.readShort=c.readInt16,c.writeUint16=function(a,b){var d,c="undefined"==typeof b;if(c&&(b=this.offset),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal value: "+a+" (not an integer)");if(a>>>=0,"number"!=typeof b||0!==b%1)throw TypeError("Illegal offset: "+b+" (not an integer)");if(b>>>=0,0>b||b+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+b+" (+"+0+") <= "+this.buffer.byteLength)}return b+=2,d=this.buffer.byteLength,b>d&&this.resize((d*=2)>b?d:b),b-=2,this.littleEndian?(this.view[b+1]=(65280&a)>>>8,this.view[b]=255&a):(this.view[b]=(65280&a)>>>8,this.view[b+1]=255&a),c&&(this.offset+=2),this},c.writeUInt16=c.writeUint16,c.readUint16=function(a){var c,b="undefined"==typeof a;if(b&&(a=this.offset),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal offset: "+a+" (not an integer)");if(a>>>=0,0>a||a+2>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+a+" (+"+2+") <= "+this.buffer.byteLength)}return c=0,this.littleEndian?(c=this.view[a],c|=this.view[a+1]<<8):(c=this.view[a]<<8,c|=this.view[a+1]),b&&(this.offset+=2),c},c.readUInt16=c.readUint16,c.writeInt32=function(a,b){var d,c="undefined"==typeof b;if(c&&(b=this.offset),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal value: "+a+" (not an integer)");if(a|=0,"number"!=typeof b||0!==b%1)throw TypeError("Illegal offset: "+b+" (not an integer)");if(b>>>=0,0>b||b+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+b+" (+"+0+") <= "+this.buffer.byteLength)}return b+=4,d=this.buffer.byteLength,b>d&&this.resize((d*=2)>b?d:b),b-=4,this.littleEndian?(this.view[b+3]=255&a>>>24,this.view[b+2]=255&a>>>16,this.view[b+1]=255&a>>>8,this.view[b]=255&a):(this.view[b]=255&a>>>24,this.view[b+1]=255&a>>>16,this.view[b+2]=255&a>>>8,this.view[b+3]=255&a),c&&(this.offset+=4),this},c.writeInt=c.writeInt32,c.readInt32=function(a){var c,b="undefined"==typeof a;if(b&&(a=this.offset),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal offset: "+a+" (not an integer)");if(a>>>=0,0>a||a+4>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+a+" (+"+4+") <= "+this.buffer.byteLength)}return c=0,this.littleEndian?(c=this.view[a+2]<<16,c|=this.view[a+1]<<8,c|=this.view[a],c+=this.view[a+3]<<24>>>0):(c=this.view[a+1]<<16,c|=this.view[a+2]<<8,c|=this.view[a+3],c+=this.view[a]<<24>>>0),c|=0,b&&(this.offset+=4),c},c.readInt=c.readInt32,c.writeUint32=function(a,b){var d,c="undefined"==typeof b;if(c&&(b=this.offset),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal value: "+a+" (not an integer)");if(a>>>=0,"number"!=typeof b||0!==b%1)throw TypeError("Illegal offset: "+b+" (not an integer)");if(b>>>=0,0>b||b+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+b+" (+"+0+") <= "+this.buffer.byteLength)}return b+=4,d=this.buffer.byteLength,b>d&&this.resize((d*=2)>b?d:b),b-=4,this.littleEndian?(this.view[b+3]=255&a>>>24,this.view[b+2]=255&a>>>16,this.view[b+1]=255&a>>>8,this.view[b]=255&a):(this.view[b]=255&a>>>24,this.view[b+1]=255&a>>>16,this.view[b+2]=255&a>>>8,this.view[b+3]=255&a),c&&(this.offset+=4),this},c.writeUInt32=c.writeUint32,c.readUint32=function(a){var c,b="undefined"==typeof a;if(b&&(a=this.offset),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal offset: "+a+" (not an integer)");if(a>>>=0,0>a||a+4>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+a+" (+"+4+") <= "+this.buffer.byteLength)}return c=0,this.littleEndian?(c=this.view[a+2]<<16,c|=this.view[a+1]<<8,c|=this.view[a],c+=this.view[a+3]<<24>>>0):(c=this.view[a+1]<<16,c|=this.view[a+2]<<8,c|=this.view[a+3],c+=this.view[a]<<24>>>0),b&&(this.offset+=4),c},c.readUInt32=c.readUint32,a&&(c.writeInt64=function(b,c){var e,f,g,d="undefined"==typeof c;if(d&&(c=this.offset),!this.noAssert){if("number"==typeof b)b=a.fromNumber(b);else if("string"==typeof b)b=a.fromString(b);else if(!(b&&b instanceof a))throw TypeError("Illegal value: "+b+" (not an integer or Long)");if("number"!=typeof c||0!==c%1)throw TypeError("Illegal offset: "+c+" (not an integer)");if(c>>>=0,0>c||c+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+c+" (+"+0+") <= "+this.buffer.byteLength)}return "number"==typeof b?b=a.fromNumber(b):"string"==typeof b&&(b=a.fromString(b)),c+=8,e=this.buffer.byteLength,c>e&&this.resize((e*=2)>c?e:c),c-=8,f=b.low,g=b.high,this.littleEndian?(this.view[c+3]=255&f>>>24,this.view[c+2]=255&f>>>16,this.view[c+1]=255&f>>>8,this.view[c]=255&f,c+=4,this.view[c+3]=255&g>>>24,this.view[c+2]=255&g>>>16,this.view[c+1]=255&g>>>8,this.view[c]=255&g):(this.view[c]=255&g>>>24,this.view[c+1]=255&g>>>16,this.view[c+2]=255&g>>>8,this.view[c+3]=255&g,c+=4,this.view[c]=255&f>>>24,this.view[c+1]=255&f>>>16,this.view[c+2]=255&f>>>8,this.view[c+3]=255&f),d&&(this.offset+=8),this},c.writeLong=c.writeInt64,c.readInt64=function(b){var d,e,f,c="undefined"==typeof b;if(c&&(b=this.offset),!this.noAssert){if("number"!=typeof b||0!==b%1)throw TypeError("Illegal offset: "+b+" (not an integer)");if(b>>>=0,0>b||b+8>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+b+" (+"+8+") <= "+this.buffer.byteLength)}return d=0,e=0,this.littleEndian?(d=this.view[b+2]<<16,d|=this.view[b+1]<<8,d|=this.view[b],d+=this.view[b+3]<<24>>>0,b+=4,e=this.view[b+2]<<16,e|=this.view[b+1]<<8,e|=this.view[b],e+=this.view[b+3]<<24>>>0):(e=this.view[b+1]<<16,e|=this.view[b+2]<<8,e|=this.view[b+3],e+=this.view[b]<<24>>>0,b+=4,d=this.view[b+1]<<16,d|=this.view[b+2]<<8,d|=this.view[b+3],d+=this.view[b]<<24>>>0),f=new a(d,e,!1),c&&(this.offset+=8),f},c.readLong=c.readInt64,c.writeUint64=function(b,c){var e,f,g,d="undefined"==typeof c;if(d&&(c=this.offset),!this.noAssert){if("number"==typeof b)b=a.fromNumber(b);else if("string"==typeof b)b=a.fromString(b);else if(!(b&&b instanceof a))throw TypeError("Illegal value: "+b+" (not an integer or Long)");if("number"!=typeof c||0!==c%1)throw TypeError("Illegal offset: "+c+" (not an integer)");if(c>>>=0,0>c||c+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+c+" (+"+0+") <= "+this.buffer.byteLength)}return "number"==typeof b?b=a.fromNumber(b):"string"==typeof b&&(b=a.fromString(b)),c+=8,e=this.buffer.byteLength,c>e&&this.resize((e*=2)>c?e:c),c-=8,f=b.low,g=b.high,this.littleEndian?(this.view[c+3]=255&f>>>24,this.view[c+2]=255&f>>>16,this.view[c+1]=255&f>>>8,this.view[c]=255&f,c+=4,this.view[c+3]=255&g>>>24,this.view[c+2]=255&g>>>16,this.view[c+1]=255&g>>>8,this.view[c]=255&g):(this.view[c]=255&g>>>24,this.view[c+1]=255&g>>>16,this.view[c+2]=255&g>>>8,this.view[c+3]=255&g,c+=4,this.view[c]=255&f>>>24,this.view[c+1]=255&f>>>16,this.view[c+2]=255&f>>>8,this.view[c+3]=255&f),d&&(this.offset+=8),this},c.writeUInt64=c.writeUint64,c.readUint64=function(b){var d,e,f,c="undefined"==typeof b;if(c&&(b=this.offset),!this.noAssert){if("number"!=typeof b||0!==b%1)throw TypeError("Illegal offset: "+b+" (not an integer)");if(b>>>=0,0>b||b+8>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+b+" (+"+8+") <= "+this.buffer.byteLength)}return d=0,e=0,this.littleEndian?(d=this.view[b+2]<<16,d|=this.view[b+1]<<8,d|=this.view[b],d+=this.view[b+3]<<24>>>0,b+=4,e=this.view[b+2]<<16,e|=this.view[b+1]<<8,e|=this.view[b],e+=this.view[b+3]<<24>>>0):(e=this.view[b+1]<<16,e|=this.view[b+2]<<8,e|=this.view[b+3],e+=this.view[b]<<24>>>0,b+=4,d=this.view[b+1]<<16,d|=this.view[b+2]<<8,d|=this.view[b+3],d+=this.view[b]<<24>>>0),f=new a(d,e,!0),c&&(this.offset+=8),f},c.readUInt64=c.readUint64),c.writeFloat32=function(a,b){var d,c="undefined"==typeof b;if(c&&(b=this.offset),!this.noAssert){if("number"!=typeof a)throw TypeError("Illegal value: "+a+" (not a number)");if("number"!=typeof b||0!==b%1)throw TypeError("Illegal offset: "+b+" (not an integer)");if(b>>>=0,0>b||b+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+b+" (+"+0+") <= "+this.buffer.byteLength)}return b+=4,d=this.buffer.byteLength,b>d&&this.resize((d*=2)>b?d:b),b-=4,i(this.view,a,b,this.littleEndian,23,4),c&&(this.offset+=4),this},c.writeFloat=c.writeFloat32,c.readFloat32=function(a){var c,b="undefined"==typeof a;if(b&&(a=this.offset),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal offset: "+a+" (not an integer)");if(a>>>=0,0>a||a+4>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+a+" (+"+4+") <= "+this.buffer.byteLength)}return c=h(this.view,a,this.littleEndian,23,4),b&&(this.offset+=4),c},c.readFloat=c.readFloat32,c.writeFloat64=function(a,b){var d,c="undefined"==typeof b;if(c&&(b=this.offset),!this.noAssert){if("number"!=typeof a)throw TypeError("Illegal value: "+a+" (not a number)");if("number"!=typeof b||0!==b%1)throw TypeError("Illegal offset: "+b+" (not an integer)");if(b>>>=0,0>b||b+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+b+" (+"+0+") <= "+this.buffer.byteLength)}return b+=8,d=this.buffer.byteLength,b>d&&this.resize((d*=2)>b?d:b),b-=8,i(this.view,a,b,this.littleEndian,52,8),c&&(this.offset+=8),this},c.writeDouble=c.writeFloat64,c.readFloat64=function(a){var c,b="undefined"==typeof a;if(b&&(a=this.offset),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal offset: "+a+" (not an integer)");if(a>>>=0,0>a||a+8>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+a+" (+"+8+") <= "+this.buffer.byteLength)}return c=h(this.view,a,this.littleEndian,52,8),b&&(this.offset+=8),c},c.readDouble=c.readFloat64,b.MAX_VARINT32_BYTES=5,b.calculateVarint32=function(a){return a>>>=0,128>a?1:16384>a?2:1<<21>a?3:1<<28>a?4:5},b.zigZagEncode32=function(a){return ((a|=0)<<1^a>>31)>>>0},b.zigZagDecode32=function(a){return 0|a>>>1^-(1&a)},c.writeVarint32=function(a,c){var f,e,g,d="undefined"==typeof c;if(d&&(c=this.offset),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal value: "+a+" (not an integer)");if(a|=0,"number"!=typeof c||0!==c%1)throw TypeError("Illegal offset: "+c+" (not an integer)");if(c>>>=0,0>c||c+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+c+" (+"+0+") <= "+this.buffer.byteLength)}for(e=b.calculateVarint32(a),c+=e,g=this.buffer.byteLength,c>g&&this.resize((g*=2)>c?g:c),c-=e,a>>>=0;a>=128;)f=128|127&a,this.view[c++]=f,a>>>=7;return this.view[c++]=a,d?(this.offset=c,this):e},c.writeVarint32ZigZag=function(a,c){return this.writeVarint32(b.zigZagEncode32(a),c)},c.readVarint32=function(a){var e,c,d,f,b="undefined"==typeof a;if(b&&(a=this.offset),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal offset: "+a+" (not an integer)");if(a>>>=0,0>a||a+1>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+a+" (+"+1+") <= "+this.buffer.byteLength)}c=0,d=0;do{if(!this.noAssert&&a>this.limit)throw f=Error("Truncated"),f.truncated=!0,f;e=this.view[a++],5>c&&(d|=(127&e)<<7*c),++c;}while(0!==(128&e));return d|=0,b?(this.offset=a,d):{value:d,length:c}},c.readVarint32ZigZag=function(a){var c=this.readVarint32(a);return "object"==typeof c?c.value=b.zigZagDecode32(c.value):c=b.zigZagDecode32(c),c},a&&(b.MAX_VARINT64_BYTES=10,b.calculateVarint64=function(b){"number"==typeof b?b=a.fromNumber(b):"string"==typeof b&&(b=a.fromString(b));var c=b.toInt()>>>0,d=b.shiftRightUnsigned(28).toInt()>>>0,e=b.shiftRightUnsigned(56).toInt()>>>0;return 0==e?0==d?16384>c?128>c?1:2:1<<21>c?3:4:16384>d?128>d?5:6:1<<21>d?7:8:128>e?9:10},b.zigZagEncode64=function(b){return "number"==typeof b?b=a.fromNumber(b,!1):"string"==typeof b?b=a.fromString(b,!1):b.unsigned!==!1&&(b=b.toSigned()),b.shiftLeft(1).xor(b.shiftRight(63)).toUnsigned()},b.zigZagDecode64=function(b){return "number"==typeof b?b=a.fromNumber(b,!1):"string"==typeof b?b=a.fromString(b,!1):b.unsigned!==!1&&(b=b.toSigned()),b.shiftRightUnsigned(1).xor(b.and(a.ONE).toSigned().negate()).toSigned()},c.writeVarint64=function(c,d){var f,g,h,i,j,e="undefined"==typeof d;if(e&&(d=this.offset),!this.noAssert){if("number"==typeof c)c=a.fromNumber(c);else if("string"==typeof c)c=a.fromString(c);else if(!(c&&c instanceof a))throw TypeError("Illegal value: "+c+" (not an integer or Long)");if("number"!=typeof d||0!==d%1)throw TypeError("Illegal offset: "+d+" (not an integer)");if(d>>>=0,0>d||d+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+d+" (+"+0+") <= "+this.buffer.byteLength)}switch("number"==typeof c?c=a.fromNumber(c,!1):"string"==typeof c?c=a.fromString(c,!1):c.unsigned!==!1&&(c=c.toSigned()),f=b.calculateVarint64(c),g=c.toInt()>>>0,h=c.shiftRightUnsigned(28).toInt()>>>0,i=c.shiftRightUnsigned(56).toInt()>>>0,d+=f,j=this.buffer.byteLength,d>j&&this.resize((j*=2)>d?j:d),d-=f,f){case 10:this.view[d+9]=1&i>>>7;case 9:this.view[d+8]=9!==f?128|i:127&i;case 8:this.view[d+7]=8!==f?128|h>>>21:127&h>>>21;case 7:this.view[d+6]=7!==f?128|h>>>14:127&h>>>14;case 6:this.view[d+5]=6!==f?128|h>>>7:127&h>>>7;case 5:this.view[d+4]=5!==f?128|h:127&h;case 4:this.view[d+3]=4!==f?128|g>>>21:127&g>>>21;case 3:this.view[d+2]=3!==f?128|g>>>14:127&g>>>14;case 2:this.view[d+1]=2!==f?128|g>>>7:127&g>>>7;case 1:this.view[d]=1!==f?128|g:127&g;}return e?(this.offset+=f,this):f},c.writeVarint64ZigZag=function(a,c){return this.writeVarint64(b.zigZagEncode64(a),c)},c.readVarint64=function(b){var d,e,f,g,h,i,c="undefined"==typeof b;if(c&&(b=this.offset),!this.noAssert){if("number"!=typeof b||0!==b%1)throw TypeError("Illegal offset: "+b+" (not an integer)");if(b>>>=0,0>b||b+1>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+b+" (+"+1+") <= "+this.buffer.byteLength)}if(d=b,e=0,f=0,g=0,h=0,h=this.view[b++],e=127&h,128&h&&(h=this.view[b++],e|=(127&h)<<7,(128&h||this.noAssert&&"undefined"==typeof h)&&(h=this.view[b++],e|=(127&h)<<14,(128&h||this.noAssert&&"undefined"==typeof h)&&(h=this.view[b++],e|=(127&h)<<21,(128&h||this.noAssert&&"undefined"==typeof h)&&(h=this.view[b++],f=127&h,(128&h||this.noAssert&&"undefined"==typeof h)&&(h=this.view[b++],f|=(127&h)<<7,(128&h||this.noAssert&&"undefined"==typeof h)&&(h=this.view[b++],f|=(127&h)<<14,(128&h||this.noAssert&&"undefined"==typeof h)&&(h=this.view[b++],f|=(127&h)<<21,(128&h||this.noAssert&&"undefined"==typeof h)&&(h=this.view[b++],g=127&h,(128&h||this.noAssert&&"undefined"==typeof h)&&(h=this.view[b++],g|=(127&h)<<7,128&h||this.noAssert&&"undefined"==typeof h))))))))))throw Error("Buffer overrun");return i=a.fromBits(e|f<<28,f>>>4|g<<24,!1),c?(this.offset=b,i):{value:i,length:b-d}},c.readVarint64ZigZag=function(c){var d=this.readVarint64(c);return d&&d.value instanceof a?d.value=b.zigZagDecode64(d.value):d=b.zigZagDecode64(d),d}),c.writeCString=function(a,b){var d,e,g,c="undefined"==typeof b;if(c&&(b=this.offset),e=a.length,!this.noAssert){if("string"!=typeof a)throw TypeError("Illegal str: Not a string");for(d=0;e>d;++d)if(0===a.charCodeAt(d))throw RangeError("Illegal str: Contains NULL-characters");if("number"!=typeof b||0!==b%1)throw TypeError("Illegal offset: "+b+" (not an integer)");if(b>>>=0,0>b||b+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+b+" (+"+0+") <= "+this.buffer.byteLength)}return e=k.calculateUTF16asUTF8(f(a))[1],b+=e+1,g=this.buffer.byteLength,b>g&&this.resize((g*=2)>b?g:b),b-=e+1,k.encodeUTF16toUTF8(f(a),function(a){this.view[b++]=a;}.bind(this)),this.view[b++]=0,c?(this.offset=b,this):e},c.readCString=function(a){var c,e,f,b="undefined"==typeof a;if(b&&(a=this.offset),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal offset: "+a+" (not an integer)");if(a>>>=0,0>a||a+1>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+a+" (+"+1+") <= "+this.buffer.byteLength)}return c=a,f=-1,k.decodeUTF8toUTF16(function(){if(0===f)return null;if(a>=this.limit)throw RangeError("Illegal range: Truncated data, "+a+" < "+this.limit);return f=this.view[a++],0===f?null:f}.bind(this),e=g(),!0),b?(this.offset=a,e()):{string:e(),length:a-c}},c.writeIString=function(a,b){var e,d,g,c="undefined"==typeof b;if(c&&(b=this.offset),!this.noAssert){if("string"!=typeof a)throw TypeError("Illegal str: Not a string");if("number"!=typeof b||0!==b%1)throw TypeError("Illegal offset: "+b+" (not an integer)");if(b>>>=0,0>b||b+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+b+" (+"+0+") <= "+this.buffer.byteLength)}if(d=b,e=k.calculateUTF16asUTF8(f(a),this.noAssert)[1],b+=4+e,g=this.buffer.byteLength,b>g&&this.resize((g*=2)>b?g:b),b-=4+e,this.littleEndian?(this.view[b+3]=255&e>>>24,this.view[b+2]=255&e>>>16,this.view[b+1]=255&e>>>8,this.view[b]=255&e):(this.view[b]=255&e>>>24,this.view[b+1]=255&e>>>16,this.view[b+2]=255&e>>>8,this.view[b+3]=255&e),b+=4,k.encodeUTF16toUTF8(f(a),function(a){this.view[b++]=a;}.bind(this)),b!==d+4+e)throw RangeError("Illegal range: Truncated data, "+b+" == "+(b+4+e));return c?(this.offset=b,this):b-d},c.readIString=function(a){var d,e,f,c="undefined"==typeof a; if(c&&(a=this.offset),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal offset: "+a+" (not an integer)");if(a>>>=0,0>a||a+4>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+a+" (+"+4+") <= "+this.buffer.byteLength)}return d=a,e=this.readUint32(a),f=this.readUTF8String(e,b.METRICS_BYTES,a+=4),a+=f.length,c?(this.offset=a,f.string):{string:f.string,length:a-d}},b.METRICS_CHARS="c",b.METRICS_BYTES="b",c.writeUTF8String=function(a,b){var d,e,g,c="undefined"==typeof b;if(c&&(b=this.offset),!this.noAssert){if("number"!=typeof b||0!==b%1)throw TypeError("Illegal offset: "+b+" (not an integer)");if(b>>>=0,0>b||b+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+b+" (+"+0+") <= "+this.buffer.byteLength)}return e=b,d=k.calculateUTF16asUTF8(f(a))[1],b+=d,g=this.buffer.byteLength,b>g&&this.resize((g*=2)>b?g:b),b-=d,k.encodeUTF16toUTF8(f(a),function(a){this.view[b++]=a;}.bind(this)),c?(this.offset=b,this):b-e},c.writeString=c.writeUTF8String,b.calculateUTF8Chars=function(a){return k.calculateUTF16asUTF8(f(a))[0]},b.calculateUTF8Bytes=function(a){return k.calculateUTF16asUTF8(f(a))[1]},b.calculateString=b.calculateUTF8Bytes,c.readUTF8String=function(a,c,d){var e,i,f,h,j;if("number"==typeof c&&(d=c,c=void 0),e="undefined"==typeof d,e&&(d=this.offset),"undefined"==typeof c&&(c=b.METRICS_CHARS),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal length: "+a+" (not an integer)");if(a|=0,"number"!=typeof d||0!==d%1)throw TypeError("Illegal offset: "+d+" (not an integer)");if(d>>>=0,0>d||d+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+d+" (+"+0+") <= "+this.buffer.byteLength)}if(f=0,h=d,c===b.METRICS_CHARS){if(i=g(),k.decodeUTF8(function(){return a>f&&d>>=0,0>d||d+a>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+d+" (+"+a+") <= "+this.buffer.byteLength)}if(j=d+a,k.decodeUTF8toUTF16(function(){return j>d?this.view[d++]:null}.bind(this),i=g(),this.noAssert),d!==j)throw RangeError("Illegal range: Truncated data, "+d+" == "+j);return e?(this.offset=d,i()):{string:i(),length:d-h}}throw TypeError("Unsupported metrics: "+c)},c.readString=c.readUTF8String,c.writeVString=function(a,c){var g,h,e,i,d="undefined"==typeof c;if(d&&(c=this.offset),!this.noAssert){if("string"!=typeof a)throw TypeError("Illegal str: Not a string");if("number"!=typeof c||0!==c%1)throw TypeError("Illegal offset: "+c+" (not an integer)");if(c>>>=0,0>c||c+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+c+" (+"+0+") <= "+this.buffer.byteLength)}if(e=c,g=k.calculateUTF16asUTF8(f(a),this.noAssert)[1],h=b.calculateVarint32(g),c+=h+g,i=this.buffer.byteLength,c>i&&this.resize((i*=2)>c?i:c),c-=h+g,c+=this.writeVarint32(g,c),k.encodeUTF16toUTF8(f(a),function(a){this.view[c++]=a;}.bind(this)),c!==e+g+h)throw RangeError("Illegal range: Truncated data, "+c+" == "+(c+g+h));return d?(this.offset=c,this):c-e},c.readVString=function(a){var d,e,f,c="undefined"==typeof a;if(c&&(a=this.offset),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal offset: "+a+" (not an integer)");if(a>>>=0,0>a||a+1>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+a+" (+"+1+") <= "+this.buffer.byteLength)}return d=a,e=this.readVarint32(a),f=this.readUTF8String(e.value,b.METRICS_BYTES,a+=e.length),a+=f.length,c?(this.offset=a,f.string):{string:f.string,length:a-d}},c.append=function(a,c,d){var e,f,g;if(("number"==typeof c||"string"!=typeof c)&&(d=c,c=void 0),e="undefined"==typeof d,e&&(d=this.offset),!this.noAssert){if("number"!=typeof d||0!==d%1)throw TypeError("Illegal offset: "+d+" (not an integer)");if(d>>>=0,0>d||d+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+d+" (+"+0+") <= "+this.buffer.byteLength)}return a instanceof b||(a=b.wrap(a,c)),f=a.limit-a.offset,0>=f?this:(d+=f,g=this.buffer.byteLength,d>g&&this.resize((g*=2)>d?g:d),d-=f,this.view.set(a.view.subarray(a.offset,a.limit),d),a.offset+=f,e&&(this.offset+=f),this)},c.appendTo=function(a,b){return a.append(this,b),this},c.assert=function(a){return this.noAssert=!a,this},c.capacity=function(){return this.buffer.byteLength},c.clear=function(){return this.offset=0,this.limit=this.buffer.byteLength,this.markedOffset=-1,this},c.clone=function(a){var c=new b(0,this.littleEndian,this.noAssert);return a?(c.buffer=new ArrayBuffer(this.buffer.byteLength),c.view=new Uint8Array(c.buffer)):(c.buffer=this.buffer,c.view=this.view),c.offset=this.offset,c.markedOffset=this.markedOffset,c.limit=this.limit,c},c.compact=function(a,b){var c,e,f;if("undefined"==typeof a&&(a=this.offset),"undefined"==typeof b&&(b=this.limit),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal begin: Not an integer");if(a>>>=0,"number"!=typeof b||0!==b%1)throw TypeError("Illegal end: Not an integer");if(b>>>=0,0>a||a>b||b>this.buffer.byteLength)throw RangeError("Illegal range: 0 <= "+a+" <= "+b+" <= "+this.buffer.byteLength)}return 0===a&&b===this.buffer.byteLength?this:(c=b-a,0===c?(this.buffer=d,this.view=null,this.markedOffset>=0&&(this.markedOffset-=a),this.offset=0,this.limit=0,this):(e=new ArrayBuffer(c),f=new Uint8Array(e),f.set(this.view.subarray(a,b)),this.buffer=e,this.view=f,this.markedOffset>=0&&(this.markedOffset-=a),this.offset=0,this.limit=c,this))},c.copy=function(a,c){if("undefined"==typeof a&&(a=this.offset),"undefined"==typeof c&&(c=this.limit),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal begin: Not an integer");if(a>>>=0,"number"!=typeof c||0!==c%1)throw TypeError("Illegal end: Not an integer");if(c>>>=0,0>a||a>c||c>this.buffer.byteLength)throw RangeError("Illegal range: 0 <= "+a+" <= "+c+" <= "+this.buffer.byteLength)}if(a===c)return new b(0,this.littleEndian,this.noAssert);var d=c-a,e=new b(d,this.littleEndian,this.noAssert);return e.offset=0,e.limit=d,e.markedOffset>=0&&(e.markedOffset-=a),this.copyTo(e,0,a,c),e},c.copyTo=function(a,c,d,e){var f,g,h;if(!this.noAssert&&!b.isByteBuffer(a))throw TypeError("Illegal target: Not a ByteBuffer");if(c=(g="undefined"==typeof c)?a.offset:0|c,d=(f="undefined"==typeof d)?this.offset:0|d,e="undefined"==typeof e?this.limit:0|e,0>c||c>a.buffer.byteLength)throw RangeError("Illegal target range: 0 <= "+c+" <= "+a.buffer.byteLength);if(0>d||e>this.buffer.byteLength)throw RangeError("Illegal source range: 0 <= "+d+" <= "+this.buffer.byteLength);return h=e-d,0===h?a:(a.ensureCapacity(c+h),a.view.set(this.view.subarray(d,e),c),f&&(this.offset+=h),g&&(a.offset+=h),this)},c.ensureCapacity=function(a){var b=this.buffer.byteLength;return a>b?this.resize((b*=2)>a?b:a):this},c.fill=function(a,b,c){var d="undefined"==typeof b;if(d&&(b=this.offset),"string"==typeof a&&a.length>0&&(a=a.charCodeAt(0)),"undefined"==typeof b&&(b=this.offset),"undefined"==typeof c&&(c=this.limit),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal value: "+a+" (not an integer)");if(a|=0,"number"!=typeof b||0!==b%1)throw TypeError("Illegal begin: Not an integer");if(b>>>=0,"number"!=typeof c||0!==c%1)throw TypeError("Illegal end: Not an integer");if(c>>>=0,0>b||b>c||c>this.buffer.byteLength)throw RangeError("Illegal range: 0 <= "+b+" <= "+c+" <= "+this.buffer.byteLength)}if(b>=c)return this;for(;c>b;)this.view[b++]=a;return d&&(this.offset=b),this},c.flip=function(){return this.limit=this.offset,this.offset=0,this},c.mark=function(a){if(a="undefined"==typeof a?this.offset:a,!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal offset: "+a+" (not an integer)");if(a>>>=0,0>a||a+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+a+" (+"+0+") <= "+this.buffer.byteLength)}return this.markedOffset=a,this},c.order=function(a){if(!this.noAssert&&"boolean"!=typeof a)throw TypeError("Illegal littleEndian: Not a boolean");return this.littleEndian=!!a,this},c.LE=function(a){return this.littleEndian="undefined"!=typeof a?!!a:!0,this},c.BE=function(a){return this.littleEndian="undefined"!=typeof a?!a:!1,this},c.prepend=function(a,c,d){var e,f,g,h,i;if(("number"==typeof c||"string"!=typeof c)&&(d=c,c=void 0),e="undefined"==typeof d,e&&(d=this.offset),!this.noAssert){if("number"!=typeof d||0!==d%1)throw TypeError("Illegal offset: "+d+" (not an integer)");if(d>>>=0,0>d||d+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+d+" (+"+0+") <= "+this.buffer.byteLength)}return a instanceof b||(a=b.wrap(a,c)),f=a.limit-a.offset,0>=f?this:(g=f-d,g>0?(h=new ArrayBuffer(this.buffer.byteLength+g),i=new Uint8Array(h),i.set(this.view.subarray(d,this.buffer.byteLength),f),this.buffer=h,this.view=i,this.offset+=g,this.markedOffset>=0&&(this.markedOffset+=g),this.limit+=g,d+=g):new Uint8Array(this.buffer),this.view.set(a.view.subarray(a.offset,a.limit),d-f),a.offset=a.limit,e&&(this.offset-=f),this)},c.prependTo=function(a,b){return a.prepend(this,b),this},c.printDebug=function(a){"function"!=typeof a&&(a=console.log.bind(console)),a(this.toString()+"\n-------------------------------------------------------------------\n"+this.toDebug(!0));},c.remaining=function(){return this.limit-this.offset},c.reset=function(){return this.markedOffset>=0?(this.offset=this.markedOffset,this.markedOffset=-1):this.offset=0,this},c.resize=function(a){var b,c;if(!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal capacity: "+a+" (not an integer)");if(a|=0,0>a)throw RangeError("Illegal capacity: 0 <= "+a)}return this.buffer.byteLength>>=0,"number"!=typeof b||0!==b%1)throw TypeError("Illegal end: Not an integer");if(b>>>=0,0>a||a>b||b>this.buffer.byteLength)throw RangeError("Illegal range: 0 <= "+a+" <= "+b+" <= "+this.buffer.byteLength)}return a===b?this:(Array.prototype.reverse.call(this.view.subarray(a,b)),this)},c.skip=function(a){if(!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal length: "+a+" (not an integer)");a|=0;}var b=this.offset+a;if(!this.noAssert&&(0>b||b>this.buffer.byteLength))throw RangeError("Illegal length: 0 <= "+this.offset+" + "+a+" <= "+this.buffer.byteLength);return this.offset=b,this},c.slice=function(a,b){if("undefined"==typeof a&&(a=this.offset),"undefined"==typeof b&&(b=this.limit),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal begin: Not an integer");if(a>>>=0,"number"!=typeof b||0!==b%1)throw TypeError("Illegal end: Not an integer");if(b>>>=0,0>a||a>b||b>this.buffer.byteLength)throw RangeError("Illegal range: 0 <= "+a+" <= "+b+" <= "+this.buffer.byteLength)}var c=this.clone();return c.offset=a,c.limit=b,c},c.toBuffer=function(a){var e,b=this.offset,c=this.limit;if(!this.noAssert){if("number"!=typeof b||0!==b%1)throw TypeError("Illegal offset: Not an integer");if(b>>>=0,"number"!=typeof c||0!==c%1)throw TypeError("Illegal limit: Not an integer");if(c>>>=0,0>b||b>c||c>this.buffer.byteLength)throw RangeError("Illegal range: 0 <= "+b+" <= "+c+" <= "+this.buffer.byteLength)}return a||0!==b||c!==this.buffer.byteLength?b===c?d:(e=new ArrayBuffer(c-b),new Uint8Array(e).set(new Uint8Array(this.buffer).subarray(b,c),0),e):this.buffer},c.toArrayBuffer=c.toBuffer,c.toString=function(a,b,c){if("undefined"==typeof a)return "ByteBufferAB(offset="+this.offset+",markedOffset="+this.markedOffset+",limit="+this.limit+",capacity="+this.capacity()+")";switch("number"==typeof a&&(a="utf8",b=a,c=b),a){case"utf8":return this.toUTF8(b,c);case"base64":return this.toBase64(b,c);case"hex":return this.toHex(b,c);case"binary":return this.toBinary(b,c);case"debug":return this.toDebug();case"columns":return this.toColumns();default:throw Error("Unsupported encoding: "+a)}},j=function(){var d,e,a={},b=[65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,48,49,50,51,52,53,54,55,56,57,43,47],c=[];for(d=0,e=b.length;e>d;++d)c[b[d]]=d;return a.encode=function(a,c){for(var d,e;null!==(d=a());)c(b[63&d>>2]),e=(3&d)<<4,null!==(d=a())?(e|=15&d>>4,c(b[63&(e|15&d>>4)]),e=(15&d)<<2,null!==(d=a())?(c(b[63&(e|3&d>>6)]),c(b[63&d])):(c(b[63&e]),c(61))):(c(b[63&e]),c(61),c(61));},a.decode=function(a,b){function g(a){throw Error("Illegal character code: "+a)}for(var d,e,f;null!==(d=a());)if(e=c[d],"undefined"==typeof e&&g(d),null!==(d=a())&&(f=c[d],"undefined"==typeof f&&g(d),b(e<<2>>>0|(48&f)>>4),null!==(d=a()))){if(e=c[d],"undefined"==typeof e){if(61===d)break;g(d);}if(b((15&f)<<4>>>0|(60&e)>>2),null!==(d=a())){if(f=c[d],"undefined"==typeof f){if(61===d)break;g(d);}b((3&e)<<6>>>0|f);}}},a.test=function(a){return /^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/.test(a)},a}(),c.toBase64=function(a,b){if("undefined"==typeof a&&(a=this.offset),"undefined"==typeof b&&(b=this.limit),a=0|a,b=0|b,0>a||b>this.capacity||a>b)throw RangeError("begin, end");var c;return j.encode(function(){return b>a?this.view[a++]:null}.bind(this),c=g()),c()},b.fromBase64=function(a,c){if("string"!=typeof a)throw TypeError("str");var d=new b(3*(a.length/4),c),e=0;return j.decode(f(a),function(a){d.view[e++]=a;}),d.limit=e,d},b.btoa=function(a){return b.fromBinary(a).toBase64()},b.atob=function(a){return b.fromBase64(a).toBinary()},c.toBinary=function(a,b){if("undefined"==typeof a&&(a=this.offset),"undefined"==typeof b&&(b=this.limit),a|=0,b|=0,0>a||b>this.capacity()||a>b)throw RangeError("begin, end");if(a===b)return "";for(var c=[],d=[];b>a;)c.push(this.view[a++]),c.length>=1024&&(d.push(String.fromCharCode.apply(String,c)),c=[]);return d.join("")+String.fromCharCode.apply(String,c)},b.fromBinary=function(a,c){if("string"!=typeof a)throw TypeError("str");for(var f,d=0,e=a.length,g=new b(e,c);e>d;){if(f=a.charCodeAt(d),f>255)throw RangeError("illegal char code: "+f);g.view[d++]=f;}return g.limit=e,g},c.toDebug=function(a){for(var d,b=-1,c=this.buffer.byteLength,e="",f="",g="";c>b;){if(-1!==b&&(d=this.view[b],e+=16>d?"0"+d.toString(16).toUpperCase():d.toString(16).toUpperCase(),a&&(f+=d>32&&127>d?String.fromCharCode(d):".")),++b,a&&b>0&&0===b%16&&b!==c){for(;e.length<51;)e+=" ";g+=e+f+"\n",e=f="";}e+=b===this.offset&&b===this.limit?b===this.markedOffset?"!":"|":b===this.offset?b===this.markedOffset?"[":"<":b===this.limit?b===this.markedOffset?"]":">":b===this.markedOffset?"'":a||0!==b&&b!==c?" ":"";}if(a&&" "!==e){for(;e.length<51;)e+=" ";g+=e+f+"\n";}return a?g:e},b.fromDebug=function(a,c,d){for(var i,j,e=a.length,f=new b(0|(e+1)/3,c,d),g=0,h=0,k=!1,l=!1,m=!1,n=!1,o=!1;e>g;){switch(i=a.charAt(g++)){case"!":if(!d){if(l||m||n){o=!0;break}l=m=n=!0;}f.offset=f.markedOffset=f.limit=h,k=!1;break;case"|":if(!d){if(l||n){o=!0;break}l=n=!0;}f.offset=f.limit=h,k=!1;break;case"[":if(!d){if(l||m){o=!0;break}l=m=!0;}f.offset=f.markedOffset=h,k=!1;break;case"<":if(!d){if(l){o=!0;break}l=!0;}f.offset=h,k=!1;break;case"]":if(!d){if(n||m){o=!0;break}n=m=!0;}f.limit=f.markedOffset=h,k=!1;break;case">":if(!d){if(n){o=!0;break}n=!0;}f.limit=h,k=!1;break;case"'":if(!d){if(m){o=!0;break}m=!0;}f.markedOffset=h,k=!1;break;case" ":k=!1;break;default:if(!d&&k){o=!0;break}if(j=parseInt(i+a.charAt(g++),16),!d&&(isNaN(j)||0>j||j>255))throw TypeError("Illegal str: Not a debug encoded string");f.view[h++]=j,k=!0;}if(o)throw TypeError("Illegal str: Invalid symbol at "+g)}if(!d){if(!l||!n)throw TypeError("Illegal str: Missing offset or limit");if(h>>=0,"number"!=typeof b||0!==b%1)throw TypeError("Illegal end: Not an integer");if(b>>>=0,0>a||a>b||b>this.buffer.byteLength)throw RangeError("Illegal range: 0 <= "+a+" <= "+b+" <= "+this.buffer.byteLength)}for(var d,c=new Array(b-a);b>a;)d=this.view[a++],16>d?c.push("0",d.toString(16)):c.push(d.toString(16));return c.join("")},b.fromHex=function(a,c,d){var g,e,f,h,i;if(!d){if("string"!=typeof a)throw TypeError("Illegal str: Not a string");if(0!==a.length%2)throw TypeError("Illegal str: Length not a multiple of 2")}for(e=a.length,f=new b(0|e/2,c),h=0,i=0;e>h;h+=2){if(g=parseInt(a.substring(h,h+2),16),!d&&(!isFinite(g)||0>g||g>255))throw TypeError("Illegal str: Contains non-hex characters");f.view[i++]=g;}return f.limit=i,f},k=function(){var a={};return a.MAX_CODEPOINT=1114111,a.encodeUTF8=function(a,b){var c=null;for("number"==typeof a&&(c=a,a=function(){return null});null!==c||null!==(c=a());)128>c?b(127&c):2048>c?(b(192|31&c>>6),b(128|63&c)):65536>c?(b(224|15&c>>12),b(128|63&c>>6),b(128|63&c)):(b(240|7&c>>18),b(128|63&c>>12),b(128|63&c>>6),b(128|63&c)),c=null;},a.decodeUTF8=function(a,b){for(var c,d,e,f,g=function(a){a=a.slice(0,a.indexOf(null));var b=Error(a.toString());throw b.name="TruncatedError",b.bytes=a,b};null!==(c=a());)if(0===(128&c))b(c);else if(192===(224&c))null===(d=a())&&g([c,d]),b((31&c)<<6|63&d);else if(224===(240&c))(null===(d=a())||null===(e=a()))&&g([c,d,e]),b((15&c)<<12|(63&d)<<6|63&e);else{if(240!==(248&c))throw RangeError("Illegal starting byte: "+c);(null===(d=a())||null===(e=a())||null===(f=a()))&&g([c,d,e,f]),b((7&c)<<18|(63&d)<<12|(63&e)<<6|63&f);}},a.UTF16toUTF8=function(a,b){for(var c,d=null;;){if(null===(c=null!==d?d:a()))break;c>=55296&&57343>=c&&null!==(d=a())&&d>=56320&&57343>=d?(b(1024*(c-55296)+d-56320+65536),d=null):b(c);}null!==d&&b(d);},a.UTF8toUTF16=function(a,b){var c=null;for("number"==typeof a&&(c=a,a=function(){return null});null!==c||null!==(c=a());)65535>=c?b(c):(c-=65536,b((c>>10)+55296),b(c%1024+56320)),c=null;},a.encodeUTF16toUTF8=function(b,c){a.UTF16toUTF8(b,function(b){a.encodeUTF8(b,c);});},a.decodeUTF8toUTF16=function(b,c){a.decodeUTF8(b,function(b){a.UTF8toUTF16(b,c);});},a.calculateCodePoint=function(a){return 128>a?1:2048>a?2:65536>a?3:4},a.calculateUTF8=function(a){for(var b,c=0;null!==(b=a());)c+=128>b?1:2048>b?2:65536>b?3:4;return c},a.calculateUTF16asUTF8=function(b){var c=0,d=0;return a.UTF16toUTF8(b,function(a){++c,d+=128>a?1:2048>a?2:65536>a?3:4;}),[c,d]},a}(),c.toUTF8=function(a,b){if("undefined"==typeof a&&(a=this.offset),"undefined"==typeof b&&(b=this.limit),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal begin: Not an integer");if(a>>>=0,"number"!=typeof b||0!==b%1)throw TypeError("Illegal end: Not an integer");if(b>>>=0,0>a||a>b||b>this.buffer.byteLength)throw RangeError("Illegal range: 0 <= "+a+" <= "+b+" <= "+this.buffer.byteLength)}var c;try{k.decodeUTF8toUTF16(function(){return b>a?this.view[a++]:null}.bind(this),c=g());}catch(d){if(a!==b)throw RangeError("Illegal range: Truncated data, "+a+" != "+b)}return c()},b.fromUTF8=function(a,c,d){if(!d&&"string"!=typeof a)throw TypeError("Illegal str: Not a string");var e=new b(k.calculateUTF16asUTF8(f(a),!0)[1],c,d),g=0;return k.encodeUTF16toUTF8(f(a),function(a){e.view[g++]=a;}),e.limit=g,e},b}(c),e=function(b,c){var f,h,i,e={};return e.ByteBuffer=b,e.c=b,f=b,e.Long=c||null,e.VERSION="5.0.1",e.WIRE_TYPES={},e.WIRE_TYPES.VARINT=0,e.WIRE_TYPES.BITS64=1,e.WIRE_TYPES.LDELIM=2,e.WIRE_TYPES.STARTGROUP=3,e.WIRE_TYPES.ENDGROUP=4,e.WIRE_TYPES.BITS32=5,e.PACKABLE_WIRE_TYPES=[e.WIRE_TYPES.VARINT,e.WIRE_TYPES.BITS64,e.WIRE_TYPES.BITS32],e.TYPES={int32:{name:"int32",wireType:e.WIRE_TYPES.VARINT,defaultValue:0},uint32:{name:"uint32",wireType:e.WIRE_TYPES.VARINT,defaultValue:0},sint32:{name:"sint32",wireType:e.WIRE_TYPES.VARINT,defaultValue:0},int64:{name:"int64",wireType:e.WIRE_TYPES.VARINT,defaultValue:e.Long?e.Long.ZERO:void 0},uint64:{name:"uint64",wireType:e.WIRE_TYPES.VARINT,defaultValue:e.Long?e.Long.UZERO:void 0},sint64:{name:"sint64",wireType:e.WIRE_TYPES.VARINT,defaultValue:e.Long?e.Long.ZERO:void 0},bool:{name:"bool",wireType:e.WIRE_TYPES.VARINT,defaultValue:!1},"double":{name:"double",wireType:e.WIRE_TYPES.BITS64,defaultValue:0},string:{name:"string",wireType:e.WIRE_TYPES.LDELIM,defaultValue:""},bytes:{name:"bytes",wireType:e.WIRE_TYPES.LDELIM,defaultValue:null},fixed32:{name:"fixed32",wireType:e.WIRE_TYPES.BITS32,defaultValue:0},sfixed32:{name:"sfixed32",wireType:e.WIRE_TYPES.BITS32,defaultValue:0},fixed64:{name:"fixed64",wireType:e.WIRE_TYPES.BITS64,defaultValue:e.Long?e.Long.UZERO:void 0},sfixed64:{name:"sfixed64",wireType:e.WIRE_TYPES.BITS64,defaultValue:e.Long?e.Long.ZERO:void 0},"float":{name:"float",wireType:e.WIRE_TYPES.BITS32,defaultValue:0},"enum":{name:"enum",wireType:e.WIRE_TYPES.VARINT,defaultValue:0},message:{name:"message",wireType:e.WIRE_TYPES.LDELIM,defaultValue:null},group:{name:"group",wireType:e.WIRE_TYPES.STARTGROUP,defaultValue:null}},e.MAP_KEY_TYPES=[e.TYPES.int32,e.TYPES.sint32,e.TYPES.sfixed32,e.TYPES.uint32,e.TYPES.fixed32,e.TYPES.int64,e.TYPES.sint64,e.TYPES.sfixed64,e.TYPES.uint64,e.TYPES.fixed64,e.TYPES.bool,e.TYPES.string,e.TYPES.bytes],e.ID_MIN=1,e.ID_MAX=536870911,e.convertFieldsToCamelCase=!1,e.populateAccessors=!0,e.populateDefaults=!0,e.Util=function(){var a={};return a.IS_NODE=!("object"!=typeof process||"[object process]"!=process+""||process.browser),a.XHR=function(){var c,a=[function(){return new XMLHttpRequest},function(){return new ActiveXObject("Msxml2.XMLHTTP")},function(){return new ActiveXObject("Msxml3.XMLHTTP")},function(){return new ActiveXObject("Microsoft.XMLHTTP")}],b=null;for(c=0;c]/g,RULE:/^(?:required|optional|repeated|map)$/,TYPE:/^(?:double|float|int32|uint32|sint32|int64|uint64|sint64|fixed32|sfixed32|fixed64|sfixed64|bool|string|bytes)$/,NAME:/^[a-zA-Z_][a-zA-Z_0-9]*$/,TYPEDEF:/^[a-zA-Z][a-zA-Z_0-9]*$/,TYPEREF:/^(?:\.?[a-zA-Z_][a-zA-Z_0-9]*)+$/,FQTYPEREF:/^(?:\.[a-zA-Z][a-zA-Z_0-9]*)+$/,NUMBER:/^-?(?:[1-9][0-9]*|0|0[xX][0-9a-fA-F]+|0[0-7]+|([0-9]*(\.[0-9]*)?([Ee][+-]?[0-9]+)?)|inf|nan)$/,NUMBER_DEC:/^(?:[1-9][0-9]*|0)$/,NUMBER_HEX:/^0[xX][0-9a-fA-F]+$/,NUMBER_OCT:/^0[0-7]+$/,NUMBER_FLT:/^([0-9]*(\.[0-9]*)?([Ee][+-]?[0-9]+)?|inf|nan)$/,BOOL:/^(?:true|false)$/i,ID:/^(?:[1-9][0-9]*|0|0[xX][0-9a-fA-F]+|0[0-7]+)$/,NEGID:/^\-?(?:[1-9][0-9]*|0|0[xX][0-9a-fA-F]+|0[0-7]+)$/,WHITESPACE:/\s/,STRING:/(?:"([^"\\]*(?:\\.[^"\\]*)*)")|(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g,STRING_DQ:/(?:"([^"\\]*(?:\\.[^"\\]*)*)")/g,STRING_SQ:/(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g},e.DotProto=function(a,b){function h(a,c){var d=-1,e=1;if("-"==a.charAt(0)&&(e=-1,a=a.substring(1)),b.NUMBER_DEC.test(a))d=parseInt(a);else if(b.NUMBER_HEX.test(a))d=parseInt(a.substring(2),16);else{if(!b.NUMBER_OCT.test(a))throw Error("illegal id value: "+(0>e?"-":"")+a);d=parseInt(a.substring(1),8);}if(d=0|e*d,!c&&0>d)throw Error("illegal id value: "+(0>e?"-":"")+a);return d}function i(a){var c=1;if("-"==a.charAt(0)&&(c=-1,a=a.substring(1)),b.NUMBER_DEC.test(a))return c*parseInt(a,10);if(b.NUMBER_HEX.test(a))return c*parseInt(a.substring(2),16);if(b.NUMBER_OCT.test(a))return c*parseInt(a.substring(1),8);if("inf"===a)return 1/0*c;if("nan"===a)return 0/0;if(b.NUMBER_FLT.test(a))return c*parseFloat(a);throw Error("illegal number value: "+(0>c?"-":"")+a)}function j(a,b,c){"undefined"==typeof a[b]?a[b]=c:(Array.isArray(a[b])||(a[b]=[a[b]]),a[b].push(c));}var f,g,c={},d=function(a){this.source=a+"",this.index=0,this.line=1,this.stack=[],this._stringOpen=null;},e=d.prototype;return e._readString=function(){var c,a='"'===this._stringOpen?b.STRING_DQ:b.STRING_SQ;if(a.lastIndex=this.index-1,c=a.exec(this.source),!c)throw Error("unterminated string");return this.index=a.lastIndex,this.stack.push(this._stringOpen),this._stringOpen=null,c[1]},e.next=function(){var a,c,d,e,f,g;if(this.stack.length>0)return this.stack.shift();if(this.index>=this.source.length)return null;if(null!==this._stringOpen)return this._readString();do{for(a=!1;b.WHITESPACE.test(d=this.source.charAt(this.index));)if("\n"===d&&++this.line,++this.index===this.source.length)return null;if("/"===this.source.charAt(this.index))if(++this.index,"/"===this.source.charAt(this.index)){for(;"\n"!==this.source.charAt(++this.index);)if(this.index==this.source.length)return null;++this.index,++this.line,a=!0;}else{if("*"!==(d=this.source.charAt(this.index)))return "/";do{if("\n"===d&&++this.line,++this.index===this.source.length)return null;c=d,d=this.source.charAt(this.index);}while("*"!==c||"/"!==d);++this.index,a=!0;}}while(a);if(this.index===this.source.length)return null;if(e=this.index,b.DELIM.lastIndex=0,f=b.DELIM.test(this.source.charAt(e++)),!f)for(;e"),f=this.tn.next(),!b.NAME.test(f))throw Error("illegal message field name: "+f);e.name=f,this.tn.skip("="),e.id=h(this.tn.next()),f=this.tn.peek(),"["===f&&this._parseFieldOptions(e),this.tn.skip(";");}else if(d="undefined"!=typeof d?d:this.tn.next(),"group"===d){if(g=this._parseMessage(a,e),!/^[A-Z]/.test(g.name))throw Error("illegal group name: "+g.name);e.type=g.name,e.name=g.name.toLowerCase(),this.tn.omit(";");}else{if(!b.TYPE.test(d)&&!b.TYPEREF.test(d))throw Error("illegal message field type: "+d);if(e.type=d,f=this.tn.next(),!b.NAME.test(f))throw Error("illegal message field name: "+f); e.name=f,this.tn.skip("="),e.id=h(this.tn.next()),f=this.tn.peek(),"["===f&&this._parseFieldOptions(e),this.tn.skip(";");}return a.fields.push(e),e},g._parseMessageOneOf=function(a){var e,d,f,c=this.tn.next();if(!b.NAME.test(c))throw Error("illegal oneof name: "+c);for(d=c,f=[],this.tn.skip("{");"}"!==(c=this.tn.next());)e=this._parseMessageField(a,"optional",c),e.oneof=d,f.push(e.id);this.tn.omit(";"),a.oneofs[d]=f;},g._parseFieldOptions=function(a){this.tn.skip("[");for(var b,c=!0;"]"!==(b=this.tn.peek());)c||this.tn.skip(","),this._parseOption(a,!0),c=!1;this.tn.next();},g._parseEnum=function(a){var e,c={name:"",values:[],options:{}},d=this.tn.next();if(!b.NAME.test(d))throw Error("illegal name: "+d);for(c.name=d,this.tn.skip("{");"}"!==(d=this.tn.next());)if("option"===d)this._parseOption(c);else{if(!b.NAME.test(d))throw Error("illegal name: "+d);this.tn.skip("="),e={name:d,id:h(this.tn.next(),!0)},d=this.tn.peek(),"["===d&&this._parseFieldOptions({options:{}}),this.tn.skip(";"),c.values.push(e);}this.tn.omit(";"),a.enums.push(c);},g._parseExtensionRanges=function(){var c,d,e,b=[];do{for(d=[];;){switch(c=this.tn.next()){case"min":e=a.ID_MIN;break;case"max":e=a.ID_MAX;break;default:e=i(c);}if(d.push(e),2===d.length)break;if("to"!==this.tn.peek()){d.push(e);break}this.tn.next();}b.push(d);}while(this.tn.omit(","));return this.tn.skip(";"),b},g._parseExtend=function(a){var d,c=this.tn.next();if(!b.TYPEREF.test(c))throw Error("illegal extend reference: "+c);for(d={ref:c,fields:[]},this.tn.skip("{");"}"!==(c=this.tn.next());)if(b.RULE.test(c))this._parseMessageField(d,c);else{if(!b.TYPEREF.test(c))throw Error("illegal extend token: "+c);if(!this.proto3)throw Error("illegal field rule: "+c);this._parseMessageField(d,"optional",c);}return this.tn.omit(";"),a.messages.push(d),d},g.toString=function(){return "Parser at line "+this.tn.line},c.Parser=f,c}(e,e.Lang),e.Reflect=function(a){function k(b){if("string"==typeof b&&(b=a.TYPES[b]),"undefined"==typeof b.defaultValue)throw Error("default value for type "+b.name+" is not supported");return b==a.TYPES.bytes?new f(0):b.defaultValue}function l(b,c){if(b&&"number"==typeof b.low&&"number"==typeof b.high&&"boolean"==typeof b.unsigned&&b.low===b.low&&b.high===b.high)return new a.Long(b.low,b.high,"undefined"==typeof c?b.unsigned:c);if("string"==typeof b)return a.Long.fromString(b,c||!1,10);if("number"==typeof b)return a.Long.fromNumber(b,c||!1);throw Error("not convertible to Long")}function o(b,c){var d=c.readVarint32(),e=7&d,f=d>>>3;switch(e){case a.WIRE_TYPES.VARINT:do d=c.readUint8();while(128===(128&d));break;case a.WIRE_TYPES.BITS64:c.offset+=8;break;case a.WIRE_TYPES.LDELIM:d=c.readVarint32(),c.offset+=d;break;case a.WIRE_TYPES.STARTGROUP:o(f,c);break;case a.WIRE_TYPES.ENDGROUP:if(f===b)return !1;throw Error("Illegal GROUPEND after unknown group: "+f+" ("+b+" expected)");case a.WIRE_TYPES.BITS32:c.offset+=4;break;default:throw Error("Illegal wire type in unknown group "+b+": "+e)}return !0}var g,h,i,j,m,n,p,q,r,s,t,u,v,w,x,y,z,A,B,c={},d=function(a,b,c){this.builder=a,this.parent=b,this.name=c,this.className;},e=d.prototype;return e.fqn=function(){for(var a=this.name,b=this;;){if(b=b.parent,null==b)break;a=b.name+"."+a;}return a},e.toString=function(a){return (a?this.className+" ":"")+this.fqn()},e.build=function(){throw Error(this.toString(!0)+" cannot be built directly")},c.T=d,g=function(a,b,c,e,f){d.call(this,a,b,c),this.className="Namespace",this.children=[],this.options=e||{},this.syntax=f||"proto2";},h=g.prototype=Object.create(d.prototype),h.getChildren=function(a){var b,c,d;if(a=a||null,null==a)return this.children.slice();for(b=[],c=0,d=this.children.length;d>c;++c)this.children[c]instanceof a&&b.push(this.children[c]);return b},h.addChild=function(a){var b;if(b=this.getChild(a.name))if(b instanceof m.Field&&b.name!==b.originalName&&null===this.getChild(b.originalName))b.name=b.originalName;else{if(!(a instanceof m.Field&&a.name!==a.originalName&&null===this.getChild(a.originalName)))throw Error("Duplicate name in namespace "+this.toString(!0)+": "+a.name);a.name=a.originalName;}this.children.push(a);},h.getChild=function(a){var c,d,b="number"==typeof a?"id":"name";for(c=0,d=this.children.length;d>c;++c)if(this.children[c][b]===a)return this.children[c];return null},h.resolve=function(a,b){var g,d="string"==typeof a?a.split("."):a,e=this,f=0;if(""===d[f]){for(;null!==e.parent;)e=e.parent;f++;}do{do{if(!(e instanceof c.Namespace)){e=null;break}if(g=e.getChild(d[f]),!(g&&g instanceof c.T&&(!b||g instanceof c.Namespace))){e=null;break}e=g,f++;}while(fc;++c)e=b[c],e instanceof g&&(a[e.name]=e.build());return Object.defineProperty&&Object.defineProperty(a,"$options",{value:this.buildOpt()}),a},h.buildOpt=function(){var c,d,e,f,a={},b=Object.keys(this.options);for(c=0,d=b.length;d>c;++c)e=b[c],f=this.options[b[c]],a[e]=f;return a},h.getOption=function(a){return "undefined"==typeof a?this.options:"undefined"!=typeof this.options[a]?this.options[a]:null},c.Namespace=g,i=function(b,c,d,e){if(this.type=b,this.resolvedType=c,this.isMapKey=d,this.syntax=e,d&&a.MAP_KEY_TYPES.indexOf(b)<0)throw Error("Invalid map key type: "+b.name)},j=i.prototype,i.defaultFieldValue=k,j.verifyValue=function(c){var f,g,h,d=function(a,b){throw Error("Illegal value for "+this.toString(!0)+" of type "+this.type.name+": "+a+" ("+b+")")}.bind(this);switch(this.type){case a.TYPES.int32:case a.TYPES.sint32:case a.TYPES.sfixed32:return ("number"!=typeof c||c===c&&0!==c%1)&&d(typeof c,"not an integer"),c>4294967295?0|c:c;case a.TYPES.uint32:case a.TYPES.fixed32:return ("number"!=typeof c||c===c&&0!==c%1)&&d(typeof c,"not an integer"),0>c?c>>>0:c;case a.TYPES.int64:case a.TYPES.sint64:case a.TYPES.sfixed64:if(a.Long)try{return l(c,!1)}catch(e){d(typeof c,e.message);}else d(typeof c,"requires Long.js");case a.TYPES.uint64:case a.TYPES.fixed64:if(a.Long)try{return l(c,!0)}catch(e){d(typeof c,e.message);}else d(typeof c,"requires Long.js");case a.TYPES.bool:return "boolean"!=typeof c&&d(typeof c,"not a boolean"),c;case a.TYPES["float"]:case a.TYPES["double"]:return "number"!=typeof c&&d(typeof c,"not a number"),c;case a.TYPES.string:return "string"==typeof c||c&&c instanceof String||d(typeof c,"not a string"),""+c;case a.TYPES.bytes:return b.isByteBuffer(c)?c:b.wrap(c);case a.TYPES["enum"]:for(f=this.resolvedType.getChildren(a.Reflect.Enum.Value),h=0;h4294967295||0>c)&&d(typeof c,"not in range for uint32"),c;d(c,"not a valid enum value");case a.TYPES.group:case a.TYPES.message:if(c&&"object"==typeof c||d(typeof c,"object expected"),c instanceof this.resolvedType.clazz)return c;if(c instanceof a.Builder.Message){g={};for(h in c)c.hasOwnProperty(h)&&(g[h]=c[h]);c=g;}return new this.resolvedType.clazz(c)}throw Error("[INTERNAL] Illegal value for "+this.toString(!0)+": "+c+" (undefined type "+this.type+")")},j.calculateLength=function(b,c){if(null===c)return 0;var d;switch(this.type){case a.TYPES.int32:return 0>c?f.calculateVarint64(c):f.calculateVarint32(c);case a.TYPES.uint32:return f.calculateVarint32(c);case a.TYPES.sint32:return f.calculateVarint32(f.zigZagEncode32(c));case a.TYPES.fixed32:case a.TYPES.sfixed32:case a.TYPES["float"]:return 4;case a.TYPES.int64:case a.TYPES.uint64:return f.calculateVarint64(c);case a.TYPES.sint64:return f.calculateVarint64(f.zigZagEncode64(c));case a.TYPES.fixed64:case a.TYPES.sfixed64:return 8;case a.TYPES.bool:return 1;case a.TYPES["enum"]:return f.calculateVarint32(c);case a.TYPES["double"]:return 8;case a.TYPES.string:return d=f.calculateUTF8Bytes(c),f.calculateVarint32(d)+d;case a.TYPES.bytes:if(c.remaining()<0)throw Error("Illegal value for "+this.toString(!0)+": "+c.remaining()+" bytes remaining");return f.calculateVarint32(c.remaining())+c.remaining();case a.TYPES.message:return d=this.resolvedType.calculate(c),f.calculateVarint32(d)+d;case a.TYPES.group:return d=this.resolvedType.calculate(c),d+f.calculateVarint32(b<<3|a.WIRE_TYPES.ENDGROUP)}throw Error("[INTERNAL] Illegal value to encode in "+this.toString(!0)+": "+c+" (unknown type)")},j.encodeValue=function(b,c,d){var e,g;if(null===c)return d;switch(this.type){case a.TYPES.int32:0>c?d.writeVarint64(c):d.writeVarint32(c);break;case a.TYPES.uint32:d.writeVarint32(c);break;case a.TYPES.sint32:d.writeVarint32ZigZag(c);break;case a.TYPES.fixed32:d.writeUint32(c);break;case a.TYPES.sfixed32:d.writeInt32(c);break;case a.TYPES.int64:case a.TYPES.uint64:d.writeVarint64(c);break;case a.TYPES.sint64:d.writeVarint64ZigZag(c);break;case a.TYPES.fixed64:d.writeUint64(c);break;case a.TYPES.sfixed64:d.writeInt64(c);break;case a.TYPES.bool:"string"==typeof c?d.writeVarint32("false"===c.toLowerCase()?0:!!c):d.writeVarint32(c?1:0);break;case a.TYPES["enum"]:d.writeVarint32(c);break;case a.TYPES["float"]:d.writeFloat32(c);break;case a.TYPES["double"]:d.writeFloat64(c);break;case a.TYPES.string:d.writeVString(c);break;case a.TYPES.bytes:if(c.remaining()<0)throw Error("Illegal value for "+this.toString(!0)+": "+c.remaining()+" bytes remaining");e=c.offset,d.writeVarint32(c.remaining()),d.append(c),c.offset=e;break;case a.TYPES.message:g=(new f).LE(),this.resolvedType.encode(c,g),d.writeVarint32(g.offset),d.append(g.flip());break;case a.TYPES.group:this.resolvedType.encode(c,d),d.writeVarint32(b<<3|a.WIRE_TYPES.ENDGROUP);break;default:throw Error("[INTERNAL] Illegal value to encode in "+this.toString(!0)+": "+c+" (unknown type)")}return d},j.decode=function(b,c,d){if(c!=this.type.wireType)throw Error("Unexpected wire type for element");var e,f;switch(this.type){case a.TYPES.int32:return 0|b.readVarint32();case a.TYPES.uint32:return b.readVarint32()>>>0;case a.TYPES.sint32:return 0|b.readVarint32ZigZag();case a.TYPES.fixed32:return b.readUint32()>>>0;case a.TYPES.sfixed32:return 0|b.readInt32();case a.TYPES.int64:return b.readVarint64();case a.TYPES.uint64:return b.readVarint64().toUnsigned();case a.TYPES.sint64:return b.readVarint64ZigZag();case a.TYPES.fixed64:return b.readUint64();case a.TYPES.sfixed64:return b.readInt64();case a.TYPES.bool:return !!b.readVarint32();case a.TYPES["enum"]:return b.readVarint32();case a.TYPES["float"]:return b.readFloat();case a.TYPES["double"]:return b.readDouble();case a.TYPES.string:return b.readVString();case a.TYPES.bytes:if(f=b.readVarint32(),b.remaining()i;++i)this[e[i].name]=null;for(i=0,j=d.length;j>i;++i)k=d[i],this[k.name]=k.repeated?[]:k.map?new a.Map(k):null,!k.required&&"proto3"!==c.syntax||null===k.defaultValue||(this[k.name]=k.defaultValue);if(arguments.length>0)if(1!==arguments.length||null===b||"object"!=typeof b||!("function"!=typeof b.encode||b instanceof g)||Array.isArray(b)||b instanceof a.Map||f.isByteBuffer(b)||b instanceof ArrayBuffer||a.Long&&b instanceof a.Long)for(i=0,j=arguments.length;j>i;++i)"undefined"!=typeof(l=arguments[i])&&this.$set(d[i].name,l);else this.$set(b);},h=g.prototype=Object.create(a.Builder.Message.prototype);for(h.add=function(b,d,e){var f=c._fieldsByName[b];if(!e){if(!f)throw Error(this+"#"+b+" is undefined");if(!(f instanceof a.Reflect.Message.Field))throw Error(this+"#"+b+" is not a field: "+f.toString(!0));if(!f.repeated)throw Error(this+"#"+b+" is not a repeated field");d=f.verifyValue(d,!0);}return null===this[b]&&(this[b]=[]),this[b].push(d),this},h.$add=h.add,h.set=function(b,d,e){var f,g,h;if(b&&"object"==typeof b){e=d;for(f in b)b.hasOwnProperty(f)&&"undefined"!=typeof(d=b[f])&&this.$set(f,d,e);return this}if(g=c._fieldsByName[b],e)this[b]=d;else{if(!g)throw Error(this+"#"+b+" is not a field: undefined");if(!(g instanceof a.Reflect.Message.Field))throw Error(this+"#"+b+" is not a field: "+g.toString(!0));this[g.name]=d=g.verifyValue(d);}return g&&g.oneof&&(h=this[g.oneof.name],null!==d?(null!==h&&h!==g.name&&(this[h]=null),this[g.oneof.name]=g.name):h===b&&(this[g.oneof.name]=null)),this},h.$set=h.set,h.get=function(b,d){if(d)return this[b];var e=c._fieldsByName[b];if(!(e&&e instanceof a.Reflect.Message.Field))throw Error(this+"#"+b+" is not a field: undefined");if(!(e instanceof a.Reflect.Message.Field))throw Error(this+"#"+b+" is not a field: "+e.toString(!0));return this[e.name]},h.$get=h.get,i=0;ie;e++)if(h=this.children[e],h instanceof t||h instanceof m||h instanceof x){if(d.hasOwnProperty(h.name))throw Error("Illegal reflect child of "+this.toString(!0)+": "+h.toString(!0)+" cannot override static property '"+h.name+"'");d[h.name]=h.build();}else if(h instanceof m.Field)h.build(),this._fields.push(h),this._fieldsById[h.id]=h,this._fieldsByName[h.name]=h;else if(!(h instanceof m.OneOf||h instanceof w))throw Error("Illegal reflect child of "+this.toString(!0)+": "+this.children[e].toString(!0));return this.clazz=d},n.encode=function(a,b,c){var e,h,f,g,i,d=null;for(f=0,g=this._fields.length;g>f;++f)e=this._fields[f],h=a[e.name],e.required&&null===h?null===d&&(d=e):e.encode(c?h:e.verifyValue(h),b,a);if(null!==d)throw i=Error("Missing at least one required field for "+this.toString(!0)+": "+d),i.encoded=b,i;return b},n.calculate=function(a){for(var e,f,b=0,c=0,d=this._fields.length;d>c;++c){if(e=this._fields[c],f=a[e.name],e.required&&null===f)throw Error("Missing at least one required field for "+this.toString(!0)+": "+e);b+=e.calculate(f,a);}return b},n.decode=function(b,c,d){var g,h,i,j,e,f,k,l,m,n,p,q;for(c="number"==typeof c?c:-1,e=b.offset,f=new this.clazz;b.offset0;){if(g=b.readVarint32(),h=7&g,i=g>>>3,h===a.WIRE_TYPES.ENDGROUP){if(i!==d)throw Error("Illegal group end indicator for "+this.toString(!0)+": "+i+" ("+(d?d+" expected":"not a group")+")");break}if(j=this._fieldsById[i])j.repeated&&!j.options.packed?f[j.name].push(j.decode(h,b)):j.map?(l=j.decode(h,b),f[j.name].set(l[0],l[1])):(f[j.name]=j.decode(h,b),j.oneof&&(m=f[j.oneof.name],null!==m&&m!==j.name&&(f[m]=null),f[j.oneof.name]=j.name));else switch(h){case a.WIRE_TYPES.VARINT:b.readVarint32();break;case a.WIRE_TYPES.BITS32:b.offset+=4;break;case a.WIRE_TYPES.BITS64:b.offset+=8;break;case a.WIRE_TYPES.LDELIM:k=b.readVarint32(),b.offset+=k;break;case a.WIRE_TYPES.STARTGROUP:for(;o(i,b););break;default:throw Error("Illegal wire type for unknown field "+i+" in "+this.toString(!0)+"#decode: "+h)}}for(n=0,p=this._fields.length;p>n;++n)if(j=this._fields[n],null===f[j.name])if("proto3"===this.syntax)f[j.name]=j.defaultValue;else{if(j.required)throw q=Error("Missing at least one required field for "+this.toString(!0)+": "+j.name),q.decoded=f,q;a.populateDefaults&&null!==j.defaultValue&&(f[j.name]=j.defaultValue);}return f},c.Message=m,p=function(b,c,e,f,g,h,i,j,k,l){d.call(this,b,c,h),this.className="Message.Field",this.required="required"===e,this.repeated="repeated"===e,this.map="map"===e,this.keyType=f||null,this.type=g,this.resolvedType=null,this.id=i,this.options=j||{},this.defaultValue=null,this.oneof=k||null,this.syntax=l||"proto2",this.originalName=this.name,this.element=null,this.keyElement=null,!this.builder.options.convertFieldsToCamelCase||this instanceof m.ExtensionField||(this.name=a.Util.toCamelCase(this.name));},q=p.prototype=Object.create(d.prototype),q.build=function(){this.element=new i(this.type,this.resolvedType,!1,this.syntax),this.map&&(this.keyElement=new i(this.keyType,void 0,!0,this.syntax)),"proto3"!==this.syntax||this.repeated||this.map?"undefined"!=typeof this.options["default"]&&(this.defaultValue=this.verifyValue(this.options["default"])):this.defaultValue=i.defaultFieldValue(this.type);},q.verifyValue=function(b,c){var d,e,f;if(c=c||!1,d=function(a,b){throw Error("Illegal value for "+this.toString(!0)+" of type "+this.type.name+": "+a+" ("+b+")")}.bind(this),null===b)return this.required&&d(typeof b,"required"),"proto3"===this.syntax&&this.type!==a.TYPES.message&&d(typeof b,"proto3 field without field presence cannot be null"),null;if(this.repeated&&!c){for(Array.isArray(b)||(b=[b]),f=[],e=0;e0;case a.TYPES.bytes:return b.remaining()>0;case a.TYPES["enum"]:return 0!==b;case a.TYPES.message:return null!==b;default:return !0}},q.encode=function(b,c,d){var e,g,h,i,j;if(null===this.type||"object"!=typeof this.type)throw Error("[INTERNAL] Unresolved type in "+this.toString(!0)+": "+this.type);if(null===b||this.repeated&&0==b.length)return c;try{if(this.repeated)if(this.options.packed&&a.PACKABLE_WIRE_TYPES.indexOf(this.type.wireType)>=0){for(c.writeVarint32(this.id<<3|a.WIRE_TYPES.LDELIM),c.ensureCapacity(c.offset+=1),g=c.offset,e=0;e1&&(j=c.slice(g,c.offset),g+=i-1,c.offset=g,c.append(j)),c.writeVarint32(h,g-i);}else for(e=0;e=0){for(d+=f.calculateVarint32(this.id<<3|a.WIRE_TYPES.LDELIM),g=0,e=0;e=0&&!d){for(f=c.readVarint32(),f=c.offset+f,h=[];c.offset0;)if(l=k.readVarint32(),b=7&l,m=l>>>3,1===m)j=this.keyElement.decode(k,b,m);else{if(2!==m)throw Error("Unexpected tag in map field key/value submessage");e=this.element.decode(k,b,m);}return [j,e]}return this.element.decode(c,b,this.id)},c.Message.Field=p,r=function(a,b,c,d,e,f,g){p.call(this,a,b,c,null,d,e,f,g),this.extension;},r.prototype=Object.create(p.prototype),c.Message.ExtensionField=r,s=function(a,b,c){d.call(this,a,b,c),this.fields=[];},c.Message.OneOf=s,t=function(a,b,c,d,e){g.call(this,a,b,c,d,e),this.className="Enum",this.object=null;},t.getName=function(a,b){var e,d,c=Object.keys(a);for(d=0;de;++e)c[d[e]["name"]]=d[e]["id"];return Object.defineProperty&&Object.defineProperty(c,"$options",{value:this.buildOpt(),enumerable:!1}),this.object=c},c.Enum=t,v=function(a,b,c,e){d.call(this,a,b,c),this.className="Enum.Value",this.id=e;},v.prototype=Object.create(d.prototype),c.Enum.Value=v,w=function(a,b,c,e){d.call(this,a,b,c),this.field=e;},w.prototype=Object.create(d.prototype),c.Extension=w,x=function(a,b,c,d){g.call(this,a,b,c,d),this.className="Service",this.clazz=null;},y=x.prototype=Object.create(g.prototype),y.build=function(b){return this.clazz&&!b?this.clazz:this.clazz=function(a,b){var g,c=function(b){a.Builder.Service.call(this),this.rpcImpl=b||function(a,b,c){setTimeout(c.bind(this,Error("Not implemented, see: https://github.com/dcodeIO/ProtoBuf.js/wiki/Services")),0);};},d=c.prototype=Object.create(a.Builder.Service.prototype),e=b.getChildren(a.Reflect.Service.RPCMethod);for(g=0;g0;){if(b=e.pop(),!Array.isArray(b))throw Error("not a valid namespace: "+JSON.stringify(b));for(;b.length>0;){if(f=b.shift(),d.isMessage(f)){if(g=new c.Message(this,this.ptr,f.name,f.options,f.isGroup,f.syntax),h={},f.oneofs&&Object.keys(f.oneofs).forEach(function(a){g.addChild(h[a]=new c.Message.OneOf(this,g,a));},this),f.fields&&f.fields.forEach(function(a){if(null!==g.getChild(0|a.id))throw Error("duplicate or invalid field id in "+g.name+": "+a.id);if(a.options&&"object"!=typeof a.options)throw Error("illegal field options in "+g.name+"#"+a.name);var b=null;if("string"==typeof a.oneof&&!(b=h[a.oneof]))throw Error("illegal oneof in "+g.name+"#"+a.name+": "+a.oneof);a=new c.Message.Field(this,g,a.rule,a.keytype,a.type,a.name,a.id,a.options,b,f.syntax),b&&b.fields.push(a),g.addChild(a);},this),i=[],f.enums&&f.enums.forEach(function(a){i.push(a);}),f.messages&&f.messages.forEach(function(a){i.push(a);}),f.services&&f.services.forEach(function(a){i.push(a);}),f.extensions&&(g.extensions="number"==typeof f.extensions[0]?[f.extensions]:f.extensions),this.ptr.addChild(g),i.length>0){e.push(b),b=i,i=null,this.ptr=g,g=null;continue}i=null;}else if(d.isEnum(f))g=new c.Enum(this,this.ptr,f.name,f.options,f.syntax),f.values.forEach(function(a){g.addChild(new c.Enum.Value(this,g,a.name,a.id));},this),this.ptr.addChild(g);else if(d.isService(f))g=new c.Service(this,this.ptr,f.name,f.options),Object.keys(f.rpc).forEach(function(a){var b=f.rpc[a];g.addChild(new c.Service.RPCMethod(this,g,a,b.request,b.response,!!b.request_stream,!!b.response_stream,b.options));},this),this.ptr.addChild(g);else{if(!d.isExtend(f))throw Error("not a valid definition: "+JSON.stringify(f));if(g=this.ptr.resolve(f.ref,!0))f.fields.forEach(function(b){var d,e,f,h;if(null!==g.getChild(0|b.id))throw Error("duplicate extended field id in "+g.name+": "+b.id); if(g.extensions&&(d=!1,g.extensions.forEach(function(a){b.id>=a[0]&&b.id<=a[1]&&(d=!0);}),!d))throw Error("illegal extended field id in "+g.name+": "+b.id+" (not within valid ranges)");e=b.name,this.options.convertFieldsToCamelCase&&(e=a.Util.toCamelCase(e)),f=new c.Message.ExtensionField(this,g,b.rule,b.type,this.ptr.fqn()+"."+e,b.id,b.options),h=new c.Extension(this,this.ptr,b.name,f),f.extension=h,this.ptr.addChild(h),g.addChild(f);},this);else if(!/\.?google\.protobuf\./.test(f.ref))throw Error("extended message "+f.ref+" is not defined")}f=null,g=null;}b=null,this.ptr=this.ptr.parent;}return this.resolved=!1,this.result=null,this},e["import"]=function(b,c){var e,g,h,i,j,k,l,m,d="/";if("string"==typeof c){if(a.Util.IS_NODE,this.files[c]===!0)return this.reset();this.files[c]=!0;}else if("object"==typeof c){if(e=c.root,a.Util.IS_NODE,(e.indexOf("\\")>=0||c.file.indexOf("\\")>=0)&&(d="\\"),g=e+d+c.file,this.files[g]===!0)return this.reset();this.files[g]=!0;}if(b.imports&&b.imports.length>0){for(i=!1,"object"==typeof c?(this.importRoot=c.root,i=!0,h=this.importRoot,c=c.file,(h.indexOf("\\")>=0||c.indexOf("\\")>=0)&&(d="\\")):"string"==typeof c?this.importRoot?h=this.importRoot:c.indexOf("/")>=0?(h=c.replace(/\/[^\/]*$/,""),""===h&&(h="/")):c.indexOf("\\")>=0?(h=c.replace(/\\[^\\]*$/,""),d="\\"):h=".":h=null,j=0;j lastUnreadTime; if (isOtherSend && isCounted && isNotAdded && (hasChanged = true)) { storageConversation[SUB_KEY.UNREAD_COUNT] = storageConversation[SUB_KEY.UNREAD_COUNT] || 0; storageConversation[SUB_KEY.UNREAD_COUNT]++; storageConversation[SUB_KEY.UNREAD_LAST_TIME] = sentTime; } else if (isOtherSend && isRecall && hasContent) { var isRecallMsgNotRead = lastUnreadTime >= content.sentTime; if (isRecallMsgNotRead) { storageConversation[SUB_KEY.UNREAD_COUNT] = storageConversation[SUB_KEY.UNREAD_COUNT] || 0; storageConversation[SUB_KEY.UNREAD_COUNT]--; } } if (isOtherSend && isMentiond && hasContent && content.mentionedInfo && (hasChanged = true)) { storageConversation[SUB_KEY.HAS_MENTIOND] = true; storageConversation[SUB_KEY.MENTIOND_INFO] = content.mentionedInfo; } if (hasChanged) { var _key = self._getConversationKey({ type: type, targetId: targetId }); self._storage.set(_key, storageConversation); } var key = self._getConversationKey(message); var cacheConversation = self.updatedConversations[key] || {}; cacheConversation = common.fixConversationData(cacheConversation); var isMsgNotAdded = (cacheConversation.latestMessage.sentTime || 0) <= sentTime; if (isPersited && isMsgNotAdded) { cacheConversation = { type: type, targetId: targetId, latestMessage: message }; self.updatedConversations[key] = cacheConversation; } var isNotifyUpdate = utils.isUndefined(isLastInAPull) ? true : isLastInAPull; if (isNotifyUpdate) { self.update(); } }; _proto.get = function get(option) { var key = this._getConversationKey(option); return this._storage.get(key) || {}; }; _proto.getTotalUnreadCount = function getTotalUnreadCount() { var allVals = this._storage.getValues() || {}; var totalCount = 0; utils.forEach(allVals, function (val) { var count = val[SUB_KEY.UNREAD_COUNT] || 0; totalCount += count; }); return totalCount; }; _proto.read = function read(option) { var key = this._getConversationKey(option); var localConversation = this._storage.get(key) || {}; var localUnread = localConversation[SUB_KEY.UNREAD_COUNT]; if (localUnread) { this._storage.remove(key); var cacheConversation = this.updatedConversations[key]; if (cacheConversation) ; else { this.updatedConversations[key] = option; } this.update(); } }; return ConversationManager; }(); var CONVERSATION_SUB_KEY = STORAGE_CONVERSATION.SUB_KEY; var WebIMEngine = function () { function WebIMEngine(option) { this._option = void 0; this._user = void 0; this._naviManager = void 0; this._cmpManager = new CMPManager(); this._conversationManager = void 0; this._serverEngine = void 0; this._imEventEmitter = new utils.EventEmitter(); this._connectionStatus = CONNECTION_STATUS.DISCONNECTED; this._connectedDomain = void 0; this._networkDetecter = void 0; var self = this; var _imEventEmitter = self._imEventEmitter; var detect = option.detect; var serverEngine = new ServerEngine(option); serverEngine.watchStatus(function (status) { self._handleConnectionStatus(status); }); serverEngine.watchMessage(function (event) { var message = event.message, hasMore = event.hasMore, isLastInAPull = event.isLastInAPull; self._conversationManager.addMessage(message, { hasMore: hasMore, isLastInAPull: isLastInAPull }); _imEventEmitter.emit(IM_EVENT.MESSAGE, { message: message, hasMore: hasMore }); }); this._serverEngine = serverEngine; this._option = option; this._networkDetecter = new utils.NetworkDetecter(detect); } var _proto = WebIMEngine.prototype; _proto._handleConnectionStatus = function _handleConnectionStatus(status) { var _cmpManager = this._cmpManager, _naviManager = this._naviManager, _connectedDomain = this._connectedDomain; var isNeedUpdateCMPList = utils.isInclude(TRANSPORTER_STATUS_NEED_UPDATE_CMP, status); var isNeedReconnect = utils.isInclude(TRANSPORTER_STATUS_NEED_RECONNECT, status); if (isNeedUpdateCMPList) { _cmpManager.addInvalid(_connectedDomain); if (_cmpManager.isAllInvalid()) { _naviManager.clear(); _cmpManager.clearInvalid(); } } if (isNeedReconnect) { this.reconnect(); } var connectionStatus = TRANSPORTER_STATUS_TO_CONNECTION_STATUS[status] || status; this._connectionStatus = connectionStatus; this._imEventEmitter.emit(IM_EVENT.STATUS, { status: connectionStatus }); }; _proto._handleConnectError = function _handleConnectError(errorInfo) { var _user = this._user; var code = errorInfo.code || errorInfo.status; if (code === ERROR_INFO.CONN_REDIRECTED.code) { this._naviManager.clear(); return this.connect(_user); } console.log('throw error', errorInfo); this._connectionStatus = CONNECTION_STATUS.DISCONNECTED; return utils.Defer.reject(errorInfo); }; _proto.watch = function watch(watchers) { var statusWatcher = watchers.status, messageWatcher = watchers.message, conversationWatcher = watchers.conversation; this._imEventEmitter.on(IM_EVENT.STATUS, function (event) { statusWatcher && statusWatcher(event); }); this._imEventEmitter.on(IM_EVENT.MESSAGE, function (event) { messageWatcher && messageWatcher(event); }); this._imEventEmitter.on(IM_EVENT.CONVERSATION, function (event) { conversationWatcher && conversationWatcher(event); }); }; _proto.getConnectionStatus = function getConnectionStatus() { return this._connectionStatus; }; _proto.connect = function connect(user) { this._handleConnectionStatus(CONNECTION_STATUS.CONNECTING); var self = this; var _option = self._option, _serverEngine = self._serverEngine, _cmpManager = self._cmpManager, _imEventEmitter = self._imEventEmitter; var naviOpt = common.getNavReqOption(_option, user); var naviManager = new NaviManager(naviOpt); self._user = utils.copy(user); self._naviManager = naviManager; return naviManager.get().then(function (configForNavi) { var cmpDomainList = common.getCMPDomainList(configForNavi); _cmpManager.setDomainList(cmpDomainList); return _cmpManager.getFaster(); }).then(function (_ref) { var domain = _ref.domain; self._connectedDomain = domain; return _serverEngine.connect(user, { domain: domain }); }).then(function (connectUser) { self._conversationManager = new ConversationManager({ appkey: _option.appkey, userId: connectUser.userId, onChanged: function onChanged(updatedConversationList) { _imEventEmitter.emit(IM_EVENT.CONVERSATION, { updatedConversationList: updatedConversationList }); } }); return connectUser; }, function (error) { return self._handleConnectError(error); }); }; _proto.reconnect = function reconnect() { var self = this; var _user = self._user; if (utils.isUndefined(_user)) { return utils.Defer.reject(ERROR_INFO.NOT_CONNECTED); } return self._networkDetecter.start().then(function () { return self.connect(_user); }); }; _proto.disconnect = function disconnect() { this._handleConnectionStatus(CONNECTION_STATUS.DISCONNECTED); this._networkDetecter.stop(); return this._serverEngine.disconnect(); }; _proto.changeUser = function changeUser(user) { this.disconnect(); return this.connect(user); }; _proto.sendMessage = function sendMessage(conversation, option) { var self = this; return self._serverEngine.sendMessage(conversation, option).then(function (message) { self._conversationManager.addMessage(message); return message; }); }; _proto.recallMessage = function recallMessage(conversation, message, option) { var self = this; return self._serverEngine.recallMessage(conversation, message, option).then(function (message) { self._conversationManager.addMessage(message); return message; }); }; _proto.getConversationList = function getConversationList(option) { var isOldServer = this._option.isOldServer, _serverEngine = this._serverEngine, _conversationManager = this._conversationManager; var func = isOldServer ? _serverEngine.getOldConversationList : _serverEngine.getConversationList; return func.call(_serverEngine, option, { afterDecode: function afterDecode(conversation) { var localConversation = _conversationManager.get(conversation); conversation.unreadMessageCount = localConversation[CONVERSATION_SUB_KEY.UNREAD_COUNT] || 0; conversation.hasMentiond = localConversation[CONVERSATION_SUB_KEY.HAS_MENTIOND] || false; conversation.mentiondInfo = localConversation[CONVERSATION_SUB_KEY.MENTIOND_INFO]; return conversation; } }); }; _proto.removeConversation = function removeConversation(conversation) { var isOldServer = this._option.isOldServer, _serverEngine = this._serverEngine; var func = isOldServer ? _serverEngine.removeOldConversation : _serverEngine.removeConversation; return func.call(_serverEngine, conversation); }; _proto.removeConversationList = function removeConversationList(conversationList) { return this._serverEngine.removeConversationList(conversationList); }; _proto.getHistoryMessages = function getHistoryMessages(conversation, option) { return this._serverEngine.getHistoryMessages(conversation, option); }; _proto.deleteHistoryMessages = function deleteHistoryMessages(conversation, messages) { return this._serverEngine.deleteHistoryMessages(conversation, messages); }; _proto.clearHistoryMessages = function clearHistoryMessages(conversation, option) { return this._serverEngine.clearHistoryMessages(conversation, option); }; _proto.getTotalUnreadCount = function getTotalUnreadCount() { var isOldServer = this._option.isOldServer, _serverEngine = this._serverEngine; if (isOldServer) { var totalCount = this._conversationManager.getTotalUnreadCount(); return utils.Defer.resolve(totalCount); } else { return _serverEngine.getTotalUnreadCount(); } }; _proto.clearUnreadCount = function clearUnreadCount(conversation, option) { var isOldServer = this._option.isOldServer, _serverEngine = this._serverEngine; if (isOldServer) { this._conversationManager.read(conversation); return utils.Defer.resolve(); } else { return _serverEngine.clearUnreadCount(conversation, option); } }; _proto.joinChatRoom = function joinChatRoom(chrm, option) { return this._serverEngine.joinChatRoom(chrm, option); }; _proto.quitChatRoom = function quitChatRoom(chrm) { return this._serverEngine.quitChatRoom(chrm); }; _proto.getChatRoomInfo = function getChatRoomInfo(chrm, option) { return this._serverEngine.getChatRoomInfo(chrm, option); }; _proto.getChatRoomHistoryMessages = function getChatRoomHistoryMessages(chrm, option) { return this._serverEngine.getChatRoomHistoryMessages(chrm, option); }; return WebIMEngine; }(); var Engine = (function (imArg) { return new WebIMEngine(imArg); }); var execEngineByEvent = function execEngineByEvent(params, engine) { var _ENGINE_EVENT$WATCH$E; var event = params.event, args = params.args; args = args || []; var engineEvent = (_ENGINE_EVENT$WATCH$E = {}, _ENGINE_EVENT$WATCH$E[ENGINE_EVENT.WATCH] = engine.watch, _ENGINE_EVENT$WATCH$E[ENGINE_EVENT.CONNECT] = engine.connect, _ENGINE_EVENT$WATCH$E[ENGINE_EVENT.DISCONNECT] = engine.disconnect, _ENGINE_EVENT$WATCH$E[ENGINE_EVENT.RECONNECT] = engine.reconnect, _ENGINE_EVENT$WATCH$E[ENGINE_EVENT.CHANGE_USER] = engine.changeUser, _ENGINE_EVENT$WATCH$E[ENGINE_EVENT.GET_CONVERSATION_LIST] = engine.getConversationList, _ENGINE_EVENT$WATCH$E[ENGINE_EVENT.REMOVE_CONVERSATION] = engine.removeConversation, _ENGINE_EVENT$WATCH$E[ENGINE_EVENT.REMOVE_CONVERSATION_LIST] = engine.removeConversationList, _ENGINE_EVENT$WATCH$E[ENGINE_EVENT.GET_TOTAL_UNREAD_COUNT] = engine.getTotalUnreadCount, _ENGINE_EVENT$WATCH$E[ENGINE_EVENT.CLEAR_UNREAD_COUNT] = engine.clearUnreadCount, _ENGINE_EVENT$WATCH$E[ENGINE_EVENT.SEND_MESSAGE] = engine.sendMessage, _ENGINE_EVENT$WATCH$E[ENGINE_EVENT.RECALL_MESSAGE] = engine.recallMessage, _ENGINE_EVENT$WATCH$E[ENGINE_EVENT.GET_HISTORY_MSGS] = engine.getHistoryMessages, _ENGINE_EVENT$WATCH$E[ENGINE_EVENT.DELETE_MESSAGES] = engine.deleteHistoryMessages, _ENGINE_EVENT$WATCH$E[ENGINE_EVENT.CLEAR_MESSAGES] = engine.clearHistoryMessages, _ENGINE_EVENT$WATCH$E[ENGINE_EVENT.JOIN_CHATROOM] = engine.joinChatRoom, _ENGINE_EVENT$WATCH$E[ENGINE_EVENT.QUIT_CHATROOM] = engine.quitChatRoom, _ENGINE_EVENT$WATCH$E[ENGINE_EVENT.GET_CHATROOM_INFO] = engine.getChatRoomInfo, _ENGINE_EVENT$WATCH$E[ENGINE_EVENT.GET_CHATROOM_MSGS] = engine.getChatRoomHistoryMessages, _ENGINE_EVENT$WATCH$E)[event] || function () { return utils.Defer.reject(ERROR_INFO.SDK_INTERNAL_ERROR); }; return engineEvent.apply(engine, args); }; var EngineDispatcher = function () { function EngineDispatcher(option) { this._engine = void 0; this._engine = new Engine(option); } var _proto = EngineDispatcher.prototype; _proto.exec = function exec(params) { var event = params.event; var engine = this._engine; var connectionStatus = engine.getConnectionStatus(); var isNotConnected = connectionStatus !== CONNECTION_STATUS.CONNECTED; var isEventNeedConnected = utils.isInclude(ENGINE_EVENT_NEED_CONNECTED, event); if (isNotConnected && isEventNeedConnected) { return utils.Defer.reject(ERROR_INFO.NOT_CONNECTED); } var isConnecting = common.isConnected(connectionStatus) || common.isConnecting(connectionStatus); var isEventNeedDisconnected = utils.isInclude(ENGINE_EVENT_NEED_DISCONNECTED, event); if (isConnecting && isEventNeedDisconnected) { return utils.Defer.reject(ERROR_INFO.RC_CONNECTION_EXIST); } var execResult = execEngineByEvent(params, engine); return utils.isPromise(execResult) ? execResult["catch"](function (error) { console.log('SDK Error', error); var errorCode = error.status || error.code || error; var errorInfo = ERROR_CODE_TO_INFO[errorCode] || { code: errorCode }; var isValidErrorCode = utils.isNumberData(errorCode); if (!isValidErrorCode) { errorInfo = utils.extendInShallow(ERROR_INFO.SDK_INTERNAL_ERROR, { error: error }); } return utils.Defer.reject(errorInfo); }) : execResult; }; return EngineDispatcher; }(); var Type = function Type(name, validator) { var self = this; self.validate = validator; self.name = name; self.canBeNull = function () { self.validate = function (data) { return utils.isUndefined(data) || utils.isNull(data) || validator(data); }; return self; }; }; Type.isType = function (type) { return type instanceof Type; }; Type.String = new Type('String', utils.isString); Type.Number = new Type('Number', utils.isNumber); Type.Boolean = new Type('Boolean', utils.isBoolean); Type.Function = new Type('Function', utils.isFunction); Type.Object = new Type('Object', utils.isObject); Type.Array = new Type('Array', utils.isArray); var conversationType = common.getConversationTypeList().join('、'); Type.ConversationType = new Type(conversationType, common.isValidConversationType); var Struct = function () { function Struct(structure, funcName, paths) { if (paths === void 0) { paths = []; } if (!(this instanceof Struct)) { return new Struct(structure, funcName, paths); } var self = this; self.structure = structure; self.paths = paths; self.funcName = funcName; if (Type.isType(structure)) { self.validate = self._validateType; } else if (utils.isArray(structure)) { self.validate = self._validateArray; } else if (utils.isObject(structure)) { self.validate = self._validateObject; } else { self.validate = self._validateOther; } } var _proto = Struct.prototype; _proto._validateType = function _validateType(data) { var structure = this.structure; var isValid = structure.validate(data); return isValid ? this._getSuccess() : this._getError(data); }; _proto._validateArray = function _validateArray(data) { var structure = this.structure; if (utils.isEmpty(structure)) { return this._getSuccess(); } if (!utils.isArray(data)) { return this._getError(data); } var typer = structure[0]; for (var filed in data) { var val = data[filed]; var result = this._validateField(typer, filed, val); if (result.isError) { return result; } } return this._getSuccess(); }; _proto._validateObject = function _validateObject(data) { var structure = this.structure, paths = this.paths; data = data || {}; if (utils.isEmpty(structure)) { return this._getSuccess(); } if (!utils.isObject(data)) { return this._getError(data); } var checkedField = []; for (var filed in data) { var typer = structure[filed], val = data[filed]; var result = this._validateField(typer, filed, val); if (result.isError) { return result; } checkedField.push(filed); } for (var checkField in structure) { var _typer = structure[checkField]; var unCheckData = data[checkField]; if (!utils.isInclude(checkedField, checkField) && !_typer.validate(unCheckData)) { var errPaths = utils.copy(paths); errPaths.push(checkField); return this._getError(unCheckData, { paths: errPaths, expect: _typer.name }); } } return this._getSuccess(); }; _proto._validateOther = function _validateOther(data) { var self = this; var structure = self.structure; if (utils.isEqual(structure, data) || utils.isEmpty(structure)) { return self._getSuccess(); } else { return self._getError(data, { current: data, expect: structure }); } }; _proto._validateField = function _validateField(typer, filed, value) { var paths = this.paths, funcName = this.funcName; var newPaths = utils.copy(paths); newPaths.push(filed); return new Struct(typer, funcName, newPaths).validate(value); }; _proto._getError = function _getError(data, options) { if (options === void 0) { options = []; } var structure = this.structure, paths = this.paths, funcName = this.funcName; options = utils.extend({ current: data, expect: structure.name || utils.getTypeName(structure), paths: paths }, options); paths = options.paths; var _options = options, current = _options.current, expect = _options.expect; var param = utils.isEmpty(paths) ? 'param' : paths.join('.'); var currentType = utils.getTypeName(current); current = utils.toJSON(current) || current; current = current + "(" + currentType + ")"; var msg = utils.tplEngine(ERROR_INFO.PARAMETER_ERROR.msg, { param: param, expect: expect, current: current }); var info = { code: ERROR_INFO.PARAMETER_ERROR.code, funcName: funcName, msg: msg }; var jsonInfo = utils.toJSON(info); if (utils.isEmpty(funcName)) delete info[funcName]; return { isError: true, info: info, jsonInfo: jsonInfo }; }; _proto._getSuccess = function _getSuccess() { return { isError: false }; }; return Struct; }(); var validate = (function (struct, params, eventName) { return Struct(struct, eventName).validate(params); }); var NAVIGATORS = ['nav.cn.ronghub.com', 'nav2-cn.ronghub.com']; var NETWORK_DETECT_OPTION = { url: 'https://cdn.ronghub.com/im_detecting', intervalTime: 1500 }; var IM_OPTION = { connectType: CONNECT_TYPE.WEBSOCKET, navigators: NAVIGATORS, detect: NETWORK_DETECT_OPTION, isOldServer: true }; var GET_MESSAGES_OPTION = { count: 10, order: MESSAGS_TIME_ORDER.DESC, timestrap: 0 }; var SEND_MESSAGE_OPTION = { isMentiond: false, isCounted: true, isPersited: true }; var GET_CHATROOM_INFO_OPTION = { count: 20, order: CHATROOM_ORDER.DESC }; var JOIN_CHATROOM_OPTION = { count: -1 }; var SEND_MESSAGE_TYPE_OPTION = { 'RC:TxtMsg': { isCounted: true, isPersited: true }, 'RC:ImgMsg': { isCounted: true, isPersited: true }, 'RC:VcMsg': { isCounted: true, isPersited: true }, 'RC:ImgTextMsg': { isCounted: true, isPersited: true }, 'RC:FileMsg': { isCounted: true, isPersited: true }, 'RC:HQVCMsg': { isCounted: true, isPersited: true }, 'RC:LBSMsg': { isCounted: true, isPersited: true }, 'RC:PSImgTxtMsg': { isCounted: true, isPersited: true }, 'RC:PSMultiImgTxtMsg': { isCounted: true, isPersited: true }, 'RCJrmf:RpMsg': { isCounted: true, isPersited: true }, 'RCJrmf:RpOpendMsg': { isCounted: true, isPersited: true }, 'RC:CombineMsg': { isCounted: true, isPersited: true }, 'RC:InfoNtf': { isCounted: false, isPersited: true }, 'RC:ContactNtf': { isCounted: false, isPersited: true }, 'RC:ProfileNtf': { isCounted: false, isPersited: true }, 'RC:CmdNtf': { isCounted: false, isPersited: true }, 'RC:GrpNtf': { isCounted: false, isPersited: true }, 'RC:RcCmd': { isCounted: false, isPersited: true }, 'RC:CmdMsg': { isCounted: false, isPersited: false }, 'RC:TypSts': { isCounted: false, isPersited: false }, 'RC:PSCmd': { isCounted: false, isPersited: false }, 'RC:SRSMsg': { isCounted: false, isPersited: false }, 'RC:RRReqMsg': { isCounted: false, isPersited: false }, 'RC:RRRspMsg': { isCounted: false, isPersited: false }, 'RC:CsChaR': { isCounted: false, isPersited: false }, 'RC:CSCha': { isCounted: false, isPersited: false }, 'RC:CsEva': { isCounted: false, isPersited: false }, 'RC:CsContact': { isCounted: false, isPersited: false }, 'RC:CsHs': { isCounted: false, isPersited: false }, 'RC:CsHsR': { isCounted: false, isPersited: false }, 'RC:CsSp': { isCounted: false, isPersited: false }, 'RC:CsEnd': { isCounted: false, isPersited: false }, 'RC:CsUpdate': { isCounted: false, isPersited: false }, 'RC:ReadNtf': { isCounted: false, isPersited: false }, 'RC:chrmKVNotiMsg': { isCounted: false, isPersited: false }, 'RC:VCAccept': { isCounted: false, isPersited: false }, 'RC:VCRinging': { isCounted: false, isPersited: false }, 'RC:VCSummary': { isCounted: false, isPersited: false }, 'RC:VCHangup': { isCounted: false, isPersited: false }, 'RC:VCInvite': { isCounted: false, isPersited: false }, 'RC:VCModifyMedia': { isCounted: false, isPersited: false }, 'RC:VCModifyMem': { isCounted: false, isPersited: false } }; var Conversation = (function (_engineDispatcher) { var _temp; return _temp = function () { Conversation.create = function create(option) { return new Conversation(option); }; Conversation.get = function get(option) { return new Conversation(option); }; Conversation.merge = function merge(option) { var conversationList = option.conversationList, updatedConversationList = option.updatedConversationList; conversationList = updatedConversationList.concat(conversationList); conversationList = common.sortConversationList(conversationList); var hashTable = {}; var newList = []; utils.forEach(conversationList, function (conversation) { var type = conversation.type, targetId = conversation.targetId; var key = type + '_' + targetId; var hashItem = hashTable[key]; if (hashItem) { var index = hashItem.index, val = hashItem.val; val = utils.extend(conversation, val); newList[index] = val; hashTable[key].val = val; } else { newList.push(conversation); hashTable[key] = { index: newList.length - 1, val: conversation }; } }); return newList; }; Conversation.remove = function remove(option) { var _validate = validate({ type: Type.ConversationType, targetId: Type.String }, option, 'Conversation.remove'), isError = _validate.isError, info = _validate.info; if (isError) { return utils.Defer.reject(info); } return _engineDispatcher.exec({ event: ENGINE_EVENT.REMOVE_CONVERSATION, args: [option] }); }; Conversation.getList = function getList(option) { var _validate2 = validate({ count: Type.Number.canBeNull(), startTime: Type.Number.canBeNull() }, option, 'Conversation.getList'), isError = _validate2.isError, info = _validate2.info; if (isError) { return utils.Defer.reject(info); } return _engineDispatcher.exec({ event: ENGINE_EVENT.GET_CONVERSATION_LIST, args: [option] }); }; Conversation.getTotalUnreadCount = function getTotalUnreadCount() { return _engineDispatcher.exec({ event: ENGINE_EVENT.GET_TOTAL_UNREAD_COUNT }); }; function Conversation(option) { this.type = void 0; this.targetId = void 0; var _validate3 = validate({ type: Type.ConversationType, targetId: Type.String }, option, 'new Conversation'), isError = _validate3.isError, jsonInfo = _validate3.jsonInfo; if (isError) { return console.error(jsonInfo); } utils.extend(this, option); } var _proto = Conversation.prototype; _proto.send = function send(option) { var _validate4 = validate({ objectName: Type.String, content: Type.Object }, option, 'conversation.send'), isError = _validate4.isError, info = _validate4.info; if (isError) { return utils.Defer.reject(info); } var _option = option, objectName = _option.objectName; option = utils.extendInShallow(SEND_MESSAGE_TYPE_OPTION[objectName], option); option = utils.extendInShallow(SEND_MESSAGE_OPTION, option); return _engineDispatcher.exec({ event: ENGINE_EVENT.SEND_MESSAGE, args: [this, option] }); }; _proto.recall = function recall(message, option) { var _validate5 = validate({ sentTime: Type.Number, messageUId: Type.String }, message, 'conversation.recall'), isError = _validate5.isError, info = _validate5.info; if (isError) { return utils.Defer.reject(info); } return _engineDispatcher.exec({ event: ENGINE_EVENT.RECALL_MESSAGE, args: [this, message, option] }); }; _proto.read = function read(option) { return _engineDispatcher.exec({ event: ENGINE_EVENT.CLEAR_UNREAD_COUNT, args: [this, option] }); }; _proto.getMessages = function getMessages(option) { var _validate6 = validate({ order: Type.Number.canBeNull(), count: Type.Number.canBeNull(), timestrap: Type.Number.canBeNull() }, option, 'conversation.getMessages'), isError = _validate6.isError, info = _validate6.info; if (isError) { return utils.Defer.reject(info); } option = utils.extendInShallow(GET_MESSAGES_OPTION, option); return _engineDispatcher.exec({ event: ENGINE_EVENT.GET_HISTORY_MSGS, args: [this, option] }); }; _proto.deleteMessages = function deleteMessages(messages) { var _validate7 = validate([{ sentTime: Type.Number, messageUId: Type.String, direction: Type.Number }], messages, 'conversation.deleteMessages'), isError = _validate7.isError, info = _validate7.info; if (isError) { return utils.Defer.reject(info); } return _engineDispatcher.exec({ event: ENGINE_EVENT.DELETE_MESSAGES, args: [this, messages] }); }; _proto.clearMessages = function clearMessages(option) { var _validate8 = validate({ timestrap: Type.Number }, option, 'conversation.clearMessages'), isError = _validate8.isError, info = _validate8.info; if (isError) { return utils.Defer.reject(info); } return _engineDispatcher.exec({ event: ENGINE_EVENT.CLEAR_MESSAGES, args: [this, option] }); }; _proto.destory = function destory() { var conversation = this; return _engineDispatcher.exec({ event: ENGINE_EVENT.REMOVE_CONVERSATION, args: [conversation] }); }; return Conversation; }(), _temp; }); var ChatRoom = (function (_engineDispatcher) { var _temp; return _temp = function () { ChatRoom.get = function get(option) { return new ChatRoom(option); }; function ChatRoom(option) { this.id = void 0; var _validate = validate({ id: Type.String }, option, 'new ChatRoom'), isError = _validate.isError, jsonInfo = _validate.jsonInfo; if (isError) { return console.error(jsonInfo); } utils.extend(this, option); } var _proto = ChatRoom.prototype; _proto.join = function join(option) { var _validate2 = validate({ count: Type.Number.canBeNull() }, option, 'chatroom.join'), isError = _validate2.isError, info = _validate2.info; if (isError) { return utils.Defer.reject(info); } option = utils.extendInShallow(JOIN_CHATROOM_OPTION, option); return _engineDispatcher.exec({ event: ENGINE_EVENT.JOIN_CHATROOM, args: [this, option] }); }; _proto.quit = function quit() { return _engineDispatcher.exec({ event: ENGINE_EVENT.QUIT_CHATROOM, args: [this] }); }; _proto.getInfo = function getInfo(option) { var _validate3 = validate({ count: Type.Number.canBeNull(), order: Type.Number.canBeNull() }, option, 'chatroom.getInfo'), isError = _validate3.isError, info = _validate3.info; if (isError) { return utils.Defer.reject(info); } option = utils.extendInShallow(GET_CHATROOM_INFO_OPTION, option); return _engineDispatcher.exec({ event: ENGINE_EVENT.GET_CHATROOM_INFO, args: [this, option] }); }; _proto.send = function send(option) { var id = this.id; var _option = option, objectName = _option.objectName; var conversation = { type: CONVERSATION_TYPE.CHATROOM, targetId: id }; option = utils.extendInShallow(SEND_MESSAGE_TYPE_OPTION[objectName], option); return _engineDispatcher.exec({ event: ENGINE_EVENT.SEND_MESSAGE, args: [conversation, option] }); }; _proto.getMessages = function getMessages(option) { return _engineDispatcher.exec({ event: ENGINE_EVENT.GET_CHATROOM_MSGS, args: [this, option] }); }; return ChatRoom; }(), _temp; }); var IM = function () { function IM(option) { this._engineDispatcher = void 0; var _validate = validate({ appkey: Type.String }, option, 'RongIMLib.init'), isError = _validate.isError, jsonInfo = _validate.jsonInfo; if (isError) { throw Error(jsonInfo); } option = utils.extendInShallow(IM_OPTION, option); option.connectType = common.getConnectType(option); var engineHandler = new EngineDispatcher(option); this._engineDispatcher = engineHandler; var Modules = { Conversation: Conversation(engineHandler), ChatRoom: ChatRoom(engineHandler) }; utils.extend(this, Modules); } var _proto = IM.prototype; _proto.watch = function watch(watchers) { var _validate2 = validate({ conversation: Type.Function.canBeNull(), message: Type.Function.canBeNull(), status: Type.Function.canBeNull() }, watchers, 'im.watch'), isError = _validate2.isError, jsonInfo = _validate2.jsonInfo; if (isError) { return console.error(jsonInfo); } return this._engineDispatcher.exec({ event: ENGINE_EVENT.WATCH, args: [watchers] }); }; _proto.connect = function connect(user) { var _validate3 = validate({ token: Type.String }, user, 'im.connect'), isError = _validate3.isError, info = _validate3.info; if (isError) { return utils.Defer.reject(info); } return this._engineDispatcher.exec({ event: ENGINE_EVENT.CONNECT, args: [user] }); }; _proto.reconnect = function reconnect() { return this._engineDispatcher.exec({ event: ENGINE_EVENT.RECONNECT }); }; _proto.disconnect = function disconnect() { return this._engineDispatcher.exec({ event: ENGINE_EVENT.DISCONNECT }); }; _proto.changeUser = function changeUser(user) { var _validate4 = validate({ token: Type.String }, user, 'im.changeUser'), isError = _validate4.isError, info = _validate4.info; if (isError) { return utils.Defer.reject(info); } var self = this; return self.disconnect().then(function () { return self.connect(user); }); }; return IM; }(); var imInstance; var init = function init(option) { if (!imInstance) { imInstance = new IM(option); } return imInstance; }; var index = utils.extend({ init: init, env: env, common: common, ERROR_CODE: ERROR_CODE }, CONST); return index; }))); ================================================ FILE: api-test/lib/js/RongIMLib-3.0.3.js ================================================ /* * RongIMLib.js v3.0.3-dev * Release Date: Tue Jun 09 2020 15:21:33 GMT+0800 (China Standard Time) * Copyright 2020 RongCloud * Released under the MIT License. */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global.RongIMLib = factory()); }(this, (function () { 'use strict'; var versionToServer = "3.0.3"; var SDK_VERSION = versionToServer; var ERROR_INFO = { TIMEOUT: { code: -1, msg: 'Network timeout' }, SDK_INTERNAL_ERROR: { code: -2, msg: 'SDK internal error' }, PARAMETER_ERROR: { code: -3, msg: 'Please check the parameters, the {param} expected a value of {expect} but received {current}' }, REJECTED_BY_BLACKLIST: { code: 405, msg: 'Blacklisted by the other party' }, SEND_TOO_FAST: { code: 20604, msg: 'Sending messages too quickly' }, NOT_IN_GROUP: { code: 22406, msg: 'Not in group' }, FORBIDDEN_IN_GROUP: { code: 22408, msg: 'Forbbiden from speaking in the group' }, NOT_IN_CHATROOM: { code: 23406, msg: 'Not in chatRoom' }, FORBIDDEN_IN_CHATROOM: { code: 23408, msg: 'Forbbiden from speaking in the chatRoom' }, KICKED_FROM_CHATROOM: { code: 23409, msg: 'Kicked out and forbbiden from joining the chatRoom' }, CHATROOM_NOT_EXIST: { code: 23410, msg: 'ChatRoom does not exist' }, CHATROOM_IS_FULL: { code: 23411, msg: 'ChatRoom members exceeded' }, PARAMETER_INVALID_CHATROOM: { code: 23412, msg: 'Invalid chatRoom parameters' }, ROAMING_SERVICE_UNAVAILABLE_CHATROOM: { code: 23414, msg: 'ChatRoom message roaming service is not open, Please go to the developer to open this service' }, RECALLMESSAGE_PARAMETER_INVALID: { code: 25101, msg: 'Invalid recall message parameter' }, PUSHSETTING_PARAMETER_INVALID: { code: 26001, msg: 'Invalid push parameter' }, OPERATION_BLOCKED: { code: 20605, msg: 'Operation is blocked' }, OPERATION_NOT_SUPPORT: { code: 20606, msg: 'Operation is not supported' }, MSG_BLOCKED_SENSITIVE_WORD: { code: 21501, msg: 'The sent message contains sensitive words' }, REPLACED_SENSITIVE_WORD: { code: 21502, msg: 'Sensitive words in the message have been replaced' }, NOT_CONNECTED: { code: 30001, msg: 'Please connect successfully first' }, NAVI_REQUEST_ERROR: { code: 30007, msg: 'Navigation http request failed' }, CMP_REQUEST_ERROR: { code: 30010, msg: 'CMP sniff http request failed' }, CONN_APPKEY_FAKE: { code: 31002, msg: 'Your appkey is fake' }, CONN_MINI_SERVICE_NOT_OPEN: { code: 31003, msg: 'Mini program service is not open, Please go to the developer to open this service' }, CONN_TOKEN_INCORRECT: { code: 31004, msg: 'Your token is not valid or expired' }, CONN_NOT_AUTHRORIZED: { code: 31005, msg: 'AppKey and Token do not match' }, CONN_REDIRECTED: { code: 31006, msg: 'Connection redirection' }, CONN_APP_BLOCKED_OR_DELETED: { code: 31008, msg: 'AppKey is banned or deleted' }, CONN_USER_BLOCKED: { code: 31009, msg: 'User blocked' }, CONN_DOMAIN_INCORRECT: { code: 31012, msg: 'Connect domain error, Please check the set security domain' }, ROAMING_SERVICE_UNAVAILABLE: { code: 33007, msg: 'Roaming service cloud is not open, Please go to the developer to open this service' }, RC_CONNECTION_EXIST: { code: 34001, msg: 'Connection already exists' }, CHATROOM_KV_EXCEED: { code: 23423, msg: 'ChatRoom KV setting exceeds maximum' }, CHATROOM_KV_OVERWRITE_INVALID: { code: 23424, msg: 'ChatRoom KV already exists' }, CHATROOM_KV_STORE_NOT_OPEN: { code: 23426, msg: 'ChatRoom KV storage service is not open, Please go to the developer to open this service' }, CHATROOM_KEY_NOT_EXIST: { code: 23427, msg: 'ChatRoom key does not exist' } }; var ERROR_CODE = {}; var ERROR_CODE_TO_INFO = {}; for (var name$1 in ERROR_INFO) { var info = ERROR_INFO[name$1]; var code = info.code; ERROR_CODE[name$1] = code; ERROR_CODE[code] = name$1; ERROR_CODE_TO_INFO[code] = info; } var SERVER_ERROR_TO_CODE = { '1': ERROR_INFO.ROAMING_SERVICE_UNAVAILABLE.code }; var _CONNECT_SERVER_STATU, _SERVER_DISCONNECT_ST, _TRANSPORTER_STATUS_T; var NAVI_ERROR_INFO = { '401': ERROR_INFO.CONN_TOKEN_INCORRECT, '403': ERROR_INFO.CONN_APPKEY_FAKE }; var CONNECTION_STATUS = { CONNECTED: 0, CONNECTING: 1, DISCONNECTED: 2, NETWORK_UNAVAILABLE: 3, SOCKET_ERROR: 4, KICKED_OFFLINE_BY_OTHER_CLIENT: 6, BLOCKED: 12 }; var SERVER_DISCONNECT_STATUS = { KICKED_OFFLINE_BY_OTHER_CLIENT: 1, BLOCKED: 2 }; var CONNECT_SERVER_STATUS = { IDENTIFIER_REJECTED: 2, CONN_MINI_SERVICE_NOT_OPEN: 3, TOKEN_INCORRECT: 4, NOT_AUTHORIZED: 5, REDIRECT: 6, PACKAGE_ERROR: 7, APP_BLOCK_OR_DELETE: 8, BLOCK: 9, TOKEN_EXPIRE: 10, DEVICE_ERROR: 11, DOMAIN_INCORRECT: 12 }; var CONNECT_SERVER_STATUS_MAP_ERROR_INFO = (_CONNECT_SERVER_STATU = {}, _CONNECT_SERVER_STATU[CONNECT_SERVER_STATUS.IDENTIFIER_REJECTED] = ERROR_INFO.CONN_APPKEY_FAKE, _CONNECT_SERVER_STATU[CONNECT_SERVER_STATUS.CONN_MINI_SERVICE_NOT_OPEN] = ERROR_INFO.CONN_MINI_SERVICE_NOT_OPEN, _CONNECT_SERVER_STATU[CONNECT_SERVER_STATUS.TOKEN_INCORRECT] = ERROR_INFO.CONN_TOKEN_INCORRECT, _CONNECT_SERVER_STATU[CONNECT_SERVER_STATUS.NOT_AUTHORIZED] = ERROR_INFO.CONN_NOT_AUTHRORIZED, _CONNECT_SERVER_STATU[CONNECT_SERVER_STATUS.REDIRECT] = ERROR_INFO.CONN_REDIRECTED, _CONNECT_SERVER_STATU[CONNECT_SERVER_STATUS.APP_BLOCK_OR_DELETE] = ERROR_INFO.CONN_APP_BLOCKED_OR_DELETED, _CONNECT_SERVER_STATU[CONNECT_SERVER_STATUS.BLOCK] = ERROR_INFO.CONN_USER_BLOCKED, _CONNECT_SERVER_STATU[CONNECT_SERVER_STATUS.TOKEN_EXPIRE] = ERROR_INFO.CONN_TOKEN_INCORRECT, _CONNECT_SERVER_STATU[CONNECT_SERVER_STATUS.DOMAIN_INCORRECT] = ERROR_INFO.CONN_DOMAIN_INCORRECT, _CONNECT_SERVER_STATU); var TRANSPORTER_STATUS = { CONNECTED: CONNECTION_STATUS.CONNECTED, KICKED_OFFLINE_BY_OTHER_CLIENT: CONNECTION_STATUS.KICKED_OFFLINE_BY_OTHER_CLIENT, BLOCKED: CONNECTION_STATUS.BLOCKED, CLOSE_NORMAL: 1000, CLOSE_GOING_AWAY: 1001, CLOSE_PROTOCOL_ERROR: 1002, CLOSE_UNSUPPORTED: 1003, CLOSE_NO_STATUS: 1005, CLOSE_ABNORMAL: 1006, UNSUPPORTED_DATA: 1007, POLICY_VIOLATION: 1008, CLOSE_TOO_LARGE: 1009, MISSING_EXTENSION: 1010, INTERNAL_ERROR: 1011, SERVICE_RESTART: 1012, TRY_AGAIN_LATER: 1013, TSL_HANDSHAKE: 1015, PING_FIRST_TIMEOUT: 2001, PING_TIMEOUT: 2002, DISCONNECT_TOO_FAST: 2003, EXCEED_MESSAGE_ID_LIMIT: 2004, COMET_REQUEST_ERROR: 2005, MINI_URL_NOT_IN_DOMAIN_LIST: 2006 }; var MINI_ERROR_MSG_TO_STATUS = { 'url not in domain list': TRANSPORTER_STATUS.MINI_URL_NOT_IN_DOMAIN_LIST }; var SERVER_DISCONNECT_STATUS_TO_TRANSPORTER_STATUS = (_SERVER_DISCONNECT_ST = {}, _SERVER_DISCONNECT_ST[SERVER_DISCONNECT_STATUS.KICKED_OFFLINE_BY_OTHER_CLIENT] = TRANSPORTER_STATUS.KICKED_OFFLINE_BY_OTHER_CLIENT, _SERVER_DISCONNECT_ST[SERVER_DISCONNECT_STATUS.BLOCKED] = TRANSPORTER_STATUS.BLOCKED, _SERVER_DISCONNECT_ST); var TRANSPORTER_STATUS_NEED_UPDATE_CMP = [TRANSPORTER_STATUS.CLOSE_NORMAL, TRANSPORTER_STATUS.CLOSE_GOING_AWAY, TRANSPORTER_STATUS.CLOSE_PROTOCOL_ERROR, TRANSPORTER_STATUS.CLOSE_UNSUPPORTED, TRANSPORTER_STATUS.UNSUPPORTED_DATA, TRANSPORTER_STATUS.POLICY_VIOLATION, TRANSPORTER_STATUS.MISSING_EXTENSION, TRANSPORTER_STATUS.INTERNAL_ERROR, TRANSPORTER_STATUS.SERVICE_RESTART, TRANSPORTER_STATUS.TRY_AGAIN_LATER, TRANSPORTER_STATUS.TSL_HANDSHAKE, TRANSPORTER_STATUS.PING_FIRST_TIMEOUT, TRANSPORTER_STATUS.DISCONNECT_TOO_FAST, TRANSPORTER_STATUS.COMET_REQUEST_ERROR]; var TRANSPORTER_STATUS_NEED_RECONNECT = TRANSPORTER_STATUS_NEED_UPDATE_CMP.concat([TRANSPORTER_STATUS.PING_TIMEOUT, TRANSPORTER_STATUS.CLOSE_ABNORMAL, TRANSPORTER_STATUS.EXCEED_MESSAGE_ID_LIMIT, TRANSPORTER_STATUS.COMET_REQUEST_ERROR]); var TRANSPORTER_STATUS_TO_CONNECTION_STATUS = (_TRANSPORTER_STATUS_T = {}, _TRANSPORTER_STATUS_T[TRANSPORTER_STATUS.CLOSE_GOING_AWAY] = CONNECTION_STATUS.SOCKET_ERROR, _TRANSPORTER_STATUS_T[TRANSPORTER_STATUS.CLOSE_PROTOCOL_ERROR] = CONNECTION_STATUS.SOCKET_ERROR, _TRANSPORTER_STATUS_T[TRANSPORTER_STATUS.CLOSE_UNSUPPORTED] = CONNECTION_STATUS.SOCKET_ERROR, _TRANSPORTER_STATUS_T[TRANSPORTER_STATUS.CLOSE_NO_STATUS] = CONNECTION_STATUS.DISCONNECTED, _TRANSPORTER_STATUS_T[TRANSPORTER_STATUS.CLOSE_ABNORMAL] = CONNECTION_STATUS.NETWORK_UNAVAILABLE, _TRANSPORTER_STATUS_T[TRANSPORTER_STATUS.DISCONNECT_TOO_FAST] = CONNECTION_STATUS.NETWORK_UNAVAILABLE, _TRANSPORTER_STATUS_T[TRANSPORTER_STATUS.UNSUPPORTED_DATA] = CONNECTION_STATUS.SOCKET_ERROR, _TRANSPORTER_STATUS_T[TRANSPORTER_STATUS.POLICY_VIOLATION] = CONNECTION_STATUS.SOCKET_ERROR, _TRANSPORTER_STATUS_T[TRANSPORTER_STATUS.CLOSE_TOO_LARGE] = CONNECTION_STATUS.SOCKET_ERROR, _TRANSPORTER_STATUS_T[TRANSPORTER_STATUS.MISSING_EXTENSION] = CONNECTION_STATUS.SOCKET_ERROR, _TRANSPORTER_STATUS_T[TRANSPORTER_STATUS.INTERNAL_ERROR] = CONNECTION_STATUS.SOCKET_ERROR, _TRANSPORTER_STATUS_T[TRANSPORTER_STATUS.SERVICE_RESTART] = CONNECTION_STATUS.SOCKET_ERROR, _TRANSPORTER_STATUS_T[TRANSPORTER_STATUS.TRY_AGAIN_LATER] = CONNECTION_STATUS.SOCKET_ERROR, _TRANSPORTER_STATUS_T[TRANSPORTER_STATUS.TSL_HANDSHAKE] = CONNECTION_STATUS.SOCKET_ERROR, _TRANSPORTER_STATUS_T[TRANSPORTER_STATUS.PING_FIRST_TIMEOUT] = CONNECTION_STATUS.NETWORK_UNAVAILABLE, _TRANSPORTER_STATUS_T[TRANSPORTER_STATUS.PING_TIMEOUT] = CONNECTION_STATUS.NETWORK_UNAVAILABLE, _TRANSPORTER_STATUS_T[TRANSPORTER_STATUS.COMET_REQUEST_ERROR] = CONNECTION_STATUS.NETWORK_UNAVAILABLE, _TRANSPORTER_STATUS_T); var CONNECT_TYPE = { COMET: 'comet', WEBSOCKET: 'websocket' }; var CONVERSATION_TYPE = { PRIVATE: 1, GROUP: 3, CHATROOM: 4, CUSTOMER_SERVICE: 5, SYSTEM: 6, RTC_ROOM: 12 }; var MESSAGE_DIRECTION = { SEND: 1, RECEIVE: 2 }; var MESSAGS_TIME_ORDER = { DESC: 0, ASC: 1 }; var CHATROOM_ORDER = { ASC: 1, DESC: 2 }; var RECALL_MESSAGE_TYPE = 'RC:RcCmd'; var MENTIOND_TYPE = { ALL: 1, SINGAL: 2 }; var MESSAGE_TYPE = { TEXT: 'RC:TxtMsg', VOICE: 'RC:VcMsg', HQ_VOICE: 'RC:HQVCMsg', IMAGE: 'RC:ImgMsg', GIF: 'RC:GIFMsg', RICH_CONTENT: 'RC:ImgTextMsg', LOCATION: 'RC:LBSMsg', FILE: 'RC:FileMsg', SIGHT: 'RC:SightMsg', COMBINE: 'RC:CombineMsg', CHRM_KV_NOTIFY: 'RC:chrmKVNotiMsg', LOG_COMMAND: 'RC:LogCmdMsg' }; var RTC_API_TYPE = { ROOM: 1, PERSON: 2 }; var FILE_TYPE = { IMAGE: 1, AUDIO: 2, VIDEO: 3, FILE: 4 }; var CHATROOM_ENTRY_TYPE = { UPDATE: 1, DELETE: 2 }; var product = { CONNECT_TYPE: CONNECT_TYPE, CONNECTION_STATUS: CONNECTION_STATUS, CONVERSATION_TYPE: CONVERSATION_TYPE, MESSAGE_DIRECTION: MESSAGE_DIRECTION, MESSAGS_TIME_ORDER: MESSAGS_TIME_ORDER, CHATROOM_ORDER: CHATROOM_ORDER, RECALL_MESSAGE_TYPE: RECALL_MESSAGE_TYPE, MESSAGE_TYPE: MESSAGE_TYPE, MENTIOND_TYPE: MENTIOND_TYPE, SDK_VERSION: SDK_VERSION, FILE_TYPE: FILE_TYPE }; var IM_TIMEOUT = 30000; var IM_PING_INTERVAL_TIME = 30000; var IM_COMET_PULLMSG_TIMEOUT = 45000; var IM_PING_MAX_TIMEOUT = 6000; var IM_PING_MIN_TIMEOUT = 2000; var HTTP_TIMEOUT = 60000; var PULL_MSG_TIME = 180000; var NAVI_EXPIRED_TIME = 7200000; var CMP_SNIFF_INTERNAL_TIME = 1000; var FIRST_PING_TIMEOUT = 1000; var NAVI_REQUEST_SUCCESS_CODE = 200; var NAVI_SEPARATOR_IN_TOKEN = '@'; var DOMAIN_SEPARATOR_IN_NAVLIST = ';'; var DOMAIN_SEPARATOR_IN_CMPLIST = ','; var MAX_SINGAL_ID = 65535; var MINIMUM_CONNECT_DURATION = 5000; var CHATROOM_KEY_LENGTH = { MAX: 128, MIN: 1 }; var CHATROOM_VALUE_LENGTH = { MAX: 4096, MIN: 1 }; var TYPE_HAS_CONVERSATION = [CONVERSATION_TYPE.PRIVATE, CONVERSATION_TYPE.GROUP, CONVERSATION_TYPE.SYSTEM]; var PLATFORM = { WEB: 'web', WX: 'wx', ZFB: 'zfb', TT: 'tt', BAIDU: 'baidu', QUICK_APP: 'quick_app' }; var REQUEST_METHOD = { POST: 'post', GET: 'get' }; var STORAGE_ROOT_KEY = 'rc-'; var STORAGE_DEVICE_ID_KEY = STORAGE_ROOT_KEY + 'deviceId'; var STORAGE_SESSION_ID_KEY = STORAGE_ROOT_KEY + 'sessionId'; var STORAGE_NAVI = { ROOT_KEY_TPL: 'nav-{appkey}-{UID}', SUB_KEY: { CONNECT_TYPE: 'connettype', TIME_WHEN_SAVED: 'time', RESPONSE: 'resp' } }; var STORAGE_SYNC_TIME = { ROOT_KEY_TPL: 'sync-{appkey}-{userId}', SUB_KEY: { SENDBOX: 'send', INBOX: 'in' } }; var STORAGE_CONVERSATION = { ROOT_KEY_TPL: 'con-{appkey}-{userId}', SUB_KEY: { ROOT_TPL: '{type}-{id}', UNREAD_COUNT: 'c', UNREAD_LAST_TIME: 't', HAS_MENTIOND: 'hm', MENTIOND_INFO: 'm' } }; var HTTP_PROTOCOL = { HTTP: 'http:', HTTPS: 'https:', FILE: 'file:' }; var WS_PROTOCOL = { WSS: 'wss:', WS: 'ws:' }; var NAVI_CALLBACK_NAME = 'getServerEndpoint'; var NAVI_TYPE = { COMET: 'cometnavi', WEBSOCKET: 'navi' }; var NAVI_URL_TPL = '{url}/{type}.js?appId={appkey}&token={token}&callBack=' + NAVI_CALLBACK_NAME + '&r={random}&v=' + SDK_VERSION; var CMP_URL_TPL = '{protocol}//{domain}/websocket?appId={appkey}&token={token}&apiVer={apiVer}&sdkVer=' + SDK_VERSION; var MINI_CMP_URL_TPL = '{protocol}//{domain}/websocket?appId={appkey}&token={token}&apiVer={apiVer}&sdkVer=' + SDK_VERSION + '&platform={platform}'; var COMET_REQ_HAS_TOPIC_URL_TPL = '{protocol}//{domain}/websocket?messageid={messageId}&header={headerCode}&sessionid={sessionId}&topic={topic}&targetid={targetId}&pid={pid}'; var COMET_REQ_NO_TOPIC_URL_TPL = '{protocol}//{domain}/websocket?messageid={messageId}&header={headerCode}&sessionid={sessionId}&pid={pid}'; var COMET_PULL_URL_TPL = '{protocol}//{domain}/pullmsg.js?sessionid={sessionId}×trap={timestamp}&pid={pid}'; var TIMER_TYPE = { INTERVAL: 'interval', TIMEOUT: 'timeout' }; var TIMER_STATUS = { PENNDING: 'pendding', BUSY: 'busy', ENDING: 'ending' }; var PLATFORM_TYPE = { MINI: 'Miniprogram', WEB: 'Web' }; var UnKown = 'UnKown'; var isMiniEnv = function isMiniEnv(global) { return global !== window; }; var hasMiniBaseEvent = function hasMiniBaseEvent(miniGlobal) { var baseMiniEventNames = ['canIUse', 'getSystemInfo']; for (var i = 0, max = baseMiniEventNames.length; i < max; i++) { var baseEventName = baseMiniEventNames[i]; if (!miniGlobal[baseEventName]) { return false; } } return true; }; var getEnvInfo = function getEnvInfo() { if (typeof wx !== 'undefined' && hasMiniBaseEvent(wx)) { return { platform: PLATFORM.WX, global: wx }; } else if (typeof swan !== 'undefined' && hasMiniBaseEvent(swan)) { return { platform: PLATFORM.BAIDU, global: swan }; } else if (typeof tt !== 'undefined' && hasMiniBaseEvent(tt)) { return { platform: PLATFORM.TT, global: tt }; } else if (typeof my !== 'undefined' && hasMiniBaseEvent(my)) { return { platform: PLATFORM.ZFB, global: my }; } else { return { platform: PLATFORM.WEB, global: window }; } }; var getWebSystemInfo = function getWebSystemInfo() { var userAgent = navigator.userAgent; var version, type; var condition = { IE: /rv:([\d.]+)\) like Gecko|MSIE ([\d.]+)/, Edge: /Edge\/([\d.]+)/, Firefox: /Firefox\/([\d.]+)/, Opera: /(?:OPERA|OPR).([\d.]+)/, WeiXin: /MicroMessenger\/([\d.]+)/, QQBrowser: /QQBrowser\/([\d.]+)/, Chrome: /Chrome\/([\d.]+)/, Safari: /Version\/([\d.]+).*Safari/ }; for (var key in condition) { if (!condition.hasOwnProperty(key)) continue; var browserContent = userAgent.match(condition[key]); if (browserContent) { type = key; version = browserContent[1] || browserContent[2]; break; } } return { model: type || UnKown, version: version || UnKown }; }; var getMiniSystemInfo = function getMiniSystemInfo(global) { var systemInfo = global.getSystemInfoSync() || {}; var model = systemInfo.model, brand = systemInfo.brand; if (model && brand) { model = model + ' ' + brand; } systemInfo.model = model; return systemInfo; }; var getProtocol = function getProtocol(global) { var location = global.location || {}; var isHttp = location.protocol === HTTP_PROTOCOL.HTTP || location.protocol === HTTP_PROTOCOL.FILE; var protocol = { http: isHttp ? HTTP_PROTOCOL.HTTP : HTTP_PROTOCOL.HTTPS, ws: WS_PROTOCOL.WSS }; if (isHttp) { protocol.ws = WS_PROTOCOL.WS; } return protocol; }; var adaptGlobalObjectCreate = function adaptGlobalObjectCreate(global, isMini) { if (!isMini && !global.Object.create) { global.Object.create = function (o, properties) { if (typeof o !== 'object' && typeof o !== 'function') throw new TypeError('Object prototype may only be an Object: ' + o);else if (o === null) throw new Error('This browser\'s implementation of Object.create is a shim and doesn\'t support \'null\' as the first argument.'); if (typeof properties !== 'undefined') throw new Error('This browser\'s implementation of Object.create is a shim and doesn\'t support a second argument.'); function F() {} F.prototype = o; return new F(); }; } }; var getMiniGlobal = function getMiniGlobal(global) { return Object.assign(global, { JSON: JSON, Promise: Promise, setTimeout: setTimeout, setInterval: setInterval, encodeURIComponent: encodeURIComponent, clearTimeout: function (_clearTimeout) { function clearTimeout(_x) { return _clearTimeout.apply(this, arguments); } clearTimeout.toString = function () { return _clearTimeout.toString(); }; return clearTimeout; }(function (id) { clearTimeout(id); }), clearInterval: function (_clearInterval) { function clearInterval(_x2) { return _clearInterval.apply(this, arguments); } clearInterval.toString = function () { return _clearInterval.toString(); }; return clearInterval; }(function (id) { clearInterval(id); }) }); }; var envInfo = getEnvInfo(); var platform = envInfo.platform, global$1 = envInfo.global; var isMini = isMiniEnv(global$1); var protocol = getProtocol(global$1); var system = isMini ? getMiniSystemInfo(global$1) : getWebSystemInfo(); system.name = platform; adaptGlobalObjectCreate(global$1, isMini); global$1 = isMini ? getMiniGlobal(global$1) : global$1; var env = { global: global$1, system: system, isMini: isMini, protocol: protocol }; var global$2 = env.global, system$1 = env.system; var isZFB = system$1.name === PLATFORM.ZFB; var ZFBStorage = function () { function ZFBStorage() {} var _proto = ZFBStorage.prototype; _proto.set = function set(key, value) { global$2.setStorageSync({ key: key, data: value }); }; _proto.get = function get(key) { return global$2.getStorageSync({ key: key }); }; _proto.remove = function remove(key) { return global$2.removeStorageSync({ key: key }); }; _proto.getKeys = function getKeys() { var res = my.getStorageInfoSync(); return res.keys; }; return ZFBStorage; }(); var MiniStorage = function () { function MiniStorage() {} var _proto2 = MiniStorage.prototype; _proto2.set = function set(key, value) { global$2.setStorageSync(key, value); }; _proto2.get = function get(key) { try { return global$2.getStorageSync(key); } catch (e) { return null; } }; _proto2.remove = function remove(key) { try { return global$2.removeStorageSync(key); } catch (e) { return null; } }; _proto2.getKeys = function getKeys() { try { var res = global$2.getStorageInfoSync(); return res.keys; } catch (e) { return []; } }; return MiniStorage; }(); var storage = isZFB ? ZFBStorage : MiniStorage; var JSON$1 = { parse: function parse(sJSON) { return new Function('', 'return (' + sJSON + ')')(); }, stringify: function stringify(value) { return JSON$1.str('', { '': value }); }, str: function str(key, holder) { var i, k, v, length, partial, value = holder[key], self = JSON$1; if (value && typeof value === 'object' && typeof value.toJSON === 'function') { value = value.toJSON(key); } switch (typeof value) { case 'string': return self.quote(value); case 'number': return isFinite(value) ? String(value) : 'null'; case 'boolean': return String(value); case 'object': if (!value) { return 'null'; } partial = []; if (Object.prototype.toString.apply(value) === '[object Array]') { length = value.length; for (i = 0; i < length; i += 1) { partial[i] = self.str(i, value) || 'null'; } v = partial.length === 0 ? '[]' : '[' + partial.join(',') + ']'; return v; } for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = self.str(k, value); if (v) { partial.push(self.quote(k) + ':' + v); } } } v = partial.length === 0 ? '{}' : '{' + partial.join(',') + '}'; return v; } }, quote: function quote(string) { var self = JSON$1; self.rx_escapable.lastIndex = 0; return self.rx_escapable.test(string) ? '"' + string.replace(self.rx_escapable, function (a) { var c = self.meta[a]; return typeof c === 'string' ? c : "\\u" + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }) + '"' : '"' + string + '"'; }, rx_escapable: new RegExp("[\\\"\\\\\"\0-\x1F\x7F-\x9F\xAD\u0600-\u0604\u070F\u17B4\u17B5\u200C-\u200F\u2028-\u202F\u2060-\u206F\uFEFF\uFFF0-\uFFFF]", 'g'), meta: { '\b': '\\b', ' ': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"': '\\"', '\'\'': '\\\'\'', '\\': '\\\\' } }; var CacheStorage = function () { function CacheStorage(values) { this.caches = {}; if (values) { this.caches = values; } } var _proto = CacheStorage.prototype; _proto.set = function set(key, value) { this.caches[key] = value; }; _proto.remove = function remove(key) { var val = this.get(key); delete this.caches[key]; return val; }; _proto.get = function get(key) { return this.caches[key]; }; _proto.getKeys = function getKeys() { var keys = []; for (var key in this.caches) { keys.push(key); } return keys; }; return CacheStorage; }(); var global$3 = env.global; var TEST_KEY = 'RC_TEST_KEY'; var TEST_VALUE = 'RC_TEST_VALUE'; var isSupportLocalStorage = function isSupportLocalStorage() { var isSupport = false; var localStorage = global$3.localStorage; if (localStorage) { try { localStorage.setItem(TEST_KEY, TEST_VALUE); var testVal = localStorage.getItem(TEST_KEY); if (testVal === TEST_VALUE) { isSupport = true; } localStorage.removeItem(TEST_KEY); } catch (e) {} } return isSupport; }; var WebStorage = function () { function WebStorage() {} var _proto = WebStorage.prototype; _proto.set = function set(key, value) { global$3.localStorage.setItem(key, JSON$1.stringify({ d: value })); }; _proto.get = function get(key) { var value; var localValue = global$3.localStorage.getItem(key); try { localValue = JSON$1.parse(localValue); } catch (e) { localValue = {}; } if (localValue && localValue.d) { value = localValue.d; } return value; }; _proto.remove = function remove(key) { return global$3.localStorage.removeItem(key); }; _proto.getKeys = function getKeys() { var keyList = []; for (var key in global$3.localStorage) { keyList.push(key); } return keyList; }; return WebStorage; }(); var WebStorage$1 = isSupportLocalStorage() ? WebStorage : CacheStorage; var isMini$1 = env.isMini; var Storage = isMini$1 ? storage : WebStorage$1, storage$1 = new Storage(); var global$4 = env.global; var TEST_KEY$1 = 'RC_TEST_KEY'; var TEST_VALUE$1 = 'RC_TEST_VALUE'; var isSupportSessionStorage = function isSupportSessionStorage() { var isSupport = false; var sessionStorage = global$4.sessionStorage; if (sessionStorage) { try { sessionStorage.setItem(TEST_KEY$1, TEST_VALUE$1); var testVal = sessionStorage.getItem(TEST_KEY$1); if (testVal === TEST_VALUE$1) { isSupport = true; } sessionStorage.removeItem(TEST_KEY$1); } catch (e) {} } return isSupport; }; var WebSession = function () { function WebSession() {} var _proto = WebSession.prototype; _proto.set = function set(key, value) { global$4.sessionStorage.setItem(key, JSON$1.stringify({ d: value })); }; _proto.get = function get(key) { var value; var localValue = global$4.sessionStorage.getItem(key); try { localValue = JSON$1.parse(localValue); } catch (e) { localValue = {}; } if (localValue && localValue.d) { value = localValue.d; } return value; }; _proto.remove = function remove(key) { return global$4.sessionStorage.removeItem(key); }; _proto.getKeys = function getKeys() { var keyList = []; for (var key in global$4.sessionStorage) { keyList.push(key); } return keyList; }; return WebSession; }(); var WebSession$1 = isSupportSessionStorage() ? WebSession : CacheStorage; var isMini$2 = env.isMini; var Session = isMini$2 ? CacheStorage : WebSession$1, session = new Session(); var global$5 = env.global; var Socket = function () { function Socket(options) { this.socket = void 0; this.socket = global$5.connectSocket(options); } var _proto = Socket.prototype; _proto.send = function send(data) { this.socket.send({ data: data }); }; _proto.close = function close() { this.socket.close(); }; _proto.onOpen = function onOpen(callback) { this.socket.onOpen(callback); }; _proto.onMessage = function onMessage(callback) { this.socket.onMessage(callback); }; _proto.onError = function onError(callback) { this.socket.onError(callback); }; _proto.onClose = function onClose(callback) { this.socket.onClose(callback); }; return Socket; }(); var Socket$1 = function () { function Socket(options) { this.socket = void 0; var url = options.url; this.socket = new WebSocket(url); this.socket.binaryType = 'arraybuffer'; return this; } var _proto = Socket.prototype; _proto.send = function send(data) { return this.socket.send(data); }; _proto.close = function close() { this.socket.close(); }; _proto.onOpen = function onOpen(callback) { this.socket.addEventListener('open', callback); }; _proto.onMessage = function onMessage(callback) { this.socket.addEventListener('message', callback); }; _proto.onError = function onError(callback) { this.socket.addEventListener('error', callback); }; _proto.onClose = function onClose(callback) { this.socket.addEventListener('close', callback); }; return Socket; }(); var isMini$3 = env.isMini; var Socket$2 = isMini$3 ? Socket : Socket$1; /*! 基于 es6-promise * Github: https://github.com/stefanpenner/es6-promise * @overview es6-promise - a tiny implementation of Promises/A+. * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald) * @license Licensed under MIT license * See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE * @version v4.2.8+1e68dce6 */ var SparePromise = (function(){function a(a){var b=typeof a;return null!==a&&("object"===b||"function"===b)}function b(a){return "function"==typeof a}function c(a){P=a;}function d(a){Q=a;}function e(){return function(){return process.nextTick(j)}}function f(){return "undefined"!=typeof O?function(){O(j);}:i()}function g(){var a=0,b=new T(j),c=document.createTextNode("");return b.observe(c,{characterData:!0}),function(){c.data=a=++a%2;}}function h(){var a=new MessageChannel;return a.port1.onmessage=j,function(){return a.port2.postMessage(0)}}function i(){var a=setTimeout;return function(){return a(j,1)}}function j(){var a,b,c;for(a=0;N>a;a+=2)b=W[a],c=W[a+1],b(c),W[a]=void 0,W[a+1]=void 0;N=0;}function k(){try{var a=Function("return this")().require("vertx");return O=a.runOnLoop||a.runOnContext,f()}catch(b){return i()}}function l(a,b){var e,f,c=this,d=new this.constructor(n);return void 0===d[Y]&&D(d),e=c._state,e?(f=arguments[e-1],Q(function(){return A(e,d,f,c._result)})):y(c,d,a,b),d}function m(a){var c,b=this;return a&&"object"==typeof a&&a.constructor===b?a:(c=new b(n),u(c,a),c)}function n(){}function o(){return new TypeError("You cannot resolve a promise with itself")}function p(){return new TypeError("A promises callback cannot return that same promise.")}function q(a,b,c,d){try{a.call(b,c,d);}catch(e){return e}}function r(a,b,c){Q(function(a){var d=!1,e=q(c,b,function(c){d||(d=!0,b!==c?u(a,c):w(a,c));},function(b){d||(d=!0,x(a,b));},"Settle: "+(a._label||" unknown promise"));!d&&e&&(d=!0,x(a,e));},a);}function s(a,b){b._state===$?w(a,b._result):b._state===_?x(a,b._result):y(b,void 0,function(b){return u(a,b)},function(b){return x(a,b)});}function t(a,c,d){c.constructor===a.constructor&&d===l&&c.constructor.resolve===m?s(a,c):void 0===d?w(a,c):b(d)?r(a,c,d):w(a,c);}function u(b,c){if(b===c)x(b,o());else if(a(c)){var d=void 0;try{d=c.then;}catch(e){return void x(b,e)}t(b,c,d);}else w(b,c);}function v(a){a._onerror&&a._onerror(a._result),z(a);}function w(a,b){a._state===Z&&(a._result=b,a._state=$,0!==a._subscribers.length&&Q(z,a));}function x(a,b){a._state===Z&&(a._state=_,a._result=b,Q(v,a));}function y(a,b,c,d){var e=a._subscribers,f=e.length;a._onerror=null,e[f]=b,e[f+$]=c,e[f+_]=d,0===f&&a._state&&Q(z,a);}function z(a){var d,e,f,g,b=a._subscribers,c=a._state;if(0!==b.length){for(d=void 0,e=void 0,f=a._result,g=0;gf;f++)b.resolve(a[f]).then(c,d);}:function(a,b){return b(new TypeError("You must pass an array to race."))})}function H(a){var b=this,c=new b(n);return x(c,a),c}function I(){throw new TypeError("You must pass a resolver function as the first argument to the promise constructor")}function J(){throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.")}function K(){var c,d,a=void 0;if("undefined"!=typeof global)a=global;else if("undefined"!=typeof self)a=self;else try{a=Function("return this")();}catch(b){throw new Error("polyfill failed because global object is unavailable in this environment")}if(c=a.Promise){d=null;try{d=Object.prototype.toString.call(c.resolve());}catch(b){}if("[object Promise]"===d&&!c.cast)return}a.Promise=cb;}var M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,$,_,ab,bb,cb,L=void 0;return L=Array.isArray?Array.isArray:function(a){return "[object Array]"===Object.prototype.toString.call(a)},M=L,N=0,O=void 0,P=void 0,Q=function(a,b){W[N]=a,W[N+1]=b,N+=2,2===N&&(P?P(j):X());},R="undefined"!=typeof window?window:void 0,S=R||{},T=S.MutationObserver||S.WebKitMutationObserver,U="undefined"==typeof self&&"undefined"!=typeof process&&"[object process]"==={}.toString.call(process),V="undefined"!=typeof Uint8ClampedArray&&"undefined"!=typeof importScripts&&"undefined"!=typeof MessageChannel,W=new Array(1e3),X=void 0,X=U?e():T?g():V?h():void 0===R&&"function"==typeof require?k():i(),Y=Math.random().toString(36).substring(2),Z=void 0,$=1,_=2,ab=0,bb=function(){function a(a,b){this._instanceConstructor=a,this.promise=new a(n),this.promise[Y]||D(this.promise),M(b)?(this.length=b.length,this._remaining=b.length,this._result=new Array(this.length),0===this.length?w(this.promise,this._result):(this.length=this.length||0,this._enumerate(b),0===this._remaining&&w(this.promise,this._result))):x(this.promise,E());}return a.prototype._enumerate=function(a){for(var b=0;this._state===Z&&b>16)+(b>>16)+(c>>16);return d<<16|65535&c}function b(a,b){return a<>>32-b}function c(c,d,e,f,g,h){return a(b(a(a(d,c),a(f,h)),g),e)}function d(a,b,d,e,f,g,h){return c(b&d|~b&e,a,b,f,g,h)}function e(a,b,d,e,f,g,h){return c(b&e|d&~e,a,b,f,g,h)}function f(a,b,d,e,f,g,h){return c(b^d^e,a,b,f,g,h)}function g(a,b,d,e,f,g,h){return c(d^(b|~e),a,b,f,g,h)}function h(b,c){var h,i,j,k,l,m,n,o,p;for(b[c>>5]|=128<>>9<<4)+14]=c,m=1732584193,n=-271733879,o=-1732584194,p=271733878,h=0;hb;b+=8)c+=String.fromCharCode(255&a[b>>5]>>>b%32);return c}function j(a){var b,d,c=[];for(c[(a.length>>2)-1]=void 0,b=0;bb;b+=8)c[b>>5]|=(255&a.charCodeAt(b/8))<16&&(d=h(d,8*a.length)),c=0;16>c;c+=1)e[c]=909522486^d[c],f[c]=1549556828^d[c];return g=h(e.concat(j(b)),512+8*b.length),i(h(f.concat(g),640))}function m(a){var d,e,b="0123456789abcdef",c="";for(e=0;e>>4)+b.charAt(15&d);return c}function n(a){return unescape(encodeURIComponent(a))}function o(a){return k(n(a))}function p(a){return m(o(a))}function q(a,b){return l(n(a),n(b))}function r(a,b){return m(q(a,b))}function s(a,b,c){return b?c?q(b,a):r(b,a):c?o(a):p(a)}return s})(); var global$8 = env.global; var Promise$1 = global$8.Promise; var isSupportPromise = function isSupportPromise() { if (!global$8.Promise) return false; var defer = function () { return global$8.Promise.resolve(); }(); return defer.then && defer["catch"] && defer["finally"]; }; var setTimeout$1 = function setTimeout(event, timeout) { return global$8.setTimeout(event, timeout); }; var clearTimeout$1 = function clearTimeout(id) { return global$8.clearTimeout(id); }; var setInterval$1 = function setInterval(event, timeout) { return global$8.setInterval(event, timeout); }; var clearInterval$1 = function clearInterval(id) { return global$8.clearInterval(id); }; var Defer = isSupportPromise() ? global$8.Promise : SparePromise; var noop = function noop(data) { return data; }; var deferNoop = function deferNoop(data) { return Promise$1.resolve(data); }; var JSON$2 = global$8.JSON || JSON$1; var allowError = function allowError(event) { var result; try { for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } result = event.apply(void 0, args); } catch (e) { result = null; } return result; }; var toJSON = function toJSON(val) { return allowError(JSON$2.stringify, val); }; var parseJSON = function parseJSON(val) { return allowError(JSON$2.parse, val); }; var copy = function copy(val) { return parseJSON(toJSON(val)); }; var isObject = function isObject(val) { return Object.prototype.toString.call(val) === '[object Object]'; }; var isArray = function isArray(val) { return Object.prototype.toString.call(val).indexOf('Array') !== -1; }; var isFunction = function isFunction(val) { return Object.prototype.toString.call(val) === '[object Function]'; }; var isString = function isString(val) { return Object.prototype.toString.call(val) === '[object String]'; }; var isBoolean = function isBoolean(val) { return Object.prototype.toString.call(val) === '[object Boolean]'; }; var isUndefined = function isUndefined(val) { return val === undefined || Object.prototype.toString.call(val) === '[object Undefined]'; }; var isNull = function isNull(val) { return Object.prototype.toString.call(val) === '[object Null]'; }; var isNumber = function isNumber(val) { return Object.prototype.toString.call(val) === '[object Number]'; }; var isArrayBuffer = function isArrayBuffer(val) { return Object.prototype.toString.call(val) === '[object ArrayBuffer]'; }; var isPromise = function isPromise(val) { var isTrue = false; try { isTrue = Object.prototype.toString.call(val) === '[object Promise]' || val && val.then && val["catch"] && val["finally"]; } catch (e) { isTrue = false; } return isTrue; }; var getTypeName = function getTypeName(data) { var typeName = Object.prototype.toString.call(data); return typeName.substring(8, typeName.length - 1); }; var isEqual = function isEqual(source, target) { return source === target; }; var ArrayBufferToArray = function ArrayBufferToArray(data) { if (isArrayBuffer(data)) { return [].slice.call(new Int8Array(data)); } return data; }; var ArrayBufferToUint8Array = function ArrayBufferToUint8Array(data) { if (isArrayBuffer(data)) { return new Uint8Array(data); } return data; }; var forEach = function forEach(source, event, options) { options = options || {}; event = event || noop; var _options = options, isReverse = _options.isReverse; var loopObj = function loopObj() { for (var key in source) { event(source[key], key, source); } }; var loopArr = function loopArr() { if (isReverse) { for (var i = source.length - 1; i >= 0; i--) { event(source[i], i); } } else { for (var j = 0, len = source.length; j < len; j++) { event(source[j], j); } } }; if (isObject(source)) { loopObj(); } if (isArray(source) || isString(source)) { loopArr(); } }; var isEmpty = function isEmpty(val) { var result = true; if (isObject(val)) { forEach(val, function () { result = false; }); } if (isString(val) || isArray(val)) { result = val.length === 0; } if (isNumber(val)) { result = val === 0; } return result; }; var isNumberData = function isNumberData(val) { var isEmptyVal = isEmpty(val); val = Number(val); return isNumber(val) && !isEmptyVal; }; var getKeys = function getKeys(obj) { var keyList = []; forEach(obj, function (val, key) { keyList.push(key); }); return keyList; }; var getValues = function getValues(obj) { var valList = []; forEach(obj, function (val) { valList.push(val); }); return valList; }; var getTimestamp = function getTimestamp(time) { return new Date(time).getTime(); }; var getCurrentTimestamp = function getCurrentTimestamp() { return new Date().getTime(); }; var formatTime = function formatTime(timestamp, options) { timestamp = timestamp || getCurrentTimestamp(); options = options || {}; var temp = options.temp; var date = new Date(timestamp), formateds = {}; formateds['YY'] = date.getFullYear(); formateds['MM'] = date.getMonth() + 1; formateds['DD'] = date.getDate(); formateds['hh'] = date.getHours(); formateds['mm'] = date.getMinutes(); formateds['ss'] = date.getSeconds(); forEach(formateds, function (val, key) { formateds[key] = val >= 10 ? val : '0' + val; }); if (temp) { var formatedText = temp; forEach(formateds, function (val, key) { formatedText = formatedText.replace(key, val); }); return formatedText; } return formateds.YY + '-' + formateds.MM + '-' + formateds.DD + ' ' + formateds.hh + ':' + formateds.mm + ':' + formateds.ss; }; var isValidJSON = function isValidJSON(jsonStr) { if (isObject(jsonStr)) { return true; } var isValid = false; try { var obj = JSON$2.parse(jsonStr); var str = JSON$2.stringify(obj); isValid = str === jsonStr; } catch (e) { isValid = false; } return isValid; }; var isSupportSocket = function isSupportSocket() { var isMini = env.isMini; if (isMini) { return true; } var Socket = global$8.WebSocket; if (isUndefined(Socket)) { return false; } var hasWS = false, isIntegrity = false; try { hasWS = typeof Socket === 'object' || typeof Socket === 'function'; isIntegrity = typeof Socket.OPEN === 'number'; } catch (e) {} return hasWS && isIntegrity; }; var indexOf = function indexOf(source, searchVal) { if (source.indexOf) { return source.indexOf(searchVal); } var index = -1; forEach(source, function (sub, i) { if (searchVal === sub) { index = i; return; } }); return index; }; var lastIndexOf = function lastIndexOf(source, searchVal) { if (source.lastIndexOf) { return source.lastIndexOf(searchVal); } var index = -1; forEach(source, function (sub, i) { if (searchVal === sub) { index = i; return; } }, { isReverse: true }); return index; }; var isInclude = function isInclude(source, searchVal) { var index = indexOf(source, searchVal); return index !== -1; }; var substring = function substring(source, start, end) { return source.substring(start, end); }; var spliceByChild = function spliceByChild(arr, item) { forEach(arr, function (child, index) { if (isEqual(child, item)) { arr.splice(index, 1); } }, { isReverse: true }); }; var parse16To10 = function parse16To10(num) { return parseInt(num, 16); }; var isPlus = function isPlus(num) { return +num === num; }; var filter = function filter(source, event) { var newArr = []; for (var i = 0, max = source.length; i < max; i++) { var data = source[i]; if (event(data, i)) { newArr.push(data); } } return newArr; }; var map = function map(source, event) { forEach(source, function (item, index) { source[index] = event(item, index); }); return source; }; var extend = function extend(destination, sources) { destination = destination || {}; sources = sources || {}; for (var key in sources) { var value = sources[key]; if (!isUndefined(value)) { destination[key] = value; } } return destination; }; var extendInShallow = function extendInShallow(destination, sources) { destination = destination || {}; sources = sources || {}; destination = copy(destination); sources = copy(sources); return extend(destination, sources); }; var deferred = function deferred(callbacks) { return new Defer(callbacks); }; var deferTimeout = function deferTimeout(timeout) { return deferred(function (resolve) { var timeouter = setTimeout$1(function () { resolve(timeouter); }, timeout); }); }; var tplEngine = function tplEngine(temp, data, regexp) { var replaceAction = function replaceAction(obj) { return temp.replace(regexp || /{([^}]+)}/g, function (match, name) { if (match.charAt(0) === '\\') { return match.slice(1); } return obj[name] !== undefined ? obj[name] : '{' + name + '}'; }); }; if (!isArray(data)) { data = [data]; } var ret = []; forEach(data, function (item) { ret.push(replaceAction(item)); }); return ret.join(''); }; var getRandomNum = function getRandomNum(max, min) { min = min || 0; var range = max - min, random = Math.random(); return min + Math.round(random * range); }; var Timer = function () { function Timer(options) { this._timerId = void 0; this._timerEvent = void 0; this._timerClearEvent = void 0; this.timeout = 0; this.type = TIMER_TYPE.TIMEOUT; this.status = TIMER_STATUS.PENNDING; var self = this; extend(self, options); var type = self.type; var isTimeout = type === TIMER_TYPE.TIMEOUT; if (isTimeout) { self._timerEvent = setTimeout$1; self._timerClearEvent = clearTimeout$1; } else { self._timerEvent = setInterval$1; self._timerClearEvent = clearInterval$1; } return self; } var _proto = Timer.prototype; _proto.start = function start(event, options) { options = options || {}; var self = this, isTimeout = self.type === TIMER_TYPE.TIMEOUT; var _options2 = options, args = _options2.args, thisArg = _options2.thisArg; self.stop(); self._timerId = self._timerEvent.call(global$8, function () { isTimeout && self.stop(); if (thisArg) { event.apply(thisArg, args); } else { event(args); } }, self.timeout); self.status = TIMER_STATUS.BUSY; }; _proto.stop = function stop() { var self = this; if (self._timerId) { self._timerClearEvent.call(global$8, self._timerId); self.status = TIMER_STATUS.ENDING; } }; return Timer; }(); var DeferHandler = function () { function DeferHandler(options) { this._list = {}; this.timeout = IM_TIMEOUT; extend(this, options); } var _proto2 = DeferHandler.prototype; _proto2._isInvalid = function _isInvalid(id) { var handlers = this._list[id]; return !isArray(handlers) || isEmpty(handlers); }; _proto2._exec = function _exec(id, isError, data) { var self = this; if (self._isInvalid(id)) { return; } var handlers = self._list[id], handler = handlers[0]; isError ? handler.reject(data) : handler.resolve(data); handlers.splice(0, 1); }; _proto2.add = function add(id, defer, options) { options = options || {}; var self = this; var resolve = defer.resolve, reject = defer.reject; var timeout = options.timeout || self.timeout; if (self._isInvalid(id)) { self._list[id] = []; } var timer = new Timer({ timeout: timeout }); timer.start(function () { self.reject(id, ERROR_INFO.TIMEOUT.code); }); self._list[id].push({ resolve: resolve, reject: reject, timer: timer }); }; _proto2.resolve = function resolve(id, data) { this._exec(id, false, data); }; _proto2.reject = function reject(id, error) { this._exec(id, true, error); }; return DeferHandler; }(); var EventEmitter = function () { function EventEmitter() { this._events = void 0; this._events = {}; } var _proto3 = EventEmitter.prototype; _proto3.on = function on(name, event) { var _events = this._events[name] || []; _events.push(event); this._events[name] = _events; }; _proto3.off = function off(name, offEvent) { if (offEvent) { var _events = this._events[name] || []; spliceByChild(_events, offEvent); } else { delete this._events[name]; } }; _proto3.emit = function emit(name, data, error) { var _events = this._events[name]; forEach(_events, function (event) { event(data, error); }); }; _proto3.clear = function clear() { this._events = {}; }; return EventEmitter; }(); var decodeURI = function decodeURI(uri) { return global$8.decodeURIComponent(uri); }; var encodeURI = function encodeURI(uri) { return global$8.encodeURIComponent(uri); }; var int64ToTimestamp = function int64ToTimestamp(obj) { if (!isObject(obj) || obj.low === undefined || obj.high === undefined) { return obj; } var low = obj.low; if (low < 0) { low += 0xffffffff + 1; } low = low.toString(16); var timestamp = parseInt(obj.high.toString(16) + '00000000'.replace(new RegExp('0{' + low.length + '}$'), low), 16); return timestamp; }; var batchInt64ToTimestamp = function batchInt64ToTimestamp(data) { forEach(data, function (item, key) { if (isObject(item)) { data[key] = int64ToTimestamp(item); } }); return data; }; var Queue = function () { function Queue(defaultConfig) { this._isRunning = false; this._list = []; this._defaultConfig = void 0; this._defaultConfig = defaultConfig; } var _proto4 = Queue.prototype; _proto4.add = function add(params) { params = params || this._defaultConfig; this._list.push(params); this.run(); }; _proto4.run = function run() { var self = this; var _isRunning = self._isRunning, _list = self._list; var isFinished = isEmpty(_list); if (_isRunning || isFinished) { return; } var firstItem = _list.splice(0, 1)[0]; var event = firstItem.event, args = firstItem.args, thisArg = firstItem.thisArg; var next = function next() { self._isRunning = false; self.run(); }; if (!event) { return next(); } self._isRunning = true; event.apply(thisArg, args).then(next)["catch"](next); }; return Queue; }(); var secondsToMilliseconds = function secondsToMilliseconds(seconds) { return seconds * 1000; }; var request$3 = function request(url, options) { options = options || {}; return deferred(function (resolve, reject) { options = extend(options, { url: url, success: function success(responseText, xhr, status) { resolve({ responseText: responseText, xhr: xhr, status: status }); }, fail: function fail(result, xhr, status) { reject({ result: result, xhr: xhr, status: status }); } }); request$2(options); }); }; var requestByUrlList = function requestByUrlList(urlList, options) { if (isEmpty(urlList)) { return Defer.reject(); } var url = urlList[0]; return request$3(url, options).then(function (result) { result = result || {}; result.urlList = urlList; return result; })["catch"](function (error) { urlList.splice(0, 1); if (isEmpty(urlList)) { return Defer.reject(error); } else { return requestByUrlList(urlList, options); } }); }; var requestForFaster = function requestForFaster(urlList, option) { option = option || {}; var timeInterval = option.timeInterval || 0; var faildCount = 0, totalCount = urlList.length; var requestXhrs = []; var totalTimer = new Timer({ timeout: 15 * 1000 }); var reqCountdownTimers = []; var clearAll = function clearAll() { forEach(reqCountdownTimers, function (timer) { timer.stop(); }); forEach(requestXhrs, function (xhr) { xhr.abort(); }); reqCountdownTimers.length = 0; requestXhrs.length = 0; }; var isAllFaild = function isAllFaild() { return faildCount === totalCount; }; return deferred(function (resolve, reject) { var _success = function success(url, index) { clearAll(); resolve({ url: url, index: index }); }; var _fail = function fail() { clearAll(); reject(); }; forEach(urlList, function (url, index) { var timer = new Timer({ timeout: timeInterval * index }); timer.start(function () { var xhr; var opt = extend({ url: url, success: function success() { _success(url, index); }, fail: function fail() { faildCount++; isAllFaild() && _fail(); } }, option); xhr = request$2(opt); requestXhrs.push(xhr); }); reqCountdownTimers.push(timer); }); totalTimer.start(_fail); }); }; var NetworkDetecter = function () { function NetworkDetecter(option) { this._option = void 0; this._detectCount = 0; this._timeoutId = void 0; this._option = option; } var _proto5 = NetworkDetecter.prototype; _proto5._detect = function _detect() { var self = this; var _detectCount = self._detectCount, _option = self._option; var url = _option.url, timeout = _option.intervalTime, max = _option.max; _detectCount++; return request$3(url).then(function () { return; }, function (_ref) { var status = _ref.status; if (isEqual(status, 404)) { return; } var isAlreadyMax = max && isEqual(max, _detectCount); if (isAlreadyMax) { return Defer.reject(); } return deferTimeout(timeout).then(function (timeoutId) { self._detectCount = _detectCount; self._timeoutId = timeoutId; return self._detect(); }); }); }; _proto5.start = function start() { return this._detect(); }; _proto5.stop = function stop() { var timeoutId = this._timeoutId; if (timeoutId) { clearTimeout$1(timeoutId); } }; return NetworkDetecter; }(); var toUpperCase = function toUpperCase(str, startIndex, endIndex) { if (isUndefined(startIndex) || isUndefined(endIndex)) { return str.toUpperCase(); } var sliceStr = str.slice(startIndex, endIndex); str = str.replace(sliceStr, function (text) { return text.toUpperCase(); }); return str; }; var getDomainByUrl = function getDomainByUrl(url) { var StartMark = '://', EndMark = '/'; var urlProtocolIndex = indexOf(url, StartMark); var hasProtocol = urlProtocolIndex > -1; if (hasProtocol) { urlProtocolIndex = urlProtocolIndex + StartMark.length; url = substring(url, urlProtocolIndex, url.length); } var urlPathIndex = indexOf(url, EndMark); var hasPath = urlPathIndex > -1; if (hasPath) { url = substring(url, 0, urlPathIndex); } return url; }; var getValidUrl = function getValidUrl(url, option) { option = option || {}; var ProtocolMark = '://'; var hasProtocol = isInclude(url, ProtocolMark); var localProtocol = env.protocol.http; var _option2 = option, protocol = _option2.protocol; if (protocol) { var domain = getDomainByUrl(url); url = protocol + "//" + domain; } if (hasProtocol) { var urlProtocolIndex = indexOf(url, ProtocolMark) + 1; var urlProtocol = substring(url, 0, urlProtocolIndex); var isHttpUrl = urlProtocol === HTTP_PROTOCOL.HTTP; var isLocalHttps = localProtocol === HTTP_PROTOCOL.HTTPS; if (isHttpUrl && isLocalHttps) { var _domain = getDomainByUrl(url); return HTTP_PROTOCOL.HTTPS + "//" + _domain; } else { return url; } } else { return localProtocol + "//" + url; } }; var quickSort = function quickSort(arr, event) { var sort = function sort(array, left, right, event) { event = event || function (a, b) { return a <= b; }; if (left < right) { var x = array[right], i = left - 1, temp; for (var j = left; j <= right; j++) { if (event(array[j], x)) { i++; temp = array[i]; array[i] = array[j]; array[j] = temp; } } sort(array, left, i - 1, event); sort(array, i + 1, right, event); } return array; }; return sort(arr, 0, arr.length - 1, event); }; var unique = function unique(arr, event) { var keyEvent = event || function (data) { return data; }; var hashTable = {}; var newArr = []; forEach(arr, function (data) { var key = keyEvent(data); if (!hashTable[key]) { hashTable[key] = true; newArr.push(data); } }); return newArr; }; var isStackError = function isStackError(error) { error = error || {}; return error.stack && error.stack.toString; }; var consoleError = function consoleError() { var _console; return (_console = console).error.apply(_console, arguments); }; var consoleLog = function consoleLog() { var _console2; return (_console2 = console).log.apply(_console2, arguments); }; var string10to64 = function string10to64(number) { var chars = '0123456789abcdefghigklmnopqrstuvwxyzABCDEFGHIGKLMNOPQRSTUVWXYZa0'.split(''), radix = chars.length + 1, qutient = +number, arr = []; do { var mod = qutient % radix; qutient = (qutient - mod) / radix; arr.unshift(chars[mod]); } while (qutient); return arr.join(''); }; var getUUID = function getUUID() { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { var r = Math.random() * 16 | 0, v = c === 'x' ? r : r & 0x3 | 0x8; return v.toString(16); }); }; var getUUID22 = function getUUID22() { var uuid = getUUID(); uuid = uuid.replace(/-/g, '') + 'a'; uuid = parseInt(uuid, 16); uuid = string10to64(uuid); if (uuid.length > 22) { uuid = uuid.slice(0, 22); } else { var len = 22 - uuid.length; for (var i = 0; i < len; i++) { uuid = uuid + '0'; } } return uuid; }; var isValidTimestamp = function isValidTimestamp(time) { return isNumber(time) && time !== 0; }; var utils = { Storage: storage$1, Session: session, Socket: Socket$2, Cache: CacheStorage, JSON: JSON$2, Defer: Defer, httpRequest: request$2, request: request$3, requestByUrlList: requestByUrlList, requestForFaster: requestForFaster, md5: md5, DeferHandler: DeferHandler, EventEmitter: EventEmitter, Timer: Timer, Queue: Queue, consoleError: consoleError, consoleLog: consoleLog, noop: noop, deferNoop: deferNoop, setTimeout: setTimeout$1, toJSON: toJSON, parseJSON: parseJSON, copy: copy, isObject: isObject, isArray: isArray, isFunction: isFunction, isArrayBuffer: isArrayBuffer, isString: isString, isBoolean: isBoolean, isUndefined: isUndefined, isNull: isNull, isNumber: isNumber, isNumberData: isNumberData, isPromise: isPromise, getTypeName: getTypeName, isPlus: isPlus, isEmpty: isEmpty, isEqual: isEqual, isValidJSON: isValidJSON, isSupportSocket: isSupportSocket, ArrayBufferToArray: ArrayBufferToArray, ArrayBufferToUint8Array: ArrayBufferToUint8Array, indexOf: indexOf, lastIndexOf: lastIndexOf, isInclude: isInclude, substring: substring, getKeys: getKeys, getValues: getValues, getTimestamp: getTimestamp, getCurrentTimestamp: getCurrentTimestamp, formatTime: formatTime, parse16To10: parse16To10, forEach: forEach, map: map, filter: filter, extend: extend, extendInShallow: extendInShallow, deferred: deferred, tplEngine: tplEngine, getRandomNum: getRandomNum, int64ToTimestamp: int64ToTimestamp, batchInt64ToTimestamp: batchInt64ToTimestamp, encodeURI: encodeURI, decodeURI: decodeURI, secondsToMilliseconds: secondsToMilliseconds, NetworkDetecter: NetworkDetecter, toUpperCase: toUpperCase, getDomainByUrl: getDomainByUrl, getValidUrl: getValidUrl, quickSort: quickSort, unique: unique, isStackError: isStackError, getUUID: getUUID, getUUID22: getUUID22, isValidTimestamp: isValidTimestamp }; function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } var _PUBLISH_TOPIC_TO_CON, _CONVERSATION_TYPE_TO, _CONVERSATION_TYPE_TO2, _CONVERSATION_TYPE_TO3, _CONVERSATION_TYPE_TO4; var SUCCESS_CODE = 0; var PULL_MSG_TYPE = { NORMAL: 1, CHATROOM: 2 }; var MESSAGE_NAME = { CONN_ACK: 'ConnAckMessage', DISCONNECT: 'DisconnectMessage', PING_REQ: 'PingReqMessage', PING_RESP: 'PingRespMessage', PUBLISH: 'PublishMessage', PUB_ACK: 'PubAckMessage', QUERY: 'QueryMessage', QUERY_CON: 'QueryConMessage', QUERY_ACK: 'QueryAckMessage' }; var QOS = { AT_MOST_ONCE: 0, AT_LEAST_ONCE: 1, EXACTLY_ONCE: 2, DEFAULT: 3, '0': 'AT_MOST_ONCE', '1': 'AT_LEAST_ONCE', '2': 'EXACTLY_ONCE', '3': 'DEFAULT' }; var OPERATE_TYPE = { CONNECT: 1, '1': 'CONNECT', CONNACK: 2, '2': 'CONNACK', PUBLISH: 3, '3': 'PUBLISH', PUBACK: 4, '4': 'PUBACK', QUERY: 5, '5': 'QUERY', QUERYACK: 6, '6': 'QUERYACK', QUERYCON: 7, '7': 'QUERYCON', SUBSCRIBE: 8, '8': 'SUBSCRIBE', SUBACK: 9, '9': 'SUBACK', UNSUBSCRIBE: 10, '10': 'UNSUBSCRIBE', UNSUBACK: 11, '11': 'UNSUBACK', PINGREQ: 12, '12': 'PINGREQ', PINGRESP: 13, '13': 'PINGRESP', DISCONNECT: 14, '14': 'DISCONNECT' }; var MESSAGE_TAG = { NONE: 0, PERSIT_ONLY: 1, COUNT_ONLY: 2, PERSIT_AND_COUNT: 3 }; var PUBLISH_TOPIC = { PRIVATE: 'ppMsgP', GROUP: 'pgMsgP', CHATROOM: 'chatMsg', CUSTOMER_SERVICE: 'pcMsgP', RECALL: 'recallMsg', NOTIFY_PULL_MSG: 's_ntf', RECEIVE_MSG: 's_msg', SYNC_STATUS: 's_stat', SERVER_NOTIFY: 's_cmd' }; var PUBLISH_STATUS_TOPIC = { PRIVATE: 'ppMsgS', GROUP: 'pgMsgS' }; var QUERY_TOPIC = { GET_SYNC_TIME: 'qrySessionsAtt', PULL_MSG: 'pullMsg', GET_CONVERSATION_LIST: 'qrySessions', REMOVE_CONVERSATION_LIST: 'delSessions', DELETE_MESSAGES: 'delMsg', CLEAR_UNREAD_COUNT: 'updRRTime', PULL_CHRM_MSG: 'chrmPull', JOIN_CHATROOM: 'joinChrm', QUIT_CHATROOM: 'exitChrm', GET_CHATROOM_INFO: 'queryChrmI', UPDATE_CHATROOM_KV: 'setKV', DELETE_CHATROOM_KV: 'delKV', PULL_CHATROOM_KV: 'pullKV', GET_OLD_CONVERSATION_LIST: 'qryRelation', REMOVE_OLD_CONVERSATION: 'delRelation', GET_UPLOAD_FILE_TOKEN: 'qnTkn', GET_UPLOAD_FILE_URL: 'qnUrl', CLEAR_MESSAGES: { PRIVATE: 'cleanPMsg', GROUP: 'cleanGMsg', CUSTOMER_SERVICE: 'cleanCMsg', SYSTEM: 'cleanSMsg' }, JOIN_RTC_ROOM: 'rtcRJoin_data', QUIT_RTC_ROOM: 'rtcRExit', PING_RTC: 'rtcPing', SET_RTC_DATA: 'rtcSetData', GET_RTC_DATA: 'rtcQryData', DEL_RTC_DATA: 'rtcDelData', SET_RTC_OUT_DATA: 'rtcSetOutData', GET_RTC_OUT_DATA: 'rtcQryUserOutData', GET_RTC_TOKEN: 'rtcToken', SET_RTC_STATE: 'rtcUserState', GET_RTC_ROOM_INFO: 'rtcRInfo', GET_RTC_USER_INFO_LIST: 'rtcUData', SET_RTC_USER_INFO: 'rtcUPut', DEL_RTC_USER_INFO: 'rtcUDel', GET_RTC_USER_LIST: 'rtcUList' }; var QUERY_HISTORY_TOPIC = { PRIVATE: 'qryPMsg', GROUP: 'qryGMsg', CHATROOM: 'qryCHMsg', CUSTOMER_SERVICE: 'qryCMsg', SYSTEM: 'qrySMsg' }; var CHATROOM_NOTIFY_TYPE = { KV_CHANGED: 2 }; var CHATROOM_KV_STATUS_CODE = { AUTO_DELETE: 0x0001, OVERWRITE: 0x0002, OPERATE: 0x0004 }; var PUBLISH_TOPIC_TO_CONVERSATION_TYPE = (_PUBLISH_TOPIC_TO_CON = {}, _PUBLISH_TOPIC_TO_CON[PUBLISH_TOPIC.PRIVATE] = CONVERSATION_TYPE.PRIVATE, _PUBLISH_TOPIC_TO_CON[PUBLISH_TOPIC.GROUP] = CONVERSATION_TYPE.GROUP, _PUBLISH_TOPIC_TO_CON[PUBLISH_TOPIC.CHATROOM] = CONVERSATION_TYPE.CHATROOM, _PUBLISH_TOPIC_TO_CON[PUBLISH_TOPIC.CUSTOMER_SERVICE] = CONVERSATION_TYPE.CUSTOMER_SERVICE, _PUBLISH_TOPIC_TO_CON); var CONVERSATION_TYPE_TO_PUBLISH_TOPIC = (_CONVERSATION_TYPE_TO = {}, _CONVERSATION_TYPE_TO[CONVERSATION_TYPE.PRIVATE] = PUBLISH_TOPIC.PRIVATE, _CONVERSATION_TYPE_TO[CONVERSATION_TYPE.GROUP] = PUBLISH_TOPIC.GROUP, _CONVERSATION_TYPE_TO[CONVERSATION_TYPE.CHATROOM] = PUBLISH_TOPIC.CHATROOM, _CONVERSATION_TYPE_TO[CONVERSATION_TYPE.CUSTOMER_SERVICE] = PUBLISH_TOPIC.CUSTOMER_SERVICE, _CONVERSATION_TYPE_TO); var CONVERSATION_TYPE_TO_PUBLISH_STATUS_TOPIC = (_CONVERSATION_TYPE_TO2 = {}, _CONVERSATION_TYPE_TO2[CONVERSATION_TYPE.PRIVATE] = PUBLISH_STATUS_TOPIC.PRIVATE, _CONVERSATION_TYPE_TO2[CONVERSATION_TYPE.GROUP] = PUBLISH_STATUS_TOPIC.GROUP, _CONVERSATION_TYPE_TO2); var CONVERSATION_TYPE_TO_QUERY_HISTORY_TOPIC = (_CONVERSATION_TYPE_TO3 = {}, _CONVERSATION_TYPE_TO3[CONVERSATION_TYPE.PRIVATE] = QUERY_HISTORY_TOPIC.PRIVATE, _CONVERSATION_TYPE_TO3[CONVERSATION_TYPE.GROUP] = QUERY_HISTORY_TOPIC.GROUP, _CONVERSATION_TYPE_TO3[CONVERSATION_TYPE.CHATROOM] = QUERY_HISTORY_TOPIC.CHATROOM, _CONVERSATION_TYPE_TO3[CONVERSATION_TYPE.CUSTOMER_SERVICE] = QUERY_HISTORY_TOPIC.CUSTOMER_SERVICE, _CONVERSATION_TYPE_TO3[CONVERSATION_TYPE.SYSTEM] = QUERY_HISTORY_TOPIC.SYSTEM, _CONVERSATION_TYPE_TO3); var CONVERSATION_TYPE_TO_CLEAR_MESSAGE_TOPIC = (_CONVERSATION_TYPE_TO4 = {}, _CONVERSATION_TYPE_TO4[CONVERSATION_TYPE.PRIVATE] = QUERY_TOPIC.CLEAR_MESSAGES.PRIVATE, _CONVERSATION_TYPE_TO4[CONVERSATION_TYPE.GROUP] = QUERY_TOPIC.CLEAR_MESSAGES.GROUP, _CONVERSATION_TYPE_TO4[CONVERSATION_TYPE.CUSTOMER_SERVICE] = QUERY_TOPIC.CLEAR_MESSAGES.CUSTOMER_SERVICE, _CONVERSATION_TYPE_TO4[CONVERSATION_TYPE.SYSTEM] = QUERY_TOPIC.CLEAR_MESSAGES.SYSTEM, _CONVERSATION_TYPE_TO4); var Header = function () { function Header(_type, _retain, _qos, _dup) { this.type = void 0; this.retain = false; this.qos = QOS.AT_LEAST_ONCE; this.dup = false; this.syncMsg = false; var isPlusType = utils.isPlus(_type); if (_type && isPlusType && arguments.length === 1) { this.retain = (_type & 1) > 0; this.qos = (_type & 6) >> 1; this.dup = (_type & 8) > 0; this.type = _type >> 4 & 15; this.syncMsg = (_type & 8) === 8; } else { this.type = _type; this.retain = _retain === undefined ? false : _retain; this.qos = _qos === undefined ? QOS.AT_LEAST_ONCE : _qos; this.dup = _dup === undefined ? false : _dup; } } var _proto = Header.prototype; _proto.encode = function encode() { var self = this; var validQosList = [QOS.AT_MOST_ONCE, QOS.AT_LEAST_ONCE, QOS.EXACTLY_ONCE, QOS.DEFAULT]; utils.forEach(validQosList, function (qos) { if (self.qos === QOS[qos]) { self.qos = qos; } }); var _byte = self.type << 4; _byte |= self.retain ? 1 : 0; _byte |= self.qos << 1; _byte |= self.dup ? 8 : 0; return _byte; }; return Header; }(); var BinaryHelper = { writeUTF: function writeUTF(str, isGetBytes) { var back = [], byteSize = 0; utils.forEach(str, function (_char, i) { var code = str.charCodeAt(i); if (code >= 0 && code <= 127) { byteSize += 1; back.push(code); } else if (code >= 128 && code <= 2047) { byteSize += 2; back.push(192 | 31 & code >> 6); back.push(128 | 63 & code); } else if (code >= 2048 && code <= 65535) { byteSize += 3; back.push(224 | 15 & code >> 12); back.push(128 | 63 & code >> 6); back.push(128 | 63 & code); } }); utils.forEach(back, function (_char2, i) { if (_char2 > 255) { back[i] &= 255; } }); if (isGetBytes) { return back; } if (byteSize <= 255) { return [0, byteSize].concat(back); } else { return [byteSize >> 8, byteSize & 255].concat(back); } }, readUTF: function readUTF(arr) { var UTF = ''; for (var i = 0, len = arr.length; i < len; i++) { var _char3 = arr[i]; if (_char3 < 0) { arr[i] += 256; } var one = arr[i].toString(2), v = one.match(/^1+?(?=0)/); if (v && one.length === 8) { var bytesLength = v[0].length, store = ''; for (var st = 0; st < bytesLength; st++) { store += arr[st + i].toString(2).slice(2); } UTF += String.fromCharCode(parseInt(store, 2)); i += bytesLength - 1; } else { UTF += String.fromCharCode(arr[i]); } } return UTF; } }; var RongStreamReader = function () { function RongStreamReader(arr) { this.pool = void 0; this.position = 0; this.poolLen = 0; this.pool = arr; this.poolLen = arr.length; } var _proto2 = RongStreamReader.prototype; _proto2.check = function check() { return this.position >= this.pool.length; }; _proto2.readInt = function readInt() { var self = this; if (self.check()) { return -1; } var end = ''; for (var i = 0; i < 4; i++) { var t = self.pool[self.position++].toString(16); if (t.length === 1) { t = '0' + t; } end += t.toString(); } return utils.parse16To10(end); }; _proto2.readLong = function readLong() { var self = this; if (self.check()) { return -1; } var end = ''; for (var i = 0; i < 8; i++) { var t = self.pool[self.position++].toString(16); if (t.length === 1) { t = '0' + t; } end += t; } return utils.parse16To10(end); }; _proto2.readByte = function readByte() { if (this.check()) { return -1; } var val = this.pool[this.position++]; if (val > 255) { val &= 255; } return val; }; _proto2.readUTF = function readUTF() { if (this.check()) { return ''; } var big = this.readByte() << 8 | this.readByte(); var pool = this.pool.subarray(this.position, this.position += big); return BinaryHelper.readUTF(pool); }; _proto2.readAll = function readAll() { return this.pool.subarray(this.position, this.poolLen); }; return RongStreamReader; }(); var RongStreamWriter = function () { function RongStreamWriter() { this.pool = []; this.position = 0; this.writen = 0; } var _proto3 = RongStreamWriter.prototype; _proto3.write = function write(_byte2) { if (utils.isArray(_byte2)) { this.pool = this.pool.concat(_byte2); } else if (utils.isPlus(_byte2)) { if (_byte2 > 255) { _byte2 &= 255; } this.pool.push(_byte2); this.writen++; } return _byte2; }; _proto3.writeArr = function writeArr(_byte3) { this.pool = this.pool.concat(_byte3); return _byte3; }; _proto3.writeUTF = function writeUTF(str) { var val = BinaryHelper.writeUTF(str); this.pool = this.pool.concat(val); this.writen += val.length; }; _proto3.getBytesArray = function getBytesArray() { return this.pool; }; return RongStreamWriter; }(); var IDENTIFIER = { PUB: 'pub', QUERY: 'qry' }; var _getIdentifier = function getIdentifier(messageId, identifier) { if (messageId && identifier) { return identifier + '_' + messageId; } else if (messageId) { return messageId; } else { return utils.getCurrentTimestamp(); } }; var BaseReader = function () { function BaseReader(header) { this._name = void 0; this._header = void 0; this.lengthSize = 0; this.messageId = void 0; this.timestamp = void 0; this.identifier = void 0; this._header = header; } var _proto = BaseReader.prototype; _proto.getIdentifier = function getIdentifier() { var messageId = this.messageId, identifier = this.identifier; return _getIdentifier(messageId, identifier); }; _proto.read = function read(stream, length) { this.readMessage(stream, length); }; _proto.readMessage = function readMessage(stream, length) { return { stream: stream, length: length }; }; return BaseReader; }(); var BaseWriter = function () { function BaseWriter(headerType) { this._header = void 0; this.lengthSize = 0; this.data = void 0; this.messageId = void 0; this.topic = void 0; this.targetId = void 0; this.identifier = void 0; this._header = new Header(headerType, false, QOS.AT_MOST_ONCE, false); } var _proto2 = BaseWriter.prototype; _proto2.getIdentifier = function getIdentifier() { var messageId = this.messageId, identifier = this.identifier; return _getIdentifier(messageId, identifier); }; _proto2.write = function write(stream) { var headerCode = this.getHeaderFlag(); stream.write(headerCode); this.writeMessage(stream); }; _proto2.writeMessage = function writeMessage(stream) { return stream; }; _proto2.setHeaderQos = function setHeaderQos(qos) { this._header.qos = qos; }; _proto2.getHeaderFlag = function getHeaderFlag() { return this._header.encode(); }; _proto2.getLengthSize = function getLengthSize() { return this.lengthSize; }; _proto2.getBufferData = function getBufferData() { var stream = new RongStreamWriter(); this.write(stream); var val = stream.getBytesArray(); var binary = new Int8Array(val); return binary; }; _proto2.getCometData = function getCometData() { var data = this.data || {}; return utils.toJSON(data); }; return BaseWriter; }(); var ConnAckReader = function (_BaseReader) { _inheritsLoose(ConnAckReader, _BaseReader); function ConnAckReader() { var _this; for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this = _BaseReader.call.apply(_BaseReader, [this].concat(args)) || this; _this._name = MESSAGE_NAME.CONN_ACK; _this.status = void 0; _this.userId = void 0; _this.timestamp = void 0; return _this; } var _proto3 = ConnAckReader.prototype; _proto3.readMessage = function readMessage(stream, msgLength) { stream.readByte(); this.status = +stream.readByte(); if (msgLength > ConnAckReader.MESSAGE_LENGTH) { this.userId = stream.readUTF(); stream.readUTF(); this.timestamp = stream.readLong(); } }; return ConnAckReader; }(BaseReader); ConnAckReader.MESSAGE_LENGTH = 2; var DisconnectReader = function (_BaseReader2) { _inheritsLoose(DisconnectReader, _BaseReader2); function DisconnectReader() { var _this2; for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } _this2 = _BaseReader2.call.apply(_BaseReader2, [this].concat(args)) || this; _this2._name = MESSAGE_NAME.DISCONNECT; _this2.status = void 0; return _this2; } var _proto4 = DisconnectReader.prototype; _proto4.readMessage = function readMessage(stream) { stream.readByte(); this.status = +stream.readByte(); }; return DisconnectReader; }(BaseReader); DisconnectReader.MESSAGE_LENGTH = 2; var PingReqWriter = function (_BaseWriter) { _inheritsLoose(PingReqWriter, _BaseWriter); function PingReqWriter() { var _this3; _this3 = _BaseWriter.call(this, OPERATE_TYPE.PINGREQ) || this; _this3._name = MESSAGE_NAME.PING_REQ; return _this3; } return PingReqWriter; }(BaseWriter); var PingRespReader = function (_BaseReader3) { _inheritsLoose(PingRespReader, _BaseReader3); function PingRespReader() { var _this4; for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { args[_key3] = arguments[_key3]; } _this4 = _BaseReader3.call.apply(_BaseReader3, [this].concat(args)) || this; _this4._name = MESSAGE_NAME.PING_RESP; return _this4; } return PingRespReader; }(BaseReader); var RetryableReader = function (_BaseReader4) { _inheritsLoose(RetryableReader, _BaseReader4); function RetryableReader() { var _this5; for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { args[_key4] = arguments[_key4]; } _this5 = _BaseReader4.call.apply(_BaseReader4, [this].concat(args)) || this; _this5.messageId = void 0; return _this5; } var _proto5 = RetryableReader.prototype; _proto5.readMessage = function readMessage(stream) { var msgId = stream.readByte() * 256 + stream.readByte(); this.messageId = parseInt(msgId, 10); }; return RetryableReader; }(BaseReader); var RetryableWriter = function (_BaseWriter2) { _inheritsLoose(RetryableWriter, _BaseWriter2); function RetryableWriter() { var _this6; for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) { args[_key5] = arguments[_key5]; } _this6 = _BaseWriter2.call.apply(_BaseWriter2, [this].concat(args)) || this; _this6.messageId = void 0; return _this6; } var _proto6 = RetryableWriter.prototype; _proto6.writeMessage = function writeMessage(stream) { var id = this.messageId; var lsb = id & 255; var msb = (id & 65280) >> 8; stream.write(msb); stream.write(lsb); }; return RetryableWriter; }(BaseWriter); var PublishReader = function (_RetryableReader) { _inheritsLoose(PublishReader, _RetryableReader); function PublishReader() { var _this7; for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) { args[_key6] = arguments[_key6]; } _this7 = _RetryableReader.call.apply(_RetryableReader, [this].concat(args)) || this; _this7._name = MESSAGE_NAME.PUBLISH; _this7.topic = void 0; _this7.data = void 0; _this7.targetId = void 0; _this7.date = void 0; _this7.syncMsg = false; _this7.identifier = IDENTIFIER.PUB; return _this7; } var _proto7 = PublishReader.prototype; _proto7.readMessage = function readMessage(stream) { this.date = stream.readInt(); this.topic = stream.readUTF(); this.targetId = stream.readUTF(); RetryableReader.prototype.readMessage.apply(this, arguments); this.data = stream.readAll(); }; return PublishReader; }(RetryableReader); var PublishWriter = function (_RetryableWriter) { _inheritsLoose(PublishWriter, _RetryableWriter); function PublishWriter(topic, data, targetId) { var _this8; _this8 = _RetryableWriter.call(this, OPERATE_TYPE.PUBLISH) || this; _this8._name = MESSAGE_NAME.PUBLISH; _this8.topic = void 0; _this8.data = void 0; _this8.targetId = void 0; _this8.date = void 0; _this8.syncMsg = false; _this8.identifier = IDENTIFIER.PUB; _this8.topic = topic; _this8.data = utils.isString(data) ? BinaryHelper.writeUTF(data) : data; _this8.targetId = targetId; return _this8; } var _proto8 = PublishWriter.prototype; _proto8.writeMessage = function writeMessage(stream) { stream.writeUTF(this.topic); stream.writeUTF(this.targetId); RetryableWriter.prototype.writeMessage.apply(this, arguments); stream.write(this.data); }; return PublishWriter; }(RetryableWriter); var PubAckReader = function (_RetryableReader2) { _inheritsLoose(PubAckReader, _RetryableReader2); function PubAckReader() { var _this9; for (var _len7 = arguments.length, args = new Array(_len7), _key7 = 0; _key7 < _len7; _key7++) { args[_key7] = arguments[_key7]; } _this9 = _RetryableReader2.call.apply(_RetryableReader2, [this].concat(args)) || this; _this9._name = MESSAGE_NAME.PUB_ACK; _this9.status = void 0; _this9.date = 0; _this9.data = void 0; _this9.millisecond = 0; _this9.messageUId = void 0; _this9.timestamp = 0; _this9.identifier = IDENTIFIER.PUB; return _this9; } var _proto9 = PubAckReader.prototype; _proto9.readMessage = function readMessage(stream) { RetryableReader.prototype.readMessage.call(this, stream); this.date = stream.readInt(); this.status = stream.readByte() * 256 + stream.readByte(); this.millisecond = stream.readByte() * 256 + stream.readByte(); this.timestamp = this.date * 1000 + this.millisecond; this.messageUId = stream.readUTF(); }; return PubAckReader; }(RetryableReader); var PubAckWriter = function (_RetryableWriter2) { _inheritsLoose(PubAckWriter, _RetryableWriter2); function PubAckWriter(messageId) { var _this10; _this10 = _RetryableWriter2.call(this, OPERATE_TYPE.PUBACK) || this; _this10._name = MESSAGE_NAME.PUB_ACK; _this10.status = void 0; _this10.date = 0; _this10.millisecond = 0; _this10.messageUId = void 0; _this10.timestamp = 0; _this10.messageId = messageId; return _this10; } var _proto10 = PubAckWriter.prototype; _proto10.writeMessage = function writeMessage(stream) { RetryableWriter.prototype.writeMessage.call(this, stream); }; return PubAckWriter; }(RetryableWriter); var QueryWriter = function (_RetryableWriter3) { _inheritsLoose(QueryWriter, _RetryableWriter3); function QueryWriter(topic, data, targetId) { var _this11; _this11 = _RetryableWriter3.call(this, OPERATE_TYPE.QUERY) || this; _this11._name = MESSAGE_NAME.QUERY; _this11.topic = void 0; _this11.data = void 0; _this11.targetId = void 0; _this11.identifier = IDENTIFIER.QUERY; _this11.topic = topic; _this11.data = utils.isString(data) ? BinaryHelper.writeUTF(data) : data; _this11.targetId = targetId; return _this11; } var _proto11 = QueryWriter.prototype; _proto11.writeMessage = function writeMessage(stream) { stream.writeUTF(this.topic); stream.writeUTF(this.targetId); RetryableWriter.prototype.writeMessage.call(this, stream); stream.write(this.data); }; return QueryWriter; }(RetryableWriter); var QueryConWriter = function (_RetryableWriter4) { _inheritsLoose(QueryConWriter, _RetryableWriter4); function QueryConWriter(messageId) { var _this12; _this12 = _RetryableWriter4.call(this, OPERATE_TYPE.QUERYCON) || this; _this12._name = MESSAGE_NAME.QUERY_CON; _this12.messageId = messageId; return _this12; } return QueryConWriter; }(RetryableWriter); var QueryAckReader = function (_RetryableReader3) { _inheritsLoose(QueryAckReader, _RetryableReader3); function QueryAckReader() { var _this13; for (var _len8 = arguments.length, args = new Array(_len8), _key8 = 0; _key8 < _len8; _key8++) { args[_key8] = arguments[_key8]; } _this13 = _RetryableReader3.call.apply(_RetryableReader3, [this].concat(args)) || this; _this13._name = MESSAGE_NAME.QUERY_ACK; _this13.data = void 0; _this13.status = void 0; _this13.date = void 0; _this13.identifier = IDENTIFIER.QUERY; return _this13; } var _proto12 = QueryAckReader.prototype; _proto12.readMessage = function readMessage(stream) { RetryableReader.prototype.readMessage.call(this, stream); this.date = stream.readInt(); this.status = stream.readByte() * 256 + stream.readByte(); this.data = stream.readAll(); }; return QueryAckReader; }(RetryableReader); var getReaderByHeader = function getReaderByHeader(header) { var type = header.type, msg = new BaseReader(header); switch (type) { case OPERATE_TYPE.CONNACK: msg = new ConnAckReader(header); break; case OPERATE_TYPE.PUBLISH: msg = new PublishReader(header); msg.syncMsg = header.syncMsg; break; case OPERATE_TYPE.PUBACK: msg = new PubAckReader(header); break; case OPERATE_TYPE.QUERYACK: msg = new QueryAckReader(header); break; case OPERATE_TYPE.SUBACK: case OPERATE_TYPE.UNSUBACK: case OPERATE_TYPE.PINGRESP: msg = new PingRespReader(header); break; case OPERATE_TYPE.DISCONNECT: msg = new DisconnectReader(header); break; default: throw new Error('No support for deserializing ' + type + ' messages'); } return msg; }; var readWSBuffer = function readWSBuffer(data) { var arr = new Uint8Array(data); var stream = new RongStreamReader(arr); var flags = stream.readByte(), header = new Header(flags); var msg = getReaderByHeader(header); msg.read(stream, arr.length - 1); return msg; }; var readCometData = function readCometData(data) { var flags = data.headerCode, header = new Header(flags); var msg = getReaderByHeader(header); utils.forEach(data, function (item, key) { if (key in msg) { msg[key] = item; } }); return msg; }; var ENGINE_EVENT = { WATCH: 'watch', UN_WATCH: 'unwatch', CONNECT: 'connect', RECONNECT: 'reconnect', DISCONNECT: 'disconnect', CHANGE_USER: 'changeUser', GET_CONNECTION_STATUS: 'getConnectionStatus', GET_CONNECTION_USER_ID: 'getConnectionUserId', GET_CONNECTED_TIME: 'getConnectedTime', GET_APP_INFO: 'getAppInfo', GET_CONVERSATION_LIST: 'getConversationList', REMOVE_CONVERSATION_LIST: 'removeConversationList', REMOVE_CONVERSATION: 'removeConversation', GET_TOTAL_UNREAD_COUNT: 'getTotalUnreadCount', CLEAR_UNREAD_COUNT: 'clearUnreadCount', GET_LOCAL_CONVERSATION: 'getLocalConversation', SEND_MESSAGE: 'sendMessage', GET_HISTORY_MSGS: 'getHistoryMessages', DELETE_MESSAGES: 'deleteHistoryMessages', CLEAR_MESSAGES: 'clearHistoryMessages', RECALL_MESSAGE: 'recallMessage', JOIN_CHATROOM: 'joinChatRoom', QUIT_CHATROOM: 'quitChatRoom', GET_CHATROOM_INFO: 'getChatRoomInfo', GET_CHATROOM_MSGS: 'getChatRoomHistoryMessages', SET_KV: 'setChatRoomKV', FORCE_SET_KV: 'forceSetChatRoomKV', DEL_KV: 'removeChatRoomKV', FORCE_DEL_KV: 'forceRemoveChatRoomKV', GET_KV: 'getChatRoomKV', GET_ALL_KV: 'getAllChatRoomKV', JOIN_RTC: 'joinRTCRoom', QUIT_RTC: 'quitRTCRoom', PING_RTC: 'RTCPing', GET_RTC_ROOM_INFO: 'getRTCRoomInfo', SET_RTC_DATA: 'setRTCData', GET_RTC_DATA: 'getRTCData', DEL_RTC_DATA: 'removeRTCData', SET_RTC_OUT_DATA: 'setRTCOutData', GET_RTC_OUT_DATA: 'getRTCOutData', GET_RTC_TOKEN: 'getRTCToken', SET_RTC_STATE: 'setRTCState', GET_RTC_USER_INFO_LIST: 'getRTCUserInfoList', SET_RTC_USER_INFO: 'setRTCUserInfo', DEL_RTC_USER_INFO: 'removeRTCUserInfo', GET_RTC_USER_LIST: 'getRTCUserList', GET_UPLOAD_TOKEN: 'getFileToken', GET_UPLOAD_URL: 'getFileUrl' }; var ENGINE_EVENT_NEED_CONNECTED = [ENGINE_EVENT.GET_CONVERSATION_LIST, ENGINE_EVENT.REMOVE_CONVERSATION_LIST, ENGINE_EVENT.REMOVE_CONVERSATION, ENGINE_EVENT.GET_TOTAL_UNREAD_COUNT, ENGINE_EVENT.CLEAR_UNREAD_COUNT, ENGINE_EVENT.SEND_MESSAGE, ENGINE_EVENT.GET_HISTORY_MSGS, ENGINE_EVENT.DELETE_MESSAGES, ENGINE_EVENT.CLEAR_MESSAGES, ENGINE_EVENT.RECALL_MESSAGE, ENGINE_EVENT.JOIN_CHATROOM, ENGINE_EVENT.QUIT_CHATROOM, ENGINE_EVENT.GET_CHATROOM_INFO, ENGINE_EVENT.GET_CHATROOM_MSGS]; var ENGINE_EVENT_NEED_DISCONNECTED = [ENGINE_EVENT.CONNECT, ENGINE_EVENT.RECONNECT]; var IM_EVENT = { STATUS: 'status', MESSAGE: 'message', CONVERSATION: 'conversation' }; var TRANSPORT_EVENT = { SIGNAL: 'signal', STATUS: 'status' }; var SERVER_EVENT_NAME = { STATUS: 'status', NOTIFY_PULL: 'notifyPull', DIRECT_MSG: 'directMessage', CHRM_KV_CHANGED: 'chatRoomKV', CHRM_KV_SET: 'chatRoomKVSet', MESSAGE_SEND: 'sendMessage', JOIN_CHATROOM: 'joinChatRoom', BEFORE_JOIN_CHATROOM: 'beforeJoinChatRoom' }; var _APP_ENGINE_EVENT_LOG; var PLATFORM$1 = 'Web'; var LEVEL = { FATAL: 0, ERROR: 1, WARN: 2, INFO: 3, DEBUG: 4 }; var STORE_SIZE = { ADVANCED: 500, LOW: 500 }; var LOG_TYPE = { 'IM': 'IM', 'RTC': 'RTC' }; var TAG = { L_GET_NAVI_T: 'L-get_navi-T', L_GET_NAVI_R: 'L-get_navi-R', L_PING_WS_T: 'L-ping_ws-T', L_PING_WS_R: 'L-ping_ws-R', L_NETWORK_CHANGED_S: 'L-network_changed-S', L_DECODE_MSG_E: 'L-decode_msg-E', L_RECONNECT_T: 'L-reconnect-T', L_RECONNECT_R: 'L-reconnect-R', L_PULL_CHRM_KV_T: 'L-pull-chrm-kv-T', L_PULL_CHRM_KV_R: 'L-pull-chrm-kv-R', L_PING_S: 'L-ping-S', L_CRASH_F: 'L-crash_web-F', A_INIT_O: 'A-init-O', A_CONNECT_T: 'A-connect-T', A_CONNECT_R: 'A-connect-R', A_DISCONNECT_T: 'A-disconnect-T', A_DISCONNECT_R: 'A-disconnect-R', A_RECONNECT_T: 'A-reconnect-T', A_RECONNECT_R: 'A-reconnect-R', A_JOIN_CHATROOM_T: 'A-join_chatroom-T', A_JOIN_CHATROOM_R: 'A-join_chatroom-R', A_QUIT_CHATROOM_T: 'A-quit_chatroom-T', A_QUIT_CHATROOM_R: 'A-quit_chatroom-R', P_NOTIFY_CHRM_KV_S: 'P-notify-chrm-kv-R', G_CRASH_E: 'G-crash-E', G_UPLOAD_LOG_S: 'G-upload_log-S', G_UPLOAD_LOG_E: 'G-upload_log-E' }; var APP_ENGINE_EVENT_LOG_TAG = (_APP_ENGINE_EVENT_LOG = {}, _APP_ENGINE_EVENT_LOG[ENGINE_EVENT.CONNECT] = { req: TAG.A_CONNECT_T, resp: TAG.A_CONNECT_R }, _APP_ENGINE_EVENT_LOG[ENGINE_EVENT.DISCONNECT] = { req: TAG.A_DISCONNECT_T, resp: TAG.A_DISCONNECT_R }, _APP_ENGINE_EVENT_LOG[ENGINE_EVENT.RECONNECT] = { req: TAG.A_RECONNECT_T, resp: TAG.A_RECONNECT_R }, _APP_ENGINE_EVENT_LOG[ENGINE_EVENT.JOIN_CHATROOM] = { req: TAG.A_JOIN_CHATROOM_T, resp: TAG.A_JOIN_CHATROOM_R }, _APP_ENGINE_EVENT_LOG[ENGINE_EVENT.QUIT_CHATROOM] = { req: TAG.A_QUIT_CHATROOM_T, resp: TAG.A_QUIT_CHATROOM_R }, _APP_ENGINE_EVENT_LOG); var REPORT_TYPE = { REALTIME: 0, FULL: 1 }; var CSV_LOG_TPL = '{sessionId},{time},{type},{level},{tag},{content}\n'; var REALTIME_URL_TPL = '{protocol}{url}?version={version}&appkey={appkey}&userId={userId}&deviceId={deviceId}&deviceInfo={deviceInfo}&platform={platform}'; var MSGNOTIF_URL_TPL = '{protocol}{url}?version={version}&appkey={appkey}&userId={userId}&logId={logId}&deviceId={deviceId}&deviceInfo={deviceInfo}&platform={platform}'; var LOG_CMD_MSG_SENDER = 'rongcloudsystem'; var NO_FULL_LOG = 'nodata'; var REQUEST_TIMEOUT = 15000; var DEFAULT_SERVER_OPTION = { isOpen: true, url: 'logcollection.ronghub.com', realtimeLevel: LEVEL.ERROR, realtimeInterval: 20000, realtimeMaxTimes: 5, fullInterval: 5000, fullMaxTimes: 3, fullLevel: LEVEL.DEBUG }; var isEmpty$1 = utils.isEmpty, tplEngine$1 = utils.tplEngine, getRandomNum$1 = utils.getRandomNum; var getTransporterUrl = function getTransporterUrl(option) { var domain = option.domain, appkey = option.appkey, token = option.token, connectType = option.connectType, protocol = option.protocol; var isComet = connectType === CONNECT_TYPE.COMET; var cmpTpl = CMP_URL_TPL; if (isEmpty$1(protocol)) { protocol = isComet ? env.protocol.http : env.protocol.ws; } var tplOption = { domain: domain, appkey: appkey, protocol: protocol, apiVer: getRandomNum$1(1e6), token: utils.encodeURI(token) }; if (env.isMini) { cmpTpl = MINI_CMP_URL_TPL; utils.extend(tplOption, { platform: PLATFORM_TYPE.MINI }); } return tplEngine$1(cmpTpl, tplOption); }; var isGroup = function isGroup(type) { return type === CONVERSATION_TYPE.GROUP; }; var isChatRoom = function isChatRoom(type) { return type === CONVERSATION_TYPE.CHATROOM; }; var getConversationTypeList = function getConversationTypeList() { return utils.getValues(CONVERSATION_TYPE); }; var isValidConversationType = function isValidConversationType(type) { var conversationTypeList = getConversationTypeList(); return utils.isNumber(type) && utils.isInclude(conversationTypeList, type); }; var getSessionId = function getSessionId(option) { var isStatusMessage = option.isStatusMessage; var isPersited = option.isPersited, isCounted = option.isCounted, isMentiond = option.isMentiond; if (isStatusMessage) { isPersited = isCounted = false; } var sessionId = 0; if (isPersited) { sessionId = sessionId | 0x01; } if (isCounted) { sessionId = sessionId | 0x02; } if (isMentiond) { sessionId = sessionId | 0x04; } return sessionId; }; var getPersitedAndCountedBySessionId = function getPersitedAndCountedBySessionId(sessionId) { var isPersited, isCounted; switch (sessionId) { case MESSAGE_TAG.COUNT_ONLY: isPersited = false; isCounted = true; break; case MESSAGE_TAG.PERSIT_ONLY: isPersited = true; isCounted = false; break; case MESSAGE_TAG.NONE: isPersited = isCounted = false; break; case MESSAGE_TAG.PERSIT_AND_COUNT: default: isPersited = isCounted = true; break; } return { isPersited: isPersited, isCounted: isCounted }; }; var getMessageOptionByStatus = function getMessageOptionByStatus(status) { var isPersited = true, isCounted = true, isMentiond = false; isPersited = !!(status & 0x10); isCounted = !!(status & 0x20); isMentiond = !!(status & 0x40); return { isPersited: isPersited, isCounted: isCounted, isMentiond: isMentiond }; }; var SignalId = { ids: {}, temp: '{appkey}_{userId}', get: function get(option) { var key = utils.tplEngine(SignalId.temp, option); var id = SignalId.ids[key] || 0; id++; SignalId.ids[key] = id; return id; }, clear: function clear(option) { var key = utils.tplEngine(SignalId.temp, option); SignalId.ids[key] = 0; }, isExceedLimit: function isExceedLimit(id) { return id > MAX_SINGAL_ID; } }; var RCSocket = function () { function RCSocket(options) { this._socket = void 0; this.eventEmitter = new utils.EventEmitter(); this.KEY = { OPEN: 'open', MSG: 'msg', ERROR: 'error', CLOSE: 'close' }; var self = this; var KEY = self.KEY; self._socket = new utils.Socket(options); self._socket.onOpen(function (data) { self.eventEmitter.emit(KEY.OPEN, data); }); self._socket.onMessage(function (data) { self.eventEmitter.emit(KEY.MSG, data); }); self._socket.onError(function (data) { data = self._formatCloseData(data); self.eventEmitter.emit(KEY.ERROR, data); }); self._socket.onClose(function (data) { data = self._formatCloseData(data); self.eventEmitter.emit(KEY.CLOSE, data); }); } var _proto = RCSocket.prototype; _proto._formatCloseData = function _formatCloseData(data) { if (env.isMini) { data = data || {}; var _data = data, errMsg = _data.errMsg; data.code = MINI_ERROR_MSG_TO_STATUS[errMsg]; } return data; }; _proto.send = function send(data) { return this._socket.send(data); }; _proto.close = function close() { this.eventEmitter.clear(); this._socket.close(); }; _proto.onOpen = function onOpen(event) { this.eventEmitter.on(this.KEY.OPEN, event); }; _proto.onMessage = function onMessage(event) { this.eventEmitter.on(this.KEY.MSG, event); }; _proto.onError = function onError(event) { this.eventEmitter.on(this.KEY.ERROR, event); }; _proto.onClose = function onClose(event) { this.eventEmitter.on(this.KEY.CLOSE, event); }; return RCSocket; }(); var RCStorage = function () { function RCStorage(suffix) { var _ref; this._cache = void 0; this.STORAGE_KEY = void 0; var storageKey = suffix ? STORAGE_ROOT_KEY + suffix : STORAGE_ROOT_KEY; var localCache = utils.Storage.get(storageKey) || {}; this._cache = new utils.Cache((_ref = {}, _ref[storageKey] = localCache, _ref)); this.STORAGE_KEY = storageKey; } var _proto2 = RCStorage.prototype; _proto2._get = function _get() { var KEY = this.STORAGE_KEY; return this._cache.get(KEY) || {}; }; _proto2._set = function _set(cache) { var KEY = this.STORAGE_KEY; cache = cache || {}; this._cache.set(KEY, cache); utils.Storage.set(KEY, cache); }; _proto2.set = function set(key, value) { var localValue = this._get(); localValue[key] = value; this._set(localValue); }; _proto2.remove = function remove(key) { var localValue = this._get(); delete localValue[key]; this._set(localValue); }; _proto2.clear = function clear() { var KEY = this.STORAGE_KEY; utils.Storage.remove(KEY); this._cache.remove(KEY); }; _proto2.get = function get(key) { var localValue = this._get(); return localValue[key]; }; _proto2.getKeys = function getKeys() { var localValue = this._get(); return utils.getKeys(localValue); }; _proto2.getValues = function getValues() { return this._get() || {}; }; return RCStorage; }(); var formatSyncTime = function formatSyncTime(_syncTime) { _syncTime = _syncTime || {}; _syncTime.inboxTime = _syncTime.inboxTime || 0; _syncTime.sendboxTime = _syncTime.sendboxTime || 0; return _syncTime; }; var MessageTimeSyner = function () { function MessageTimeSyner(option) { this._syncTime = void 0; this._storage = void 0; option = option || {}; var _option = option, startSyncTime = _option.startSyncTime; this._initStorage(option); if (startSyncTime) { this._syncTime = formatSyncTime(startSyncTime); } } var _proto3 = MessageTimeSyner.prototype; _proto3._initStorage = function _initStorage(option) { var appkey = option.appkey, userId = option.userId; var ROOT_KEY = utils.tplEngine(STORAGE_SYNC_TIME.ROOT_KEY_TPL, { appkey: appkey, userId: userId }); var storage = new RCStorage(ROOT_KEY); var syncTime = { sendboxTime: storage.get(STORAGE_SYNC_TIME.SUB_KEY.SENDBOX), inboxTime: storage.get(STORAGE_SYNC_TIME.SUB_KEY.INBOX) }; this._storage = storage; this._syncTime = formatSyncTime(syncTime); }; _proto3.setInbox = function setInbox(time) { var beforeTime = this._syncTime.inboxTime || 0; if (beforeTime < time) { this._syncTime.inboxTime = time; this._storage.set(STORAGE_SYNC_TIME.SUB_KEY.INBOX, time); } }; _proto3.setSendbox = function setSendbox(time) { var beforeTime = this._syncTime.sendboxTime || 0; if (beforeTime < time) { this._syncTime.sendboxTime = time; this._storage.set(STORAGE_SYNC_TIME.SUB_KEY.SENDBOX, time); } }; _proto3.setByMessage = function setByMessage(msg) { var messageDirection = msg.messageDirection, sentTime = msg.sentTime; var isSelfSend = messageDirection === MESSAGE_DIRECTION.SEND; isSelfSend ? this.setSendbox(sentTime) : this.setInbox(sentTime); }; _proto3.get = function get() { return formatSyncTime(this._syncTime); }; return MessageTimeSyner; }(); var ChatRoomMessageTimeSyner = function () { function ChatRoomMessageTimeSyner() { this._pullTimes = {}; } var _proto4 = ChatRoomMessageTimeSyner.prototype; _proto4.set = function set(chrmId, time) { this._pullTimes[chrmId] = time; }; _proto4.get = function get(chrmId) { return this._pullTimes[chrmId] || 0; }; _proto4.setByMessage = function setByMessage(msg) { var sentTime = msg.sentTime; var chrmId = msg.targetId; var beforeTime = this.get(chrmId); if (beforeTime < sentTime) { this.set(chrmId, sentTime); } }; return ChatRoomMessageTimeSyner; }(); var getUIDByToken = function getUIDByToken(token) { return utils.md5(token).slice(8, 16); }; var isIncludeNavi = function isIncludeNavi(token) { return utils.isInclude(token, NAVI_SEPARATOR_IN_TOKEN); }; var getNaviListByToken = function getNaviListByToken(token) { var navDomainList = []; if (isIncludeNavi(token)) { var separatorIndex = utils.indexOf(token, NAVI_SEPARATOR_IN_TOKEN); var navsText = token.substring(separatorIndex + 1, token.length); var domainList = navsText.split(DOMAIN_SEPARATOR_IN_NAVLIST); utils.forEach(domainList, function (domain) { if (!isEmpty$1(domain)) { navDomainList.push(domain); } }); } return navDomainList; }; var getCMPDomainList = function getCMPDomainList(option, customOption) { var server = option.server, backupServer = option.backupServer; server = server || ''; backupServer = backupServer || ''; var backupCMPList = backupServer.split(DOMAIN_SEPARATOR_IN_CMPLIST); var cmpList = []; if (!utils.isEmpty(server)) { cmpList.push(server); } utils.forEach(backupCMPList, function (cmp) { if (!utils.isEmpty(cmp)) { cmpList.push(cmp); } }); if (!utils.isUndefined(customOption.customCMP)) { cmpList = customOption.customCMP; } return cmpList; }; var getValidToken = function getValidToken(token) { if (isIncludeNavi(token)) { var separatorIndex = utils.indexOf(token, NAVI_SEPARATOR_IN_TOKEN); token = token.substring(0, separatorIndex + 1); } return token; }; var getConnectType = function getConnectType(option) { var connectType = option.connectType; var isSpecifiedSocket = connectType === CONNECT_TYPE.WEBSOCKET; var isSocket = isSpecifiedSocket && utils.isSupportSocket(); return isSocket ? CONNECT_TYPE.WEBSOCKET : CONNECT_TYPE.COMET; }; var isConnected = function isConnected(status) { return utils.isEqual(status, CONNECTION_STATUS.CONNECTED); }; var isConnecting = function isConnecting(status) { return utils.isEqual(status, CONNECTION_STATUS.CONNECTING); }; var isDisconnected = function isDisconnected(status) { return !isConnected(status) && !isConnecting(status); }; var getNavReqOption = function getNavReqOption(option, user) { option = utils.copy(option); option.token = user.token; return option; }; var getPingTimeout = function getPingTimeout(timeSpentConnect) { var timeout = timeSpentConnect * 3; if (timeout < IM_PING_MIN_TIMEOUT) { return IM_PING_MIN_TIMEOUT; } if (timeout > IM_PING_MAX_TIMEOUT) { return IM_PING_MAX_TIMEOUT; } return timeout; }; var fixConversationData = function fixConversationData(conversation) { conversation = conversation || {}; conversation.latestMessage = conversation.latestMessage || {}; conversation.latestMessage.sentTime = conversation.latestMessage.sentTime || 0; return conversation; }; var sortConversationList = function sortConversationList(conversationList) { return utils.quickSort(conversationList, function (before, after) { before = fixConversationData(before); after = fixConversationData(after); return after.latestMessage.sentTime <= before.latestMessage.sentTime; }); }; var DelayTimer = { _delayTime: 0, setTime: function setTime(time) { var currentTime = utils.getCurrentTimestamp(); DelayTimer._delayTime = currentTime - time; }, getTime: function getTime() { var delayTime = DelayTimer._delayTime; var currentTime = utils.getCurrentTimestamp(); return currentTime - delayTime; } }; var isSupportStatusMessage = function isSupportStatusMessage(type) { return !!CONVERSATION_TYPE_TO_PUBLISH_STATUS_TOPIC[type]; }; var getConversationKey = function getConversationKey(option) { var type = option.type, targetId = option.targetId; return type + '_' + targetId; }; var getChatRoomKVOptStatus = function getChatRoomKVOptStatus(entity, action) { var status = 0; if (entity.isAutoDelete) { status = status | CHATROOM_KV_STATUS_CODE.AUTO_DELETE; } if (entity.isOverwrite) { status = status | CHATROOM_KV_STATUS_CODE.OVERWRITE; } if (utils.isEqual(action, CHATROOM_ENTRY_TYPE.DELETE)) { status = status | CHATROOM_KV_STATUS_CODE.OPERATE; } return status; }; var getChatRoomKVByStatus = function getChatRoomKVByStatus(status) { var isDeleteOpt = !!(status & CHATROOM_KV_STATUS_CODE.OPERATE); return { isAutoDelete: !!(status & CHATROOM_KV_STATUS_CODE.AUTO_DELETE), isOverwrite: !!(status & CHATROOM_KV_STATUS_CODE.OVERWRITE), type: isDeleteOpt ? CHATROOM_ENTRY_TYPE.DELETE : CHATROOM_ENTRY_TYPE.UPDATE }; }; var TextCompressor = { _dataType: { Tail: 0x30, Compressed: 0x40, NormalExt: 0x50, Normal: 0x60, Mark: 0x70 }, _chars: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', _scale: 62, _max: 238327, _indexOf: function _indexOf(map, source, fromIndex) { var result = { length: 0, offset: -1 }; if (fromIndex >= source.length - 1) { return result; } var c1 = source.charAt(fromIndex); var c2 = source.charAt(fromIndex + 1); var items = map[c1 + c2]; if (items[0] === fromIndex) { return result; } var space1 = source.length - fromIndex; for (var i = 0, len = items.length; i < len; i++) { var item = items[i]; var space2 = fromIndex - item; if (space2 > TextCompressor._max) { continue; } var end = Math.min(space1, space2); if (end <= result.length) { break; } if (result.length > 2) { if (source.charAt(item + result.length - 1) !== source.charAt(fromIndex + result.length - 1)) { continue; } } var m = 2; for (var j = m; j < end; j++) { if (source.charAt(item + j) === source.charAt(fromIndex + j)) { m++; } else { break; } } if (m >= result.length) { result.length = m; result.offset = item; } } return result; }, _numberEncode: function _numberEncode(num) { var result = [], remainder = 0; do { remainder = num % TextCompressor._scale; result.push(TextCompressor._chars.charAt(remainder)); num = (num - remainder) / TextCompressor._scale; } while (num > 0); return result.join(''); }, _numberDecode: function _numberDecode(str) { var num = 0, index = 0; for (var i = str.length - 1; i >= 0; i--) { index = TextCompressor._chars.indexOf(str.charAt(i)); if (index === -1) { throw new Error('decode number error, data is \'' + str + '\''); } num = num * TextCompressor._scale + index; } return num; }, compress: function compress(data) { var map = {}; for (var p = 0; p < data.length - 1; p++) { var c1 = data.charAt(p); var c2 = data.charAt(p + 1); var c = c1 + c2; if (!map.hasOwnProperty(c)) { map[c] = [p]; continue; } map[c].push(p); } var compressedData = [], normalBlockBuffer = []; var encodeNormalBlock = function encodeNormalBlock() { if (normalBlockBuffer.length > 0) { var normalBlock = normalBlockBuffer.join(''); normalBlockBuffer = []; if (normalBlock.length > 26) { var normalExtBlockLength = TextCompressor._numberEncode(normalBlock.length); var normalExtBlockHeader = String.fromCharCode(TextCompressor._dataType.NormalExt | normalExtBlockLength.length); compressedData.push(normalExtBlockHeader + normalExtBlockLength); } else { var normalBlockHeader = String.fromCharCode(TextCompressor._dataType.Normal | normalBlock.length); compressedData.push(normalBlockHeader); } compressedData.push(normalBlock); } }; var i = 0; while (i < data.length) { var r = TextCompressor._indexOf(map, data, i); if (r.length < 2) { normalBlockBuffer.push(data.charAt(i++)); continue; } if (r.length < 4) { normalBlockBuffer.push(data.substr(i, r.length)); i += r.length; continue; } var offset = TextCompressor._numberEncode(i - r.offset); var length = TextCompressor._numberEncode(r.length); if (offset.length + length.length >= r.length) { normalBlockBuffer.push(data.substr(i, r.length)); i += r.length; continue; } encodeNormalBlock(); var compressedBlockHeader = String.fromCharCode(TextCompressor._dataType.Compressed | offset.length << 2 | length.length); compressedData.push(compressedBlockHeader + offset + length); i += r.length; } encodeNormalBlock(); var dataLengthTo62 = TextCompressor._numberEncode(data.length); var tailBlockHeader = String.fromCharCode(TextCompressor._dataType.Tail | dataLengthTo62.length); compressedData.push(tailBlockHeader + dataLengthTo62); return compressedData.join(''); }, uncompress: function uncompress(data) { var i = 0; var result = ''; label1: do { var header = data.charCodeAt(i++); var headerType = header & TextCompressor._dataType.Mark; var headerVal = header & 0xF; switch (headerType) { case TextCompressor._dataType.Compressed: var p1 = headerVal >> 2; var p2 = headerVal & 3; if (p1 === 0 || p2 === 0) { throw new Error('Data parsing error,at ' + i); } var offset = TextCompressor._numberDecode(data.substr(i, p1)); var len = TextCompressor._numberDecode(data.substr(i += p1, p2)); offset = result.length - offset; if (offset + len > result.length) { throw new Error('Data parsing error,at ' + i); } i += p2; result += result.substr(offset, len); break; case TextCompressor._dataType.Tail: var num = TextCompressor._numberDecode(data.substr(i, headerVal)); if (num !== result.length) { throw new Error('Data parsing error,at ' + i); } i += headerVal; break label1; case TextCompressor._dataType.NormalExt: var normalNum = TextCompressor._numberDecode(data.substr(i, headerVal)); result += data.substr(i += headerVal, normalNum); i += normalNum; break; case TextCompressor._dataType.Normal: result += data.substr(i, headerVal); i += headerVal; break; case TextCompressor._dataType.Mark: if (headerVal > 10) { throw new Error('Data parsing error,at ' + i); } result += data.substr(i, 16 + headerVal); i += 16 + headerVal; break; default: throw new Error('Data parsing error,at ' + i + ' header:' + headerType); } } while (i < data.length); return result; } }; var isBelowIE = function isBelowIE(version) { var system = env.system; var flag = system.model === 'IE' && Number(system.version) < version ? true : false; return flag; }; var stringToCsv = function stringToCsv(str) { var csvStr = str.replace(/"/g, '""'); var tpl = '"{csvStr}"'; return tplEngine$1(tpl, { csvStr: csvStr }); }; var getWebSessionId = function getWebSessionId() { var sessionId = utils.Session.get(STORAGE_SESSION_ID_KEY); if (utils.isEmpty(sessionId)) { sessionId = utils.getUUID22().slice(0, 10); utils.Session.set(STORAGE_SESSION_ID_KEY, sessionId); } return sessionId; }; var getDeviceId = function getDeviceId() { var deviceId = utils.Storage.get(STORAGE_DEVICE_ID_KEY); if (utils.isEmpty(deviceId)) { deviceId = utils.getUUID22(); utils.Storage.set(STORAGE_DEVICE_ID_KEY, deviceId); } return deviceId; }; var getDeviceInfo = function getDeviceInfo() { var tpl = '{brower}|{version}|{sessionId}'; return tplEngine$1(tpl, { brower: env.system.model, version: env.system.version, sessionId: getWebSessionId() }); }; var getReportLogUrl = function getReportLogUrl(params) { var entireUrl = '', protocol = env.protocol.http + '//'; var urlConf = { protocol: protocol, url: params.url, version: SDK_VERSION, appkey: params.appkey, deviceId: getDeviceId(), deviceInfo: getDeviceInfo(), platform: PLATFORM$1, userId: params.userId }; switch (params.type) { case REPORT_TYPE.REALTIME: entireUrl = tplEngine$1(REALTIME_URL_TPL, urlConf); break; case REPORT_TYPE.FULL: entireUrl = tplEngine$1(MSGNOTIF_URL_TPL, utils.extend(urlConf, { logId: params.logId })); break; default: break; } return entireUrl; }; var isLogCommandMsg = function isLogCommandMsg(msg) { var content = msg.content; return msg.messageType === MESSAGE_TYPE.LOG_COMMAND && msg.senderUserId === LOG_CMD_MSG_SENDER && content.platform === 'Web'; }; var isValidChatRoomKey = function isValidChatRoomKey(key) { if (!utils.isString(key)) { return; } var isValid = /^[A-Za-z0-9_=+-]+$/.test(key), keyLen = key.length, isLimit = keyLen <= CHATROOM_KEY_LENGTH.MAX && keyLen >= CHATROOM_KEY_LENGTH.MIN; return isValid && isLimit; }; var isValidChatRoomValue = function isValidChatRoomValue(value) { if (!utils.isString(value)) { return; } var valLen = value.length; return valLen <= CHATROOM_VALUE_LENGTH.MAX && valLen >= CHATROOM_VALUE_LENGTH.MIN; }; var common = { isConnected: isConnected, isConnecting: isConnecting, isDisconnected: isDisconnected, getConnectType: getConnectType, getTransporterUrl: getTransporterUrl, isGroup: isGroup, isChatRoom: isChatRoom, getConversationTypeList: getConversationTypeList, isValidConversationType: isValidConversationType, getUIDByToken: getUIDByToken, getSessionId: getSessionId, getMessageOptionByStatus: getMessageOptionByStatus, getPersitedAndCountedBySessionId: getPersitedAndCountedBySessionId, SignalId: SignalId, MessageTimeSyner: MessageTimeSyner, ChatRoomMessageTimeSyner: ChatRoomMessageTimeSyner, getCMPDomainList: getCMPDomainList, getNaviListByToken: getNaviListByToken, getValidToken: getValidToken, RCSocket: RCSocket, RCStorage: RCStorage, getNavReqOption: getNavReqOption, getPingTimeout: getPingTimeout, fixConversationData: fixConversationData, sortConversationList: sortConversationList, DelayTimer: DelayTimer, isSupportStatusMessage: isSupportStatusMessage, getConversationKey: getConversationKey, getChatRoomKVOptStatus: getChatRoomKVOptStatus, getChatRoomKVByStatus: getChatRoomKVByStatus, TextCompressor: TextCompressor, isBelowIE: isBelowIE, getReportLogUrl: getReportLogUrl, isLogCommandMsg: isLogCommandMsg, getWebSessionId: getWebSessionId, getDeviceId: getDeviceId, stringToCsv: stringToCsv, isValidChatRoomKey: isValidChatRoomKey, isValidChatRoomValue: isValidChatRoomValue }; var EventEmitter$1 = utils.EventEmitter, DeferHandler$1 = utils.DeferHandler, Timer$1 = utils.Timer; var RCSocket$1 = common.RCSocket; var TransHandlerID = { CONNECT: 'connect', PING: 'ping' }; var Heartbeat = function () { function Heartbeat(transporter, option) { this._transporter = void 0; this._timer = void 0; option = option || {}; var timeout = option.timeout; this._transporter = transporter; this._timer = new Timer$1({ type: TIMER_TYPE.INTERVAL, timeout: timeout }); } var _proto = Heartbeat.prototype; _proto.check = function check(timeout) { var _transporter = this._transporter; var _deferHandler = _transporter._deferHandler; var pingReqSignal = new PingReqWriter(); _transporter.sendSignal(pingReqSignal); return utils.deferred(function (resolve, reject) { _deferHandler.add(TransHandlerID.PING, { resolve: resolve, reject: reject }, { timeout: timeout }); }); }; _proto.start = function start(timeout, onError) { var self = this; self._timer.start(function () { self.check(timeout).then(utils.noop)["catch"](onError); }); }; _proto.stop = function stop() { this._timer && this._timer.stop(); }; return Heartbeat; }(); var SocketTransporter = function () { function SocketTransporter(option) { this._socket = void 0; this._option = void 0; this._transporterEventEmiiter = new EventEmitter$1(); this._deferHandler = new DeferHandler$1(); this._heartbeat = new Heartbeat(this, { timeout: IM_PING_INTERVAL_TIME }); this._connectedTime = void 0; this._option = option; } var _proto2 = SocketTransporter.prototype; _proto2._createSocket = function _createSocket(url) { var self = this; var _transporterEventEmiiter = self._transporterEventEmiiter; var socket = new RCSocket$1({ url: url }); var onClose = function onClose(event) { event = event || {}; var code = event.code || TRANSPORTER_STATUS.CLOSE_ABNORMAL; _transporterEventEmiiter.emit(TRANSPORT_EVENT.STATUS, code); self.disconnect(); }; socket.onMessage(function (msg) { var data = msg.data; if (!utils.isArrayBuffer(data)) { throw new Error('Error socket signal'); } var signal = readWSBuffer(data); self.handleSignal(signal); }); socket.onError(onClose); socket.onClose(onClose); return socket; }; _proto2._startHeartbeat = function _startHeartbeat(timeSpentConnect) { var self = this; var _heartbeat = self._heartbeat, _transporterEventEmiiter = self._transporterEventEmiiter; _heartbeat.check(FIRST_PING_TIMEOUT).then(utils.noop)["catch"](function () { _transporterEventEmiiter.emit(TRANSPORT_EVENT.STATUS, TRANSPORTER_STATUS.PING_FIRST_TIMEOUT); self.disconnect(); }); var pingTimeout = common.getPingTimeout(timeSpentConnect); _heartbeat.start(pingTimeout, function () { _transporterEventEmiiter.emit(TRANSPORT_EVENT.STATUS, TRANSPORTER_STATUS.PING_TIMEOUT); self.disconnect(); }); }; _proto2._stopHeartbeat = function _stopHeartbeat() { this._heartbeat.stop(); }; _proto2.watchSignal = function watchSignal(watcher) { this._transporterEventEmiiter.on(TRANSPORT_EVENT.SIGNAL, watcher); }; _proto2.watchStatus = function watchStatus(watcher) { this._transporterEventEmiiter.on(TRANSPORT_EVENT.STATUS, watcher); }; _proto2.connect = function connect(user, option) { var self = this; var _self$_option = self._option, appkey = _self$_option.appkey, connectType = _self$_option.connectType, _deferHandler = self._deferHandler; var token = user.token; var domain = option.domain; var url = common.getTransporterUrl({ domain: domain, appkey: appkey, connectType: connectType, token: token }); var timeBeforeConnect = utils.getCurrentTimestamp(); self._socket = this._createSocket(url); return utils.deferred(function (resolve, reject) { _deferHandler.add(TransHandlerID.CONNECT, { resolve: resolve, reject: reject }); }).then(function (result) { var timeAfterConnect = utils.getCurrentTimestamp(); var timeSpentConnect = timeAfterConnect - timeBeforeConnect; self._startHeartbeat(timeSpentConnect); return result; }); }; _proto2.sendSignal = function sendSignal(writer) { var binary = writer.getBufferData(); this._socket.send(binary.buffer); }; _proto2.handleSignal = function handleSignal(signal) { var _transporterEventEmiiter = this._transporterEventEmiiter, _deferHandler = this._deferHandler; if (signal instanceof ConnAckReader) { this.handleConnAck(signal); } else if (signal instanceof PingRespReader) { _deferHandler.resolve(TransHandlerID.PING); } else { _transporterEventEmiiter.emit(TRANSPORT_EVENT.SIGNAL, signal); } if (signal && utils.isValidTimestamp(signal.timestamp)) { common.DelayTimer.setTime(signal.timestamp); } }; _proto2.handleConnAck = function handleConnAck(signal) { var self = this; var _deferHandler = self._deferHandler, _transporterEventEmiiter = self._transporterEventEmiiter; var status = signal.status; var isConnected = status === SUCCESS_CODE; var event = isConnected ? _deferHandler.resolve : _deferHandler.reject; event.call(_deferHandler, TransHandlerID.CONNECT, signal); if (isConnected) { self._connectedTime = utils.getCurrentTimestamp(); } isConnected && _transporterEventEmiiter.emit(TRANSPORT_EVENT.STATUS, TRANSPORTER_STATUS.CONNECTED); }; _proto2.disconnect = function disconnect() { this._stopHeartbeat(); this._socket && this._socket.close(); }; return SocketTransporter; }(); var logEventEmitter = new utils.EventEmitter(); var LogEventName = 'log'; var LocalLogPrefix = '[Rong]'; var ServerOption = DEFAULT_SERVER_OPTION; var Option = { isDebug: false, isUploadToServer: false, appkey: '', userId: '', isNetworkUnavailable: true }; var realTimeUploadHasStarted = false, RealtimeUploadTimes = 1, isRealtimeUploading = false, fullLogId = ''; var isFirstDefaultUpload = function isFirstDefaultUpload(interval) { return interval === 20000; }; var getRealtimeUploadInterval = function getRealtimeUploadInterval(uploadTimes) { var realtimeInterval = ServerOption.realtimeInterval; return realtimeInterval * Math.pow(2, uploadTimes - 1); }; var getFullUploadInterval = function getFullUploadInterval(uploadTimes) { var fullInterval = ServerOption.fullInterval; return fullInterval * Math.pow(2, uploadTimes - 1); }; var getCSVForLog = function getCSVForLog(log) { log = log || {}; var content = log.content || {}; utils.forEach(content, function (val, key) { if (utils.isObject(val) || utils.isArray(val)) { content[key] = utils.toJSON(val); } }); content = utils.toJSON(content) || '""'; content = common.stringToCsv(content); return utils.tplEngine(CSV_LOG_TPL, { sessionId: common.getWebSessionId(), time: log.time, type: log.type, level: log.level, tag: log.tag, content: content }); }; var setServerOption = function setServerOption(serverData) { var logSwitch = serverData.logSwitch, logPolicy = serverData.logPolicy; var isOpen = !!logSwitch; if (utils.isEmpty(serverData)) return; ServerOption.isOpen = isOpen; if (!isOpen) { return; } var logConf = utils.parseJSON(logPolicy || '') || {}; var url = logConf.url, level = logConf.level, itv = logConf.itv, times = logConf.times; utils.extend(ServerOption, { url: url, realtimeLevel: Number(level), realtimeInterval: Number(itv) * 1000, realtimeMaxTimes: Number(times) }); }; var setServerResponseOption = function setServerResponseOption(resText) { var resConf = utils.parseJSON(resText || ''); var nextTime = resConf.nextTime, level = resConf.level, logSwitch = resConf.logSwitch; if (utils.isEmpty(resConf)) return; var isOpen = !!logSwitch; ServerOption.isOpen = isOpen; if (!isOpen) return; utils.extend(ServerOption, { realtimeLevel: Number(level), realtimeInterval: Number(nextTime) * 1000 }); }; var getLogLevel = function getLogLevel(log) { log = log || {}; var _Option = Option, isNetworkUnavailable = _Option.isNetworkUnavailable, _log = log, level = _log.level, isLevelToDegrad = utils.isEqual(level, LEVEL.ERROR) || utils.isEqual(level, LEVEL.WARN); if (isNetworkUnavailable && isLevelToDegrad) { log.level = LEVEL.INFO; } return log; }; var LogStore = { _list: [], MaxSize: common.isBelowIE(9) ? STORE_SIZE.LOW : STORE_SIZE.ADVANCED, add: function add(log) { log = getLogLevel(log); LogStore._list.push(log); var currentSize = LogStore._list.length, maxSize = LogStore.MaxSize; if (currentSize > maxSize) { LogStore._list.splice(0, currentSize - maxSize); } }, get: function get(option) { var type = option.type, uploadLevel = option.level; var _list = LogStore._list; var uploadList = []; utils.forEach(_list, function (log, index) { var logTime = log.time || 0, logLevel = log.level || LEVEL.DEBUG, isUploadLevel = logLevel <= uploadLevel, fullUploadOption = option.fullUploadOption || {}, startTime = fullUploadOption.startTime || 0, endTime = fullUploadOption.endTime || common.DelayTimer.getTime(); var isUpload = isUploadLevel; switch (type) { case REPORT_TYPE.REALTIME: isUpload = isUpload && !log.isUploaded; isUpload && (LogStore._list[index].isUploaded = true); break; case REPORT_TYPE.FULL: isUpload = isUpload && logTime >= startTime && logTime <= endTime; break; default: } if (isUpload) { uploadList.push(log); } }); return uploadList; }, clear: function clear() { LogStore._list = []; } }; var upload = function upload(option) { var url = option.url, logList = option.logList, type = option.type; var requestUrl = common.getReportLogUrl({ type: type, appkey: Option.appkey || '', userId: Option.userId || '', url: url || ServerOption.url || DEFAULT_SERVER_OPTION.url, logId: option.logId }); var csvLog = ''; utils.forEach(logList, function (log) { csvLog += getCSVForLog(log); }); if (utils.isEmpty(csvLog) && type === REPORT_TYPE.REALTIME) { return utils.Defer.reject(); } if (utils.isEmpty(csvLog) && type === REPORT_TYPE.FULL) { csvLog = NO_FULL_LOG; } csvLog = common.TextCompressor.compress(csvLog); return utils.request(requestUrl, { method: REQUEST_METHOD.POST, body: csvLog, timeout: REQUEST_TIMEOUT }); }; var uploadRealtime = function uploadRealtime() { if (isRealtimeUploading) { return; } var interval = getRealtimeUploadInterval(RealtimeUploadTimes); var realtimeMaxTimes = ServerOption.realtimeMaxTimes, realtimeLevel = ServerOption.realtimeLevel; if (RealtimeUploadTimes < realtimeMaxTimes) { RealtimeUploadTimes++; } if (isFirstDefaultUpload(interval)) { RealtimeUploadTimes = 1; } utils.setTimeout(function () { var logList = LogStore.get({ type: REPORT_TYPE.REALTIME, level: realtimeLevel }); isRealtimeUploading = true; upload({ logList: logList, type: REPORT_TYPE.REALTIME }).then(function (response) { isRealtimeUploading = false; var responseText = response.responseText || '{}'; var conf = response.responseText || {}; setServerResponseOption(responseText); if (ServerOption.isOpen) { RealtimeUploadTimes = utils.isEmpty(conf) ? RealtimeUploadTimes : 1; uploadRealtime(); } })["catch"](function () { isRealtimeUploading = false; uploadRealtime(); }); }, interval); }; var uploadFull = function uploadFull(uploadTimes, option, connectedTime) { if (!Option.isUploadToServer) { return; } uploadTimes = uploadTimes || 0; option = option || {}; var _option = option, uri = _option.uri, logId = _option.logId; var isFirst = uploadTimes === 0; var interval = isFirst ? 0 : getFullUploadInterval(uploadTimes); var fullMaxTimes = ServerOption.fullMaxTimes, fullLevel = ServerOption.fullLevel; if (fullLogId === logId) return; if (uploadTimes <= fullMaxTimes) { uploadTimes++; } else { return; } fullLogId = logId; (function (option) { utils.setTimeout(function () { var logList = LogStore.get({ type: REPORT_TYPE.FULL, level: fullLevel, fullUploadOption: option }); if (logList.length === 0 && Number(option.endTime) < connectedTime) return; upload({ logId: logId, url: uri, logList: logList, type: REPORT_TYPE.FULL }).then(function () {})["catch"](function () { uploadFull(uploadTimes, option, connectedTime); }); }, interval); })(option); }; var writeLocalLog = function writeLocalLog(log) { var time = log.time; var formatedTime = utils.formatTime(time); var localLog = LocalLogPrefix + ":" + formatedTime + ": " + utils.toJSON(log); logEventEmitter.emit(LogEventName, localLog); if (Option.isDebug) { utils.consoleLog(localLog); } }; var Logger = { _events: [], LogStore: LogStore, setOption: function setOption(option) { Option = utils.extend(Option, option); }, setServerOption: setServerOption, watchLog: function watchLog(event) { logEventEmitter.on(LogEventName, event); Logger._events.push(event); }, write: function write(log) { log = log || {}; log.tag = log.tag || TAG.L_CRASH_F; log.time = log.time || common.DelayTimer.getTime(); log.type = log.type || LOG_TYPE.IM; LogStore.add(log); writeLocalLog(log); }, fatal: function fatal(tag, content) { Logger.write({ tag: tag, content: content, level: LEVEL.FATAL }); }, error: function error(tag, content) { Logger.write({ tag: tag, content: content, level: LEVEL.ERROR }); }, warn: function warn(tag, content) { Logger.write({ tag: tag, content: content, level: LEVEL.WARN }); }, info: function info(tag, content) { Logger.write({ tag: tag, content: content, level: LEVEL.INFO }); }, debug: function debug(tag, content) { Logger.write({ tag: tag, content: content, level: LEVEL.DEBUG }); }, startRealtimeUpload: function startRealtimeUpload() { if (realTimeUploadHasStarted) return; Option.isUploadToServer && uploadRealtime(); realTimeUploadHasStarted = true; }, resetRealtimeUpload: function resetRealtimeUpload() { RealtimeUploadTimes = 1; }, uploadFull: uploadFull }; var EventEmitter$2 = utils.EventEmitter, DeferHandler$2 = utils.DeferHandler, httpRequest = utils.httpRequest, request$4 = utils.request, Defer$1 = utils.Defer; var CometTransporter = function () { function CometTransporter(option) { this._option = void 0; this._transporterEventEmiiter = new EventEmitter$2(); this._deferHandler = new DeferHandler$2(); this._pid = utils.encodeURI(utils.getCurrentTimestamp() + Math.random() + ''); this._domain = void 0; this._sessionid = void 0; this._xhrCache = new utils.Cache(); this._pullSignalTimer = new utils.Timer({ timeout: IM_COMET_PULLMSG_TIMEOUT }); this._isDisconnected = true; this._option = option; } var _proto = CometTransporter.prototype; _proto._startPullSignal = function _startPullSignal() { var self = this; var _domain = self._domain, _sessionid = self._sessionid, _pid = self._pid, _transporterEventEmiiter = self._transporterEventEmiiter, _pullSignalTimer = self._pullSignalTimer; var timestamp = utils.getCurrentTimestamp(); var protocol = env.protocol.http; var url = utils.tplEngine(COMET_PULL_URL_TPL, { protocol: protocol, timestamp: timestamp, domain: _domain, sessionId: _sessionid, pid: _pid }); var xhr = httpRequest({ url: url, body: { pid: _pid }, timeout: IM_COMET_PULLMSG_TIMEOUT, success: function success(responseText) { _pullSignalTimer.stop(); var isSuccess = self.handleCometResponse(responseText); if (isSuccess) { !self._isDisconnected && self._startPullSignal(); } else if (!self._isDisconnected) { _transporterEventEmiiter.emit(TRANSPORT_EVENT.STATUS, TRANSPORTER_STATUS.COMET_REQUEST_ERROR); } self._xhrCache.remove(url); }, fail: function fail() { _pullSignalTimer.stop(); if (!self._isDisconnected) { _transporterEventEmiiter.emit(TRANSPORT_EVENT.STATUS, TRANSPORTER_STATUS.COMET_REQUEST_ERROR); } self._xhrCache.remove(url); } }); _pullSignalTimer.start(function () { if (!self._isDisconnected) { _transporterEventEmiiter.emit(TRANSPORT_EVENT.STATUS, TRANSPORTER_STATUS.PING_TIMEOUT); self.disconnect(); } }); self._xhrCache.set(url, xhr); }; _proto.watchSignal = function watchSignal(event) { this._transporterEventEmiiter.on(TRANSPORT_EVENT.SIGNAL, event); }; _proto.watchStatus = function watchStatus(event) { this._transporterEventEmiiter.on(TRANSPORT_EVENT.STATUS, function (status) { event && event(status); }); }; _proto.connect = function connect(user, option) { var self = this; var _transporterEventEmiiter = self._transporterEventEmiiter, _pid = self._pid, _self$_option = self._option, appkey = _self$_option.appkey, connectType = _self$_option.connectType; var token = user.token; var domain = option.domain; var url = common.getTransporterUrl({ domain: domain, appkey: appkey, token: token, connectType: connectType }); self._domain = domain; self._isDisconnected = false; var success = function success(_ref) { var responseText = _ref.responseText; if (!utils.isValidJSON(responseText)) { return Defer$1.reject(); } var response = utils.isObject(responseText) ? responseText : utils.parseJSON(responseText); var isConnectSuccess = utils.isEqual(response.status, SUCCESS_CODE); if (isConnectSuccess && utils.isObject(response) && utils.isValidTimestamp(response.timestamp)) { common.DelayTimer.setTime(response.timestamp); } return isConnectSuccess ? Defer$1.resolve(response) : Defer$1.reject(response); }; return request$4(url, { body: { pid: _pid } }).then(success).then(function (response) { _transporterEventEmiiter.emit(TRANSPORT_EVENT.STATUS, CONNECTION_STATUS.CONNECTED); self._sessionid = response.sessionid; self._startPullSignal(); return response; }); }; _proto.sendSignal = function sendSignal(writer) { var self = this; var _domain = self._domain, _sessionid = self._sessionid, _pid = self._pid; var messageId = writer.messageId, topic = writer.topic, targetId = writer.targetId; var headerCode = writer.getHeaderFlag(); var protocol = env.protocol.http; var TPL = topic ? COMET_REQ_HAS_TOPIC_URL_TPL : COMET_REQ_NO_TOPIC_URL_TPL; var url = utils.tplEngine(TPL, { protocol: protocol, messageId: messageId, headerCode: headerCode, topic: topic, targetId: targetId, pid: _pid, sessionId: _sessionid, domain: _domain }); var currentTime = utils.getCurrentTimestamp() + ''; var xhr = httpRequest({ url: url, method: REQUEST_METHOD.POST, body: writer.getCometData(), success: function success(responseText) { var isSuccess = self.handleCometResponse(responseText); if (!isSuccess) { self.handleError(messageId); } self._xhrCache.remove(currentTime); }, fail: function fail(error) { self.handleError(messageId); self._xhrCache.remove(currentTime); Logger.error(TAG.L_CRASH_F, { content: { info: 'comet error', error: error } }); } }); self._xhrCache.set(currentTime, xhr); }; _proto.handleCometResponse = function handleCometResponse(responseText) { var self = this; var _transporterEventEmiiter = self._transporterEventEmiiter; var response = utils.isString(responseText) ? utils.parseJSON(responseText) : responseText; if (!response) { return false; } if (!response || !utils.isArray(response)) { return true; } utils.forEach(response, function (data) { var sessionid = data.sessionid; if (sessionid) { self._sessionid = sessionid; } var signal = readCometData(data); _transporterEventEmiiter.emit(TRANSPORT_EVENT.SIGNAL, signal); if (signal && utils.isValidTimestamp(signal.timestamp)) { common.DelayTimer.setTime(signal.timestamp); } }); return true; }; _proto.handleError = function handleError(messageId, status) { var signal = { messageId: messageId, status: status || ERROR_CODE.TIMEOUT }; this._transporterEventEmiiter.emit(TRANSPORT_EVENT.SIGNAL, signal); }; _proto.disconnect = function disconnect() { var self = this; self._isDisconnected = true; var _xhrCache = self._xhrCache, _pullSignalTimer = self._pullSignalTimer; var xhrKeys = _xhrCache.getKeys(); _pullSignalTimer.stop(); utils.forEach(xhrKeys, function (key) { var xhr = _xhrCache.get(key); xhr.abort(); _xhrCache.remove(key); }); }; return CometTransporter; }(); var Transporter = (function (option) { var connectType = option.connectType; var isSocket = connectType === CONNECT_TYPE.WEBSOCKET; var Transporter = isSocket ? SocketTransporter : CometTransporter; return new Transporter(option); }); var PBName = { UpStreamMessage: 'UpStreamMessage', DownStreamMessage: 'DownStreamMessage', DownStreamMessages: 'DownStreamMessages', SessionsAttQryInput: 'SessionsAttQryInput', SessionsAttOutput: 'SessionsAttOutput', SyncRequestMsg: 'SyncRequestMsg', ChrmPullMsg: 'ChrmPullMsg', NotifyMsg: 'NotifyMsg', HistoryMsgInput: 'HistoryMsgInput', HistoryMsgOuput: 'HistoryMsgOuput', RelationQryInput: 'RelationQryInput', RelationsOutput: 'RelationsOutput', DeleteSessionsInput: 'DeleteSessionsInput', SessionInfo: 'SessionInfo', DeleteSessionsOutput: 'DeleteSessionsOutput', RelationsInput: 'RelationsInput', DeleteMsgInput: 'DeleteMsgInput', CleanHisMsgInput: 'CleanHisMsgInput', SessionMsgReadInput: 'SessionMsgReadInput', ChrmInput: 'ChrmInput', QueryChatRoomInfoInput: 'QueryChatRoomInfoInput', QueryChatRoomInfoOutput: 'QueryChatRoomInfoOutput', RtcInput: 'RtcInput', RtcUserListOutput: 'RtcUserListOutput', SetUserStatusInput: 'SetUserStatusInput', RtcSetDataInput: 'RtcSetDataInput', RtcDataInput: 'RtcDataInput', RtcSetOutDataInput: 'RtcSetOutDataInput', MCFollowInput: 'MCFollowInput', RtcTokenOutput: 'RtcTokenOutput', RtcQryOutput: 'RtcQryOutput', RtcQryUserOutDataInput: 'RtcQryUserOutDataInput', RtcUserOutDataOutput: 'RtcUserOutDataOutput', RtcQueryListInput: 'RtcQueryListInput', RtcRoomInfoOutput: 'RtcRoomInfoOutput', RtcValueInfo: 'RtcValueInfo', RtcKeyDeleteInput: 'RtcKeyDeleteInput', GetQNupTokenInput: 'GetQNupTokenInput', GetQNupTokenOutput: 'GetQNupTokenOutput', GetQNdownloadUrlInput: 'GetQNdownloadUrlInput', GetQNdownloadUrlOutput: 'GetQNdownloadUrlOutput', SetChrmKV: 'SetChrmKV', ChrmKVOutput: 'ChrmKVOutput', QueryChrmKV: 'QueryChrmKV', ChrmNotifyMsg: 'ChrmNotifyMsg' }; var _SSMsg; var SSMsg = (_SSMsg = {}, _SSMsg[PBName.UpStreamMessage] = ['sessionId', 'classname', 'content', 'pushText', 'userId', 'configFlag', 'appData'], _SSMsg[PBName.DownStreamMessages] = ['list', 'syncTime', 'finished'], _SSMsg[PBName.DownStreamMessage] = ['fromUserId', 'type', 'groupId', 'classname', 'content', 'dataTime', 'status', 'msgId'], _SSMsg[PBName.SessionsAttQryInput] = ['nothing'], _SSMsg[PBName.SessionsAttOutput] = ['inboxTime', 'sendboxTime', 'totalUnreadCount'], _SSMsg[PBName.SyncRequestMsg] = ['syncTime', 'ispolling', 'isweb', 'isPullSend', 'isKeeping', 'sendBoxSyncTime'], _SSMsg[PBName.ChrmPullMsg] = ['syncTime', 'count'], _SSMsg[PBName.NotifyMsg] = ['type', 'time', 'chrmId'], _SSMsg[PBName.HistoryMsgInput] = ['targetId', 'time', 'count', 'order'], _SSMsg[PBName.HistoryMsgOuput] = ['list', 'syncTime', 'hasMsg'], _SSMsg[PBName.RelationQryInput] = ['type', 'count', 'startTime', 'order'], _SSMsg[PBName.RelationsOutput] = ['info'], _SSMsg[PBName.DeleteSessionsInput] = ['sessions'], _SSMsg[PBName.SessionInfo] = ['type', 'channelId'], _SSMsg[PBName.DeleteSessionsOutput] = ['nothing'], _SSMsg[PBName.RelationsInput] = ['type', 'msg', 'count', 'offset', 'startTime', 'endTime'], _SSMsg[PBName.DeleteMsgInput] = ['type', 'conversationId', 'msgs'], _SSMsg[PBName.CleanHisMsgInput] = ['targetId', 'dataTime', 'conversationType'], _SSMsg[PBName.SessionMsgReadInput] = ['type', 'msgTime', 'channelId'], _SSMsg[PBName.ChrmInput] = ['nothing'], _SSMsg[PBName.QueryChatRoomInfoInput] = ['count', 'order'], _SSMsg[PBName.QueryChatRoomInfoOutput] = ['userTotalNums', 'userInfos'], _SSMsg[PBName.GetQNupTokenInput] = ['type'], _SSMsg[PBName.GetQNdownloadUrlInput] = ['type', 'key', 'fileName'], _SSMsg[PBName.GetQNupTokenOutput] = ['deadline', 'token'], _SSMsg[PBName.GetQNdownloadUrlOutput] = ['downloadUrl'], _SSMsg[PBName.SetChrmKV] = ['entry', 'bNotify', 'notification', 'type'], _SSMsg[PBName.ChrmKVOutput] = ['entries', 'bFullUpdate', 'syncTime'], _SSMsg[PBName.QueryChrmKV] = ['timestamp'], _SSMsg[PBName.ChrmNotifyMsg] = ['type', 'time', 'chrmId'], _SSMsg); var Codec = {}; utils.forEach(SSMsg, function (paramList, name) { Codec[name] = function () {}; Codec[name].prototype.data = {}; Codec[name].prototype.getData = function () { return this.data; }; utils.forEach(paramList, function (param) { var setEventName = 'set' + utils.toUpperCase(param, 0, 1); Codec[name].prototype[setEventName] = function (item) { this.data[param] = item; }; }); Codec[name].decode = function (data) { var decodeResult = {}; if (utils.isString(data)) { data = utils.parseJSON(data); } var _loop = function _loop(key) { var getEventName = 'get' + utils.toUpperCase(key, 0, 1); decodeResult[key] = data[key]; decodeResult[getEventName] = function () { return data[key]; }; }; for (var key in data) { _loop(key); } return decodeResult; }; }); Codec.getModule = function (pbName) { var modules = new Codec[pbName](); modules.getArrayData = function () { return modules.getData(); }; return modules; }; function protobuf(a){var b=void 0,c=function(){function a(a,b,c){this.low=0|a,this.high=0|b,this.unsigned=!!c;}function b(a){return (a&&a.__isLong__)===!0}function e(a,b){var e,f,h;return b?(a>>>=0,(h=a>=0&&256>a)&&(f=d[a])?f:(e=g(a,0>(0|a)?-1:0,!0),h&&(d[a]=e),e)):(a|=0,(h=a>=-128&&128>a)&&(f=c[a])?f:(e=g(a,0>a?-1:0,!1),h&&(c[a]=e),e))}function f(a,b){if(isNaN(a)||!isFinite(a))return b?r:q;if(b){if(0>a)return r;if(a>=n)return w}else{if(-o>=a)return x;if(a+1>=o)return v}return 0>a?f(-a,b).neg():g(0|a%m,0|a/m,b)}function g(b,c,d){return new a(b,c,d)}function i(a,b,c){var d,e,g,j,k,l,m;if(0===a.length)throw Error("empty string");if("NaN"===a||"Infinity"===a||"+Infinity"===a||"-Infinity"===a)return q;if("number"==typeof b?(c=b,b=!1):b=!!b,c=c||10,2>c||c>36)throw RangeError("radix");if((d=a.indexOf("-"))>0)throw Error("interior hyphen");if(0===d)return i(a.substring(1),b,c).neg();for(e=f(h(c,8)),g=q,j=0;jk?(m=f(h(c,k)),g=g.mul(m).add(f(l))):(g=g.mul(e),g=g.add(f(l)));return g.unsigned=b,g}function j(b){return b instanceof a?b:"number"==typeof b?f(b):"string"==typeof b?i(b):g(b.low,b.high,b.unsigned)}var c,d,h,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y;return Object.defineProperty(a.prototype,"__isLong__",{value:!0,enumerable:!1,configurable:!1}),a.isLong=b,c={},d={},a.fromInt=e,a.fromNumber=f,a.fromBits=g,h=Math.pow,a.fromString=i,a.fromValue=j,k=65536,l=1<<24,m=k*k,n=m*m,o=n/2,p=e(l),q=e(0),a.ZERO=q,r=e(0,!0),a.UZERO=r,s=e(1),a.ONE=s,t=e(1,!0),a.UONE=t,u=e(-1),a.NEG_ONE=u,v=g(-1,2147483647,!1),a.MAX_VALUE=v,w=g(-1,-1,!0),a.MAX_UNSIGNED_VALUE=w,x=g(0,-2147483648,!1),a.MIN_VALUE=x,y=a.prototype,y.toInt=function(){return this.unsigned?this.low>>>0:this.low},y.toNumber=function(){return this.unsigned?(this.high>>>0)*m+(this.low>>>0):this.high*m+(this.low>>>0)},y.toString=function(a){var b,c,d,e,g,i,j,k,l;if(a=a||10,2>a||a>36)throw RangeError("radix");if(this.isZero())return "0";if(this.isNegative())return this.eq(x)?(b=f(a),c=this.div(b),d=c.mul(b).sub(this),c.toString(a)+d.toInt().toString(a)):"-"+this.neg().toString(a);for(e=f(h(a,6),this.unsigned),g=this,i="";;){if(j=g.div(e),k=g.sub(j.mul(e)).toInt()>>>0,l=k.toString(a),g=j,g.isZero())return l+i;for(;l.length<6;)l="0"+l;i=""+l+i;}},y.getHighBits=function(){return this.high},y.getHighBitsUnsigned=function(){return this.high>>>0},y.getLowBits=function(){return this.low},y.getLowBitsUnsigned=function(){return this.low>>>0},y.getNumBitsAbs=function(){var a,b;if(this.isNegative())return this.eq(x)?64:this.neg().getNumBitsAbs();for(a=0!=this.high?this.high:this.low,b=31;b>0&&0==(a&1<=0},y.isOdd=function(){return 1===(1&this.low)},y.isEven=function(){return 0===(1&this.low)},y.equals=function(a){return b(a)||(a=j(a)),this.unsigned!==a.unsigned&&1===this.high>>>31&&1===a.high>>>31?!1:this.high===a.high&&this.low===a.low},y.eq=y.equals,y.notEquals=function(a){return !this.eq(a)},y.neq=y.notEquals,y.lessThan=function(a){return this.comp(a)<0},y.lt=y.lessThan,y.lessThanOrEqual=function(a){return this.comp(a)<=0},y.lte=y.lessThanOrEqual,y.greaterThan=function(a){return this.comp(a)>0},y.gt=y.greaterThan,y.greaterThanOrEqual=function(a){return this.comp(a)>=0},y.gte=y.greaterThanOrEqual,y.compare=function(a){if(b(a)||(a=j(a)),this.eq(a))return 0;var c=this.isNegative(),d=a.isNegative();return c&&!d?-1:!c&&d?1:this.unsigned?a.high>>>0>this.high>>>0||a.high===this.high&&a.low>>>0>this.low>>>0?-1:1:this.sub(a).isNegative()?-1:1},y.comp=y.compare,y.negate=function(){return !this.unsigned&&this.eq(x)?x:this.not().add(s)},y.neg=y.negate,y.add=function(a){var c,d,e,f,h,i,k,l,m,n,o,p;return b(a)||(a=j(a)),c=this.high>>>16,d=65535&this.high,e=this.low>>>16,f=65535&this.low,h=a.high>>>16,i=65535&a.high,k=a.low>>>16,l=65535&a.low,m=0,n=0,o=0,p=0,p+=f+l,o+=p>>>16,p&=65535,o+=e+k,n+=o>>>16,o&=65535,n+=d+i,m+=n>>>16,n&=65535,m+=c+h,m&=65535,g(o<<16|p,m<<16|n,this.unsigned)},y.subtract=function(a){return b(a)||(a=j(a)),this.add(a.neg())},y.sub=y.subtract,y.multiply=function(a){var c,d,e,h,i,k,l,m,n,o,r,s;return this.isZero()?q:(b(a)||(a=j(a)),a.isZero()?q:this.eq(x)?a.isOdd()?x:q:a.eq(x)?this.isOdd()?x:q:this.isNegative()?a.isNegative()?this.neg().mul(a.neg()):this.neg().mul(a).neg():a.isNegative()?this.mul(a.neg()).neg():this.lt(p)&&a.lt(p)?f(this.toNumber()*a.toNumber(),this.unsigned):(c=this.high>>>16,d=65535&this.high,e=this.low>>>16,h=65535&this.low,i=a.high>>>16,k=65535&a.high,l=a.low>>>16,m=65535&a.low,n=0,o=0,r=0,s=0,s+=h*m,r+=s>>>16,s&=65535,r+=e*m,o+=r>>>16,r&=65535,r+=h*l,o+=r>>>16,r&=65535,o+=d*m,n+=o>>>16,o&=65535,o+=e*l,n+=o>>>16,o&=65535,o+=h*k,n+=o>>>16,o&=65535,n+=c*m+d*l+e*k+h*i,n&=65535,g(r<<16|s,n<<16|o,this.unsigned)))},y.mul=y.multiply,y.divide=function(a){var c,d,e,g,i,k,l,m;if(b(a)||(a=j(a)),a.isZero())throw Error("division by zero");if(this.isZero())return this.unsigned?r:q;if(this.unsigned){if(a.unsigned||(a=a.toUnsigned()),a.gt(this))return r;if(a.gt(this.shru(1)))return t;e=r;}else{if(this.eq(x))return a.eq(s)||a.eq(u)?x:a.eq(x)?s:(g=this.shr(1),c=g.div(a).shl(1),c.eq(q)?a.isNegative()?s:u:(d=this.sub(a.mul(c)),e=c.add(d.div(a))));if(a.eq(x))return this.unsigned?r:q;if(this.isNegative())return a.isNegative()?this.neg().div(a.neg()):this.neg().div(a).neg();if(a.isNegative())return this.div(a.neg()).neg();e=q;}for(d=this;d.gte(a);){for(c=Math.max(1,Math.floor(d.toNumber()/a.toNumber())),i=Math.ceil(Math.log(c)/Math.LN2),k=48>=i?1:h(2,i-48),l=f(c),m=l.mul(a);m.isNegative()||m.gt(d);)c-=k,l=f(c,this.unsigned),m=l.mul(a);l.isZero()&&(l=s),e=e.add(l),d=d.sub(m);}return e},y.div=y.divide,y.modulo=function(a){return b(a)||(a=j(a)),this.sub(this.div(a).mul(a))},y.mod=y.modulo,y.not=function(){return g(~this.low,~this.high,this.unsigned)},y.and=function(a){return b(a)||(a=j(a)),g(this.low&a.low,this.high&a.high,this.unsigned)},y.or=function(a){return b(a)||(a=j(a)),g(this.low|a.low,this.high|a.high,this.unsigned)},y.xor=function(a){return b(a)||(a=j(a)),g(this.low^a.low,this.high^a.high,this.unsigned)},y.shiftLeft=function(a){return b(a)&&(a=a.toInt()),0===(a&=63)?this:32>a?g(this.low<>>32-a,this.unsigned):g(0,this.low<a?g(this.low>>>a|this.high<<32-a,this.high>>a,this.unsigned):g(this.high>>a-32,this.high>=0?0:-1,this.unsigned)},y.shr=y.shiftRight,y.shiftRightUnsigned=function(a){var c,d;return b(a)&&(a=a.toInt()),a&=63,0===a?this:(c=this.high,32>a?(d=this.low,g(d>>>a|c<<32-a,c>>>a,this.unsigned)):32===a?g(c,0,this.unsigned):g(c>>>a-32,0,this.unsigned))},y.shru=y.shiftRightUnsigned,y.toSigned=function(){return this.unsigned?g(this.low,this.high,!1):this},y.toUnsigned=function(){return this.unsigned?this:g(this.low,this.high,!0)},y.toBytes=function(a){return a?this.toBytesLE():this.toBytesBE()},y.toBytesLE=function(){var a=this.high,b=this.low;return [255&b,255&b>>>8,255&b>>>16,255&b>>>24,255&a,255&a>>>8,255&a>>>16,255&a>>>24]},y.toBytesBE=function(){var a=this.high,b=this.low;return [255&a>>>24,255&a>>>16,255&a>>>8,255&a,255&b>>>24,255&b>>>16,255&b>>>8,255&b]},a}(),d=function(a){function f(a){var b=0;return function(){return b1024&&(b.push(e.apply(String,a)),a.length=0),Array.prototype.push.apply(a,arguments),void 0)}}function h(a,b,c,d,e){var f,g,h=8*e-d-1,i=(1<>1,k=-7,l=c?e-1:0,m=c?-1:1,n=a[b+l];for(l+=m,f=n&(1<<-k)-1,n>>=-k,k+=h;k>0;f=256*f+a[b+l],l+=m,k-=8);for(g=f&(1<<-k)-1,f>>=-k,k+=d;k>0;g=256*g+a[b+l],l+=m,k-=8);if(0===f)f=1-j;else{if(f===i)return g?0/0:1/0*(n?-1:1);g+=Math.pow(2,d),f-=j;}return (n?-1:1)*g*Math.pow(2,f-d)}function i(a,b,c,d,e,f){var g,h,i,j=8*f-e-1,k=(1<>1,m=23===e?Math.pow(2,-24)-Math.pow(2,-77):0,n=d?0:f-1,o=d?1:-1,p=0>b||0===b&&0>1/b?1:0;for(b=Math.abs(b),isNaN(b)||1/0===b?(h=isNaN(b)?1:0,g=k):(g=Math.floor(Math.log(b)/Math.LN2),b*(i=Math.pow(2,-g))<1&&(g--,i*=2),b+=g+l>=1?m/i:m*Math.pow(2,1-l),b*i>=2&&(g++,i/=2),g+l>=k?(h=0,g=k):g+l>=1?(h=(b*i-1)*Math.pow(2,e),g+=l):(h=b*Math.pow(2,l-1)*Math.pow(2,e),g=0));e>=8;a[c+n]=255&h,n+=o,h/=256,e-=8);for(g=g<0;a[c+n]=255&g,n+=o,g/=256,j-=8);a[c+n-o]|=128*p;}var c,d,e,j,k,b=function(a,c,e){if("undefined"==typeof a&&(a=b.DEFAULT_CAPACITY),"undefined"==typeof c&&(c=b.DEFAULT_ENDIAN),"undefined"==typeof e&&(e=b.DEFAULT_NOASSERT),!e){if(a=0|a,0>a)throw RangeError("Illegal capacity");c=!!c,e=!!e;}this.buffer=0===a?d:new ArrayBuffer(a),this.view=0===a?null:new Uint8Array(this.buffer),this.offset=0,this.markedOffset=-1,this.limit=a,this.littleEndian=c,this.noAssert=e;};return b.VERSION="5.0.1",b.LITTLE_ENDIAN=!0,b.BIG_ENDIAN=!1,b.DEFAULT_CAPACITY=16,b.DEFAULT_ENDIAN=b.BIG_ENDIAN,b.DEFAULT_NOASSERT=!1,b.Long=a||null,c=b.prototype,c.__isByteBuffer__,Object.defineProperty(c,"__isByteBuffer__",{value:!0,enumerable:!1,configurable:!1}),d=new ArrayBuffer(0),e=String.fromCharCode,b.accessor=function(){return Uint8Array},b.allocate=function(a,c,d){return new b(a,c,d)},b.concat=function(a,c,d,e){var f,i,g,h,k,j;for(("boolean"==typeof c||"string"!=typeof c)&&(e=d,d=c,c=void 0),f=0,g=0,h=a.length;h>g;++g)b.isByteBuffer(a[g])||(a[g]=b.wrap(a[g],c)),i=a[g].limit-a[g].offset,i>0&&(f+=i);if(0===f)return new b(0,d,e);for(j=new b(f,d,e),g=0;h>g;)k=a[g++],i=k.limit-k.offset,0>=i||(j.view.set(k.view.subarray(k.offset,k.limit),j.offset),j.offset+=i);return j.limit=j.offset,j.offset=0,j},b.isByteBuffer=function(a){return (a&&a.__isByteBuffer__)===!0},b.type=function(){return ArrayBuffer},b.wrap=function(a,d,e,f){var g,h;if("string"!=typeof d&&(f=e,e=d,d=void 0),"string"==typeof a)switch("undefined"==typeof d&&(d="utf8"),d){case"base64":return b.fromBase64(a,e);case"hex":return b.fromHex(a,e);case"binary":return b.fromBinary(a,e);case"utf8":return b.fromUTF8(a,e);case"debug":return b.fromDebug(a,e);default:throw Error("Unsupported encoding: "+d)}if(null===a||"object"!=typeof a)throw TypeError("Illegal buffer");if(b.isByteBuffer(a))return g=c.clone.call(a),g.markedOffset=-1,g;if(a instanceof Uint8Array)g=new b(0,e,f),a.length>0&&(g.buffer=a.buffer,g.offset=a.byteOffset,g.limit=a.byteOffset+a.byteLength,g.view=new Uint8Array(a.buffer));else if(a instanceof ArrayBuffer)g=new b(0,e,f),a.byteLength>0&&(g.buffer=a,g.offset=0,g.limit=a.byteLength,g.view=a.byteLength>0?new Uint8Array(a):null);else{if("[object Array]"!==Object.prototype.toString.call(a))throw TypeError("Illegal buffer");for(g=new b(a.length,e,f),g.limit=a.length,h=0;h>>=0,0>b||b+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+b+" (+"+0+") <= "+this.buffer.byteLength)}for(d=b,e=a.length,f=e>>3,g=0,b+=this.writeVarint32(e,b);f--;)h=1&!!a[g++]|(1&!!a[g++])<<1|(1&!!a[g++])<<2|(1&!!a[g++])<<3|(1&!!a[g++])<<4|(1&!!a[g++])<<5|(1&!!a[g++])<<6|(1&!!a[g++])<<7,this.writeByte(h,b++);if(e>g){for(i=0,h=0;e>g;)h|=(1&!!a[g++])<>3,f=0,g=[],a+=c.length;e--;)h=this.readByte(a++),g[f++]=!!(1&h),g[f++]=!!(2&h),g[f++]=!!(4&h),g[f++]=!!(8&h),g[f++]=!!(16&h),g[f++]=!!(32&h),g[f++]=!!(64&h),g[f++]=!!(128&h);if(d>f)for(i=0,h=this.readByte(a++);d>f;)g[f++]=!!(1&h>>i++);return b&&(this.offset=a),g},c.readBytes=function(a,b){var d,c="undefined"==typeof b;if(c&&(b=this.offset),!this.noAssert){if("number"!=typeof b||0!==b%1)throw TypeError("Illegal offset: "+b+" (not an integer)");if(b>>>=0,0>b||b+a>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+b+" (+"+a+") <= "+this.buffer.byteLength)}return d=this.slice(b,b+a),c&&(this.offset+=a),d},c.writeBytes=c.append,c.writeInt8=function(a,b){var d,c="undefined"==typeof b;if(c&&(b=this.offset),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal value: "+a+" (not an integer)");if(a|=0,"number"!=typeof b||0!==b%1)throw TypeError("Illegal offset: "+b+" (not an integer)");if(b>>>=0,0>b||b+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+b+" (+"+0+") <= "+this.buffer.byteLength)}return b+=1,d=this.buffer.byteLength,b>d&&this.resize((d*=2)>b?d:b),b-=1,this.view[b]=a,c&&(this.offset+=1),this},c.writeByte=c.writeInt8,c.readInt8=function(a){var c,b="undefined"==typeof a;if(b&&(a=this.offset),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal offset: "+a+" (not an integer)");if(a>>>=0,0>a||a+1>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+a+" (+"+1+") <= "+this.buffer.byteLength)}return c=this.view[a],128===(128&c)&&(c=-(255-c+1)),b&&(this.offset+=1),c},c.readByte=c.readInt8,c.writeUint8=function(a,b){var d,c="undefined"==typeof b;if(c&&(b=this.offset),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal value: "+a+" (not an integer)");if(a>>>=0,"number"!=typeof b||0!==b%1)throw TypeError("Illegal offset: "+b+" (not an integer)");if(b>>>=0,0>b||b+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+b+" (+"+0+") <= "+this.buffer.byteLength)}return b+=1,d=this.buffer.byteLength,b>d&&this.resize((d*=2)>b?d:b),b-=1,this.view[b]=a,c&&(this.offset+=1),this},c.writeUInt8=c.writeUint8,c.readUint8=function(a){var c,b="undefined"==typeof a;if(b&&(a=this.offset),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal offset: "+a+" (not an integer)");if(a>>>=0,0>a||a+1>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+a+" (+"+1+") <= "+this.buffer.byteLength)}return c=this.view[a],b&&(this.offset+=1),c},c.readUInt8=c.readUint8,c.writeInt16=function(a,b){var d,c="undefined"==typeof b;if(c&&(b=this.offset),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal value: "+a+" (not an integer)");if(a|=0,"number"!=typeof b||0!==b%1)throw TypeError("Illegal offset: "+b+" (not an integer)");if(b>>>=0,0>b||b+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+b+" (+"+0+") <= "+this.buffer.byteLength)}return b+=2,d=this.buffer.byteLength,b>d&&this.resize((d*=2)>b?d:b),b-=2,this.littleEndian?(this.view[b+1]=(65280&a)>>>8,this.view[b]=255&a):(this.view[b]=(65280&a)>>>8,this.view[b+1]=255&a),c&&(this.offset+=2),this},c.writeShort=c.writeInt16,c.readInt16=function(a){var c,b="undefined"==typeof a;if(b&&(a=this.offset),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal offset: "+a+" (not an integer)");if(a>>>=0,0>a||a+2>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+a+" (+"+2+") <= "+this.buffer.byteLength)}return c=0,this.littleEndian?(c=this.view[a],c|=this.view[a+1]<<8):(c=this.view[a]<<8,c|=this.view[a+1]),32768===(32768&c)&&(c=-(65535-c+1)),b&&(this.offset+=2),c},c.readShort=c.readInt16,c.writeUint16=function(a,b){var d,c="undefined"==typeof b;if(c&&(b=this.offset),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal value: "+a+" (not an integer)");if(a>>>=0,"number"!=typeof b||0!==b%1)throw TypeError("Illegal offset: "+b+" (not an integer)");if(b>>>=0,0>b||b+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+b+" (+"+0+") <= "+this.buffer.byteLength)}return b+=2,d=this.buffer.byteLength,b>d&&this.resize((d*=2)>b?d:b),b-=2,this.littleEndian?(this.view[b+1]=(65280&a)>>>8,this.view[b]=255&a):(this.view[b]=(65280&a)>>>8,this.view[b+1]=255&a),c&&(this.offset+=2),this},c.writeUInt16=c.writeUint16,c.readUint16=function(a){var c,b="undefined"==typeof a;if(b&&(a=this.offset),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal offset: "+a+" (not an integer)");if(a>>>=0,0>a||a+2>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+a+" (+"+2+") <= "+this.buffer.byteLength)}return c=0,this.littleEndian?(c=this.view[a],c|=this.view[a+1]<<8):(c=this.view[a]<<8,c|=this.view[a+1]),b&&(this.offset+=2),c},c.readUInt16=c.readUint16,c.writeInt32=function(a,b){var d,c="undefined"==typeof b;if(c&&(b=this.offset),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal value: "+a+" (not an integer)");if(a|=0,"number"!=typeof b||0!==b%1)throw TypeError("Illegal offset: "+b+" (not an integer)");if(b>>>=0,0>b||b+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+b+" (+"+0+") <= "+this.buffer.byteLength)}return b+=4,d=this.buffer.byteLength,b>d&&this.resize((d*=2)>b?d:b),b-=4,this.littleEndian?(this.view[b+3]=255&a>>>24,this.view[b+2]=255&a>>>16,this.view[b+1]=255&a>>>8,this.view[b]=255&a):(this.view[b]=255&a>>>24,this.view[b+1]=255&a>>>16,this.view[b+2]=255&a>>>8,this.view[b+3]=255&a),c&&(this.offset+=4),this},c.writeInt=c.writeInt32,c.readInt32=function(a){var c,b="undefined"==typeof a;if(b&&(a=this.offset),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal offset: "+a+" (not an integer)");if(a>>>=0,0>a||a+4>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+a+" (+"+4+") <= "+this.buffer.byteLength)}return c=0,this.littleEndian?(c=this.view[a+2]<<16,c|=this.view[a+1]<<8,c|=this.view[a],c+=this.view[a+3]<<24>>>0):(c=this.view[a+1]<<16,c|=this.view[a+2]<<8,c|=this.view[a+3],c+=this.view[a]<<24>>>0),c|=0,b&&(this.offset+=4),c},c.readInt=c.readInt32,c.writeUint32=function(a,b){var d,c="undefined"==typeof b;if(c&&(b=this.offset),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal value: "+a+" (not an integer)");if(a>>>=0,"number"!=typeof b||0!==b%1)throw TypeError("Illegal offset: "+b+" (not an integer)");if(b>>>=0,0>b||b+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+b+" (+"+0+") <= "+this.buffer.byteLength)}return b+=4,d=this.buffer.byteLength,b>d&&this.resize((d*=2)>b?d:b),b-=4,this.littleEndian?(this.view[b+3]=255&a>>>24,this.view[b+2]=255&a>>>16,this.view[b+1]=255&a>>>8,this.view[b]=255&a):(this.view[b]=255&a>>>24,this.view[b+1]=255&a>>>16,this.view[b+2]=255&a>>>8,this.view[b+3]=255&a),c&&(this.offset+=4),this},c.writeUInt32=c.writeUint32,c.readUint32=function(a){var c,b="undefined"==typeof a;if(b&&(a=this.offset),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal offset: "+a+" (not an integer)");if(a>>>=0,0>a||a+4>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+a+" (+"+4+") <= "+this.buffer.byteLength)}return c=0,this.littleEndian?(c=this.view[a+2]<<16,c|=this.view[a+1]<<8,c|=this.view[a],c+=this.view[a+3]<<24>>>0):(c=this.view[a+1]<<16,c|=this.view[a+2]<<8,c|=this.view[a+3],c+=this.view[a]<<24>>>0),b&&(this.offset+=4),c},c.readUInt32=c.readUint32,a&&(c.writeInt64=function(b,c){var e,f,g,d="undefined"==typeof c;if(d&&(c=this.offset),!this.noAssert){if("number"==typeof b)b=a.fromNumber(b);else if("string"==typeof b)b=a.fromString(b);else if(!(b&&b instanceof a))throw TypeError("Illegal value: "+b+" (not an integer or Long)");if("number"!=typeof c||0!==c%1)throw TypeError("Illegal offset: "+c+" (not an integer)");if(c>>>=0,0>c||c+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+c+" (+"+0+") <= "+this.buffer.byteLength)}return "number"==typeof b?b=a.fromNumber(b):"string"==typeof b&&(b=a.fromString(b)),c+=8,e=this.buffer.byteLength,c>e&&this.resize((e*=2)>c?e:c),c-=8,f=b.low,g=b.high,this.littleEndian?(this.view[c+3]=255&f>>>24,this.view[c+2]=255&f>>>16,this.view[c+1]=255&f>>>8,this.view[c]=255&f,c+=4,this.view[c+3]=255&g>>>24,this.view[c+2]=255&g>>>16,this.view[c+1]=255&g>>>8,this.view[c]=255&g):(this.view[c]=255&g>>>24,this.view[c+1]=255&g>>>16,this.view[c+2]=255&g>>>8,this.view[c+3]=255&g,c+=4,this.view[c]=255&f>>>24,this.view[c+1]=255&f>>>16,this.view[c+2]=255&f>>>8,this.view[c+3]=255&f),d&&(this.offset+=8),this},c.writeLong=c.writeInt64,c.readInt64=function(b){var d,e,f,c="undefined"==typeof b;if(c&&(b=this.offset),!this.noAssert){if("number"!=typeof b||0!==b%1)throw TypeError("Illegal offset: "+b+" (not an integer)");if(b>>>=0,0>b||b+8>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+b+" (+"+8+") <= "+this.buffer.byteLength)}return d=0,e=0,this.littleEndian?(d=this.view[b+2]<<16,d|=this.view[b+1]<<8,d|=this.view[b],d+=this.view[b+3]<<24>>>0,b+=4,e=this.view[b+2]<<16,e|=this.view[b+1]<<8,e|=this.view[b],e+=this.view[b+3]<<24>>>0):(e=this.view[b+1]<<16,e|=this.view[b+2]<<8,e|=this.view[b+3],e+=this.view[b]<<24>>>0,b+=4,d=this.view[b+1]<<16,d|=this.view[b+2]<<8,d|=this.view[b+3],d+=this.view[b]<<24>>>0),f=new a(d,e,!1),c&&(this.offset+=8),f},c.readLong=c.readInt64,c.writeUint64=function(b,c){var e,f,g,d="undefined"==typeof c;if(d&&(c=this.offset),!this.noAssert){if("number"==typeof b)b=a.fromNumber(b);else if("string"==typeof b)b=a.fromString(b);else if(!(b&&b instanceof a))throw TypeError("Illegal value: "+b+" (not an integer or Long)");if("number"!=typeof c||0!==c%1)throw TypeError("Illegal offset: "+c+" (not an integer)");if(c>>>=0,0>c||c+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+c+" (+"+0+") <= "+this.buffer.byteLength)}return "number"==typeof b?b=a.fromNumber(b):"string"==typeof b&&(b=a.fromString(b)),c+=8,e=this.buffer.byteLength,c>e&&this.resize((e*=2)>c?e:c),c-=8,f=b.low,g=b.high,this.littleEndian?(this.view[c+3]=255&f>>>24,this.view[c+2]=255&f>>>16,this.view[c+1]=255&f>>>8,this.view[c]=255&f,c+=4,this.view[c+3]=255&g>>>24,this.view[c+2]=255&g>>>16,this.view[c+1]=255&g>>>8,this.view[c]=255&g):(this.view[c]=255&g>>>24,this.view[c+1]=255&g>>>16,this.view[c+2]=255&g>>>8,this.view[c+3]=255&g,c+=4,this.view[c]=255&f>>>24,this.view[c+1]=255&f>>>16,this.view[c+2]=255&f>>>8,this.view[c+3]=255&f),d&&(this.offset+=8),this},c.writeUInt64=c.writeUint64,c.readUint64=function(b){var d,e,f,c="undefined"==typeof b;if(c&&(b=this.offset),!this.noAssert){if("number"!=typeof b||0!==b%1)throw TypeError("Illegal offset: "+b+" (not an integer)");if(b>>>=0,0>b||b+8>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+b+" (+"+8+") <= "+this.buffer.byteLength)}return d=0,e=0,this.littleEndian?(d=this.view[b+2]<<16,d|=this.view[b+1]<<8,d|=this.view[b],d+=this.view[b+3]<<24>>>0,b+=4,e=this.view[b+2]<<16,e|=this.view[b+1]<<8,e|=this.view[b],e+=this.view[b+3]<<24>>>0):(e=this.view[b+1]<<16,e|=this.view[b+2]<<8,e|=this.view[b+3],e+=this.view[b]<<24>>>0,b+=4,d=this.view[b+1]<<16,d|=this.view[b+2]<<8,d|=this.view[b+3],d+=this.view[b]<<24>>>0),f=new a(d,e,!0),c&&(this.offset+=8),f},c.readUInt64=c.readUint64),c.writeFloat32=function(a,b){var d,c="undefined"==typeof b;if(c&&(b=this.offset),!this.noAssert){if("number"!=typeof a)throw TypeError("Illegal value: "+a+" (not a number)");if("number"!=typeof b||0!==b%1)throw TypeError("Illegal offset: "+b+" (not an integer)");if(b>>>=0,0>b||b+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+b+" (+"+0+") <= "+this.buffer.byteLength)}return b+=4,d=this.buffer.byteLength,b>d&&this.resize((d*=2)>b?d:b),b-=4,i(this.view,a,b,this.littleEndian,23,4),c&&(this.offset+=4),this},c.writeFloat=c.writeFloat32,c.readFloat32=function(a){var c,b="undefined"==typeof a;if(b&&(a=this.offset),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal offset: "+a+" (not an integer)");if(a>>>=0,0>a||a+4>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+a+" (+"+4+") <= "+this.buffer.byteLength)}return c=h(this.view,a,this.littleEndian,23,4),b&&(this.offset+=4),c},c.readFloat=c.readFloat32,c.writeFloat64=function(a,b){var d,c="undefined"==typeof b;if(c&&(b=this.offset),!this.noAssert){if("number"!=typeof a)throw TypeError("Illegal value: "+a+" (not a number)");if("number"!=typeof b||0!==b%1)throw TypeError("Illegal offset: "+b+" (not an integer)");if(b>>>=0,0>b||b+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+b+" (+"+0+") <= "+this.buffer.byteLength)}return b+=8,d=this.buffer.byteLength,b>d&&this.resize((d*=2)>b?d:b),b-=8,i(this.view,a,b,this.littleEndian,52,8),c&&(this.offset+=8),this},c.writeDouble=c.writeFloat64,c.readFloat64=function(a){var c,b="undefined"==typeof a;if(b&&(a=this.offset),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal offset: "+a+" (not an integer)");if(a>>>=0,0>a||a+8>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+a+" (+"+8+") <= "+this.buffer.byteLength)}return c=h(this.view,a,this.littleEndian,52,8),b&&(this.offset+=8),c},c.readDouble=c.readFloat64,b.MAX_VARINT32_BYTES=5,b.calculateVarint32=function(a){return a>>>=0,128>a?1:16384>a?2:1<<21>a?3:1<<28>a?4:5},b.zigZagEncode32=function(a){return ((a|=0)<<1^a>>31)>>>0},b.zigZagDecode32=function(a){return 0|a>>>1^-(1&a)},c.writeVarint32=function(a,c){var f,e,g,d="undefined"==typeof c;if(d&&(c=this.offset),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal value: "+a+" (not an integer)");if(a|=0,"number"!=typeof c||0!==c%1)throw TypeError("Illegal offset: "+c+" (not an integer)");if(c>>>=0,0>c||c+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+c+" (+"+0+") <= "+this.buffer.byteLength)}for(e=b.calculateVarint32(a),c+=e,g=this.buffer.byteLength,c>g&&this.resize((g*=2)>c?g:c),c-=e,a>>>=0;a>=128;)f=128|127&a,this.view[c++]=f,a>>>=7;return this.view[c++]=a,d?(this.offset=c,this):e},c.writeVarint32ZigZag=function(a,c){return this.writeVarint32(b.zigZagEncode32(a),c)},c.readVarint32=function(a){var e,c,d,f,b="undefined"==typeof a;if(b&&(a=this.offset),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal offset: "+a+" (not an integer)");if(a>>>=0,0>a||a+1>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+a+" (+"+1+") <= "+this.buffer.byteLength)}c=0,d=0;do{if(!this.noAssert&&a>this.limit)throw f=Error("Truncated"),f.truncated=!0,f;e=this.view[a++],5>c&&(d|=(127&e)<<7*c),++c;}while(0!==(128&e));return d|=0,b?(this.offset=a,d):{value:d,length:c}},c.readVarint32ZigZag=function(a){var c=this.readVarint32(a);return "object"==typeof c?c.value=b.zigZagDecode32(c.value):c=b.zigZagDecode32(c),c},a&&(b.MAX_VARINT64_BYTES=10,b.calculateVarint64=function(b){"number"==typeof b?b=a.fromNumber(b):"string"==typeof b&&(b=a.fromString(b));var c=b.toInt()>>>0,d=b.shiftRightUnsigned(28).toInt()>>>0,e=b.shiftRightUnsigned(56).toInt()>>>0;return 0==e?0==d?16384>c?128>c?1:2:1<<21>c?3:4:16384>d?128>d?5:6:1<<21>d?7:8:128>e?9:10},b.zigZagEncode64=function(b){return "number"==typeof b?b=a.fromNumber(b,!1):"string"==typeof b?b=a.fromString(b,!1):b.unsigned!==!1&&(b=b.toSigned()),b.shiftLeft(1).xor(b.shiftRight(63)).toUnsigned()},b.zigZagDecode64=function(b){return "number"==typeof b?b=a.fromNumber(b,!1):"string"==typeof b?b=a.fromString(b,!1):b.unsigned!==!1&&(b=b.toSigned()),b.shiftRightUnsigned(1).xor(b.and(a.ONE).toSigned().negate()).toSigned()},c.writeVarint64=function(c,d){var f,g,h,i,j,e="undefined"==typeof d;if(e&&(d=this.offset),!this.noAssert){if("number"==typeof c)c=a.fromNumber(c);else if("string"==typeof c)c=a.fromString(c);else if(!(c&&c instanceof a))throw TypeError("Illegal value: "+c+" (not an integer or Long)");if("number"!=typeof d||0!==d%1)throw TypeError("Illegal offset: "+d+" (not an integer)");if(d>>>=0,0>d||d+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+d+" (+"+0+") <= "+this.buffer.byteLength)}switch("number"==typeof c?c=a.fromNumber(c,!1):"string"==typeof c?c=a.fromString(c,!1):c.unsigned!==!1&&(c=c.toSigned()),f=b.calculateVarint64(c),g=c.toInt()>>>0,h=c.shiftRightUnsigned(28).toInt()>>>0,i=c.shiftRightUnsigned(56).toInt()>>>0,d+=f,j=this.buffer.byteLength,d>j&&this.resize((j*=2)>d?j:d),d-=f,f){case 10:this.view[d+9]=1&i>>>7;case 9:this.view[d+8]=9!==f?128|i:127&i;case 8:this.view[d+7]=8!==f?128|h>>>21:127&h>>>21;case 7:this.view[d+6]=7!==f?128|h>>>14:127&h>>>14;case 6:this.view[d+5]=6!==f?128|h>>>7:127&h>>>7;case 5:this.view[d+4]=5!==f?128|h:127&h;case 4:this.view[d+3]=4!==f?128|g>>>21:127&g>>>21;case 3:this.view[d+2]=3!==f?128|g>>>14:127&g>>>14;case 2:this.view[d+1]=2!==f?128|g>>>7:127&g>>>7;case 1:this.view[d]=1!==f?128|g:127&g;}return e?(this.offset+=f,this):f},c.writeVarint64ZigZag=function(a,c){return this.writeVarint64(b.zigZagEncode64(a),c)},c.readVarint64=function(b){var d,e,f,g,h,i,c="undefined"==typeof b;if(c&&(b=this.offset),!this.noAssert){if("number"!=typeof b||0!==b%1)throw TypeError("Illegal offset: "+b+" (not an integer)");if(b>>>=0,0>b||b+1>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+b+" (+"+1+") <= "+this.buffer.byteLength)}if(d=b,e=0,f=0,g=0,h=0,h=this.view[b++],e=127&h,128&h&&(h=this.view[b++],e|=(127&h)<<7,(128&h||this.noAssert&&"undefined"==typeof h)&&(h=this.view[b++],e|=(127&h)<<14,(128&h||this.noAssert&&"undefined"==typeof h)&&(h=this.view[b++],e|=(127&h)<<21,(128&h||this.noAssert&&"undefined"==typeof h)&&(h=this.view[b++],f=127&h,(128&h||this.noAssert&&"undefined"==typeof h)&&(h=this.view[b++],f|=(127&h)<<7,(128&h||this.noAssert&&"undefined"==typeof h)&&(h=this.view[b++],f|=(127&h)<<14,(128&h||this.noAssert&&"undefined"==typeof h)&&(h=this.view[b++],f|=(127&h)<<21,(128&h||this.noAssert&&"undefined"==typeof h)&&(h=this.view[b++],g=127&h,(128&h||this.noAssert&&"undefined"==typeof h)&&(h=this.view[b++],g|=(127&h)<<7,128&h||this.noAssert&&"undefined"==typeof h))))))))))throw Error("Buffer overrun");return i=a.fromBits(e|f<<28,f>>>4|g<<24,!1),c?(this.offset=b,i):{value:i,length:b-d}},c.readVarint64ZigZag=function(c){var d=this.readVarint64(c);return d&&d.value instanceof a?d.value=b.zigZagDecode64(d.value):d=b.zigZagDecode64(d),d}),c.writeCString=function(a,b){var d,e,g,c="undefined"==typeof b;if(c&&(b=this.offset),e=a.length,!this.noAssert){if("string"!=typeof a)throw TypeError("Illegal str: Not a string");for(d=0;e>d;++d)if(0===a.charCodeAt(d))throw RangeError("Illegal str: Contains NULL-characters");if("number"!=typeof b||0!==b%1)throw TypeError("Illegal offset: "+b+" (not an integer)");if(b>>>=0,0>b||b+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+b+" (+"+0+") <= "+this.buffer.byteLength)}return e=k.calculateUTF16asUTF8(f(a))[1],b+=e+1,g=this.buffer.byteLength,b>g&&this.resize((g*=2)>b?g:b),b-=e+1,k.encodeUTF16toUTF8(f(a),function(a){this.view[b++]=a;}.bind(this)),this.view[b++]=0,c?(this.offset=b,this):e},c.readCString=function(a){var c,e,f,b="undefined"==typeof a;if(b&&(a=this.offset),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal offset: "+a+" (not an integer)");if(a>>>=0,0>a||a+1>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+a+" (+"+1+") <= "+this.buffer.byteLength)}return c=a,f=-1,k.decodeUTF8toUTF16(function(){if(0===f)return null;if(a>=this.limit)throw RangeError("Illegal range: Truncated data, "+a+" < "+this.limit);return f=this.view[a++],0===f?null:f}.bind(this),e=g(),!0),b?(this.offset=a,e()):{string:e(),length:a-c}},c.writeIString=function(a,b){var e,d,g,c="undefined"==typeof b;if(c&&(b=this.offset),!this.noAssert){if("string"!=typeof a)throw TypeError("Illegal str: Not a string");if("number"!=typeof b||0!==b%1)throw TypeError("Illegal offset: "+b+" (not an integer)");if(b>>>=0,0>b||b+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+b+" (+"+0+") <= "+this.buffer.byteLength)}if(d=b,e=k.calculateUTF16asUTF8(f(a),this.noAssert)[1],b+=4+e,g=this.buffer.byteLength,b>g&&this.resize((g*=2)>b?g:b),b-=4+e,this.littleEndian?(this.view[b+3]=255&e>>>24,this.view[b+2]=255&e>>>16,this.view[b+1]=255&e>>>8,this.view[b]=255&e):(this.view[b]=255&e>>>24,this.view[b+1]=255&e>>>16,this.view[b+2]=255&e>>>8,this.view[b+3]=255&e),b+=4,k.encodeUTF16toUTF8(f(a),function(a){this.view[b++]=a;}.bind(this)),b!==d+4+e)throw RangeError("Illegal range: Truncated data, "+b+" == "+(b+4+e));return c?(this.offset=b,this):b-d},c.readIString=function(a){var d,e,f,c="undefined"==typeof a; if(c&&(a=this.offset),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal offset: "+a+" (not an integer)");if(a>>>=0,0>a||a+4>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+a+" (+"+4+") <= "+this.buffer.byteLength)}return d=a,e=this.readUint32(a),f=this.readUTF8String(e,b.METRICS_BYTES,a+=4),a+=f.length,c?(this.offset=a,f.string):{string:f.string,length:a-d}},b.METRICS_CHARS="c",b.METRICS_BYTES="b",c.writeUTF8String=function(a,b){var d,e,g,c="undefined"==typeof b;if(c&&(b=this.offset),!this.noAssert){if("number"!=typeof b||0!==b%1)throw TypeError("Illegal offset: "+b+" (not an integer)");if(b>>>=0,0>b||b+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+b+" (+"+0+") <= "+this.buffer.byteLength)}return e=b,d=k.calculateUTF16asUTF8(f(a))[1],b+=d,g=this.buffer.byteLength,b>g&&this.resize((g*=2)>b?g:b),b-=d,k.encodeUTF16toUTF8(f(a),function(a){this.view[b++]=a;}.bind(this)),c?(this.offset=b,this):b-e},c.writeString=c.writeUTF8String,b.calculateUTF8Chars=function(a){return k.calculateUTF16asUTF8(f(a))[0]},b.calculateUTF8Bytes=function(a){return k.calculateUTF16asUTF8(f(a))[1]},b.calculateString=b.calculateUTF8Bytes,c.readUTF8String=function(a,c,d){var e,i,f,h,j;if("number"==typeof c&&(d=c,c=void 0),e="undefined"==typeof d,e&&(d=this.offset),"undefined"==typeof c&&(c=b.METRICS_CHARS),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal length: "+a+" (not an integer)");if(a|=0,"number"!=typeof d||0!==d%1)throw TypeError("Illegal offset: "+d+" (not an integer)");if(d>>>=0,0>d||d+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+d+" (+"+0+") <= "+this.buffer.byteLength)}if(f=0,h=d,c===b.METRICS_CHARS){if(i=g(),k.decodeUTF8(function(){return a>f&&d>>=0,0>d||d+a>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+d+" (+"+a+") <= "+this.buffer.byteLength)}if(j=d+a,k.decodeUTF8toUTF16(function(){return j>d?this.view[d++]:null}.bind(this),i=g(),this.noAssert),d!==j)throw RangeError("Illegal range: Truncated data, "+d+" == "+j);return e?(this.offset=d,i()):{string:i(),length:d-h}}throw TypeError("Unsupported metrics: "+c)},c.readString=c.readUTF8String,c.writeVString=function(a,c){var g,h,e,i,d="undefined"==typeof c;if(d&&(c=this.offset),!this.noAssert){if("string"!=typeof a)throw TypeError("Illegal str: Not a string");if("number"!=typeof c||0!==c%1)throw TypeError("Illegal offset: "+c+" (not an integer)");if(c>>>=0,0>c||c+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+c+" (+"+0+") <= "+this.buffer.byteLength)}if(e=c,g=k.calculateUTF16asUTF8(f(a),this.noAssert)[1],h=b.calculateVarint32(g),c+=h+g,i=this.buffer.byteLength,c>i&&this.resize((i*=2)>c?i:c),c-=h+g,c+=this.writeVarint32(g,c),k.encodeUTF16toUTF8(f(a),function(a){this.view[c++]=a;}.bind(this)),c!==e+g+h)throw RangeError("Illegal range: Truncated data, "+c+" == "+(c+g+h));return d?(this.offset=c,this):c-e},c.readVString=function(a){var d,e,f,c="undefined"==typeof a;if(c&&(a=this.offset),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal offset: "+a+" (not an integer)");if(a>>>=0,0>a||a+1>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+a+" (+"+1+") <= "+this.buffer.byteLength)}return d=a,e=this.readVarint32(a),f=this.readUTF8String(e.value,b.METRICS_BYTES,a+=e.length),a+=f.length,c?(this.offset=a,f.string):{string:f.string,length:a-d}},c.append=function(a,c,d){var e,f,g;if(("number"==typeof c||"string"!=typeof c)&&(d=c,c=void 0),e="undefined"==typeof d,e&&(d=this.offset),!this.noAssert){if("number"!=typeof d||0!==d%1)throw TypeError("Illegal offset: "+d+" (not an integer)");if(d>>>=0,0>d||d+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+d+" (+"+0+") <= "+this.buffer.byteLength)}return a instanceof b||(a=b.wrap(a,c)),f=a.limit-a.offset,0>=f?this:(d+=f,g=this.buffer.byteLength,d>g&&this.resize((g*=2)>d?g:d),d-=f,this.view.set(a.view.subarray(a.offset,a.limit),d),a.offset+=f,e&&(this.offset+=f),this)},c.appendTo=function(a,b){return a.append(this,b),this},c.assert=function(a){return this.noAssert=!a,this},c.capacity=function(){return this.buffer.byteLength},c.clear=function(){return this.offset=0,this.limit=this.buffer.byteLength,this.markedOffset=-1,this},c.clone=function(a){var c=new b(0,this.littleEndian,this.noAssert);return a?(c.buffer=new ArrayBuffer(this.buffer.byteLength),c.view=new Uint8Array(c.buffer)):(c.buffer=this.buffer,c.view=this.view),c.offset=this.offset,c.markedOffset=this.markedOffset,c.limit=this.limit,c},c.compact=function(a,b){var c,e,f;if("undefined"==typeof a&&(a=this.offset),"undefined"==typeof b&&(b=this.limit),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal begin: Not an integer");if(a>>>=0,"number"!=typeof b||0!==b%1)throw TypeError("Illegal end: Not an integer");if(b>>>=0,0>a||a>b||b>this.buffer.byteLength)throw RangeError("Illegal range: 0 <= "+a+" <= "+b+" <= "+this.buffer.byteLength)}return 0===a&&b===this.buffer.byteLength?this:(c=b-a,0===c?(this.buffer=d,this.view=null,this.markedOffset>=0&&(this.markedOffset-=a),this.offset=0,this.limit=0,this):(e=new ArrayBuffer(c),f=new Uint8Array(e),f.set(this.view.subarray(a,b)),this.buffer=e,this.view=f,this.markedOffset>=0&&(this.markedOffset-=a),this.offset=0,this.limit=c,this))},c.copy=function(a,c){if("undefined"==typeof a&&(a=this.offset),"undefined"==typeof c&&(c=this.limit),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal begin: Not an integer");if(a>>>=0,"number"!=typeof c||0!==c%1)throw TypeError("Illegal end: Not an integer");if(c>>>=0,0>a||a>c||c>this.buffer.byteLength)throw RangeError("Illegal range: 0 <= "+a+" <= "+c+" <= "+this.buffer.byteLength)}if(a===c)return new b(0,this.littleEndian,this.noAssert);var d=c-a,e=new b(d,this.littleEndian,this.noAssert);return e.offset=0,e.limit=d,e.markedOffset>=0&&(e.markedOffset-=a),this.copyTo(e,0,a,c),e},c.copyTo=function(a,c,d,e){var f,g,h;if(!this.noAssert&&!b.isByteBuffer(a))throw TypeError("Illegal target: Not a ByteBuffer");if(c=(g="undefined"==typeof c)?a.offset:0|c,d=(f="undefined"==typeof d)?this.offset:0|d,e="undefined"==typeof e?this.limit:0|e,0>c||c>a.buffer.byteLength)throw RangeError("Illegal target range: 0 <= "+c+" <= "+a.buffer.byteLength);if(0>d||e>this.buffer.byteLength)throw RangeError("Illegal source range: 0 <= "+d+" <= "+this.buffer.byteLength);return h=e-d,0===h?a:(a.ensureCapacity(c+h),a.view.set(this.view.subarray(d,e),c),f&&(this.offset+=h),g&&(a.offset+=h),this)},c.ensureCapacity=function(a){var b=this.buffer.byteLength;return a>b?this.resize((b*=2)>a?b:a):this},c.fill=function(a,b,c){var d="undefined"==typeof b;if(d&&(b=this.offset),"string"==typeof a&&a.length>0&&(a=a.charCodeAt(0)),"undefined"==typeof b&&(b=this.offset),"undefined"==typeof c&&(c=this.limit),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal value: "+a+" (not an integer)");if(a|=0,"number"!=typeof b||0!==b%1)throw TypeError("Illegal begin: Not an integer");if(b>>>=0,"number"!=typeof c||0!==c%1)throw TypeError("Illegal end: Not an integer");if(c>>>=0,0>b||b>c||c>this.buffer.byteLength)throw RangeError("Illegal range: 0 <= "+b+" <= "+c+" <= "+this.buffer.byteLength)}if(b>=c)return this;for(;c>b;)this.view[b++]=a;return d&&(this.offset=b),this},c.flip=function(){return this.limit=this.offset,this.offset=0,this},c.mark=function(a){if(a="undefined"==typeof a?this.offset:a,!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal offset: "+a+" (not an integer)");if(a>>>=0,0>a||a+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+a+" (+"+0+") <= "+this.buffer.byteLength)}return this.markedOffset=a,this},c.order=function(a){if(!this.noAssert&&"boolean"!=typeof a)throw TypeError("Illegal littleEndian: Not a boolean");return this.littleEndian=!!a,this},c.LE=function(a){return this.littleEndian="undefined"!=typeof a?!!a:!0,this},c.BE=function(a){return this.littleEndian="undefined"!=typeof a?!a:!1,this},c.prepend=function(a,c,d){var e,f,g,h,i;if(("number"==typeof c||"string"!=typeof c)&&(d=c,c=void 0),e="undefined"==typeof d,e&&(d=this.offset),!this.noAssert){if("number"!=typeof d||0!==d%1)throw TypeError("Illegal offset: "+d+" (not an integer)");if(d>>>=0,0>d||d+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+d+" (+"+0+") <= "+this.buffer.byteLength)}return a instanceof b||(a=b.wrap(a,c)),f=a.limit-a.offset,0>=f?this:(g=f-d,g>0?(h=new ArrayBuffer(this.buffer.byteLength+g),i=new Uint8Array(h),i.set(this.view.subarray(d,this.buffer.byteLength),f),this.buffer=h,this.view=i,this.offset+=g,this.markedOffset>=0&&(this.markedOffset+=g),this.limit+=g,d+=g):new Uint8Array(this.buffer),this.view.set(a.view.subarray(a.offset,a.limit),d-f),a.offset=a.limit,e&&(this.offset-=f),this)},c.prependTo=function(a,b){return a.prepend(this,b),this},c.printDebug=function(a){"function"!=typeof a&&(a=console.log.bind(console)),a(this.toString()+"\n-------------------------------------------------------------------\n"+this.toDebug(!0));},c.remaining=function(){return this.limit-this.offset},c.reset=function(){return this.markedOffset>=0?(this.offset=this.markedOffset,this.markedOffset=-1):this.offset=0,this},c.resize=function(a){var b,c;if(!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal capacity: "+a+" (not an integer)");if(a|=0,0>a)throw RangeError("Illegal capacity: 0 <= "+a)}return this.buffer.byteLength>>=0,"number"!=typeof b||0!==b%1)throw TypeError("Illegal end: Not an integer");if(b>>>=0,0>a||a>b||b>this.buffer.byteLength)throw RangeError("Illegal range: 0 <= "+a+" <= "+b+" <= "+this.buffer.byteLength)}return a===b?this:(Array.prototype.reverse.call(this.view.subarray(a,b)),this)},c.skip=function(a){if(!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal length: "+a+" (not an integer)");a|=0;}var b=this.offset+a;if(!this.noAssert&&(0>b||b>this.buffer.byteLength))throw RangeError("Illegal length: 0 <= "+this.offset+" + "+a+" <= "+this.buffer.byteLength);return this.offset=b,this},c.slice=function(a,b){if("undefined"==typeof a&&(a=this.offset),"undefined"==typeof b&&(b=this.limit),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal begin: Not an integer");if(a>>>=0,"number"!=typeof b||0!==b%1)throw TypeError("Illegal end: Not an integer");if(b>>>=0,0>a||a>b||b>this.buffer.byteLength)throw RangeError("Illegal range: 0 <= "+a+" <= "+b+" <= "+this.buffer.byteLength)}var c=this.clone();return c.offset=a,c.limit=b,c},c.toBuffer=function(a){var e,b=this.offset,c=this.limit;if(!this.noAssert){if("number"!=typeof b||0!==b%1)throw TypeError("Illegal offset: Not an integer");if(b>>>=0,"number"!=typeof c||0!==c%1)throw TypeError("Illegal limit: Not an integer");if(c>>>=0,0>b||b>c||c>this.buffer.byteLength)throw RangeError("Illegal range: 0 <= "+b+" <= "+c+" <= "+this.buffer.byteLength)}return a||0!==b||c!==this.buffer.byteLength?b===c?d:(e=new ArrayBuffer(c-b),new Uint8Array(e).set(new Uint8Array(this.buffer).subarray(b,c),0),e):this.buffer},c.toArrayBuffer=c.toBuffer,c.toString=function(a,b,c){if("undefined"==typeof a)return "ByteBufferAB(offset="+this.offset+",markedOffset="+this.markedOffset+",limit="+this.limit+",capacity="+this.capacity()+")";switch("number"==typeof a&&(a="utf8",b=a,c=b),a){case"utf8":return this.toUTF8(b,c);case"base64":return this.toBase64(b,c);case"hex":return this.toHex(b,c);case"binary":return this.toBinary(b,c);case"debug":return this.toDebug();case"columns":return this.toColumns();default:throw Error("Unsupported encoding: "+a)}},j=function(){var d,e,a={},b=[65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,48,49,50,51,52,53,54,55,56,57,43,47],c=[];for(d=0,e=b.length;e>d;++d)c[b[d]]=d;return a.encode=function(a,c){for(var d,e;null!==(d=a());)c(b[63&d>>2]),e=(3&d)<<4,null!==(d=a())?(e|=15&d>>4,c(b[63&(e|15&d>>4)]),e=(15&d)<<2,null!==(d=a())?(c(b[63&(e|3&d>>6)]),c(b[63&d])):(c(b[63&e]),c(61))):(c(b[63&e]),c(61),c(61));},a.decode=function(a,b){function g(a){throw Error("Illegal character code: "+a)}for(var d,e,f;null!==(d=a());)if(e=c[d],"undefined"==typeof e&&g(d),null!==(d=a())&&(f=c[d],"undefined"==typeof f&&g(d),b(e<<2>>>0|(48&f)>>4),null!==(d=a()))){if(e=c[d],"undefined"==typeof e){if(61===d)break;g(d);}if(b((15&f)<<4>>>0|(60&e)>>2),null!==(d=a())){if(f=c[d],"undefined"==typeof f){if(61===d)break;g(d);}b((3&e)<<6>>>0|f);}}},a.test=function(a){return /^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/.test(a)},a}(),c.toBase64=function(a,b){if("undefined"==typeof a&&(a=this.offset),"undefined"==typeof b&&(b=this.limit),a=0|a,b=0|b,0>a||b>this.capacity||a>b)throw RangeError("begin, end");var c;return j.encode(function(){return b>a?this.view[a++]:null}.bind(this),c=g()),c()},b.fromBase64=function(a,c){if("string"!=typeof a)throw TypeError("str");var d=new b(3*(a.length/4),c),e=0;return j.decode(f(a),function(a){d.view[e++]=a;}),d.limit=e,d},b.btoa=function(a){return b.fromBinary(a).toBase64()},b.atob=function(a){return b.fromBase64(a).toBinary()},c.toBinary=function(a,b){if("undefined"==typeof a&&(a=this.offset),"undefined"==typeof b&&(b=this.limit),a|=0,b|=0,0>a||b>this.capacity()||a>b)throw RangeError("begin, end");if(a===b)return "";for(var c=[],d=[];b>a;)c.push(this.view[a++]),c.length>=1024&&(d.push(String.fromCharCode.apply(String,c)),c=[]);return d.join("")+String.fromCharCode.apply(String,c)},b.fromBinary=function(a,c){if("string"!=typeof a)throw TypeError("str");for(var f,d=0,e=a.length,g=new b(e,c);e>d;){if(f=a.charCodeAt(d),f>255)throw RangeError("illegal char code: "+f);g.view[d++]=f;}return g.limit=e,g},c.toDebug=function(a){for(var d,b=-1,c=this.buffer.byteLength,e="",f="",g="";c>b;){if(-1!==b&&(d=this.view[b],e+=16>d?"0"+d.toString(16).toUpperCase():d.toString(16).toUpperCase(),a&&(f+=d>32&&127>d?String.fromCharCode(d):".")),++b,a&&b>0&&0===b%16&&b!==c){for(;e.length<51;)e+=" ";g+=e+f+"\n",e=f="";}e+=b===this.offset&&b===this.limit?b===this.markedOffset?"!":"|":b===this.offset?b===this.markedOffset?"[":"<":b===this.limit?b===this.markedOffset?"]":">":b===this.markedOffset?"'":a||0!==b&&b!==c?" ":"";}if(a&&" "!==e){for(;e.length<51;)e+=" ";g+=e+f+"\n";}return a?g:e},b.fromDebug=function(a,c,d){for(var i,j,e=a.length,f=new b(0|(e+1)/3,c,d),g=0,h=0,k=!1,l=!1,m=!1,n=!1,o=!1;e>g;){switch(i=a.charAt(g++)){case"!":if(!d){if(l||m||n){o=!0;break}l=m=n=!0;}f.offset=f.markedOffset=f.limit=h,k=!1;break;case"|":if(!d){if(l||n){o=!0;break}l=n=!0;}f.offset=f.limit=h,k=!1;break;case"[":if(!d){if(l||m){o=!0;break}l=m=!0;}f.offset=f.markedOffset=h,k=!1;break;case"<":if(!d){if(l){o=!0;break}l=!0;}f.offset=h,k=!1;break;case"]":if(!d){if(n||m){o=!0;break}n=m=!0;}f.limit=f.markedOffset=h,k=!1;break;case">":if(!d){if(n){o=!0;break}n=!0;}f.limit=h,k=!1;break;case"'":if(!d){if(m){o=!0;break}m=!0;}f.markedOffset=h,k=!1;break;case" ":k=!1;break;default:if(!d&&k){o=!0;break}if(j=parseInt(i+a.charAt(g++),16),!d&&(isNaN(j)||0>j||j>255))throw TypeError("Illegal str: Not a debug encoded string");f.view[h++]=j,k=!0;}if(o)throw TypeError("Illegal str: Invalid symbol at "+g)}if(!d){if(!l||!n)throw TypeError("Illegal str: Missing offset or limit");if(h>>=0,"number"!=typeof b||0!==b%1)throw TypeError("Illegal end: Not an integer");if(b>>>=0,0>a||a>b||b>this.buffer.byteLength)throw RangeError("Illegal range: 0 <= "+a+" <= "+b+" <= "+this.buffer.byteLength)}for(var d,c=new Array(b-a);b>a;)d=this.view[a++],16>d?c.push("0",d.toString(16)):c.push(d.toString(16));return c.join("")},b.fromHex=function(a,c,d){var g,e,f,h,i;if(!d){if("string"!=typeof a)throw TypeError("Illegal str: Not a string");if(0!==a.length%2)throw TypeError("Illegal str: Length not a multiple of 2")}for(e=a.length,f=new b(0|e/2,c),h=0,i=0;e>h;h+=2){if(g=parseInt(a.substring(h,h+2),16),!d&&(!isFinite(g)||0>g||g>255))throw TypeError("Illegal str: Contains non-hex characters");f.view[i++]=g;}return f.limit=i,f},k=function(){var a={};return a.MAX_CODEPOINT=1114111,a.encodeUTF8=function(a,b){var c=null;for("number"==typeof a&&(c=a,a=function(){return null});null!==c||null!==(c=a());)128>c?b(127&c):2048>c?(b(192|31&c>>6),b(128|63&c)):65536>c?(b(224|15&c>>12),b(128|63&c>>6),b(128|63&c)):(b(240|7&c>>18),b(128|63&c>>12),b(128|63&c>>6),b(128|63&c)),c=null;},a.decodeUTF8=function(a,b){for(var c,d,e,f,g=function(a){a=a.slice(0,a.indexOf(null));var b=Error(a.toString());throw b.name="TruncatedError",b.bytes=a,b};null!==(c=a());)if(0===(128&c))b(c);else if(192===(224&c))null===(d=a())&&g([c,d]),b((31&c)<<6|63&d);else if(224===(240&c))(null===(d=a())||null===(e=a()))&&g([c,d,e]),b((15&c)<<12|(63&d)<<6|63&e);else{if(240!==(248&c))throw RangeError("Illegal starting byte: "+c);(null===(d=a())||null===(e=a())||null===(f=a()))&&g([c,d,e,f]),b((7&c)<<18|(63&d)<<12|(63&e)<<6|63&f);}},a.UTF16toUTF8=function(a,b){for(var c,d=null;;){if(null===(c=null!==d?d:a()))break;c>=55296&&57343>=c&&null!==(d=a())&&d>=56320&&57343>=d?(b(1024*(c-55296)+d-56320+65536),d=null):b(c);}null!==d&&b(d);},a.UTF8toUTF16=function(a,b){var c=null;for("number"==typeof a&&(c=a,a=function(){return null});null!==c||null!==(c=a());)65535>=c?b(c):(c-=65536,b((c>>10)+55296),b(c%1024+56320)),c=null;},a.encodeUTF16toUTF8=function(b,c){a.UTF16toUTF8(b,function(b){a.encodeUTF8(b,c);});},a.decodeUTF8toUTF16=function(b,c){a.decodeUTF8(b,function(b){a.UTF8toUTF16(b,c);});},a.calculateCodePoint=function(a){return 128>a?1:2048>a?2:65536>a?3:4},a.calculateUTF8=function(a){for(var b,c=0;null!==(b=a());)c+=128>b?1:2048>b?2:65536>b?3:4;return c},a.calculateUTF16asUTF8=function(b){var c=0,d=0;return a.UTF16toUTF8(b,function(a){++c,d+=128>a?1:2048>a?2:65536>a?3:4;}),[c,d]},a}(),c.toUTF8=function(a,b){if("undefined"==typeof a&&(a=this.offset),"undefined"==typeof b&&(b=this.limit),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal begin: Not an integer");if(a>>>=0,"number"!=typeof b||0!==b%1)throw TypeError("Illegal end: Not an integer");if(b>>>=0,0>a||a>b||b>this.buffer.byteLength)throw RangeError("Illegal range: 0 <= "+a+" <= "+b+" <= "+this.buffer.byteLength)}var c;try{k.decodeUTF8toUTF16(function(){return b>a?this.view[a++]:null}.bind(this),c=g());}catch(d){if(a!==b)throw RangeError("Illegal range: Truncated data, "+a+" != "+b)}return c()},b.fromUTF8=function(a,c,d){if(!d&&"string"!=typeof a)throw TypeError("Illegal str: Not a string");var e=new b(k.calculateUTF16asUTF8(f(a),!0)[1],c,d),g=0;return k.encodeUTF16toUTF8(f(a),function(a){e.view[g++]=a;}),e.limit=g,e},b}(c),e=function(b,c){var f,h,i,e={};return e.ByteBuffer=b,e.c=b,f=b,e.Long=c||null,e.VERSION="5.0.1",e.WIRE_TYPES={},e.WIRE_TYPES.VARINT=0,e.WIRE_TYPES.BITS64=1,e.WIRE_TYPES.LDELIM=2,e.WIRE_TYPES.STARTGROUP=3,e.WIRE_TYPES.ENDGROUP=4,e.WIRE_TYPES.BITS32=5,e.PACKABLE_WIRE_TYPES=[e.WIRE_TYPES.VARINT,e.WIRE_TYPES.BITS64,e.WIRE_TYPES.BITS32],e.TYPES={int32:{name:"int32",wireType:e.WIRE_TYPES.VARINT,defaultValue:0},uint32:{name:"uint32",wireType:e.WIRE_TYPES.VARINT,defaultValue:0},sint32:{name:"sint32",wireType:e.WIRE_TYPES.VARINT,defaultValue:0},int64:{name:"int64",wireType:e.WIRE_TYPES.VARINT,defaultValue:e.Long?e.Long.ZERO:void 0},uint64:{name:"uint64",wireType:e.WIRE_TYPES.VARINT,defaultValue:e.Long?e.Long.UZERO:void 0},sint64:{name:"sint64",wireType:e.WIRE_TYPES.VARINT,defaultValue:e.Long?e.Long.ZERO:void 0},bool:{name:"bool",wireType:e.WIRE_TYPES.VARINT,defaultValue:!1},"double":{name:"double",wireType:e.WIRE_TYPES.BITS64,defaultValue:0},string:{name:"string",wireType:e.WIRE_TYPES.LDELIM,defaultValue:""},bytes:{name:"bytes",wireType:e.WIRE_TYPES.LDELIM,defaultValue:null},fixed32:{name:"fixed32",wireType:e.WIRE_TYPES.BITS32,defaultValue:0},sfixed32:{name:"sfixed32",wireType:e.WIRE_TYPES.BITS32,defaultValue:0},fixed64:{name:"fixed64",wireType:e.WIRE_TYPES.BITS64,defaultValue:e.Long?e.Long.UZERO:void 0},sfixed64:{name:"sfixed64",wireType:e.WIRE_TYPES.BITS64,defaultValue:e.Long?e.Long.ZERO:void 0},"float":{name:"float",wireType:e.WIRE_TYPES.BITS32,defaultValue:0},"enum":{name:"enum",wireType:e.WIRE_TYPES.VARINT,defaultValue:0},message:{name:"message",wireType:e.WIRE_TYPES.LDELIM,defaultValue:null},group:{name:"group",wireType:e.WIRE_TYPES.STARTGROUP,defaultValue:null}},e.MAP_KEY_TYPES=[e.TYPES.int32,e.TYPES.sint32,e.TYPES.sfixed32,e.TYPES.uint32,e.TYPES.fixed32,e.TYPES.int64,e.TYPES.sint64,e.TYPES.sfixed64,e.TYPES.uint64,e.TYPES.fixed64,e.TYPES.bool,e.TYPES.string,e.TYPES.bytes],e.ID_MIN=1,e.ID_MAX=536870911,e.convertFieldsToCamelCase=!1,e.populateAccessors=!0,e.populateDefaults=!0,e.Util=function(){var a={};return a.IS_NODE=!("object"!=typeof process||"[object process]"!=process+""||process.browser),a.XHR=function(){var c,a=[function(){return new XMLHttpRequest},function(){return new ActiveXObject("Msxml2.XMLHTTP")},function(){return new ActiveXObject("Msxml3.XMLHTTP")},function(){return new ActiveXObject("Microsoft.XMLHTTP")}],b=null;for(c=0;c]/g,RULE:/^(?:required|optional|repeated|map)$/,TYPE:/^(?:double|float|int32|uint32|sint32|int64|uint64|sint64|fixed32|sfixed32|fixed64|sfixed64|bool|string|bytes)$/,NAME:/^[a-zA-Z_][a-zA-Z_0-9]*$/,TYPEDEF:/^[a-zA-Z][a-zA-Z_0-9]*$/,TYPEREF:/^(?:\.?[a-zA-Z_][a-zA-Z_0-9]*)+$/,FQTYPEREF:/^(?:\.[a-zA-Z][a-zA-Z_0-9]*)+$/,NUMBER:/^-?(?:[1-9][0-9]*|0|0[xX][0-9a-fA-F]+|0[0-7]+|([0-9]*(\.[0-9]*)?([Ee][+-]?[0-9]+)?)|inf|nan)$/,NUMBER_DEC:/^(?:[1-9][0-9]*|0)$/,NUMBER_HEX:/^0[xX][0-9a-fA-F]+$/,NUMBER_OCT:/^0[0-7]+$/,NUMBER_FLT:/^([0-9]*(\.[0-9]*)?([Ee][+-]?[0-9]+)?|inf|nan)$/,BOOL:/^(?:true|false)$/i,ID:/^(?:[1-9][0-9]*|0|0[xX][0-9a-fA-F]+|0[0-7]+)$/,NEGID:/^\-?(?:[1-9][0-9]*|0|0[xX][0-9a-fA-F]+|0[0-7]+)$/,WHITESPACE:/\s/,STRING:/(?:"([^"\\]*(?:\\.[^"\\]*)*)")|(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g,STRING_DQ:/(?:"([^"\\]*(?:\\.[^"\\]*)*)")/g,STRING_SQ:/(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g},e.DotProto=function(a,b){function h(a,c){var d=-1,e=1;if("-"==a.charAt(0)&&(e=-1,a=a.substring(1)),b.NUMBER_DEC.test(a))d=parseInt(a);else if(b.NUMBER_HEX.test(a))d=parseInt(a.substring(2),16);else{if(!b.NUMBER_OCT.test(a))throw Error("illegal id value: "+(0>e?"-":"")+a);d=parseInt(a.substring(1),8);}if(d=0|e*d,!c&&0>d)throw Error("illegal id value: "+(0>e?"-":"")+a);return d}function i(a){var c=1;if("-"==a.charAt(0)&&(c=-1,a=a.substring(1)),b.NUMBER_DEC.test(a))return c*parseInt(a,10);if(b.NUMBER_HEX.test(a))return c*parseInt(a.substring(2),16);if(b.NUMBER_OCT.test(a))return c*parseInt(a.substring(1),8);if("inf"===a)return 1/0*c;if("nan"===a)return 0/0;if(b.NUMBER_FLT.test(a))return c*parseFloat(a);throw Error("illegal number value: "+(0>c?"-":"")+a)}function j(a,b,c){"undefined"==typeof a[b]?a[b]=c:(Array.isArray(a[b])||(a[b]=[a[b]]),a[b].push(c));}var f,g,c={},d=function(a){this.source=a+"",this.index=0,this.line=1,this.stack=[],this._stringOpen=null;},e=d.prototype;return e._readString=function(){var c,a='"'===this._stringOpen?b.STRING_DQ:b.STRING_SQ;if(a.lastIndex=this.index-1,c=a.exec(this.source),!c)throw Error("unterminated string");return this.index=a.lastIndex,this.stack.push(this._stringOpen),this._stringOpen=null,c[1]},e.next=function(){var a,c,d,e,f,g;if(this.stack.length>0)return this.stack.shift();if(this.index>=this.source.length)return null;if(null!==this._stringOpen)return this._readString();do{for(a=!1;b.WHITESPACE.test(d=this.source.charAt(this.index));)if("\n"===d&&++this.line,++this.index===this.source.length)return null;if("/"===this.source.charAt(this.index))if(++this.index,"/"===this.source.charAt(this.index)){for(;"\n"!==this.source.charAt(++this.index);)if(this.index==this.source.length)return null;++this.index,++this.line,a=!0;}else{if("*"!==(d=this.source.charAt(this.index)))return "/";do{if("\n"===d&&++this.line,++this.index===this.source.length)return null;c=d,d=this.source.charAt(this.index);}while("*"!==c||"/"!==d);++this.index,a=!0;}}while(a);if(this.index===this.source.length)return null;if(e=this.index,b.DELIM.lastIndex=0,f=b.DELIM.test(this.source.charAt(e++)),!f)for(;e"),f=this.tn.next(),!b.NAME.test(f))throw Error("illegal message field name: "+f);e.name=f,this.tn.skip("="),e.id=h(this.tn.next()),f=this.tn.peek(),"["===f&&this._parseFieldOptions(e),this.tn.skip(";");}else if(d="undefined"!=typeof d?d:this.tn.next(),"group"===d){if(g=this._parseMessage(a,e),!/^[A-Z]/.test(g.name))throw Error("illegal group name: "+g.name);e.type=g.name,e.name=g.name.toLowerCase(),this.tn.omit(";");}else{if(!b.TYPE.test(d)&&!b.TYPEREF.test(d))throw Error("illegal message field type: "+d);if(e.type=d,f=this.tn.next(),!b.NAME.test(f))throw Error("illegal message field name: "+f); e.name=f,this.tn.skip("="),e.id=h(this.tn.next()),f=this.tn.peek(),"["===f&&this._parseFieldOptions(e),this.tn.skip(";");}return a.fields.push(e),e},g._parseMessageOneOf=function(a){var e,d,f,c=this.tn.next();if(!b.NAME.test(c))throw Error("illegal oneof name: "+c);for(d=c,f=[],this.tn.skip("{");"}"!==(c=this.tn.next());)e=this._parseMessageField(a,"optional",c),e.oneof=d,f.push(e.id);this.tn.omit(";"),a.oneofs[d]=f;},g._parseFieldOptions=function(a){this.tn.skip("[");for(var b,c=!0;"]"!==(b=this.tn.peek());)c||this.tn.skip(","),this._parseOption(a,!0),c=!1;this.tn.next();},g._parseEnum=function(a){var e,c={name:"",values:[],options:{}},d=this.tn.next();if(!b.NAME.test(d))throw Error("illegal name: "+d);for(c.name=d,this.tn.skip("{");"}"!==(d=this.tn.next());)if("option"===d)this._parseOption(c);else{if(!b.NAME.test(d))throw Error("illegal name: "+d);this.tn.skip("="),e={name:d,id:h(this.tn.next(),!0)},d=this.tn.peek(),"["===d&&this._parseFieldOptions({options:{}}),this.tn.skip(";"),c.values.push(e);}this.tn.omit(";"),a.enums.push(c);},g._parseExtensionRanges=function(){var c,d,e,b=[];do{for(d=[];;){switch(c=this.tn.next()){case"min":e=a.ID_MIN;break;case"max":e=a.ID_MAX;break;default:e=i(c);}if(d.push(e),2===d.length)break;if("to"!==this.tn.peek()){d.push(e);break}this.tn.next();}b.push(d);}while(this.tn.omit(","));return this.tn.skip(";"),b},g._parseExtend=function(a){var d,c=this.tn.next();if(!b.TYPEREF.test(c))throw Error("illegal extend reference: "+c);for(d={ref:c,fields:[]},this.tn.skip("{");"}"!==(c=this.tn.next());)if(b.RULE.test(c))this._parseMessageField(d,c);else{if(!b.TYPEREF.test(c))throw Error("illegal extend token: "+c);if(!this.proto3)throw Error("illegal field rule: "+c);this._parseMessageField(d,"optional",c);}return this.tn.omit(";"),a.messages.push(d),d},g.toString=function(){return "Parser at line "+this.tn.line},c.Parser=f,c}(e,e.Lang),e.Reflect=function(a){function k(b){if("string"==typeof b&&(b=a.TYPES[b]),"undefined"==typeof b.defaultValue)throw Error("default value for type "+b.name+" is not supported");return b==a.TYPES.bytes?new f(0):b.defaultValue}function l(b,c){if(b&&"number"==typeof b.low&&"number"==typeof b.high&&"boolean"==typeof b.unsigned&&b.low===b.low&&b.high===b.high)return new a.Long(b.low,b.high,"undefined"==typeof c?b.unsigned:c);if("string"==typeof b)return a.Long.fromString(b,c||!1,10);if("number"==typeof b)return a.Long.fromNumber(b,c||!1);throw Error("not convertible to Long")}function o(b,c){var d=c.readVarint32(),e=7&d,f=d>>>3;switch(e){case a.WIRE_TYPES.VARINT:do d=c.readUint8();while(128===(128&d));break;case a.WIRE_TYPES.BITS64:c.offset+=8;break;case a.WIRE_TYPES.LDELIM:d=c.readVarint32(),c.offset+=d;break;case a.WIRE_TYPES.STARTGROUP:o(f,c);break;case a.WIRE_TYPES.ENDGROUP:if(f===b)return !1;throw Error("Illegal GROUPEND after unknown group: "+f+" ("+b+" expected)");case a.WIRE_TYPES.BITS32:c.offset+=4;break;default:throw Error("Illegal wire type in unknown group "+b+": "+e)}return !0}var g,h,i,j,m,n,p,q,r,s,t,u,v,w,x,y,z,A,B,c={},d=function(a,b,c){this.builder=a,this.parent=b,this.name=c,this.className;},e=d.prototype;return e.fqn=function(){for(var a=this.name,b=this;;){if(b=b.parent,null==b)break;a=b.name+"."+a;}return a},e.toString=function(a){return (a?this.className+" ":"")+this.fqn()},e.build=function(){throw Error(this.toString(!0)+" cannot be built directly")},c.T=d,g=function(a,b,c,e,f){d.call(this,a,b,c),this.className="Namespace",this.children=[],this.options=e||{},this.syntax=f||"proto2";},h=g.prototype=Object.create(d.prototype),h.getChildren=function(a){var b,c,d;if(a=a||null,null==a)return this.children.slice();for(b=[],c=0,d=this.children.length;d>c;++c)this.children[c]instanceof a&&b.push(this.children[c]);return b},h.addChild=function(a){var b;if(b=this.getChild(a.name))if(b instanceof m.Field&&b.name!==b.originalName&&null===this.getChild(b.originalName))b.name=b.originalName;else{if(!(a instanceof m.Field&&a.name!==a.originalName&&null===this.getChild(a.originalName)))throw Error("Duplicate name in namespace "+this.toString(!0)+": "+a.name);a.name=a.originalName;}this.children.push(a);},h.getChild=function(a){var c,d,b="number"==typeof a?"id":"name";for(c=0,d=this.children.length;d>c;++c)if(this.children[c][b]===a)return this.children[c];return null},h.resolve=function(a,b){var g,d="string"==typeof a?a.split("."):a,e=this,f=0;if(""===d[f]){for(;null!==e.parent;)e=e.parent;f++;}do{do{if(!(e instanceof c.Namespace)){e=null;break}if(g=e.getChild(d[f]),!(g&&g instanceof c.T&&(!b||g instanceof c.Namespace))){e=null;break}e=g,f++;}while(fc;++c)e=b[c],e instanceof g&&(a[e.name]=e.build());return Object.defineProperty&&Object.defineProperty(a,"$options",{value:this.buildOpt()}),a},h.buildOpt=function(){var c,d,e,f,a={},b=Object.keys(this.options);for(c=0,d=b.length;d>c;++c)e=b[c],f=this.options[b[c]],a[e]=f;return a},h.getOption=function(a){return "undefined"==typeof a?this.options:"undefined"!=typeof this.options[a]?this.options[a]:null},c.Namespace=g,i=function(b,c,d,e){if(this.type=b,this.resolvedType=c,this.isMapKey=d,this.syntax=e,d&&a.MAP_KEY_TYPES.indexOf(b)<0)throw Error("Invalid map key type: "+b.name)},j=i.prototype,i.defaultFieldValue=k,j.verifyValue=function(c){var f,g,h,d=function(a,b){throw Error("Illegal value for "+this.toString(!0)+" of type "+this.type.name+": "+a+" ("+b+")")}.bind(this);switch(this.type){case a.TYPES.int32:case a.TYPES.sint32:case a.TYPES.sfixed32:return ("number"!=typeof c||c===c&&0!==c%1)&&d(typeof c,"not an integer"),c>4294967295?0|c:c;case a.TYPES.uint32:case a.TYPES.fixed32:return ("number"!=typeof c||c===c&&0!==c%1)&&d(typeof c,"not an integer"),0>c?c>>>0:c;case a.TYPES.int64:case a.TYPES.sint64:case a.TYPES.sfixed64:if(a.Long)try{return l(c,!1)}catch(e){d(typeof c,e.message);}else d(typeof c,"requires Long.js");case a.TYPES.uint64:case a.TYPES.fixed64:if(a.Long)try{return l(c,!0)}catch(e){d(typeof c,e.message);}else d(typeof c,"requires Long.js");case a.TYPES.bool:return "boolean"!=typeof c&&d(typeof c,"not a boolean"),c;case a.TYPES["float"]:case a.TYPES["double"]:return "number"!=typeof c&&d(typeof c,"not a number"),c;case a.TYPES.string:return "string"==typeof c||c&&c instanceof String||d(typeof c,"not a string"),""+c;case a.TYPES.bytes:return b.isByteBuffer(c)?c:b.wrap(c);case a.TYPES["enum"]:for(f=this.resolvedType.getChildren(a.Reflect.Enum.Value),h=0;h4294967295||0>c)&&d(typeof c,"not in range for uint32"),c;d(c,"not a valid enum value");case a.TYPES.group:case a.TYPES.message:if(c&&"object"==typeof c||d(typeof c,"object expected"),c instanceof this.resolvedType.clazz)return c;if(c instanceof a.Builder.Message){g={};for(h in c)c.hasOwnProperty(h)&&(g[h]=c[h]);c=g;}return new this.resolvedType.clazz(c)}throw Error("[INTERNAL] Illegal value for "+this.toString(!0)+": "+c+" (undefined type "+this.type+")")},j.calculateLength=function(b,c){if(null===c)return 0;var d;switch(this.type){case a.TYPES.int32:return 0>c?f.calculateVarint64(c):f.calculateVarint32(c);case a.TYPES.uint32:return f.calculateVarint32(c);case a.TYPES.sint32:return f.calculateVarint32(f.zigZagEncode32(c));case a.TYPES.fixed32:case a.TYPES.sfixed32:case a.TYPES["float"]:return 4;case a.TYPES.int64:case a.TYPES.uint64:return f.calculateVarint64(c);case a.TYPES.sint64:return f.calculateVarint64(f.zigZagEncode64(c));case a.TYPES.fixed64:case a.TYPES.sfixed64:return 8;case a.TYPES.bool:return 1;case a.TYPES["enum"]:return f.calculateVarint32(c);case a.TYPES["double"]:return 8;case a.TYPES.string:return d=f.calculateUTF8Bytes(c),f.calculateVarint32(d)+d;case a.TYPES.bytes:if(c.remaining()<0)throw Error("Illegal value for "+this.toString(!0)+": "+c.remaining()+" bytes remaining");return f.calculateVarint32(c.remaining())+c.remaining();case a.TYPES.message:return d=this.resolvedType.calculate(c),f.calculateVarint32(d)+d;case a.TYPES.group:return d=this.resolvedType.calculate(c),d+f.calculateVarint32(b<<3|a.WIRE_TYPES.ENDGROUP)}throw Error("[INTERNAL] Illegal value to encode in "+this.toString(!0)+": "+c+" (unknown type)")},j.encodeValue=function(b,c,d){var e,g;if(null===c)return d;switch(this.type){case a.TYPES.int32:0>c?d.writeVarint64(c):d.writeVarint32(c);break;case a.TYPES.uint32:d.writeVarint32(c);break;case a.TYPES.sint32:d.writeVarint32ZigZag(c);break;case a.TYPES.fixed32:d.writeUint32(c);break;case a.TYPES.sfixed32:d.writeInt32(c);break;case a.TYPES.int64:case a.TYPES.uint64:d.writeVarint64(c);break;case a.TYPES.sint64:d.writeVarint64ZigZag(c);break;case a.TYPES.fixed64:d.writeUint64(c);break;case a.TYPES.sfixed64:d.writeInt64(c);break;case a.TYPES.bool:"string"==typeof c?d.writeVarint32("false"===c.toLowerCase()?0:!!c):d.writeVarint32(c?1:0);break;case a.TYPES["enum"]:d.writeVarint32(c);break;case a.TYPES["float"]:d.writeFloat32(c);break;case a.TYPES["double"]:d.writeFloat64(c);break;case a.TYPES.string:d.writeVString(c);break;case a.TYPES.bytes:if(c.remaining()<0)throw Error("Illegal value for "+this.toString(!0)+": "+c.remaining()+" bytes remaining");e=c.offset,d.writeVarint32(c.remaining()),d.append(c),c.offset=e;break;case a.TYPES.message:g=(new f).LE(),this.resolvedType.encode(c,g),d.writeVarint32(g.offset),d.append(g.flip());break;case a.TYPES.group:this.resolvedType.encode(c,d),d.writeVarint32(b<<3|a.WIRE_TYPES.ENDGROUP);break;default:throw Error("[INTERNAL] Illegal value to encode in "+this.toString(!0)+": "+c+" (unknown type)")}return d},j.decode=function(b,c,d){if(c!=this.type.wireType)throw Error("Unexpected wire type for element");var e,f;switch(this.type){case a.TYPES.int32:return 0|b.readVarint32();case a.TYPES.uint32:return b.readVarint32()>>>0;case a.TYPES.sint32:return 0|b.readVarint32ZigZag();case a.TYPES.fixed32:return b.readUint32()>>>0;case a.TYPES.sfixed32:return 0|b.readInt32();case a.TYPES.int64:return b.readVarint64();case a.TYPES.uint64:return b.readVarint64().toUnsigned();case a.TYPES.sint64:return b.readVarint64ZigZag();case a.TYPES.fixed64:return b.readUint64();case a.TYPES.sfixed64:return b.readInt64();case a.TYPES.bool:return !!b.readVarint32();case a.TYPES["enum"]:return b.readVarint32();case a.TYPES["float"]:return b.readFloat();case a.TYPES["double"]:return b.readDouble();case a.TYPES.string:return b.readVString();case a.TYPES.bytes:if(f=b.readVarint32(),b.remaining()i;++i)this[e[i].name]=null;for(i=0,j=d.length;j>i;++i)k=d[i],this[k.name]=k.repeated?[]:k.map?new a.Map(k):null,!k.required&&"proto3"!==c.syntax||null===k.defaultValue||(this[k.name]=k.defaultValue);if(arguments.length>0)if(1!==arguments.length||null===b||"object"!=typeof b||!("function"!=typeof b.encode||b instanceof g)||Array.isArray(b)||b instanceof a.Map||f.isByteBuffer(b)||b instanceof ArrayBuffer||a.Long&&b instanceof a.Long)for(i=0,j=arguments.length;j>i;++i)"undefined"!=typeof(l=arguments[i])&&this.$set(d[i].name,l);else this.$set(b);},h=g.prototype=Object.create(a.Builder.Message.prototype);for(h.add=function(b,d,e){var f=c._fieldsByName[b];if(!e){if(!f)throw Error(this+"#"+b+" is undefined");if(!(f instanceof a.Reflect.Message.Field))throw Error(this+"#"+b+" is not a field: "+f.toString(!0));if(!f.repeated)throw Error(this+"#"+b+" is not a repeated field");d=f.verifyValue(d,!0);}return null===this[b]&&(this[b]=[]),this[b].push(d),this},h.$add=h.add,h.set=function(b,d,e){var f,g,h;if(b&&"object"==typeof b){e=d;for(f in b)b.hasOwnProperty(f)&&"undefined"!=typeof(d=b[f])&&this.$set(f,d,e);return this}if(g=c._fieldsByName[b],e)this[b]=d;else{if(!g)throw Error(this+"#"+b+" is not a field: undefined");if(!(g instanceof a.Reflect.Message.Field))throw Error(this+"#"+b+" is not a field: "+g.toString(!0));this[g.name]=d=g.verifyValue(d);}return g&&g.oneof&&(h=this[g.oneof.name],null!==d?(null!==h&&h!==g.name&&(this[h]=null),this[g.oneof.name]=g.name):h===b&&(this[g.oneof.name]=null)),this},h.$set=h.set,h.get=function(b,d){if(d)return this[b];var e=c._fieldsByName[b];if(!(e&&e instanceof a.Reflect.Message.Field))throw Error(this+"#"+b+" is not a field: undefined");if(!(e instanceof a.Reflect.Message.Field))throw Error(this+"#"+b+" is not a field: "+e.toString(!0));return this[e.name]},h.$get=h.get,i=0;ie;e++)if(h=this.children[e],h instanceof t||h instanceof m||h instanceof x){if(d.hasOwnProperty(h.name))throw Error("Illegal reflect child of "+this.toString(!0)+": "+h.toString(!0)+" cannot override static property '"+h.name+"'");d[h.name]=h.build();}else if(h instanceof m.Field)h.build(),this._fields.push(h),this._fieldsById[h.id]=h,this._fieldsByName[h.name]=h;else if(!(h instanceof m.OneOf||h instanceof w))throw Error("Illegal reflect child of "+this.toString(!0)+": "+this.children[e].toString(!0));return this.clazz=d},n.encode=function(a,b,c){var e,h,f,g,i,d=null;for(f=0,g=this._fields.length;g>f;++f)e=this._fields[f],h=a[e.name],e.required&&null===h?null===d&&(d=e):e.encode(c?h:e.verifyValue(h),b,a);if(null!==d)throw i=Error("Missing at least one required field for "+this.toString(!0)+": "+d),i.encoded=b,i;return b},n.calculate=function(a){for(var e,f,b=0,c=0,d=this._fields.length;d>c;++c){if(e=this._fields[c],f=a[e.name],e.required&&null===f)throw Error("Missing at least one required field for "+this.toString(!0)+": "+e);b+=e.calculate(f,a);}return b},n.decode=function(b,c,d){var g,h,i,j,e,f,k,l,m,n,p,q;for(c="number"==typeof c?c:-1,e=b.offset,f=new this.clazz;b.offset0;){if(g=b.readVarint32(),h=7&g,i=g>>>3,h===a.WIRE_TYPES.ENDGROUP){if(i!==d)throw Error("Illegal group end indicator for "+this.toString(!0)+": "+i+" ("+(d?d+" expected":"not a group")+")");break}if(j=this._fieldsById[i])j.repeated&&!j.options.packed?f[j.name].push(j.decode(h,b)):j.map?(l=j.decode(h,b),f[j.name].set(l[0],l[1])):(f[j.name]=j.decode(h,b),j.oneof&&(m=f[j.oneof.name],null!==m&&m!==j.name&&(f[m]=null),f[j.oneof.name]=j.name));else switch(h){case a.WIRE_TYPES.VARINT:b.readVarint32();break;case a.WIRE_TYPES.BITS32:b.offset+=4;break;case a.WIRE_TYPES.BITS64:b.offset+=8;break;case a.WIRE_TYPES.LDELIM:k=b.readVarint32(),b.offset+=k;break;case a.WIRE_TYPES.STARTGROUP:for(;o(i,b););break;default:throw Error("Illegal wire type for unknown field "+i+" in "+this.toString(!0)+"#decode: "+h)}}for(n=0,p=this._fields.length;p>n;++n)if(j=this._fields[n],null===f[j.name])if("proto3"===this.syntax)f[j.name]=j.defaultValue;else{if(j.required)throw q=Error("Missing at least one required field for "+this.toString(!0)+": "+j.name),q.decoded=f,q;a.populateDefaults&&null!==j.defaultValue&&(f[j.name]=j.defaultValue);}return f},c.Message=m,p=function(b,c,e,f,g,h,i,j,k,l){d.call(this,b,c,h),this.className="Message.Field",this.required="required"===e,this.repeated="repeated"===e,this.map="map"===e,this.keyType=f||null,this.type=g,this.resolvedType=null,this.id=i,this.options=j||{},this.defaultValue=null,this.oneof=k||null,this.syntax=l||"proto2",this.originalName=this.name,this.element=null,this.keyElement=null,!this.builder.options.convertFieldsToCamelCase||this instanceof m.ExtensionField||(this.name=a.Util.toCamelCase(this.name));},q=p.prototype=Object.create(d.prototype),q.build=function(){this.element=new i(this.type,this.resolvedType,!1,this.syntax),this.map&&(this.keyElement=new i(this.keyType,void 0,!0,this.syntax)),"proto3"!==this.syntax||this.repeated||this.map?"undefined"!=typeof this.options["default"]&&(this.defaultValue=this.verifyValue(this.options["default"])):this.defaultValue=i.defaultFieldValue(this.type);},q.verifyValue=function(b,c){var d,e,f;if(c=c||!1,d=function(a,b){throw Error("Illegal value for "+this.toString(!0)+" of type "+this.type.name+": "+a+" ("+b+")")}.bind(this),null===b)return this.required&&d(typeof b,"required"),"proto3"===this.syntax&&this.type!==a.TYPES.message&&d(typeof b,"proto3 field without field presence cannot be null"),null;if(this.repeated&&!c){for(Array.isArray(b)||(b=[b]),f=[],e=0;e0;case a.TYPES.bytes:return b.remaining()>0;case a.TYPES["enum"]:return 0!==b;case a.TYPES.message:return null!==b;default:return !0}},q.encode=function(b,c,d){var e,g,h,i,j;if(null===this.type||"object"!=typeof this.type)throw Error("[INTERNAL] Unresolved type in "+this.toString(!0)+": "+this.type);if(null===b||this.repeated&&0==b.length)return c;try{if(this.repeated)if(this.options.packed&&a.PACKABLE_WIRE_TYPES.indexOf(this.type.wireType)>=0){for(c.writeVarint32(this.id<<3|a.WIRE_TYPES.LDELIM),c.ensureCapacity(c.offset+=1),g=c.offset,e=0;e1&&(j=c.slice(g,c.offset),g+=i-1,c.offset=g,c.append(j)),c.writeVarint32(h,g-i);}else for(e=0;e=0){for(d+=f.calculateVarint32(this.id<<3|a.WIRE_TYPES.LDELIM),g=0,e=0;e=0&&!d){for(f=c.readVarint32(),f=c.offset+f,h=[];c.offset0;)if(l=k.readVarint32(),b=7&l,m=l>>>3,1===m)j=this.keyElement.decode(k,b,m);else{if(2!==m)throw Error("Unexpected tag in map field key/value submessage");e=this.element.decode(k,b,m);}return [j,e]}return this.element.decode(c,b,this.id)},c.Message.Field=p,r=function(a,b,c,d,e,f,g){p.call(this,a,b,c,null,d,e,f,g),this.extension;},r.prototype=Object.create(p.prototype),c.Message.ExtensionField=r,s=function(a,b,c){d.call(this,a,b,c),this.fields=[];},c.Message.OneOf=s,t=function(a,b,c,d,e){g.call(this,a,b,c,d,e),this.className="Enum",this.object=null;},t.getName=function(a,b){var e,d,c=Object.keys(a);for(d=0;de;++e)c[d[e]["name"]]=d[e]["id"];return Object.defineProperty&&Object.defineProperty(c,"$options",{value:this.buildOpt(),enumerable:!1}),this.object=c},c.Enum=t,v=function(a,b,c,e){d.call(this,a,b,c),this.className="Enum.Value",this.id=e;},v.prototype=Object.create(d.prototype),c.Enum.Value=v,w=function(a,b,c,e){d.call(this,a,b,c),this.field=e;},w.prototype=Object.create(d.prototype),c.Extension=w,x=function(a,b,c,d){g.call(this,a,b,c,d),this.className="Service",this.clazz=null;},y=x.prototype=Object.create(g.prototype),y.build=function(b){return this.clazz&&!b?this.clazz:this.clazz=function(a,b){var g,c=function(b){a.Builder.Service.call(this),this.rpcImpl=b||function(a,b,c){setTimeout(c.bind(this,Error("Not implemented, see: https://github.com/dcodeIO/ProtoBuf.js/wiki/Services")),0);};},d=c.prototype=Object.create(a.Builder.Service.prototype),e=b.getChildren(a.Reflect.Service.RPCMethod);for(g=0;g0;){if(b=e.pop(),!Array.isArray(b))throw Error("not a valid namespace: "+JSON.stringify(b));for(;b.length>0;){if(f=b.shift(),d.isMessage(f)){if(g=new c.Message(this,this.ptr,f.name,f.options,f.isGroup,f.syntax),h={},f.oneofs&&Object.keys(f.oneofs).forEach(function(a){g.addChild(h[a]=new c.Message.OneOf(this,g,a));},this),f.fields&&f.fields.forEach(function(a){if(null!==g.getChild(0|a.id))throw Error("duplicate or invalid field id in "+g.name+": "+a.id);if(a.options&&"object"!=typeof a.options)throw Error("illegal field options in "+g.name+"#"+a.name);var b=null;if("string"==typeof a.oneof&&!(b=h[a.oneof]))throw Error("illegal oneof in "+g.name+"#"+a.name+": "+a.oneof);a=new c.Message.Field(this,g,a.rule,a.keytype,a.type,a.name,a.id,a.options,b,f.syntax),b&&b.fields.push(a),g.addChild(a);},this),i=[],f.enums&&f.enums.forEach(function(a){i.push(a);}),f.messages&&f.messages.forEach(function(a){i.push(a);}),f.services&&f.services.forEach(function(a){i.push(a);}),f.extensions&&(g.extensions="number"==typeof f.extensions[0]?[f.extensions]:f.extensions),this.ptr.addChild(g),i.length>0){e.push(b),b=i,i=null,this.ptr=g,g=null;continue}i=null;}else if(d.isEnum(f))g=new c.Enum(this,this.ptr,f.name,f.options,f.syntax),f.values.forEach(function(a){g.addChild(new c.Enum.Value(this,g,a.name,a.id));},this),this.ptr.addChild(g);else if(d.isService(f))g=new c.Service(this,this.ptr,f.name,f.options),Object.keys(f.rpc).forEach(function(a){var b=f.rpc[a];g.addChild(new c.Service.RPCMethod(this,g,a,b.request,b.response,!!b.request_stream,!!b.response_stream,b.options));},this),this.ptr.addChild(g);else{if(!d.isExtend(f))throw Error("not a valid definition: "+JSON.stringify(f));if(g=this.ptr.resolve(f.ref,!0))f.fields.forEach(function(b){var d,e,f,h;if(null!==g.getChild(0|b.id))throw Error("duplicate extended field id in "+g.name+": "+b.id); if(g.extensions&&(d=!1,g.extensions.forEach(function(a){b.id>=a[0]&&b.id<=a[1]&&(d=!0);}),!d))throw Error("illegal extended field id in "+g.name+": "+b.id+" (not within valid ranges)");e=b.name,this.options.convertFieldsToCamelCase&&(e=a.Util.toCamelCase(e)),f=new c.Message.ExtensionField(this,g,b.rule,b.type,this.ptr.fqn()+"."+e,b.id,b.options),h=new c.Extension(this,this.ptr,b.name,f),f.extension=h,this.ptr.addChild(h),g.addChild(f);},this);else if(!/\.?google\.protobuf\./.test(f.ref))throw Error("extended message "+f.ref+" is not defined")}f=null,g=null;}b=null,this.ptr=this.ptr.parent;}return this.resolved=!1,this.result=null,this},e["import"]=function(b,c){var e,g,h,i,j,k,l,m,d="/";if("string"==typeof c){if(a.Util.IS_NODE,this.files[c]===!0)return this.reset();this.files[c]=!0;}else if("object"==typeof c){if(e=c.root,a.Util.IS_NODE,(e.indexOf("\\")>=0||c.file.indexOf("\\")>=0)&&(d="\\"),g=e+d+c.file,this.files[g]===!0)return this.reset();this.files[g]=!0;}if(b.imports&&b.imports.length>0){for(i=!1,"object"==typeof c?(this.importRoot=c.root,i=!0,h=this.importRoot,c=c.file,(h.indexOf("\\")>=0||c.indexOf("\\")>=0)&&(d="\\")):"string"==typeof c?this.importRoot?h=this.importRoot:c.indexOf("/")>=0?(h=c.replace(/\/[^\/]*$/,""),""===h&&(h="/")):c.indexOf("\\")>=0?(h=c.replace(/\\[^\\]*$/,""),d="\\"):h=".":h=null,j=0;j lastUnreadTime; if (isOtherSend && isCounted && isNotAdded && (hasChanged = true)) { storageConversation.unreadMessageCount = unreadMessageCount + 1; storageConversation.lastUnreadTime = sentTime; } else if (isOtherSend && isRecall && hasContent && (hasChanged = true)) { var isRecallMsgNotRead = lastUnreadTime >= content.sentTime; if (isRecallMsgNotRead && unreadMessageCount) { storageConversation.unreadMessageCount = unreadMessageCount - 1; } } if (isOtherSend && isMentiond && hasContent && content.mentionedInfo && (hasChanged = true)) { storageConversation.hasMentiond = true; storageConversation.mentiondInfo = content.mentionedInfo; } if (hasChanged) { self.set(message, storageConversation); } self._setCache(message); var isNeedNotifyUpdate = utils.isUndefined(isLastInAPull) ? true : isLastInAPull; if (isNeedNotifyUpdate) { self._update(); } }; _proto._setCache = function _setCache(message) { var self = this; var type = message.type, targetId = message.targetId, isPersited = message.isPersited; var key = common.getConversationKey(message); var cacheConversation = self.updatedConversations[key] || {}; cacheConversation = common.fixConversationData(cacheConversation); var cacheMsgSentTime = cacheConversation.latestMessage.sentTime || 0; var newMsgSentTime = message.sentTime; var isMsgNotAdded = cacheMsgSentTime <= newMsgSentTime; if (isPersited && isMsgNotAdded) { cacheConversation = { type: type, targetId: targetId, latestMessage: message }; self.updatedConversations[key] = cacheConversation; } }; _proto.set = function set(option, storageConversationOption) { var _setVals; var unreadMessageCount = storageConversationOption.unreadMessageCount, lastUnreadTime = storageConversationOption.lastUnreadTime, hasMentiond = storageConversationOption.hasMentiond, mentiondInfo = storageConversationOption.mentiondInfo, key = common.getConversationKey(option), storageConversation = this._storage.get(key) || {}, setVals = (_setVals = {}, _setVals[SUB_KEY.UNREAD_COUNT] = { val: unreadMessageCount }, _setVals[SUB_KEY.UNREAD_LAST_TIME] = { val: lastUnreadTime }, _setVals[SUB_KEY.HAS_MENTIOND] = { val: hasMentiond, checkEvent: function checkEvent(val) { return val; } }, _setVals[SUB_KEY.MENTIOND_INFO] = { val: mentiondInfo, checkEvent: utils.isObject }, _setVals); utils.forEach(setVals, function (_ref, key) { var val = _ref.val, checkEvent = _ref.checkEvent; checkEvent = checkEvent || function (val) { return !utils.isEmpty(val); }; if (utils.isUndefined(val)) { return; } if (checkEvent(val)) { storageConversation[key] = val; } else { delete storageConversation[key]; } }); this._storage.set(key, storageConversation); }; _proto.get = function get(option) { var key = common.getConversationKey(option); var storageConversation = this._storage.get(key) || {}; return { unreadMessageCount: storageConversation[SUB_KEY.UNREAD_COUNT] || 0, lastUnreadTime: storageConversation[SUB_KEY.UNREAD_LAST_TIME] || 0, hasMentiond: storageConversation[SUB_KEY.HAS_MENTIOND] || false, mentiondInfo: storageConversation[SUB_KEY.MENTIOND_INFO] }; }; _proto.remove = function remove(option) { var key = common.getConversationKey(option); this._storage.remove(key); }; _proto.getTotalUnreadCount = function getTotalUnreadCount() { var allVals = this._storage.getValues() || {}; var totalCount = 0; utils.forEach(allVals, function (val) { var count = val[SUB_KEY.UNREAD_COUNT] || 0; totalCount += count; }); return totalCount; }; _proto.read = function read(option) { var self = this; var key = common.getConversationKey(option); var localConversation = self.get(option) || {}; var localUnread = localConversation.unreadMessageCount; if (localUnread) { self.remove(option); var cacheConversation = self.updatedConversations[key]; if (cacheConversation) ; else { self.updatedConversations[key] = option; } self._update(); } }; return ConversationManager; }(); var PullQueueManager = function () { function PullQueueManager(option) { this.isLoading = false; this._queue = new utils.Queue(); this._option = void 0; option = option || {}; this._option = option; } var _proto = PullQueueManager.prototype; _proto._execEvent = function _execEvent() { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } var self = this; var _this$_option = this._option, event = _this$_option.event, thisArg = _this$_option.thisArg, onBefore = this._option.onBefore || function () { return args; }, onFinished = this._option.onFinished || utils.noop, onError = this._option.onError || utils.noop; onBefore.apply(void 0, args); self.isLoading = true; return event.apply(thisArg, args).then(function (result) { self.isLoading = false; onFinished.apply(void 0, [result].concat(args)); })["catch"](function (error) { self.isLoading = false; onError(error); }); }; _proto.pull = function pull() { for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } this._queue.add({ event: this._execEvent, args: args, thisArg: this }); }; return PullQueueManager; }(); var MessageTimeSyner$1 = common.MessageTimeSyner, ChatRoomMessageTimeSyner$1 = common.ChatRoomMessageTimeSyner; var EVENT_NAME$1 = { MESSAGE_RECEIVED: 'msg-received' }; var MessagePullManager = function () { function MessagePullManager(serverEngine, option) { var _serverEngine$watch; this._serverEngine = void 0; this._pullQueue = void 0; this._messageTimeSyner = void 0; this._chatRoomMessageTimeSyner = new ChatRoomMessageTimeSyner$1(); this._eventEmitter = new utils.EventEmitter(); this._pullMessageTimer = new utils.Timer({ type: TIMER_TYPE.INTERVAL, timeout: PULL_MSG_TIME }); this._sentMsgCacheInPulling = {}; this._handleDirectMessage = void 0; this._handleNotifyPull = void 0; this._handleJoinChatRoom = void 0; this._handleSendMessage = void 0; var self = this; var appkey = serverEngine.option.appkey, userId = serverEngine._selfUserId; var startSyncTime = option.startSyncTime; var pullQueue = new PullQueueManager({ event: this._pullEvent, thisArg: this, onFinished: function onFinished() {}, onError: function onError() {} }); self._handleDirectMessage = function (message) { !pullQueue.isLoading && self.notifyMessage({ message: message, hasMore: false }); }; self._handleNotifyPull = function (option) { pullQueue.pull(option); }; self._handleJoinChatRoom = function (_ref) { var id = _ref.id, count = _ref.count; if (utils.isEqual(count, CHATROOM_NOT_PULL_MSG_COUNT)) { self._chatRoomMessageTimeSyner.set(id, common.DelayTimer.getTime()); } else { var type = PULL_MSG_TYPE.CHATROOM, time = 0, chrmId = id; self._chatRoomMessageTimeSyner.set(id, time); pullQueue.pull({ type: type, time: time, chrmId: chrmId, count: count }); } }; self._handleSendMessage = function (message) { pullQueue.isLoading ? self._setSentMsgCacheInPulling(message) : self._setPullTime(message); }; serverEngine.watch((_serverEngine$watch = {}, _serverEngine$watch[SERVER_EVENT_NAME.DIRECT_MSG] = self._handleDirectMessage, _serverEngine$watch[SERVER_EVENT_NAME.NOTIFY_PULL] = self._handleNotifyPull, _serverEngine$watch[SERVER_EVENT_NAME.JOIN_CHATROOM] = self._handleJoinChatRoom, _serverEngine$watch[SERVER_EVENT_NAME.MESSAGE_SEND] = self._handleSendMessage, _serverEngine$watch)); self._serverEngine = serverEngine; self._pullQueue = pullQueue; self._messageTimeSyner = new MessageTimeSyner$1({ appkey: appkey, userId: userId, startSyncTime: startSyncTime }); self._pullMessageTimer.start(pullQueue.pull, { thisArg: pullQueue }); pullQueue.pull(); } var _proto = MessagePullManager.prototype; _proto.watchMessage = function watchMessage(event) { this._eventEmitter.on(EVENT_NAME$1.MESSAGE_RECEIVED, event); }; _proto.notifyMessage = function notifyMessage(messageArgs) { var message = messageArgs.message; this._setPullTime(message); this._eventEmitter.emit(EVENT_NAME$1.MESSAGE_RECEIVED, messageArgs); }; _proto.close = function close() { var _this$_serverEngine$u; this._pullMessageTimer.stop(); this._sentMsgCacheInPulling = {}; this._serverEngine.unwatch((_this$_serverEngine$u = {}, _this$_serverEngine$u[SERVER_EVENT_NAME.DIRECT_MSG] = this._handleDirectMessage, _this$_serverEngine$u[SERVER_EVENT_NAME.NOTIFY_PULL] = this._handleNotifyPull, _this$_serverEngine$u[SERVER_EVENT_NAME.JOIN_CHATROOM] = this._handleJoinChatRoom, _this$_serverEngine$u[SERVER_EVENT_NAME.MESSAGE_SEND] = this._handleSendMessage, _this$_serverEngine$u)); }; _proto._pullEvent = function _pullEvent(option) { option = option || {}; var self = this, _serverEngine = self._serverEngine, _messageTimeSyner = self._messageTimeSyner, _chatRoomMessageTimeSyner = self._chatRoomMessageTimeSyner, _option = option, type = _option.type, chrmId = _option.chrmId, serverPullTime = _option.time, count = _option.count, isPullChrmMsg = utils.isEqual(type, PULL_MSG_TYPE.CHATROOM), msgSyncTime = _messageTimeSyner.get(), currentReceiveTime = isPullChrmMsg ? _chatRoomMessageTimeSyner.get(chrmId) : msgSyncTime.inboxTime, syncTime = utils.copy(msgSyncTime); if (serverPullTime && serverPullTime < currentReceiveTime) { return utils.Defer.resolve(); } var onMessage = function onMessage(_ref2) { var message = _ref2.message, finished = _ref2.finished, isLastInAPull = _ref2.isLastInAPull; self._displatchMessages({ message: message, finished: finished, isPullChrmMsg: isPullChrmMsg, isLastInAPull: isLastInAPull, normalSyncTime: syncTime, chatRoomReceiveTime: currentReceiveTime }); }; if (isPullChrmMsg) { return _serverEngine.pullChrmMessageList(chrmId, currentReceiveTime, count, { onMessage: onMessage }); } else { return _serverEngine.pullMessageList(syncTime, { onMessage: onMessage }); } }; _proto._displatchMessages = function _displatchMessages(option) { var self = this, message = option.message, finished = option.finished, isPullChrmMsg = option.isPullChrmMsg, isLastInAPull = option.isLastInAPull, _ref3 = option.normalSyncTime || {}, inboxTime = _ref3.inboxTime, sendboxTime = _ref3.sendboxTime, sentTime = message.sentTime, messageDirection = message.messageDirection, messageUId = message.messageUId, isSelfSend = messageDirection === MESSAGE_DIRECTION.SEND, pullTime = isSelfSend ? sendboxTime : inboxTime; if (sentTime <= pullTime && !isPullChrmMsg) { return; } if (self._sentMsgCacheInPulling[messageUId]) { return; } self.notifyMessage({ message: message, hasMore: !finished, isLastInAPull: isLastInAPull }); }; _proto._setPullTime = function _setPullTime(message) { var isChatRoom = message.type === CONVERSATION_TYPE.CHATROOM; isChatRoom ? this._chatRoomMessageTimeSyner.setByMessage(message) : this._messageTimeSyner.setByMessage(message); }; _proto._setSentMsgCacheInPulling = function _setSentMsgCacheInPulling(message) { var messageUId = message.messageUId; if (utils.isUndefined(messageUId)) { return; } this._sentMsgCacheInPulling[messageUId] = message; }; _proto._consumeSentMsgCacheInPulling = function _consumeSentMsgCacheInPulling() { var self = this; var _sentMsgCacheInPulling = self._sentMsgCacheInPulling; utils.forEach(_sentMsgCacheInPulling, function (message) { self._setPullTime(message); }); self._sentMsgCacheInPulling = {}; }; return MessagePullManager; }(); var ChatRoomKVStore = function () { function ChatRoomKVStore(chrmId, currentUserId) { this._chatRoomId = void 0; this._kvCaches = {}; this._currentUserId = void 0; this._chatRoomId = chrmId; this._currentUserId = currentUserId; } var _proto = ChatRoomKVStore.prototype; _proto.setEntries = function setEntries(data) { data = data || {}; var self = this; var _data = data, kvList = _data.kvEntries, isFullUpdate = _data.isFullUpdate; kvList = kvList || []; isFullUpdate = isFullUpdate || false; isFullUpdate && self.clear(); utils.forEach(kvList, function (kv) { self.setEntry(kv, { isFullUpdate: isFullUpdate }); }); }; _proto.setEntry = function setEntry(kv, option) { option = option || {}; var _option = option, isFullUpdate = _option.isFullUpdate, key = kv.key, type = kv.type, isOverwrite = kv.isOverwrite, userId = kv.userId, latestUserId = this.getSetUserId(key), isDeleteOpt = utils.isEqual(type, CHATROOM_ENTRY_TYPE.DELETE), isSameAtLastSetUser = utils.isEqual(latestUserId, userId), isKeyNotExist = !this.isExisted(key); var event = isDeleteOpt ? this.remove : this.add; if (isFullUpdate) { event.call(this, kv); } else if (isOverwrite || isSameAtLastSetUser || isKeyNotExist) { event.call(this, kv); } }; _proto.add = function add(kv) { var key = kv.key; kv.isDeleted = false; this._kvCaches[key] = kv; }; _proto.remove = function remove(kv) { var key = kv.key; var cacheKV = this.get(key) || {}; cacheKV.isDeleted = true; this._kvCaches[key] = cacheKV; }; _proto.clear = function clear() { this._kvCaches = {}; }; _proto.get = function get(key) { return this._kvCaches[key]; }; _proto.getSetUserId = function getSetUserId(key) { var cache = this.get(key) || {}; return cache.userId; }; _proto.getValue = function getValue(key) { var kv = this._kvCaches[key] || {}; var isDeleted = kv.isDeleted; return isDeleted ? null : kv.value; }; _proto.getAll = function getAll() { var kvEntries = {}; utils.forEach(this._kvCaches, function (kv, key) { if (!kv.isDeleted) { kvEntries[key] = kv.value; } }); return kvEntries; }; _proto.getUpdatedTime = function getUpdatedTime() { var maxTime = 0; utils.forEach(this._kvCaches, function (entry) { var timestamp = entry.timestamp || 0; if (maxTime < timestamp) { maxTime = timestamp; } }); return maxTime; }; _proto.isExisted = function isExisted(key) { var cache = this.get(key) || {}; var value = cache.value, isDeletedOnLatestOperate = cache.isDeleted; return value && !isDeletedOnLatestOperate; }; return ChatRoomKVStore; }(); var storeCaches = {}; var get = function get(chrmId) { return storeCaches[chrmId]; }; var set$1 = function set(chrmId, data, currentUserId) { var kvStore = get(chrmId); if (utils.isEmpty(kvStore)) { kvStore = new ChatRoomKVStore(chrmId, currentUserId); } kvStore.setEntries(data); storeCaches[chrmId] = kvStore; }; var getValue = function getValue(chrmId, key) { var kvStore = get(chrmId); var value = kvStore ? kvStore.getValue(key) : null; return value; }; var getAll = function getAll(chrmId) { var kvStore = get(chrmId); var kvs = {}; if (kvStore) { kvs = kvStore.getAll(); } return kvs; }; var clear = function clear(chrmId) { var kvStore = get(chrmId) || {}; kvStore.clear && kvStore.clear(); }; var ChatRoomKVStore$1 = { get: get, set: set$1, getValue: getValue, getAll: getAll, clear: clear }; var PullTimeCache = { _caches: {}, set: function set(chrmId, time) { PullTimeCache._caches[chrmId] = time; }, get: function get(chrmId) { return PullTimeCache._caches[chrmId] || 0; }, clear: function clear(chrmId) { PullTimeCache._caches[chrmId] = 0; } }; var ChatRoomKVManager = function () { function ChatRoomKVManager(serverEngine) { var _serverEngine$watch; this._serverEngine = void 0; this._pullQueue = void 0; this._handleChrmKVSet = void 0; this._handleChrmKVChanged = void 0; this._handleBeforeJoinChrm = void 0; var self = this; var userId = serverEngine._selfUserId; var pullQueue = new PullQueueManager({ event: this._pullEvent, thisArg: this, onFinished: function onFinished(data, option) { if (!data || !option.chrmId) { return; } var chrmId = option.chrmId; if (data.isFullUpdate) { self._reset(chrmId); } Logger.info(TAG.L_PULL_CHRM_KV_R, { data: data, option: option }); ChatRoomKVStore$1.set(chrmId, data, userId); PullTimeCache.set(chrmId, data.syncTime || 0); } }); self._handleChrmKVSet = function (_ref) { var id = _ref.id, data = _ref.data; ChatRoomKVStore$1.set(id, data, userId); }; self._handleChrmKVChanged = function (data) { self.pull(data); }; self._handleBeforeJoinChrm = function (_ref2) { var id = _ref2.id; self._reset(id); }; serverEngine.watch((_serverEngine$watch = {}, _serverEngine$watch[SERVER_EVENT_NAME.CHRM_KV_SET] = self._handleChrmKVSet, _serverEngine$watch[SERVER_EVENT_NAME.CHRM_KV_CHANGED] = self._handleChrmKVChanged, _serverEngine$watch[SERVER_EVENT_NAME.BEFORE_JOIN_CHATROOM] = self._handleBeforeJoinChrm, _serverEngine$watch)); this._serverEngine = serverEngine; this._pullQueue = pullQueue; } var _proto = ChatRoomKVManager.prototype; _proto._reset = function _reset(chrmId) { ChatRoomKVStore$1.clear(chrmId); PullTimeCache.clear(chrmId); }; _proto._pullEvent = function _pullEvent(data) { var time = data.time, chrmId = data.chrmId, currentTime = PullTimeCache.get(chrmId), isUpdated = currentTime > time; Logger.info(TAG.L_PULL_CHRM_KV_T, { currentTime: currentTime, serverTime: time, isUpdated: isUpdated, data: data }); if (isUpdated) { Logger.info(TAG.L_PULL_CHRM_KV_R, { info: 'kv is updated. not pull again' }); return utils.Defer.resolve(); } return this._serverEngine.pullChatRoomKV({ id: chrmId }, currentTime); }; _proto.pull = function pull(data) { this._pullQueue.pull(data); }; _proto.getValue = function getValue(chrmId, key) { return ChatRoomKVStore$1.getValue(chrmId, key); }; _proto.getAll = function getAll(chrmId) { return ChatRoomKVStore$1.getAll(chrmId); }; _proto.close = function close() { var _self$_serverEngine$u; var self = this; self._serverEngine.unwatch((_self$_serverEngine$u = {}, _self$_serverEngine$u[SERVER_EVENT_NAME.CHRM_KV_SET] = self._handleChrmKVSet, _self$_serverEngine$u[SERVER_EVENT_NAME.CHRM_KV_CHANGED] = self._handleChrmKVChanged, _self$_serverEngine$u[SERVER_EVENT_NAME.BEFORE_JOIN_CHATROOM] = self._handleBeforeJoinChrm, _self$_serverEngine$u)); }; return ChatRoomKVManager; }(); var WebIMEngine = function () { function WebIMEngine(option) { this._option = void 0; this._user = void 0; this._naviManager = void 0; this._cmpManager = new CMPManager(); this._conversationManager = void 0; this._messageManager = void 0; this._chatRoomKVManager = void 0; this._serverEngine = void 0; this._imEventEmitter = new utils.EventEmitter(); this._connectionStatus = CONNECTION_STATUS.DISCONNECTED; this._connectedDomain = void 0; this._networkDetecter = void 0; var self = this; var detect = option.detect; var serverEngine = new ServerEngine(option); serverEngine.watch({ status: function status(_status) { self._handleConnectionStatus(_status); } }); this._serverEngine = serverEngine; this._option = option; this._networkDetecter = new utils.NetworkDetecter(detect); utils.forEach(ServerEngine.prototype, function (event, eventName) { var server = serverEngine, web = self; var selfEvent = web[eventName], serverEvent = server[eventName]; if (!selfEvent && serverEvent && utils.isFunction(serverEvent)) { web[eventName] = function () { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return serverEvent.call.apply(serverEvent, [server].concat(args)); }; } }); } var _proto = WebIMEngine.prototype; _proto._notifyMessage = function _notifyMessage(event) { var self = this; var message = event.message, hasMore = event.hasMore, isLastInAPull = event.isLastInAPull; var _serverEngine = self._serverEngine; var connectedTime = _serverEngine.getConnectedTime(); if (common.isLogCommandMsg(message)) { var content = message.content; Logger.uploadFull(0, content, connectedTime); return; } this._conversationManager.addMessage(message, { hasMore: hasMore, isLastInAPull: isLastInAPull }); this._imEventEmitter.emit(IM_EVENT.MESSAGE, event); }; _proto._handleConnectionStatus = function _handleConnectionStatus(status) { var _cmpManager = this._cmpManager, _naviManager = this._naviManager, _connectedDomain = this._connectedDomain; var isNeedUpdateCMPList = utils.isInclude(TRANSPORTER_STATUS_NEED_UPDATE_CMP, status); var isNeedReconnect = utils.isInclude(TRANSPORTER_STATUS_NEED_RECONNECT, status); if (isNeedUpdateCMPList) { _cmpManager.addInvalid(_connectedDomain); if (_cmpManager.isAllInvalid()) { _naviManager.clear(); _cmpManager.clearInvalid(); } } if (isNeedReconnect) { this.disconnect(); this.reconnect(); } var connectionStatus = TRANSPORTER_STATUS_TO_CONNECTION_STATUS[status] || status; this._connectionStatus = connectionStatus; this._imEventEmitter.emit(IM_EVENT.STATUS, { status: connectionStatus }); }; _proto._handleConnectError = function _handleConnectError(errorInfo) { var _user = this._user; var code = errorInfo.code || errorInfo.status; this.disconnect(); if (code === ERROR_INFO.CONN_REDIRECTED.code) { this._naviManager.clear(); return this.connect(_user); } this._connectionStatus = CONNECTION_STATUS.DISCONNECTED; return utils.Defer.reject(errorInfo); }; _proto._afterConnect = function _afterConnect(connectUser, syncTime) { var self = this; var _serverEngine = self._serverEngine, appkey = self._option.appkey, _imEventEmitter = self._imEventEmitter; var id = connectUser.id; Logger.setOption({ userId: id }); self._user.id = id; self._conversationManager = new ConversationManager({ appkey: appkey, userId: id, onChanged: function onChanged(updatedConversationList) { _imEventEmitter.emit(IM_EVENT.CONVERSATION, { updatedConversationList: updatedConversationList }); } }); self._messageManager = new MessagePullManager(_serverEngine, { startSyncTime: syncTime }); self._messageManager.watchMessage(function (event) { self._notifyMessage(event); }); self._chatRoomKVManager = new ChatRoomKVManager(_serverEngine); }; _proto.watch = function watch(watchers) { var _events; var statusWatcher = watchers.status, messageWatcher = watchers.message, conversationWatcher = watchers.conversation; var self = this; var events = (_events = {}, _events[IM_EVENT.STATUS] = statusWatcher, _events[IM_EVENT.MESSAGE] = messageWatcher, _events[IM_EVENT.CONVERSATION] = conversationWatcher, _events); utils.forEach(events, function (event, eventName) { utils.isFunction(event) && self._imEventEmitter.on(eventName, event); }); }; _proto.unwatch = function unwatch(watchers) { var _imEventEmitter = this._imEventEmitter; var offEventNameObj = { status: 'IM_EVENT.STATUS', message: 'IM_EVENT.MESSAGE', conversation: 'IM_EVENT.CONVERSATION' }; if (watchers) { utils.forEach(watchers, function (val, key) { if (offEventNameObj[key]) { _imEventEmitter.off(key, val); } }); } else { _imEventEmitter.clear(); } }; _proto.getConnectionStatus = function getConnectionStatus() { return this._connectionStatus; }; _proto.getConnectionUserId = function getConnectionUserId() { var user = this._user || {}; return user.id; }; _proto.getAppInfo = function getAppInfo() { var _option = this._option, _naviManager = this._naviManager; return utils.extend({ navi: _naviManager.getLocalConfig() }, _option); }; _proto.connect = function connect(user) { Logger.startRealtimeUpload(); var self = this; var _option = self._option, _serverEngine = self._serverEngine, _cmpManager = self._cmpManager; var naviOpt = common.getNavReqOption(_option, user); var naviManager = new NaviManager(naviOpt); var getServerConfig = _option.isOldServer ? _serverEngine.getOldServerConfig : _serverEngine.getServerConfig; self._handleConnectionStatus(CONNECTION_STATUS.CONNECTING); self._user = utils.copy(user); self._naviManager = naviManager; var connectUser; return naviManager.get().then(function (configForNavi) { var cmpDomainList = common.getCMPDomainList(configForNavi, _option); Logger.setServerOption(configForNavi); _cmpManager.setDomainList(cmpDomainList); return _cmpManager.getFaster(); }).then(function (_ref) { var domain = _ref.domain; self._connectedDomain = domain; return _serverEngine.connect(user, { domain: domain }); }).then(function (user) { connectUser = user; return getServerConfig.call(_serverEngine, user.id); }).then(function (serverConfig) { self._afterConnect(connectUser, serverConfig); return connectUser; })["catch"](function (error) { return self._handleConnectError(error); }); }; _proto.reconnect = function reconnect() { var self = this; var _user = self._user; if (utils.isUndefined(_user)) { return utils.Defer.reject(ERROR_INFO.NOT_CONNECTED); } return self._networkDetecter.start().then(function () { return self.connect(_user); }); }; _proto.disconnect = function disconnect(isNotify) { isNotify && this._handleConnectionStatus(CONNECTION_STATUS.DISCONNECTED); this._networkDetecter && this._networkDetecter.stop(); this._messageManager && this._messageManager.close(); this._chatRoomKVManager && this._chatRoomKVManager.close(); return this._serverEngine.disconnect(); }; _proto.changeUser = function changeUser(user) { this.disconnect(true); return this.connect(user); }; _proto.sendMessage = function sendMessage(conversation, option) { var self = this; return self._serverEngine.sendMessage(conversation, option).then(function (message) { self._conversationManager.addMessage(message); return message; }); }; _proto.recallMessage = function recallMessage(conversation, message, option) { var self = this; return self._serverEngine.recallMessage(conversation, message, option).then(function (message) { self._conversationManager.addMessage(message); return message; }); }; _proto.getConversationList = function getConversationList(option) { var isOldServer = this._option.isOldServer, _serverEngine = this._serverEngine, _conversationManager = this._conversationManager; var func = isOldServer ? _serverEngine.getOldConversationList : _serverEngine.getConversationList; return func.call(_serverEngine, option, { afterDecode: function afterDecode(conversation) { var localConversation = _conversationManager.get(conversation); conversation.unreadMessageCount = localConversation.unreadMessageCount || 0; conversation.hasMentiond = localConversation.hasMentiond || false; conversation.mentiondInfo = localConversation.mentiondInfo; return conversation; } }); }; _proto.getLocalConversation = function getLocalConversation(conversation) { var local = this._conversationManager.get(conversation); return { unreadMessageCount: local.unreadMessageCount || 0, hasMentiond: local.hasMentiond || false, mentiondInfo: local.mentiondInfo }; }; _proto.removeConversation = function removeConversation(conversation) { var isOldServer = this._option.isOldServer, _serverEngine = this._serverEngine; var func = isOldServer ? _serverEngine.removeOldConversation : _serverEngine.removeConversation; return func.call(_serverEngine, conversation); }; _proto.getTotalUnreadCount = function getTotalUnreadCount() { var isOldServer = this._option.isOldServer, _serverEngine = this._serverEngine; if (isOldServer) { var totalCount = this._conversationManager.getTotalUnreadCount(); return utils.Defer.resolve(totalCount); } else { return _serverEngine.getTotalUnreadCount(); } }; _proto.clearUnreadCount = function clearUnreadCount(conversation, option) { var isOldServer = this._option.isOldServer, _serverEngine = this._serverEngine; if (isOldServer) { this._conversationManager.read(conversation); return utils.Defer.resolve(); } else { return _serverEngine.clearUnreadCount(conversation, option); } }; _proto.joinChatRoom = function joinChatRoom(chrm, option) { var self = this; var _serverEngine = self._serverEngine, _naviManager = self._naviManager, _chatRoomKVManager = self._chatRoomKVManager; return _serverEngine.joinChatRoom(chrm, option).then(function () { return _naviManager.get(); }).then(function (configForNavi) { var isOpenKVStorageService = configForNavi.kvStorage; var initialTime = 0; return isOpenKVStorageService ? _chatRoomKVManager.pull({ time: initialTime, chrmId: chrm.id }) : utils.Defer.resolve(); }); }; _proto.setChatRoomKV = function setChatRoomKV(chrm, entry) { var self = this; utils.extend(entry, { type: CHATROOM_ENTRY_TYPE.UPDATE, userId: self._user.id }); entry.type = CHATROOM_ENTRY_TYPE.UPDATE; return self._serverEngine.modifyChatRoomKV(chrm, entry); }; _proto.forceSetChatRoomKV = function forceSetChatRoomKV(chrm, entry) { entry.isOverwrite = true; return this.setChatRoomKV(chrm, entry); }; _proto.removeChatRoomKV = function removeChatRoomKV(chrm, entry) { var self = this; utils.extend(entry, { type: CHATROOM_ENTRY_TYPE.DELETE, userId: self._user.id }); return self._serverEngine.modifyChatRoomKV(chrm, entry); }; _proto.forceRemoveChatRoomKV = function forceRemoveChatRoomKV(chrm, entry) { entry.isOverwrite = true; return this.removeChatRoomKV(chrm, entry); }; _proto.getChatRoomKV = function getChatRoomKV(chrm, key) { var value = this._chatRoomKVManager.getValue(chrm.id, key); if (utils.isEmpty(value)) { return utils.Defer.reject(ERROR_INFO.CHATROOM_KEY_NOT_EXIST); } else { return utils.Defer.resolve(value); } }; _proto.getAllChatRoomKV = function getAllChatRoomKV(chrm) { var kvs = this._chatRoomKVManager.getAll(chrm.id); return utils.Defer.resolve(kvs); }; return WebIMEngine; }(); var Engine = (function (imArg) { return new WebIMEngine(imArg); }); var execEngineByEvent = function execEngineByEvent(params, engine) { var eventName = params.event, args = params.args; args = args || []; var engineEvent = engine[eventName] || function () { return utils.Defer.reject(ERROR_INFO.SDK_INTERNAL_ERROR); }; return engineEvent.apply(engine, args); }; var EngineDispatcher = function () { function EngineDispatcher(option) { this._engine = void 0; this._engine = new Engine(option); } var _proto = EngineDispatcher.prototype; _proto._isEventNeedConnect = function _isEventNeedConnect(eventName) { var engine = this._engine, connectionStatus = engine.getConnectionStatus(), isNotConnected = connectionStatus !== CONNECTION_STATUS.CONNECTED, isEventNeedConnected = utils.isInclude(ENGINE_EVENT_NEED_CONNECTED, eventName); return isNotConnected && isEventNeedConnected; }; _proto._isEventNeedDisconnect = function _isEventNeedDisconnect(eventName) { var engine = this._engine, connectionStatus = engine.getConnectionStatus(), isConnecting = common.isConnected(connectionStatus) || common.isConnecting(connectionStatus), isEventNeedDisconnected = utils.isInclude(ENGINE_EVENT_NEED_DISCONNECTED, eventName); return isConnecting && isEventNeedDisconnected; }; _proto._exec = function _exec(params) { var event = params.event; var engine = this._engine; if (this._isEventNeedConnect(event)) { return utils.Defer.reject(ERROR_INFO.NOT_CONNECTED); } if (this._isEventNeedDisconnect(event)) { return utils.Defer.reject(ERROR_INFO.RC_CONNECTION_EXIST); } var execResult = execEngineByEvent(params, engine); return utils.isPromise(execResult) ? execResult["catch"](function (error) { var errorCode = error.status || error.code || error; var msg = utils.isObject(error) ? error.msg : null; var errorInfo = ERROR_CODE_TO_INFO[errorCode] || { code: errorCode }; if (msg) { errorInfo.msg = msg; } var isValidErrorCode = utils.isNumberData(errorCode); if (!isValidErrorCode) { if (utils.isStackError(error)) { error = error.stack.toString(); } Logger.fatal(TAG.L_CRASH_F, { content: { desc: 'SDK Error', error: error } }); errorInfo = utils.extendInShallow(ERROR_INFO.SDK_INTERNAL_ERROR, { error: error }); } return utils.Defer.reject(errorInfo); }) : execResult; }; _proto.exec = function exec(params) { var event = params.event; var LOG_TAG = APP_ENGINE_EVENT_LOG_TAG[event], isNeedLog = !utils.isEmpty(LOG_TAG), _ref = LOG_TAG || {}, reqLogTag = _ref.req, respLogTag = _ref.resp; isNeedLog && Logger.info(reqLogTag, params); var execResult = this._exec(params); if (utils.isPromise(execResult)) { return execResult.then(function (result) { isNeedLog && Logger.info(respLogTag, result); return result; })["catch"](function (error) { isNeedLog && Logger.error(respLogTag, error); return utils.Defer.reject(error); }); } else { isNeedLog && Logger.info(respLogTag, execResult); return execResult; } }; return EngineDispatcher; }(); var Type = function Type(name, validator, options) { options = options || {}; var self = this; self.validate = validator; self.name = name; self.errorInfo = options.errorInfo; self.canBeNull = function () { self.validate = function (data) { return utils.isUndefined(data) || utils.isNull(data) || validator(data); }; return self; }; }; Type.isType = function (type) { return type instanceof Type; }; Type.String = new Type('String', utils.isString); Type.Number = new Type('Number', utils.isNumber); Type.Boolean = new Type('Boolean', utils.isBoolean); Type.Function = new Type('Function', utils.isFunction); Type.Object = new Type('Object', utils.isObject); Type.Array = new Type('Array', utils.isArray); var conversationType = common.getConversationTypeList().join('、'); Type.ConversationType = new Type(conversationType, common.isValidConversationType); Type.ChatRoomEntryKey = new Type('ChatRoomEntryKey', common.isValidChatRoomKey, { errorInfo: 'ChatRoom Key length must be 1 - 128, Only letters、numbers、+、=、-、_ are supported' }); Type.ChatRoomEntryValue = new Type('ChatRoomEntryValue', common.isValidChatRoomValue, { errorInfo: 'ChatRoom Value length must be 1 - 4096' }); var Struct = function () { function Struct(structure, funcName, paths) { if (paths === void 0) { paths = []; } if (!(this instanceof Struct)) { return new Struct(structure, funcName, paths); } var self = this; self.structure = structure; self.paths = paths; self.funcName = funcName; if (Type.isType(structure)) { self.validate = self._validateType; } else if (utils.isArray(structure)) { self.validate = self._validateArray; } else if (utils.isObject(structure)) { self.validate = self._validateObject; } else { self.validate = self._validateOther; } } var _proto = Struct.prototype; _proto._validateType = function _validateType(data) { var structure = this.structure; var isValid = structure.validate(data); return isValid ? this._getSuccess() : this._getError(data); }; _proto._validateArray = function _validateArray(data) { var structure = this.structure; if (utils.isEmpty(structure)) { return this._getSuccess(); } if (!utils.isArray(data)) { return this._getError(data); } var typer = structure[0]; for (var filed in data) { var val = data[filed]; var result = this._validateField(typer, filed, val); if (result.isError) { return result; } } return this._getSuccess(); }; _proto._validateObject = function _validateObject(data) { var structure = this.structure, paths = this.paths; data = data || {}; if (utils.isEmpty(structure)) { return this._getSuccess(); } if (!utils.isObject(data)) { return this._getError(data); } var checkedField = []; for (var filed in data) { var typer = structure[filed], val = data[filed]; var result = this._validateField(typer, filed, val); if (result.isError) { return result; } checkedField.push(filed); } for (var checkField in structure) { var _typer = structure[checkField]; var unCheckData = data[checkField]; if (!utils.isInclude(checkedField, checkField) && !_typer.validate(unCheckData)) { var errPaths = utils.copy(paths); errPaths.push(checkField); return this._getError(unCheckData, { paths: errPaths, expect: _typer.name }); } } return this._getSuccess(); }; _proto._validateOther = function _validateOther(data) { var self = this; var structure = self.structure; if (utils.isEqual(structure, data) || utils.isEmpty(structure)) { return self._getSuccess(); } else { return self._getError(data, { current: data, expect: structure }); } }; _proto._validateField = function _validateField(typer, filed, value) { var paths = this.paths, funcName = this.funcName; var newPaths = utils.copy(paths); newPaths.push(filed); return new Struct(typer, funcName, newPaths).validate(value); }; _proto._getError = function _getError(data, options) { if (options === void 0) { options = []; } var structure = this.structure, paths = this.paths, funcName = this.funcName; options = utils.extend({ current: data, expect: structure.name || utils.getTypeName(structure), paths: paths }, options); paths = options.paths; var _options = options, current = _options.current, expect = _options.expect; var param = utils.isEmpty(paths) ? 'param' : paths.join('.'); var currentType = utils.getTypeName(current); current = utils.toJSON(current) || current; current = current + "(" + currentType + ")"; var msg = utils.tplEngine(ERROR_INFO.PARAMETER_ERROR.msg, { param: param, expect: expect, current: current }); var info = { code: ERROR_INFO.PARAMETER_ERROR.code, funcName: funcName, msg: msg }; var jsonInfo = utils.toJSON(info); if (utils.isEmpty(funcName)) delete info[funcName]; if (structure.errorInfo) { info = structure.errorInfo; } return { isError: true, info: info, jsonInfo: jsonInfo }; }; _proto._getSuccess = function _getSuccess() { return { isError: false }; }; return Struct; }(); var validate = (function (struct, params, eventName) { return Struct(struct, eventName).validate(params); }); var _MESSAGE_TYPE_VALIDAT; var MESSAGE_TYPE_VALIDATE = (_MESSAGE_TYPE_VALIDAT = {}, _MESSAGE_TYPE_VALIDAT[MESSAGE_TYPE.TEXT] = { content: Type.String }, _MESSAGE_TYPE_VALIDAT[MESSAGE_TYPE.VOICE] = { content: Type.String, duration: Type.Number }, _MESSAGE_TYPE_VALIDAT[MESSAGE_TYPE.HQ_VOICE] = { remoteUrl: Type.String, duration: Type.Number }, _MESSAGE_TYPE_VALIDAT[MESSAGE_TYPE.IMAGE] = { content: Type.String, imageUri: Type.String }, _MESSAGE_TYPE_VALIDAT[MESSAGE_TYPE.GIF] = { gifDataSize: Type.Number, width: Type.Number, height: Type.Number, remoteUrl: Type.String }, _MESSAGE_TYPE_VALIDAT[MESSAGE_TYPE.RICH_CONTENT] = { title: Type.String, content: Type.String, imageUri: Type.String, url: Type.String }, _MESSAGE_TYPE_VALIDAT[MESSAGE_TYPE.LOCATION] = { content: Type.String, latitude: Type.Number, longitude: Type.Number, poi: Type.String }, _MESSAGE_TYPE_VALIDAT[MESSAGE_TYPE.FILE] = { name: Type.String, size: Type.Number, type: Type.String, fileUrl: Type.String }, _MESSAGE_TYPE_VALIDAT[MESSAGE_TYPE.SIGHT] = { sightUrl: Type.String, content: Type.String, duration: Type.Number, size: Type.Number, name: Type.String }, _MESSAGE_TYPE_VALIDAT[MESSAGE_TYPE.COMBINE] = { remoteUrl: Type.String, conversationType: Type.Number, nameList: Type.Array, summaryList: Type.Array }, _MESSAGE_TYPE_VALIDAT); var validateMsgContent = (function (objectName, option, eventName) { var validateByObjectName = MESSAGE_TYPE_VALIDATE[objectName]; if (validateByObjectName) { return validate(validateByObjectName, option, eventName); } else { return { isError: false, info: '' }; } }); var Conversation = (function (_engineDispatcher) { var _temp; return _temp = function () { Conversation.create = function create(option) { return new Conversation(option); }; Conversation.get = function get(option) { return new Conversation(option); }; Conversation.merge = function merge(option) { try { var conversationList = option.conversationList, updatedConversationList = option.updatedConversationList; conversationList = updatedConversationList.concat(conversationList); conversationList = common.sortConversationList(conversationList); var hashTable = {}; var newList = []; utils.forEach(conversationList, function (conversation) { if (!utils.isObject(conversation)) { return; } var type = conversation.type, targetId = conversation.targetId; var localConversation = _engineDispatcher.exec({ event: ENGINE_EVENT.GET_LOCAL_CONVERSATION, args: [conversation] }) || {}; localConversation.unreadMessageCount = localConversation.unreadMessageCount || 0; var key = type + '_' + targetId; var hashItem = hashTable[key]; if (hashItem) { var index = hashItem.index, val = hashItem.val; val = utils.extend(conversation, val); val.unreadMessageCount = localConversation.unreadMessageCount; newList[index] = val; hashTable[key].val = val; } else { conversation.unreadMessageCount = localConversation.unreadMessageCount; newList.push(conversation); hashTable[key] = { index: newList.length - 1, val: conversation }; } }); return newList; } catch (e) { utils.consoleError(e); } }; Conversation.remove = function remove(option) { var _validate = validate({ type: Type.ConversationType, targetId: Type.String }, option, 'Conversation.remove'), isError = _validate.isError, info = _validate.info; if (isError) { return utils.Defer.reject(info); } return _engineDispatcher.exec({ event: ENGINE_EVENT.REMOVE_CONVERSATION, args: [option] }); }; Conversation.getList = function getList(option) { var _validate2 = validate({ count: Type.Number.canBeNull(), startTime: Type.Number.canBeNull() }, option, 'Conversation.getList'), isError = _validate2.isError, info = _validate2.info; if (isError) { return utils.Defer.reject(info); } return _engineDispatcher.exec({ event: ENGINE_EVENT.GET_CONVERSATION_LIST, args: [option] }); }; Conversation.getTotalUnreadCount = function getTotalUnreadCount() { return _engineDispatcher.exec({ event: ENGINE_EVENT.GET_TOTAL_UNREAD_COUNT }); }; function Conversation(option) { this.type = void 0; this.targetId = void 0; var _validate3 = validate({ type: Type.ConversationType, targetId: Type.String }, option, 'new Conversation'), isError = _validate3.isError, jsonInfo = _validate3.jsonInfo; if (isError) { utils.consoleError(jsonInfo); return jsonInfo; } utils.extend(this, option); } var _proto = Conversation.prototype; _proto.send = function send(option) { var eventName = 'conversation.send'; var _validate4 = validate({ messageType: Type.String, content: Type.Object }, option, eventName), isError = _validate4.isError, info = _validate4.info; if (isError) { return utils.Defer.reject(info); } var _option = option, messageType = _option.messageType, content = _option.content; var _validateMsgContent = validateMsgContent(messageType, content, eventName), isContentError = _validateMsgContent.isError, formatInfo = _validateMsgContent.info; if (isContentError) { return utils.Defer.reject(formatInfo); } option = utils.extendInShallow(SEND_MESSAGE_TYPE_OPTION[messageType], option); option = utils.extendInShallow(SEND_MESSAGE_OPTION, option); return _engineDispatcher.exec({ event: ENGINE_EVENT.SEND_MESSAGE, args: [this, option] }); }; _proto.recall = function recall(message, option) { var _validate5 = validate({ sentTime: Type.Number, messageUId: Type.String }, message, 'conversation.recall'), isError = _validate5.isError, info = _validate5.info; if (isError) { return utils.Defer.reject(info); } return _engineDispatcher.exec({ event: ENGINE_EVENT.RECALL_MESSAGE, args: [this, message, option] }); }; _proto.read = function read(option) { return _engineDispatcher.exec({ event: ENGINE_EVENT.CLEAR_UNREAD_COUNT, args: [this, option] }); }; _proto.getMessages = function getMessages(option) { var _validate6 = validate({ order: Type.Number.canBeNull(), count: Type.Number.canBeNull(), timestrap: Type.Number.canBeNull() }, option, 'conversation.getMessages'), isError = _validate6.isError, info = _validate6.info; if (isError) { return utils.Defer.reject(info); } option = utils.extendInShallow(GET_MESSAGES_OPTION, option); return _engineDispatcher.exec({ event: ENGINE_EVENT.GET_HISTORY_MSGS, args: [this, option] }); }; _proto.deleteMessages = function deleteMessages(messages) { var _validate7 = validate([{ sentTime: Type.Number, messageUId: Type.String, messageDirection: Type.Number }], messages, 'conversation.deleteMessages'), isError = _validate7.isError, info = _validate7.info; if (isError) { return utils.Defer.reject(info); } return _engineDispatcher.exec({ event: ENGINE_EVENT.DELETE_MESSAGES, args: [this, messages] }); }; _proto.clearMessages = function clearMessages(option) { var _validate8 = validate({ timestrap: Type.Number }, option, 'conversation.clearMessages'), isError = _validate8.isError, info = _validate8.info; if (isError) { return utils.Defer.reject(info); } return _engineDispatcher.exec({ event: ENGINE_EVENT.CLEAR_MESSAGES, args: [this, option] }); }; _proto.destory = function destory() { var conversation = this; return _engineDispatcher.exec({ event: ENGINE_EVENT.REMOVE_CONVERSATION, args: [conversation] }); }; return Conversation; }(), _temp; }); var ChatRoom = (function (_engineDispatcher) { var _temp; return _temp = function () { ChatRoom.get = function get(option) { return new ChatRoom(option); }; function ChatRoom(option) { this.id = void 0; var _validate = validate({ id: Type.String }, option, 'new ChatRoom'), isError = _validate.isError, jsonInfo = _validate.jsonInfo; if (isError) { utils.consoleError(jsonInfo); return jsonInfo; } utils.extend(this, option); } var _proto = ChatRoom.prototype; _proto.join = function join(option) { var _validate2 = validate({ count: Type.Number.canBeNull() }, option, 'chatRoom.join'), isError = _validate2.isError, info = _validate2.info; if (isError) { return utils.Defer.reject(info); } option = utils.extendInShallow(JOIN_CHATROOM_OPTION, option); return _engineDispatcher.exec({ event: ENGINE_EVENT.JOIN_CHATROOM, args: [this, option] }); }; _proto.quit = function quit() { return _engineDispatcher.exec({ event: ENGINE_EVENT.QUIT_CHATROOM, args: [this] }); }; _proto.getInfo = function getInfo(option) { var _validate3 = validate({ count: Type.Number.canBeNull(), order: Type.Number.canBeNull() }, option, 'chatRoom.getInfo'), isError = _validate3.isError, info = _validate3.info; if (isError) { return utils.Defer.reject(info); } option = utils.extendInShallow(GET_CHATROOM_INFO_OPTION, option); return _engineDispatcher.exec({ event: ENGINE_EVENT.GET_CHATROOM_INFO, args: [this, option] }); }; _proto.send = function send(option) { var eventName = 'chatRoom.send'; var _validate4 = validate({ messageType: Type.String, content: Type.Object }, option, eventName), isError = _validate4.isError, info = _validate4.info; if (isError) { return utils.Defer.reject(info); } var id = this.id; var _option = option, messageType = _option.messageType, content = _option.content; var _validateMsgContent = validateMsgContent(messageType, content, eventName), isContentError = _validateMsgContent.isError, formatInfo = _validateMsgContent.info; if (isContentError) { return utils.Defer.reject(formatInfo); } var conversation = { type: CONVERSATION_TYPE.CHATROOM, targetId: id }; option = utils.extendInShallow(SEND_MESSAGE_TYPE_OPTION[messageType], option); return _engineDispatcher.exec({ event: ENGINE_EVENT.SEND_MESSAGE, args: [conversation, option] }); }; _proto.getMessages = function getMessages(option) { var _validate5 = validate({ count: Type.Number.canBeNull(), order: Type.Number.canBeNull(), timestrap: Type.Number }, option, 'chatRoom.getInfo'), isError = _validate5.isError, info = _validate5.info; if (isError) { return utils.Defer.reject(info); } option = utils.extendInShallow(GET_CHATROOM_MESSAGES, option); return _engineDispatcher.exec({ event: ENGINE_EVENT.GET_CHATROOM_MSGS, args: [this, option] }); }; _proto.setEntry = function setEntry(option) { var _validate6 = validate({ key: Type.ChatRoomEntryKey, value: Type.ChatRoomEntryValue }, option, 'chatRoom.setEntry'), isError = _validate6.isError, info = _validate6.info; if (isError) { return utils.Defer.reject(info); } return _engineDispatcher.exec({ event: ENGINE_EVENT.SET_KV, args: [this, option] }); }; _proto.forceSetEntry = function forceSetEntry(option) { var _validate7 = validate({ key: Type.ChatRoomEntryKey, value: Type.ChatRoomEntryValue }, option, 'chatRoom.forceSetEntry'), isError = _validate7.isError, info = _validate7.info; if (isError) { return utils.Defer.reject(info); } return _engineDispatcher.exec({ event: ENGINE_EVENT.FORCE_SET_KV, args: [this, option] }); }; _proto.removeEntry = function removeEntry(option) { var _validate8 = validate({ key: Type.ChatRoomEntryKey }, option, 'chatRoom.removeEntry'), isError = _validate8.isError, info = _validate8.info; if (isError) { return utils.Defer.reject(info); } return _engineDispatcher.exec({ event: ENGINE_EVENT.DEL_KV, args: [this, option] }); }; _proto.forceRemoveEntry = function forceRemoveEntry(option) { var _validate9 = validate({ key: Type.ChatRoomEntryKey }, option, 'chatRoom.forceRemoveEntry'), isError = _validate9.isError, info = _validate9.info; if (isError) { return utils.Defer.reject(info); } return _engineDispatcher.exec({ event: ENGINE_EVENT.FORCE_DEL_KV, args: [this, option] }); }; _proto.getEntry = function getEntry(key) { var _validate10 = validate(Type.ChatRoomEntryKey, key, 'chatRoom.getEntry'), isError = _validate10.isError, info = _validate10.info; if (isError) { return utils.Defer.reject(info); } return _engineDispatcher.exec({ event: ENGINE_EVENT.GET_KV, args: [this, key] }); }; _proto.getAllEntries = function getAllEntries() { return _engineDispatcher.exec({ event: ENGINE_EVENT.GET_ALL_KV, args: [this] }); }; return ChatRoom; }(), _temp; }); var RTC = (function (_engineDispatcher) { var _temp; return _temp = function () { RTC.get = function get(option) { return new RTC(option); }; function RTC(option) { this.roomId = void 0; this.option = void 0; this.roomId = option.id; this.option = option; } var _proto = RTC.prototype; _proto.join = function join() { return _engineDispatcher.exec({ event: ENGINE_EVENT.JOIN_RTC, args: [this.option] }); }; _proto.quit = function quit() { return _engineDispatcher.exec({ event: ENGINE_EVENT.QUIT_RTC, args: [this.option] }); }; _proto.ping = function ping() { return _engineDispatcher.exec({ event: ENGINE_EVENT.PING_RTC, args: [this.option] }); }; _proto.getRoomInfo = function getRoomInfo() { return _engineDispatcher.exec({ event: ENGINE_EVENT.GET_RTC_ROOM_INFO, args: [this.option] }); }; _proto.getUserInfoList = function getUserInfoList() { return _engineDispatcher.exec({ event: ENGINE_EVENT.GET_RTC_USER_INFO_LIST, args: [this.option] }); }; _proto.setUserInfo = function setUserInfo(info) { return _engineDispatcher.exec({ event: ENGINE_EVENT.SET_RTC_USER_INFO, args: [this.option, info] }); }; _proto.removeUserInfo = function removeUserInfo(info) { return _engineDispatcher.exec({ event: ENGINE_EVENT.DEL_RTC_USER_INFO, args: [this.option, info] }); }; _proto.setData = function setData(key, value, isInner, apiType, message) { return _engineDispatcher.exec({ event: ENGINE_EVENT.SET_RTC_DATA, args: [this.roomId, key, value, isInner, apiType, message] }); }; _proto.getData = function getData(keys, isInner, apiType) { return _engineDispatcher.exec({ event: ENGINE_EVENT.GET_RTC_DATA, args: [this.roomId, keys, isInner, apiType] }); }; _proto.removeData = function removeData(keys, isInner, apiType, message) { return _engineDispatcher.exec({ event: ENGINE_EVENT.DEL_RTC_DATA, args: [this.roomId, keys, isInner, apiType, message] }); }; _proto.setUserData = function setUserData(key, value, isInner, message) { return this.setData(key, value, isInner, RTC_API_TYPE.PERSON, message); }; _proto.getUserData = function getUserData(keys, isInner) { return this.getData(keys, isInner, RTC_API_TYPE.PERSON); }; _proto.removeUserData = function removeUserData(keys, isInner, message) { return this.removeData(keys, isInner, RTC_API_TYPE.PERSON, message); }; _proto.setRoomData = function setRoomData(key, value, isInner, message) { return this.setData(key, value, isInner, RTC_API_TYPE.ROOM, message); }; _proto.getRoomData = function getRoomData(keys, isInner) { return this.getData(keys, isInner, RTC_API_TYPE.ROOM); }; _proto.removeRoomData = function removeRoomData(keys, isInner, message) { return this.removeData(keys, isInner, RTC_API_TYPE.ROOM, message); }; _proto.getUserList = function getUserList() { return _engineDispatcher.exec({ event: ENGINE_EVENT.GET_RTC_USER_LIST, args: [this.option] }); }; _proto.setOutData = function setOutData(rtcData, type, message) { return _engineDispatcher.exec({ event: ENGINE_EVENT.SET_RTC_OUT_DATA, args: [this.roomId, rtcData, type, message] }); }; _proto.getOutData = function getOutData(userIds) { return _engineDispatcher.exec({ event: ENGINE_EVENT.GET_RTC_OUT_DATA, args: [this.roomId, userIds] }); }; _proto.getToken = function getToken() { return _engineDispatcher.exec({ event: ENGINE_EVENT.GET_RTC_TOKEN, args: [this.option] }); }; _proto.setState = function setState(content) { return _engineDispatcher.exec({ event: ENGINE_EVENT.SET_RTC_STATE, args: [this.option, content] }); }; _proto.send = function send(option) { var id = this.roomId; var conversation = { type: CONVERSATION_TYPE.RTC_ROOM, targetId: id }; return _engineDispatcher.exec({ event: ENGINE_EVENT.SEND_MESSAGE, args: [conversation, option] }); }; return RTC; }(), _temp; }); var IM = function () { function IM(option) { this._engineDispatcher = void 0; var _validate = validate({ appkey: Type.String }, option, 'RongIMLib.init'), isError = _validate.isError, jsonInfo = _validate.jsonInfo; if (isError) { throw Error(jsonInfo); } var engineHandler = new EngineDispatcher(option); this._engineDispatcher = engineHandler; var Modules = { Conversation: Conversation(engineHandler), ChatRoom: ChatRoom(engineHandler), RTC: RTC(engineHandler) }; utils.extend(this, Modules); } var _proto = IM.prototype; _proto.getConnectionStatus = function getConnectionStatus() { return this._engineDispatcher.exec({ event: ENGINE_EVENT.GET_CONNECTION_STATUS }); }; _proto.getConnectionUserId = function getConnectionUserId() { return this._engineDispatcher.exec({ event: ENGINE_EVENT.GET_CONNECTION_USER_ID }); }; _proto.getConnectedTime = function getConnectedTime() { return this._engineDispatcher.exec({ event: ENGINE_EVENT.GET_CONNECTED_TIME }); }; _proto.getAppInfo = function getAppInfo() { return this._engineDispatcher.exec({ event: ENGINE_EVENT.GET_APP_INFO }); }; _proto.watch = function watch(watchers) { var _validate2 = validate({ conversation: Type.Function.canBeNull(), message: Type.Function.canBeNull(), status: Type.Function.canBeNull() }, watchers, 'im.watch'), isError = _validate2.isError, jsonInfo = _validate2.jsonInfo; if (isError) { utils.consoleError(jsonInfo); return jsonInfo; } return this._engineDispatcher.exec({ event: ENGINE_EVENT.WATCH, args: [watchers] }); }; _proto.unwatch = function unwatch(watchers) { return this._engineDispatcher.exec({ event: ENGINE_EVENT.UN_WATCH, args: [watchers] }); }; _proto.connect = function connect(user) { var _validate3 = validate({ token: Type.String }, user, 'im.connect'), isError = _validate3.isError, info = _validate3.info; if (isError) { return utils.Defer.reject(info); } return this._engineDispatcher.exec({ event: ENGINE_EVENT.CONNECT, args: [user] }); }; _proto.reconnect = function reconnect() { return this._engineDispatcher.exec({ event: ENGINE_EVENT.RECONNECT }); }; _proto.disconnect = function disconnect() { return this._engineDispatcher.exec({ event: ENGINE_EVENT.DISCONNECT, args: [true] }); }; _proto.changeUser = function changeUser(user) { var _validate4 = validate({ token: Type.String }, user, 'im.changeUser'), isError = _validate4.isError, info = _validate4.info; if (isError) { return utils.Defer.reject(info); } var self = this; return self.disconnect().then(function () { return self.connect(user); }); }; _proto.getFileToken = function getFileToken(fileType) { return this._engineDispatcher.exec({ event: ENGINE_EVENT.GET_UPLOAD_TOKEN, args: [fileType] }); }; _proto.getFileUrl = function getFileUrl(fileType, fileName, originName) { return this._engineDispatcher.exec({ event: ENGINE_EVENT.GET_UPLOAD_URL, args: [fileType, fileName, originName] }); }; return IM; }(); var imInstance; var initLogger = function initLogger(option, im) { var isDebug = option.isDebug, appkey = option.appkey, logCollectEvent = option.logger; utils.isFunction(logCollectEvent) && Logger.watchLog(logCollectEvent); Logger.setOption({ isDebug: isDebug, appkey: appkey }); Logger.info(TAG.A_INIT_O, { content: option }); im.watch({ status: function status(_ref) { var _status = _ref.status; Logger.setOption({ isNetworkUnavailable: utils.isEqual(_status, CONNECTION_STATUS.NETWORK_UNAVAILABLE) }); } }); }; var init = function init(option) { option = utils.extendInShallow(IM_OPTION, option); option.connectType = common.getConnectType(option); if (!imInstance) { imInstance = new IM(option); initLogger(option, imInstance); } return imInstance; }; var getInstance = function getInstance() { return imInstance; }; var index = utils.extend({ init: init, getInstance: getInstance, env: env, common: common, ERROR_CODE: ERROR_CODE, Logger: Logger }, product); return index; }))); ================================================ FILE: api-test/lib/js/RongIMLib-3.0.5-mentioned.js ================================================ /* * RongIMLib.js v3.0.5-dev * CodeVersion: 03caf1eb0aea5d9db625b9b939e52338de427ba1 * Release Date: Wed Aug 12 2020 19:04:27 GMT+0800 (China Standard Time) * Copyright 2020 RongCloud */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global.RongIMLib = factory()); }(this, (function () { 'use strict'; var versionToServer = "3.0.5"; var SDK_VERSION = versionToServer; var ERROR_INFO = { TIMEOUT: { code: -1, msg: 'Network timeout' }, SDK_INTERNAL_ERROR: { code: -2, msg: 'SDK internal error' }, PARAMETER_ERROR: { code: -3, msg: 'Please check the parameters, the {param} expected a value of {expect} but received {current}' }, REJECTED_BY_BLACKLIST: { code: 405, msg: 'Blacklisted by the other party' }, SEND_TOO_FAST: { code: 20604, msg: 'Sending messages too quickly' }, NOT_IN_GROUP: { code: 22406, msg: 'Not in group' }, FORBIDDEN_IN_GROUP: { code: 22408, msg: 'Forbbiden from speaking in the group' }, NOT_IN_CHATROOM: { code: 23406, msg: 'Not in chatRoom' }, FORBIDDEN_IN_CHATROOM: { code: 23408, msg: 'Forbbiden from speaking in the chatRoom' }, KICKED_FROM_CHATROOM: { code: 23409, msg: 'Kicked out and forbbiden from joining the chatRoom' }, CHATROOM_NOT_EXIST: { code: 23410, msg: 'ChatRoom does not exist' }, CHATROOM_IS_FULL: { code: 23411, msg: 'ChatRoom members exceeded' }, PARAMETER_INVALID_CHATROOM: { code: 23412, msg: 'Invalid chatRoom parameters' }, ROAMING_SERVICE_UNAVAILABLE_CHATROOM: { code: 23414, msg: 'ChatRoom message roaming service is not open, Please go to the developer to open this service' }, RECALLMESSAGE_PARAMETER_INVALID: { code: 25101, msg: 'Invalid recall message parameter' }, PUSHSETTING_PARAMETER_INVALID: { code: 26001, msg: 'Invalid push parameter' }, OPERATION_BLOCKED: { code: 20605, msg: 'Operation is blocked' }, OPERATION_NOT_SUPPORT: { code: 20606, msg: 'Operation is not supported' }, MSG_BLOCKED_SENSITIVE_WORD: { code: 21501, msg: 'The sent message contains sensitive words' }, REPLACED_SENSITIVE_WORD: { code: 21502, msg: 'Sensitive words in the message have been replaced' }, NOT_CONNECTED: { code: 30001, msg: 'Please connect successfully first' }, NAVI_REQUEST_ERROR: { code: 30007, msg: 'Navigation http request failed' }, CMP_REQUEST_ERROR: { code: 30010, msg: 'CMP sniff http request failed' }, CONN_APPKEY_FAKE: { code: 31002, msg: 'Your appkey is fake' }, CONN_MINI_SERVICE_NOT_OPEN: { code: 31003, msg: 'Mini program service is not open, Please go to the developer to open this service' }, CONN_TOKEN_INCORRECT: { code: 31004, msg: 'Your token is not valid or expired' }, CONN_NOT_AUTHRORIZED: { code: 31005, msg: 'AppKey and Token do not match' }, CONN_REDIRECTED: { code: 31006, msg: 'Connection redirection' }, CONN_APP_BLOCKED_OR_DELETED: { code: 31008, msg: 'AppKey is banned or deleted' }, CONN_USER_BLOCKED: { code: 31009, msg: 'User blocked' }, CONN_DOMAIN_INCORRECT: { code: 31012, msg: 'Connect domain error, Please check the set security domain' }, ROAMING_SERVICE_UNAVAILABLE: { code: 33007, msg: 'Roaming service cloud is not open, Please go to the developer to open this service' }, RC_CONNECTION_EXIST: { code: 34001, msg: 'Connection already exists' }, CHATROOM_KV_EXCEED: { code: 23423, msg: 'ChatRoom KV setting exceeds maximum' }, CHATROOM_KV_OVERWRITE_INVALID: { code: 23424, msg: 'ChatRoom KV already exists' }, CHATROOM_KV_STORE_NOT_OPEN: { code: 23426, msg: 'ChatRoom KV storage service is not open, Please go to the developer to open this service' }, CHATROOM_KEY_NOT_EXIST: { code: 23427, msg: 'ChatRoom key does not exist' } }; var ERROR_CODE = {}; var ERROR_CODE_TO_INFO = {}; for (var name$1 in ERROR_INFO) { var info = ERROR_INFO[name$1]; var code = info.code; ERROR_CODE[name$1] = code; ERROR_CODE[code] = name$1; ERROR_CODE_TO_INFO[code] = info; } var SERVER_ERROR_TO_CODE = { '1': ERROR_INFO.ROAMING_SERVICE_UNAVAILABLE.code }; var _CONNECT_SERVER_STATU, _SERVER_DISCONNECT_ST, _TRANSPORTER_STATUS_T; var NAVI_ERROR_INFO = { '401': ERROR_INFO.CONN_TOKEN_INCORRECT, '403': ERROR_INFO.CONN_APPKEY_FAKE }; var CONNECTION_STATUS = { CONNECTED: 0, CONNECTING: 1, DISCONNECTED: 2, NETWORK_UNAVAILABLE: 3, SOCKET_ERROR: 4, KICKED_OFFLINE_BY_OTHER_CLIENT: 6, BLOCKED: 12 }; var SERVER_DISCONNECT_STATUS = { KICKED_OFFLINE_BY_OTHER_CLIENT: 1, BLOCKED: 2 }; var CONNECT_SERVER_STATUS = { IDENTIFIER_REJECTED: 2, CONN_MINI_SERVICE_NOT_OPEN: 3, TOKEN_INCORRECT: 4, NOT_AUTHORIZED: 5, REDIRECT: 6, PACKAGE_ERROR: 7, APP_BLOCK_OR_DELETE: 8, BLOCK: 9, TOKEN_EXPIRE: 10, DEVICE_ERROR: 11, DOMAIN_INCORRECT: 12 }; var CONNECT_SERVER_STATUS_MAP_ERROR_INFO = (_CONNECT_SERVER_STATU = {}, _CONNECT_SERVER_STATU[CONNECT_SERVER_STATUS.IDENTIFIER_REJECTED] = ERROR_INFO.CONN_APPKEY_FAKE, _CONNECT_SERVER_STATU[CONNECT_SERVER_STATUS.CONN_MINI_SERVICE_NOT_OPEN] = ERROR_INFO.CONN_MINI_SERVICE_NOT_OPEN, _CONNECT_SERVER_STATU[CONNECT_SERVER_STATUS.TOKEN_INCORRECT] = ERROR_INFO.CONN_TOKEN_INCORRECT, _CONNECT_SERVER_STATU[CONNECT_SERVER_STATUS.NOT_AUTHORIZED] = ERROR_INFO.CONN_NOT_AUTHRORIZED, _CONNECT_SERVER_STATU[CONNECT_SERVER_STATUS.REDIRECT] = ERROR_INFO.CONN_REDIRECTED, _CONNECT_SERVER_STATU[CONNECT_SERVER_STATUS.APP_BLOCK_OR_DELETE] = ERROR_INFO.CONN_APP_BLOCKED_OR_DELETED, _CONNECT_SERVER_STATU[CONNECT_SERVER_STATUS.BLOCK] = ERROR_INFO.CONN_USER_BLOCKED, _CONNECT_SERVER_STATU[CONNECT_SERVER_STATUS.TOKEN_EXPIRE] = ERROR_INFO.CONN_TOKEN_INCORRECT, _CONNECT_SERVER_STATU[CONNECT_SERVER_STATUS.DOMAIN_INCORRECT] = ERROR_INFO.CONN_DOMAIN_INCORRECT, _CONNECT_SERVER_STATU); var TRANSPORTER_STATUS = { CONNECTED: CONNECTION_STATUS.CONNECTED, KICKED_OFFLINE_BY_OTHER_CLIENT: CONNECTION_STATUS.KICKED_OFFLINE_BY_OTHER_CLIENT, BLOCKED: CONNECTION_STATUS.BLOCKED, CLOSE_NORMAL: 1000, CLOSE_GOING_AWAY: 1001, CLOSE_PROTOCOL_ERROR: 1002, CLOSE_UNSUPPORTED: 1003, CLOSE_NO_STATUS: 1005, CLOSE_ABNORMAL: 1006, UNSUPPORTED_DATA: 1007, POLICY_VIOLATION: 1008, CLOSE_TOO_LARGE: 1009, MISSING_EXTENSION: 1010, INTERNAL_ERROR: 1011, SERVICE_RESTART: 1012, TRY_AGAIN_LATER: 1013, TSL_HANDSHAKE: 1015, PING_FIRST_TIMEOUT: 2001, PING_TIMEOUT: 2002, DISCONNECT_TOO_FAST: 2003, EXCEED_MESSAGE_ID_LIMIT: 2004, COMET_REQUEST_ERROR: 2005, MINI_URL_NOT_IN_DOMAIN_LIST: 2006 }; var MINI_ERROR_MSG_TO_STATUS = { 'url not in domain list': TRANSPORTER_STATUS.MINI_URL_NOT_IN_DOMAIN_LIST }; var SERVER_DISCONNECT_STATUS_TO_TRANSPORTER_STATUS = (_SERVER_DISCONNECT_ST = {}, _SERVER_DISCONNECT_ST[SERVER_DISCONNECT_STATUS.KICKED_OFFLINE_BY_OTHER_CLIENT] = TRANSPORTER_STATUS.KICKED_OFFLINE_BY_OTHER_CLIENT, _SERVER_DISCONNECT_ST[SERVER_DISCONNECT_STATUS.BLOCKED] = TRANSPORTER_STATUS.BLOCKED, _SERVER_DISCONNECT_ST); var TRANSPORTER_STATUS_NEED_UPDATE_CMP = [TRANSPORTER_STATUS.CLOSE_NORMAL, TRANSPORTER_STATUS.CLOSE_GOING_AWAY, TRANSPORTER_STATUS.CLOSE_PROTOCOL_ERROR, TRANSPORTER_STATUS.CLOSE_UNSUPPORTED, TRANSPORTER_STATUS.UNSUPPORTED_DATA, TRANSPORTER_STATUS.POLICY_VIOLATION, TRANSPORTER_STATUS.MISSING_EXTENSION, TRANSPORTER_STATUS.INTERNAL_ERROR, TRANSPORTER_STATUS.SERVICE_RESTART, TRANSPORTER_STATUS.TRY_AGAIN_LATER, TRANSPORTER_STATUS.TSL_HANDSHAKE, TRANSPORTER_STATUS.PING_FIRST_TIMEOUT, TRANSPORTER_STATUS.DISCONNECT_TOO_FAST, TRANSPORTER_STATUS.COMET_REQUEST_ERROR]; var TRANSPORTER_STATUS_NEED_RECONNECT = TRANSPORTER_STATUS_NEED_UPDATE_CMP.concat([TRANSPORTER_STATUS.PING_TIMEOUT, TRANSPORTER_STATUS.CLOSE_ABNORMAL, TRANSPORTER_STATUS.EXCEED_MESSAGE_ID_LIMIT, TRANSPORTER_STATUS.COMET_REQUEST_ERROR]); var TRANSPORTER_STATUS_TO_CONNECTION_STATUS = (_TRANSPORTER_STATUS_T = {}, _TRANSPORTER_STATUS_T[TRANSPORTER_STATUS.CLOSE_GOING_AWAY] = CONNECTION_STATUS.SOCKET_ERROR, _TRANSPORTER_STATUS_T[TRANSPORTER_STATUS.CLOSE_PROTOCOL_ERROR] = CONNECTION_STATUS.SOCKET_ERROR, _TRANSPORTER_STATUS_T[TRANSPORTER_STATUS.CLOSE_UNSUPPORTED] = CONNECTION_STATUS.SOCKET_ERROR, _TRANSPORTER_STATUS_T[TRANSPORTER_STATUS.CLOSE_NO_STATUS] = CONNECTION_STATUS.DISCONNECTED, _TRANSPORTER_STATUS_T[TRANSPORTER_STATUS.CLOSE_ABNORMAL] = CONNECTION_STATUS.NETWORK_UNAVAILABLE, _TRANSPORTER_STATUS_T[TRANSPORTER_STATUS.DISCONNECT_TOO_FAST] = CONNECTION_STATUS.NETWORK_UNAVAILABLE, _TRANSPORTER_STATUS_T[TRANSPORTER_STATUS.UNSUPPORTED_DATA] = CONNECTION_STATUS.SOCKET_ERROR, _TRANSPORTER_STATUS_T[TRANSPORTER_STATUS.POLICY_VIOLATION] = CONNECTION_STATUS.SOCKET_ERROR, _TRANSPORTER_STATUS_T[TRANSPORTER_STATUS.CLOSE_TOO_LARGE] = CONNECTION_STATUS.SOCKET_ERROR, _TRANSPORTER_STATUS_T[TRANSPORTER_STATUS.MISSING_EXTENSION] = CONNECTION_STATUS.SOCKET_ERROR, _TRANSPORTER_STATUS_T[TRANSPORTER_STATUS.INTERNAL_ERROR] = CONNECTION_STATUS.SOCKET_ERROR, _TRANSPORTER_STATUS_T[TRANSPORTER_STATUS.SERVICE_RESTART] = CONNECTION_STATUS.SOCKET_ERROR, _TRANSPORTER_STATUS_T[TRANSPORTER_STATUS.TRY_AGAIN_LATER] = CONNECTION_STATUS.SOCKET_ERROR, _TRANSPORTER_STATUS_T[TRANSPORTER_STATUS.TSL_HANDSHAKE] = CONNECTION_STATUS.SOCKET_ERROR, _TRANSPORTER_STATUS_T[TRANSPORTER_STATUS.PING_FIRST_TIMEOUT] = CONNECTION_STATUS.NETWORK_UNAVAILABLE, _TRANSPORTER_STATUS_T[TRANSPORTER_STATUS.PING_TIMEOUT] = CONNECTION_STATUS.NETWORK_UNAVAILABLE, _TRANSPORTER_STATUS_T[TRANSPORTER_STATUS.COMET_REQUEST_ERROR] = CONNECTION_STATUS.NETWORK_UNAVAILABLE, _TRANSPORTER_STATUS_T); var CONNECT_TYPE = { COMET: 'comet', WEBSOCKET: 'websocket' }; var CONVERSATION_TYPE = { PRIVATE: 1, GROUP: 3, CHATROOM: 4, CUSTOMER_SERVICE: 5, SYSTEM: 6, RTC_ROOM: 12 }; var MESSAGE_DIRECTION = { SEND: 1, RECEIVE: 2 }; var MESSAGS_TIME_ORDER = { DESC: 0, ASC: 1 }; var CHATROOM_ORDER = { ASC: 1, DESC: 2 }; var RECALL_MESSAGE_TYPE = 'RC:RcCmd'; var MENTIOND_TYPE = { ALL: 1, SINGAL: 2 }; var MESSAGE_TYPE = { TEXT: 'RC:TxtMsg', VOICE: 'RC:VcMsg', HQ_VOICE: 'RC:HQVCMsg', IMAGE: 'RC:ImgMsg', GIF: 'RC:GIFMsg', RICH_CONTENT: 'RC:ImgTextMsg', LOCATION: 'RC:LBSMsg', FILE: 'RC:FileMsg', SIGHT: 'RC:SightMsg', COMBINE: 'RC:CombineMsg', CHRM_KV_NOTIFY: 'RC:chrmKVNotiMsg', LOG_COMMAND: 'RC:LogCmdMsg' }; var RTC_API_TYPE = { ROOM: 1, PERSON: 2 }; var FILE_TYPE = { IMAGE: 1, AUDIO: 2, VIDEO: 3, FILE: 4 }; var CHATROOM_ENTRY_TYPE = { UPDATE: 1, DELETE: 2 }; var NOTIFICATION_STATUS = { DO_NOT_DISTURB: 1, NOTIFY: 2 }; var product = { CONNECT_TYPE: CONNECT_TYPE, CONNECTION_STATUS: CONNECTION_STATUS, CONVERSATION_TYPE: CONVERSATION_TYPE, MESSAGE_DIRECTION: MESSAGE_DIRECTION, MESSAGS_TIME_ORDER: MESSAGS_TIME_ORDER, CHATROOM_ORDER: CHATROOM_ORDER, RECALL_MESSAGE_TYPE: RECALL_MESSAGE_TYPE, MESSAGE_TYPE: MESSAGE_TYPE, MENTIOND_TYPE: MENTIOND_TYPE, SDK_VERSION: SDK_VERSION, FILE_TYPE: FILE_TYPE, CHATROOM_ENTRY_TYPE: CHATROOM_ENTRY_TYPE, NOTIFICATION_STATUS: NOTIFICATION_STATUS }; var IM_TIMEOUT = 30000; var IM_PING_INTERVAL_TIME = 30000; var IM_COMET_PULLMSG_TIMEOUT = 45000; var IM_PING_MAX_TIMEOUT = 6000; var IM_PING_MIN_TIMEOUT = 2000; var PULL_MSG_TIME = 180000; var NAVI_EXPIRED_TIME = 7200000; var CMP_SNIFF_INTERNAL_TIME = 1000; var FIRST_PING_TIMEOUT = 1000; var NAVI_REQUEST_SUCCESS_CODE = 200; var NAVI_SEPARATOR_IN_TOKEN = '@'; var DOMAIN_SEPARATOR_IN_NAVLIST = ';'; var DOMAIN_SEPARATOR_IN_CMPLIST = ','; var MAX_SINGAL_ID = 65535; var MINIMUM_CONNECT_DURATION = 5000; var CHATROOM_KEY_LENGTH = { MAX: 128, MIN: 1 }; var CHATROOM_VALUE_LENGTH = { MAX: 4096, MIN: 1 }; var TYPE_HAS_CONVERSATION = [CONVERSATION_TYPE.PRIVATE, CONVERSATION_TYPE.GROUP, CONVERSATION_TYPE.SYSTEM]; var PLATFORM = { WEB: 'web', WX: 'wx', ZFB: 'zfb', TT: 'tt', BAIDU: 'baidu', QUICK_APP: 'quick_app', UNI: 'uni' }; var REQUEST_METHOD = { POST: 'post', GET: 'get' }; var STORAGE_ROOT_KEY = 'rc-'; var STORAGE_DEVICE_ID_KEY = STORAGE_ROOT_KEY + 'deviceId'; var STORAGE_SESSION_ID_KEY = STORAGE_ROOT_KEY + 'sessionId'; var STORAGE_NAVI = { ROOT_KEY_TPL: 'nav-{appkey}-{UID}', SUB_KEY: { CONNECT_TYPE: 'connettype', TIME_WHEN_SAVED: 'time', RESPONSE: 'resp' } }; var STORAGE_SYNC_TIME = { ROOT_KEY_TPL: 'sync-{appkey}-{userId}', SUB_KEY: { SENDBOX: 'send', INBOX: 'in' } }; var SESSION_SYNC_TIME = { ROOT_KEY_TPL: 'sync-{appkey}-{userId}', SUB_KEY: { TIME: 't' } }; var STORAGE_CONVERSATION = { ROOT_KEY_TPL: 'con-{appkey}-{userId}', SUB_KEY: { ROOT_TPL: '{type}-{id}', UNREAD_COUNT: 'c', UNREAD_LAST_TIME: 't', HAS_MENTIOND: 'hm', MENTIOND_INFO: 'm', NOTIFICATION: 'no', TOP: 'to' } }; var STORAGE_CONVERSATION_STATUS = { ROOT_KEY_TPL: 'con-s-{appkey}-{userId}', SUB_KEY: { TIME: 't' } }; var STORAGE_USER_SETTING = { ROOT_KEY_TPL: 'sett-{appkey}-{userId}', SUB_KEY: { VERSION: 'v', SETTINGS: 's' } }; var HTTP_PROTOCOL = { HTTP: 'http:', HTTPS: 'https:', FILE: 'file:' }; var WS_PROTOCOL = { WSS: 'wss:', WS: 'ws:' }; var NAVI_CALLBACK_NAME = 'getServerEndpoint'; var NAVI_TYPE = { COMET: 'cometnavi', WEBSOCKET: 'navi' }; var NAVI_URL_TPL = '{url}/{type}.js?appId={appkey}&token={token}&callBack=' + NAVI_CALLBACK_NAME + '&r={random}&v=' + SDK_VERSION; var CMP_URL_TPL = '{protocol}//{domain}/websocket?appId={appkey}&token={token}&apiVer={apiVer}&sdkVer=' + SDK_VERSION; var MINI_CMP_URL_TPL = '{protocol}//{domain}/websocket?appId={appkey}&token={token}&apiVer={apiVer}&sdkVer=' + SDK_VERSION + '&platform={platform}'; var COMET_REQ_HAS_TOPIC_URL_TPL = '{protocol}//{domain}/websocket?messageid={messageId}&header={headerCode}&sessionid={sessionId}&topic={topic}&targetid={targetId}&pid={pid}'; var COMET_REQ_NO_TOPIC_URL_TPL = '{protocol}//{domain}/websocket?messageid={messageId}&header={headerCode}&sessionid={sessionId}&pid={pid}'; var COMET_PULL_URL_TPL = '{protocol}//{domain}/pullmsg.js?sessionid={sessionId}×trap={timestamp}&pid={pid}'; var TIMER_TYPE = { INTERVAL: 'interval', TIMEOUT: 'timeout' }; var TIMER_STATUS = { PENNDING: 'pendding', BUSY: 'busy', ENDING: 'ending' }; var PLATFORM_TYPE = { MINI: 'MiniProgram', WEB: 'Web' }; var SESSION_SYNC_CHATROOM = { ROOT_KEY_TPL: 'sync-chrm-{appkey}-{userId}' }; var UnKown = 'UnKown'; var hasMiniBaseEvent = function hasMiniBaseEvent(miniGlobal) { var baseMiniEventNames = ['canIUse', 'getSystemInfo']; for (var i = 0, max = baseMiniEventNames.length; i < max; i++) { var baseEventName = baseMiniEventNames[i]; if (!miniGlobal[baseEventName]) { return false; } } return true; }; var isFromUniappEnv = function isFromUniappEnv() { if (typeof uni !== 'undefined' && hasMiniBaseEvent(uni)) { return true; } return false; }; var isFromUniapp = isFromUniappEnv(); var isAppPlusEnv = function isAppPlusEnv() { if (isFromUniapp) { var systemInfo = uni.getSystemInfoSync(); if (['ios', 'android'].includes(systemInfo.platform) && systemInfo.version) { return true; } } return false; }; var isAppPlus = isAppPlusEnv(); var isMiniEnv = function isMiniEnv(global) { if (isAppPlus) { return false; } return global !== window; }; var getEnvInfo = function getEnvInfo() { if (isAppPlus) { return { platform: PLATFORM.UNI, global: uni }; } else if (typeof swan !== 'undefined' && hasMiniBaseEvent(swan)) { return { platform: PLATFORM.BAIDU, global: swan }; } else if (typeof tt !== 'undefined' && hasMiniBaseEvent(tt)) { return { platform: PLATFORM.TT, global: tt }; } else if (typeof my !== 'undefined' && hasMiniBaseEvent(my)) { return { platform: PLATFORM.ZFB, global: my }; } else if (typeof wx !== 'undefined' && hasMiniBaseEvent(wx) && !navigator) { return { platform: PLATFORM.WX, global: wx }; } else { return { platform: PLATFORM.WEB, global: window }; } }; var getWebSystemInfo = function getWebSystemInfo() { var userAgent = navigator.userAgent; var version, type; var condition = { IE: /rv:([\d.]+)\) like Gecko|MSIE ([\d.]+)/, Edge: /Edge\/([\d.]+)/, Firefox: /Firefox\/([\d.]+)/, Opera: /(?:OPERA|OPR).([\d.]+)/, WeiXin: /MicroMessenger\/([\d.]+)/, QQBrowser: /QQBrowser\/([\d.]+)/, Chrome: /Chrome\/([\d.]+)/, Safari: /Version\/([\d.]+).*Safari/ }; for (var key in condition) { if (!condition.hasOwnProperty(key)) continue; var browserContent = userAgent.match(condition[key]); if (browserContent) { type = key; version = browserContent[1] || browserContent[2]; break; } } return { model: type || UnKown, version: version || UnKown }; }; var getMiniSystemInfo = function getMiniSystemInfo(global) { var systemInfo = global.getSystemInfoSync() || {}; var model = systemInfo.model, brand = systemInfo.brand; if (model && brand) { model = model + ' ' + brand; } systemInfo.model = model; return systemInfo; }; var getProtocol = function getProtocol(global) { var location = global.location || {}; var isHttp = location.protocol === HTTP_PROTOCOL.HTTP || location.protocol === HTTP_PROTOCOL.FILE; var protocol = { http: isHttp ? HTTP_PROTOCOL.HTTP : HTTP_PROTOCOL.HTTPS, ws: WS_PROTOCOL.WSS }; if (isHttp) { protocol.ws = WS_PROTOCOL.WS; } return protocol; }; var adaptGlobalObjectCreate = function adaptGlobalObjectCreate(global, isMini) { if (!isMini && !isAppPlus && !global.Object.create) { global.Object.create = function (o, properties) { if (typeof o !== 'object' && typeof o !== 'function') throw new TypeError('Object prototype may only be an Object: ' + o);else if (o === null) throw new Error('This browser\'s implementation of Object.create is a shim and doesn\'t support \'null\' as the first argument.'); if (typeof properties !== 'undefined') throw new Error('This browser\'s implementation of Object.create is a shim and doesn\'t support a second argument.'); function F() {} F.prototype = o; return new F(); }; } }; var getMiniGlobal = function getMiniGlobal(global) { return Object.assign(global, { JSON: JSON, Promise: Promise, setTimeout: setTimeout, setInterval: setInterval, encodeURIComponent: encodeURIComponent, clearTimeout: function (_clearTimeout) { function clearTimeout(_x) { return _clearTimeout.apply(this, arguments); } clearTimeout.toString = function () { return _clearTimeout.toString(); }; return clearTimeout; }(function (id) { clearTimeout(id); }), clearInterval: function (_clearInterval) { function clearInterval(_x2) { return _clearInterval.apply(this, arguments); } clearInterval.toString = function () { return _clearInterval.toString(); }; return clearInterval; }(function (id) { clearInterval(id); }) }); }; var envInfo = getEnvInfo(); var platform = envInfo.platform, global$1 = envInfo.global; var isMini = isMiniEnv(global$1); var protocol = getProtocol(global$1); var system = isMini || isAppPlus ? getMiniSystemInfo(global$1) : getWebSystemInfo(); system.name = platform; adaptGlobalObjectCreate(global$1, isMini); global$1 = isMini || isAppPlus ? getMiniGlobal(global$1) : global$1; var env = { global: global$1, system: system, isMini: isMini, protocol: protocol, isAppPlus: isAppPlus, isFromUniapp: isFromUniapp }; var global$2 = env.global, system$1 = env.system; var isZFB = system$1.name === PLATFORM.ZFB; var ZFBStorage = function () { function ZFBStorage() {} var _proto = ZFBStorage.prototype; _proto.set = function set(key, value) { global$2.setStorageSync({ key: key, data: value }); }; _proto.get = function get(key) { return global$2.getStorageSync({ key: key }); }; _proto.remove = function remove(key) { return global$2.removeStorageSync({ key: key }); }; _proto.getKeys = function getKeys() { var res = my.getStorageInfoSync(); return res.keys; }; return ZFBStorage; }(); var MiniStorage = function () { function MiniStorage() {} var _proto2 = MiniStorage.prototype; _proto2.set = function set(key, value) { global$2.setStorageSync(key, value); }; _proto2.get = function get(key) { try { return global$2.getStorageSync(key); } catch (e) { return null; } }; _proto2.remove = function remove(key) { try { return global$2.removeStorageSync(key); } catch (e) { return null; } }; _proto2.getKeys = function getKeys() { try { var res = global$2.getStorageInfoSync(); return res.keys; } catch (e) { return []; } }; return MiniStorage; }(); var storage = isZFB ? ZFBStorage : MiniStorage; var JSON$1 = { parse: function parse(sJSON) { return new Function('', 'return (' + sJSON + ')')(); }, stringify: function stringify(value) { return JSON$1.str('', { '': value }); }, str: function str(key, holder) { var i, k, v, length, partial, value = holder[key], self = JSON$1; if (value && typeof value === 'object' && typeof value.toJSON === 'function') { value = value.toJSON(key); } switch (typeof value) { case 'string': return self.quote(value); case 'number': return isFinite(value) ? String(value) : 'null'; case 'boolean': return String(value); case 'object': if (!value) { return 'null'; } partial = []; if (Object.prototype.toString.apply(value) === '[object Array]') { length = value.length; for (i = 0; i < length; i += 1) { partial[i] = self.str(i, value) || 'null'; } v = partial.length === 0 ? '[]' : '[' + partial.join(',') + ']'; return v; } for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = self.str(k, value); if (v) { partial.push(self.quote(k) + ':' + v); } } } v = partial.length === 0 ? '{}' : '{' + partial.join(',') + '}'; return v; } }, quote: function quote(string) { var self = JSON$1; self.rx_escapable.lastIndex = 0; return self.rx_escapable.test(string) ? '"' + string.replace(self.rx_escapable, function (a) { var c = self.meta[a]; return typeof c === 'string' ? c : "\\u" + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }) + '"' : '"' + string + '"'; }, rx_escapable: new RegExp("[\\\"\\\\\"\0-\x1F\x7F-\x9F\xAD\u0600-\u0604\u070F\u17B4\u17B5\u200C-\u200F\u2028-\u202F\u2060-\u206F\uFEFF\uFFF0-\uFFFF]", 'g'), meta: { '\b': '\\b', ' ': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"': '\\"', '\'\'': '\\\'\'', '\\': '\\\\' } }; var CacheStorage = function () { function CacheStorage(values) { this.caches = {}; if (values) { this.caches = values; } } var _proto = CacheStorage.prototype; _proto.set = function set(key, value) { this.caches[key] = value; }; _proto.remove = function remove(key) { var val = this.get(key); delete this.caches[key]; return val; }; _proto.get = function get(key) { return this.caches[key]; }; _proto.getKeys = function getKeys() { var keys = []; for (var key in this.caches) { keys.push(key); } return keys; }; return CacheStorage; }(); var global$3 = env.global; var TEST_KEY = 'RC_TEST_KEY'; var TEST_VALUE = 'RC_TEST_VALUE'; var isSupportLocalStorage = function isSupportLocalStorage() { var isSupport = false; var localStorage = global$3.localStorage; if (localStorage) { try { localStorage.setItem(TEST_KEY, TEST_VALUE); var testVal = localStorage.getItem(TEST_KEY); if (testVal === TEST_VALUE) { isSupport = true; } localStorage.removeItem(TEST_KEY); } catch (e) {} } return isSupport; }; var WebStorage = function () { function WebStorage() {} var _proto = WebStorage.prototype; _proto.set = function set(key, value) { global$3.localStorage.setItem(key, JSON$1.stringify({ d: value })); }; _proto.get = function get(key) { var value; var localValue = global$3.localStorage.getItem(key); try { localValue = JSON$1.parse(localValue); } catch (e) { localValue = {}; } if (localValue && localValue.d) { value = localValue.d; } return value; }; _proto.remove = function remove(key) { return global$3.localStorage.removeItem(key); }; _proto.getKeys = function getKeys() { var keyList = []; for (var key in global$3.localStorage) { keyList.push(key); } return keyList; }; return WebStorage; }(); var WebStorage$1 = isSupportLocalStorage() ? WebStorage : CacheStorage; var isMini$1 = env.isMini, isAppPlus$1 = env.isAppPlus; var Storage = isMini$1 || isAppPlus$1 ? storage : WebStorage$1, storage$1 = new Storage(); var global$4 = env.global; var TEST_KEY$1 = 'RC_TEST_KEY'; var TEST_VALUE$1 = 'RC_TEST_VALUE'; var isSupportSessionStorage = function isSupportSessionStorage() { var isSupport = false; var sessionStorage = global$4.sessionStorage; if (sessionStorage) { try { sessionStorage.setItem(TEST_KEY$1, TEST_VALUE$1); var testVal = sessionStorage.getItem(TEST_KEY$1); if (testVal === TEST_VALUE$1) { isSupport = true; } sessionStorage.removeItem(TEST_KEY$1); } catch (e) {} } return isSupport; }; var WebSession = function () { function WebSession() {} var _proto = WebSession.prototype; _proto.set = function set(key, value) { global$4.sessionStorage.setItem(key, JSON$1.stringify({ d: value })); }; _proto.get = function get(key) { var value; var localValue = global$4.sessionStorage.getItem(key); try { localValue = JSON$1.parse(localValue); } catch (e) { localValue = {}; } if (localValue && localValue.d) { value = localValue.d; } return value; }; _proto.remove = function remove(key) { return global$4.sessionStorage.removeItem(key); }; _proto.getKeys = function getKeys() { var keyList = []; for (var key in global$4.sessionStorage) { keyList.push(key); } return keyList; }; return WebSession; }(); var WebSession$1 = isSupportSessionStorage() ? WebSession : CacheStorage; var isMini$2 = env.isMini, isAppPlus$2 = env.isAppPlus; var Session = isMini$2 || isAppPlus$2 ? CacheStorage : WebSession$1, session = new Session(); var global$5 = env.global, isAppPlus$3 = env.isAppPlus; var Socket = function () { function Socket(options) { this.socket = void 0; if (isAppPlus$3) { options['complete'] = function () {}; } this.socket = global$5.connectSocket(options); } var _proto = Socket.prototype; _proto.send = function send(data) { this.socket.send({ data: data }); }; _proto.close = function close() { this.socket.close(); }; _proto.onOpen = function onOpen(callback) { this.socket.onOpen(callback); }; _proto.onMessage = function onMessage(callback) { this.socket.onMessage(callback); }; _proto.onError = function onError(callback) { this.socket.onError(callback); }; _proto.onClose = function onClose(callback) { this.socket.onClose(callback); }; return Socket; }(); var Socket$1 = function () { function Socket(options) { this.socket = void 0; var url = options.url; this.socket = new WebSocket(url); this.socket.binaryType = 'arraybuffer'; return this; } var _proto = Socket.prototype; _proto.send = function send(data) { return this.socket.send(data); }; _proto.close = function close() { this.socket.close(); }; _proto.onOpen = function onOpen(callback) { this.socket.addEventListener('open', callback); }; _proto.onMessage = function onMessage(callback) { this.socket.addEventListener('message', callback); }; _proto.onError = function onError(callback) { this.socket.addEventListener('error', callback); }; _proto.onClose = function onClose(callback) { this.socket.addEventListener('close', callback); }; return Socket; }(); var isMini$3 = env.isMini, isAppPlus$4 = env.isAppPlus; var Socket$2 = isMini$3 || isAppPlus$4 ? Socket : Socket$1; /*! 基于 es6-promise * Github: https://github.com/stefanpenner/es6-promise * @overview es6-promise - a tiny implementation of Promises/A+. * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald) * @license Licensed under MIT license * See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE * @version v4.2.8+1e68dce6 */ var SparePromise = (function(){function a(a){var b=typeof a;return null!==a&&("object"===b||"function"===b)}function b(a){return "function"==typeof a}function c(a){P=a;}function d(a){Q=a;}function e(){return function(){return process.nextTick(j)}}function f(){return "undefined"!=typeof O?function(){O(j);}:i()}function g(){var a=0,b=new T(j),c=document.createTextNode("");return b.observe(c,{characterData:!0}),function(){c.data=a=++a%2;}}function h(){var a=new MessageChannel;return a.port1.onmessage=j,function(){return a.port2.postMessage(0)}}function i(){var a=setTimeout;return function(){return a(j,1)}}function j(){var a,b,c;for(a=0;N>a;a+=2)b=W[a],c=W[a+1],b(c),W[a]=void 0,W[a+1]=void 0;N=0;}function k(){try{var a=Function("return this")().require("vertx");return O=a.runOnLoop||a.runOnContext,f()}catch(b){return i()}}function l(a,b){var e,f,c=this,d=new this.constructor(n);return void 0===d[Y]&&D(d),e=c._state,e?(f=arguments[e-1],Q(function(){return A(e,d,f,c._result)})):y(c,d,a,b),d}function m(a){var c,b=this;return a&&"object"==typeof a&&a.constructor===b?a:(c=new b(n),u(c,a),c)}function n(){}function o(){return new TypeError("You cannot resolve a promise with itself")}function p(){return new TypeError("A promises callback cannot return that same promise.")}function q(a,b,c,d){try{a.call(b,c,d);}catch(e){return e}}function r(a,b,c){Q(function(a){var d=!1,e=q(c,b,function(c){d||(d=!0,b!==c?u(a,c):w(a,c));},function(b){d||(d=!0,x(a,b));},"Settle: "+(a._label||" unknown promise"));!d&&e&&(d=!0,x(a,e));},a);}function s(a,b){b._state===$?w(a,b._result):b._state===_?x(a,b._result):y(b,void 0,function(b){return u(a,b)},function(b){return x(a,b)});}function t(a,c,d){c.constructor===a.constructor&&d===l&&c.constructor.resolve===m?s(a,c):void 0===d?w(a,c):b(d)?r(a,c,d):w(a,c);}function u(b,c){if(b===c)x(b,o());else if(a(c)){var d=void 0;try{d=c.then;}catch(e){return void x(b,e)}t(b,c,d);}else w(b,c);}function v(a){a._onerror&&a._onerror(a._result),z(a);}function w(a,b){a._state===Z&&(a._result=b,a._state=$,0!==a._subscribers.length&&Q(z,a));}function x(a,b){a._state===Z&&(a._state=_,a._result=b,Q(v,a));}function y(a,b,c,d){var e=a._subscribers,f=e.length;a._onerror=null,e[f]=b,e[f+$]=c,e[f+_]=d,0===f&&a._state&&Q(z,a);}function z(a){var d,e,f,g,b=a._subscribers,c=a._state;if(0!==b.length){for(d=void 0,e=void 0,f=a._result,g=0;gf;f++)b.resolve(a[f]).then(c,d);}:function(a,b){return b(new TypeError("You must pass an array to race."))})}function H(a){var b=this,c=new b(n);return x(c,a),c}function I(){throw new TypeError("You must pass a resolver function as the first argument to the promise constructor")}function J(){throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.")}function K(){var c,d,a=void 0;if("undefined"!=typeof global)a=global;else if("undefined"!=typeof self)a=self;else try{a=Function("return this")();}catch(b){throw new Error("polyfill failed because global object is unavailable in this environment")}if(c=a.Promise){d=null;try{d=Object.prototype.toString.call(c.resolve());}catch(b){}if("[object Promise]"===d&&!c.cast)return}a.Promise=cb;}var M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,$,_,ab,bb,cb,L=void 0;return L=Array.isArray?Array.isArray:function(a){return "[object Array]"===Object.prototype.toString.call(a)},M=L,N=0,O=void 0,P=void 0,Q=function(a,b){W[N]=a,W[N+1]=b,N+=2,2===N&&(P?P(j):X());},R="undefined"!=typeof window?window:void 0,S=R||{},T=S.MutationObserver||S.WebKitMutationObserver,U="undefined"==typeof self&&"undefined"!=typeof process&&"[object process]"==={}.toString.call(process),V="undefined"!=typeof Uint8ClampedArray&&"undefined"!=typeof importScripts&&"undefined"!=typeof MessageChannel,W=new Array(1e3),X=void 0,X=U?e():T?g():V?h():void 0===R&&"function"==typeof require?k():i(),Y=Math.random().toString(36).substring(2),Z=void 0,$=1,_=2,ab=0,bb=function(){function a(a,b){this._instanceConstructor=a,this.promise=new a(n),this.promise[Y]||D(this.promise),M(b)?(this.length=b.length,this._remaining=b.length,this._result=new Array(this.length),0===this.length?w(this.promise,this._result):(this.length=this.length||0,this._enumerate(b),0===this._remaining&&w(this.promise,this._result))):x(this.promise,E());}return a.prototype._enumerate=function(a){for(var b=0;this._state===Z&&b>16)+(b>>16)+(c>>16);return d<<16|65535&c}function b(a,b){return a<>>32-b}function c(c,d,e,f,g,h){return a(b(a(a(d,c),a(f,h)),g),e)}function d(a,b,d,e,f,g,h){return c(b&d|~b&e,a,b,f,g,h)}function e(a,b,d,e,f,g,h){return c(b&e|d&~e,a,b,f,g,h)}function f(a,b,d,e,f,g,h){return c(b^d^e,a,b,f,g,h)}function g(a,b,d,e,f,g,h){return c(d^(b|~e),a,b,f,g,h)}function h(b,c){var h,i,j,k,l,m,n,o,p;for(b[c>>5]|=128<>>9<<4)+14]=c,m=1732584193,n=-271733879,o=-1732584194,p=271733878,h=0;hb;b+=8)c+=String.fromCharCode(255&a[b>>5]>>>b%32);return c}function j(a){var b,d,c=[];for(c[(a.length>>2)-1]=void 0,b=0;bb;b+=8)c[b>>5]|=(255&a.charCodeAt(b/8))<16&&(d=h(d,8*a.length)),c=0;16>c;c+=1)e[c]=909522486^d[c],f[c]=1549556828^d[c];return g=h(e.concat(j(b)),512+8*b.length),i(h(f.concat(g),640))}function m(a){var d,e,b="0123456789abcdef",c="";for(e=0;e>>4)+b.charAt(15&d);return c}function n(a){return unescape(encodeURIComponent(a))}function o(a){return k(n(a))}function p(a){return m(o(a))}function q(a,b){return l(n(a),n(b))}function r(a,b){return m(q(a,b))}function s(a,b,c){return b?c?q(b,a):r(b,a):c?o(a):p(a)}return s})(); var global$8 = env.global; var Promise$1 = global$8.Promise; var isSupportPromise = function isSupportPromise() { if (!global$8.Promise) return false; var defer = function () { return global$8.Promise.resolve(); }(); return defer.then && defer["catch"] && defer["finally"]; }; var setTimeout$1 = function setTimeout(event, timeout) { return global$8.setTimeout(event, timeout); }; var clearTimeout$1 = function clearTimeout(id) { return global$8.clearTimeout(id); }; var setInterval$1 = function setInterval(event, timeout) { return global$8.setInterval(event, timeout); }; var clearInterval$1 = function clearInterval(id) { return global$8.clearInterval(id); }; var Defer = isSupportPromise() ? global$8.Promise : SparePromise; var noop = function noop(data) { return data; }; var deferNoop = function deferNoop(data) { return Promise$1.resolve(data); }; var JSON$2 = global$8.JSON || JSON$1; var allowError = function allowError(event) { var result; try { for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } result = event.apply(void 0, args); } catch (e) { result = null; } return result; }; var toJSON = function toJSON(val) { return allowError(JSON$2.stringify, val); }; var parseJSON = function parseJSON(val) { return allowError(JSON$2.parse, val); }; var copy = function copy(val) { return parseJSON(toJSON(val)); }; var isObject = function isObject(val) { return Object.prototype.toString.call(val) === '[object Object]'; }; var isArray = function isArray(val) { return Object.prototype.toString.call(val).indexOf('Array') !== -1; }; var isFunction = function isFunction(val) { return Object.prototype.toString.call(val) === '[object Function]'; }; var isString = function isString(val) { return Object.prototype.toString.call(val) === '[object String]'; }; var isBoolean = function isBoolean(val) { return Object.prototype.toString.call(val) === '[object Boolean]'; }; var isUndefined = function isUndefined(val) { return val === undefined || Object.prototype.toString.call(val) === '[object Undefined]'; }; var isNull = function isNull(val) { return Object.prototype.toString.call(val) === '[object Null]'; }; var isNumber = function isNumber(val) { return Object.prototype.toString.call(val) === '[object Number]'; }; var isArrayBuffer = function isArrayBuffer(val) { return Object.prototype.toString.call(val) === '[object ArrayBuffer]'; }; var isPromise = function isPromise(val) { var isTrue = false; try { isTrue = Object.prototype.toString.call(val) === '[object Promise]' || val && val.then && val["catch"] && val["finally"]; } catch (e) { isTrue = false; } return isTrue; }; var getTypeName = function getTypeName(data) { var typeName = Object.prototype.toString.call(data); return typeName.substring(8, typeName.length - 1); }; var isEqual = function isEqual(source, target) { return source === target; }; var ArrayBufferToArray = function ArrayBufferToArray(data) { if (isArrayBuffer(data)) { return [].slice.call(new Int8Array(data)); } return data; }; var ArrayBufferToUint8Array = function ArrayBufferToUint8Array(data) { if (isArrayBuffer(data)) { return new Uint8Array(data); } return data; }; var forEach = function forEach(source, event, options) { options = options || {}; event = event || noop; var _options = options, isReverse = _options.isReverse; var loopObj = function loopObj() { for (var key in source) { event(source[key], key, source); } }; var loopArr = function loopArr() { if (isReverse) { for (var i = source.length - 1; i >= 0; i--) { event(source[i], i); } } else { for (var j = 0, len = source.length; j < len; j++) { event(source[j], j); } } }; if (isObject(source)) { loopObj(); } if (isArray(source) || isString(source)) { loopArr(); } }; var isFalse = function isFalse(val) { return val === false; }; var isEmpty = function isEmpty(val) { var result = true; if (isObject(val)) { forEach(val, function () { result = false; }); } if (isString(val) || isArray(val)) { result = val.length === 0; } if (isNumber(val)) { result = val === 0; } return result; }; var isNumberData = function isNumberData(val) { var isEmptyVal = isEmpty(val); val = Number(val); return isNumber(val) && !isEmptyVal; }; var getKeys = function getKeys(obj) { var keyList = []; forEach(obj, function (val, key) { keyList.push(key); }); return keyList; }; var getValues = function getValues(obj) { var valList = []; forEach(obj, function (val) { valList.push(val); }); return valList; }; var getTimestamp = function getTimestamp(time) { return new Date(time).getTime(); }; var getCurrentTimestamp = function getCurrentTimestamp() { return new Date().getTime(); }; var formatTime = function formatTime(timestamp, options) { timestamp = timestamp || getCurrentTimestamp(); options = options || {}; var temp = options.temp; var date = new Date(timestamp), formateds = {}; formateds['YY'] = date.getFullYear(); formateds['MM'] = date.getMonth() + 1; formateds['DD'] = date.getDate(); formateds['hh'] = date.getHours(); formateds['mm'] = date.getMinutes(); formateds['ss'] = date.getSeconds(); forEach(formateds, function (val, key) { formateds[key] = val >= 10 ? val : '0' + val; }); if (temp) { var formatedText = temp; forEach(formateds, function (val, key) { formatedText = formatedText.replace(key, val); }); return formatedText; } return formateds.YY + '-' + formateds.MM + '-' + formateds.DD + ' ' + formateds.hh + ':' + formateds.mm + ':' + formateds.ss; }; var isValidJSON = function isValidJSON(jsonStr) { if (isObject(jsonStr)) { return true; } var isValid = false; try { var obj = JSON$2.parse(jsonStr); var str = JSON$2.stringify(obj); isValid = str === jsonStr; } catch (e) { isValid = false; } return isValid; }; var isSupportSocket = function isSupportSocket() { var isMini = env.isMini; var isAppPlus = env.isAppPlus; if (isMini || isAppPlus) { return true; } var Socket = global$8.WebSocket; if (isUndefined(Socket)) { return false; } var hasWS = false, isIntegrity = false; try { hasWS = typeof Socket === 'object' || typeof Socket === 'function'; isIntegrity = typeof Socket.OPEN === 'number'; } catch (e) {} return hasWS && isIntegrity; }; var indexOf = function indexOf(source, searchVal) { if (source.indexOf) { return source.indexOf(searchVal); } var index = -1; forEach(source, function (sub, i) { if (searchVal === sub) { index = i; return; } }); return index; }; var lastIndexOf = function lastIndexOf(source, searchVal) { if (source.lastIndexOf) { return source.lastIndexOf(searchVal); } var index = -1; forEach(source, function (sub, i) { if (searchVal === sub) { index = i; return; } }, { isReverse: true }); return index; }; var isInclude = function isInclude(source, searchVal) { if (isObject(source)) { var arr = []; forEach(source, function (val) { arr.push(val); }); source = arr; } var index = indexOf(source, searchVal); return index !== -1; }; var substring = function substring(source, start, end) { return source.substring(start, end); }; var spliceByChild = function spliceByChild(arr, item) { forEach(arr, function (child, index) { if (isEqual(child, item)) { arr.splice(index, 1); } }, { isReverse: true }); }; var parse16To10 = function parse16To10(num) { return parseInt(num, 16); }; var isPlus = function isPlus(num) { return +num === num; }; var filter = function filter(source, event) { var newArr = []; for (var i = 0, max = source.length; i < max; i++) { var data = source[i]; if (event(data, i)) { newArr.push(data); } } return newArr; }; var map = function map(source, event) { forEach(source, function (item, index) { source[index] = event(item, index); }); return source; }; var extend = function extend(destination, sources, option) { option = option || {}; var _option2 = option, isAllowNull = _option2.isAllowNull; destination = destination || {}; sources = sources || {}; for (var key in sources) { var value = sources[key]; if (!isUndefined(value) || isAllowNull) { destination[key] = value; } } return destination; }; var extendAllowNull = function extendAllowNull(destination, sources) { return extend(destination, sources, { isAllowNull: true }); }; var extendInShallow = function extendInShallow(destination, sources) { destination = destination || {}; sources = sources || {}; destination = copy(destination); sources = copy(sources); return extend(destination, sources); }; var deferred = function deferred(callbacks) { return new Defer(callbacks); }; var deferTimeout = function deferTimeout(timeout) { return deferred(function (resolve) { var timeouter = setTimeout$1(function () { resolve(timeouter); }, timeout); }); }; var tplEngine = function tplEngine(temp, data, regexp) { var replaceAction = function replaceAction(obj) { return temp.replace(regexp || /{([^}]+)}/g, function (match, name) { if (match.charAt(0) === '\\') { return match.slice(1); } return obj[name] !== undefined ? obj[name] : '{' + name + '}'; }); }; if (!isArray(data)) { data = [data]; } var ret = []; forEach(data, function (item) { ret.push(replaceAction(item)); }); return ret.join(''); }; var getRandomNum = function getRandomNum(max, min) { min = min || 0; var range = max - min, random = Math.random(); return min + Math.round(random * range); }; var Timer = function () { function Timer(options) { this._timerId = void 0; this._timerEvent = void 0; this._timerClearEvent = void 0; this.timeout = 0; this.type = TIMER_TYPE.TIMEOUT; this.status = TIMER_STATUS.PENNDING; var self = this; extend(self, options); var type = self.type; var isTimeout = type === TIMER_TYPE.TIMEOUT; if (isTimeout) { self._timerEvent = setTimeout$1; self._timerClearEvent = clearTimeout$1; } else { self._timerEvent = setInterval$1; self._timerClearEvent = clearInterval$1; } return self; } var _proto = Timer.prototype; _proto.start = function start(event, options) { options = options || {}; var self = this, isTimeout = self.type === TIMER_TYPE.TIMEOUT; var _options2 = options, args = _options2.args, thisArg = _options2.thisArg; self.stop(); self._timerId = self._timerEvent.call(global$8, function () { isTimeout && self.stop(); if (thisArg) { event.apply(thisArg, args); } else { event(args); } }, self.timeout); self.status = TIMER_STATUS.BUSY; }; _proto.stop = function stop() { var self = this; if (self._timerId) { self._timerClearEvent.call(global$8, self._timerId); self.status = TIMER_STATUS.ENDING; } }; return Timer; }(); var DeferHandler = function () { function DeferHandler(options) { this._list = {}; this.timeout = IM_TIMEOUT; extend(this, options); } var _proto2 = DeferHandler.prototype; _proto2._isInvalid = function _isInvalid(id) { var handlers = this._list[id]; return !isArray(handlers) || isEmpty(handlers); }; _proto2._exec = function _exec(id, isError, data) { var self = this; if (self._isInvalid(id)) { return; } var handlers = self._list[id], handler = handlers[0]; isError ? handler.reject(data) : handler.resolve(data); handlers.splice(0, 1); }; _proto2.add = function add(id, defer, options) { options = options || {}; var self = this; var resolve = defer.resolve, reject = defer.reject; var timeout = options.timeout || self.timeout; if (self._isInvalid(id)) { self._list[id] = []; } var timer = new Timer({ timeout: timeout }); timer.start(function () { self.reject(id, ERROR_INFO.TIMEOUT.code); }); self._list[id].push({ resolve: resolve, reject: reject, timer: timer }); }; _proto2.resolve = function resolve(id, data) { this._exec(id, false, data); }; _proto2.reject = function reject(id, error) { this._exec(id, true, error); }; return DeferHandler; }(); var EventEmitter = function () { function EventEmitter() { this._events = void 0; this._events = {}; } var _proto3 = EventEmitter.prototype; _proto3.on = function on(name, event) { var _events = this._events[name] || []; _events.push(event); this._events[name] = _events; }; _proto3.off = function off(name, offEvent) { if (offEvent) { var _events = this._events[name] || []; spliceByChild(_events, offEvent); } else { delete this._events[name]; } }; _proto3.emit = function emit(name, data, error) { var _events = this._events[name]; forEach(_events, function (event) { isFunction(event) && event(data, error); }); }; _proto3.clear = function clear() { this._events = {}; }; return EventEmitter; }(); var decodeURI = function decodeURI(uri) { return global$8.decodeURIComponent(uri); }; var encodeURI = function encodeURI(uri) { return global$8.encodeURIComponent(uri); }; var int64ToTimestamp = function int64ToTimestamp(obj) { if (!isObject(obj) || obj.low === undefined || obj.high === undefined) { return obj; } var low = obj.low; if (low < 0) { low += 0xffffffff + 1; } low = low.toString(16); var timestamp = parseInt(obj.high.toString(16) + '00000000'.replace(new RegExp('0{' + low.length + '}$'), low), 16); return timestamp; }; var batchInt64ToTimestamp = function batchInt64ToTimestamp(data) { forEach(data, function (item, key) { if (isObject(item)) { data[key] = int64ToTimestamp(item); } }); return data; }; var Queue = function () { function Queue(defaultConfig) { this._isRunning = false; this._list = []; this._defaultConfig = void 0; this._defaultConfig = defaultConfig; } var _proto4 = Queue.prototype; _proto4.add = function add(params) { params = params || this._defaultConfig; this._list.push(params); this.run(); }; _proto4.run = function run() { var self = this; var _isRunning = self._isRunning, _list = self._list; var isFinished = isEmpty(_list); if (_isRunning || isFinished) { return; } var firstItem = _list.splice(0, 1)[0]; var event = firstItem.event, args = firstItem.args, thisArg = firstItem.thisArg; var next = function next() { self._isRunning = false; self.run(); }; if (!event) { return next(); } self._isRunning = true; event.apply(thisArg, args).then(next)["catch"](next); }; return Queue; }(); var secondsToMilliseconds = function secondsToMilliseconds(seconds) { return seconds * 1000; }; var request$2 = function request(url, options) { options = options || {}; return deferred(function (resolve, reject) { options = extend(options, { url: url, success: function success(responseText, xhr, status) { resolve({ responseText: responseText, xhr: xhr, status: status }); }, fail: function fail(result, xhr, status) { reject({ result: result, xhr: xhr, status: status }); } }); request$1(options); }); }; var requestByUrlList = function requestByUrlList(urlList, options) { if (isEmpty(urlList)) { return Defer.reject(); } var url = urlList[0]; var fixedNaviResp = { 'responseText': '{"isFixedNaviResp":true}' }; return request$2(url, options).then(function (result) { result = result || {}; result.urlList = urlList; return result; })["catch"](function () { urlList.splice(0, 1); if (isEmpty(urlList)) { return fixedNaviResp; } else { return requestByUrlList(urlList, options); } }); }; var requestForFaster = function requestForFaster(urlList, option) { option = option || {}; var timeInterval = option.timeInterval || 0; var faildCount = 0, totalCount = urlList.length; var requestXhrs = []; var totalTimer = new Timer({ timeout: 15 * 1000 }); var reqCountdownTimers = []; var clearAll = function clearAll() { forEach(reqCountdownTimers, function (timer) { timer.stop(); }); forEach(requestXhrs, function (xhr) { xhr.abort(); }); reqCountdownTimers.length = 0; requestXhrs.length = 0; }; var isAllFaild = function isAllFaild() { return faildCount === totalCount; }; return deferred(function (resolve, reject) { var _success = function success(url, index) { clearAll(); resolve({ url: url, index: index }); }; var _fail = function fail() { clearAll(); reject(); }; forEach(urlList, function (url, index) { var timer = new Timer({ timeout: timeInterval * index }); timer.start(function () { var xhr; var opt = extend({ url: url, success: function success() { _success(url, index); }, fail: function fail() { faildCount++; isAllFaild() && _fail(); } }, option); xhr = request$1(opt); requestXhrs.push(xhr); }); reqCountdownTimers.push(timer); }); totalTimer.start(_fail); }); }; var NetworkDetecter = function () { function NetworkDetecter(option) { this._option = void 0; this._detectCount = 0; this._timeoutId = void 0; this._option = option; } var _proto5 = NetworkDetecter.prototype; _proto5._detect = function _detect() { var self = this; var _detectCount = self._detectCount, _option = self._option; var url = _option.url, timeout = _option.intervalTime, max = _option.max; _detectCount++; return request$2(url).then(function () { return; }, function (_ref) { var status = _ref.status; if (isEqual(status, 404)) { return; } var isAlreadyMax = max && isEqual(max, _detectCount); if (isAlreadyMax) { return Defer.reject(); } return deferTimeout(timeout).then(function (timeoutId) { self._detectCount = _detectCount; self._timeoutId = timeoutId; return self._detect(); }); }); }; _proto5.start = function start() { return this._detect(); }; _proto5.stop = function stop() { var timeoutId = this._timeoutId; if (timeoutId) { clearTimeout$1(timeoutId); } }; return NetworkDetecter; }(); var toUpperCase = function toUpperCase(str, startIndex, endIndex) { if (isUndefined(startIndex) || isUndefined(endIndex)) { return str.toUpperCase(); } var sliceStr = str.slice(startIndex, endIndex); str = str.replace(sliceStr, function (text) { return text.toUpperCase(); }); return str; }; var getDomainByUrl = function getDomainByUrl(url) { var StartMark = '://', EndMark = '/'; var urlProtocolIndex = indexOf(url, StartMark); var hasProtocol = urlProtocolIndex > -1; if (hasProtocol) { urlProtocolIndex = urlProtocolIndex + StartMark.length; url = substring(url, urlProtocolIndex, url.length); } var urlPathIndex = indexOf(url, EndMark); var hasPath = urlPathIndex > -1; if (hasPath) { url = substring(url, 0, urlPathIndex); } return url; }; var getValidUrl = function getValidUrl(url, option) { option = option || {}; var ProtocolMark = '://'; var hasProtocol = isInclude(url, ProtocolMark); var localProtocol = env.protocol.http; var _option3 = option, protocol = _option3.protocol; if (protocol) { var domain = getDomainByUrl(url); url = protocol + "//" + domain; } if (hasProtocol) { var urlProtocolIndex = indexOf(url, ProtocolMark) + 1; var urlProtocol = substring(url, 0, urlProtocolIndex); var isHttpUrl = urlProtocol === HTTP_PROTOCOL.HTTP; var isLocalHttps = localProtocol === HTTP_PROTOCOL.HTTPS; if (isHttpUrl && isLocalHttps) { var _domain = getDomainByUrl(url); return HTTP_PROTOCOL.HTTPS + "//" + _domain; } else { return url; } } else { return localProtocol + "//" + url; } }; var quickSort = function quickSort(arr, event) { var sort = function sort(array, left, right, event) { event = event || function (a, b) { return a <= b; }; if (left < right) { var x = array[right], i = left - 1, temp; for (var j = left; j <= right; j++) { if (event(array[j], x)) { i++; temp = array[i]; array[i] = array[j]; array[j] = temp; } } sort(array, left, i - 1, event); sort(array, i + 1, right, event); } return array; }; return sort(arr, 0, arr.length - 1, event); }; var unique = function unique(arr, event) { var keyEvent = event || function (data) { return data; }; var hashTable = {}; var newArr = []; forEach(arr, function (data) { var key = keyEvent(data); if (!hashTable[key]) { hashTable[key] = true; newArr.push(data); } }); return newArr; }; var isStackError = function isStackError(error) { error = error || {}; return error.stack && error.stack.toString; }; var consoleError = function consoleError() { var _console; return (_console = console).error.apply(_console, arguments); }; var consoleLog = function consoleLog() { var _console2; return (_console2 = console).log.apply(_console2, arguments); }; var string10to64 = function string10to64(number) { var chars = '0123456789abcdefghigklmnopqrstuvwxyzABCDEFGHIGKLMNOPQRSTUVWXYZa0'.split(''), radix = chars.length + 1, qutient = +number, arr = []; do { var mod = qutient % radix; qutient = (qutient - mod) / radix; arr.unshift(chars[mod]); } while (qutient); return arr.join(''); }; var getUUID = function getUUID() { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { var r = Math.random() * 16 | 0, v = c === 'x' ? r : r & 0x3 | 0x8; return v.toString(16); }); }; var getUUID22 = function getUUID22() { var uuid = getUUID(); uuid = uuid.replace(/-/g, '') + 'a'; uuid = parseInt(uuid, 16); uuid = string10to64(uuid); if (uuid.length > 22) { uuid = uuid.slice(0, 22); } else { var len = 22 - uuid.length; for (var i = 0; i < len; i++) { uuid = uuid + '0'; } } return uuid; }; var isValidTimestamp = function isValidTimestamp(time) { return isNumber(time) && time !== 0; }; var formateDate = function formateDate(seperator) { var date = new Date(); var year = date.getFullYear(); var month = date.getMonth() + 1; var day = date.getDate(); return tplEngine('{year}{seperator}{month}{seperator}{day}', { year: year, month: month, day: day, seperator: seperator }); }; var utils = { Storage: storage$1, Session: session, Socket: Socket$2, Cache: CacheStorage, JSON: JSON$2, Defer: Defer, httpRequest: request$1, request: request$2, requestByUrlList: requestByUrlList, requestForFaster: requestForFaster, md5: md5, DeferHandler: DeferHandler, EventEmitter: EventEmitter, Timer: Timer, Queue: Queue, consoleError: consoleError, consoleLog: consoleLog, noop: noop, deferNoop: deferNoop, setTimeout: setTimeout$1, toJSON: toJSON, parseJSON: parseJSON, copy: copy, isObject: isObject, isArray: isArray, isFunction: isFunction, isArrayBuffer: isArrayBuffer, isString: isString, isBoolean: isBoolean, isUndefined: isUndefined, isNull: isNull, isNumber: isNumber, isNumberData: isNumberData, isPromise: isPromise, getTypeName: getTypeName, isPlus: isPlus, isEmpty: isEmpty, isFalse: isFalse, isEqual: isEqual, isValidJSON: isValidJSON, isSupportSocket: isSupportSocket, ArrayBufferToArray: ArrayBufferToArray, ArrayBufferToUint8Array: ArrayBufferToUint8Array, indexOf: indexOf, lastIndexOf: lastIndexOf, isInclude: isInclude, substring: substring, getKeys: getKeys, getValues: getValues, getTimestamp: getTimestamp, getCurrentTimestamp: getCurrentTimestamp, formatTime: formatTime, parse16To10: parse16To10, forEach: forEach, map: map, filter: filter, extend: extend, extendAllowNull: extendAllowNull, extendInShallow: extendInShallow, deferred: deferred, tplEngine: tplEngine, getRandomNum: getRandomNum, int64ToTimestamp: int64ToTimestamp, batchInt64ToTimestamp: batchInt64ToTimestamp, encodeURI: encodeURI, decodeURI: decodeURI, secondsToMilliseconds: secondsToMilliseconds, NetworkDetecter: NetworkDetecter, toUpperCase: toUpperCase, getDomainByUrl: getDomainByUrl, getValidUrl: getValidUrl, quickSort: quickSort, unique: unique, isStackError: isStackError, getUUID: getUUID, getUUID22: getUUID22, isValidTimestamp: isValidTimestamp, formateDate: formateDate }; function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } var _PUBLISH_TOPIC_TO_CON, _CONVERSATION_TYPE_TO, _CONVERSATION_TYPE_TO2, _CONVERSATION_TYPE_TO3, _CONVERSATION_TYPE_TO4; var SUCCESS_CODE = 0; var PULL_MSG_TYPE = { NORMAL: 1, CHATROOM: 2 }; var MESSAGE_NAME = { CONN_ACK: 'ConnAckMessage', DISCONNECT: 'DisconnectMessage', PING_REQ: 'PingReqMessage', PING_RESP: 'PingRespMessage', PUBLISH: 'PublishMessage', PUB_ACK: 'PubAckMessage', QUERY: 'QueryMessage', QUERY_CON: 'QueryConMessage', QUERY_ACK: 'QueryAckMessage' }; var QOS = { AT_MOST_ONCE: 0, AT_LEAST_ONCE: 1, EXACTLY_ONCE: 2, DEFAULT: 3, '0': 'AT_MOST_ONCE', '1': 'AT_LEAST_ONCE', '2': 'EXACTLY_ONCE', '3': 'DEFAULT' }; var OPERATE_TYPE = { CONNECT: 1, '1': 'CONNECT', CONNACK: 2, '2': 'CONNACK', PUBLISH: 3, '3': 'PUBLISH', PUBACK: 4, '4': 'PUBACK', QUERY: 5, '5': 'QUERY', QUERYACK: 6, '6': 'QUERYACK', QUERYCON: 7, '7': 'QUERYCON', SUBSCRIBE: 8, '8': 'SUBSCRIBE', SUBACK: 9, '9': 'SUBACK', UNSUBSCRIBE: 10, '10': 'UNSUBSCRIBE', UNSUBACK: 11, '11': 'UNSUBACK', PINGREQ: 12, '12': 'PINGREQ', PINGRESP: 13, '13': 'PINGRESP', DISCONNECT: 14, '14': 'DISCONNECT' }; var MESSAGE_TAG = { NONE: 0, PERSIT_ONLY: 1, COUNT_ONLY: 2, PERSIT_AND_COUNT: 3 }; var PUBLISH_TOPIC = { PRIVATE: 'ppMsgP', GROUP: 'pgMsgP', CHATROOM: 'chatMsg', CUSTOMER_SERVICE: 'pcMsgP', RECALL: 'recallMsg', NOTIFY_PULL_MSG: 's_ntf', RECEIVE_MSG: 's_msg', SYNC_STATUS: 's_stat', SERVER_NOTIFY: 's_cmd', SETTING_NOTIFY: 's_us' }; var PUBLISH_STATUS_TOPIC = { PRIVATE: 'ppMsgS', GROUP: 'pgMsgS', CHATROOM: 'chatMsgS' }; var QUERY_TOPIC = { GET_SYNC_TIME: 'qrySessionsAtt', PULL_MSG: 'pullMsg', GET_CONVERSATION_LIST: 'qrySessions', REMOVE_CONVERSATION_LIST: 'delSessions', DELETE_MESSAGES: 'delMsg', CLEAR_UNREAD_COUNT: 'updRRTime', PULL_USER_SETTING: 'pullUS', PULL_CHRM_MSG: 'chrmPull', JOIN_CHATROOM: 'joinChrm', JOIN_EXIST_CHATROOM: 'joinChrmR', QUIT_CHATROOM: 'exitChrm', GET_CHATROOM_INFO: 'queryChrmI', UPDATE_CHATROOM_KV: 'setKV', DELETE_CHATROOM_KV: 'delKV', PULL_CHATROOM_KV: 'pullKV', GET_OLD_CONVERSATION_LIST: 'qryRelation', REMOVE_OLD_CONVERSATION: 'delRelation', GET_CONVERSATION_STATUS: 'pullSeAtts', SET_CONVERSATION_STATUS: 'setSeAtt', GET_UPLOAD_FILE_TOKEN: 'qnTkn', GET_UPLOAD_FILE_URL: 'qnUrl', CLEAR_MESSAGES: { PRIVATE: 'cleanPMsg', GROUP: 'cleanGMsg', CUSTOMER_SERVICE: 'cleanCMsg', SYSTEM: 'cleanSMsg' }, JOIN_RTC_ROOM: 'rtcRJoin_data', QUIT_RTC_ROOM: 'rtcRExit', PING_RTC: 'rtcPing', SET_RTC_DATA: 'rtcSetData', USER_SET_RTC_DATA: 'userSetData', GET_RTC_DATA: 'rtcQryData', DEL_RTC_DATA: 'rtcDelData', SET_RTC_OUT_DATA: 'rtcSetOutData', GET_RTC_OUT_DATA: 'rtcQryUserOutData', GET_RTC_TOKEN: 'rtcToken', SET_RTC_STATE: 'rtcUserState', GET_RTC_ROOM_INFO: 'rtcRInfo', GET_RTC_USER_INFO_LIST: 'rtcUData', SET_RTC_USER_INFO: 'rtcUPut', DEL_RTC_USER_INFO: 'rtcUDel', GET_RTC_USER_LIST: 'rtcUList' }; var QUERY_HISTORY_TOPIC = { PRIVATE: 'qryPMsg', GROUP: 'qryGMsg', CHATROOM: 'qryCHMsg', CUSTOMER_SERVICE: 'qryCMsg', SYSTEM: 'qrySMsg' }; var SERVER_NOTIFY_TYPE = { KV_CHANGED: 2, CONVERSATION_STATUS_CHANGED: 3 }; var CHATROOM_KV_STATUS_CODE = { AUTO_DELETE: 0x0001, OVERWRITE: 0x0002, OPERATE: 0x0004 }; var PUBLISH_TOPIC_TO_CONVERSATION_TYPE = (_PUBLISH_TOPIC_TO_CON = {}, _PUBLISH_TOPIC_TO_CON[PUBLISH_TOPIC.PRIVATE] = CONVERSATION_TYPE.PRIVATE, _PUBLISH_TOPIC_TO_CON[PUBLISH_TOPIC.GROUP] = CONVERSATION_TYPE.GROUP, _PUBLISH_TOPIC_TO_CON[PUBLISH_TOPIC.CHATROOM] = CONVERSATION_TYPE.CHATROOM, _PUBLISH_TOPIC_TO_CON[PUBLISH_TOPIC.CUSTOMER_SERVICE] = CONVERSATION_TYPE.CUSTOMER_SERVICE, _PUBLISH_TOPIC_TO_CON[PUBLISH_STATUS_TOPIC.PRIVATE] = CONVERSATION_TYPE.PRIVATE, _PUBLISH_TOPIC_TO_CON[PUBLISH_STATUS_TOPIC.GROUP] = CONVERSATION_TYPE.GROUP, _PUBLISH_TOPIC_TO_CON[PUBLISH_STATUS_TOPIC.CHATROOM] = CONVERSATION_TYPE.CHATROOM, _PUBLISH_TOPIC_TO_CON); var CONVERSATION_TYPE_TO_PUBLISH_TOPIC = (_CONVERSATION_TYPE_TO = {}, _CONVERSATION_TYPE_TO[CONVERSATION_TYPE.PRIVATE] = PUBLISH_TOPIC.PRIVATE, _CONVERSATION_TYPE_TO[CONVERSATION_TYPE.GROUP] = PUBLISH_TOPIC.GROUP, _CONVERSATION_TYPE_TO[CONVERSATION_TYPE.CHATROOM] = PUBLISH_TOPIC.CHATROOM, _CONVERSATION_TYPE_TO[CONVERSATION_TYPE.CUSTOMER_SERVICE] = PUBLISH_TOPIC.CUSTOMER_SERVICE, _CONVERSATION_TYPE_TO); var CONVERSATION_TYPE_TO_PUBLISH_STATUS_TOPIC = (_CONVERSATION_TYPE_TO2 = {}, _CONVERSATION_TYPE_TO2[CONVERSATION_TYPE.PRIVATE] = PUBLISH_STATUS_TOPIC.PRIVATE, _CONVERSATION_TYPE_TO2[CONVERSATION_TYPE.GROUP] = PUBLISH_STATUS_TOPIC.GROUP, _CONVERSATION_TYPE_TO2); var CONVERSATION_TYPE_TO_QUERY_HISTORY_TOPIC = (_CONVERSATION_TYPE_TO3 = {}, _CONVERSATION_TYPE_TO3[CONVERSATION_TYPE.PRIVATE] = QUERY_HISTORY_TOPIC.PRIVATE, _CONVERSATION_TYPE_TO3[CONVERSATION_TYPE.GROUP] = QUERY_HISTORY_TOPIC.GROUP, _CONVERSATION_TYPE_TO3[CONVERSATION_TYPE.CHATROOM] = QUERY_HISTORY_TOPIC.CHATROOM, _CONVERSATION_TYPE_TO3[CONVERSATION_TYPE.CUSTOMER_SERVICE] = QUERY_HISTORY_TOPIC.CUSTOMER_SERVICE, _CONVERSATION_TYPE_TO3[CONVERSATION_TYPE.SYSTEM] = QUERY_HISTORY_TOPIC.SYSTEM, _CONVERSATION_TYPE_TO3); var CONVERSATION_TYPE_TO_CLEAR_MESSAGE_TOPIC = (_CONVERSATION_TYPE_TO4 = {}, _CONVERSATION_TYPE_TO4[CONVERSATION_TYPE.PRIVATE] = QUERY_TOPIC.CLEAR_MESSAGES.PRIVATE, _CONVERSATION_TYPE_TO4[CONVERSATION_TYPE.GROUP] = QUERY_TOPIC.CLEAR_MESSAGES.GROUP, _CONVERSATION_TYPE_TO4[CONVERSATION_TYPE.CUSTOMER_SERVICE] = QUERY_TOPIC.CLEAR_MESSAGES.CUSTOMER_SERVICE, _CONVERSATION_TYPE_TO4[CONVERSATION_TYPE.SYSTEM] = QUERY_TOPIC.CLEAR_MESSAGES.SYSTEM, _CONVERSATION_TYPE_TO4); var USER_SETTING_STATUS = { ADD: 1, UPDATE: 2, DELETE: 3 }; var CONVERSATION_STATUS_CONFIG = { ENABLED: '1', DISABLED: '0' }; var CONVERSATION_STATUS_TYPE = { DO_NOT_DISTURB: 1, TOP: 2 }; var Header = function () { function Header(_type, _retain, _qos, _dup) { this.type = void 0; this.retain = false; this.qos = QOS.AT_LEAST_ONCE; this.dup = false; this.syncMsg = false; var isPlusType = utils.isPlus(_type); if (_type && isPlusType && arguments.length === 1) { this.retain = (_type & 1) > 0; this.qos = (_type & 6) >> 1; this.dup = (_type & 8) > 0; this.type = _type >> 4 & 15; this.syncMsg = (_type & 8) === 8; } else { this.type = _type; this.retain = _retain === undefined ? false : _retain; this.qos = _qos === undefined ? QOS.AT_LEAST_ONCE : _qos; this.dup = _dup === undefined ? false : _dup; } } var _proto = Header.prototype; _proto.encode = function encode() { var self = this; var validQosList = [QOS.AT_MOST_ONCE, QOS.AT_LEAST_ONCE, QOS.EXACTLY_ONCE, QOS.DEFAULT]; utils.forEach(validQosList, function (qos) { if (self.qos === QOS[qos]) { self.qos = qos; } }); var _byte = self.type << 4; _byte |= self.retain ? 1 : 0; _byte |= self.qos << 1; _byte |= self.dup ? 8 : 0; return _byte; }; return Header; }(); var BinaryHelper = { writeUTF: function writeUTF(str, isGetBytes) { var back = [], byteSize = 0; utils.forEach(str, function (_char, i) { var code = str.charCodeAt(i); if (code >= 0 && code <= 127) { byteSize += 1; back.push(code); } else if (code >= 128 && code <= 2047) { byteSize += 2; back.push(192 | 31 & code >> 6); back.push(128 | 63 & code); } else if (code >= 2048 && code <= 65535) { byteSize += 3; back.push(224 | 15 & code >> 12); back.push(128 | 63 & code >> 6); back.push(128 | 63 & code); } }); utils.forEach(back, function (_char2, i) { if (_char2 > 255) { back[i] &= 255; } }); if (isGetBytes) { return back; } if (byteSize <= 255) { return [0, byteSize].concat(back); } else { return [byteSize >> 8, byteSize & 255].concat(back); } }, readUTF: function readUTF(arr) { var UTF = ''; for (var i = 0, len = arr.length; i < len; i++) { var _char3 = arr[i]; if (_char3 < 0) { arr[i] += 256; } var one = arr[i].toString(2), v = one.match(/^1+?(?=0)/); if (v && one.length === 8) { var bytesLength = v[0].length, store = ''; for (var st = 0; st < bytesLength; st++) { store += arr[st + i].toString(2).slice(2); } UTF += String.fromCharCode(parseInt(store, 2)); i += bytesLength - 1; } else { UTF += String.fromCharCode(arr[i]); } } return UTF; } }; var RongStreamReader = function () { function RongStreamReader(arr) { this.pool = void 0; this.position = 0; this.poolLen = 0; this.pool = arr; this.poolLen = arr.length; } var _proto2 = RongStreamReader.prototype; _proto2.check = function check() { return this.position >= this.pool.length; }; _proto2.readInt = function readInt() { var self = this; if (self.check()) { return -1; } var end = ''; for (var i = 0; i < 4; i++) { var t = self.pool[self.position++].toString(16); if (t.length === 1) { t = '0' + t; } end += t.toString(); } return utils.parse16To10(end); }; _proto2.readLong = function readLong() { var self = this; if (self.check()) { return -1; } var end = ''; for (var i = 0; i < 8; i++) { var t = self.pool[self.position++].toString(16); if (t.length === 1) { t = '0' + t; } end += t; } return utils.parse16To10(end); }; _proto2.readByte = function readByte() { if (this.check()) { return -1; } var val = this.pool[this.position++]; if (val > 255) { val &= 255; } return val; }; _proto2.readUTF = function readUTF() { if (this.check()) { return ''; } var big = this.readByte() << 8 | this.readByte(); var pool = this.pool.subarray(this.position, this.position += big); return BinaryHelper.readUTF(pool); }; _proto2.readAll = function readAll() { return this.pool.subarray(this.position, this.poolLen); }; return RongStreamReader; }(); var RongStreamWriter = function () { function RongStreamWriter() { this.pool = []; this.position = 0; this.writen = 0; } var _proto3 = RongStreamWriter.prototype; _proto3.write = function write(_byte2) { if (utils.isArray(_byte2)) { this.pool = this.pool.concat(_byte2); } else if (utils.isPlus(_byte2)) { if (_byte2 > 255) { _byte2 &= 255; } this.pool.push(_byte2); this.writen++; } return _byte2; }; _proto3.writeArr = function writeArr(_byte3) { this.pool = this.pool.concat(_byte3); return _byte3; }; _proto3.writeUTF = function writeUTF(str) { var val = BinaryHelper.writeUTF(str); this.pool = this.pool.concat(val); this.writen += val.length; }; _proto3.getBytesArray = function getBytesArray() { return this.pool; }; return RongStreamWriter; }(); var IDENTIFIER = { PUB: 'pub', QUERY: 'qry' }; var _getIdentifier = function getIdentifier(messageId, identifier) { if (messageId && identifier) { return identifier + '_' + messageId; } else if (messageId) { return messageId; } else { return utils.getCurrentTimestamp(); } }; var BaseReader = function () { function BaseReader(header) { this._name = void 0; this._header = void 0; this.lengthSize = 0; this.messageId = void 0; this.timestamp = void 0; this.identifier = void 0; this._header = header; } var _proto = BaseReader.prototype; _proto.getIdentifier = function getIdentifier() { var messageId = this.messageId, identifier = this.identifier; return _getIdentifier(messageId, identifier); }; _proto.read = function read(stream, length) { this.readMessage(stream, length); }; _proto.readMessage = function readMessage(stream, length) { return { stream: stream, length: length }; }; return BaseReader; }(); var BaseWriter = function () { function BaseWriter(headerType) { this._header = void 0; this.lengthSize = 0; this.data = void 0; this.messageId = void 0; this.topic = void 0; this.targetId = void 0; this.identifier = void 0; this._header = new Header(headerType, false, QOS.AT_MOST_ONCE, false); } var _proto2 = BaseWriter.prototype; _proto2.getIdentifier = function getIdentifier() { var messageId = this.messageId, identifier = this.identifier; return _getIdentifier(messageId, identifier); }; _proto2.write = function write(stream) { var headerCode = this.getHeaderFlag(); stream.write(headerCode); this.writeMessage(stream); }; _proto2.writeMessage = function writeMessage(stream) { return stream; }; _proto2.setHeaderQos = function setHeaderQos(qos) { this._header.qos = qos; }; _proto2.getHeaderFlag = function getHeaderFlag() { return this._header.encode(); }; _proto2.getLengthSize = function getLengthSize() { return this.lengthSize; }; _proto2.getBufferData = function getBufferData() { var stream = new RongStreamWriter(); this.write(stream); var val = stream.getBytesArray(); var binary = new Int8Array(val); return binary; }; _proto2.getCometData = function getCometData() { var data = this.data || {}; return utils.toJSON(data); }; return BaseWriter; }(); var ConnAckReader = function (_BaseReader) { _inheritsLoose(ConnAckReader, _BaseReader); function ConnAckReader() { var _this; for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this = _BaseReader.call.apply(_BaseReader, [this].concat(args)) || this; _this._name = MESSAGE_NAME.CONN_ACK; _this.status = void 0; _this.userId = void 0; _this.timestamp = void 0; return _this; } var _proto3 = ConnAckReader.prototype; _proto3.readMessage = function readMessage(stream, msgLength) { stream.readByte(); this.status = +stream.readByte(); if (msgLength > ConnAckReader.MESSAGE_LENGTH) { this.userId = stream.readUTF(); stream.readUTF(); this.timestamp = stream.readLong(); } }; return ConnAckReader; }(BaseReader); ConnAckReader.MESSAGE_LENGTH = 2; var DisconnectReader = function (_BaseReader2) { _inheritsLoose(DisconnectReader, _BaseReader2); function DisconnectReader() { var _this2; for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } _this2 = _BaseReader2.call.apply(_BaseReader2, [this].concat(args)) || this; _this2._name = MESSAGE_NAME.DISCONNECT; _this2.status = void 0; return _this2; } var _proto4 = DisconnectReader.prototype; _proto4.readMessage = function readMessage(stream) { stream.readByte(); this.status = +stream.readByte(); }; return DisconnectReader; }(BaseReader); DisconnectReader.MESSAGE_LENGTH = 2; var PingReqWriter = function (_BaseWriter) { _inheritsLoose(PingReqWriter, _BaseWriter); function PingReqWriter() { var _this3; _this3 = _BaseWriter.call(this, OPERATE_TYPE.PINGREQ) || this; _this3._name = MESSAGE_NAME.PING_REQ; return _this3; } return PingReqWriter; }(BaseWriter); var PingRespReader = function (_BaseReader3) { _inheritsLoose(PingRespReader, _BaseReader3); function PingRespReader() { var _this4; for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { args[_key3] = arguments[_key3]; } _this4 = _BaseReader3.call.apply(_BaseReader3, [this].concat(args)) || this; _this4._name = MESSAGE_NAME.PING_RESP; return _this4; } return PingRespReader; }(BaseReader); var RetryableReader = function (_BaseReader4) { _inheritsLoose(RetryableReader, _BaseReader4); function RetryableReader() { var _this5; for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { args[_key4] = arguments[_key4]; } _this5 = _BaseReader4.call.apply(_BaseReader4, [this].concat(args)) || this; _this5.messageId = void 0; return _this5; } var _proto5 = RetryableReader.prototype; _proto5.readMessage = function readMessage(stream) { var msgId = stream.readByte() * 256 + stream.readByte(); this.messageId = parseInt(msgId, 10); }; return RetryableReader; }(BaseReader); var RetryableWriter = function (_BaseWriter2) { _inheritsLoose(RetryableWriter, _BaseWriter2); function RetryableWriter() { var _this6; for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) { args[_key5] = arguments[_key5]; } _this6 = _BaseWriter2.call.apply(_BaseWriter2, [this].concat(args)) || this; _this6.messageId = void 0; return _this6; } var _proto6 = RetryableWriter.prototype; _proto6.writeMessage = function writeMessage(stream) { var id = this.messageId; var lsb = id & 255; var msb = (id & 65280) >> 8; stream.write(msb); stream.write(lsb); }; return RetryableWriter; }(BaseWriter); var PublishReader = function (_RetryableReader) { _inheritsLoose(PublishReader, _RetryableReader); function PublishReader() { var _this7; for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) { args[_key6] = arguments[_key6]; } _this7 = _RetryableReader.call.apply(_RetryableReader, [this].concat(args)) || this; _this7._name = MESSAGE_NAME.PUBLISH; _this7.topic = void 0; _this7.data = void 0; _this7.targetId = void 0; _this7.date = void 0; _this7.syncMsg = false; _this7.identifier = IDENTIFIER.PUB; return _this7; } var _proto7 = PublishReader.prototype; _proto7.readMessage = function readMessage(stream) { this.date = stream.readInt(); this.topic = stream.readUTF(); this.targetId = stream.readUTF(); RetryableReader.prototype.readMessage.apply(this, arguments); this.data = stream.readAll(); }; return PublishReader; }(RetryableReader); var PublishWriter = function (_RetryableWriter) { _inheritsLoose(PublishWriter, _RetryableWriter); function PublishWriter(topic, data, targetId) { var _this8; _this8 = _RetryableWriter.call(this, OPERATE_TYPE.PUBLISH) || this; _this8._name = MESSAGE_NAME.PUBLISH; _this8.topic = void 0; _this8.data = void 0; _this8.targetId = void 0; _this8.date = void 0; _this8.syncMsg = false; _this8.identifier = IDENTIFIER.PUB; _this8.topic = topic; _this8.data = utils.isString(data) ? BinaryHelper.writeUTF(data) : data; _this8.targetId = targetId; return _this8; } var _proto8 = PublishWriter.prototype; _proto8.writeMessage = function writeMessage(stream) { stream.writeUTF(this.topic); stream.writeUTF(this.targetId); RetryableWriter.prototype.writeMessage.apply(this, arguments); stream.write(this.data); }; return PublishWriter; }(RetryableWriter); var PubAckReader = function (_RetryableReader2) { _inheritsLoose(PubAckReader, _RetryableReader2); function PubAckReader() { var _this9; for (var _len7 = arguments.length, args = new Array(_len7), _key7 = 0; _key7 < _len7; _key7++) { args[_key7] = arguments[_key7]; } _this9 = _RetryableReader2.call.apply(_RetryableReader2, [this].concat(args)) || this; _this9._name = MESSAGE_NAME.PUB_ACK; _this9.status = void 0; _this9.date = 0; _this9.data = void 0; _this9.millisecond = 0; _this9.messageUId = void 0; _this9.timestamp = 0; _this9.identifier = IDENTIFIER.PUB; return _this9; } var _proto9 = PubAckReader.prototype; _proto9.readMessage = function readMessage(stream) { RetryableReader.prototype.readMessage.call(this, stream); this.date = stream.readInt(); this.status = stream.readByte() * 256 + stream.readByte(); this.millisecond = stream.readByte() * 256 + stream.readByte(); this.timestamp = this.date * 1000 + this.millisecond; this.messageUId = stream.readUTF(); }; return PubAckReader; }(RetryableReader); var PubAckWriter = function (_RetryableWriter2) { _inheritsLoose(PubAckWriter, _RetryableWriter2); function PubAckWriter(messageId) { var _this10; _this10 = _RetryableWriter2.call(this, OPERATE_TYPE.PUBACK) || this; _this10._name = MESSAGE_NAME.PUB_ACK; _this10.status = void 0; _this10.date = 0; _this10.millisecond = 0; _this10.messageUId = void 0; _this10.timestamp = 0; _this10.messageId = messageId; return _this10; } var _proto10 = PubAckWriter.prototype; _proto10.writeMessage = function writeMessage(stream) { RetryableWriter.prototype.writeMessage.call(this, stream); }; return PubAckWriter; }(RetryableWriter); var QueryWriter = function (_RetryableWriter3) { _inheritsLoose(QueryWriter, _RetryableWriter3); function QueryWriter(topic, data, targetId) { var _this11; _this11 = _RetryableWriter3.call(this, OPERATE_TYPE.QUERY) || this; _this11._name = MESSAGE_NAME.QUERY; _this11.topic = void 0; _this11.data = void 0; _this11.targetId = void 0; _this11.identifier = IDENTIFIER.QUERY; _this11.topic = topic; _this11.data = utils.isString(data) ? BinaryHelper.writeUTF(data) : data; _this11.targetId = targetId; return _this11; } var _proto11 = QueryWriter.prototype; _proto11.writeMessage = function writeMessage(stream) { stream.writeUTF(this.topic); stream.writeUTF(this.targetId); RetryableWriter.prototype.writeMessage.call(this, stream); stream.write(this.data); }; return QueryWriter; }(RetryableWriter); var QueryConWriter = function (_RetryableWriter4) { _inheritsLoose(QueryConWriter, _RetryableWriter4); function QueryConWriter(messageId) { var _this12; _this12 = _RetryableWriter4.call(this, OPERATE_TYPE.QUERYCON) || this; _this12._name = MESSAGE_NAME.QUERY_CON; _this12.messageId = messageId; return _this12; } return QueryConWriter; }(RetryableWriter); var QueryAckReader = function (_RetryableReader3) { _inheritsLoose(QueryAckReader, _RetryableReader3); function QueryAckReader() { var _this13; for (var _len8 = arguments.length, args = new Array(_len8), _key8 = 0; _key8 < _len8; _key8++) { args[_key8] = arguments[_key8]; } _this13 = _RetryableReader3.call.apply(_RetryableReader3, [this].concat(args)) || this; _this13._name = MESSAGE_NAME.QUERY_ACK; _this13.data = void 0; _this13.status = void 0; _this13.date = void 0; _this13.identifier = IDENTIFIER.QUERY; return _this13; } var _proto12 = QueryAckReader.prototype; _proto12.readMessage = function readMessage(stream) { RetryableReader.prototype.readMessage.call(this, stream); this.date = stream.readInt(); this.status = stream.readByte() * 256 + stream.readByte(); this.data = stream.readAll(); }; return QueryAckReader; }(RetryableReader); var getReaderByHeader = function getReaderByHeader(header) { var type = header.type, msg = new BaseReader(header); switch (type) { case OPERATE_TYPE.CONNACK: msg = new ConnAckReader(header); break; case OPERATE_TYPE.PUBLISH: msg = new PublishReader(header); msg.syncMsg = header.syncMsg; break; case OPERATE_TYPE.PUBACK: msg = new PubAckReader(header); break; case OPERATE_TYPE.QUERYACK: msg = new QueryAckReader(header); break; case OPERATE_TYPE.SUBACK: case OPERATE_TYPE.UNSUBACK: case OPERATE_TYPE.PINGRESP: msg = new PingRespReader(header); break; case OPERATE_TYPE.DISCONNECT: msg = new DisconnectReader(header); break; default: throw new Error('No support for deserializing ' + type + ' messages'); } return msg; }; var readWSBuffer = function readWSBuffer(data) { var arr = new Uint8Array(data); var stream = new RongStreamReader(arr); var flags = stream.readByte(), header = new Header(flags); var msg = getReaderByHeader(header); msg.read(stream, arr.length - 1); return msg; }; var readCometData = function readCometData(data) { var flags = data.headerCode, header = new Header(flags); var msg = getReaderByHeader(header); utils.forEach(data, function (item, key) { if (key in msg) { msg[key] = item; } }); return msg; }; var ENGINE_EVENT = { WATCH: 'watch', UN_WATCH: 'unwatch', CONNECT: 'connect', RECONNECT: 'reconnect', DISCONNECT: 'disconnect', CHANGE_USER: 'changeUser', GET_CONNECTION_STATUS: 'getConnectionStatus', GET_CONNECTION_USER_ID: 'getConnectionUserId', GET_CONNECTED_TIME: 'getConnectedTime', GET_APP_INFO: 'getAppInfo', GET_CONVERSATION_LIST: 'getConversationList', REMOVE_CONVERSATION_LIST: 'removeConversationList', REMOVE_CONVERSATION: 'removeConversation', GET_TOTAL_UNREAD_COUNT: 'getTotalUnreadCount', CLEAR_UNREAD_COUNT: 'clearUnreadCount', GET_UNREAD_COUNT: 'getUnreadCount', GET_LOCAL_CONVERSATION: 'getLocalConversation', SET_CONVERSATION_STATUS_LIST: 'setConversationStatusList', SEND_MESSAGE: 'sendMessage', GET_HISTORY_MSGS: 'getHistoryMessages', DELETE_MESSAGES: 'deleteHistoryMessages', CLEAR_MESSAGES: 'clearHistoryMessages', RECALL_MESSAGE: 'recallMessage', JOIN_CHATROOM: 'joinChatRoom', QUIT_CHATROOM: 'quitChatRoom', GET_CHATROOM_INFO: 'getChatRoomInfo', GET_CHATROOM_MSGS: 'getChatRoomHistoryMessages', SET_KV: 'setChatRoomKV', FORCE_SET_KV: 'forceSetChatRoomKV', DEL_KV: 'removeChatRoomKV', FORCE_DEL_KV: 'forceRemoveChatRoomKV', GET_KV: 'getChatRoomKV', GET_ALL_KV: 'getAllChatRoomKV', JOIN_RTC: 'joinRTCRoom', QUIT_RTC: 'quitRTCRoom', PING_RTC: 'RTCPing', GET_RTC_ROOM_INFO: 'getRTCRoomInfo', SET_RTC_DATA: 'setRTCData', SET_RTC_USER_DATA: 'setRTCUserData', GET_RTC_DATA: 'getRTCData', DEL_RTC_DATA: 'removeRTCData', SET_RTC_OUT_DATA: 'setRTCOutData', GET_RTC_OUT_DATA: 'getRTCOutData', GET_RTC_TOKEN: 'getRTCToken', SET_RTC_STATE: 'setRTCState', GET_RTC_USER_INFO_LIST: 'getRTCUserInfoList', SET_RTC_USER_INFO: 'setRTCUserInfo', DEL_RTC_USER_INFO: 'removeRTCUserInfo', GET_RTC_USER_LIST: 'getRTCUserList', GET_UPLOAD_TOKEN: 'getFileToken', GET_UPLOAD_URL: 'getFileUrl' }; var ENGINE_EVENT_NEED_CONNECTED = [ENGINE_EVENT.GET_CONVERSATION_LIST, ENGINE_EVENT.REMOVE_CONVERSATION_LIST, ENGINE_EVENT.REMOVE_CONVERSATION, ENGINE_EVENT.GET_TOTAL_UNREAD_COUNT, ENGINE_EVENT.CLEAR_UNREAD_COUNT, ENGINE_EVENT.SEND_MESSAGE, ENGINE_EVENT.GET_HISTORY_MSGS, ENGINE_EVENT.DELETE_MESSAGES, ENGINE_EVENT.CLEAR_MESSAGES, ENGINE_EVENT.RECALL_MESSAGE, ENGINE_EVENT.JOIN_CHATROOM, ENGINE_EVENT.QUIT_CHATROOM, ENGINE_EVENT.GET_CHATROOM_INFO, ENGINE_EVENT.GET_CHATROOM_MSGS]; var ENGINE_EVENT_NEED_DISCONNECTED = [ENGINE_EVENT.CONNECT, ENGINE_EVENT.RECONNECT]; var IM_EVENT = { STATUS: 'status', MESSAGE: 'message', CONVERSATION: 'conversation', SETTING: 'setting', CHATROOM: 'chatroom' }; var TRANSPORT_EVENT = { SIGNAL: 'signal', STATUS: 'status' }; var SERVER_EVENT_NAME = { STATUS: 'status', NOTIFY_PULL: 'notifyPull', DIRECT_MSG: 'directMessage', CHRM_KV_CHANGED: 'chatRoomKV', CHRM_KV_SET: 'chatRoomKVSet', MESSAGE_SEND: 'sendMessage', JOIN_CHATROOM: 'joinChatRoom', BEFORE_JOIN_CHATROOM: 'beforeJoinChatRoom', USER_SETTING_CHANGED: 'userSetting', CONVERSATION_STATUS_CHANGED: 'converStatusChanged', CONVERSATION_STATUS_SETED: 'converStatusSeted' }; var _APP_ENGINE_EVENT_LOG; var PLATFORM$1 = 'Web'; var LEVEL = { FATAL: 0, ERROR: 1, WARN: 2, INFO: 3, DEBUG: 4 }; var STORE_SIZE = { ADVANCED: 500, LOW: 500 }; var LOG_TYPE = { 'IM': 'IM', 'RTC': 'RTC' }; var TAG = { L_GET_NAVI_T: 'L-get_navi-T', L_GET_NAVI_R: 'L-get_navi-R', L_PING_WS_T: 'L-ping_ws-T', L_PING_WS_R: 'L-ping_ws-R', L_NETWORK_CHANGED_S: 'L-network_changed-S', L_DECODE_MSG_E: 'L-decode_msg-E', L_RECONNECT_T: 'L-reconnect-T', L_RECONNECT_R: 'L-reconnect-R', L_PULL_CHRM_KV_T: 'L-pull-chrm-kv-T', L_PULL_CHRM_KV_R: 'L-pull-chrm-kv-R', L_PING_S: 'L-ping-S', L_CRASH_E: 'L-crash-E', L_COMET_SEND_SIGNAL_E: 'L-comet_send_signal-E', A_INIT_O: 'A-init-O', A_CONNECT_T: 'A-connect-T', A_CONNECT_R: 'A-connect-R', A_DISCONNECT_T: 'A-disconnect-T', A_DISCONNECT_R: 'A-disconnect-R', A_RECONNECT_T: 'A-reconnect-T', A_RECONNECT_R: 'A-reconnect-R', A_JOIN_CHATROOM_T: 'A-join_chatroom-T', A_JOIN_CHATROOM_R: 'A-join_chatroom-R', A_QUIT_CHATROOM_T: 'A-quit_chatroom-T', A_QUIT_CHATROOM_R: 'A-quit_chatroom-R', P_NOTIFY_CHRM_KV_S: 'P-notify-chrm-kv-R', G_CRASH_E: 'G-crash-E', G_UPLOAD_LOG_S: 'G-upload_log-S', G_UPLOAD_LOG_E: 'G-upload_log-E' }; var APP_ENGINE_EVENT_LOG_TAG = (_APP_ENGINE_EVENT_LOG = {}, _APP_ENGINE_EVENT_LOG[ENGINE_EVENT.CONNECT] = { req: TAG.A_CONNECT_T, resp: TAG.A_CONNECT_R }, _APP_ENGINE_EVENT_LOG[ENGINE_EVENT.DISCONNECT] = { req: TAG.A_DISCONNECT_T, resp: TAG.A_DISCONNECT_R }, _APP_ENGINE_EVENT_LOG[ENGINE_EVENT.RECONNECT] = { req: TAG.A_RECONNECT_T, resp: TAG.A_RECONNECT_R }, _APP_ENGINE_EVENT_LOG[ENGINE_EVENT.JOIN_CHATROOM] = { req: TAG.A_JOIN_CHATROOM_T, resp: TAG.A_JOIN_CHATROOM_R }, _APP_ENGINE_EVENT_LOG[ENGINE_EVENT.QUIT_CHATROOM] = { req: TAG.A_QUIT_CHATROOM_T, resp: TAG.A_QUIT_CHATROOM_R }, _APP_ENGINE_EVENT_LOG); var REPORT_TYPE = { REALTIME: 0, FULL: 1 }; var CSV_LOG_TPL = '{sessionId},{time},{type},{level},{tag},{content}\n'; var REALTIME_URL_TPL = '{protocol}{url}?version={version}&appkey={appkey}&userId={userId}&deviceId={deviceId}&deviceInfo={deviceInfo}&platform={platform}'; var MSGNOTIF_URL_TPL = '{protocol}{url}?version={version}&appkey={appkey}&userId={userId}&logId={logId}&deviceId={deviceId}&deviceInfo={deviceInfo}&platform={platform}'; var LOG_CMD_MSG_SENDER = 'rongcloudsystem'; var NO_FULL_LOG = 'nodata'; var REQUEST_TIMEOUT = 15000; var DEFAULT_SERVER_OPTION = { isOpen: true, url: 'logcollection.ronghub.com', realtimeLevel: LEVEL.ERROR, realtimeInterval: 20000, realtimeMaxTimes: 5, fullInterval: 5000, fullMaxTimes: 3, fullLevel: LEVEL.DEBUG }; var IGNORE_ERROR_CODE = [ERROR_CODE.RC_CONNECTION_EXIST]; var isEmpty$1 = utils.isEmpty, tplEngine$1 = utils.tplEngine; var getTransporterUrl = function getTransporterUrl(option) { var domain = option.domain, appkey = option.appkey, token = option.token, connectType = option.connectType, protocol = option.protocol; var isComet = connectType === CONNECT_TYPE.COMET; var cmpTpl = CMP_URL_TPL; if (isEmpty$1(protocol)) { protocol = isComet ? env.protocol.http : env.protocol.ws; } var tplOption = { domain: domain, appkey: appkey, protocol: protocol, apiVer: env.isFromUniapp ? 'uniapp' : 'normal', token: utils.encodeURI(token) }; if (env.isMini) { cmpTpl = MINI_CMP_URL_TPL; utils.extend(tplOption, { platform: PLATFORM_TYPE.MINI }); } return tplEngine$1(cmpTpl, tplOption); }; var isGroup = function isGroup(type) { return type === CONVERSATION_TYPE.GROUP; }; var isChatRoom = function isChatRoom(type) { return type === CONVERSATION_TYPE.CHATROOM; }; var getConversationTypeList = function getConversationTypeList() { return utils.getValues(CONVERSATION_TYPE); }; var isValidConversationType = function isValidConversationType(type) { var conversationTypeList = getConversationTypeList(); return utils.isNumber(type) && utils.isInclude(conversationTypeList, type); }; var getSessionId = function getSessionId(option) { var isStatusMessage = option.isStatusMessage; var isPersited = option.isPersited, isCounted = option.isCounted, isMentiond = option.isMentiond, disableNotification = option.disableNotification; if (isStatusMessage) { isPersited = isCounted = false; } var sessionId = 0; if (isPersited) { sessionId = sessionId | 0x01; } if (isCounted) { sessionId = sessionId | 0x02; } if (isMentiond) { sessionId = sessionId | 0x04; } if (disableNotification) { sessionId = sessionId | 0x20; } return sessionId; }; var getPersitedAndCountedBySessionId = function getPersitedAndCountedBySessionId(sessionId) { var isPersited, isCounted; switch (sessionId) { case MESSAGE_TAG.COUNT_ONLY: isPersited = false; isCounted = true; break; case MESSAGE_TAG.PERSIT_ONLY: isPersited = true; isCounted = false; break; case MESSAGE_TAG.NONE: isPersited = isCounted = false; break; case MESSAGE_TAG.PERSIT_AND_COUNT: default: isPersited = isCounted = true; break; } return { isPersited: isPersited, isCounted: isCounted }; }; var getPersitedAndCountedAndSlientBySessionId = function getPersitedAndCountedAndSlientBySessionId(sessionId) { var binaryNum = Number(sessionId).toString(2); var sessionIdArr = []; for (var i = 0; i < binaryNum.length; i++) { var index = binaryNum.length - 1 - i; sessionIdArr.push(Number(binaryNum[index])); } return { isPersited: Boolean(sessionIdArr[0]), isCounted: Boolean(sessionIdArr[1]), disableNotification: Boolean(sessionIdArr[5]) }; }; var getMessageOptionByStatus = function getMessageOptionByStatus(status) { var isPersited = true, isCounted = true, isMentiond = false, disableNotification = false; isPersited = !!(status & 0x10); isCounted = !!(status & 0x20); isMentiond = !!(status & 0x40); disableNotification = !!(status & 0x200); return { isPersited: isPersited, isCounted: isCounted, isMentiond: isMentiond, disableNotification: disableNotification }; }; var SignalId = { ids: {}, temp: '{appkey}_{userId}', get: function get(option) { var key = utils.tplEngine(SignalId.temp, option); var id = SignalId.ids[key] || 0; id++; SignalId.ids[key] = id; return id; }, clear: function clear(option) { var key = utils.tplEngine(SignalId.temp, option); SignalId.ids[key] = 0; }, isExceedLimit: function isExceedLimit(id) { return id > MAX_SINGAL_ID; } }; var RCSocket = function () { function RCSocket(options) { this._socket = void 0; this.eventEmitter = new utils.EventEmitter(); this.KEY = { OPEN: 'open', MSG: 'msg', ERROR: 'error', CLOSE: 'close' }; var self = this; var KEY = self.KEY; self._socket = new utils.Socket(options); self._socket.onOpen(function (data) { self.eventEmitter.emit(KEY.OPEN, data); }); self._socket.onMessage(function (data) { self.eventEmitter.emit(KEY.MSG, data); }); self._socket.onError(function (data) { data = self._formatCloseData(data); self.eventEmitter.emit(KEY.ERROR, data); }); self._socket.onClose(function (data) { data = self._formatCloseData(data); self.eventEmitter.emit(KEY.CLOSE, data); }); } var _proto = RCSocket.prototype; _proto._formatCloseData = function _formatCloseData(data) { if (env.isMini || env.isAppPlus) { data = data || {}; var _data = data, errMsg = _data.errMsg; data.code = MINI_ERROR_MSG_TO_STATUS[errMsg]; } return data; }; _proto.send = function send(data) { return this._socket.send(data); }; _proto.close = function close() { this.eventEmitter.clear(); this._socket.close(); }; _proto.onOpen = function onOpen(event) { this.eventEmitter.on(this.KEY.OPEN, event); }; _proto.onMessage = function onMessage(event) { this.eventEmitter.on(this.KEY.MSG, event); }; _proto.onError = function onError(event) { this.eventEmitter.on(this.KEY.ERROR, event); }; _proto.onClose = function onClose(event) { this.eventEmitter.on(this.KEY.CLOSE, event); }; return RCSocket; }(); var RCStorage = function () { function RCStorage(suffix) { var _ref; this._cache = void 0; this.STORAGE_KEY = void 0; var storageKey = suffix ? STORAGE_ROOT_KEY + suffix : STORAGE_ROOT_KEY; var localCache = utils.Storage.get(storageKey) || {}; this._cache = new utils.Cache((_ref = {}, _ref[storageKey] = localCache, _ref)); this.STORAGE_KEY = storageKey; } var _proto2 = RCStorage.prototype; _proto2._get = function _get() { var KEY = this.STORAGE_KEY; return this._cache.get(KEY) || {}; }; _proto2._set = function _set(cache) { var KEY = this.STORAGE_KEY; cache = cache || {}; this._cache.set(KEY, cache); utils.Storage.set(KEY, cache); }; _proto2.set = function set(key, value) { var localValue = this._get(); localValue[key] = value; this._set(localValue); }; _proto2.remove = function remove(key) { var localValue = this._get(); delete localValue[key]; this._set(localValue); }; _proto2.clear = function clear() { var KEY = this.STORAGE_KEY; utils.Storage.remove(KEY); this._cache.remove(KEY); }; _proto2.get = function get(key) { var localValue = this._get(); return localValue[key]; }; _proto2.getKeys = function getKeys() { var localValue = this._get(); return utils.getKeys(localValue); }; _proto2.getValues = function getValues() { return this._get() || {}; }; return RCStorage; }(); var formatSyncTime = function formatSyncTime(_syncTime) { _syncTime = _syncTime || {}; _syncTime.inboxTime = _syncTime.inboxTime || 0; _syncTime.sendboxTime = _syncTime.sendboxTime || 0; return _syncTime; }; var MessageTimeSyner = function () { function MessageTimeSyner(option) { this._syncTime = void 0; this._storage = void 0; option = option || {}; var _option = option, startSyncTime = _option.startSyncTime; this._initStorage(option); if (startSyncTime) { this._syncTime = formatSyncTime(startSyncTime); } } var _proto3 = MessageTimeSyner.prototype; _proto3._initStorage = function _initStorage(option) { var appkey = option.appkey, userId = option.userId; var ROOT_KEY = utils.tplEngine(STORAGE_SYNC_TIME.ROOT_KEY_TPL, { appkey: appkey, userId: userId }); var storage = new RCStorage(ROOT_KEY); var syncTime = { sendboxTime: storage.get(STORAGE_SYNC_TIME.SUB_KEY.SENDBOX), inboxTime: storage.get(STORAGE_SYNC_TIME.SUB_KEY.INBOX) }; this._storage = storage; this._syncTime = formatSyncTime(syncTime); }; _proto3.setInbox = function setInbox(time) { var beforeTime = this._syncTime.inboxTime || 0; if (beforeTime < time) { this._syncTime.inboxTime = time; this._storage.set(STORAGE_SYNC_TIME.SUB_KEY.INBOX, time); } }; _proto3.setSendbox = function setSendbox(time) { var beforeTime = this._syncTime.sendboxTime || 0; if (beforeTime < time) { this._syncTime.sendboxTime = time; this._storage.set(STORAGE_SYNC_TIME.SUB_KEY.SENDBOX, time); } }; _proto3.setByMessage = function setByMessage(msg) { var messageDirection = msg.messageDirection, sentTime = msg.sentTime; var isSelfSend = messageDirection === MESSAGE_DIRECTION.SEND; isSelfSend ? this.setSendbox(sentTime) : this.setInbox(sentTime); }; _proto3.get = function get() { return formatSyncTime(this._syncTime); }; return MessageTimeSyner; }(); var ChatRoomMessageTimeSyner = function () { function ChatRoomMessageTimeSyner(option) { this._rootKey = void 0; this._pullTimes = {}; option = option || {}; var _option2 = option, appkey = _option2.appkey, userId = _option2.userId; this._rootKey = utils.tplEngine(SESSION_SYNC_TIME.ROOT_KEY_TPL, { appkey: appkey, userId: userId }); } var _proto4 = ChatRoomMessageTimeSyner.prototype; _proto4.set = function set(chrmId, time) { this._pullTimes[chrmId] = time; utils.Session.set(this._rootKey, this._pullTimes); }; _proto4.get = function get(chrmId) { var pullTimes; if (utils.isEmpty(this._pullTimes)) { pullTimes = utils.Session.get(this._rootKey) || {}; } else { pullTimes = this._pullTimes; } return pullTimes[chrmId] || 0; }; _proto4.setByMessage = function setByMessage(msg) { var sentTime = msg.sentTime; var chrmId = msg.targetId; var beforeTime = this.get(chrmId); if (beforeTime < sentTime) { this.set(chrmId, sentTime); } }; return ChatRoomMessageTimeSyner; }(); var JoinedChatRoomSyner = function () { function JoinedChatRoomSyner(option) { this._rootKey = void 0; this._joinedChatRoomInfos = []; option = option || {}; var _option3 = option, appkey = _option3.appkey, userId = _option3.userId; this._rootKey = utils.tplEngine(SESSION_SYNC_CHATROOM.ROOT_KEY_TPL, { appkey: appkey, userId: userId }); } var _proto5 = JoinedChatRoomSyner.prototype; _proto5.set = function set(option) { var _this = this; var chrmId = option.chrmId, count = option.count, isOpenJoinMulitpleChrmService = option.isOpenJoinMulitpleChrmService; var backupJoinedChatRoomInfos = utils.copy(this._joinedChatRoomInfos); if (isOpenJoinMulitpleChrmService) { utils.forEach(backupJoinedChatRoomInfos, function (chrmInfo, index) { if (chrmInfo.chrmId === option.chrmId) { _this._joinedChatRoomInfos.splice(index, 1); } }); this._joinedChatRoomInfos.push({ chrmId: chrmId, count: count }); } else { this._joinedChatRoomInfos = [{ chrmId: chrmId, count: count }]; } utils.Session.set(this._rootKey, this._joinedChatRoomInfos); }; _proto5.get = function get() { if (utils.isEmpty(this._joinedChatRoomInfos)) { return utils.Session.get(this._rootKey) || []; } else { return this._joinedChatRoomInfos; } }; _proto5.remove = function remove(chrmId) { var joinedChatRoom = utils.isEmpty(this._joinedChatRoomInfos) ? this._joinedChatRoomInfos : utils.Session.get(this._rootKey); if (utils.isEmpty(joinedChatRoom)) return; utils.forEach(joinedChatRoom, function (chrmInfo, index) { if (chrmInfo.chrmId === chrmId) { return joinedChatRoom.splice(index, 1); } }); utils.Session.set(this._rootKey, joinedChatRoom); }; _proto5.clear = function clear() { this._joinedChatRoomInfos = []; utils.Session.remove(this._rootKey); }; return JoinedChatRoomSyner; }(); var getUIDByToken = function getUIDByToken(token) { return utils.md5(token).slice(8, 16); }; var isIncludeNavi = function isIncludeNavi(token) { return utils.isInclude(token, NAVI_SEPARATOR_IN_TOKEN); }; var getNaviListByToken = function getNaviListByToken(token) { var navDomainList = []; if (isIncludeNavi(token)) { var separatorIndex = utils.indexOf(token, NAVI_SEPARATOR_IN_TOKEN); var navsText = token.substring(separatorIndex + 1, token.length); var domainList = navsText.split(DOMAIN_SEPARATOR_IN_NAVLIST); utils.forEach(domainList, function (domain) { if (!isEmpty$1(domain)) { navDomainList.push(domain); } }); } return navDomainList; }; var getCMPDomainList = function getCMPDomainList(option, customOption) { var server = option.server, backupServer = option.backupServer; server = server || ''; backupServer = backupServer || ''; var backupCMPList = backupServer.split(DOMAIN_SEPARATOR_IN_CMPLIST); var cmpList = []; if (!utils.isEmpty(server)) { cmpList.push(server); } utils.forEach(backupCMPList, function (cmp) { if (!utils.isEmpty(cmp)) { cmpList.push(cmp); } }); if (!utils.isUndefined(customOption.customCMP) && !utils.isEmpty(customOption.customCMP)) { cmpList = customOption.customCMP; } return cmpList; }; var getValidToken = function getValidToken(token) { if (isIncludeNavi(token)) { var separatorIndex = utils.indexOf(token, NAVI_SEPARATOR_IN_TOKEN); token = token.substring(0, separatorIndex + 1); } return token; }; var getConnectType = function getConnectType(option) { var connectType = option.connectType; var isSpecifiedSocket = connectType === CONNECT_TYPE.WEBSOCKET; var isSocket = isSpecifiedSocket && utils.isSupportSocket(); return isSocket ? CONNECT_TYPE.WEBSOCKET : CONNECT_TYPE.COMET; }; var isConnected = function isConnected(status) { return utils.isEqual(status, CONNECTION_STATUS.CONNECTED); }; var isConnecting = function isConnecting(status) { return utils.isEqual(status, CONNECTION_STATUS.CONNECTING); }; var isDisconnected = function isDisconnected(status) { return !isConnected(status) && !isConnecting(status); }; var getNavReqOption = function getNavReqOption(option, user) { option = utils.copy(option); option.token = user.token; return option; }; var getPingTimeout = function getPingTimeout(timeSpentConnect) { var timeout = timeSpentConnect * 3; if (timeout < IM_PING_MIN_TIMEOUT) { return IM_PING_MIN_TIMEOUT; } if (timeout > IM_PING_MAX_TIMEOUT) { return IM_PING_MAX_TIMEOUT; } return timeout; }; var DelayTimer = { _delayTime: 0, setTime: function setTime(time) { var currentTime = utils.getCurrentTimestamp(); DelayTimer._delayTime = currentTime - time; }, getTime: function getTime() { var delayTime = DelayTimer._delayTime; var currentTime = utils.getCurrentTimestamp(); return currentTime - delayTime; } }; var isInValidConversationData = function isInValidConversationData(conversation) { return !conversation.type || !conversation.targetId || !utils.isObject(conversation.latestMessage) || utils.isUndefined(conversation.unreadMessageCount); }; var fixConversationData = function fixConversationData(conversation) { conversation = conversation || {}; var _conversation = conversation, targetId = _conversation.targetId, type = _conversation.type; var defaultType = CONVERSATION_TYPE.PRIVATE, defaultId = '', defaultMsg = { messageType: MESSAGE_TYPE.TEXT, sentTime: DelayTimer.getTime(), content: { content: '' }, senderUserId: targetId, targetId: targetId, type: type }; conversation.type = type || defaultType; conversation.targetId = targetId || defaultId; conversation.latestMessage = conversation.latestMessage || defaultMsg; return conversation; }; var sortConversationList = function sortConversationList(conversationList) { if (utils.isEmpty(conversationList)) { return []; } return utils.quickSort(conversationList, function (before, after) { before = before || {}; after = after || {}; var beforeLatestMessage = before.latestMessage || {}, afterLatestMessage = after.latestMessage || {}, beforeLatestSentTime = beforeLatestMessage.sentTime || 0, afterLatestSentTime = afterLatestMessage.sentTime || 0; var flag = false; if (before.isTop && !after.isTop) { flag = false; } else if (!before.isTop && after.isTop) { flag = true; } else { flag = afterLatestSentTime <= beforeLatestSentTime; } return flag; }); }; var splitConversationListByIsTop = function splitConversationListByIsTop(conversationList) { var topConversationList = [], unToppedConversationList = []; utils.forEach(conversationList, function (conversation) { var hasMentiond = conversation.hasMentiond, mentiondInfo = conversation.mentiondInfo; conversation.hasMentioned = hasMentiond; conversation.mentionedInfo = mentiondInfo; var isTop = conversation.isTop || false; if (isTop) { topConversationList.push(conversation); } else { unToppedConversationList.push(conversation); } }); return { topConversationList: topConversationList || [], unToppedConversationList: unToppedConversationList || [] }; }; var sortConList = function sortConList(conversationList) { if (utils.isEmpty(conversationList)) { return []; } var splitConversationList = splitConversationListByIsTop(conversationList); var _sortListBySentTime = function _sortListBySentTime(convers) { return utils.quickSort(convers, function (before, after) { before = before || {}; after = after || {}; var beforeLatestMessage = before.latestMessage || {}, afterLatestMessage = after.latestMessage || {}, beforeLatestSentTime = beforeLatestMessage.sentTime || 0, afterLatestSentTime = afterLatestMessage.sentTime || 0; return afterLatestSentTime <= beforeLatestSentTime; }); }; var topConversationList = _sortListBySentTime(splitConversationList.topConversationList); var unToppedConversationList = _sortListBySentTime(splitConversationList.unToppedConversationList); topConversationList.push.apply(topConversationList, unToppedConversationList); return topConversationList; }; var isSupportStatusMessage = function isSupportStatusMessage(type) { return !!CONVERSATION_TYPE_TO_PUBLISH_STATUS_TOPIC[type]; }; var getConversationKey = function getConversationKey(option) { var type = option.type, targetId = option.targetId; return type + '_' + targetId; }; var getConversationByKey = function getConversationByKey(key) { key = key || ''; var arr = key.split('_'); if (arr.length === 2) { return { type: arr[0], targetId: arr[1] }; } else { return { type: CONVERSATION_TYPE.PRIVATE, targetId: '' }; } }; var getChatRoomKVOptStatus = function getChatRoomKVOptStatus(entity, action) { var status = 0; if (entity.isAutoDelete) { status = status | CHATROOM_KV_STATUS_CODE.AUTO_DELETE; } if (entity.isOverwrite) { status = status | CHATROOM_KV_STATUS_CODE.OVERWRITE; } if (utils.isEqual(action, CHATROOM_ENTRY_TYPE.DELETE)) { status = status | CHATROOM_KV_STATUS_CODE.OPERATE; } return status; }; var getChatRoomKVByStatus = function getChatRoomKVByStatus(status) { var isDeleteOpt = !!(status & CHATROOM_KV_STATUS_CODE.OPERATE); return { isAutoDelete: !!(status & CHATROOM_KV_STATUS_CODE.AUTO_DELETE), isOverwrite: !!(status & CHATROOM_KV_STATUS_CODE.OVERWRITE), type: isDeleteOpt ? CHATROOM_ENTRY_TYPE.DELETE : CHATROOM_ENTRY_TYPE.UPDATE }; }; var TextCompressor = { _dataType: { Tail: 0x30, Compressed: 0x40, NormalExt: 0x50, Normal: 0x60, Mark: 0x70 }, _chars: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', _scale: 62, _max: 238327, _indexOf: function _indexOf(map, source, fromIndex) { var result = { length: 0, offset: -1 }; if (fromIndex >= source.length - 1) { return result; } var c1 = source.charAt(fromIndex); var c2 = source.charAt(fromIndex + 1); var items = map[c1 + c2]; if (items[0] === fromIndex) { return result; } var space1 = source.length - fromIndex; for (var i = 0, len = items.length; i < len; i++) { var item = items[i]; var space2 = fromIndex - item; if (space2 > TextCompressor._max) { continue; } var end = Math.min(space1, space2); if (end <= result.length) { break; } if (result.length > 2) { if (source.charAt(item + result.length - 1) !== source.charAt(fromIndex + result.length - 1)) { continue; } } var m = 2; for (var j = m; j < end; j++) { if (source.charAt(item + j) === source.charAt(fromIndex + j)) { m++; } else { break; } } if (m >= result.length) { result.length = m; result.offset = item; } } return result; }, _numberEncode: function _numberEncode(num) { var result = [], remainder = 0; do { remainder = num % TextCompressor._scale; result.push(TextCompressor._chars.charAt(remainder)); num = (num - remainder) / TextCompressor._scale; } while (num > 0); return result.join(''); }, _numberDecode: function _numberDecode(str) { var num = 0, index = 0; for (var i = str.length - 1; i >= 0; i--) { index = TextCompressor._chars.indexOf(str.charAt(i)); if (index === -1) { throw new Error('decode number error, data is \'' + str + '\''); } num = num * TextCompressor._scale + index; } return num; }, compress: function compress(data) { var map = {}; for (var p = 0; p < data.length - 1; p++) { var c1 = data.charAt(p); var c2 = data.charAt(p + 1); var c = c1 + c2; if (!map.hasOwnProperty(c)) { map[c] = [p]; continue; } map[c].push(p); } var compressedData = [], normalBlockBuffer = []; var encodeNormalBlock = function encodeNormalBlock() { if (normalBlockBuffer.length > 0) { var normalBlock = normalBlockBuffer.join(''); normalBlockBuffer = []; if (normalBlock.length > 26) { var normalExtBlockLength = TextCompressor._numberEncode(normalBlock.length); var normalExtBlockHeader = String.fromCharCode(TextCompressor._dataType.NormalExt | normalExtBlockLength.length); compressedData.push(normalExtBlockHeader + normalExtBlockLength); } else { var normalBlockHeader = String.fromCharCode(TextCompressor._dataType.Normal | normalBlock.length); compressedData.push(normalBlockHeader); } compressedData.push(normalBlock); } }; var i = 0; while (i < data.length) { var r = TextCompressor._indexOf(map, data, i); if (r.length < 2) { normalBlockBuffer.push(data.charAt(i++)); continue; } if (r.length < 4) { normalBlockBuffer.push(data.substr(i, r.length)); i += r.length; continue; } var offset = TextCompressor._numberEncode(i - r.offset); var length = TextCompressor._numberEncode(r.length); if (offset.length + length.length >= r.length) { normalBlockBuffer.push(data.substr(i, r.length)); i += r.length; continue; } encodeNormalBlock(); var compressedBlockHeader = String.fromCharCode(TextCompressor._dataType.Compressed | offset.length << 2 | length.length); compressedData.push(compressedBlockHeader + offset + length); i += r.length; } encodeNormalBlock(); var dataLengthTo62 = TextCompressor._numberEncode(data.length); var tailBlockHeader = String.fromCharCode(TextCompressor._dataType.Tail | dataLengthTo62.length); compressedData.push(tailBlockHeader + dataLengthTo62); return compressedData.join(''); }, uncompress: function uncompress(data) { var i = 0; var result = ''; label1: do { var header = data.charCodeAt(i++); var headerType = header & TextCompressor._dataType.Mark; var headerVal = header & 0xF; switch (headerType) { case TextCompressor._dataType.Compressed: var p1 = headerVal >> 2; var p2 = headerVal & 3; if (p1 === 0 || p2 === 0) { throw new Error('Data parsing error,at ' + i); } var offset = TextCompressor._numberDecode(data.substr(i, p1)); var len = TextCompressor._numberDecode(data.substr(i += p1, p2)); offset = result.length - offset; if (offset + len > result.length) { throw new Error('Data parsing error,at ' + i); } i += p2; result += result.substr(offset, len); break; case TextCompressor._dataType.Tail: var num = TextCompressor._numberDecode(data.substr(i, headerVal)); if (num !== result.length) { throw new Error('Data parsing error,at ' + i); } i += headerVal; break label1; case TextCompressor._dataType.NormalExt: var normalNum = TextCompressor._numberDecode(data.substr(i, headerVal)); result += data.substr(i += headerVal, normalNum); i += normalNum; break; case TextCompressor._dataType.Normal: result += data.substr(i, headerVal); i += headerVal; break; case TextCompressor._dataType.Mark: if (headerVal > 10) { throw new Error('Data parsing error,at ' + i); } result += data.substr(i, 16 + headerVal); i += 16 + headerVal; break; default: throw new Error('Data parsing error,at ' + i + ' header:' + headerType); } } while (i < data.length); return result; } }; var isBelowIE = function isBelowIE(version) { var system = env.system; var flag = system.model === 'IE' && Number(system.version) < version ? true : false; return flag; }; var stringToCsv = function stringToCsv(str) { var csvStr = str.replace(/"/g, '""'); var tpl = '"{csvStr}"'; return tplEngine$1(tpl, { csvStr: csvStr }); }; var getWebSessionId = function getWebSessionId() { var sessionId = utils.Session.get(STORAGE_SESSION_ID_KEY); if (utils.isEmpty(sessionId)) { sessionId = utils.getUUID22().slice(0, 10); utils.Session.set(STORAGE_SESSION_ID_KEY, sessionId); } return sessionId; }; var getDeviceId = function getDeviceId() { var deviceId = utils.Storage.get(STORAGE_DEVICE_ID_KEY); if (utils.isEmpty(deviceId)) { deviceId = utils.getUUID22(); utils.Storage.set(STORAGE_DEVICE_ID_KEY, deviceId); } return deviceId; }; var getDeviceInfo = function getDeviceInfo() { var tpl = '{brower}|{version}|{sessionId}'; return tplEngine$1(tpl, { brower: env.system.model, version: env.system.version, sessionId: getWebSessionId() }); }; var getReportLogUrl = function getReportLogUrl(params) { var entireUrl = '', protocol = env.protocol.http + '//'; var urlConf = { protocol: protocol, url: params.url, version: SDK_VERSION, appkey: params.appkey, deviceId: getDeviceId(), deviceInfo: getDeviceInfo(), platform: PLATFORM$1, userId: params.userId }; switch (params.type) { case REPORT_TYPE.REALTIME: entireUrl = tplEngine$1(REALTIME_URL_TPL, urlConf); break; case REPORT_TYPE.FULL: entireUrl = tplEngine$1(MSGNOTIF_URL_TPL, utils.extend(urlConf, { logId: params.logId })); break; default: break; } return entireUrl; }; var isLogCommandMsg = function isLogCommandMsg(msg) { var content = msg.content; return msg.messageType === MESSAGE_TYPE.LOG_COMMAND && msg.senderUserId === LOG_CMD_MSG_SENDER && content.platform === 'Web'; }; var isValidChatRoomKey = function isValidChatRoomKey(key) { if (!utils.isString(key)) { return; } var isValid = /^[A-Za-z0-9_=+-]+$/.test(key), keyLen = key.length, isLimit = keyLen <= CHATROOM_KEY_LENGTH.MAX && keyLen >= CHATROOM_KEY_LENGTH.MIN; return isValid && isLimit; }; var isValidChatRoomValue = function isValidChatRoomValue(value) { if (!utils.isString(value)) { return; } var valLen = value.length; return valLen <= CHATROOM_VALUE_LENGTH.MAX && valLen >= CHATROOM_VALUE_LENGTH.MIN; }; var genUploadFileName = function genUploadFileName(type, fileName) { var tpl = '{type}__RC-{date}_{random}_{timestamp}{uuid}{extension}'; var random = Math.floor(Math.random() * 1000 % 10000); var uuid = utils.getUUID(); var fileNameArr, extension; if (fileName) { fileNameArr = fileName.split('.'); extension = '.' + fileNameArr[fileNameArr.length - 1]; } return tplEngine$1(tpl, { type: type, date: utils.formateDate('-'), random: random, uuid: uuid, timestamp: DelayTimer.getTime(), extension: extension || '' }); }; var getUploadFileDomains = function getUploadFileDomains(navi) { var uploadServer = navi.uploadServer, bosAddr = navi.bosAddr; return { qiniu: uploadServer, bos: bosAddr }; }; var mergeConversationList = function mergeConversationList(option) { option = option || {}; var _option4 = option, conversationList = _option4.conversationList, updatedConversationList = _option4.updatedConversationList; var allConversationList = updatedConversationList.concat(conversationList); var hashTable = {}; var newList = []; var invalidDataIndexList = []; utils.forEach(allConversationList, function (conversation) { if (!utils.isObject(conversation)) { return; } var key = getConversationKey(conversation), hashItem = hashTable[key] || {}, hashIndex = utils.isUndefined(hashItem.index) ? newList.length : hashItem.index, hashVal = hashItem.val || {}, cacheUpdatedItems = hashVal.updatedItems || {}, updatedItems = conversation.updatedItems || {}; conversation = utils.extend(conversation, hashVal); utils.forEach(cacheUpdatedItems, function (item, key) { conversation[key] = item.val; }); utils.forEach(updatedItems, function (item, key) { var cacheItem = cacheUpdatedItems[key] || {}, cacheItemUpdatedTime = cacheItem.time || 0; if (item.time > cacheItemUpdatedTime) { conversation[key] = item.val; } }); hashTable[key] = { index: hashIndex, val: conversation }; newList[hashIndex] = conversation; isInValidConversationData(conversation) && invalidDataIndexList.push(hashIndex); }); utils.forEach(invalidDataIndexList, function (invalidIndex) { var conversation = newList[invalidIndex]; newList[invalidIndex] = fixConversationData(conversation); }); newList = sortConList(newList); return utils.map(newList, function (item) { delete item.updatedItems; return item; }); }; var common = { isConnected: isConnected, isConnecting: isConnecting, isDisconnected: isDisconnected, getConnectType: getConnectType, getTransporterUrl: getTransporterUrl, isGroup: isGroup, isChatRoom: isChatRoom, getConversationTypeList: getConversationTypeList, isValidConversationType: isValidConversationType, getUIDByToken: getUIDByToken, getSessionId: getSessionId, getMessageOptionByStatus: getMessageOptionByStatus, getPersitedAndCountedBySessionId: getPersitedAndCountedBySessionId, SignalId: SignalId, MessageTimeSyner: MessageTimeSyner, ChatRoomMessageTimeSyner: ChatRoomMessageTimeSyner, JoinedChatRoomSyner: JoinedChatRoomSyner, getCMPDomainList: getCMPDomainList, getNaviListByToken: getNaviListByToken, getValidToken: getValidToken, RCSocket: RCSocket, RCStorage: RCStorage, getNavReqOption: getNavReqOption, getPingTimeout: getPingTimeout, fixConversationData: fixConversationData, sortConversationList: sortConversationList, DelayTimer: DelayTimer, isSupportStatusMessage: isSupportStatusMessage, getConversationKey: getConversationKey, getConversationByKey: getConversationByKey, getChatRoomKVOptStatus: getChatRoomKVOptStatus, getChatRoomKVByStatus: getChatRoomKVByStatus, TextCompressor: TextCompressor, isBelowIE: isBelowIE, getReportLogUrl: getReportLogUrl, isLogCommandMsg: isLogCommandMsg, getWebSessionId: getWebSessionId, getDeviceId: getDeviceId, stringToCsv: stringToCsv, isValidChatRoomKey: isValidChatRoomKey, isValidChatRoomValue: isValidChatRoomValue, genUploadFileName: genUploadFileName, getUploadFileDomains: getUploadFileDomains, mergeConversationList: mergeConversationList, sortConList: sortConList, getPersitedAndCountedAndSlientBySessionId: getPersitedAndCountedAndSlientBySessionId }; var EventEmitter$1 = utils.EventEmitter, DeferHandler$1 = utils.DeferHandler, Timer$1 = utils.Timer; var RCSocket$1 = common.RCSocket; var TransHandlerID = { CONNECT: 'connect', PING: 'ping' }; var Heartbeat = function () { function Heartbeat(transporter, option) { this._transporter = void 0; this._timer = void 0; option = option || {}; var timeout = option.timeout; this._transporter = transporter; this._timer = new Timer$1({ type: TIMER_TYPE.INTERVAL, timeout: timeout }); } var _proto = Heartbeat.prototype; _proto.check = function check(timeout) { var _transporter = this._transporter; var _deferHandler = _transporter._deferHandler; var pingReqSignal = new PingReqWriter(); _transporter.sendSignal(pingReqSignal); return utils.deferred(function (resolve, reject) { _deferHandler.add(TransHandlerID.PING, { resolve: resolve, reject: reject }, { timeout: timeout }); }); }; _proto.start = function start(timeout, onError) { var self = this; self._timer.start(function () { self.check(timeout).then(utils.noop)["catch"](onError); }); }; _proto.stop = function stop() { this._timer && this._timer.stop(); }; return Heartbeat; }(); var SocketTransporter = function () { function SocketTransporter(option) { this._socket = void 0; this._option = void 0; this._transporterEventEmiiter = new EventEmitter$1(); this._deferHandler = new DeferHandler$1(); this._heartbeat = new Heartbeat(this, { timeout: IM_PING_INTERVAL_TIME }); this._connectedTime = void 0; this._option = option; } var _proto2 = SocketTransporter.prototype; _proto2._createSocket = function _createSocket(url) { var self = this; var _transporterEventEmiiter = self._transporterEventEmiiter; var socket = new RCSocket$1({ url: url }); var onClose = function onClose(event) { event = event || {}; var code = event.code || TRANSPORTER_STATUS.CLOSE_ABNORMAL; _transporterEventEmiiter.emit(TRANSPORT_EVENT.STATUS, code); self.disconnect(); }; socket.onMessage(function (msg) { var data = msg.data; if (!utils.isArrayBuffer(data)) { throw new Error('Error socket signal'); } var signal = readWSBuffer(data); self.handleSignal(signal); }); socket.onError(onClose); socket.onClose(onClose); return socket; }; _proto2._startHeartbeat = function _startHeartbeat(timeSpentConnect) { var self = this; var _heartbeat = self._heartbeat, _transporterEventEmiiter = self._transporterEventEmiiter; _heartbeat.check(FIRST_PING_TIMEOUT).then(utils.noop)["catch"](function () { _transporterEventEmiiter.emit(TRANSPORT_EVENT.STATUS, TRANSPORTER_STATUS.PING_FIRST_TIMEOUT); self.disconnect(); }); var pingTimeout = common.getPingTimeout(timeSpentConnect); _heartbeat.start(pingTimeout, function () { _transporterEventEmiiter.emit(TRANSPORT_EVENT.STATUS, TRANSPORTER_STATUS.PING_TIMEOUT); self.disconnect(); }); }; _proto2._stopHeartbeat = function _stopHeartbeat() { this._heartbeat.stop(); }; _proto2.watchSignal = function watchSignal(watcher) { this._transporterEventEmiiter.on(TRANSPORT_EVENT.SIGNAL, watcher); }; _proto2.watchStatus = function watchStatus(watcher) { this._transporterEventEmiiter.on(TRANSPORT_EVENT.STATUS, watcher); }; _proto2.connect = function connect(user, option) { var self = this; var _self$_option = self._option, appkey = _self$_option.appkey, connectType = _self$_option.connectType, _deferHandler = self._deferHandler; var token = user.token; var domain = option.domain; var url = common.getTransporterUrl({ domain: domain, appkey: appkey, connectType: connectType, token: token }); var timeBeforeConnect = utils.getCurrentTimestamp(); self._socket = this._createSocket(url); return utils.deferred(function (resolve, reject) { _deferHandler.add(TransHandlerID.CONNECT, { resolve: resolve, reject: reject }); }).then(function (result) { var timeAfterConnect = utils.getCurrentTimestamp(); var timeSpentConnect = timeAfterConnect - timeBeforeConnect; self._startHeartbeat(timeSpentConnect); return result; }); }; _proto2.sendSignal = function sendSignal(writer) { var binary = writer.getBufferData(); this._socket.send(binary.buffer); }; _proto2.handleSignal = function handleSignal(signal) { var _transporterEventEmiiter = this._transporterEventEmiiter, _deferHandler = this._deferHandler; if (signal instanceof ConnAckReader) { this.handleConnAck(signal); } else if (signal instanceof PingRespReader) { _deferHandler.resolve(TransHandlerID.PING); } else { _transporterEventEmiiter.emit(TRANSPORT_EVENT.SIGNAL, signal); } if (signal && utils.isValidTimestamp(signal.timestamp)) { common.DelayTimer.setTime(signal.timestamp); } }; _proto2.handleConnAck = function handleConnAck(signal) { var self = this; var _deferHandler = self._deferHandler; var status = signal.status; var isConnected = status === SUCCESS_CODE; var event = isConnected ? _deferHandler.resolve : _deferHandler.reject; event.call(_deferHandler, TransHandlerID.CONNECT, signal); if (isConnected) { self._connectedTime = utils.getCurrentTimestamp(); } }; _proto2.disconnect = function disconnect() { this._stopHeartbeat(); this._socket && this._socket.close(); }; return SocketTransporter; }(); var logEventEmitter = new utils.EventEmitter(); var LogEventName = 'log'; var LocalLogPrefix = '[Rong]'; var ServerOption = DEFAULT_SERVER_OPTION; var Option = { isDebug: false, isUploadToServer: true, appkey: '', userId: '', isNetworkUnavailable: true }; var realTimeUploadHasStarted = false, RealtimeUploadTimes = 1, isRealtimeUploading = false, fullLogId = ''; var isFirstDefaultUpload = function isFirstDefaultUpload(interval) { return interval === 20000; }; var getRealtimeUploadInterval = function getRealtimeUploadInterval(uploadTimes) { var realtimeInterval = ServerOption.realtimeInterval; return realtimeInterval * Math.pow(2, uploadTimes - 1); }; var getFullUploadInterval = function getFullUploadInterval(uploadTimes) { var fullInterval = ServerOption.fullInterval; return fullInterval * Math.pow(2, uploadTimes - 1); }; var getCSVForLog = function getCSVForLog(log) { log = log || {}; var content = log.content || {}; utils.forEach(content, function (val, key) { if (utils.isObject(val) || utils.isArray(val)) { content[key] = utils.toJSON(val); } }); content = utils.toJSON(content) || '""'; content = common.stringToCsv(content); return utils.tplEngine(CSV_LOG_TPL, { sessionId: common.getWebSessionId(), time: log.time, type: log.type, level: log.level, tag: log.tag, content: content }); }; var setServerOption = function setServerOption(serverData) { var logSwitch = serverData.logSwitch, logPolicy = serverData.logPolicy; var isOpen = !!logSwitch; if (utils.isEmpty(serverData)) return; ServerOption.isOpen = isOpen; if (!isOpen) { return; } var logConf = utils.parseJSON(logPolicy || '') || {}; var url = logConf.url, level = logConf.level, itv = logConf.itv, times = logConf.times; utils.extend(ServerOption, { url: url, realtimeLevel: Number(level), realtimeInterval: Number(itv) * 1000, realtimeMaxTimes: Number(times) }); }; var setServerResponseOption = function setServerResponseOption(resText) { var resConf = utils.parseJSON(resText || ''); var nextTime = resConf.nextTime, level = resConf.level, logSwitch = resConf.logSwitch; if (utils.isEmpty(resConf)) return; var isOpen = !!logSwitch; ServerOption.isOpen = isOpen; if (!isOpen) return; utils.extend(ServerOption, { realtimeLevel: Number(level), realtimeInterval: Number(nextTime) * 1000 }); }; var getLogLevel = function getLogLevel(log) { log = log || {}; var _Option = Option, isNetworkUnavailable = _Option.isNetworkUnavailable, _log = log, level = _log.level, isLevelToDegrad = utils.isEqual(level, LEVEL.ERROR) || utils.isEqual(level, LEVEL.WARN); if (isNetworkUnavailable && isLevelToDegrad) { log.level = LEVEL.INFO; } return log; }; var LogStore = { _list: [], MaxSize: common.isBelowIE(9) ? STORE_SIZE.LOW : STORE_SIZE.ADVANCED, add: function add(log) { log = getLogLevel(log); LogStore._list.push(log); var currentSize = LogStore._list.length, maxSize = LogStore.MaxSize; if (currentSize > maxSize) { LogStore._list.splice(0, currentSize - maxSize); } }, get: function get(option) { var type = option.type, uploadLevel = option.level; var _list = LogStore._list; var uploadList = []; utils.forEach(_list, function (log, index) { var logTime = log.time || 0, logLevel = log.level || LEVEL.DEBUG, isUploadLevel = logLevel <= uploadLevel, fullUploadOption = option.fullUploadOption || {}, startTime = fullUploadOption.startTime || 0, endTime = fullUploadOption.endTime || common.DelayTimer.getTime(); var isUpload = isUploadLevel; switch (type) { case REPORT_TYPE.REALTIME: isUpload = isUpload && !log.isUploaded; isUpload && (LogStore._list[index].isUploaded = true); break; case REPORT_TYPE.FULL: isUpload = isUpload && logTime >= startTime && logTime <= endTime; break; default: } if (isUpload) { uploadList.push(log); } }); return uploadList; }, clear: function clear() { LogStore._list = []; } }; var upload = function upload(option) { var url = option.url, logList = option.logList, type = option.type; var requestUrl = common.getReportLogUrl({ type: type, appkey: Option.appkey || '', userId: Option.userId || '', url: url || ServerOption.url || DEFAULT_SERVER_OPTION.url, logId: option.logId }); var csvLog = ''; utils.forEach(logList, function (log) { csvLog += getCSVForLog(log); }); if (utils.isEmpty(csvLog) && type === REPORT_TYPE.REALTIME) { return utils.Defer.reject(); } if (utils.isEmpty(csvLog) && type === REPORT_TYPE.FULL) { csvLog = NO_FULL_LOG; } csvLog = common.TextCompressor.compress(csvLog); return utils.request(requestUrl, { method: REQUEST_METHOD.POST, body: csvLog, timeout: REQUEST_TIMEOUT }); }; var uploadRealtime = function uploadRealtime() { if (isRealtimeUploading) { return; } var interval = getRealtimeUploadInterval(RealtimeUploadTimes); var realtimeMaxTimes = ServerOption.realtimeMaxTimes, realtimeLevel = ServerOption.realtimeLevel; if (RealtimeUploadTimes < realtimeMaxTimes) { RealtimeUploadTimes++; } if (isFirstDefaultUpload(interval)) { RealtimeUploadTimes = 1; } utils.setTimeout(function () { var logList = LogStore.get({ type: REPORT_TYPE.REALTIME, level: realtimeLevel }); isRealtimeUploading = true; upload({ logList: logList, type: REPORT_TYPE.REALTIME }).then(function (response) { isRealtimeUploading = false; var responseText = response.responseText || '{}'; var conf = response.responseText || {}; setServerResponseOption(responseText); if (ServerOption.isOpen) { RealtimeUploadTimes = utils.isEmpty(conf) ? RealtimeUploadTimes : 1; uploadRealtime(); } })["catch"](function () { isRealtimeUploading = false; uploadRealtime(); }); }, interval); }; var uploadFull = function uploadFull(uploadTimes, option, connectedTime) { if (!Option.isUploadToServer || env.isMini) { return; } uploadTimes = uploadTimes || 0; option = option || {}; var _option = option, uri = _option.uri, logId = _option.logId; var isFirst = uploadTimes === 0; var interval = isFirst ? 0 : getFullUploadInterval(uploadTimes); var fullMaxTimes = ServerOption.fullMaxTimes, fullLevel = ServerOption.fullLevel; if (fullLogId === logId) return; if (uploadTimes <= fullMaxTimes) { uploadTimes++; } else { return; } fullLogId = logId; (function (option) { utils.setTimeout(function () { var logList = LogStore.get({ type: REPORT_TYPE.FULL, level: fullLevel, fullUploadOption: option }); if (logList.length === 0 && Number(option.endTime) < connectedTime) return; upload({ logId: logId, url: uri, logList: logList, type: REPORT_TYPE.FULL }).then(function () {})["catch"](function () { uploadFull(uploadTimes, option, connectedTime); }); }, interval); })(option); }; var writeLocalLog = function writeLocalLog(log) { var time = log.time; var formatedTime = utils.formatTime(time); var localLog = LocalLogPrefix + ":" + formatedTime + ": " + utils.toJSON(log); logEventEmitter.emit(LogEventName, localLog); if (Option.isDebug) { utils.consoleLog(localLog); } }; var isIgnoreErrorCode = function isIgnoreErrorCode(code) { return utils.indexOf(IGNORE_ERROR_CODE, code) > -1; }; var Logger = { _events: [], LogStore: LogStore, setOption: function setOption(option) { Option = utils.extend(Option, option); }, setServerOption: setServerOption, watchLog: function watchLog(event) { logEventEmitter.on(LogEventName, event); Logger._events.push(event); }, write: function write(log) { log = log || {}; log.tag = log.tag || TAG.L_CRASH_E; log.time = log.time || common.DelayTimer.getTime(); log.type = log.type || LOG_TYPE.IM; LogStore.add(log); writeLocalLog(log); }, fatal: function fatal(tag, content) { Logger.write({ tag: tag, content: content, level: LEVEL.FATAL }); }, error: function error(tag, content) { Logger.write({ tag: tag, content: content, level: LEVEL.ERROR }); }, warn: function warn(tag, content) { Logger.write({ tag: tag, content: content, level: LEVEL.WARN }); }, info: function info(tag, content) { Logger.write({ tag: tag, content: content, level: LEVEL.INFO }); }, debug: function debug(tag, content) { Logger.write({ tag: tag, content: content, level: LEVEL.DEBUG }); }, startRealtimeUpload: function startRealtimeUpload() { if (realTimeUploadHasStarted) return; if (Option.isUploadToServer && !env.isMini) { uploadRealtime(); } realTimeUploadHasStarted = true; }, resetRealtimeUpload: function resetRealtimeUpload() { RealtimeUploadTimes = 1; }, uploadFull: uploadFull, isIgnoreErrorCode: isIgnoreErrorCode }; var EventEmitter$2 = utils.EventEmitter, DeferHandler$2 = utils.DeferHandler, httpRequest = utils.httpRequest, request$3 = utils.request, Defer$1 = utils.Defer; var CometTransporter = function () { function CometTransporter(option) { this._option = void 0; this._transporterEventEmiiter = new EventEmitter$2(); this._deferHandler = new DeferHandler$2(); this._pid = utils.encodeURI(utils.getCurrentTimestamp() + Math.random() + ''); this._domain = void 0; this._sessionid = void 0; this._xhrCache = new utils.Cache(); this._pullSignalTimer = new utils.Timer({ timeout: IM_COMET_PULLMSG_TIMEOUT }); this._isDisconnected = true; this._option = option; } var _proto = CometTransporter.prototype; _proto._startPullSignal = function _startPullSignal() { var self = this; var _domain = self._domain, _sessionid = self._sessionid, _pid = self._pid, _transporterEventEmiiter = self._transporterEventEmiiter, _pullSignalTimer = self._pullSignalTimer; var timestamp = utils.getCurrentTimestamp(); var protocol = env.protocol.http; var url = utils.tplEngine(COMET_PULL_URL_TPL, { protocol: protocol, timestamp: timestamp, domain: _domain, sessionId: _sessionid, pid: _pid }); var xhr = httpRequest({ url: url, body: { pid: _pid }, timeout: IM_COMET_PULLMSG_TIMEOUT, success: function success(responseText) { _pullSignalTimer.stop(); var isSuccess = self.handleCometResponse(responseText); if (isSuccess) { !self._isDisconnected && self._startPullSignal(); } else if (!self._isDisconnected) { _transporterEventEmiiter.emit(TRANSPORT_EVENT.STATUS, TRANSPORTER_STATUS.COMET_REQUEST_ERROR); } self._xhrCache.remove(url); }, fail: function fail() { _pullSignalTimer.stop(); if (!self._isDisconnected) { _transporterEventEmiiter.emit(TRANSPORT_EVENT.STATUS, TRANSPORTER_STATUS.COMET_REQUEST_ERROR); } self._xhrCache.remove(url); } }); _pullSignalTimer.start(function () { if (!self._isDisconnected) { _transporterEventEmiiter.emit(TRANSPORT_EVENT.STATUS, TRANSPORTER_STATUS.PING_TIMEOUT); self.disconnect(); } }); self._xhrCache.set(url, xhr); }; _proto.watchSignal = function watchSignal(event) { this._transporterEventEmiiter.on(TRANSPORT_EVENT.SIGNAL, event); }; _proto.watchStatus = function watchStatus(event) { this._transporterEventEmiiter.on(TRANSPORT_EVENT.STATUS, function (status) { event && event(status); }); }; _proto.connect = function connect(user, option) { var self = this; var _pid = self._pid, _self$_option = self._option, appkey = _self$_option.appkey, connectType = _self$_option.connectType; var token = user.token; var domain = option.domain; var url = common.getTransporterUrl({ domain: domain, appkey: appkey, token: token, connectType: connectType }); self._domain = domain; self._isDisconnected = false; var success = function success(_ref) { var responseText = _ref.responseText; if (!utils.isValidJSON(responseText)) { return Defer$1.reject(); } var response = utils.isObject(responseText) ? responseText : utils.parseJSON(responseText); var isConnectSuccess = utils.isEqual(response.status, SUCCESS_CODE); if (isConnectSuccess && utils.isObject(response) && utils.isValidTimestamp(response.timestamp)) { common.DelayTimer.setTime(response.timestamp); } return isConnectSuccess ? Defer$1.resolve(response) : Defer$1.reject(response); }; return request$3(url, { body: { pid: _pid } }).then(success).then(function (response) { self._sessionid = response.sessionid; self._startPullSignal(); return response; }); }; _proto.sendSignal = function sendSignal(writer) { var self = this; var _domain = self._domain, _sessionid = self._sessionid, _pid = self._pid; var messageId = writer.messageId, topic = writer.topic, targetId = writer.targetId; var headerCode = writer.getHeaderFlag(); var protocol = env.protocol.http; var TPL = topic ? COMET_REQ_HAS_TOPIC_URL_TPL : COMET_REQ_NO_TOPIC_URL_TPL; var url = utils.tplEngine(TPL, { protocol: protocol, messageId: messageId, headerCode: headerCode, topic: topic, targetId: targetId, pid: _pid, sessionId: _sessionid, domain: _domain }); var currentTime = utils.getCurrentTimestamp() + ''; var xhr = httpRequest({ url: url, method: REQUEST_METHOD.POST, body: writer.getCometData(), success: function success(responseText) { var isSuccess = self.handleCometResponse(responseText); if (!isSuccess) { self.handleError(messageId); } self._xhrCache.remove(currentTime); }, fail: function fail(error) { self.handleError(messageId); self._xhrCache.remove(currentTime); Logger.error(TAG.L_COMET_SEND_SIGNAL_E, { content: { info: 'comet error', error: error } }); } }); self._xhrCache.set(currentTime, xhr); }; _proto.handleCometResponse = function handleCometResponse(responseText) { var self = this; var _transporterEventEmiiter = self._transporterEventEmiiter; var response = utils.isString(responseText) ? utils.parseJSON(responseText) : responseText; if (!response) { return false; } if (!response || !utils.isArray(response)) { return true; } utils.forEach(response, function (data) { var sessionid = data.sessionid; if (sessionid) { self._sessionid = sessionid; } var signal = readCometData(data); _transporterEventEmiiter.emit(TRANSPORT_EVENT.SIGNAL, signal); if (signal && utils.isValidTimestamp(signal.timestamp)) { common.DelayTimer.setTime(signal.timestamp); } }); return true; }; _proto.handleError = function handleError(messageId, status) { var signal = { messageId: messageId, status: status || ERROR_CODE.TIMEOUT }; this._transporterEventEmiiter.emit(TRANSPORT_EVENT.SIGNAL, signal); }; _proto.disconnect = function disconnect() { var self = this; self._isDisconnected = true; var _xhrCache = self._xhrCache, _pullSignalTimer = self._pullSignalTimer; var xhrKeys = _xhrCache.getKeys(); _pullSignalTimer.stop(); utils.forEach(xhrKeys, function (key) { var xhr = _xhrCache.get(key); xhr.abort(); _xhrCache.remove(key); }); }; return CometTransporter; }(); var Transporter = (function (option) { var connectType = option.connectType; var isSocket = connectType === CONNECT_TYPE.WEBSOCKET; var Transporter = isSocket ? SocketTransporter : CometTransporter; return new Transporter(option); }); var PBName = { UpStreamMessage: 'UpStreamMessage', DownStreamMessage: 'DownStreamMessage', DownStreamMessages: 'DownStreamMessages', SessionsAttQryInput: 'SessionsAttQryInput', SessionsAttOutput: 'SessionsAttOutput', SyncRequestMsg: 'SyncRequestMsg', ChrmPullMsg: 'ChrmPullMsg', NotifyMsg: 'NotifyMsg', HistoryMsgInput: 'HistoryMsgInput', HistoryMsgOuput: 'HistoryMsgOuput', RelationQryInput: 'RelationQryInput', RelationsOutput: 'RelationsOutput', DeleteSessionsInput: 'DeleteSessionsInput', SessionInfo: 'SessionInfo', DeleteSessionsOutput: 'DeleteSessionsOutput', RelationsInput: 'RelationsInput', DeleteMsgInput: 'DeleteMsgInput', CleanHisMsgInput: 'CleanHisMsgInput', SessionMsgReadInput: 'SessionMsgReadInput', ChrmInput: 'ChrmInput', QueryChatRoomInfoInput: 'QueryChatRoomInfoInput', QueryChatRoomInfoOutput: 'QueryChatRoomInfoOutput', RtcInput: 'RtcInput', RtcUserListOutput: 'RtcUserListOutput', SetUserStatusInput: 'SetUserStatusInput', RtcSetDataInput: 'RtcSetDataInput', RtcUserSetDataInput: 'RtcUserSetDataInput', RtcDataInput: 'RtcDataInput', RtcSetOutDataInput: 'RtcSetOutDataInput', MCFollowInput: 'MCFollowInput', RtcTokenOutput: 'RtcTokenOutput', RtcQryOutput: 'RtcQryOutput', RtcQryUserOutDataInput: 'RtcQryUserOutDataInput', RtcUserOutDataOutput: 'RtcUserOutDataOutput', RtcQueryListInput: 'RtcQueryListInput', RtcRoomInfoOutput: 'RtcRoomInfoOutput', RtcValueInfo: 'RtcValueInfo', RtcKeyDeleteInput: 'RtcKeyDeleteInput', GetQNupTokenInput: 'GetQNupTokenInput', GetQNupTokenOutput: 'GetQNupTokenOutput', GetQNdownloadUrlInput: 'GetQNdownloadUrlInput', GetQNdownloadUrlOutput: 'GetQNdownloadUrlOutput', SetChrmKV: 'SetChrmKV', ChrmKVOutput: 'ChrmKVOutput', QueryChrmKV: 'QueryChrmKV', ChrmNotifyMsg: 'ChrmNotifyMsg', SetUserSettingInput: 'SetUserSettingInput', SetUserSettingOutput: 'SetUserSettingOutput', PullUserSettingInput: 'PullUserSettingInput', PullUserSettingOutput: 'PullUserSettingOutput', UserSettingNotification: 'UserSettingNotification', SessionReq: 'SessionReq', SessionStates: 'SessionStates', SessionState: 'SessionState', SessionStateItem: 'SessionStateItem', SessionStateModifyReq: 'SessionStateModifyReq', SessionStateModifyResp: 'SessionStateModifyResp' }; var _SSMsg; var SSMsg = (_SSMsg = {}, _SSMsg[PBName.UpStreamMessage] = ['sessionId', 'classname', 'content', 'pushText', 'userId', 'configFlag', 'appData'], _SSMsg[PBName.DownStreamMessages] = ['list', 'syncTime', 'finished'], _SSMsg[PBName.DownStreamMessage] = ['fromUserId', 'type', 'groupId', 'classname', 'content', 'dataTime', 'status', 'msgId'], _SSMsg[PBName.SessionsAttQryInput] = ['nothing'], _SSMsg[PBName.SessionsAttOutput] = ['inboxTime', 'sendboxTime', 'totalUnreadCount'], _SSMsg[PBName.SyncRequestMsg] = ['syncTime', 'ispolling', 'isweb', 'isPullSend', 'isKeeping', 'sendBoxSyncTime'], _SSMsg[PBName.ChrmPullMsg] = ['syncTime', 'count'], _SSMsg[PBName.NotifyMsg] = ['type', 'time', 'chrmId'], _SSMsg[PBName.HistoryMsgInput] = ['targetId', 'time', 'count', 'order'], _SSMsg[PBName.HistoryMsgOuput] = ['list', 'syncTime', 'hasMsg'], _SSMsg[PBName.RelationQryInput] = ['type', 'count', 'startTime', 'order'], _SSMsg[PBName.RelationsOutput] = ['info'], _SSMsg[PBName.DeleteSessionsInput] = ['sessions'], _SSMsg[PBName.SessionInfo] = ['type', 'channelId'], _SSMsg[PBName.DeleteSessionsOutput] = ['nothing'], _SSMsg[PBName.RelationsInput] = ['type', 'msg', 'count', 'offset', 'startTime', 'endTime'], _SSMsg[PBName.DeleteMsgInput] = ['type', 'conversationId', 'msgs'], _SSMsg[PBName.CleanHisMsgInput] = ['targetId', 'dataTime', 'conversationType'], _SSMsg[PBName.SessionMsgReadInput] = ['type', 'msgTime', 'channelId'], _SSMsg[PBName.ChrmInput] = ['nothing'], _SSMsg[PBName.QueryChatRoomInfoInput] = ['count', 'order'], _SSMsg[PBName.QueryChatRoomInfoOutput] = ['userTotalNums', 'userInfos'], _SSMsg[PBName.GetQNupTokenInput] = ['type'], _SSMsg[PBName.GetQNdownloadUrlInput] = ['type', 'key', 'fileName'], _SSMsg[PBName.GetQNupTokenOutput] = ['deadline', 'token'], _SSMsg[PBName.GetQNdownloadUrlOutput] = ['downloadUrl'], _SSMsg[PBName.SetChrmKV] = ['entry', 'bNotify', 'notification', 'type'], _SSMsg[PBName.ChrmKVOutput] = ['entries', 'bFullUpdate', 'syncTime'], _SSMsg[PBName.QueryChrmKV] = ['timestamp'], _SSMsg[PBName.ChrmNotifyMsg] = ['type', 'time', 'chrmId'], _SSMsg[PBName.SetUserSettingInput] = ['version', 'value'], _SSMsg[PBName.SetUserSettingOutput] = ['version', 'reserve'], _SSMsg[PBName.PullUserSettingInput] = ['version', 'reserve'], _SSMsg[PBName.PullUserSettingOutput] = ['items', 'version'], _SSMsg); var Codec = {}; utils.forEach(SSMsg, function (paramList, name) { Codec[name] = function () {}; Codec[name].prototype.data = {}; Codec[name].prototype.getData = function () { return this.data; }; utils.forEach(paramList, function (param) { var setEventName = 'set' + utils.toUpperCase(param, 0, 1); Codec[name].prototype[setEventName] = function (item) { this.data[param] = item; }; }); Codec[name].decode = function (data) { var decodeResult = {}; if (utils.isString(data)) { data = utils.parseJSON(data); } var _loop = function _loop(key) { var getEventName = 'get' + utils.toUpperCase(key, 0, 1); decodeResult[key] = data[key]; decodeResult[getEventName] = function () { return data[key]; }; }; for (var key in data) { _loop(key); } return decodeResult; }; }); Codec.getModule = function (pbName) { var modules = new Codec[pbName](); modules.getArrayData = function () { return modules.getData(); }; return modules; }; function protobuf(a){var b=void 0,c=function(){function a(a,b,c){this.low=0|a,this.high=0|b,this.unsigned=!!c;}function b(a){return (a&&a.__isLong__)===!0}function e(a,b){var e,f,h;return b?(a>>>=0,(h=a>=0&&256>a)&&(f=d[a])?f:(e=g(a,0>(0|a)?-1:0,!0),h&&(d[a]=e),e)):(a|=0,(h=a>=-128&&128>a)&&(f=c[a])?f:(e=g(a,0>a?-1:0,!1),h&&(c[a]=e),e))}function f(a,b){if(isNaN(a)||!isFinite(a))return b?r:q;if(b){if(0>a)return r;if(a>=n)return w}else{if(-o>=a)return x;if(a+1>=o)return v}return 0>a?f(-a,b).neg():g(0|a%m,0|a/m,b)}function g(b,c,d){return new a(b,c,d)}function i(a,b,c){var d,e,g,j,k,l,m;if(0===a.length)throw Error("empty string");if("NaN"===a||"Infinity"===a||"+Infinity"===a||"-Infinity"===a)return q;if("number"==typeof b?(c=b,b=!1):b=!!b,c=c||10,2>c||c>36)throw RangeError("radix");if((d=a.indexOf("-"))>0)throw Error("interior hyphen");if(0===d)return i(a.substring(1),b,c).neg();for(e=f(h(c,8)),g=q,j=0;jk?(m=f(h(c,k)),g=g.mul(m).add(f(l))):(g=g.mul(e),g=g.add(f(l)));return g.unsigned=b,g}function j(b){return b instanceof a?b:"number"==typeof b?f(b):"string"==typeof b?i(b):g(b.low,b.high,b.unsigned)}var c,d,h,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y;return Object.defineProperty(a.prototype,"__isLong__",{value:!0,enumerable:!1,configurable:!1}),a.isLong=b,c={},d={},a.fromInt=e,a.fromNumber=f,a.fromBits=g,h=Math.pow,a.fromString=i,a.fromValue=j,k=65536,l=1<<24,m=k*k,n=m*m,o=n/2,p=e(l),q=e(0),a.ZERO=q,r=e(0,!0),a.UZERO=r,s=e(1),a.ONE=s,t=e(1,!0),a.UONE=t,u=e(-1),a.NEG_ONE=u,v=g(-1,2147483647,!1),a.MAX_VALUE=v,w=g(-1,-1,!0),a.MAX_UNSIGNED_VALUE=w,x=g(0,-2147483648,!1),a.MIN_VALUE=x,y=a.prototype,y.toInt=function(){return this.unsigned?this.low>>>0:this.low},y.toNumber=function(){return this.unsigned?(this.high>>>0)*m+(this.low>>>0):this.high*m+(this.low>>>0)},y.toString=function(a){var b,c,d,e,g,i,j,k,l;if(a=a||10,2>a||a>36)throw RangeError("radix");if(this.isZero())return "0";if(this.isNegative())return this.eq(x)?(b=f(a),c=this.div(b),d=c.mul(b).sub(this),c.toString(a)+d.toInt().toString(a)):"-"+this.neg().toString(a);for(e=f(h(a,6),this.unsigned),g=this,i="";;){if(j=g.div(e),k=g.sub(j.mul(e)).toInt()>>>0,l=k.toString(a),g=j,g.isZero())return l+i;for(;l.length<6;)l="0"+l;i=""+l+i;}},y.getHighBits=function(){return this.high},y.getHighBitsUnsigned=function(){return this.high>>>0},y.getLowBits=function(){return this.low},y.getLowBitsUnsigned=function(){return this.low>>>0},y.getNumBitsAbs=function(){var a,b;if(this.isNegative())return this.eq(x)?64:this.neg().getNumBitsAbs();for(a=0!=this.high?this.high:this.low,b=31;b>0&&0==(a&1<=0},y.isOdd=function(){return 1===(1&this.low)},y.isEven=function(){return 0===(1&this.low)},y.equals=function(a){return b(a)||(a=j(a)),this.unsigned!==a.unsigned&&1===this.high>>>31&&1===a.high>>>31?!1:this.high===a.high&&this.low===a.low},y.eq=y.equals,y.notEquals=function(a){return !this.eq(a)},y.neq=y.notEquals,y.lessThan=function(a){return this.comp(a)<0},y.lt=y.lessThan,y.lessThanOrEqual=function(a){return this.comp(a)<=0},y.lte=y.lessThanOrEqual,y.greaterThan=function(a){return this.comp(a)>0},y.gt=y.greaterThan,y.greaterThanOrEqual=function(a){return this.comp(a)>=0},y.gte=y.greaterThanOrEqual,y.compare=function(a){if(b(a)||(a=j(a)),this.eq(a))return 0;var c=this.isNegative(),d=a.isNegative();return c&&!d?-1:!c&&d?1:this.unsigned?a.high>>>0>this.high>>>0||a.high===this.high&&a.low>>>0>this.low>>>0?-1:1:this.sub(a).isNegative()?-1:1},y.comp=y.compare,y.negate=function(){return !this.unsigned&&this.eq(x)?x:this.not().add(s)},y.neg=y.negate,y.add=function(a){var c,d,e,f,h,i,k,l,m,n,o,p;return b(a)||(a=j(a)),c=this.high>>>16,d=65535&this.high,e=this.low>>>16,f=65535&this.low,h=a.high>>>16,i=65535&a.high,k=a.low>>>16,l=65535&a.low,m=0,n=0,o=0,p=0,p+=f+l,o+=p>>>16,p&=65535,o+=e+k,n+=o>>>16,o&=65535,n+=d+i,m+=n>>>16,n&=65535,m+=c+h,m&=65535,g(o<<16|p,m<<16|n,this.unsigned)},y.subtract=function(a){return b(a)||(a=j(a)),this.add(a.neg())},y.sub=y.subtract,y.multiply=function(a){var c,d,e,h,i,k,l,m,n,o,r,s;return this.isZero()?q:(b(a)||(a=j(a)),a.isZero()?q:this.eq(x)?a.isOdd()?x:q:a.eq(x)?this.isOdd()?x:q:this.isNegative()?a.isNegative()?this.neg().mul(a.neg()):this.neg().mul(a).neg():a.isNegative()?this.mul(a.neg()).neg():this.lt(p)&&a.lt(p)?f(this.toNumber()*a.toNumber(),this.unsigned):(c=this.high>>>16,d=65535&this.high,e=this.low>>>16,h=65535&this.low,i=a.high>>>16,k=65535&a.high,l=a.low>>>16,m=65535&a.low,n=0,o=0,r=0,s=0,s+=h*m,r+=s>>>16,s&=65535,r+=e*m,o+=r>>>16,r&=65535,r+=h*l,o+=r>>>16,r&=65535,o+=d*m,n+=o>>>16,o&=65535,o+=e*l,n+=o>>>16,o&=65535,o+=h*k,n+=o>>>16,o&=65535,n+=c*m+d*l+e*k+h*i,n&=65535,g(r<<16|s,n<<16|o,this.unsigned)))},y.mul=y.multiply,y.divide=function(a){var c,d,e,g,i,k,l,m;if(b(a)||(a=j(a)),a.isZero())throw Error("division by zero");if(this.isZero())return this.unsigned?r:q;if(this.unsigned){if(a.unsigned||(a=a.toUnsigned()),a.gt(this))return r;if(a.gt(this.shru(1)))return t;e=r;}else{if(this.eq(x))return a.eq(s)||a.eq(u)?x:a.eq(x)?s:(g=this.shr(1),c=g.div(a).shl(1),c.eq(q)?a.isNegative()?s:u:(d=this.sub(a.mul(c)),e=c.add(d.div(a))));if(a.eq(x))return this.unsigned?r:q;if(this.isNegative())return a.isNegative()?this.neg().div(a.neg()):this.neg().div(a).neg();if(a.isNegative())return this.div(a.neg()).neg();e=q;}for(d=this;d.gte(a);){for(c=Math.max(1,Math.floor(d.toNumber()/a.toNumber())),i=Math.ceil(Math.log(c)/Math.LN2),k=48>=i?1:h(2,i-48),l=f(c),m=l.mul(a);m.isNegative()||m.gt(d);)c-=k,l=f(c,this.unsigned),m=l.mul(a);l.isZero()&&(l=s),e=e.add(l),d=d.sub(m);}return e},y.div=y.divide,y.modulo=function(a){return b(a)||(a=j(a)),this.sub(this.div(a).mul(a))},y.mod=y.modulo,y.not=function(){return g(~this.low,~this.high,this.unsigned)},y.and=function(a){return b(a)||(a=j(a)),g(this.low&a.low,this.high&a.high,this.unsigned)},y.or=function(a){return b(a)||(a=j(a)),g(this.low|a.low,this.high|a.high,this.unsigned)},y.xor=function(a){return b(a)||(a=j(a)),g(this.low^a.low,this.high^a.high,this.unsigned)},y.shiftLeft=function(a){return b(a)&&(a=a.toInt()),0===(a&=63)?this:32>a?g(this.low<>>32-a,this.unsigned):g(0,this.low<a?g(this.low>>>a|this.high<<32-a,this.high>>a,this.unsigned):g(this.high>>a-32,this.high>=0?0:-1,this.unsigned)},y.shr=y.shiftRight,y.shiftRightUnsigned=function(a){var c,d;return b(a)&&(a=a.toInt()),a&=63,0===a?this:(c=this.high,32>a?(d=this.low,g(d>>>a|c<<32-a,c>>>a,this.unsigned)):32===a?g(c,0,this.unsigned):g(c>>>a-32,0,this.unsigned))},y.shru=y.shiftRightUnsigned,y.toSigned=function(){return this.unsigned?g(this.low,this.high,!1):this},y.toUnsigned=function(){return this.unsigned?this:g(this.low,this.high,!0)},y.toBytes=function(a){return a?this.toBytesLE():this.toBytesBE()},y.toBytesLE=function(){var a=this.high,b=this.low;return [255&b,255&b>>>8,255&b>>>16,255&b>>>24,255&a,255&a>>>8,255&a>>>16,255&a>>>24]},y.toBytesBE=function(){var a=this.high,b=this.low;return [255&a>>>24,255&a>>>16,255&a>>>8,255&a,255&b>>>24,255&b>>>16,255&b>>>8,255&b]},a}(),d=function(a){function f(a){var b=0;return function(){return b1024&&(b.push(e.apply(String,a)),a.length=0),Array.prototype.push.apply(a,arguments),void 0)}}function h(a,b,c,d,e){var f,g,h=8*e-d-1,i=(1<>1,k=-7,l=c?e-1:0,m=c?-1:1,n=a[b+l];for(l+=m,f=n&(1<<-k)-1,n>>=-k,k+=h;k>0;f=256*f+a[b+l],l+=m,k-=8);for(g=f&(1<<-k)-1,f>>=-k,k+=d;k>0;g=256*g+a[b+l],l+=m,k-=8);if(0===f)f=1-j;else{if(f===i)return g?0/0:1/0*(n?-1:1);g+=Math.pow(2,d),f-=j;}return (n?-1:1)*g*Math.pow(2,f-d)}function i(a,b,c,d,e,f){var g,h,i,j=8*f-e-1,k=(1<>1,m=23===e?Math.pow(2,-24)-Math.pow(2,-77):0,n=d?0:f-1,o=d?1:-1,p=0>b||0===b&&0>1/b?1:0;for(b=Math.abs(b),isNaN(b)||1/0===b?(h=isNaN(b)?1:0,g=k):(g=Math.floor(Math.log(b)/Math.LN2),b*(i=Math.pow(2,-g))<1&&(g--,i*=2),b+=g+l>=1?m/i:m*Math.pow(2,1-l),b*i>=2&&(g++,i/=2),g+l>=k?(h=0,g=k):g+l>=1?(h=(b*i-1)*Math.pow(2,e),g+=l):(h=b*Math.pow(2,l-1)*Math.pow(2,e),g=0));e>=8;a[c+n]=255&h,n+=o,h/=256,e-=8);for(g=g<0;a[c+n]=255&g,n+=o,g/=256,j-=8);a[c+n-o]|=128*p;}var c,d,e,j,k,b=function(a,c,e){if("undefined"==typeof a&&(a=b.DEFAULT_CAPACITY),"undefined"==typeof c&&(c=b.DEFAULT_ENDIAN),"undefined"==typeof e&&(e=b.DEFAULT_NOASSERT),!e){if(a=0|a,0>a)throw RangeError("Illegal capacity");c=!!c,e=!!e;}this.buffer=0===a?d:new ArrayBuffer(a),this.view=0===a?null:new Uint8Array(this.buffer),this.offset=0,this.markedOffset=-1,this.limit=a,this.littleEndian=c,this.noAssert=e;};return b.VERSION="5.0.1",b.LITTLE_ENDIAN=!0,b.BIG_ENDIAN=!1,b.DEFAULT_CAPACITY=16,b.DEFAULT_ENDIAN=b.BIG_ENDIAN,b.DEFAULT_NOASSERT=!1,b.Long=a||null,c=b.prototype,c.__isByteBuffer__,Object.defineProperty(c,"__isByteBuffer__",{value:!0,enumerable:!1,configurable:!1}),d=new ArrayBuffer(0),e=String.fromCharCode,b.accessor=function(){return Uint8Array},b.allocate=function(a,c,d){return new b(a,c,d)},b.concat=function(a,c,d,e){var f,i,g,h,k,j;for(("boolean"==typeof c||"string"!=typeof c)&&(e=d,d=c,c=void 0),f=0,g=0,h=a.length;h>g;++g)b.isByteBuffer(a[g])||(a[g]=b.wrap(a[g],c)),i=a[g].limit-a[g].offset,i>0&&(f+=i);if(0===f)return new b(0,d,e);for(j=new b(f,d,e),g=0;h>g;)k=a[g++],i=k.limit-k.offset,0>=i||(j.view.set(k.view.subarray(k.offset,k.limit),j.offset),j.offset+=i);return j.limit=j.offset,j.offset=0,j},b.isByteBuffer=function(a){return (a&&a.__isByteBuffer__)===!0},b.type=function(){return ArrayBuffer},b.wrap=function(a,d,e,f){var g,h;if("string"!=typeof d&&(f=e,e=d,d=void 0),"string"==typeof a)switch("undefined"==typeof d&&(d="utf8"),d){case"base64":return b.fromBase64(a,e);case"hex":return b.fromHex(a,e);case"binary":return b.fromBinary(a,e);case"utf8":return b.fromUTF8(a,e);case"debug":return b.fromDebug(a,e);default:throw Error("Unsupported encoding: "+d)}if(null===a||"object"!=typeof a)throw TypeError("Illegal buffer");if(b.isByteBuffer(a))return g=c.clone.call(a),g.markedOffset=-1,g;if(a instanceof Uint8Array)g=new b(0,e,f),a.length>0&&(g.buffer=a.buffer,g.offset=a.byteOffset,g.limit=a.byteOffset+a.byteLength,g.view=new Uint8Array(a.buffer));else if(a instanceof ArrayBuffer)g=new b(0,e,f),a.byteLength>0&&(g.buffer=a,g.offset=0,g.limit=a.byteLength,g.view=a.byteLength>0?new Uint8Array(a):null);else{if("[object Array]"!==Object.prototype.toString.call(a))throw TypeError("Illegal buffer");for(g=new b(a.length,e,f),g.limit=a.length,h=0;h>>=0,0>b||b+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+b+" (+"+0+") <= "+this.buffer.byteLength)}for(d=b,e=a.length,f=e>>3,g=0,b+=this.writeVarint32(e,b);f--;)h=1&!!a[g++]|(1&!!a[g++])<<1|(1&!!a[g++])<<2|(1&!!a[g++])<<3|(1&!!a[g++])<<4|(1&!!a[g++])<<5|(1&!!a[g++])<<6|(1&!!a[g++])<<7,this.writeByte(h,b++);if(e>g){for(i=0,h=0;e>g;)h|=(1&!!a[g++])<>3,f=0,g=[],a+=c.length;e--;)h=this.readByte(a++),g[f++]=!!(1&h),g[f++]=!!(2&h),g[f++]=!!(4&h),g[f++]=!!(8&h),g[f++]=!!(16&h),g[f++]=!!(32&h),g[f++]=!!(64&h),g[f++]=!!(128&h);if(d>f)for(i=0,h=this.readByte(a++);d>f;)g[f++]=!!(1&h>>i++);return b&&(this.offset=a),g},c.readBytes=function(a,b){var d,c="undefined"==typeof b;if(c&&(b=this.offset),!this.noAssert){if("number"!=typeof b||0!==b%1)throw TypeError("Illegal offset: "+b+" (not an integer)");if(b>>>=0,0>b||b+a>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+b+" (+"+a+") <= "+this.buffer.byteLength)}return d=this.slice(b,b+a),c&&(this.offset+=a),d},c.writeBytes=c.append,c.writeInt8=function(a,b){var d,c="undefined"==typeof b;if(c&&(b=this.offset),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal value: "+a+" (not an integer)");if(a|=0,"number"!=typeof b||0!==b%1)throw TypeError("Illegal offset: "+b+" (not an integer)");if(b>>>=0,0>b||b+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+b+" (+"+0+") <= "+this.buffer.byteLength)}return b+=1,d=this.buffer.byteLength,b>d&&this.resize((d*=2)>b?d:b),b-=1,this.view[b]=a,c&&(this.offset+=1),this},c.writeByte=c.writeInt8,c.readInt8=function(a){var c,b="undefined"==typeof a;if(b&&(a=this.offset),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal offset: "+a+" (not an integer)");if(a>>>=0,0>a||a+1>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+a+" (+"+1+") <= "+this.buffer.byteLength)}return c=this.view[a],128===(128&c)&&(c=-(255-c+1)),b&&(this.offset+=1),c},c.readByte=c.readInt8,c.writeUint8=function(a,b){var d,c="undefined"==typeof b;if(c&&(b=this.offset),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal value: "+a+" (not an integer)");if(a>>>=0,"number"!=typeof b||0!==b%1)throw TypeError("Illegal offset: "+b+" (not an integer)");if(b>>>=0,0>b||b+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+b+" (+"+0+") <= "+this.buffer.byteLength)}return b+=1,d=this.buffer.byteLength,b>d&&this.resize((d*=2)>b?d:b),b-=1,this.view[b]=a,c&&(this.offset+=1),this},c.writeUInt8=c.writeUint8,c.readUint8=function(a){var c,b="undefined"==typeof a;if(b&&(a=this.offset),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal offset: "+a+" (not an integer)");if(a>>>=0,0>a||a+1>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+a+" (+"+1+") <= "+this.buffer.byteLength)}return c=this.view[a],b&&(this.offset+=1),c},c.readUInt8=c.readUint8,c.writeInt16=function(a,b){var d,c="undefined"==typeof b;if(c&&(b=this.offset),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal value: "+a+" (not an integer)");if(a|=0,"number"!=typeof b||0!==b%1)throw TypeError("Illegal offset: "+b+" (not an integer)");if(b>>>=0,0>b||b+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+b+" (+"+0+") <= "+this.buffer.byteLength)}return b+=2,d=this.buffer.byteLength,b>d&&this.resize((d*=2)>b?d:b),b-=2,this.littleEndian?(this.view[b+1]=(65280&a)>>>8,this.view[b]=255&a):(this.view[b]=(65280&a)>>>8,this.view[b+1]=255&a),c&&(this.offset+=2),this},c.writeShort=c.writeInt16,c.readInt16=function(a){var c,b="undefined"==typeof a;if(b&&(a=this.offset),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal offset: "+a+" (not an integer)");if(a>>>=0,0>a||a+2>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+a+" (+"+2+") <= "+this.buffer.byteLength)}return c=0,this.littleEndian?(c=this.view[a],c|=this.view[a+1]<<8):(c=this.view[a]<<8,c|=this.view[a+1]),32768===(32768&c)&&(c=-(65535-c+1)),b&&(this.offset+=2),c},c.readShort=c.readInt16,c.writeUint16=function(a,b){var d,c="undefined"==typeof b;if(c&&(b=this.offset),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal value: "+a+" (not an integer)");if(a>>>=0,"number"!=typeof b||0!==b%1)throw TypeError("Illegal offset: "+b+" (not an integer)");if(b>>>=0,0>b||b+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+b+" (+"+0+") <= "+this.buffer.byteLength)}return b+=2,d=this.buffer.byteLength,b>d&&this.resize((d*=2)>b?d:b),b-=2,this.littleEndian?(this.view[b+1]=(65280&a)>>>8,this.view[b]=255&a):(this.view[b]=(65280&a)>>>8,this.view[b+1]=255&a),c&&(this.offset+=2),this},c.writeUInt16=c.writeUint16,c.readUint16=function(a){var c,b="undefined"==typeof a;if(b&&(a=this.offset),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal offset: "+a+" (not an integer)");if(a>>>=0,0>a||a+2>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+a+" (+"+2+") <= "+this.buffer.byteLength)}return c=0,this.littleEndian?(c=this.view[a],c|=this.view[a+1]<<8):(c=this.view[a]<<8,c|=this.view[a+1]),b&&(this.offset+=2),c},c.readUInt16=c.readUint16,c.writeInt32=function(a,b){var d,c="undefined"==typeof b;if(c&&(b=this.offset),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal value: "+a+" (not an integer)");if(a|=0,"number"!=typeof b||0!==b%1)throw TypeError("Illegal offset: "+b+" (not an integer)");if(b>>>=0,0>b||b+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+b+" (+"+0+") <= "+this.buffer.byteLength)}return b+=4,d=this.buffer.byteLength,b>d&&this.resize((d*=2)>b?d:b),b-=4,this.littleEndian?(this.view[b+3]=255&a>>>24,this.view[b+2]=255&a>>>16,this.view[b+1]=255&a>>>8,this.view[b]=255&a):(this.view[b]=255&a>>>24,this.view[b+1]=255&a>>>16,this.view[b+2]=255&a>>>8,this.view[b+3]=255&a),c&&(this.offset+=4),this},c.writeInt=c.writeInt32,c.readInt32=function(a){var c,b="undefined"==typeof a;if(b&&(a=this.offset),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal offset: "+a+" (not an integer)");if(a>>>=0,0>a||a+4>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+a+" (+"+4+") <= "+this.buffer.byteLength)}return c=0,this.littleEndian?(c=this.view[a+2]<<16,c|=this.view[a+1]<<8,c|=this.view[a],c+=this.view[a+3]<<24>>>0):(c=this.view[a+1]<<16,c|=this.view[a+2]<<8,c|=this.view[a+3],c+=this.view[a]<<24>>>0),c|=0,b&&(this.offset+=4),c},c.readInt=c.readInt32,c.writeUint32=function(a,b){var d,c="undefined"==typeof b;if(c&&(b=this.offset),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal value: "+a+" (not an integer)");if(a>>>=0,"number"!=typeof b||0!==b%1)throw TypeError("Illegal offset: "+b+" (not an integer)");if(b>>>=0,0>b||b+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+b+" (+"+0+") <= "+this.buffer.byteLength)}return b+=4,d=this.buffer.byteLength,b>d&&this.resize((d*=2)>b?d:b),b-=4,this.littleEndian?(this.view[b+3]=255&a>>>24,this.view[b+2]=255&a>>>16,this.view[b+1]=255&a>>>8,this.view[b]=255&a):(this.view[b]=255&a>>>24,this.view[b+1]=255&a>>>16,this.view[b+2]=255&a>>>8,this.view[b+3]=255&a),c&&(this.offset+=4),this},c.writeUInt32=c.writeUint32,c.readUint32=function(a){var c,b="undefined"==typeof a;if(b&&(a=this.offset),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal offset: "+a+" (not an integer)");if(a>>>=0,0>a||a+4>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+a+" (+"+4+") <= "+this.buffer.byteLength)}return c=0,this.littleEndian?(c=this.view[a+2]<<16,c|=this.view[a+1]<<8,c|=this.view[a],c+=this.view[a+3]<<24>>>0):(c=this.view[a+1]<<16,c|=this.view[a+2]<<8,c|=this.view[a+3],c+=this.view[a]<<24>>>0),b&&(this.offset+=4),c},c.readUInt32=c.readUint32,a&&(c.writeInt64=function(b,c){var e,f,g,d="undefined"==typeof c;if(d&&(c=this.offset),!this.noAssert){if("number"==typeof b)b=a.fromNumber(b);else if("string"==typeof b)b=a.fromString(b);else if(!(b&&b instanceof a))throw TypeError("Illegal value: "+b+" (not an integer or Long)");if("number"!=typeof c||0!==c%1)throw TypeError("Illegal offset: "+c+" (not an integer)");if(c>>>=0,0>c||c+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+c+" (+"+0+") <= "+this.buffer.byteLength)}return "number"==typeof b?b=a.fromNumber(b):"string"==typeof b&&(b=a.fromString(b)),c+=8,e=this.buffer.byteLength,c>e&&this.resize((e*=2)>c?e:c),c-=8,f=b.low,g=b.high,this.littleEndian?(this.view[c+3]=255&f>>>24,this.view[c+2]=255&f>>>16,this.view[c+1]=255&f>>>8,this.view[c]=255&f,c+=4,this.view[c+3]=255&g>>>24,this.view[c+2]=255&g>>>16,this.view[c+1]=255&g>>>8,this.view[c]=255&g):(this.view[c]=255&g>>>24,this.view[c+1]=255&g>>>16,this.view[c+2]=255&g>>>8,this.view[c+3]=255&g,c+=4,this.view[c]=255&f>>>24,this.view[c+1]=255&f>>>16,this.view[c+2]=255&f>>>8,this.view[c+3]=255&f),d&&(this.offset+=8),this},c.writeLong=c.writeInt64,c.readInt64=function(b){var d,e,f,c="undefined"==typeof b;if(c&&(b=this.offset),!this.noAssert){if("number"!=typeof b||0!==b%1)throw TypeError("Illegal offset: "+b+" (not an integer)");if(b>>>=0,0>b||b+8>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+b+" (+"+8+") <= "+this.buffer.byteLength)}return d=0,e=0,this.littleEndian?(d=this.view[b+2]<<16,d|=this.view[b+1]<<8,d|=this.view[b],d+=this.view[b+3]<<24>>>0,b+=4,e=this.view[b+2]<<16,e|=this.view[b+1]<<8,e|=this.view[b],e+=this.view[b+3]<<24>>>0):(e=this.view[b+1]<<16,e|=this.view[b+2]<<8,e|=this.view[b+3],e+=this.view[b]<<24>>>0,b+=4,d=this.view[b+1]<<16,d|=this.view[b+2]<<8,d|=this.view[b+3],d+=this.view[b]<<24>>>0),f=new a(d,e,!1),c&&(this.offset+=8),f},c.readLong=c.readInt64,c.writeUint64=function(b,c){var e,f,g,d="undefined"==typeof c;if(d&&(c=this.offset),!this.noAssert){if("number"==typeof b)b=a.fromNumber(b);else if("string"==typeof b)b=a.fromString(b);else if(!(b&&b instanceof a))throw TypeError("Illegal value: "+b+" (not an integer or Long)");if("number"!=typeof c||0!==c%1)throw TypeError("Illegal offset: "+c+" (not an integer)");if(c>>>=0,0>c||c+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+c+" (+"+0+") <= "+this.buffer.byteLength)}return "number"==typeof b?b=a.fromNumber(b):"string"==typeof b&&(b=a.fromString(b)),c+=8,e=this.buffer.byteLength,c>e&&this.resize((e*=2)>c?e:c),c-=8,f=b.low,g=b.high,this.littleEndian?(this.view[c+3]=255&f>>>24,this.view[c+2]=255&f>>>16,this.view[c+1]=255&f>>>8,this.view[c]=255&f,c+=4,this.view[c+3]=255&g>>>24,this.view[c+2]=255&g>>>16,this.view[c+1]=255&g>>>8,this.view[c]=255&g):(this.view[c]=255&g>>>24,this.view[c+1]=255&g>>>16,this.view[c+2]=255&g>>>8,this.view[c+3]=255&g,c+=4,this.view[c]=255&f>>>24,this.view[c+1]=255&f>>>16,this.view[c+2]=255&f>>>8,this.view[c+3]=255&f),d&&(this.offset+=8),this},c.writeUInt64=c.writeUint64,c.readUint64=function(b){var d,e,f,c="undefined"==typeof b;if(c&&(b=this.offset),!this.noAssert){if("number"!=typeof b||0!==b%1)throw TypeError("Illegal offset: "+b+" (not an integer)");if(b>>>=0,0>b||b+8>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+b+" (+"+8+") <= "+this.buffer.byteLength)}return d=0,e=0,this.littleEndian?(d=this.view[b+2]<<16,d|=this.view[b+1]<<8,d|=this.view[b],d+=this.view[b+3]<<24>>>0,b+=4,e=this.view[b+2]<<16,e|=this.view[b+1]<<8,e|=this.view[b],e+=this.view[b+3]<<24>>>0):(e=this.view[b+1]<<16,e|=this.view[b+2]<<8,e|=this.view[b+3],e+=this.view[b]<<24>>>0,b+=4,d=this.view[b+1]<<16,d|=this.view[b+2]<<8,d|=this.view[b+3],d+=this.view[b]<<24>>>0),f=new a(d,e,!0),c&&(this.offset+=8),f},c.readUInt64=c.readUint64),c.writeFloat32=function(a,b){var d,c="undefined"==typeof b;if(c&&(b=this.offset),!this.noAssert){if("number"!=typeof a)throw TypeError("Illegal value: "+a+" (not a number)");if("number"!=typeof b||0!==b%1)throw TypeError("Illegal offset: "+b+" (not an integer)");if(b>>>=0,0>b||b+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+b+" (+"+0+") <= "+this.buffer.byteLength)}return b+=4,d=this.buffer.byteLength,b>d&&this.resize((d*=2)>b?d:b),b-=4,i(this.view,a,b,this.littleEndian,23,4),c&&(this.offset+=4),this},c.writeFloat=c.writeFloat32,c.readFloat32=function(a){var c,b="undefined"==typeof a;if(b&&(a=this.offset),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal offset: "+a+" (not an integer)");if(a>>>=0,0>a||a+4>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+a+" (+"+4+") <= "+this.buffer.byteLength)}return c=h(this.view,a,this.littleEndian,23,4),b&&(this.offset+=4),c},c.readFloat=c.readFloat32,c.writeFloat64=function(a,b){var d,c="undefined"==typeof b;if(c&&(b=this.offset),!this.noAssert){if("number"!=typeof a)throw TypeError("Illegal value: "+a+" (not a number)");if("number"!=typeof b||0!==b%1)throw TypeError("Illegal offset: "+b+" (not an integer)");if(b>>>=0,0>b||b+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+b+" (+"+0+") <= "+this.buffer.byteLength)}return b+=8,d=this.buffer.byteLength,b>d&&this.resize((d*=2)>b?d:b),b-=8,i(this.view,a,b,this.littleEndian,52,8),c&&(this.offset+=8),this},c.writeDouble=c.writeFloat64,c.readFloat64=function(a){var c,b="undefined"==typeof a;if(b&&(a=this.offset),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal offset: "+a+" (not an integer)");if(a>>>=0,0>a||a+8>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+a+" (+"+8+") <= "+this.buffer.byteLength)}return c=h(this.view,a,this.littleEndian,52,8),b&&(this.offset+=8),c},c.readDouble=c.readFloat64,b.MAX_VARINT32_BYTES=5,b.calculateVarint32=function(a){return a>>>=0,128>a?1:16384>a?2:1<<21>a?3:1<<28>a?4:5},b.zigZagEncode32=function(a){return ((a|=0)<<1^a>>31)>>>0},b.zigZagDecode32=function(a){return 0|a>>>1^-(1&a)},c.writeVarint32=function(a,c){var f,e,g,d="undefined"==typeof c;if(d&&(c=this.offset),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal value: "+a+" (not an integer)");if(a|=0,"number"!=typeof c||0!==c%1)throw TypeError("Illegal offset: "+c+" (not an integer)");if(c>>>=0,0>c||c+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+c+" (+"+0+") <= "+this.buffer.byteLength)}for(e=b.calculateVarint32(a),c+=e,g=this.buffer.byteLength,c>g&&this.resize((g*=2)>c?g:c),c-=e,a>>>=0;a>=128;)f=128|127&a,this.view[c++]=f,a>>>=7;return this.view[c++]=a,d?(this.offset=c,this):e},c.writeVarint32ZigZag=function(a,c){return this.writeVarint32(b.zigZagEncode32(a),c)},c.readVarint32=function(a){var e,c,d,f,b="undefined"==typeof a;if(b&&(a=this.offset),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal offset: "+a+" (not an integer)");if(a>>>=0,0>a||a+1>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+a+" (+"+1+") <= "+this.buffer.byteLength)}c=0,d=0;do{if(!this.noAssert&&a>this.limit)throw f=Error("Truncated"),f.truncated=!0,f;e=this.view[a++],5>c&&(d|=(127&e)<<7*c),++c;}while(0!==(128&e));return d|=0,b?(this.offset=a,d):{value:d,length:c}},c.readVarint32ZigZag=function(a){var c=this.readVarint32(a);return "object"==typeof c?c.value=b.zigZagDecode32(c.value):c=b.zigZagDecode32(c),c},a&&(b.MAX_VARINT64_BYTES=10,b.calculateVarint64=function(b){"number"==typeof b?b=a.fromNumber(b):"string"==typeof b&&(b=a.fromString(b));var c=b.toInt()>>>0,d=b.shiftRightUnsigned(28).toInt()>>>0,e=b.shiftRightUnsigned(56).toInt()>>>0;return 0==e?0==d?16384>c?128>c?1:2:1<<21>c?3:4:16384>d?128>d?5:6:1<<21>d?7:8:128>e?9:10},b.zigZagEncode64=function(b){return "number"==typeof b?b=a.fromNumber(b,!1):"string"==typeof b?b=a.fromString(b,!1):b.unsigned!==!1&&(b=b.toSigned()),b.shiftLeft(1).xor(b.shiftRight(63)).toUnsigned()},b.zigZagDecode64=function(b){return "number"==typeof b?b=a.fromNumber(b,!1):"string"==typeof b?b=a.fromString(b,!1):b.unsigned!==!1&&(b=b.toSigned()),b.shiftRightUnsigned(1).xor(b.and(a.ONE).toSigned().negate()).toSigned()},c.writeVarint64=function(c,d){var f,g,h,i,j,e="undefined"==typeof d;if(e&&(d=this.offset),!this.noAssert){if("number"==typeof c)c=a.fromNumber(c);else if("string"==typeof c)c=a.fromString(c);else if(!(c&&c instanceof a))throw TypeError("Illegal value: "+c+" (not an integer or Long)");if("number"!=typeof d||0!==d%1)throw TypeError("Illegal offset: "+d+" (not an integer)");if(d>>>=0,0>d||d+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+d+" (+"+0+") <= "+this.buffer.byteLength)}switch("number"==typeof c?c=a.fromNumber(c,!1):"string"==typeof c?c=a.fromString(c,!1):c.unsigned!==!1&&(c=c.toSigned()),f=b.calculateVarint64(c),g=c.toInt()>>>0,h=c.shiftRightUnsigned(28).toInt()>>>0,i=c.shiftRightUnsigned(56).toInt()>>>0,d+=f,j=this.buffer.byteLength,d>j&&this.resize((j*=2)>d?j:d),d-=f,f){case 10:this.view[d+9]=1&i>>>7;case 9:this.view[d+8]=9!==f?128|i:127&i;case 8:this.view[d+7]=8!==f?128|h>>>21:127&h>>>21;case 7:this.view[d+6]=7!==f?128|h>>>14:127&h>>>14;case 6:this.view[d+5]=6!==f?128|h>>>7:127&h>>>7;case 5:this.view[d+4]=5!==f?128|h:127&h;case 4:this.view[d+3]=4!==f?128|g>>>21:127&g>>>21;case 3:this.view[d+2]=3!==f?128|g>>>14:127&g>>>14;case 2:this.view[d+1]=2!==f?128|g>>>7:127&g>>>7;case 1:this.view[d]=1!==f?128|g:127&g;}return e?(this.offset+=f,this):f},c.writeVarint64ZigZag=function(a,c){return this.writeVarint64(b.zigZagEncode64(a),c)},c.readVarint64=function(b){var d,e,f,g,h,i,c="undefined"==typeof b;if(c&&(b=this.offset),!this.noAssert){if("number"!=typeof b||0!==b%1)throw TypeError("Illegal offset: "+b+" (not an integer)");if(b>>>=0,0>b||b+1>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+b+" (+"+1+") <= "+this.buffer.byteLength)}if(d=b,e=0,f=0,g=0,h=0,h=this.view[b++],e=127&h,128&h&&(h=this.view[b++],e|=(127&h)<<7,(128&h||this.noAssert&&"undefined"==typeof h)&&(h=this.view[b++],e|=(127&h)<<14,(128&h||this.noAssert&&"undefined"==typeof h)&&(h=this.view[b++],e|=(127&h)<<21,(128&h||this.noAssert&&"undefined"==typeof h)&&(h=this.view[b++],f=127&h,(128&h||this.noAssert&&"undefined"==typeof h)&&(h=this.view[b++],f|=(127&h)<<7,(128&h||this.noAssert&&"undefined"==typeof h)&&(h=this.view[b++],f|=(127&h)<<14,(128&h||this.noAssert&&"undefined"==typeof h)&&(h=this.view[b++],f|=(127&h)<<21,(128&h||this.noAssert&&"undefined"==typeof h)&&(h=this.view[b++],g=127&h,(128&h||this.noAssert&&"undefined"==typeof h)&&(h=this.view[b++],g|=(127&h)<<7,128&h||this.noAssert&&"undefined"==typeof h))))))))))throw Error("Buffer overrun");return i=a.fromBits(e|f<<28,f>>>4|g<<24,!1),c?(this.offset=b,i):{value:i,length:b-d}},c.readVarint64ZigZag=function(c){var d=this.readVarint64(c);return d&&d.value instanceof a?d.value=b.zigZagDecode64(d.value):d=b.zigZagDecode64(d),d}),c.writeCString=function(a,b){var d,e,g,c="undefined"==typeof b;if(c&&(b=this.offset),e=a.length,!this.noAssert){if("string"!=typeof a)throw TypeError("Illegal str: Not a string");for(d=0;e>d;++d)if(0===a.charCodeAt(d))throw RangeError("Illegal str: Contains NULL-characters");if("number"!=typeof b||0!==b%1)throw TypeError("Illegal offset: "+b+" (not an integer)");if(b>>>=0,0>b||b+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+b+" (+"+0+") <= "+this.buffer.byteLength)}return e=k.calculateUTF16asUTF8(f(a))[1],b+=e+1,g=this.buffer.byteLength,b>g&&this.resize((g*=2)>b?g:b),b-=e+1,k.encodeUTF16toUTF8(f(a),function(a){this.view[b++]=a;}.bind(this)),this.view[b++]=0,c?(this.offset=b,this):e},c.readCString=function(a){var c,e,f,b="undefined"==typeof a;if(b&&(a=this.offset),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal offset: "+a+" (not an integer)");if(a>>>=0,0>a||a+1>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+a+" (+"+1+") <= "+this.buffer.byteLength)}return c=a,f=-1,k.decodeUTF8toUTF16(function(){if(0===f)return null;if(a>=this.limit)throw RangeError("Illegal range: Truncated data, "+a+" < "+this.limit);return f=this.view[a++],0===f?null:f}.bind(this),e=g(),!0),b?(this.offset=a,e()):{string:e(),length:a-c}},c.writeIString=function(a,b){var e,d,g,c="undefined"==typeof b;if(c&&(b=this.offset),!this.noAssert){if("string"!=typeof a)throw TypeError("Illegal str: Not a string");if("number"!=typeof b||0!==b%1)throw TypeError("Illegal offset: "+b+" (not an integer)");if(b>>>=0,0>b||b+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+b+" (+"+0+") <= "+this.buffer.byteLength)}if(d=b,e=k.calculateUTF16asUTF8(f(a),this.noAssert)[1],b+=4+e,g=this.buffer.byteLength,b>g&&this.resize((g*=2)>b?g:b),b-=4+e,this.littleEndian?(this.view[b+3]=255&e>>>24,this.view[b+2]=255&e>>>16,this.view[b+1]=255&e>>>8,this.view[b]=255&e):(this.view[b]=255&e>>>24,this.view[b+1]=255&e>>>16,this.view[b+2]=255&e>>>8,this.view[b+3]=255&e),b+=4,k.encodeUTF16toUTF8(f(a),function(a){this.view[b++]=a;}.bind(this)),b!==d+4+e)throw RangeError("Illegal range: Truncated data, "+b+" == "+(b+4+e));return c?(this.offset=b,this):b-d},c.readIString=function(a){var d,e,f,c="undefined"==typeof a; if(c&&(a=this.offset),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal offset: "+a+" (not an integer)");if(a>>>=0,0>a||a+4>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+a+" (+"+4+") <= "+this.buffer.byteLength)}return d=a,e=this.readUint32(a),f=this.readUTF8String(e,b.METRICS_BYTES,a+=4),a+=f.length,c?(this.offset=a,f.string):{string:f.string,length:a-d}},b.METRICS_CHARS="c",b.METRICS_BYTES="b",c.writeUTF8String=function(a,b){var d,e,g,c="undefined"==typeof b;if(c&&(b=this.offset),!this.noAssert){if("number"!=typeof b||0!==b%1)throw TypeError("Illegal offset: "+b+" (not an integer)");if(b>>>=0,0>b||b+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+b+" (+"+0+") <= "+this.buffer.byteLength)}return e=b,d=k.calculateUTF16asUTF8(f(a))[1],b+=d,g=this.buffer.byteLength,b>g&&this.resize((g*=2)>b?g:b),b-=d,k.encodeUTF16toUTF8(f(a),function(a){this.view[b++]=a;}.bind(this)),c?(this.offset=b,this):b-e},c.writeString=c.writeUTF8String,b.calculateUTF8Chars=function(a){return k.calculateUTF16asUTF8(f(a))[0]},b.calculateUTF8Bytes=function(a){return k.calculateUTF16asUTF8(f(a))[1]},b.calculateString=b.calculateUTF8Bytes,c.readUTF8String=function(a,c,d){var e,i,f,h,j;if("number"==typeof c&&(d=c,c=void 0),e="undefined"==typeof d,e&&(d=this.offset),"undefined"==typeof c&&(c=b.METRICS_CHARS),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal length: "+a+" (not an integer)");if(a|=0,"number"!=typeof d||0!==d%1)throw TypeError("Illegal offset: "+d+" (not an integer)");if(d>>>=0,0>d||d+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+d+" (+"+0+") <= "+this.buffer.byteLength)}if(f=0,h=d,c===b.METRICS_CHARS){if(i=g(),k.decodeUTF8(function(){return a>f&&d>>=0,0>d||d+a>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+d+" (+"+a+") <= "+this.buffer.byteLength)}if(j=d+a,k.decodeUTF8toUTF16(function(){return j>d?this.view[d++]:null}.bind(this),i=g(),this.noAssert),d!==j)throw RangeError("Illegal range: Truncated data, "+d+" == "+j);return e?(this.offset=d,i()):{string:i(),length:d-h}}throw TypeError("Unsupported metrics: "+c)},c.readString=c.readUTF8String,c.writeVString=function(a,c){var g,h,e,i,d="undefined"==typeof c;if(d&&(c=this.offset),!this.noAssert){if("string"!=typeof a)throw TypeError("Illegal str: Not a string");if("number"!=typeof c||0!==c%1)throw TypeError("Illegal offset: "+c+" (not an integer)");if(c>>>=0,0>c||c+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+c+" (+"+0+") <= "+this.buffer.byteLength)}if(e=c,g=k.calculateUTF16asUTF8(f(a),this.noAssert)[1],h=b.calculateVarint32(g),c+=h+g,i=this.buffer.byteLength,c>i&&this.resize((i*=2)>c?i:c),c-=h+g,c+=this.writeVarint32(g,c),k.encodeUTF16toUTF8(f(a),function(a){this.view[c++]=a;}.bind(this)),c!==e+g+h)throw RangeError("Illegal range: Truncated data, "+c+" == "+(c+g+h));return d?(this.offset=c,this):c-e},c.readVString=function(a){var d,e,f,c="undefined"==typeof a;if(c&&(a=this.offset),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal offset: "+a+" (not an integer)");if(a>>>=0,0>a||a+1>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+a+" (+"+1+") <= "+this.buffer.byteLength)}return d=a,e=this.readVarint32(a),f=this.readUTF8String(e.value,b.METRICS_BYTES,a+=e.length),a+=f.length,c?(this.offset=a,f.string):{string:f.string,length:a-d}},c.append=function(a,c,d){var e,f,g;if(("number"==typeof c||"string"!=typeof c)&&(d=c,c=void 0),e="undefined"==typeof d,e&&(d=this.offset),!this.noAssert){if("number"!=typeof d||0!==d%1)throw TypeError("Illegal offset: "+d+" (not an integer)");if(d>>>=0,0>d||d+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+d+" (+"+0+") <= "+this.buffer.byteLength)}return a instanceof b||(a=b.wrap(a,c)),f=a.limit-a.offset,0>=f?this:(d+=f,g=this.buffer.byteLength,d>g&&this.resize((g*=2)>d?g:d),d-=f,this.view.set(a.view.subarray(a.offset,a.limit),d),a.offset+=f,e&&(this.offset+=f),this)},c.appendTo=function(a,b){return a.append(this,b),this},c.assert=function(a){return this.noAssert=!a,this},c.capacity=function(){return this.buffer.byteLength},c.clear=function(){return this.offset=0,this.limit=this.buffer.byteLength,this.markedOffset=-1,this},c.clone=function(a){var c=new b(0,this.littleEndian,this.noAssert);return a?(c.buffer=new ArrayBuffer(this.buffer.byteLength),c.view=new Uint8Array(c.buffer)):(c.buffer=this.buffer,c.view=this.view),c.offset=this.offset,c.markedOffset=this.markedOffset,c.limit=this.limit,c},c.compact=function(a,b){var c,e,f;if("undefined"==typeof a&&(a=this.offset),"undefined"==typeof b&&(b=this.limit),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal begin: Not an integer");if(a>>>=0,"number"!=typeof b||0!==b%1)throw TypeError("Illegal end: Not an integer");if(b>>>=0,0>a||a>b||b>this.buffer.byteLength)throw RangeError("Illegal range: 0 <= "+a+" <= "+b+" <= "+this.buffer.byteLength)}return 0===a&&b===this.buffer.byteLength?this:(c=b-a,0===c?(this.buffer=d,this.view=null,this.markedOffset>=0&&(this.markedOffset-=a),this.offset=0,this.limit=0,this):(e=new ArrayBuffer(c),f=new Uint8Array(e),f.set(this.view.subarray(a,b)),this.buffer=e,this.view=f,this.markedOffset>=0&&(this.markedOffset-=a),this.offset=0,this.limit=c,this))},c.copy=function(a,c){if("undefined"==typeof a&&(a=this.offset),"undefined"==typeof c&&(c=this.limit),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal begin: Not an integer");if(a>>>=0,"number"!=typeof c||0!==c%1)throw TypeError("Illegal end: Not an integer");if(c>>>=0,0>a||a>c||c>this.buffer.byteLength)throw RangeError("Illegal range: 0 <= "+a+" <= "+c+" <= "+this.buffer.byteLength)}if(a===c)return new b(0,this.littleEndian,this.noAssert);var d=c-a,e=new b(d,this.littleEndian,this.noAssert);return e.offset=0,e.limit=d,e.markedOffset>=0&&(e.markedOffset-=a),this.copyTo(e,0,a,c),e},c.copyTo=function(a,c,d,e){var f,g,h;if(!this.noAssert&&!b.isByteBuffer(a))throw TypeError("Illegal target: Not a ByteBuffer");if(c=(g="undefined"==typeof c)?a.offset:0|c,d=(f="undefined"==typeof d)?this.offset:0|d,e="undefined"==typeof e?this.limit:0|e,0>c||c>a.buffer.byteLength)throw RangeError("Illegal target range: 0 <= "+c+" <= "+a.buffer.byteLength);if(0>d||e>this.buffer.byteLength)throw RangeError("Illegal source range: 0 <= "+d+" <= "+this.buffer.byteLength);return h=e-d,0===h?a:(a.ensureCapacity(c+h),a.view.set(this.view.subarray(d,e),c),f&&(this.offset+=h),g&&(a.offset+=h),this)},c.ensureCapacity=function(a){var b=this.buffer.byteLength;return a>b?this.resize((b*=2)>a?b:a):this},c.fill=function(a,b,c){var d="undefined"==typeof b;if(d&&(b=this.offset),"string"==typeof a&&a.length>0&&(a=a.charCodeAt(0)),"undefined"==typeof b&&(b=this.offset),"undefined"==typeof c&&(c=this.limit),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal value: "+a+" (not an integer)");if(a|=0,"number"!=typeof b||0!==b%1)throw TypeError("Illegal begin: Not an integer");if(b>>>=0,"number"!=typeof c||0!==c%1)throw TypeError("Illegal end: Not an integer");if(c>>>=0,0>b||b>c||c>this.buffer.byteLength)throw RangeError("Illegal range: 0 <= "+b+" <= "+c+" <= "+this.buffer.byteLength)}if(b>=c)return this;for(;c>b;)this.view[b++]=a;return d&&(this.offset=b),this},c.flip=function(){return this.limit=this.offset,this.offset=0,this},c.mark=function(a){if(a="undefined"==typeof a?this.offset:a,!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal offset: "+a+" (not an integer)");if(a>>>=0,0>a||a+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+a+" (+"+0+") <= "+this.buffer.byteLength)}return this.markedOffset=a,this},c.order=function(a){if(!this.noAssert&&"boolean"!=typeof a)throw TypeError("Illegal littleEndian: Not a boolean");return this.littleEndian=!!a,this},c.LE=function(a){return this.littleEndian="undefined"!=typeof a?!!a:!0,this},c.BE=function(a){return this.littleEndian="undefined"!=typeof a?!a:!1,this},c.prepend=function(a,c,d){var e,f,g,h,i;if(("number"==typeof c||"string"!=typeof c)&&(d=c,c=void 0),e="undefined"==typeof d,e&&(d=this.offset),!this.noAssert){if("number"!=typeof d||0!==d%1)throw TypeError("Illegal offset: "+d+" (not an integer)");if(d>>>=0,0>d||d+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+d+" (+"+0+") <= "+this.buffer.byteLength)}return a instanceof b||(a=b.wrap(a,c)),f=a.limit-a.offset,0>=f?this:(g=f-d,g>0?(h=new ArrayBuffer(this.buffer.byteLength+g),i=new Uint8Array(h),i.set(this.view.subarray(d,this.buffer.byteLength),f),this.buffer=h,this.view=i,this.offset+=g,this.markedOffset>=0&&(this.markedOffset+=g),this.limit+=g,d+=g):new Uint8Array(this.buffer),this.view.set(a.view.subarray(a.offset,a.limit),d-f),a.offset=a.limit,e&&(this.offset-=f),this)},c.prependTo=function(a,b){return a.prepend(this,b),this},c.printDebug=function(a){"function"!=typeof a&&(a=console.log.bind(console)),a(this.toString()+"\n-------------------------------------------------------------------\n"+this.toDebug(!0));},c.remaining=function(){return this.limit-this.offset},c.reset=function(){return this.markedOffset>=0?(this.offset=this.markedOffset,this.markedOffset=-1):this.offset=0,this},c.resize=function(a){var b,c;if(!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal capacity: "+a+" (not an integer)");if(a|=0,0>a)throw RangeError("Illegal capacity: 0 <= "+a)}return this.buffer.byteLength>>=0,"number"!=typeof b||0!==b%1)throw TypeError("Illegal end: Not an integer");if(b>>>=0,0>a||a>b||b>this.buffer.byteLength)throw RangeError("Illegal range: 0 <= "+a+" <= "+b+" <= "+this.buffer.byteLength)}return a===b?this:(Array.prototype.reverse.call(this.view.subarray(a,b)),this)},c.skip=function(a){if(!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal length: "+a+" (not an integer)");a|=0;}var b=this.offset+a;if(!this.noAssert&&(0>b||b>this.buffer.byteLength))throw RangeError("Illegal length: 0 <= "+this.offset+" + "+a+" <= "+this.buffer.byteLength);return this.offset=b,this},c.slice=function(a,b){if("undefined"==typeof a&&(a=this.offset),"undefined"==typeof b&&(b=this.limit),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal begin: Not an integer");if(a>>>=0,"number"!=typeof b||0!==b%1)throw TypeError("Illegal end: Not an integer");if(b>>>=0,0>a||a>b||b>this.buffer.byteLength)throw RangeError("Illegal range: 0 <= "+a+" <= "+b+" <= "+this.buffer.byteLength)}var c=this.clone();return c.offset=a,c.limit=b,c},c.toBuffer=function(a){var e,b=this.offset,c=this.limit;if(!this.noAssert){if("number"!=typeof b||0!==b%1)throw TypeError("Illegal offset: Not an integer");if(b>>>=0,"number"!=typeof c||0!==c%1)throw TypeError("Illegal limit: Not an integer");if(c>>>=0,0>b||b>c||c>this.buffer.byteLength)throw RangeError("Illegal range: 0 <= "+b+" <= "+c+" <= "+this.buffer.byteLength)}return a||0!==b||c!==this.buffer.byteLength?b===c?d:(e=new ArrayBuffer(c-b),new Uint8Array(e).set(new Uint8Array(this.buffer).subarray(b,c),0),e):this.buffer},c.toArrayBuffer=c.toBuffer,c.toString=function(a,b,c){if("undefined"==typeof a)return "ByteBufferAB(offset="+this.offset+",markedOffset="+this.markedOffset+",limit="+this.limit+",capacity="+this.capacity()+")";switch("number"==typeof a&&(a="utf8",b=a,c=b),a){case"utf8":return this.toUTF8(b,c);case"base64":return this.toBase64(b,c);case"hex":return this.toHex(b,c);case"binary":return this.toBinary(b,c);case"debug":return this.toDebug();case"columns":return this.toColumns();default:throw Error("Unsupported encoding: "+a)}},j=function(){var d,e,a={},b=[65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,48,49,50,51,52,53,54,55,56,57,43,47],c=[];for(d=0,e=b.length;e>d;++d)c[b[d]]=d;return a.encode=function(a,c){for(var d,e;null!==(d=a());)c(b[63&d>>2]),e=(3&d)<<4,null!==(d=a())?(e|=15&d>>4,c(b[63&(e|15&d>>4)]),e=(15&d)<<2,null!==(d=a())?(c(b[63&(e|3&d>>6)]),c(b[63&d])):(c(b[63&e]),c(61))):(c(b[63&e]),c(61),c(61));},a.decode=function(a,b){function g(a){throw Error("Illegal character code: "+a)}for(var d,e,f;null!==(d=a());)if(e=c[d],"undefined"==typeof e&&g(d),null!==(d=a())&&(f=c[d],"undefined"==typeof f&&g(d),b(e<<2>>>0|(48&f)>>4),null!==(d=a()))){if(e=c[d],"undefined"==typeof e){if(61===d)break;g(d);}if(b((15&f)<<4>>>0|(60&e)>>2),null!==(d=a())){if(f=c[d],"undefined"==typeof f){if(61===d)break;g(d);}b((3&e)<<6>>>0|f);}}},a.test=function(a){return /^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/.test(a)},a}(),c.toBase64=function(a,b){if("undefined"==typeof a&&(a=this.offset),"undefined"==typeof b&&(b=this.limit),a=0|a,b=0|b,0>a||b>this.capacity||a>b)throw RangeError("begin, end");var c;return j.encode(function(){return b>a?this.view[a++]:null}.bind(this),c=g()),c()},b.fromBase64=function(a,c){if("string"!=typeof a)throw TypeError("str");var d=new b(3*(a.length/4),c),e=0;return j.decode(f(a),function(a){d.view[e++]=a;}),d.limit=e,d},b.btoa=function(a){return b.fromBinary(a).toBase64()},b.atob=function(a){return b.fromBase64(a).toBinary()},c.toBinary=function(a,b){if("undefined"==typeof a&&(a=this.offset),"undefined"==typeof b&&(b=this.limit),a|=0,b|=0,0>a||b>this.capacity()||a>b)throw RangeError("begin, end");if(a===b)return "";for(var c=[],d=[];b>a;)c.push(this.view[a++]),c.length>=1024&&(d.push(String.fromCharCode.apply(String,c)),c=[]);return d.join("")+String.fromCharCode.apply(String,c)},b.fromBinary=function(a,c){if("string"!=typeof a)throw TypeError("str");for(var f,d=0,e=a.length,g=new b(e,c);e>d;){if(f=a.charCodeAt(d),f>255)throw RangeError("illegal char code: "+f);g.view[d++]=f;}return g.limit=e,g},c.toDebug=function(a){for(var d,b=-1,c=this.buffer.byteLength,e="",f="",g="";c>b;){if(-1!==b&&(d=this.view[b],e+=16>d?"0"+d.toString(16).toUpperCase():d.toString(16).toUpperCase(),a&&(f+=d>32&&127>d?String.fromCharCode(d):".")),++b,a&&b>0&&0===b%16&&b!==c){for(;e.length<51;)e+=" ";g+=e+f+"\n",e=f="";}e+=b===this.offset&&b===this.limit?b===this.markedOffset?"!":"|":b===this.offset?b===this.markedOffset?"[":"<":b===this.limit?b===this.markedOffset?"]":">":b===this.markedOffset?"'":a||0!==b&&b!==c?" ":"";}if(a&&" "!==e){for(;e.length<51;)e+=" ";g+=e+f+"\n";}return a?g:e},b.fromDebug=function(a,c,d){for(var i,j,e=a.length,f=new b(0|(e+1)/3,c,d),g=0,h=0,k=!1,l=!1,m=!1,n=!1,o=!1;e>g;){switch(i=a.charAt(g++)){case"!":if(!d){if(l||m||n){o=!0;break}l=m=n=!0;}f.offset=f.markedOffset=f.limit=h,k=!1;break;case"|":if(!d){if(l||n){o=!0;break}l=n=!0;}f.offset=f.limit=h,k=!1;break;case"[":if(!d){if(l||m){o=!0;break}l=m=!0;}f.offset=f.markedOffset=h,k=!1;break;case"<":if(!d){if(l){o=!0;break}l=!0;}f.offset=h,k=!1;break;case"]":if(!d){if(n||m){o=!0;break}n=m=!0;}f.limit=f.markedOffset=h,k=!1;break;case">":if(!d){if(n){o=!0;break}n=!0;}f.limit=h,k=!1;break;case"'":if(!d){if(m){o=!0;break}m=!0;}f.markedOffset=h,k=!1;break;case" ":k=!1;break;default:if(!d&&k){o=!0;break}if(j=parseInt(i+a.charAt(g++),16),!d&&(isNaN(j)||0>j||j>255))throw TypeError("Illegal str: Not a debug encoded string");f.view[h++]=j,k=!0;}if(o)throw TypeError("Illegal str: Invalid symbol at "+g)}if(!d){if(!l||!n)throw TypeError("Illegal str: Missing offset or limit");if(h>>=0,"number"!=typeof b||0!==b%1)throw TypeError("Illegal end: Not an integer");if(b>>>=0,0>a||a>b||b>this.buffer.byteLength)throw RangeError("Illegal range: 0 <= "+a+" <= "+b+" <= "+this.buffer.byteLength)}for(var d,c=new Array(b-a);b>a;)d=this.view[a++],16>d?c.push("0",d.toString(16)):c.push(d.toString(16));return c.join("")},b.fromHex=function(a,c,d){var g,e,f,h,i;if(!d){if("string"!=typeof a)throw TypeError("Illegal str: Not a string");if(0!==a.length%2)throw TypeError("Illegal str: Length not a multiple of 2")}for(e=a.length,f=new b(0|e/2,c),h=0,i=0;e>h;h+=2){if(g=parseInt(a.substring(h,h+2),16),!d&&(!isFinite(g)||0>g||g>255))throw TypeError("Illegal str: Contains non-hex characters");f.view[i++]=g;}return f.limit=i,f},k=function(){var a={};return a.MAX_CODEPOINT=1114111,a.encodeUTF8=function(a,b){var c=null;for("number"==typeof a&&(c=a,a=function(){return null});null!==c||null!==(c=a());)128>c?b(127&c):2048>c?(b(192|31&c>>6),b(128|63&c)):65536>c?(b(224|15&c>>12),b(128|63&c>>6),b(128|63&c)):(b(240|7&c>>18),b(128|63&c>>12),b(128|63&c>>6),b(128|63&c)),c=null;},a.decodeUTF8=function(a,b){for(var c,d,e,f,g=function(a){a=a.slice(0,a.indexOf(null));var b=Error(a.toString());throw b.name="TruncatedError",b.bytes=a,b};null!==(c=a());)if(0===(128&c))b(c);else if(192===(224&c))null===(d=a())&&g([c,d]),b((31&c)<<6|63&d);else if(224===(240&c))(null===(d=a())||null===(e=a()))&&g([c,d,e]),b((15&c)<<12|(63&d)<<6|63&e);else{if(240!==(248&c))throw RangeError("Illegal starting byte: "+c);(null===(d=a())||null===(e=a())||null===(f=a()))&&g([c,d,e,f]),b((7&c)<<18|(63&d)<<12|(63&e)<<6|63&f);}},a.UTF16toUTF8=function(a,b){for(var c,d=null;;){if(null===(c=null!==d?d:a()))break;c>=55296&&57343>=c&&null!==(d=a())&&d>=56320&&57343>=d?(b(1024*(c-55296)+d-56320+65536),d=null):b(c);}null!==d&&b(d);},a.UTF8toUTF16=function(a,b){var c=null;for("number"==typeof a&&(c=a,a=function(){return null});null!==c||null!==(c=a());)65535>=c?b(c):(c-=65536,b((c>>10)+55296),b(c%1024+56320)),c=null;},a.encodeUTF16toUTF8=function(b,c){a.UTF16toUTF8(b,function(b){a.encodeUTF8(b,c);});},a.decodeUTF8toUTF16=function(b,c){a.decodeUTF8(b,function(b){a.UTF8toUTF16(b,c);});},a.calculateCodePoint=function(a){return 128>a?1:2048>a?2:65536>a?3:4},a.calculateUTF8=function(a){for(var b,c=0;null!==(b=a());)c+=128>b?1:2048>b?2:65536>b?3:4;return c},a.calculateUTF16asUTF8=function(b){var c=0,d=0;return a.UTF16toUTF8(b,function(a){++c,d+=128>a?1:2048>a?2:65536>a?3:4;}),[c,d]},a}(),c.toUTF8=function(a,b){if("undefined"==typeof a&&(a=this.offset),"undefined"==typeof b&&(b=this.limit),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal begin: Not an integer");if(a>>>=0,"number"!=typeof b||0!==b%1)throw TypeError("Illegal end: Not an integer");if(b>>>=0,0>a||a>b||b>this.buffer.byteLength)throw RangeError("Illegal range: 0 <= "+a+" <= "+b+" <= "+this.buffer.byteLength)}var c;try{k.decodeUTF8toUTF16(function(){return b>a?this.view[a++]:null}.bind(this),c=g());}catch(d){if(a!==b)throw RangeError("Illegal range: Truncated data, "+a+" != "+b)}return c()},b.fromUTF8=function(a,c,d){if(!d&&"string"!=typeof a)throw TypeError("Illegal str: Not a string");var e=new b(k.calculateUTF16asUTF8(f(a),!0)[1],c,d),g=0;return k.encodeUTF16toUTF8(f(a),function(a){e.view[g++]=a;}),e.limit=g,e},b}(c),e=function(b,c){var f,h,i,e={};return e.ByteBuffer=b,e.c=b,f=b,e.Long=c||null,e.VERSION="5.0.1",e.WIRE_TYPES={},e.WIRE_TYPES.VARINT=0,e.WIRE_TYPES.BITS64=1,e.WIRE_TYPES.LDELIM=2,e.WIRE_TYPES.STARTGROUP=3,e.WIRE_TYPES.ENDGROUP=4,e.WIRE_TYPES.BITS32=5,e.PACKABLE_WIRE_TYPES=[e.WIRE_TYPES.VARINT,e.WIRE_TYPES.BITS64,e.WIRE_TYPES.BITS32],e.TYPES={int32:{name:"int32",wireType:e.WIRE_TYPES.VARINT,defaultValue:0},uint32:{name:"uint32",wireType:e.WIRE_TYPES.VARINT,defaultValue:0},sint32:{name:"sint32",wireType:e.WIRE_TYPES.VARINT,defaultValue:0},int64:{name:"int64",wireType:e.WIRE_TYPES.VARINT,defaultValue:e.Long?e.Long.ZERO:void 0},uint64:{name:"uint64",wireType:e.WIRE_TYPES.VARINT,defaultValue:e.Long?e.Long.UZERO:void 0},sint64:{name:"sint64",wireType:e.WIRE_TYPES.VARINT,defaultValue:e.Long?e.Long.ZERO:void 0},bool:{name:"bool",wireType:e.WIRE_TYPES.VARINT,defaultValue:!1},"double":{name:"double",wireType:e.WIRE_TYPES.BITS64,defaultValue:0},string:{name:"string",wireType:e.WIRE_TYPES.LDELIM,defaultValue:""},bytes:{name:"bytes",wireType:e.WIRE_TYPES.LDELIM,defaultValue:null},fixed32:{name:"fixed32",wireType:e.WIRE_TYPES.BITS32,defaultValue:0},sfixed32:{name:"sfixed32",wireType:e.WIRE_TYPES.BITS32,defaultValue:0},fixed64:{name:"fixed64",wireType:e.WIRE_TYPES.BITS64,defaultValue:e.Long?e.Long.UZERO:void 0},sfixed64:{name:"sfixed64",wireType:e.WIRE_TYPES.BITS64,defaultValue:e.Long?e.Long.ZERO:void 0},"float":{name:"float",wireType:e.WIRE_TYPES.BITS32,defaultValue:0},"enum":{name:"enum",wireType:e.WIRE_TYPES.VARINT,defaultValue:0},message:{name:"message",wireType:e.WIRE_TYPES.LDELIM,defaultValue:null},group:{name:"group",wireType:e.WIRE_TYPES.STARTGROUP,defaultValue:null}},e.MAP_KEY_TYPES=[e.TYPES.int32,e.TYPES.sint32,e.TYPES.sfixed32,e.TYPES.uint32,e.TYPES.fixed32,e.TYPES.int64,e.TYPES.sint64,e.TYPES.sfixed64,e.TYPES.uint64,e.TYPES.fixed64,e.TYPES.bool,e.TYPES.string,e.TYPES.bytes],e.ID_MIN=1,e.ID_MAX=536870911,e.convertFieldsToCamelCase=!1,e.populateAccessors=!0,e.populateDefaults=!0,e.Util=function(){var a={};return a.IS_NODE=!("object"!=typeof process||"[object process]"!=process+""||process.browser),a.XHR=function(){var c,a=[function(){return new XMLHttpRequest},function(){return new ActiveXObject("Msxml2.XMLHTTP")},function(){return new ActiveXObject("Msxml3.XMLHTTP")},function(){return new ActiveXObject("Microsoft.XMLHTTP")}],b=null;for(c=0;c]/g,RULE:/^(?:required|optional|repeated|map)$/,TYPE:/^(?:double|float|int32|uint32|sint32|int64|uint64|sint64|fixed32|sfixed32|fixed64|sfixed64|bool|string|bytes)$/,NAME:/^[a-zA-Z_][a-zA-Z_0-9]*$/,TYPEDEF:/^[a-zA-Z][a-zA-Z_0-9]*$/,TYPEREF:/^(?:\.?[a-zA-Z_][a-zA-Z_0-9]*)+$/,FQTYPEREF:/^(?:\.[a-zA-Z][a-zA-Z_0-9]*)+$/,NUMBER:/^-?(?:[1-9][0-9]*|0|0[xX][0-9a-fA-F]+|0[0-7]+|([0-9]*(\.[0-9]*)?([Ee][+-]?[0-9]+)?)|inf|nan)$/,NUMBER_DEC:/^(?:[1-9][0-9]*|0)$/,NUMBER_HEX:/^0[xX][0-9a-fA-F]+$/,NUMBER_OCT:/^0[0-7]+$/,NUMBER_FLT:/^([0-9]*(\.[0-9]*)?([Ee][+-]?[0-9]+)?|inf|nan)$/,BOOL:/^(?:true|false)$/i,ID:/^(?:[1-9][0-9]*|0|0[xX][0-9a-fA-F]+|0[0-7]+)$/,NEGID:/^\-?(?:[1-9][0-9]*|0|0[xX][0-9a-fA-F]+|0[0-7]+)$/,WHITESPACE:/\s/,STRING:/(?:"([^"\\]*(?:\\.[^"\\]*)*)")|(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g,STRING_DQ:/(?:"([^"\\]*(?:\\.[^"\\]*)*)")/g,STRING_SQ:/(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g},e.DotProto=function(a,b){function h(a,c){var d=-1,e=1;if("-"==a.charAt(0)&&(e=-1,a=a.substring(1)),b.NUMBER_DEC.test(a))d=parseInt(a);else if(b.NUMBER_HEX.test(a))d=parseInt(a.substring(2),16);else{if(!b.NUMBER_OCT.test(a))throw Error("illegal id value: "+(0>e?"-":"")+a);d=parseInt(a.substring(1),8);}if(d=0|e*d,!c&&0>d)throw Error("illegal id value: "+(0>e?"-":"")+a);return d}function i(a){var c=1;if("-"==a.charAt(0)&&(c=-1,a=a.substring(1)),b.NUMBER_DEC.test(a))return c*parseInt(a,10);if(b.NUMBER_HEX.test(a))return c*parseInt(a.substring(2),16);if(b.NUMBER_OCT.test(a))return c*parseInt(a.substring(1),8);if("inf"===a)return 1/0*c;if("nan"===a)return 0/0;if(b.NUMBER_FLT.test(a))return c*parseFloat(a);throw Error("illegal number value: "+(0>c?"-":"")+a)}function j(a,b,c){"undefined"==typeof a[b]?a[b]=c:(Array.isArray(a[b])||(a[b]=[a[b]]),a[b].push(c));}var f,g,c={},d=function(a){this.source=a+"",this.index=0,this.line=1,this.stack=[],this._stringOpen=null;},e=d.prototype;return e._readString=function(){var c,a='"'===this._stringOpen?b.STRING_DQ:b.STRING_SQ;if(a.lastIndex=this.index-1,c=a.exec(this.source),!c)throw Error("unterminated string");return this.index=a.lastIndex,this.stack.push(this._stringOpen),this._stringOpen=null,c[1]},e.next=function(){var a,c,d,e,f,g;if(this.stack.length>0)return this.stack.shift();if(this.index>=this.source.length)return null;if(null!==this._stringOpen)return this._readString();do{for(a=!1;b.WHITESPACE.test(d=this.source.charAt(this.index));)if("\n"===d&&++this.line,++this.index===this.source.length)return null;if("/"===this.source.charAt(this.index))if(++this.index,"/"===this.source.charAt(this.index)){for(;"\n"!==this.source.charAt(++this.index);)if(this.index==this.source.length)return null;++this.index,++this.line,a=!0;}else{if("*"!==(d=this.source.charAt(this.index)))return "/";do{if("\n"===d&&++this.line,++this.index===this.source.length)return null;c=d,d=this.source.charAt(this.index);}while("*"!==c||"/"!==d);++this.index,a=!0;}}while(a);if(this.index===this.source.length)return null;if(e=this.index,b.DELIM.lastIndex=0,f=b.DELIM.test(this.source.charAt(e++)),!f)for(;e"),f=this.tn.next(),!b.NAME.test(f))throw Error("illegal message field name: "+f);e.name=f,this.tn.skip("="),e.id=h(this.tn.next()),f=this.tn.peek(),"["===f&&this._parseFieldOptions(e),this.tn.skip(";");}else if(d="undefined"!=typeof d?d:this.tn.next(),"group"===d){if(g=this._parseMessage(a,e),!/^[A-Z]/.test(g.name))throw Error("illegal group name: "+g.name);e.type=g.name,e.name=g.name.toLowerCase(),this.tn.omit(";");}else{if(!b.TYPE.test(d)&&!b.TYPEREF.test(d))throw Error("illegal message field type: "+d);if(e.type=d,f=this.tn.next(),!b.NAME.test(f))throw Error("illegal message field name: "+f); e.name=f,this.tn.skip("="),e.id=h(this.tn.next()),f=this.tn.peek(),"["===f&&this._parseFieldOptions(e),this.tn.skip(";");}return a.fields.push(e),e},g._parseMessageOneOf=function(a){var e,d,f,c=this.tn.next();if(!b.NAME.test(c))throw Error("illegal oneof name: "+c);for(d=c,f=[],this.tn.skip("{");"}"!==(c=this.tn.next());)e=this._parseMessageField(a,"optional",c),e.oneof=d,f.push(e.id);this.tn.omit(";"),a.oneofs[d]=f;},g._parseFieldOptions=function(a){this.tn.skip("[");for(var b,c=!0;"]"!==(b=this.tn.peek());)c||this.tn.skip(","),this._parseOption(a,!0),c=!1;this.tn.next();},g._parseEnum=function(a){var e,c={name:"",values:[],options:{}},d=this.tn.next();if(!b.NAME.test(d))throw Error("illegal name: "+d);for(c.name=d,this.tn.skip("{");"}"!==(d=this.tn.next());)if("option"===d)this._parseOption(c);else{if(!b.NAME.test(d))throw Error("illegal name: "+d);this.tn.skip("="),e={name:d,id:h(this.tn.next(),!0)},d=this.tn.peek(),"["===d&&this._parseFieldOptions({options:{}}),this.tn.skip(";"),c.values.push(e);}this.tn.omit(";"),a.enums.push(c);},g._parseExtensionRanges=function(){var c,d,e,b=[];do{for(d=[];;){switch(c=this.tn.next()){case"min":e=a.ID_MIN;break;case"max":e=a.ID_MAX;break;default:e=i(c);}if(d.push(e),2===d.length)break;if("to"!==this.tn.peek()){d.push(e);break}this.tn.next();}b.push(d);}while(this.tn.omit(","));return this.tn.skip(";"),b},g._parseExtend=function(a){var d,c=this.tn.next();if(!b.TYPEREF.test(c))throw Error("illegal extend reference: "+c);for(d={ref:c,fields:[]},this.tn.skip("{");"}"!==(c=this.tn.next());)if(b.RULE.test(c))this._parseMessageField(d,c);else{if(!b.TYPEREF.test(c))throw Error("illegal extend token: "+c);if(!this.proto3)throw Error("illegal field rule: "+c);this._parseMessageField(d,"optional",c);}return this.tn.omit(";"),a.messages.push(d),d},g.toString=function(){return "Parser at line "+this.tn.line},c.Parser=f,c}(e,e.Lang),e.Reflect=function(a){function k(b){if("string"==typeof b&&(b=a.TYPES[b]),"undefined"==typeof b.defaultValue)throw Error("default value for type "+b.name+" is not supported");return b==a.TYPES.bytes?new f(0):b.defaultValue}function l(b,c){if(b&&"number"==typeof b.low&&"number"==typeof b.high&&"boolean"==typeof b.unsigned&&b.low===b.low&&b.high===b.high)return new a.Long(b.low,b.high,"undefined"==typeof c?b.unsigned:c);if("string"==typeof b)return a.Long.fromString(b,c||!1,10);if("number"==typeof b)return a.Long.fromNumber(b,c||!1);throw Error("not convertible to Long")}function o(b,c){var d=c.readVarint32(),e=7&d,f=d>>>3;switch(e){case a.WIRE_TYPES.VARINT:do d=c.readUint8();while(128===(128&d));break;case a.WIRE_TYPES.BITS64:c.offset+=8;break;case a.WIRE_TYPES.LDELIM:d=c.readVarint32(),c.offset+=d;break;case a.WIRE_TYPES.STARTGROUP:o(f,c);break;case a.WIRE_TYPES.ENDGROUP:if(f===b)return !1;throw Error("Illegal GROUPEND after unknown group: "+f+" ("+b+" expected)");case a.WIRE_TYPES.BITS32:c.offset+=4;break;default:throw Error("Illegal wire type in unknown group "+b+": "+e)}return !0}var g,h,i,j,m,n,p,q,r,s,t,u,v,w,x,y,z,A,B,c={},d=function(a,b,c){this.builder=a,this.parent=b,this.name=c,this.className;},e=d.prototype;return e.fqn=function(){for(var a=this.name,b=this;;){if(b=b.parent,null==b)break;a=b.name+"."+a;}return a},e.toString=function(a){return (a?this.className+" ":"")+this.fqn()},e.build=function(){throw Error(this.toString(!0)+" cannot be built directly")},c.T=d,g=function(a,b,c,e,f){d.call(this,a,b,c),this.className="Namespace",this.children=[],this.options=e||{},this.syntax=f||"proto2";},h=g.prototype=Object.create(d.prototype),h.getChildren=function(a){var b,c,d;if(a=a||null,null==a)return this.children.slice();for(b=[],c=0,d=this.children.length;d>c;++c)this.children[c]instanceof a&&b.push(this.children[c]);return b},h.addChild=function(a){var b;if(b=this.getChild(a.name))if(b instanceof m.Field&&b.name!==b.originalName&&null===this.getChild(b.originalName))b.name=b.originalName;else{if(!(a instanceof m.Field&&a.name!==a.originalName&&null===this.getChild(a.originalName)))throw Error("Duplicate name in namespace "+this.toString(!0)+": "+a.name);a.name=a.originalName;}this.children.push(a);},h.getChild=function(a){var c,d,b="number"==typeof a?"id":"name";for(c=0,d=this.children.length;d>c;++c)if(this.children[c][b]===a)return this.children[c];return null},h.resolve=function(a,b){var g,d="string"==typeof a?a.split("."):a,e=this,f=0;if(""===d[f]){for(;null!==e.parent;)e=e.parent;f++;}do{do{if(!(e instanceof c.Namespace)){e=null;break}if(g=e.getChild(d[f]),!(g&&g instanceof c.T&&(!b||g instanceof c.Namespace))){e=null;break}e=g,f++;}while(fc;++c)e=b[c],e instanceof g&&(a[e.name]=e.build());return Object.defineProperty&&Object.defineProperty(a,"$options",{value:this.buildOpt()}),a},h.buildOpt=function(){var c,d,e,f,a={},b=Object.keys(this.options);for(c=0,d=b.length;d>c;++c)e=b[c],f=this.options[b[c]],a[e]=f;return a},h.getOption=function(a){return "undefined"==typeof a?this.options:"undefined"!=typeof this.options[a]?this.options[a]:null},c.Namespace=g,i=function(b,c,d,e){if(this.type=b,this.resolvedType=c,this.isMapKey=d,this.syntax=e,d&&a.MAP_KEY_TYPES.indexOf(b)<0)throw Error("Invalid map key type: "+b.name)},j=i.prototype,i.defaultFieldValue=k,j.verifyValue=function(c){var f,g,h,d=function(a,b){throw Error("Illegal value for "+this.toString(!0)+" of type "+this.type.name+": "+a+" ("+b+")")}.bind(this);switch(this.type){case a.TYPES.int32:case a.TYPES.sint32:case a.TYPES.sfixed32:return ("number"!=typeof c||c===c&&0!==c%1)&&d(typeof c,"not an integer"),c>4294967295?0|c:c;case a.TYPES.uint32:case a.TYPES.fixed32:return ("number"!=typeof c||c===c&&0!==c%1)&&d(typeof c,"not an integer"),0>c?c>>>0:c;case a.TYPES.int64:case a.TYPES.sint64:case a.TYPES.sfixed64:if(a.Long)try{return l(c,!1)}catch(e){d(typeof c,e.message);}else d(typeof c,"requires Long.js");case a.TYPES.uint64:case a.TYPES.fixed64:if(a.Long)try{return l(c,!0)}catch(e){d(typeof c,e.message);}else d(typeof c,"requires Long.js");case a.TYPES.bool:return "boolean"!=typeof c&&d(typeof c,"not a boolean"),c;case a.TYPES["float"]:case a.TYPES["double"]:return "number"!=typeof c&&d(typeof c,"not a number"),c;case a.TYPES.string:return "string"==typeof c||c&&c instanceof String||d(typeof c,"not a string"),""+c;case a.TYPES.bytes:return b.isByteBuffer(c)?c:b.wrap(c);case a.TYPES["enum"]:for(f=this.resolvedType.getChildren(a.Reflect.Enum.Value),h=0;h4294967295||0>c)&&d(typeof c,"not in range for uint32"),c;d(c,"not a valid enum value");case a.TYPES.group:case a.TYPES.message:if(c&&"object"==typeof c||d(typeof c,"object expected"),c instanceof this.resolvedType.clazz)return c;if(c instanceof a.Builder.Message){g={};for(h in c)c.hasOwnProperty(h)&&(g[h]=c[h]);c=g;}return new this.resolvedType.clazz(c)}throw Error("[INTERNAL] Illegal value for "+this.toString(!0)+": "+c+" (undefined type "+this.type+")")},j.calculateLength=function(b,c){if(null===c)return 0;var d;switch(this.type){case a.TYPES.int32:return 0>c?f.calculateVarint64(c):f.calculateVarint32(c);case a.TYPES.uint32:return f.calculateVarint32(c);case a.TYPES.sint32:return f.calculateVarint32(f.zigZagEncode32(c));case a.TYPES.fixed32:case a.TYPES.sfixed32:case a.TYPES["float"]:return 4;case a.TYPES.int64:case a.TYPES.uint64:return f.calculateVarint64(c);case a.TYPES.sint64:return f.calculateVarint64(f.zigZagEncode64(c));case a.TYPES.fixed64:case a.TYPES.sfixed64:return 8;case a.TYPES.bool:return 1;case a.TYPES["enum"]:return f.calculateVarint32(c);case a.TYPES["double"]:return 8;case a.TYPES.string:return d=f.calculateUTF8Bytes(c),f.calculateVarint32(d)+d;case a.TYPES.bytes:if(c.remaining()<0)throw Error("Illegal value for "+this.toString(!0)+": "+c.remaining()+" bytes remaining");return f.calculateVarint32(c.remaining())+c.remaining();case a.TYPES.message:return d=this.resolvedType.calculate(c),f.calculateVarint32(d)+d;case a.TYPES.group:return d=this.resolvedType.calculate(c),d+f.calculateVarint32(b<<3|a.WIRE_TYPES.ENDGROUP)}throw Error("[INTERNAL] Illegal value to encode in "+this.toString(!0)+": "+c+" (unknown type)")},j.encodeValue=function(b,c,d){var e,g;if(null===c)return d;switch(this.type){case a.TYPES.int32:0>c?d.writeVarint64(c):d.writeVarint32(c);break;case a.TYPES.uint32:d.writeVarint32(c);break;case a.TYPES.sint32:d.writeVarint32ZigZag(c);break;case a.TYPES.fixed32:d.writeUint32(c);break;case a.TYPES.sfixed32:d.writeInt32(c);break;case a.TYPES.int64:case a.TYPES.uint64:d.writeVarint64(c);break;case a.TYPES.sint64:d.writeVarint64ZigZag(c);break;case a.TYPES.fixed64:d.writeUint64(c);break;case a.TYPES.sfixed64:d.writeInt64(c);break;case a.TYPES.bool:"string"==typeof c?d.writeVarint32("false"===c.toLowerCase()?0:!!c):d.writeVarint32(c?1:0);break;case a.TYPES["enum"]:d.writeVarint32(c);break;case a.TYPES["float"]:d.writeFloat32(c);break;case a.TYPES["double"]:d.writeFloat64(c);break;case a.TYPES.string:d.writeVString(c);break;case a.TYPES.bytes:if(c.remaining()<0)throw Error("Illegal value for "+this.toString(!0)+": "+c.remaining()+" bytes remaining");e=c.offset,d.writeVarint32(c.remaining()),d.append(c),c.offset=e;break;case a.TYPES.message:g=(new f).LE(),this.resolvedType.encode(c,g),d.writeVarint32(g.offset),d.append(g.flip());break;case a.TYPES.group:this.resolvedType.encode(c,d),d.writeVarint32(b<<3|a.WIRE_TYPES.ENDGROUP);break;default:throw Error("[INTERNAL] Illegal value to encode in "+this.toString(!0)+": "+c+" (unknown type)")}return d},j.decode=function(b,c,d){if(c!=this.type.wireType)throw Error("Unexpected wire type for element");var e,f;switch(this.type){case a.TYPES.int32:return 0|b.readVarint32();case a.TYPES.uint32:return b.readVarint32()>>>0;case a.TYPES.sint32:return 0|b.readVarint32ZigZag();case a.TYPES.fixed32:return b.readUint32()>>>0;case a.TYPES.sfixed32:return 0|b.readInt32();case a.TYPES.int64:return b.readVarint64();case a.TYPES.uint64:return b.readVarint64().toUnsigned();case a.TYPES.sint64:return b.readVarint64ZigZag();case a.TYPES.fixed64:return b.readUint64();case a.TYPES.sfixed64:return b.readInt64();case a.TYPES.bool:return !!b.readVarint32();case a.TYPES["enum"]:return b.readVarint32();case a.TYPES["float"]:return b.readFloat();case a.TYPES["double"]:return b.readDouble();case a.TYPES.string:return b.readVString();case a.TYPES.bytes:if(f=b.readVarint32(),b.remaining()i;++i)this[e[i].name]=null;for(i=0,j=d.length;j>i;++i)k=d[i],this[k.name]=k.repeated?[]:k.map?new a.Map(k):null,!k.required&&"proto3"!==c.syntax||null===k.defaultValue||(this[k.name]=k.defaultValue);if(arguments.length>0)if(1!==arguments.length||null===b||"object"!=typeof b||!("function"!=typeof b.encode||b instanceof g)||Array.isArray(b)||b instanceof a.Map||f.isByteBuffer(b)||b instanceof ArrayBuffer||a.Long&&b instanceof a.Long)for(i=0,j=arguments.length;j>i;++i)"undefined"!=typeof(l=arguments[i])&&this.$set(d[i].name,l);else this.$set(b);},h=g.prototype=Object.create(a.Builder.Message.prototype);for(h.add=function(b,d,e){var f=c._fieldsByName[b];if(!e){if(!f)throw Error(this+"#"+b+" is undefined");if(!(f instanceof a.Reflect.Message.Field))throw Error(this+"#"+b+" is not a field: "+f.toString(!0));if(!f.repeated)throw Error(this+"#"+b+" is not a repeated field");d=f.verifyValue(d,!0);}return null===this[b]&&(this[b]=[]),this[b].push(d),this},h.$add=h.add,h.set=function(b,d,e){var f,g,h;if(b&&"object"==typeof b){e=d;for(f in b)b.hasOwnProperty(f)&&"undefined"!=typeof(d=b[f])&&this.$set(f,d,e);return this}if(g=c._fieldsByName[b],e)this[b]=d;else{if(!g)throw Error(this+"#"+b+" is not a field: undefined");if(!(g instanceof a.Reflect.Message.Field))throw Error(this+"#"+b+" is not a field: "+g.toString(!0));this[g.name]=d=g.verifyValue(d);}return g&&g.oneof&&(h=this[g.oneof.name],null!==d?(null!==h&&h!==g.name&&(this[h]=null),this[g.oneof.name]=g.name):h===b&&(this[g.oneof.name]=null)),this},h.$set=h.set,h.get=function(b,d){if(d)return this[b];var e=c._fieldsByName[b];if(!(e&&e instanceof a.Reflect.Message.Field))throw Error(this+"#"+b+" is not a field: undefined");if(!(e instanceof a.Reflect.Message.Field))throw Error(this+"#"+b+" is not a field: "+e.toString(!0));return this[e.name]},h.$get=h.get,i=0;ie;e++)if(h=this.children[e],h instanceof t||h instanceof m||h instanceof x){if(d.hasOwnProperty(h.name))throw Error("Illegal reflect child of "+this.toString(!0)+": "+h.toString(!0)+" cannot override static property '"+h.name+"'");d[h.name]=h.build();}else if(h instanceof m.Field)h.build(),this._fields.push(h),this._fieldsById[h.id]=h,this._fieldsByName[h.name]=h;else if(!(h instanceof m.OneOf||h instanceof w))throw Error("Illegal reflect child of "+this.toString(!0)+": "+this.children[e].toString(!0));return this.clazz=d},n.encode=function(a,b,c){var e,h,f,g,i,d=null;for(f=0,g=this._fields.length;g>f;++f)e=this._fields[f],h=a[e.name],e.required&&null===h?null===d&&(d=e):e.encode(c?h:e.verifyValue(h),b,a);if(null!==d)throw i=Error("Missing at least one required field for "+this.toString(!0)+": "+d),i.encoded=b,i;return b},n.calculate=function(a){for(var e,f,b=0,c=0,d=this._fields.length;d>c;++c){if(e=this._fields[c],f=a[e.name],e.required&&null===f)throw Error("Missing at least one required field for "+this.toString(!0)+": "+e);b+=e.calculate(f,a);}return b},n.decode=function(b,c,d){var g,h,i,j,e,f,k,l,m,n,p,q;for(c="number"==typeof c?c:-1,e=b.offset,f=new this.clazz;b.offset0;){if(g=b.readVarint32(),h=7&g,i=g>>>3,h===a.WIRE_TYPES.ENDGROUP){if(i!==d)throw Error("Illegal group end indicator for "+this.toString(!0)+": "+i+" ("+(d?d+" expected":"not a group")+")");break}if(j=this._fieldsById[i])j.repeated&&!j.options.packed?f[j.name].push(j.decode(h,b)):j.map?(l=j.decode(h,b),f[j.name].set(l[0],l[1])):(f[j.name]=j.decode(h,b),j.oneof&&(m=f[j.oneof.name],null!==m&&m!==j.name&&(f[m]=null),f[j.oneof.name]=j.name));else switch(h){case a.WIRE_TYPES.VARINT:b.readVarint32();break;case a.WIRE_TYPES.BITS32:b.offset+=4;break;case a.WIRE_TYPES.BITS64:b.offset+=8;break;case a.WIRE_TYPES.LDELIM:k=b.readVarint32(),b.offset+=k;break;case a.WIRE_TYPES.STARTGROUP:for(;o(i,b););break;default:throw Error("Illegal wire type for unknown field "+i+" in "+this.toString(!0)+"#decode: "+h)}}for(n=0,p=this._fields.length;p>n;++n)if(j=this._fields[n],null===f[j.name])if("proto3"===this.syntax)f[j.name]=j.defaultValue;else{if(j.required)throw q=Error("Missing at least one required field for "+this.toString(!0)+": "+j.name),q.decoded=f,q;a.populateDefaults&&null!==j.defaultValue&&(f[j.name]=j.defaultValue);}return f},c.Message=m,p=function(b,c,e,f,g,h,i,j,k,l){d.call(this,b,c,h),this.className="Message.Field",this.required="required"===e,this.repeated="repeated"===e,this.map="map"===e,this.keyType=f||null,this.type=g,this.resolvedType=null,this.id=i,this.options=j||{},this.defaultValue=null,this.oneof=k||null,this.syntax=l||"proto2",this.originalName=this.name,this.element=null,this.keyElement=null,!this.builder.options.convertFieldsToCamelCase||this instanceof m.ExtensionField||(this.name=a.Util.toCamelCase(this.name));},q=p.prototype=Object.create(d.prototype),q.build=function(){this.element=new i(this.type,this.resolvedType,!1,this.syntax),this.map&&(this.keyElement=new i(this.keyType,void 0,!0,this.syntax)),"proto3"!==this.syntax||this.repeated||this.map?"undefined"!=typeof this.options["default"]&&(this.defaultValue=this.verifyValue(this.options["default"])):this.defaultValue=i.defaultFieldValue(this.type);},q.verifyValue=function(b,c){var d,e,f;if(c=c||!1,d=function(a,b){throw Error("Illegal value for "+this.toString(!0)+" of type "+this.type.name+": "+a+" ("+b+")")}.bind(this),null===b)return this.required&&d(typeof b,"required"),"proto3"===this.syntax&&this.type!==a.TYPES.message&&d(typeof b,"proto3 field without field presence cannot be null"),null;if(this.repeated&&!c){for(Array.isArray(b)||(b=[b]),f=[],e=0;e0;case a.TYPES.bytes:return b.remaining()>0;case a.TYPES["enum"]:return 0!==b;case a.TYPES.message:return null!==b;default:return !0}},q.encode=function(b,c,d){var e,g,h,i,j;if(null===this.type||"object"!=typeof this.type)throw Error("[INTERNAL] Unresolved type in "+this.toString(!0)+": "+this.type);if(null===b||this.repeated&&0==b.length)return c;try{if(this.repeated)if(this.options.packed&&a.PACKABLE_WIRE_TYPES.indexOf(this.type.wireType)>=0){for(c.writeVarint32(this.id<<3|a.WIRE_TYPES.LDELIM),c.ensureCapacity(c.offset+=1),g=c.offset,e=0;e1&&(j=c.slice(g,c.offset),g+=i-1,c.offset=g,c.append(j)),c.writeVarint32(h,g-i);}else for(e=0;e=0){for(d+=f.calculateVarint32(this.id<<3|a.WIRE_TYPES.LDELIM),g=0,e=0;e=0&&!d){for(f=c.readVarint32(),f=c.offset+f,h=[];c.offset0;)if(l=k.readVarint32(),b=7&l,m=l>>>3,1===m)j=this.keyElement.decode(k,b,m);else{if(2!==m)throw Error("Unexpected tag in map field key/value submessage");e=this.element.decode(k,b,m);}return [j,e]}return this.element.decode(c,b,this.id)},c.Message.Field=p,r=function(a,b,c,d,e,f,g){p.call(this,a,b,c,null,d,e,f,g),this.extension;},r.prototype=Object.create(p.prototype),c.Message.ExtensionField=r,s=function(a,b,c){d.call(this,a,b,c),this.fields=[];},c.Message.OneOf=s,t=function(a,b,c,d,e){g.call(this,a,b,c,d,e),this.className="Enum",this.object=null;},t.getName=function(a,b){var e,d,c=Object.keys(a);for(d=0;de;++e)c[d[e]["name"]]=d[e]["id"];return Object.defineProperty&&Object.defineProperty(c,"$options",{value:this.buildOpt(),enumerable:!1}),this.object=c},c.Enum=t,v=function(a,b,c,e){d.call(this,a,b,c),this.className="Enum.Value",this.id=e;},v.prototype=Object.create(d.prototype),c.Enum.Value=v,w=function(a,b,c,e){d.call(this,a,b,c),this.field=e;},w.prototype=Object.create(d.prototype),c.Extension=w,x=function(a,b,c,d){g.call(this,a,b,c,d),this.className="Service",this.clazz=null;},y=x.prototype=Object.create(g.prototype),y.build=function(b){return this.clazz&&!b?this.clazz:this.clazz=function(a,b){var g,c=function(b){a.Builder.Service.call(this),this.rpcImpl=b||function(a,b,c){setTimeout(c.bind(this,Error("Not implemented, see: https://github.com/dcodeIO/ProtoBuf.js/wiki/Services")),0);};},d=c.prototype=Object.create(a.Builder.Service.prototype),e=b.getChildren(a.Reflect.Service.RPCMethod);for(g=0;g0;){if(b=e.pop(),!Array.isArray(b))throw Error("not a valid namespace: "+JSON.stringify(b));for(;b.length>0;){if(f=b.shift(),d.isMessage(f)){if(g=new c.Message(this,this.ptr,f.name,f.options,f.isGroup,f.syntax),h={},f.oneofs&&Object.keys(f.oneofs).forEach(function(a){g.addChild(h[a]=new c.Message.OneOf(this,g,a));},this),f.fields&&f.fields.forEach(function(a){if(null!==g.getChild(0|a.id))throw Error("duplicate or invalid field id in "+g.name+": "+a.id);if(a.options&&"object"!=typeof a.options)throw Error("illegal field options in "+g.name+"#"+a.name);var b=null;if("string"==typeof a.oneof&&!(b=h[a.oneof]))throw Error("illegal oneof in "+g.name+"#"+a.name+": "+a.oneof);a=new c.Message.Field(this,g,a.rule,a.keytype,a.type,a.name,a.id,a.options,b,f.syntax),b&&b.fields.push(a),g.addChild(a);},this),i=[],f.enums&&f.enums.forEach(function(a){i.push(a);}),f.messages&&f.messages.forEach(function(a){i.push(a);}),f.services&&f.services.forEach(function(a){i.push(a);}),f.extensions&&(g.extensions="number"==typeof f.extensions[0]?[f.extensions]:f.extensions),this.ptr.addChild(g),i.length>0){e.push(b),b=i,i=null,this.ptr=g,g=null;continue}i=null;}else if(d.isEnum(f))g=new c.Enum(this,this.ptr,f.name,f.options,f.syntax),f.values.forEach(function(a){g.addChild(new c.Enum.Value(this,g,a.name,a.id));},this),this.ptr.addChild(g);else if(d.isService(f))g=new c.Service(this,this.ptr,f.name,f.options),Object.keys(f.rpc).forEach(function(a){var b=f.rpc[a];g.addChild(new c.Service.RPCMethod(this,g,a,b.request,b.response,!!b.request_stream,!!b.response_stream,b.options));},this),this.ptr.addChild(g);else{if(!d.isExtend(f))throw Error("not a valid definition: "+JSON.stringify(f));if(g=this.ptr.resolve(f.ref,!0))f.fields.forEach(function(b){var d,e,f,h;if(null!==g.getChild(0|b.id))throw Error("duplicate extended field id in "+g.name+": "+b.id); if(g.extensions&&(d=!1,g.extensions.forEach(function(a){b.id>=a[0]&&b.id<=a[1]&&(d=!0);}),!d))throw Error("illegal extended field id in "+g.name+": "+b.id+" (not within valid ranges)");e=b.name,this.options.convertFieldsToCamelCase&&(e=a.Util.toCamelCase(e)),f=new c.Message.ExtensionField(this,g,b.rule,b.type,this.ptr.fqn()+"."+e,b.id,b.options),h=new c.Extension(this,this.ptr,b.name,f),f.extension=h,this.ptr.addChild(h),g.addChild(f);},this);else if(!/\.?google\.protobuf\./.test(f.ref))throw Error("extended message "+f.ref+" is not defined")}f=null,g=null;}b=null,this.ptr=this.ptr.parent;}return this.resolved=!1,this.result=null,this},e["import"]=function(b,c){var e,g,h,i,j,k,l,m,d="/";if("string"==typeof c){if(a.Util.IS_NODE,this.files[c]===!0)return this.reset();this.files[c]=!0;}else if("object"==typeof c){if(e=c.root,a.Util.IS_NODE,(e.indexOf("\\")>=0||c.file.indexOf("\\")>=0)&&(d="\\"),g=e+d+c.file,this.files[g]===!0)return this.reset();this.files[g]=!0;}if(b.imports&&b.imports.length>0){for(i=!1,"object"==typeof c?(this.importRoot=c.root,i=!0,h=this.importRoot,c=c.file,(h.indexOf("\\")>=0||c.indexOf("\\")>=0)&&(d="\\")):"string"==typeof c?this.importRoot?h=this.importRoot:c.indexOf("/")>=0?(h=c.replace(/\/[^\/]*$/,""),""===h&&(h="/")):c.indexOf("\\")>=0?(h=c.replace(/\\[^\\]*$/,""),d="\\"):h=".":h=null,j=0;j= time) { return this._serverEngine.getConversationStatus(time); } else { return utils.Defer.reject(); } }; _proto._set = function _set(list) { var self = this; if (utils.isUndefined(list)) { return; } var time = self._timeStorage.get(STORAGE_CONVERSATION_STATUS.SUB_KEY.TIME) || 0; var listCount = list.length; utils.forEach(list, function (statusItem, index) { var updatedTime = statusItem.updatedTime || 0; time = updatedTime > time ? updatedTime : time; self._eventEmitter.emit(EventName.CHANGED, { statusItem: statusItem, isLastInAPull: index === listCount - 1 }); }); self._timeStorage.set(STORAGE_CONVERSATION_STATUS.SUB_KEY.TIME, time); }; return ConversationStatusManager; }(); var EventName$1 = { CHANGED: 'conversationChanged' }; var ConversationManager = function () { function ConversationManager(option, serverEngine) { this._selfUserId = void 0; this._store = void 0; this._eventEmitter = new utils.EventEmitter(); this._statusManager = void 0; this._allConversationList = []; this._updatedConversations = {}; var self = this; var statusManager = new ConversationStatusManager(serverEngine); statusManager.watchChanged(function (_ref) { var statusItem = _ref.statusItem, isLastInAPull = _ref.isLastInAPull; self._addStatus(statusItem, isLastInAPull); }); self._store = new ConversationStore(option); self._selfUserId = option.userId; self._statusManager = statusManager; } var _proto = ConversationManager.prototype; _proto.watch = function watch(events) { var conversation = events.conversation; this._eventEmitter.on(EventName$1.CHANGED, conversation); }; _proto.addMessage = function addMessage(msgArgs) { var self = this; var message = msgArgs.message, isLastInAPull = msgArgs.isLastInAPull, type = message.type, isPersited = message.isPersited, isSaveConversationType = utils.isInclude(TYPE_HAS_CONVERSATION, type); if (!isSaveConversationType) { return; } var hasChanged = false; var storageConversation = self._store.get(message); var calcEvents = [self._setUnreadCount, self._setMentiondInfo]; utils.forEach(calcEvents, function (event) { var _event$call = event.call(self, message, storageConversation), hasCalcChanged = _event$call.hasChanged, conversation = _event$call.conversation; hasChanged = hasChanged || hasCalcChanged; storageConversation = conversation; }); if (hasChanged) { self._store.set(message, storageConversation); } if (isPersited) { var conversation = self._getConversationByMessage(message); conversation.updatedItems = { latestMessage: { time: message.sentTime, val: message } }; self._setUpdatedConversation(conversation); } var isNeedNotifyUpdate = utils.isUndefined(isLastInAPull) ? true : isLastInAPull; if (isNeedNotifyUpdate) { self._notifyConversationChanged(); } }; _proto.get = function get(option) { var conversation = this._store.get(option); var notificationStatus = conversation.notificationStatus, isNotDisturb = utils.isEqual(notificationStatus, NOTIFICATION_STATUS.DO_NOT_DISTURB); if (isNotDisturb) { conversation.unreadMessageCount = 0; } return conversation; }; _proto.read = function read(option) { var self = this, type = option.type, targetId = option.targetId, _store = self._store, _updatedConversations = self._updatedConversations, key = common.getConversationKey(option), updatedConversation = _updatedConversations[key] || {}; var storeConversation = _store.get(option) || {}, _storeConversation = storeConversation, unreadMessageCount = _storeConversation.unreadMessageCount, hasMentiond = _storeConversation.hasMentiond; if (unreadMessageCount || hasMentiond) { var updatedTime = common.DelayTimer.getTime(); var updatedValues = { type: type, targetId: targetId, unreadMessageCount: 0, hasMentiond: false, mentiondInfo: null, updatedItems: { unreadMessageCount: { time: updatedTime, val: 0 }, hasMentiond: { time: updatedTime, val: false }, mentiondInfo: { time: updatedTime, val: null } } }; storeConversation = utils.extendAllowNull(storeConversation, updatedValues); _store.set(option, storeConversation); _updatedConversations[key] = utils.extendAllowNull(updatedConversation, updatedValues); self._notifyConversationChanged(); } }; _proto.getTotalUnreadCount = function getTotalUnreadCount() { var _store = this._store, conversationList = _store.getValues(); var totalCount = 0; utils.forEach(conversationList, function (_ref2) { var unreadMessageCount = _ref2.unreadMessageCount; unreadMessageCount = utils.isNumber(unreadMessageCount) ? unreadMessageCount : 0; totalCount += unreadMessageCount; }); return totalCount; }; _proto.getUnreadCount = function getUnreadCount(option) { var _store = this._store; var storeConversation = _store.get(option) || {}; var unreadMessageCount = storeConversation.unreadMessageCount; var count = utils.isNumber(unreadMessageCount) ? unreadMessageCount : 0; return count; }; _proto.close = function close() { this._statusManager.close(); }; _proto._getConversationByMessage = function _getConversationByMessage(message) { var type = message.type, targetId = message.targetId, storeConversation = this._store.get(message); var conversation = utils.extend(storeConversation, { type: type, targetId: targetId, latestMessage: message }); return conversation; }; _proto._getUpdatedConversationList = function _getUpdatedConversationList() { var self = this, updatedConversations = self._updatedConversations, list = []; utils.forEach(updatedConversations, function (conversation) { var storageItems = self._store.get(conversation); utils.forEach(storageItems, function (val, key) { conversation[key] = val; }); list.push(conversation); }); return common.sortConList(list); }; _proto._setUnreadCount = function _setUnreadCount(message, conversation) { var content = message.content, messageType = message.messageType, sentTime = message.sentTime, isCounted = message.isCounted, messageDirection = message.messageDirection, senderUserId = message.senderUserId, isSelfSend = utils.isEqual(messageDirection, MESSAGE_DIRECTION.SEND) || utils.isEqual(senderUserId, this._selfUserId), isRecall = utils.isEqual(messageType, RECALL_MESSAGE_TYPE), hasContent = utils.isObject(content); var hasChanged = false; var lastUnreadTime = conversation.lastUnreadTime || 0, unreadMessageCount = conversation.unreadMessageCount || 0, hasBeenAdded = lastUnreadTime > sentTime; if (hasBeenAdded || isSelfSend) { return { hasChanged: hasChanged, conversation: conversation }; } if (isCounted) { conversation.unreadMessageCount = unreadMessageCount + 1; conversation.lastUnreadTime = sentTime; hasChanged = true; } if (isRecall && hasContent) { var isNotRead = lastUnreadTime >= content.sentTime; if (isNotRead && unreadMessageCount) { conversation.unreadMessageCount = unreadMessageCount - 1; hasChanged = true; } } return { hasChanged: hasChanged, conversation: conversation }; }; _proto._setMentiondInfo = function _setMentiondInfo(message, conversation) { var content = message.content, messageDirection = message.messageDirection, isMentiond = message.isMentiond, isSelfSend = utils.isEqual(messageDirection, MESSAGE_DIRECTION.SEND), hasContent = utils.isObject(content); var hasChanged = false; if (isSelfSend) ; else if (isMentiond && hasContent && content.mentionedInfo) { conversation.hasMentiond = true; conversation.mentiondInfo = content.mentionedInfo; hasChanged = true; } return { hasChanged: hasChanged, conversation: conversation }; }; _proto._setUpdatedConversation = function _setUpdatedConversation(conversation) { if (utils.isObject(conversation) && conversation.targetId && conversation.type) { var self = this, cacheKey = common.getConversationKey(conversation), cacheConversation = self._updatedConversations[cacheKey]; self._updatedConversations[cacheKey] = utils.extendAllowNull(cacheConversation, conversation); } }; _proto._notifyConversationChanged = function _notifyConversationChanged() { var self = this, _eventEmitter = self._eventEmitter, updatedConversationList = self._getUpdatedConversationList(); if (utils.isEmpty(updatedConversationList)) ; else { utils.setTimeout(function () { _eventEmitter.emit(EventName$1.CHANGED, { updatedConversationList: updatedConversationList }); self._updatedConversations = {}; }, 0); } }; _proto._addStatus = function _addStatus(conversationStatus, isLastInAPull) { var type = conversationStatus.type, targetId = conversationStatus.targetId, updatedTime = conversationStatus.updatedTime, notificationStatus = conversationStatus.notificationStatus, isTop = conversationStatus.isTop, option = { type: type, targetId: targetId }; var updatedItems = {}; if (!utils.isUndefined(notificationStatus)) { updatedItems['notificationStatus'] = { time: updatedTime, val: notificationStatus }; } if (!utils.isUndefined(isTop)) { updatedItems['isTop'] = { time: updatedTime, val: isTop }; } this._setUpdatedConversation({ type: type, targetId: targetId, updatedItems: updatedItems }); this._store.set(option, { notificationStatus: notificationStatus, isTop: isTop }); if (isLastInAPull) { this._notifyConversationChanged(); } }; return ConversationManager; }(); var MessageTimeSyner$1 = common.MessageTimeSyner, ChatRoomMessageTimeSyner$1 = common.ChatRoomMessageTimeSyner; var EVENT_NAME$1 = { MESSAGE_RECEIVED: 'msg-received' }; var MessagePullManager = function () { function MessagePullManager(serverEngine, option) { var _serverEngine$watch; this._serverEngine = void 0; this._pullQueue = void 0; this._messageTimeSyner = void 0; this._chatRoomMessageTimeSyner = void 0; this._eventEmitter = new utils.EventEmitter(); this._pullMessageTimer = new utils.Timer({ type: TIMER_TYPE.INTERVAL, timeout: PULL_MSG_TIME }); this._sentMsgCacheInPulling = {}; this._handleDirectMessage = void 0; this._handleNotifyPull = void 0; this._handleJoinChatRoom = void 0; this._handleSendMessage = void 0; var self = this; var appkey = serverEngine.option.appkey, userId = serverEngine._selfUserId; var startSyncTime = option.startSyncTime; var pullQueue = new PullQueueManager({ event: this._pullEvent, thisArg: this, onFinished: function onFinished() {}, onError: function onError() {} }); self._handleDirectMessage = function (message) { !pullQueue.isLoading && self.notifyMessage({ message: message, hasMore: false }); }; self._handleNotifyPull = function (option) { pullQueue.pull(option); }; self._handleJoinChatRoom = function (_ref) { var id = _ref.id, count = _ref.count, isAutoRejoin = _ref.isAutoRejoin; if (utils.isEqual(count, CHATROOM_NOT_PULL_MSG_COUNT)) { self._chatRoomMessageTimeSyner.set(id, common.DelayTimer.getTime()); } else { var type = PULL_MSG_TYPE.CHATROOM, chrmId = id; var time = isAutoRejoin ? self._chatRoomMessageTimeSyner.get(id) + 1 : 0; self._chatRoomMessageTimeSyner.set(id, time); pullQueue.pull({ type: type, time: time, chrmId: chrmId, count: count }); } }; self._handleSendMessage = function (message) { pullQueue.isLoading ? self._setSentMsgCacheInPulling(message) : self._setPullTime(message); }; serverEngine.watch((_serverEngine$watch = {}, _serverEngine$watch[SERVER_EVENT_NAME.DIRECT_MSG] = self._handleDirectMessage, _serverEngine$watch[SERVER_EVENT_NAME.NOTIFY_PULL] = self._handleNotifyPull, _serverEngine$watch[SERVER_EVENT_NAME.JOIN_CHATROOM] = self._handleJoinChatRoom, _serverEngine$watch[SERVER_EVENT_NAME.MESSAGE_SEND] = self._handleSendMessage, _serverEngine$watch)); self._serverEngine = serverEngine; self._pullQueue = pullQueue; self._messageTimeSyner = new MessageTimeSyner$1({ appkey: appkey, userId: userId, startSyncTime: startSyncTime }); self._chatRoomMessageTimeSyner = new ChatRoomMessageTimeSyner$1({ appkey: appkey, userId: userId }); self._pullMessageTimer.start(pullQueue.pull, { thisArg: pullQueue }); pullQueue.pull(); } var _proto = MessagePullManager.prototype; _proto.watchMessage = function watchMessage(event) { this._eventEmitter.on(EVENT_NAME$1.MESSAGE_RECEIVED, event); }; _proto.notifyMessage = function notifyMessage(messageArgs) { var message = messageArgs.message; this._setPullTime(message); this._eventEmitter.emit(EVENT_NAME$1.MESSAGE_RECEIVED, messageArgs); }; _proto.close = function close() { var _this$_serverEngine$u; this._pullMessageTimer.stop(); this._sentMsgCacheInPulling = {}; this._serverEngine.unwatch((_this$_serverEngine$u = {}, _this$_serverEngine$u[SERVER_EVENT_NAME.DIRECT_MSG] = this._handleDirectMessage, _this$_serverEngine$u[SERVER_EVENT_NAME.NOTIFY_PULL] = this._handleNotifyPull, _this$_serverEngine$u[SERVER_EVENT_NAME.JOIN_CHATROOM] = this._handleJoinChatRoom, _this$_serverEngine$u[SERVER_EVENT_NAME.MESSAGE_SEND] = this._handleSendMessage, _this$_serverEngine$u)); }; _proto._pullEvent = function _pullEvent(option) { option = option || {}; var self = this, _serverEngine = self._serverEngine, _messageTimeSyner = self._messageTimeSyner, _chatRoomMessageTimeSyner = self._chatRoomMessageTimeSyner, _option = option, type = _option.type, chrmId = _option.chrmId, serverPullTime = _option.time, count = _option.count, isPullChrmMsg = utils.isEqual(type, PULL_MSG_TYPE.CHATROOM), msgSyncTime = _messageTimeSyner.get(), currentReceiveTime = isPullChrmMsg ? _chatRoomMessageTimeSyner.get(chrmId) : msgSyncTime.inboxTime, syncTime = utils.copy(msgSyncTime); if (serverPullTime && serverPullTime < currentReceiveTime) { return utils.Defer.resolve(); } var onMessage = function onMessage(_ref2) { var message = _ref2.message, finished = _ref2.finished, isLastInAPull = _ref2.isLastInAPull; self._displatchMessages({ message: message, finished: finished, isPullChrmMsg: isPullChrmMsg, isLastInAPull: isLastInAPull, normalSyncTime: syncTime, chatRoomReceiveTime: currentReceiveTime }); }; if (isPullChrmMsg) { return _serverEngine.pullChrmMessageList(chrmId, currentReceiveTime, count, { onMessage: onMessage }); } else { return _serverEngine.pullMessageList(syncTime, { onMessage: onMessage }); } }; _proto._displatchMessages = function _displatchMessages(option) { var self = this, message = option.message, finished = option.finished, isPullChrmMsg = option.isPullChrmMsg, isLastInAPull = option.isLastInAPull, _ref3 = option.normalSyncTime || {}, inboxTime = _ref3.inboxTime, sendboxTime = _ref3.sendboxTime, sentTime = message.sentTime, messageDirection = message.messageDirection, messageUId = message.messageUId, isSelfSend = messageDirection === MESSAGE_DIRECTION.SEND, pullTime = isSelfSend ? sendboxTime : inboxTime; if (sentTime <= pullTime && !isPullChrmMsg) { return; } if (self._sentMsgCacheInPulling[messageUId]) { return; } self.notifyMessage({ message: message, hasMore: !finished, isLastInAPull: isLastInAPull }); }; _proto._setPullTime = function _setPullTime(message) { var isChatRoom = message.type === CONVERSATION_TYPE.CHATROOM; isChatRoom ? this._chatRoomMessageTimeSyner.setByMessage(message) : this._messageTimeSyner.setByMessage(message); }; _proto._setSentMsgCacheInPulling = function _setSentMsgCacheInPulling(message) { var messageUId = message.messageUId; if (utils.isUndefined(messageUId)) { return; } this._sentMsgCacheInPulling[messageUId] = message; }; _proto._consumeSentMsgCacheInPulling = function _consumeSentMsgCacheInPulling() { var self = this; var _sentMsgCacheInPulling = self._sentMsgCacheInPulling; utils.forEach(_sentMsgCacheInPulling, function (message) { self._setPullTime(message); }); self._sentMsgCacheInPulling = {}; }; return MessagePullManager; }(); var ChatRoomKVStore = function () { function ChatRoomKVStore(chrmId, currentUserId) { this._chatRoomId = void 0; this._kvCaches = {}; this._currentUserId = void 0; this._chatRoomId = chrmId; this._currentUserId = currentUserId; } var _proto = ChatRoomKVStore.prototype; _proto.setEntries = function setEntries(data) { data = data || {}; var self = this; var _data = data, kvList = _data.kvEntries, isFullUpdate = _data.isFullUpdate; kvList = kvList || []; isFullUpdate = isFullUpdate || false; isFullUpdate && self.clear(); utils.forEach(kvList, function (kv) { self.setEntry(kv, { isFullUpdate: isFullUpdate }); }); }; _proto.setEntry = function setEntry(kv, option) { option = option || {}; var _option = option, isFullUpdate = _option.isFullUpdate, key = kv.key, type = kv.type, isOverwrite = kv.isOverwrite, userId = kv.userId, latestUserId = this.getSetUserId(key), isDeleteOpt = utils.isEqual(type, CHATROOM_ENTRY_TYPE.DELETE), isSameAtLastSetUser = utils.isEqual(latestUserId, userId), isKeyNotExist = !this.isExisted(key); var event = isDeleteOpt ? this.remove : this.add; if (isFullUpdate) { event.call(this, kv); } else if (isOverwrite || isSameAtLastSetUser || isKeyNotExist) { event.call(this, kv); } }; _proto.add = function add(kv) { var key = kv.key; kv.isDeleted = false; this._kvCaches[key] = kv; }; _proto.remove = function remove(kv) { var key = kv.key; var cacheKV = this.get(key) || {}; cacheKV.isDeleted = true; this._kvCaches[key] = cacheKV; }; _proto.clear = function clear() { this._kvCaches = {}; }; _proto.get = function get(key) { return this._kvCaches[key]; }; _proto.getSetUserId = function getSetUserId(key) { var cache = this.get(key) || {}; return cache.userId; }; _proto.getValue = function getValue(key) { var kv = this._kvCaches[key] || {}; var isDeleted = kv.isDeleted; return isDeleted ? null : kv.value; }; _proto.getAll = function getAll() { var kvEntries = {}; utils.forEach(this._kvCaches, function (kv, key) { if (!kv.isDeleted) { kvEntries[key] = kv.value; } }); return kvEntries; }; _proto.getUpdatedTime = function getUpdatedTime() { var maxTime = 0; utils.forEach(this._kvCaches, function (entry) { var timestamp = entry.timestamp || 0; if (maxTime < timestamp) { maxTime = timestamp; } }); return maxTime; }; _proto.isExisted = function isExisted(key) { var cache = this.get(key) || {}; var value = cache.value, isDeletedOnLatestOperate = cache.isDeleted; return value && !isDeletedOnLatestOperate; }; return ChatRoomKVStore; }(); var storeCaches = {}; var get = function get(chrmId) { return storeCaches[chrmId]; }; var set$1 = function set(chrmId, data, currentUserId) { var kvStore = get(chrmId); if (utils.isEmpty(kvStore)) { kvStore = new ChatRoomKVStore(chrmId, currentUserId); } kvStore.setEntries(data); storeCaches[chrmId] = kvStore; }; var getValue = function getValue(chrmId, key) { var kvStore = get(chrmId); var value = kvStore ? kvStore.getValue(key) : null; return value; }; var getAll = function getAll(chrmId) { var kvStore = get(chrmId); var kvs = {}; if (kvStore) { kvs = kvStore.getAll(); } return kvs; }; var clear = function clear(chrmId) { var kvStore = get(chrmId) || {}; kvStore.clear && kvStore.clear(); }; var ChatRoomKVStore$1 = { get: get, set: set$1, getValue: getValue, getAll: getAll, clear: clear }; var PullTimeCache = { _caches: {}, set: function set(chrmId, time) { PullTimeCache._caches[chrmId] = time; }, get: function get(chrmId) { return PullTimeCache._caches[chrmId] || 0; }, clear: function clear(chrmId) { PullTimeCache._caches[chrmId] = 0; } }; var ChatRoomKVManager = function () { function ChatRoomKVManager(serverEngine) { var _serverEngine$watch; this._serverEngine = void 0; this._pullQueue = void 0; this._handleChrmKVSet = void 0; this._handleChrmKVChanged = void 0; this._handleBeforeJoinChrm = void 0; var self = this; var userId = serverEngine._selfUserId; var pullQueue = new PullQueueManager({ event: this._pullEvent, thisArg: this, onFinished: function onFinished(data, option) { if (!data || !option.chrmId) { return; } var chrmId = option.chrmId; if (data.isFullUpdate) { self._reset(chrmId); } Logger.info(TAG.L_PULL_CHRM_KV_R, { data: data, option: option }); ChatRoomKVStore$1.set(chrmId, data, userId); PullTimeCache.set(chrmId, data.syncTime || 0); } }); self._handleChrmKVSet = function (_ref) { var id = _ref.id, data = _ref.data; ChatRoomKVStore$1.set(id, data, userId); }; self._handleChrmKVChanged = function (data) { self.pull(data); }; self._handleBeforeJoinChrm = function (_ref2) { var id = _ref2.id; self._reset(id); }; serverEngine.watch((_serverEngine$watch = {}, _serverEngine$watch[SERVER_EVENT_NAME.CHRM_KV_SET] = self._handleChrmKVSet, _serverEngine$watch[SERVER_EVENT_NAME.CHRM_KV_CHANGED] = self._handleChrmKVChanged, _serverEngine$watch[SERVER_EVENT_NAME.BEFORE_JOIN_CHATROOM] = self._handleBeforeJoinChrm, _serverEngine$watch)); this._serverEngine = serverEngine; this._pullQueue = pullQueue; } var _proto = ChatRoomKVManager.prototype; _proto._reset = function _reset(chrmId) { ChatRoomKVStore$1.clear(chrmId); PullTimeCache.clear(chrmId); }; _proto._pullEvent = function _pullEvent(data) { var time = data.time, chrmId = data.chrmId, currentTime = PullTimeCache.get(chrmId), isUpdated = currentTime > time; Logger.info(TAG.L_PULL_CHRM_KV_T, { currentTime: currentTime, serverTime: time, isUpdated: isUpdated, data: data }); if (isUpdated) { Logger.info(TAG.L_PULL_CHRM_KV_R, { info: 'kv is updated. not pull again' }); return utils.Defer.resolve(); } return this._serverEngine.pullChatRoomKV({ id: chrmId }, currentTime); }; _proto.pull = function pull(data) { this._pullQueue.pull(data); }; _proto.getValue = function getValue(chrmId, key) { return ChatRoomKVStore$1.getValue(chrmId, key); }; _proto.getAll = function getAll(chrmId) { return ChatRoomKVStore$1.getAll(chrmId); }; _proto.close = function close() { var _self$_serverEngine$u; var self = this; self._serverEngine.unwatch((_self$_serverEngine$u = {}, _self$_serverEngine$u[SERVER_EVENT_NAME.CHRM_KV_SET] = self._handleChrmKVSet, _self$_serverEngine$u[SERVER_EVENT_NAME.CHRM_KV_CHANGED] = self._handleChrmKVChanged, _self$_serverEngine$u[SERVER_EVENT_NAME.BEFORE_JOIN_CHATROOM] = self._handleBeforeJoinChrm, _self$_serverEngine$u)); }; return ChatRoomKVManager; }(); var SettingStore = function () { function SettingStore(appkey, userId) { this._storage = void 0; var storageKey = utils.tplEngine(STORAGE_USER_SETTING.ROOT_KEY_TPL, { appkey: appkey, userId: userId }); this._storage = new common.RCStorage(storageKey); } var _proto = SettingStore.prototype; _proto.set = function set(serverData) { var self = this, _storage = self._storage, settings = serverData.settings, oldSettingItems = _storage.get(STORAGE_USER_SETTING.SUB_KEY.SETTINGS) || {}; var newSettingItems = oldSettingItems, isChanged = false; utils.forEach(settings, function (newSetting, key) { newSetting = newSetting || {}; var oldSetting = oldSettingItems[key] || {}, _newSetting = newSetting, newVersion = _newSetting.version, status = _newSetting.status, newValue = _newSetting.value, oldGlobalVersion = _storage.get(STORAGE_USER_SETTING.SUB_KEY.VERSION) || 0, isNeedUpdateItem = newVersion > (oldSetting.version || 0), isNeedUpdateVersion = newVersion > oldGlobalVersion; if (!isNeedUpdateItem) { return; } isChanged = true; switch (status) { case USER_SETTING_STATUS.ADD: case USER_SETTING_STATUS.UPDATE: newSettingItems[key] = { value: newValue, version: newVersion }; break; case USER_SETTING_STATUS.DELETE: delete newSettingItems[key]; break; default: } if (isNeedUpdateVersion) { _storage.set(STORAGE_USER_SETTING.SUB_KEY.VERSION, newVersion); } }); if (!isChanged) { return; } if (utils.isEmpty(newSettingItems)) { _storage.remove(STORAGE_USER_SETTING.SUB_KEY.SETTINGS); } else { _storage.set(STORAGE_USER_SETTING.SUB_KEY.SETTINGS, newSettingItems); } }; _proto.getSetting = function getSetting() { var settings = this._storage.get(STORAGE_USER_SETTING.SUB_KEY.SETTINGS) || {}; return utils.map(settings, function (set) { set = set || {}; return set.value; }); }; _proto.getVersion = function getVersion() { return this._storage.get(STORAGE_USER_SETTING.SUB_KEY.VERSION) || 0; }; return SettingStore; }(); var EventNames = { CHANGED: 'change' }; var SettingManager = function () { function SettingManager(serverEngine, option) { var _serverEngine$watch; this._serverEngine = void 0; this._settingStore = void 0; this._pullQueue = void 0; this._eventEmitter = new utils.EventEmitter(); this._handleNotifySettingChanged = void 0; var self = this, appkey = option.appkey, userId = option.userId, isAutoPull = option.isAutoPull, settingStore = new SettingStore(appkey, userId), localVersion = settingStore.getVersion() || 0; var pullQueue = new PullQueueManager({ event: serverEngine.getUserSettings, thisArg: serverEngine, onFinished: function onFinished(serverData) { if (serverData && serverData.version) { self._settingStore.set(serverData); self._eventEmitter.emit(EventNames.CHANGED, self.get()); } } }); self._handleNotifySettingChanged = function (notifyData) { var version = notifyData.version, localVersion = self._settingStore.getVersion(); if (version >= localVersion) { pullQueue.pull(localVersion); } }; self._settingStore = new SettingStore(appkey, userId); self._pullQueue = pullQueue; self._serverEngine = serverEngine; serverEngine.watch((_serverEngine$watch = {}, _serverEngine$watch[SERVER_EVENT_NAME.USER_SETTING_CHANGED] = self._handleNotifySettingChanged, _serverEngine$watch)); isAutoPull && pullQueue.pull(localVersion); } var _proto = SettingManager.prototype; _proto.watchSettingChanged = function watchSettingChanged(event) { this._eventEmitter.on(EventNames.CHANGED, event); }; _proto.get = function get() { return this._settingStore.getSetting() || {}; }; _proto.close = function close() { var _this$_serverEngine$u; this._serverEngine.unwatch((_this$_serverEngine$u = {}, _this$_serverEngine$u[SERVER_EVENT_NAME.USER_SETTING_CHANGED] = this._handleNotifySettingChanged, _this$_serverEngine$u)); }; return SettingManager; }(); var WebIMEngine = function () { function WebIMEngine(option) { this._option = void 0; this._user = void 0; this._naviManager = void 0; this._cmpManager = new CMPManager(); this._conversationManager = void 0; this._messageManager = void 0; this._chatRoomKVManager = void 0; this._userSettingManager = void 0; this._serverEngine = void 0; this._imEventEmitter = new utils.EventEmitter(); this._connectionStatus = CONNECTION_STATUS.DISCONNECTED; this._connectedDomain = void 0; this._networkDetecter = void 0; this._joinedChatRoomSyner = void 0; var self = this; var detect = option.detect; var serverEngine = new ServerEngine(option); serverEngine.watch({ status: function status(_status) { self._handleConnectionStatus(_status); } }); this._serverEngine = serverEngine; this._option = option; this._networkDetecter = new utils.NetworkDetecter(detect); utils.forEach(ServerEngine.prototype, function (event, eventName) { var server = serverEngine, web = self; var selfEvent = web[eventName], serverEvent = server[eventName]; if (!selfEvent && serverEvent && utils.isFunction(serverEvent)) { web[eventName] = function () { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return serverEvent.call.apply(serverEvent, [server].concat(args)); }; } }); } var _proto = WebIMEngine.prototype; _proto._notifyMessage = function _notifyMessage(event) { var self = this; var message = event.message; var _serverEngine = self._serverEngine; var connectedTime = _serverEngine.getConnectedTime(); if (common.isLogCommandMsg(message)) { var content = message.content; Logger.uploadFull(0, content, connectedTime); return; } this._conversationManager.addMessage(event); this._imEventEmitter.emit(IM_EVENT.MESSAGE, event); }; _proto._handleConnectionStatus = function _handleConnectionStatus(status) { var _cmpManager = this._cmpManager, _naviManager = this._naviManager, _connectedDomain = this._connectedDomain; var isNeedUpdateCMPList = utils.isInclude(TRANSPORTER_STATUS_NEED_UPDATE_CMP, status); var isNeedReconnect = utils.isInclude(TRANSPORTER_STATUS_NEED_RECONNECT, status); var isKickedOfflineByOtherClient = utils.isEqual(CONNECTION_STATUS.KICKED_OFFLINE_BY_OTHER_CLIENT, status); if (isNeedUpdateCMPList) { _cmpManager.addInvalid(_connectedDomain); if (_cmpManager.isAllInvalid()) { _naviManager.clear(); _cmpManager.clearInvalid(); } } if (isNeedReconnect) { this.disconnect(); this.reconnect(true); } if (isKickedOfflineByOtherClient) { this.disconnect(); } var connectionStatus = TRANSPORTER_STATUS_TO_CONNECTION_STATUS[status] || status; this._connectionStatus = connectionStatus; this._imEventEmitter.emit(IM_EVENT.STATUS, { status: connectionStatus }); }; _proto._handleConnectError = function _handleConnectError(errorInfo) { var _user = this._user; var code = errorInfo.code || errorInfo.status; this.disconnect(); if (code === ERROR_INFO.CONN_REDIRECTED.code) { this._naviManager.clear(); return this.connect(_user); } this._connectionStatus = CONNECTION_STATUS.DISCONNECTED; return utils.Defer.reject(errorInfo); }; _proto._afterConnect = function _afterConnect(connectUser, syncTime) { var self = this, _serverEngine = self._serverEngine, appkey = self._option.appkey, _imEventEmitter = self._imEventEmitter, _naviManager = self._naviManager, id = connectUser.id, localNavi = _naviManager.getLocalConfig() || {}; Logger.setOption({ userId: id }); self._user.id = id; var conversationManager = new ConversationManager({ appkey: appkey, userId: id }, _serverEngine); conversationManager.watch({ conversation: function conversation(_ref) { var updatedConversationList = _ref.updatedConversationList; _imEventEmitter.emit(IM_EVENT.CONVERSATION, { updatedConversationList: updatedConversationList }); } }); self._conversationManager = conversationManager; var messageManager = new MessagePullManager(_serverEngine, { startSyncTime: syncTime }); messageManager.watchMessage(function (event) { self._notifyMessage(event); }); self._messageManager = messageManager; self._chatRoomKVManager = new ChatRoomKVManager(_serverEngine); var isAutoPull = !!Number(localNavi.openUS); var userSettingManager = new SettingManager(_serverEngine, { appkey: appkey, userId: id, isAutoPull: isAutoPull }); self._joinedChatRoomSyner = new common.JoinedChatRoomSyner({ appkey: appkey, userId: id }); userSettingManager.watchSettingChanged(function (config) { config = config || {}; var _config = config, voipCallInfo = _config.VoipInfo; _naviManager.setLocalConfig({ voipCallInfo: utils.toJSON(voipCallInfo) }); self._imEventEmitter.emit(IM_EVENT.SETTING, config); }); self._userSettingManager = userSettingManager; }; _proto.watch = function watch(watchers) { var _events; var statusWatcher = watchers.status, messageWatcher = watchers.message, conversationWatcher = watchers.conversation, chatroomWatcher = watchers.chatroom; var self = this; var events = (_events = {}, _events[IM_EVENT.STATUS] = statusWatcher, _events[IM_EVENT.MESSAGE] = messageWatcher, _events[IM_EVENT.CONVERSATION] = conversationWatcher, _events[IM_EVENT.CHATROOM] = chatroomWatcher, _events); utils.forEach(events, function (event, eventName) { utils.isFunction(event) && self._imEventEmitter.on(eventName, event); }); }; _proto.unwatch = function unwatch(watchers) { var _imEventEmitter = this._imEventEmitter; var offEventNameObj = { status: 'IM_EVENT.STATUS', message: 'IM_EVENT.MESSAGE', conversation: 'IM_EVENT.CONVERSATION', chatroom: 'IM_EVENT.CHATROOM' }; if (watchers) { utils.forEach(watchers, function (val, key) { if (offEventNameObj[key]) { _imEventEmitter.off(key, val); } }); } else { _imEventEmitter.clear(); } }; _proto.getConnectionStatus = function getConnectionStatus() { return this._connectionStatus; }; _proto.getConnectionUserId = function getConnectionUserId() { var user = this._user || {}; return user.id; }; _proto.getAppInfo = function getAppInfo() { var _option = this._option, _naviManager = this._naviManager, _userSettingManager = this._userSettingManager; return utils.extendInShallow(_option, { navi: _naviManager.getLocalConfig(), serverConfig: _userSettingManager ? _userSettingManager.get() : {} }); }; _proto.connect = function connect(user, options) { Logger.startRealtimeUpload(); var self = this; var _option = self._option, _serverEngine = self._serverEngine, _cmpManager = self._cmpManager; var naviOpt = common.getNavReqOption(_option, user); var naviManager = new NaviManager(naviOpt); var getServerConfig = _option.isOldServer ? _serverEngine.getOldServerConfig : _serverEngine.getServerConfig; options = options || {}; var isAutoReconnect = options.isAutoReconnect; self._handleConnectionStatus(CONNECTION_STATUS.CONNECTING); self._user = utils.copy(user); self._naviManager = naviManager; var connectUser; return naviManager.get().then(function (configForNavi) { var cmpDomainList = common.getCMPDomainList(configForNavi, _option); Logger.setServerOption(configForNavi); _cmpManager.setDomainList(cmpDomainList); return _cmpManager.getFaster(); }).then(function (_ref2) { var domain = _ref2.domain; self._connectedDomain = domain; return _serverEngine.connect(user, { domain: domain }); }).then(function (user) { connectUser = user; isAutoReconnect && self.rejoinChatRoom(); return getServerConfig.call(_serverEngine, user.id); }).then(function (serverConfig) { self._afterConnect(connectUser, serverConfig); self._handleConnectionStatus(CONNECTION_STATUS.CONNECTED); return connectUser; })["catch"](function (error) { return self._handleConnectError(error); }); }; _proto.reconnect = function reconnect(isAutoReconnect) { var self = this; var _user = self._user; if (utils.isUndefined(_user)) { return utils.Defer.reject(ERROR_INFO.NOT_CONNECTED); } return self._networkDetecter.start().then(function () { return self.connect(_user, { isAutoReconnect: isAutoReconnect }); }); }; _proto.disconnect = function disconnect(isNotify) { isNotify && this._handleConnectionStatus(CONNECTION_STATUS.DISCONNECTED); this._networkDetecter && this._networkDetecter.stop(); this._messageManager && this._messageManager.close(); this._chatRoomKVManager && this._chatRoomKVManager.close(); this._userSettingManager && this._userSettingManager.close(); this._conversationManager && this._conversationManager.close(); return this._serverEngine.disconnect(); }; _proto.changeUser = function changeUser(user) { this.disconnect(true); return this.connect(user); }; _proto.sendMessage = function sendMessage(conversation, option) { var self = this; return self._serverEngine.sendMessage(conversation, option).then(function (message) { self._conversationManager.addMessage({ message: message, hasMore: false }); return message; }); }; _proto.recallMessage = function recallMessage(conversation, message, option) { var self = this; return self._serverEngine.recallMessage(conversation, message, option).then(function (message) { self._conversationManager.addMessage({ message: message, hasMore: false }); return message; }); }; _proto.getConversationList = function getConversationList(option) { var isOldServer = this._option.isOldServer, _serverEngine = this._serverEngine, _conversationManager = this._conversationManager; var func = isOldServer ? _serverEngine.getOldConversationList : _serverEngine.getConversationList; return func.call(_serverEngine, option, { afterDecode: function afterDecode(conversation) { var localConversation = _conversationManager.get(conversation); conversation = utils.extendAllowNull(conversation, localConversation); return conversation; } }).then(function (list) { return common.sortConList(list); }); }; _proto.getLocalConversation = function getLocalConversation(conversation) { var local = this._conversationManager.get(conversation); return { unreadMessageCount: local.unreadMessageCount || 0, hasMentiond: local.hasMentiond || false, mentiondInfo: local.mentiondInfo }; }; _proto.removeConversation = function removeConversation(conversation) { var isOldServer = this._option.isOldServer, _serverEngine = this._serverEngine; var func = isOldServer ? _serverEngine.removeOldConversation : _serverEngine.removeConversation; return func.call(_serverEngine, conversation); }; _proto.getTotalUnreadCount = function getTotalUnreadCount() { var isOldServer = this._option.isOldServer, _serverEngine = this._serverEngine; if (isOldServer) { var totalCount = this._conversationManager.getTotalUnreadCount(); return utils.Defer.resolve(totalCount); } else { return _serverEngine.getTotalUnreadCount(); } }; _proto.getUnreadCount = function getUnreadCount(conversation) { var isOldServer = this._option.isOldServer; if (isOldServer) { var count = this._conversationManager.getUnreadCount(conversation); return utils.Defer.resolve(count); } }; _proto.clearUnreadCount = function clearUnreadCount(conversation, option) { var isOldServer = this._option.isOldServer, _serverEngine = this._serverEngine; if (isOldServer) { this._conversationManager.read(conversation); return utils.Defer.resolve(); } else { return _serverEngine.clearUnreadCount(conversation, option); } }; _proto.joinChatRoom = function joinChatRoom(chrm, option) { var self = this; var _serverEngine = self._serverEngine, _naviManager = self._naviManager, _chatRoomKVManager = self._chatRoomKVManager, _joinedChatRoomSyner = self._joinedChatRoomSyner; var isAutoRejoin = option.isAutoRejoin; return _serverEngine.joinChatRoom(chrm, option).then(function () { return _naviManager.get(); }).then(function (configForNavi) { var isOpenKVStorageService = configForNavi.kvStorage, isOpenJoinMulitpleChrmService = configForNavi.joinMChrm; !isAutoRejoin && _joinedChatRoomSyner.set({ chrmId: chrm.id, count: option.count, isOpenJoinMulitpleChrmService: isOpenJoinMulitpleChrmService }); var initialTime = 0; return isOpenKVStorageService ? _chatRoomKVManager.pull({ time: initialTime, chrmId: chrm.id }) : utils.Defer.resolve(); }); }; _proto.quitChatRoom = function quitChatRoom(chrm) { var self = this; var _serverEngine = self._serverEngine; return _serverEngine.quitChatRoom(chrm).then(function () { self._joinedChatRoomSyner.remove(chrm.id); return utils.Defer.resolve(); }); }; _proto.rejoinChatRoom = function rejoinChatRoom() { var self = this; var _joinedChatRoomSyner = self._joinedChatRoomSyner, _imEventEmitter = self._imEventEmitter; var joinedChrmInfos = _joinedChatRoomSyner.get(); utils.forEach(joinedChrmInfos, function (chrmInfo) { var chrmId = chrmInfo.chrmId, count = chrmInfo.count; var isAutoRejoin = true, isJoinExist = true; return self.joinChatRoom({ id: chrmId }, { count: count, isAutoRejoin: isAutoRejoin, isJoinExist: isJoinExist }).then(function () { _imEventEmitter.emit(IM_EVENT.CHATROOM, { chatroomId: chrmId, count: count }); }, function (reason) { _imEventEmitter.emit(IM_EVENT.CHATROOM, { chatroomId: chrmId, count: count, errorCode: reason }); }); }); }; _proto.setChatRoomKV = function setChatRoomKV(chrm, entry) { var self = this; utils.extend(entry, { type: CHATROOM_ENTRY_TYPE.UPDATE, userId: self._user.id }); entry.type = CHATROOM_ENTRY_TYPE.UPDATE; return self._serverEngine.modifyChatRoomKV(chrm, entry); }; _proto.forceSetChatRoomKV = function forceSetChatRoomKV(chrm, entry) { entry.isOverwrite = true; return this.setChatRoomKV(chrm, entry); }; _proto.removeChatRoomKV = function removeChatRoomKV(chrm, entry) { var self = this; utils.extend(entry, { type: CHATROOM_ENTRY_TYPE.DELETE, userId: self._user.id }); return self._serverEngine.modifyChatRoomKV(chrm, entry); }; _proto.forceRemoveChatRoomKV = function forceRemoveChatRoomKV(chrm, entry) { entry.isOverwrite = true; return this.removeChatRoomKV(chrm, entry); }; _proto.getChatRoomKV = function getChatRoomKV(chrm, key) { var value = this._chatRoomKVManager.getValue(chrm.id, key); if (utils.isEmpty(value)) { return utils.Defer.reject(ERROR_INFO.CHATROOM_KEY_NOT_EXIST); } else { return utils.Defer.resolve(value); } }; _proto.getAllChatRoomKV = function getAllChatRoomKV(chrm) { var kvs = this._chatRoomKVManager.getAll(chrm.id); return utils.Defer.resolve(kvs); }; _proto.getFileToken = function getFileToken(fileType, originName) { var self = this; var fileName = common.genUploadFileName(fileType, originName); var uploadDomains = common.getUploadFileDomains(self._naviManager.getLocalConfig()); return self._serverEngine.getFileToken(fileType, fileName).then(function (data) { return utils.extendInShallow(uploadDomains, data); }); }; _proto.getFileUrl = function getFileUrl(fileType, fileName, originName, uploadResp) { var self = this; uploadResp = uploadResp || {}; if (uploadResp.isBosRes) { return utils.Defer.resolve(uploadResp); } return self._serverEngine.getFileUrl(fileType, fileName, originName); }; return WebIMEngine; }(); var Engine = (function (imArg) { return new WebIMEngine(imArg); }); var execEngineByEvent = function execEngineByEvent(params, engine) { var eventName = params.event, args = params.args; args = args || []; var engineEvent = engine[eventName] || function () { return utils.Defer.reject(ERROR_INFO.SDK_INTERNAL_ERROR); }; return engineEvent.apply(engine, args); }; var EngineDispatcher = function () { function EngineDispatcher(option) { this._engine = void 0; this._engine = new Engine(option); } var _proto = EngineDispatcher.prototype; _proto._isEventNeedConnect = function _isEventNeedConnect(eventName) { var engine = this._engine, connectionStatus = engine.getConnectionStatus(), isNotConnected = connectionStatus !== CONNECTION_STATUS.CONNECTED, isEventNeedConnected = utils.isInclude(ENGINE_EVENT_NEED_CONNECTED, eventName); return isNotConnected && isEventNeedConnected; }; _proto._isEventNeedDisconnect = function _isEventNeedDisconnect(eventName) { var engine = this._engine, connectionStatus = engine.getConnectionStatus(), isConnecting = common.isConnected(connectionStatus) || common.isConnecting(connectionStatus), isEventNeedDisconnected = utils.isInclude(ENGINE_EVENT_NEED_DISCONNECTED, eventName); return isConnecting && isEventNeedDisconnected; }; _proto._exec = function _exec(params) { var event = params.event; var engine = this._engine; if (this._isEventNeedConnect(event)) { return utils.Defer.reject(ERROR_INFO.NOT_CONNECTED); } if (this._isEventNeedDisconnect(event)) { return utils.Defer.reject(ERROR_INFO.RC_CONNECTION_EXIST); } var execResult = execEngineByEvent(params, engine); return utils.isPromise(execResult) ? execResult["catch"](function (error) { var errorCode = error.status || error.code || error; var msg = utils.isObject(error) ? error.msg : null; var errorInfo = ERROR_CODE_TO_INFO[errorCode] || { code: errorCode }; if (msg) { errorInfo.msg = msg; } var isValidErrorCode = utils.isNumberData(errorCode); if (!isValidErrorCode) { if (utils.isStackError(error)) { error = error.stack.toString(); } Logger.fatal(TAG.L_CRASH_E, { content: { desc: 'SDK Error', error: error } }); errorInfo = utils.extendInShallow(ERROR_INFO.SDK_INTERNAL_ERROR, { error: error }); } return utils.Defer.reject(errorInfo); }) : execResult; }; _proto.exec = function exec(params) { var event = params.event; var LOG_TAG = APP_ENGINE_EVENT_LOG_TAG[event], isNeedLog = !utils.isEmpty(LOG_TAG), _ref = LOG_TAG || {}, reqLogTag = _ref.req, respLogTag = _ref.resp; isNeedLog && Logger.info(reqLogTag, params); var execResult = this._exec(params); if (utils.isPromise(execResult)) { return execResult.then(function (result) { isNeedLog && Logger.info(respLogTag, result); return result; })["catch"](function (error) { error = error || {}; var _error = error, code = _error.code; if (isNeedLog && !Logger.isIgnoreErrorCode(code)) { Logger.error(respLogTag, error); } return utils.Defer.reject(error); }); } else { isNeedLog && Logger.info(respLogTag, execResult); return execResult; } }; return EngineDispatcher; }(); var Type = function Type(name, validator, options) { options = options || {}; var self = this; self.validate = validator; self.name = name; self.errorInfo = options.errorInfo; self.canBeNull = function () { self.validate = function (data) { return utils.isUndefined(data) || utils.isNull(data) || validator(data); }; return self; }; }; Type.isType = function (type) { return type instanceof Type; }; Type.String = new Type('String', utils.isString); Type.Number = new Type('Number', utils.isNumber); Type.Boolean = new Type('Boolean', utils.isBoolean); Type.Function = new Type('Function', utils.isFunction); Type.Object = new Type('Object', utils.isObject); Type.Array = new Type('Array', utils.isArray); Type.NotAllUndefined = new Type('AllUndefined', function (obj) { if (utils.isObject(obj) || utils.isArray(obj)) { var isNotUndefined = false; utils.forEach(obj, function (val) { if (!utils.isUndefined(val)) { isNotUndefined = true; } }); return isNotUndefined; } else { return !utils.isUndefined(obj); } }); var conversationType = common.getConversationTypeList().join('、'); Type.ConversationType = new Type(conversationType, common.isValidConversationType, { errorInfo: 'Not all settings are empty' }); Type.ChatRoomEntryKey = new Type('ChatRoomEntryKey', common.isValidChatRoomKey, { errorInfo: 'ChatRoom Key length must be 1 - 128, Only letters、numbers、+、=、-、_ are supported' }); Type.ChatRoomEntryValue = new Type('ChatRoomEntryValue', common.isValidChatRoomValue, { errorInfo: 'ChatRoom Value length must be 1 - 4096' }); var Struct = function () { function Struct(structure, funcName, paths) { if (paths === void 0) { paths = []; } if (!(this instanceof Struct)) { return new Struct(structure, funcName, paths); } var self = this; self.structure = structure; self.paths = paths; self.funcName = funcName; if (Type.isType(structure)) { self.validate = self._validateType; } else if (utils.isArray(structure)) { self.validate = self._validateArray; } else if (utils.isObject(structure)) { self.validate = self._validateObject; } else { self.validate = self._validateOther; } } var _proto = Struct.prototype; _proto._validateType = function _validateType(data) { var structure = this.structure; var isValid = structure.validate(data); return isValid ? this._getSuccess() : this._getError(data); }; _proto._validateArray = function _validateArray(data) { var structure = this.structure; if (utils.isEmpty(structure)) { return this._getSuccess(); } if (!utils.isArray(data)) { return this._getError(data); } var typer = structure[0]; for (var filed in data) { var val = data[filed]; var result = this._validateField(typer, filed, val); if (result.isError) { return result; } } return this._getSuccess(); }; _proto._validateObject = function _validateObject(data) { var structure = this.structure, paths = this.paths; data = data || {}; if (utils.isEmpty(structure)) { return this._getSuccess(); } if (!utils.isObject(data)) { return this._getError(data); } var checkedField = []; for (var filed in data) { var typer = structure[filed], val = data[filed]; var result = this._validateField(typer, filed, val); if (result.isError) { return result; } checkedField.push(filed); } for (var checkField in structure) { var _typer = structure[checkField]; var unCheckData = data[checkField]; if (!utils.isInclude(checkedField, checkField) && !_typer.validate(unCheckData)) { var errPaths = utils.copy(paths); errPaths.push(checkField); return this._getError(unCheckData, { paths: errPaths, expect: _typer.name }); } } return this._getSuccess(); }; _proto._validateOther = function _validateOther(data) { var self = this; var structure = self.structure; if (utils.isEqual(structure, data) || utils.isEmpty(structure)) { return self._getSuccess(); } else { return self._getError(data, { current: data, expect: structure }); } }; _proto._validateField = function _validateField(typer, filed, value) { var paths = this.paths, funcName = this.funcName; var newPaths = utils.copy(paths); newPaths.push(filed); return new Struct(typer, funcName, newPaths).validate(value); }; _proto._getError = function _getError(data, options) { if (options === void 0) { options = []; } var structure = this.structure, paths = this.paths, funcName = this.funcName; options = utils.extend({ current: data, expect: structure.name || utils.getTypeName(structure), paths: paths }, options); paths = options.paths; var _options = options, current = _options.current, expect = _options.expect; var param = utils.isEmpty(paths) ? 'param' : paths.join('.'); var currentType = utils.getTypeName(current); current = utils.toJSON(current) || current; current = current + "(" + currentType + ")"; var msg = utils.tplEngine(ERROR_INFO.PARAMETER_ERROR.msg, { param: param, expect: expect, current: current }); var info = { code: ERROR_INFO.PARAMETER_ERROR.code, funcName: funcName, msg: msg }; var jsonInfo = utils.toJSON(info); if (utils.isEmpty(funcName)) delete info[funcName]; if (structure.errorInfo) { info = structure.errorInfo; } return { isError: true, info: info, jsonInfo: jsonInfo }; }; _proto._getSuccess = function _getSuccess() { return { isError: false }; }; return Struct; }(); var validate = (function (struct, params, eventName) { return Struct(struct, eventName).validate(params); }); var _MESSAGE_TYPE_VALIDAT; var MESSAGE_TYPE_VALIDATE = (_MESSAGE_TYPE_VALIDAT = {}, _MESSAGE_TYPE_VALIDAT[MESSAGE_TYPE.TEXT] = { content: Type.String }, _MESSAGE_TYPE_VALIDAT[MESSAGE_TYPE.VOICE] = { content: Type.String, duration: Type.Number }, _MESSAGE_TYPE_VALIDAT[MESSAGE_TYPE.HQ_VOICE] = { remoteUrl: Type.String, duration: Type.Number }, _MESSAGE_TYPE_VALIDAT[MESSAGE_TYPE.IMAGE] = { content: Type.String, imageUri: Type.String }, _MESSAGE_TYPE_VALIDAT[MESSAGE_TYPE.GIF] = { gifDataSize: Type.Number, width: Type.Number, height: Type.Number, remoteUrl: Type.String }, _MESSAGE_TYPE_VALIDAT[MESSAGE_TYPE.RICH_CONTENT] = { title: Type.String, content: Type.String, imageUri: Type.String, url: Type.String }, _MESSAGE_TYPE_VALIDAT[MESSAGE_TYPE.LOCATION] = { content: Type.String, latitude: Type.Number, longitude: Type.Number, poi: Type.String }, _MESSAGE_TYPE_VALIDAT[MESSAGE_TYPE.FILE] = { name: Type.String, size: Type.Number, type: Type.String, fileUrl: Type.String }, _MESSAGE_TYPE_VALIDAT[MESSAGE_TYPE.SIGHT] = { sightUrl: Type.String, content: Type.String, duration: Type.Number, size: Type.Number, name: Type.String }, _MESSAGE_TYPE_VALIDAT[MESSAGE_TYPE.COMBINE] = { remoteUrl: Type.String, conversationType: Type.Number, nameList: Type.Array, summaryList: Type.Array }, _MESSAGE_TYPE_VALIDAT); var validateMsgContent = (function (objectName, option, eventName) { var validateByObjectName = MESSAGE_TYPE_VALIDATE[objectName]; if (validateByObjectName) { return validate(validateByObjectName, option, eventName); } else { return { isError: false, info: '' }; } }); var Conversation = (function (_engineDispatcher) { var _temp; return _temp = function () { Conversation.create = function create(option) { return new Conversation(option); }; Conversation.get = function get(option) { return new Conversation(option); }; Conversation.merge = function merge(option) { try { return common.mergeConversationList(option); } catch (e) { utils.consoleError(e); } }; Conversation.remove = function remove(option) { var _validate = validate({ type: Type.ConversationType, targetId: Type.String }, option, 'Conversation.remove'), isError = _validate.isError, info = _validate.info; if (isError) { return utils.Defer.reject(info); } return _engineDispatcher.exec({ event: ENGINE_EVENT.REMOVE_CONVERSATION, args: [option] }); }; Conversation.getList = function getList(option) { var _validate2 = validate({ count: Type.Number.canBeNull(), startTime: Type.Number.canBeNull() }, option, 'Conversation.getList'), isError = _validate2.isError, info = _validate2.info; if (isError) { return utils.Defer.reject(info); } return _engineDispatcher.exec({ event: ENGINE_EVENT.GET_CONVERSATION_LIST, args: [option] }); }; Conversation.getTotalUnreadCount = function getTotalUnreadCount() { return _engineDispatcher.exec({ event: ENGINE_EVENT.GET_TOTAL_UNREAD_COUNT }); }; function Conversation(option) { this.type = void 0; this.targetId = void 0; var _validate3 = validate({ type: Type.ConversationType, targetId: Type.String }, option, 'new Conversation'), isError = _validate3.isError, jsonInfo = _validate3.jsonInfo; if (isError) { utils.consoleError(jsonInfo); return jsonInfo; } utils.extend(this, option); } var _proto = Conversation.prototype; _proto.send = function send(option) { var eventName = 'conversation.send'; var _validate4 = validate({ messageType: Type.String, content: Type.Object }, option, eventName), isError = _validate4.isError, info = _validate4.info; if (isError) { return utils.Defer.reject(info); } var _option = option, messageType = _option.messageType, content = _option.content; var _validateMsgContent = validateMsgContent(messageType, content, eventName), isContentError = _validateMsgContent.isError, formatInfo = _validateMsgContent.info; if (isContentError) { return utils.Defer.reject(formatInfo); } var _option2 = option, isMentiond = _option2.isMentiond, mentiondType = _option2.mentiondType, mentiondUserIdList = _option2.mentiondUserIdList; isMentiond && (option.isMentioned = isMentiond); mentiondType && (option.mentionedType = mentiondType); mentiondUserIdList && (option.mentionedUserIdList = mentiondUserIdList); option = utils.extendInShallow(SEND_MESSAGE_TYPE_OPTION[messageType], option); option = utils.extendInShallow(SEND_MESSAGE_OPTION, option); return _engineDispatcher.exec({ event: ENGINE_EVENT.SEND_MESSAGE, args: [this, option] }); }; _proto.recall = function recall(message, option) { var _validate5 = validate({ sentTime: Type.Number, messageUId: Type.String }, message, 'conversation.recall'), isError = _validate5.isError, info = _validate5.info; if (isError) { return utils.Defer.reject(info); } return _engineDispatcher.exec({ event: ENGINE_EVENT.RECALL_MESSAGE, args: [this, message, option] }); }; _proto.read = function read(option) { return _engineDispatcher.exec({ event: ENGINE_EVENT.CLEAR_UNREAD_COUNT, args: [this, option] }); }; _proto.getUnreadCount = function getUnreadCount() { var conversation = this; return _engineDispatcher.exec({ event: ENGINE_EVENT.GET_UNREAD_COUNT, args: [conversation] }); }; _proto.getMessages = function getMessages(option) { var _validate6 = validate({ order: Type.Number.canBeNull(), count: Type.Number.canBeNull(), timestrap: Type.Number.canBeNull() }, option, 'conversation.getMessages'), isError = _validate6.isError, info = _validate6.info; if (isError) { return utils.Defer.reject(info); } option = utils.extendInShallow(GET_MESSAGES_OPTION, option); return _engineDispatcher.exec({ event: ENGINE_EVENT.GET_HISTORY_MSGS, args: [this, option] }); }; _proto.deleteMessages = function deleteMessages(messages) { var _validate7 = validate([{ sentTime: Type.Number, messageUId: Type.String, messageDirection: Type.Number }], messages, 'conversation.deleteMessages'), isError = _validate7.isError, info = _validate7.info; if (isError) { return utils.Defer.reject(info); } return _engineDispatcher.exec({ event: ENGINE_EVENT.DELETE_MESSAGES, args: [this, messages] }); }; _proto.clearMessages = function clearMessages(option) { var _validate8 = validate({ timestrap: Type.Number }, option, 'conversation.clearMessages'), isError = _validate8.isError, info = _validate8.info; if (isError) { return utils.Defer.reject(info); } return _engineDispatcher.exec({ event: ENGINE_EVENT.CLEAR_MESSAGES, args: [this, option] }); }; _proto.setStatus = function setStatus(option) { var _validate9 = validate({ notificationStatus: Type.Number.canBeNull(), isTop: Type.Boolean.canBeNull() }, option, 'conversation.setStatus'), isError = _validate9.isError, info = _validate9.info; if (isError) { return utils.Defer.reject(info); } var allUndefinedValidate = validate(Type.NotAllUndefined, option); isError = allUndefinedValidate.isError; if (isError) { info = allUndefinedValidate.info; return utils.Defer.reject(info); } var notificationStatus = option.notificationStatus, isTop = option.isTop; return _engineDispatcher.exec({ event: ENGINE_EVENT.SET_CONVERSATION_STATUS_LIST, args: [[{ type: this.type, targetId: this.targetId, notificationStatus: notificationStatus, isTop: isTop }]] }); }; _proto.setStatusList = function setStatusList(statusList) { var _validate10 = validate([{ notificationStatus: Type.Number.canBeNull(), isTop: Type.Boolean.canBeNull() }], statusList, 'conversation.setStatusList'), isError = _validate10.isError, info = _validate10.info; if (isError) { return utils.Defer.reject(info); } var self = this; statusList = utils.map(statusList, function (status) { return utils.extend(status, { type: self.type, targetId: self.targetId }); }); return _engineDispatcher.exec({ event: ENGINE_EVENT.SET_CONVERSATION_STATUS_LIST, args: [statusList] }); }; _proto.destory = function destory() { var conversation = this; return _engineDispatcher.exec({ event: ENGINE_EVENT.REMOVE_CONVERSATION, args: [conversation] }); }; return Conversation; }(), _temp; }); var ChatRoom = (function (_engineDispatcher) { var _temp; return _temp = function () { ChatRoom.get = function get(option) { return new ChatRoom(option); }; function ChatRoom(option) { this.id = void 0; var _validate = validate({ id: Type.String }, option, 'new ChatRoom'), isError = _validate.isError, jsonInfo = _validate.jsonInfo; if (isError) { utils.consoleError(jsonInfo); return jsonInfo; } utils.extend(this, option); } var _proto = ChatRoom.prototype; _proto.join = function join(option) { var _validate2 = validate({ count: Type.Number.canBeNull() }, option, 'chatRoom.join'), isError = _validate2.isError, info = _validate2.info; if (isError) { return utils.Defer.reject(info); } option = utils.extendInShallow(JOIN_CHATROOM_OPTION, option); return _engineDispatcher.exec({ event: ENGINE_EVENT.JOIN_CHATROOM, args: [this, option] }); }; _proto.joinExist = function joinExist(option) { var _validate3 = validate({ count: Type.Number.canBeNull() }, option, 'chatRoom.joinExist'), isError = _validate3.isError, info = _validate3.info; if (isError) { return utils.Defer.reject(info); } option['isJoinExist'] = true; option = utils.extendInShallow(JOIN_CHATROOM_OPTION, option); return _engineDispatcher.exec({ event: ENGINE_EVENT.JOIN_CHATROOM, args: [this, option] }); }; _proto.quit = function quit() { return _engineDispatcher.exec({ event: ENGINE_EVENT.QUIT_CHATROOM, args: [this] }); }; _proto.getInfo = function getInfo(option) { var _validate4 = validate({ count: Type.Number.canBeNull(), order: Type.Number.canBeNull() }, option, 'chatRoom.getInfo'), isError = _validate4.isError, info = _validate4.info; if (isError) { return utils.Defer.reject(info); } option = utils.extendInShallow(GET_CHATROOM_INFO_OPTION, option); return _engineDispatcher.exec({ event: ENGINE_EVENT.GET_CHATROOM_INFO, args: [this, option] }); }; _proto.send = function send(option) { var eventName = 'chatRoom.send'; var _validate5 = validate({ messageType: Type.String, content: Type.Object }, option, eventName), isError = _validate5.isError, info = _validate5.info; if (isError) { return utils.Defer.reject(info); } var id = this.id; var _option = option, messageType = _option.messageType, content = _option.content; var _validateMsgContent = validateMsgContent(messageType, content, eventName), isContentError = _validateMsgContent.isError, formatInfo = _validateMsgContent.info; if (isContentError) { return utils.Defer.reject(formatInfo); } var conversation = { type: CONVERSATION_TYPE.CHATROOM, targetId: id }; option = utils.extendInShallow(SEND_MESSAGE_TYPE_OPTION[messageType], option); return _engineDispatcher.exec({ event: ENGINE_EVENT.SEND_MESSAGE, args: [conversation, option] }); }; _proto.getMessages = function getMessages(option) { var _validate6 = validate({ count: Type.Number.canBeNull(), order: Type.Number.canBeNull(), timestrap: Type.Number }, option, 'chatRoom.getInfo'), isError = _validate6.isError, info = _validate6.info; if (isError) { return utils.Defer.reject(info); } option = utils.extendInShallow(GET_CHATROOM_MESSAGES, option); return _engineDispatcher.exec({ event: ENGINE_EVENT.GET_CHATROOM_MSGS, args: [this, option] }); }; _proto.setEntry = function setEntry(option) { var _validate7 = validate({ key: Type.ChatRoomEntryKey, value: Type.ChatRoomEntryValue }, option, 'chatRoom.setEntry'), isError = _validate7.isError, info = _validate7.info; if (isError) { return utils.Defer.reject(info); } return _engineDispatcher.exec({ event: ENGINE_EVENT.SET_KV, args: [this, option] }); }; _proto.forceSetEntry = function forceSetEntry(option) { var _validate8 = validate({ key: Type.ChatRoomEntryKey, value: Type.ChatRoomEntryValue }, option, 'chatRoom.forceSetEntry'), isError = _validate8.isError, info = _validate8.info; if (isError) { return utils.Defer.reject(info); } return _engineDispatcher.exec({ event: ENGINE_EVENT.FORCE_SET_KV, args: [this, option] }); }; _proto.removeEntry = function removeEntry(option) { var _validate9 = validate({ key: Type.ChatRoomEntryKey }, option, 'chatRoom.removeEntry'), isError = _validate9.isError, info = _validate9.info; if (isError) { return utils.Defer.reject(info); } return _engineDispatcher.exec({ event: ENGINE_EVENT.DEL_KV, args: [this, option] }); }; _proto.forceRemoveEntry = function forceRemoveEntry(option) { var _validate10 = validate({ key: Type.ChatRoomEntryKey }, option, 'chatRoom.forceRemoveEntry'), isError = _validate10.isError, info = _validate10.info; if (isError) { return utils.Defer.reject(info); } return _engineDispatcher.exec({ event: ENGINE_EVENT.FORCE_DEL_KV, args: [this, option] }); }; _proto.getEntry = function getEntry(key) { var _validate11 = validate(Type.ChatRoomEntryKey, key, 'chatRoom.getEntry'), isError = _validate11.isError, info = _validate11.info; if (isError) { return utils.Defer.reject(info); } return _engineDispatcher.exec({ event: ENGINE_EVENT.GET_KV, args: [this, key] }); }; _proto.getAllEntries = function getAllEntries() { return _engineDispatcher.exec({ event: ENGINE_EVENT.GET_ALL_KV, args: [this] }); }; return ChatRoom; }(), _temp; }); var RTC = (function (_engineDispatcher) { var _temp; return _temp = function () { RTC.get = function get(option) { return new RTC(option); }; function RTC(option) { this.roomId = void 0; this.option = void 0; this.roomId = option.id; this.option = option; } var _proto = RTC.prototype; _proto.join = function join() { return _engineDispatcher.exec({ event: ENGINE_EVENT.JOIN_RTC, args: [this.option] }); }; _proto.quit = function quit() { return _engineDispatcher.exec({ event: ENGINE_EVENT.QUIT_RTC, args: [this.option] }); }; _proto.ping = function ping() { return _engineDispatcher.exec({ event: ENGINE_EVENT.PING_RTC, args: [this.option] }); }; _proto.getRoomInfo = function getRoomInfo() { return _engineDispatcher.exec({ event: ENGINE_EVENT.GET_RTC_ROOM_INFO, args: [this.option] }); }; _proto.getUserInfoList = function getUserInfoList() { return _engineDispatcher.exec({ event: ENGINE_EVENT.GET_RTC_USER_INFO_LIST, args: [this.option] }); }; _proto.setUserInfo = function setUserInfo(info) { return _engineDispatcher.exec({ event: ENGINE_EVENT.SET_RTC_USER_INFO, args: [this.option, info] }); }; _proto.removeUserInfo = function removeUserInfo(info) { return _engineDispatcher.exec({ event: ENGINE_EVENT.DEL_RTC_USER_INFO, args: [this.option, info] }); }; _proto.setData = function setData(key, value, isInner, apiType, message) { return _engineDispatcher.exec({ event: ENGINE_EVENT.SET_RTC_DATA, args: [this.roomId, key, value, isInner, apiType, message] }); }; _proto.getData = function getData(keys, isInner, apiType) { return _engineDispatcher.exec({ event: ENGINE_EVENT.GET_RTC_DATA, args: [this.roomId, keys, isInner, apiType] }); }; _proto.removeData = function removeData(keys, isInner, apiType, message) { return _engineDispatcher.exec({ event: ENGINE_EVENT.DEL_RTC_DATA, args: [this.roomId, keys, isInner, apiType, message] }); }; _proto.setUserData = function setUserData(key, value, isInner, message) { return this.setData(key, value, isInner, RTC_API_TYPE.PERSON, message); }; _proto.setRTCUserData = function setRTCUserData(message, valueInfo, objectName) { return _engineDispatcher.exec({ event: ENGINE_EVENT.SET_RTC_USER_DATA, args: [this.roomId, message, valueInfo, objectName] }); }; _proto.getUserData = function getUserData(keys, isInner) { return this.getData(keys, isInner, RTC_API_TYPE.PERSON); }; _proto.removeUserData = function removeUserData(keys, isInner, message) { return this.removeData(keys, isInner, RTC_API_TYPE.PERSON, message); }; _proto.setRoomData = function setRoomData(key, value, isInner, message) { return this.setData(key, value, isInner, RTC_API_TYPE.ROOM, message); }; _proto.getRoomData = function getRoomData(keys, isInner) { return this.getData(keys, isInner, RTC_API_TYPE.ROOM); }; _proto.removeRoomData = function removeRoomData(keys, isInner, message) { return this.removeData(keys, isInner, RTC_API_TYPE.ROOM, message); }; _proto.getUserList = function getUserList() { return _engineDispatcher.exec({ event: ENGINE_EVENT.GET_RTC_USER_LIST, args: [this.option] }); }; _proto.setOutData = function setOutData(rtcData, type, message) { return _engineDispatcher.exec({ event: ENGINE_EVENT.SET_RTC_OUT_DATA, args: [this.roomId, rtcData, type, message] }); }; _proto.getOutData = function getOutData(userIds) { return _engineDispatcher.exec({ event: ENGINE_EVENT.GET_RTC_OUT_DATA, args: [this.roomId, userIds] }); }; _proto.getToken = function getToken() { return _engineDispatcher.exec({ event: ENGINE_EVENT.GET_RTC_TOKEN, args: [this.option] }); }; _proto.setState = function setState(content) { return _engineDispatcher.exec({ event: ENGINE_EVENT.SET_RTC_STATE, args: [this.option, content] }); }; _proto.send = function send(option) { var id = this.roomId; var conversation = { type: CONVERSATION_TYPE.RTC_ROOM, targetId: id }; return _engineDispatcher.exec({ event: ENGINE_EVENT.SEND_MESSAGE, args: [conversation, option] }); }; return RTC; }(), _temp; }); var IM = function () { function IM(option) { this._engineDispatcher = void 0; var _validate = validate({ appkey: Type.String }, option, 'RongIMLib.init'), isError = _validate.isError, jsonInfo = _validate.jsonInfo; if (isError) { throw Error(jsonInfo); } var engineHandler = new EngineDispatcher(option); this._engineDispatcher = engineHandler; var Modules = { Conversation: Conversation(engineHandler), ChatRoom: ChatRoom(engineHandler), RTC: RTC(engineHandler) }; utils.extend(this, Modules); } var _proto = IM.prototype; _proto.getConnectionStatus = function getConnectionStatus() { return this._engineDispatcher.exec({ event: ENGINE_EVENT.GET_CONNECTION_STATUS }); }; _proto.getConnectionUserId = function getConnectionUserId() { return this._engineDispatcher.exec({ event: ENGINE_EVENT.GET_CONNECTION_USER_ID }); }; _proto.getConnectedTime = function getConnectedTime() { return this._engineDispatcher.exec({ event: ENGINE_EVENT.GET_CONNECTED_TIME }); }; _proto.getAppInfo = function getAppInfo() { return this._engineDispatcher.exec({ event: ENGINE_EVENT.GET_APP_INFO }); }; _proto.watch = function watch(watchers) { var _validate2 = validate({ conversation: Type.Function.canBeNull(), message: Type.Function.canBeNull(), status: Type.Function.canBeNull(), setting: Type.Function.canBeNull() }, watchers, 'im.watch'), isError = _validate2.isError, jsonInfo = _validate2.jsonInfo; if (isError) { utils.consoleError(jsonInfo); return jsonInfo; } return this._engineDispatcher.exec({ event: ENGINE_EVENT.WATCH, args: [watchers] }); }; _proto.unwatch = function unwatch(watchers) { return this._engineDispatcher.exec({ event: ENGINE_EVENT.UN_WATCH, args: [watchers] }); }; _proto.connect = function connect(user) { var _validate3 = validate({ token: Type.String }, user, 'im.connect'), isError = _validate3.isError, info = _validate3.info; if (isError) { return utils.Defer.reject(info); } return this._engineDispatcher.exec({ event: ENGINE_EVENT.CONNECT, args: [user] }); }; _proto.reconnect = function reconnect() { return this._engineDispatcher.exec({ event: ENGINE_EVENT.RECONNECT }); }; _proto.disconnect = function disconnect() { return this._engineDispatcher.exec({ event: ENGINE_EVENT.DISCONNECT, args: [true] }); }; _proto.changeUser = function changeUser(user) { var _validate4 = validate({ token: Type.String }, user, 'im.changeUser'), isError = _validate4.isError, info = _validate4.info; if (isError) { return utils.Defer.reject(info); } var self = this; return self.disconnect().then(function () { return self.connect(user); }); }; _proto.getFileToken = function getFileToken(fileType, originName) { return this._engineDispatcher.exec({ event: ENGINE_EVENT.GET_UPLOAD_TOKEN, args: [fileType, originName] }); }; _proto.getFileUrl = function getFileUrl(fileType, fileName, originName, uploadResp) { return this._engineDispatcher.exec({ event: ENGINE_EVENT.GET_UPLOAD_URL, args: [fileType, fileName, originName, uploadResp] }); }; return IM; }(); var imInstance; var initLogger = function initLogger(option, im) { var isDebug = option.isDebug, appkey = option.appkey, logCollectEvent = option.logger; utils.isFunction(logCollectEvent) && Logger.watchLog(logCollectEvent); Logger.setOption({ isDebug: isDebug, appkey: appkey }); Logger.info(TAG.A_INIT_O, { content: option }); im.watch({ status: function status(_ref) { var _status = _ref.status; Logger.setOption({ isNetworkUnavailable: utils.isEqual(_status, CONNECTION_STATUS.NETWORK_UNAVAILABLE) }); } }); }; var init = function init(option) { option = utils.extendInShallow(IM_OPTION, option); option.connectType = common.getConnectType(option); if (!imInstance) { imInstance = new IM(option); initLogger(option, imInstance); } return imInstance; }; var getInstance = function getInstance() { return imInstance; }; var index = utils.extend({ init: init, getInstance: getInstance, env: env, common: common, ERROR_CODE: ERROR_CODE, Logger: Logger }, product); return index; }))); ================================================ FILE: api-test/lib/js/RongIMLib-3.0.6.js ================================================ /* * RongIMLib.js v3.0.6-dev * CodeVersion: bd0b45c07bd62b49b88cfc01b0e0d37aca0ae91c * Release Date: Thu Aug 13 2020 18:01:59 GMT+0800 (China Standard Time) * Copyright 2020 RongCloud */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global.RongIMLib = factory()); }(this, (function () { 'use strict'; var versionToServer = "3.0.6"; var SDK_VERSION = versionToServer; var ERROR_INFO = { TIMEOUT: { code: -1, msg: 'Network timeout' }, SDK_INTERNAL_ERROR: { code: -2, msg: 'SDK internal error' }, PARAMETER_ERROR: { code: -3, msg: 'Please check the parameters, the {param} expected a value of {expect} but received {current}' }, REJECTED_BY_BLACKLIST: { code: 405, msg: 'Blacklisted by the other party' }, SEND_TOO_FAST: { code: 20604, msg: 'Sending messages too quickly' }, NOT_IN_GROUP: { code: 22406, msg: 'Not in group' }, FORBIDDEN_IN_GROUP: { code: 22408, msg: 'Forbbiden from speaking in the group' }, NOT_IN_CHATROOM: { code: 23406, msg: 'Not in chatRoom' }, FORBIDDEN_IN_CHATROOM: { code: 23408, msg: 'Forbbiden from speaking in the chatRoom' }, KICKED_FROM_CHATROOM: { code: 23409, msg: 'Kicked out and forbbiden from joining the chatRoom' }, CHATROOM_NOT_EXIST: { code: 23410, msg: 'ChatRoom does not exist' }, CHATROOM_IS_FULL: { code: 23411, msg: 'ChatRoom members exceeded' }, PARAMETER_INVALID_CHATROOM: { code: 23412, msg: 'Invalid chatRoom parameters' }, ROAMING_SERVICE_UNAVAILABLE_CHATROOM: { code: 23414, msg: 'ChatRoom message roaming service is not open, Please go to the developer to open this service' }, RECALLMESSAGE_PARAMETER_INVALID: { code: 25101, msg: 'Invalid recall message parameter' }, PUSHSETTING_PARAMETER_INVALID: { code: 26001, msg: 'Invalid push parameter' }, OPERATION_BLOCKED: { code: 20605, msg: 'Operation is blocked' }, OPERATION_NOT_SUPPORT: { code: 20606, msg: 'Operation is not supported' }, MSG_BLOCKED_SENSITIVE_WORD: { code: 21501, msg: 'The sent message contains sensitive words' }, REPLACED_SENSITIVE_WORD: { code: 21502, msg: 'Sensitive words in the message have been replaced' }, NOT_CONNECTED: { code: 30001, msg: 'Please connect successfully first' }, NAVI_REQUEST_ERROR: { code: 30007, msg: 'Navigation http request failed' }, CMP_REQUEST_ERROR: { code: 30010, msg: 'CMP sniff http request failed' }, CONN_APPKEY_FAKE: { code: 31002, msg: 'Your appkey is fake' }, CONN_MINI_SERVICE_NOT_OPEN: { code: 31003, msg: 'Mini program service is not open, Please go to the developer to open this service' }, CONN_ACK_TIMEOUT: { code: 31000, msg: 'Connection ACK timeout' }, CONN_TOKEN_INCORRECT: { code: 31004, msg: 'Your token is not valid or expired' }, CONN_NOT_AUTHRORIZED: { code: 31005, msg: 'AppKey and Token do not match' }, CONN_REDIRECTED: { code: 31006, msg: 'Connection redirection' }, CONN_APP_BLOCKED_OR_DELETED: { code: 31008, msg: 'AppKey is banned or deleted' }, CONN_USER_BLOCKED: { code: 31009, msg: 'User blocked' }, CONN_DOMAIN_INCORRECT: { code: 31012, msg: 'Connect domain error, Please check the set security domain' }, ROAMING_SERVICE_UNAVAILABLE: { code: 33007, msg: 'Roaming service cloud is not open, Please go to the developer to open this service' }, RC_CONNECTION_EXIST: { code: 34001, msg: 'Connection already exists' }, CHATROOM_KV_EXCEED: { code: 23423, msg: 'ChatRoom KV setting exceeds maximum' }, CHATROOM_KV_OVERWRITE_INVALID: { code: 23424, msg: 'ChatRoom KV already exists' }, CHATROOM_KV_STORE_NOT_OPEN: { code: 23426, msg: 'ChatRoom KV storage service is not open, Please go to the developer to open this service' }, CHATROOM_KEY_NOT_EXIST: { code: 23427, msg: 'ChatRoom key does not exist' } }; var ERROR_CODE = {}; var ERROR_CODE_TO_INFO = {}; for (var name$1 in ERROR_INFO) { var info = ERROR_INFO[name$1]; var code = info.code; ERROR_CODE[name$1] = code; ERROR_CODE[code] = name$1; ERROR_CODE_TO_INFO[code] = info; } var SERVER_ERROR_TO_CODE = { '1': ERROR_INFO.ROAMING_SERVICE_UNAVAILABLE.code }; var _CONNECT_SERVER_STATU, _SERVER_DISCONNECT_ST, _TRANSPORTER_STATUS_T; var NAVI_ERROR_INFO = { '401': ERROR_INFO.CONN_TOKEN_INCORRECT, '403': ERROR_INFO.CONN_APPKEY_FAKE }; var CONNECTION_STATUS = { CONNECTED: 0, CONNECTING: 1, DISCONNECTED: 2, NETWORK_UNAVAILABLE: 3, SOCKET_ERROR: 4, KICKED_OFFLINE_BY_OTHER_CLIENT: 6, BLOCKED: 12 }; var SERVER_DISCONNECT_STATUS = { KICKED_OFFLINE_BY_OTHER_CLIENT: 1, BLOCKED: 2 }; var CONNECT_SERVER_STATUS = { IDENTIFIER_REJECTED: 2, CONN_MINI_SERVICE_NOT_OPEN: 3, TOKEN_INCORRECT: 4, NOT_AUTHORIZED: 5, REDIRECT: 6, PACKAGE_ERROR: 7, APP_BLOCK_OR_DELETE: 8, BLOCK: 9, TOKEN_EXPIRE: 10, DEVICE_ERROR: 11, DOMAIN_INCORRECT: 12 }; var TRANSPORTER_STATUS = { CONNECTED: CONNECTION_STATUS.CONNECTED, KICKED_OFFLINE_BY_OTHER_CLIENT: CONNECTION_STATUS.KICKED_OFFLINE_BY_OTHER_CLIENT, BLOCKED: CONNECTION_STATUS.BLOCKED, CLOSE_NORMAL: 1000, CLOSE_GOING_AWAY: 1001, CLOSE_PROTOCOL_ERROR: 1002, CLOSE_UNSUPPORTED: 1003, CLOSE_NO_STATUS: 1005, CLOSE_ABNORMAL: 1006, UNSUPPORTED_DATA: 1007, POLICY_VIOLATION: 1008, CLOSE_TOO_LARGE: 1009, MISSING_EXTENSION: 1010, INTERNAL_ERROR: 1011, SERVICE_RESTART: 1012, TRY_AGAIN_LATER: 1013, TSL_HANDSHAKE: 1015, PING_FIRST_TIMEOUT: 2001, PING_TIMEOUT: 2002, DISCONNECT_TOO_FAST: 2003, EXCEED_MESSAGE_ID_LIMIT: 2004, COMET_REQUEST_ERROR: 2005, MINI_URL_NOT_IN_DOMAIN_LIST: 2006, CMP_CONNECTION_TIMEOUT: 2007 }; var CONNECT_SERVER_STATUS_MAP_ERROR_INFO = (_CONNECT_SERVER_STATU = {}, _CONNECT_SERVER_STATU[CONNECT_SERVER_STATUS.IDENTIFIER_REJECTED] = ERROR_INFO.CONN_APPKEY_FAKE, _CONNECT_SERVER_STATU[CONNECT_SERVER_STATUS.CONN_MINI_SERVICE_NOT_OPEN] = ERROR_INFO.CONN_MINI_SERVICE_NOT_OPEN, _CONNECT_SERVER_STATU[CONNECT_SERVER_STATUS.TOKEN_INCORRECT] = ERROR_INFO.CONN_TOKEN_INCORRECT, _CONNECT_SERVER_STATU[CONNECT_SERVER_STATUS.NOT_AUTHORIZED] = ERROR_INFO.CONN_NOT_AUTHRORIZED, _CONNECT_SERVER_STATU[CONNECT_SERVER_STATUS.REDIRECT] = ERROR_INFO.CONN_REDIRECTED, _CONNECT_SERVER_STATU[CONNECT_SERVER_STATUS.APP_BLOCK_OR_DELETE] = ERROR_INFO.CONN_APP_BLOCKED_OR_DELETED, _CONNECT_SERVER_STATU[CONNECT_SERVER_STATUS.BLOCK] = ERROR_INFO.CONN_USER_BLOCKED, _CONNECT_SERVER_STATU[CONNECT_SERVER_STATUS.TOKEN_EXPIRE] = ERROR_INFO.CONN_TOKEN_INCORRECT, _CONNECT_SERVER_STATU[CONNECT_SERVER_STATUS.DOMAIN_INCORRECT] = ERROR_INFO.CONN_DOMAIN_INCORRECT, _CONNECT_SERVER_STATU[TRANSPORTER_STATUS.CMP_CONNECTION_TIMEOUT] = ERROR_INFO.CONN_ACK_TIMEOUT, _CONNECT_SERVER_STATU); var MINI_ERROR_MSG_TO_STATUS = { 'url not in domain list': TRANSPORTER_STATUS.MINI_URL_NOT_IN_DOMAIN_LIST }; var SERVER_DISCONNECT_STATUS_TO_TRANSPORTER_STATUS = (_SERVER_DISCONNECT_ST = {}, _SERVER_DISCONNECT_ST[SERVER_DISCONNECT_STATUS.KICKED_OFFLINE_BY_OTHER_CLIENT] = TRANSPORTER_STATUS.KICKED_OFFLINE_BY_OTHER_CLIENT, _SERVER_DISCONNECT_ST[SERVER_DISCONNECT_STATUS.BLOCKED] = TRANSPORTER_STATUS.BLOCKED, _SERVER_DISCONNECT_ST); var TRANSPORTER_STATUS_NEED_UPDATE_CMP = [TRANSPORTER_STATUS.CLOSE_NORMAL, TRANSPORTER_STATUS.CLOSE_GOING_AWAY, TRANSPORTER_STATUS.CLOSE_PROTOCOL_ERROR, TRANSPORTER_STATUS.CLOSE_UNSUPPORTED, TRANSPORTER_STATUS.UNSUPPORTED_DATA, TRANSPORTER_STATUS.POLICY_VIOLATION, TRANSPORTER_STATUS.MISSING_EXTENSION, TRANSPORTER_STATUS.INTERNAL_ERROR, TRANSPORTER_STATUS.SERVICE_RESTART, TRANSPORTER_STATUS.TRY_AGAIN_LATER, TRANSPORTER_STATUS.TSL_HANDSHAKE, TRANSPORTER_STATUS.PING_FIRST_TIMEOUT, TRANSPORTER_STATUS.DISCONNECT_TOO_FAST, TRANSPORTER_STATUS.COMET_REQUEST_ERROR]; var TRANSPORTER_STATUS_NEED_RECONNECT = TRANSPORTER_STATUS_NEED_UPDATE_CMP.concat([TRANSPORTER_STATUS.PING_TIMEOUT, TRANSPORTER_STATUS.CLOSE_ABNORMAL, TRANSPORTER_STATUS.EXCEED_MESSAGE_ID_LIMIT, TRANSPORTER_STATUS.COMET_REQUEST_ERROR]); var TRANSPORTER_STATUS_TO_CONNECTION_STATUS = (_TRANSPORTER_STATUS_T = {}, _TRANSPORTER_STATUS_T[TRANSPORTER_STATUS.CLOSE_GOING_AWAY] = CONNECTION_STATUS.SOCKET_ERROR, _TRANSPORTER_STATUS_T[TRANSPORTER_STATUS.CLOSE_PROTOCOL_ERROR] = CONNECTION_STATUS.SOCKET_ERROR, _TRANSPORTER_STATUS_T[TRANSPORTER_STATUS.CLOSE_UNSUPPORTED] = CONNECTION_STATUS.SOCKET_ERROR, _TRANSPORTER_STATUS_T[TRANSPORTER_STATUS.CLOSE_NO_STATUS] = CONNECTION_STATUS.DISCONNECTED, _TRANSPORTER_STATUS_T[TRANSPORTER_STATUS.CLOSE_ABNORMAL] = CONNECTION_STATUS.NETWORK_UNAVAILABLE, _TRANSPORTER_STATUS_T[TRANSPORTER_STATUS.DISCONNECT_TOO_FAST] = CONNECTION_STATUS.NETWORK_UNAVAILABLE, _TRANSPORTER_STATUS_T[TRANSPORTER_STATUS.UNSUPPORTED_DATA] = CONNECTION_STATUS.SOCKET_ERROR, _TRANSPORTER_STATUS_T[TRANSPORTER_STATUS.POLICY_VIOLATION] = CONNECTION_STATUS.SOCKET_ERROR, _TRANSPORTER_STATUS_T[TRANSPORTER_STATUS.CLOSE_TOO_LARGE] = CONNECTION_STATUS.SOCKET_ERROR, _TRANSPORTER_STATUS_T[TRANSPORTER_STATUS.MISSING_EXTENSION] = CONNECTION_STATUS.SOCKET_ERROR, _TRANSPORTER_STATUS_T[TRANSPORTER_STATUS.INTERNAL_ERROR] = CONNECTION_STATUS.SOCKET_ERROR, _TRANSPORTER_STATUS_T[TRANSPORTER_STATUS.SERVICE_RESTART] = CONNECTION_STATUS.SOCKET_ERROR, _TRANSPORTER_STATUS_T[TRANSPORTER_STATUS.TRY_AGAIN_LATER] = CONNECTION_STATUS.SOCKET_ERROR, _TRANSPORTER_STATUS_T[TRANSPORTER_STATUS.TSL_HANDSHAKE] = CONNECTION_STATUS.SOCKET_ERROR, _TRANSPORTER_STATUS_T[TRANSPORTER_STATUS.PING_FIRST_TIMEOUT] = CONNECTION_STATUS.NETWORK_UNAVAILABLE, _TRANSPORTER_STATUS_T[TRANSPORTER_STATUS.PING_TIMEOUT] = CONNECTION_STATUS.NETWORK_UNAVAILABLE, _TRANSPORTER_STATUS_T[TRANSPORTER_STATUS.COMET_REQUEST_ERROR] = CONNECTION_STATUS.NETWORK_UNAVAILABLE, _TRANSPORTER_STATUS_T); var CONNECT_TYPE = { COMET: 'comet', WEBSOCKET: 'websocket' }; var CONVERSATION_TYPE = { PRIVATE: 1, GROUP: 3, CHATROOM: 4, CUSTOMER_SERVICE: 5, SYSTEM: 6, RTC_ROOM: 12 }; var MESSAGE_DIRECTION = { SEND: 1, RECEIVE: 2 }; var MESSAGS_TIME_ORDER = { DESC: 0, ASC: 1 }; var CHATROOM_ORDER = { ASC: 1, DESC: 2 }; var RECALL_MESSAGE_TYPE = 'RC:RcCmd'; var MENTIOND_TYPE = { ALL: 1, SINGAL: 2 }; var MESSAGE_TYPE = { TEXT: 'RC:TxtMsg', VOICE: 'RC:VcMsg', HQ_VOICE: 'RC:HQVCMsg', IMAGE: 'RC:ImgMsg', GIF: 'RC:GIFMsg', RICH_CONTENT: 'RC:ImgTextMsg', LOCATION: 'RC:LBSMsg', FILE: 'RC:FileMsg', SIGHT: 'RC:SightMsg', COMBINE: 'RC:CombineMsg', CHRM_KV_NOTIFY: 'RC:chrmKVNotiMsg', LOG_COMMAND: 'RC:LogCmdMsg' }; var RTC_API_TYPE = { ROOM: 1, PERSON: 2 }; var FILE_TYPE = { IMAGE: 1, AUDIO: 2, VIDEO: 3, FILE: 4 }; var CHATROOM_ENTRY_TYPE = { UPDATE: 1, DELETE: 2 }; var NOTIFICATION_STATUS = { DO_NOT_DISTURB: 1, NOTIFY: 2 }; var RECEIVED_STATUS = { READ: 0x1, LISTENED: 0x2, DOWNLOADED: 0x4, RETRIEVED: 0x8, UNREAD: 0 }; var product = { CONNECT_TYPE: CONNECT_TYPE, CONNECTION_STATUS: CONNECTION_STATUS, CONVERSATION_TYPE: CONVERSATION_TYPE, MESSAGE_DIRECTION: MESSAGE_DIRECTION, MESSAGS_TIME_ORDER: MESSAGS_TIME_ORDER, CHATROOM_ORDER: CHATROOM_ORDER, RECALL_MESSAGE_TYPE: RECALL_MESSAGE_TYPE, MESSAGE_TYPE: MESSAGE_TYPE, MENTIOND_TYPE: MENTIOND_TYPE, SDK_VERSION: SDK_VERSION, FILE_TYPE: FILE_TYPE, CHATROOM_ENTRY_TYPE: CHATROOM_ENTRY_TYPE, NOTIFICATION_STATUS: NOTIFICATION_STATUS, RECEIVED_STATUS: RECEIVED_STATUS }; var IM_TIMEOUT = 30000; var IM_PING_INTERVAL_TIME = 30000; var IM_COMET_PULLMSG_TIMEOUT = 45000; var IM_PING_MAX_TIMEOUT = 6000; var IM_PING_MIN_TIMEOUT = 2000; var PULL_MSG_TIME = 180000; var NAVI_EXPIRED_TIME = 7200000; var CMP_SNIFF_INTERNAL_TIME = 1000; var CMP_CONNECT_TIMEOUT_TIME = 10000; var FIRST_PING_TIMEOUT = 1000; var NAVI_REQUEST_SUCCESS_CODE = 200; var NAVI_SEPARATOR_IN_TOKEN = '@'; var NAVI_REQUEST_TIMEOUT = 10000; var DOMAIN_SEPARATOR_IN_NAVLIST = ';'; var DOMAIN_SEPARATOR_IN_CMPLIST = ','; var MAX_SINGAL_ID = 65535; var MINIMUM_CONNECT_DURATION = 5000; var CHATROOM_KEY_LENGTH = { MAX: 128, MIN: 1 }; var CHATROOM_VALUE_LENGTH = { MAX: 4096, MIN: 1 }; var TYPE_HAS_CONVERSATION = [CONVERSATION_TYPE.PRIVATE, CONVERSATION_TYPE.GROUP, CONVERSATION_TYPE.SYSTEM]; var PLATFORM = { WEB: 'web', WX: 'wx', ZFB: 'zfb', TT: 'tt', BAIDU: 'baidu', QUICK_APP: 'quick_app', UNI: 'uni' }; var REQUEST_METHOD = { POST: 'post', GET: 'get' }; var STORAGE_ROOT_KEY = 'rc-'; var STORAGE_DEVICE_ID_KEY = STORAGE_ROOT_KEY + 'deviceId'; var STORAGE_SESSION_ID_KEY = STORAGE_ROOT_KEY + 'sessionId'; var STORAGE_NAVI = { ROOT_KEY_TPL: 'nav-{appkey}-{UID}', SUB_KEY: { CONNECT_TYPE: 'connettype', TIME_WHEN_SAVED: 'time', RESPONSE: 'resp' } }; var STORAGE_SYNC_TIME = { ROOT_KEY_TPL: 'sync-{appkey}-{userId}', SUB_KEY: { SENDBOX: 'send', INBOX: 'in' } }; var SESSION_SYNC_TIME = { ROOT_KEY_TPL: 'sync-{appkey}-{userId}', SUB_KEY: { TIME: 't' } }; var STORAGE_CONVERSATION = { ROOT_KEY_TPL: 'con-{appkey}-{userId}', SUB_KEY: { ROOT_TPL: '{type}-{id}', UNREAD_COUNT: 'c', UNREAD_LAST_TIME: 't', HAS_MENTIOND: 'hm', MENTIOND_INFO: 'm', NOTIFICATION: 'no', TOP: 'to' } }; var STORAGE_CONVERSATION_STATUS = { ROOT_KEY_TPL: 'con-s-{appkey}-{userId}', SUB_KEY: { TIME: 't' } }; var STORAGE_USER_SETTING = { ROOT_KEY_TPL: 'sett-{appkey}-{userId}', SUB_KEY: { VERSION: 'v', SETTINGS: 's' } }; var HTTP_PROTOCOL = { HTTP: 'http:', HTTPS: 'https:', FILE: 'file:' }; var WS_PROTOCOL = { WSS: 'wss:', WS: 'ws:' }; var NAVI_CALLBACK_NAME = 'getServerEndpoint'; var NAVI_TYPE = { COMET: 'cometnavi', WEBSOCKET: 'navi' }; var NAVI_URL_TPL = '{url}/{type}.js?appId={appkey}&token={token}&callBack=' + NAVI_CALLBACK_NAME + '&r={random}&v=' + SDK_VERSION; var CMP_URL_TPL = '{protocol}//{domain}/websocket?appId={appkey}&token={token}&apiVer={apiVer}&sdkVer=' + SDK_VERSION; var MINI_CMP_URL_TPL = '{protocol}//{domain}/websocket?appId={appkey}&token={token}&apiVer={apiVer}&sdkVer=' + SDK_VERSION + '&platform={platform}'; var COMET_REQ_HAS_TOPIC_URL_TPL = '{protocol}//{domain}/websocket?messageid={messageId}&header={headerCode}&sessionid={sessionId}&topic={topic}&targetid={targetId}&pid={pid}'; var COMET_REQ_NO_TOPIC_URL_TPL = '{protocol}//{domain}/websocket?messageid={messageId}&header={headerCode}&sessionid={sessionId}&pid={pid}'; var COMET_PULL_URL_TPL = '{protocol}//{domain}/pullmsg.js?sessionid={sessionId}×trap={timestamp}&pid={pid}'; var TIMER_TYPE = { INTERVAL: 'interval', TIMEOUT: 'timeout' }; var TIMER_STATUS = { PENNDING: 'pendding', BUSY: 'busy', ENDING: 'ending' }; var PLATFORM_TYPE = { MINI: 'MiniProgram', WEB: 'Web' }; var SESSION_SYNC_CHATROOM = { ROOT_KEY_TPL: 'sync-chrm-{appkey}-{userId}' }; var UnKown = 'UnKown'; var hasMiniBaseEvent = function hasMiniBaseEvent(miniGlobal) { var baseMiniEventNames = ['canIUse', 'getSystemInfo']; for (var i = 0, max = baseMiniEventNames.length; i < max; i++) { var baseEventName = baseMiniEventNames[i]; if (!miniGlobal[baseEventName]) { return false; } } return true; }; var isFromUniappEnv = function isFromUniappEnv() { if (typeof uni !== 'undefined' && hasMiniBaseEvent(uni)) { return true; } return false; }; var isFromUniapp = isFromUniappEnv(); var isAppPlus = false; var isMiniEnv = function isMiniEnv(global) { if (isAppPlus) { return false; } return global !== window; }; var getEnvInfo = function getEnvInfo() { if (typeof swan !== 'undefined' && hasMiniBaseEvent(swan)) { return { platform: PLATFORM.BAIDU, global: swan }; } else if (typeof tt !== 'undefined' && hasMiniBaseEvent(tt)) { return { platform: PLATFORM.TT, global: tt }; } else if (typeof my !== 'undefined' && hasMiniBaseEvent(my)) { return { platform: PLATFORM.ZFB, global: my }; } else if (typeof wx !== 'undefined' && hasMiniBaseEvent(wx)) { return { platform: PLATFORM.WX, global: wx }; } else { return { platform: PLATFORM.WEB, global: window }; } }; var getFromUniEnvInfo = function getFromUniEnvInfo() { var uniPlatform = process.env.VUE_APP_PLATFORM; switch (uniPlatform) { case 'app-plus': isAppPlus = true; return { platform: PLATFORM.UNI, global: uni }; case 'mp-baidu': return { platform: PLATFORM.BAIDU, global: swan }; case 'mp-toutiao': return { platform: PLATFORM.TT, global: tt }; case 'mp-alipay': return { platform: PLATFORM.ZFB, global: my }; case 'mp-weixin': return { platform: PLATFORM.WX, global: wx }; case 'h5': return { platform: PLATFORM.WEB, global: window }; default: return { platform: 'not included platform', global: window }; } }; var getWebSystemInfo = function getWebSystemInfo() { var userAgent = navigator.userAgent; var version, type; var condition = { IE: /rv:([\d.]+)\) like Gecko|MSIE ([\d.]+)/, Edge: /Edge\/([\d.]+)/, Firefox: /Firefox\/([\d.]+)/, Opera: /(?:OPERA|OPR).([\d.]+)/, WeiXin: /MicroMessenger\/([\d.]+)/, QQBrowser: /QQBrowser\/([\d.]+)/, Chrome: /Chrome\/([\d.]+)/, Safari: /Version\/([\d.]+).*Safari/ }; for (var key in condition) { if (!condition.hasOwnProperty(key)) continue; var browserContent = userAgent.match(condition[key]); if (browserContent) { type = key; version = browserContent[1] || browserContent[2]; break; } } return { model: type || UnKown, version: version || UnKown }; }; var getMiniSystemInfo = function getMiniSystemInfo(global) { var systemInfo = global.getSystemInfoSync() || {}; var model = systemInfo.model, brand = systemInfo.brand; if (model && brand) { model = model + ' ' + brand; } systemInfo.model = model; return systemInfo; }; var getProtocol = function getProtocol(global) { var location = global.location || {}; var isHttp = location.protocol === HTTP_PROTOCOL.HTTP || location.protocol === HTTP_PROTOCOL.FILE; var protocol = { http: isHttp ? HTTP_PROTOCOL.HTTP : HTTP_PROTOCOL.HTTPS, ws: WS_PROTOCOL.WSS }; if (isHttp) { protocol.ws = WS_PROTOCOL.WS; } return protocol; }; var adaptGlobalObjectCreate = function adaptGlobalObjectCreate(global, isMini) { if (!isMini && !isAppPlus && !global.Object.create) { global.Object.create = function (o, properties) { if (typeof o !== 'object' && typeof o !== 'function') throw new TypeError('Object prototype may only be an Object: ' + o);else if (o === null) throw new Error('This browser\'s implementation of Object.create is a shim and doesn\'t support \'null\' as the first argument.'); if (typeof properties !== 'undefined') throw new Error('This browser\'s implementation of Object.create is a shim and doesn\'t support a second argument.'); function F() {} F.prototype = o; return new F(); }; } }; var getMiniGlobal = function getMiniGlobal(global) { return Object.assign(global, { JSON: JSON, Promise: Promise, setTimeout: setTimeout, setInterval: setInterval, encodeURIComponent: encodeURIComponent, clearTimeout: function (_clearTimeout) { function clearTimeout(_x) { return _clearTimeout.apply(this, arguments); } clearTimeout.toString = function () { return _clearTimeout.toString(); }; return clearTimeout; }(function (id) { clearTimeout(id); }), clearInterval: function (_clearInterval) { function clearInterval(_x2) { return _clearInterval.apply(this, arguments); } clearInterval.toString = function () { return _clearInterval.toString(); }; return clearInterval; }(function (id) { clearInterval(id); }) }); }; var envInfo = isFromUniapp ? getFromUniEnvInfo() : getEnvInfo(); var platform = envInfo.platform, global$1 = envInfo.global; var isMini = isMiniEnv(global$1); var protocol = getProtocol(global$1); var system = isMini || isAppPlus ? getMiniSystemInfo(global$1) : getWebSystemInfo(); system.name = platform; adaptGlobalObjectCreate(global$1, isMini); global$1 = isMini || isAppPlus ? getMiniGlobal(global$1) : global$1; var env = { global: global$1, system: system, isMini: isMini, protocol: protocol, isAppPlus: isAppPlus, isFromUniapp: isFromUniapp }; var global$2 = env.global, system$1 = env.system; var isZFB = system$1.name === PLATFORM.ZFB; var ZFBStorage = function () { function ZFBStorage() {} var _proto = ZFBStorage.prototype; _proto.set = function set(key, value) { global$2.setStorageSync({ key: key, data: value }); }; _proto.get = function get(key) { return global$2.getStorageSync({ key: key }); }; _proto.remove = function remove(key) { return global$2.removeStorageSync({ key: key }); }; _proto.getKeys = function getKeys() { var res = my.getStorageInfoSync(); return res.keys; }; return ZFBStorage; }(); var MiniStorage = function () { function MiniStorage() {} var _proto2 = MiniStorage.prototype; _proto2.set = function set(key, value) { global$2.setStorageSync(key, value); }; _proto2.get = function get(key) { try { return global$2.getStorageSync(key); } catch (e) { return null; } }; _proto2.remove = function remove(key) { try { return global$2.removeStorageSync(key); } catch (e) { return null; } }; _proto2.getKeys = function getKeys() { try { var res = global$2.getStorageInfoSync(); return res.keys; } catch (e) { return []; } }; return MiniStorage; }(); var storage = isZFB ? ZFBStorage : MiniStorage; var JSON$1 = { parse: function parse(sJSON) { return new Function('', 'return (' + sJSON + ')')(); }, stringify: function stringify(value) { return JSON$1.str('', { '': value }); }, str: function str(key, holder) { var i, k, v, length, partial, value = holder[key], self = JSON$1; if (value && typeof value === 'object' && typeof value.toJSON === 'function') { value = value.toJSON(key); } switch (typeof value) { case 'string': return self.quote(value); case 'number': return isFinite(value) ? String(value) : 'null'; case 'boolean': return String(value); case 'object': if (!value) { return 'null'; } partial = []; if (Object.prototype.toString.apply(value) === '[object Array]') { length = value.length; for (i = 0; i < length; i += 1) { partial[i] = self.str(i, value) || 'null'; } v = partial.length === 0 ? '[]' : '[' + partial.join(',') + ']'; return v; } for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = self.str(k, value); if (v) { partial.push(self.quote(k) + ':' + v); } } } v = partial.length === 0 ? '{}' : '{' + partial.join(',') + '}'; return v; } }, quote: function quote(string) { var self = JSON$1; self.rx_escapable.lastIndex = 0; return self.rx_escapable.test(string) ? '"' + string.replace(self.rx_escapable, function (a) { var c = self.meta[a]; return typeof c === 'string' ? c : "\\u" + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }) + '"' : '"' + string + '"'; }, rx_escapable: new RegExp("[\\\"\\\\\"\0-\x1F\x7F-\x9F\xAD\u0600-\u0604\u070F\u17B4\u17B5\u200C-\u200F\u2028-\u202F\u2060-\u206F\uFEFF\uFFF0-\uFFFF]", 'g'), meta: { '\b': '\\b', ' ': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"': '\\"', '\'\'': '\\\'\'', '\\': '\\\\' } }; var CacheStorage = function () { function CacheStorage(values) { this.caches = {}; if (values) { this.caches = values; } } var _proto = CacheStorage.prototype; _proto.set = function set(key, value) { this.caches[key] = value; }; _proto.remove = function remove(key) { var val = this.get(key); delete this.caches[key]; return val; }; _proto.get = function get(key) { return this.caches[key]; }; _proto.getKeys = function getKeys() { var keys = []; for (var key in this.caches) { keys.push(key); } return keys; }; return CacheStorage; }(); var global$3 = env.global; var TEST_KEY = 'RC_TEST_KEY'; var TEST_VALUE = 'RC_TEST_VALUE'; var isSupportLocalStorage = function isSupportLocalStorage() { var isSupport = false; var localStorage = global$3.localStorage; if (localStorage) { try { localStorage.setItem(TEST_KEY, TEST_VALUE); var testVal = localStorage.getItem(TEST_KEY); if (testVal === TEST_VALUE) { isSupport = true; } localStorage.removeItem(TEST_KEY); } catch (e) {} } return isSupport; }; var WebStorage = function () { function WebStorage() {} var _proto = WebStorage.prototype; _proto.set = function set(key, value) { global$3.localStorage.setItem(key, JSON$1.stringify({ d: value })); }; _proto.get = function get(key) { var value; var localValue = global$3.localStorage.getItem(key); try { localValue = JSON$1.parse(localValue); } catch (e) { localValue = {}; } if (localValue && localValue.d) { value = localValue.d; } return value; }; _proto.remove = function remove(key) { return global$3.localStorage.removeItem(key); }; _proto.getKeys = function getKeys() { var keyList = []; for (var key in global$3.localStorage) { keyList.push(key); } return keyList; }; return WebStorage; }(); var WebStorage$1 = isSupportLocalStorage() ? WebStorage : CacheStorage; var isMini$1 = env.isMini, isAppPlus$1 = env.isAppPlus; var Storage = isMini$1 || isAppPlus$1 ? storage : WebStorage$1, storage$1 = new Storage(); var global$4 = env.global; var TEST_KEY$1 = 'RC_TEST_KEY'; var TEST_VALUE$1 = 'RC_TEST_VALUE'; var isSupportSessionStorage = function isSupportSessionStorage() { var isSupport = false; var sessionStorage = global$4.sessionStorage; if (sessionStorage) { try { sessionStorage.setItem(TEST_KEY$1, TEST_VALUE$1); var testVal = sessionStorage.getItem(TEST_KEY$1); if (testVal === TEST_VALUE$1) { isSupport = true; } sessionStorage.removeItem(TEST_KEY$1); } catch (e) {} } return isSupport; }; var WebSession = function () { function WebSession() {} var _proto = WebSession.prototype; _proto.set = function set(key, value) { global$4.sessionStorage.setItem(key, JSON$1.stringify({ d: value })); }; _proto.get = function get(key) { var value; var localValue = global$4.sessionStorage.getItem(key); try { localValue = JSON$1.parse(localValue); } catch (e) { localValue = {}; } if (localValue && localValue.d) { value = localValue.d; } return value; }; _proto.remove = function remove(key) { return global$4.sessionStorage.removeItem(key); }; _proto.getKeys = function getKeys() { var keyList = []; for (var key in global$4.sessionStorage) { keyList.push(key); } return keyList; }; return WebSession; }(); var WebSession$1 = isSupportSessionStorage() ? WebSession : CacheStorage; var isMini$2 = env.isMini, isAppPlus$2 = env.isAppPlus; var Session = isMini$2 || isAppPlus$2 ? CacheStorage : WebSession$1, session = new Session(); var global$5 = env.global, isAppPlus$3 = env.isAppPlus; var Socket = function () { function Socket(options) { this.socket = void 0; if (isAppPlus$3) { options['complete'] = function () {}; } this.socket = global$5.connectSocket(options); } var _proto = Socket.prototype; _proto.send = function send(data) { this.socket.send({ data: data }); }; _proto.close = function close() { this.socket.close(); }; _proto.onOpen = function onOpen(callback) { this.socket.onOpen(callback); }; _proto.onMessage = function onMessage(callback) { this.socket.onMessage(callback); }; _proto.onError = function onError(callback) { this.socket.onError(callback); }; _proto.onClose = function onClose(callback) { this.socket.onClose(callback); }; return Socket; }(); var Socket$1 = function () { function Socket(options) { this.socket = void 0; var url = options.url; this.socket = new WebSocket(url); this.socket.binaryType = 'arraybuffer'; return this; } var _proto = Socket.prototype; _proto.send = function send(data) { return this.socket.send(data); }; _proto.close = function close() { this.socket.close(); }; _proto.onOpen = function onOpen(callback) { this.socket.addEventListener('open', callback); }; _proto.onMessage = function onMessage(callback) { this.socket.addEventListener('message', callback); }; _proto.onError = function onError(callback) { this.socket.addEventListener('error', callback); }; _proto.onClose = function onClose(callback) { this.socket.addEventListener('close', callback); }; return Socket; }(); var isMini$3 = env.isMini, isAppPlus$4 = env.isAppPlus; var Socket$2 = isMini$3 || isAppPlus$4 ? Socket : Socket$1; /*! 基于 es6-promise * Github: https://github.com/stefanpenner/es6-promise * @overview es6-promise - a tiny implementation of Promises/A+. * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald) * @license Licensed under MIT license * See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE * @version v4.2.8+1e68dce6 */ var SparePromise = (function(){function a(a){var b=typeof a;return null!==a&&("object"===b||"function"===b)}function b(a){return "function"==typeof a}function c(a){P=a;}function d(a){Q=a;}function e(){return function(){return process.nextTick(j)}}function f(){return "undefined"!=typeof O?function(){O(j);}:i()}function g(){var a=0,b=new T(j),c=document.createTextNode("");return b.observe(c,{characterData:!0}),function(){c.data=a=++a%2;}}function h(){var a=new MessageChannel;return a.port1.onmessage=j,function(){return a.port2.postMessage(0)}}function i(){var a=setTimeout;return function(){return a(j,1)}}function j(){var a,b,c;for(a=0;N>a;a+=2)b=W[a],c=W[a+1],b(c),W[a]=void 0,W[a+1]=void 0;N=0;}function k(){try{var a=Function("return this")().require("vertx");return O=a.runOnLoop||a.runOnContext,f()}catch(b){return i()}}function l(a,b){var e,f,c=this,d=new this.constructor(n);return void 0===d[Y]&&D(d),e=c._state,e?(f=arguments[e-1],Q(function(){return A(e,d,f,c._result)})):y(c,d,a,b),d}function m(a){var c,b=this;return a&&"object"==typeof a&&a.constructor===b?a:(c=new b(n),u(c,a),c)}function n(){}function o(){return new TypeError("You cannot resolve a promise with itself")}function p(){return new TypeError("A promises callback cannot return that same promise.")}function q(a,b,c,d){try{a.call(b,c,d);}catch(e){return e}}function r(a,b,c){Q(function(a){var d=!1,e=q(c,b,function(c){d||(d=!0,b!==c?u(a,c):w(a,c));},function(b){d||(d=!0,x(a,b));},"Settle: "+(a._label||" unknown promise"));!d&&e&&(d=!0,x(a,e));},a);}function s(a,b){b._state===$?w(a,b._result):b._state===_?x(a,b._result):y(b,void 0,function(b){return u(a,b)},function(b){return x(a,b)});}function t(a,c,d){c.constructor===a.constructor&&d===l&&c.constructor.resolve===m?s(a,c):void 0===d?w(a,c):b(d)?r(a,c,d):w(a,c);}function u(b,c){if(b===c)x(b,o());else if(a(c)){var d=void 0;try{d=c.then;}catch(e){return void x(b,e)}t(b,c,d);}else w(b,c);}function v(a){a._onerror&&a._onerror(a._result),z(a);}function w(a,b){a._state===Z&&(a._result=b,a._state=$,0!==a._subscribers.length&&Q(z,a));}function x(a,b){a._state===Z&&(a._state=_,a._result=b,Q(v,a));}function y(a,b,c,d){var e=a._subscribers,f=e.length;a._onerror=null,e[f]=b,e[f+$]=c,e[f+_]=d,0===f&&a._state&&Q(z,a);}function z(a){var d,e,f,g,b=a._subscribers,c=a._state;if(0!==b.length){for(d=void 0,e=void 0,f=a._result,g=0;gf;f++)b.resolve(a[f]).then(c,d);}:function(a,b){return b(new TypeError("You must pass an array to race."))})}function H(a){var b=this,c=new b(n);return x(c,a),c}function I(){throw new TypeError("You must pass a resolver function as the first argument to the promise constructor")}function J(){throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.")}function K(){var c,d,a=void 0;if("undefined"!=typeof global)a=global;else if("undefined"!=typeof self)a=self;else try{a=Function("return this")();}catch(b){throw new Error("polyfill failed because global object is unavailable in this environment")}if(c=a.Promise){d=null;try{d=Object.prototype.toString.call(c.resolve());}catch(b){}if("[object Promise]"===d&&!c.cast)return}a.Promise=cb;}var M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,$,_,ab,bb,cb,L=void 0;return L=Array.isArray?Array.isArray:function(a){return "[object Array]"===Object.prototype.toString.call(a)},M=L,N=0,O=void 0,P=void 0,Q=function(a,b){W[N]=a,W[N+1]=b,N+=2,2===N&&(P?P(j):X());},R="undefined"!=typeof window?window:void 0,S=R||{},T=S.MutationObserver||S.WebKitMutationObserver,U="undefined"==typeof self&&"undefined"!=typeof process&&"[object process]"==={}.toString.call(process),V="undefined"!=typeof Uint8ClampedArray&&"undefined"!=typeof importScripts&&"undefined"!=typeof MessageChannel,W=new Array(1e3),X=void 0,X=U?e():T?g():V?h():void 0===R&&"function"==typeof require?k():i(),Y=Math.random().toString(36).substring(2),Z=void 0,$=1,_=2,ab=0,bb=function(){function a(a,b){this._instanceConstructor=a,this.promise=new a(n),this.promise[Y]||D(this.promise),M(b)?(this.length=b.length,this._remaining=b.length,this._result=new Array(this.length),0===this.length?w(this.promise,this._result):(this.length=this.length||0,this._enumerate(b),0===this._remaining&&w(this.promise,this._result))):x(this.promise,E());}return a.prototype._enumerate=function(a){for(var b=0;this._state===Z&&b>16)+(b>>16)+(c>>16);return d<<16|65535&c}function b(a,b){return a<>>32-b}function c(c,d,e,f,g,h){return a(b(a(a(d,c),a(f,h)),g),e)}function d(a,b,d,e,f,g,h){return c(b&d|~b&e,a,b,f,g,h)}function e(a,b,d,e,f,g,h){return c(b&e|d&~e,a,b,f,g,h)}function f(a,b,d,e,f,g,h){return c(b^d^e,a,b,f,g,h)}function g(a,b,d,e,f,g,h){return c(d^(b|~e),a,b,f,g,h)}function h(b,c){var h,i,j,k,l,m,n,o,p;for(b[c>>5]|=128<>>9<<4)+14]=c,m=1732584193,n=-271733879,o=-1732584194,p=271733878,h=0;hb;b+=8)c+=String.fromCharCode(255&a[b>>5]>>>b%32);return c}function j(a){var b,d,c=[];for(c[(a.length>>2)-1]=void 0,b=0;bb;b+=8)c[b>>5]|=(255&a.charCodeAt(b/8))<16&&(d=h(d,8*a.length)),c=0;16>c;c+=1)e[c]=909522486^d[c],f[c]=1549556828^d[c];return g=h(e.concat(j(b)),512+8*b.length),i(h(f.concat(g),640))}function m(a){var d,e,b="0123456789abcdef",c="";for(e=0;e>>4)+b.charAt(15&d);return c}function n(a){return unescape(encodeURIComponent(a))}function o(a){return k(n(a))}function p(a){return m(o(a))}function q(a,b){return l(n(a),n(b))}function r(a,b){return m(q(a,b))}function s(a,b,c){return b?c?q(b,a):r(b,a):c?o(a):p(a)}return s})(); var global$8 = env.global; var Promise$1 = global$8.Promise; var isSupportPromise = function isSupportPromise() { if (!global$8.Promise) return false; var defer = function () { return global$8.Promise.resolve(); }(); return defer.then && defer["catch"] && defer["finally"]; }; var setTimeout$1 = function setTimeout(event, timeout) { return global$8.setTimeout(event, timeout); }; var clearTimeout$1 = function clearTimeout(id) { return global$8.clearTimeout(id); }; var setInterval$1 = function setInterval(event, timeout) { return global$8.setInterval(event, timeout); }; var clearInterval$1 = function clearInterval(id) { return global$8.clearInterval(id); }; var Defer = isSupportPromise() ? global$8.Promise : SparePromise; var noop = function noop(data) { return data; }; var deferNoop = function deferNoop(data) { return Promise$1.resolve(data); }; var JSON$2 = global$8.JSON || JSON$1; var allowError = function allowError(event) { var result; try { for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } result = event.apply(void 0, args); } catch (e) { result = null; } return result; }; var toJSON = function toJSON(val) { return allowError(JSON$2.stringify, val); }; var parseJSON = function parseJSON(val) { return allowError(JSON$2.parse, val); }; var copy = function copy(val) { return parseJSON(toJSON(val)); }; var isObject = function isObject(val) { return Object.prototype.toString.call(val) === '[object Object]'; }; var isArray = function isArray(val) { return Object.prototype.toString.call(val).indexOf('Array') !== -1; }; var isFunction = function isFunction(val) { return Object.prototype.toString.call(val) === '[object Function]'; }; var isString = function isString(val) { return Object.prototype.toString.call(val) === '[object String]'; }; var isBoolean = function isBoolean(val) { return Object.prototype.toString.call(val) === '[object Boolean]'; }; var isUndefined = function isUndefined(val) { return val === undefined || Object.prototype.toString.call(val) === '[object Undefined]'; }; var isNull = function isNull(val) { return Object.prototype.toString.call(val) === '[object Null]'; }; var isNumber = function isNumber(val) { return Object.prototype.toString.call(val) === '[object Number]'; }; var isArrayBuffer = function isArrayBuffer(val) { return Object.prototype.toString.call(val) === '[object ArrayBuffer]'; }; var isPromise = function isPromise(val) { var isTrue = false; try { isTrue = Object.prototype.toString.call(val) === '[object Promise]' || val && val.then && val["catch"] && val["finally"]; } catch (e) { isTrue = false; } return isTrue; }; var getTypeName = function getTypeName(data) { var typeName = Object.prototype.toString.call(data); return typeName.substring(8, typeName.length - 1); }; var isEqual = function isEqual(source, target) { return source === target; }; var ArrayBufferToArray = function ArrayBufferToArray(data) { if (isArrayBuffer(data)) { return [].slice.call(new Int8Array(data)); } return data; }; var ArrayBufferToUint8Array = function ArrayBufferToUint8Array(data) { if (isArrayBuffer(data)) { return new Uint8Array(data); } return data; }; var forEach = function forEach(source, event, options) { options = options || {}; event = event || noop; var _options = options, isReverse = _options.isReverse; var loopObj = function loopObj() { for (var key in source) { event(source[key], key, source); } }; var loopArr = function loopArr() { if (isReverse) { for (var i = source.length - 1; i >= 0; i--) { event(source[i], i); } } else { for (var j = 0, len = source.length; j < len; j++) { event(source[j], j); } } }; if (isObject(source)) { loopObj(); } if (isArray(source) || isString(source)) { loopArr(); } }; var isFalse = function isFalse(val) { return val === false; }; var isEmpty = function isEmpty(val) { var result = true; if (isObject(val)) { forEach(val, function () { result = false; }); } if (isString(val) || isArray(val)) { result = val.length === 0; } if (isNumber(val)) { result = val === 0; } return result; }; var isNumberData = function isNumberData(val) { var isEmptyVal = isEmpty(val); val = Number(val); return isNumber(val) && !isEmptyVal; }; var getKeys = function getKeys(obj) { var keyList = []; forEach(obj, function (val, key) { keyList.push(key); }); return keyList; }; var getValues = function getValues(obj) { var valList = []; forEach(obj, function (val) { valList.push(val); }); return valList; }; var getTimestamp = function getTimestamp(time) { return new Date(time).getTime(); }; var getCurrentTimestamp = function getCurrentTimestamp() { return new Date().getTime(); }; var formatTime = function formatTime(timestamp, options) { timestamp = timestamp || getCurrentTimestamp(); options = options || {}; var temp = options.temp; var date = new Date(timestamp), formateds = {}; formateds['YY'] = date.getFullYear(); formateds['MM'] = date.getMonth() + 1; formateds['DD'] = date.getDate(); formateds['hh'] = date.getHours(); formateds['mm'] = date.getMinutes(); formateds['ss'] = date.getSeconds(); forEach(formateds, function (val, key) { formateds[key] = val >= 10 ? val : '0' + val; }); if (temp) { var formatedText = temp; forEach(formateds, function (val, key) { formatedText = formatedText.replace(key, val); }); return formatedText; } return formateds.YY + '-' + formateds.MM + '-' + formateds.DD + ' ' + formateds.hh + ':' + formateds.mm + ':' + formateds.ss; }; var isValidJSON = function isValidJSON(jsonStr) { if (isObject(jsonStr)) { return true; } var isValid = false; try { var obj = JSON$2.parse(jsonStr); var str = JSON$2.stringify(obj); isValid = str === jsonStr; } catch (e) { isValid = false; } return isValid; }; var isSupportSocket = function isSupportSocket() { var isMini = env.isMini; var isAppPlus = env.isAppPlus; if (isMini || isAppPlus) { return true; } var Socket = global$8.WebSocket; if (isUndefined(Socket)) { return false; } var hasWS = false, isIntegrity = false; try { hasWS = typeof Socket === 'object' || typeof Socket === 'function'; isIntegrity = typeof Socket.OPEN === 'number'; } catch (e) {} return hasWS && isIntegrity; }; var indexOf = function indexOf(source, searchVal) { if (source.indexOf) { return source.indexOf(searchVal); } var index = -1; forEach(source, function (sub, i) { if (searchVal === sub) { index = i; return; } }); return index; }; var lastIndexOf = function lastIndexOf(source, searchVal) { if (source.lastIndexOf) { return source.lastIndexOf(searchVal); } var index = -1; forEach(source, function (sub, i) { if (searchVal === sub) { index = i; return; } }, { isReverse: true }); return index; }; var isInclude = function isInclude(source, searchVal) { if (isObject(source)) { var arr = []; forEach(source, function (val) { arr.push(val); }); source = arr; } var index = indexOf(source, searchVal); return index !== -1; }; var substring = function substring(source, start, end) { return source.substring(start, end); }; var spliceByChild = function spliceByChild(arr, item) { forEach(arr, function (child, index) { if (isEqual(child, item)) { arr.splice(index, 1); } }, { isReverse: true }); }; var parse16To10 = function parse16To10(num) { return parseInt(num, 16); }; var isPlus = function isPlus(num) { return +num === num; }; var filter = function filter(source, event) { var newArr = []; for (var i = 0, max = source.length; i < max; i++) { var data = source[i]; if (event(data, i)) { newArr.push(data); } } return newArr; }; var map = function map(source, event) { forEach(source, function (item, index) { source[index] = event(item, index); }); return source; }; var extend = function extend(destination, sources, option) { option = option || {}; var _option2 = option, isAllowNull = _option2.isAllowNull; destination = destination || {}; sources = sources || {}; for (var key in sources) { var value = sources[key]; if (!isUndefined(value) || isAllowNull) { destination[key] = value; } } return destination; }; var extendAllowNull = function extendAllowNull(destination, sources) { return extend(destination, sources, { isAllowNull: true }); }; var extendInShallow = function extendInShallow(destination, sources) { destination = destination || {}; sources = sources || {}; destination = copy(destination); sources = copy(sources); return extend(destination, sources); }; var deferred = function deferred(callbacks) { return new Defer(callbacks); }; var deferTimeout = function deferTimeout(timeout) { return deferred(function (resolve) { var timeouter = setTimeout$1(function () { resolve(timeouter); }, timeout); }); }; var tplEngine = function tplEngine(temp, data, regexp) { var replaceAction = function replaceAction(obj) { return temp.replace(regexp || /{([^}]+)}/g, function (match, name) { if (match.charAt(0) === '\\') { return match.slice(1); } return obj[name] !== undefined ? obj[name] : '{' + name + '}'; }); }; if (!isArray(data)) { data = [data]; } var ret = []; forEach(data, function (item) { ret.push(replaceAction(item)); }); return ret.join(''); }; var getRandomNum = function getRandomNum(max, min) { min = min || 0; var range = max - min, random = Math.random(); return min + Math.round(random * range); }; var Timer = function () { function Timer(options) { this._timerId = void 0; this._timerEvent = void 0; this._timerClearEvent = void 0; this.timeout = 0; this.type = TIMER_TYPE.TIMEOUT; this.status = TIMER_STATUS.PENNDING; var self = this; extend(self, options); var type = self.type; var isTimeout = type === TIMER_TYPE.TIMEOUT; if (isTimeout) { self._timerEvent = setTimeout$1; self._timerClearEvent = clearTimeout$1; } else { self._timerEvent = setInterval$1; self._timerClearEvent = clearInterval$1; } return self; } var _proto = Timer.prototype; _proto.start = function start(event, options) { options = options || {}; var self = this, isTimeout = self.type === TIMER_TYPE.TIMEOUT; var _options2 = options, args = _options2.args, thisArg = _options2.thisArg; self.stop(); self._timerId = self._timerEvent.call(global$8, function () { isTimeout && self.stop(); if (thisArg) { event.apply(thisArg, args); } else { event(args); } }, self.timeout); self.status = TIMER_STATUS.BUSY; }; _proto.stop = function stop() { var self = this; if (self._timerId) { self._timerClearEvent.call(global$8, self._timerId); self.status = TIMER_STATUS.ENDING; } }; return Timer; }(); var DeferHandler = function () { function DeferHandler(options) { this._list = {}; this.timeout = IM_TIMEOUT; extend(this, options); } var _proto2 = DeferHandler.prototype; _proto2._isInvalid = function _isInvalid(id) { var handlers = this._list[id]; return !isArray(handlers) || isEmpty(handlers); }; _proto2._exec = function _exec(id, isError, data) { var self = this; if (self._isInvalid(id)) { return; } var handlers = self._list[id], handler = handlers[0]; isError ? handler.reject(data) : handler.resolve(data); handlers.splice(0, 1); }; _proto2.add = function add(id, defer, options) { options = options || {}; var self = this; var resolve = defer.resolve, reject = defer.reject; var timeout = options.timeout || self.timeout; if (self._isInvalid(id)) { self._list[id] = []; } var timer = new Timer({ timeout: timeout }); timer.start(function () { self.reject(id, ERROR_INFO.TIMEOUT.code); }); self._list[id].push({ resolve: resolve, reject: reject, timer: timer }); }; _proto2.resolve = function resolve(id, data) { this._exec(id, false, data); }; _proto2.reject = function reject(id, error) { this._exec(id, true, error); }; return DeferHandler; }(); var EventEmitter = function () { function EventEmitter() { this._events = void 0; this._events = {}; } var _proto3 = EventEmitter.prototype; _proto3.on = function on(name, event) { var _events = this._events[name] || []; _events.push(event); this._events[name] = _events; }; _proto3.off = function off(name, offEvent) { if (offEvent) { var _events = this._events[name] || []; spliceByChild(_events, offEvent); } else { delete this._events[name]; } }; _proto3.emit = function emit(name, data, error) { var _events = this._events[name]; forEach(_events, function (event) { isFunction(event) && event(data, error); }); }; _proto3.clear = function clear() { this._events = {}; }; return EventEmitter; }(); var decodeURI = function decodeURI(uri) { return global$8.decodeURIComponent(uri); }; var encodeURI = function encodeURI(uri) { return global$8.encodeURIComponent(uri); }; var int64ToTimestamp = function int64ToTimestamp(obj) { if (!isObject(obj) || obj.low === undefined || obj.high === undefined) { return obj; } var low = obj.low; if (low < 0) { low += 0xffffffff + 1; } low = low.toString(16); var timestamp = parseInt(obj.high.toString(16) + '00000000'.replace(new RegExp('0{' + low.length + '}$'), low), 16); return timestamp; }; var batchInt64ToTimestamp = function batchInt64ToTimestamp(data) { forEach(data, function (item, key) { if (isObject(item)) { data[key] = int64ToTimestamp(item); } }); return data; }; var Queue = function () { function Queue(defaultConfig) { this._isRunning = false; this._list = []; this._defaultConfig = void 0; this._defaultConfig = defaultConfig; } var _proto4 = Queue.prototype; _proto4.add = function add(params) { params = params || this._defaultConfig; this._list.push(params); this.run(); }; _proto4.run = function run() { var self = this; var _isRunning = self._isRunning, _list = self._list; var isFinished = isEmpty(_list); if (_isRunning || isFinished) { return; } var firstItem = _list.splice(0, 1)[0]; var event = firstItem.event, args = firstItem.args, thisArg = firstItem.thisArg; var next = function next() { self._isRunning = false; self.run(); }; if (!event) { return next(); } self._isRunning = true; event.apply(thisArg, args).then(next)["catch"](next); }; return Queue; }(); var secondsToMilliseconds = function secondsToMilliseconds(seconds) { return seconds * 1000; }; var request$2 = function request(url, options) { options = options || {}; return deferred(function (resolve, reject) { options = extend(options, { url: url, success: function success(responseText, xhr, status) { resolve({ responseText: responseText, xhr: xhr, status: status }); }, fail: function fail(result, xhr, status) { reject({ result: result, xhr: xhr, status: status }); } }); request$1(options); }); }; var requestByUrlList = function requestByUrlList(urlList, options) { if (isEmpty(urlList)) { return Defer.reject(); } var url = urlList[0]; return request$2(url, options).then(function (result) { result = result || {}; result.urlList = urlList; return result; })["catch"](function (error) { urlList.splice(0, 1); if (isEmpty(urlList)) { return Defer.reject(error); } else { return requestByUrlList(urlList, options); } }); }; var requestForFaster = function requestForFaster(urlList, option) { option = option || {}; var timeInterval = option.timeInterval || 0; var faildCount = 0, totalCount = urlList.length; var requestXhrs = []; var totalTimer = new Timer({ timeout: 15 * 1000 }); var reqCountdownTimers = []; var clearAll = function clearAll() { forEach(reqCountdownTimers, function (timer) { timer.stop(); }); forEach(requestXhrs, function (xhr) { xhr.abort(); }); reqCountdownTimers.length = 0; requestXhrs.length = 0; }; var isAllFaild = function isAllFaild() { return faildCount === totalCount; }; return deferred(function (resolve, reject) { var _success = function success(url, index) { clearAll(); resolve({ url: url, index: index }); }; var _fail = function fail() { clearAll(); reject(); }; forEach(urlList, function (url, index) { var timer = new Timer({ timeout: timeInterval * index }); timer.start(function () { var xhr; var opt = extend({ url: url, success: function success() { _success(url, index); }, fail: function fail() { faildCount++; isAllFaild() && _fail(); } }, option); xhr = request$1(opt); requestXhrs.push(xhr); }); reqCountdownTimers.push(timer); }); totalTimer.start(_fail); }); }; var NetworkDetecter = function () { function NetworkDetecter(option) { this._option = void 0; this._detectCount = 0; this._timeoutId = void 0; this._option = option; } var _proto5 = NetworkDetecter.prototype; _proto5._detect = function _detect() { var self = this; var _detectCount = self._detectCount, _option = self._option; var url = _option.url, timeout = _option.intervalTime, max = _option.max; _detectCount++; return request$2(url).then(function () { return; }, function (_ref) { var status = _ref.status; if (isEqual(status, 404)) { return; } var isAlreadyMax = max && isEqual(max, _detectCount); if (isAlreadyMax) { return Defer.reject(); } return deferTimeout(timeout).then(function (timeoutId) { self._detectCount = _detectCount; self._timeoutId = timeoutId; return self._detect(); }); }); }; _proto5.start = function start() { return this._detect(); }; _proto5.stop = function stop() { var timeoutId = this._timeoutId; if (timeoutId) { clearTimeout$1(timeoutId); } }; return NetworkDetecter; }(); var toUpperCase = function toUpperCase(str, startIndex, endIndex) { if (isUndefined(startIndex) || isUndefined(endIndex)) { return str.toUpperCase(); } var sliceStr = str.slice(startIndex, endIndex); str = str.replace(sliceStr, function (text) { return text.toUpperCase(); }); return str; }; var getDomainByUrl = function getDomainByUrl(url) { var StartMark = '://', EndMark = '/'; var urlProtocolIndex = indexOf(url, StartMark); var hasProtocol = urlProtocolIndex > -1; if (hasProtocol) { urlProtocolIndex = urlProtocolIndex + StartMark.length; url = substring(url, urlProtocolIndex, url.length); } var urlPathIndex = indexOf(url, EndMark); var hasPath = urlPathIndex > -1; if (hasPath) { url = substring(url, 0, urlPathIndex); } return url; }; var getValidUrl = function getValidUrl(url, option) { option = option || {}; var ProtocolMark = '://'; var hasProtocol = isInclude(url, ProtocolMark); var localProtocol = env.protocol.http; var _option3 = option, protocol = _option3.protocol; if (protocol) { var domain = getDomainByUrl(url); url = protocol + "//" + domain; } if (hasProtocol) { var urlProtocolIndex = indexOf(url, ProtocolMark) + 1; var urlProtocol = substring(url, 0, urlProtocolIndex); var isHttpUrl = urlProtocol === HTTP_PROTOCOL.HTTP; var isLocalHttps = localProtocol === HTTP_PROTOCOL.HTTPS; if (isHttpUrl && isLocalHttps) { var _domain = getDomainByUrl(url); return HTTP_PROTOCOL.HTTPS + "//" + _domain; } else { return url; } } else { return localProtocol + "//" + url; } }; var quickSort = function quickSort(arr, event) { var sort = function sort(array, left, right, event) { event = event || function (a, b) { return a <= b; }; if (left < right) { var x = array[right], i = left - 1, temp; for (var j = left; j <= right; j++) { if (event(array[j], x)) { i++; temp = array[i]; array[i] = array[j]; array[j] = temp; } } sort(array, left, i - 1, event); sort(array, i + 1, right, event); } return array; }; return sort(arr, 0, arr.length - 1, event); }; var unique = function unique(arr, event) { var keyEvent = event || function (data) { return data; }; var hashTable = {}; var newArr = []; forEach(arr, function (data) { var key = keyEvent(data); if (!hashTable[key]) { hashTable[key] = true; newArr.push(data); } }); return newArr; }; var isStackError = function isStackError(error) { error = error || {}; return error.stack && error.stack.toString; }; var consoleError = function consoleError() { var _console; return (_console = console).error.apply(_console, arguments); }; var consoleLog = function consoleLog() { var _console2; return (_console2 = console).log.apply(_console2, arguments); }; var string10to64 = function string10to64(number) { var chars = '0123456789abcdefghigklmnopqrstuvwxyzABCDEFGHIGKLMNOPQRSTUVWXYZa0'.split(''), radix = chars.length + 1, qutient = +number, arr = []; do { var mod = qutient % radix; qutient = (qutient - mod) / radix; arr.unshift(chars[mod]); } while (qutient); return arr.join(''); }; var getUUID = function getUUID() { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { var r = Math.random() * 16 | 0, v = c === 'x' ? r : r & 0x3 | 0x8; return v.toString(16); }); }; var getUUID22 = function getUUID22() { var uuid = getUUID(); uuid = uuid.replace(/-/g, '') + 'a'; uuid = parseInt(uuid, 16); uuid = string10to64(uuid); if (uuid.length > 22) { uuid = uuid.slice(0, 22); } else { var len = 22 - uuid.length; for (var i = 0; i < len; i++) { uuid = uuid + '0'; } } return uuid; }; var isValidTimestamp = function isValidTimestamp(time) { return isNumber(time) && time !== 0; }; var formateDate = function formateDate(seperator) { var date = new Date(); var year = date.getFullYear(); var month = date.getMonth() + 1; var day = date.getDate(); return tplEngine('{year}{seperator}{month}{seperator}{day}', { year: year, month: month, day: day, seperator: seperator }); }; var utils = { Storage: storage$1, Session: session, Socket: Socket$2, Cache: CacheStorage, JSON: JSON$2, Defer: Defer, httpRequest: request$1, request: request$2, requestByUrlList: requestByUrlList, requestForFaster: requestForFaster, md5: md5, DeferHandler: DeferHandler, EventEmitter: EventEmitter, Timer: Timer, Queue: Queue, consoleError: consoleError, consoleLog: consoleLog, noop: noop, deferNoop: deferNoop, setTimeout: setTimeout$1, toJSON: toJSON, parseJSON: parseJSON, copy: copy, isObject: isObject, isArray: isArray, isFunction: isFunction, isArrayBuffer: isArrayBuffer, isString: isString, isBoolean: isBoolean, isUndefined: isUndefined, isNull: isNull, isNumber: isNumber, isNumberData: isNumberData, isPromise: isPromise, getTypeName: getTypeName, isPlus: isPlus, isEmpty: isEmpty, isFalse: isFalse, isEqual: isEqual, isValidJSON: isValidJSON, isSupportSocket: isSupportSocket, ArrayBufferToArray: ArrayBufferToArray, ArrayBufferToUint8Array: ArrayBufferToUint8Array, indexOf: indexOf, lastIndexOf: lastIndexOf, isInclude: isInclude, substring: substring, getKeys: getKeys, getValues: getValues, getTimestamp: getTimestamp, getCurrentTimestamp: getCurrentTimestamp, formatTime: formatTime, parse16To10: parse16To10, forEach: forEach, map: map, filter: filter, extend: extend, extendAllowNull: extendAllowNull, extendInShallow: extendInShallow, deferred: deferred, tplEngine: tplEngine, getRandomNum: getRandomNum, int64ToTimestamp: int64ToTimestamp, batchInt64ToTimestamp: batchInt64ToTimestamp, encodeURI: encodeURI, decodeURI: decodeURI, secondsToMilliseconds: secondsToMilliseconds, NetworkDetecter: NetworkDetecter, toUpperCase: toUpperCase, getDomainByUrl: getDomainByUrl, getValidUrl: getValidUrl, quickSort: quickSort, unique: unique, isStackError: isStackError, getUUID: getUUID, getUUID22: getUUID22, isValidTimestamp: isValidTimestamp, formateDate: formateDate }; function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } var _PUBLISH_TOPIC_TO_CON, _CONVERSATION_TYPE_TO, _CONVERSATION_TYPE_TO2, _CONVERSATION_TYPE_TO3, _CONVERSATION_TYPE_TO4; var SUCCESS_CODE = 0; var PULL_MSG_TYPE = { NORMAL: 1, CHATROOM: 2 }; var MESSAGE_NAME = { CONN_ACK: 'ConnAckMessage', DISCONNECT: 'DisconnectMessage', PING_REQ: 'PingReqMessage', PING_RESP: 'PingRespMessage', PUBLISH: 'PublishMessage', PUB_ACK: 'PubAckMessage', QUERY: 'QueryMessage', QUERY_CON: 'QueryConMessage', QUERY_ACK: 'QueryAckMessage' }; var QOS = { AT_MOST_ONCE: 0, AT_LEAST_ONCE: 1, EXACTLY_ONCE: 2, DEFAULT: 3, '0': 'AT_MOST_ONCE', '1': 'AT_LEAST_ONCE', '2': 'EXACTLY_ONCE', '3': 'DEFAULT' }; var OPERATE_TYPE = { CONNECT: 1, '1': 'CONNECT', CONNACK: 2, '2': 'CONNACK', PUBLISH: 3, '3': 'PUBLISH', PUBACK: 4, '4': 'PUBACK', QUERY: 5, '5': 'QUERY', QUERYACK: 6, '6': 'QUERYACK', QUERYCON: 7, '7': 'QUERYCON', SUBSCRIBE: 8, '8': 'SUBSCRIBE', SUBACK: 9, '9': 'SUBACK', UNSUBSCRIBE: 10, '10': 'UNSUBSCRIBE', UNSUBACK: 11, '11': 'UNSUBACK', PINGREQ: 12, '12': 'PINGREQ', PINGRESP: 13, '13': 'PINGRESP', DISCONNECT: 14, '14': 'DISCONNECT' }; var PUBLISH_TOPIC = { PRIVATE: 'ppMsgP', GROUP: 'pgMsgP', CHATROOM: 'chatMsg', CUSTOMER_SERVICE: 'pcMsgP', RECALL: 'recallMsg', RTC_MSG: 'prMsgS', NOTIFY_PULL_MSG: 's_ntf', RECEIVE_MSG: 's_msg', SYNC_STATUS: 's_stat', SERVER_NOTIFY: 's_cmd', SETTING_NOTIFY: 's_us' }; var PUBLISH_STATUS_TOPIC = { PRIVATE: 'ppMsgS', GROUP: 'pgMsgS', CHATROOM: 'chatMsgS' }; var QUERY_TOPIC = { GET_SYNC_TIME: 'qrySessionsAtt', PULL_MSG: 'pullMsg', GET_CONVERSATION_LIST: 'qrySessions', REMOVE_CONVERSATION_LIST: 'delSessions', DELETE_MESSAGES: 'delMsg', CLEAR_UNREAD_COUNT: 'updRRTime', PULL_USER_SETTING: 'pullUS', PULL_CHRM_MSG: 'chrmPull', JOIN_CHATROOM: 'joinChrm', JOIN_EXIST_CHATROOM: 'joinChrmR', QUIT_CHATROOM: 'exitChrm', GET_CHATROOM_INFO: 'queryChrmI', UPDATE_CHATROOM_KV: 'setKV', DELETE_CHATROOM_KV: 'delKV', PULL_CHATROOM_KV: 'pullKV', GET_OLD_CONVERSATION_LIST: 'qryRelation', REMOVE_OLD_CONVERSATION: 'delRelation', GET_CONVERSATION_STATUS: 'pullSeAtts', SET_CONVERSATION_STATUS: 'setSeAtt', GET_UPLOAD_FILE_TOKEN: 'qnTkn', GET_UPLOAD_FILE_URL: 'qnUrl', CLEAR_MESSAGES: { PRIVATE: 'cleanPMsg', GROUP: 'cleanGMsg', CUSTOMER_SERVICE: 'cleanCMsg', SYSTEM: 'cleanSMsg' }, JOIN_RTC_ROOM: 'rtcRJoin_data', QUIT_RTC_ROOM: 'rtcRExit', PING_RTC: 'rtcPing', SET_RTC_DATA: 'rtcSetData', USER_SET_RTC_DATA: 'userSetData', GET_RTC_DATA: 'rtcQryData', DEL_RTC_DATA: 'rtcDelData', SET_RTC_OUT_DATA: 'rtcSetOutData', GET_RTC_OUT_DATA: 'rtcQryUserOutData', GET_RTC_TOKEN: 'rtcToken', SET_RTC_STATE: 'rtcUserState', GET_RTC_ROOM_INFO: 'rtcRInfo', GET_RTC_USER_INFO_LIST: 'rtcUData', SET_RTC_USER_INFO: 'rtcUPut', DEL_RTC_USER_INFO: 'rtcUDel', GET_RTC_USER_LIST: 'rtcUList' }; var QUERY_HISTORY_TOPIC = { PRIVATE: 'qryPMsg', GROUP: 'qryGMsg', CHATROOM: 'qryCHMsg', CUSTOMER_SERVICE: 'qryCMsg', SYSTEM: 'qrySMsg' }; var SERVER_NOTIFY_TYPE = { KV_CHANGED: 2, CONVERSATION_STATUS_CHANGED: 3 }; var CHATROOM_KV_STATUS_CODE = { AUTO_DELETE: 0x0001, OVERWRITE: 0x0002, OPERATE: 0x0004 }; var PUBLISH_TOPIC_TO_CONVERSATION_TYPE = (_PUBLISH_TOPIC_TO_CON = {}, _PUBLISH_TOPIC_TO_CON[PUBLISH_TOPIC.PRIVATE] = CONVERSATION_TYPE.PRIVATE, _PUBLISH_TOPIC_TO_CON[PUBLISH_TOPIC.GROUP] = CONVERSATION_TYPE.GROUP, _PUBLISH_TOPIC_TO_CON[PUBLISH_TOPIC.CHATROOM] = CONVERSATION_TYPE.CHATROOM, _PUBLISH_TOPIC_TO_CON[PUBLISH_TOPIC.CUSTOMER_SERVICE] = CONVERSATION_TYPE.CUSTOMER_SERVICE, _PUBLISH_TOPIC_TO_CON[PUBLISH_STATUS_TOPIC.PRIVATE] = CONVERSATION_TYPE.PRIVATE, _PUBLISH_TOPIC_TO_CON[PUBLISH_STATUS_TOPIC.GROUP] = CONVERSATION_TYPE.GROUP, _PUBLISH_TOPIC_TO_CON[PUBLISH_STATUS_TOPIC.CHATROOM] = CONVERSATION_TYPE.CHATROOM, _PUBLISH_TOPIC_TO_CON); var CONVERSATION_TYPE_TO_PUBLISH_TOPIC = (_CONVERSATION_TYPE_TO = {}, _CONVERSATION_TYPE_TO[CONVERSATION_TYPE.PRIVATE] = PUBLISH_TOPIC.PRIVATE, _CONVERSATION_TYPE_TO[CONVERSATION_TYPE.GROUP] = PUBLISH_TOPIC.GROUP, _CONVERSATION_TYPE_TO[CONVERSATION_TYPE.CHATROOM] = PUBLISH_TOPIC.CHATROOM, _CONVERSATION_TYPE_TO[CONVERSATION_TYPE.CUSTOMER_SERVICE] = PUBLISH_TOPIC.CUSTOMER_SERVICE, _CONVERSATION_TYPE_TO[CONVERSATION_TYPE.RTC_ROOM] = PUBLISH_TOPIC.RTC_MSG, _CONVERSATION_TYPE_TO); var CONVERSATION_TYPE_TO_PUBLISH_STATUS_TOPIC = (_CONVERSATION_TYPE_TO2 = {}, _CONVERSATION_TYPE_TO2[CONVERSATION_TYPE.PRIVATE] = PUBLISH_STATUS_TOPIC.PRIVATE, _CONVERSATION_TYPE_TO2[CONVERSATION_TYPE.GROUP] = PUBLISH_STATUS_TOPIC.GROUP, _CONVERSATION_TYPE_TO2); var CONVERSATION_TYPE_TO_QUERY_HISTORY_TOPIC = (_CONVERSATION_TYPE_TO3 = {}, _CONVERSATION_TYPE_TO3[CONVERSATION_TYPE.PRIVATE] = QUERY_HISTORY_TOPIC.PRIVATE, _CONVERSATION_TYPE_TO3[CONVERSATION_TYPE.GROUP] = QUERY_HISTORY_TOPIC.GROUP, _CONVERSATION_TYPE_TO3[CONVERSATION_TYPE.CHATROOM] = QUERY_HISTORY_TOPIC.CHATROOM, _CONVERSATION_TYPE_TO3[CONVERSATION_TYPE.CUSTOMER_SERVICE] = QUERY_HISTORY_TOPIC.CUSTOMER_SERVICE, _CONVERSATION_TYPE_TO3[CONVERSATION_TYPE.SYSTEM] = QUERY_HISTORY_TOPIC.SYSTEM, _CONVERSATION_TYPE_TO3); var CONVERSATION_TYPE_TO_CLEAR_MESSAGE_TOPIC = (_CONVERSATION_TYPE_TO4 = {}, _CONVERSATION_TYPE_TO4[CONVERSATION_TYPE.PRIVATE] = QUERY_TOPIC.CLEAR_MESSAGES.PRIVATE, _CONVERSATION_TYPE_TO4[CONVERSATION_TYPE.GROUP] = QUERY_TOPIC.CLEAR_MESSAGES.GROUP, _CONVERSATION_TYPE_TO4[CONVERSATION_TYPE.CUSTOMER_SERVICE] = QUERY_TOPIC.CLEAR_MESSAGES.CUSTOMER_SERVICE, _CONVERSATION_TYPE_TO4[CONVERSATION_TYPE.SYSTEM] = QUERY_TOPIC.CLEAR_MESSAGES.SYSTEM, _CONVERSATION_TYPE_TO4); var USER_SETTING_STATUS = { ADD: 1, UPDATE: 2, DELETE: 3 }; var CONVERSATION_STATUS_CONFIG = { ENABLED: '1', DISABLED: '0' }; var CONVERSATION_STATUS_TYPE = { DO_NOT_DISTURB: 1, TOP: 2 }; var Header = function () { function Header(_type, _retain, _qos, _dup) { this.type = void 0; this.retain = false; this.qos = QOS.AT_LEAST_ONCE; this.dup = false; this.syncMsg = false; var isPlusType = utils.isPlus(_type); if (_type && isPlusType && arguments.length === 1) { this.retain = (_type & 1) > 0; this.qos = (_type & 6) >> 1; this.dup = (_type & 8) > 0; this.type = _type >> 4 & 15; this.syncMsg = (_type & 8) === 8; } else { this.type = _type; this.retain = _retain === undefined ? false : _retain; this.qos = _qos === undefined ? QOS.AT_LEAST_ONCE : _qos; this.dup = _dup === undefined ? false : _dup; } } var _proto = Header.prototype; _proto.encode = function encode() { var self = this; var validQosList = [QOS.AT_MOST_ONCE, QOS.AT_LEAST_ONCE, QOS.EXACTLY_ONCE, QOS.DEFAULT]; utils.forEach(validQosList, function (qos) { if (self.qos === QOS[qos]) { self.qos = qos; } }); var _byte = self.type << 4; _byte |= self.retain ? 1 : 0; _byte |= self.qos << 1; _byte |= self.dup ? 8 : 0; return _byte; }; return Header; }(); var BinaryHelper = { writeUTF: function writeUTF(str, isGetBytes) { var back = [], byteSize = 0; utils.forEach(str, function (_char, i) { var code = str.charCodeAt(i); if (code >= 0 && code <= 127) { byteSize += 1; back.push(code); } else if (code >= 128 && code <= 2047) { byteSize += 2; back.push(192 | 31 & code >> 6); back.push(128 | 63 & code); } else if (code >= 2048 && code <= 65535) { byteSize += 3; back.push(224 | 15 & code >> 12); back.push(128 | 63 & code >> 6); back.push(128 | 63 & code); } }); utils.forEach(back, function (_char2, i) { if (_char2 > 255) { back[i] &= 255; } }); if (isGetBytes) { return back; } if (byteSize <= 255) { return [0, byteSize].concat(back); } else { return [byteSize >> 8, byteSize & 255].concat(back); } }, readUTF: function readUTF(arr) { var MAX_SIZE = 0x4000; var codeUnits = []; var highSurrogate; var lowSurrogate; var index = -1; var strBytes = arr; var result = ''; while (++index < strBytes.length) { var codePoint = Number(strBytes[index]); if (codePoint === (codePoint & 0x7F)) ; else if (0xF0 === (codePoint & 0xF0)) { codePoint ^= 0xF0; codePoint = codePoint << 6 | strBytes[++index] ^ 0x80; codePoint = codePoint << 6 | strBytes[++index] ^ 0x80; codePoint = codePoint << 6 | strBytes[++index] ^ 0x80; } else if (0xE0 === (codePoint & 0xE0)) { codePoint ^= 0xE0; codePoint = codePoint << 6 | strBytes[++index] ^ 0x80; codePoint = codePoint << 6 | strBytes[++index] ^ 0x80; } else if (0xC0 === (codePoint & 0xC0)) { codePoint ^= 0xC0; codePoint = codePoint << 6 | strBytes[++index] ^ 0x80; } if (!isFinite(codePoint) || codePoint < 0 || codePoint > 0x10FFFF || Math.floor(codePoint) !== codePoint) throw RangeError('Invalid code point: ' + codePoint); if (codePoint <= 0xFFFF) codeUnits.push(codePoint);else { codePoint -= 0x10000; highSurrogate = codePoint >> 10 | 0xD800; lowSurrogate = codePoint % 0x400 | 0xDC00; codeUnits.push(highSurrogate, lowSurrogate); } if (index + 1 === strBytes.length || codeUnits.length > MAX_SIZE) { result += String.fromCharCode.apply(null, codeUnits); codeUnits.length = 0; } } return result; } }; var RongStreamReader = function () { function RongStreamReader(arr) { this.pool = void 0; this.position = 0; this.poolLen = 0; this.pool = arr; this.poolLen = arr.length; } var _proto2 = RongStreamReader.prototype; _proto2.check = function check() { return this.position >= this.pool.length; }; _proto2.readInt = function readInt() { var self = this; if (self.check()) { return -1; } var end = ''; for (var i = 0; i < 4; i++) { var t = self.pool[self.position++].toString(16); if (t.length === 1) { t = '0' + t; } end += t.toString(); } return utils.parse16To10(end); }; _proto2.readLong = function readLong() { var self = this; if (self.check()) { return -1; } var end = ''; for (var i = 0; i < 8; i++) { var t = self.pool[self.position++].toString(16); if (t.length === 1) { t = '0' + t; } end += t; } return utils.parse16To10(end); }; _proto2.readByte = function readByte() { if (this.check()) { return -1; } var val = this.pool[this.position++]; if (val > 255) { val &= 255; } return val; }; _proto2.readUTF = function readUTF() { if (this.check()) { return ''; } var big = this.readByte() << 8 | this.readByte(); var pool = this.pool.subarray(this.position, this.position += big); return BinaryHelper.readUTF(pool); }; _proto2.readAll = function readAll() { return this.pool.subarray(this.position, this.poolLen); }; return RongStreamReader; }(); var RongStreamWriter = function () { function RongStreamWriter() { this.pool = []; this.position = 0; this.writen = 0; } var _proto3 = RongStreamWriter.prototype; _proto3.write = function write(_byte2) { if (utils.isArray(_byte2)) { this.pool = this.pool.concat(_byte2); } else if (utils.isPlus(_byte2)) { if (_byte2 > 255) { _byte2 &= 255; } this.pool.push(_byte2); this.writen++; } return _byte2; }; _proto3.writeArr = function writeArr(_byte3) { this.pool = this.pool.concat(_byte3); return _byte3; }; _proto3.writeUTF = function writeUTF(str) { var val = BinaryHelper.writeUTF(str); this.pool = this.pool.concat(val); this.writen += val.length; }; _proto3.getBytesArray = function getBytesArray() { return this.pool; }; return RongStreamWriter; }(); var IDENTIFIER = { PUB: 'pub', QUERY: 'qry' }; var _getIdentifier = function getIdentifier(messageId, identifier) { if (messageId && identifier) { return identifier + '_' + messageId; } else if (messageId) { return messageId; } else { return utils.getCurrentTimestamp(); } }; var BaseReader = function () { function BaseReader(header) { this._name = void 0; this._header = void 0; this.lengthSize = 0; this.messageId = void 0; this.timestamp = void 0; this.identifier = void 0; this._header = header; } var _proto = BaseReader.prototype; _proto.getIdentifier = function getIdentifier() { var messageId = this.messageId, identifier = this.identifier; return _getIdentifier(messageId, identifier); }; _proto.read = function read(stream, length) { this.readMessage(stream, length); }; _proto.readMessage = function readMessage(stream, length) { return { stream: stream, length: length }; }; return BaseReader; }(); var BaseWriter = function () { function BaseWriter(headerType) { this._header = void 0; this.lengthSize = 0; this.data = void 0; this.messageId = void 0; this.topic = void 0; this.targetId = void 0; this.identifier = void 0; this._header = new Header(headerType, false, QOS.AT_MOST_ONCE, false); } var _proto2 = BaseWriter.prototype; _proto2.getIdentifier = function getIdentifier() { var messageId = this.messageId, identifier = this.identifier; return _getIdentifier(messageId, identifier); }; _proto2.write = function write(stream) { var headerCode = this.getHeaderFlag(); stream.write(headerCode); this.writeMessage(stream); }; _proto2.writeMessage = function writeMessage(stream) { return stream; }; _proto2.setHeaderQos = function setHeaderQos(qos) { this._header.qos = qos; }; _proto2.getHeaderFlag = function getHeaderFlag() { return this._header.encode(); }; _proto2.getLengthSize = function getLengthSize() { return this.lengthSize; }; _proto2.getBufferData = function getBufferData() { var stream = new RongStreamWriter(); this.write(stream); var val = stream.getBytesArray(); var binary = new Int8Array(val); return binary; }; _proto2.getCometData = function getCometData() { var data = this.data || {}; return utils.toJSON(data); }; return BaseWriter; }(); var ConnAckReader = function (_BaseReader) { _inheritsLoose(ConnAckReader, _BaseReader); function ConnAckReader() { var _this; for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this = _BaseReader.call.apply(_BaseReader, [this].concat(args)) || this; _this._name = MESSAGE_NAME.CONN_ACK; _this.status = void 0; _this.userId = void 0; _this.timestamp = void 0; return _this; } var _proto3 = ConnAckReader.prototype; _proto3.readMessage = function readMessage(stream, msgLength) { stream.readByte(); this.status = +stream.readByte(); if (msgLength > ConnAckReader.MESSAGE_LENGTH) { this.userId = stream.readUTF(); stream.readUTF(); this.timestamp = stream.readLong(); } }; return ConnAckReader; }(BaseReader); ConnAckReader.MESSAGE_LENGTH = 2; var DisconnectReader = function (_BaseReader2) { _inheritsLoose(DisconnectReader, _BaseReader2); function DisconnectReader() { var _this2; for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } _this2 = _BaseReader2.call.apply(_BaseReader2, [this].concat(args)) || this; _this2._name = MESSAGE_NAME.DISCONNECT; _this2.status = void 0; return _this2; } var _proto4 = DisconnectReader.prototype; _proto4.readMessage = function readMessage(stream) { stream.readByte(); this.status = +stream.readByte(); }; return DisconnectReader; }(BaseReader); DisconnectReader.MESSAGE_LENGTH = 2; var PingReqWriter = function (_BaseWriter) { _inheritsLoose(PingReqWriter, _BaseWriter); function PingReqWriter() { var _this3; _this3 = _BaseWriter.call(this, OPERATE_TYPE.PINGREQ) || this; _this3._name = MESSAGE_NAME.PING_REQ; return _this3; } return PingReqWriter; }(BaseWriter); var PingRespReader = function (_BaseReader3) { _inheritsLoose(PingRespReader, _BaseReader3); function PingRespReader() { var _this4; for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { args[_key3] = arguments[_key3]; } _this4 = _BaseReader3.call.apply(_BaseReader3, [this].concat(args)) || this; _this4._name = MESSAGE_NAME.PING_RESP; return _this4; } return PingRespReader; }(BaseReader); var RetryableReader = function (_BaseReader4) { _inheritsLoose(RetryableReader, _BaseReader4); function RetryableReader() { var _this5; for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { args[_key4] = arguments[_key4]; } _this5 = _BaseReader4.call.apply(_BaseReader4, [this].concat(args)) || this; _this5.messageId = void 0; return _this5; } var _proto5 = RetryableReader.prototype; _proto5.readMessage = function readMessage(stream) { var msgId = stream.readByte() * 256 + stream.readByte(); this.messageId = parseInt(msgId, 10); }; return RetryableReader; }(BaseReader); var RetryableWriter = function (_BaseWriter2) { _inheritsLoose(RetryableWriter, _BaseWriter2); function RetryableWriter() { var _this6; for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) { args[_key5] = arguments[_key5]; } _this6 = _BaseWriter2.call.apply(_BaseWriter2, [this].concat(args)) || this; _this6.messageId = void 0; return _this6; } var _proto6 = RetryableWriter.prototype; _proto6.writeMessage = function writeMessage(stream) { var id = this.messageId; var lsb = id & 255; var msb = (id & 65280) >> 8; stream.write(msb); stream.write(lsb); }; return RetryableWriter; }(BaseWriter); var PublishReader = function (_RetryableReader) { _inheritsLoose(PublishReader, _RetryableReader); function PublishReader() { var _this7; for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) { args[_key6] = arguments[_key6]; } _this7 = _RetryableReader.call.apply(_RetryableReader, [this].concat(args)) || this; _this7._name = MESSAGE_NAME.PUBLISH; _this7.topic = void 0; _this7.data = void 0; _this7.targetId = void 0; _this7.date = void 0; _this7.syncMsg = false; _this7.identifier = IDENTIFIER.PUB; return _this7; } var _proto7 = PublishReader.prototype; _proto7.readMessage = function readMessage(stream) { this.date = stream.readInt(); this.topic = stream.readUTF(); this.targetId = stream.readUTF(); RetryableReader.prototype.readMessage.apply(this, arguments); this.data = stream.readAll(); }; return PublishReader; }(RetryableReader); var PublishWriter = function (_RetryableWriter) { _inheritsLoose(PublishWriter, _RetryableWriter); function PublishWriter(topic, data, targetId) { var _this8; _this8 = _RetryableWriter.call(this, OPERATE_TYPE.PUBLISH) || this; _this8._name = MESSAGE_NAME.PUBLISH; _this8.topic = void 0; _this8.data = void 0; _this8.targetId = void 0; _this8.date = void 0; _this8.syncMsg = false; _this8.identifier = IDENTIFIER.PUB; _this8.topic = topic; _this8.data = utils.isString(data) ? BinaryHelper.writeUTF(data) : data; _this8.targetId = targetId; return _this8; } var _proto8 = PublishWriter.prototype; _proto8.writeMessage = function writeMessage(stream) { stream.writeUTF(this.topic); stream.writeUTF(this.targetId); RetryableWriter.prototype.writeMessage.apply(this, arguments); stream.write(this.data); }; return PublishWriter; }(RetryableWriter); var PubAckReader = function (_RetryableReader2) { _inheritsLoose(PubAckReader, _RetryableReader2); function PubAckReader() { var _this9; for (var _len7 = arguments.length, args = new Array(_len7), _key7 = 0; _key7 < _len7; _key7++) { args[_key7] = arguments[_key7]; } _this9 = _RetryableReader2.call.apply(_RetryableReader2, [this].concat(args)) || this; _this9._name = MESSAGE_NAME.PUB_ACK; _this9.status = void 0; _this9.date = 0; _this9.data = void 0; _this9.millisecond = 0; _this9.messageUId = void 0; _this9.timestamp = 0; _this9.identifier = IDENTIFIER.PUB; return _this9; } var _proto9 = PubAckReader.prototype; _proto9.readMessage = function readMessage(stream) { RetryableReader.prototype.readMessage.call(this, stream); this.date = stream.readInt(); this.status = stream.readByte() * 256 + stream.readByte(); this.millisecond = stream.readByte() * 256 + stream.readByte(); this.timestamp = this.date * 1000 + this.millisecond; this.messageUId = stream.readUTF(); }; return PubAckReader; }(RetryableReader); var PubAckWriter = function (_RetryableWriter2) { _inheritsLoose(PubAckWriter, _RetryableWriter2); function PubAckWriter(messageId) { var _this10; _this10 = _RetryableWriter2.call(this, OPERATE_TYPE.PUBACK) || this; _this10._name = MESSAGE_NAME.PUB_ACK; _this10.status = void 0; _this10.date = 0; _this10.millisecond = 0; _this10.messageUId = void 0; _this10.timestamp = 0; _this10.messageId = messageId; return _this10; } var _proto10 = PubAckWriter.prototype; _proto10.writeMessage = function writeMessage(stream) { RetryableWriter.prototype.writeMessage.call(this, stream); }; return PubAckWriter; }(RetryableWriter); var QueryWriter = function (_RetryableWriter3) { _inheritsLoose(QueryWriter, _RetryableWriter3); function QueryWriter(topic, data, targetId) { var _this11; _this11 = _RetryableWriter3.call(this, OPERATE_TYPE.QUERY) || this; _this11._name = MESSAGE_NAME.QUERY; _this11.topic = void 0; _this11.data = void 0; _this11.targetId = void 0; _this11.identifier = IDENTIFIER.QUERY; _this11.topic = topic; _this11.data = utils.isString(data) ? BinaryHelper.writeUTF(data) : data; _this11.targetId = targetId; return _this11; } var _proto11 = QueryWriter.prototype; _proto11.writeMessage = function writeMessage(stream) { stream.writeUTF(this.topic); stream.writeUTF(this.targetId); RetryableWriter.prototype.writeMessage.call(this, stream); stream.write(this.data); }; return QueryWriter; }(RetryableWriter); var QueryConWriter = function (_RetryableWriter4) { _inheritsLoose(QueryConWriter, _RetryableWriter4); function QueryConWriter(messageId) { var _this12; _this12 = _RetryableWriter4.call(this, OPERATE_TYPE.QUERYCON) || this; _this12._name = MESSAGE_NAME.QUERY_CON; _this12.messageId = messageId; return _this12; } return QueryConWriter; }(RetryableWriter); var QueryAckReader = function (_RetryableReader3) { _inheritsLoose(QueryAckReader, _RetryableReader3); function QueryAckReader() { var _this13; for (var _len8 = arguments.length, args = new Array(_len8), _key8 = 0; _key8 < _len8; _key8++) { args[_key8] = arguments[_key8]; } _this13 = _RetryableReader3.call.apply(_RetryableReader3, [this].concat(args)) || this; _this13._name = MESSAGE_NAME.QUERY_ACK; _this13.data = void 0; _this13.status = void 0; _this13.date = void 0; _this13.identifier = IDENTIFIER.QUERY; return _this13; } var _proto12 = QueryAckReader.prototype; _proto12.readMessage = function readMessage(stream) { RetryableReader.prototype.readMessage.call(this, stream); this.date = stream.readInt(); this.status = stream.readByte() * 256 + stream.readByte(); this.data = stream.readAll(); }; return QueryAckReader; }(RetryableReader); var getReaderByHeader = function getReaderByHeader(header) { var type = header.type, msg = new BaseReader(header); switch (type) { case OPERATE_TYPE.CONNACK: msg = new ConnAckReader(header); break; case OPERATE_TYPE.PUBLISH: msg = new PublishReader(header); msg.syncMsg = header.syncMsg; break; case OPERATE_TYPE.PUBACK: msg = new PubAckReader(header); break; case OPERATE_TYPE.QUERYACK: msg = new QueryAckReader(header); break; case OPERATE_TYPE.SUBACK: case OPERATE_TYPE.UNSUBACK: case OPERATE_TYPE.PINGRESP: msg = new PingRespReader(header); break; case OPERATE_TYPE.DISCONNECT: msg = new DisconnectReader(header); break; default: throw new Error('No support for deserializing ' + type + ' messages'); } return msg; }; var readWSBuffer = function readWSBuffer(data) { var arr = new Uint8Array(data); var stream = new RongStreamReader(arr); var flags = stream.readByte(), header = new Header(flags); var msg = getReaderByHeader(header); msg.read(stream, arr.length - 1); return msg; }; var readCometData = function readCometData(data) { var flags = data.headerCode, header = new Header(flags); var msg = getReaderByHeader(header); utils.forEach(data, function (item, key) { if (key in msg) { msg[key] = item; } }); return msg; }; var ENGINE_EVENT = { WATCH: 'watch', UN_WATCH: 'unwatch', CONNECT: 'connect', RECONNECT: 'reconnect', DISCONNECT: 'disconnect', CHANGE_USER: 'changeUser', GET_CONNECTION_STATUS: 'getConnectionStatus', GET_CONNECTION_USER_ID: 'getConnectionUserId', GET_CONNECTED_TIME: 'getConnectedTime', GET_APP_INFO: 'getAppInfo', GET_CONVERSATION_LIST: 'getConversationList', REMOVE_CONVERSATION_LIST: 'removeConversationList', REMOVE_CONVERSATION: 'removeConversation', GET_TOTAL_UNREAD_COUNT: 'getTotalUnreadCount', CLEAR_UNREAD_COUNT: 'clearUnreadCount', GET_UNREAD_COUNT: 'getUnreadCount', GET_LOCAL_CONVERSATION: 'getLocalConversation', SET_CONVERSATION_STATUS_LIST: 'setConversationStatusList', SEND_MESSAGE: 'sendMessage', GET_HISTORY_MSGS: 'getHistoryMessages', DELETE_MESSAGES: 'deleteHistoryMessages', CLEAR_MESSAGES: 'clearHistoryMessages', RECALL_MESSAGE: 'recallMessage', JOIN_CHATROOM: 'joinChatRoom', QUIT_CHATROOM: 'quitChatRoom', GET_CHATROOM_INFO: 'getChatRoomInfo', GET_CHATROOM_MSGS: 'getChatRoomHistoryMessages', SET_KV: 'setChatRoomKV', FORCE_SET_KV: 'forceSetChatRoomKV', DEL_KV: 'removeChatRoomKV', FORCE_DEL_KV: 'forceRemoveChatRoomKV', GET_KV: 'getChatRoomKV', GET_ALL_KV: 'getAllChatRoomKV', JOIN_RTC: 'joinRTCRoom', QUIT_RTC: 'quitRTCRoom', PING_RTC: 'RTCPing', GET_RTC_ROOM_INFO: 'getRTCRoomInfo', SET_RTC_DATA: 'setRTCData', SET_RTC_USER_DATA: 'setRTCUserData', GET_RTC_DATA: 'getRTCData', DEL_RTC_DATA: 'removeRTCData', SET_RTC_OUT_DATA: 'setRTCOutData', GET_RTC_OUT_DATA: 'getRTCOutData', GET_RTC_TOKEN: 'getRTCToken', SET_RTC_STATE: 'setRTCState', GET_RTC_USER_INFO_LIST: 'getRTCUserInfoList', SET_RTC_USER_INFO: 'setRTCUserInfo', DEL_RTC_USER_INFO: 'removeRTCUserInfo', GET_RTC_USER_LIST: 'getRTCUserList', GET_UPLOAD_TOKEN: 'getFileToken', GET_UPLOAD_URL: 'getFileUrl' }; var ENGINE_EVENT_NEED_CONNECTED = [ENGINE_EVENT.GET_CONVERSATION_LIST, ENGINE_EVENT.REMOVE_CONVERSATION_LIST, ENGINE_EVENT.REMOVE_CONVERSATION, ENGINE_EVENT.GET_TOTAL_UNREAD_COUNT, ENGINE_EVENT.CLEAR_UNREAD_COUNT, ENGINE_EVENT.SEND_MESSAGE, ENGINE_EVENT.GET_HISTORY_MSGS, ENGINE_EVENT.DELETE_MESSAGES, ENGINE_EVENT.CLEAR_MESSAGES, ENGINE_EVENT.RECALL_MESSAGE, ENGINE_EVENT.JOIN_CHATROOM, ENGINE_EVENT.QUIT_CHATROOM, ENGINE_EVENT.GET_CHATROOM_INFO, ENGINE_EVENT.GET_CHATROOM_MSGS]; var ENGINE_EVENT_NEED_DISCONNECTED = [ENGINE_EVENT.CONNECT, ENGINE_EVENT.RECONNECT]; var IM_EVENT = { STATUS: 'status', MESSAGE: 'message', CONVERSATION: 'conversation', SETTING: 'setting', CHATROOM: 'chatroom' }; var TRANSPORT_EVENT = { SIGNAL: 'signal', STATUS: 'status' }; var SERVER_EVENT_NAME = { STATUS: 'status', NOTIFY_PULL: 'notifyPull', DIRECT_MSG: 'directMessage', CHRM_KV_CHANGED: 'chatRoomKV', CHRM_KV_SET: 'chatRoomKVSet', MESSAGE_SEND: 'sendMessage', JOIN_CHATROOM: 'joinChatRoom', BEFORE_JOIN_CHATROOM: 'beforeJoinChatRoom', USER_SETTING_CHANGED: 'userSetting', CONVERSATION_STATUS_CHANGED: 'converStatusChanged', CONVERSATION_STATUS_SETED: 'converStatusSeted' }; var _APP_ENGINE_EVENT_LOG; var PLATFORM$1 = 'Web'; var LEVEL = { FATAL: 0, ERROR: 1, WARN: 2, INFO: 3, DEBUG: 4 }; var STORE_SIZE = { ADVANCED: 500, LOW: 500 }; var LOG_TYPE = { 'IM': 'IM', 'RTC': 'RTC' }; var TAG = { L_GET_NAVI_T: 'L-get_navi-T', L_GET_NAVI_R: 'L-get_navi-R', L_PING_WS_T: 'L-ping_ws-T', L_PING_WS_R: 'L-ping_ws-R', L_NETWORK_CHANGED_S: 'L-network_changed-S', L_DECODE_MSG_E: 'L-decode_msg-E', L_RECONNECT_T: 'L-reconnect-T', L_RECONNECT_R: 'L-reconnect-R', L_PULL_CHRM_KV_T: 'L-pull-chrm-kv-T', L_PULL_CHRM_KV_R: 'L-pull-chrm-kv-R', L_PING_S: 'L-ping-S', L_CRASH_E: 'L-crash-E', L_COMET_SEND_SIGNAL_E: 'L-comet_send_signal-E', A_INIT_O: 'A-init-O', A_CONNECT_T: 'A-connect-T', A_CONNECT_R: 'A-connect-R', A_DISCONNECT_T: 'A-disconnect-T', A_DISCONNECT_R: 'A-disconnect-R', A_RECONNECT_T: 'A-reconnect-T', A_RECONNECT_R: 'A-reconnect-R', A_JOIN_CHATROOM_T: 'A-join_chatroom-T', A_JOIN_CHATROOM_R: 'A-join_chatroom-R', A_QUIT_CHATROOM_T: 'A-quit_chatroom-T', A_QUIT_CHATROOM_R: 'A-quit_chatroom-R', P_NOTIFY_CHRM_KV_S: 'P-notify-chrm-kv-R', G_CRASH_E: 'G-crash-E', G_UPLOAD_LOG_S: 'G-upload_log-S', G_UPLOAD_LOG_E: 'G-upload_log-E' }; var APP_ENGINE_EVENT_LOG_TAG = (_APP_ENGINE_EVENT_LOG = {}, _APP_ENGINE_EVENT_LOG[ENGINE_EVENT.CONNECT] = { req: TAG.A_CONNECT_T, resp: TAG.A_CONNECT_R }, _APP_ENGINE_EVENT_LOG[ENGINE_EVENT.DISCONNECT] = { req: TAG.A_DISCONNECT_T, resp: TAG.A_DISCONNECT_R }, _APP_ENGINE_EVENT_LOG[ENGINE_EVENT.RECONNECT] = { req: TAG.A_RECONNECT_T, resp: TAG.A_RECONNECT_R }, _APP_ENGINE_EVENT_LOG[ENGINE_EVENT.JOIN_CHATROOM] = { req: TAG.A_JOIN_CHATROOM_T, resp: TAG.A_JOIN_CHATROOM_R }, _APP_ENGINE_EVENT_LOG[ENGINE_EVENT.QUIT_CHATROOM] = { req: TAG.A_QUIT_CHATROOM_T, resp: TAG.A_QUIT_CHATROOM_R }, _APP_ENGINE_EVENT_LOG); var REPORT_TYPE = { REALTIME: 0, FULL: 1 }; var CSV_LOG_TPL = '{sessionId},{time},{type},{level},{tag},{content}\n'; var REALTIME_URL_TPL = '{protocol}{url}?version={version}&appkey={appkey}&userId={userId}&deviceId={deviceId}&deviceInfo={deviceInfo}&platform={platform}'; var MSGNOTIF_URL_TPL = '{protocol}{url}?version={version}&appkey={appkey}&userId={userId}&logId={logId}&deviceId={deviceId}&deviceInfo={deviceInfo}&platform={platform}'; var LOG_CMD_MSG_SENDER = 'rongcloudsystem'; var NO_FULL_LOG = 'nodata'; var REQUEST_TIMEOUT = 15000; var DEFAULT_SERVER_OPTION = { isOpen: true, url: 'logcollection.ronghub.com', realtimeLevel: LEVEL.ERROR, realtimeInterval: 20000, realtimeMaxTimes: 5, fullInterval: 5000, fullMaxTimes: 3, fullLevel: LEVEL.DEBUG }; var IGNORE_ERROR_CODE = [ERROR_CODE.RC_CONNECTION_EXIST]; var isEmpty$1 = utils.isEmpty, tplEngine$1 = utils.tplEngine; var getTransporterUrl = function getTransporterUrl(option) { var domain = option.domain, appkey = option.appkey, token = option.token, connectType = option.connectType, protocol = option.protocol; var isComet = connectType === CONNECT_TYPE.COMET; var cmpTpl = CMP_URL_TPL; if (isEmpty$1(protocol)) { protocol = isComet ? env.protocol.http : env.protocol.ws; } var tplOption = { domain: domain, appkey: appkey, protocol: protocol, apiVer: env.isFromUniapp ? 'uniapp' : 'normal', token: utils.encodeURI(token) }; if (env.isMini) { cmpTpl = MINI_CMP_URL_TPL; utils.extend(tplOption, { platform: PLATFORM_TYPE.MINI }); } return tplEngine$1(cmpTpl, tplOption); }; var isGroup = function isGroup(type) { return type === CONVERSATION_TYPE.GROUP; }; var isChatRoom = function isChatRoom(type) { return type === CONVERSATION_TYPE.CHATROOM; }; var getConversationTypeList = function getConversationTypeList() { return utils.getValues(CONVERSATION_TYPE); }; var isValidConversationType = function isValidConversationType(type) { var conversationTypeList = getConversationTypeList(); return utils.isNumber(type) && utils.isInclude(conversationTypeList, type); }; var getSessionId = function getSessionId(option) { var isStatusMessage = option.isStatusMessage; var isPersited = option.isPersited, isCounted = option.isCounted, isMentiond = option.isMentiond, disableNotification = option.disableNotification; if (isStatusMessage) { isPersited = isCounted = false; } var sessionId = 0; if (isPersited) { sessionId = sessionId | 0x01; } if (isCounted) { sessionId = sessionId | 0x02; } if (isMentiond) { sessionId = sessionId | 0x04; } if (disableNotification) { sessionId = sessionId | 0x20; } return sessionId; }; var getUpMessageOptionBySessionId = function getUpMessageOptionBySessionId(sessionId) { var isPersited = false, isCounted = false, disableNotification = false; isPersited = !!(sessionId & 0x01); isCounted = !!(sessionId & 0x02); disableNotification = !!(sessionId & 0x10); return { isPersited: isPersited, isCounted: isCounted, disableNotification: disableNotification }; }; var getMessageOptionByStatus = function getMessageOptionByStatus(status) { var isPersited = true, isCounted = true, isMentiond = false, disableNotification = false, receivedStatus = RECEIVED_STATUS.READ; var isReceivedByOtherClient = false; isPersited = !!(status & 0x10); isCounted = !!(status & 0x20); isMentiond = !!(status & 0x40); disableNotification = !!(status & 0x100); isReceivedByOtherClient = !!(status & 0x02); receivedStatus = isReceivedByOtherClient ? RECEIVED_STATUS.RETRIEVED : receivedStatus; return { isPersited: isPersited, isCounted: isCounted, isMentiond: isMentiond, disableNotification: disableNotification, receivedStatus: receivedStatus }; }; var SignalId = { ids: {}, temp: '{appkey}_{userId}', get: function get(option) { var key = utils.tplEngine(SignalId.temp, option); var id = SignalId.ids[key] || 0; id++; SignalId.ids[key] = id; return id; }, clear: function clear(option) { var key = utils.tplEngine(SignalId.temp, option); SignalId.ids[key] = 0; }, isExceedLimit: function isExceedLimit(id) { return id > MAX_SINGAL_ID; } }; var RCSocket = function () { function RCSocket(options) { this._socket = void 0; this.eventEmitter = new utils.EventEmitter(); this.KEY = { OPEN: 'open', MSG: 'msg', ERROR: 'error', CLOSE: 'close' }; var self = this; var KEY = self.KEY; self._socket = new utils.Socket(options); self._socket.onOpen(function (data) { self.eventEmitter.emit(KEY.OPEN, data); }); self._socket.onMessage(function (data) { self.eventEmitter.emit(KEY.MSG, data); }); self._socket.onError(function (data) { data = self._formatCloseData(data); self.eventEmitter.emit(KEY.ERROR, data); }); self._socket.onClose(function (data) { data = self._formatCloseData(data); self.eventEmitter.emit(KEY.CLOSE, data); }); } var _proto = RCSocket.prototype; _proto._formatCloseData = function _formatCloseData(data) { if (env.isMini || env.isAppPlus) { data = data || {}; var _data = data, errMsg = _data.errMsg; data.code = MINI_ERROR_MSG_TO_STATUS[errMsg]; } return data; }; _proto.send = function send(data) { return this._socket.send(data); }; _proto.close = function close() { this.eventEmitter.clear(); this._socket.close(); }; _proto.onOpen = function onOpen(event) { this.eventEmitter.on(this.KEY.OPEN, event); }; _proto.onMessage = function onMessage(event) { this.eventEmitter.on(this.KEY.MSG, event); }; _proto.onError = function onError(event) { this.eventEmitter.on(this.KEY.ERROR, event); }; _proto.onClose = function onClose(event) { this.eventEmitter.on(this.KEY.CLOSE, event); }; return RCSocket; }(); var RCStorage = function () { function RCStorage(suffix) { var _ref; this._cache = void 0; this.STORAGE_KEY = void 0; var storageKey = suffix ? STORAGE_ROOT_KEY + suffix : STORAGE_ROOT_KEY; var localCache = utils.Storage.get(storageKey) || {}; this._cache = new utils.Cache((_ref = {}, _ref[storageKey] = localCache, _ref)); this.STORAGE_KEY = storageKey; } var _proto2 = RCStorage.prototype; _proto2._get = function _get() { var KEY = this.STORAGE_KEY; return this._cache.get(KEY) || {}; }; _proto2._set = function _set(cache) { var KEY = this.STORAGE_KEY; cache = cache || {}; this._cache.set(KEY, cache); utils.Storage.set(KEY, cache); }; _proto2.set = function set(key, value) { var localValue = this._get(); localValue[key] = value; this._set(localValue); }; _proto2.remove = function remove(key) { var localValue = this._get(); delete localValue[key]; this._set(localValue); }; _proto2.clear = function clear() { var KEY = this.STORAGE_KEY; utils.Storage.remove(KEY); this._cache.remove(KEY); }; _proto2.get = function get(key) { var localValue = this._get(); return localValue[key]; }; _proto2.getKeys = function getKeys() { var localValue = this._get(); return utils.getKeys(localValue); }; _proto2.getValues = function getValues() { return this._get() || {}; }; return RCStorage; }(); var formatSyncTime = function formatSyncTime(_syncTime) { _syncTime = _syncTime || {}; _syncTime.inboxTime = _syncTime.inboxTime || 0; _syncTime.sendboxTime = _syncTime.sendboxTime || 0; return _syncTime; }; var MessageTimeSyner = function () { function MessageTimeSyner(option) { this._syncTime = void 0; this._storage = void 0; option = option || {}; var _option = option, startSyncTime = _option.startSyncTime; this._initStorage(option); if (startSyncTime) { this._syncTime = formatSyncTime(startSyncTime); } } var _proto3 = MessageTimeSyner.prototype; _proto3._initStorage = function _initStorage(option) { var appkey = option.appkey, userId = option.userId; var ROOT_KEY = utils.tplEngine(STORAGE_SYNC_TIME.ROOT_KEY_TPL, { appkey: appkey, userId: userId }); var storage = new RCStorage(ROOT_KEY); var syncTime = { sendboxTime: storage.get(STORAGE_SYNC_TIME.SUB_KEY.SENDBOX), inboxTime: storage.get(STORAGE_SYNC_TIME.SUB_KEY.INBOX) }; this._storage = storage; this._syncTime = formatSyncTime(syncTime); }; _proto3.setInbox = function setInbox(time) { var beforeTime = this._syncTime.inboxTime || 0; if (beforeTime < time) { this._syncTime.inboxTime = time; this._storage.set(STORAGE_SYNC_TIME.SUB_KEY.INBOX, time); } }; _proto3.setSendbox = function setSendbox(time) { var beforeTime = this._syncTime.sendboxTime || 0; if (beforeTime < time) { this._syncTime.sendboxTime = time; this._storage.set(STORAGE_SYNC_TIME.SUB_KEY.SENDBOX, time); } }; _proto3.setByMessage = function setByMessage(msg) { var messageDirection = msg.messageDirection, sentTime = msg.sentTime; var isSelfSend = messageDirection === MESSAGE_DIRECTION.SEND; isSelfSend ? this.setSendbox(sentTime) : this.setInbox(sentTime); }; _proto3.get = function get() { return formatSyncTime(this._syncTime); }; return MessageTimeSyner; }(); var ChatRoomMessageTimeSyner = function () { function ChatRoomMessageTimeSyner(option) { this._rootKey = void 0; this._pullTimes = {}; option = option || {}; var _option2 = option, appkey = _option2.appkey, userId = _option2.userId; this._rootKey = utils.tplEngine(SESSION_SYNC_TIME.ROOT_KEY_TPL, { appkey: appkey, userId: userId }); } var _proto4 = ChatRoomMessageTimeSyner.prototype; _proto4.set = function set(chrmId, time) { this._pullTimes[chrmId] = time; utils.Session.set(this._rootKey, this._pullTimes); }; _proto4.get = function get(chrmId) { var pullTimes; if (utils.isEmpty(this._pullTimes)) { pullTimes = utils.Session.get(this._rootKey) || {}; } else { pullTimes = this._pullTimes; } return pullTimes[chrmId] || 0; }; _proto4.setByMessage = function setByMessage(msg) { var sentTime = msg.sentTime; var chrmId = msg.targetId; var beforeTime = this.get(chrmId); if (beforeTime < sentTime) { this.set(chrmId, sentTime); } }; return ChatRoomMessageTimeSyner; }(); var JoinedChatRoomSyner = function () { function JoinedChatRoomSyner(option) { this._rootKey = void 0; this._joinedChatRoomInfos = []; option = option || {}; var _option3 = option, appkey = _option3.appkey, userId = _option3.userId; this._rootKey = utils.tplEngine(SESSION_SYNC_CHATROOM.ROOT_KEY_TPL, { appkey: appkey, userId: userId }); } var _proto5 = JoinedChatRoomSyner.prototype; _proto5.set = function set(option) { var _this = this; var chrmId = option.chrmId, count = option.count, isOpenJoinMulitpleChrmService = option.isOpenJoinMulitpleChrmService; var backupJoinedChatRoomInfos = utils.copy(this._joinedChatRoomInfos); if (isOpenJoinMulitpleChrmService) { utils.forEach(backupJoinedChatRoomInfos, function (chrmInfo, index) { if (chrmInfo.chrmId === option.chrmId) { _this._joinedChatRoomInfos.splice(index, 1); } }); this._joinedChatRoomInfos.push({ chrmId: chrmId, count: count }); } else { this._joinedChatRoomInfos = [{ chrmId: chrmId, count: count }]; } utils.Session.set(this._rootKey, this._joinedChatRoomInfos); }; _proto5.get = function get() { if (utils.isEmpty(this._joinedChatRoomInfos)) { return utils.Session.get(this._rootKey) || []; } else { return this._joinedChatRoomInfos; } }; _proto5.remove = function remove(chrmId) { var joinedChatRoom = utils.isEmpty(this._joinedChatRoomInfos) ? this._joinedChatRoomInfos : utils.Session.get(this._rootKey); if (utils.isEmpty(joinedChatRoom)) return; utils.forEach(joinedChatRoom, function (chrmInfo, index) { if (chrmInfo.chrmId === chrmId) { return joinedChatRoom.splice(index, 1); } }); utils.Session.set(this._rootKey, joinedChatRoom); }; _proto5.clear = function clear() { this._joinedChatRoomInfos = []; utils.Session.remove(this._rootKey); }; return JoinedChatRoomSyner; }(); var getUIDByToken = function getUIDByToken(token) { return utils.md5(token).slice(8, 16); }; var isIncludeNavi = function isIncludeNavi(token) { return utils.isInclude(token, NAVI_SEPARATOR_IN_TOKEN); }; var getNaviListByToken = function getNaviListByToken(token) { var navDomainList = []; if (isIncludeNavi(token)) { var separatorIndex = utils.indexOf(token, NAVI_SEPARATOR_IN_TOKEN); var navsText = token.substring(separatorIndex + 1, token.length); var domainList = navsText.split(DOMAIN_SEPARATOR_IN_NAVLIST); utils.forEach(domainList, function (domain) { if (!isEmpty$1(domain)) { navDomainList.push(domain); } }); } return navDomainList; }; var getCMPDomainList = function getCMPDomainList(option, customOption) { var server = option.server, backupServer = option.backupServer; server = server || ''; backupServer = backupServer || ''; var backupCMPList = backupServer.split(DOMAIN_SEPARATOR_IN_CMPLIST); var cmpList = []; if (!utils.isEmpty(server)) { cmpList.push(server); } utils.forEach(backupCMPList, function (cmp) { if (!utils.isEmpty(cmp)) { cmpList.push(cmp); } }); if (!utils.isUndefined(customOption.customCMP) && !utils.isEmpty(customOption.customCMP)) { cmpList = customOption.customCMP; } return cmpList; }; var getValidToken = function getValidToken(token) { if (isIncludeNavi(token)) { var separatorIndex = utils.indexOf(token, NAVI_SEPARATOR_IN_TOKEN); token = token.substring(0, separatorIndex + 1); } return token; }; var getConnectType = function getConnectType(option) { var connectType = option.connectType; var isSpecifiedSocket = connectType === CONNECT_TYPE.WEBSOCKET; var isSocket = isSpecifiedSocket && utils.isSupportSocket(); return isSocket ? CONNECT_TYPE.WEBSOCKET : CONNECT_TYPE.COMET; }; var isConnected = function isConnected(status) { return utils.isEqual(status, CONNECTION_STATUS.CONNECTED); }; var isConnecting = function isConnecting(status) { return utils.isEqual(status, CONNECTION_STATUS.CONNECTING); }; var isDisconnected = function isDisconnected(status) { return !isConnected(status) && !isConnecting(status); }; var getNavReqOption = function getNavReqOption(option, user) { option = utils.copy(option); option.token = user.token; return option; }; var getPingTimeout = function getPingTimeout(timeSpentConnect) { var timeout = timeSpentConnect * 3; if (timeout < IM_PING_MIN_TIMEOUT) { return IM_PING_MIN_TIMEOUT; } if (timeout > IM_PING_MAX_TIMEOUT) { return IM_PING_MAX_TIMEOUT; } return timeout; }; var DelayTimer = { _delayTime: 0, setTime: function setTime(time) { var currentTime = utils.getCurrentTimestamp(); DelayTimer._delayTime = currentTime - time; }, getTime: function getTime() { var delayTime = DelayTimer._delayTime; var currentTime = utils.getCurrentTimestamp(); return currentTime - delayTime; } }; var isInValidConversationData = function isInValidConversationData(conversation) { return !conversation.type || !conversation.targetId || !utils.isObject(conversation.latestMessage) || utils.isUndefined(conversation.unreadMessageCount); }; var fixConversationData = function fixConversationData(conversation) { conversation = conversation || {}; var _conversation = conversation, targetId = _conversation.targetId, type = _conversation.type; var defaultType = CONVERSATION_TYPE.PRIVATE, defaultId = '', defaultMsg = { messageType: MESSAGE_TYPE.TEXT, sentTime: DelayTimer.getTime(), content: { content: '' }, senderUserId: targetId, targetId: targetId, type: type }; conversation.type = type || defaultType; conversation.targetId = targetId || defaultId; conversation.latestMessage = conversation.latestMessage || defaultMsg; return conversation; }; var sortConversationList = function sortConversationList(conversationList) { if (utils.isEmpty(conversationList)) { return []; } return utils.quickSort(conversationList, function (before, after) { before = before || {}; after = after || {}; var beforeLatestMessage = before.latestMessage || {}, afterLatestMessage = after.latestMessage || {}, beforeLatestSentTime = beforeLatestMessage.sentTime || 0, afterLatestSentTime = afterLatestMessage.sentTime || 0; var flag = false; if (before.isTop && !after.isTop) { flag = false; } else if (!before.isTop && after.isTop) { flag = true; } else { flag = afterLatestSentTime <= beforeLatestSentTime; } return flag; }); }; var splitConversationListByIsTop = function splitConversationListByIsTop(conversationList) { var topConversationList = [], unToppedConversationList = []; utils.forEach(conversationList, function (conversation) { var hasMentiond = conversation.hasMentiond, mentiondInfo = conversation.mentiondInfo; conversation.hasMentioned = hasMentiond; conversation.mentionedInfo = mentiondInfo; var isTop = conversation.isTop || false; if (isTop) { topConversationList.push(conversation); } else { unToppedConversationList.push(conversation); } }); return { topConversationList: topConversationList || [], unToppedConversationList: unToppedConversationList || [] }; }; var sortConList = function sortConList(conversationList) { if (utils.isEmpty(conversationList)) { return []; } var splitConversationList = splitConversationListByIsTop(conversationList); var _sortListBySentTime = function _sortListBySentTime(convers) { return utils.quickSort(convers, function (before, after) { before = before || {}; after = after || {}; var beforeLatestMessage = before.latestMessage || {}, afterLatestMessage = after.latestMessage || {}, beforeLatestSentTime = beforeLatestMessage.sentTime || 0, afterLatestSentTime = afterLatestMessage.sentTime || 0; return afterLatestSentTime <= beforeLatestSentTime; }); }; var topConversationList = _sortListBySentTime(splitConversationList.topConversationList); var unToppedConversationList = _sortListBySentTime(splitConversationList.unToppedConversationList); topConversationList.push.apply(topConversationList, unToppedConversationList); return topConversationList; }; var isSupportStatusMessage = function isSupportStatusMessage(type) { return !!CONVERSATION_TYPE_TO_PUBLISH_STATUS_TOPIC[type]; }; var getConversationKey = function getConversationKey(option) { var type = option.type, targetId = option.targetId; return type + '_' + targetId; }; var getConversationByKey = function getConversationByKey(key) { key = key || ''; var arr = key.split('_'); if (arr.length === 2) { return { type: arr[0], targetId: arr[1] }; } else { return { type: CONVERSATION_TYPE.PRIVATE, targetId: '' }; } }; var getChatRoomKVOptStatus = function getChatRoomKVOptStatus(entity, action) { var status = 0; if (entity.isAutoDelete) { status = status | CHATROOM_KV_STATUS_CODE.AUTO_DELETE; } if (entity.isOverwrite) { status = status | CHATROOM_KV_STATUS_CODE.OVERWRITE; } if (utils.isEqual(action, CHATROOM_ENTRY_TYPE.DELETE)) { status = status | CHATROOM_KV_STATUS_CODE.OPERATE; } return status; }; var getChatRoomKVByStatus = function getChatRoomKVByStatus(status) { var isDeleteOpt = !!(status & CHATROOM_KV_STATUS_CODE.OPERATE); return { isAutoDelete: !!(status & CHATROOM_KV_STATUS_CODE.AUTO_DELETE), isOverwrite: !!(status & CHATROOM_KV_STATUS_CODE.OVERWRITE), type: isDeleteOpt ? CHATROOM_ENTRY_TYPE.DELETE : CHATROOM_ENTRY_TYPE.UPDATE }; }; var TextCompressor = { _dataType: { Tail: 0x30, Compressed: 0x40, NormalExt: 0x50, Normal: 0x60, Mark: 0x70 }, _chars: '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz', _scale: 62, _max: 238327, _indexOf: function _indexOf(map, source, fromIndex) { var result = { length: 0, offset: -1 }; if (fromIndex >= source.length - 1) { return result; } var c1 = source.charAt(fromIndex); var c2 = source.charAt(fromIndex + 1); var items = map[c1 + c2]; if (items[0] === fromIndex) { return result; } var space1 = source.length - fromIndex; for (var i = 0, len = items.length; i < len; i++) { var item = items[i]; var space2 = fromIndex - item; if (space2 > TextCompressor._max) { continue; } var end = Math.min(space1, space2); if (end <= result.length) { break; } if (result.length > 2) { if (source.charAt(item + result.length - 1) !== source.charAt(fromIndex + result.length - 1)) { continue; } } var m = 2; for (var j = m; j < end; j++) { if (source.charAt(item + j) === source.charAt(fromIndex + j)) { m++; } else { break; } } if (m >= result.length) { result.length = m; result.offset = item; } } return result; }, _numberEncode: function _numberEncode(num) { var result = [], remainder = 0; do { remainder = num % TextCompressor._scale; result.push(TextCompressor._chars.charAt(remainder)); num = (num - remainder) / TextCompressor._scale; } while (num > 0); return result.join(''); }, _numberDecode: function _numberDecode(str) { var num = 0, index = 0; for (var i = str.length - 1; i >= 0; i--) { index = TextCompressor._chars.indexOf(str.charAt(i)); if (index === -1) { throw new Error('decode number error, data is \'' + str + '\''); } num = num * TextCompressor._scale + index; } return num; }, compress: function compress(data) { var map = {}; for (var p = 0; p < data.length - 1; p++) { var c1 = data.charAt(p); var c2 = data.charAt(p + 1); var c = c1 + c2; if (!map.hasOwnProperty(c)) { map[c] = [p]; continue; } map[c].push(p); } var compressedData = [], normalBlockBuffer = []; var encodeNormalBlock = function encodeNormalBlock() { if (normalBlockBuffer.length > 0) { var normalBlock = normalBlockBuffer.join(''); normalBlockBuffer = []; if (normalBlock.length > 26) { var normalExtBlockLength = TextCompressor._numberEncode(normalBlock.length); var normalExtBlockHeader = String.fromCharCode(TextCompressor._dataType.NormalExt | normalExtBlockLength.length); compressedData.push(normalExtBlockHeader + normalExtBlockLength); } else { var normalBlockHeader = String.fromCharCode(TextCompressor._dataType.Normal | normalBlock.length); compressedData.push(normalBlockHeader); } compressedData.push(normalBlock); } }; var i = 0; while (i < data.length) { var r = TextCompressor._indexOf(map, data, i); if (r.length < 2) { normalBlockBuffer.push(data.charAt(i++)); continue; } if (r.length < 4) { normalBlockBuffer.push(data.substr(i, r.length)); i += r.length; continue; } var offset = TextCompressor._numberEncode(i - r.offset); var length = TextCompressor._numberEncode(r.length); if (offset.length + length.length >= r.length) { normalBlockBuffer.push(data.substr(i, r.length)); i += r.length; continue; } encodeNormalBlock(); var compressedBlockHeader = String.fromCharCode(TextCompressor._dataType.Compressed | offset.length << 2 | length.length); compressedData.push(compressedBlockHeader + offset + length); i += r.length; } encodeNormalBlock(); var dataLengthTo62 = TextCompressor._numberEncode(data.length); var tailBlockHeader = String.fromCharCode(TextCompressor._dataType.Tail | dataLengthTo62.length); compressedData.push(tailBlockHeader + dataLengthTo62); return compressedData.join(''); }, uncompress: function uncompress(data) { var i = 0; var result = ''; label1: do { var header = data.charCodeAt(i++); var headerType = header & TextCompressor._dataType.Mark; var headerVal = header & 0xF; switch (headerType) { case TextCompressor._dataType.Compressed: var p1 = headerVal >> 2; var p2 = headerVal & 3; if (p1 === 0 || p2 === 0) { throw new Error('Data parsing error,at ' + i); } var offset = TextCompressor._numberDecode(data.substr(i, p1)); var len = TextCompressor._numberDecode(data.substr(i += p1, p2)); offset = result.length - offset; if (offset + len > result.length) { throw new Error('Data parsing error,at ' + i); } i += p2; result += result.substr(offset, len); break; case TextCompressor._dataType.Tail: var num = TextCompressor._numberDecode(data.substr(i, headerVal)); if (num !== result.length) { throw new Error('Data parsing error,at ' + i); } i += headerVal; break label1; case TextCompressor._dataType.NormalExt: var normalNum = TextCompressor._numberDecode(data.substr(i, headerVal)); result += data.substr(i += headerVal, normalNum); i += normalNum; break; case TextCompressor._dataType.Normal: result += data.substr(i, headerVal); i += headerVal; break; case TextCompressor._dataType.Mark: if (headerVal > 10) { throw new Error('Data parsing error,at ' + i); } result += data.substr(i, 16 + headerVal); i += 16 + headerVal; break; default: throw new Error('Data parsing error,at ' + i + ' header:' + headerType); } } while (i < data.length); return result; } }; var isBelowIE = function isBelowIE(version) { var system = env.system; var flag = system.model === 'IE' && Number(system.version) < version ? true : false; return flag; }; var stringToCsv = function stringToCsv(str) { var csvStr = str.replace(/"/g, '""'); var tpl = '"{csvStr}"'; return tplEngine$1(tpl, { csvStr: csvStr }); }; var getWebSessionId = function getWebSessionId() { var sessionId = utils.Session.get(STORAGE_SESSION_ID_KEY); if (utils.isEmpty(sessionId)) { sessionId = utils.getUUID22().slice(0, 10); utils.Session.set(STORAGE_SESSION_ID_KEY, sessionId); } return sessionId; }; var getDeviceId = function getDeviceId() { var deviceId = utils.Storage.get(STORAGE_DEVICE_ID_KEY); if (utils.isEmpty(deviceId)) { deviceId = utils.getUUID22(); utils.Storage.set(STORAGE_DEVICE_ID_KEY, deviceId); } return deviceId; }; var getDeviceInfo = function getDeviceInfo() { var tpl = '{brower}|{version}|{sessionId}'; return tplEngine$1(tpl, { brower: env.system.model, version: env.system.version, sessionId: getWebSessionId() }); }; var getReportLogUrl = function getReportLogUrl(params) { var entireUrl = '', protocol = env.protocol.http + '//'; var urlConf = { protocol: protocol, url: params.url, version: SDK_VERSION, appkey: params.appkey, deviceId: getDeviceId(), deviceInfo: getDeviceInfo(), platform: PLATFORM$1, userId: params.userId }; switch (params.type) { case REPORT_TYPE.REALTIME: entireUrl = tplEngine$1(REALTIME_URL_TPL, urlConf); break; case REPORT_TYPE.FULL: entireUrl = tplEngine$1(MSGNOTIF_URL_TPL, utils.extend(urlConf, { logId: params.logId })); break; default: break; } return entireUrl; }; var isLogCommandMsg = function isLogCommandMsg(msg) { var content = msg.content; return msg.messageType === MESSAGE_TYPE.LOG_COMMAND && msg.senderUserId === LOG_CMD_MSG_SENDER && content.platform === 'Web'; }; var isValidChatRoomKey = function isValidChatRoomKey(key) { if (!utils.isString(key)) { return; } var isValid = /^[A-Za-z0-9_=+-]+$/.test(key), keyLen = key.length, isLimit = keyLen <= CHATROOM_KEY_LENGTH.MAX && keyLen >= CHATROOM_KEY_LENGTH.MIN; return isValid && isLimit; }; var isValidChatRoomValue = function isValidChatRoomValue(value) { if (!utils.isString(value)) { return; } var valLen = value.length; return valLen <= CHATROOM_VALUE_LENGTH.MAX && valLen >= CHATROOM_VALUE_LENGTH.MIN; }; var genUploadFileName = function genUploadFileName(type, fileName) { var tpl = '{type}__RC-{date}_{random}_{timestamp}{uuid}{extension}'; var random = Math.floor(Math.random() * 1000 % 10000); var uuid = utils.getUUID(); var fileNameArr, extension; if (fileName) { fileNameArr = fileName.split('.'); extension = '.' + fileNameArr[fileNameArr.length - 1]; } return tplEngine$1(tpl, { type: type, date: utils.formateDate('-'), random: random, uuid: uuid, timestamp: DelayTimer.getTime(), extension: extension || '' }); }; var getUploadFileDomains = function getUploadFileDomains(navi) { var uploadServer = navi.uploadServer, bosAddr = navi.bosAddr; return { qiniu: uploadServer, bos: bosAddr }; }; var mergeConversationList = function mergeConversationList(option) { option = option || {}; var _option4 = option, conversationList = _option4.conversationList, updatedConversationList = _option4.updatedConversationList; var allConversationList = updatedConversationList.concat(conversationList); var hashTable = {}; var newList = []; var invalidDataIndexList = []; utils.forEach(allConversationList, function (conversation) { if (!utils.isObject(conversation)) { return; } var key = getConversationKey(conversation), hashItem = hashTable[key] || {}, hashIndex = utils.isUndefined(hashItem.index) ? newList.length : hashItem.index, hashVal = hashItem.val || {}, cacheUpdatedItems = hashVal.updatedItems || {}, updatedItems = conversation.updatedItems || {}; conversation = utils.extend(conversation, hashVal); utils.forEach(cacheUpdatedItems, function (item, key) { conversation[key] = item.val; }); utils.forEach(updatedItems, function (item, key) { var cacheItem = cacheUpdatedItems[key] || {}, cacheItemUpdatedTime = cacheItem.time || 0; if (item.time > cacheItemUpdatedTime) { conversation[key] = item.val; } }); hashTable[key] = { index: hashIndex, val: conversation }; newList[hashIndex] = conversation; isInValidConversationData(conversation) && invalidDataIndexList.push(hashIndex); }); utils.forEach(invalidDataIndexList, function (invalidIndex) { var conversation = newList[invalidIndex]; newList[invalidIndex] = fixConversationData(conversation); }); newList = sortConList(newList); return utils.map(newList, function (item) { delete item.updatedItems; return item; }); }; var common = { isConnected: isConnected, isConnecting: isConnecting, isDisconnected: isDisconnected, getConnectType: getConnectType, getTransporterUrl: getTransporterUrl, isGroup: isGroup, isChatRoom: isChatRoom, getConversationTypeList: getConversationTypeList, isValidConversationType: isValidConversationType, getUIDByToken: getUIDByToken, getSessionId: getSessionId, getMessageOptionByStatus: getMessageOptionByStatus, SignalId: SignalId, MessageTimeSyner: MessageTimeSyner, ChatRoomMessageTimeSyner: ChatRoomMessageTimeSyner, JoinedChatRoomSyner: JoinedChatRoomSyner, getCMPDomainList: getCMPDomainList, getNaviListByToken: getNaviListByToken, getValidToken: getValidToken, RCSocket: RCSocket, RCStorage: RCStorage, getNavReqOption: getNavReqOption, getPingTimeout: getPingTimeout, fixConversationData: fixConversationData, sortConversationList: sortConversationList, DelayTimer: DelayTimer, isSupportStatusMessage: isSupportStatusMessage, getConversationKey: getConversationKey, getConversationByKey: getConversationByKey, getChatRoomKVOptStatus: getChatRoomKVOptStatus, getChatRoomKVByStatus: getChatRoomKVByStatus, TextCompressor: TextCompressor, isBelowIE: isBelowIE, getReportLogUrl: getReportLogUrl, isLogCommandMsg: isLogCommandMsg, getWebSessionId: getWebSessionId, getDeviceId: getDeviceId, stringToCsv: stringToCsv, isValidChatRoomKey: isValidChatRoomKey, isValidChatRoomValue: isValidChatRoomValue, genUploadFileName: genUploadFileName, getUploadFileDomains: getUploadFileDomains, mergeConversationList: mergeConversationList, sortConList: sortConList, getUpMessageOptionBySessionId: getUpMessageOptionBySessionId }; var EventEmitter$1 = utils.EventEmitter, DeferHandler$1 = utils.DeferHandler, Timer$1 = utils.Timer; var RCSocket$1 = common.RCSocket; var TransHandlerID = { CONNECT: 'connect', PING: 'ping' }; var Heartbeat = function () { function Heartbeat(transporter, option) { this._transporter = void 0; this._timer = void 0; option = option || {}; var timeout = option.timeout; this._transporter = transporter; this._timer = new Timer$1({ type: TIMER_TYPE.INTERVAL, timeout: timeout }); } var _proto = Heartbeat.prototype; _proto.check = function check(timeout) { var _transporter = this._transporter; var _deferHandler = _transporter._deferHandler; var pingReqSignal = new PingReqWriter(); _transporter.sendSignal(pingReqSignal); return utils.deferred(function (resolve, reject) { _deferHandler.add(TransHandlerID.PING, { resolve: resolve, reject: reject }, { timeout: timeout }); }); }; _proto.start = function start(timeout, onError) { var self = this; self._timer.start(function () { self.check(timeout).then(utils.noop)["catch"](onError); }); }; _proto.stop = function stop() { this._timer && this._timer.stop(); }; return Heartbeat; }(); var SocketTransporter = function () { function SocketTransporter(option) { this._socket = void 0; this._option = void 0; this._transporterEventEmiiter = new EventEmitter$1(); this._deferHandler = new DeferHandler$1(); this._heartbeat = new Heartbeat(this, { timeout: IM_PING_INTERVAL_TIME }); this._connectedTime = void 0; this._timer = void 0; this._option = option; this._timer = new Timer$1({ type: TIMER_TYPE.TIMEOUT, timeout: CMP_CONNECT_TIMEOUT_TIME }); } var _proto2 = SocketTransporter.prototype; _proto2._createSocket = function _createSocket(url) { var self = this; var _transporterEventEmiiter = self._transporterEventEmiiter; var socket = new RCSocket$1({ url: url }); var onClose = function onClose(event) { event = event || {}; var code = event.code || TRANSPORTER_STATUS.CLOSE_ABNORMAL; _transporterEventEmiiter.emit(TRANSPORT_EVENT.STATUS, code); self.disconnect(); }; socket.onMessage(function (msg) { var data = msg.data; if (!utils.isArrayBuffer(data)) { throw new Error('Error socket signal'); } var signal = readWSBuffer(data); self.handleSignal(signal); }); socket.onError(onClose); socket.onClose(onClose); return socket; }; _proto2._startHeartbeat = function _startHeartbeat(timeSpentConnect) { var self = this; var _heartbeat = self._heartbeat, _transporterEventEmiiter = self._transporterEventEmiiter; _heartbeat.check(FIRST_PING_TIMEOUT).then(utils.noop)["catch"](function () { _transporterEventEmiiter.emit(TRANSPORT_EVENT.STATUS, TRANSPORTER_STATUS.PING_FIRST_TIMEOUT); self.disconnect(); }); var pingTimeout = common.getPingTimeout(timeSpentConnect); _heartbeat.start(pingTimeout, function () { _transporterEventEmiiter.emit(TRANSPORT_EVENT.STATUS, TRANSPORTER_STATUS.PING_TIMEOUT); self.disconnect(); }); }; _proto2._stopHeartbeat = function _stopHeartbeat() { this._heartbeat.stop(); }; _proto2.watchSignal = function watchSignal(watcher) { this._transporterEventEmiiter.on(TRANSPORT_EVENT.SIGNAL, watcher); }; _proto2.watchStatus = function watchStatus(watcher) { this._transporterEventEmiiter.on(TRANSPORT_EVENT.STATUS, watcher); }; _proto2.connect = function connect(user, option) { var self = this; var _self$_option = self._option, appkey = _self$_option.appkey, connectType = _self$_option.connectType, _deferHandler = self._deferHandler; var token = user.token; var domain = option.domain; var url = common.getTransporterUrl({ domain: domain, appkey: appkey, connectType: connectType, token: token }); var timeBeforeConnect = utils.getCurrentTimestamp(); self._socket = this._createSocket(url); self._timer.start(function () { self.disconnect(); _deferHandler.reject(TransHandlerID.CONNECT, { status: TRANSPORTER_STATUS.CMP_CONNECTION_TIMEOUT }); }); return utils.deferred(function (resolve, reject) { _deferHandler.add(TransHandlerID.CONNECT, { resolve: resolve, reject: reject }); }).then(function (result) { var timeAfterConnect = utils.getCurrentTimestamp(); var timeSpentConnect = timeAfterConnect - timeBeforeConnect; self._startHeartbeat(timeSpentConnect); self._timer.stop(); return result; }); }; _proto2.sendSignal = function sendSignal(writer) { var binary = writer.getBufferData(); this._socket.send(binary.buffer); }; _proto2.handleSignal = function handleSignal(signal) { var _transporterEventEmiiter = this._transporterEventEmiiter, _deferHandler = this._deferHandler; if (signal instanceof ConnAckReader) { this.handleConnAck(signal); } else if (signal instanceof PingRespReader) { _deferHandler.resolve(TransHandlerID.PING); } else { _transporterEventEmiiter.emit(TRANSPORT_EVENT.SIGNAL, signal); } if (signal && utils.isValidTimestamp(signal.timestamp)) { common.DelayTimer.setTime(signal.timestamp); } }; _proto2.handleConnAck = function handleConnAck(signal) { var self = this; var _deferHandler = self._deferHandler; var status = signal.status; var isConnected = status === SUCCESS_CODE; var event = isConnected ? _deferHandler.resolve : _deferHandler.reject; event.call(_deferHandler, TransHandlerID.CONNECT, signal); if (isConnected) { self._connectedTime = utils.getCurrentTimestamp(); } }; _proto2.disconnect = function disconnect() { this._stopHeartbeat(); this._socket && this._socket.close(); }; return SocketTransporter; }(); var logEventEmitter = new utils.EventEmitter(); var LogEventName = 'log'; var LocalLogPrefix = '[Rong]'; var ServerOption = DEFAULT_SERVER_OPTION; var Option = { isDebug: false, isUploadToServer: true, appkey: '', userId: '', isNetworkUnavailable: true }; var realTimeUploadHasStarted = false, RealtimeUploadTimes = 1, isRealtimeUploading = false, fullLogId = ''; var isFirstDefaultUpload = function isFirstDefaultUpload(interval) { return interval === 20000; }; var getRealtimeUploadInterval = function getRealtimeUploadInterval(uploadTimes) { var realtimeInterval = ServerOption.realtimeInterval; return realtimeInterval * Math.pow(2, uploadTimes - 1); }; var getFullUploadInterval = function getFullUploadInterval(uploadTimes) { var fullInterval = ServerOption.fullInterval; return fullInterval * Math.pow(2, uploadTimes - 1); }; var getCSVForLog = function getCSVForLog(log) { log = log || {}; var content = log.content || {}; utils.forEach(content, function (val, key) { if (utils.isObject(val) || utils.isArray(val)) { content[key] = utils.toJSON(val); } }); content = utils.toJSON(content) || '""'; content = common.stringToCsv(content); return utils.tplEngine(CSV_LOG_TPL, { sessionId: common.getWebSessionId(), time: log.time, type: log.type, level: log.level, tag: log.tag, content: content }); }; var setServerOption = function setServerOption(serverData) { var logSwitch = serverData.logSwitch, logPolicy = serverData.logPolicy; var isOpen = !!logSwitch; if (utils.isEmpty(serverData)) return; ServerOption.isOpen = isOpen; if (!isOpen) { return; } var logConf = utils.parseJSON(logPolicy || '') || {}; var url = logConf.url, level = logConf.level, itv = logConf.itv, times = logConf.times; utils.extend(ServerOption, { url: url, realtimeLevel: Number(level), realtimeInterval: Number(itv) * 1000, realtimeMaxTimes: Number(times) }); }; var setServerResponseOption = function setServerResponseOption(resText) { var resConf = utils.parseJSON(resText || ''); var nextTime = resConf.nextTime, level = resConf.level, logSwitch = resConf.logSwitch; if (utils.isEmpty(resConf)) return; var isOpen = !!logSwitch; ServerOption.isOpen = isOpen; if (!isOpen) return; utils.extend(ServerOption, { realtimeLevel: Number(level), realtimeInterval: Number(nextTime) * 1000 }); }; var getLogLevel = function getLogLevel(log) { log = log || {}; var _Option = Option, isNetworkUnavailable = _Option.isNetworkUnavailable, _log = log, level = _log.level, isLevelToDegrad = utils.isEqual(level, LEVEL.ERROR) || utils.isEqual(level, LEVEL.WARN); if (isNetworkUnavailable && isLevelToDegrad) { log.level = LEVEL.INFO; } return log; }; var LogStore = { _list: [], MaxSize: common.isBelowIE(9) ? STORE_SIZE.LOW : STORE_SIZE.ADVANCED, add: function add(log) { log = getLogLevel(log); LogStore._list.push(log); var currentSize = LogStore._list.length, maxSize = LogStore.MaxSize; if (currentSize > maxSize) { LogStore._list.splice(0, currentSize - maxSize); } }, get: function get(option) { var type = option.type, uploadLevel = option.level; var _list = LogStore._list; var uploadList = []; utils.forEach(_list, function (log, index) { var logTime = log.time || 0, logLevel = log.level || LEVEL.DEBUG, isUploadLevel = logLevel <= uploadLevel, fullUploadOption = option.fullUploadOption || {}, startTime = fullUploadOption.startTime || 0, endTime = fullUploadOption.endTime || common.DelayTimer.getTime(); var isUpload = isUploadLevel; switch (type) { case REPORT_TYPE.REALTIME: isUpload = isUpload && !log.isUploaded; isUpload && (LogStore._list[index].isUploaded = true); break; case REPORT_TYPE.FULL: isUpload = isUpload && logTime >= startTime && logTime <= endTime; break; default: } if (isUpload) { uploadList.push(log); } }); return uploadList; }, clear: function clear() { LogStore._list = []; } }; var upload = function upload(option) { var url = option.url, logList = option.logList, type = option.type; var requestUrl = common.getReportLogUrl({ type: type, appkey: Option.appkey || '', userId: Option.userId || '', url: url || ServerOption.url || DEFAULT_SERVER_OPTION.url, logId: option.logId }); var csvLog = ''; utils.forEach(logList, function (log) { csvLog += getCSVForLog(log); }); if (utils.isEmpty(csvLog) && type === REPORT_TYPE.REALTIME) { return utils.Defer.reject(); } if (utils.isEmpty(csvLog) && type === REPORT_TYPE.FULL) { csvLog = NO_FULL_LOG; } csvLog = common.TextCompressor.compress(csvLog); return utils.request(requestUrl, { method: REQUEST_METHOD.POST, body: csvLog, timeout: REQUEST_TIMEOUT }); }; var uploadRealtime = function uploadRealtime() { if (isRealtimeUploading) { return; } var interval = getRealtimeUploadInterval(RealtimeUploadTimes); var realtimeMaxTimes = ServerOption.realtimeMaxTimes, realtimeLevel = ServerOption.realtimeLevel; if (RealtimeUploadTimes < realtimeMaxTimes) { RealtimeUploadTimes++; } if (isFirstDefaultUpload(interval)) { RealtimeUploadTimes = 1; } utils.setTimeout(function () { var logList = LogStore.get({ type: REPORT_TYPE.REALTIME, level: realtimeLevel }); isRealtimeUploading = true; upload({ logList: logList, type: REPORT_TYPE.REALTIME }).then(function (response) { isRealtimeUploading = false; var responseText = response.responseText || '{}'; var conf = response.responseText || {}; setServerResponseOption(responseText); if (ServerOption.isOpen) { RealtimeUploadTimes = utils.isEmpty(conf) ? RealtimeUploadTimes : 1; uploadRealtime(); } })["catch"](function () { isRealtimeUploading = false; uploadRealtime(); }); }, interval); }; var uploadFull = function uploadFull(uploadTimes, option, connectedTime) { if (!Option.isUploadToServer || env.isMini) { return; } uploadTimes = uploadTimes || 0; option = option || {}; var _option = option, uri = _option.uri, logId = _option.logId; var isFirst = uploadTimes === 0; var interval = isFirst ? 0 : getFullUploadInterval(uploadTimes); var fullMaxTimes = ServerOption.fullMaxTimes, fullLevel = ServerOption.fullLevel; if (fullLogId === logId) return; if (uploadTimes <= fullMaxTimes) { uploadTimes++; } else { return; } fullLogId = logId; (function (option) { utils.setTimeout(function () { var logList = LogStore.get({ type: REPORT_TYPE.FULL, level: fullLevel, fullUploadOption: option }); if (logList.length === 0 && Number(option.endTime) < connectedTime) return; upload({ logId: logId, url: uri, logList: logList, type: REPORT_TYPE.FULL }).then(function () {})["catch"](function () { uploadFull(uploadTimes, option, connectedTime); }); }, interval); })(option); }; var writeLocalLog = function writeLocalLog(log) { var time = log.time; var formatedTime = utils.formatTime(time); var localLog = LocalLogPrefix + ":" + formatedTime + ": " + utils.toJSON(log); logEventEmitter.emit(LogEventName, localLog); if (Option.isDebug) { utils.consoleLog(localLog); } }; var isIgnoreErrorCode = function isIgnoreErrorCode(code) { return utils.indexOf(IGNORE_ERROR_CODE, code) > -1; }; var Logger = { _events: [], LogStore: LogStore, setOption: function setOption(option) { Option = utils.extend(Option, option); }, setServerOption: setServerOption, watchLog: function watchLog(event) { logEventEmitter.on(LogEventName, event); Logger._events.push(event); }, write: function write(log) { log = log || {}; log.tag = log.tag || TAG.L_CRASH_E; log.time = log.time || common.DelayTimer.getTime(); log.type = log.type || LOG_TYPE.IM; LogStore.add(log); writeLocalLog(log); }, fatal: function fatal(tag, content) { Logger.write({ tag: tag, content: content, level: LEVEL.FATAL }); }, error: function error(tag, content) { Logger.write({ tag: tag, content: content, level: LEVEL.ERROR }); }, warn: function warn(tag, content) { Logger.write({ tag: tag, content: content, level: LEVEL.WARN }); }, info: function info(tag, content) { Logger.write({ tag: tag, content: content, level: LEVEL.INFO }); }, debug: function debug(tag, content) { Logger.write({ tag: tag, content: content, level: LEVEL.DEBUG }); }, startRealtimeUpload: function startRealtimeUpload() { if (realTimeUploadHasStarted) return; if (Option.isUploadToServer && !env.isMini) { uploadRealtime(); } realTimeUploadHasStarted = true; }, resetRealtimeUpload: function resetRealtimeUpload() { RealtimeUploadTimes = 1; }, uploadFull: uploadFull, isIgnoreErrorCode: isIgnoreErrorCode }; var EventEmitter$2 = utils.EventEmitter, DeferHandler$2 = utils.DeferHandler, httpRequest = utils.httpRequest, request$3 = utils.request, Defer$1 = utils.Defer; var CometTransporter = function () { function CometTransporter(option) { this._option = void 0; this._transporterEventEmiiter = new EventEmitter$2(); this._deferHandler = new DeferHandler$2(); this._pid = utils.encodeURI(utils.getCurrentTimestamp() + Math.random() + ''); this._domain = void 0; this._sessionid = void 0; this._xhrCache = new utils.Cache(); this._pullSignalTimer = new utils.Timer({ timeout: IM_COMET_PULLMSG_TIMEOUT }); this._isDisconnected = true; this._option = option; } var _proto = CometTransporter.prototype; _proto._startPullSignal = function _startPullSignal() { var self = this; var _domain = self._domain, _sessionid = self._sessionid, _pid = self._pid, _transporterEventEmiiter = self._transporterEventEmiiter, _pullSignalTimer = self._pullSignalTimer; var timestamp = utils.getCurrentTimestamp(); var protocol = env.protocol.http; var url = utils.tplEngine(COMET_PULL_URL_TPL, { protocol: protocol, timestamp: timestamp, domain: _domain, sessionId: _sessionid, pid: _pid }); var xhr = httpRequest({ url: url, body: { pid: _pid }, timeout: IM_COMET_PULLMSG_TIMEOUT, success: function success(responseText) { _pullSignalTimer.stop(); var isSuccess = self.handleCometResponse(responseText); if (isSuccess) { !self._isDisconnected && self._startPullSignal(); } else if (!self._isDisconnected) { _transporterEventEmiiter.emit(TRANSPORT_EVENT.STATUS, TRANSPORTER_STATUS.COMET_REQUEST_ERROR); } self._xhrCache.remove(url); }, fail: function fail() { _pullSignalTimer.stop(); if (!self._isDisconnected) { _transporterEventEmiiter.emit(TRANSPORT_EVENT.STATUS, TRANSPORTER_STATUS.COMET_REQUEST_ERROR); } self._xhrCache.remove(url); } }); _pullSignalTimer.start(function () { if (!self._isDisconnected) { _transporterEventEmiiter.emit(TRANSPORT_EVENT.STATUS, TRANSPORTER_STATUS.PING_TIMEOUT); self.disconnect(); } }); self._xhrCache.set(url, xhr); }; _proto.watchSignal = function watchSignal(event) { this._transporterEventEmiiter.on(TRANSPORT_EVENT.SIGNAL, event); }; _proto.watchStatus = function watchStatus(event) { this._transporterEventEmiiter.on(TRANSPORT_EVENT.STATUS, function (status) { event && event(status); }); }; _proto.connect = function connect(user, option) { var self = this; var _pid = self._pid, _self$_option = self._option, appkey = _self$_option.appkey, connectType = _self$_option.connectType; var token = user.token; var domain = option.domain; var url = common.getTransporterUrl({ domain: domain, appkey: appkey, token: token, connectType: connectType }); self._domain = domain; self._isDisconnected = false; var success = function success(_ref) { var responseText = _ref.responseText; if (!utils.isValidJSON(responseText)) { return Defer$1.reject(); } var response = utils.isObject(responseText) ? responseText : utils.parseJSON(responseText); var isConnectSuccess = utils.isEqual(response.status, SUCCESS_CODE); if (isConnectSuccess && utils.isObject(response) && utils.isValidTimestamp(response.timestamp)) { common.DelayTimer.setTime(response.timestamp); } return isConnectSuccess ? Defer$1.resolve(response) : Defer$1.reject(response); }; return request$3(url, { body: { pid: _pid } }).then(success).then(function (response) { self._sessionid = response.sessionid; self._startPullSignal(); return response; }); }; _proto.sendSignal = function sendSignal(writer) { var self = this; var _domain = self._domain, _sessionid = self._sessionid, _pid = self._pid; var messageId = writer.messageId, topic = writer.topic, targetId = writer.targetId; var headerCode = writer.getHeaderFlag(); var protocol = env.protocol.http; var TPL = topic ? COMET_REQ_HAS_TOPIC_URL_TPL : COMET_REQ_NO_TOPIC_URL_TPL; var url = utils.tplEngine(TPL, { protocol: protocol, messageId: messageId, headerCode: headerCode, topic: topic, targetId: targetId, pid: _pid, sessionId: _sessionid, domain: _domain }); var currentTime = utils.getCurrentTimestamp() + ''; var xhr = httpRequest({ url: url, method: REQUEST_METHOD.POST, body: writer.getCometData(), success: function success(responseText) { var isSuccess = self.handleCometResponse(responseText); if (!isSuccess) { self.handleError(messageId); } self._xhrCache.remove(currentTime); }, fail: function fail(error) { self.handleError(messageId); self._xhrCache.remove(currentTime); Logger.error(TAG.L_COMET_SEND_SIGNAL_E, { content: { info: 'comet error', error: error } }); } }); self._xhrCache.set(currentTime, xhr); }; _proto.handleCometResponse = function handleCometResponse(responseText) { var self = this; var _transporterEventEmiiter = self._transporterEventEmiiter; var response = utils.isString(responseText) ? utils.parseJSON(responseText) : responseText; if (!response) { return false; } if (!response || !utils.isArray(response)) { return true; } utils.forEach(response, function (data) { var sessionid = data.sessionid; if (sessionid) { self._sessionid = sessionid; } var signal = readCometData(data); _transporterEventEmiiter.emit(TRANSPORT_EVENT.SIGNAL, signal); if (signal && utils.isValidTimestamp(signal.timestamp)) { common.DelayTimer.setTime(signal.timestamp); } }); return true; }; _proto.handleError = function handleError(messageId, status) { var signal = { messageId: messageId, status: status || ERROR_CODE.TIMEOUT }; this._transporterEventEmiiter.emit(TRANSPORT_EVENT.SIGNAL, signal); }; _proto.disconnect = function disconnect() { var self = this; self._isDisconnected = true; var _xhrCache = self._xhrCache, _pullSignalTimer = self._pullSignalTimer; var xhrKeys = _xhrCache.getKeys(); _pullSignalTimer.stop(); utils.forEach(xhrKeys, function (key) { var xhr = _xhrCache.get(key); xhr.abort(); _xhrCache.remove(key); }); }; return CometTransporter; }(); var Transporter = (function (option) { var connectType = option.connectType; var isSocket = connectType === CONNECT_TYPE.WEBSOCKET; var Transporter = isSocket ? SocketTransporter : CometTransporter; return new Transporter(option); }); var PBName = { UpStreamMessage: 'UpStreamMessage', DownStreamMessage: 'DownStreamMessage', DownStreamMessages: 'DownStreamMessages', SessionsAttQryInput: 'SessionsAttQryInput', SessionsAttOutput: 'SessionsAttOutput', SyncRequestMsg: 'SyncRequestMsg', ChrmPullMsg: 'ChrmPullMsg', NotifyMsg: 'NotifyMsg', HistoryMsgInput: 'HistoryMsgInput', HistoryMsgOuput: 'HistoryMsgOuput', RelationQryInput: 'RelationQryInput', RelationsOutput: 'RelationsOutput', DeleteSessionsInput: 'DeleteSessionsInput', SessionInfo: 'SessionInfo', DeleteSessionsOutput: 'DeleteSessionsOutput', RelationsInput: 'RelationsInput', DeleteMsgInput: 'DeleteMsgInput', CleanHisMsgInput: 'CleanHisMsgInput', SessionMsgReadInput: 'SessionMsgReadInput', ChrmInput: 'ChrmInput', QueryChatRoomInfoInput: 'QueryChatRoomInfoInput', QueryChatRoomInfoOutput: 'QueryChatRoomInfoOutput', RtcInput: 'RtcInput', RtcUserListOutput: 'RtcUserListOutput', SetUserStatusInput: 'SetUserStatusInput', RtcSetDataInput: 'RtcSetDataInput', RtcUserSetDataInput: 'RtcUserSetDataInput', RtcDataInput: 'RtcDataInput', RtcSetOutDataInput: 'RtcSetOutDataInput', MCFollowInput: 'MCFollowInput', RtcTokenOutput: 'RtcTokenOutput', RtcQryOutput: 'RtcQryOutput', RtcQryUserOutDataInput: 'RtcQryUserOutDataInput', RtcUserOutDataOutput: 'RtcUserOutDataOutput', RtcQueryListInput: 'RtcQueryListInput', RtcRoomInfoOutput: 'RtcRoomInfoOutput', RtcValueInfo: 'RtcValueInfo', RtcKeyDeleteInput: 'RtcKeyDeleteInput', GetQNupTokenInput: 'GetQNupTokenInput', GetQNupTokenOutput: 'GetQNupTokenOutput', GetQNdownloadUrlInput: 'GetQNdownloadUrlInput', GetQNdownloadUrlOutput: 'GetQNdownloadUrlOutput', SetChrmKV: 'SetChrmKV', ChrmKVOutput: 'ChrmKVOutput', QueryChrmKV: 'QueryChrmKV', ChrmNotifyMsg: 'ChrmNotifyMsg', SetUserSettingInput: 'SetUserSettingInput', SetUserSettingOutput: 'SetUserSettingOutput', PullUserSettingInput: 'PullUserSettingInput', PullUserSettingOutput: 'PullUserSettingOutput', UserSettingNotification: 'UserSettingNotification', SessionReq: 'SessionReq', SessionStates: 'SessionStates', SessionState: 'SessionState', SessionStateItem: 'SessionStateItem', SessionStateModifyReq: 'SessionStateModifyReq', SessionStateModifyResp: 'SessionStateModifyResp' }; var _SSMsg; var SSMsg = (_SSMsg = {}, _SSMsg[PBName.UpStreamMessage] = ['sessionId', 'classname', 'content', 'pushText', 'userId', 'configFlag', 'appData'], _SSMsg[PBName.DownStreamMessages] = ['list', 'syncTime', 'finished'], _SSMsg[PBName.DownStreamMessage] = ['fromUserId', 'type', 'groupId', 'classname', 'content', 'dataTime', 'status', 'msgId'], _SSMsg[PBName.SessionsAttQryInput] = ['nothing'], _SSMsg[PBName.SessionsAttOutput] = ['inboxTime', 'sendboxTime', 'totalUnreadCount'], _SSMsg[PBName.SyncRequestMsg] = ['syncTime', 'ispolling', 'isweb', 'isPullSend', 'isKeeping', 'sendBoxSyncTime'], _SSMsg[PBName.ChrmPullMsg] = ['syncTime', 'count'], _SSMsg[PBName.NotifyMsg] = ['type', 'time', 'chrmId'], _SSMsg[PBName.HistoryMsgInput] = ['targetId', 'time', 'count', 'order'], _SSMsg[PBName.HistoryMsgOuput] = ['list', 'syncTime', 'hasMsg'], _SSMsg[PBName.RelationQryInput] = ['type', 'count', 'startTime', 'order'], _SSMsg[PBName.RelationsOutput] = ['info'], _SSMsg[PBName.DeleteSessionsInput] = ['sessions'], _SSMsg[PBName.SessionInfo] = ['type', 'channelId'], _SSMsg[PBName.DeleteSessionsOutput] = ['nothing'], _SSMsg[PBName.RelationsInput] = ['type', 'msg', 'count', 'offset', 'startTime', 'endTime'], _SSMsg[PBName.DeleteMsgInput] = ['type', 'conversationId', 'msgs'], _SSMsg[PBName.CleanHisMsgInput] = ['targetId', 'dataTime', 'conversationType'], _SSMsg[PBName.SessionMsgReadInput] = ['type', 'msgTime', 'channelId'], _SSMsg[PBName.ChrmInput] = ['nothing'], _SSMsg[PBName.QueryChatRoomInfoInput] = ['count', 'order'], _SSMsg[PBName.QueryChatRoomInfoOutput] = ['userTotalNums', 'userInfos'], _SSMsg[PBName.GetQNupTokenInput] = ['type'], _SSMsg[PBName.GetQNdownloadUrlInput] = ['type', 'key', 'fileName'], _SSMsg[PBName.GetQNupTokenOutput] = ['deadline', 'token'], _SSMsg[PBName.GetQNdownloadUrlOutput] = ['downloadUrl'], _SSMsg[PBName.SetChrmKV] = ['entry', 'bNotify', 'notification', 'type'], _SSMsg[PBName.ChrmKVOutput] = ['entries', 'bFullUpdate', 'syncTime'], _SSMsg[PBName.QueryChrmKV] = ['timestamp'], _SSMsg[PBName.ChrmNotifyMsg] = ['type', 'time', 'chrmId'], _SSMsg[PBName.SetUserSettingInput] = ['version', 'value'], _SSMsg[PBName.SetUserSettingOutput] = ['version', 'reserve'], _SSMsg[PBName.PullUserSettingInput] = ['version', 'reserve'], _SSMsg[PBName.PullUserSettingOutput] = ['items', 'version'], _SSMsg); var Codec = {}; utils.forEach(SSMsg, function (paramList, name) { Codec[name] = function () {}; Codec[name].prototype.data = {}; Codec[name].prototype.getData = function () { return this.data; }; utils.forEach(paramList, function (param) { var setEventName = 'set' + utils.toUpperCase(param, 0, 1); Codec[name].prototype[setEventName] = function (item) { this.data[param] = item; }; }); Codec[name].decode = function (data) { var decodeResult = {}; if (utils.isString(data)) { data = utils.parseJSON(data); } var _loop = function _loop(key) { var getEventName = 'get' + utils.toUpperCase(key, 0, 1); decodeResult[key] = data[key]; decodeResult[getEventName] = function () { return data[key]; }; }; for (var key in data) { _loop(key); } return decodeResult; }; }); Codec.getModule = function (pbName) { var modules = new Codec[pbName](); modules.getArrayData = function () { return modules.getData(); }; return modules; }; function protobuf(a){var b=void 0,c=function(){function a(a,b,c){this.low=0|a,this.high=0|b,this.unsigned=!!c;}function b(a){return (a&&a.__isLong__)===!0}function e(a,b){var e,f,h;return b?(a>>>=0,(h=a>=0&&256>a)&&(f=d[a])?f:(e=g(a,0>(0|a)?-1:0,!0),h&&(d[a]=e),e)):(a|=0,(h=a>=-128&&128>a)&&(f=c[a])?f:(e=g(a,0>a?-1:0,!1),h&&(c[a]=e),e))}function f(a,b){if(isNaN(a)||!isFinite(a))return b?r:q;if(b){if(0>a)return r;if(a>=n)return w}else{if(-o>=a)return x;if(a+1>=o)return v}return 0>a?f(-a,b).neg():g(0|a%m,0|a/m,b)}function g(b,c,d){return new a(b,c,d)}function i(a,b,c){var d,e,g,j,k,l,m;if(0===a.length)throw Error("empty string");if("NaN"===a||"Infinity"===a||"+Infinity"===a||"-Infinity"===a)return q;if("number"==typeof b?(c=b,b=!1):b=!!b,c=c||10,2>c||c>36)throw RangeError("radix");if((d=a.indexOf("-"))>0)throw Error("interior hyphen");if(0===d)return i(a.substring(1),b,c).neg();for(e=f(h(c,8)),g=q,j=0;jk?(m=f(h(c,k)),g=g.mul(m).add(f(l))):(g=g.mul(e),g=g.add(f(l)));return g.unsigned=b,g}function j(b){return b instanceof a?b:"number"==typeof b?f(b):"string"==typeof b?i(b):g(b.low,b.high,b.unsigned)}var c,d,h,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y;return Object.defineProperty(a.prototype,"__isLong__",{value:!0,enumerable:!1,configurable:!1}),a.isLong=b,c={},d={},a.fromInt=e,a.fromNumber=f,a.fromBits=g,h=Math.pow,a.fromString=i,a.fromValue=j,k=65536,l=1<<24,m=k*k,n=m*m,o=n/2,p=e(l),q=e(0),a.ZERO=q,r=e(0,!0),a.UZERO=r,s=e(1),a.ONE=s,t=e(1,!0),a.UONE=t,u=e(-1),a.NEG_ONE=u,v=g(-1,2147483647,!1),a.MAX_VALUE=v,w=g(-1,-1,!0),a.MAX_UNSIGNED_VALUE=w,x=g(0,-2147483648,!1),a.MIN_VALUE=x,y=a.prototype,y.toInt=function(){return this.unsigned?this.low>>>0:this.low},y.toNumber=function(){return this.unsigned?(this.high>>>0)*m+(this.low>>>0):this.high*m+(this.low>>>0)},y.toString=function(a){var b,c,d,e,g,i,j,k,l;if(a=a||10,2>a||a>36)throw RangeError("radix");if(this.isZero())return "0";if(this.isNegative())return this.eq(x)?(b=f(a),c=this.div(b),d=c.mul(b).sub(this),c.toString(a)+d.toInt().toString(a)):"-"+this.neg().toString(a);for(e=f(h(a,6),this.unsigned),g=this,i="";;){if(j=g.div(e),k=g.sub(j.mul(e)).toInt()>>>0,l=k.toString(a),g=j,g.isZero())return l+i;for(;l.length<6;)l="0"+l;i=""+l+i;}},y.getHighBits=function(){return this.high},y.getHighBitsUnsigned=function(){return this.high>>>0},y.getLowBits=function(){return this.low},y.getLowBitsUnsigned=function(){return this.low>>>0},y.getNumBitsAbs=function(){var a,b;if(this.isNegative())return this.eq(x)?64:this.neg().getNumBitsAbs();for(a=0!=this.high?this.high:this.low,b=31;b>0&&0==(a&1<=0},y.isOdd=function(){return 1===(1&this.low)},y.isEven=function(){return 0===(1&this.low)},y.equals=function(a){return b(a)||(a=j(a)),this.unsigned!==a.unsigned&&1===this.high>>>31&&1===a.high>>>31?!1:this.high===a.high&&this.low===a.low},y.eq=y.equals,y.notEquals=function(a){return !this.eq(a)},y.neq=y.notEquals,y.lessThan=function(a){return this.comp(a)<0},y.lt=y.lessThan,y.lessThanOrEqual=function(a){return this.comp(a)<=0},y.lte=y.lessThanOrEqual,y.greaterThan=function(a){return this.comp(a)>0},y.gt=y.greaterThan,y.greaterThanOrEqual=function(a){return this.comp(a)>=0},y.gte=y.greaterThanOrEqual,y.compare=function(a){if(b(a)||(a=j(a)),this.eq(a))return 0;var c=this.isNegative(),d=a.isNegative();return c&&!d?-1:!c&&d?1:this.unsigned?a.high>>>0>this.high>>>0||a.high===this.high&&a.low>>>0>this.low>>>0?-1:1:this.sub(a).isNegative()?-1:1},y.comp=y.compare,y.negate=function(){return !this.unsigned&&this.eq(x)?x:this.not().add(s)},y.neg=y.negate,y.add=function(a){var c,d,e,f,h,i,k,l,m,n,o,p;return b(a)||(a=j(a)),c=this.high>>>16,d=65535&this.high,e=this.low>>>16,f=65535&this.low,h=a.high>>>16,i=65535&a.high,k=a.low>>>16,l=65535&a.low,m=0,n=0,o=0,p=0,p+=f+l,o+=p>>>16,p&=65535,o+=e+k,n+=o>>>16,o&=65535,n+=d+i,m+=n>>>16,n&=65535,m+=c+h,m&=65535,g(o<<16|p,m<<16|n,this.unsigned)},y.subtract=function(a){return b(a)||(a=j(a)),this.add(a.neg())},y.sub=y.subtract,y.multiply=function(a){var c,d,e,h,i,k,l,m,n,o,r,s;return this.isZero()?q:(b(a)||(a=j(a)),a.isZero()?q:this.eq(x)?a.isOdd()?x:q:a.eq(x)?this.isOdd()?x:q:this.isNegative()?a.isNegative()?this.neg().mul(a.neg()):this.neg().mul(a).neg():a.isNegative()?this.mul(a.neg()).neg():this.lt(p)&&a.lt(p)?f(this.toNumber()*a.toNumber(),this.unsigned):(c=this.high>>>16,d=65535&this.high,e=this.low>>>16,h=65535&this.low,i=a.high>>>16,k=65535&a.high,l=a.low>>>16,m=65535&a.low,n=0,o=0,r=0,s=0,s+=h*m,r+=s>>>16,s&=65535,r+=e*m,o+=r>>>16,r&=65535,r+=h*l,o+=r>>>16,r&=65535,o+=d*m,n+=o>>>16,o&=65535,o+=e*l,n+=o>>>16,o&=65535,o+=h*k,n+=o>>>16,o&=65535,n+=c*m+d*l+e*k+h*i,n&=65535,g(r<<16|s,n<<16|o,this.unsigned)))},y.mul=y.multiply,y.divide=function(a){var c,d,e,g,i,k,l,m;if(b(a)||(a=j(a)),a.isZero())throw Error("division by zero");if(this.isZero())return this.unsigned?r:q;if(this.unsigned){if(a.unsigned||(a=a.toUnsigned()),a.gt(this))return r;if(a.gt(this.shru(1)))return t;e=r;}else{if(this.eq(x))return a.eq(s)||a.eq(u)?x:a.eq(x)?s:(g=this.shr(1),c=g.div(a).shl(1),c.eq(q)?a.isNegative()?s:u:(d=this.sub(a.mul(c)),e=c.add(d.div(a))));if(a.eq(x))return this.unsigned?r:q;if(this.isNegative())return a.isNegative()?this.neg().div(a.neg()):this.neg().div(a).neg();if(a.isNegative())return this.div(a.neg()).neg();e=q;}for(d=this;d.gte(a);){for(c=Math.max(1,Math.floor(d.toNumber()/a.toNumber())),i=Math.ceil(Math.log(c)/Math.LN2),k=48>=i?1:h(2,i-48),l=f(c),m=l.mul(a);m.isNegative()||m.gt(d);)c-=k,l=f(c,this.unsigned),m=l.mul(a);l.isZero()&&(l=s),e=e.add(l),d=d.sub(m);}return e},y.div=y.divide,y.modulo=function(a){return b(a)||(a=j(a)),this.sub(this.div(a).mul(a))},y.mod=y.modulo,y.not=function(){return g(~this.low,~this.high,this.unsigned)},y.and=function(a){return b(a)||(a=j(a)),g(this.low&a.low,this.high&a.high,this.unsigned)},y.or=function(a){return b(a)||(a=j(a)),g(this.low|a.low,this.high|a.high,this.unsigned)},y.xor=function(a){return b(a)||(a=j(a)),g(this.low^a.low,this.high^a.high,this.unsigned)},y.shiftLeft=function(a){return b(a)&&(a=a.toInt()),0===(a&=63)?this:32>a?g(this.low<>>32-a,this.unsigned):g(0,this.low<a?g(this.low>>>a|this.high<<32-a,this.high>>a,this.unsigned):g(this.high>>a-32,this.high>=0?0:-1,this.unsigned)},y.shr=y.shiftRight,y.shiftRightUnsigned=function(a){var c,d;return b(a)&&(a=a.toInt()),a&=63,0===a?this:(c=this.high,32>a?(d=this.low,g(d>>>a|c<<32-a,c>>>a,this.unsigned)):32===a?g(c,0,this.unsigned):g(c>>>a-32,0,this.unsigned))},y.shru=y.shiftRightUnsigned,y.toSigned=function(){return this.unsigned?g(this.low,this.high,!1):this},y.toUnsigned=function(){return this.unsigned?this:g(this.low,this.high,!0)},y.toBytes=function(a){return a?this.toBytesLE():this.toBytesBE()},y.toBytesLE=function(){var a=this.high,b=this.low;return [255&b,255&b>>>8,255&b>>>16,255&b>>>24,255&a,255&a>>>8,255&a>>>16,255&a>>>24]},y.toBytesBE=function(){var a=this.high,b=this.low;return [255&a>>>24,255&a>>>16,255&a>>>8,255&a,255&b>>>24,255&b>>>16,255&b>>>8,255&b]},a}(),d=function(a){function f(a){var b=0;return function(){return b1024&&(b.push(e.apply(String,a)),a.length=0),Array.prototype.push.apply(a,arguments),void 0)}}function h(a,b,c,d,e){var f,g,h=8*e-d-1,i=(1<>1,k=-7,l=c?e-1:0,m=c?-1:1,n=a[b+l];for(l+=m,f=n&(1<<-k)-1,n>>=-k,k+=h;k>0;f=256*f+a[b+l],l+=m,k-=8);for(g=f&(1<<-k)-1,f>>=-k,k+=d;k>0;g=256*g+a[b+l],l+=m,k-=8);if(0===f)f=1-j;else{if(f===i)return g?0/0:1/0*(n?-1:1);g+=Math.pow(2,d),f-=j;}return (n?-1:1)*g*Math.pow(2,f-d)}function i(a,b,c,d,e,f){var g,h,i,j=8*f-e-1,k=(1<>1,m=23===e?Math.pow(2,-24)-Math.pow(2,-77):0,n=d?0:f-1,o=d?1:-1,p=0>b||0===b&&0>1/b?1:0;for(b=Math.abs(b),isNaN(b)||1/0===b?(h=isNaN(b)?1:0,g=k):(g=Math.floor(Math.log(b)/Math.LN2),b*(i=Math.pow(2,-g))<1&&(g--,i*=2),b+=g+l>=1?m/i:m*Math.pow(2,1-l),b*i>=2&&(g++,i/=2),g+l>=k?(h=0,g=k):g+l>=1?(h=(b*i-1)*Math.pow(2,e),g+=l):(h=b*Math.pow(2,l-1)*Math.pow(2,e),g=0));e>=8;a[c+n]=255&h,n+=o,h/=256,e-=8);for(g=g<0;a[c+n]=255&g,n+=o,g/=256,j-=8);a[c+n-o]|=128*p;}var c,d,e,j,k,b=function(a,c,e){if("undefined"==typeof a&&(a=b.DEFAULT_CAPACITY),"undefined"==typeof c&&(c=b.DEFAULT_ENDIAN),"undefined"==typeof e&&(e=b.DEFAULT_NOASSERT),!e){if(a=0|a,0>a)throw RangeError("Illegal capacity");c=!!c,e=!!e;}this.buffer=0===a?d:new ArrayBuffer(a),this.view=0===a?null:new Uint8Array(this.buffer),this.offset=0,this.markedOffset=-1,this.limit=a,this.littleEndian=c,this.noAssert=e;};return b.VERSION="5.0.1",b.LITTLE_ENDIAN=!0,b.BIG_ENDIAN=!1,b.DEFAULT_CAPACITY=16,b.DEFAULT_ENDIAN=b.BIG_ENDIAN,b.DEFAULT_NOASSERT=!1,b.Long=a||null,c=b.prototype,c.__isByteBuffer__,Object.defineProperty(c,"__isByteBuffer__",{value:!0,enumerable:!1,configurable:!1}),d=new ArrayBuffer(0),e=String.fromCharCode,b.accessor=function(){return Uint8Array},b.allocate=function(a,c,d){return new b(a,c,d)},b.concat=function(a,c,d,e){var f,i,g,h,k,j;for(("boolean"==typeof c||"string"!=typeof c)&&(e=d,d=c,c=void 0),f=0,g=0,h=a.length;h>g;++g)b.isByteBuffer(a[g])||(a[g]=b.wrap(a[g],c)),i=a[g].limit-a[g].offset,i>0&&(f+=i);if(0===f)return new b(0,d,e);for(j=new b(f,d,e),g=0;h>g;)k=a[g++],i=k.limit-k.offset,0>=i||(j.view.set(k.view.subarray(k.offset,k.limit),j.offset),j.offset+=i);return j.limit=j.offset,j.offset=0,j},b.isByteBuffer=function(a){return (a&&a.__isByteBuffer__)===!0},b.type=function(){return ArrayBuffer},b.wrap=function(a,d,e,f){var g,h;if("string"!=typeof d&&(f=e,e=d,d=void 0),"string"==typeof a)switch("undefined"==typeof d&&(d="utf8"),d){case"base64":return b.fromBase64(a,e);case"hex":return b.fromHex(a,e);case"binary":return b.fromBinary(a,e);case"utf8":return b.fromUTF8(a,e);case"debug":return b.fromDebug(a,e);default:throw Error("Unsupported encoding: "+d)}if(null===a||"object"!=typeof a)throw TypeError("Illegal buffer");if(b.isByteBuffer(a))return g=c.clone.call(a),g.markedOffset=-1,g;if(a instanceof Uint8Array)g=new b(0,e,f),a.length>0&&(g.buffer=a.buffer,g.offset=a.byteOffset,g.limit=a.byteOffset+a.byteLength,g.view=new Uint8Array(a.buffer));else if(a instanceof ArrayBuffer)g=new b(0,e,f),a.byteLength>0&&(g.buffer=a,g.offset=0,g.limit=a.byteLength,g.view=a.byteLength>0?new Uint8Array(a):null);else{if("[object Array]"!==Object.prototype.toString.call(a))throw TypeError("Illegal buffer");for(g=new b(a.length,e,f),g.limit=a.length,h=0;h>>=0,0>b||b+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+b+" (+"+0+") <= "+this.buffer.byteLength)}for(d=b,e=a.length,f=e>>3,g=0,b+=this.writeVarint32(e,b);f--;)h=1&!!a[g++]|(1&!!a[g++])<<1|(1&!!a[g++])<<2|(1&!!a[g++])<<3|(1&!!a[g++])<<4|(1&!!a[g++])<<5|(1&!!a[g++])<<6|(1&!!a[g++])<<7,this.writeByte(h,b++);if(e>g){for(i=0,h=0;e>g;)h|=(1&!!a[g++])<>3,f=0,g=[],a+=c.length;e--;)h=this.readByte(a++),g[f++]=!!(1&h),g[f++]=!!(2&h),g[f++]=!!(4&h),g[f++]=!!(8&h),g[f++]=!!(16&h),g[f++]=!!(32&h),g[f++]=!!(64&h),g[f++]=!!(128&h);if(d>f)for(i=0,h=this.readByte(a++);d>f;)g[f++]=!!(1&h>>i++);return b&&(this.offset=a),g},c.readBytes=function(a,b){var d,c="undefined"==typeof b;if(c&&(b=this.offset),!this.noAssert){if("number"!=typeof b||0!==b%1)throw TypeError("Illegal offset: "+b+" (not an integer)");if(b>>>=0,0>b||b+a>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+b+" (+"+a+") <= "+this.buffer.byteLength)}return d=this.slice(b,b+a),c&&(this.offset+=a),d},c.writeBytes=c.append,c.writeInt8=function(a,b){var d,c="undefined"==typeof b;if(c&&(b=this.offset),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal value: "+a+" (not an integer)");if(a|=0,"number"!=typeof b||0!==b%1)throw TypeError("Illegal offset: "+b+" (not an integer)");if(b>>>=0,0>b||b+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+b+" (+"+0+") <= "+this.buffer.byteLength)}return b+=1,d=this.buffer.byteLength,b>d&&this.resize((d*=2)>b?d:b),b-=1,this.view[b]=a,c&&(this.offset+=1),this},c.writeByte=c.writeInt8,c.readInt8=function(a){var c,b="undefined"==typeof a;if(b&&(a=this.offset),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal offset: "+a+" (not an integer)");if(a>>>=0,0>a||a+1>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+a+" (+"+1+") <= "+this.buffer.byteLength)}return c=this.view[a],128===(128&c)&&(c=-(255-c+1)),b&&(this.offset+=1),c},c.readByte=c.readInt8,c.writeUint8=function(a,b){var d,c="undefined"==typeof b;if(c&&(b=this.offset),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal value: "+a+" (not an integer)");if(a>>>=0,"number"!=typeof b||0!==b%1)throw TypeError("Illegal offset: "+b+" (not an integer)");if(b>>>=0,0>b||b+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+b+" (+"+0+") <= "+this.buffer.byteLength)}return b+=1,d=this.buffer.byteLength,b>d&&this.resize((d*=2)>b?d:b),b-=1,this.view[b]=a,c&&(this.offset+=1),this},c.writeUInt8=c.writeUint8,c.readUint8=function(a){var c,b="undefined"==typeof a;if(b&&(a=this.offset),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal offset: "+a+" (not an integer)");if(a>>>=0,0>a||a+1>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+a+" (+"+1+") <= "+this.buffer.byteLength)}return c=this.view[a],b&&(this.offset+=1),c},c.readUInt8=c.readUint8,c.writeInt16=function(a,b){var d,c="undefined"==typeof b;if(c&&(b=this.offset),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal value: "+a+" (not an integer)");if(a|=0,"number"!=typeof b||0!==b%1)throw TypeError("Illegal offset: "+b+" (not an integer)");if(b>>>=0,0>b||b+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+b+" (+"+0+") <= "+this.buffer.byteLength)}return b+=2,d=this.buffer.byteLength,b>d&&this.resize((d*=2)>b?d:b),b-=2,this.littleEndian?(this.view[b+1]=(65280&a)>>>8,this.view[b]=255&a):(this.view[b]=(65280&a)>>>8,this.view[b+1]=255&a),c&&(this.offset+=2),this},c.writeShort=c.writeInt16,c.readInt16=function(a){var c,b="undefined"==typeof a;if(b&&(a=this.offset),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal offset: "+a+" (not an integer)");if(a>>>=0,0>a||a+2>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+a+" (+"+2+") <= "+this.buffer.byteLength)}return c=0,this.littleEndian?(c=this.view[a],c|=this.view[a+1]<<8):(c=this.view[a]<<8,c|=this.view[a+1]),32768===(32768&c)&&(c=-(65535-c+1)),b&&(this.offset+=2),c},c.readShort=c.readInt16,c.writeUint16=function(a,b){var d,c="undefined"==typeof b;if(c&&(b=this.offset),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal value: "+a+" (not an integer)");if(a>>>=0,"number"!=typeof b||0!==b%1)throw TypeError("Illegal offset: "+b+" (not an integer)");if(b>>>=0,0>b||b+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+b+" (+"+0+") <= "+this.buffer.byteLength)}return b+=2,d=this.buffer.byteLength,b>d&&this.resize((d*=2)>b?d:b),b-=2,this.littleEndian?(this.view[b+1]=(65280&a)>>>8,this.view[b]=255&a):(this.view[b]=(65280&a)>>>8,this.view[b+1]=255&a),c&&(this.offset+=2),this},c.writeUInt16=c.writeUint16,c.readUint16=function(a){var c,b="undefined"==typeof a;if(b&&(a=this.offset),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal offset: "+a+" (not an integer)");if(a>>>=0,0>a||a+2>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+a+" (+"+2+") <= "+this.buffer.byteLength)}return c=0,this.littleEndian?(c=this.view[a],c|=this.view[a+1]<<8):(c=this.view[a]<<8,c|=this.view[a+1]),b&&(this.offset+=2),c},c.readUInt16=c.readUint16,c.writeInt32=function(a,b){var d,c="undefined"==typeof b;if(c&&(b=this.offset),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal value: "+a+" (not an integer)");if(a|=0,"number"!=typeof b||0!==b%1)throw TypeError("Illegal offset: "+b+" (not an integer)");if(b>>>=0,0>b||b+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+b+" (+"+0+") <= "+this.buffer.byteLength)}return b+=4,d=this.buffer.byteLength,b>d&&this.resize((d*=2)>b?d:b),b-=4,this.littleEndian?(this.view[b+3]=255&a>>>24,this.view[b+2]=255&a>>>16,this.view[b+1]=255&a>>>8,this.view[b]=255&a):(this.view[b]=255&a>>>24,this.view[b+1]=255&a>>>16,this.view[b+2]=255&a>>>8,this.view[b+3]=255&a),c&&(this.offset+=4),this},c.writeInt=c.writeInt32,c.readInt32=function(a){var c,b="undefined"==typeof a;if(b&&(a=this.offset),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal offset: "+a+" (not an integer)");if(a>>>=0,0>a||a+4>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+a+" (+"+4+") <= "+this.buffer.byteLength)}return c=0,this.littleEndian?(c=this.view[a+2]<<16,c|=this.view[a+1]<<8,c|=this.view[a],c+=this.view[a+3]<<24>>>0):(c=this.view[a+1]<<16,c|=this.view[a+2]<<8,c|=this.view[a+3],c+=this.view[a]<<24>>>0),c|=0,b&&(this.offset+=4),c},c.readInt=c.readInt32,c.writeUint32=function(a,b){var d,c="undefined"==typeof b;if(c&&(b=this.offset),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal value: "+a+" (not an integer)");if(a>>>=0,"number"!=typeof b||0!==b%1)throw TypeError("Illegal offset: "+b+" (not an integer)");if(b>>>=0,0>b||b+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+b+" (+"+0+") <= "+this.buffer.byteLength)}return b+=4,d=this.buffer.byteLength,b>d&&this.resize((d*=2)>b?d:b),b-=4,this.littleEndian?(this.view[b+3]=255&a>>>24,this.view[b+2]=255&a>>>16,this.view[b+1]=255&a>>>8,this.view[b]=255&a):(this.view[b]=255&a>>>24,this.view[b+1]=255&a>>>16,this.view[b+2]=255&a>>>8,this.view[b+3]=255&a),c&&(this.offset+=4),this},c.writeUInt32=c.writeUint32,c.readUint32=function(a){var c,b="undefined"==typeof a;if(b&&(a=this.offset),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal offset: "+a+" (not an integer)");if(a>>>=0,0>a||a+4>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+a+" (+"+4+") <= "+this.buffer.byteLength)}return c=0,this.littleEndian?(c=this.view[a+2]<<16,c|=this.view[a+1]<<8,c|=this.view[a],c+=this.view[a+3]<<24>>>0):(c=this.view[a+1]<<16,c|=this.view[a+2]<<8,c|=this.view[a+3],c+=this.view[a]<<24>>>0),b&&(this.offset+=4),c},c.readUInt32=c.readUint32,a&&(c.writeInt64=function(b,c){var e,f,g,d="undefined"==typeof c;if(d&&(c=this.offset),!this.noAssert){if("number"==typeof b)b=a.fromNumber(b);else if("string"==typeof b)b=a.fromString(b);else if(!(b&&b instanceof a))throw TypeError("Illegal value: "+b+" (not an integer or Long)");if("number"!=typeof c||0!==c%1)throw TypeError("Illegal offset: "+c+" (not an integer)");if(c>>>=0,0>c||c+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+c+" (+"+0+") <= "+this.buffer.byteLength)}return "number"==typeof b?b=a.fromNumber(b):"string"==typeof b&&(b=a.fromString(b)),c+=8,e=this.buffer.byteLength,c>e&&this.resize((e*=2)>c?e:c),c-=8,f=b.low,g=b.high,this.littleEndian?(this.view[c+3]=255&f>>>24,this.view[c+2]=255&f>>>16,this.view[c+1]=255&f>>>8,this.view[c]=255&f,c+=4,this.view[c+3]=255&g>>>24,this.view[c+2]=255&g>>>16,this.view[c+1]=255&g>>>8,this.view[c]=255&g):(this.view[c]=255&g>>>24,this.view[c+1]=255&g>>>16,this.view[c+2]=255&g>>>8,this.view[c+3]=255&g,c+=4,this.view[c]=255&f>>>24,this.view[c+1]=255&f>>>16,this.view[c+2]=255&f>>>8,this.view[c+3]=255&f),d&&(this.offset+=8),this},c.writeLong=c.writeInt64,c.readInt64=function(b){var d,e,f,c="undefined"==typeof b;if(c&&(b=this.offset),!this.noAssert){if("number"!=typeof b||0!==b%1)throw TypeError("Illegal offset: "+b+" (not an integer)");if(b>>>=0,0>b||b+8>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+b+" (+"+8+") <= "+this.buffer.byteLength)}return d=0,e=0,this.littleEndian?(d=this.view[b+2]<<16,d|=this.view[b+1]<<8,d|=this.view[b],d+=this.view[b+3]<<24>>>0,b+=4,e=this.view[b+2]<<16,e|=this.view[b+1]<<8,e|=this.view[b],e+=this.view[b+3]<<24>>>0):(e=this.view[b+1]<<16,e|=this.view[b+2]<<8,e|=this.view[b+3],e+=this.view[b]<<24>>>0,b+=4,d=this.view[b+1]<<16,d|=this.view[b+2]<<8,d|=this.view[b+3],d+=this.view[b]<<24>>>0),f=new a(d,e,!1),c&&(this.offset+=8),f},c.readLong=c.readInt64,c.writeUint64=function(b,c){var e,f,g,d="undefined"==typeof c;if(d&&(c=this.offset),!this.noAssert){if("number"==typeof b)b=a.fromNumber(b);else if("string"==typeof b)b=a.fromString(b);else if(!(b&&b instanceof a))throw TypeError("Illegal value: "+b+" (not an integer or Long)");if("number"!=typeof c||0!==c%1)throw TypeError("Illegal offset: "+c+" (not an integer)");if(c>>>=0,0>c||c+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+c+" (+"+0+") <= "+this.buffer.byteLength)}return "number"==typeof b?b=a.fromNumber(b):"string"==typeof b&&(b=a.fromString(b)),c+=8,e=this.buffer.byteLength,c>e&&this.resize((e*=2)>c?e:c),c-=8,f=b.low,g=b.high,this.littleEndian?(this.view[c+3]=255&f>>>24,this.view[c+2]=255&f>>>16,this.view[c+1]=255&f>>>8,this.view[c]=255&f,c+=4,this.view[c+3]=255&g>>>24,this.view[c+2]=255&g>>>16,this.view[c+1]=255&g>>>8,this.view[c]=255&g):(this.view[c]=255&g>>>24,this.view[c+1]=255&g>>>16,this.view[c+2]=255&g>>>8,this.view[c+3]=255&g,c+=4,this.view[c]=255&f>>>24,this.view[c+1]=255&f>>>16,this.view[c+2]=255&f>>>8,this.view[c+3]=255&f),d&&(this.offset+=8),this},c.writeUInt64=c.writeUint64,c.readUint64=function(b){var d,e,f,c="undefined"==typeof b;if(c&&(b=this.offset),!this.noAssert){if("number"!=typeof b||0!==b%1)throw TypeError("Illegal offset: "+b+" (not an integer)");if(b>>>=0,0>b||b+8>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+b+" (+"+8+") <= "+this.buffer.byteLength)}return d=0,e=0,this.littleEndian?(d=this.view[b+2]<<16,d|=this.view[b+1]<<8,d|=this.view[b],d+=this.view[b+3]<<24>>>0,b+=4,e=this.view[b+2]<<16,e|=this.view[b+1]<<8,e|=this.view[b],e+=this.view[b+3]<<24>>>0):(e=this.view[b+1]<<16,e|=this.view[b+2]<<8,e|=this.view[b+3],e+=this.view[b]<<24>>>0,b+=4,d=this.view[b+1]<<16,d|=this.view[b+2]<<8,d|=this.view[b+3],d+=this.view[b]<<24>>>0),f=new a(d,e,!0),c&&(this.offset+=8),f},c.readUInt64=c.readUint64),c.writeFloat32=function(a,b){var d,c="undefined"==typeof b;if(c&&(b=this.offset),!this.noAssert){if("number"!=typeof a)throw TypeError("Illegal value: "+a+" (not a number)");if("number"!=typeof b||0!==b%1)throw TypeError("Illegal offset: "+b+" (not an integer)");if(b>>>=0,0>b||b+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+b+" (+"+0+") <= "+this.buffer.byteLength)}return b+=4,d=this.buffer.byteLength,b>d&&this.resize((d*=2)>b?d:b),b-=4,i(this.view,a,b,this.littleEndian,23,4),c&&(this.offset+=4),this},c.writeFloat=c.writeFloat32,c.readFloat32=function(a){var c,b="undefined"==typeof a;if(b&&(a=this.offset),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal offset: "+a+" (not an integer)");if(a>>>=0,0>a||a+4>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+a+" (+"+4+") <= "+this.buffer.byteLength)}return c=h(this.view,a,this.littleEndian,23,4),b&&(this.offset+=4),c},c.readFloat=c.readFloat32,c.writeFloat64=function(a,b){var d,c="undefined"==typeof b;if(c&&(b=this.offset),!this.noAssert){if("number"!=typeof a)throw TypeError("Illegal value: "+a+" (not a number)");if("number"!=typeof b||0!==b%1)throw TypeError("Illegal offset: "+b+" (not an integer)");if(b>>>=0,0>b||b+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+b+" (+"+0+") <= "+this.buffer.byteLength)}return b+=8,d=this.buffer.byteLength,b>d&&this.resize((d*=2)>b?d:b),b-=8,i(this.view,a,b,this.littleEndian,52,8),c&&(this.offset+=8),this},c.writeDouble=c.writeFloat64,c.readFloat64=function(a){var c,b="undefined"==typeof a;if(b&&(a=this.offset),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal offset: "+a+" (not an integer)");if(a>>>=0,0>a||a+8>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+a+" (+"+8+") <= "+this.buffer.byteLength)}return c=h(this.view,a,this.littleEndian,52,8),b&&(this.offset+=8),c},c.readDouble=c.readFloat64,b.MAX_VARINT32_BYTES=5,b.calculateVarint32=function(a){return a>>>=0,128>a?1:16384>a?2:1<<21>a?3:1<<28>a?4:5},b.zigZagEncode32=function(a){return ((a|=0)<<1^a>>31)>>>0},b.zigZagDecode32=function(a){return 0|a>>>1^-(1&a)},c.writeVarint32=function(a,c){var f,e,g,d="undefined"==typeof c;if(d&&(c=this.offset),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal value: "+a+" (not an integer)");if(a|=0,"number"!=typeof c||0!==c%1)throw TypeError("Illegal offset: "+c+" (not an integer)");if(c>>>=0,0>c||c+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+c+" (+"+0+") <= "+this.buffer.byteLength)}for(e=b.calculateVarint32(a),c+=e,g=this.buffer.byteLength,c>g&&this.resize((g*=2)>c?g:c),c-=e,a>>>=0;a>=128;)f=128|127&a,this.view[c++]=f,a>>>=7;return this.view[c++]=a,d?(this.offset=c,this):e},c.writeVarint32ZigZag=function(a,c){return this.writeVarint32(b.zigZagEncode32(a),c)},c.readVarint32=function(a){var e,c,d,f,b="undefined"==typeof a;if(b&&(a=this.offset),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal offset: "+a+" (not an integer)");if(a>>>=0,0>a||a+1>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+a+" (+"+1+") <= "+this.buffer.byteLength)}c=0,d=0;do{if(!this.noAssert&&a>this.limit)throw f=Error("Truncated"),f.truncated=!0,f;e=this.view[a++],5>c&&(d|=(127&e)<<7*c),++c;}while(0!==(128&e));return d|=0,b?(this.offset=a,d):{value:d,length:c}},c.readVarint32ZigZag=function(a){var c=this.readVarint32(a);return "object"==typeof c?c.value=b.zigZagDecode32(c.value):c=b.zigZagDecode32(c),c},a&&(b.MAX_VARINT64_BYTES=10,b.calculateVarint64=function(b){"number"==typeof b?b=a.fromNumber(b):"string"==typeof b&&(b=a.fromString(b));var c=b.toInt()>>>0,d=b.shiftRightUnsigned(28).toInt()>>>0,e=b.shiftRightUnsigned(56).toInt()>>>0;return 0==e?0==d?16384>c?128>c?1:2:1<<21>c?3:4:16384>d?128>d?5:6:1<<21>d?7:8:128>e?9:10},b.zigZagEncode64=function(b){return "number"==typeof b?b=a.fromNumber(b,!1):"string"==typeof b?b=a.fromString(b,!1):b.unsigned!==!1&&(b=b.toSigned()),b.shiftLeft(1).xor(b.shiftRight(63)).toUnsigned()},b.zigZagDecode64=function(b){return "number"==typeof b?b=a.fromNumber(b,!1):"string"==typeof b?b=a.fromString(b,!1):b.unsigned!==!1&&(b=b.toSigned()),b.shiftRightUnsigned(1).xor(b.and(a.ONE).toSigned().negate()).toSigned()},c.writeVarint64=function(c,d){var f,g,h,i,j,e="undefined"==typeof d;if(e&&(d=this.offset),!this.noAssert){if("number"==typeof c)c=a.fromNumber(c);else if("string"==typeof c)c=a.fromString(c);else if(!(c&&c instanceof a))throw TypeError("Illegal value: "+c+" (not an integer or Long)");if("number"!=typeof d||0!==d%1)throw TypeError("Illegal offset: "+d+" (not an integer)");if(d>>>=0,0>d||d+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+d+" (+"+0+") <= "+this.buffer.byteLength)}switch("number"==typeof c?c=a.fromNumber(c,!1):"string"==typeof c?c=a.fromString(c,!1):c.unsigned!==!1&&(c=c.toSigned()),f=b.calculateVarint64(c),g=c.toInt()>>>0,h=c.shiftRightUnsigned(28).toInt()>>>0,i=c.shiftRightUnsigned(56).toInt()>>>0,d+=f,j=this.buffer.byteLength,d>j&&this.resize((j*=2)>d?j:d),d-=f,f){case 10:this.view[d+9]=1&i>>>7;case 9:this.view[d+8]=9!==f?128|i:127&i;case 8:this.view[d+7]=8!==f?128|h>>>21:127&h>>>21;case 7:this.view[d+6]=7!==f?128|h>>>14:127&h>>>14;case 6:this.view[d+5]=6!==f?128|h>>>7:127&h>>>7;case 5:this.view[d+4]=5!==f?128|h:127&h;case 4:this.view[d+3]=4!==f?128|g>>>21:127&g>>>21;case 3:this.view[d+2]=3!==f?128|g>>>14:127&g>>>14;case 2:this.view[d+1]=2!==f?128|g>>>7:127&g>>>7;case 1:this.view[d]=1!==f?128|g:127&g;}return e?(this.offset+=f,this):f},c.writeVarint64ZigZag=function(a,c){return this.writeVarint64(b.zigZagEncode64(a),c)},c.readVarint64=function(b){var d,e,f,g,h,i,c="undefined"==typeof b;if(c&&(b=this.offset),!this.noAssert){if("number"!=typeof b||0!==b%1)throw TypeError("Illegal offset: "+b+" (not an integer)");if(b>>>=0,0>b||b+1>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+b+" (+"+1+") <= "+this.buffer.byteLength)}if(d=b,e=0,f=0,g=0,h=0,h=this.view[b++],e=127&h,128&h&&(h=this.view[b++],e|=(127&h)<<7,(128&h||this.noAssert&&"undefined"==typeof h)&&(h=this.view[b++],e|=(127&h)<<14,(128&h||this.noAssert&&"undefined"==typeof h)&&(h=this.view[b++],e|=(127&h)<<21,(128&h||this.noAssert&&"undefined"==typeof h)&&(h=this.view[b++],f=127&h,(128&h||this.noAssert&&"undefined"==typeof h)&&(h=this.view[b++],f|=(127&h)<<7,(128&h||this.noAssert&&"undefined"==typeof h)&&(h=this.view[b++],f|=(127&h)<<14,(128&h||this.noAssert&&"undefined"==typeof h)&&(h=this.view[b++],f|=(127&h)<<21,(128&h||this.noAssert&&"undefined"==typeof h)&&(h=this.view[b++],g=127&h,(128&h||this.noAssert&&"undefined"==typeof h)&&(h=this.view[b++],g|=(127&h)<<7,128&h||this.noAssert&&"undefined"==typeof h))))))))))throw Error("Buffer overrun");return i=a.fromBits(e|f<<28,f>>>4|g<<24,!1),c?(this.offset=b,i):{value:i,length:b-d}},c.readVarint64ZigZag=function(c){var d=this.readVarint64(c);return d&&d.value instanceof a?d.value=b.zigZagDecode64(d.value):d=b.zigZagDecode64(d),d}),c.writeCString=function(a,b){var d,e,g,c="undefined"==typeof b;if(c&&(b=this.offset),e=a.length,!this.noAssert){if("string"!=typeof a)throw TypeError("Illegal str: Not a string");for(d=0;e>d;++d)if(0===a.charCodeAt(d))throw RangeError("Illegal str: Contains NULL-characters");if("number"!=typeof b||0!==b%1)throw TypeError("Illegal offset: "+b+" (not an integer)");if(b>>>=0,0>b||b+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+b+" (+"+0+") <= "+this.buffer.byteLength)}return e=k.calculateUTF16asUTF8(f(a))[1],b+=e+1,g=this.buffer.byteLength,b>g&&this.resize((g*=2)>b?g:b),b-=e+1,k.encodeUTF16toUTF8(f(a),function(a){this.view[b++]=a;}.bind(this)),this.view[b++]=0,c?(this.offset=b,this):e},c.readCString=function(a){var c,e,f,b="undefined"==typeof a;if(b&&(a=this.offset),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal offset: "+a+" (not an integer)");if(a>>>=0,0>a||a+1>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+a+" (+"+1+") <= "+this.buffer.byteLength)}return c=a,f=-1,k.decodeUTF8toUTF16(function(){if(0===f)return null;if(a>=this.limit)throw RangeError("Illegal range: Truncated data, "+a+" < "+this.limit);return f=this.view[a++],0===f?null:f}.bind(this),e=g(),!0),b?(this.offset=a,e()):{string:e(),length:a-c}},c.writeIString=function(a,b){var e,d,g,c="undefined"==typeof b;if(c&&(b=this.offset),!this.noAssert){if("string"!=typeof a)throw TypeError("Illegal str: Not a string");if("number"!=typeof b||0!==b%1)throw TypeError("Illegal offset: "+b+" (not an integer)");if(b>>>=0,0>b||b+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+b+" (+"+0+") <= "+this.buffer.byteLength)}if(d=b,e=k.calculateUTF16asUTF8(f(a),this.noAssert)[1],b+=4+e,g=this.buffer.byteLength,b>g&&this.resize((g*=2)>b?g:b),b-=4+e,this.littleEndian?(this.view[b+3]=255&e>>>24,this.view[b+2]=255&e>>>16,this.view[b+1]=255&e>>>8,this.view[b]=255&e):(this.view[b]=255&e>>>24,this.view[b+1]=255&e>>>16,this.view[b+2]=255&e>>>8,this.view[b+3]=255&e),b+=4,k.encodeUTF16toUTF8(f(a),function(a){this.view[b++]=a;}.bind(this)),b!==d+4+e)throw RangeError("Illegal range: Truncated data, "+b+" == "+(b+4+e));return c?(this.offset=b,this):b-d},c.readIString=function(a){var d,e,f,c="undefined"==typeof a; if(c&&(a=this.offset),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal offset: "+a+" (not an integer)");if(a>>>=0,0>a||a+4>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+a+" (+"+4+") <= "+this.buffer.byteLength)}return d=a,e=this.readUint32(a),f=this.readUTF8String(e,b.METRICS_BYTES,a+=4),a+=f.length,c?(this.offset=a,f.string):{string:f.string,length:a-d}},b.METRICS_CHARS="c",b.METRICS_BYTES="b",c.writeUTF8String=function(a,b){var d,e,g,c="undefined"==typeof b;if(c&&(b=this.offset),!this.noAssert){if("number"!=typeof b||0!==b%1)throw TypeError("Illegal offset: "+b+" (not an integer)");if(b>>>=0,0>b||b+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+b+" (+"+0+") <= "+this.buffer.byteLength)}return e=b,d=k.calculateUTF16asUTF8(f(a))[1],b+=d,g=this.buffer.byteLength,b>g&&this.resize((g*=2)>b?g:b),b-=d,k.encodeUTF16toUTF8(f(a),function(a){this.view[b++]=a;}.bind(this)),c?(this.offset=b,this):b-e},c.writeString=c.writeUTF8String,b.calculateUTF8Chars=function(a){return k.calculateUTF16asUTF8(f(a))[0]},b.calculateUTF8Bytes=function(a){return k.calculateUTF16asUTF8(f(a))[1]},b.calculateString=b.calculateUTF8Bytes,c.readUTF8String=function(a,c,d){var e,i,f,h,j;if("number"==typeof c&&(d=c,c=void 0),e="undefined"==typeof d,e&&(d=this.offset),"undefined"==typeof c&&(c=b.METRICS_CHARS),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal length: "+a+" (not an integer)");if(a|=0,"number"!=typeof d||0!==d%1)throw TypeError("Illegal offset: "+d+" (not an integer)");if(d>>>=0,0>d||d+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+d+" (+"+0+") <= "+this.buffer.byteLength)}if(f=0,h=d,c===b.METRICS_CHARS){if(i=g(),k.decodeUTF8(function(){return a>f&&d>>=0,0>d||d+a>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+d+" (+"+a+") <= "+this.buffer.byteLength)}if(j=d+a,k.decodeUTF8toUTF16(function(){return j>d?this.view[d++]:null}.bind(this),i=g(),this.noAssert),d!==j)throw RangeError("Illegal range: Truncated data, "+d+" == "+j);return e?(this.offset=d,i()):{string:i(),length:d-h}}throw TypeError("Unsupported metrics: "+c)},c.readString=c.readUTF8String,c.writeVString=function(a,c){var g,h,e,i,d="undefined"==typeof c;if(d&&(c=this.offset),!this.noAssert){if("string"!=typeof a)throw TypeError("Illegal str: Not a string");if("number"!=typeof c||0!==c%1)throw TypeError("Illegal offset: "+c+" (not an integer)");if(c>>>=0,0>c||c+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+c+" (+"+0+") <= "+this.buffer.byteLength)}if(e=c,g=k.calculateUTF16asUTF8(f(a),this.noAssert)[1],h=b.calculateVarint32(g),c+=h+g,i=this.buffer.byteLength,c>i&&this.resize((i*=2)>c?i:c),c-=h+g,c+=this.writeVarint32(g,c),k.encodeUTF16toUTF8(f(a),function(a){this.view[c++]=a;}.bind(this)),c!==e+g+h)throw RangeError("Illegal range: Truncated data, "+c+" == "+(c+g+h));return d?(this.offset=c,this):c-e},c.readVString=function(a){var d,e,f,c="undefined"==typeof a;if(c&&(a=this.offset),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal offset: "+a+" (not an integer)");if(a>>>=0,0>a||a+1>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+a+" (+"+1+") <= "+this.buffer.byteLength)}return d=a,e=this.readVarint32(a),f=this.readUTF8String(e.value,b.METRICS_BYTES,a+=e.length),a+=f.length,c?(this.offset=a,f.string):{string:f.string,length:a-d}},c.append=function(a,c,d){var e,f,g;if(("number"==typeof c||"string"!=typeof c)&&(d=c,c=void 0),e="undefined"==typeof d,e&&(d=this.offset),!this.noAssert){if("number"!=typeof d||0!==d%1)throw TypeError("Illegal offset: "+d+" (not an integer)");if(d>>>=0,0>d||d+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+d+" (+"+0+") <= "+this.buffer.byteLength)}return a instanceof b||(a=b.wrap(a,c)),f=a.limit-a.offset,0>=f?this:(d+=f,g=this.buffer.byteLength,d>g&&this.resize((g*=2)>d?g:d),d-=f,this.view.set(a.view.subarray(a.offset,a.limit),d),a.offset+=f,e&&(this.offset+=f),this)},c.appendTo=function(a,b){return a.append(this,b),this},c.assert=function(a){return this.noAssert=!a,this},c.capacity=function(){return this.buffer.byteLength},c.clear=function(){return this.offset=0,this.limit=this.buffer.byteLength,this.markedOffset=-1,this},c.clone=function(a){var c=new b(0,this.littleEndian,this.noAssert);return a?(c.buffer=new ArrayBuffer(this.buffer.byteLength),c.view=new Uint8Array(c.buffer)):(c.buffer=this.buffer,c.view=this.view),c.offset=this.offset,c.markedOffset=this.markedOffset,c.limit=this.limit,c},c.compact=function(a,b){var c,e,f;if("undefined"==typeof a&&(a=this.offset),"undefined"==typeof b&&(b=this.limit),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal begin: Not an integer");if(a>>>=0,"number"!=typeof b||0!==b%1)throw TypeError("Illegal end: Not an integer");if(b>>>=0,0>a||a>b||b>this.buffer.byteLength)throw RangeError("Illegal range: 0 <= "+a+" <= "+b+" <= "+this.buffer.byteLength)}return 0===a&&b===this.buffer.byteLength?this:(c=b-a,0===c?(this.buffer=d,this.view=null,this.markedOffset>=0&&(this.markedOffset-=a),this.offset=0,this.limit=0,this):(e=new ArrayBuffer(c),f=new Uint8Array(e),f.set(this.view.subarray(a,b)),this.buffer=e,this.view=f,this.markedOffset>=0&&(this.markedOffset-=a),this.offset=0,this.limit=c,this))},c.copy=function(a,c){if("undefined"==typeof a&&(a=this.offset),"undefined"==typeof c&&(c=this.limit),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal begin: Not an integer");if(a>>>=0,"number"!=typeof c||0!==c%1)throw TypeError("Illegal end: Not an integer");if(c>>>=0,0>a||a>c||c>this.buffer.byteLength)throw RangeError("Illegal range: 0 <= "+a+" <= "+c+" <= "+this.buffer.byteLength)}if(a===c)return new b(0,this.littleEndian,this.noAssert);var d=c-a,e=new b(d,this.littleEndian,this.noAssert);return e.offset=0,e.limit=d,e.markedOffset>=0&&(e.markedOffset-=a),this.copyTo(e,0,a,c),e},c.copyTo=function(a,c,d,e){var f,g,h;if(!this.noAssert&&!b.isByteBuffer(a))throw TypeError("Illegal target: Not a ByteBuffer");if(c=(g="undefined"==typeof c)?a.offset:0|c,d=(f="undefined"==typeof d)?this.offset:0|d,e="undefined"==typeof e?this.limit:0|e,0>c||c>a.buffer.byteLength)throw RangeError("Illegal target range: 0 <= "+c+" <= "+a.buffer.byteLength);if(0>d||e>this.buffer.byteLength)throw RangeError("Illegal source range: 0 <= "+d+" <= "+this.buffer.byteLength);return h=e-d,0===h?a:(a.ensureCapacity(c+h),a.view.set(this.view.subarray(d,e),c),f&&(this.offset+=h),g&&(a.offset+=h),this)},c.ensureCapacity=function(a){var b=this.buffer.byteLength;return a>b?this.resize((b*=2)>a?b:a):this},c.fill=function(a,b,c){var d="undefined"==typeof b;if(d&&(b=this.offset),"string"==typeof a&&a.length>0&&(a=a.charCodeAt(0)),"undefined"==typeof b&&(b=this.offset),"undefined"==typeof c&&(c=this.limit),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal value: "+a+" (not an integer)");if(a|=0,"number"!=typeof b||0!==b%1)throw TypeError("Illegal begin: Not an integer");if(b>>>=0,"number"!=typeof c||0!==c%1)throw TypeError("Illegal end: Not an integer");if(c>>>=0,0>b||b>c||c>this.buffer.byteLength)throw RangeError("Illegal range: 0 <= "+b+" <= "+c+" <= "+this.buffer.byteLength)}if(b>=c)return this;for(;c>b;)this.view[b++]=a;return d&&(this.offset=b),this},c.flip=function(){return this.limit=this.offset,this.offset=0,this},c.mark=function(a){if(a="undefined"==typeof a?this.offset:a,!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal offset: "+a+" (not an integer)");if(a>>>=0,0>a||a+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+a+" (+"+0+") <= "+this.buffer.byteLength)}return this.markedOffset=a,this},c.order=function(a){if(!this.noAssert&&"boolean"!=typeof a)throw TypeError("Illegal littleEndian: Not a boolean");return this.littleEndian=!!a,this},c.LE=function(a){return this.littleEndian="undefined"!=typeof a?!!a:!0,this},c.BE=function(a){return this.littleEndian="undefined"!=typeof a?!a:!1,this},c.prepend=function(a,c,d){var e,f,g,h,i;if(("number"==typeof c||"string"!=typeof c)&&(d=c,c=void 0),e="undefined"==typeof d,e&&(d=this.offset),!this.noAssert){if("number"!=typeof d||0!==d%1)throw TypeError("Illegal offset: "+d+" (not an integer)");if(d>>>=0,0>d||d+0>this.buffer.byteLength)throw RangeError("Illegal offset: 0 <= "+d+" (+"+0+") <= "+this.buffer.byteLength)}return a instanceof b||(a=b.wrap(a,c)),f=a.limit-a.offset,0>=f?this:(g=f-d,g>0?(h=new ArrayBuffer(this.buffer.byteLength+g),i=new Uint8Array(h),i.set(this.view.subarray(d,this.buffer.byteLength),f),this.buffer=h,this.view=i,this.offset+=g,this.markedOffset>=0&&(this.markedOffset+=g),this.limit+=g,d+=g):new Uint8Array(this.buffer),this.view.set(a.view.subarray(a.offset,a.limit),d-f),a.offset=a.limit,e&&(this.offset-=f),this)},c.prependTo=function(a,b){return a.prepend(this,b),this},c.printDebug=function(a){"function"!=typeof a&&(a=console.log.bind(console)),a(this.toString()+"\n-------------------------------------------------------------------\n"+this.toDebug(!0));},c.remaining=function(){return this.limit-this.offset},c.reset=function(){return this.markedOffset>=0?(this.offset=this.markedOffset,this.markedOffset=-1):this.offset=0,this},c.resize=function(a){var b,c;if(!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal capacity: "+a+" (not an integer)");if(a|=0,0>a)throw RangeError("Illegal capacity: 0 <= "+a)}return this.buffer.byteLength>>=0,"number"!=typeof b||0!==b%1)throw TypeError("Illegal end: Not an integer");if(b>>>=0,0>a||a>b||b>this.buffer.byteLength)throw RangeError("Illegal range: 0 <= "+a+" <= "+b+" <= "+this.buffer.byteLength)}return a===b?this:(Array.prototype.reverse.call(this.view.subarray(a,b)),this)},c.skip=function(a){if(!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal length: "+a+" (not an integer)");a|=0;}var b=this.offset+a;if(!this.noAssert&&(0>b||b>this.buffer.byteLength))throw RangeError("Illegal length: 0 <= "+this.offset+" + "+a+" <= "+this.buffer.byteLength);return this.offset=b,this},c.slice=function(a,b){if("undefined"==typeof a&&(a=this.offset),"undefined"==typeof b&&(b=this.limit),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal begin: Not an integer");if(a>>>=0,"number"!=typeof b||0!==b%1)throw TypeError("Illegal end: Not an integer");if(b>>>=0,0>a||a>b||b>this.buffer.byteLength)throw RangeError("Illegal range: 0 <= "+a+" <= "+b+" <= "+this.buffer.byteLength)}var c=this.clone();return c.offset=a,c.limit=b,c},c.toBuffer=function(a){var e,b=this.offset,c=this.limit;if(!this.noAssert){if("number"!=typeof b||0!==b%1)throw TypeError("Illegal offset: Not an integer");if(b>>>=0,"number"!=typeof c||0!==c%1)throw TypeError("Illegal limit: Not an integer");if(c>>>=0,0>b||b>c||c>this.buffer.byteLength)throw RangeError("Illegal range: 0 <= "+b+" <= "+c+" <= "+this.buffer.byteLength)}return a||0!==b||c!==this.buffer.byteLength?b===c?d:(e=new ArrayBuffer(c-b),new Uint8Array(e).set(new Uint8Array(this.buffer).subarray(b,c),0),e):this.buffer},c.toArrayBuffer=c.toBuffer,c.toString=function(a,b,c){if("undefined"==typeof a)return "ByteBufferAB(offset="+this.offset+",markedOffset="+this.markedOffset+",limit="+this.limit+",capacity="+this.capacity()+")";switch("number"==typeof a&&(a="utf8",b=a,c=b),a){case"utf8":return this.toUTF8(b,c);case"base64":return this.toBase64(b,c);case"hex":return this.toHex(b,c);case"binary":return this.toBinary(b,c);case"debug":return this.toDebug();case"columns":return this.toColumns();default:throw Error("Unsupported encoding: "+a)}},j=function(){var d,e,a={},b=[65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,48,49,50,51,52,53,54,55,56,57,43,47],c=[];for(d=0,e=b.length;e>d;++d)c[b[d]]=d;return a.encode=function(a,c){for(var d,e;null!==(d=a());)c(b[63&d>>2]),e=(3&d)<<4,null!==(d=a())?(e|=15&d>>4,c(b[63&(e|15&d>>4)]),e=(15&d)<<2,null!==(d=a())?(c(b[63&(e|3&d>>6)]),c(b[63&d])):(c(b[63&e]),c(61))):(c(b[63&e]),c(61),c(61));},a.decode=function(a,b){function g(a){throw Error("Illegal character code: "+a)}for(var d,e,f;null!==(d=a());)if(e=c[d],"undefined"==typeof e&&g(d),null!==(d=a())&&(f=c[d],"undefined"==typeof f&&g(d),b(e<<2>>>0|(48&f)>>4),null!==(d=a()))){if(e=c[d],"undefined"==typeof e){if(61===d)break;g(d);}if(b((15&f)<<4>>>0|(60&e)>>2),null!==(d=a())){if(f=c[d],"undefined"==typeof f){if(61===d)break;g(d);}b((3&e)<<6>>>0|f);}}},a.test=function(a){return /^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/.test(a)},a}(),c.toBase64=function(a,b){if("undefined"==typeof a&&(a=this.offset),"undefined"==typeof b&&(b=this.limit),a=0|a,b=0|b,0>a||b>this.capacity||a>b)throw RangeError("begin, end");var c;return j.encode(function(){return b>a?this.view[a++]:null}.bind(this),c=g()),c()},b.fromBase64=function(a,c){if("string"!=typeof a)throw TypeError("str");var d=new b(3*(a.length/4),c),e=0;return j.decode(f(a),function(a){d.view[e++]=a;}),d.limit=e,d},b.btoa=function(a){return b.fromBinary(a).toBase64()},b.atob=function(a){return b.fromBase64(a).toBinary()},c.toBinary=function(a,b){if("undefined"==typeof a&&(a=this.offset),"undefined"==typeof b&&(b=this.limit),a|=0,b|=0,0>a||b>this.capacity()||a>b)throw RangeError("begin, end");if(a===b)return "";for(var c=[],d=[];b>a;)c.push(this.view[a++]),c.length>=1024&&(d.push(String.fromCharCode.apply(String,c)),c=[]);return d.join("")+String.fromCharCode.apply(String,c)},b.fromBinary=function(a,c){if("string"!=typeof a)throw TypeError("str");for(var f,d=0,e=a.length,g=new b(e,c);e>d;){if(f=a.charCodeAt(d),f>255)throw RangeError("illegal char code: "+f);g.view[d++]=f;}return g.limit=e,g},c.toDebug=function(a){for(var d,b=-1,c=this.buffer.byteLength,e="",f="",g="";c>b;){if(-1!==b&&(d=this.view[b],e+=16>d?"0"+d.toString(16).toUpperCase():d.toString(16).toUpperCase(),a&&(f+=d>32&&127>d?String.fromCharCode(d):".")),++b,a&&b>0&&0===b%16&&b!==c){for(;e.length<51;)e+=" ";g+=e+f+"\n",e=f="";}e+=b===this.offset&&b===this.limit?b===this.markedOffset?"!":"|":b===this.offset?b===this.markedOffset?"[":"<":b===this.limit?b===this.markedOffset?"]":">":b===this.markedOffset?"'":a||0!==b&&b!==c?" ":"";}if(a&&" "!==e){for(;e.length<51;)e+=" ";g+=e+f+"\n";}return a?g:e},b.fromDebug=function(a,c,d){for(var i,j,e=a.length,f=new b(0|(e+1)/3,c,d),g=0,h=0,k=!1,l=!1,m=!1,n=!1,o=!1;e>g;){switch(i=a.charAt(g++)){case"!":if(!d){if(l||m||n){o=!0;break}l=m=n=!0;}f.offset=f.markedOffset=f.limit=h,k=!1;break;case"|":if(!d){if(l||n){o=!0;break}l=n=!0;}f.offset=f.limit=h,k=!1;break;case"[":if(!d){if(l||m){o=!0;break}l=m=!0;}f.offset=f.markedOffset=h,k=!1;break;case"<":if(!d){if(l){o=!0;break}l=!0;}f.offset=h,k=!1;break;case"]":if(!d){if(n||m){o=!0;break}n=m=!0;}f.limit=f.markedOffset=h,k=!1;break;case">":if(!d){if(n){o=!0;break}n=!0;}f.limit=h,k=!1;break;case"'":if(!d){if(m){o=!0;break}m=!0;}f.markedOffset=h,k=!1;break;case" ":k=!1;break;default:if(!d&&k){o=!0;break}if(j=parseInt(i+a.charAt(g++),16),!d&&(isNaN(j)||0>j||j>255))throw TypeError("Illegal str: Not a debug encoded string");f.view[h++]=j,k=!0;}if(o)throw TypeError("Illegal str: Invalid symbol at "+g)}if(!d){if(!l||!n)throw TypeError("Illegal str: Missing offset or limit");if(h>>=0,"number"!=typeof b||0!==b%1)throw TypeError("Illegal end: Not an integer");if(b>>>=0,0>a||a>b||b>this.buffer.byteLength)throw RangeError("Illegal range: 0 <= "+a+" <= "+b+" <= "+this.buffer.byteLength)}for(var d,c=new Array(b-a);b>a;)d=this.view[a++],16>d?c.push("0",d.toString(16)):c.push(d.toString(16));return c.join("")},b.fromHex=function(a,c,d){var g,e,f,h,i;if(!d){if("string"!=typeof a)throw TypeError("Illegal str: Not a string");if(0!==a.length%2)throw TypeError("Illegal str: Length not a multiple of 2")}for(e=a.length,f=new b(0|e/2,c),h=0,i=0;e>h;h+=2){if(g=parseInt(a.substring(h,h+2),16),!d&&(!isFinite(g)||0>g||g>255))throw TypeError("Illegal str: Contains non-hex characters");f.view[i++]=g;}return f.limit=i,f},k=function(){var a={};return a.MAX_CODEPOINT=1114111,a.encodeUTF8=function(a,b){var c=null;for("number"==typeof a&&(c=a,a=function(){return null});null!==c||null!==(c=a());)128>c?b(127&c):2048>c?(b(192|31&c>>6),b(128|63&c)):65536>c?(b(224|15&c>>12),b(128|63&c>>6),b(128|63&c)):(b(240|7&c>>18),b(128|63&c>>12),b(128|63&c>>6),b(128|63&c)),c=null;},a.decodeUTF8=function(a,b){for(var c,d,e,f,g=function(a){a=a.slice(0,a.indexOf(null));var b=Error(a.toString());throw b.name="TruncatedError",b.bytes=a,b};null!==(c=a());)if(0===(128&c))b(c);else if(192===(224&c))null===(d=a())&&g([c,d]),b((31&c)<<6|63&d);else if(224===(240&c))(null===(d=a())||null===(e=a()))&&g([c,d,e]),b((15&c)<<12|(63&d)<<6|63&e);else{if(240!==(248&c))throw RangeError("Illegal starting byte: "+c);(null===(d=a())||null===(e=a())||null===(f=a()))&&g([c,d,e,f]),b((7&c)<<18|(63&d)<<12|(63&e)<<6|63&f);}},a.UTF16toUTF8=function(a,b){for(var c,d=null;;){if(null===(c=null!==d?d:a()))break;c>=55296&&57343>=c&&null!==(d=a())&&d>=56320&&57343>=d?(b(1024*(c-55296)+d-56320+65536),d=null):b(c);}null!==d&&b(d);},a.UTF8toUTF16=function(a,b){var c=null;for("number"==typeof a&&(c=a,a=function(){return null});null!==c||null!==(c=a());)65535>=c?b(c):(c-=65536,b((c>>10)+55296),b(c%1024+56320)),c=null;},a.encodeUTF16toUTF8=function(b,c){a.UTF16toUTF8(b,function(b){a.encodeUTF8(b,c);});},a.decodeUTF8toUTF16=function(b,c){a.decodeUTF8(b,function(b){a.UTF8toUTF16(b,c);});},a.calculateCodePoint=function(a){return 128>a?1:2048>a?2:65536>a?3:4},a.calculateUTF8=function(a){for(var b,c=0;null!==(b=a());)c+=128>b?1:2048>b?2:65536>b?3:4;return c},a.calculateUTF16asUTF8=function(b){var c=0,d=0;return a.UTF16toUTF8(b,function(a){++c,d+=128>a?1:2048>a?2:65536>a?3:4;}),[c,d]},a}(),c.toUTF8=function(a,b){if("undefined"==typeof a&&(a=this.offset),"undefined"==typeof b&&(b=this.limit),!this.noAssert){if("number"!=typeof a||0!==a%1)throw TypeError("Illegal begin: Not an integer");if(a>>>=0,"number"!=typeof b||0!==b%1)throw TypeError("Illegal end: Not an integer");if(b>>>=0,0>a||a>b||b>this.buffer.byteLength)throw RangeError("Illegal range: 0 <= "+a+" <= "+b+" <= "+this.buffer.byteLength)}var c;try{k.decodeUTF8toUTF16(function(){return b>a?this.view[a++]:null}.bind(this),c=g());}catch(d){if(a!==b)throw RangeError("Illegal range: Truncated data, "+a+" != "+b)}return c()},b.fromUTF8=function(a,c,d){if(!d&&"string"!=typeof a)throw TypeError("Illegal str: Not a string");var e=new b(k.calculateUTF16asUTF8(f(a),!0)[1],c,d),g=0;return k.encodeUTF16toUTF8(f(a),function(a){e.view[g++]=a;}),e.limit=g,e},b}(c),e=function(b,c){var f,h,i,e={};return e.ByteBuffer=b,e.c=b,f=b,e.Long=c||null,e.VERSION="5.0.1",e.WIRE_TYPES={},e.WIRE_TYPES.VARINT=0,e.WIRE_TYPES.BITS64=1,e.WIRE_TYPES.LDELIM=2,e.WIRE_TYPES.STARTGROUP=3,e.WIRE_TYPES.ENDGROUP=4,e.WIRE_TYPES.BITS32=5,e.PACKABLE_WIRE_TYPES=[e.WIRE_TYPES.VARINT,e.WIRE_TYPES.BITS64,e.WIRE_TYPES.BITS32],e.TYPES={int32:{name:"int32",wireType:e.WIRE_TYPES.VARINT,defaultValue:0},uint32:{name:"uint32",wireType:e.WIRE_TYPES.VARINT,defaultValue:0},sint32:{name:"sint32",wireType:e.WIRE_TYPES.VARINT,defaultValue:0},int64:{name:"int64",wireType:e.WIRE_TYPES.VARINT,defaultValue:e.Long?e.Long.ZERO:void 0},uint64:{name:"uint64",wireType:e.WIRE_TYPES.VARINT,defaultValue:e.Long?e.Long.UZERO:void 0},sint64:{name:"sint64",wireType:e.WIRE_TYPES.VARINT,defaultValue:e.Long?e.Long.ZERO:void 0},bool:{name:"bool",wireType:e.WIRE_TYPES.VARINT,defaultValue:!1},"double":{name:"double",wireType:e.WIRE_TYPES.BITS64,defaultValue:0},string:{name:"string",wireType:e.WIRE_TYPES.LDELIM,defaultValue:""},bytes:{name:"bytes",wireType:e.WIRE_TYPES.LDELIM,defaultValue:null},fixed32:{name:"fixed32",wireType:e.WIRE_TYPES.BITS32,defaultValue:0},sfixed32:{name:"sfixed32",wireType:e.WIRE_TYPES.BITS32,defaultValue:0},fixed64:{name:"fixed64",wireType:e.WIRE_TYPES.BITS64,defaultValue:e.Long?e.Long.UZERO:void 0},sfixed64:{name:"sfixed64",wireType:e.WIRE_TYPES.BITS64,defaultValue:e.Long?e.Long.ZERO:void 0},"float":{name:"float",wireType:e.WIRE_TYPES.BITS32,defaultValue:0},"enum":{name:"enum",wireType:e.WIRE_TYPES.VARINT,defaultValue:0},message:{name:"message",wireType:e.WIRE_TYPES.LDELIM,defaultValue:null},group:{name:"group",wireType:e.WIRE_TYPES.STARTGROUP,defaultValue:null}},e.MAP_KEY_TYPES=[e.TYPES.int32,e.TYPES.sint32,e.TYPES.sfixed32,e.TYPES.uint32,e.TYPES.fixed32,e.TYPES.int64,e.TYPES.sint64,e.TYPES.sfixed64,e.TYPES.uint64,e.TYPES.fixed64,e.TYPES.bool,e.TYPES.string,e.TYPES.bytes],e.ID_MIN=1,e.ID_MAX=536870911,e.convertFieldsToCamelCase=!1,e.populateAccessors=!0,e.populateDefaults=!0,e.Util=function(){var a={};return a.IS_NODE=!("object"!=typeof process||"[object process]"!=process+""||process.browser),a.XHR=function(){var c,a=[function(){return new XMLHttpRequest},function(){return new ActiveXObject("Msxml2.XMLHTTP")},function(){return new ActiveXObject("Msxml3.XMLHTTP")},function(){return new ActiveXObject("Microsoft.XMLHTTP")}],b=null;for(c=0;c]/g,RULE:/^(?:required|optional|repeated|map)$/,TYPE:/^(?:double|float|int32|uint32|sint32|int64|uint64|sint64|fixed32|sfixed32|fixed64|sfixed64|bool|string|bytes)$/,NAME:/^[a-zA-Z_][a-zA-Z_0-9]*$/,TYPEDEF:/^[a-zA-Z][a-zA-Z_0-9]*$/,TYPEREF:/^(?:\.?[a-zA-Z_][a-zA-Z_0-9]*)+$/,FQTYPEREF:/^(?:\.[a-zA-Z][a-zA-Z_0-9]*)+$/,NUMBER:/^-?(?:[1-9][0-9]*|0|0[xX][0-9a-fA-F]+|0[0-7]+|([0-9]*(\.[0-9]*)?([Ee][+-]?[0-9]+)?)|inf|nan)$/,NUMBER_DEC:/^(?:[1-9][0-9]*|0)$/,NUMBER_HEX:/^0[xX][0-9a-fA-F]+$/,NUMBER_OCT:/^0[0-7]+$/,NUMBER_FLT:/^([0-9]*(\.[0-9]*)?([Ee][+-]?[0-9]+)?|inf|nan)$/,BOOL:/^(?:true|false)$/i,ID:/^(?:[1-9][0-9]*|0|0[xX][0-9a-fA-F]+|0[0-7]+)$/,NEGID:/^\-?(?:[1-9][0-9]*|0|0[xX][0-9a-fA-F]+|0[0-7]+)$/,WHITESPACE:/\s/,STRING:/(?:"([^"\\]*(?:\\.[^"\\]*)*)")|(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g,STRING_DQ:/(?:"([^"\\]*(?:\\.[^"\\]*)*)")/g,STRING_SQ:/(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g},e.DotProto=function(a,b){function h(a,c){var d=-1,e=1;if("-"==a.charAt(0)&&(e=-1,a=a.substring(1)),b.NUMBER_DEC.test(a))d=parseInt(a);else if(b.NUMBER_HEX.test(a))d=parseInt(a.substring(2),16);else{if(!b.NUMBER_OCT.test(a))throw Error("illegal id value: "+(0>e?"-":"")+a);d=parseInt(a.substring(1),8);}if(d=0|e*d,!c&&0>d)throw Error("illegal id value: "+(0>e?"-":"")+a);return d}function i(a){var c=1;if("-"==a.charAt(0)&&(c=-1,a=a.substring(1)),b.NUMBER_DEC.test(a))return c*parseInt(a,10);if(b.NUMBER_HEX.test(a))return c*parseInt(a.substring(2),16);if(b.NUMBER_OCT.test(a))return c*parseInt(a.substring(1),8);if("inf"===a)return 1/0*c;if("nan"===a)return 0/0;if(b.NUMBER_FLT.test(a))return c*parseFloat(a);throw Error("illegal number value: "+(0>c?"-":"")+a)}function j(a,b,c){"undefined"==typeof a[b]?a[b]=c:(Array.isArray(a[b])||(a[b]=[a[b]]),a[b].push(c));}var f,g,c={},d=function(a){this.source=a+"",this.index=0,this.line=1,this.stack=[],this._stringOpen=null;},e=d.prototype;return e._readString=function(){var c,a='"'===this._stringOpen?b.STRING_DQ:b.STRING_SQ;if(a.lastIndex=this.index-1,c=a.exec(this.source),!c)throw Error("unterminated string");return this.index=a.lastIndex,this.stack.push(this._stringOpen),this._stringOpen=null,c[1]},e.next=function(){var a,c,d,e,f,g;if(this.stack.length>0)return this.stack.shift();if(this.index>=this.source.length)return null;if(null!==this._stringOpen)return this._readString();do{for(a=!1;b.WHITESPACE.test(d=this.source.charAt(this.index));)if("\n"===d&&++this.line,++this.index===this.source.length)return null;if("/"===this.source.charAt(this.index))if(++this.index,"/"===this.source.charAt(this.index)){for(;"\n"!==this.source.charAt(++this.index);)if(this.index==this.source.length)return null;++this.index,++this.line,a=!0;}else{if("*"!==(d=this.source.charAt(this.index)))return "/";do{if("\n"===d&&++this.line,++this.index===this.source.length)return null;c=d,d=this.source.charAt(this.index);}while("*"!==c||"/"!==d);++this.index,a=!0;}}while(a);if(this.index===this.source.length)return null;if(e=this.index,b.DELIM.lastIndex=0,f=b.DELIM.test(this.source.charAt(e++)),!f)for(;e"),f=this.tn.next(),!b.NAME.test(f))throw Error("illegal message field name: "+f);e.name=f,this.tn.skip("="),e.id=h(this.tn.next()),f=this.tn.peek(),"["===f&&this._parseFieldOptions(e),this.tn.skip(";");}else if(d="undefined"!=typeof d?d:this.tn.next(),"group"===d){if(g=this._parseMessage(a,e),!/^[A-Z]/.test(g.name))throw Error("illegal group name: "+g.name);e.type=g.name,e.name=g.name.toLowerCase(),this.tn.omit(";");}else{if(!b.TYPE.test(d)&&!b.TYPEREF.test(d))throw Error("illegal message field type: "+d);if(e.type=d,f=this.tn.next(),!b.NAME.test(f))throw Error("illegal message field name: "+f); e.name=f,this.tn.skip("="),e.id=h(this.tn.next()),f=this.tn.peek(),"["===f&&this._parseFieldOptions(e),this.tn.skip(";");}return a.fields.push(e),e},g._parseMessageOneOf=function(a){var e,d,f,c=this.tn.next();if(!b.NAME.test(c))throw Error("illegal oneof name: "+c);for(d=c,f=[],this.tn.skip("{");"}"!==(c=this.tn.next());)e=this._parseMessageField(a,"optional",c),e.oneof=d,f.push(e.id);this.tn.omit(";"),a.oneofs[d]=f;},g._parseFieldOptions=function(a){this.tn.skip("[");for(var b,c=!0;"]"!==(b=this.tn.peek());)c||this.tn.skip(","),this._parseOption(a,!0),c=!1;this.tn.next();},g._parseEnum=function(a){var e,c={name:"",values:[],options:{}},d=this.tn.next();if(!b.NAME.test(d))throw Error("illegal name: "+d);for(c.name=d,this.tn.skip("{");"}"!==(d=this.tn.next());)if("option"===d)this._parseOption(c);else{if(!b.NAME.test(d))throw Error("illegal name: "+d);this.tn.skip("="),e={name:d,id:h(this.tn.next(),!0)},d=this.tn.peek(),"["===d&&this._parseFieldOptions({options:{}}),this.tn.skip(";"),c.values.push(e);}this.tn.omit(";"),a.enums.push(c);},g._parseExtensionRanges=function(){var c,d,e,b=[];do{for(d=[];;){switch(c=this.tn.next()){case"min":e=a.ID_MIN;break;case"max":e=a.ID_MAX;break;default:e=i(c);}if(d.push(e),2===d.length)break;if("to"!==this.tn.peek()){d.push(e);break}this.tn.next();}b.push(d);}while(this.tn.omit(","));return this.tn.skip(";"),b},g._parseExtend=function(a){var d,c=this.tn.next();if(!b.TYPEREF.test(c))throw Error("illegal extend reference: "+c);for(d={ref:c,fields:[]},this.tn.skip("{");"}"!==(c=this.tn.next());)if(b.RULE.test(c))this._parseMessageField(d,c);else{if(!b.TYPEREF.test(c))throw Error("illegal extend token: "+c);if(!this.proto3)throw Error("illegal field rule: "+c);this._parseMessageField(d,"optional",c);}return this.tn.omit(";"),a.messages.push(d),d},g.toString=function(){return "Parser at line "+this.tn.line},c.Parser=f,c}(e,e.Lang),e.Reflect=function(a){function k(b){if("string"==typeof b&&(b=a.TYPES[b]),"undefined"==typeof b.defaultValue)throw Error("default value for type "+b.name+" is not supported");return b==a.TYPES.bytes?new f(0):b.defaultValue}function l(b,c){if(b&&"number"==typeof b.low&&"number"==typeof b.high&&"boolean"==typeof b.unsigned&&b.low===b.low&&b.high===b.high)return new a.Long(b.low,b.high,"undefined"==typeof c?b.unsigned:c);if("string"==typeof b)return a.Long.fromString(b,c||!1,10);if("number"==typeof b)return a.Long.fromNumber(b,c||!1);throw Error("not convertible to Long")}function o(b,c){var d=c.readVarint32(),e=7&d,f=d>>>3;switch(e){case a.WIRE_TYPES.VARINT:do d=c.readUint8();while(128===(128&d));break;case a.WIRE_TYPES.BITS64:c.offset+=8;break;case a.WIRE_TYPES.LDELIM:d=c.readVarint32(),c.offset+=d;break;case a.WIRE_TYPES.STARTGROUP:o(f,c);break;case a.WIRE_TYPES.ENDGROUP:if(f===b)return !1;throw Error("Illegal GROUPEND after unknown group: "+f+" ("+b+" expected)");case a.WIRE_TYPES.BITS32:c.offset+=4;break;default:throw Error("Illegal wire type in unknown group "+b+": "+e)}return !0}var g,h,i,j,m,n,p,q,r,s,t,u,v,w,x,y,z,A,B,c={},d=function(a,b,c){this.builder=a,this.parent=b,this.name=c,this.className;},e=d.prototype;return e.fqn=function(){for(var a=this.name,b=this;;){if(b=b.parent,null==b)break;a=b.name+"."+a;}return a},e.toString=function(a){return (a?this.className+" ":"")+this.fqn()},e.build=function(){throw Error(this.toString(!0)+" cannot be built directly")},c.T=d,g=function(a,b,c,e,f){d.call(this,a,b,c),this.className="Namespace",this.children=[],this.options=e||{},this.syntax=f||"proto2";},h=g.prototype=Object.create(d.prototype),h.getChildren=function(a){var b,c,d;if(a=a||null,null==a)return this.children.slice();for(b=[],c=0,d=this.children.length;d>c;++c)this.children[c]instanceof a&&b.push(this.children[c]);return b},h.addChild=function(a){var b;if(b=this.getChild(a.name))if(b instanceof m.Field&&b.name!==b.originalName&&null===this.getChild(b.originalName))b.name=b.originalName;else{if(!(a instanceof m.Field&&a.name!==a.originalName&&null===this.getChild(a.originalName)))throw Error("Duplicate name in namespace "+this.toString(!0)+": "+a.name);a.name=a.originalName;}this.children.push(a);},h.getChild=function(a){var c,d,b="number"==typeof a?"id":"name";for(c=0,d=this.children.length;d>c;++c)if(this.children[c][b]===a)return this.children[c];return null},h.resolve=function(a,b){var g,d="string"==typeof a?a.split("."):a,e=this,f=0;if(""===d[f]){for(;null!==e.parent;)e=e.parent;f++;}do{do{if(!(e instanceof c.Namespace)){e=null;break}if(g=e.getChild(d[f]),!(g&&g instanceof c.T&&(!b||g instanceof c.Namespace))){e=null;break}e=g,f++;}while(fc;++c)e=b[c],e instanceof g&&(a[e.name]=e.build());return Object.defineProperty&&Object.defineProperty(a,"$options",{value:this.buildOpt()}),a},h.buildOpt=function(){var c,d,e,f,a={},b=Object.keys(this.options);for(c=0,d=b.length;d>c;++c)e=b[c],f=this.options[b[c]],a[e]=f;return a},h.getOption=function(a){return "undefined"==typeof a?this.options:"undefined"!=typeof this.options[a]?this.options[a]:null},c.Namespace=g,i=function(b,c,d,e){if(this.type=b,this.resolvedType=c,this.isMapKey=d,this.syntax=e,d&&a.MAP_KEY_TYPES.indexOf(b)<0)throw Error("Invalid map key type: "+b.name)},j=i.prototype,i.defaultFieldValue=k,j.verifyValue=function(c){var f,g,h,d=function(a,b){throw Error("Illegal value for "+this.toString(!0)+" of type "+this.type.name+": "+a+" ("+b+")")}.bind(this);switch(this.type){case a.TYPES.int32:case a.TYPES.sint32:case a.TYPES.sfixed32:return ("number"!=typeof c||c===c&&0!==c%1)&&d(typeof c,"not an integer"),c>4294967295?0|c:c;case a.TYPES.uint32:case a.TYPES.fixed32:return ("number"!=typeof c||c===c&&0!==c%1)&&d(typeof c,"not an integer"),0>c?c>>>0:c;case a.TYPES.int64:case a.TYPES.sint64:case a.TYPES.sfixed64:if(a.Long)try{return l(c,!1)}catch(e){d(typeof c,e.message);}else d(typeof c,"requires Long.js");case a.TYPES.uint64:case a.TYPES.fixed64:if(a.Long)try{return l(c,!0)}catch(e){d(typeof c,e.message);}else d(typeof c,"requires Long.js");case a.TYPES.bool:return "boolean"!=typeof c&&d(typeof c,"not a boolean"),c;case a.TYPES["float"]:case a.TYPES["double"]:return "number"!=typeof c&&d(typeof c,"not a number"),c;case a.TYPES.string:return "string"==typeof c||c&&c instanceof String||d(typeof c,"not a string"),""+c;case a.TYPES.bytes:return b.isByteBuffer(c)?c:b.wrap(c);case a.TYPES["enum"]:for(f=this.resolvedType.getChildren(a.Reflect.Enum.Value),h=0;h4294967295||0>c)&&d(typeof c,"not in range for uint32"),c;d(c,"not a valid enum value");case a.TYPES.group:case a.TYPES.message:if(c&&"object"==typeof c||d(typeof c,"object expected"),c instanceof this.resolvedType.clazz)return c;if(c instanceof a.Builder.Message){g={};for(h in c)c.hasOwnProperty(h)&&(g[h]=c[h]);c=g;}return new this.resolvedType.clazz(c)}throw Error("[INTERNAL] Illegal value for "+this.toString(!0)+": "+c+" (undefined type "+this.type+")")},j.calculateLength=function(b,c){if(null===c)return 0;var d;switch(this.type){case a.TYPES.int32:return 0>c?f.calculateVarint64(c):f.calculateVarint32(c);case a.TYPES.uint32:return f.calculateVarint32(c);case a.TYPES.sint32:return f.calculateVarint32(f.zigZagEncode32(c));case a.TYPES.fixed32:case a.TYPES.sfixed32:case a.TYPES["float"]:return 4;case a.TYPES.int64:case a.TYPES.uint64:return f.calculateVarint64(c);case a.TYPES.sint64:return f.calculateVarint64(f.zigZagEncode64(c));case a.TYPES.fixed64:case a.TYPES.sfixed64:return 8;case a.TYPES.bool:return 1;case a.TYPES["enum"]:return f.calculateVarint32(c);case a.TYPES["double"]:return 8;case a.TYPES.string:return d=f.calculateUTF8Bytes(c),f.calculateVarint32(d)+d;case a.TYPES.bytes:if(c.remaining()<0)throw Error("Illegal value for "+this.toString(!0)+": "+c.remaining()+" bytes remaining");return f.calculateVarint32(c.remaining())+c.remaining();case a.TYPES.message:return d=this.resolvedType.calculate(c),f.calculateVarint32(d)+d;case a.TYPES.group:return d=this.resolvedType.calculate(c),d+f.calculateVarint32(b<<3|a.WIRE_TYPES.ENDGROUP)}throw Error("[INTERNAL] Illegal value to encode in "+this.toString(!0)+": "+c+" (unknown type)")},j.encodeValue=function(b,c,d){var e,g;if(null===c)return d;switch(this.type){case a.TYPES.int32:0>c?d.writeVarint64(c):d.writeVarint32(c);break;case a.TYPES.uint32:d.writeVarint32(c);break;case a.TYPES.sint32:d.writeVarint32ZigZag(c);break;case a.TYPES.fixed32:d.writeUint32(c);break;case a.TYPES.sfixed32:d.writeInt32(c);break;case a.TYPES.int64:case a.TYPES.uint64:d.writeVarint64(c);break;case a.TYPES.sint64:d.writeVarint64ZigZag(c);break;case a.TYPES.fixed64:d.writeUint64(c);break;case a.TYPES.sfixed64:d.writeInt64(c);break;case a.TYPES.bool:"string"==typeof c?d.writeVarint32("false"===c.toLowerCase()?0:!!c):d.writeVarint32(c?1:0);break;case a.TYPES["enum"]:d.writeVarint32(c);break;case a.TYPES["float"]:d.writeFloat32(c);break;case a.TYPES["double"]:d.writeFloat64(c);break;case a.TYPES.string:d.writeVString(c);break;case a.TYPES.bytes:if(c.remaining()<0)throw Error("Illegal value for "+this.toString(!0)+": "+c.remaining()+" bytes remaining");e=c.offset,d.writeVarint32(c.remaining()),d.append(c),c.offset=e;break;case a.TYPES.message:g=(new f).LE(),this.resolvedType.encode(c,g),d.writeVarint32(g.offset),d.append(g.flip());break;case a.TYPES.group:this.resolvedType.encode(c,d),d.writeVarint32(b<<3|a.WIRE_TYPES.ENDGROUP);break;default:throw Error("[INTERNAL] Illegal value to encode in "+this.toString(!0)+": "+c+" (unknown type)")}return d},j.decode=function(b,c,d){if(c!=this.type.wireType)throw Error("Unexpected wire type for element");var e,f;switch(this.type){case a.TYPES.int32:return 0|b.readVarint32();case a.TYPES.uint32:return b.readVarint32()>>>0;case a.TYPES.sint32:return 0|b.readVarint32ZigZag();case a.TYPES.fixed32:return b.readUint32()>>>0;case a.TYPES.sfixed32:return 0|b.readInt32();case a.TYPES.int64:return b.readVarint64();case a.TYPES.uint64:return b.readVarint64().toUnsigned();case a.TYPES.sint64:return b.readVarint64ZigZag();case a.TYPES.fixed64:return b.readUint64();case a.TYPES.sfixed64:return b.readInt64();case a.TYPES.bool:return !!b.readVarint32();case a.TYPES["enum"]:return b.readVarint32();case a.TYPES["float"]:return b.readFloat();case a.TYPES["double"]:return b.readDouble();case a.TYPES.string:return b.readVString();case a.TYPES.bytes:if(f=b.readVarint32(),b.remaining()i;++i)this[e[i].name]=null;for(i=0,j=d.length;j>i;++i)k=d[i],this[k.name]=k.repeated?[]:k.map?new a.Map(k):null,!k.required&&"proto3"!==c.syntax||null===k.defaultValue||(this[k.name]=k.defaultValue);if(arguments.length>0)if(1!==arguments.length||null===b||"object"!=typeof b||!("function"!=typeof b.encode||b instanceof g)||Array.isArray(b)||b instanceof a.Map||f.isByteBuffer(b)||b instanceof ArrayBuffer||a.Long&&b instanceof a.Long)for(i=0,j=arguments.length;j>i;++i)"undefined"!=typeof(l=arguments[i])&&this.$set(d[i].name,l);else this.$set(b);},h=g.prototype=Object.create(a.Builder.Message.prototype);for(h.add=function(b,d,e){var f=c._fieldsByName[b];if(!e){if(!f)throw Error(this+"#"+b+" is undefined");if(!(f instanceof a.Reflect.Message.Field))throw Error(this+"#"+b+" is not a field: "+f.toString(!0));if(!f.repeated)throw Error(this+"#"+b+" is not a repeated field");d=f.verifyValue(d,!0);}return null===this[b]&&(this[b]=[]),this[b].push(d),this},h.$add=h.add,h.set=function(b,d,e){var f,g,h;if(b&&"object"==typeof b){e=d;for(f in b)b.hasOwnProperty(f)&&"undefined"!=typeof(d=b[f])&&this.$set(f,d,e);return this}if(g=c._fieldsByName[b],e)this[b]=d;else{if(!g)throw Error(this+"#"+b+" is not a field: undefined");if(!(g instanceof a.Reflect.Message.Field))throw Error(this+"#"+b+" is not a field: "+g.toString(!0));this[g.name]=d=g.verifyValue(d);}return g&&g.oneof&&(h=this[g.oneof.name],null!==d?(null!==h&&h!==g.name&&(this[h]=null),this[g.oneof.name]=g.name):h===b&&(this[g.oneof.name]=null)),this},h.$set=h.set,h.get=function(b,d){if(d)return this[b];var e=c._fieldsByName[b];if(!(e&&e instanceof a.Reflect.Message.Field))throw Error(this+"#"+b+" is not a field: undefined");if(!(e instanceof a.Reflect.Message.Field))throw Error(this+"#"+b+" is not a field: "+e.toString(!0));return this[e.name]},h.$get=h.get,i=0;ie;e++)if(h=this.children[e],h instanceof t||h instanceof m||h instanceof x){if(d.hasOwnProperty(h.name))throw Error("Illegal reflect child of "+this.toString(!0)+": "+h.toString(!0)+" cannot override static property '"+h.name+"'");d[h.name]=h.build();}else if(h instanceof m.Field)h.build(),this._fields.push(h),this._fieldsById[h.id]=h,this._fieldsByName[h.name]=h;else if(!(h instanceof m.OneOf||h instanceof w))throw Error("Illegal reflect child of "+this.toString(!0)+": "+this.children[e].toString(!0));return this.clazz=d},n.encode=function(a,b,c){var e,h,f,g,i,d=null;for(f=0,g=this._fields.length;g>f;++f)e=this._fields[f],h=a[e.name],e.required&&null===h?null===d&&(d=e):e.encode(c?h:e.verifyValue(h),b,a);if(null!==d)throw i=Error("Missing at least one required field for "+this.toString(!0)+": "+d),i.encoded=b,i;return b},n.calculate=function(a){for(var e,f,b=0,c=0,d=this._fields.length;d>c;++c){if(e=this._fields[c],f=a[e.name],e.required&&null===f)throw Error("Missing at least one required field for "+this.toString(!0)+": "+e);b+=e.calculate(f,a);}return b},n.decode=function(b,c,d){var g,h,i,j,e,f,k,l,m,n,p,q;for(c="number"==typeof c?c:-1,e=b.offset,f=new this.clazz;b.offset0;){if(g=b.readVarint32(),h=7&g,i=g>>>3,h===a.WIRE_TYPES.ENDGROUP){if(i!==d)throw Error("Illegal group end indicator for "+this.toString(!0)+": "+i+" ("+(d?d+" expected":"not a group")+")");break}if(j=this._fieldsById[i])j.repeated&&!j.options.packed?f[j.name].push(j.decode(h,b)):j.map?(l=j.decode(h,b),f[j.name].set(l[0],l[1])):(f[j.name]=j.decode(h,b),j.oneof&&(m=f[j.oneof.name],null!==m&&m!==j.name&&(f[m]=null),f[j.oneof.name]=j.name));else switch(h){case a.WIRE_TYPES.VARINT:b.readVarint32();break;case a.WIRE_TYPES.BITS32:b.offset+=4;break;case a.WIRE_TYPES.BITS64:b.offset+=8;break;case a.WIRE_TYPES.LDELIM:k=b.readVarint32(),b.offset+=k;break;case a.WIRE_TYPES.STARTGROUP:for(;o(i,b););break;default:throw Error("Illegal wire type for unknown field "+i+" in "+this.toString(!0)+"#decode: "+h)}}for(n=0,p=this._fields.length;p>n;++n)if(j=this._fields[n],null===f[j.name])if("proto3"===this.syntax)f[j.name]=j.defaultValue;else{if(j.required)throw q=Error("Missing at least one required field for "+this.toString(!0)+": "+j.name),q.decoded=f,q;a.populateDefaults&&null!==j.defaultValue&&(f[j.name]=j.defaultValue);}return f},c.Message=m,p=function(b,c,e,f,g,h,i,j,k,l){d.call(this,b,c,h),this.className="Message.Field",this.required="required"===e,this.repeated="repeated"===e,this.map="map"===e,this.keyType=f||null,this.type=g,this.resolvedType=null,this.id=i,this.options=j||{},this.defaultValue=null,this.oneof=k||null,this.syntax=l||"proto2",this.originalName=this.name,this.element=null,this.keyElement=null,!this.builder.options.convertFieldsToCamelCase||this instanceof m.ExtensionField||(this.name=a.Util.toCamelCase(this.name));},q=p.prototype=Object.create(d.prototype),q.build=function(){this.element=new i(this.type,this.resolvedType,!1,this.syntax),this.map&&(this.keyElement=new i(this.keyType,void 0,!0,this.syntax)),"proto3"!==this.syntax||this.repeated||this.map?"undefined"!=typeof this.options["default"]&&(this.defaultValue=this.verifyValue(this.options["default"])):this.defaultValue=i.defaultFieldValue(this.type);},q.verifyValue=function(b,c){var d,e,f;if(c=c||!1,d=function(a,b){throw Error("Illegal value for "+this.toString(!0)+" of type "+this.type.name+": "+a+" ("+b+")")}.bind(this),null===b)return this.required&&d(typeof b,"required"),"proto3"===this.syntax&&this.type!==a.TYPES.message&&d(typeof b,"proto3 field without field presence cannot be null"),null;if(this.repeated&&!c){for(Array.isArray(b)||(b=[b]),f=[],e=0;e0;case a.TYPES.bytes:return b.remaining()>0;case a.TYPES["enum"]:return 0!==b;case a.TYPES.message:return null!==b;default:return !0}},q.encode=function(b,c,d){var e,g,h,i,j;if(null===this.type||"object"!=typeof this.type)throw Error("[INTERNAL] Unresolved type in "+this.toString(!0)+": "+this.type);if(null===b||this.repeated&&0==b.length)return c;try{if(this.repeated)if(this.options.packed&&a.PACKABLE_WIRE_TYPES.indexOf(this.type.wireType)>=0){for(c.writeVarint32(this.id<<3|a.WIRE_TYPES.LDELIM),c.ensureCapacity(c.offset+=1),g=c.offset,e=0;e1&&(j=c.slice(g,c.offset),g+=i-1,c.offset=g,c.append(j)),c.writeVarint32(h,g-i);}else for(e=0;e=0){for(d+=f.calculateVarint32(this.id<<3|a.WIRE_TYPES.LDELIM),g=0,e=0;e=0&&!d){for(f=c.readVarint32(),f=c.offset+f,h=[];c.offset0;)if(l=k.readVarint32(),b=7&l,m=l>>>3,1===m)j=this.keyElement.decode(k,b,m);else{if(2!==m)throw Error("Unexpected tag in map field key/value submessage");e=this.element.decode(k,b,m);}return [j,e]}return this.element.decode(c,b,this.id)},c.Message.Field=p,r=function(a,b,c,d,e,f,g){p.call(this,a,b,c,null,d,e,f,g),this.extension;},r.prototype=Object.create(p.prototype),c.Message.ExtensionField=r,s=function(a,b,c){d.call(this,a,b,c),this.fields=[];},c.Message.OneOf=s,t=function(a,b,c,d,e){g.call(this,a,b,c,d,e),this.className="Enum",this.object=null;},t.getName=function(a,b){var e,d,c=Object.keys(a);for(d=0;de;++e)c[d[e]["name"]]=d[e]["id"];return Object.defineProperty&&Object.defineProperty(c,"$options",{value:this.buildOpt(),enumerable:!1}),this.object=c},c.Enum=t,v=function(a,b,c,e){d.call(this,a,b,c),this.className="Enum.Value",this.id=e;},v.prototype=Object.create(d.prototype),c.Enum.Value=v,w=function(a,b,c,e){d.call(this,a,b,c),this.field=e;},w.prototype=Object.create(d.prototype),c.Extension=w,x=function(a,b,c,d){g.call(this,a,b,c,d),this.className="Service",this.clazz=null;},y=x.prototype=Object.create(g.prototype),y.build=function(b){return this.clazz&&!b?this.clazz:this.clazz=function(a,b){var g,c=function(b){a.Builder.Service.call(this),this.rpcImpl=b||function(a,b,c){setTimeout(c.bind(this,Error("Not implemented, see: https://github.com/dcodeIO/ProtoBuf.js/wiki/Services")),0);};},d=c.prototype=Object.create(a.Builder.Service.prototype),e=b.getChildren(a.Reflect.Service.RPCMethod);for(g=0;g0;){if(b=e.pop(),!Array.isArray(b))throw Error("not a valid namespace: "+JSON.stringify(b));for(;b.length>0;){if(f=b.shift(),d.isMessage(f)){if(g=new c.Message(this,this.ptr,f.name,f.options,f.isGroup,f.syntax),h={},f.oneofs&&Object.keys(f.oneofs).forEach(function(a){g.addChild(h[a]=new c.Message.OneOf(this,g,a));},this),f.fields&&f.fields.forEach(function(a){if(null!==g.getChild(0|a.id))throw Error("duplicate or invalid field id in "+g.name+": "+a.id);if(a.options&&"object"!=typeof a.options)throw Error("illegal field options in "+g.name+"#"+a.name);var b=null;if("string"==typeof a.oneof&&!(b=h[a.oneof]))throw Error("illegal oneof in "+g.name+"#"+a.name+": "+a.oneof);a=new c.Message.Field(this,g,a.rule,a.keytype,a.type,a.name,a.id,a.options,b,f.syntax),b&&b.fields.push(a),g.addChild(a);},this),i=[],f.enums&&f.enums.forEach(function(a){i.push(a);}),f.messages&&f.messages.forEach(function(a){i.push(a);}),f.services&&f.services.forEach(function(a){i.push(a);}),f.extensions&&(g.extensions="number"==typeof f.extensions[0]?[f.extensions]:f.extensions),this.ptr.addChild(g),i.length>0){e.push(b),b=i,i=null,this.ptr=g,g=null;continue}i=null;}else if(d.isEnum(f))g=new c.Enum(this,this.ptr,f.name,f.options,f.syntax),f.values.forEach(function(a){g.addChild(new c.Enum.Value(this,g,a.name,a.id));},this),this.ptr.addChild(g);else if(d.isService(f))g=new c.Service(this,this.ptr,f.name,f.options),Object.keys(f.rpc).forEach(function(a){var b=f.rpc[a];g.addChild(new c.Service.RPCMethod(this,g,a,b.request,b.response,!!b.request_stream,!!b.response_stream,b.options));},this),this.ptr.addChild(g);else{if(!d.isExtend(f))throw Error("not a valid definition: "+JSON.stringify(f));if(g=this.ptr.resolve(f.ref,!0))f.fields.forEach(function(b){var d,e,f,h;if(null!==g.getChild(0|b.id))throw Error("duplicate extended field id in "+g.name+": "+b.id); if(g.extensions&&(d=!1,g.extensions.forEach(function(a){b.id>=a[0]&&b.id<=a[1]&&(d=!0);}),!d))throw Error("illegal extended field id in "+g.name+": "+b.id+" (not within valid ranges)");e=b.name,this.options.convertFieldsToCamelCase&&(e=a.Util.toCamelCase(e)),f=new c.Message.ExtensionField(this,g,b.rule,b.type,this.ptr.fqn()+"."+e,b.id,b.options),h=new c.Extension(this,this.ptr,b.name,f),f.extension=h,this.ptr.addChild(h),g.addChild(f);},this);else if(!/\.?google\.protobuf\./.test(f.ref))throw Error("extended message "+f.ref+" is not defined")}f=null,g=null;}b=null,this.ptr=this.ptr.parent;}return this.resolved=!1,this.result=null,this},e["import"]=function(b,c){var e,g,h,i,j,k,l,m,d="/";if("string"==typeof c){if(a.Util.IS_NODE,this.files[c]===!0)return this.reset();this.files[c]=!0;}else if("object"==typeof c){if(e=c.root,a.Util.IS_NODE,(e.indexOf("\\")>=0||c.file.indexOf("\\")>=0)&&(d="\\"),g=e+d+c.file,this.files[g]===!0)return this.reset();this.files[g]=!0;}if(b.imports&&b.imports.length>0){for(i=!1,"object"==typeof c?(this.importRoot=c.root,i=!0,h=this.importRoot,c=c.file,(h.indexOf("\\")>=0||c.indexOf("\\")>=0)&&(d="\\")):"string"==typeof c?this.importRoot?h=this.importRoot:c.indexOf("/")>=0?(h=c.replace(/\/[^\/]*$/,""),""===h&&(h="/")):c.indexOf("\\")>=0?(h=c.replace(/\\[^\\]*$/,""),d="\\"):h=".":h=null,j=0;j= time) { return this._serverEngine.getConversationStatus(time); } else { return utils.Defer.reject(); } }; _proto._set = function _set(list) { var self = this; if (utils.isUndefined(list)) { return; } var time = self._timeStorage.get(STORAGE_CONVERSATION_STATUS.SUB_KEY.TIME) || 0; var listCount = list.length; utils.forEach(list, function (statusItem, index) { var updatedTime = statusItem.updatedTime || 0; time = updatedTime > time ? updatedTime : time; self._eventEmitter.emit(EventName.CHANGED, { statusItem: statusItem, isLastInAPull: index === listCount - 1 }); }); self._timeStorage.set(STORAGE_CONVERSATION_STATUS.SUB_KEY.TIME, time); }; return ConversationStatusManager; }(); var EventName$1 = { CHANGED: 'conversationChanged' }; var ConversationManager = function () { function ConversationManager(option, serverEngine) { this._selfUserId = void 0; this._store = void 0; this._eventEmitter = new utils.EventEmitter(); this._statusManager = void 0; this._allConversationList = []; this._updatedConversations = {}; var self = this; var statusManager = new ConversationStatusManager(serverEngine); statusManager.watchChanged(function (_ref) { var statusItem = _ref.statusItem, isLastInAPull = _ref.isLastInAPull; self._addStatus(statusItem, isLastInAPull); }); self._store = new ConversationStore(option); self._selfUserId = option.userId; self._statusManager = statusManager; } var _proto = ConversationManager.prototype; _proto.watch = function watch(events) { var conversation = events.conversation; this._eventEmitter.on(EventName$1.CHANGED, conversation); }; _proto.addMessage = function addMessage(msgArgs) { var self = this; var message = msgArgs.message, isLastInAPull = msgArgs.isLastInAPull, type = message.type, isPersited = message.isPersited, isSaveConversationType = utils.isInclude(TYPE_HAS_CONVERSATION, type); if (!isSaveConversationType) { return; } var hasChanged = false; var storageConversation = self._store.get(message); var calcEvents = [self._setUnreadCount, self._setMentiondInfo]; utils.forEach(calcEvents, function (event) { var _event$call = event.call(self, message, storageConversation), hasCalcChanged = _event$call.hasChanged, conversation = _event$call.conversation; hasChanged = hasChanged || hasCalcChanged; storageConversation = conversation; }); if (hasChanged) { self._store.set(message, storageConversation); } if (isPersited) { var conversation = self._getConversationByMessage(message); conversation.updatedItems = { latestMessage: { time: message.sentTime, val: message } }; self._setUpdatedConversation(conversation); } var isNeedNotifyUpdate = utils.isUndefined(isLastInAPull) ? true : isLastInAPull; if (isNeedNotifyUpdate) { self._notifyConversationChanged(); } }; _proto.get = function get(option) { var conversation = this._store.get(option); var notificationStatus = conversation.notificationStatus, isNotDisturb = utils.isEqual(notificationStatus, NOTIFICATION_STATUS.DO_NOT_DISTURB); if (isNotDisturb) { conversation.unreadMessageCount = 0; } return conversation; }; _proto.read = function read(option) { var self = this, type = option.type, targetId = option.targetId, _store = self._store, _updatedConversations = self._updatedConversations, key = common.getConversationKey(option), updatedConversation = _updatedConversations[key] || {}; var storeConversation = _store.get(option) || {}, _storeConversation = storeConversation, unreadMessageCount = _storeConversation.unreadMessageCount, hasMentiond = _storeConversation.hasMentiond; if (unreadMessageCount || hasMentiond) { var updatedTime = common.DelayTimer.getTime(); var updatedValues = { type: type, targetId: targetId, unreadMessageCount: 0, hasMentiond: false, mentiondInfo: null, updatedItems: { unreadMessageCount: { time: updatedTime, val: 0 }, hasMentiond: { time: updatedTime, val: false }, mentiondInfo: { time: updatedTime, val: null } } }; storeConversation = utils.extendAllowNull(storeConversation, updatedValues); _store.set(option, storeConversation); _updatedConversations[key] = utils.extendAllowNull(updatedConversation, updatedValues); self._notifyConversationChanged(); } }; _proto.getTotalUnreadCount = function getTotalUnreadCount() { var _store = this._store, conversationList = _store.getValues(); var totalCount = 0; utils.forEach(conversationList, function (_ref2) { var unreadMessageCount = _ref2.unreadMessageCount; unreadMessageCount = utils.isNumber(unreadMessageCount) ? unreadMessageCount : 0; totalCount += unreadMessageCount; }); return totalCount; }; _proto.getUnreadCount = function getUnreadCount(option) { var _store = this._store; var storeConversation = _store.get(option) || {}; var unreadMessageCount = storeConversation.unreadMessageCount; var count = utils.isNumber(unreadMessageCount) ? unreadMessageCount : 0; return count; }; _proto.close = function close() { this._statusManager.close(); }; _proto._getConversationByMessage = function _getConversationByMessage(message) { var type = message.type, targetId = message.targetId, storeConversation = this._store.get(message); var conversation = utils.extend(storeConversation, { type: type, targetId: targetId, latestMessage: message }); return conversation; }; _proto._getUpdatedConversationList = function _getUpdatedConversationList() { var self = this, updatedConversations = self._updatedConversations, list = []; utils.forEach(updatedConversations, function (conversation) { var storageItems = self._store.get(conversation); utils.forEach(storageItems, function (val, key) { conversation[key] = val; }); list.push(conversation); }); return common.sortConList(list); }; _proto._setUnreadCount = function _setUnreadCount(message, conversation) { var content = message.content, messageType = message.messageType, sentTime = message.sentTime, isCounted = message.isCounted, messageDirection = message.messageDirection, senderUserId = message.senderUserId, isSelfSend = utils.isEqual(messageDirection, MESSAGE_DIRECTION.SEND) || utils.isEqual(senderUserId, this._selfUserId), isRecall = utils.isEqual(messageType, RECALL_MESSAGE_TYPE), hasContent = utils.isObject(content); var hasChanged = false; var lastUnreadTime = conversation.lastUnreadTime || 0, unreadMessageCount = conversation.unreadMessageCount || 0, hasBeenAdded = lastUnreadTime > sentTime; if (hasBeenAdded || isSelfSend) { return { hasChanged: hasChanged, conversation: conversation }; } if (isCounted) { conversation.unreadMessageCount = unreadMessageCount + 1; conversation.lastUnreadTime = sentTime; hasChanged = true; } if (isRecall && hasContent) { var isNotRead = lastUnreadTime >= content.sentTime; if (isNotRead && unreadMessageCount) { conversation.unreadMessageCount = unreadMessageCount - 1; hasChanged = true; } } return { hasChanged: hasChanged, conversation: conversation }; }; _proto._setMentiondInfo = function _setMentiondInfo(message, conversation) { var content = message.content, messageDirection = message.messageDirection, isMentiond = message.isMentiond, isSelfSend = utils.isEqual(messageDirection, MESSAGE_DIRECTION.SEND), hasContent = utils.isObject(content); var hasChanged = false; if (isSelfSend) ; else if (isMentiond && hasContent && content.mentionedInfo) { conversation.hasMentiond = true; conversation.mentiondInfo = content.mentionedInfo; hasChanged = true; } return { hasChanged: hasChanged, conversation: conversation }; }; _proto._setUpdatedConversation = function _setUpdatedConversation(conversation) { if (utils.isObject(conversation) && conversation.targetId && conversation.type) { var self = this, cacheKey = common.getConversationKey(conversation), cacheConversation = self._updatedConversations[cacheKey]; self._updatedConversations[cacheKey] = utils.extendAllowNull(cacheConversation, conversation); } }; _proto._notifyConversationChanged = function _notifyConversationChanged() { var self = this, _eventEmitter = self._eventEmitter, updatedConversationList = self._getUpdatedConversationList(); if (utils.isEmpty(updatedConversationList)) ; else { utils.setTimeout(function () { _eventEmitter.emit(EventName$1.CHANGED, { updatedConversationList: updatedConversationList }); self._updatedConversations = {}; }, 0); } }; _proto._addStatus = function _addStatus(conversationStatus, isLastInAPull) { var type = conversationStatus.type, targetId = conversationStatus.targetId, updatedTime = conversationStatus.updatedTime, notificationStatus = conversationStatus.notificationStatus, isTop = conversationStatus.isTop, option = { type: type, targetId: targetId }; var updatedItems = {}; if (!utils.isUndefined(notificationStatus)) { updatedItems['notificationStatus'] = { time: updatedTime, val: notificationStatus }; } if (!utils.isUndefined(isTop)) { updatedItems['isTop'] = { time: updatedTime, val: isTop }; } this._setUpdatedConversation({ type: type, targetId: targetId, updatedItems: updatedItems }); this._store.set(option, { notificationStatus: notificationStatus, isTop: isTop }); if (isLastInAPull) { this._notifyConversationChanged(); } }; return ConversationManager; }(); var MessageTimeSyner$1 = common.MessageTimeSyner, ChatRoomMessageTimeSyner$1 = common.ChatRoomMessageTimeSyner; var EVENT_NAME$1 = { MESSAGE_RECEIVED: 'msg-received' }; var MessagePullManager = function () { function MessagePullManager(serverEngine, option) { var _serverEngine$watch; this._serverEngine = void 0; this._pullQueue = void 0; this._messageTimeSyner = void 0; this._chatRoomMessageTimeSyner = void 0; this._eventEmitter = new utils.EventEmitter(); this._pullMessageTimer = new utils.Timer({ type: TIMER_TYPE.INTERVAL, timeout: PULL_MSG_TIME }); this._sentMsgCacheInPulling = {}; this._handleDirectMessage = void 0; this._handleNotifyPull = void 0; this._handleJoinChatRoom = void 0; this._handleSendMessage = void 0; var self = this; var appkey = serverEngine.option.appkey, userId = serverEngine._selfUserId; var startSyncTime = option.startSyncTime; var pullQueue = new PullQueueManager({ event: this._pullEvent, thisArg: this, onFinished: function onFinished() {}, onError: function onError() {} }); self._handleDirectMessage = function (message) { !pullQueue.isLoading && self.notifyMessage({ message: message, hasMore: false }); }; self._handleNotifyPull = function (option) { pullQueue.pull(option); }; self._handleJoinChatRoom = function (_ref) { var id = _ref.id, count = _ref.count, isAutoRejoin = _ref.isAutoRejoin; if (utils.isEqual(count, CHATROOM_NOT_PULL_MSG_COUNT)) { self._chatRoomMessageTimeSyner.set(id, common.DelayTimer.getTime()); } else { var type = PULL_MSG_TYPE.CHATROOM, chrmId = id; var time = isAutoRejoin ? self._chatRoomMessageTimeSyner.get(id) + 1 : 0; self._chatRoomMessageTimeSyner.set(id, time); pullQueue.pull({ type: type, time: time, chrmId: chrmId, count: count }); } }; self._handleSendMessage = function (message) { pullQueue.isLoading ? self._setSentMsgCacheInPulling(message) : self._setPullTime(message); }; serverEngine.watch((_serverEngine$watch = {}, _serverEngine$watch[SERVER_EVENT_NAME.DIRECT_MSG] = self._handleDirectMessage, _serverEngine$watch[SERVER_EVENT_NAME.NOTIFY_PULL] = self._handleNotifyPull, _serverEngine$watch[SERVER_EVENT_NAME.JOIN_CHATROOM] = self._handleJoinChatRoom, _serverEngine$watch[SERVER_EVENT_NAME.MESSAGE_SEND] = self._handleSendMessage, _serverEngine$watch)); self._serverEngine = serverEngine; self._pullQueue = pullQueue; self._messageTimeSyner = new MessageTimeSyner$1({ appkey: appkey, userId: userId, startSyncTime: startSyncTime }); self._chatRoomMessageTimeSyner = new ChatRoomMessageTimeSyner$1({ appkey: appkey, userId: userId }); self._pullMessageTimer.start(pullQueue.pull, { thisArg: pullQueue }); pullQueue.pull(); } var _proto = MessagePullManager.prototype; _proto.watchMessage = function watchMessage(event) { this._eventEmitter.on(EVENT_NAME$1.MESSAGE_RECEIVED, event); }; _proto.notifyMessage = function notifyMessage(messageArgs) { var message = messageArgs.message; this._setPullTime(message); this._eventEmitter.emit(EVENT_NAME$1.MESSAGE_RECEIVED, messageArgs); }; _proto.close = function close() { var _this$_serverEngine$u; this._pullMessageTimer.stop(); this._sentMsgCacheInPulling = {}; this._serverEngine.unwatch((_this$_serverEngine$u = {}, _this$_serverEngine$u[SERVER_EVENT_NAME.DIRECT_MSG] = this._handleDirectMessage, _this$_serverEngine$u[SERVER_EVENT_NAME.NOTIFY_PULL] = this._handleNotifyPull, _this$_serverEngine$u[SERVER_EVENT_NAME.JOIN_CHATROOM] = this._handleJoinChatRoom, _this$_serverEngine$u[SERVER_EVENT_NAME.MESSAGE_SEND] = this._handleSendMessage, _this$_serverEngine$u)); }; _proto._pullEvent = function _pullEvent(option) { option = option || {}; var self = this, _serverEngine = self._serverEngine, _messageTimeSyner = self._messageTimeSyner, _chatRoomMessageTimeSyner = self._chatRoomMessageTimeSyner, _option = option, type = _option.type, chrmId = _option.chrmId, serverPullTime = _option.time, count = _option.count, isPullChrmMsg = utils.isEqual(type, PULL_MSG_TYPE.CHATROOM), msgSyncTime = _messageTimeSyner.get(), currentReceiveTime = isPullChrmMsg ? _chatRoomMessageTimeSyner.get(chrmId) : msgSyncTime.inboxTime, syncTime = utils.copy(msgSyncTime); if (serverPullTime && serverPullTime < currentReceiveTime) { return utils.Defer.resolve(); } var onMessage = function onMessage(_ref2) { var message = _ref2.message, finished = _ref2.finished, isLastInAPull = _ref2.isLastInAPull; self._displatchMessages({ message: message, finished: finished, isPullChrmMsg: isPullChrmMsg, isLastInAPull: isLastInAPull, normalSyncTime: syncTime, chatRoomReceiveTime: currentReceiveTime }); }; if (isPullChrmMsg) { return _serverEngine.pullChrmMessageList(chrmId, currentReceiveTime, count, { onMessage: onMessage }); } else { return _serverEngine.pullMessageList(syncTime, { onMessage: onMessage }); } }; _proto._displatchMessages = function _displatchMessages(option) { var self = this, message = option.message, finished = option.finished, isPullChrmMsg = option.isPullChrmMsg, isLastInAPull = option.isLastInAPull, _ref3 = option.normalSyncTime || {}, inboxTime = _ref3.inboxTime, sendboxTime = _ref3.sendboxTime, sentTime = message.sentTime, messageDirection = message.messageDirection, messageUId = message.messageUId, isSelfSend = messageDirection === MESSAGE_DIRECTION.SEND, pullTime = isSelfSend ? sendboxTime : inboxTime; if (sentTime <= pullTime && !isPullChrmMsg) { return; } if (self._sentMsgCacheInPulling[messageUId]) { return; } self.notifyMessage({ message: message, hasMore: !finished, isLastInAPull: isLastInAPull }); }; _proto._setPullTime = function _setPullTime(message) { var isChatRoom = message.type === CONVERSATION_TYPE.CHATROOM; isChatRoom ? this._chatRoomMessageTimeSyner.setByMessage(message) : this._messageTimeSyner.setByMessage(message); }; _proto._setSentMsgCacheInPulling = function _setSentMsgCacheInPulling(message) { var messageUId = message.messageUId; if (utils.isUndefined(messageUId)) { return; } this._sentMsgCacheInPulling[messageUId] = message; }; _proto._consumeSentMsgCacheInPulling = function _consumeSentMsgCacheInPulling() { var self = this; var _sentMsgCacheInPulling = self._sentMsgCacheInPulling; utils.forEach(_sentMsgCacheInPulling, function (message) { self._setPullTime(message); }); self._sentMsgCacheInPulling = {}; }; return MessagePullManager; }(); var ChatRoomKVStore = function () { function ChatRoomKVStore(chrmId, currentUserId) { this._chatRoomId = void 0; this._kvCaches = {}; this._currentUserId = void 0; this._chatRoomId = chrmId; this._currentUserId = currentUserId; } var _proto = ChatRoomKVStore.prototype; _proto.setEntries = function setEntries(data) { data = data || {}; var self = this; var _data = data, kvList = _data.kvEntries, isFullUpdate = _data.isFullUpdate; kvList = kvList || []; isFullUpdate = isFullUpdate || false; isFullUpdate && self.clear(); utils.forEach(kvList, function (kv) { self.setEntry(kv, { isFullUpdate: isFullUpdate }); }); }; _proto.setEntry = function setEntry(kv, option) { option = option || {}; var _option = option, isFullUpdate = _option.isFullUpdate, key = kv.key, type = kv.type, isOverwrite = kv.isOverwrite, userId = kv.userId, latestUserId = this.getSetUserId(key), isDeleteOpt = utils.isEqual(type, CHATROOM_ENTRY_TYPE.DELETE), isSameAtLastSetUser = utils.isEqual(latestUserId, userId), isKeyNotExist = !this.isExisted(key); var event = isDeleteOpt ? this.remove : this.add; if (isFullUpdate) { event.call(this, kv); } else if (isOverwrite || isSameAtLastSetUser || isKeyNotExist) { event.call(this, kv); } }; _proto.add = function add(kv) { var key = kv.key; kv.isDeleted = false; this._kvCaches[key] = kv; }; _proto.remove = function remove(kv) { var key = kv.key; var cacheKV = this.get(key) || {}; cacheKV.isDeleted = true; this._kvCaches[key] = cacheKV; }; _proto.clear = function clear() { this._kvCaches = {}; }; _proto.get = function get(key) { return this._kvCaches[key]; }; _proto.getSetUserId = function getSetUserId(key) { var cache = this.get(key) || {}; return cache.userId; }; _proto.getValue = function getValue(key) { var kv = this._kvCaches[key] || {}; var isDeleted = kv.isDeleted; return isDeleted ? null : kv.value; }; _proto.getAll = function getAll() { var kvEntries = {}; utils.forEach(this._kvCaches, function (kv, key) { if (!kv.isDeleted) { kvEntries[key] = kv.value; } }); return kvEntries; }; _proto.getUpdatedTime = function getUpdatedTime() { var maxTime = 0; utils.forEach(this._kvCaches, function (entry) { var timestamp = entry.timestamp || 0; if (maxTime < timestamp) { maxTime = timestamp; } }); return maxTime; }; _proto.isExisted = function isExisted(key) { var cache = this.get(key) || {}; var value = cache.value, isDeletedOnLatestOperate = cache.isDeleted; return value && !isDeletedOnLatestOperate; }; return ChatRoomKVStore; }(); var storeCaches = {}; var get = function get(chrmId) { return storeCaches[chrmId]; }; var set$1 = function set(chrmId, data, currentUserId) { var kvStore = get(chrmId); if (utils.isEmpty(kvStore)) { kvStore = new ChatRoomKVStore(chrmId, currentUserId); } kvStore.setEntries(data); storeCaches[chrmId] = kvStore; }; var getValue = function getValue(chrmId, key) { var kvStore = get(chrmId); var value = kvStore ? kvStore.getValue(key) : null; return value; }; var getAll = function getAll(chrmId) { var kvStore = get(chrmId); var kvs = {}; if (kvStore) { kvs = kvStore.getAll(); } return kvs; }; var clear = function clear(chrmId) { var kvStore = get(chrmId) || {}; kvStore.clear && kvStore.clear(); }; var ChatRoomKVStore$1 = { get: get, set: set$1, getValue: getValue, getAll: getAll, clear: clear }; var PullTimeCache = { _caches: {}, set: function set(chrmId, time) { PullTimeCache._caches[chrmId] = time; }, get: function get(chrmId) { return PullTimeCache._caches[chrmId] || 0; }, clear: function clear(chrmId) { PullTimeCache._caches[chrmId] = 0; } }; var KV_EVENT_NAME = { KV_RECEIVED: 'kv-received' }; var ChatRoomKVManager = function () { function ChatRoomKVManager(serverEngine) { var _serverEngine$watch; this._serverEngine = void 0; this._pullQueue = void 0; this._handleChrmKVSet = void 0; this._handleChrmKVChanged = void 0; this._handleBeforeJoinChrm = void 0; this._eventEmitter = new utils.EventEmitter(); var self = this; var userId = serverEngine._selfUserId; var pullQueue = new PullQueueManager({ event: this._pullEvent, thisArg: this, onFinished: function onFinished(data, option) { if (!data || !option.chrmId) { return; } var chrmId = option.chrmId; if (data.isFullUpdate) { self._reset(chrmId); } Logger.info(TAG.L_PULL_CHRM_KV_R, { data: data, option: option }); ChatRoomKVStore$1.set(chrmId, data, userId); PullTimeCache.set(chrmId, data.syncTime || 0); self._notifyReceivedKV(chrmId, data); } }); self._handleChrmKVSet = function (_ref) { var id = _ref.id, data = _ref.data; ChatRoomKVStore$1.set(id, data, userId); }; self._handleChrmKVChanged = function (data) { self.pull(data); }; self._handleBeforeJoinChrm = function (_ref2) { var id = _ref2.id; self._reset(id); }; serverEngine.watch((_serverEngine$watch = {}, _serverEngine$watch[SERVER_EVENT_NAME.CHRM_KV_SET] = self._handleChrmKVSet, _serverEngine$watch[SERVER_EVENT_NAME.CHRM_KV_CHANGED] = self._handleChrmKVChanged, _serverEngine$watch[SERVER_EVENT_NAME.BEFORE_JOIN_CHATROOM] = self._handleBeforeJoinChrm, _serverEngine$watch)); this._serverEngine = serverEngine; this._pullQueue = pullQueue; } var _proto = ChatRoomKVManager.prototype; _proto._reset = function _reset(chrmId) { ChatRoomKVStore$1.clear(chrmId); PullTimeCache.clear(chrmId); }; _proto._pullEvent = function _pullEvent(data) { var time = data.time, chrmId = data.chrmId, currentTime = PullTimeCache.get(chrmId), isUpdated = currentTime > time; Logger.info(TAG.L_PULL_CHRM_KV_T, { currentTime: currentTime, serverTime: time, isUpdated: isUpdated, data: data }); if (isUpdated) { Logger.info(TAG.L_PULL_CHRM_KV_R, { info: 'kv is updated. not pull again' }); return utils.Defer.resolve(); } return this._serverEngine.pullChatRoomKV({ id: chrmId }, currentTime); }; _proto.pull = function pull(data) { this._pullQueue.pull(data); }; _proto.getValue = function getValue(chrmId, key) { return ChatRoomKVStore$1.getValue(chrmId, key); }; _proto.getAll = function getAll(chrmId) { return ChatRoomKVStore$1.getAll(chrmId); }; _proto._notifyReceivedKV = function _notifyReceivedKV(chrmId, data) { var self = this; var kvEntries = data.kvEntries, updatedEntries = []; if (kvEntries.length > 0) { utils.forEach(kvEntries, function (entry) { var key = entry.key, value = entry.value, type = entry.type, timestamp = entry.timestamp; if (utils.isEqual(type, CHATROOM_ENTRY_TYPE.UPDATE)) { updatedEntries.push({ key: key, value: value, timestamp: timestamp, chatroomId: chrmId }); } }); self._eventEmitter.emit(KV_EVENT_NAME.KV_RECEIVED, updatedEntries); } }; _proto.watchReceived = function watchReceived(event) { this._eventEmitter.on(KV_EVENT_NAME.KV_RECEIVED, event); }; _proto.close = function close() { var _self$_serverEngine$u; var self = this; self._serverEngine.unwatch((_self$_serverEngine$u = {}, _self$_serverEngine$u[SERVER_EVENT_NAME.CHRM_KV_SET] = self._handleChrmKVSet, _self$_serverEngine$u[SERVER_EVENT_NAME.CHRM_KV_CHANGED] = self._handleChrmKVChanged, _self$_serverEngine$u[SERVER_EVENT_NAME.BEFORE_JOIN_CHATROOM] = self._handleBeforeJoinChrm, _self$_serverEngine$u)); }; return ChatRoomKVManager; }(); var SettingStore = function () { function SettingStore(appkey, userId) { this._storage = void 0; var storageKey = utils.tplEngine(STORAGE_USER_SETTING.ROOT_KEY_TPL, { appkey: appkey, userId: userId }); this._storage = new common.RCStorage(storageKey); } var _proto = SettingStore.prototype; _proto.set = function set(serverData) { var self = this, _storage = self._storage, settings = serverData.settings, oldSettingItems = _storage.get(STORAGE_USER_SETTING.SUB_KEY.SETTINGS) || {}; var newSettingItems = oldSettingItems, isChanged = false; utils.forEach(settings, function (newSetting, key) { newSetting = newSetting || {}; var oldSetting = oldSettingItems[key] || {}, _newSetting = newSetting, newVersion = _newSetting.version, status = _newSetting.status, newValue = _newSetting.value, oldGlobalVersion = _storage.get(STORAGE_USER_SETTING.SUB_KEY.VERSION) || 0, isNeedUpdateItem = newVersion > (oldSetting.version || 0), isNeedUpdateVersion = newVersion > oldGlobalVersion; if (!isNeedUpdateItem) { return; } isChanged = true; switch (status) { case USER_SETTING_STATUS.ADD: case USER_SETTING_STATUS.UPDATE: newSettingItems[key] = { value: newValue, version: newVersion }; break; case USER_SETTING_STATUS.DELETE: delete newSettingItems[key]; break; default: } if (isNeedUpdateVersion) { _storage.set(STORAGE_USER_SETTING.SUB_KEY.VERSION, newVersion); } }); if (!isChanged) { return; } if (utils.isEmpty(newSettingItems)) { _storage.remove(STORAGE_USER_SETTING.SUB_KEY.SETTINGS); } else { _storage.set(STORAGE_USER_SETTING.SUB_KEY.SETTINGS, newSettingItems); } }; _proto.getSetting = function getSetting() { var settings = this._storage.get(STORAGE_USER_SETTING.SUB_KEY.SETTINGS) || {}; return utils.map(settings, function (set) { set = set || {}; return set.value; }); }; _proto.getVersion = function getVersion() { return this._storage.get(STORAGE_USER_SETTING.SUB_KEY.VERSION) || 0; }; return SettingStore; }(); var EventNames = { CHANGED: 'change' }; var SettingManager = function () { function SettingManager(serverEngine, option) { var _serverEngine$watch; this._serverEngine = void 0; this._settingStore = void 0; this._pullQueue = void 0; this._eventEmitter = new utils.EventEmitter(); this._handleNotifySettingChanged = void 0; var self = this, appkey = option.appkey, userId = option.userId, isAutoPull = option.isAutoPull, settingStore = new SettingStore(appkey, userId), localVersion = settingStore.getVersion() || 0; var pullQueue = new PullQueueManager({ event: serverEngine.getUserSettings, thisArg: serverEngine, onFinished: function onFinished(serverData) { if (serverData && serverData.version) { self._settingStore.set(serverData); self._eventEmitter.emit(EventNames.CHANGED, self.get()); } } }); self._handleNotifySettingChanged = function (notifyData) { var version = notifyData.version, localVersion = self._settingStore.getVersion(); if (version >= localVersion) { pullQueue.pull(localVersion); } }; self._settingStore = new SettingStore(appkey, userId); self._pullQueue = pullQueue; self._serverEngine = serverEngine; serverEngine.watch((_serverEngine$watch = {}, _serverEngine$watch[SERVER_EVENT_NAME.USER_SETTING_CHANGED] = self._handleNotifySettingChanged, _serverEngine$watch)); isAutoPull && pullQueue.pull(localVersion); } var _proto = SettingManager.prototype; _proto.watchSettingChanged = function watchSettingChanged(event) { this._eventEmitter.on(EventNames.CHANGED, event); }; _proto.get = function get() { return this._settingStore.getSetting() || {}; }; _proto.close = function close() { var _this$_serverEngine$u; this._serverEngine.unwatch((_this$_serverEngine$u = {}, _this$_serverEngine$u[SERVER_EVENT_NAME.USER_SETTING_CHANGED] = this._handleNotifySettingChanged, _this$_serverEngine$u)); }; return SettingManager; }(); var WebIMEngine = function () { function WebIMEngine(option) { this._option = void 0; this._user = void 0; this._naviManager = void 0; this._cmpManager = new CMPManager(); this._conversationManager = void 0; this._messageManager = void 0; this._chatRoomKVManager = void 0; this._userSettingManager = void 0; this._serverEngine = void 0; this._imEventEmitter = new utils.EventEmitter(); this._connectionStatus = CONNECTION_STATUS.DISCONNECTED; this._connectedDomain = void 0; this._networkDetecter = void 0; this._joinedChatRoomSyner = void 0; var self = this; var detect = option.detect; var serverEngine = new ServerEngine(option); serverEngine.watch({ status: function status(_status) { self._handleConnectionStatus(_status); } }); this._serverEngine = serverEngine; this._option = option; this._networkDetecter = new utils.NetworkDetecter(detect); utils.forEach(ServerEngine.prototype, function (event, eventName) { var server = serverEngine, web = self; var selfEvent = web[eventName], serverEvent = server[eventName]; if (!selfEvent && serverEvent && utils.isFunction(serverEvent)) { web[eventName] = function () { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return serverEvent.call.apply(serverEvent, [server].concat(args)); }; } }); } var _proto = WebIMEngine.prototype; _proto._notifyMessage = function _notifyMessage(event) { var self = this; var message = event.message; var _serverEngine = self._serverEngine; var connectedTime = _serverEngine.getConnectedTime(); if (common.isLogCommandMsg(message)) { var content = message.content; Logger.uploadFull(0, content, connectedTime); return; } this._conversationManager.addMessage(event); this._imEventEmitter.emit(IM_EVENT.MESSAGE, event); }; _proto._handleConnectionStatus = function _handleConnectionStatus(status) { var _cmpManager = this._cmpManager, _naviManager = this._naviManager, _connectedDomain = this._connectedDomain; var isNeedUpdateCMPList = utils.isInclude(TRANSPORTER_STATUS_NEED_UPDATE_CMP, status); var isNeedReconnect = utils.isInclude(TRANSPORTER_STATUS_NEED_RECONNECT, status); var isKickedOfflineByOtherClient = utils.isEqual(CONNECTION_STATUS.KICKED_OFFLINE_BY_OTHER_CLIENT, status); if (isNeedUpdateCMPList) { _cmpManager.addInvalid(_connectedDomain); if (_cmpManager.isAllInvalid()) { _naviManager.clear(); _cmpManager.clearInvalid(); } } if (isNeedReconnect) { this.disconnect(); this.reconnect(true); } if (isKickedOfflineByOtherClient) { this.disconnect(); } var connectionStatus = TRANSPORTER_STATUS_TO_CONNECTION_STATUS[status] || status; this._connectionStatus = connectionStatus; this._imEventEmitter.emit(IM_EVENT.STATUS, { status: connectionStatus }); }; _proto._handleConnectError = function _handleConnectError(errorInfo) { var _user = this._user; var code = errorInfo.code || errorInfo.status; this.disconnect(); if (code === ERROR_INFO.CONN_REDIRECTED.code) { this._naviManager.clear(); return this.connect(_user); } this._connectionStatus = CONNECTION_STATUS.DISCONNECTED; return utils.Defer.reject(errorInfo); }; _proto._afterConnect = function _afterConnect(connectUser, syncTime) { var self = this, _serverEngine = self._serverEngine, appkey = self._option.appkey, _imEventEmitter = self._imEventEmitter, _naviManager = self._naviManager, id = connectUser.id, localNavi = _naviManager.getLocalConfig() || {}; Logger.setOption({ userId: id }); self._user.id = id; var conversationManager = new ConversationManager({ appkey: appkey, userId: id }, _serverEngine); conversationManager.watch({ conversation: function conversation(_ref) { var updatedConversationList = _ref.updatedConversationList; _imEventEmitter.emit(IM_EVENT.CONVERSATION, { updatedConversationList: updatedConversationList }); } }); self._conversationManager = conversationManager; var messageManager = new MessagePullManager(_serverEngine, { startSyncTime: syncTime }); messageManager.watchMessage(function (event) { self._notifyMessage(event); }); self._messageManager = messageManager; self._chatRoomKVManager = new ChatRoomKVManager(_serverEngine); self._chatRoomKVManager.watchReceived(function (updatedEntries) { self._imEventEmitter.emit(IM_EVENT.CHATROOM, { updatedEntries: updatedEntries }); }); var isAutoPull = !!Number(localNavi.openUS); var userSettingManager = new SettingManager(_serverEngine, { appkey: appkey, userId: id, isAutoPull: isAutoPull }); self._joinedChatRoomSyner = new common.JoinedChatRoomSyner({ appkey: appkey, userId: id }); userSettingManager.watchSettingChanged(function (config) { config = config || {}; var _config = config, voipCallInfo = _config.VoipInfo; _naviManager.setLocalConfig({ voipCallInfo: utils.toJSON(voipCallInfo) }); self._imEventEmitter.emit(IM_EVENT.SETTING, config); }); self._userSettingManager = userSettingManager; }; _proto.watch = function watch(watchers) { var _events; var statusWatcher = watchers.status, messageWatcher = watchers.message, conversationWatcher = watchers.conversation, chatroomWatcher = watchers.chatroom; var self = this; var events = (_events = {}, _events[IM_EVENT.STATUS] = statusWatcher, _events[IM_EVENT.MESSAGE] = messageWatcher, _events[IM_EVENT.CONVERSATION] = conversationWatcher, _events[IM_EVENT.CHATROOM] = chatroomWatcher, _events); utils.forEach(events, function (event, eventName) { utils.isFunction(event) && self._imEventEmitter.on(eventName, event); }); }; _proto.unwatch = function unwatch(watchers) { var _imEventEmitter = this._imEventEmitter; var offEventNameObj = { status: 'IM_EVENT.STATUS', message: 'IM_EVENT.MESSAGE', conversation: 'IM_EVENT.CONVERSATION', chatroom: 'IM_EVENT.CHATROOM' }; if (watchers) { utils.forEach(watchers, function (val, key) { if (offEventNameObj[key]) { _imEventEmitter.off(key, val); } }); } else { _imEventEmitter.clear(); } }; _proto.getConnectionStatus = function getConnectionStatus() { return this._connectionStatus; }; _proto.getConnectionUserId = function getConnectionUserId() { var user = this._user || {}; return user.id; }; _proto.getAppInfo = function getAppInfo() { var _option = this._option, _naviManager = this._naviManager, _userSettingManager = this._userSettingManager; return utils.extendInShallow(_option, { navi: _naviManager.getLocalConfig(), serverConfig: _userSettingManager ? _userSettingManager.get() : {} }); }; _proto.connect = function connect(user, options) { Logger.startRealtimeUpload(); var self = this; var _option = self._option, _serverEngine = self._serverEngine, _cmpManager = self._cmpManager; var naviOpt = common.getNavReqOption(_option, user); var naviManager = new NaviManager(naviOpt); var getServerConfig = _option.isOldServer ? _serverEngine.getOldServerConfig : _serverEngine.getServerConfig; options = options || {}; var isAutoReconnect = options.isAutoReconnect; self._handleConnectionStatus(CONNECTION_STATUS.CONNECTING); self._user = utils.copy(user); self._naviManager = naviManager; var connectUser; return naviManager.get().then(function (configForNavi) { var cmpDomainList = common.getCMPDomainList(configForNavi, _option); Logger.setServerOption(configForNavi); _cmpManager.setDomainList(cmpDomainList); return _cmpManager.getFaster(); }).then(function (_ref2) { var domain = _ref2.domain; self._connectedDomain = domain; return _serverEngine.connect(user, { domain: domain }); }).then(function (user) { connectUser = user; isAutoReconnect && self.rejoinChatRoom(); return getServerConfig.call(_serverEngine, user.id); }).then(function (serverConfig) { self._afterConnect(connectUser, serverConfig); self._handleConnectionStatus(CONNECTION_STATUS.CONNECTED); return connectUser; })["catch"](function (error) { return self._handleConnectError(error); }); }; _proto.reconnect = function reconnect(isAutoReconnect) { var self = this; var _user = self._user; if (utils.isUndefined(_user)) { return utils.Defer.reject(ERROR_INFO.NOT_CONNECTED); } return self._networkDetecter.start().then(function () { return self.connect(_user, { isAutoReconnect: isAutoReconnect }); }); }; _proto.disconnect = function disconnect(isNotify) { isNotify && this._handleConnectionStatus(CONNECTION_STATUS.DISCONNECTED); this._networkDetecter && this._networkDetecter.stop(); this._messageManager && this._messageManager.close(); this._chatRoomKVManager && this._chatRoomKVManager.close(); this._userSettingManager && this._userSettingManager.close(); this._conversationManager && this._conversationManager.close(); return this._serverEngine.disconnect(); }; _proto.changeUser = function changeUser(user) { this.disconnect(true); return this.connect(user); }; _proto.sendMessage = function sendMessage(conversation, option) { var self = this; return self._serverEngine.sendMessage(conversation, option).then(function (message) { self._conversationManager.addMessage({ message: message, hasMore: false }); return message; }); }; _proto.recallMessage = function recallMessage(conversation, message, option) { var self = this; return self._serverEngine.recallMessage(conversation, message, option).then(function (message) { self._conversationManager.addMessage({ message: message, hasMore: false }); return message; }); }; _proto.getConversationList = function getConversationList(option) { var isOldServer = this._option.isOldServer, _serverEngine = this._serverEngine, _conversationManager = this._conversationManager; var func = isOldServer ? _serverEngine.getOldConversationList : _serverEngine.getConversationList; return func.call(_serverEngine, option, { afterDecode: function afterDecode(conversation) { var localConversation = _conversationManager.get(conversation); conversation = utils.extendAllowNull(conversation, localConversation); return conversation; } }).then(function (list) { return common.sortConList(list); }); }; _proto.getLocalConversation = function getLocalConversation(conversation) { var local = this._conversationManager.get(conversation); return { unreadMessageCount: local.unreadMessageCount || 0, hasMentiond: local.hasMentiond || false, mentiondInfo: local.mentiondInfo }; }; _proto.removeConversation = function removeConversation(conversation) { var isOldServer = this._option.isOldServer, _serverEngine = this._serverEngine; var func = isOldServer ? _serverEngine.removeOldConversation : _serverEngine.removeConversation; return func.call(_serverEngine, conversation); }; _proto.getTotalUnreadCount = function getTotalUnreadCount() { var isOldServer = this._option.isOldServer, _serverEngine = this._serverEngine; if (isOldServer) { var totalCount = this._conversationManager.getTotalUnreadCount(); return utils.Defer.resolve(totalCount); } else { return _serverEngine.getTotalUnreadCount(); } }; _proto.getUnreadCount = function getUnreadCount(conversation) { var isOldServer = this._option.isOldServer; if (isOldServer) { var count = this._conversationManager.getUnreadCount(conversation); return utils.Defer.resolve(count); } }; _proto.clearUnreadCount = function clearUnreadCount(conversation, option) { var isOldServer = this._option.isOldServer, _serverEngine = this._serverEngine; if (isOldServer) { this._conversationManager.read(conversation); return utils.Defer.resolve(); } else { return _serverEngine.clearUnreadCount(conversation, option); } }; _proto.joinChatRoom = function joinChatRoom(chrm, option) { var self = this; var _serverEngine = self._serverEngine, _naviManager = self._naviManager, _chatRoomKVManager = self._chatRoomKVManager, _joinedChatRoomSyner = self._joinedChatRoomSyner; var isAutoRejoin = option.isAutoRejoin; return _serverEngine.joinChatRoom(chrm, option).then(function () { return _naviManager.get(); }).then(function (configForNavi) { var isOpenKVStorageService = configForNavi.kvStorage, isOpenJoinMulitpleChrmService = configForNavi.joinMChrm; !isAutoRejoin && _joinedChatRoomSyner.set({ chrmId: chrm.id, count: option.count, isOpenJoinMulitpleChrmService: isOpenJoinMulitpleChrmService }); var initialTime = 0; return isOpenKVStorageService ? _chatRoomKVManager.pull({ time: initialTime, chrmId: chrm.id }) : utils.Defer.resolve(); }); }; _proto.quitChatRoom = function quitChatRoom(chrm) { var self = this; var _serverEngine = self._serverEngine; return _serverEngine.quitChatRoom(chrm).then(function () { self._joinedChatRoomSyner.remove(chrm.id); return utils.Defer.resolve(); }); }; _proto.rejoinChatRoom = function rejoinChatRoom() { var self = this; var _joinedChatRoomSyner = self._joinedChatRoomSyner, _imEventEmitter = self._imEventEmitter; var joinedChrmInfos = _joinedChatRoomSyner.get(); utils.forEach(joinedChrmInfos, function (chrmInfo) { var chrmId = chrmInfo.chrmId, count = chrmInfo.count; var isAutoRejoin = true, isJoinExist = true; var rejoinedRoom = { chrmId: chrmId, count: count }; return self.joinChatRoom({ id: chrmId }, { count: count, isAutoRejoin: isAutoRejoin, isJoinExist: isJoinExist }).then(function () { _imEventEmitter.emit(IM_EVENT.CHATROOM, { rejoinedRoom: rejoinedRoom }); }, function (reason) { _imEventEmitter.emit(IM_EVENT.CHATROOM, { rejoinedRoom: utils.extend(rejoinedRoom, { errorCode: reason }) }); }); }); }; _proto.setChatRoomKV = function setChatRoomKV(chrm, entry) { var self = this; utils.extend(entry, { type: CHATROOM_ENTRY_TYPE.UPDATE, userId: self._user.id }); entry.type = CHATROOM_ENTRY_TYPE.UPDATE; return self._serverEngine.modifyChatRoomKV(chrm, entry); }; _proto.forceSetChatRoomKV = function forceSetChatRoomKV(chrm, entry) { entry.isOverwrite = true; return this.setChatRoomKV(chrm, entry); }; _proto.removeChatRoomKV = function removeChatRoomKV(chrm, entry) { var self = this; utils.extend(entry, { type: CHATROOM_ENTRY_TYPE.DELETE, userId: self._user.id }); return self._serverEngine.modifyChatRoomKV(chrm, entry); }; _proto.forceRemoveChatRoomKV = function forceRemoveChatRoomKV(chrm, entry) { entry.isOverwrite = true; return this.removeChatRoomKV(chrm, entry); }; _proto.getChatRoomKV = function getChatRoomKV(chrm, key) { var value = this._chatRoomKVManager.getValue(chrm.id, key); if (utils.isEmpty(value)) { return utils.Defer.reject(ERROR_INFO.CHATROOM_KEY_NOT_EXIST); } else { return utils.Defer.resolve(value); } }; _proto.getAllChatRoomKV = function getAllChatRoomKV(chrm) { var kvs = this._chatRoomKVManager.getAll(chrm.id); return utils.Defer.resolve(kvs); }; _proto.getFileToken = function getFileToken(fileType, originName) { var self = this; var fileName = common.genUploadFileName(fileType, originName); var uploadDomains = common.getUploadFileDomains(self._naviManager.getLocalConfig()); return self._serverEngine.getFileToken(fileType, fileName).then(function (data) { return utils.extendInShallow(uploadDomains, data); }); }; _proto.getFileUrl = function getFileUrl(fileType, fileName, originName, uploadResp) { var self = this; uploadResp = uploadResp || {}; if (uploadResp.isBosRes) { return utils.Defer.resolve(uploadResp); } return self._serverEngine.getFileUrl(fileType, fileName, originName); }; return WebIMEngine; }(); var Engine = (function (imArg) { return new WebIMEngine(imArg); }); var execEngineByEvent = function execEngineByEvent(params, engine) { var eventName = params.event, args = params.args; args = args || []; var engineEvent = engine[eventName] || function () { return utils.Defer.reject(ERROR_INFO.SDK_INTERNAL_ERROR); }; return engineEvent.apply(engine, args); }; var EngineDispatcher = function () { function EngineDispatcher(option) { this._engine = void 0; this._engine = new Engine(option); } var _proto = EngineDispatcher.prototype; _proto._isEventNeedConnect = function _isEventNeedConnect(eventName) { var engine = this._engine, connectionStatus = engine.getConnectionStatus(), isNotConnected = connectionStatus !== CONNECTION_STATUS.CONNECTED, isEventNeedConnected = utils.isInclude(ENGINE_EVENT_NEED_CONNECTED, eventName); return isNotConnected && isEventNeedConnected; }; _proto._isEventNeedDisconnect = function _isEventNeedDisconnect(eventName) { var engine = this._engine, connectionStatus = engine.getConnectionStatus(), isConnecting = common.isConnected(connectionStatus) || common.isConnecting(connectionStatus), isEventNeedDisconnected = utils.isInclude(ENGINE_EVENT_NEED_DISCONNECTED, eventName); return isConnecting && isEventNeedDisconnected; }; _proto._exec = function _exec(params) { var event = params.event; var engine = this._engine; if (this._isEventNeedConnect(event)) { return utils.Defer.reject(ERROR_INFO.NOT_CONNECTED); } if (this._isEventNeedDisconnect(event)) { return utils.Defer.reject(ERROR_INFO.RC_CONNECTION_EXIST); } var execResult = execEngineByEvent(params, engine); return utils.isPromise(execResult) ? execResult["catch"](function (error) { var errorCode = error.status || error.code || error; var msg = utils.isObject(error) ? error.msg : null; var errorInfo = ERROR_CODE_TO_INFO[errorCode] || { code: errorCode }; if (msg) { errorInfo.msg = msg; } var isValidErrorCode = utils.isNumberData(errorCode); if (!isValidErrorCode) { if (utils.isStackError(error)) { error = error.stack.toString(); } Logger.fatal(TAG.L_CRASH_E, { content: { desc: 'SDK Error', error: error } }); errorInfo = utils.extendInShallow(ERROR_INFO.SDK_INTERNAL_ERROR, { error: error }); } return utils.Defer.reject(errorInfo); }) : execResult; }; _proto.exec = function exec(params) { var event = params.event; var LOG_TAG = APP_ENGINE_EVENT_LOG_TAG[event], isNeedLog = !utils.isEmpty(LOG_TAG), _ref = LOG_TAG || {}, reqLogTag = _ref.req, respLogTag = _ref.resp; isNeedLog && Logger.info(reqLogTag, params); var execResult = this._exec(params); if (utils.isPromise(execResult)) { return execResult.then(function (result) { isNeedLog && Logger.info(respLogTag, result); return result; })["catch"](function (error) { error = error || {}; var _error = error, code = _error.code; if (isNeedLog && !Logger.isIgnoreErrorCode(code)) { Logger.error(respLogTag, error); } return utils.Defer.reject(error); }); } else { isNeedLog && Logger.info(respLogTag, execResult); return execResult; } }; return EngineDispatcher; }(); var Type = function Type(name, validator, options) { options = options || {}; var self = this; self.validate = validator; self.name = name; self.errorInfo = options.errorInfo; self.canBeNull = function () { self.validate = function (data) { return utils.isUndefined(data) || utils.isNull(data) || validator(data); }; return self; }; }; Type.isType = function (type) { return type instanceof Type; }; Type.String = new Type('String', utils.isString); Type.Number = new Type('Number', utils.isNumber); Type.Boolean = new Type('Boolean', utils.isBoolean); Type.Function = new Type('Function', utils.isFunction); Type.Object = new Type('Object', utils.isObject); Type.Array = new Type('Array', utils.isArray); Type.NotAllUndefined = new Type('AllUndefined', function (obj) { if (utils.isObject(obj) || utils.isArray(obj)) { var isNotUndefined = false; utils.forEach(obj, function (val) { if (!utils.isUndefined(val)) { isNotUndefined = true; } }); return isNotUndefined; } else { return !utils.isUndefined(obj); } }); var conversationType = common.getConversationTypeList().join('、'); Type.ConversationType = new Type(conversationType, common.isValidConversationType, { errorInfo: 'Not all settings are empty' }); Type.ChatRoomEntryKey = new Type('ChatRoomEntryKey', common.isValidChatRoomKey, { errorInfo: 'ChatRoom Key length must be 1 - 128, Only letters、numbers、+、=、-、_ are supported' }); Type.ChatRoomEntryValue = new Type('ChatRoomEntryValue', common.isValidChatRoomValue, { errorInfo: 'ChatRoom Value length must be 1 - 4096' }); var Struct = function () { function Struct(structure, funcName, paths) { if (paths === void 0) { paths = []; } if (!(this instanceof Struct)) { return new Struct(structure, funcName, paths); } var self = this; self.structure = structure; self.paths = paths; self.funcName = funcName; if (Type.isType(structure)) { self.validate = self._validateType; } else if (utils.isArray(structure)) { self.validate = self._validateArray; } else if (utils.isObject(structure)) { self.validate = self._validateObject; } else { self.validate = self._validateOther; } } var _proto = Struct.prototype; _proto._validateType = function _validateType(data) { var structure = this.structure; var isValid = structure.validate(data); return isValid ? this._getSuccess() : this._getError(data); }; _proto._validateArray = function _validateArray(data) { var structure = this.structure; if (utils.isEmpty(structure)) { return this._getSuccess(); } if (!utils.isArray(data)) { return this._getError(data); } var typer = structure[0]; for (var filed in data) { var val = data[filed]; var result = this._validateField(typer, filed, val); if (result.isError) { return result; } } return this._getSuccess(); }; _proto._validateObject = function _validateObject(data) { var structure = this.structure, paths = this.paths; data = data || {}; if (utils.isEmpty(structure)) { return this._getSuccess(); } if (!utils.isObject(data)) { return this._getError(data); } var checkedField = []; for (var filed in data) { var typer = structure[filed], val = data[filed]; var result = this._validateField(typer, filed, val); if (result.isError) { return result; } checkedField.push(filed); } for (var checkField in structure) { var _typer = structure[checkField]; var unCheckData = data[checkField]; if (!utils.isInclude(checkedField, checkField) && !_typer.validate(unCheckData)) { var errPaths = utils.copy(paths); errPaths.push(checkField); return this._getError(unCheckData, { paths: errPaths, expect: _typer.name }); } } return this._getSuccess(); }; _proto._validateOther = function _validateOther(data) { var self = this; var structure = self.structure; if (utils.isEqual(structure, data) || utils.isEmpty(structure)) { return self._getSuccess(); } else { return self._getError(data, { current: data, expect: structure }); } }; _proto._validateField = function _validateField(typer, filed, value) { var paths = this.paths, funcName = this.funcName; var newPaths = utils.copy(paths); newPaths.push(filed); return new Struct(typer, funcName, newPaths).validate(value); }; _proto._getError = function _getError(data, options) { if (options === void 0) { options = []; } var structure = this.structure, paths = this.paths, funcName = this.funcName; options = utils.extend({ current: data, expect: structure.name || utils.getTypeName(structure), paths: paths }, options); paths = options.paths; var _options = options, current = _options.current, expect = _options.expect; var param = utils.isEmpty(paths) ? 'param' : paths.join('.'); var currentType = utils.getTypeName(current); current = utils.toJSON(current) || current; current = current + "(" + currentType + ")"; var msg = utils.tplEngine(ERROR_INFO.PARAMETER_ERROR.msg, { param: param, expect: expect, current: current }); var info = { code: ERROR_INFO.PARAMETER_ERROR.code, funcName: funcName, msg: msg }; var jsonInfo = utils.toJSON(info); if (utils.isEmpty(funcName)) delete info[funcName]; if (structure.errorInfo) { info = structure.errorInfo; } return { isError: true, info: info, jsonInfo: jsonInfo }; }; _proto._getSuccess = function _getSuccess() { return { isError: false }; }; return Struct; }(); var validate = (function (struct, params, eventName) { return Struct(struct, eventName).validate(params); }); var _MESSAGE_TYPE_VALIDAT; var MESSAGE_TYPE_VALIDATE = (_MESSAGE_TYPE_VALIDAT = {}, _MESSAGE_TYPE_VALIDAT[MESSAGE_TYPE.TEXT] = { content: Type.String }, _MESSAGE_TYPE_VALIDAT[MESSAGE_TYPE.VOICE] = { content: Type.String, duration: Type.Number }, _MESSAGE_TYPE_VALIDAT[MESSAGE_TYPE.HQ_VOICE] = { remoteUrl: Type.String, duration: Type.Number }, _MESSAGE_TYPE_VALIDAT[MESSAGE_TYPE.IMAGE] = { content: Type.String, imageUri: Type.String }, _MESSAGE_TYPE_VALIDAT[MESSAGE_TYPE.GIF] = { gifDataSize: Type.Number, width: Type.Number, height: Type.Number, remoteUrl: Type.String }, _MESSAGE_TYPE_VALIDAT[MESSAGE_TYPE.RICH_CONTENT] = { title: Type.String, content: Type.String, imageUri: Type.String, url: Type.String }, _MESSAGE_TYPE_VALIDAT[MESSAGE_TYPE.LOCATION] = { content: Type.String, latitude: Type.Number, longitude: Type.Number, poi: Type.String }, _MESSAGE_TYPE_VALIDAT[MESSAGE_TYPE.FILE] = { name: Type.String, size: Type.Number, type: Type.String, fileUrl: Type.String }, _MESSAGE_TYPE_VALIDAT[MESSAGE_TYPE.SIGHT] = { sightUrl: Type.String, content: Type.String, duration: Type.Number, size: Type.Number, name: Type.String }, _MESSAGE_TYPE_VALIDAT[MESSAGE_TYPE.COMBINE] = { remoteUrl: Type.String, conversationType: Type.Number, nameList: Type.Array, summaryList: Type.Array }, _MESSAGE_TYPE_VALIDAT); var validateMsgContent = (function (objectName, option, eventName) { var validateByObjectName = MESSAGE_TYPE_VALIDATE[objectName]; if (validateByObjectName) { return validate(validateByObjectName, option, eventName); } else { return { isError: false, info: '' }; } }); var Conversation = (function (_engineDispatcher) { var _temp; return _temp = function () { Conversation.create = function create(option) { return new Conversation(option); }; Conversation.get = function get(option) { return new Conversation(option); }; Conversation.merge = function merge(option) { try { return common.mergeConversationList(option); } catch (e) { utils.consoleError(e); } }; Conversation.remove = function remove(option) { var _validate = validate({ type: Type.ConversationType, targetId: Type.String }, option, 'Conversation.remove'), isError = _validate.isError, info = _validate.info; if (isError) { return utils.Defer.reject(info); } return _engineDispatcher.exec({ event: ENGINE_EVENT.REMOVE_CONVERSATION, args: [option] }); }; Conversation.getList = function getList(option) { var _validate2 = validate({ count: Type.Number.canBeNull(), startTime: Type.Number.canBeNull() }, option, 'Conversation.getList'), isError = _validate2.isError, info = _validate2.info; if (isError) { return utils.Defer.reject(info); } return _engineDispatcher.exec({ event: ENGINE_EVENT.GET_CONVERSATION_LIST, args: [option] }); }; Conversation.getTotalUnreadCount = function getTotalUnreadCount() { return _engineDispatcher.exec({ event: ENGINE_EVENT.GET_TOTAL_UNREAD_COUNT }); }; function Conversation(option) { this.type = void 0; this.targetId = void 0; var _validate3 = validate({ type: Type.ConversationType, targetId: Type.String }, option, 'new Conversation'), isError = _validate3.isError, jsonInfo = _validate3.jsonInfo; if (isError) { utils.consoleError(jsonInfo); return jsonInfo; } utils.extend(this, option); } var _proto = Conversation.prototype; _proto.send = function send(option) { var eventName = 'conversation.send'; var _validate4 = validate({ messageType: Type.String, content: Type.Object }, option, eventName), isError = _validate4.isError, info = _validate4.info; if (isError) { return utils.Defer.reject(info); } var _option = option, messageType = _option.messageType, content = _option.content; var _validateMsgContent = validateMsgContent(messageType, content, eventName), isContentError = _validateMsgContent.isError, formatInfo = _validateMsgContent.info; if (isContentError) { return utils.Defer.reject(formatInfo); } var _option2 = option, isMentioned = _option2.isMentioned, mentionedType = _option2.mentionedType, mentionedUserIdList = _option2.mentionedUserIdList; isMentioned && (option.isMentiond = isMentioned); mentionedType && (option.mentiondType = mentionedType); mentionedUserIdList && (option.mentiondUserIdList = mentionedUserIdList); option = utils.extendInShallow(SEND_MESSAGE_TYPE_OPTION[messageType], option); option = utils.extendInShallow(SEND_MESSAGE_OPTION, option); return _engineDispatcher.exec({ event: ENGINE_EVENT.SEND_MESSAGE, args: [this, option] }); }; _proto.recall = function recall(message, option) { var _validate5 = validate({ sentTime: Type.Number, messageUId: Type.String }, message, 'conversation.recall'), isError = _validate5.isError, info = _validate5.info; if (isError) { return utils.Defer.reject(info); } return _engineDispatcher.exec({ event: ENGINE_EVENT.RECALL_MESSAGE, args: [this, message, option] }); }; _proto.read = function read(option) { return _engineDispatcher.exec({ event: ENGINE_EVENT.CLEAR_UNREAD_COUNT, args: [this, option] }); }; _proto.getUnreadCount = function getUnreadCount() { var conversation = this; return _engineDispatcher.exec({ event: ENGINE_EVENT.GET_UNREAD_COUNT, args: [conversation] }); }; _proto.getMessages = function getMessages(option) { var _validate6 = validate({ order: Type.Number.canBeNull(), count: Type.Number.canBeNull(), timestrap: Type.Number.canBeNull() }, option, 'conversation.getMessages'), isError = _validate6.isError, info = _validate6.info; if (isError) { return utils.Defer.reject(info); } option = utils.extendInShallow(GET_MESSAGES_OPTION, option); return _engineDispatcher.exec({ event: ENGINE_EVENT.GET_HISTORY_MSGS, args: [this, option] }); }; _proto.deleteMessages = function deleteMessages(messages) { var _validate7 = validate([{ sentTime: Type.Number, messageUId: Type.String, messageDirection: Type.Number }], messages, 'conversation.deleteMessages'), isError = _validate7.isError, info = _validate7.info; if (isError) { return utils.Defer.reject(info); } return _engineDispatcher.exec({ event: ENGINE_EVENT.DELETE_MESSAGES, args: [this, messages] }); }; _proto.clearMessages = function clearMessages(option) { var _validate8 = validate({ timestrap: Type.Number }, option, 'conversation.clearMessages'), isError = _validate8.isError, info = _validate8.info; if (isError) { return utils.Defer.reject(info); } return _engineDispatcher.exec({ event: ENGINE_EVENT.CLEAR_MESSAGES, args: [this, option] }); }; _proto.setStatus = function setStatus(option) { var _validate9 = validate({ notificationStatus: Type.Number.canBeNull(), isTop: Type.Boolean.canBeNull() }, option, 'conversation.setStatus'), isError = _validate9.isError, info = _validate9.info; if (isError) { return utils.Defer.reject(info); } var allUndefinedValidate = validate(Type.NotAllUndefined, option); isError = allUndefinedValidate.isError; if (isError) { info = allUndefinedValidate.info; return utils.Defer.reject(info); } var notificationStatus = option.notificationStatus, isTop = option.isTop; return _engineDispatcher.exec({ event: ENGINE_EVENT.SET_CONVERSATION_STATUS_LIST, args: [[{ type: this.type, targetId: this.targetId, notificationStatus: notificationStatus, isTop: isTop }]] }); }; _proto.setStatusList = function setStatusList(statusList) { var _validate10 = validate([{ notificationStatus: Type.Number.canBeNull(), isTop: Type.Boolean.canBeNull() }], statusList, 'conversation.setStatusList'), isError = _validate10.isError, info = _validate10.info; if (isError) { return utils.Defer.reject(info); } var self = this; statusList = utils.map(statusList, function (status) { return utils.extend(status, { type: self.type, targetId: self.targetId }); }); return _engineDispatcher.exec({ event: ENGINE_EVENT.SET_CONVERSATION_STATUS_LIST, args: [statusList] }); }; _proto.destory = function destory() { var conversation = this; return _engineDispatcher.exec({ event: ENGINE_EVENT.REMOVE_CONVERSATION, args: [conversation] }); }; return Conversation; }(), _temp; }); var ChatRoom = (function (_engineDispatcher) { var _temp; return _temp = function () { ChatRoom.get = function get(option) { return new ChatRoom(option); }; function ChatRoom(option) { this.id = void 0; var _validate = validate({ id: Type.String }, option, 'new ChatRoom'), isError = _validate.isError, jsonInfo = _validate.jsonInfo; if (isError) { utils.consoleError(jsonInfo); return jsonInfo; } utils.extend(this, option); } var _proto = ChatRoom.prototype; _proto.join = function join(option) { var _validate2 = validate({ count: Type.Number.canBeNull() }, option, 'chatRoom.join'), isError = _validate2.isError, info = _validate2.info; if (isError) { return utils.Defer.reject(info); } option = utils.extendInShallow(JOIN_CHATROOM_OPTION, option); return _engineDispatcher.exec({ event: ENGINE_EVENT.JOIN_CHATROOM, args: [this, option] }); }; _proto.joinExist = function joinExist(option) { var _validate3 = validate({ count: Type.Number.canBeNull() }, option, 'chatRoom.joinExist'), isError = _validate3.isError, info = _validate3.info; if (isError) { return utils.Defer.reject(info); } option['isJoinExist'] = true; option = utils.extendInShallow(JOIN_CHATROOM_OPTION, option); return _engineDispatcher.exec({ event: ENGINE_EVENT.JOIN_CHATROOM, args: [this, option] }); }; _proto.quit = function quit() { return _engineDispatcher.exec({ event: ENGINE_EVENT.QUIT_CHATROOM, args: [this] }); }; _proto.getInfo = function getInfo(option) { var _validate4 = validate({ count: Type.Number.canBeNull(), order: Type.Number.canBeNull() }, option, 'chatRoom.getInfo'), isError = _validate4.isError, info = _validate4.info; if (isError) { return utils.Defer.reject(info); } option = utils.extendInShallow(GET_CHATROOM_INFO_OPTION, option); return _engineDispatcher.exec({ event: ENGINE_EVENT.GET_CHATROOM_INFO, args: [this, option] }); }; _proto.send = function send(option) { var eventName = 'chatRoom.send'; var _validate5 = validate({ messageType: Type.String, content: Type.Object }, option, eventName), isError = _validate5.isError, info = _validate5.info; if (isError) { return utils.Defer.reject(info); } var id = this.id; var _option = option, messageType = _option.messageType, content = _option.content; var _validateMsgContent = validateMsgContent(messageType, content, eventName), isContentError = _validateMsgContent.isError, formatInfo = _validateMsgContent.info; if (isContentError) { return utils.Defer.reject(formatInfo); } var conversation = { type: CONVERSATION_TYPE.CHATROOM, targetId: id }; option = utils.extendInShallow(SEND_MESSAGE_TYPE_OPTION[messageType], option); return _engineDispatcher.exec({ event: ENGINE_EVENT.SEND_MESSAGE, args: [conversation, option] }); }; _proto.getMessages = function getMessages(option) { var _validate6 = validate({ count: Type.Number.canBeNull(), order: Type.Number.canBeNull(), timestrap: Type.Number }, option, 'chatRoom.getInfo'), isError = _validate6.isError, info = _validate6.info; if (isError) { return utils.Defer.reject(info); } option = utils.extendInShallow(GET_CHATROOM_MESSAGES, option); return _engineDispatcher.exec({ event: ENGINE_EVENT.GET_CHATROOM_MSGS, args: [this, option] }); }; _proto.setEntry = function setEntry(option) { var _validate7 = validate({ key: Type.ChatRoomEntryKey, value: Type.ChatRoomEntryValue }, option, 'chatRoom.setEntry'), isError = _validate7.isError, info = _validate7.info; if (isError) { return utils.Defer.reject(info); } return _engineDispatcher.exec({ event: ENGINE_EVENT.SET_KV, args: [this, option] }); }; _proto.forceSetEntry = function forceSetEntry(option) { var _validate8 = validate({ key: Type.ChatRoomEntryKey, value: Type.ChatRoomEntryValue }, option, 'chatRoom.forceSetEntry'), isError = _validate8.isError, info = _validate8.info; if (isError) { return utils.Defer.reject(info); } return _engineDispatcher.exec({ event: ENGINE_EVENT.FORCE_SET_KV, args: [this, option] }); }; _proto.removeEntry = function removeEntry(option) { var _validate9 = validate({ key: Type.ChatRoomEntryKey }, option, 'chatRoom.removeEntry'), isError = _validate9.isError, info = _validate9.info; if (isError) { return utils.Defer.reject(info); } return _engineDispatcher.exec({ event: ENGINE_EVENT.DEL_KV, args: [this, option] }); }; _proto.forceRemoveEntry = function forceRemoveEntry(option) { var _validate10 = validate({ key: Type.ChatRoomEntryKey }, option, 'chatRoom.forceRemoveEntry'), isError = _validate10.isError, info = _validate10.info; if (isError) { return utils.Defer.reject(info); } return _engineDispatcher.exec({ event: ENGINE_EVENT.FORCE_DEL_KV, args: [this, option] }); }; _proto.getEntry = function getEntry(key) { var _validate11 = validate(Type.ChatRoomEntryKey, key, 'chatRoom.getEntry'), isError = _validate11.isError, info = _validate11.info; if (isError) { return utils.Defer.reject(info); } return _engineDispatcher.exec({ event: ENGINE_EVENT.GET_KV, args: [this, key] }); }; _proto.getAllEntries = function getAllEntries() { return _engineDispatcher.exec({ event: ENGINE_EVENT.GET_ALL_KV, args: [this] }); }; return ChatRoom; }(), _temp; }); var RTC = (function (_engineDispatcher) { var _temp; return _temp = function () { RTC.get = function get(option) { return new RTC(option); }; function RTC(option) { this.roomId = void 0; this.option = void 0; this.roomId = option.id; this.option = option; } var _proto = RTC.prototype; _proto.join = function join() { return _engineDispatcher.exec({ event: ENGINE_EVENT.JOIN_RTC, args: [this.option] }); }; _proto.quit = function quit() { return _engineDispatcher.exec({ event: ENGINE_EVENT.QUIT_RTC, args: [this.option] }); }; _proto.ping = function ping() { return _engineDispatcher.exec({ event: ENGINE_EVENT.PING_RTC, args: [this.option] }); }; _proto.getRoomInfo = function getRoomInfo() { return _engineDispatcher.exec({ event: ENGINE_EVENT.GET_RTC_ROOM_INFO, args: [this.option] }); }; _proto.getUserInfoList = function getUserInfoList() { return _engineDispatcher.exec({ event: ENGINE_EVENT.GET_RTC_USER_INFO_LIST, args: [this.option] }); }; _proto.setUserInfo = function setUserInfo(info) { return _engineDispatcher.exec({ event: ENGINE_EVENT.SET_RTC_USER_INFO, args: [this.option, info] }); }; _proto.removeUserInfo = function removeUserInfo(info) { return _engineDispatcher.exec({ event: ENGINE_EVENT.DEL_RTC_USER_INFO, args: [this.option, info] }); }; _proto.setData = function setData(key, value, isInner, apiType, message) { return _engineDispatcher.exec({ event: ENGINE_EVENT.SET_RTC_DATA, args: [this.roomId, key, value, isInner, apiType, message] }); }; _proto.getData = function getData(keys, isInner, apiType) { return _engineDispatcher.exec({ event: ENGINE_EVENT.GET_RTC_DATA, args: [this.roomId, keys, isInner, apiType] }); }; _proto.removeData = function removeData(keys, isInner, apiType, message) { return _engineDispatcher.exec({ event: ENGINE_EVENT.DEL_RTC_DATA, args: [this.roomId, keys, isInner, apiType, message] }); }; _proto.setUserData = function setUserData(key, value, isInner, message) { return this.setData(key, value, isInner, RTC_API_TYPE.PERSON, message); }; _proto.setRTCUserData = function setRTCUserData(message, valueInfo, objectName) { return _engineDispatcher.exec({ event: ENGINE_EVENT.SET_RTC_USER_DATA, args: [this.roomId, message, valueInfo, objectName] }); }; _proto.getUserData = function getUserData(keys, isInner) { return this.getData(keys, isInner, RTC_API_TYPE.PERSON); }; _proto.removeUserData = function removeUserData(keys, isInner, message) { return this.removeData(keys, isInner, RTC_API_TYPE.PERSON, message); }; _proto.setRoomData = function setRoomData(key, value, isInner, message) { return this.setData(key, value, isInner, RTC_API_TYPE.ROOM, message); }; _proto.getRoomData = function getRoomData(keys, isInner) { return this.getData(keys, isInner, RTC_API_TYPE.ROOM); }; _proto.removeRoomData = function removeRoomData(keys, isInner, message) { return this.removeData(keys, isInner, RTC_API_TYPE.ROOM, message); }; _proto.getUserList = function getUserList() { return _engineDispatcher.exec({ event: ENGINE_EVENT.GET_RTC_USER_LIST, args: [this.option] }); }; _proto.setOutData = function setOutData(rtcData, type, message) { return _engineDispatcher.exec({ event: ENGINE_EVENT.SET_RTC_OUT_DATA, args: [this.roomId, rtcData, type, message] }); }; _proto.getOutData = function getOutData(userIds) { return _engineDispatcher.exec({ event: ENGINE_EVENT.GET_RTC_OUT_DATA, args: [this.roomId, userIds] }); }; _proto.getToken = function getToken() { return _engineDispatcher.exec({ event: ENGINE_EVENT.GET_RTC_TOKEN, args: [this.option] }); }; _proto.setState = function setState(content) { return _engineDispatcher.exec({ event: ENGINE_EVENT.SET_RTC_STATE, args: [this.option, content] }); }; _proto.send = function send(option) { var id = this.roomId; var conversation = { type: CONVERSATION_TYPE.RTC_ROOM, targetId: id }; return _engineDispatcher.exec({ event: ENGINE_EVENT.SEND_MESSAGE, args: [conversation, option] }); }; return RTC; }(), _temp; }); var IM = function () { function IM(option) { this._engineDispatcher = void 0; var _validate = validate({ appkey: Type.String }, option, 'RongIMLib.init'), isError = _validate.isError, jsonInfo = _validate.jsonInfo; if (isError) { throw Error(jsonInfo); } var engineHandler = new EngineDispatcher(option); this._engineDispatcher = engineHandler; var Modules = { Conversation: Conversation(engineHandler), ChatRoom: ChatRoom(engineHandler), RTC: RTC(engineHandler) }; utils.extend(this, Modules); } var _proto = IM.prototype; _proto.getConnectionStatus = function getConnectionStatus() { return this._engineDispatcher.exec({ event: ENGINE_EVENT.GET_CONNECTION_STATUS }); }; _proto.getConnectionUserId = function getConnectionUserId() { return this._engineDispatcher.exec({ event: ENGINE_EVENT.GET_CONNECTION_USER_ID }); }; _proto.getConnectedTime = function getConnectedTime() { return this._engineDispatcher.exec({ event: ENGINE_EVENT.GET_CONNECTED_TIME }); }; _proto.getAppInfo = function getAppInfo() { return this._engineDispatcher.exec({ event: ENGINE_EVENT.GET_APP_INFO }); }; _proto.watch = function watch(watchers) { var _validate2 = validate({ conversation: Type.Function.canBeNull(), message: Type.Function.canBeNull(), status: Type.Function.canBeNull(), setting: Type.Function.canBeNull() }, watchers, 'im.watch'), isError = _validate2.isError, jsonInfo = _validate2.jsonInfo; if (isError) { utils.consoleError(jsonInfo); return jsonInfo; } return this._engineDispatcher.exec({ event: ENGINE_EVENT.WATCH, args: [watchers] }); }; _proto.unwatch = function unwatch(watchers) { return this._engineDispatcher.exec({ event: ENGINE_EVENT.UN_WATCH, args: [watchers] }); }; _proto.connect = function connect(user) { var _validate3 = validate({ token: Type.String }, user, 'im.connect'), isError = _validate3.isError, info = _validate3.info; if (isError) { return utils.Defer.reject(info); } return this._engineDispatcher.exec({ event: ENGINE_EVENT.CONNECT, args: [user] }); }; _proto.reconnect = function reconnect() { return this._engineDispatcher.exec({ event: ENGINE_EVENT.RECONNECT }); }; _proto.disconnect = function disconnect() { return this._engineDispatcher.exec({ event: ENGINE_EVENT.DISCONNECT, args: [true] }); }; _proto.changeUser = function changeUser(user) { var _validate4 = validate({ token: Type.String }, user, 'im.changeUser'), isError = _validate4.isError, info = _validate4.info; if (isError) { return utils.Defer.reject(info); } var self = this; return self.disconnect().then(function () { return self.connect(user); }); }; _proto.getFileToken = function getFileToken(fileType, originName) { return this._engineDispatcher.exec({ event: ENGINE_EVENT.GET_UPLOAD_TOKEN, args: [fileType, originName] }); }; _proto.getFileUrl = function getFileUrl(fileType, fileName, originName, uploadResp) { return this._engineDispatcher.exec({ event: ENGINE_EVENT.GET_UPLOAD_URL, args: [fileType, fileName, originName, uploadResp] }); }; return IM; }(); var imInstance; var initLogger = function initLogger(option, im) { var isDebug = option.isDebug, appkey = option.appkey, logCollectEvent = option.logger; utils.isFunction(logCollectEvent) && Logger.watchLog(logCollectEvent); Logger.setOption({ isDebug: isDebug, appkey: appkey }); Logger.info(TAG.A_INIT_O, { content: option }); im.watch({ status: function status(_ref) { var _status = _ref.status; Logger.setOption({ isNetworkUnavailable: utils.isEqual(_status, CONNECTION_STATUS.NETWORK_UNAVAILABLE) }); } }); }; var init = function init(option) { option = utils.extendInShallow(IM_OPTION, option); option.connectType = common.getConnectType(option); if (!imInstance) { imInstance = new IM(option); initLogger(option, imInstance); } return imInstance; }; var getInstance = function getInstance() { return imInstance; }; var index = utils.extend({ init: init, getInstance: getInstance, env: env, common: common, ERROR_CODE: ERROR_CODE, Logger: Logger }, product); return index; }))); ================================================ FILE: api-test/lib/js/es6-promise.js ================================================ !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):t.ES6Promise=e()}(this,function(){"use strict";function t(t){var e=typeof t;return null!==t&&("object"===e||"function"===e)}function e(t){return"function"==typeof t}function n(t){W=t}function r(t){z=t}function o(){return function(){return process.nextTick(a)}}function i(){return"undefined"!=typeof U?function(){U(a)}:c()}function s(){var t=0,e=new H(a),n=document.createTextNode("");return e.observe(n,{characterData:!0}),function(){n.data=t=++t%2}}function u(){var t=new MessageChannel;return t.port1.onmessage=a,function(){return t.port2.postMessage(0)}}function c(){var t=setTimeout;return function(){return t(a,1)}}function a(){for(var t=0;t=0&&Math.floor(t)===t&&isFinite(e)}function u(e){return n(e)&&"function"==typeof e.then&&"function"==typeof e.catch}function l(e){return null==e?"":Array.isArray(e)||s(e)&&e.toString===a?JSON.stringify(e,null,2):String(e)}function f(e){var t=parseFloat(e);return isNaN(t)?e:t}function p(e,t){for(var n=Object.create(null),r=e.split(","),i=0;i-1)return e.splice(n,1)}}var m=Object.prototype.hasOwnProperty;function y(e,t){return m.call(e,t)}function g(e){var t=Object.create(null);return function(n){return t[n]||(t[n]=e(n))}}var _=/-(\w)/g,b=g(function(e){return e.replace(_,function(e,t){return t?t.toUpperCase():""})}),$=g(function(e){return e.charAt(0).toUpperCase()+e.slice(1)}),w=/\B([A-Z])/g,C=g(function(e){return e.replace(w,"-$1").toLowerCase()});var x=Function.prototype.bind?function(e,t){return e.bind(t)}:function(e,t){function n(n){var r=arguments.length;return r?r>1?e.apply(t,arguments):e.call(t,n):e.call(t)}return n._length=e.length,n};function k(e,t){t=t||0;for(var n=e.length-t,r=new Array(n);n--;)r[n]=e[n+t];return r}function A(e,t){for(var n in t)e[n]=t[n];return e}function O(e){for(var t={},n=0;n0,Z=J&&J.indexOf("edge/")>0,G=(J&&J.indexOf("android"),J&&/iphone|ipad|ipod|ios/.test(J)||"ios"===K),X=(J&&/chrome\/\d+/.test(J),J&&/phantomjs/.test(J),J&&J.match(/firefox\/(\d+)/)),Y={}.watch,Q=!1;if(z)try{var ee={};Object.defineProperty(ee,"passive",{get:function(){Q=!0}}),window.addEventListener("test-passive",null,ee)}catch(e){}var te=function(){return void 0===B&&(B=!z&&!V&&"undefined"!=typeof global&&(global.process&&"server"===global.process.env.VUE_ENV)),B},ne=z&&window.__VUE_DEVTOOLS_GLOBAL_HOOK__;function re(e){return"function"==typeof e&&/native code/.test(e.toString())}var ie,oe="undefined"!=typeof Symbol&&re(Symbol)&&"undefined"!=typeof Reflect&&re(Reflect.ownKeys);ie="undefined"!=typeof Set&&re(Set)?Set:function(){function e(){this.set=Object.create(null)}return e.prototype.has=function(e){return!0===this.set[e]},e.prototype.add=function(e){this.set[e]=!0},e.prototype.clear=function(){this.set=Object.create(null)},e}();var ae=S,se=0,ce=function(){this.id=se++,this.subs=[]};ce.prototype.addSub=function(e){this.subs.push(e)},ce.prototype.removeSub=function(e){h(this.subs,e)},ce.prototype.depend=function(){ce.target&&ce.target.addDep(this)},ce.prototype.notify=function(){for(var e=this.subs.slice(),t=0,n=e.length;t-1)if(o&&!y(i,"default"))a=!1;else if(""===a||a===C(e)){var c=Pe(String,i.type);(c<0||s0&&(st((u=e(u,(a||"")+"_"+c))[0])&&st(f)&&(s[l]=he(f.text+u[0].text),u.shift()),s.push.apply(s,u)):i(u)?st(f)?s[l]=he(f.text+u):""!==u&&s.push(he(u)):st(u)&&st(f)?s[l]=he(f.text+u.text):(r(o._isVList)&&n(u.tag)&&t(u.key)&&n(a)&&(u.key="__vlist"+a+"_"+c+"__"),s.push(u)));return s}(e):void 0}function st(e){return n(e)&&n(e.text)&&!1===e.isComment}function ct(e,t){if(e){for(var n=Object.create(null),r=oe?Reflect.ownKeys(e):Object.keys(e),i=0;i0,a=t?!!t.$stable:!o,s=t&&t.$key;if(t){if(t._normalized)return t._normalized;if(a&&r&&r!==e&&s===r.$key&&!o&&!r.$hasNormal)return r;for(var c in i={},t)t[c]&&"$"!==c[0]&&(i[c]=pt(n,c,t[c]))}else i={};for(var u in n)u in i||(i[u]=dt(n,u));return t&&Object.isExtensible(t)&&(t._normalized=i),R(i,"$stable",a),R(i,"$key",s),R(i,"$hasNormal",o),i}function pt(e,t,n){var r=function(){var e=arguments.length?n.apply(null,arguments):n({});return(e=e&&"object"==typeof e&&!Array.isArray(e)?[e]:at(e))&&(0===e.length||1===e.length&&e[0].isComment)?void 0:e};return n.proxy&&Object.defineProperty(e,t,{get:r,enumerable:!0,configurable:!0}),r}function dt(e,t){return function(){return e[t]}}function vt(e,t){var r,i,a,s,c;if(Array.isArray(e)||"string"==typeof e)for(r=new Array(e.length),i=0,a=e.length;idocument.createEvent("Event").timeStamp&&(sn=function(){return cn.now()})}function un(){var e,t;for(an=sn(),rn=!0,Qt.sort(function(e,t){return e.id-t.id}),on=0;onon&&Qt[n].id>e.id;)n--;Qt.splice(n+1,0,e)}else Qt.push(e);nn||(nn=!0,Ye(un))}}(this)},fn.prototype.run=function(){if(this.active){var e=this.get();if(e!==this.value||o(e)||this.deep){var t=this.value;if(this.value=e,this.user)try{this.cb.call(this.vm,e,t)}catch(e){Re(e,this.vm,'callback for watcher "'+this.expression+'"')}else this.cb.call(this.vm,e,t)}}},fn.prototype.evaluate=function(){this.value=this.get(),this.dirty=!1},fn.prototype.depend=function(){for(var e=this.deps.length;e--;)this.deps[e].depend()},fn.prototype.teardown=function(){if(this.active){this.vm._isBeingDestroyed||h(this.vm._watchers,this);for(var e=this.deps.length;e--;)this.deps[e].removeSub(this);this.active=!1}};var pn={enumerable:!0,configurable:!0,get:S,set:S};function dn(e,t,n){pn.get=function(){return this[t][n]},pn.set=function(e){this[t][n]=e},Object.defineProperty(e,n,pn)}function vn(e){e._watchers=[];var t=e.$options;t.props&&function(e,t){var n=e.$options.propsData||{},r=e._props={},i=e.$options._propKeys=[];e.$parent&&$e(!1);var o=function(o){i.push(o);var a=Me(o,t,n,e);xe(r,o,a),o in e||dn(e,"_props",o)};for(var a in t)o(a);$e(!0)}(e,t.props),t.methods&&function(e,t){e.$options.props;for(var n in t)e[n]="function"!=typeof t[n]?S:x(t[n],e)}(e,t.methods),t.data?function(e){var t=e.$options.data;s(t=e._data="function"==typeof t?function(e,t){le();try{return e.call(t,t)}catch(e){return Re(e,t,"data()"),{}}finally{fe()}}(t,e):t||{})||(t={});var n=Object.keys(t),r=e.$options.props,i=(e.$options.methods,n.length);for(;i--;){var o=n[i];r&&y(r,o)||(a=void 0,36!==(a=(o+"").charCodeAt(0))&&95!==a&&dn(e,"_data",o))}var a;Ce(t,!0)}(e):Ce(e._data={},!0),t.computed&&function(e,t){var n=e._computedWatchers=Object.create(null),r=te();for(var i in t){var o=t[i],a="function"==typeof o?o:o.get;r||(n[i]=new fn(e,a||S,S,hn)),i in e||mn(e,i,o)}}(e,t.computed),t.watch&&t.watch!==Y&&function(e,t){for(var n in t){var r=t[n];if(Array.isArray(r))for(var i=0;i-1:"string"==typeof e?e.split(",").indexOf(t)>-1:(n=e,"[object RegExp]"===a.call(n)&&e.test(t));var n}function An(e,t){var n=e.cache,r=e.keys,i=e._vnode;for(var o in n){var a=n[o];if(a){var s=xn(a.componentOptions);s&&!t(s)&&On(n,o,r,i)}}}function On(e,t,n,r){var i=e[t];!i||r&&i.tag===r.tag||i.componentInstance.$destroy(),e[t]=null,h(n,t)}!function(t){t.prototype._init=function(t){var n=this;n._uid=bn++,n._isVue=!0,t&&t._isComponent?function(e,t){var n=e.$options=Object.create(e.constructor.options),r=t._parentVnode;n.parent=t.parent,n._parentVnode=r;var i=r.componentOptions;n.propsData=i.propsData,n._parentListeners=i.listeners,n._renderChildren=i.children,n._componentTag=i.tag,t.render&&(n.render=t.render,n.staticRenderFns=t.staticRenderFns)}(n,t):n.$options=De($n(n.constructor),t||{},n),n._renderProxy=n,n._self=n,function(e){var t=e.$options,n=t.parent;if(n&&!t.abstract){for(;n.$options.abstract&&n.$parent;)n=n.$parent;n.$children.push(e)}e.$parent=n,e.$root=n?n.$root:e,e.$children=[],e.$refs={},e._watcher=null,e._inactive=null,e._directInactive=!1,e._isMounted=!1,e._isDestroyed=!1,e._isBeingDestroyed=!1}(n),function(e){e._events=Object.create(null),e._hasHookEvent=!1;var t=e.$options._parentListeners;t&&qt(e,t)}(n),function(t){t._vnode=null,t._staticTrees=null;var n=t.$options,r=t.$vnode=n._parentVnode,i=r&&r.context;t.$slots=ut(n._renderChildren,i),t.$scopedSlots=e,t._c=function(e,n,r,i){return Pt(t,e,n,r,i,!1)},t.$createElement=function(e,n,r,i){return Pt(t,e,n,r,i,!0)};var o=r&&r.data;xe(t,"$attrs",o&&o.attrs||e,null,!0),xe(t,"$listeners",n._parentListeners||e,null,!0)}(n),Yt(n,"beforeCreate"),function(e){var t=ct(e.$options.inject,e);t&&($e(!1),Object.keys(t).forEach(function(n){xe(e,n,t[n])}),$e(!0))}(n),vn(n),function(e){var t=e.$options.provide;t&&(e._provided="function"==typeof t?t.call(e):t)}(n),Yt(n,"created"),n.$options.el&&n.$mount(n.$options.el)}}(wn),function(e){var t={get:function(){return this._data}},n={get:function(){return this._props}};Object.defineProperty(e.prototype,"$data",t),Object.defineProperty(e.prototype,"$props",n),e.prototype.$set=ke,e.prototype.$delete=Ae,e.prototype.$watch=function(e,t,n){if(s(t))return _n(this,e,t,n);(n=n||{}).user=!0;var r=new fn(this,e,t,n);if(n.immediate)try{t.call(this,r.value)}catch(e){Re(e,this,'callback for immediate watcher "'+r.expression+'"')}return function(){r.teardown()}}}(wn),function(e){var t=/^hook:/;e.prototype.$on=function(e,n){var r=this;if(Array.isArray(e))for(var i=0,o=e.length;i1?k(t):t;for(var n=k(arguments,1),r='event handler for "'+e+'"',i=0,o=t.length;iparseInt(this.max)&&On(a,s[0],s,this._vnode)),t.data.keepAlive=!0}return t||e&&e[0]}}};!function(e){var t={get:function(){return F}};Object.defineProperty(e,"config",t),e.util={warn:ae,extend:A,mergeOptions:De,defineReactive:xe},e.set=ke,e.delete=Ae,e.nextTick=Ye,e.observable=function(e){return Ce(e),e},e.options=Object.create(null),M.forEach(function(t){e.options[t+"s"]=Object.create(null)}),e.options._base=e,A(e.options.components,Tn),function(e){e.use=function(e){var t=this._installedPlugins||(this._installedPlugins=[]);if(t.indexOf(e)>-1)return this;var n=k(arguments,1);return n.unshift(this),"function"==typeof e.install?e.install.apply(e,n):"function"==typeof e&&e.apply(null,n),t.push(e),this}}(e),function(e){e.mixin=function(e){return this.options=De(this.options,e),this}}(e),Cn(e),function(e){M.forEach(function(t){e[t]=function(e,n){return n?("component"===t&&s(n)&&(n.name=n.name||e,n=this.options._base.extend(n)),"directive"===t&&"function"==typeof n&&(n={bind:n,update:n}),this.options[t+"s"][e]=n,n):this.options[t+"s"][e]}})}(e)}(wn),Object.defineProperty(wn.prototype,"$isServer",{get:te}),Object.defineProperty(wn.prototype,"$ssrContext",{get:function(){return this.$vnode&&this.$vnode.ssrContext}}),Object.defineProperty(wn,"FunctionalRenderContext",{value:Tt}),wn.version="2.6.11";var En=p("style,class"),Nn=p("input,textarea,option,select,progress"),jn=function(e,t,n){return"value"===n&&Nn(e)&&"button"!==t||"selected"===n&&"option"===e||"checked"===n&&"input"===e||"muted"===n&&"video"===e},Dn=p("contenteditable,draggable,spellcheck"),Ln=p("events,caret,typing,plaintext-only"),Mn=function(e,t){return Hn(t)||"false"===t?"false":"contenteditable"===e&&Ln(t)?t:"true"},In=p("allowfullscreen,async,autofocus,autoplay,checked,compact,controls,declare,default,defaultchecked,defaultmuted,defaultselected,defer,disabled,enabled,formnovalidate,hidden,indeterminate,inert,ismap,itemscope,loop,multiple,muted,nohref,noresize,noshade,novalidate,nowrap,open,pauseonexit,readonly,required,reversed,scoped,seamless,selected,sortable,translate,truespeed,typemustmatch,visible"),Fn="http://www.w3.org/1999/xlink",Pn=function(e){return":"===e.charAt(5)&&"xlink"===e.slice(0,5)},Rn=function(e){return Pn(e)?e.slice(6,e.length):""},Hn=function(e){return null==e||!1===e};function Bn(e){for(var t=e.data,r=e,i=e;n(i.componentInstance);)(i=i.componentInstance._vnode)&&i.data&&(t=Un(i.data,t));for(;n(r=r.parent);)r&&r.data&&(t=Un(t,r.data));return function(e,t){if(n(e)||n(t))return zn(e,Vn(t));return""}(t.staticClass,t.class)}function Un(e,t){return{staticClass:zn(e.staticClass,t.staticClass),class:n(e.class)?[e.class,t.class]:t.class}}function zn(e,t){return e?t?e+" "+t:e:t||""}function Vn(e){return Array.isArray(e)?function(e){for(var t,r="",i=0,o=e.length;i-1?hr(e,t,n):In(t)?Hn(n)?e.removeAttribute(t):(n="allowfullscreen"===t&&"EMBED"===e.tagName?"true":t,e.setAttribute(t,n)):Dn(t)?e.setAttribute(t,Mn(t,n)):Pn(t)?Hn(n)?e.removeAttributeNS(Fn,Rn(t)):e.setAttributeNS(Fn,t,n):hr(e,t,n)}function hr(e,t,n){if(Hn(n))e.removeAttribute(t);else{if(q&&!W&&"TEXTAREA"===e.tagName&&"placeholder"===t&&""!==n&&!e.__ieph){var r=function(t){t.stopImmediatePropagation(),e.removeEventListener("input",r)};e.addEventListener("input",r),e.__ieph=!0}e.setAttribute(t,n)}}var mr={create:dr,update:dr};function yr(e,r){var i=r.elm,o=r.data,a=e.data;if(!(t(o.staticClass)&&t(o.class)&&(t(a)||t(a.staticClass)&&t(a.class)))){var s=Bn(r),c=i._transitionClasses;n(c)&&(s=zn(s,Vn(c))),s!==i._prevClass&&(i.setAttribute("class",s),i._prevClass=s)}}var gr,_r,br,$r,wr,Cr,xr={create:yr,update:yr},kr=/[\w).+\-_$\]]/;function Ar(e){var t,n,r,i,o,a=!1,s=!1,c=!1,u=!1,l=0,f=0,p=0,d=0;for(r=0;r=0&&" "===(h=e.charAt(v));v--);h&&kr.test(h)||(u=!0)}}else void 0===i?(d=r+1,i=e.slice(0,r).trim()):m();function m(){(o||(o=[])).push(e.slice(d,r).trim()),d=r+1}if(void 0===i?i=e.slice(0,r).trim():0!==d&&m(),o)for(r=0;r-1?{exp:e.slice(0,$r),key:'"'+e.slice($r+1)+'"'}:{exp:e,key:null};_r=e,$r=wr=Cr=0;for(;!zr();)Vr(br=Ur())?Jr(br):91===br&&Kr(br);return{exp:e.slice(0,wr),key:e.slice(wr+1,Cr)}}(e);return null===n.key?e+"="+t:"$set("+n.exp+", "+n.key+", "+t+")"}function Ur(){return _r.charCodeAt(++$r)}function zr(){return $r>=gr}function Vr(e){return 34===e||39===e}function Kr(e){var t=1;for(wr=$r;!zr();)if(Vr(e=Ur()))Jr(e);else if(91===e&&t++,93===e&&t--,0===t){Cr=$r;break}}function Jr(e){for(var t=e;!zr()&&(e=Ur())!==t;);}var qr,Wr="__r",Zr="__c";function Gr(e,t,n){var r=qr;return function i(){null!==t.apply(null,arguments)&&Qr(e,i,n,r)}}var Xr=Ve&&!(X&&Number(X[1])<=53);function Yr(e,t,n,r){if(Xr){var i=an,o=t;t=o._wrapper=function(e){if(e.target===e.currentTarget||e.timeStamp>=i||e.timeStamp<=0||e.target.ownerDocument!==document)return o.apply(this,arguments)}}qr.addEventListener(e,t,Q?{capture:n,passive:r}:n)}function Qr(e,t,n,r){(r||qr).removeEventListener(e,t._wrapper||t,n)}function ei(e,r){if(!t(e.data.on)||!t(r.data.on)){var i=r.data.on||{},o=e.data.on||{};qr=r.elm,function(e){if(n(e[Wr])){var t=q?"change":"input";e[t]=[].concat(e[Wr],e[t]||[]),delete e[Wr]}n(e[Zr])&&(e.change=[].concat(e[Zr],e.change||[]),delete e[Zr])}(i),rt(i,o,Yr,Qr,Gr,r.context),qr=void 0}}var ti,ni={create:ei,update:ei};function ri(e,r){if(!t(e.data.domProps)||!t(r.data.domProps)){var i,o,a=r.elm,s=e.data.domProps||{},c=r.data.domProps||{};for(i in n(c.__ob__)&&(c=r.data.domProps=A({},c)),s)i in c||(a[i]="");for(i in c){if(o=c[i],"textContent"===i||"innerHTML"===i){if(r.children&&(r.children.length=0),o===s[i])continue;1===a.childNodes.length&&a.removeChild(a.childNodes[0])}if("value"===i&&"PROGRESS"!==a.tagName){a._value=o;var u=t(o)?"":String(o);ii(a,u)&&(a.value=u)}else if("innerHTML"===i&&qn(a.tagName)&&t(a.innerHTML)){(ti=ti||document.createElement("div")).innerHTML=""+o+"";for(var l=ti.firstChild;a.firstChild;)a.removeChild(a.firstChild);for(;l.firstChild;)a.appendChild(l.firstChild)}else if(o!==s[i])try{a[i]=o}catch(e){}}}}function ii(e,t){return!e.composing&&("OPTION"===e.tagName||function(e,t){var n=!0;try{n=document.activeElement!==e}catch(e){}return n&&e.value!==t}(e,t)||function(e,t){var r=e.value,i=e._vModifiers;if(n(i)){if(i.number)return f(r)!==f(t);if(i.trim)return r.trim()!==t.trim()}return r!==t}(e,t))}var oi={create:ri,update:ri},ai=g(function(e){var t={},n=/:(.+)/;return e.split(/;(?![^(]*\))/g).forEach(function(e){if(e){var r=e.split(n);r.length>1&&(t[r[0].trim()]=r[1].trim())}}),t});function si(e){var t=ci(e.style);return e.staticStyle?A(e.staticStyle,t):t}function ci(e){return Array.isArray(e)?O(e):"string"==typeof e?ai(e):e}var ui,li=/^--/,fi=/\s*!important$/,pi=function(e,t,n){if(li.test(t))e.style.setProperty(t,n);else if(fi.test(n))e.style.setProperty(C(t),n.replace(fi,""),"important");else{var r=vi(t);if(Array.isArray(n))for(var i=0,o=n.length;i-1?t.split(yi).forEach(function(t){return e.classList.add(t)}):e.classList.add(t);else{var n=" "+(e.getAttribute("class")||"")+" ";n.indexOf(" "+t+" ")<0&&e.setAttribute("class",(n+t).trim())}}function _i(e,t){if(t&&(t=t.trim()))if(e.classList)t.indexOf(" ")>-1?t.split(yi).forEach(function(t){return e.classList.remove(t)}):e.classList.remove(t),e.classList.length||e.removeAttribute("class");else{for(var n=" "+(e.getAttribute("class")||"")+" ",r=" "+t+" ";n.indexOf(r)>=0;)n=n.replace(r," ");(n=n.trim())?e.setAttribute("class",n):e.removeAttribute("class")}}function bi(e){if(e){if("object"==typeof e){var t={};return!1!==e.css&&A(t,$i(e.name||"v")),A(t,e),t}return"string"==typeof e?$i(e):void 0}}var $i=g(function(e){return{enterClass:e+"-enter",enterToClass:e+"-enter-to",enterActiveClass:e+"-enter-active",leaveClass:e+"-leave",leaveToClass:e+"-leave-to",leaveActiveClass:e+"-leave-active"}}),wi=z&&!W,Ci="transition",xi="animation",ki="transition",Ai="transitionend",Oi="animation",Si="animationend";wi&&(void 0===window.ontransitionend&&void 0!==window.onwebkittransitionend&&(ki="WebkitTransition",Ai="webkitTransitionEnd"),void 0===window.onanimationend&&void 0!==window.onwebkitanimationend&&(Oi="WebkitAnimation",Si="webkitAnimationEnd"));var Ti=z?window.requestAnimationFrame?window.requestAnimationFrame.bind(window):setTimeout:function(e){return e()};function Ei(e){Ti(function(){Ti(e)})}function Ni(e,t){var n=e._transitionClasses||(e._transitionClasses=[]);n.indexOf(t)<0&&(n.push(t),gi(e,t))}function ji(e,t){e._transitionClasses&&h(e._transitionClasses,t),_i(e,t)}function Di(e,t,n){var r=Mi(e,t),i=r.type,o=r.timeout,a=r.propCount;if(!i)return n();var s=i===Ci?Ai:Si,c=0,u=function(){e.removeEventListener(s,l),n()},l=function(t){t.target===e&&++c>=a&&u()};setTimeout(function(){c0&&(n=Ci,l=a,f=o.length):t===xi?u>0&&(n=xi,l=u,f=c.length):f=(n=(l=Math.max(a,u))>0?a>u?Ci:xi:null)?n===Ci?o.length:c.length:0,{type:n,timeout:l,propCount:f,hasTransform:n===Ci&&Li.test(r[ki+"Property"])}}function Ii(e,t){for(;e.length1}function Ui(e,t){!0!==t.data.show&&Pi(t)}var zi=function(e){var o,a,s={},c=e.modules,u=e.nodeOps;for(o=0;ov?_(e,t(i[y+1])?null:i[y+1].elm,i,d,y,o):d>y&&$(r,p,v)}(p,h,y,o,l):n(y)?(n(e.text)&&u.setTextContent(p,""),_(p,null,y,0,y.length-1,o)):n(h)?$(h,0,h.length-1):n(e.text)&&u.setTextContent(p,""):e.text!==i.text&&u.setTextContent(p,i.text),n(v)&&n(d=v.hook)&&n(d=d.postpatch)&&d(e,i)}}}function k(e,t,i){if(r(i)&&n(e.parent))e.parent.data.pendingInsert=t;else for(var o=0;o-1,a.selected!==o&&(a.selected=o);else if(N(Wi(a),r))return void(e.selectedIndex!==s&&(e.selectedIndex=s));i||(e.selectedIndex=-1)}}function qi(e,t){return t.every(function(t){return!N(t,e)})}function Wi(e){return"_value"in e?e._value:e.value}function Zi(e){e.target.composing=!0}function Gi(e){e.target.composing&&(e.target.composing=!1,Xi(e.target,"input"))}function Xi(e,t){var n=document.createEvent("HTMLEvents");n.initEvent(t,!0,!0),e.dispatchEvent(n)}function Yi(e){return!e.componentInstance||e.data&&e.data.transition?e:Yi(e.componentInstance._vnode)}var Qi={model:Vi,show:{bind:function(e,t,n){var r=t.value,i=(n=Yi(n)).data&&n.data.transition,o=e.__vOriginalDisplay="none"===e.style.display?"":e.style.display;r&&i?(n.data.show=!0,Pi(n,function(){e.style.display=o})):e.style.display=r?o:"none"},update:function(e,t,n){var r=t.value;!r!=!t.oldValue&&((n=Yi(n)).data&&n.data.transition?(n.data.show=!0,r?Pi(n,function(){e.style.display=e.__vOriginalDisplay}):Ri(n,function(){e.style.display="none"})):e.style.display=r?e.__vOriginalDisplay:"none")},unbind:function(e,t,n,r,i){i||(e.style.display=e.__vOriginalDisplay)}}},eo={name:String,appear:Boolean,css:Boolean,mode:String,type:String,enterClass:String,leaveClass:String,enterToClass:String,leaveToClass:String,enterActiveClass:String,leaveActiveClass:String,appearClass:String,appearActiveClass:String,appearToClass:String,duration:[Number,String,Object]};function to(e){var t=e&&e.componentOptions;return t&&t.Ctor.options.abstract?to(zt(t.children)):e}function no(e){var t={},n=e.$options;for(var r in n.propsData)t[r]=e[r];var i=n._parentListeners;for(var o in i)t[b(o)]=i[o];return t}function ro(e,t){if(/\d-keep-alive$/.test(t.tag))return e("keep-alive",{props:t.componentOptions.propsData})}var io=function(e){return e.tag||Ut(e)},oo=function(e){return"show"===e.name},ao={name:"transition",props:eo,abstract:!0,render:function(e){var t=this,n=this.$slots.default;if(n&&(n=n.filter(io)).length){var r=this.mode,o=n[0];if(function(e){for(;e=e.parent;)if(e.data.transition)return!0}(this.$vnode))return o;var a=to(o);if(!a)return o;if(this._leaving)return ro(e,o);var s="__transition-"+this._uid+"-";a.key=null==a.key?a.isComment?s+"comment":s+a.tag:i(a.key)?0===String(a.key).indexOf(s)?a.key:s+a.key:a.key;var c=(a.data||(a.data={})).transition=no(this),u=this._vnode,l=to(u);if(a.data.directives&&a.data.directives.some(oo)&&(a.data.show=!0),l&&l.data&&!function(e,t){return t.key===e.key&&t.tag===e.tag}(a,l)&&!Ut(l)&&(!l.componentInstance||!l.componentInstance._vnode.isComment)){var f=l.data.transition=A({},c);if("out-in"===r)return this._leaving=!0,it(f,"afterLeave",function(){t._leaving=!1,t.$forceUpdate()}),ro(e,o);if("in-out"===r){if(Ut(a))return u;var p,d=function(){p()};it(c,"afterEnter",d),it(c,"enterCancelled",d),it(f,"delayLeave",function(e){p=e})}}return o}}},so=A({tag:String,moveClass:String},eo);function co(e){e.elm._moveCb&&e.elm._moveCb(),e.elm._enterCb&&e.elm._enterCb()}function uo(e){e.data.newPos=e.elm.getBoundingClientRect()}function lo(e){var t=e.data.pos,n=e.data.newPos,r=t.left-n.left,i=t.top-n.top;if(r||i){e.data.moved=!0;var o=e.elm.style;o.transform=o.WebkitTransform="translate("+r+"px,"+i+"px)",o.transitionDuration="0s"}}delete so.mode;var fo={Transition:ao,TransitionGroup:{props:so,beforeMount:function(){var e=this,t=this._update;this._update=function(n,r){var i=Zt(e);e.__patch__(e._vnode,e.kept,!1,!0),e._vnode=e.kept,i(),t.call(e,n,r)}},render:function(e){for(var t=this.tag||this.$vnode.data.tag||"span",n=Object.create(null),r=this.prevChildren=this.children,i=this.$slots.default||[],o=this.children=[],a=no(this),s=0;s-1?Gn[e]=t.constructor===window.HTMLUnknownElement||t.constructor===window.HTMLElement:Gn[e]=/HTMLUnknownElement/.test(t.toString())},A(wn.options.directives,Qi),A(wn.options.components,fo),wn.prototype.__patch__=z?zi:S,wn.prototype.$mount=function(e,t){return function(e,t,n){var r;return e.$el=t,e.$options.render||(e.$options.render=ve),Yt(e,"beforeMount"),r=function(){e._update(e._render(),n)},new fn(e,r,S,{before:function(){e._isMounted&&!e._isDestroyed&&Yt(e,"beforeUpdate")}},!0),n=!1,null==e.$vnode&&(e._isMounted=!0,Yt(e,"mounted")),e}(this,e=e&&z?Yn(e):void 0,t)},z&&setTimeout(function(){F.devtools&&ne&&ne.emit("init",wn)},0);var po=/\{\{((?:.|\r?\n)+?)\}\}/g,vo=/[-.*+?^${}()|[\]\/\\]/g,ho=g(function(e){var t=e[0].replace(vo,"\\$&"),n=e[1].replace(vo,"\\$&");return new RegExp(t+"((?:.|\\n)+?)"+n,"g")});var mo={staticKeys:["staticClass"],transformNode:function(e,t){t.warn;var n=Fr(e,"class");n&&(e.staticClass=JSON.stringify(n));var r=Ir(e,"class",!1);r&&(e.classBinding=r)},genData:function(e){var t="";return e.staticClass&&(t+="staticClass:"+e.staticClass+","),e.classBinding&&(t+="class:"+e.classBinding+","),t}};var yo,go={staticKeys:["staticStyle"],transformNode:function(e,t){t.warn;var n=Fr(e,"style");n&&(e.staticStyle=JSON.stringify(ai(n)));var r=Ir(e,"style",!1);r&&(e.styleBinding=r)},genData:function(e){var t="";return e.staticStyle&&(t+="staticStyle:"+e.staticStyle+","),e.styleBinding&&(t+="style:("+e.styleBinding+"),"),t}},_o=function(e){return(yo=yo||document.createElement("div")).innerHTML=e,yo.textContent},bo=p("area,base,br,col,embed,frame,hr,img,input,isindex,keygen,link,meta,param,source,track,wbr"),$o=p("colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr,source"),wo=p("address,article,aside,base,blockquote,body,caption,col,colgroup,dd,details,dialog,div,dl,dt,fieldset,figcaption,figure,footer,form,h1,h2,h3,h4,h5,h6,head,header,hgroup,hr,html,legend,li,menuitem,meta,optgroup,option,param,rp,rt,source,style,summary,tbody,td,tfoot,th,thead,title,tr,track"),Co=/^\s*([^\s"'<>\/=]+)(?:\s*(=)\s*(?:"([^"]*)"+|'([^']*)'+|([^\s"'=<>`]+)))?/,xo=/^\s*((?:v-[\w-]+:|@|:|#)\[[^=]+\][^\s"'<>\/=]*)(?:\s*(=)\s*(?:"([^"]*)"+|'([^']*)'+|([^\s"'=<>`]+)))?/,ko="[a-zA-Z_][\\-\\.0-9_a-zA-Z"+P.source+"]*",Ao="((?:"+ko+"\\:)?"+ko+")",Oo=new RegExp("^<"+Ao),So=/^\s*(\/?)>/,To=new RegExp("^<\\/"+Ao+"[^>]*>"),Eo=/^]+>/i,No=/^",""":'"',"&":"&"," ":"\n"," ":"\t","'":"'"},Io=/&(?:lt|gt|quot|amp|#39);/g,Fo=/&(?:lt|gt|quot|amp|#39|#10|#9);/g,Po=p("pre,textarea",!0),Ro=function(e,t){return e&&Po(e)&&"\n"===t[0]};function Ho(e,t){var n=t?Fo:Io;return e.replace(n,function(e){return Mo[e]})}var Bo,Uo,zo,Vo,Ko,Jo,qo,Wo,Zo=/^@|^v-on:/,Go=/^v-|^@|^:|^#/,Xo=/([\s\S]*?)\s+(?:in|of)\s+([\s\S]*)/,Yo=/,([^,\}\]]*)(?:,([^,\}\]]*))?$/,Qo=/^\(|\)$/g,ea=/^\[.*\]$/,ta=/:(.*)$/,na=/^:|^\.|^v-bind:/,ra=/\.[^.\]]+(?=[^\]]*$)/g,ia=/^v-slot(:|$)|^#/,oa=/[\r\n]/,aa=/\s+/g,sa=g(_o),ca="_empty_";function ua(e,t,n){return{type:1,tag:e,attrsList:t,attrsMap:ma(t),rawAttrsMap:{},parent:n,children:[]}}function la(e,t){Bo=t.warn||Sr,Jo=t.isPreTag||T,qo=t.mustUseProp||T,Wo=t.getTagNamespace||T;t.isReservedTag;zo=Tr(t.modules,"transformNode"),Vo=Tr(t.modules,"preTransformNode"),Ko=Tr(t.modules,"postTransformNode"),Uo=t.delimiters;var n,r,i=[],o=!1!==t.preserveWhitespace,a=t.whitespace,s=!1,c=!1;function u(e){if(l(e),s||e.processed||(e=fa(e,t)),i.length||e===n||n.if&&(e.elseif||e.else)&&da(n,{exp:e.elseif,block:e}),r&&!e.forbidden)if(e.elseif||e.else)a=e,(u=function(e){var t=e.length;for(;t--;){if(1===e[t].type)return e[t];e.pop()}}(r.children))&&u.if&&da(u,{exp:a.elseif,block:a});else{if(e.slotScope){var o=e.slotTarget||'"default"';(r.scopedSlots||(r.scopedSlots={}))[o]=e}r.children.push(e),e.parent=r}var a,u;e.children=e.children.filter(function(e){return!e.slotScope}),l(e),e.pre&&(s=!1),Jo(e.tag)&&(c=!1);for(var f=0;f]*>)","i")),p=e.replace(f,function(e,n,r){return u=r.length,Do(l)||"noscript"===l||(n=n.replace(//g,"$1").replace(//g,"$1")),Ro(l,n)&&(n=n.slice(1)),t.chars&&t.chars(n),""});c+=e.length-p.length,e=p,A(l,c-u,c)}else{var d=e.indexOf("<");if(0===d){if(No.test(e)){var v=e.indexOf("--\x3e");if(v>=0){t.shouldKeepComment&&t.comment(e.substring(4,v),c,c+v+3),C(v+3);continue}}if(jo.test(e)){var h=e.indexOf("]>");if(h>=0){C(h+2);continue}}var m=e.match(Eo);if(m){C(m[0].length);continue}var y=e.match(To);if(y){var g=c;C(y[0].length),A(y[1],g,c);continue}var _=x();if(_){k(_),Ro(_.tagName,e)&&C(1);continue}}var b=void 0,$=void 0,w=void 0;if(d>=0){for($=e.slice(d);!(To.test($)||Oo.test($)||No.test($)||jo.test($)||(w=$.indexOf("<",1))<0);)d+=w,$=e.slice(d);b=e.substring(0,d)}d<0&&(b=e),b&&C(b.length),t.chars&&b&&t.chars(b,c-b.length,c)}if(e===n){t.chars&&t.chars(e);break}}function C(t){c+=t,e=e.substring(t)}function x(){var t=e.match(Oo);if(t){var n,r,i={tagName:t[1],attrs:[],start:c};for(C(t[0].length);!(n=e.match(So))&&(r=e.match(xo)||e.match(Co));)r.start=c,C(r[0].length),r.end=c,i.attrs.push(r);if(n)return i.unarySlash=n[1],C(n[0].length),i.end=c,i}}function k(e){var n=e.tagName,c=e.unarySlash;o&&("p"===r&&wo(n)&&A(r),s(n)&&r===n&&A(n));for(var u=a(n)||!!c,l=e.attrs.length,f=new Array(l),p=0;p=0&&i[a].lowerCasedTag!==s;a--);else a=0;if(a>=0){for(var u=i.length-1;u>=a;u--)t.end&&t.end(i[u].tag,n,o);i.length=a,r=a&&i[a-1].tag}else"br"===s?t.start&&t.start(e,[],!0,n,o):"p"===s&&(t.start&&t.start(e,[],!1,n,o),t.end&&t.end(e,n,o))}A()}(e,{warn:Bo,expectHTML:t.expectHTML,isUnaryTag:t.isUnaryTag,canBeLeftOpenTag:t.canBeLeftOpenTag,shouldDecodeNewlines:t.shouldDecodeNewlines,shouldDecodeNewlinesForHref:t.shouldDecodeNewlinesForHref,shouldKeepComment:t.comments,outputSourceRange:t.outputSourceRange,start:function(e,o,a,l,f){var p=r&&r.ns||Wo(e);q&&"svg"===p&&(o=function(e){for(var t=[],n=0;nc&&(s.push(o=e.slice(c,i)),a.push(JSON.stringify(o)));var u=Ar(r[1].trim());a.push("_s("+u+")"),s.push({"@binding":u}),c=i+r[0].length}return c-1"+("true"===o?":("+t+")":":_q("+t+","+o+")")),Mr(e,"change","var $$a="+t+",$$el=$event.target,$$c=$$el.checked?("+o+"):("+a+");if(Array.isArray($$a)){var $$v="+(r?"_n("+i+")":i)+",$$i=_i($$a,$$v);if($$el.checked){$$i<0&&("+Br(t,"$$a.concat([$$v])")+")}else{$$i>-1&&("+Br(t,"$$a.slice(0,$$i).concat($$a.slice($$i+1))")+")}}else{"+Br(t,"$$c")+"}",null,!0)}(e,r,i);else if("input"===o&&"radio"===a)!function(e,t,n){var r=n&&n.number,i=Ir(e,"value")||"null";Er(e,"checked","_q("+t+","+(i=r?"_n("+i+")":i)+")"),Mr(e,"change",Br(t,i),null,!0)}(e,r,i);else if("input"===o||"textarea"===o)!function(e,t,n){var r=e.attrsMap.type,i=n||{},o=i.lazy,a=i.number,s=i.trim,c=!o&&"range"!==r,u=o?"change":"range"===r?Wr:"input",l="$event.target.value";s&&(l="$event.target.value.trim()"),a&&(l="_n("+l+")");var f=Br(t,l);c&&(f="if($event.target.composing)return;"+f),Er(e,"value","("+t+")"),Mr(e,u,f,null,!0),(s||a)&&Mr(e,"blur","$forceUpdate()")}(e,r,i);else if(!F.isReservedTag(o))return Hr(e,r,i),!1;return!0},text:function(e,t){t.value&&Er(e,"textContent","_s("+t.value+")",t)},html:function(e,t){t.value&&Er(e,"innerHTML","_s("+t.value+")",t)}},isPreTag:function(e){return"pre"===e},isUnaryTag:bo,mustUseProp:jn,canBeLeftOpenTag:$o,isReservedTag:Wn,getTagNamespace:Zn,staticKeys:function(e){return e.reduce(function(e,t){return e.concat(t.staticKeys||[])},[]).join(",")}(ba)},xa=g(function(e){return p("type,tag,attrsList,attrsMap,plain,parent,children,attrs,start,end,rawAttrsMap"+(e?","+e:""))});function ka(e,t){e&&($a=xa(t.staticKeys||""),wa=t.isReservedTag||T,function e(t){t.static=function(e){if(2===e.type)return!1;if(3===e.type)return!0;return!(!e.pre&&(e.hasBindings||e.if||e.for||d(e.tag)||!wa(e.tag)||function(e){for(;e.parent;){if("template"!==(e=e.parent).tag)return!1;if(e.for)return!0}return!1}(e)||!Object.keys(e).every($a)))}(t);if(1===t.type){if(!wa(t.tag)&&"slot"!==t.tag&&null==t.attrsMap["inline-template"])return;for(var n=0,r=t.children.length;n|^function(?:\s+[\w$]+)?\s*\(/,Oa=/\([^)]*?\);*$/,Sa=/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*|\['[^']*?']|\["[^"]*?"]|\[\d+]|\[[A-Za-z_$][\w$]*])*$/,Ta={esc:27,tab:9,enter:13,space:32,up:38,left:37,right:39,down:40,delete:[8,46]},Ea={esc:["Esc","Escape"],tab:"Tab",enter:"Enter",space:[" ","Spacebar"],up:["Up","ArrowUp"],left:["Left","ArrowLeft"],right:["Right","ArrowRight"],down:["Down","ArrowDown"],delete:["Backspace","Delete","Del"]},Na=function(e){return"if("+e+")return null;"},ja={stop:"$event.stopPropagation();",prevent:"$event.preventDefault();",self:Na("$event.target !== $event.currentTarget"),ctrl:Na("!$event.ctrlKey"),shift:Na("!$event.shiftKey"),alt:Na("!$event.altKey"),meta:Na("!$event.metaKey"),left:Na("'button' in $event && $event.button !== 0"),middle:Na("'button' in $event && $event.button !== 1"),right:Na("'button' in $event && $event.button !== 2")};function Da(e,t){var n=t?"nativeOn:":"on:",r="",i="";for(var o in e){var a=La(e[o]);e[o]&&e[o].dynamic?i+=o+","+a+",":r+='"'+o+'":'+a+","}return r="{"+r.slice(0,-1)+"}",i?n+"_d("+r+",["+i.slice(0,-1)+"])":n+r}function La(e){if(!e)return"function(){}";if(Array.isArray(e))return"["+e.map(function(e){return La(e)}).join(",")+"]";var t=Sa.test(e.value),n=Aa.test(e.value),r=Sa.test(e.value.replace(Oa,""));if(e.modifiers){var i="",o="",a=[];for(var s in e.modifiers)if(ja[s])o+=ja[s],Ta[s]&&a.push(s);else if("exact"===s){var c=e.modifiers;o+=Na(["ctrl","shift","alt","meta"].filter(function(e){return!c[e]}).map(function(e){return"$event."+e+"Key"}).join("||"))}else a.push(s);return a.length&&(i+=function(e){return"if(!$event.type.indexOf('key')&&"+e.map(Ma).join("&&")+")return null;"}(a)),o&&(i+=o),"function($event){"+i+(t?"return "+e.value+"($event)":n?"return ("+e.value+")($event)":r?"return "+e.value:e.value)+"}"}return t||n?e.value:"function($event){"+(r?"return "+e.value:e.value)+"}"}function Ma(e){var t=parseInt(e,10);if(t)return"$event.keyCode!=="+t;var n=Ta[e],r=Ea[e];return"_k($event.keyCode,"+JSON.stringify(e)+","+JSON.stringify(n)+",$event.key,"+JSON.stringify(r)+")"}var Ia={on:function(e,t){e.wrapListeners=function(e){return"_g("+e+","+t.value+")"}},bind:function(e,t){e.wrapData=function(n){return"_b("+n+",'"+e.tag+"',"+t.value+","+(t.modifiers&&t.modifiers.prop?"true":"false")+(t.modifiers&&t.modifiers.sync?",true":"")+")"}},cloak:S},Fa=function(e){this.options=e,this.warn=e.warn||Sr,this.transforms=Tr(e.modules,"transformCode"),this.dataGenFns=Tr(e.modules,"genData"),this.directives=A(A({},Ia),e.directives);var t=e.isReservedTag||T;this.maybeComponent=function(e){return!!e.component||!t(e.tag)},this.onceId=0,this.staticRenderFns=[],this.pre=!1};function Pa(e,t){var n=new Fa(t);return{render:"with(this){return "+(e?Ra(e,n):'_c("div")')+"}",staticRenderFns:n.staticRenderFns}}function Ra(e,t){if(e.parent&&(e.pre=e.pre||e.parent.pre),e.staticRoot&&!e.staticProcessed)return Ha(e,t);if(e.once&&!e.onceProcessed)return Ba(e,t);if(e.for&&!e.forProcessed)return za(e,t);if(e.if&&!e.ifProcessed)return Ua(e,t);if("template"!==e.tag||e.slotTarget||t.pre){if("slot"===e.tag)return function(e,t){var n=e.slotName||'"default"',r=qa(e,t),i="_t("+n+(r?","+r:""),o=e.attrs||e.dynamicAttrs?Ga((e.attrs||[]).concat(e.dynamicAttrs||[]).map(function(e){return{name:b(e.name),value:e.value,dynamic:e.dynamic}})):null,a=e.attrsMap["v-bind"];!o&&!a||r||(i+=",null");o&&(i+=","+o);a&&(i+=(o?"":",null")+","+a);return i+")"}(e,t);var n;if(e.component)n=function(e,t,n){var r=t.inlineTemplate?null:qa(t,n,!0);return"_c("+e+","+Va(t,n)+(r?","+r:"")+")"}(e.component,e,t);else{var r;(!e.plain||e.pre&&t.maybeComponent(e))&&(r=Va(e,t));var i=e.inlineTemplate?null:qa(e,t,!0);n="_c('"+e.tag+"'"+(r?","+r:"")+(i?","+i:"")+")"}for(var o=0;o>>0}(a):"")+")"}(e,e.scopedSlots,t)+","),e.model&&(n+="model:{value:"+e.model.value+",callback:"+e.model.callback+",expression:"+e.model.expression+"},"),e.inlineTemplate){var o=function(e,t){var n=e.children[0];if(n&&1===n.type){var r=Pa(n,t.options);return"inlineTemplate:{render:function(){"+r.render+"},staticRenderFns:["+r.staticRenderFns.map(function(e){return"function(){"+e+"}"}).join(",")+"]}"}}(e,t);o&&(n+=o+",")}return n=n.replace(/,$/,"")+"}",e.dynamicAttrs&&(n="_b("+n+',"'+e.tag+'",'+Ga(e.dynamicAttrs)+")"),e.wrapData&&(n=e.wrapData(n)),e.wrapListeners&&(n=e.wrapListeners(n)),n}function Ka(e){return 1===e.type&&("slot"===e.tag||e.children.some(Ka))}function Ja(e,t){var n=e.attrsMap["slot-scope"];if(e.if&&!e.ifProcessed&&!n)return Ua(e,t,Ja,"null");if(e.for&&!e.forProcessed)return za(e,t,Ja);var r=e.slotScope===ca?"":String(e.slotScope),i="function("+r+"){return "+("template"===e.tag?e.if&&n?"("+e.if+")?"+(qa(e,t)||"undefined")+":undefined":qa(e,t)||"undefined":Ra(e,t))+"}",o=r?"":",proxy:true";return"{key:"+(e.slotTarget||'"default"')+",fn:"+i+o+"}"}function qa(e,t,n,r,i){var o=e.children;if(o.length){var a=o[0];if(1===o.length&&a.for&&"template"!==a.tag&&"slot"!==a.tag){var s=n?t.maybeComponent(a)?",1":",0":"";return""+(r||Ra)(a,t)+s}var c=n?function(e,t){for(var n=0,r=0;r':'
',ts.innerHTML.indexOf(" ")>0}var os=!!z&&is(!1),as=!!z&&is(!0),ss=g(function(e){var t=Yn(e);return t&&t.innerHTML}),cs=wn.prototype.$mount;return wn.prototype.$mount=function(e,t){if((e=e&&Yn(e))===document.body||e===document.documentElement)return this;var n=this.$options;if(!n.render){var r=n.template;if(r)if("string"==typeof r)"#"===r.charAt(0)&&(r=ss(r));else{if(!r.nodeType)return this;r=r.innerHTML}else e&&(r=function(e){if(e.outerHTML)return e.outerHTML;var t=document.createElement("div");return t.appendChild(e.cloneNode(!0)),t.innerHTML}(e));if(r){var i=rs(r,{outputSourceRange:!1,shouldDecodeNewlines:os,shouldDecodeNewlinesForHref:as,delimiters:n.delimiters,comments:n.comments},this),o=i.render,a=i.staticRenderFns;n.render=o,n.staticRenderFns=a}}return cs.call(this,e,t)},wn.compile=rs,wn}); ================================================ FILE: api-test/lib/js/vue-json-pretty.js ================================================ !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.VueJsonPretty=t():e.VueJsonPretty=t()}("undefined"!=typeof self?self:this,function(){return function(e){function t(r){if(n[r])return n[r].exports;var o=n[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,t),o.l=!0,o.exports}var n={};return t.m=e,t.c=n,t.d=function(e,n,r){t.o(e,n)||Object.defineProperty(e,n,{configurable:!1,enumerable:!0,get:r})},t.n=function(e){var n=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(n,"a",n),n},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p="",t(t.s=39)}([function(e,t){var n=e.exports={version:"2.6.9"};"number"==typeof __e&&(__e=n)},function(e,t,n){var r=n(25)("wks"),o=n(27),i=n(3).Symbol,s="function"==typeof i;(e.exports=function(e){return r[e]||(r[e]=s&&i[e]||(s?i:o)("Symbol."+e))}).store=r},function(e,t){e.exports=function(e,t,n,r,o,i){var s,a=e=e||{},c=typeof e.default;"object"!==c&&"function"!==c||(s=e,a=e.default);var u="function"==typeof a?a.options:a;t&&(u.render=t.render,u.staticRenderFns=t.staticRenderFns,u._compiled=!0),n&&(u.functional=!0),o&&(u._scopeId=o);var l;if(i?(l=function(e){e=e||this.$vnode&&this.$vnode.ssrContext||this.parent&&this.parent.$vnode&&this.parent.$vnode.ssrContext,e||"undefined"==typeof __VUE_SSR_CONTEXT__||(e=__VUE_SSR_CONTEXT__),r&&r.call(this,e),e&&e._registeredComponents&&e._registeredComponents.add(i)},u._ssrRegister=l):r&&(l=r),l){var f=u.functional,d=f?u.render:u.beforeCreate;f?(u._injectStyles=l,u.render=function(e,t){return l.call(t),d(e,t)}):u.beforeCreate=d?[].concat(d,l):[l]}return{esModule:s,exports:a,options:u}}},function(e,t){var n=e.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=n)},function(e,t,n){e.exports=!n(9)(function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a})},function(e,t,n){var r=n(3),o=n(0),i=n(19),s=n(6),a=n(10),c=function(e,t,n){var u,l,f,d=e&c.F,p=e&c.G,h=e&c.S,v=e&c.P,b=e&c.B,m=e&c.W,y=p?o:o[t]||(o[t]={}),g=y.prototype,_=p?r:h?r[t]:(r[t]||{}).prototype;p&&(n=t);for(u in n)(l=!d&&_&&void 0!==_[u])&&a(y,u)||(f=l?_[u]:n[u],y[u]=p&&"function"!=typeof _[u]?n[u]:b&&l?i(f,r):m&&_[u]==f?function(e){var t=function(t,n,r){if(this instanceof e){switch(arguments.length){case 0:return new e;case 1:return new e(t);case 2:return new e(t,n)}return new e(t,n,r)}return e.apply(this,arguments)};return t.prototype=e.prototype,t}(f):v&&"function"==typeof f?i(Function.call,f):f,v&&((y.virtual||(y.virtual={}))[u]=f,e&c.R&&g&&!g[u]&&s(g,u,f)))};c.F=1,c.G=2,c.S=4,c.P=8,c.B=16,c.W=32,c.U=64,c.R=128,e.exports=c},function(e,t,n){var r=n(7),o=n(13);e.exports=n(4)?function(e,t,n){return r.f(e,t,o(1,n))}:function(e,t,n){return e[t]=n,e}},function(e,t,n){var r=n(8),o=n(44),i=n(45),s=Object.defineProperty;t.f=n(4)?Object.defineProperty:function(e,t,n){if(r(e),t=i(t,!0),r(n),o)try{return s(e,t,n)}catch(e){}if("get"in n||"set"in n)throw TypeError("Accessors not supported!");return"value"in n&&(e[t]=n.value),e}},function(e,t,n){var r=n(12);e.exports=function(e){if(!r(e))throw TypeError(e+" is not an object!");return e}},function(e,t){e.exports=function(e){try{return!!e()}catch(e){return!0}}},function(e,t){var n={}.hasOwnProperty;e.exports=function(e,t){return n.call(e,t)}},function(e,t,n){var r=n(15);e.exports=function(e){return Object(r(e))}},function(e,t){e.exports=function(e){return"object"==typeof e?null!==e:"function"==typeof e}},function(e,t){e.exports=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}}},function(e,t,n){var r=n(47),o=n(28);e.exports=Object.keys||function(e){return r(e,o)}},function(e,t){e.exports=function(e){if(void 0==e)throw TypeError("Can't call method on "+e);return e}},function(e,t){var n=Math.ceil,r=Math.floor;e.exports=function(e){return isNaN(e=+e)?0:(e>0?r:n)(e)}},function(e,t,n){var r=n(25)("keys"),o=n(27);e.exports=function(e){return r[e]||(r[e]=o(e))}},function(e,t){e.exports={}},function(e,t,n){var r=n(43);e.exports=function(e,t,n){if(r(e),void 0===t)return e;switch(n){case 1:return function(n){return e.call(t,n)};case 2:return function(n,r){return e.call(t,n,r)};case 3:return function(n,r,o){return e.call(t,n,r,o)}}return function(){return e.apply(t,arguments)}}},function(e,t,n){var r=n(12),o=n(3).document,i=r(o)&&r(o.createElement);e.exports=function(e){return i?o.createElement(e):{}}},function(e,t,n){var r=n(22),o=n(15);e.exports=function(e){return r(o(e))}},function(e,t,n){var r=n(23);e.exports=Object("z").propertyIsEnumerable(0)?Object:function(e){return"String"==r(e)?e.split(""):Object(e)}},function(e,t){var n={}.toString;e.exports=function(e){return n.call(e).slice(8,-1)}},function(e,t,n){var r=n(16),o=Math.min;e.exports=function(e){return e>0?o(r(e),9007199254740991):0}},function(e,t,n){var r=n(0),o=n(3),i=o["__core-js_shared__"]||(o["__core-js_shared__"]={});(e.exports=function(e,t){return i[e]||(i[e]=void 0!==t?t:{})})("versions",[]).push({version:r.version,mode:n(26)?"pure":"global",copyright:"© 2019 Denis Pushkarev (zloirock.ru)"})},function(e,t){e.exports=!0},function(e,t){var n=0,r=Math.random();e.exports=function(e){return"Symbol(".concat(void 0===e?"":e,")_",(++n+r).toString(36))}},function(e,t){e.exports="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(",")},function(e,t,n){"use strict";var r=n(53),o=n.n(r),i=n(31),s=n.n(i),a=n(75),c=n(77),u=n(79),l=n(81),f=n(83),d=n(33);t.a={name:"vue-json-pretty",components:{SimpleText:a.a,VueCheckbox:c.a,VueRadio:u.a,BracketsLeft:l.a,BracketsRight:f.a},props:{data:{},deep:{type:Number,default:1/0},showLength:{type:Boolean,default:!1},showDoubleQuotes:{type:Boolean,default:!0},path:{type:String,default:"root"},selectableType:{type:String,default:""},showSelectController:{type:Boolean,default:!1},showLine:{type:Boolean,default:!0},selectOnClickNode:{type:Boolean,default:!0},value:{type:[Array,String],default:function(){return""}},pathSelectable:{type:Function,default:function(){return!0}},highlightMouseoverNode:{type:Boolean,default:!1},highlightSelectedNode:{type:Boolean,default:!0},collapsedOnClickBrackets:{type:Boolean,default:!0},parentData:{},currentDeep:{type:Number,default:1},currentKey:[Number,String]},data:function(){return{visible:this.currentDeep<=this.deep,isMouseover:!1,currentCheckboxVal:!!Array.isArray(this.value)&&this.value.includes(this.path)}},computed:{model:{get:function(){var e="multiple"===this.selectableType?[]:"single"===this.selectableType?"":null;return this.value||e},set:function(e){this.$emit("input",e)}},lastKey:function(){if(Array.isArray(this.parentData))return this.parentData.length-1;if(this.isObject(this.parentData)){var e=s()(this.parentData);return e[e.length-1]}},notLastKey:function(){return this.currentKey!==this.lastKey},selectable:function(){return this.pathSelectable(this.path,this.data)&&(this.isMultiple||this.isSingle)},isMultiple:function(){return"multiple"===this.selectableType},isSingle:function(){return"single"===this.selectableType},isSelected:function(){return this.isMultiple?this.model.includes(this.path):!!this.isSingle&&this.model===this.path},propsError:function(){return!this.selectableType||this.selectOnClickNode||this.showSelectController?"":"When selectableType is not null, selectOnClickNode and showSelectController cannot be false at the same time, because this will cause the selection to fail."}},methods:{handleValueChange:function(e){var t=this;if(!this.isMultiple||"checkbox"!==e&&"tree"!==e){if(this.isSingle&&("radio"===e||"tree"===e)&&this.model!==this.path){var n=this.model,r=this.path;this.model=r,this.$emit("change",r,n)}}else{var i=this.model.findIndex(function(e){return e===t.path}),s=[].concat(o()(this.model));-1!==i?this.model.splice(i,1):this.model.push(this.path),"checkbox"!==e&&(this.currentCheckboxVal=!this.currentCheckboxVal),this.$emit("change",this.model,s)}},handleClick:function(e){e._uid&&e._uid!==this._uid||(e._uid=this._uid,this.$emit("click",this.path,this.data),this.selectable&&this.selectOnClickNode&&this.handleValueChange("tree"))},handleItemClick:function(e,t){this.$emit("click",e,t)},handleItemChange:function(e,t){this.selectable&&this.$emit("change",e,t)},handleMouseover:function(){this.highlightMouseoverNode&&(this.selectable||""===this.selectableType)&&(this.isMouseover=!0)},handleMouseout:function(){this.highlightMouseoverNode&&(this.selectable||""===this.selectableType)&&(this.isMouseover=!1)},isObject:function(e){return"object"===Object(d.a)(e)},keyFormatter:function(e){return this.showDoubleQuotes?'"'+e+'"':e}},errorCaptured:function(){return!1},watch:{deep:function(e){this.visible=this.currentDeep<=e},propsError:{handler:function(e){if(e)throw new Error("[vue-json-pretty] "+e)},immediate:!0}}}},function(e,t,n){var r=n(7).f,o=n(10),i=n(1)("toStringTag");e.exports=function(e,t,n){e&&!o(e=n?e:e.prototype,i)&&r(e,i,{configurable:!0,value:t})}},function(e,t,n){e.exports={default:n(72),__esModule:!0}},function(e,t,n){"use strict";var r=n(33);t.a={props:{showDoubleQuotes:Boolean,parentData:{},data:{},showComma:Boolean,currentKey:[Number,String]},computed:{dataType:function(){return Object(r.a)(this.data)},parentDataType:function(){return Object(r.a)(this.parentData)}},methods:{textFormatter:function(e){var t=e+"";return"string"===this.dataType&&(t='"'+t+'"'),this.showComma&&(t+=","),t}}}},function(e,t,n){"use strict";function r(e){return Object.prototype.toString.call(e).slice(8,-1).toLowerCase()}t.a=r},function(e,t,n){"use strict";t.a={props:{value:{type:Boolean,default:!1}},data:function(){return{focus:!1}},computed:{model:{get:function(){return this.value},set:function(e){this.$emit("input",e)}}}}},function(e,t,n){"use strict";t.a={props:{path:String,value:{type:String,default:""}},data:function(){return{focus:!1}},computed:{currentPath:function(){return this.path},model:{get:function(){return this.value},set:function(e){this.$emit("input",e)}}},methods:{change:function(){this.$emit("change",this.model)}}}},function(e,t,n){"use strict";var r=n(31),o=n.n(r),i=n(37);t.a={mixins:[i.a],props:{showLength:Boolean},methods:{closedBracketsGenerator:function(e){var t=Array.isArray(e)?"[...]":"{...}";return this.bracketsFormatter(t)},lengthGenerator:function(e){return" // "+(Array.isArray(e)?e.length+" items":o()(e).length+" keys")}}}},function(e,t,n){"use strict";t.a={props:{visible:{required:!0,type:Boolean},data:{required:!0},showComma:Boolean,collapsedOnClickBrackets:Boolean},computed:{dataVisible:{get:function(){return this.visible},set:function(e){this.collapsedOnClickBrackets&&this.$emit("update:visible",e)}}},methods:{toggleBrackets:function(){this.dataVisible=!this.dataVisible},bracketsFormatter:function(e){return this.showComma?e+",":e}}}},function(e,t,n){"use strict";var r=n(37);t.a={mixins:[r.a]}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(40),o=n.n(r),i=n(52),s=n(86);n.n(s);t.default=o()({},i.a,{version:"1.6.2"})},function(e,t,n){e.exports={default:n(41),__esModule:!0}},function(e,t,n){n(42),e.exports=n(0).Object.assign},function(e,t,n){var r=n(5);r(r.S+r.F,"Object",{assign:n(46)})},function(e,t){e.exports=function(e){if("function"!=typeof e)throw TypeError(e+" is not a function!");return e}},function(e,t,n){e.exports=!n(4)&&!n(9)(function(){return 7!=Object.defineProperty(n(20)("div"),"a",{get:function(){return 7}}).a})},function(e,t,n){var r=n(12);e.exports=function(e,t){if(!r(e))return e;var n,o;if(t&&"function"==typeof(n=e.toString)&&!r(o=n.call(e)))return o;if("function"==typeof(n=e.valueOf)&&!r(o=n.call(e)))return o;if(!t&&"function"==typeof(n=e.toString)&&!r(o=n.call(e)))return o;throw TypeError("Can't convert object to primitive value")}},function(e,t,n){"use strict";var r=n(4),o=n(14),i=n(50),s=n(51),a=n(11),c=n(22),u=Object.assign;e.exports=!u||n(9)(function(){var e={},t={},n=Symbol(),r="abcdefghijklmnopqrst";return e[n]=7,r.split("").forEach(function(e){t[e]=e}),7!=u({},e)[n]||Object.keys(u({},t)).join("")!=r})?function(e,t){for(var n=a(e),u=arguments.length,l=1,f=i.f,d=s.f;u>l;)for(var p,h=c(arguments[l++]),v=f?o(h).concat(f(h)):o(h),b=v.length,m=0;b>m;)p=v[m++],r&&!d.call(h,p)||(n[p]=h[p]);return n}:u},function(e,t,n){var r=n(10),o=n(21),i=n(48)(!1),s=n(17)("IE_PROTO");e.exports=function(e,t){var n,a=o(e),c=0,u=[];for(n in a)n!=s&&r(a,n)&&u.push(n);for(;t.length>c;)r(a,n=t[c++])&&(~i(u,n)||u.push(n));return u}},function(e,t,n){var r=n(21),o=n(24),i=n(49);e.exports=function(e){return function(t,n,s){var a,c=r(t),u=o(c.length),l=i(s,u);if(e&&n!=n){for(;u>l;)if((a=c[l++])!=a)return!0}else for(;u>l;l++)if((e||l in c)&&c[l]===n)return e||l||0;return!e&&-1}}},function(e,t,n){var r=n(16),o=Math.max,i=Math.min;e.exports=function(e,t){return e=r(e),e<0?o(e+t,0):i(e,t)}},function(e,t){t.f=Object.getOwnPropertySymbols},function(e,t){t.f={}.propertyIsEnumerable},function(e,t,n){"use strict";var r=n(29),o=n(85),i=n(2),s=i(r.a,o.a,!1,null,null,null);t.a=s.exports},function(e,t,n){"use strict";t.__esModule=!0;var r=n(54),o=function(e){return e&&e.__esModule?e:{default:e}}(r);t.default=function(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t=t.length?{value:void 0,done:!0}:(e=r(t,n),this._i+=e.length,{value:e,done:!1})})},function(e,t,n){var r=n(16),o=n(15);e.exports=function(e){return function(t,n){var i,s,a=String(o(t)),c=r(n),u=a.length;return c<0||c>=u?e?"":void 0:(i=a.charCodeAt(c),i<55296||i>56319||c+1===u||(s=a.charCodeAt(c+1))<56320||s>57343?e?a.charAt(c):i:e?a.slice(c,c+2):s-56320+(i-55296<<10)+65536)}}},function(e,t,n){"use strict";var r=n(26),o=n(5),i=n(59),s=n(6),a=n(18),c=n(60),u=n(30),l=n(64),f=n(1)("iterator"),d=!([].keys&&"next"in[].keys()),p=function(){return this};e.exports=function(e,t,n,h,v,b,m){c(n,t,h);var y,g,_,x=function(e){if(!d&&e in C)return C[e];switch(e){case"keys":case"values":return function(){return new n(this,e)}}return function(){return new n(this,e)}},k=t+" Iterator",j="values"==v,w=!1,C=e.prototype,O=C[f]||C["@@iterator"]||v&&C[v],S=O||x(v),A=v?j?x("entries"):S:void 0,M="Array"==t?C.entries||O:O;if(M&&(_=l(M.call(new e)))!==Object.prototype&&_.next&&(u(_,k,!0),r||"function"==typeof _[f]||s(_,f,p)),j&&O&&"values"!==O.name&&(w=!0,S=function(){return O.call(this)}),r&&!m||!d&&!w&&C[f]||s(C,f,S),a[t]=S,a[k]=p,v)if(y={values:j?S:x("values"),keys:b?S:x("keys"),entries:A},m)for(g in y)g in C||i(C,g,y[g]);else o(o.P+o.F*(d||w),t,y);return y}},function(e,t,n){e.exports=n(6)},function(e,t,n){"use strict";var r=n(61),o=n(13),i=n(30),s={};n(6)(s,n(1)("iterator"),function(){return this}),e.exports=function(e,t,n){e.prototype=r(s,{next:o(1,n)}),i(e,t+" Iterator")}},function(e,t,n){var r=n(8),o=n(62),i=n(28),s=n(17)("IE_PROTO"),a=function(){},c=function(){var e,t=n(20)("iframe"),r=i.length;for(t.style.display="none",n(63).appendChild(t),t.src="javascript:",e=t.contentWindow.document,e.open(),e.write(" ================================================ FILE: api-test-v2/index.html ================================================ Api Test

Web SDK Demo 示例源码

{{opt.name}}

提示: {{RunType[runType].prompt}}

运行
================================================ FILE: api-test-v2/js/common/api-list.js ================================================ (function (win, dependencies) { var RongIMLib = win.RongIMLib, RongIMClient = RongIMLib.RongIMClient; var RongIM = dependencies.RongIM, utils = RongIM.Utils, Service = RongIM.Service, config = RongIM.config.im, urlQueryConfig = utils.getUrlQuery(); var MiniUnSupportEventList = [ 'sendRecallMessage', 'deleteRemoteMessages', 'clearRemoteHistoryMessages' ]; var disconnect = { name: '断开链接', event: Service.disconnect, eventName: 'disconnect', desc: '断开链接', doc: 'https://docs.rongcloud.cn/v2/views/im/noui/guide/private/connection/disconnect/web.html', params: [] }; var reconnect = { name: '重新链接', event: Service.reconnect, eventName: 'reconnect', desc: '重新链接', doc: 'https://docs.rongcloud.cn/v3/views/im/noui/guide/private/connection/reconnect/web.html', params: [ { name: '是否嗅探', type: 'boolean', value: true }, { name: '嗅探 url', type: 'string', value: 'https://cdn.ronghub.com/RongIMLib-2.2.6.min.js?d=' + Date.now() }, { name: '嗅探频率', type: 'string', value: '100,1000,3000,3000,3000' } ] }; var changeUser = { name: '切换用户', evnet: utils.noop, eventName: 'logout', desc: '切换用户', doc: 'https://docs.rongcloud.cn/v3/views/im/noui/guide/private/connection/disconnect/web.html#logout', params: [ { name: 'Token', type: 'string', value: '5JQlp5czM31GNl99DOZyI3xpRjANxKgfakOnYLFljI+TMvOF0hGaVtR1n9Qp4baLgKBGsyl3w5j4gAWBbNZ3nOKrvnVo8Ldl' } ] }; var registerMessage = { name: '注册自定义消息', event: Service.registerMessage, eventName: 'registerMessageType', desc: '注册自定义消息', doc: 'https://docs.rongcloud.cn/v3/views/im/noui/guide/private/msgmanage/msgsend/web.html#createcustom', params: [ { name: 'messageType', type: 'string', value: 'PersonMessage' }, { name: 'objectName', type: 'string', value: 's:person' }, { name: '是否计数', type: 'boolean', value: true }, { name: '是否存储', type: 'boolean', value: true }, { name: '属性', type: 'string', value: 'name,age' }, ] }; var getConversationList = { name: '获取会话列表', event: Service.getConversationList, eventName: 'getConversationList', desc: '获取会话列表', doc: 'https://docs.rongcloud.cn/v3/views/im/noui/guide/private/conversation/getall/web.html', params: [ { name: '数量', type: 'number', value: 1000 } ] }; var removeConversation = { name: '删除会话列表', event: Service.removeConversation, eventName: 'removeConversation', desc: '删除会话列表', doc: 'https://docs.rongcloud.cn/v3/views/im/noui/guide/private/conversation/clearall/web.html', params: [ { name: '会话类型', type: 'number', value: 1 }, { name: '对方 id', type: 'string', value: config.targetId } ] }; var getHistoryMessages = { name: '获取历史消息', event: Service.getHistoryMessages, eventName: 'getHistoryMessages', desc: '获取历史消息', doc: 'https://docs.rongcloud.cn/v3/views/im/noui/guide/private/msgmanage/storage/web.html', params: [ { name: '时间戳', type: 'number', value: 0 }, { name: '数量', type: 'number', value: 20 }, { name: '会话类型', type: 'number', value: 1 }, { name: '对方 id', type: 'string', value: config.targetId } ] }; var deleteRemoteMessages = { name: '删除历史消息(按消息)', event: Service.deleteRemoteMessages, eventName: 'deleteRemoteMessages', desc: '按消息删除指定历史消息', doc: 'https://docs.rongcloud.cn/v3/views/im/noui/guide/private/msgmanage/delete/web.html#deletebyid', params: [ { name: '消息 Uid', type: 'string', value: '', event: Service.getLastCacheMsgUId }, { name: '发送时间', type: 'number', value: 0, event: Service.getLastCacheMsgSentTime }, { name: '消息方向', type: 'number', value: 1, event: Service.getLastCacheMsgDirection }, { name: '会话类型', type: 'number', value: 1 }, { name: '对方 id', type: 'string', value: config.targetId } ] }; var clearHistoryMessages = { name: '删除历史消息(按时间)', event: Service.clearHistoryMessages, eventName: 'clearRemoteHistoryMessages', desc: '按时间删除历史消息', doc: 'https://docs.rongcloud.cn/v3/views/im/noui/guide/private/msgmanage/delete/web.html#delete', params: [ { name: '删除时间戳', type: 'number', value: Date.now() }, { name: '会话类型', type: 'number', value: 1 }, { name: '对方 id', type: 'string', value: config.targetId } ] }; var sendTextMessage = { name: '发送文字消息', event: Service.sendTextMessage, eventName: 'sendMessage', desc: '发送文字消息(TextMessage)', doc: 'https://docs.rongcloud.cn/v3/views/im/noui/guide/private/msgmanage/msgsend/web.html#TxtMsg', params: [ { name: '文字内容', type: 'string', value: '我是一条文字消息' }, { name: '会话类型', type: 'number', value: 1 }, { name: '对方 id', type: 'string', value: config.targetId }, { name: '静默消息', type: 'boolean', value: false } ] }; var sendImageMessage = { name: '发送图片消息', event: Service.sendImageMessage, eventName: 'sendMessage', desc: '发送图片消息(ImageMessage)', doc: 'https://docs.rongcloud.cn/v3/views/im/noui/guide/private/msgmanage/msgsend/web.html#ImgTextMsg', params: [ { name: '缩略图', type: 'string', value: utils.getBase64Image() }, { name: '原图 url', type: 'string', value: 'http://rongcloud.cn/images/newVersion/log_wx.png' }, { name: '会话类型', type: 'number', value: 1 }, { name: '对方 id', type: 'string', value: config.targetId }, { name: '静默消息', type: 'boolean', value: false } ] }; var sendFileMessage = { name: '发送文件消息', event: Service.sendFileMessage, eventName: 'sendMessage', desc: '发送文件消息(FileMessage)', doc: 'https://docs.rongcloud.cn/v3/views/im/noui/guide/private/msgmanage/msgsend/web.html#FileMsg', params: [ { name: '文件名', type: 'string', value: 'logo_wx' }, { name: '文件大小', type: 'number', value: 2000000000 }, { name: '文件类型', type: 'string', value: 'png' }, { name: '文件 url', type: 'string', value: 'http://rongcloud.cn/images/newVersion/log_wx.png' }, { name: '会话类型', type: 'number', value: 1 }, { name: '对方 id', type: 'string', value: config.targetId }, { name: '静默消息', type: 'boolean', value: false } ] }; var sendVoiceMessage = { name: '发送语音消息', event: Service.sendVoiceMessage, eventName: 'sendMessage', desc: '发送语音消息(HQVoiceMessage)', doc: 'https://docs.rongcloud.cn/v3/views/im/noui/guide/private/msgmanage/msgsend/web.html#HQVCMsg', params: [ { name: '语音 url', type: 'string', value: 'https://rongcloud-audio.cn.ronghub.com/audio_amr__RC-2020-03-17_42_1584413950049.aac?e=1599965952&token=CddrKW5AbOMQaDRwc3ReDNvo3-sL_SO1fSUBKV3H:CDngyWj7ZApNmAfoecng7L_3SaU=' }, { name: '语音时长', type: 'number', value: 7 }, { name: '会话类型', type: 'number', value: 1 }, { name: '对方 id', type: 'string', value: config.targetId }, { name: '静默消息', type: 'boolean', value: false } ] }; var sendRecallMessage = { name: '发送撤回消息', event: Service.sendRecallMessage, eventName: 'sendRecallMessage', desc: '发送撤回消息', doc: 'https://docs.rongcloud.cn/v3/views/im/noui/guide/private/msgmanage/msgrecall/web.html', params: [ { name: '消息 Uid', type: 'string', value: '', event: Service.getLastCacheMsgUId }, { name: '发送时间', type: 'number', value: 0, event: Service.getLastCacheMsgSentTime }, { name: '会话类型', type: 'number', value: 1 }, { name: '对方 id', type: 'string', value: config.targetId }, { name: '静默消息', type: 'boolean', value: false } ] }; var sendAtMessage = { name: '发送 @ 消息', event: Service.sendAtMessage, eventName: 'sendMessage', desc: '发送 @ 消息', doc: 'https://docs.rongcloud.cn/v3/views/im/noui/guide/group/msgmanage/msgsend/web.html#at', params: [ { name: '文字内容', type: 'string', value: '我是一条文本消息, 我 @ 了其他人' }, { name: '@ 对象 id', type: 'string', value: config.targetId }, { name: '会话类型', type: 'number', value: 3 }, { name: '群组 id', type: 'string', value: config.targetId }, { name: '静默消息', type: 'boolean', value: false } ] }; var sendRegisterMessage = { name: '发送自定义消息', event: Service.sendRegisterMessage, eventName: 'sendMessage', desc: '发送自定义消息(RegisterMessage)', doc: 'https://docs.rongcloud.cn/v3/views/im/noui/guide/group/msgmanage/msgsend/web.html#send', params: [ { name: '消息类型', type: 'string', value: 'PersonMessage' }, { name: '属性值', type: 'string', value: 'name,age' }, { name: '会话类型', type: 'number', value: 1 }, { name: '对方 id', type: 'string', value: config.targetId }, { name: '静默消息', type: 'boolean', value: false } ] }; var sendLocationMessage = { name: '发送位置消息', event: Service.sendLocationMessage, eventName: 'sendMessage', desc: '发送位置消息(sendLocationMessage)', doc: 'https://docs.rongcloud.cn/v3/views/im/noui/guide/group/msgmanage/msgsend/web.html#LBSMsg', params: [ { name: '位置缩略图', type: 'string', value: '/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDABsSFBcUERsXFhceHBsgKE' }, { name: '维度', type: 'number', value: 40.0317727 }, { name: '经度', type: 'number', value: 116.4175057 }, { name: '位置信息', type: 'string', value: '北苑路北辰·泰岳' }, { name: '会话类型', type: 'number', value: 1 }, { name: '对方 id', type: 'string', value: config.targetId }, { name: '静默消息', type: 'boolean', value: false } ] }; var sendRichContentMessage = { name: '发送富文本消息', event: Service.sendRichContentMessage, eventName: 'sendMessage', desc: '发送富文本(图文)消息(sendRichContentMessage)', doc: 'https://docs.rongcloud.cn/v3/views/im/noui/guide/group/msgmanage/msgsend/web.html#ImgTextMsg', params: [ { name: '图文标题', type: 'string', value: '标题: 融云' }, { name: '图文内容', type: 'string', value: '为用户提供 IM 即时通讯和音视频通讯云服务' }, { name: '图片信息', type: 'string', value: 'https://www.rongcloud.cn/images/newVersion/log_wx.png' }, { name: '图文链接', type: 'string', value: 'https://developer.rongcloud.cn' }, { name: '会话类型', type: 'number', value: 1 }, { name: '对方 id', type: 'string', value: config.targetId }, { name: '静默消息', type: 'boolean', value: false } ] }; var sendTypingStatusMessage = { name: '发送正在输入状态消息', event: Service.sendTypingStatusMessage, eventName: 'sendMessage', desc: '发送正在输入状态消息(sendTypingStatusMessage)', doc: 'https://docs.rongcloud.cn/v3/views/im/noui/guide/group/msgmanage/msgsend/web.html#TypSts', params: [ { name: '会话类型', type: 'number', value: 1 }, { name: '对方 id', type: 'string', value: config.targetId }, { name: '消息 ObjectName', type: 'string', value: 'RC:TxtMsg' }, { name: '携带信息', type: 'string', value: '携带信息' }, { name: '静默消息', type: 'boolean', value: false } ] }; var getUnreadCount = { name: '获取会话未读数', event: Service.getUnreadCount, eventName: 'getUnreadCount', desc: '获取指定会话未读数', doc: 'https://docs.rongcloud.cn/v3/views/im/noui/guide/group/conversation/unreadcount/web.html#one', params: [ { name: '会话类型', type: 'number', value: 1 }, { name: '对方 id', type: 'string', value: config.targetId } ] }; var getTotalUnreadCount = { name: '获取会话未读数总数', event: Service.getTotalUnreadCount, eventName: 'getTotalUnreadCount', desc: '获取会话未读总数', doc: 'https://docs.rongcloud.cn/v3/views/im/noui/guide/group/conversation/unreadcount/web.html', params: [ ] }; var clearUnreadCount = { name: '清除会话未读数', event: Service.clearUnreadCount, eventName: 'clearUnreadCount', desc: '清除指定会话未读数', doc: 'https://docs.rongcloud.cn/v3/views/im/noui/guide/group/conversation/unreadcount/web.html#clear', params: [ { name: '会话类型', type: 'number', value: 1 }, { name: '对方 id', type: 'string', value: config.targetId } ] }; var joinChatRoom = { name: '加入聊天室', event: Service.joinChatRoom, eventName: 'joinChatRoom', desc: '加入指定聊天室, 并拉取消息', doc: 'https://docs.rongcloud.cn/im/imlib/web/chatroom/#join', params: [ { name: '聊天室 id', type: 'string', value: config.targetId }, { name: '拉取消息数', type: 'number', value: 2 } ] }; var quitChatRoom = { name: '退出聊天室', event: Service.quitChatRoom, eventName: 'quitChatRoom', desc: '退出聊天室', doc: 'https://docs.rongcloud.cn/im/imlib/web/chatroom/#quit', params: [ { name: '聊天室 id', type: 'string', value: config.targetId } ] }; var getChatRoomInfo = { name: '获取聊天室信息', event: Service.getChatRoomInfo, eventName: 'getChatRoomInfo', desc: '获取聊天室信息', doc: 'https://docs.rongcloud.cn/im/imlib/web/chatroom/#get', params: [ { name: '聊天室 id', type: 'string', value: config.targetId }, { name: '获取人数', type: 'number', value: 20 }, { name: '排序方式', type: 'number', value: 1 } ] }; var setChatroomEntry = { name: '设置聊天室属性', event: Service.setChatroomEntry, eventName: 'setChatroomEntry', desc: '设置聊天室自定义属性', doc: 'https://docs.rongcloud.cn/im/imlib/web/chatroom/#_1', params: [ { name: '属性 key', type: 'string', value: 'chrmKey1' }, { name: '属性 value', type: 'string', value: '我是一个聊天室 value' }, { name: '是否退出清除', type: 'boolean', value: true }, { name: '是否发送消息', type: 'boolean', value: true }, { name: '附加信息', type: 'string', value: '我是消息中的附加信息' }, { name: '聊天室 id', type: 'string', value: config.targetId } ] }; var forceSetChatroomEntry = { name: '设置聊天室属性(强制)', event: Service.forceSetChatroomEntry, eventName: 'forceSetChatroomEntry', desc: '强制设置聊天室自定义属性', doc: 'https://docs.rongcloud.cn/im/imlib/web/chatroom/#_2', params: [ { name: '属性 key', type: 'string', value: 'chrmKey2' }, { name: '属性 value', type: 'string', value: '我是一个聊天室 value' }, { name: '是否退出清除', type: 'boolean', value: true }, { name: '是否发送消息', type: 'boolean', value: true }, { name: '附加信息', type: 'string', value: '我是消息中的附加信息' }, { name: '聊天室 id', type: 'string', value: config.targetId } ] }; var removeChatroomEntry = { name: '删除聊天室属性', event: Service.removeChatroomEntry, eventName: 'removeChatroomEntry', desc: '删除聊天室自定义属性', doc: 'https://docs.rongcloud.cn/im/imlib/web/chatroom/#_3', params: [ { name: '属性 key', type: 'string', value: 'chrmKey1' }, { name: '是否发送消息', type: 'boolean', value: true }, { name: '附加信息', type: 'string', value: '我是消息中的附加信息' }, { name: '聊天室 id', type: 'string', value: config.targetId } ] }; var forceRemoveChatroomEntry = { name: '删除聊天室属性(强制)', event: Service.forceRemoveChatroomEntry, eventName: 'forceRemoveChatroomEntry', desc: '强制删除聊天室自定义属性', doc: 'https://docs.rongcloud.cn/im/imlib/web/chatroom/#_4', params: [ { name: '属性 key', type: 'string', value: 'chrmKey2' }, { name: '是否发送消息', type: 'boolean', value: true }, { name: '附加信息', type: 'string', value: '我是消息中的附加信息' }, { name: '聊天室 id', type: 'string', value: config.targetId } ] }; var getChatroomEntry = { name: '获取聊天室属性', event: Service.getChatroomEntry, eventName: 'getChatroomEntry', desc: '获取指定聊天室自定义属性', doc: 'https://docs.rongcloud.cn/im/imlib/web/chatroom/#_5', params: [ { name: '属性 key', type: 'string', value: 'chrmKey1' }, { name: '聊天室 id', type: 'string', value: config.targetId } ] }; var getAllChatroomEntries = { name: '获取聊天室属性(所有)', event: Service.getAllChatroomEntries, eventName: 'getAllChatroomEntries', desc: '获取所有聊天室自定义属性', doc: 'https://docs.rongcloud.cn/im/imlib/web/chatroom/#_6', params: [ { name: '聊天室 id', type: 'string', value: config.targetId } ] }; var sendChatroomMessage = { name: '发送聊天室消息', event: Service.sendChatroomMessage, eventName: 'sendMessage', desc: '发送聊天室消息, 以文本消息为例(TextMessage)', doc: 'https://docs.rongcloud.cn/im/imlib/web/message-send/#example', params: [ { name: '文字内容', type: 'string', value: '我是一条聊天室的文字消息' }, { name: '会话类型', type: 'number', value: 4 }, { name: '聊天室 id', type: 'string', value: config.targetId } ] }; var setConversationStatus = { name: '设置会话状态', event: Service.setConversationStatus, eventName: 'setConversationStatus', desc: '设置会话状态', doc: 'https://docs.rongcloud.cn/v3/views/im/noui/guide/private/conversation/notify/web.html', params: [ { name: '免打扰', type: 'number', value: 1 }, { name: '置顶', type: 'boolean', value: true }, { name: '会话类型', type: 'number', value: 1 }, { name: '对方 id', type: 'string', value: config.targetId } ] }; win.RongIM = win.RongIM || {}; var DefailtReadyApiQueue = [ [disconnect, reconnect], [registerMessage], [getConversationList, removeConversation, getUnreadCount, getTotalUnreadCount, clearUnreadCount, setConversationStatus], [sendTextMessage, sendImageMessage, sendRecallMessage, sendFileMessage, sendVoiceMessage, sendRegisterMessage, sendAtMessage, sendLocationMessage, sendRichContentMessage, sendTypingStatusMessage], [getHistoryMessages, deleteRemoteMessages, clearHistoryMessages], [joinChatRoom, getChatRoomInfo, sendChatroomMessage], [setChatroomEntry, getChatroomEntry, forceSetChatroomEntry, getAllChatroomEntries, removeChatroomEntry, forceRemoveChatroomEntry], [quitChatRoom] ]; urlQueryConfig.isMini && utils.forEach(DefailtReadyApiQueue, function (list, i) { utils.forEach(list, function (item, j) { if (MiniUnSupportEventList.indexOf(item.eventName) !== -1) { list.splice(j, 1); } }, { isReverse: true }) }); win.RongIM.DefailtReadyApiQueue = DefailtReadyApiQueue; win.RongIM.ApiList = [ getConversationList ]; window.RongIM.Api = { changeUser: changeUser } })(window, { RongIM: RongIM }); ================================================ FILE: api-test-v2/js/common/service.js ================================================ (function(win) { var RongIMLib = win.RongIMLib, RongIM = win.RongIM, RongIMClient = RongIMLib.RongIMClient, utils = RongIM.Utils; var sendMsgTimeout = RongIM.config.isDebug ? 300 : 0; var selfUserId; // 缓存消息, 用作撤回、删除等操作的参数 var CacheMsg = { eventEmitter: new utils.EventEmitter(), _list: [], set: function (msg) { this._list.push(msg); this.eventEmitter.emit('msgChanged'); }, remove: function (msg) { var list = this._list; utils.forEach(list, function(child, index) { if (child.messageUId === msg.messageUId) { list.splice(index, 1); } }, { isReverse: true }); this.eventEmitter.emit('msgChanged'); }, getLast: function () { var list = this._list, length = list.length; var msg = {}; if (length) { msg = list[length - 1]; } return msg; } }; /** * 初始化以及链接 * @param {object} config * @param {string} config.appkey 融云颁发的 appkey * @param {string} config.token 融云颁发的 token(代表某一个用户) * @param {Object} watcher * @param {Object} watcher.status 监听链接状态的变化 * @param {Object} watcher.message 监听消息的接收 */ function init(config, watcher) { watcher = watcher || {}; return utils.defered(function(resolve, reject) { var appkey = config.appkey; var token = config.token; config = utils.clearUndefKey(config); config = utils.copy(config); // config.cmpUrl = 'wsap-cn.ronghub.com'; /* 初始化 文档: https://docs.rongcloud.cn/im/imlib/web/init/ */ RongIMClient.init(appkey, null, config); RongIMClient.setConnectionStatusListener({ onChanged: function (status) { // 不处理的状态码 var unHandleStatus = []; if (unHandleStatus.indexOf(status) === -1) { watcher.status(status); } } }); RongIMClient.setOnReceiveMessageListener({ onReceived: watcher.message }); RongIMClient.setConversationStatusListener && RongIMClient.setConversationStatusListener({ onChanged: watcher.conversationStatus }); /* 链接 文档: https://docs.rongcloud.cn/im/imlib/web/connect/ */ RongIMClient.connect(token, { onSuccess: function (userId) { selfUserId = userId; resolve(userId); }, onTokenIncorrect: function () { reject('Token 错误'); }, onError: reject }); }); } /** * 断开链接 * 文档: https://docs.rongcloud.cn/im/imlib/web/connect/#disconnect */ function disconnect() { return utils.defered(function (resolve) { RongIMClient.getInstance().disconnect(); resolve(); }); } function changeUser(config, watcher) { RongIMClient.getInstance().clearCache(); RongIMClient.getInstance().logout(); return init(config, watcher); } /** * 重新链接 * 文档: https://docs.rongcloud.cn/im/imlib/web/connect/#reconnect */ function reconnect(isAuto, url, rate) { rate = rate.split(','); utils.forEach(rate, function (rate, index) { rate[index] = Number(rate); }); var config = { auto: isAuto, url: url, rate: rate }; return utils.defered(function (resolve, reject) { var callback = { onSuccess: resolve, onTokenIncorrect: reject, onError: reject // 注: 此处因网络还不可用导致重连失败后, 可调用 reconnect(config) 继续重连 }; RongIMClient.reconnect(callback, config); }); } /** * 获取会话列表 * 文档: https://docs.rongcloud.cn/im/imlib/web/conversation/get-list/ * * @param {number} count 获取会话的数量 */ function getConversationList(count) { return utils.defered(function(resolve, reject) { RongIMClient.getInstance().getConversationList({ onSuccess: resolve, onError: reject }, null, count); }); } /** * 删除会话列表 * 文档: https://docs.rongcloud.cn/im/imlib/web/conversation/remove/ */ function removeConversation(conversationType, targetId) { conversationType = Number(conversationType); return utils.defered(function (resolve, reject) { RongIMClient.getInstance().removeConversation(conversationType, targetId, { onSuccess: resolve, onError: reject }); }); } /** * 获取历史消息 * 文档: https://docs.rongcloud.cn/im/imlib/web/message-list/get-list/ * * @param {number} timestrap 时间戳 * @param {number} count 数量 */ function getHistoryMessages(timestrap, count, conversationType, targetId) { conversationType = Number(conversationType); return utils.defered(function (resolve, reject) { RongIMClient.getInstance().getHistoryMessages(conversationType, targetId, timestrap, count, { onSuccess: resolve, onError: reject }); }); } /** * 按时间删除历史消息 * 文档: https://docs.rongcloud.cn/im/imlib/web/message-list/remove-list/#_1 * * @param {number} timestrap 时间戳 */ function clearHistoryMessages(timestamp, conversationType, targetId) { conversationType = Number(conversationType); var params = { conversationType: conversationType, targetId: targetId, timestamp: timestamp }; return utils.defered(function (resolve, reject) { RongIMClient.getInstance().clearRemoteHistoryMessages(params, { onSuccess: resolve, onError: reject }); }); } /** * 按消息删除历史消息 * @param {string} messageUId 消息在 server 的唯一标识 * @param {number} sentTime 消息发送时间 * @param {number} messageDirection 消息方向 */ function deleteRemoteMessages(messageUId, sentTime, messageDirection, conversationType, targetId) { conversationType = Number(conversationType); if (!messageUId || !sentTime) { return utils.Defer.reject('请先发送消息, 再进行删除历史消息操作'); } var deleteMsg = { messageUId: messageUId, sentTime: sentTime, messageDirection: messageDirection }; var messages = [ deleteMsg ]; return utils.defered(function (resolve, reject) { RongIMClient.getInstance().deleteRemoteMessages(conversationType, targetId, messages, { onSuccess: resolve, onError: reject }); }); } /** * 获取指定会话未读数 * 文档: https://docs.rongcloud.cn/im/imlib/web/conversation/unreadcount/#get-one * * @param {number} conversationType 会话类型 * @param {string} targetId 目标 id (对方 id、群组 id、聊天室 id 等) */ function getUnreadCount(conversationType, targetId) { conversationType = Number(conversationType); return utils.defered(function (resolve, reject) { RongIMClient.getInstance().getUnreadCount(conversationType, targetId, { onSuccess: resolve, onError: reject }); }); } /** * 获取所有会话未读数 * 文档: https://docs.rongcloud.cn/im/imlib/web/conversation/unreadcount/#get-all */ function getTotalUnreadCount() { return utils.defered(function (resolve, reject) { RongIMClient.getInstance().getTotalUnreadCount({ onSuccess: resolve, onError: reject }); }); } /** * 清除指定会话未读数 * 文档: https://docs.rongcloud.cn/im/imlib/web/conversation/unreadcount/#clear */ function clearUnreadCount(conversationType, targetId) { conversationType = Number(conversationType); return utils.defered(function (resolve, reject) { RongIMClient.getInstance().clearUnreadCount(conversationType, targetId, { onSuccess: resolve, onError: reject }); }); } function sendMessage(conversationType, targetId, msg, disableNotification) { conversationType = Number(conversationType); return utils.defered(function (resolve, reject) { let callbacks = { onSuccess: function (message) { CacheMsg.set(message); resolve(message); }, onError: reject }; let config = { disableNotification: disableNotification }; setTimeout(function() { // 开发者忽略 setTimeout RongIMClient.getInstance().sendMessage(conversationType, targetId, msg, callbacks, null, null, null, null, config); }, sendMsgTimeout); }); } /** * 发送文本消息 * 文档: https://docs.rongcloud.cn/im/imlib/web/message-send/#text * 注意事项: * 1: 单条消息整体不得大于128K * 2: conversationType 类型是 number,targetId 类型是 string * * @param {string} text 文字内容 * @param {number} conversationType 会话类型 * @param {string} targetId 目标 id (对方 id、群组 id、聊天室 id 等) */ function sendTextMessage(text, conversationType, targetId, disableNotification) { var content = { content: text // 文本内容 }; var msg = new RongIMLib.TextMessage(content); return sendMessage(conversationType, targetId, msg, disableNotification); } /** * 发送图片消息 * 文档: https://docs.rongcloud.cn/im/imlib/web/message-send/#image * 注意事项: * 1. 略缩图(content 字段)必须是 base64 字符串, 类型必须为 jpg * 2. base64 略缩图必须不带前缀 * 3. base64 字符串大小不可超过 100 k * 4. 可通过 FileReader 或者 canvas 对图片进行压缩, 生成压缩后的 base64 字符串 * imageUri 为上传至服务器的原图 url, 用来展示高清图片 * 上传图片需开发者实现. 可参考上传插件: https://docs.rongcloud.cn/im/imlib/web/plugin/upload * * @param {string} base64 图片 base64 缩略图 * @param {string} imageUri 图片上传后的 url */ function sendImageMessage(base64, imageUri, conversationType, targetId, disableNotification) { var content = { content: base64, // 压缩后的 base64 略缩图, 用来快速展示图片 imageUri: imageUri // 上传到服务器的 url. 用来展示高清图片 }; var msg = new RongIMLib.ImageMessage(content); return sendMessage(conversationType, targetId, msg, disableNotification); } /** * 发送文件消息 * 文档:https://docs.rongcloud.cn/im/imlib/web/message-send/#file * * @param {string} fileName 文件名 * @param {string} fileSize 文件大小 * @param {string} fileType 文件类型 * @param {string} fileUrl 文件上传后的 url */ function sendFileMessage(fileName, fileSize, fileType, fileUrl, conversationType, targetId, disableNotification) { var content = { name: fileName, // 文件名 size: fileSize, // 文件大小 type: fileType, // 文件类型 fileUrl: fileUrl // 文件地址 }; var msg = new RongIMLib.FileMessage(content); return sendMessage(conversationType, targetId, msg, disableNotification); } /** * 高质量语音消息: https://docs.rongcloud.cn/im/introduction/message_structure/#hqvoice_message * 注意事项: * 融云不提供声音录制的方法. remoteUrl 的生成需开发者实现 * * @param {string} remoteUrl 语音上传后的 url * @param {number} duration 语音时长 */ function sendVoiceMessage(remoteUrl, duration, conversationType, targetId, disableNotification) { var content = { remoteUrl: remoteUrl, // 音频 url, 建议格式: aac duration: duration // 音频时长 }; var msg = new RongIMLib.HQVoiceMessage(content); return sendMessage(conversationType, targetId, msg, disableNotification); } /** * 撤回消息: https://docs.rongcloud.cn/im/imlib/web/message-send/#recall * 注意事项: * 消息撤回操作服务器端没有撤回时间范围的限制,由客户端决定 * * @param {string} messageUId 撤回的消息 Uid * @param {number} sentTime 撤回的消息 sentTime */ function sendRecallMessage(messageUId, sentTime, conversationType, targetId, disableNotification) { if (!messageUId || !sentTime) { return utils.Defer.reject('请先发送消息, 再进行撤回操作'); } var recallMessage = { messageUId: messageUId, sentTime: sentTime, senderUserId: selfUserId, conversationType: conversationType, targetId: targetId }; var config = { disableNotification } return utils.defered(function (resolve, reject) { var callbacks = { onSuccess: resolve, onError: reject } RongIMClient.getInstance().sendRecallMessage(recallMessage, callbacks, config); }) } /** * 发送 @ 消息(此处以文本消息举例) * 文档: https://docs.rongcloud.cn/im/imlib/web/message-send/#example * * @param {string} text 文字内容 * @param {string} methiondId @ 对象的 id */ function sendAtMessage(text, methiondId, conversationType, targetId, disableNotification) { conversationType = Number(conversationType); var isMentioned = true; var mentioneds = new RongIMLib.MentionedInfo(); mentioneds.type = RongIMLib.MentionedType.PART; mentioneds.userIdList = [methiondId]; // @ 人 id 列表 var content = { content: text, mentionedInfo: mentioneds }; var msg = new RongIMLib.TextMessage(content); let config = { disableNotification: disableNotification }; return utils.defered(function (resolve, reject) { RongIMClient.getInstance().sendMessage(conversationType, targetId, msg, { onSuccess: resolve, onError: reject }, isMentioned, null, null, null, config); }); } /** * 注册自定义消息 * 文档: https://docs.rongcloud.cn/im/imlib/web/message-send/#custom * * @param {string} messageName 注册消息的 Web 端类型名 * @param {string} objectName 注册消息的唯一名称. 注: 此名称需多端一致 * @param {boolean} isCounted 是否计数 * @param {boolean} isPersited 是否存储 * @param {Array} props 消息包含的字段集合 */ function registerMessage(messageName, objectName, isCounted, isPersited, props) { var mesasgeTag = new RongIMLib.MessageTag(isCounted, isPersited); //true true 保存且计数,false false 不保存不计数。 props = props.split(','); // 将字符串截取为数组. 此处为 Demo 逻辑, 与融云无关 RongIMClient.registerMessageType(messageName, objectName, mesasgeTag, props); return utils.Defer.resolve(); } /** * 发送自定义消息 * 文档: https://docs.rongcloud.cn/im/imlib/web/message-send/#custom * * @param {string} messageType 注册消息的 Web 端类型名 * @param {*} props 消息包含的字段集合 */ function sendRegisterMessage(messageType, props, conversationType, targetId, disableNotification) { var content = props.split(','); var msg = new RongIMClient.RegisterMessage[messageType](content); return sendMessage(conversationType, targetId, msg, disableNotification); } /** * 发送位置消息 * 文档: https://docs.rongcloud.cn/im/imlib/web/message-send/#location * 注意事项: * 1. 缩略图必须是base64码的jpg图, 而且不带前缀"data:image/jpeg;base64,", 不得超过100K * 2. 需要开发者做显示效果, 一般显示逻辑: 图片加链接, 传入经纬度并跳转进入地图网站 * * @param {string} base64 位置缩略图 * @param {number} latitude 维度 * @param {number} longitude 经度 * @param {string} poi 位置信息 */ function sendLocationMessage(base64, latitude, longitude, poi, conversationType, targetId, disableNotification) { var msg = new RongIMLib.LocationMessage({ latitude: latitude, longitude: longitude, poi: poi, content: base64 }); return sendMessage(conversationType, targetId, msg, disableNotification); } /** * 发送富文本(图文)消息 * 文档: https://docs.rongcloud.cn/im/imlib/web/message-send/#rich-content * * @param {string} title 图文标题 * @param {number} content 图文内容 * @param {number} imageUri 显示图片的 url(图片信息) * @param {string} url 点击图文后打开的 url */ function sendRichContentMessage(title, content, imageUri, url, conversationType, targetId, disableNotification) { var msg = new RongIMLib.RichContentMessage({ title: title, content: content, imageUri: imageUri, url: url }); return sendMessage(conversationType, targetId, msg, disableNotification); } /** * 发送正在输入状态消息 * @param {number} conversationType * @param {string} targetId * @param {string} data * @param {string} typingContentType */ function sendTypingStatusMessage(conversationType, targetId, typingContentType, data, disableNotification) { var msg = new RongIMLib.TypingStatusMessage({ typingContentType: typingContentType, data: data }); return sendMessage(conversationType, targetId, msg, disableNotification); } /** * 加入聊天室 * 文档: https://docs.rongcloud.cn/im/imlib/web/chatroom/#join * * @param {string} chatRoomId 聊天室 id * @param {number} count 拉取消息数量 */ function joinChatRoom(chatRoomId, count) { return utils.defered(function (resolve, reject) { RongIMClient.getInstance().joinChatRoom(chatRoomId, count, { onSuccess: resolve, onError: reject }); }); } /** * 退出聊天室 * 文档: https://docs.rongcloud.cn/im/imlib/web/chatroom/#quit * * @param {string} chatRoomId 聊天室 id */ function quitChatRoom(chatRoomId) { return utils.defered(function (resolve, reject) { RongIMClient.getInstance().quitChatRoom(chatRoomId, { onSuccess: resolve, onError: reject }); }); } /** * 获取聊天室信息 * 文档: https://docs.rongcloud.cn/im/imlib/web/chatroom/#get * * @param {string} chatRoomId 聊天室 id * @param {string} count 获取人数 * @param {string} order 排序方式 */ function getChatRoomInfo(chatRoomId, count, order) { return utils.defered(function (resolve, reject) { RongIMClient.getInstance().getChatRoomInfo(chatRoomId, count, order, { onSuccess: resolve, onError: reject }); }); } /** * 发送聊天室消息(以文本消息为例) * 文档: https://docs.rongcloud.cn/im/imlib/web/message-send/#text * * @param {string} text 文字内容 */ function sendChatroomMessage(text, conversationType, targetId) { var content = { content: text // 文本内容 }; var msg = new RongIMLib.TextMessage(content); return sendMessage(conversationType, targetId, msg); } function setChatroomEntry(key, value, isAutoDelete, isSendNotification, extra, chatRoomId) { var entry = { key: key, value: value, notificationExtra: extra, isAutoDelete: isAutoDelete, isSendNotification: isSendNotification }; return utils.defered(function (resolve, reject) { RongIMClient.getInstance().setChatroomEntry(chatRoomId, entry, { onSuccess: resolve, onError: reject }); }); } function forceSetChatroomEntry(key, value, isAutoDelete, isSendNotification, extra, chatRoomId) { var entry = { key: key, value: value, notificationExtra: extra, isAutoDelete: isAutoDelete, isSendNotification: isSendNotification }; return utils.defered(function (resolve, reject) { RongIMClient.getInstance().forceSetChatroomEntry(chatRoomId, entry, { onSuccess: resolve, onError: reject }); }); } function removeChatroomEntry(key, isSendNotification, extra, chatRoomId) { var entry = { key: key, notificationExtra: extra, isSendNotification: isSendNotification }; return utils.defered(function (resolve, reject) { RongIMClient.getInstance().removeChatroomEntry(chatRoomId, entry, { onSuccess: resolve, onError: reject }); }); } function forceRemoveChatroomEntry(key, isSendNotification, extra, chatRoomId) { var entry = { key: key, notificationExtra: extra, isSendNotification: isSendNotification }; return utils.defered(function (resolve, reject) { RongIMClient.getInstance().forceRemoveChatroomEntry(chatRoomId, entry, { onSuccess: resolve, onError: reject }); }); } function getChatroomEntry(key, chatRoomId) { return utils.defered(function (resolve, reject) { RongIMClient.getInstance().getChatroomEntry(chatRoomId, key, { onSuccess: resolve, onError: reject }); }); } function getAllChatroomEntries(chatRoomId) { return utils.defered(function (resolve, reject) { RongIMClient.getInstance().getAllChatroomEntries(chatRoomId, { onSuccess: resolve, onError: reject }); }); } function setConversationStatus(notificationStatus, isTop, conversationType, targetId) { return utils.defered(function (resolve, reject) { RongIMClient.getInstance().setConversationStatus(conversationType, targetId, { notificationStatus: notificationStatus, isTop: isTop }, { onSuccess: resolve, onError: reject }); }); } function getLastCacheMsgUId() { return CacheMsg.getLast().messageUId; } function getLastCacheMsgSentTime() { return CacheMsg.getLast().sentTime; } function getLastCacheMsgDirection() { return CacheMsg.getLast().messageDirection; } win.RongIM = win.RongIM || {}; win.RongIM.Service = { init: init, disconnect: disconnect, reconnect: reconnect, registerMessage: registerMessage, sendRegisterMessage: sendRegisterMessage, getConversationList: getConversationList, removeConversation: removeConversation, getHistoryMessages: getHistoryMessages, clearHistoryMessages: clearHistoryMessages, deleteRemoteMessages: deleteRemoteMessages, sendTextMessage: sendTextMessage, sendImageMessage: sendImageMessage, sendFileMessage: sendFileMessage, sendVoiceMessage: sendVoiceMessage, sendAtMessage: sendAtMessage, sendLocationMessage: sendLocationMessage, sendRichContentMessage: sendRichContentMessage, sendRecallMessage: sendRecallMessage, sendTypingStatusMessage: sendTypingStatusMessage, getUnreadCount: getUnreadCount, getTotalUnreadCount: getTotalUnreadCount, clearUnreadCount: clearUnreadCount, joinChatRoom: joinChatRoom, quitChatRoom: quitChatRoom, getChatRoomInfo: getChatRoomInfo, sendChatroomMessage: sendChatroomMessage, setChatroomEntry: setChatroomEntry, forceSetChatroomEntry: forceSetChatroomEntry, removeChatroomEntry: removeChatroomEntry, forceRemoveChatroomEntry: forceRemoveChatroomEntry, getChatroomEntry: getChatroomEntry, getAllChatroomEntries: getAllChatroomEntries, getLastCacheMsgSentTime: getLastCacheMsgSentTime, getLastCacheMsgUId: getLastCacheMsgUId, getLastCacheMsgDirection: getLastCacheMsgDirection, setConversationStatus: setConversationStatus, msgEmitter: CacheMsg.eventEmitter, changeUser: changeUser }; })(window); ================================================ FILE: api-test-v2/js/common/utils.js ================================================ (function (win) { var Defer = win.Promise || ES6Promise; var Vue = win.Vue; var TypeColor = { FAILED: '#ed4014', MSG: '#2db7f5', STATUS: '#ff9900' }; var ConversationName = { 1: '单聊', 3: '群聊', 4: '聊天室', 5: '客服', 6: '系统', 7: '公众号', 8: '公众号' }; var StatusName = { 0: '已连接', 1: '正在链接', 2: '主动断开链接', 3: '网络不可用', 4: '链接关闭', 6: '其他设备登录, 被踢', 7: 'Socket 不可用', 8: 'Socket 错误', 12: '安全域名错误', 20: 'AppKey 错误', 201: '正在请求 Navi', 202: '请求 Navi 成功', 203: '请求 Navi 错误', 204: '请求 Navi 超时' }; var SuccessStatus = [0, 1, 2, 4, 201, 202, 203, 204]; var noop = function () {}; function isObject(obj) { return Object.prototype.toString.call(obj) === '[object Object]'; } function isArray(arr) { return Object.prototype.toString.call(arr) === '[object Array]'; } function isNodeList(arr) { return Object.prototype.toString.call(arr) === '[object NodeList]' || Object.prototype.toString.call(arr) === '[object HTMLCollection]'; } function isFunction(arr) { return Object.prototype.toString.call(arr) === '[object Function]'; } function isString(str) { return Object.prototype.toString.call(str) === '[object String]'; } function isBoolean(str) { return Object.prototype.toString.call(str) === '[object Boolean]'; } function isUndefined(str) { return Object.prototype.toString.call(str) === '[object Undefined]'; } function isNull(str) { return Object.prototype.toString.call(str) === '[object Null]'; } function isNumber(str) { return Object.prototype.toString.call(str) === '[object Number]'; } function defered(callback) { return new Defer(callback); } function tplEngine(temp, data, regexp) { var replaceAction = function (object) { return temp.replace(regexp || (/{([^}]+)}/g), function (match, name) { if (match.charAt(0) === '\\') return match.slice(1); return (object[name] !== undefined) ? object[name] : '{' + name + '}'; }); }; if (!(Object.prototype.toString.call(data) === '[object Array]')) data = [data]; var ret = []; for (var i = 0, j = data.length; i < j; i++) { ret.push(replaceAction(data[i])); } return ret.join(''); } function forEach(obj, callback, options) { options = options || {}; callback = callback || noop; var isReverse = options.isReverse; var loopObj = function() { for (var key in obj) { callback(obj[key], key, obj); } }; var loopArr = function() { if (isReverse) { for (var i = obj.length - 1; i >= 0; i--) { callback(obj[i], i); } } else { for (var j = 0, len = obj.length; j < len; j++) { callback(obj[j], j); } } }; if (isObject(obj)) { loopObj(); } if (isArray(obj) || isNodeList(obj)) { loopArr(); } }; function clearUndefKey(obj) { forEach(obj, function (key, val) { if (isUndefined(val)) { delete obj[key]; } }); return obj; } function map(arr, event) { forEach(arr, function(item, index) { arr[index] = event(item, index); }); return arr; } function deepMap(arr, event) { forEach(arr, function (item, index) { if (isArray(item) || isObject(item)) { arr[index] = deepMap(item, event); } else { arr[index] = event(item, index); } }); return arr; } function isEqual(obj1, obj2) { if (isObject(obj1) && isObject(obj2)) { var isEq = true; forEach(obj1, function (val, key) { if (obj2[key] !== val) { isEq = false; } }); return isEq; } else { return obj1 == obj2; } } function getDom(id) { return document.getElementById(id); } function queryAllDom(sel) { return document.querySelectorAll(sel); } function queryDom(sel) { return document.querySelector(sel); } function removeDom(dom) { var parent = dom.parentNode || dom.parentElement; parent.removeChild(dom); } function getParent(dom) { return dom.parentNode || dom.parentElement; } function getChildren(dom) { return dom.children; } function getTemp(id) { var dom = getDom(id); return dom.innerHTML; } function getDomIndex(dom) { var parent = getParent(dom); var children = parent.children; for (var i = 0, max = children.length; i < max; i++) { var child = children[i]; if (dom === child) { return i; } } return -1; } function toJSON(obj) { return JSON.stringify(obj); } function parseJSON(str) { var val; try { val = JSON.parse(str); } catch(e) {} return val; } function copy(obj) { var copyObj = parseJSON(toJSON(obj)); return copyObj; } function hasClass(el, className) { if (!el) { return false; } var classList = el.classList; for (var i = 0, max = classList.length; i < max; i++) { if (classList[i] === className) { return true; } } return false; } function timestampToString(timestamp) { var date = timestamp ? new Date(timestamp) : new Date(); Y = date.getFullYear() + '-'; M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'; D = date.getDate() + ' '; h = date.getHours() + ':'; m = date.getMinutes() + ':'; s = date.getSeconds(); return Y + M + D + h + m + s; } function extend(destination, sources) { for (var key in sources) { var value = sources[key]; if (!isUndefined(value)) { destination[key] = value; } } return destination; }; /** * 封装弹框组件 * @param {object} options */ function mountDialog(options, instance) { options.parent = instance; var Dialog = Vue.extend(options); var instance = new Dialog({ el: document.createElement('div') }); var wrap = document.getElementsByTagName('body')[0]; wrap.appendChild(instance.$el); return instance; } function reverse(obj) { var newObj = copy(obj); return newObj.reverse(); } function openUrl(url) { window.open(url); } function getBase64Image() { var canvas = document.createElement('canvas'); canvas.width = 100; canvas.height = 100; var context = canvas.getContext('2d'); context.font = '20pt Arial'; context.fillStyle = 'blue'; context.fillText('RongCloud.cn', 10, 20); var content = canvas.toDataURL('image/jpeg'); content = content.replace('data:image/jpeg;base64,', ''); return content; } var increaseNumber = 0; function getIncreasNumber() { return ++increaseNumber; } var EventEmitter = function () { this._events = {}; this.on = function (name, event) { var _events = this._events[name] || []; _events.push(event); this._events[name] = _events; }; this.emit = function (name, data) { var _events = this._events[name]; forEach(_events, function(event) { event(data); }); }; }; var Storage = { ConfigKey: 'config', get: function (key) { var str = localStorage.getItem(key); return parseJSON(str); }, set: function (key, val) { var str = toJSON(val); localStorage.setItem(key, str); } }; function getUrlQuery() { var url = location.search; //获取url中"?"符后的字串 var theRequest = new Object(); if (url.indexOf('?') != -1) { var str = url.substr(1); strs = str.split('&'); for (var i = 0; i < strs.length; i++) { theRequest[strs[i].split('=')[0]] = unescape(strs[i].split('=')[1]); } } return theRequest; } function getRCUrlQuery() { var theRequest = getUrlQuery(); var transMap = { 'true': true, 'false': false }; map(theRequest, function (val, key) { var transVal = transMap[val]; if (!isUndefined(transVal)) { val = transVal; } return val; }); forEach(theRequest, function (val, key) { if (key === 'encodeToken') { theRequest.token = decodeURIComponent(val); delete theRequest.encodeToken; } if (key === 'isMini') { delete theRequest.isMini; } }); return theRequest; } function deferNoop() { return Defer.resolve(); } var request = (function () { const isValidRequest = function(obj) { return typeof obj === 'function' || typeof obj === 'object'; }; const createXHR = function() { let item = { XMLHttpRequest: function() { return new XMLHttpRequest(); }, XDomainRequest: function() { return new XDomainRequest(); }, ActiveXObject: function() { return new ActiveXObject('Microsoft.XMLHTTP'); } }; let isXHR = isValidRequest(window.XMLHttpRequest); let isXDR = isValidRequest(window.XDomainRequest); let key = isXHR ? 'XMLHttpRequest' : isXDR ? 'XDomainRequest' : 'ActiveXObject'; return item[key](); }; const isRequestSuccess = function(status) { let responseStatus = status + ''; // test 仅 string 类型可调用 return /^(200|202)$/.test(responseStatus); }; const request = function(option) { var url = option.url, method = option.method, body = option.body, headers = option.headers, success = option.success, fail = option.fail; method = method || 'get'; let xhr = createXHR(); xhr.open(method, url); if (headers && xhr.setRequestHeader) { for (let key in headers) { xhr.setRequestHeader(key, headers[key]); } } xhr.onreadystatechange = function() { if (xhr.readyState === 4) { let result = xhr.responseText, status = xhr.status; if (isRequestSuccess(status)) { success(result, xhr); } else { fail(result, xhr, status); } } }; xhr.onerror = function(error) { fail(error); }; xhr.send(body); }; return request; })(); win.RongIM = win.RongIM || {}; win.RongIM.Utils = { Storage: Storage, TypeColor: TypeColor, ConversationName: ConversationName, StatusName: StatusName, SuccessStatus: SuccessStatus, request: request, EventEmitter: EventEmitter, noop: noop, isNumber: isNumber, isFunction: isFunction, map: map, deepMap: deepMap, isEqual: isEqual, clearUndefKey: clearUndefKey, Defer: Defer, defered: defered, tplEngine: tplEngine, forEach: forEach, toJSON: toJSON, parseJSON: parseJSON, copy: copy, removeDom: removeDom, getParent: getParent, getChildren: getChildren, hasClass: hasClass, getDomIndex: getDomIndex, timestampToString: timestampToString, extend: extend, reverse: reverse, openUrl: openUrl, getBase64Image: getBase64Image, getIncreasNumber: getIncreasNumber, getDom: getDom, queryDom: queryDom, queryAllDom: queryAllDom, getTemp: getTemp, mountDialog: mountDialog, getUrlQuery: getUrlQuery, getRCUrlQuery: getRCUrlQuery, deferNoop: deferNoop }; })(window); ================================================ FILE: api-test-v2/js/components/button.js ================================================ (function (win, dependencies, components) { var Vue = dependencies.Vue, RongIM = dependencies.RongIM, utils = RongIM.Utils, Service = RongIM.Service; var OutputMark = { SUCCESS: '成功', FAILED: '失败' }; var copyApi = function (api) { var params = api.params || []; var copyParams = utils.copy(params); utils.forEach(params, function (item, index) { utils.forEach(item, function (val, key) { if (utils.isFunction(val)) { copyParams[index][key] = val; } }); }); api.params = copyParams; return api; }; components.apiBtn = Vue.component('api-btn', { template: utils.getTemp('rong-tpl-apibtn'), props: ['api', 'isdragging'], data: function() { return { isShowEditDialog: false, selfApi: copyApi(this.api) } }, watch: { markMessage: function (newMsg) { console.log(newMsg); } }, computed: { tip: function() { var api = this.selfApi; return utils.tplEngine(TipTpl, api); }, apiValue: function() { var api = this.selfApi; return utils.toJSON(api); }, paramList: function () { var paramList = this.selfApi.params; return paramList; }, hasParams: function () { var params = this.selfApi.params; return params && params.length; } }, methods: { openUrl: utils.openUrl, showEditDialog: function() { this.isShowEditDialog = true; }, hideEditDialog: function() { this.isShowEditDialog = false; }, change: function() { }, run: function() { var self = this; var params = []; var startTime = +new Date(); utils.forEach(self.selfApi.params, function(item) { if (item.type === 'number') { item.value = Number(item.value); } params.push(item.value); }); var imInstance = RongIM.vueInstance; var addOutput = function(data, isSuccess) { var currentTime = +new Date(); var consumedTime = currentTime - startTime; var title = self.api.name + (isSuccess ? OutputMark.SUCCESS : OutputMark.FAILED); var config = {}; if (!isSuccess) { config.color = utils.TypeColor.FAILED; } self.hideEditDialog(); return imInstance.addOutput(title, data, consumedTime, params, config); }; return self.api.event.apply(void 0, params).then(function(data) { var data = addOutput(data, true); return { isSuccess: true, data: data }; }).catch(function(error) { // TODO 报警 error = utils.isNumber(error) ? error : error.toString(); var data = addOutput(error, false); return { isSuccess: false, data: data }; }); } }, mounted: function() { var self = this; var setParams = function () { var paramList = self.selfApi.params; utils.forEach(paramList, function (item) { if (item.event) { item.value = item.value || item.event(); } }); }; setParams(); Service.msgEmitter.on('msgChanged', setParams); } }); })(window, { Vue: Vue, iview: iview, RongIM: RongIM }, window.RongIM.components); ================================================ FILE: api-test-v2/js/components/json-alert.js ================================================ (function (win, dependencies) { var RongIM = dependencies.RongIM; var utils = RongIM.Utils; RongIM.dialog = RongIM.dialog || {}; RongIM.dialog.jsonAlert = function(options) { var vueInstance = RongIM.vueInstance; options = options || {}; utils.mountDialog({ name: 'json-alert', template: '#rong-json-alert', data: function () { return { isShow: true, data: options.data }; }, watch: { isShow: function(isShow) { if (!isShow) { utils.removeDom(this.$el); } } }, methods: { hide: function() { this.isShow = false; } } }, vueInstance); }; })(window, { RongIM: RongIM }); ================================================ FILE: api-test-v2/js/login.js ================================================ (function (win, dependencies, components) { var Vue = dependencies.Vue, RongIM = dependencies.RongIM, utils = RongIM.Utils, isDebug = RongIM.config.isDebug, debugConf = RongIM.config.debugConf; var ConfigPlacehoder = { appkey: '开发者的融云 AppKey', token: '开发者的用户 Token', targetId: '对方 id. 发消息、获取历史消息等都默认对此用户操作. 默认聊天室、群组、个人 id 都为此 id', navi: '导航地址. 注: 国内数据中心可不填', cmpUrl: '链接地址(开发者忽略此项)', isPolling: '若使用长轮训链接方式, 可选择此项(开发者可忽略)' }; components.login = Vue.component('login', { template: utils.getTemp('rong-global-config'), props: ['config', 'login'], computed: { configList: function() { var items = []; utils.forEach(this.config, function(val, key) { items.push({ type: typeof val, name: key }); }); return items; }, prompt: function() { return ConfigPlacehoder; } }, methods: { clearStorage: function () { window.localStorage.clear(); this.$Message.success({ background: true, content: '清空本地缓存成功' }); } }, mounted: function () { if (isDebug && debugConf.autoRun) { var self = this; Vue.nextTick(function () { self.login(self.config); }); } } }); })(window, { Vue: Vue, iview: iview, RongIM: RongIM }, window.RongIM.components); ================================================ FILE: api-test-v2/js/main.js ================================================ (function (win, dependencies, components) { var Vue = dependencies.Vue, iview = dependencies.iview, VueJsonPretty = dependencies.VueJsonPretty, RongIM = dependencies.RongIM, Service = RongIM.Service, utils = RongIM.Utils, ApiList = RongIM.ApiList, DefailtReadyApiQueue = RongIM.DefailtReadyApiQueue, DefaultConfig = RongIM.config.im, Config = utils.copy(DefaultConfig), Storage = utils.Storage, StorageConfig = Storage.get(Storage.ConfigKey), DefaultTargetId = Config.targetId, isDebug = RongIM.config.isDebug, debugConf = RongIM.config.debugConf; DefailtReadyApiQueue.push([]); var ValidStatus = [0, 1, 2, 6, 201, 202]; var ValidErrorCode = [23424, 23427, 23426, 23423]; var isStop = false; var isStorageConfig = false; if (StorageConfig && !isDebug) { isStorageConfig = true; Config = utils.copy(StorageConfig); } var urlQueryConfig = utils.getRCUrlQuery(); Config = utils.extend(Config, urlQueryConfig); var ReceiveMsgTextTpl = '监听到{typeName} ({conversationType})消息. 发送者: {senderUserId}'; var StatusTextTpl = '链接状态: {statusName} ({status})'; var OptBoxClass = 'rong-ready-box'; var ApiBoxClass = 'rong-api-list'; var ApiSourceClass = 'rong-api-source'; var RunType = { OneByOne: { name: '逐个运行', prompt: 'Api 逐个执行' }, LineByLine: { name: '逐行运行', prompt: '每行 Api 并行. 执行完一行后执行下一行' } }; var vueInstance; function runAllApi(allRefs, currentIndex, finishCallback) { var total = allRefs.length; var isFinished = total === currentIndex || isStop; if (isFinished) { return finishCallback && finishCallback(); } var refList = allRefs[currentIndex]; var deferArr = []; utils.forEach(refList, function (instance) { deferArr.push(instance.run()); }); return utils.Defer.all(deferArr).then(function (result) { result = result[0]; var isSuccess = result.isSuccess || ValidErrorCode.indexOf(result.data.result) !== -1; if (isSuccess) { vueInstance.runInfo.successApiCount++; } else { vueInstance.runInfo.failApiList.push(result.data); } currentIndex++; runAllApi(allRefs, currentIndex, finishCallback); }); } function runOneByOne(finishCallback) { var refs = vueInstance.$refs; var allRefs = []; utils.forEach(refs, function (subRefList) { utils.forEach(subRefList, function (ref) { allRefs.push([ ref ]); }); }); runAllApi(allRefs, 0, finishCallback); } function runLineByLine(finishCallback) { var refs = vueInstance.$refs; var allRefs = []; utils.forEach(refs, function (ins) { allRefs.push(ins); }); runAllApi(allRefs, 0, finishCallback); } function setConfig(config) { var currentTargetId = config.targetId; vueInstance.globalConfig = config; vueInstance.readyApiQueue = utils.deepMap(vueInstance.readyApiQueue, function (item) { if (item === DefaultTargetId) { item = currentTargetId; } return item; }); } function watchStatus(status) { var title = utils.tplEngine(StatusTextTpl, { status: status, statusName: utils.StatusName[status] }); var output = vueInstance.addOutput(title, status, 0, [], { color: utils.TypeColor.STATUS }); if (ValidStatus.indexOf(status) === -1) { vueInstance.runInfo.failApiList.push(output); } var isSuccess = utils.SuccessStatus.indexOf(status) !== -1; var event = isSuccess ? vueInstance.$Message.success : vueInstance.$Message.error; event.call(vueInstance.$Message, { background: true, content: title }); } function watchConversationStatus(status) { vueInstance.addOutput('会话状态变更', status, 0, [], { color: utils.TypeColor.MSG }); } function watchMessage(message) { if (RongIM.config.isDebug && !RongIM.config.debugConf.isShowMsg) { return; } var title = utils.tplEngine(ReceiveMsgTextTpl, { typeName: utils.ConversationName[message.conversationType], conversationType: message.conversationType, senderUserId: message.senderUserId }); vueInstance.addOutput(title, message, 0, [], { color: utils.TypeColor.MSG }); console.log('Reveice Msg', utils.toJSON(message)); } function autoRun() { Vue.nextTick(function () { runOneByOne(function () { vueInstance.runInfo.runCount++; localStorage.removeItem('rong_servers'); localStorage.removeItem('rong_fullnavi'); vueInstance.outputList = []; vueInstance.allOutputList = []; !isStop && autoRun(); }); }); } function loginSuccessEvent(userId, config) { vueInstance.$Message.success({ background: true, content: '链接成功 ' + userId }); vueInstance.currentUserId = userId; vueInstance.isLogged = true; if (isDebug && debugConf.autoRun) { Vue.nextTick(autoRun); } } function login(config) { setConfig(config); return Service.init(config, { status: watchStatus, message: watchMessage, conversationStatus: watchConversationStatus }).then(function (userId) { Storage.set(Storage.ConfigKey, config); loginSuccessEvent(userId, config); }).catch(function (error) { vueInstance.$Message.error({ background: true, content: '链接失败 ' + error }); return utils.Defer.reject(); }); } function getApiListMethods() { return { addOutput: function (title, result, consumedTime, params, config) { config = config || {}; var output = { id: utils.getIncreasNumber(), title: title, result: result, consumedTime: consumedTime, params: params, config: config }; output.time = utils.timestampToString(); vueInstance.allOutputList.push(output); vueInstance.outputList.push(output); return output; }, clearOutput: function () { vueInstance.outputList = []; }, showAllOutput: function () { vueInstance.outputList = vueInstance.allOutputList; }, toJSON: function (data) { return utils.toJSON(data); }, showJSONAlert: function(data) { RongIM.dialog.jsonAlert({ data: data }); }, runAllApi: function() { if (vueInstance.runType === 'OneByOne') { runOneByOne(); } else { runLineByLine(); } }, startDragging: function () { setTimeout(function() { vueInstance.isDragging = true; }, 100); } }; } function getServiceMethods() { return { openUrl: utils.openUrl, reverse: utils.reverse, login: function(config) { var isEqualStorage = utils.isEqual(config, StorageConfig); var isEqualDefault = utils.isEqual(config, DefaultConfig); if (isStorageConfig && isEqualStorage && !isEqualDefault && !isDebug) { vueInstance.$Modal.confirm({ title: '注意', content: '您目前使用的为上一次链接配置, 请确定配置是否可用 ?', onOk: function () { login(config); } }); } else { return login(config); } }, alarm: function () { if (!this.isAlarmMuted) { vueInstance.$refs.alarm.play(); } }, mute: function () { vueInstance.$refs.alarm.pause(); } }; } Vue.use(iview); vueInstance = new Vue({ el: '#app', data: function() { return { currentUserId: '', isLogged: false, readyApiQueue: DefailtReadyApiQueue, allOutputList: [], outputList: [], globalConfig: Config, RunType: RunType, runType: 'OneByOne', alertJSON: null, isDragging: false, isShowRunType: false, isShowOutList: false, isDebug: RongIM.config.isDebug, runInfo: { runCount: 0, successApiCount: 0, failApiList: [] }, isAlarmMuted: false }; }, computed: { apiList: function() { return ApiList; }, changeUserApi: function () { var self = this; var changeUserApi = RongIM.Api.changeUser; var changeUserEvent = changeUserApi.event; changeUserApi.event = function (token) { var globalConfig = self.globalConfig globalConfig.token = token; return Service.changeUser(globalConfig, { status: watchStatus, message: watchMessage }).then(function (userId) { loginSuccessEvent(userId, globalConfig); }).catch(function () { vueInstance.$Message.error({ background: true, content: '切换用户失败 ' + error }); }); }; return changeUserApi; }, currentOutput: function() { var outputList = this.outputList; if (outputList.length) { return outputList[outputList.length - 1]; } }, displayedOutputList: function () { if (isDebug) { return this.runInfo.failApiList; } else { return this.outputList; } } }, watch: { 'runInfo.failApiList': function (newList) { if (newList.length > 20) { this.alarm(); } }, isAlarmMuted: function (isMuted) { if (isMuted) { this.mute(); } } }, components: { apiBtn: components.apiBtn, login: components.login, prettyjson: Vue.component('prettyjson', VueJsonPretty.default) }, mounted: function() { this.isPageLoaded = true; }, methods: utils.extend(getApiListMethods(), getServiceMethods()) }); RongIM.vueInstance = vueInstance; (function () { function start() { isStop = false; if (vueInstance.isLogged) { autoRun(); } else { vueInstance.login(vueInstance.globalConfig).then(autoRun); } } window.addEventListener("message", function (event) { var type = event.data; if (type === 'start') { start(); } else if (type === 'pause') { isStop = true; } }, false); })(); })(window, { Vue: Vue, iview: iview, VueJsonPretty: VueJsonPretty, RongIM: RongIM }, window.RongIM.components); ================================================ FILE: api-test-v2/lib/js/RongIMLib-2.3.1-revise-20200311-222.js ================================================ /* 切换新版 SDK 检查记录:杨川 修改红包消息命名错误 JrmfReadPacketMessage => JrmfRedPacketMessage JrmfReadPacketOpenedMessage => JrmfRedPacketOpenedMessage 缺失方法 clearData C++ 消息监听 VCDataProvider.prototype.setOnReceiveMessageListener 缺失音视频消息过滤 _voipProvider.onReceived VCDataProvider.prototype.getRemoteConversationList obj 少了空字符串判断 VCDataProvider.prototype.sendReceiptResponse 方法为空 RCE 未用到 voip 2018-3-10 修改 InviteMessage MemberModifyMessage 消息体重增加 observerUserIds 属性 导航重定向修改 setConnectionStatusListener() 抛出一些状态码 注册消息时增加搜索项 addon.registerMessageType searchProp */ /* 说明: 请勿修改 header.js 和 footer.js 用途: 自动拼接暴露方式 命令: grunt release 中 concat */ /* date: 2018-07-02 auth: yangchuan bug: Web 端消息是否计数标识不生效 update: Web 接收消息时判断消息是否需要计数 date: 2018-07-10 auth: yangchuan update: 发送消息敏感词替换,触发成功回调并返回对应 code 码 以上已合并至 SDK ------------------------------------------------------ date: 2018-10-25 auth: yuhongda feat: 消息监听增加 `是否还有离线消息` feature: 用此属性区分是否还有离线消息,待会补偿消息拉取完成后更新一次会话 date: 2018-10-26 auth: yuhongda feat: addon.getUnreadCount 支持同步获取 date: 2018-10-27 auth: yuhongda feat: 会话列表增加分页 memo: 仅 c++ 支持会话列表分页 date: 2018-12-3 auth: yuhongda feat: 增加获取公众号历史消息的信令 memo: 仅 web 端生效 Date: 2019-05-05 Author: YuHongDa 增加获取服务端会话列表接口(getRemoteConversations),此接口参会成功失败,C++ 层做数据合并,此接口仅在 Electron 中有效 date: 2019-05-08 auth: LiuYuqi update: RCE 增加管理员撤回消息修改 RecallCommandMessage 增加属性 isDelete 是否仅删除不提示撤回消息 isAdmin 是否管理员撤回 adminId 管理员 Id Date: 2019-05-30 auth: KongCong update: 1. getRemoteConversations 暂时不可用,因 c++ 协议栈接口变更 2. searchConversationByContent 新增 customMsgTypes 参数,参数为数组,直接透传给 c++ 协议栈,用于修复获取到的会话中 matchCount 匹配消息数量与 searchMessageByContent 实际获取的消息数不相等 Date: 2019-06-05 auth: kongcong update: getRemoteConversations 适配 c++ 协议栈,此方法增加 beginTime, order 参数,用于获取指定时间点开始、向前或向后的会话 beginTime: 时间戳,若值为 0,则默认使用服务系统时间戳 order: 时间方向,0 获取指定时间点以前的会话,1 获取指定时间点以后的会话 Date: 2019-07-24 auth: LiuYuqi update: 增加 clearCache 方法,解决 web 端切换用户时,获取会话列表后,返回值为上一个用户的数据 Date: 2020-03-11 auth: WangYongHao update: 文字、图片、语音、高清语音消息增加阅后即焚 burnDuration 字段 */ (function(global, factory) { if (typeof exports === 'object' && typeof module !== 'undefined') { module.exports = factory(); } else if (typeof define === 'function' && define.amd) { define(factory); } else { var tempIMLib = factory(); var tempClient = tempIMLib.RongIMClient; var isExists = (!!global.RongIMLib); if (isExists) { var currentClient = RongIMLib.RongIMClient || {}; for(var key in currentClient){ tempClient[key] = currentClient[key]; } } global.RongIMLib = tempIMLib; global.RongIMClient = tempClient; } })(this, function(){ var Polling = { SetUserStatusInput: function(){ var a = {}; this.setStatus = function(b){ a.status = b; }; this.toArrayBuffer = function(){ return a; }; }, SetUserStatusOutput: function(){ var a = {}; this.setNothing = function(b){ a.nothing = b; }; this.toArrayBuffer = function(){ return a; }; }, GetUserStatusInput: function(){ var a = {}; this.setNothing = function(b){ a.nothing = b; }; this.toArrayBuffer = function(){ return a; }; }, GetUserStatusOutput: function(){ var a = {}; this.setStatus = function(b){ a.status = b; }; this.setSubUserId = function(b){ a.subUserId = b; }; this.toArrayBuffer = function(){ return a; }; }, SubUserStatusInput: function(){ var a = {}; this.setUserid = function(b){ a.userid = b; }; this.toArrayBuffer = function(){ return a; }; }, SubUserStatusOutput: function(){ var a = {}; this.setNothing = function(b){ a.nothing = b; }; this.toArrayBuffer = function(){ return a; }; }, CleanHisMsgInput: function(){ var a = {}; this.setTargetId = function(b){ a.targetId = b; }; this.setDataTime = function(b){ a.dataTime = b; }; this.setConversationType = function(b){ a.conversationType = b; }; this.toArrayBuffer = function(){ return a; }; }, DeleteMsgInput:function(){ var a = {}; this.setType = function(b){ a.type = b; }; this.setConversationId = function(b){ a.conversationId = b; }; this.setMsgs = function(b){ a.msgs = b; }; this.toArrayBuffer = function () { return a; } }, DeleteMsg:function(){ var a = {}; this.setMsgId = function(b){ a.msgId = b; }; this.setMsgDataTime = function(b){ a.msgDataTime = b; }; this.setDirect = function(b){ a.direct = b; }; this.toArrayBuffer = function () { return a; } }, DeleteMsgOutput:function(){ var a = {}; this.setNothing = function(b){ a.nothing = b; }; this.toArrayBuffer = function () { return a; } }, SearchMpInput:function(){ var a = {}; this.setType = function (b) { a.type = b; }; this.setId = function (b) { a.id = b; }; this.toArrayBuffer = function () { return a; } }, SearchMpOutput:function(){ var a = {}; this.setNothing = function (b) { a.nothing = b; }; this.setInfo = function (b) { a.info = b; }; this.toArrayBuffer = function () { return a; } }, MpInfo:function(){ var a = {}; this.setMpid = function(b){ a.mpid = b; }; this.setName = function(b){ a.name = b; }; this.setType = function(b){ a.type = b; }; this.setTime = function(b){ a.time = b; }; this.setPortraitUri = function(b){ a.portraitUrl = b; }; this.setExtra = function(b){ a.extra = b; }; this.toArrayBuffer = function () { return a; } }, PullMpInput:function(){ var a = {}; this.setMpid = function(b){ a.mpid = b; }; this.setTime = function(b){ a.time = b; }; this.toArrayBuffer = function () { return a; }; }, PullMpOutput:function(){ var a = {}; this.setStatus = function(b){ a.status = b; } this.setInfo = function(b){ a.info = b; }; this.toArrayBuffer = function () { return a; }; }, MPFollowInput:function(){ var a = {}; this.setId = function(b){ a.id = b; }; this.toArrayBuffer = function () { return a; }; }, MPFollowOutput:function(){ var a = {}; this.setNothing = function(b){ a.nothing = b; }; this.setInfo = function(b){ a.info = b; }; this.toArrayBuffer = function () { return a; }; }, NotifyMsg: function () { var a = {}; this.setType = function (b) { a.type = b; }; this.setTime = function (b) { a.time = b; }; this.setChrmId = function(b){ a.chrmId = b; }; this.toArrayBuffer = function () { return a; }; }, SyncRequestMsg: function () { var a = {}; this.setSyncTime = function (b) { a.syncTime = b || 0; }; this.setIspolling = function (b) { a.ispolling = !!b; }; this.setIsweb = function (b) { a.isweb = !!b; }; this.setIsPullSend = function (b) { a.isPullSend = !!b; }; this.toArrayBuffer = function () { return a; }; }, UpStreamMessage: function () { var a = {}; this.setSessionId = function (b) { a.sessionId = b }; this.setClassname = function (b) { a.classname = b }; this.setContent = function (b) { if (b) a.content = b; }; this.setPushText = function (b) { a.pushText = b }; this.setUserId = function(b){ a.userId = b; }; this.setAppData = function(b){ a.appData = b; }; this.toArrayBuffer = function () { return a }; }, DownStreamMessages: function () { var a = {}; this.setList = function (b) { a.list = b }; this.setSyncTime = function (b) { a.syncTime = b; }; this.toArrayBuffer = function () { return a }; }, DownStreamMessage: function () { var a = {}; this.setFromUserId = function (b) { a.fromUserId = b }; this.setType = function (b) { a.type = b }; this.setGroupId = function (b) { a.groupId = b }; this.setClassname = function (b) { a.classname = b }; this.setContent = function (b) { if (b) a.content = b }; this.setDataTime = function (b) { a.dataTime = b; }; this.setStatus = function (b) { a.status = b; }; this.setMsgId = function (b) { a.msgId = b; }; this.toArrayBuffer = function () { return a; }; }, CreateDiscussionInput: function () { var a = {}; this.setName = function (b) { a.name = b }; this.toArrayBuffer = function () { return a } }, CreateDiscussionOutput: function () { var a = {}; this.setId = function (b) { a.id = b }; this.toArrayBuffer = function () { return a }; }, ChannelInvitationInput: function () { var a = {}; this.setUsers = function (b) { a.users = b }; this.toArrayBuffer = function () { return a }; }, LeaveChannelInput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b }; this.toArrayBuffer = function () { return a }; }, QueryChatroomInfoInput:function(){ var a = {}; this.setCount = function (b) { a.count = b; }; this.setOrder = function (b) { a.order = b; }; this.toArrayBuffer = function () { return a }; }, QueryChatroomInfoOutput:function(){ var a = {}; this.setUserTotalNums = function (b) { a.userTotalNums = b; }; this.setUserInfos = function (b) { a.userInfos = b; }; this.toArrayBuffer = function () { return a; }; }, ChannelEvictionInput: function () { var a = {}; this.setUser = function (b) { a.user = b }; this.toArrayBuffer = function () { return a }; }, RenameChannelInput: function () { var a = {}; this.setName = function (b) { a.name = b }; this.toArrayBuffer = function () { return a } }, ChannelInfoInput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b }; this.toArrayBuffer = function () { return a } }, ChannelInfoOutput: function () { var a = {}; this.setType = function (b) { a.type = b }; this.setChannelId = function (b) { a.channelId = b }; this.setChannelName = function (b) { a.channelName = b }; this.setAdminUserId = function (b) { a.adminUserId = b }; this.setFirstTenUserIds = function (b) { a.firstTenUserIds = b }; this.setOpenStatus = function (b) { a.openStatus = b }; this.toArrayBuffer = function () { return a } }, ChannelInfosInput: function () { var a = {}; this.setPage = function (b) { a.page = b }; this.setNumber = function (b) { a.number = b }; this.toArrayBuffer = function () { return a }; }, ChannelInfosOutput: function () { var a = {}; this.setChannels = function (b) { a.channels = b }; this.setTotal = function (b) { a.total = b }; this.toArrayBuffer = function () { return a }; }, MemberInfo: function () { var a = {}; this.setUserId = function (b) { a.userId = b }; this.setUserName = function (b) { a.userName = b }; this.setUserPortrait = function (b) { a.userPortrait = b }; this.setExtension = function (b) { a.extension = b }; this.toArrayBuffer = function () { return a }; }, GroupMembersInput: function () { var a = {}; this.setPage = function (b) { a.page = b }; this.setNumber = function (b) { a.number = b }; this.toArrayBuffer = function () { return a }; }, GroupMembersOutput: function () { var a = {}; this.setMembers = function (b) { a.members = b }; this.setTotal = function (b) { a.total = b }; this.toArrayBuffer = function () { return a }; }, GetUserInfoInput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b }; this.toArrayBuffer = function () { return a }; }, GetUserInfoOutput: function () { var a = {}; this.setUserId = function (b) { a.userId = b }; this.setUserName = function (b) { a.userName = b }; this.setUserPortrait = function (b) { a.userPortrait = b }; this.toArrayBuffer = function () { return a }; }, GetSessionIdInput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b }; this.toArrayBuffer = function () { return a }; }, GetSessionIdOutput: function () { var a = {}; this.setSessionId = function (b) { a.sessionId = b }; this.toArrayBuffer = function () { return a }; }, GetQNupTokenInput: function () { var a = {}; this.setType = function (b) { a.type = b; } this.toArrayBuffer = function () { return a } }, GetQNupTokenOutput: function () { var a = {}; this.setDeadline = function (b) { a.deadline = b }; this.setToken = function (b) { a.token = b; }; this.toArrayBuffer = function () { return a } }, GetQNdownloadUrlInput: function () { var a = {}; this.setType = function (b) { a.type = b; }; this.setKey = function (b) { a.key = b; }; this.setFileName = function(b){ a.fileName = b; }; this.toArrayBuffer = function () { return a } }, GetQNdownloadUrlOutput: function () { var a = {}; this.setDownloadUrl = function (b) { a.downloadUrl = b; }; this.toArrayBuffer = function () { return a } }, Add2BlackListInput: function () { var a = {}; this.setUserId = function (b) { a.userId = b; }; this.toArrayBuffer = function () { return a } }, RemoveFromBlackListInput: function () { var a = {}; this.setUserId = function (b) { a.userId = b; }; this.toArrayBuffer = function () { return a } }, QueryBlackListInput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b; }; this.toArrayBuffer = function () { return a } }, QueryBlackListOutput: function () { var a = {}; this.setUserIds = function (b) { a.userIds = b; }; this.toArrayBuffer = function () { return a } }, BlackListStatusInput: function () { var a = {}; this.setUserId = function (b) { a.userId = b; }; this.toArrayBuffer = function () { return a } }, BlockPushInput: function () { var a = {}; this.setBlockeeId = function (b) { a.blockeeId = b; }; this.toArrayBuffer = function () { return a } }, ModifyPermissionInput: function () { var a = {}; this.setOpenStatus = function (b) { a.openStatus = b; }; this.toArrayBuffer = function () { return a }; }, GroupInput: function () { var a = {}; this.setGroupInfo = function (b) { for (var i = 0, arr = []; i < b.length; i++) { arr.push({id: b[i].getContent().id, name: b[i].getContent().name}) } a.groupInfo = arr; }; this.toArrayBuffer = function () { return a }; }, GroupOutput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b; }; this.toArrayBuffer = function () { return a }; }, GroupInfo: function () { var a = {}; this.setId = function (b) { a.id = b; }; this.setName = function (b) { a.name = b; }; this.getContent = function () { return a; }; this.toArrayBuffer = function () { return a }; }, GroupHashInput: function () { var a = {}; this.setUserId = function (b) { a.userId = b; }; this.setGroupHashCode = function (b) { a.groupHashCode = b; }; this.toArrayBuffer = function () { return a }; }, GroupHashOutput: function () { var a = {}; this.setResult = function (b) { a.result = b; }; this.toArrayBuffer = function () { return a }; }, ChrmInput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b; }; this.toArrayBuffer = function () { return a }; }, ChrmOutput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b; }; this.toArrayBuffer = function () { return a }; }, ChrmPullMsg: function () { var a = {}; this.setSyncTime = function (b) { a.syncTime = b }; this.setCount = function (b) { a.count = b; }; this.toArrayBuffer = function () { return a }; }, RelationsInput: function () { var a = {}; this.setType = function (b) { a.type = b; }; this.setMsg = function(b){ a.msg = b; }; this.setCount = function(b){ a.count = b; }; this.toArrayBuffer = function () { return a }; }, RelationsOutput: function () { var a = {}; this.setInfo = function (b) { a.info = b; }; this.toArrayBuffer = function () { return a } }, RelationInfo: function () { var a = {}; this.setType = function (b) { a.type = b; }; this.setUserId = function (b) { a.userId = b; }; this.setMsg = function(b){ a.msg = b; }; this.toArrayBuffer = function () { return a } }, HistoryMessageInput: function () { var a={}; this.setTargetId=function(b){ a.targetId=b; }; this.setDataTime=function(b){ a.dataTime=b; }; this.setSize=function(b){ a.size=b; }; this.toArrayBuffer = function () { return a } }, HistoryMessagesOuput: function () { var a={}; this.setList=function(b){ a.list=b; }; this.setSyncTime=function(b){ a.syncTime=b; }; this.setHasMsg=function(b){ a.hasMsg=b; }; this.toArrayBuffer = function () { return a } }, HistoryMsgInput: function(){ var a = {}; this.setTargetId = function(b){ a.targetId = b; }; this.setTime = function(b){ a.time = b; }; this.setCount = function(b){ a.count = b; }; this.setOrder = function(b){ a.order = b; }; this.toArrayBuffer = function(){ return a; }; }, HistoryMsgOuput: function(){ var a = {}; this.setList = function(b){ a.list = b; }; this.setSyncTime = function(b){ a.syncTime = b; }; this.setHasMsg = function(b){ a.hasMsg = b; }; this.toArrayBuffer = function(){ return a; }; } }; for (var f in Polling) { Polling[f].decode = function (b) { var back = {}, val = JSON.parse(b) || eval("(" + b + ")"); for (var i in val) { back[i]=val[i]; back["get"+ i.charAt(0).toUpperCase()+i.slice(1)]=function(){ return val[i]; } } return back; } } /* * JavaScript MD5 * https://github.com/blueimp/JavaScript-MD5 * * Copyright 2011, Sebastian Tschan * https://blueimp.net * * Licensed under the MIT license: * http://www.opensource.org/licenses/MIT * * Based on * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message * Digest Algorithm, as defined in RFC 1321. * Version 2.2 Copyright (C) Paul Johnston 1999 - 2009 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet * Distributed under the BSD License * See http://pajhome.org.uk/crypt/md5 for more info. */ /*jslint bitwise: true */ /*global unescape, define, module */ var md5 = (function () { 'use strict'; /* * Add integers, wrapping at 2^32. This uses 16-bit operations internally * to work around bugs in some JS interpreters. */ function safe_add(x, y) { var lsw = (x & 0xFFFF) + (y & 0xFFFF), msw = (x >> 16) + (y >> 16) + (lsw >> 16); return (msw << 16) | (lsw & 0xFFFF); } /* * Bitwise rotate a 32-bit number to the left. */ function bit_rol(num, cnt) { return (num << cnt) | (num >>> (32 - cnt)); } /* * These functions implement the four basic operations the algorithm uses. */ function md5_cmn(q, a, b, x, s, t) { return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s), b); } function md5_ff(a, b, c, d, x, s, t) { return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t); } function md5_gg(a, b, c, d, x, s, t) { return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t); } function md5_hh(a, b, c, d, x, s, t) { return md5_cmn(b ^ c ^ d, a, b, x, s, t); } function md5_ii(a, b, c, d, x, s, t) { return md5_cmn(c ^ (b | (~d)), a, b, x, s, t); } /* * Calculate the MD5 of an array of little-endian words, and a bit length. */ function binl_md5(x, len) { /* append padding */ x[len >> 5] |= 0x80 << (len % 32); x[(((len + 64) >>> 9) << 4) + 14] = len; var i, olda, oldb, oldc, oldd, a = 1732584193, b = -271733879, c = -1732584194, d = 271733878; for (i = 0; i < x.length; i += 16) { olda = a; oldb = b; oldc = c; oldd = d; a = md5_ff(a, b, c, d, x[i], 7, -680876936); d = md5_ff(d, a, b, c, x[i + 1], 12, -389564586); c = md5_ff(c, d, a, b, x[i + 2], 17, 606105819); b = md5_ff(b, c, d, a, x[i + 3], 22, -1044525330); a = md5_ff(a, b, c, d, x[i + 4], 7, -176418897); d = md5_ff(d, a, b, c, x[i + 5], 12, 1200080426); c = md5_ff(c, d, a, b, x[i + 6], 17, -1473231341); b = md5_ff(b, c, d, a, x[i + 7], 22, -45705983); a = md5_ff(a, b, c, d, x[i + 8], 7, 1770035416); d = md5_ff(d, a, b, c, x[i + 9], 12, -1958414417); c = md5_ff(c, d, a, b, x[i + 10], 17, -42063); b = md5_ff(b, c, d, a, x[i + 11], 22, -1990404162); a = md5_ff(a, b, c, d, x[i + 12], 7, 1804603682); d = md5_ff(d, a, b, c, x[i + 13], 12, -40341101); c = md5_ff(c, d, a, b, x[i + 14], 17, -1502002290); b = md5_ff(b, c, d, a, x[i + 15], 22, 1236535329); a = md5_gg(a, b, c, d, x[i + 1], 5, -165796510); d = md5_gg(d, a, b, c, x[i + 6], 9, -1069501632); c = md5_gg(c, d, a, b, x[i + 11], 14, 643717713); b = md5_gg(b, c, d, a, x[i], 20, -373897302); a = md5_gg(a, b, c, d, x[i + 5], 5, -701558691); d = md5_gg(d, a, b, c, x[i + 10], 9, 38016083); c = md5_gg(c, d, a, b, x[i + 15], 14, -660478335); b = md5_gg(b, c, d, a, x[i + 4], 20, -405537848); a = md5_gg(a, b, c, d, x[i + 9], 5, 568446438); d = md5_gg(d, a, b, c, x[i + 14], 9, -1019803690); c = md5_gg(c, d, a, b, x[i + 3], 14, -187363961); b = md5_gg(b, c, d, a, x[i + 8], 20, 1163531501); a = md5_gg(a, b, c, d, x[i + 13], 5, -1444681467); d = md5_gg(d, a, b, c, x[i + 2], 9, -51403784); c = md5_gg(c, d, a, b, x[i + 7], 14, 1735328473); b = md5_gg(b, c, d, a, x[i + 12], 20, -1926607734); a = md5_hh(a, b, c, d, x[i + 5], 4, -378558); d = md5_hh(d, a, b, c, x[i + 8], 11, -2022574463); c = md5_hh(c, d, a, b, x[i + 11], 16, 1839030562); b = md5_hh(b, c, d, a, x[i + 14], 23, -35309556); a = md5_hh(a, b, c, d, x[i + 1], 4, -1530992060); d = md5_hh(d, a, b, c, x[i + 4], 11, 1272893353); c = md5_hh(c, d, a, b, x[i + 7], 16, -155497632); b = md5_hh(b, c, d, a, x[i + 10], 23, -1094730640); a = md5_hh(a, b, c, d, x[i + 13], 4, 681279174); d = md5_hh(d, a, b, c, x[i], 11, -358537222); c = md5_hh(c, d, a, b, x[i + 3], 16, -722521979); b = md5_hh(b, c, d, a, x[i + 6], 23, 76029189); a = md5_hh(a, b, c, d, x[i + 9], 4, -640364487); d = md5_hh(d, a, b, c, x[i + 12], 11, -421815835); c = md5_hh(c, d, a, b, x[i + 15], 16, 530742520); b = md5_hh(b, c, d, a, x[i + 2], 23, -995338651); a = md5_ii(a, b, c, d, x[i], 6, -198630844); d = md5_ii(d, a, b, c, x[i + 7], 10, 1126891415); c = md5_ii(c, d, a, b, x[i + 14], 15, -1416354905); b = md5_ii(b, c, d, a, x[i + 5], 21, -57434055); a = md5_ii(a, b, c, d, x[i + 12], 6, 1700485571); d = md5_ii(d, a, b, c, x[i + 3], 10, -1894986606); c = md5_ii(c, d, a, b, x[i + 10], 15, -1051523); b = md5_ii(b, c, d, a, x[i + 1], 21, -2054922799); a = md5_ii(a, b, c, d, x[i + 8], 6, 1873313359); d = md5_ii(d, a, b, c, x[i + 15], 10, -30611744); c = md5_ii(c, d, a, b, x[i + 6], 15, -1560198380); b = md5_ii(b, c, d, a, x[i + 13], 21, 1309151649); a = md5_ii(a, b, c, d, x[i + 4], 6, -145523070); d = md5_ii(d, a, b, c, x[i + 11], 10, -1120210379); c = md5_ii(c, d, a, b, x[i + 2], 15, 718787259); b = md5_ii(b, c, d, a, x[i + 9], 21, -343485551); a = safe_add(a, olda); b = safe_add(b, oldb); c = safe_add(c, oldc); d = safe_add(d, oldd); } return [a, b, c, d]; } /* * Convert an array of little-endian words to a string */ function binl2rstr(input) { var i, output = ''; for (i = 0; i < input.length * 32; i += 8) { output += String.fromCharCode((input[i >> 5] >>> (i % 32)) & 0xFF); } return output; } /* * Convert a raw string to an array of little-endian words * Characters >255 have their high-byte silently ignored. */ function rstr2binl(input) { var i, output = []; output[(input.length >> 2) - 1] = undefined; for (i = 0; i < output.length; i += 1) { output[i] = 0; } for (i = 0; i < input.length * 8; i += 8) { output[i >> 5] |= (input.charCodeAt(i / 8) & 0xFF) << (i % 32); } return output; } /* * Calculate the MD5 of a raw string */ function rstr_md5(s) { return binl2rstr(binl_md5(rstr2binl(s), s.length * 8)); } /* * Calculate the HMAC-MD5, of a key and some data (raw strings) */ function rstr_hmac_md5(key, data) { var i, bkey = rstr2binl(key), ipad = [], opad = [], hash; ipad[15] = opad[15] = undefined; if (bkey.length > 16) { bkey = binl_md5(bkey, key.length * 8); } for (i = 0; i < 16; i += 1) { ipad[i] = bkey[i] ^ 0x36363636; opad[i] = bkey[i] ^ 0x5C5C5C5C; } hash = binl_md5(ipad.concat(rstr2binl(data)), 512 + data.length * 8); return binl2rstr(binl_md5(opad.concat(hash), 512 + 128)); } /* * Convert a raw string to a hex string */ function rstr2hex(input) { var hex_tab = '0123456789abcdef', output = '', x, i; for (i = 0; i < input.length; i += 1) { x = input.charCodeAt(i); output += hex_tab.charAt((x >>> 4) & 0x0F) + hex_tab.charAt(x & 0x0F); } return output; } /* * Encode a string as utf-8 */ function str2rstr_utf8(input) { return unescape(encodeURIComponent(input)); } /* * Take string arguments and return either raw or hex encoded strings */ function raw_md5(s) { return rstr_md5(str2rstr_utf8(s)); } function hex_md5(s) { return rstr2hex(raw_md5(s)); } function raw_hmac_md5(k, d) { return rstr_hmac_md5(str2rstr_utf8(k), str2rstr_utf8(d)); } function hex_hmac_md5(k, d) { return rstr2hex(raw_hmac_md5(k, d)); } function md5(string, key, raw) { if (!key) { if (!raw) { return hex_md5(string); } return raw_md5(string); } if (!raw) { return hex_hmac_md5(key, string); } return raw_hmac_md5(key, string); } return md5; }()); var RongIMLib; (function (RongIMLib) { (function (MentionedType) { MentionedType[MentionedType["ALL"] = 1] = "ALL"; MentionedType[MentionedType["PART"] = 2] = "PART"; })(RongIMLib.MentionedType || (RongIMLib.MentionedType = {})); var MentionedType = RongIMLib.MentionedType; (function (MethodType) { MethodType[MethodType["CUSTOMER_SERVICE"] = 1] = "CUSTOMER_SERVICE"; MethodType[MethodType["RECALL"] = 2] = "RECALL"; })(RongIMLib.MethodType || (RongIMLib.MethodType = {})); var MethodType = RongIMLib.MethodType; (function (BlacklistStatus) { /** * 在黑名单中。 */ BlacklistStatus[BlacklistStatus["IN_BLACK_LIST"] = 0] = "IN_BLACK_LIST"; /** * 不在黑名单中。 */ BlacklistStatus[BlacklistStatus["NOT_IN_BLACK_LIST"] = 1] = "NOT_IN_BLACK_LIST"; })(RongIMLib.BlacklistStatus || (RongIMLib.BlacklistStatus = {})); var BlacklistStatus = RongIMLib.BlacklistStatus; (function (ConnectionChannel) { ConnectionChannel[ConnectionChannel["XHR_POLLING"] = 0] = "XHR_POLLING"; ConnectionChannel[ConnectionChannel["WEBSOCKET"] = 1] = "WEBSOCKET"; //外部调用 ConnectionChannel[ConnectionChannel["HTTP"] = 0] = "HTTP"; //外部调用 ConnectionChannel[ConnectionChannel["HTTPS"] = 1] = "HTTPS"; })(RongIMLib.ConnectionChannel || (RongIMLib.ConnectionChannel = {})); var ConnectionChannel = RongIMLib.ConnectionChannel; (function (CustomerType) { CustomerType[CustomerType["ONLY_ROBOT"] = 1] = "ONLY_ROBOT"; CustomerType[CustomerType["ONLY_HUMAN"] = 2] = "ONLY_HUMAN"; CustomerType[CustomerType["ROBOT_FIRST"] = 3] = "ROBOT_FIRST"; CustomerType[CustomerType["HUMAN_FIRST"] = 4] = "HUMAN_FIRST"; })(RongIMLib.CustomerType || (RongIMLib.CustomerType = {})); var CustomerType = RongIMLib.CustomerType; (function (GetChatRoomType) { GetChatRoomType[GetChatRoomType["NONE"] = 0] = "NONE"; GetChatRoomType[GetChatRoomType["SQQUENCE"] = 1] = "SQQUENCE"; GetChatRoomType[GetChatRoomType["REVERSE"] = 2] = "REVERSE"; })(RongIMLib.GetChatRoomType || (RongIMLib.GetChatRoomType = {})); var GetChatRoomType = RongIMLib.GetChatRoomType; (function (ConnectionStatus) { /** * 连接成功。 */ ConnectionStatus[ConnectionStatus["CONNECTED"] = 0] = "CONNECTED"; /** * 连接中。 */ ConnectionStatus[ConnectionStatus["CONNECTING"] = 1] = "CONNECTING"; /** * 断开连接。 */ ConnectionStatus[ConnectionStatus["DISCONNECTED"] = 2] = "DISCONNECTED"; /** * 用户账户在其他设备登录,本机会被踢掉线。 */ ConnectionStatus[ConnectionStatus["KICKED_OFFLINE_BY_OTHER_CLIENT"] = 6] = "KICKED_OFFLINE_BY_OTHER_CLIENT"; /** * 网络不可用。 */ ConnectionStatus[ConnectionStatus["NETWORK_UNAVAILABLE"] = 3] = "NETWORK_UNAVAILABLE"; /** * 域名错误 */ ConnectionStatus[ConnectionStatus["DOMAIN_INCORRECT"] = 12] = "DOMAIN_INCORRECT"; /** * 连接关闭。 */ ConnectionStatus[ConnectionStatus["CONNECTION_CLOSED"] = 4] = "CONNECTION_CLOSED"; /* 互踢次数过多(count > 5),此时可能出现:在其它他设备登陆有 reconnect 逻辑 */ ConnectionStatus[ConnectionStatus["ULTRALIMIT"] = 1101] = "ULTRALIMIT"; })(RongIMLib.ConnectionStatus || (RongIMLib.ConnectionStatus = {})); var ConnectionStatus = RongIMLib.ConnectionStatus; (function (ConversationNotificationStatus) { /** * 免打扰状态,关闭对应会话的通知提醒。 */ ConversationNotificationStatus[ConversationNotificationStatus["DO_NOT_DISTURB"] = 0] = "DO_NOT_DISTURB"; /** * 提醒。 */ ConversationNotificationStatus[ConversationNotificationStatus["NOTIFY"] = 1] = "NOTIFY"; })(RongIMLib.ConversationNotificationStatus || (RongIMLib.ConversationNotificationStatus = {})); var ConversationNotificationStatus = RongIMLib.ConversationNotificationStatus; (function (ConversationType) { ConversationType[ConversationType["NONE"] = 0] = "NONE"; ConversationType[ConversationType["PRIVATE"] = 1] = "PRIVATE"; ConversationType[ConversationType["DISCUSSION"] = 2] = "DISCUSSION"; ConversationType[ConversationType["GROUP"] = 3] = "GROUP"; ConversationType[ConversationType["CHATROOM"] = 4] = "CHATROOM"; ConversationType[ConversationType["CUSTOMER_SERVICE"] = 5] = "CUSTOMER_SERVICE"; ConversationType[ConversationType["SYSTEM"] = 6] = "SYSTEM"; //默认关注 MC ConversationType[ConversationType["APP_PUBLIC_SERVICE"] = 7] = "APP_PUBLIC_SERVICE"; //手工关注 MP ConversationType[ConversationType["PUBLIC_SERVICE"] = 8] = "PUBLIC_SERVICE"; })(RongIMLib.ConversationType || (RongIMLib.ConversationType = {})); var ConversationType = RongIMLib.ConversationType; (function (DiscussionInviteStatus) { /** * 开放邀请。 */ DiscussionInviteStatus[DiscussionInviteStatus["OPENED"] = 0] = "OPENED"; /** * 关闭邀请。 */ DiscussionInviteStatus[DiscussionInviteStatus["CLOSED"] = 1] = "CLOSED"; })(RongIMLib.DiscussionInviteStatus || (RongIMLib.DiscussionInviteStatus = {})); var DiscussionInviteStatus = RongIMLib.DiscussionInviteStatus; (function (ErrorCode) { ErrorCode[ErrorCode["RECALL_MESSAGE"] = 25101] = "RECALL_MESSAGE"; /** * 发送频率过快 */ ErrorCode[ErrorCode["SEND_FREQUENCY_TOO_FAST"] = 20604] = "SEND_FREQUENCY_TOO_FAST"; ErrorCode[ErrorCode["RC_MSG_UNAUTHORIZED"] = 20406] = "RC_MSG_UNAUTHORIZED"; /** * 群组 Id 无效 */ ErrorCode[ErrorCode["RC_DISCUSSION_GROUP_ID_INVALID"] = 20407] = "RC_DISCUSSION_GROUP_ID_INVALID"; /** * 群组被禁言 */ ErrorCode[ErrorCode["FORBIDDEN_IN_GROUP"] = 22408] = "FORBIDDEN_IN_GROUP"; /** * 不在讨论组。 */ ErrorCode[ErrorCode["NOT_IN_DISCUSSION"] = 21406] = "NOT_IN_DISCUSSION"; /** * 不在群组。 */ ErrorCode[ErrorCode["NOT_IN_GROUP"] = 22406] = "NOT_IN_GROUP"; /** * 不在聊天室。 */ ErrorCode[ErrorCode["NOT_IN_CHATROOM"] = 23406] = "NOT_IN_CHATROOM"; /** *聊天室被禁言 */ ErrorCode[ErrorCode["FORBIDDEN_IN_CHATROOM"] = 23408] = "FORBIDDEN_IN_CHATROOM"; /** * 聊天室中成员被踢出 */ ErrorCode[ErrorCode["RC_CHATROOM_USER_KICKED"] = 23409] = "RC_CHATROOM_USER_KICKED"; /** * 聊天室不存在 */ ErrorCode[ErrorCode["RC_CHATROOM_NOT_EXIST"] = 23410] = "RC_CHATROOM_NOT_EXIST"; /** * 聊天室成员已满 */ ErrorCode[ErrorCode["RC_CHATROOM_IS_FULL"] = 23411] = "RC_CHATROOM_IS_FULL"; /** * 获取聊天室信息参数无效 */ ErrorCode[ErrorCode["RC_CHATROOM_PATAMETER_INVALID"] = 23412] = "RC_CHATROOM_PATAMETER_INVALID"; /** * 聊天室异常 */ ErrorCode[ErrorCode["CHATROOM_GET_HISTORYMSG_ERROR"] = 23413] = "CHATROOM_GET_HISTORYMSG_ERROR"; /** * 没有打开聊天室消息存储 */ ErrorCode[ErrorCode["CHATROOM_NOT_OPEN_HISTORYMSG_STORE"] = 23414] = "CHATROOM_NOT_OPEN_HISTORYMSG_STORE"; ErrorCode[ErrorCode["TIMEOUT"] = -1] = "TIMEOUT"; /** * 未知原因失败。 */ ErrorCode[ErrorCode["UNKNOWN"] = -2] = "UNKNOWN"; /** * 加入讨论失败 */ ErrorCode[ErrorCode["JOIN_IN_DISCUSSION"] = 21407] = "JOIN_IN_DISCUSSION"; /** * 创建讨论组失败 */ ErrorCode[ErrorCode["CREATE_DISCUSSION"] = 21408] = "CREATE_DISCUSSION"; /** * 设置讨论组邀请状态失败 */ ErrorCode[ErrorCode["INVITE_DICUSSION"] = 21409] = "INVITE_DICUSSION"; /** *获取用户失败 */ ErrorCode[ErrorCode["GET_USERINFO_ERROR"] = 23407] = "GET_USERINFO_ERROR"; /** * 在黑名单中。 */ ErrorCode[ErrorCode["REJECTED_BY_BLACKLIST"] = 405] = "REJECTED_BY_BLACKLIST"; /** * 通信过程中,当前 Socket 不存在。 */ ErrorCode[ErrorCode["RC_NET_CHANNEL_INVALID"] = 30001] = "RC_NET_CHANNEL_INVALID"; /** * Socket 连接不可用。 */ ErrorCode[ErrorCode["RC_NET_UNAVAILABLE"] = 30002] = "RC_NET_UNAVAILABLE"; /** * 通信超时。 */ ErrorCode[ErrorCode["RC_MSG_RESP_TIMEOUT"] = 30003] = "RC_MSG_RESP_TIMEOUT"; /** * 导航操作时,Http 请求失败。 */ ErrorCode[ErrorCode["RC_HTTP_SEND_FAIL"] = 30004] = "RC_HTTP_SEND_FAIL"; /** * HTTP 请求失败。 */ ErrorCode[ErrorCode["RC_HTTP_REQ_TIMEOUT"] = 30005] = "RC_HTTP_REQ_TIMEOUT"; /** * HTTP 接收失败。 */ ErrorCode[ErrorCode["RC_HTTP_RECV_FAIL"] = 30006] = "RC_HTTP_RECV_FAIL"; /** * 导航操作的 HTTP 请求,返回不是200。 */ ErrorCode[ErrorCode["RC_NAVI_RESOURCE_ERROR"] = 30007] = "RC_NAVI_RESOURCE_ERROR"; /** * 导航数据解析后,其中不存在有效数据。 */ ErrorCode[ErrorCode["RC_NODE_NOT_FOUND"] = 30008] = "RC_NODE_NOT_FOUND"; /** * 导航数据解析后,其中不存在有效 IP 地址。 */ ErrorCode[ErrorCode["RC_DOMAIN_NOT_RESOLVE"] = 30009] = "RC_DOMAIN_NOT_RESOLVE"; /** * 创建 Socket 失败。 */ ErrorCode[ErrorCode["RC_SOCKET_NOT_CREATED"] = 30010] = "RC_SOCKET_NOT_CREATED"; /** * Socket 被断开。 */ ErrorCode[ErrorCode["RC_SOCKET_DISCONNECTED"] = 30011] = "RC_SOCKET_DISCONNECTED"; /** * PING 操作失败。 */ ErrorCode[ErrorCode["RC_PING_SEND_FAIL"] = 30012] = "RC_PING_SEND_FAIL"; /** * PING 超时。 */ ErrorCode[ErrorCode["RC_PONG_RECV_FAIL"] = 30013] = "RC_PONG_RECV_FAIL"; /** * 消息发送失败。 */ ErrorCode[ErrorCode["RC_MSG_SEND_FAIL"] = 30014] = "RC_MSG_SEND_FAIL"; /** * 做 connect 连接时,收到的 ACK 超时。 */ ErrorCode[ErrorCode["RC_CONN_ACK_TIMEOUT"] = 31000] = "RC_CONN_ACK_TIMEOUT"; /** * 参数错误。 */ ErrorCode[ErrorCode["RC_CONN_PROTO_VERSION_ERROR"] = 31001] = "RC_CONN_PROTO_VERSION_ERROR"; /** * 参数错误,App Id 错误。 */ ErrorCode[ErrorCode["RC_CONN_ID_REJECT"] = 31002] = "RC_CONN_ID_REJECT"; /** * 服务器不可用。 */ ErrorCode[ErrorCode["RC_CONN_SERVER_UNAVAILABLE"] = 31003] = "RC_CONN_SERVER_UNAVAILABLE"; /** * Token 错误。 */ ErrorCode[ErrorCode["RC_CONN_USER_OR_PASSWD_ERROR"] = 31004] = "RC_CONN_USER_OR_PASSWD_ERROR"; /** * App Id 与 Token 不匹配。 */ ErrorCode[ErrorCode["RC_CONN_NOT_AUTHRORIZED"] = 31005] = "RC_CONN_NOT_AUTHRORIZED"; /** * 重定向,地址错误。 */ ErrorCode[ErrorCode["RC_CONN_REDIRECTED"] = 31006] = "RC_CONN_REDIRECTED"; /** * NAME 与后台注册信息不一致。 */ ErrorCode[ErrorCode["RC_CONN_PACKAGE_NAME_INVALID"] = 31007] = "RC_CONN_PACKAGE_NAME_INVALID"; /** * APP 被屏蔽、删除或不存在。 */ ErrorCode[ErrorCode["RC_CONN_APP_BLOCKED_OR_DELETED"] = 31008] = "RC_CONN_APP_BLOCKED_OR_DELETED"; /** * 用户被屏蔽。 */ ErrorCode[ErrorCode["RC_CONN_USER_BLOCKED"] = 31009] = "RC_CONN_USER_BLOCKED"; /** * Disconnect,由服务器返回,比如用户互踢。 */ ErrorCode[ErrorCode["RC_DISCONN_KICK"] = 31010] = "RC_DISCONN_KICK"; /** * Disconnect,由服务器返回,比如用户互踢。 */ ErrorCode[ErrorCode["RC_DISCONN_EXCEPTION"] = 31011] = "RC_DISCONN_EXCEPTION"; /** * 协议层内部错误。query,上传下载过程中数据错误。 */ ErrorCode[ErrorCode["RC_QUERY_ACK_NO_DATA"] = 32001] = "RC_QUERY_ACK_NO_DATA"; /** * 协议层内部错误。 */ ErrorCode[ErrorCode["RC_MSG_DATA_INCOMPLETE"] = 32002] = "RC_MSG_DATA_INCOMPLETE"; /** * 未调用 init 初始化函数。 */ ErrorCode[ErrorCode["BIZ_ERROR_CLIENT_NOT_INIT"] = 33001] = "BIZ_ERROR_CLIENT_NOT_INIT"; /** * 数据库初始化失败。 */ ErrorCode[ErrorCode["BIZ_ERROR_DATABASE_ERROR"] = 33002] = "BIZ_ERROR_DATABASE_ERROR"; /** * 传入参数无效。 */ ErrorCode[ErrorCode["BIZ_ERROR_INVALID_PARAMETER"] = 33003] = "BIZ_ERROR_INVALID_PARAMETER"; /** * 通道无效。 */ ErrorCode[ErrorCode["BIZ_ERROR_NO_CHANNEL"] = 33004] = "BIZ_ERROR_NO_CHANNEL"; /** * 重新连接成功。 */ ErrorCode[ErrorCode["BIZ_ERROR_RECONNECT_SUCCESS"] = 33005] = "BIZ_ERROR_RECONNECT_SUCCESS"; /** * 连接中,再调用 connect 被拒绝。 */ ErrorCode[ErrorCode["BIZ_ERROR_CONNECTING"] = 33006] = "BIZ_ERROR_CONNECTING"; /** * 消息漫游服务未开通 */ ErrorCode[ErrorCode["MSG_ROAMING_SERVICE_UNAVAILABLE"] = 33007] = "MSG_ROAMING_SERVICE_UNAVAILABLE"; ErrorCode[ErrorCode["MSG_INSERT_ERROR"] = 33008] = "MSG_INSERT_ERROR"; ErrorCode[ErrorCode["MSG_DEL_ERROR"] = 33009] = "MSG_DEL_ERROR"; /** * 删除会话失败 */ ErrorCode[ErrorCode["CONVER_REMOVE_ERROR"] = 34001] = "CONVER_REMOVE_ERROR"; /** *拉取历史消息 */ ErrorCode[ErrorCode["CONVER_GETLIST_ERROR"] = 34002] = "CONVER_GETLIST_ERROR"; /** * 会话指定异常 */ ErrorCode[ErrorCode["CONVER_SETOP_ERROR"] = 34003] = "CONVER_SETOP_ERROR"; /** * 获取会话未读消息总数失败 */ ErrorCode[ErrorCode["CONVER_TOTAL_UNREAD_ERROR"] = 34004] = "CONVER_TOTAL_UNREAD_ERROR"; /** * 获取指定会话类型未读消息数异常 */ ErrorCode[ErrorCode["CONVER_TYPE_UNREAD_ERROR"] = 34005] = "CONVER_TYPE_UNREAD_ERROR"; /** * 获取指定用户ID&会话类型未读消息数异常 */ ErrorCode[ErrorCode["CONVER_ID_TYPE_UNREAD_ERROR"] = 34006] = "CONVER_ID_TYPE_UNREAD_ERROR"; ErrorCode[ErrorCode["CONVER_CLEAR_ERROR"] = 34007] = "CONVER_CLEAR_ERROR"; ErrorCode[ErrorCode["CLEAR_HIS_ERROR"] = 34010] = "CLEAR_HIS_ERROR"; ErrorCode[ErrorCode["CLEAR_HIS_TYPE_ERROR"] = 34008] = "CLEAR_HIS_TYPE_ERROR"; ErrorCode[ErrorCode["CLEAR_HIS_TIME_ERROR"] = 34011] = "CLEAR_HIS_TIME_ERROR"; /* */ ErrorCode[ErrorCode["CONVER_GET_ERROR"] = 34009] = "CONVER_GET_ERROR"; //群组异常信息 /** * */ ErrorCode[ErrorCode["GROUP_SYNC_ERROR"] = 35001] = "GROUP_SYNC_ERROR"; /** * 匹配群信息异常 */ ErrorCode[ErrorCode["GROUP_MATCH_ERROR"] = 35002] = "GROUP_MATCH_ERROR"; //聊天室异常 /** * 加入聊天室Id为空 */ ErrorCode[ErrorCode["CHATROOM_ID_ISNULL"] = 36001] = "CHATROOM_ID_ISNULL"; /** * 加入聊天室失败 */ ErrorCode[ErrorCode["CHARTOOM_JOIN_ERROR"] = 36002] = "CHARTOOM_JOIN_ERROR"; /** * 拉取聊天室历史消息失败 */ ErrorCode[ErrorCode["CHATROOM_HISMESSAGE_ERROR"] = 36003] = "CHATROOM_HISMESSAGE_ERROR"; //黑名单异常 /** * 加入黑名单异常 */ ErrorCode[ErrorCode["BLACK_ADD_ERROR"] = 37001] = "BLACK_ADD_ERROR"; /** * 获得指定人员再黑名单中的状态异常 */ ErrorCode[ErrorCode["BLACK_GETSTATUS_ERROR"] = 37002] = "BLACK_GETSTATUS_ERROR"; /** * 移除黑名单异常 */ ErrorCode[ErrorCode["BLACK_REMOVE_ERROR"] = 37003] = "BLACK_REMOVE_ERROR"; /** * 获取草稿失败 */ ErrorCode[ErrorCode["DRAF_GET_ERROR"] = 38001] = "DRAF_GET_ERROR"; /** * 保存草稿失败 */ ErrorCode[ErrorCode["DRAF_SAVE_ERROR"] = 38002] = "DRAF_SAVE_ERROR"; /** * 删除草稿失败 */ ErrorCode[ErrorCode["DRAF_REMOVE_ERROR"] = 38003] = "DRAF_REMOVE_ERROR"; /** * 关注公众号失败 */ ErrorCode[ErrorCode["SUBSCRIBE_ERROR"] = 39001] = "SUBSCRIBE_ERROR"; /** * 关注公众号失败 */ ErrorCode[ErrorCode["QNTKN_FILETYPE_ERROR"] = 41001] = "QNTKN_FILETYPE_ERROR"; /** * 获取七牛token失败 */ ErrorCode[ErrorCode["QNTKN_GET_ERROR"] = 41002] = "QNTKN_GET_ERROR"; /** * cookie被禁用 */ ErrorCode[ErrorCode["COOKIE_ENABLE"] = 51001] = "COOKIE_ENABLE"; ErrorCode[ErrorCode["GET_MESSAGE_BY_ID_ERROR"] = 61001] = "GET_MESSAGE_BY_ID_ERROR"; // 没有注册DeviveId 也就是用户没有登陆 ErrorCode[ErrorCode["HAVNODEVICEID"] = 24001] = "HAVNODEVICEID"; // 已经存在 ErrorCode[ErrorCode["DEVICEIDISHAVE"] = 24002] = "DEVICEIDISHAVE"; // 成功 ErrorCode[ErrorCode["SUCCESS"] = 0] = "SUCCESS"; // 没有对应的用户或token ErrorCode[ErrorCode["FEILD"] = 24009] = "FEILD"; // voip为空 ErrorCode[ErrorCode["VOIPISNULL"] = 24013] = "VOIPISNULL"; // 不支持的Voip引擎 ErrorCode[ErrorCode["NOENGINETYPE"] = 24010] = "NOENGINETYPE"; // channleName 是空 ErrorCode[ErrorCode["NULLCHANNELNAME"] = 24011] = "NULLCHANNELNAME"; // 生成Voipkey失败 ErrorCode[ErrorCode["VOIPDYANMICERROR"] = 24012] = "VOIPDYANMICERROR"; // 没有配置voip ErrorCode[ErrorCode["NOVOIP"] = 24014] = "NOVOIP"; // 服务器内部错误 ErrorCode[ErrorCode["INTERNALERRROR"] = 24015] = "INTERNALERRROR"; //VOIP close ErrorCode[ErrorCode["VOIPCLOSE"] = 24016] = "VOIPCLOSE"; ErrorCode[ErrorCode["CLOSE_BEFORE_OPEN"] = 51001] = "CLOSE_BEFORE_OPEN"; ErrorCode[ErrorCode["ALREADY_IN_USE"] = 51002] = "ALREADY_IN_USE"; ErrorCode[ErrorCode["INVALID_CHANNEL_NAME"] = 51003] = "INVALID_CHANNEL_NAME"; ErrorCode[ErrorCode["VIDEO_CONTAINER_IS_NULL"] = 51004] = "VIDEO_CONTAINER_IS_NULL"; /** * 删除消息数组长度为 0 . */ ErrorCode[ErrorCode["DELETE_MESSAGE_ID_IS_NULL"] = 61001] = "DELETE_MESSAGE_ID_IS_NULL"; /*! 己方取消已发出的通话请求 */ ErrorCode[ErrorCode["CANCEL"] = 1] = "CANCEL"; /*! 己方拒绝收到的通话请求 */ ErrorCode[ErrorCode["REJECT"] = 2] = "REJECT"; /*! 己方挂断 */ ErrorCode[ErrorCode["HANGUP"] = 3] = "HANGUP"; /*! 己方忙碌 */ ErrorCode[ErrorCode["BUSYLINE"] = 4] = "BUSYLINE"; /*! 己方未接听 */ ErrorCode[ErrorCode["NO_RESPONSE"] = 5] = "NO_RESPONSE"; /*! 己方不支持当前引擎 */ ErrorCode[ErrorCode["ENGINE_UN_SUPPORTED"] = 6] = "ENGINE_UN_SUPPORTED"; /*! 己方网络出错 */ ErrorCode[ErrorCode["NETWORK_ERROR"] = 7] = "NETWORK_ERROR"; /*! 对方取消已发出的通话请求 */ ErrorCode[ErrorCode["REMOTE_CANCEL"] = 11] = "REMOTE_CANCEL"; /*! 对方拒绝收到的通话请求 */ ErrorCode[ErrorCode["REMOTE_REJECT"] = 12] = "REMOTE_REJECT"; /*! 通话过程对方挂断 */ ErrorCode[ErrorCode["REMOTE_HANGUP"] = 13] = "REMOTE_HANGUP"; /*! 对方忙碌 */ ErrorCode[ErrorCode["REMOTE_BUSYLINE"] = 14] = "REMOTE_BUSYLINE"; /*! 对方未接听 */ ErrorCode[ErrorCode["REMOTE_NO_RESPONSE"] = 15] = "REMOTE_NO_RESPONSE"; /*! 对方网络错误 */ ErrorCode[ErrorCode["REMOTE_ENGINE_UN_SUPPORTED"] = 16] = "REMOTE_ENGINE_UN_SUPPORTED"; /*! 对方网络错误 */ ErrorCode[ErrorCode["REMOTE_NETWORK_ERROR"] = 17] = "REMOTE_NETWORK_ERROR"; /*! VoIP 不可用 */ ErrorCode[ErrorCode["VOIP_NOT_AVALIABLE"] = 18] = "VOIP_NOT_AVALIABLE"; })(RongIMLib.ErrorCode || (RongIMLib.ErrorCode = {})); var ErrorCode = RongIMLib.ErrorCode; (function (VoIPMediaType) { VoIPMediaType[VoIPMediaType["MEDIA_AUDIO"] = 1] = "MEDIA_AUDIO"; VoIPMediaType[VoIPMediaType["MEDIA_VEDIO"] = 2] = "MEDIA_VEDIO"; })(RongIMLib.VoIPMediaType || (RongIMLib.VoIPMediaType = {})); var VoIPMediaType = RongIMLib.VoIPMediaType; (function (MediaType) { /** * 图片。 */ MediaType[MediaType["IMAGE"] = 1] = "IMAGE"; /** * 声音。 */ MediaType[MediaType["AUDIO"] = 2] = "AUDIO"; /** * 视频。 */ MediaType[MediaType["VIDEO"] = 3] = "VIDEO"; /** * 通用文件。 */ MediaType[MediaType["FILE"] = 100] = "FILE"; })(RongIMLib.MediaType || (RongIMLib.MediaType = {})); var MediaType = RongIMLib.MediaType; (function (MessageDirection) { /** * 发送消息。 */ MessageDirection[MessageDirection["SEND"] = 1] = "SEND"; /** * 接收消息。 */ MessageDirection[MessageDirection["RECEIVE"] = 2] = "RECEIVE"; })(RongIMLib.MessageDirection || (RongIMLib.MessageDirection = {})); var MessageDirection = RongIMLib.MessageDirection; (function (FileType) { FileType[FileType["IMAGE"] = 1] = "IMAGE"; FileType[FileType["AUDIO"] = 2] = "AUDIO"; FileType[FileType["VIDEO"] = 3] = "VIDEO"; FileType[FileType["FILE"] = 4] = "FILE"; })(RongIMLib.FileType || (RongIMLib.FileType = {})); var FileType = RongIMLib.FileType; (function (RealTimeLocationErrorCode) { /** * 未初始化 RealTimeLocation 实例 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_NOT_INIT"] = -1] = "RC_REAL_TIME_LOCATION_NOT_INIT"; /** * 执行成功。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_SUCCESS"] = 0] = "RC_REAL_TIME_LOCATION_SUCCESS"; /** * 获取 RealTimeLocation 实例时返回 * GPS 未打开。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_GPS_DISABLED"] = 1] = "RC_REAL_TIME_LOCATION_GPS_DISABLED"; /** * 获取 RealTimeLocation 实例时返回 * 当前会话不支持位置共享。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_CONVERSATION_NOT_SUPPORT"] = 2] = "RC_REAL_TIME_LOCATION_CONVERSATION_NOT_SUPPORT"; /** * 获取 RealTimeLocation 实例时返回 * 对方已发起位置共享。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_IS_ON_GOING"] = 3] = "RC_REAL_TIME_LOCATION_IS_ON_GOING"; /** * Join 时返回 * 当前位置共享已超过最大支持人数。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_EXCEED_MAX_PARTICIPANT"] = 4] = "RC_REAL_TIME_LOCATION_EXCEED_MAX_PARTICIPANT"; /** * Join 时返回 * 加入位置共享失败。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_JOIN_FAILURE"] = 5] = "RC_REAL_TIME_LOCATION_JOIN_FAILURE"; /** * Start 时返回 * 发起位置共享失败。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_START_FAILURE"] = 6] = "RC_REAL_TIME_LOCATION_START_FAILURE"; /** * 网络不可用。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_NETWORK_UNAVAILABLE"] = 7] = "RC_REAL_TIME_LOCATION_NETWORK_UNAVAILABLE"; })(RongIMLib.RealTimeLocationErrorCode || (RongIMLib.RealTimeLocationErrorCode = {})); var RealTimeLocationErrorCode = RongIMLib.RealTimeLocationErrorCode; (function (RealTimeLocationStatus) { /** * 空闲状态 (默认状态) * 对方或者自己都未发起位置共享业务,或者位置共享业务已结束。 */ RealTimeLocationStatus[RealTimeLocationStatus["RC_REAL_TIME_LOCATION_STATUS_IDLE"] = 0] = "RC_REAL_TIME_LOCATION_STATUS_IDLE"; /** * 呼入状态 (待加入) * 1. 对方发起了位置共享业务,此状态下,自己只能选择加入。 * 2. 自己从已连接的位置共享中退出。 */ RealTimeLocationStatus[RealTimeLocationStatus["RC_REAL_TIME_LOCATION_STATUS_INCOMING"] = 1] = "RC_REAL_TIME_LOCATION_STATUS_INCOMING"; /** * 呼出状态 =(自己创建) * 1. 自己发起位置共享业务,对方只能选择加入。 * 2. 对方从已连接的位置共享业务中退出。 */ RealTimeLocationStatus[RealTimeLocationStatus["RC_REAL_TIME_LOCATION_STATUS_OUTGOING"] = 2] = "RC_REAL_TIME_LOCATION_STATUS_OUTGOING"; /** * 连接状态 (自己加入) * 对方加入了自己发起的位置共享,或者自己加入了对方发起的位置共享。 */ RealTimeLocationStatus[RealTimeLocationStatus["RC_REAL_TIME_LOCATION_STATUS_CONNECTED"] = 3] = "RC_REAL_TIME_LOCATION_STATUS_CONNECTED"; })(RongIMLib.RealTimeLocationStatus || (RongIMLib.RealTimeLocationStatus = {})); var RealTimeLocationStatus = RongIMLib.RealTimeLocationStatus; (function (ReceivedStatus) { ReceivedStatus[ReceivedStatus["READ"] = 1] = "READ"; ReceivedStatus[ReceivedStatus["LISTENED"] = 2] = "LISTENED"; ReceivedStatus[ReceivedStatus["DOWNLOADED"] = 4] = "DOWNLOADED"; ReceivedStatus[ReceivedStatus["RETRIEVED"] = 8] = "RETRIEVED"; ReceivedStatus[ReceivedStatus["UNREAD"] = 0] = "UNREAD"; })(RongIMLib.ReceivedStatus || (RongIMLib.ReceivedStatus = {})); var ReceivedStatus = RongIMLib.ReceivedStatus; (function (ReadStatus) { ReadStatus[ReadStatus["READ"] = 1] = "READ"; ReadStatus[ReadStatus["LISTENED"] = 2] = "LISTENED"; ReadStatus[ReadStatus["DOWNLOADED"] = 4] = "DOWNLOADED"; ReadStatus[ReadStatus["RETRIEVED"] = 8] = "RETRIEVED"; ReadStatus[ReadStatus["UNREAD"] = 0] = "UNREAD"; })(RongIMLib.ReadStatus || (RongIMLib.ReadStatus = {})); var ReadStatus = RongIMLib.ReadStatus; (function (SearchType) { /** * 精确。 */ SearchType[SearchType["EXACT"] = 0] = "EXACT"; /** * 模糊。 */ SearchType[SearchType["FUZZY"] = 1] = "FUZZY"; })(RongIMLib.SearchType || (RongIMLib.SearchType = {})); var SearchType = RongIMLib.SearchType; (function (SentStatus) { /** * 发送中。 */ SentStatus[SentStatus["SENDING"] = 10] = "SENDING"; /** * 发送失败。 */ SentStatus[SentStatus["FAILED"] = 20] = "FAILED"; /** * 已发送。 */ SentStatus[SentStatus["SENT"] = 30] = "SENT"; /** * 对方已接收。 */ SentStatus[SentStatus["RECEIVED"] = 40] = "RECEIVED"; /** * 对方已读。 */ SentStatus[SentStatus["READ"] = 50] = "READ"; /** * 对方已销毁。 */ SentStatus[SentStatus["DESTROYED"] = 60] = "DESTROYED"; })(RongIMLib.SentStatus || (RongIMLib.SentStatus = {})); var SentStatus = RongIMLib.SentStatus; (function (ConnectionState) { ConnectionState[ConnectionState["ACCEPTED"] = 0] = "ACCEPTED"; ConnectionState[ConnectionState["UNACCEPTABLE_PROTOCOL_VERSION"] = 1] = "UNACCEPTABLE_PROTOCOL_VERSION"; ConnectionState[ConnectionState["IDENTIFIER_REJECTED"] = 2] = "IDENTIFIER_REJECTED"; ConnectionState[ConnectionState["SERVER_UNAVAILABLE"] = 3] = "SERVER_UNAVAILABLE"; /** * token无效 */ ConnectionState[ConnectionState["TOKEN_INCORRECT"] = 4] = "TOKEN_INCORRECT"; ConnectionState[ConnectionState["NOT_AUTHORIZED"] = 5] = "NOT_AUTHORIZED"; ConnectionState[ConnectionState["REDIRECT"] = 6] = "REDIRECT"; ConnectionState[ConnectionState["PACKAGE_ERROR"] = 7] = "PACKAGE_ERROR"; ConnectionState[ConnectionState["APP_BLOCK_OR_DELETE"] = 8] = "APP_BLOCK_OR_DELETE"; ConnectionState[ConnectionState["BLOCK"] = 9] = "BLOCK"; ConnectionState[ConnectionState["TOKEN_EXPIRE"] = 10] = "TOKEN_EXPIRE"; ConnectionState[ConnectionState["DEVICE_ERROR"] = 11] = "DEVICE_ERROR"; })(RongIMLib.ConnectionState || (RongIMLib.ConnectionState = {})); var ConnectionState = RongIMLib.ConnectionState; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var RongIMClient = (function () { function RongIMClient() { } RongIMClient.getInstance = function () { if (!RongIMClient._instance) { throw new Error("RongIMClient is not initialized. Call .init() method first."); } return RongIMClient._instance; }; RongIMClient.showError = function (errorInfo) { var hasConsole = (console && console.error); if (hasConsole) { console.error(JSON.stringify(errorInfo)); } }; RongIMClient.logger = function (params) { var code = params.code; var errorInfo = RongIMClient.LogFactory[code] || params; errorInfo.funcName = params.funcName; errorInfo.msg = params.msg || errorInfo.msg; if (RongIMClient._memoryStore.depend.showError) { RongIMClient.showError(errorInfo); } }; RongIMClient.logCallback = function (callback, funcName) { return { onSuccess: callback.onSuccess, onError: function (errorCode) { RongIMClient.logger({ code: errorCode, funcName: funcName }); callback.onError(errorCode); } }; }; ; RongIMClient.logSendCallback = function (callback, funcName) { return { onSuccess: callback.onSuccess, onError: function (errorCode, result) { RongIMClient.logger({ code: errorCode, funcName: funcName }); callback.onError(errorCode, result); }, onBefore: callback.onBefore }; }; ; /** * 初始化 SDK,在整个应用全局只需要调用一次。 * @param appKey 开发者后台申请的 AppKey,用来标识应用。 * @param dataAccessProvider 必须是DataAccessProvider的实例 */ RongIMClient.init = function (appKey, dataAccessProvider, options, callback) { if (RongIMClient._instance) { return RongIMClient._memoryStore.sdkInfo; } RongIMClient._instance = new RongIMClient(); options = options || {}; var protocol = "//", wsScheme = 'ws://'; var protocols = 'http:,https:'; if (protocols.indexOf(location.protocol) == -1) { protocol = 'http://'; } if (location.protocol == 'https:') { wsScheme = 'wss://'; } var isPolling = false; if (typeof WebSocket != 'function') { isPolling = true; } var isIntegrity = function () { //iOS 9 var hasWS = (typeof WebSocket); var integrity = (typeof WebSocket.OPEN == 'number'); return (hasWS && integrity); }; if (typeof WebSocket == 'object' && isIntegrity()) { isPolling = false; } var supportUserData = function () { var element = document.documentElement; return element.addBehavior; }; if (RongIMLib.RongUtil.supportLocalStorage()) { RongIMClient._storageProvider = new RongIMLib.LocalStorageProvider(); } else if (supportUserData()) { RongIMClient._storageProvider = new RongIMLib.UserDataProvider(); } else { RongIMClient._storageProvider = new RongIMLib.MemeoryProvider(); } var serverIndex = RongIMClient._storageProvider.getItem('serverIndex'); RongIMClient.serverStore.index = serverIndex || 0; var pathTmpl = '{0}{1}'; var _serverPath = { navi: 'nav.cn.ronghub.com', api: 'api.cn.ronghub.com' }; RongIMLib.RongUtil.forEach(_serverPath, function (path, key) { _serverPath[key] = RongIMLib.RongUtil.stringFormat(pathTmpl, [protocol, path]); }); RongIMLib.RongUtil.forEach(_serverPath, function (path, key) { var hasProto = (key in options); var config = { path: options[key], tmpl: pathTmpl, protocol: protocol, sub: true }; path = hasProto ? RongIMLib.RongUtil.formatProtoclPath(config) : path; options[key] = path; }); var _sourcePath = { protobuf: 'cdn.ronghub.com/protobuf-2.3.1.min.js' }; RongIMLib.RongUtil.forEach(_sourcePath, function (path, key) { _sourcePath[key] = RongIMLib.RongUtil.stringFormat(pathTmpl, [protocol, path]); }); RongIMLib.RongUtil.extend(_sourcePath, options); var _defaultOpts = { isPolling: isPolling, wsScheme: wsScheme, protocol: protocol, showError: true, openMp: true, snifferTime: 2000 }; RongIMLib.RongUtil.extend(_defaultOpts, options); if (RongIMLib.RongUtil.isFunction(options.protobuf)) { RongIMClient.Protobuf = options.protobuf; } RongIMClient.userStatusObserver = new RongIMLib.RongObserver(); var pather = new RongIMLib.FeaturePatcher(); pather.patchAll(); var tempStore = { token: "", callback: null, lastReadTime: new RongIMLib.LimitableMap(), conversationList: [], appKey: appKey, publicServiceMap: new RongIMLib.PublicServiceMap(), providerType: 1, deltaTime: 0, filterMessages: [], isSyncRemoteConverList: true, otherDevice: false, custStore: {}, converStore: { latestMessage: {} }, connectAckTime: 0, voipStategy: 0, isFirstPingMsg: true, depend: options, listenerList: RongIMClient._memoryStore.listenerList, notification: {} }; RongIMClient._memoryStore = tempStore; if (dataAccessProvider && Object.prototype.toString.call(dataAccessProvider) == "[object Object]") { RongIMClient._dataAccessProvider = dataAccessProvider; } else { RongIMClient._dataAccessProvider = new RongIMLib.ServerDataProvider(); } options.appCallback = callback; var sdkInfo = RongIMClient._dataAccessProvider.init(appKey, options); RongIMClient._memoryStore.sdkInfo = sdkInfo; // 兼容 c++ 设置导航,Web 端不生效 RongIMClient._dataAccessProvider.setServerInfo({ navi: location.protocol + options.navi + '/navi.xml' }); RongIMClient.MessageParams = { TextMessage: { objectName: "RC:TxtMsg", msgTag: new RongIMLib.MessageTag(true, true) }, ImageMessage: { objectName: "RC:ImgMsg", msgTag: new RongIMLib.MessageTag(true, true) }, DiscussionNotificationMessage: { objectName: "RC:DizNtf", msgTag: new RongIMLib.MessageTag(false, true) }, VoiceMessage: { objectName: "RC:VcMsg", msgTag: new RongIMLib.MessageTag(true, true) }, RichContentMessage: { objectName: "RC:ImgTextMsg", msgTag: new RongIMLib.MessageTag(true, true) }, FileMessage: { objectName: "RC:FileMsg", msgTag: new RongIMLib.MessageTag(true, true) }, HandshakeMessage: { objectName: "", msgTag: new RongIMLib.MessageTag(true, true) }, UnknownMessage: { objectName: "", msgTag: new RongIMLib.MessageTag(true, true) }, LocationMessage: { objectName: "RC:LBSMsg", msgTag: new RongIMLib.MessageTag(true, true) }, InformationNotificationMessage: { objectName: "RC:InfoNtf", msgTag: new RongIMLib.MessageTag(false, true) }, ContactNotificationMessage: { objectName: "RC:ContactNtf", msgTag: new RongIMLib.MessageTag(false, true) }, ProfileNotificationMessage: { objectName: "RC:ProfileNtf", msgTag: new RongIMLib.MessageTag(false, true) }, CommandNotificationMessage: { objectName: "RC:CmdNtf", msgTag: new RongIMLib.MessageTag(true, true) }, PublicServiceRichContentMessage: { objectName: "RC:PSImgTxtMsg", msgTag: new RongIMLib.MessageTag(true, true) }, PublicServiceMultiRichContentMessage: { objectName: "RC:PSMultiImgTxtMsg", msgTag: new RongIMLib.MessageTag(true, true) }, JrmfRedPacketMessage: { objectName: "RCJrmf:RpMsg", msgTag: new RongIMLib.MessageTag(true, true) }, JrmfRedPacketOpenedMessage: { objectName: "RCJrmf:RpOpendMsg", msgTag: new RongIMLib.MessageTag(true, true) }, GroupNotificationMessage: { objectName: "RC:GrpNtf", msgTag: new RongIMLib.MessageTag(false, true) }, CommandMessage: { objectName: "RC:CmdMsg", msgTag: new RongIMLib.MessageTag(false, false) }, TypingStatusMessage: { objectName: "RC:TypSts", msgTag: new RongIMLib.MessageTag(false, false) }, PublicServiceCommandMessage: { objectName: "RC:PSCmd", msgTag: new RongIMLib.MessageTag(false, false) }, RecallCommandMessage: { objectName: "RC:RcCmd", msgTag: new RongIMLib.MessageTag(false, true) }, SyncReadStatusMessage: { objectName: "RC:SRSMsg", msgTag: new RongIMLib.MessageTag(false, false) }, ReadReceiptRequestMessage: { objectName: "RC:RRReqMsg", msgTag: new RongIMLib.MessageTag(false, false) }, ReadReceiptResponseMessage: { objectName: "RC:RRRspMsg", msgTag: new RongIMLib.MessageTag(false, false) }, ChangeModeResponseMessage: { objectName: "RC:CsChaR", msgTag: new RongIMLib.MessageTag(false, false) }, ChangeModeMessage: { objectName: "RC:CSCha", msgTag: new RongIMLib.MessageTag(false, false) }, EvaluateMessage: { objectName: "RC:CsEva", msgTag: new RongIMLib.MessageTag(false, false) }, CustomerContact: { objectName: "RC:CsContact", msgTag: new RongIMLib.MessageTag(false, false) }, HandShakeMessage: { objectName: "RC:CsHs", msgTag: new RongIMLib.MessageTag(false, false) }, HandShakeResponseMessage: { objectName: "RC:CsHsR", msgTag: new RongIMLib.MessageTag(false, false) }, SuspendMessage: { objectName: "RC:CsSp", msgTag: new RongIMLib.MessageTag(false, false) }, TerminateMessage: { objectName: "RC:CsEnd", msgTag: new RongIMLib.MessageTag(false, false) }, CustomerStatusUpdateMessage: { objectName: "RC:CsUpdate", msgTag: new RongIMLib.MessageTag(false, false) }, ReadReceiptMessage: { objectName: "RC:ReadNtf", msgTag: new RongIMLib.MessageTag(false, false) } }; RongIMClient.MessageParams["AcceptMessage"] = { objectName: "RC:VCAccept", msgTag: new RongIMLib.MessageTag(false, false) }; RongIMClient.MessageParams["RingingMessage"] = { objectName: "RC:VCRinging", msgTag: new RongIMLib.MessageTag(false, false) }; RongIMClient.MessageParams["SummaryMessage"] = { objectName: "RC:VCSummary", msgTag: new RongIMLib.MessageTag(false, false) }; RongIMClient.MessageParams["HungupMessage"] = { objectName: "RC:VCHangup", msgTag: new RongIMLib.MessageTag(false, false) }; RongIMClient.MessageParams["InviteMessage"] = { objectName: "RC:VCInvite", msgTag: new RongIMLib.MessageTag(false, false) }; RongIMClient.MessageParams["MediaModifyMessage"] = { objectName: "RC:VCModifyMedia", msgTag: new RongIMLib.MessageTag(false, false) }; RongIMClient.MessageParams["MemberModifyMessage"] = { objectName: "RC:VCModifyMem", msgTag: new RongIMLib.MessageTag(false, false) }; RongIMClient.MessageType = { TextMessage: "TextMessage", ImageMessage: "ImageMessage", DiscussionNotificationMessage: "DiscussionNotificationMessage", VoiceMessage: "VoiceMessage", RichContentMessage: "RichContentMessage", HandshakeMessage: "HandshakeMessage", UnknownMessage: "UnknownMessage", LocationMessage: "LocationMessage", InformationNotificationMessage: "InformationNotificationMessage", ContactNotificationMessage: "ContactNotificationMessage", ProfileNotificationMessage: "ProfileNotificationMessage", CommandNotificationMessage: "CommandNotificationMessage", CommandMessage: "CommandMessage", TypingStatusMessage: "TypingStatusMessage", ChangeModeResponseMessage: "ChangeModeResponseMessage", ChangeModeMessage: "ChangeModeMessage", EvaluateMessage: "EvaluateMessage", HandShakeMessage: "HandShakeMessage", HandShakeResponseMessage: "HandShakeResponseMessage", SuspendMessage: "SuspendMessage", TerminateMessage: "TerminateMessage", CustomerContact: "CustomerContact", CustomerStatusUpdateMessage: "CustomerStatusUpdateMessage", SyncReadStatusMessage: "SyncReadStatusMessage", ReadReceiptRequestMessage: "ReadReceiptRequestMessage", ReadReceiptResponseMessage: "ReadReceiptResponseMessage", FileMessage: 'FileMessage', AcceptMessage: "AcceptMessage", RingingMessage: "RingingMessage", SummaryMessage: "SummaryMessage", HungupMessage: "HungupMessage", InviteMessage: "InviteMessage", MediaModifyMessage: "MediaModifyMessage", MemberModifyMessage: "MemberModifyMessage", JrmfRedPacketMessage: "JrmfRedPacketMessage", JrmfRedPacketOpenedMessage: "JrmfRedPacketOpenedMessage", GroupNotificationMessage: "GroupNotificationMessage", PublicServiceRichContentMessage: "PublicServiceRichContentMessage", PublicServiceMultiRichContentMessage: "PublicServiceMultiRichContentMessage", PublicServiceCommandMessage: "PublicServiceCommandMessage", RecallCommandMessage: "RecallCommandMessage", ReadReceiptMessage: "ReadReceiptMessage" }; RongIMClient.LogFactory = { /** * 个人 */ "-1": { code: "-1", msg: "服务器超时" }, "-2": { code: "-2", msg: "未知原因失败" }, "-3": { code: "-3", msg: "参数错误" }, "-4": { code: "-4", msg: "参数不正确或尚未实例化" }, "25101": { code: "25101", msg: "撤回消息参数错误", desc: "请检查撤回消息参数 https://rongcloud.github.io/websdk-demo/api-test.html" }, "25102": { code: "25101", msg: "只能撤回自发发送的消息" }, "20604": { code: "20604", msg: "发送频率过快", desc: "https://developer.rongcloud.cn/ticket/info/9Q3L6vRKd1cLS7rycA==?type=1" }, "20406": { code: "20406", msg: "被禁言" }, "23407": { code: "23407", msg: "获取用户失败" }, /** * 群组 */ "20407": { code: "20407", msg: "群组Id无效" }, "22408": { code: "22408", msg: "群组被禁言" }, "22406": { code: "22406", msg: "不在群组" }, "35001": { code: "35001", msg: "群组同步异常" }, "35002": { code: "35002", msg: "匹配群信息异常" }, /** * 讨论组 */ "21406": { code: "21406", msg: "不在讨论组" }, "21407": { code: "21407", msg: "加入讨论失败" }, "21408": { code: "21408", msg: "创建讨论组失败" }, "21409": { code: "21409", msg: "设置讨论组邀请状态失败" }, /** * 聊天室 */ "23406": { code: "23406", msg: "不在聊天室" }, "23408": { code: "23408", msg: "聊天室被禁言" }, "23409": { code: "23409", msg: "聊天室中成员被踢出" }, "23410": { code: "23410", msg: "聊天室不存在" }, "23411": { code: "23411", msg: "聊天室成员已满" }, "23412": { code: "23412", msg: "获取聊天室信息参数无效" }, "23413": { code: "23413", msg: "聊天室异常" }, "23414": { code: "23414", msg: "没有打开聊天室消息存储" }, "36001": { code: "36001", msg: "加入聊天室Id为空" }, "36002": { code: "36002", msg: "加入聊天室失败" }, "36003": { code: "36003", msg: "拉取聊天室历史消息失败" }, /** * voip */ "24001": { code: "24001", msg: "没有注册DeviveId 也就是用户没有登陆" }, "24002": { code: "24002", msg: "用户已经存在" }, "0": { code: "0", msg: "成功" }, "24009": { code: "24009", msg: "没有对应的用户或token" }, "24013": { code: "24013", msg: "voip为空" }, "24010": { code: "24010", msg: "不支持的Voip引擎" }, "24011": { code: "24011", msg: "channelName 是空" }, "24012": { code: "24012", msg: "生成Voipkey失败" }, "24014": { code: "24014", msg: "没有配置voip" }, "24015": { code: "24015", msg: "服务器内部错误" }, "24016": { code: "24016", msg: "VOIP close" }, /** * 通讯、导航 */ "30001": { code: "30001", msg: "通信过程中,当前Socket不存在" }, "30002": { code: "30002", msg: "Socket连接不可用" }, "30003": { code: "30003", msg: "通信超时" }, "30004": { code: "30004", msg: "导航操作时,Http请求失败" }, "30005": { code: "30005", msg: "HTTP请求失败" }, "30006": { code: "30006", msg: "HTTP接收失败" }, "30007": { code: "30007", msg: "导航资源错误" }, "30008": { code: "30008", msg: "没有有效数据" }, "30009": { code: "30009", msg: "不存在有效 IP 地址" }, "30010": { code: "30010", msg: "创建 Socket 失败" }, "30011": { code: "30011", msg: " Socket 被断开" }, "30012": { code: "30012", msg: "PING 操作失败" }, "30013": { code: "30013", msg: "PING 超时" }, "30014": { code: "30014", msg: "消息发送失败" }, /** * 连接 */ "31000": { code: "31000", msg: "做 connect 连接时,收到的 ACK 超时" }, "31001": { code: "31001", msg: "参数错误" }, "31002": { code: "31002", msg: "参数错误,App Id 错误" }, "31003": { code: "31003", msg: "服务器不可用" }, "31004": { code: "31004", msg: "Token 错误" }, "31005": { code: "31005", msg: "App Id 与 Token 不匹配" }, "31006": { code: "31006", msg: "重定向,地址错误" }, "31007": { code: "31007", msg: "NAME 与后台注册信息不一致" }, "31008": { code: "31008", msg: "APP 被屏蔽、删除或不存在" }, "31009": { code: "31009", msg: "用户被屏蔽" }, "31010": { code: "31010", msg: "Disconnect,由服务器返回,比如用户互踢" }, "31011": { code: "31011", msg: "Disconnect,由服务器返回,比如用户互踢" }, /** * 协议 */ "32001": { code: "32001", msg: "协议层内部错误。query,上传下载过程中数据错误" }, "32002": { code: "32002", msg: "协议层内部错误" }, /** * BIZ */ "33001": { code: "33001", msg: "未调用 init 初始化函数" }, "33002": { code: "33002", msg: "数据库初始化失败" }, "33003": { code: "33003", msg: "传入参数无效" }, "33004": { code: "33004", msg: "通道无效" }, "33005": { code: "33005", msg: "重新连接成功" }, "33006": { code: "33006", msg: "连接中,再调用 connect 被拒绝" }, "33007": { code: "33007", msg: "消息漫游服务未开通" }, "33008": { code: "33008", msg: "消息添加失败" }, "33009": { code: "33009", msg: "消息删除失败" }, /** * 会话 */ "34001": { code: "34001", msg: "删除会话失败" }, "34002": { code: "34002", msg: "拉取历史消息失败" }, "34003": { code: "34003", msg: "会话指定异常" }, "34004": { code: "34004", msg: "获取会话未读消息总数失败" }, "34005": { code: "34005", msg: "获取指定会话类型未读消息数异常" }, "34006": { code: "34006", msg: "获取指定用户ID&会话类型未读消息数异常" }, "34007": { code: "34007", msg: "清除会话消息异常" }, "34008": { code: "34008", msg: "获取会话消息异常" }, "34009": { code: "34009", msg: "清除历史消息会话类型不正确" }, "34010": { code: "34010", msg: "清除历史消息失败,请检查传入参数" }, /** * 黑名单异常 */ "37001": { code: "37001", msg: "加入黑名单异常" }, "37002": { code: "37002", msg: "获得指定人员再黑名单中的状态异常" }, "37003": { code: "37003", msg: "移除黑名单异常" }, "405": { code: "405", msg: "在黑名单中" }, /** * 草稿 */ "38001": { code: "38001", msg: "获取草稿失败" }, "38002": { code: "38002", msg: "保存草稿失败" }, "38003": { code: "38003", msg: "删除草稿失败" }, /** * 公众号 */ "39001": { code: "39001", msg: "关注公众号失败" }, /** * 文件 */ "41001": { code: "41001", msg: "文件类型错误" }, "41002": { code: "41002", msg: "获取七牛token失败" }, /** * */ "51001": { code: "51001", msg: "未安装或未启动插件" }, "51002": { code: "51002", msg: "视频已经存在" }, "51003": { code: "51003", msg: "无效的channelName" }, "51004": { code: "51004", msg: "视频内容为空" }, /** * */ "61001": { code: "61001", msg: "删除消息数组长度为 0" } }; return sdkInfo; }; ; /** var config = { appkey: appkey, token: token, dataAccessProvider:dataAccessProvider, opts: opts }; callback(_instance, userId); */ RongIMClient.initApp = function (config, callback) { RongIMClient.init(config.appkey, config.dataAccessProvider, config.opts, function () { var instance = RongIMClient._instance; //备用 var error = null; callback(error, instance); }); }; /** * 连接服务器,在整个应用全局只需要调用一次,断线后 SDK 会自动重连。 * * @param token 从服务端获取的用户身份令牌(Token)。 * @param callback 连接回调,返回连接的成功或者失败状态。 */ RongIMClient.connect = function (token, _callback, userId, serverConf) { RongIMLib.CheckParam.getInstance().check(["string", "object", "string|null|object|global|undefined", "object|null|global|undefined"], "connect", true, arguments); var connectCallback = { onSuccess: _callback.onSuccess, onTokenIncorrect: _callback.onTokenIncorrect, onError: function (errorCode) { RongIMClient.logger({ code: errorCode, funcName: "connect" }); _callback.onError(errorCode); } }; RongIMClient._dataAccessProvider.connect(token, connectCallback, userId, serverConf); }; RongIMClient.reconnect = function (callback, config) { var connectCallback = { onSuccess: callback.onSuccess, onTokenIncorrect: callback.onTokenIncorrect, onError: function (errorCode) { RongIMClient.logger({ code: errorCode, funcName: "connect" }); callback.onError(errorCode); } }; RongIMClient._dataAccessProvider.reconnect(connectCallback, config); }; /** * 注册消息类型,用于注册用户自定义的消息。 * 内建的消息类型已经注册过,不需要再次注册。 * 自定义消息声明需放在执行顺序最高的位置(在RongIMClient.init(appkey)之后即可) * @param objectName 消息内置名称 */ RongIMClient.registerMessageType = function (messageType, objectName, messageTag, messageContent, searchProp) { RongIMClient._dataAccessProvider.registerMessageType(messageType, objectName, messageTag, messageContent, searchProp); RongIMClient.RegisterMessage[messageType].messageName = messageType; RongIMClient.MessageType[messageType] = messageType; RongIMClient.MessageParams[messageType] = { objectName: objectName, msgTag: messageTag }; }; /** * 设置连接状态变化的监听器。 * * @param listener 连接状态变化的监听器。 */ RongIMClient.setConnectionStatusListener = function (listener) { if (RongIMClient._dataAccessProvider) { RongIMClient._dataAccessProvider.setConnectionStatusListener(listener); } else { RongIMClient._memoryStore.listenerList.push(listener); } }; /** * 设置接收消息的监听器。 * * @param listener 接收消息的监听器。 */ RongIMClient.setOnReceiveMessageListener = function (listener) { if (RongIMClient._dataAccessProvider) { RongIMClient._dataAccessProvider.setOnReceiveMessageListener(listener); } else { RongIMClient._memoryStore.listenerList.push(listener); } }; /** * 清理所有连接相关的变量 */ RongIMClient.prototype.logout = function () { RongIMClient._dataAccessProvider.logout(); }; /** * 断开连接。 */ RongIMClient.prototype.disconnect = function () { RongIMClient._dataAccessProvider.disconnect(); }; RongIMClient.prototype.startCustomService = function (custId, callback, groupId) { if (!custId || !callback) return; var msg; if (typeof groupId == 'undefined') { msg = new RongIMLib.HandShakeMessage(); } else { msg = new RongIMLib.HandShakeMessage({ groupid: groupId }); } var me = this; RongIMLib.RongIMClient._memoryStore.custStore["isInit"] = true; RongIMClient.getInstance().sendMessage(RongIMLib.ConversationType.CUSTOMER_SERVICE, custId, msg, { onSuccess: function (data) { if (data.isBlack) { callback.onError(); me.stopCustomeService(custId, { onSuccess: function () { }, onError: function () { } }); } else { callback.onSuccess(); } }, onError: function () { callback.onError(); }, onBefore: function () { } }); }; RongIMClient.prototype.stopCustomeService = function (custId, callback) { if (!custId || !callback) return; var session = RongIMClient._memoryStore.custStore[custId]; if (!session) return; var msg = new RongIMLib.SuspendMessage({ sid: session.sid, uid: session.uid, pid: session.pid }); this.sendCustMessage(custId, msg, { onSuccess: function () { // delete RongIMClient._memoryStore.custStore[custId]; setTimeout(function () { callback.onSuccess(); }); }, onError: function () { setTimeout(function () { callback.onError(); }); } }); }; RongIMClient.prototype.switchToHumanMode = function (custId, callback) { if (!custId || !callback) return; var session = RongIMClient._memoryStore.custStore[custId]; if (!session) return; var msg = new RongIMLib.ChangeModeMessage({ sid: session.sid, uid: session.uid, pid: session.pid }); this.sendCustMessage(custId, msg, callback); }; RongIMClient.prototype.evaluateRebotCustomService = function (custId, isRobotResolved, sugest, callback) { if (!custId || !callback) return; var session = RongIMClient._memoryStore.custStore[custId]; if (!session) return; var msg = new RongIMLib.EvaluateMessage({ sid: session.sid, uid: session.uid, pid: session.pid, isRobotResolved: isRobotResolved, sugest: sugest, type: 0 }); this.sendCustMessage(custId, msg, callback); }; RongIMClient.prototype.evaluateHumanCustomService = function (custId, humanValue, sugest, callback) { if (!custId || !callback) return; var session = RongIMClient._memoryStore.custStore[custId]; if (!session) return; var msg = new RongIMLib.EvaluateMessage({ sid: session.sid, uid: session.uid, pid: session.pid, humanValue: humanValue, sugest: sugest, type: 1 }); this.sendCustMessage(custId, msg, callback); }; RongIMClient.prototype.sendCustMessage = function (custId, msg, callback) { RongIMClient.getInstance().sendMessage(RongIMLib.ConversationType.CUSTOMER_SERVICE, custId, msg, { onSuccess: function (data) { callback.onSuccess(); }, onError: function () { callback.onError(); }, onBefore: function () { } }); }; /** * 获取当前连接的状态。 */ RongIMClient.prototype.getCurrentConnectionStatus = function () { return RongIMClient._dataAccessProvider.getCurrentConnectionStatus(); }; /** * 获取当前使用的连接通道。 */ RongIMClient.prototype.getConnectionChannel = function () { if (RongIMLib.Transportations._TransportType == RongIMLib.Socket.XHR_POLLING) { return RongIMLib.ConnectionChannel.XHR_POLLING; } else if (RongIMLib.Transportations._TransportType == RongIMLib.Socket.WEBSOCKET) { return RongIMLib.ConnectionChannel.WEBSOCKET; } }; /** * 获取当前使用的本地储存提供者。 TODO */ RongIMClient.prototype.getStorageProvider = function () { if (RongIMClient._memoryStore.providerType == 1) { return "ServerDataProvider"; } else { return "OtherDataProvider"; } }; /** * 过滤聊天室消息(拉取最近聊天消息) * @param {string[]} msgFilterNames */ RongIMClient.prototype.setFilterMessages = function (msgFilterNames) { if (Object.prototype.toString.call(msgFilterNames) == "[object Array]") { RongIMClient._memoryStore.filterMessages = msgFilterNames; } }; RongIMClient.prototype.getAgoraDynamicKey = function (engineType, channelName, callback) { RongIMClient._dataAccessProvider.getAgoraDynamicKey(engineType, channelName, callback); }; /** * 获取当前连接用户的 UserId。 */ RongIMClient.prototype.getCurrentUserId = function () { return RongIMLib.Bridge._client.userId; }; /** * 获取服务器时间与本地时间的差值,单位为毫秒。 * 计算公式:差值 = 本地时间毫秒数 - 服务器时间毫秒数 * @param callback 获取的回调,返回差值。 */ RongIMClient.prototype.getDeltaTime = function () { return RongIMClient._dataAccessProvider.getDelaTime(); }; // #region Message RongIMClient.prototype.getMessage = function (messageId, callback) { RongIMClient._dataAccessProvider.getMessage(messageId, RongIMClient.logCallback(callback, "getMessage")); }; RongIMClient.prototype.deleteLocalMessages = function (conversationType, targetId, messageIds, callback) { RongIMClient._dataAccessProvider.removeLocalMessage(conversationType, targetId, messageIds, RongIMClient.logCallback(callback, "deleteLocalMessages")); }; RongIMClient.prototype.updateMessage = function (message, callback) { RongIMClient._dataAccessProvider.updateMessage(message, RongIMClient.logCallback(callback, "updateMessage")); }; RongIMClient.prototype.clearMessages = function (conversationType, targetId, callback) { RongIMClient._dataAccessProvider.clearMessages(conversationType, targetId, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "clearMessages" }); callback.onError(errorCode); }); } }); }; /**TODO 清楚本地存储的未读消息,目前清空内存中的未读消息 * [clearMessagesUnreadStatus 清空指定会话未读消息] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [用户id] * @param {ResultCallback} callback [返回值,参数回调] */ RongIMClient.prototype.clearMessagesUnreadStatus = function (conversationType, targetId, callback) { RongIMClient._dataAccessProvider.updateMessages(conversationType, targetId, "readStatus", null, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "clearMessagesUnreadStatus" }); callback.onError(errorCode); }); } }); }; RongIMClient.prototype.deleteRemoteMessages = function (conversationType, targetId, delMsgs, callback) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "array", "object"], "deleteRemoteMessages", false, arguments); if (delMsgs.length == 0) { var errorCode = RongIMLib.ErrorCode.DELETE_MESSAGE_ID_IS_NULL; RongIMClient.logger({ code: errorCode, funcName: "deleteRemoteMessages" }); callback.onError(RongIMLib.ErrorCode.DELETE_MESSAGE_ID_IS_NULL); return; } else if (delMsgs.length > 100) { delMsgs.length = 100; } // 后续增加,去掉注释即可 callback.onSuccess(true); // var modules = new RongIMClient.Protobuf.DeleteMsgInput(); // modules.setType(conversationType); // modules.setConversationId(targetId); // modules.setMsgs(delMsgs); // RongIMClient.bridge.queryMsg(33, MessageUtil.ArrayForm(modules.toArrayBuffer()), Bridge._client.userId, { // onSuccess: function(info: any) { // callback.onSuccess(true); // }, // onError: function(err: any) { // callback.onError(err); // } // }, "DeleteMsgOutput"); }; /** * [deleteMessages 删除消息记录。] * @param {ConversationType} conversationType [description] * @param {string} targetId [description] * @param {number[]} messageIds [description] * @param {ResultCallback} callback [description] */ RongIMClient.prototype.deleteMessages = function (conversationType, targetId, delMsgs, callback) { RongIMClient._dataAccessProvider.removeMessage(conversationType, targetId, delMsgs, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "deleteMessages" }); callback.onError(errorCode); }); } }); }; RongIMClient.prototype.sendLocalMessage = function (message, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object"], "sendLocalMessage", false, arguments); RongIMClient._dataAccessProvider.updateMessage(message); this.sendMessage(message.conversationType, message.targetId, message.content, RongIMClient.logSendCallback(callback, "sendLocalMessage")); }; /** * [sendMessage 发送消息。] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [目标Id] * @param {MessageContent} messageContent [消息类型] * @param {SendMessageCallback} sendCallback [] * @param {ResultCallback} resultCallback [返回值,函数回调] * @param {string} pushContent [] * @param {string} pushData [] */ RongIMClient.prototype.sendMessage = function (conversationType, targetId, messageContent, sendCallback, mentiondMsg, pushText, appData, methodType, params) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object", "object", "undefined|object|null|global|boolean", "undefined|object|null|global|string", "undefined|object|null|global|string", "undefined|object|null|global|number", "undefined|object|null|global"], "sendMessage", false, arguments); RongIMClient._dataAccessProvider.sendMessage(conversationType, targetId, messageContent, RongIMClient.logSendCallback(sendCallback, "sendMessage"), mentiondMsg, pushText, appData, methodType, params); }; RongIMClient.prototype.sendReceiptResponse = function (conversationType, targetId, sendCallback) { RongIMClient._dataAccessProvider.sendReceiptResponse(conversationType, targetId, RongIMClient.logSendCallback(sendCallback, "sendReceiptResponse")); }; RongIMClient.prototype.sendTypingStatusMessage = function (conversationType, targetId, messageName, sendCallback) { RongIMClient._dataAccessProvider.sendTypingStatusMessage(conversationType, targetId, messageName, RongIMClient.logSendCallback(sendCallback, "sendTypingStatusMessage")); }; /** * [sendStatusMessage description] * @param {MessageContent} messageContent [description] * @param {SendMessageCallback} sendCallback [description] * @param {ResultCallback} resultCallback [description] */ RongIMClient.prototype.sendStatusMessage = function (messageContent, sendCallback, resultCallback) { throw new Error("Not implemented yet"); }; /** * [sendTextMessage 发送TextMessage快捷方式] * @param {string} content [消息内容] * @param {ResultCallback} resultCallback [返回值,参数回调] */ RongIMClient.prototype.sendTextMessage = function (conversationType, targetId, content, sendMessageCallback) { RongIMClient._dataAccessProvider.sendTextMessage(conversationType, targetId, content, RongIMClient.logSendCallback(sendMessageCallback, "sendTextMessage")); }; RongIMClient.prototype.sendRecallMessage = function (content, sendMessageCallback) { var callback = RongIMClient.logSendCallback(sendMessageCallback, "sendRecallMessage"); var senderUserId = content.senderUserId; var userId = RongIMLib.Bridge._client.userId; var isOther = (senderUserId != userId); if (isOther) { var callback = RongIMClient.logSendCallback(sendMessageCallback, "sendRecallMessage"); callback.onError(RongIMLib.ErrorCode.RECALL_MESSAGE, content); return; } RongIMClient._dataAccessProvider.sendRecallMessage(content, callback); }; /** * [insertMessage 向本地插入一条消息,不发送到服务器。] * @param {ConversationType} conversationType [description] * @param {string} targetId [description] * @param {string} senderUserId [description] * @param {MessageContent} content [description] * @param {ResultCallback} callback [description] */ RongIMClient.prototype.insertMessage = function (conversationType, targetId, content, callback) { RongIMClient._dataAccessProvider.addMessage(conversationType, targetId, content, RongIMClient.logCallback(callback, "insertMessage")); }; /** * [getHistoryMessages 拉取历史消息记录。] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [用户Id] * @param {number|null} pullMessageTime [拉取历史消息起始位置(格式为毫秒数),可以为null] * @param {number} count [历史消息数量] * @param {ResultCallback} callback [回调函数] * @param {string} objectName [objectName] */ RongIMClient.prototype.getHistoryMessages = function (conversationType, targetId, timestamp, count, callback, objectname, direction) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "number|null|global|object", "number", "object", "undefined|object|null|global|string", "boolean|null|global|object"], "getHistoryMessages", false, arguments); if (count > 20) { throw new Error("HistroyMessage count must be less than or equal to 20!"); } if (conversationType.valueOf() < 0) { throw new Error("ConversationType must be greater than -1"); } RongIMClient._dataAccessProvider.getHistoryMessages(conversationType, targetId, timestamp, count, RongIMClient.logCallback(callback, "getHistoryMessages"), objectname, direction); }; RongIMClient.prototype.setMessageContent = function (messageId, content, objectName) { RongIMClient._dataAccessProvider.setMessageContent(messageId, content, objectName); }; ; /** * [getRemoteHistoryMessages 拉取某个时间戳之前的消息] * @param {ConversationType} conversationType [description] * @param {string} targetId [description] * @param {Date} dateTime [description] * @param {number} count [description] * @param {ResultCallback} callback [description] */ RongIMClient.prototype.getRemoteHistoryMessages = function (conversationType, targetId, timestamp, count, callback) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "number|null|global|object", "number", "object"], "getRemoteHistoryMessages", false, arguments); var funcName = "getRemoteHistoryMessages"; var log = { errorCode: RongIMLib.ErrorCode.RC_CONN_PROTO_VERSION_ERROR, funcName: "getRemoteHistoryMessages" }; if (count > 20) { RongIMClient.logger(log); callback.onError(RongIMLib.ErrorCode.RC_CONN_PROTO_VERSION_ERROR); return; } if (conversationType.valueOf() < 0) { RongIMClient.logger(log); callback.onError(RongIMLib.ErrorCode.RC_CONN_PROTO_VERSION_ERROR); return; } RongIMClient._dataAccessProvider.getRemoteHistoryMessages(conversationType, targetId, timestamp, count, RongIMClient.logCallback(callback, funcName)); }; RongIMClient.prototype.clearHistoryMessages = function (params, callback) { RongIMClient._dataAccessProvider.clearHistoryMessages(params, callback); }; RongIMClient.prototype.clearRemoteHistoryMessages = function (params, callback) { RongIMClient._dataAccessProvider.clearRemoteHistoryMessages(params, RongIMClient.logCallback(callback, "clearRemoteHistoryMessages")); }; /** * [hasRemoteUnreadMessages 是否有未接收的消息,jsonp方法] * @param {string} appkey [appkey] * @param {string} token [token] * @param {ConnectCallback} callback [返回值,参数回调] */ RongIMClient.prototype.hasRemoteUnreadMessages = function (token, callback) { RongIMClient._dataAccessProvider.hasRemoteUnreadMessages(token, RongIMClient.logCallback(callback, "hasRemoteUnreadMessages")); }; RongIMClient.prototype.getTotalUnreadCount = function (callback, conversationTypes) { return RongIMClient._dataAccessProvider.getTotalUnreadCount({ onSuccess: function (count) { setTimeout(function () { callback.onSuccess(count); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "getTotalUnreadCount" }); callback.onError(errorCode); }); } }, conversationTypes); }; /** * [getConversationUnreadCount 指定多种会话类型获取未读消息数] * @param {ResultCallback} callback [返回值,参数回调。] * @param {ConversationType[]} ...conversationTypes [会话类型。] */ RongIMClient.prototype.getConversationUnreadCount = function (conversationTypes, callback) { RongIMClient._dataAccessProvider.getConversationUnreadCount(conversationTypes, { onSuccess: function (count) { setTimeout(function () { callback.onSuccess(count); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "getConversationUnreadCount" }); callback.onError(errorCode); }); } }); }; /** * [getUnreadCount 指定用户、会话类型的未读消息总数。] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [用户Id] */ RongIMClient.prototype.getUnreadCount = function (conversationType, targetId, callback) { callback = callback || function(){}; return RongIMClient._dataAccessProvider.getUnreadCount(conversationType, targetId, { onSuccess: function (count) { setTimeout(function () { callback.onSuccess(count); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "getUnreadCount" }); callback.onError(errorCode); }); } }); }; RongIMClient.prototype.clearUnreadCountByTimestamp = function (conversationType, targetId, timestamp, callback) { RongIMClient._dataAccessProvider.clearUnreadCountByTimestamp(conversationType, targetId, timestamp, RongIMClient.logCallback(callback, "clearUnreadCountByTimestamp")); }; /** * 清楚会话未读消息数 * @param {ConversationType} conversationType 会话类型 * @param {string} targetId 目标Id * @param {ResultCallback} callback 返回值,函数回调 */ RongIMClient.prototype.clearUnreadCount = function (conversationType, targetId, callback) { RongIMClient._dataAccessProvider.clearUnreadCount(conversationType, targetId, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "clearUnreadCount" }); callback.onError(errorCode); }); } }); }; RongIMClient.prototype.clearLocalStorage = function (callback) { RongIMClient._storageProvider.clearItem(); callback(); }; RongIMClient.prototype.setMessageExtra = function (messageId, value, callback) { RongIMClient._dataAccessProvider.setMessageExtra(messageId, value, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "setMessageExtra" }); callback.onError(errorCode); }); } }); }; RongIMClient.prototype.setMessageReceivedStatus = function (messageUId, receivedStatus, callback) { RongIMClient._dataAccessProvider.setMessageReceivedStatus(messageUId, receivedStatus, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "setMessageReceivedStatus" }); callback.onError(errorCode); }); } }); }; RongIMClient.prototype.setMessageStatus = function (conersationType, targetId, timestamp, status, callback) { RongIMClient._dataAccessProvider.setMessageStatus(conersationType, targetId, timestamp, status, RongIMClient.logCallback(callback, "setMessageStatus")); }; RongIMClient.prototype.setMessageSentStatus = function (messageId, sentStatus, callback) { RongIMClient._dataAccessProvider.setMessageSentStatus(messageId, sentStatus, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "setMessageSentStatus" }); callback.onError(errorCode); }); } }); }; // #endregion Message // #region TextMessage Draft /** * clearTextMessageDraft 清除指定会话和消息类型的草稿。 * @param {ConversationType} conversationType 会话类型 * @param {string} targetId 目标Id */ RongIMClient.prototype.clearTextMessageDraft = function (conversationType, targetId) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "clearTextMessageDraft", false, arguments); var key = "darf_" + conversationType + "_" + targetId; delete RongIMClient._memoryStore[key]; return true; }; /** * [getTextMessageDraft 获取指定消息和会话的草稿。] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [目标Id] */ RongIMClient.prototype.getTextMessageDraft = function (conversationType, targetId) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "getTextMessageDraft", false, arguments); if (targetId == "" || conversationType < 0) { throw new Error("params error : " + RongIMLib.ErrorCode.DRAF_GET_ERROR); } var key = "darf_" + conversationType + "_" + targetId; return RongIMClient._memoryStore[key]; }; /** * [saveTextMessageDraft description] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [目标Id] * @param {string} value [草稿值] */ RongIMClient.prototype.saveTextMessageDraft = function (conversationType, targetId, value) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "string", "object"], "saveTextMessageDraft", false, arguments); var key = "darf_" + conversationType + "_" + targetId; RongIMClient._memoryStore[key] = value; return true; }; // #endregion TextMessage Draft // #region Conversation RongIMClient.prototype.searchConversationByContent = function (keyword, callback, conversationTypes, customMsgTypes) { RongIMClient._dataAccessProvider.searchConversationByContent(keyword, RongIMClient.logCallback(callback, "searchConversationByContent"), conversationTypes, customMsgTypes); }; RongIMClient.prototype.searchMessageByContent = function (conversationType, targetId, keyword, timestamp, count, total, callback) { RongIMClient._dataAccessProvider.searchMessageByContent(conversationType, targetId, keyword, timestamp, count, total, RongIMClient.logCallback(callback, "searchMessageByContent")); }; RongIMClient.prototype.clearCache = function () { RongIMClient._dataAccessProvider.clearCache(); }; RongIMClient.prototype.clearConversations = function (callback) { var conversationTypes = []; for (var _i = 1; _i < arguments.length; _i++) { conversationTypes[_i - 1] = arguments[_i]; } if (conversationTypes.length == 0) { conversationTypes = [RongIMLib.ConversationType.CHATROOM, RongIMLib.ConversationType.CUSTOMER_SERVICE, RongIMLib.ConversationType.DISCUSSION, RongIMLib.ConversationType.GROUP, RongIMLib.ConversationType.PRIVATE, RongIMLib.ConversationType.SYSTEM, RongIMLib.ConversationType.PUBLIC_SERVICE, RongIMLib.ConversationType.APP_PUBLIC_SERVICE]; } RongIMClient._dataAccessProvider.clearConversations(conversationTypes, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "clearConversations" }); callback.onError(errorCode); }); } }); }; /** * [getConversation 获取指定会话,此方法需在getConversationList之后执行] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [目标Id] * @param {ResultCallback} callback [返回值,函数回调] */ RongIMClient.prototype.getConversation = function (conversationType, targetId, callback) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "getConversation", false, arguments); return RongIMClient._dataAccessProvider.getConversation(conversationType, targetId, { onSuccess: function (conver) { setTimeout(function () { callback.onSuccess(conver); }); }, onError: function (error) { setTimeout(function () { RongIMClient.logger({ code: error, funcName: "getConversation" }); callback.onError(error); }); } }); }; /** * [pottingConversation 组装会话列表] * @param {any} tempConver [临时会话] * conver_conversationType_targetId_no. * msg_conversationType_targetId_no. */ RongIMClient.prototype.pottingConversation = function (tempConver) { var self = this, isUseReplace = false; RongIMClient._dataAccessProvider.getConversation(tempConver.type, tempConver.userId, { onSuccess: function (conver) { if (!conver) { conver = new RongIMLib.Conversation(); } else { isUseReplace = true; } conver.conversationType = tempConver.type; conver.targetId = tempConver.userId; conver.latestMessage = RongIMLib.MessageUtil.messageParser(tempConver.msg); conver.latestMessageId = conver.latestMessage.messageId; conver.objectName = conver.latestMessage.objectName; conver.receivedStatus = conver.latestMessage.receivedStatus; conver.receivedTime = conver.latestMessage.receiveTime; conver.sentStatus = conver.latestMessage.sentStatus; conver.sentTime = conver.latestMessage.sentTime; var mentioneds = RongIMClient._storageProvider.getItem("mentioneds_" + RongIMLib.Bridge._client.userId + '_' + conver.conversationType + '_' + conver.targetId); if (mentioneds) { var info = JSON.parse(mentioneds); conver.mentionedMsg = info[tempConver.type + "_" + tempConver.userId]; } if (!isUseReplace) { if (RongIMLib.RongUtil.supportLocalStorage()) { var count = RongIMClient._storageProvider.getItem("cu" + RongIMLib.Bridge._client.userId + tempConver.type + tempConver.userId); conver.unreadMessageCount = Number(count); } else { conver.unreadMessageCount = 0; } } if (conver.conversationType == RongIMLib.ConversationType.DISCUSSION) { self.getDiscussion(tempConver.userId, { onSuccess: function (info) { conver.conversationTitle = info.name; }, onError: function (error) { } }); } RongIMClient._dataAccessProvider.addConversation(conver, { onSuccess: function (data) { } }); }, onError: function (error) { } }); }; RongIMClient.prototype.addConversation = function (conversation, callback) { RongIMClient._dataAccessProvider.addConversation(conversation, callback); }; RongIMClient.prototype.sortConversationList = function (conversationList) { var convers = []; for (var i = 0, len = conversationList.length; i < len; i++) { if (!conversationList[i]) { continue; } if (conversationList[i].isTop) { convers.push(conversationList[i]); conversationList.splice(i, 1); continue; } for (var j = 0; j < len - i - 1; j++) { if (conversationList[j].sentTime < conversationList[j + 1].sentTime) { var swap = conversationList[j]; conversationList[j] = conversationList[j + 1]; conversationList[j + 1] = swap; } } } return RongIMClient._memoryStore.conversationList = convers.concat(conversationList); }; /* var conversation = { // 会话类型 types: [1, 2, 3, 4, 5, 6, 7, 8], // 获取会话的开始始时间, 0 ,按会话中最后一条消息最大 sentTime 倒序开始获取 sentTime: 0, // 获取条数 count: 100 }; var callbacks = { onSuccess: function(){ }, onError: function(){ } }; */ RongIMClient.prototype.getConversationsByPage = function (conversation, callbacks) { return RongIMClient._dataAccessProvider.getConversationsByPage(conversation, callbacks); }; RongIMClient.prototype.getConversationList = function (callback, conversationTypes, count, isGetHiddenConvers) { RongIMLib.CheckParam.getInstance().check(["object", "null|undefined|array|object|global", "number|undefined|null|object|global", "boolean|undefined|null|object|global"], "getConversationList", false, arguments); var me = this; RongIMClient._dataAccessProvider.getConversationList({ onSuccess: function (data) { if (conversationTypes || RongIMClient._dataAccessProvider) { setTimeout(function () { callback.onSuccess(data); }); } else { setTimeout(function () { callback.onSuccess(RongIMClient._memoryStore.conversationList); }); } }, onError: function (error) { setTimeout(function () { RongIMClient.logger({ code: error, funcName: "getConversationList" }); callback.onError(error); }); } }, conversationTypes, count, isGetHiddenConvers); }; RongIMClient.prototype.getRemoteConversations = function(count, beginTime, order, callback){ RongIMLib.CheckParam.getInstance().check(["number", "number", "number", "object"], "getRemoteConversations", false, arguments); RongIMClient._dataAccessProvider.getRemoteConversations(count, beginTime, order, callback); }; RongIMClient.prototype.getRemoteConversationList = function (callback, conversationTypes, count, isGetHiddenConvers) { RongIMLib.CheckParam.getInstance().check(["object", "null|array|object|global", "number|undefined|null|object|global", "boolean|undefined|null|object|global"], "getRemoteConversationList", false, arguments); RongIMClient._dataAccessProvider.getRemoteConversationList(RongIMClient.logCallback(callback, "getRemoteConversationList"), conversationTypes, count, isGetHiddenConvers); }; RongIMClient.prototype.updateConversation = function (conversation) { return RongIMClient._dataAccessProvider.updateConversation(conversation); }; RongIMClient.prototype.clearData = function () { return RongIMClient._dataAccessProvider.clearData(); }; /** * [createConversation 创建会话。] * @param {number} conversationType [会话类型] * @param {string} targetId [目标Id] * @param {string} converTitle [会话标题] * @param {boolean} islocal [是否同步到服务器,ture:同步,false:不同步] */ RongIMClient.prototype.createConversation = function (conversationType, targetId, converTitle) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "string"], "createConversation", false, arguments); var conver = new RongIMLib.Conversation(); conver.targetId = targetId; conver.conversationType = conversationType; conver.conversationTitle = converTitle; conver.latestMessage = {}; conver.unreadMessageCount = 0; return conver; }; //TODO 删除本地和服务器、删除本地和服务器分开 RongIMClient.prototype.removeConversation = function (conversationType, targetId, callback) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "removeConversation", false, arguments); RongIMClient._dataAccessProvider.removeConversation(conversationType, targetId, RongIMClient.logCallback(callback, "removeConversation")); }; RongIMClient.prototype.setConversationHidden = function (conversationType, targetId, isHidden) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "boolean"], "setConversationHidden", false, arguments); RongIMClient._dataAccessProvider.setConversationHidden(conversationType, targetId, isHidden); }; RongIMClient.prototype.setConversationToTop = function (conversationType, targetId, isTop, callback) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "boolean", "object"], "setConversationToTop", false, arguments); RongIMClient._dataAccessProvider.setConversationToTop(conversationType, targetId, isTop, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "setConversationToTop" }); callback.onError(errorCode); }); } }); }; // #endregion Conversation // #region Notifications /** * [getConversationNotificationStatus 获取指定用户和会话类型免提醒。] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [目标Id] * @param {ResultCallback} callback [返回值,函数回调] */ RongIMClient.prototype.getConversationNotificationStatus = function (conversationType, targetId, callback) { var params = { conversationType: conversationType, targetId: targetId }; RongIMClient._dataAccessProvider.getConversationNotificationStatus(params, RongIMClient.logCallback(callback, "getConversationNotificationStatus")); }; /** * [setConversationNotificationStatus 设置指定用户和会话类型免提醒。] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [目标Id] * @param {ResultCallback} callback [返回值,函数回调] */ RongIMClient.prototype.setConversationNotificationStatus = function (conversationType, targetId, notificationStatus, callback) { var params = { conversationType: conversationType, targetId: targetId, status: status }; RongIMClient._dataAccessProvider.setConversationNotificationStatus(params, RongIMClient.logCallback(callback, "setConversationNotificationStatus")); }; /** * [getNotificationQuietHours 获取免提醒消息时间。] * @param {GetNotificationQuietHoursCallback} callback [返回值,函数回调] */ RongIMClient.prototype.getNotificationQuietHours = function (callback) { throw new Error("Not implemented yet"); }; /** * [removeNotificationQuietHours 移除免提醒消息时间。] * @param {GetNotificationQuietHoursCallback} callback [返回值,函数回调] */ RongIMClient.prototype.removeNotificationQuietHours = function (callback) { throw new Error("Not implemented yet"); }; /** * [setNotificationQuietHours 设置免提醒消息时间。] * @param {GetNotificationQuietHoursCallback} callback [返回值,函数回调] */ RongIMClient.prototype.setNotificationQuietHours = function (startTime, spanMinutes, callback) { throw new Error("Not implemented yet"); }; // #endregion Notifications // #region Discussion /** * [addMemberToDiscussion 加入讨论组] * @param {string} discussionId [讨论组Id] * @param {string[]} userIdList [讨论中成员] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.addMemberToDiscussion = function (discussionId, userIdList, callback) { RongIMLib.CheckParam.getInstance().check(["string", "array", "object"], "addMemberToDiscussion", false, arguments); RongIMClient._dataAccessProvider.addMemberToDiscussion(discussionId, userIdList, RongIMClient.logCallback(callback, "addMemberToDiscussion")); }; /** * [createDiscussion 创建讨论组] * @param {string} name [讨论组名称] * @param {string[]} userIdList [讨论组成员] * @param {CreateDiscussionCallback} callback [返回值,函数回调] */ RongIMClient.prototype.createDiscussion = function (name, userIdList, callback) { RongIMLib.CheckParam.getInstance().check(["string", "array", "object"], "createDiscussion", false, arguments); RongIMClient._dataAccessProvider.createDiscussion(name, userIdList, callback); }; /** * [getDiscussion 获取讨论组信息] * @param {string} discussionId [讨论组Id] * @param {ResultCallback} callback [返回值,函数回调] */ RongIMClient.prototype.getDiscussion = function (discussionId, callback) { RongIMLib.CheckParam.getInstance().check(["string", "object"], "getDiscussion", false, arguments); RongIMClient._dataAccessProvider.getDiscussion(discussionId, RongIMClient.logCallback(callback, "getDiscussion")); }; /** * [quitDiscussion 退出讨论组] * @param {string} discussionId [讨论组Id] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.quitDiscussion = function (discussionId, callback) { RongIMLib.CheckParam.getInstance().check(["string", "object"], "quitDiscussion", false, arguments); RongIMClient._dataAccessProvider.quitDiscussion(discussionId, RongIMClient.logCallback(callback, "quitDiscussion")); }; /** * [removeMemberFromDiscussion 将指定成员移除讨论租] * @param {string} discussionId [讨论组Id] * @param {string} userId [被移除的用户Id] * @param {OperationCallback} callback [返回值,参数回调] */ RongIMClient.prototype.removeMemberFromDiscussion = function (discussionId, userId, callback) { RongIMLib.CheckParam.getInstance().check(["string", "string", "object"], "removeMemberFromDiscussion", false, arguments); RongIMClient._dataAccessProvider.removeMemberFromDiscussion(discussionId, userId, RongIMClient.logCallback(callback, "removeMemberFromDiscussion")); }; /** * [setDiscussionInviteStatus 设置讨论组邀请状态] * @param {string} discussionId [讨论组Id] * @param {DiscussionInviteStatus} status [邀请状态] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.setDiscussionInviteStatus = function (discussionId, status, callback) { RongIMLib.CheckParam.getInstance().check(["string", "number", "object"], "setDiscussionInviteStatus", false, arguments); RongIMClient._dataAccessProvider.setDiscussionInviteStatus(discussionId, status, RongIMClient.logCallback(callback, "setDiscussionInviteStatus")); }; /** * [setDiscussionName 设置讨论组名称] * @param {string} discussionId [讨论组Id] * @param {string} name [讨论组名称] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.setDiscussionName = function (discussionId, name, callback) { RongIMLib.CheckParam.getInstance().check(["string", "string", "object"], "setDiscussionName", false, arguments); RongIMClient._dataAccessProvider.setDiscussionName(discussionId, name, RongIMClient.logCallback(callback, "setDiscussionName")); }; // #endregion Discussion // #region ChatRoom /** * [加入聊天室。] * @param {string} chatroomId [聊天室Id] * @param {number} messageCount [拉取消息数量,-1为不拉去消息] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.joinChatRoom = function (chatroomId, messageCount, callback) { RongIMLib.CheckParam.getInstance().check(["string|number", "number", "object"], "joinChatRoom", false, arguments); if (chatroomId == "") { setTimeout(function () { var errorCode = RongIMLib.ErrorCode.CHATROOM_ID_ISNULL; RongIMClient.logger({ code: errorCode, funcName: "joinChatRoom" }); callback.onError(RongIMLib.ErrorCode.CHATROOM_ID_ISNULL); }); return; } RongIMClient._dataAccessProvider.joinChatRoom(chatroomId, messageCount, RongIMClient.logCallback(callback, "joinChatRoom")); }; RongIMClient.prototype.setDeviceInfo = function (device) { RongIMClient._dataAccessProvider.setDeviceInfo(device); }; RongIMClient.prototype.setChatroomHisMessageTimestamp = function (chatRoomId, timestamp) { RongIMLib.CheckParam.getInstance().check(["string|number", "number"], "setChatroomHisMessageTimestamp", false, arguments); RongIMClient._dataAccessProvider.setChatroomHisMessageTimestamp(chatRoomId, timestamp); }; RongIMClient.prototype.getChatRoomHistoryMessages = function (chatRoomId, count, order, callback) { RongIMLib.CheckParam.getInstance().check(["string|number", "number", "number", "object"], "getChatRoomHistoryMessages", false, arguments); RongIMClient._dataAccessProvider.getChatRoomHistoryMessages(chatRoomId, count, order, RongIMClient.logCallback(callback, "getChatRoomHistoryMessages")); }; RongIMClient.prototype.getChatRoomInfo = function (chatRoomId, count, order, callback) { RongIMLib.CheckParam.getInstance().check(["string|number", "number", "number", "object"], "getChatRoomInfo", false, arguments); RongIMClient._dataAccessProvider.getChatRoomInfo(chatRoomId, count, order, RongIMClient.logCallback(callback, "getChatRoomInfo")); }; /** * [退出聊天室] * @param {string} chatroomId [聊天室Id] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.quitChatRoom = function (chatroomId, callback) { RongIMLib.CheckParam.getInstance().check(["string|number", "object"], "quitChatRoom", false, arguments); RongIMClient._dataAccessProvider.quitChatRoom(chatroomId, RongIMClient.logCallback(callback, "quitChatRoom")); }; // #endregion ChatRoom // #region Public Service RongIMClient.prototype.getRemotePublicServiceList = function (callback, pullMessageTime) { RongIMClient._dataAccessProvider.getRemotePublicServiceList(RongIMClient.logCallback(callback, "getRemotePublicServiceList"), pullMessageTime); }; /** * [getPublicServiceList ]获取本地的公共账号列表 * @param {ResultCallback} callback [返回值,参数回调] */ RongIMClient.prototype.getPublicServiceList = function (callback) { if (RongIMClient._memoryStore.depend.openMp) { RongIMLib.CheckParam.getInstance().check(["object"], "getPublicServiceList", false, arguments); this.getRemotePublicServiceList(RongIMClient.logCallback(callback, "getPublicServiceList")); } }; /** * [getPublicServiceProfile ] 获取某公共服务信息。 * @param {PublicServiceType} publicServiceType [公众服务类型。] * @param {string} publicServiceId [公共服务 Id。] * @param {ResultCallback} callback [公共账号信息回调。] */ RongIMClient.prototype.getPublicServiceProfile = function (publicServiceType, publicServiceId, callback) { if (RongIMClient._memoryStore.depend.openMp) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "getPublicServiceProfile", false, arguments); RongIMClient._dataAccessProvider.getPublicServiceProfile(publicServiceType, publicServiceId, RongIMClient.logCallback(callback, "getPublicServiceProfile")); } }; /** * [pottingPublicSearchType ] 公众好查询类型 * @param {number} bussinessType [ 0-all 1-mp 2-mc] * @param {number} searchType [0-exact 1-fuzzy] */ RongIMClient.prototype.pottingPublicSearchType = function (bussinessType, searchType) { if (RongIMClient._memoryStore.depend.openMp) { var bits = 0; if (bussinessType == 0) { bits |= 3; if (searchType == 0) { bits |= 12; } else { bits |= 48; } } else if (bussinessType == 1) { bits |= 1; if (searchType == 0) { bits |= 8; } else { bits |= 32; } } else { bits |= 2; if (bussinessType == 0) { bits |= 4; } else { bits |= 16; } } return bits; } }; /** * [searchPublicService ]按公众服务类型搜索公众服务。 * @param {SearchType} searchType [搜索类型枚举。] * @param {string} keywords [搜索关键字。] * @param {ResultCallback} callback [搜索结果回调。] */ RongIMClient.prototype.searchPublicService = function (searchType, keywords, callback) { if (RongIMClient._memoryStore.depend.openMp) { RongIMLib.CheckParam.getInstance().check(["number", "string", "object"], "searchPublicService", false, arguments); var modules = new RongIMClient.Protobuf.SearchMpInput(); modules.setType(this.pottingPublicSearchType(0, searchType)); modules.setId(keywords); RongIMClient.bridge.queryMsg(29, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, RongIMClient.logCallback(callback, "searchPublicService"), "SearchMpOutput"); } }; /** * [searchPublicServiceByType ]按公众服务类型搜索公众服务。 * @param {PublicServiceType} publicServiceType [公众服务类型。] * @param {SearchType} searchType [搜索类型枚举。] * @param {string} keywords [搜索关键字。] * @param {ResultCallback} callback [搜索结果回调。] */ RongIMClient.prototype.searchPublicServiceByType = function (publicServiceType, searchType, keywords, callback) { if (RongIMClient._memoryStore.depend.openMp) { RongIMLib.CheckParam.getInstance().check(["number", "number", "string", "object"], "searchPublicServiceByType", false, arguments); var type = publicServiceType == RongIMLib.ConversationType.APP_PUBLIC_SERVICE ? 2 : 1; var modules = new RongIMClient.Protobuf.SearchMpInput(); modules.setType(this.pottingPublicSearchType(type, searchType)); modules.setId(keywords); RongIMClient.bridge.queryMsg(29, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, RongIMClient.logCallback(callback, "searchPublicServiceByType"), "SearchMpOutput"); } }; /** * [subscribePublicService ] 订阅公众号。 * @param {PublicServiceType} publicServiceType [公众服务类型。] * @param {string} publicServiceId [公共服务 Id。] * @param {OperationCallback} callback [订阅公众号回调。] */ RongIMClient.prototype.subscribePublicService = function (publicServiceType, publicServiceId, callback) { if (RongIMClient._memoryStore.depend.openMp) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "subscribePublicService", false, arguments); var modules = new RongIMClient.Protobuf.MPFollowInput(), me = this, follow = publicServiceType == RongIMLib.ConversationType.APP_PUBLIC_SERVICE ? "mcFollow" : "mpFollow"; modules.setId(publicServiceId); RongIMClient.bridge.queryMsg(follow, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function () { me.getRemotePublicServiceList({ onSuccess: function () { }, onError: function () { } }); callback.onSuccess(); }, onError: function (code) { var errorCode = code; RongIMClient.logger({ code: errorCode, funcName: "subscribePublicService" }); callback.onError(code); } }, "MPFollowOutput"); } }; /** * [unsubscribePublicService ] 取消订阅公众号。 * @param {PublicServiceType} publicServiceType [公众服务类型。] * @param {string} publicServiceId [公共服务 Id。] * @param {OperationCallback} callback [取消订阅公众号回调。] */ RongIMClient.prototype.unsubscribePublicService = function (publicServiceType, publicServiceId, callback) { if (RongIMClient._memoryStore.depend.openMp) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "unsubscribePublicService", false, arguments); var modules = new RongIMClient.Protobuf.MPFollowInput(), me = this, follow = publicServiceType == RongIMLib.ConversationType.APP_PUBLIC_SERVICE ? "mcUnFollow" : "mpUnFollow"; modules.setId(publicServiceId); RongIMClient.bridge.queryMsg(follow, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function () { RongIMClient._memoryStore.publicServiceMap.remove(publicServiceType, publicServiceId); callback.onSuccess(); }, onError: function (code) { var errorCode = code; RongIMClient.logger({ code: errorCode, funcName: "unsubscribePublicService" }); callback.onError(code); } }, "MPFollowOutput"); } }; // #endregion Public Service // #region Blacklist /** * [加入黑名单] * @param {string} userId [将被加入黑名单的用户Id] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.addToBlacklist = function (userId, callback) { RongIMLib.CheckParam.getInstance().check(["string|number", "object"], "addToBlacklist", false, arguments); RongIMClient._dataAccessProvider.addToBlacklist(userId, RongIMClient.logCallback(callback, "addToBlacklist")); }; /** * [获取黑名单列表] * @param {GetBlacklistCallback} callback [返回值,函数回调] */ RongIMClient.prototype.getBlacklist = function (callback) { RongIMLib.CheckParam.getInstance().check(["object"], "getBlacklist", false, arguments); RongIMClient._dataAccessProvider.getBlacklist(callback); }; /** * [得到指定人员再黑名单中的状态] * @param {string} userId [description] * @param {ResultCallback} callback [返回值,函数回调] */ //TODO 如果人员不在黑名单中,获取状态会出现异常 RongIMClient.prototype.getBlacklistStatus = function (userId, callback) { RongIMLib.CheckParam.getInstance().check(["string|number", "object"], "getBlacklistStatus", false, arguments); RongIMClient._dataAccessProvider.getBlacklistStatus(userId, RongIMClient.logCallback(callback, "getBlacklistStatus")); }; /** * [将指定用户移除黑名单] * @param {string} userId [将被移除的用户Id] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.removeFromBlacklist = function (userId, callback) { RongIMLib.CheckParam.getInstance().check(["string|number", "object"], "removeFromBlacklist", false, arguments); RongIMClient._dataAccessProvider.removeFromBlacklist(userId, RongIMClient.logCallback(callback, "removeFromBlacklist")); }; RongIMClient.prototype.getFileToken = function (fileType, callback) { RongIMLib.CheckParam.getInstance().check(["number", "object"], "getQnTkn", false, arguments); RongIMClient._dataAccessProvider.getFileToken(fileType, RongIMClient.logCallback(callback, "getFileToken")); }; RongIMClient.prototype.getFileUrl = function (fileType, fileName, oriName, callback) { RongIMLib.CheckParam.getInstance().check(["number", "string", "string|global|object|null", "object"], "getQnTkn", false, arguments); RongIMClient._dataAccessProvider.getFileUrl(fileType, fileName, oriName, RongIMClient.logCallback(callback, "getFileUrl")); }; ; // #endregion Blacklist // #region Real-time Location Service RongIMClient.prototype.addRealTimeLocationListener = function (conversationType, targetId, listener) { throw new Error("Not implemented yet"); }; RongIMClient.prototype.getRealTimeLocation = function (conversationType, targetId) { throw new Error("Not implemented yet"); }; RongIMClient.prototype.getRealTimeLocationCurrentState = function (conversationType, targetId) { throw new Error("Not implemented yet"); }; RongIMClient.prototype.getRealTimeLocationParticipants = function (conversationType, targetId) { throw new Error("Not implemented yet"); }; RongIMClient.prototype.joinRealTimeLocation = function (conversationType, targetId) { throw new Error("Not implemented yet"); }; RongIMClient.prototype.quitRealTimeLocation = function (conversationType, targetId) { throw new Error("Not implemented yet"); }; RongIMClient.prototype.startRealTimeLocation = function (conversationType, targetId) { throw new Error("Not implemented yet"); }; RongIMClient.prototype.updateRealTimeLocationStatus = function (conversationType, targetId, latitude, longitude) { throw new Error("Not implemented yet"); }; // #endregion Real-time Location Service // # startVoIP RongIMClient.prototype.startCall = function (converType, targetId, userIds, mediaType, extra, callback) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "array", "number", "string", "object"], "startCall", false, arguments); if (RongIMClient._memoryStore.voipStategy) { RongIMClient._voipProvider.startCall(converType, targetId, userIds, mediaType, extra, RongIMClient.logCallback(callback, "startCall")); } else { var errorCode = RongIMLib.ErrorCode.VOIP_NOT_AVALIABLE; RongIMClient.logger({ code: errorCode, funcName: "startCall" }); callback.onError(RongIMLib.ErrorCode.VOIP_NOT_AVALIABLE); } }; RongIMClient.prototype.joinCall = function (mediaType, callback) { RongIMLib.CheckParam.getInstance().check(['number', 'object'], "joinCall", false, arguments); if (RongIMClient._memoryStore.voipStategy) { RongIMClient._voipProvider.joinCall(mediaType, RongIMClient.logCallback(callback, "joinCall")); } else { var errorCode = RongIMLib.ErrorCode.VOIP_NOT_AVALIABLE; RongIMClient.logger({ code: errorCode, funcName: "joinCall" }); callback.onError(RongIMLib.ErrorCode.VOIP_NOT_AVALIABLE); } }; RongIMClient.prototype.hungupCall = function (converType, targetId, reason) { RongIMLib.CheckParam.getInstance().check(["number", "string", "number"], "hungupCall", false, arguments); if (RongIMClient._memoryStore.voipStategy) { RongIMClient._voipProvider.hungupCall(converType, targetId, reason); } }; RongIMClient.prototype.changeMediaType = function (converType, targetId, mediaType, callback) { RongIMLib.CheckParam.getInstance().check(["number", "string", "number", "object"], "changeMediaType", false, arguments); if (RongIMClient._memoryStore.voipStategy) { RongIMClient._voipProvider.changeMediaType(converType, targetId, mediaType, RongIMClient.logCallback(callback, "changeMediaType")); } else { var errorCode = RongIMLib.ErrorCode.VOIP_NOT_AVALIABLE; RongIMClient.logger({ code: errorCode, funcName: "changeMediaType" }); callback.onError(RongIMLib.ErrorCode.VOIP_NOT_AVALIABLE); } }; // # endVoIP RongIMClient.prototype.getUnreadMentionedMessages = function (conversationType, targetId) { return RongIMClient._dataAccessProvider.getUnreadMentionedMessages(conversationType, targetId); }; RongIMClient.prototype.clearListeners = function () { RongIMClient._dataAccessProvider.clearListeners(); }; // UserStatus start RongIMClient.prototype.getUserStatus = function (userId, callback) { RongIMClient._dataAccessProvider.getUserStatus(userId, RongIMClient.logCallback(callback, "getUserStatus")); }; RongIMClient.prototype.setUserStatus = function (status, callback) { RongIMClient._dataAccessProvider.setUserStatus(status, RongIMClient.logCallback(callback, "setUserStatus")); }; RongIMClient.prototype.setUserStatusListener = function (params, callback) { var userIds = params.userIds; var multiple = params.multiple; RongIMClient.userStatusObserver.watch({ key: userIds, func: callback, multiple: multiple }); RongIMClient._dataAccessProvider.setUserStatusListener(params, callback); }; RongIMClient.LogFactory = {}; RongIMClient.MessageType = {}; RongIMClient.RegisterMessage = {}; RongIMClient._memoryStore = { listenerList: [], isPullFinished: true, syncMsgQueue: [] }; RongIMClient.isNotPullMsg = false; RongIMClient.userStatusObserver = null; RongIMClient.sdkver = '2.3.1'; RongIMClient.otherDeviceLoginCount = 0; RongIMClient.serverStore = { index: 0 }; RongIMClient.userStatusListener = null; return RongIMClient; })(); RongIMLib.RongIMClient = RongIMClient; })(RongIMLib || (RongIMLib = {})); //用于连接通道 var RongIMLib; (function (RongIMLib) { (function (Qos) { Qos[Qos["AT_MOST_ONCE"] = 0] = "AT_MOST_ONCE"; Qos[Qos["AT_LEAST_ONCE"] = 1] = "AT_LEAST_ONCE"; Qos[Qos["EXACTLY_ONCE"] = 2] = "EXACTLY_ONCE"; Qos[Qos["DEFAULT"] = 3] = "DEFAULT"; })(RongIMLib.Qos || (RongIMLib.Qos = {})); var Qos = RongIMLib.Qos; (function (Type) { Type[Type["CONNECT"] = 1] = "CONNECT"; Type[Type["CONNACK"] = 2] = "CONNACK"; Type[Type["PUBLISH"] = 3] = "PUBLISH"; Type[Type["PUBACK"] = 4] = "PUBACK"; Type[Type["QUERY"] = 5] = "QUERY"; Type[Type["QUERYACK"] = 6] = "QUERYACK"; Type[Type["QUERYCON"] = 7] = "QUERYCON"; Type[Type["SUBSCRIBE"] = 8] = "SUBSCRIBE"; Type[Type["SUBACK"] = 9] = "SUBACK"; Type[Type["UNSUBSCRIBE"] = 10] = "UNSUBSCRIBE"; Type[Type["UNSUBACK"] = 11] = "UNSUBACK"; Type[Type["PINGREQ"] = 12] = "PINGREQ"; Type[Type["PINGRESP"] = 13] = "PINGRESP"; Type[Type["DISCONNECT"] = 14] = "DISCONNECT"; })(RongIMLib.Type || (RongIMLib.Type = {})); var Type = RongIMLib.Type; var _topic = ["invtDiz", "crDiz", "qnUrl", "userInf", "dizInf", "userInf", "joinGrp", "quitDiz", "exitGrp", "evctDiz", ["", "ppMsgP", "pdMsgP", "pgMsgP", "chatMsg", "pcMsgP", "", "pmcMsgN", "pmpMsgN"], "pdOpen", "rename", "uGcmpr", "qnTkn", "destroyChrm", "createChrm", "exitChrm", "queryChrm", "joinChrm", "pGrps", "addBlack", "rmBlack", "getBlack", "blackStat", "addRelation", "qryRelation", "delRelation", "pullMp", "schMp", "qnTkn", "qnUrl", "qryVoipK", "delMsg", "qryCHMsg", "getUserStatus", "setUserStatus", "subUserStatus", "cleanHisMsg"]; var Channel = (function () { function Channel(cb, self) { this.connectionStatus = -1; var appId = self.appId; var token = encodeURIComponent(self.token); var sdkVer = self.sdkVer; var apiVer = self.apiVer; this.self = self; this.socket = Socket.getInstance().createServer(); var that = this; var storage = RongIMLib.RongIMClient._storageProvider; var servers = storage.getItem('servers'); servers = JSON.parse(servers); var startConnect = function (host) { var tpl = '{host}/websocket?appId={appId}&token={token}&sdkVer={sdkVer}&apiVer={apiVer}'; that.url = RongIMLib.RongUtil.tplEngine(tpl, { host: host, appId: appId, token: token, sdkVer: sdkVer, apiVer: apiVer }); that.socket.connect(that.url, cb); // 临时兼容 Comet 逻辑,Comet 中用到 var userId = storage.getItem('rong_current_user'); RongIMLib.Navigation.Endpoint = { host: host, userId: userId }; }; var connectMap = { ws: function () { // 所有链接计算器,超过 15 秒后认为所有 CMP 地址均不可用 var totalTimer = new RongIMLib.Timer({ timeout: 1 * 1000 * 15 }); var timers = []; var elements = []; var isFinished = false; var clearHandler = function () { for (var i = 0; i < timers.length; i++) { var timer = timers[i]; clearTimeout(timer); } for (var i = 0; i < elements.length; i++) { var el = elements[i]; document.body.removeChild(el); } }; var request = function (config, callback) { var url = config.url; var time = config.time; if (isFinished) { return; } var timer = setTimeout(function () { var el = document.createElement("script"); el.src = url; document.body.appendChild(el); el.onerror = function () { if (isFinished) { return; } clearHandler(); isFinished = true; totalTimer.pause(); var url = el.src; callback(url); }; elements.push(el); }, time); timers.push(timer); }; var snifferCallback = function (url) { var reg = /(http|https):\/\/([^\/]+)/i; var host = url.match(reg)[2]; startConnect(host); }; var snifferTpl = '//{server}/{path}'; for (var i = 0; i < servers.length; i++) { var server = RongIMLib.RongUtil.tplEngine(snifferTpl, { server: servers[i], path: i }); if (server) { request({ url: server, time: i * 1000 }, snifferCallback); } } totalTimer.resume(function () { clearHandler(); that.socket.fire("StatusChanged", RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE); }); }, comet: function () { var host = servers[0]; startConnect(host); } }; var depend = RongIMLib.RongIMClient._memoryStore.depend; var isPolling = depend.isPolling; var type = isPolling ? 'comet' : 'ws'; connectMap[type](); //注册状态改变观察者 var StatusEvent = Channel._ConnectionStatusListener; var hasEvent = (typeof StatusEvent == "object"); var me = this; me.socket.on("StatusChanged", function (code) { if (!hasEvent) { throw new Error("setConnectStatusListener:Parameter format is incorrect"); } me.connectionStatus = code; setTimeout(function () { StatusEvent.onChanged(code); }); var isDisconnected = (code == RongIMLib.ConnectionStatus.DISCONNECTED); if (isDisconnected) { self.clearHeartbeat(); } var isOtherDevice = (code == RongIMLib.ConnectionStatus.KICKED_OFFLINE_BY_OTHER_CLIENT); if (isOtherDevice) { // 累计其他设备登陆次数,超过 5 次后,自动销毁内部对象 // 删除位置:ServerDataProivder.prototype.connect RongIMLib.RongIMClient.otherDeviceLoginCount++; } }); //注册message观察者 this.socket.on("message", self.handler.handleMessage); //注册断开连接观察者 this.socket.on("disconnect", function (status) { that.socket.fire("StatusChanged", status ? status : 2); }); } Channel.prototype.writeAndFlush = function (val) { this.socket.send(val); }; Channel.prototype.reconnect = function (callback) { RongIMLib.MessageIdHandler.clearMessageId(); this.socket = this.socket.reconnect(); if (callback) { this.self.reconnectObj = callback; } }; Channel.prototype.disconnect = function (status) { this.socket.disconnect(status); }; return Channel; })(); RongIMLib.Channel = Channel; var Socket = (function () { function Socket() { this.socket = null; this._events = {}; } Socket.getInstance = function () { return new Socket(); }; Socket.prototype.connect = function (url, cb) { if (this.socket) { if (url) { RongIMLib.RongIMClient._storageProvider.setItem("rongSDK", this.checkTransport()); this.on("connect", cb || new Function); } if (url) { this.currentURL = url; } this.socket.createTransport(url); } return this; }; Socket.prototype.createServer = function () { var transport = this.getTransport(this.checkTransport()); if (transport === null) { throw new Error("the channel was not supported"); } return transport; }; Socket.prototype.getTransport = function (transportType) { if (transportType == Socket.XHR_POLLING) { this.socket = new RongIMLib.PollingTransportation(this); } else if (transportType == Socket.WEBSOCKET) { this.socket = new RongIMLib.SocketTransportation(this); } return this; }; Socket.prototype.send = function (data) { if (this.socket) { if (this.checkTransport() == Socket.WEBSOCKET) { this.socket.send(data); } else { this.socket.send(this._encode(data)); } } }; Socket.prototype.onMessage = function (data) { this.fire("message", data); }; Socket.prototype.disconnect = function (status) { this.socket.disconnect(status); this.fire("disconnect", status); return this; }; Socket.prototype.reconnect = function () { if (this.currentURL && RongIMLib.RongIMClient._storageProvider.getItem("rongSDK")) { return this.connect(this.currentURL, null); } else { throw new Error("reconnect:no have URL"); } }; /** * [checkTransport 返回通道类型] */ Socket.prototype.checkTransport = function () { if (RongIMLib.RongIMClient._memoryStore.depend.isPolling) { RongIMLib.Transportations._TransportType = Socket.XHR_POLLING; } return RongIMLib.Transportations._TransportType; }; Socket.prototype.fire = function (x, args) { if (x in this._events) { for (var i = 0, ii = this._events[x].length; i < ii; i++) { this._events[x][i](args); } } return this; }; Socket.prototype.on = function (x, func) { if (!(typeof func == "function" && x)) { return this; } if (x in this._events) { RongIMLib.MessageUtil.indexOf(this._events, func) == -1 && this._events[x].push(func); } else { this._events[x] = [func]; } return this; }; Socket.prototype.removeEvent = function (x, fn) { if (x in this._events) { for (var a = 0, l = this._events[x].length; a < l; a++) { if (this._events[x][a] == fn) { this._events[x].splice(a, 1); } } } return this; }; Socket.prototype._encode = function (x) { var str = "?messageid=" + x.getMessageId() + "&header=" + x.getHeaderFlag() + "&sessionid=" + RongIMLib.RongIMClient._storageProvider.getItem("sId" + RongIMLib.Navigation.Endpoint.userId); if (!/(PubAckMessage|QueryConMessage)/.test(x._name)) { str += "&topic=" + x.getTopic() + "&targetid=" + (x.getTargetId() || ""); } return { url: str, data: "getData" in x ? x.getData() : "" }; }; //消息通道常量,所有和通道相关判断均用 XHR_POLLING WEBSOCKET两属性 Socket.XHR_POLLING = "xhr-polling"; Socket.WEBSOCKET = "websocket"; return Socket; })(); RongIMLib.Socket = Socket; //连接端消息累 var Client = (function () { function Client(token, appId) { this.timeoutMillis = 6000; this.timeout_ = 0; this.sdkVer = ''; this.apiVer = Math.floor(Math.random() * 1e6); this.channel = null; this.handler = null; this.userId = ""; this.reconnectObj = {}; this.heartbeat = 0; this.pullMsgHearbeat = 0; this.chatroomId = ""; this.SyncTimeQueue = []; this.cacheMessageIds = []; this.token = token; this.appId = appId; this.SyncTimeQueue.state = "complete"; this.sdkVer = RongIMLib.RongIMClient.sdkver; } Client.prototype.resumeTimer = function () { var me = this; this.timeout_ = setTimeout(function () { me.channel.disconnect(); }, this.timeoutMillis); }; Client.prototype.pauseTimer = function () { if (this.timeout_) { clearTimeout(this.timeout_); this.timeout_ = 0; } }; Client.prototype.connect = function (_callback) { //实例消息处理类 this.handler = new MessageHandler(this); //设置连接回调 this.handler.setConnectCallback(_callback); //实例通道类型 var me = this; this.channel = new Channel(function () { RongIMLib.Transportations._TransportType == Socket.WEBSOCKET && me.keepLive(); }, this); //触发状态改变观察者 this.channel.socket.fire("StatusChanged", RongIMLib.ConnectionStatus.CONNECTING); //没有返回地址就手动抛出错误 //_callback.onError(ConnectionState.NOT_AUTHORIZED); }; Client.prototype.checkSocket = function (callback) { var me = this; me.channel.writeAndFlush(new RongIMLib.PingReqMessage()); var count = 0; var checkTimeout = setInterval(function () { if (!RongIMLib.RongIMClient._memoryStore.isFirstPingMsg) { clearInterval(checkTimeout); callback.onSuccess(); } else { if (count > 15) { clearInterval(checkTimeout); callback.onError(); } } count++; }, 100); }; Client.prototype.keepLive = function () { if (this.heartbeat > 0) { clearInterval(this.heartbeat); } var me = this; me.heartbeat = setInterval(function () { me.resumeTimer(); me.channel.writeAndFlush(new RongIMLib.PingReqMessage()); }, 30000); if (me.pullMsgHearbeat > 0) { clearInterval(me.pullMsgHearbeat); } me.pullMsgHearbeat = setInterval(function () { me.syncTime(true, undefined, undefined, false); }, 180000); }; Client.prototype.clearHeartbeat = function () { clearInterval(this.heartbeat); this.heartbeat = 0; this.pauseTimer(); clearInterval(this.pullMsgHearbeat); this.pullMsgHearbeat = 0; }; Client.prototype.publishMessage = function (_topic, _data, _targetId, _callback, _msg) { var msgId = RongIMLib.MessageIdHandler.messageIdPlus(this.channel.reconnect); if (!msgId) { return; } var msg = new RongIMLib.PublishMessage(_topic, _data, _targetId); msg.setMessageId(msgId); if (_callback) { msg.setQos(Qos.AT_LEAST_ONCE); this.handler.putCallback(new RongIMLib.PublishCallback(_callback.onSuccess, _callback.onError), msg.getMessageId(), _msg); } else { msg.setQos(Qos.AT_MOST_ONCE); } this.channel.writeAndFlush(msg); }; Client.prototype.queryMessage = function (_topic, _data, _targetId, _qos, _callback, pbtype) { if (_topic == "userInf") { if (Client.userInfoMapping[_targetId]) { _callback.onSuccess(Client.userInfoMapping[_targetId]); return; } } var msgId = RongIMLib.MessageIdHandler.messageIdPlus(this.channel.reconnect); if (!msgId) { return; } var msg = new RongIMLib.QueryMessage(_topic, _data, _targetId); msg.setMessageId(msgId); msg.setQos(_qos); this.handler.putCallback(new RongIMLib.QueryCallback(_callback.onSuccess, _callback.onError), msg.getMessageId(), pbtype); this.channel.writeAndFlush(msg); }; Client.prototype.invoke = function (isPullMsg, chrmId, offlineMsg) { var time, modules, str, me = this, target, temp = this.SyncTimeQueue.shift(); if (temp == undefined) { return; } this.SyncTimeQueue.state = "pending"; if (temp.type != 2) { //普通消息 time = RongIMLib.RongIMClient._storageProvider.getItem(this.userId) || '0'; modules = new RongIMLib.RongIMClient.Protobuf.SyncRequestMsg(); modules.setIspolling(false); str = "pullMsg"; target = this.userId; } else { //聊天室消息 target = temp.chrmId || me.chatroomId; time = RongIMLib.RongIMClient._memoryStore.lastReadTime.get(target + Bridge._client.userId + "CST") || 0; modules = new RongIMLib.RongIMClient.Protobuf.ChrmPullMsg(); modules.setCount(0); str = "chrmPull"; if (!target) { throw new Error("syncTime:Received messages of chatroom but was not init"); } } //判断服务器给的时间是否消息本地存储的时间,小于的话不执行拉取操作,进行一下步队列操作 if (temp.pulltime <= time) { this.SyncTimeQueue.state = "complete"; this.invoke(isPullMsg, target); return; } if (isPullMsg && 'setIsPullSend' in modules) { modules.setIsPullSend(true); } modules.setSyncTime(time); //发送queryMessage请求 this.queryMessage(str, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), target, Qos.AT_LEAST_ONCE, { onSuccess: function (collection) { var sync = RongIMLib.MessageUtil.int64ToTimestamp(collection.syncTime), symbol = target; //把返回时间戳存入本地,普通消息key为userid,聊天室消息key为userid+'CST';value都为服务器返回的时间戳 if (str == "chrmPull") { symbol += Bridge._client.userId + "CST"; RongIMLib.RongIMClient._memoryStore.lastReadTime.set(symbol, sync); } else { var storage = RongIMLib.RongIMClient._storageProvider; if (sync > storage.getItem(symbol)) { storage.setItem(symbol, sync); } } //防止因离线消息造成会话列表不为空而无法从服务器拉取会话列表。 //offlineMsg && (RongIMClient._memoryStore.isSyncRemoteConverList = true); me.SyncTimeQueue.state = "complete"; me.invoke(isPullMsg, target); //把拉取到的消息逐条传给消息监听器 var list = collection.list; for (var i = 0, len = list.length, count = len; i < len; i++) { if (!(list[i].msgId in me.cacheMessageIds)) { count -= 1; var message = list[i]; var sentTime = RongIMLib.MessageUtil.int64ToTimestamp(message.dataTime); if (sentTime > time) { Bridge._client.handler.onReceived(message, undefined, offlineMsg, count); var arrLen = me.cacheMessageIds.unshift(list[i].msgId); if (arrLen > 20) { me.cacheMessageIds.length = 20; } } } } var isPullFinished = collection.finished; RongIMLib.RongIMClient._memoryStore.isPullFinished = isPullFinished; }, onError: function (error) { me.SyncTimeQueue.state = "complete"; me.invoke(isPullMsg, target); } }, "DownStreamMessages"); }; Client.prototype.syncTime = function (_type, pullTime, chrmId, offlineMsg) { this.SyncTimeQueue.push({ type: _type, pulltime: pullTime, chrmId: chrmId }); //如果队列中只有一个成员并且状态已经完成就执行invoke方法 if (this.SyncTimeQueue.length == 1 && this.SyncTimeQueue.state == "complete") { this.invoke(!_type, chrmId, offlineMsg); } }; Client.prototype.__init = function (f) { this.channel = new Channel(f, this); }; Client.userInfoMapping = {}; return Client; })(); RongIMLib.Client = Client; //连接类,实现imclient与connect_client的连接 var Bridge = (function () { function Bridge() { } Bridge.getInstance = function () { return new Bridge(); }; //连接服务器 Bridge.prototype.connect = function (appKey, token, callback) { if (!RongIMLib.RongIMClient.Protobuf) { return; } Bridge._client = new RongIMLib.Navigation().connect(appKey, token, callback); return Bridge._client; }; Bridge.prototype.setListener = function (_changer) { if (typeof _changer == "object") { if (typeof _changer.onChanged == "function") { Channel._ConnectionStatusListener = _changer; } else if (typeof _changer.onReceived == "function") { Channel._ReceiveMessageListener = _changer; } } }; Bridge.prototype.reconnect = function (callabck) { Bridge._client.channel.reconnect(callabck); }; Bridge.prototype.disconnect = function () { Bridge._client.channel.disconnect(2); }; //执行queryMessage请求 Bridge.prototype.queryMsg = function (topic, content, targetId, callback, pbname) { if (typeof topic != "string") { topic = _topic[topic]; } Bridge._client.queryMessage(topic, content, targetId, Qos.AT_MOST_ONCE, callback, pbname); }; //发送消息 执行publishMessage 请求 Bridge.prototype.pubMsg = function (topic, content, targetId, callback, msg, methodType) { if (typeof methodType == 'number') { if (methodType == RongIMLib.MethodType.CUSTOMER_SERVICE) { Bridge._client.publishMessage("pcuMsgP", content, targetId, callback, msg); } else if (methodType == RongIMLib.MethodType.RECALL) { Bridge._client.publishMessage("recallMsg", content, targetId, callback, msg); } } else { Bridge._client.publishMessage(_topic[10][topic], content, targetId, callback, msg); } }; return Bridge; })(); RongIMLib.Bridge = Bridge; var MessageHandler = (function () { function MessageHandler(client) { this.map = {}; this.connectCallback = null; if (!Channel._ReceiveMessageListener) { throw new Error("please set onReceiveMessageListener"); } this._onReceived = Channel._ReceiveMessageListener.onReceived; this._client = client; this.syncMsgMap = new Object; } //把对象推入回调对象队列中,并启动定时器 MessageHandler.prototype.putCallback = function (callbackObj, _publishMessageId, _msg) { var item = { Callback: callbackObj, Message: _msg }; item.Callback.resumeTimer(); this.map[_publishMessageId] = item; }; //设置连接回调对象,启动定时器 MessageHandler.prototype.setConnectCallback = function (_connectCallback) { if (_connectCallback) { this.connectCallback = new RongIMLib.ConnectAck(_connectCallback.onSuccess, _connectCallback.onError, this._client); } }; MessageHandler.prototype.onReceived = function (msg, pubAckItem, offlineMsg, leftCount, isSync) { //实体对象 var entity, //解析完成的消息对象 message, //会话对象 con; if (msg._name != "PublishMessage") { entity = msg; RongIMLib.RongIMClient._storageProvider.setItem(this._client.userId, RongIMLib.MessageUtil.int64ToTimestamp(entity.dataTime)); } else { if (msg.getTopic() == "s_ntf") { entity = RongIMLib.RongIMClient.Protobuf.NotifyMsg.decode(msg.getData()); this._client.syncTime(entity.type, RongIMLib.MessageUtil.int64ToTimestamp(entity.time), entity.chrmId); return; } else if (msg.getTopic() == "s_msg") { entity = RongIMLib.RongIMClient.Protobuf.DownStreamMessage.decode(msg.getData()); var timestamp = RongIMLib.MessageUtil.int64ToTimestamp(entity.dataTime); RongIMLib.RongIMClient._storageProvider.setItem(this._client.userId, timestamp); RongIMLib.RongIMClient._memoryStore.lastReadTime.get(this._client.userId, timestamp); } else if (msg.getTopic() == "s_stat") { entity = RongIMLib.RongIMClient.Protobuf.GetUserStatusOutput.decode(msg.getData()); entity = RongIMLib.RongInnerTools.convertUserStatus(entity); RongIMLib.RongIMClient.userStatusObserver.notify({ key: entity.userId, entity: entity }); return; } else { if (Bridge._client.sdkVer && Bridge._client.sdkVer == "1.0.0") { return; } if (!RongIMLib.RongIMClient._memoryStore.isPullFinished) { return; } entity = RongIMLib.RongIMClient.Protobuf.UpStreamMessage.decode(msg.getData()); var tmpTopic = msg.getTopic(); var tmpType = tmpTopic.substr(0, 2); if (tmpType == "pp") { entity.type = 1; } else if (tmpType == "pd") { entity.type = 2; } else if (tmpType == "pg") { entity.type = 3; } else if (tmpType == "ch") { entity.type = 4; } else if (tmpType == "pc") { entity.type = 5; } //复用字段,targetId 以此为准 entity.groupId = msg.getTargetId(); entity.fromUserId = this._client.userId; entity.dataTime = Date.parse(new Date().toString()); } if (!entity) { return; } } //解析实体对象为消息对象。 message = RongIMLib.MessageUtil.messageParser(entity, this._onReceived, offlineMsg); var isRecall = (msg.getTopic && msg.getTopic() == "recallMsg"); if (isRecall) { var content = message.content; message.conversationType = content.conversationType; message.targetId = content.targetId; message.messageId = null; } if (pubAckItem) { message.messageUId = pubAckItem.getMessageUId(); message.sentTime = pubAckItem.getTimestamp(); RongIMLib.RongIMClient._storageProvider.setItem(this._client.userId, message.sentTime); } if (message === null) { return; } var isSend = (message.messageDirection == RongIMLib.MessageDirection.SEND); if (isSend) { var storageProvider = RongIMLib.RongIMClient._storageProvider; var userId = RongIMLib.Bridge._client.userId; var lastSentTime = storageProvider.getItem('last_sentTime_' + userId) || 0; if (message.sentTime <= lastSentTime && !isSync) { return; } } // 设置会话时间戳并且判断是否传递 message 发送消息未处理会话时间戳 // key:'converST_' + 当前用户 + conversationType + targetId // RongIMClient._storageProvider.setItem('converST_' + Bridge._client.userId + message.conversationType + message.targetId, message.sentTime); var msgTag = RongIMLib.RongIMClient.MessageParams[message.messageType].msgTag; var isPersited = msgTag.isPersited; if (isPersited) { RongIMLib.RongIMClient._dataAccessProvider.getConversation(message.conversationType, message.targetId, { onSuccess: function (con) { if (!con) { con = RongIMLib.RongIMClient.getInstance().createConversation(message.conversationType, message.targetId, ""); } if (message.messageDirection == RongIMLib.MessageDirection.RECEIVE && (entity.status & 64) == 64) { var mentioneds = RongIMLib.RongIMClient._storageProvider.getItem("mentioneds_" + Bridge._client.userId + '_' + message.conversationType + '_' + message.targetId); var key = message.conversationType + '_' + message.targetId, info = {}; if (message.content && message.content.mentionedInfo) { info[key] = { uid: message.messageUId, time: message.sentTime, mentionedInfo: message.content.mentionedInfo }; RongIMLib.RongIMClient._storageProvider.setItem("mentioneds_" + Bridge._client.userId + '_' + message.conversationType + '_' + message.targetId, JSON.stringify(info)); mentioneds = JSON.stringify(info); } if (mentioneds) { var info = JSON.parse(mentioneds); con.mentionedMsg = info[key]; } } // var isCounted = con.conversationType != 0 && message.senderUserId != Bridge._client.userId && message.receivedStatus != RongIMLib.ReceivedStatus.RETRIEVED && message.messageType != RongIMLib.RongIMClient.MessageType["ReadReceiptRequestMessage"] && message.messageType != RongIMLib.RongIMClient.MessageType["ReadReceiptResponseMessage"] var isReceiver = message.messageDirection == 2; if (isReceiver && msgTag.getMessageTag() > 0) { con.unreadMessageCount = con.unreadMessageCount + 1; if (RongIMLib.RongUtil.supportLocalStorage()) { var count = RongIMLib.RongIMClient._storageProvider.getItem("cu" + Bridge._client.userId + con.conversationType + con.targetId); // 与本地存储会话合并 RongIMLib.RongIMClient._storageProvider.setItem("cu" + Bridge._client.userId + con.conversationType + message.targetId, Number(count) + 1); } } con.receivedTime = new Date().getTime(); con.receivedStatus = message.receivedStatus; con.senderUserId = message.sendUserId; con.notificationStatus = RongIMLib.ConversationNotificationStatus.DO_NOT_DISTURB; con.latestMessageId = message.messageId; con.latestMessage = message; con.sentTime = message.sentTime; RongIMLib.RongIMClient._dataAccessProvider.addConversation(con, { onSuccess: function (data) { }, onError: function () { } }); }, onError: function (error) { } }); } if (message.conversationType == RongIMLib.ConversationType.CUSTOMER_SERVICE && (message.messageType == "ChangeModeResponseMessage" || message.messageType == "SuspendMessage" || message.messageType == "HandShakeResponseMessage" || message.messageType == "TerminateMessage" || message.messageType == "CustomerStatusUpdateMessage" || message.messageType == "TextMessage" || message.messageType == "InformationNotificationMessage")) { if (!RongIMLib.RongIMClient._memoryStore.custStore["isInit"]) { return; } } if (message.conversationType == RongIMLib.ConversationType.CUSTOMER_SERVICE && message.messageType != "HandShakeResponseMessage") { if (!RongIMLib.RongIMClient._memoryStore.custStore[message.targetId]) { return; } if (message.messageType == "TerminateMessage") { if (RongIMLib.RongIMClient._memoryStore.custStore[message.targetId].sid != message.content.sid) { return; } } } if (message.messageType === RongIMLib.RongIMClient.MessageType["HandShakeResponseMessage"]) { var session = message.content.data; RongIMLib.RongIMClient._memoryStore.custStore[message.targetId] = session; if (session.serviceType == RongIMLib.CustomerType.ONLY_HUMAN || session.serviceType == RongIMLib.CustomerType.HUMAN_FIRST) { if (session.notAutoCha == "1") { RongIMLib.RongIMClient.getInstance().switchToHumanMode(message.targetId, { onSuccess: function () { }, onError: function () { } }); } } } var d = new Date(), m = d.getMonth() + 1, date = d.getFullYear() + '/' + (m.toString().length == 1 ? '0' + m : m) + '/' + d.getDate(); //new Date(date).getTime() - message.sentTime < 1 逻辑判断 超过 1 天未收的 ReadReceiptRequestMessage 离线消息自动忽略。 var dealtime = new Date(date).getTime() - message.sentTime < 0; if (RongIMLib.RongUtil.supportLocalStorage() && message.messageType === RongIMLib.RongIMClient.MessageType["ReadReceiptRequestMessage"] && dealtime && message.messageDirection == RongIMLib.MessageDirection.SEND) { var sentkey = Bridge._client.userId + message.content.messageUId + "SENT"; RongIMLib.RongIMClient._storageProvider.setItem(sentkey, JSON.stringify({ count: 0, dealtime: message.sentTime, userIds: {} })); } else if (RongIMLib.RongUtil.supportLocalStorage() && message.messageType === RongIMLib.RongIMClient.MessageType["ReadReceiptRequestMessage"] && dealtime) { var reckey = Bridge._client.userId + message.conversationType + message.targetId + 'RECEIVED', recData = JSON.parse(RongIMLib.RongIMClient._storageProvider.getItem(reckey)); if (recData) { if (message.senderUserId in recData) { if (recData[message.senderUserId].uIds && recData[message.senderUserId].uIds && recData[message.senderUserId].uIds.indexOf(message.content.messageUId) == -1) { recData[message.senderUserId].uIds.push(message.content.messageUId); recData[message.senderUserId].dealtime = message.sentTime; recData[message.senderUserId].isResponse = false; RongIMLib.RongIMClient._storageProvider.setItem(reckey, JSON.stringify(recData)); } else { return; } } else { var objSon = { uIds: [message.content.messageUId], dealtime: message.sentTime, isResponse: false }; recData[message.senderUserId] = objSon; RongIMLib.RongIMClient._storageProvider.setItem(reckey, JSON.stringify(recData)); } } else { var obj = {}; obj[message.senderUserId] = { uIds: [message.content.messageUId], dealtime: message.sentTime, isResponse: false }; RongIMLib.RongIMClient._storageProvider.setItem(reckey, JSON.stringify(obj)); } } if (RongIMLib.RongUtil.supportLocalStorage() && message.messageType === RongIMLib.RongIMClient.MessageType["ReadReceiptResponseMessage"] && dealtime) { var receiptResponseMsg = message.content, uIds = receiptResponseMsg.receiptMessageDic[Bridge._client.userId], sentkey = "", sentObj; message.receiptResponse || (message.receiptResponse = {}); if (uIds) { var cbuIds = []; for (var i = 0, len = uIds.length; i < len; i++) { sentkey = Bridge._client.userId + uIds[i] + "SENT"; sentObj = JSON.parse(RongIMLib.RongIMClient._storageProvider.getItem(sentkey)); if (sentObj && !(message.senderUserId in sentObj.userIds)) { cbuIds.push(uIds[i]); sentObj.count += 1; sentObj.userIds[message.senderUserId] = message.sentTime; message.receiptResponse[uIds[i]] = sentObj.count; RongIMLib.RongIMClient._storageProvider.setItem(sentkey, JSON.stringify(sentObj)); } } receiptResponseMsg.receiptMessageDic[Bridge._client.userId] = cbuIds; message.content = receiptResponseMsg; } } var that = this; if (RongIMLib.RongIMClient._voipProvider && ['AcceptMessage', 'RingingMessage', 'HungupMessage', 'InviteMessage', 'MediaModifyMessage', 'MemberModifyMessage'].indexOf(message.messageType) > -1) { setTimeout(function () { RongIMLib.RongIMClient._voipProvider.onReceived(message); }); } else { var lcount = leftCount || 0; // TODO: Web 暂时未获取是否还有更多离线消息,所以复制 false 默认没有更多离线消息 var hasMore = false; RongIMLib.RongIMClient._dataAccessProvider.addMessage(message.conversationType, message.targetId, message, { onSuccess: function (ret) { setTimeout(function () { that._onReceived(ret, lcount, hasMore); }); }, onError: function (error) { setTimeout(function () { that._onReceived(message, lcount, hasMore); }); } }); } }; MessageHandler.prototype.handleMessage = function (msg) { if (!msg) { return; } switch (msg._name) { case "ConnAckMessage": Bridge._client.handler.connectCallback.process(msg.getStatus(), msg.getUserId(), msg.getTimestamp()); break; case "PublishMessage": if (!msg.getSyncMsg() && msg.getQos() != 0) { Bridge._client.channel.writeAndFlush(new RongIMLib.PubAckMessage(msg.getMessageId())); } // TODO && -> if (msg.getSyncMsg() && !RongIMLib.RongIMClient._memoryStore.depend.isPolling) { Bridge._client.handler.syncMsgMap[msg.getMessageId()] = msg; } else { //如果是PublishMessage就把该对象给onReceived方法执行处理 Bridge._client.handler.onReceived(msg); } break; case "QueryAckMessage": if (msg.getQos() != 0) { Bridge._client.channel.writeAndFlush(new RongIMLib.QueryConMessage(msg.getMessageId())); } var temp = Bridge._client.handler.map[msg.getMessageId()]; if (temp) { //执行回调操作 temp.Callback.process(msg.getStatus(), msg.getData(), msg.getDate(), temp.Message); delete Bridge._client.handler.map[msg.getMessageId()]; } break; case "PubAckMessage": var item = Bridge._client.handler.map[msg.getMessageId()]; if (item) { item.Callback.process(msg.getStatus() || 0, msg.getMessageUId(), msg.getTimestamp(), item.Message, msg.getMessageId()); delete Bridge._client.handler.map[msg.getMessageId()]; } else { var userId = RongIMLib.Bridge._client.userId; RongIMLib.RongIMClient._storageProvider.setItem('last_sentTime_' + userId, msg.timestamp); Bridge._client.handler.onReceived(Bridge._client.handler.syncMsgMap[msg.messageId], msg, null, null, true); delete Bridge._client.handler.syncMsgMap[msg.getMessageId()]; } break; case "PingRespMessage": if (RongIMLib.RongIMClient._memoryStore.isFirstPingMsg) { RongIMLib.RongIMClient._memoryStore.isFirstPingMsg = false; } else { Bridge._client.pauseTimer(); } break; case "DisconnectMessage": Bridge._client.channel.disconnect(msg.getStatus()); break; default: } }; return MessageHandler; })(); RongIMLib.MessageHandler = MessageHandler; })(RongIMLib || (RongIMLib = {})); var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; /// var RongIMLib; (function (RongIMLib) { var MessageCallback = (function () { function MessageCallback(error) { this.timeout = null; this.onError = null; if (error && typeof error == "number") { this.timeoutMillis = error; } else { this.timeoutMillis = 30000; this.onError = error; } } MessageCallback.prototype.resumeTimer = function () { var me = this; if (this.timeoutMillis > 0 && !this.timeout) { this.timeout = setTimeout(function () { me.readTimeOut(true); }, this.timeoutMillis); } }; MessageCallback.prototype.pauseTimer = function () { if (this.timeout) { clearTimeout(this.timeout); this.timeout = null; } }; MessageCallback.prototype.readTimeOut = function (isTimeout) { if (isTimeout && this.onError) { this.onError(RongIMLib.ErrorCode.TIMEOUT); } else { this.pauseTimer(); } }; return MessageCallback; })(); RongIMLib.MessageCallback = MessageCallback; var CallbackMapping = (function () { function CallbackMapping() { this.publicServiceList = []; } CallbackMapping.getInstance = function () { return new CallbackMapping(); }; CallbackMapping.prototype.pottingProfile = function (item) { var temp; this.profile = new RongIMLib.PublicServiceProfile(); temp = JSON.parse(item.extra); this.profile.isGlobal = temp.isGlobal; this.profile.introduction = temp.introduction; this.profile.menu = temp.menu; this.profile.hasFollowed = temp.follow; this.profile.publicServiceId = item.mpid; this.profile.name = item.name; this.profile.portraitUri = item.portraitUrl; this.profile.conversationType = item.type == "mc" ? RongIMLib.ConversationType.APP_PUBLIC_SERVICE : RongIMLib.ConversationType.PUBLIC_SERVICE; this.publicServiceList.push(this.profile); }; CallbackMapping.prototype.mapping = function (entity, tag) { switch (tag) { case "GetUserInfoOutput": var userInfo = new RongIMLib.UserInfo(entity.userId, entity.userName, entity.userPortrait); return userInfo; case "GetQNupTokenOutput": return { deadline: RongIMLib.MessageUtil.int64ToTimestamp(entity.deadline), token: entity.token }; case "GetQNdownloadUrlOutput": return { downloadUrl: entity.downloadUrl }; case "CreateDiscussionOutput": return entity.id; case "ChannelInfoOutput": var disInfo = new RongIMLib.Discussion(); disInfo.creatorId = entity.adminUserId; disInfo.id = entity.channelId; disInfo.memberIdList = entity.firstTenUserIds; disInfo.name = entity.channelName; disInfo.isOpen = entity.openStatus; return disInfo; case "GroupHashOutput": return entity.result; case "QueryBlackListOutput": return entity.userIds; case "SearchMpOutput": case "PullMpOutput": if (entity.info) { var self = this; Array.forEach(entity.info, function (item) { setTimeout(self.pottingProfile(item), 100); }); } return this.publicServiceList; default: return entity; } }; return CallbackMapping; })(); RongIMLib.CallbackMapping = CallbackMapping; var PublishCallback = (function (_super) { __extends(PublishCallback, _super); function PublishCallback(_cb, _timeout) { _super.call(this, _timeout); this._cb = _cb; this._timeout = _timeout; } PublishCallback.prototype.process = function (_status, messageUId, timestamp, _msg, messageId) { this.readTimeOut(); if (_status == 0 || _status == 21502) { if (_msg) { _msg.setSentStatus = _status; } var userId = RongIMLib.Bridge._client.userId; var stroageProvider = RongIMLib.RongIMClient._storageProvider; stroageProvider.setItem(userId, timestamp); stroageProvider.setItem('last_sentTime_' + userId, timestamp); RongIMLib.RongIMClient._memoryStore.lastReadTime.get(userId, timestamp); this._cb({ messageUId: messageUId, timestamp: timestamp, messageId: messageId }, _status); } else { this._timeout(_status, { messageUId: messageUId, timestamp: timestamp, messageId: messageId }); } }; PublishCallback.prototype.readTimeOut = function (x) { MessageCallback.prototype.readTimeOut.call(this, x); }; return PublishCallback; })(MessageCallback); RongIMLib.PublishCallback = PublishCallback; var QueryCallback = (function (_super) { __extends(QueryCallback, _super); function QueryCallback(_cb, _timeout) { _super.call(this, _timeout); this._cb = _cb; this._timeout = _timeout; } QueryCallback.prototype.process = function (status, data, serverTime, pbtype) { this.readTimeOut(); if (pbtype && data && status == 0) { try { data = CallbackMapping.getInstance().mapping(RongIMLib.RongIMClient.Protobuf[pbtype].decode(data), pbtype); } catch (e) { this._timeout(RongIMLib.ErrorCode.UNKNOWN); return; } if ("GetUserInfoOutput" == pbtype) { //pb类型为GetUserInfoOutput的话就把data放入userinfo缓存队列 RongIMLib.Client.userInfoMapping[data.userId] = data; } this._cb(data); } else { status > 0 ? this._timeout(status) : this._cb(status); } }; QueryCallback.prototype.readTimeOut = function (x) { MessageCallback.prototype.readTimeOut.call(this, x); }; return QueryCallback; })(MessageCallback); RongIMLib.QueryCallback = QueryCallback; var ConnectAck = (function (_super) { __extends(ConnectAck, _super); function ConnectAck(_cb, _timeout, client) { _super.call(this, _timeout); this._client = client; this._cb = _cb; this._timeout = _timeout; } ConnectAck.prototype.process = function (status, userId, timestamp) { this.readTimeOut(); if (status == 0) { this._client.userId = userId; var self = this; if (!RongIMLib.RongIMClient._memoryStore.depend.isPolling && RongIMLib.RongIMClient._memoryStore.isFirstPingMsg) { RongIMLib.Bridge._client.checkSocket({ onSuccess: function () { if (!RongIMLib.RongIMClient.isNotPullMsg) { self._client.syncTime(undefined, undefined, undefined, true); } }, onError: function () { RongIMLib.RongIMClient._memoryStore.isFirstPingMsg = false; RongIMLib.RongIMClient.getInstance().disconnect(); RongIMLib.RongIMClient.connect(RongIMLib.RongIMClient._memoryStore.token, RongIMLib.RongIMClient._memoryStore.callback); } }); } else { if (!RongIMLib.RongIMClient.isNotPullMsg) { self._client.syncTime(undefined, undefined, undefined, true); } } if (this._client.reconnectObj.onSuccess) { this._client.reconnectObj.onSuccess(userId); delete this._client.reconnectObj.onSuccess; } else { var me = this; setTimeout(function () { me._cb(userId); }, 500); } RongIMLib.Bridge._client.channel.socket.fire("StatusChanged", 0); RongIMLib.RongIMClient._memoryStore.connectAckTime = timestamp; if (!(new Date().getTime() - timestamp)) { RongIMLib.RongIMClient._memoryStore.deltaTime = 0; } else { RongIMLib.RongIMClient._memoryStore.deltaTime = new Date().getTime() - timestamp; } } else if (status == 6) { //重定向 连错 CMP var x = {}; var me = this; new RongIMLib.Navigation().getServerEndpoint(this._client.token, this._client.appId, function () { me._client.clearHeartbeat(); new RongIMLib.Client(me._client.token, me._client.appId).__init.call(x, function () { RongIMLib.Transportations._TransportType == "websocket" && me._client.keepLive(); }); me._client.channel.socket.fire("StatusChanged", 2); }, me._timeout, false); } else { RongIMLib.Bridge._client.channel.socket.socket._status = status; if (this._client.reconnectObj.onError) { this._client.reconnectObj.onError(status); delete this._client.reconnectObj.onError; } else { this._timeout(status); } } }; ConnectAck.prototype.readTimeOut = function (x) { MessageCallback.prototype.readTimeOut.call(this, x); }; return ConnectAck; })(MessageCallback); RongIMLib.ConnectAck = ConnectAck; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var Navigation = (function () { function Navigation() { window.getServerEndpoint = function (result) { var server = result.server; if (server) { server += ','; } var backupServer = result.backupServer || ''; var tpl = '{server}{backupServer}'; var servers = RongIMLib.RongUtil.tplEngine(tpl, { server: server, backupServer: backupServer }); var storage = RongIMLib.RongIMClient._storageProvider; servers = servers.split(','); storage.setItem('servers', JSON.stringify(servers)); var token = RongIMLib.Bridge._client.token; var uid = RongIMLib.InnerUtil.getUId(token); storage.setItem('rc_uid', uid); var userId = result.userId; storage.setItem('current_user', userId); if (result.voipCallInfo) { var callInfo = JSON.parse(result.voipCallInfo); RongIMLib.RongIMClient._memoryStore.voipStategy = callInfo.strategy; storage.setItem("voipStrategy", callInfo.strategy); } //替换本地存储的导航信息 var openMp = result.openMp; storage.setItem('openMp' + uid, openMp); RongIMLib.RongIMClient._memoryStore.depend.openMp = openMp; }; } Navigation.clear = function () { var storage = RongIMLib.RongIMClient._storageProvider; storage.removeItem('rc_uid'); storage.removeItem('serverIndex'); }; Navigation.prototype.connect = function (appId, token, callback) { var oldAppId = RongIMLib.RongIMClient._storageProvider.getItem("appId"); //如果appid和本地存储的不一样,清空所有本地存储数据 if (oldAppId && oldAppId != appId) { RongIMLib.RongIMClient._storageProvider.clearItem(); RongIMLib.RongIMClient._storageProvider.setItem("appId", appId); } if (!oldAppId) { RongIMLib.RongIMClient._storageProvider.setItem("appId", appId); } var client = new RongIMLib.Client(token, appId); var me = this; this.getServerEndpoint(token, appId, function () { client.connect(callback); }, callback.onError, true); return client; }; Navigation.prototype.getServerEndpoint = function (token, appId, _onsuccess, _onerror, unignore) { if (unignore) { //根据token生成MD5截取8-16下标的数据与本地存储的导航信息进行比对 //如果信息和上次的通道类型都一样,不执行navi请求,用本地存储的导航信息连接服务器 var uId = md5(token).slice(8, 16); var storage = RongIMLib.RongIMClient._storageProvider; var transportType = storage.getItem("rongSDK"); var isSameType = (RongIMLib.Transportations._TransportType == transportType); var _old = storage.getItem('rc_uid'); var isSameUser = (_old == uId); if (isSameUser && isSameType) { RongIMLib.RongIMClient._memoryStore.voipStategy = storage.getItem("voipStrategy"); var openMp = storage.getItem('openMp' + uId); RongIMLib.RongIMClient._memoryStore.depend.openMp = openMp; setTimeout(function () { _onsuccess(); }, 300); return; } } Navigation.clear(); //导航信息,切换Url对象的key进行线上线下测试操作 var xss = document.createElement("script"); //进行jsonp请求 var depend = RongIMLib.RongIMClient._memoryStore.depend; var domain = depend.navi; var path = (depend.isPolling ? 'cometnavi' : 'navi'); token = encodeURIComponent(token); var sdkver = RongIMLib.RongIMClient.sdkver; var tpl = '{domain}/{path}.js?appId={appId}&token={token}&callBack=getServerEndpoint&v={sdkver}'; var url = RongIMLib.RongUtil.tplEngine(tpl, { domain: domain, path: path, appId: appId, token: token, sdkver: sdkver }); xss.src = url; document.body.appendChild(xss); xss.onerror = function () { _onerror(RongIMLib.ConnectionState.TOKEN_INCORRECT); }; if ("onload" in xss) { xss.onload = _onsuccess; } else { xss.onreadystatechange = function () { xss.readyState == "loaded" && _onsuccess(); }; } }; Navigation.Endpoint = new Object; return Navigation; })(); RongIMLib.Navigation = Navigation; })(RongIMLib || (RongIMLib = {})); // TODO: 统一变量、方法等命名规范 var RongIMLib; (function (RongIMLib) { /** * 消息基类 */ var BaseMessage = (function () { function BaseMessage(arg) { this._name = "BaseMessage"; this.lengthSize = 0; if (arg instanceof RongIMLib.Header) { this._header = arg; } else { this._header = new RongIMLib.Header(arg, false, RongIMLib.Qos.AT_MOST_ONCE, false); } } BaseMessage.prototype.read = function (In, length) { this.readMessage(In, length); }; BaseMessage.prototype.write = function (Out) { var binaryHelper = new RongIMLib.BinaryHelper(); var out = binaryHelper.convertStream(Out); this._headerCode = this.getHeaderFlag(); out.write(this._headerCode); this.writeMessage(out); return out; }; BaseMessage.prototype.getHeaderFlag = function () { return this._header.encode(); }; BaseMessage.prototype.getLengthSize = function () { return this.lengthSize; }; BaseMessage.prototype.toBytes = function () { return this.write([]).getBytesArray(); }; BaseMessage.prototype.isRetained = function () { return this._header.retain; }; BaseMessage.prototype.setRetained = function (retain) { this._header.retain = retain; }; BaseMessage.prototype.setQos = function (qos) { this._header.qos = Object.prototype.toString.call(qos) == "[object Object]" ? qos : RongIMLib.Qos[qos]; }; BaseMessage.prototype.setDup = function (dup) { this._header.dup = dup; }; BaseMessage.prototype.isDup = function () { return this._header.dup; }; BaseMessage.prototype.getType = function () { return this._header.type; }; BaseMessage.prototype.getQos = function () { return this._header.qos; }; BaseMessage.prototype.messageLength = function () { return 0; }; BaseMessage.prototype.writeMessage = function (out) { }; BaseMessage.prototype.readMessage = function (In, length) { }; BaseMessage.prototype.init = function (args) { var valName, nana, me = this; for (nana in args) { if (!args.hasOwnProperty(nana)) { continue; } valName = nana.replace(/^\w/, function (x) { var tt = x.charCodeAt(0); return "set" + (tt >= 0x61 ? String.fromCharCode(tt & ~32) : x); }); if (valName in me) { if (nana == "status") { me[valName](disconnectStatus[args[nana]] ? disconnectStatus[args[nana]] : args[nana]); } else { me[valName](args[nana]); } } } }; return BaseMessage; })(); RongIMLib.BaseMessage = BaseMessage; /** *连接消息类型 */ var ConnectMessage = (function (_super) { __extends(ConnectMessage, _super); function ConnectMessage(header) { _super.call(this, arguments.length == 0 || arguments.length == 3 ? RongIMLib.Type.CONNECT : arguments[0]); this._name = "ConnectMessage"; this.CONNECT_HEADER_SIZE = 12; this.protocolId = "RCloud"; this.binaryHelper = new RongIMLib.BinaryHelper(); this.protocolVersion = 3; switch (arguments.length) { case 0: case 1: case 3: if (!arguments[0] || arguments[0].length > 64) { throw new Error("ConnectMessage:Client Id cannot be null and must be at most 64 characters long: " + arguments[0]); } this.clientId = arguments[0]; this.cleanSession = arguments[1]; this.keepAlive = arguments[2]; break; } } ConnectMessage.prototype.messageLength = function () { var payloadSize = this.binaryHelper.toMQttString(this.clientId).length; payloadSize += this.binaryHelper.toMQttString(this.willTopic).length; payloadSize += this.binaryHelper.toMQttString(this.will).length; payloadSize += this.binaryHelper.toMQttString(this.appId).length; payloadSize += this.binaryHelper.toMQttString(this.token).length; return payloadSize + this.CONNECT_HEADER_SIZE; }; ConnectMessage.prototype.readMessage = function (stream) { this.protocolId = stream.readUTF(); this.protocolVersion = stream.readByte(); var cFlags = stream.readByte(); this.hasAppId = (cFlags & 128) > 0; this.hasToken = (cFlags & 64) > 0; this.retainWill = (cFlags & 32) > 0; this.willQos = cFlags >> 3 & 3; this.hasWill = (cFlags & 4) > 0; this.cleanSession = (cFlags & 32) > 0; this.keepAlive = stream.read() * 256 + stream.read(); this.clientId = stream.readUTF(); if (this.hasWill) { this.willTopic = stream.readUTF(); this.will = stream.readUTF(); } if (this.hasAppId) { try { this.appId = stream.readUTF(); } catch (ex) { throw new Error(ex); } } if (this.hasToken) { try { this.token = stream.readUTF(); } catch (ex) { throw new Error(ex); } } return stream; }; ConnectMessage.prototype.writeMessage = function (out) { var stream = this.binaryHelper.convertStream(out); stream.writeUTF(this.protocolId); stream.write(this.protocolVersion); var flags = this.cleanSession ? 2 : 0; flags |= this.hasWill ? 4 : 0; flags |= this.willQos ? this.willQos >> 3 : 0; flags |= this.retainWill ? 32 : 0; flags |= this.hasToken ? 64 : 0; flags |= this.hasAppId ? 128 : 0; stream.write(flags); stream.writeChar(this.keepAlive); stream.writeUTF(this.clientId); if (this.hasWill) { stream.writeUTF(this.willTopic); stream.writeUTF(this.will); } if (this.hasAppId) { stream.writeUTF(this.appId); } if (this.hasToken) { stream.writeUTF(this.token); } return stream; }; return ConnectMessage; })(BaseMessage); RongIMLib.ConnectMessage = ConnectMessage; /** *连接应答类型 */ var ConnAckMessage = (function (_super) { __extends(ConnAckMessage, _super); function ConnAckMessage(header) { _super.call(this, arguments.length == 0 ? RongIMLib.Type.CONNACK : arguments.length == 1 ? arguments[0] instanceof RongIMLib.Header ? arguments[0] : RongIMLib.Type.CONNACK : null); this._name = "ConnAckMessage"; this.MESSAGE_LENGTH = 2; this.binaryHelper = new RongIMLib.BinaryHelper(); var me = this; switch (arguments.length) { case 0: case 1: if (!(arguments[0] instanceof RongIMLib.Header)) { if (arguments[0] in RongIMLib.ConnectionState) { if (arguments[0] == null) { throw new Error("ConnAckMessage:The status of ConnAskMessage can't be null"); } me.setStatus(arguments[0]); } } break; } } ; ConnAckMessage.prototype.messageLength = function () { var length = this.MESSAGE_LENGTH; if (this.userId) { length += this.binaryHelper.toMQttString(this.userId).length; } return length; }; ; ConnAckMessage.prototype.readMessage = function (_in, msglength) { _in.read(); var result = +_in.read(); if (result >= 0 && result <= 12) { this.setStatus(result); } else { throw new Error("Unsupported CONNACK code:" + result); } if (msglength > this.MESSAGE_LENGTH) { this.setUserId(_in.readUTF()); var sessionId = _in.readUTF(); var timestamp = _in.readLong(); this.setTimestamp(timestamp); } }; ; ConnAckMessage.prototype.writeMessage = function (out) { var stream = this.binaryHelper.convertStream(out); stream.write(128); switch (+status) { case 0: case 1: case 2: case 5: case 6: stream.write(+status); break; case 3: case 4: stream.write(3); break; default: throw new Error("Unsupported CONNACK code:" + status); } if (this.userId) { stream.writeUTF(this.userId); } return stream; }; ; ConnAckMessage.prototype.setStatus = function (x) { this.status = x; }; ; ConnAckMessage.prototype.setUserId = function (_userId) { this.userId = _userId; }; ; ConnAckMessage.prototype.getStatus = function () { return this.status; }; ; ConnAckMessage.prototype.getUserId = function () { return this.userId; }; ; ConnAckMessage.prototype.setTimestamp = function (x) { this.timestrap = x; }; ; ConnAckMessage.prototype.getTimestamp = function () { return this.timestrap; }; return ConnAckMessage; })(BaseMessage); RongIMLib.ConnAckMessage = ConnAckMessage; /** *断开消息类型 */ var DisconnectMessage = (function (_super) { __extends(DisconnectMessage, _super); function DisconnectMessage(header) { _super.call(this, header instanceof RongIMLib.Header ? header : RongIMLib.Type.DISCONNECT); this._name = "DisconnectMessage"; this.MESSAGE_LENGTH = 2; this.binaryHelper = new RongIMLib.BinaryHelper(); if (!(header instanceof RongIMLib.Header)) { if (header in RongIMLib.ConnectionStatus) { this.status = header; } } } DisconnectMessage.prototype.messageLength = function () { return this.MESSAGE_LENGTH; }; DisconnectMessage.prototype.readMessage = function (_in) { _in.read(); var result = +_in.read(); if (result >= 0 && result <= 5) { this.setStatus(disconnectStatus[result] ? disconnectStatus[result] : result); } else { throw new Error("Unsupported CONNACK code:" + result); } }; DisconnectMessage.prototype.writeMessage = function (Out) { var out = this.binaryHelper.convertStream(Out); out.write(0); if (+status >= 1 && +status <= 3) { out.write((+status) - 1); } else { throw new Error("Unsupported CONNACK code:" + status); } }; DisconnectMessage.prototype.setStatus = function (x) { this.status = x; }; ; DisconnectMessage.prototype.getStatus = function () { return this.status; }; ; return DisconnectMessage; })(BaseMessage); RongIMLib.DisconnectMessage = DisconnectMessage; /** *请求消息信令 */ var PingReqMessage = (function (_super) { __extends(PingReqMessage, _super); function PingReqMessage(header) { _super.call(this, (header && header instanceof RongIMLib.Header) ? header : RongIMLib.Type.PINGREQ); this._name = "PingReqMessage"; } return PingReqMessage; })(BaseMessage); RongIMLib.PingReqMessage = PingReqMessage; /** *响应消息信令 */ var PingRespMessage = (function (_super) { __extends(PingRespMessage, _super); function PingRespMessage(header) { _super.call(this, (header && header instanceof RongIMLib.Header) ? header : RongIMLib.Type.PINGRESP); this._name = "PingRespMessage"; } return PingRespMessage; })(BaseMessage); RongIMLib.PingRespMessage = PingRespMessage; /** *封装MesssageId */ var RetryableMessage = (function (_super) { __extends(RetryableMessage, _super); function RetryableMessage(argu) { _super.call(this, argu); this._name = "RetryableMessage"; this.binaryHelper = new RongIMLib.BinaryHelper(); } RetryableMessage.prototype.messageLength = function () { return 2; }; RetryableMessage.prototype.writeMessage = function (Out) { var out = this.binaryHelper.convertStream(Out), Id = this.getMessageId(), lsb = Id & 255, msb = (Id & 65280) >> 8; out.write(msb); out.write(lsb); return out; }; RetryableMessage.prototype.readMessage = function (_in, msgLength) { var msgId = _in.read() * 256 + _in.read(); this.setMessageId(parseInt(msgId, 10)); }; RetryableMessage.prototype.setMessageId = function (_messageId) { this.messageId = _messageId; }; RetryableMessage.prototype.getMessageId = function () { return this.messageId; }; return RetryableMessage; })(BaseMessage); RongIMLib.RetryableMessage = RetryableMessage; /** *发送消息应答(双向) *qos为1必须给出应答(所有消息类型一样) */ var PubAckMessage = (function (_super) { __extends(PubAckMessage, _super); function PubAckMessage(header) { _super.call(this, (header instanceof RongIMLib.Header) ? header : RongIMLib.Type.PUBACK); this.msgLen = 2; this.date = 0; this.millisecond = 0; this.timestamp = 0; this.binaryHelper = new RongIMLib.BinaryHelper(); this._name = "PubAckMessage"; if (!(header instanceof RongIMLib.Header)) { _super.prototype.setMessageId.call(this, header); } } PubAckMessage.prototype.messageLength = function () { return this.msgLen; }; PubAckMessage.prototype.writeMessage = function (Out) { var out = this.binaryHelper.convertStream(Out); RetryableMessage.prototype.writeMessage.call(this, out); }; PubAckMessage.prototype.readMessage = function (_in, msgLength) { RetryableMessage.prototype.readMessage.call(this, _in); this.date = _in.readInt(); this.status = _in.read() * 256 + _in.read(); this.millisecond = _in.read() * 256 + _in.read(); this.timestamp = this.date * 1000 + this.millisecond; this.messageUId = _in.readUTF(); }; PubAckMessage.prototype.setStatus = function (x) { this.status = x; }; PubAckMessage.prototype.setTimestamp = function (timestamp) { this.timestamp = timestamp; }; PubAckMessage.prototype.setMessageUId = function (messageUId) { this.messageUId = messageUId; }; PubAckMessage.prototype.getStatus = function () { return this.status; }; PubAckMessage.prototype.getDate = function () { return this.date; }; PubAckMessage.prototype.getTimestamp = function () { return this.timestamp; }; PubAckMessage.prototype.getMessageUId = function () { return this.messageUId; }; return PubAckMessage; })(RetryableMessage); RongIMLib.PubAckMessage = PubAckMessage; /** *发布消息 */ var PublishMessage = (function (_super) { __extends(PublishMessage, _super); function PublishMessage(header, two, three) { _super.call(this, (arguments.length == 1 && header instanceof RongIMLib.Header) ? header : arguments.length == 3 ? RongIMLib.Type.PUBLISH : 0); this._name = "PublishMessage"; this.binaryHelper = new RongIMLib.BinaryHelper(); this.syncMsg = false; if (arguments.length == 3) { this.topic = header; this.targetId = three; this.data = typeof two == "string" ? this.binaryHelper.toMQttString(two) : two; } } PublishMessage.prototype.messageLength = function () { var length = 10; length += this.binaryHelper.toMQttString(this.topic).length; length += this.binaryHelper.toMQttString(this.targetId).length; length += this.data.length; return length; }; PublishMessage.prototype.writeMessage = function (Out) { var out = this.binaryHelper.convertStream(Out); out.writeUTF(this.topic); out.writeUTF(this.targetId); RetryableMessage.prototype.writeMessage.apply(this, arguments); out.write(this.data); }; ; PublishMessage.prototype.readMessage = function (_in, msgLength) { var pos = 6; this.date = _in.readInt(); this.topic = _in.readUTF(); pos += this.binaryHelper.toMQttString(this.topic).length; this.targetId = _in.readUTF(); pos += this.binaryHelper.toMQttString(this.targetId).length; RetryableMessage.prototype.readMessage.apply(this, arguments); this.data = new Array(msgLength - pos); this.data = _in.read(this.data); }; ; PublishMessage.prototype.setTopic = function (x) { this.topic = x; }; PublishMessage.prototype.setData = function (x) { this.data = x; }; PublishMessage.prototype.setTargetId = function (x) { this.targetId = x; }; PublishMessage.prototype.setDate = function (x) { this.date = x; }; PublishMessage.prototype.setSyncMsg = function (x) { this.syncMsg = x; }; //是否是其他端同步过来的消息 PublishMessage.prototype.getSyncMsg = function () { return this.syncMsg; }; PublishMessage.prototype.getTopic = function () { return this.topic; }; PublishMessage.prototype.getData = function () { return this.data; }; PublishMessage.prototype.getTargetId = function () { return this.targetId; }; PublishMessage.prototype.getDate = function () { return this.date; }; return PublishMessage; })(RetryableMessage); RongIMLib.PublishMessage = PublishMessage; /** *请求查询 */ var QueryMessage = (function (_super) { __extends(QueryMessage, _super); function QueryMessage(header, two, three) { _super.call(this, header instanceof RongIMLib.Header ? header : arguments.length == 3 ? RongIMLib.Type.QUERY : null); this.binaryHelper = new RongIMLib.BinaryHelper(); this._name = "QueryMessage"; if (arguments.length == 3) { this.data = typeof two == "string" ? this.binaryHelper.toMQttString(two) : two; this.topic = header; this.targetId = three; } } QueryMessage.prototype.messageLength = function () { var length = 0; length += this.binaryHelper.toMQttString(this.topic).length; length += this.binaryHelper.toMQttString(this.targetId).length; length += 2; length += this.data.length; return length; }; QueryMessage.prototype.writeMessage = function (Out) { var out = this.binaryHelper.convertStream(Out); out.writeUTF(this.topic); out.writeUTF(this.targetId); RetryableMessage.prototype.writeMessage.call(this, out); out.write(this.data); }; QueryMessage.prototype.readMessage = function (_in, msgLength) { var pos = 0; this.topic = _in.readUTF(); this.targetId = _in.readUTF(); pos += this.binaryHelper.toMQttString(this.topic).length; pos += this.binaryHelper.toMQttString(this.targetId).length; this.readMessage.apply(this, arguments); pos += 2; this.data = new Array(msgLength - pos); _in.read(this.data); }; QueryMessage.prototype.setTopic = function (x) { this.topic = x; }; QueryMessage.prototype.setData = function (x) { this.data = x; }; QueryMessage.prototype.setTargetId = function (x) { this.targetId = x; }; QueryMessage.prototype.getTopic = function () { return this.topic; }; QueryMessage.prototype.getData = function () { return this.data; }; QueryMessage.prototype.getTargetId = function () { return this.targetId; }; return QueryMessage; })(RetryableMessage); RongIMLib.QueryMessage = QueryMessage; /** *请求查询确认 */ var QueryConMessage = (function (_super) { __extends(QueryConMessage, _super); function QueryConMessage(messageId) { _super.call(this, (messageId instanceof RongIMLib.Header) ? messageId : RongIMLib.Type.QUERYCON); this._name = "QueryConMessage"; if (!(messageId instanceof RongIMLib.Header)) { _super.prototype.setMessageId.call(this, messageId); } } return QueryConMessage; })(RetryableMessage); RongIMLib.QueryConMessage = QueryConMessage; /** *请求查询应答 */ var QueryAckMessage = (function (_super) { __extends(QueryAckMessage, _super); function QueryAckMessage(header) { _super.call(this, header); this._name = "QueryAckMessage"; this.binaryHelper = new RongIMLib.BinaryHelper(); } QueryAckMessage.prototype.readMessage = function (In, msgLength) { RetryableMessage.prototype.readMessage.call(this, In); this.date = In.readInt(); this.setStatus(In.read() * 256 + In.read()); if (msgLength > 0) { this.data = new Array(msgLength - 8); this.data = In.read(this.data); } }; QueryAckMessage.prototype.getData = function () { return this.data; }; QueryAckMessage.prototype.getStatus = function () { return this.status; }; QueryAckMessage.prototype.getDate = function () { return this.date; }; QueryAckMessage.prototype.setDate = function (x) { this.date = x; }; QueryAckMessage.prototype.setStatus = function (x) { this.status = x; }; QueryAckMessage.prototype.setData = function (x) { this.data = x; }; return QueryAckMessage; })(RetryableMessage); RongIMLib.QueryAckMessage = QueryAckMessage; })(RongIMLib || (RongIMLib = {})); /// var RongIMLib; (function (RongIMLib) { /** * 把消息对象写入流中 * 发送消息时用到 */ var MessageOutputStream = (function () { function MessageOutputStream(_out) { var binaryHelper = new RongIMLib.BinaryHelper(); this.out = binaryHelper.convertStream(_out); } MessageOutputStream.prototype.writeMessage = function (msg) { if (msg instanceof RongIMLib.BaseMessage) { msg.write(this.out); } }; return MessageOutputStream; })(); RongIMLib.MessageOutputStream = MessageOutputStream; /** * 流转换为消息对象 * 服务器返回消息时用到 */ var MessageInputStream = (function () { function MessageInputStream(In, isPolling) { if (!isPolling) { var _in = new RongIMLib.BinaryHelper().convertStream(In); this.flags = _in.readByte(); this._in = _in; } else { this.flags = In["headerCode"]; } this.header = new RongIMLib.Header(this.flags); this.isPolling = isPolling; this.In = In; } MessageInputStream.prototype.readMessage = function () { switch (this.header.getType()) { case 1: this.msg = new RongIMLib.ConnectMessage(this.header); break; case 2: this.msg = new RongIMLib.ConnAckMessage(this.header); break; case 3: this.msg = new RongIMLib.PublishMessage(this.header); this.msg.setSyncMsg(this.header.getSyncMsg()); break; case 4: this.msg = new RongIMLib.PubAckMessage(this.header); break; case 5: this.msg = new RongIMLib.QueryMessage(this.header); break; case 6: this.msg = new RongIMLib.QueryAckMessage(this.header); break; case 7: this.msg = new RongIMLib.QueryConMessage(this.header); break; case 9: case 11: case 13: this.msg = new RongIMLib.PingRespMessage(this.header); break; case 8: case 10: case 12: this.msg = new RongIMLib.PingReqMessage(this.header); break; case 14: this.msg = new RongIMLib.DisconnectMessage(this.header); break; default: throw new Error("No support for deserializing " + this.header.getType() + " messages"); } if (this.isPolling) { this.msg.init(this.In); } else { this.msg.read(this._in, this.In.length - 1); } return this.msg; }; return MessageInputStream; })(); RongIMLib.MessageInputStream = MessageInputStream; var Header = (function () { function Header(_type, _retain, _qos, _dup) { this.retain = false; this.qos = RongIMLib.Qos.AT_LEAST_ONCE; this.dup = false; this.syncMsg = false; if (_type && +_type == _type && arguments.length == 1) { this.retain = (_type & 1) > 0; this.qos = (_type & 6) >> 1; this.dup = (_type & 8) > 0; this.type = (_type >> 4) & 15; this.syncMsg = (_type & 8) == 8; } else { this.type = _type; this.retain = _retain; this.qos = _qos; this.dup = _dup; } } Header.prototype.getSyncMsg = function () { return this.syncMsg; }; Header.prototype.getType = function () { return this.type; }; Header.prototype.encode = function () { var me = this; switch (this.qos) { case RongIMLib.Qos[0]: me.qos = RongIMLib.Qos.AT_MOST_ONCE; break; case RongIMLib.Qos[1]: me.qos = RongIMLib.Qos.AT_LEAST_ONCE; break; case RongIMLib.Qos[2]: me.qos = RongIMLib.Qos.EXACTLY_ONCE; break; case RongIMLib.Qos[3]: me.qos = RongIMLib.Qos.DEFAULT; break; } var _byte = (this.type << 4); _byte |= this.retain ? 1 : 0; _byte |= this.qos << 1; _byte |= this.dup ? 8 : 0; return _byte; }; Header.prototype.toString = function () { return "Header [type=" + this.type + ",retain=" + this.retain + ",qos=" + this.qos + ",dup=" + this.dup + "]"; }; return Header; })(); RongIMLib.Header = Header; /** * 二进制帮助对象 */ var BinaryHelper = (function () { function BinaryHelper() { } BinaryHelper.prototype.writeUTF = function (str, isGetBytes) { var back = [], byteSize = 0; for (var i = 0, len = str.length; i < len; i++) { var code = str.charCodeAt(i); if (code >= 0 && code <= 127) { byteSize += 1; back.push(code); } else if (code >= 128 && code <= 2047) { byteSize += 2; back.push((192 | (31 & (code >> 6)))); back.push((128 | (63 & code))); } else if (code >= 2048 && code <= 65535) { byteSize += 3; back.push((224 | (15 & (code >> 12)))); back.push((128 | (63 & (code >> 6)))); back.push((128 | (63 & code))); } } for (var i = 0, len = back.length; i < len; i++) { if (back[i] > 255) { back[i] &= 255; } } if (isGetBytes) { return back; } if (byteSize <= 255) { return [0, byteSize].concat(back); } else { return [byteSize >> 8, byteSize & 255].concat(back); } }; BinaryHelper.prototype.readUTF = function (arr) { if (Object.prototype.toString.call(arr) == "[object String]") { return arr; } var UTF = "", _arr = arr; for (var i = 0, len = _arr.length; i < len; i++) { if (_arr[i] < 0) { _arr[i] += 256; } ; var one = _arr[i].toString(2), v = one.match(/^1+?(?=0)/); if (v && one.length == 8) { var bytesLength = v[0].length, // store = _arr[i].toString(2).slice(7 - bytesLength); store = ''; for (var st = 0; st < bytesLength; st++) { store += _arr[st + i].toString(2).slice(2); } UTF += String.fromCharCode(parseInt(store, 2)); i += bytesLength - 1; } else { UTF += String.fromCharCode(_arr[i]); } } return UTF; }; /** * [convertStream 将参数x转化为RongIMStream对象] * @param {any} x [参数] */ BinaryHelper.prototype.convertStream = function (x) { if (x instanceof RongIMStream) { return x; } else { return new RongIMStream(x); } }; BinaryHelper.prototype.toMQttString = function (str) { return this.writeUTF(str); }; return BinaryHelper; })(); RongIMLib.BinaryHelper = BinaryHelper; var RongIMStream = (function () { function RongIMStream(arr) { //当前流执行的起始位置 this.position = 0; //当前流写入的多少字节 this.writen = 0; this.poolLen = 0; this.binaryHelper = new BinaryHelper(); this.pool = arr; this.poolLen = arr.length; } RongIMStream.prototype.check = function () { return this.position >= this.pool.length; }; RongIMStream.prototype.readInt = function () { if (this.check()) { return -1; } var end = ""; for (var i = 0; i < 4; i++) { var t = this.pool[this.position++].toString(16); if (t.length == 1) { t = "0" + t; } end += t.toString(16); } return parseInt(end, 16); }; RongIMStream.prototype.readLong = function () { if (this.check()) { return -1; } var end = ""; for (var i = 0; i < 8; i++) { var t = this.pool[this.position++].toString(16); if (t.length == 1) { t = "0" + t; } end += t; } return parseInt(end, 16); }; RongIMStream.prototype.readTimestamp = function () { if (this.check()) { return -1; } var end = ""; for (var i = 0; i < 8; i++) { end += this.pool[this.position++].toString(16); } end = end.substring(2, 8); return parseInt(end, 16); }; RongIMStream.prototype.readUTF = function () { if (this.check()) { return -1; } var big = (this.readByte() << 8) | this.readByte(); return this.binaryHelper.readUTF(this.pool.subarray(this.position, this.position += big)); }; RongIMStream.prototype.readByte = function () { if (this.check()) { return -1; } var val = this.pool[this.position++]; if (val > 255) { val &= 255; } return val; }; RongIMStream.prototype.read = function (bytesArray) { if (bytesArray) { return this.pool.subarray(this.position, this.poolLen); } else { return this.readByte(); } }; RongIMStream.prototype.write = function (_byte) { var b = _byte; if (Object.prototype.toString.call(b).toLowerCase() == "[object array]") { [].push.apply(this.pool, b); } else { if (+b == b) { if (b > 255) { b &= 255; } this.pool.push(b); this.writen++; } } return b; }; RongIMStream.prototype.writeChar = function (v) { if (+v != v) { throw new Error("writeChar:arguments type is error"); } this.write(v >> 8 & 255); this.write(v & 255); this.writen += 2; }; RongIMStream.prototype.writeUTF = function (str) { var val = this.binaryHelper.writeUTF(str); [].push.apply(this.pool, val); this.writen += val.length; }; RongIMStream.prototype.toComplements = function () { var _tPool = this.pool; for (var i = 0; i < this.poolLen; i++) { if (_tPool[i] > 128) { _tPool[i] -= 256; } } return _tPool; }; RongIMStream.prototype.getBytesArray = function (isCom) { if (isCom) { return this.toComplements(); } return this.pool; }; return RongIMStream; })(); RongIMLib.RongIMStream = RongIMStream; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var SocketTransportation = (function () { /** * [constructor] * @param {string} url [连接地址:包含token、version] */ function SocketTransportation(_socket) { //连接状态 true:已连接 false:未连接 this.connected = false; //是否关闭: true:已关闭 false:未关闭 this.isClose = false; //存放消息队列的临时变量 this.queue = []; this.empty = new Function; this._socket = _socket; return this; } /** * [createTransport 创建WebScoket对象] */ SocketTransportation.prototype.createTransport = function (url, method) { if (!url) { throw new Error("URL can't be empty"); } ; this.url = url; var depend = RongIMLib.RongIMClient._memoryStore.depend; var wsScheme = depend.wsScheme; var tpl = '{wsScheme}{url}'; url = RongIMLib.RongUtil.tplEngine(tpl, { wsScheme: wsScheme, url: url }); this.socket = new WebSocket(url); this.socket.binaryType = "arraybuffer"; this.addEvent(); return this.socket; }; /** * [send 传送消息流] * @param {ArrayBuffer} data [二进制消息流] */ SocketTransportation.prototype.send = function (data) { if (!this.connected && !this.isClose) { //当通道不可用时,加入消息队列 this.queue.push(data); return; } if (this.isClose) { this._socket.fire("StatusChanged", RongIMLib.ConnectionStatus.CONNECTION_CLOSED); return; } var stream = new RongIMLib.RongIMStream([]), msg = new RongIMLib.MessageOutputStream(stream); msg.writeMessage(data); var val = stream.getBytesArray(true); var binary = new Int8Array(val); this.socket.send(binary.buffer); return this; }; /** * [onData 通道返回数据时调用的方法,用来想上层传递服务器返回的二进制消息流] * @param {ArrayBuffer} data [二进制消息流] */ SocketTransportation.prototype.onData = function (data) { if (RongIMLib.MessageUtil.isArray(data)) { this._socket.onMessage(new RongIMLib.MessageInputStream(data).readMessage()); } else { this._socket.onMessage(new RongIMLib.MessageInputStream(RongIMLib.MessageUtil.ArrayFormInput(data)).readMessage()); } return ""; }; /** * [onClose 通道关闭时触发的方法] */ SocketTransportation.prototype.onClose = function (ev) { var me = this; me.isClose = true; me.socket = this.empty; RongIMLib.Bridge._client.clearHeartbeat(); if (ev.code == 1006 && !this._status) { me._socket.fire("StatusChanged", RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE); } else { me._status = 0; } }; /** * [onError 通道报错时触发的方法] * @param {any} error [抛出异常] */ SocketTransportation.prototype.onError = function (error) { throw new Error(error); }; /** * [addEvent 为通道绑定事件] */ SocketTransportation.prototype.addEvent = function () { var self = this; self.socket.onopen = function () { self.connected = true; self.isClose = false; //通道可以用后,调用发送队列方法,把所有等得发送的消息发出 self.doQueue(); self._socket.fire("connect"); }; self.socket.onmessage = function (ev) { //判断数据是不是字符串,如果是字符串那么就是flash传过来的。 if (typeof ev.data == "string") { self.onData(ev.data.split(",")); } else { self.onData(ev.data); } }; self.socket.onerror = function (ev) { self.onError(ev); }; self.socket.onclose = function (ev) { self.onClose(ev); }; }; /** * [doQueue 消息队列,把队列中消息发出] */ SocketTransportation.prototype.doQueue = function () { var self = this; for (var i = 0, len = self.queue.length; i < len; i++) { self.send(self.queue[i]); } }; /** * [disconnect 断开连接] */ SocketTransportation.prototype.disconnect = function (status) { var me = this; if (me.socket.readyState) { me.isClose = true; if (status) { me._status = status; } me.socket.close(); } }; /** * [reconnect 重新连接] */ SocketTransportation.prototype.reconnect = function () { this.disconnect(); this.createTransport(this.url); }; SocketTransportation.prototype.close = function () { this.socket.close(); }; return SocketTransportation; })(); RongIMLib.SocketTransportation = SocketTransportation; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var PollingTransportation = (function () { function PollingTransportation(socket) { this.empty = new Function; this.connected = false; this.pid = +new Date + Math.random() + ""; this.queue = []; this.socket = socket; return this; } PollingTransportation.prototype.createTransport = function (url, method) { if (!url) { throw new Error("Url is empty,Please check it!"); } ; this.url = url; var sid = RongIMLib.RongIMClient._storageProvider.getItem("sId" + RongIMLib.Navigation.Endpoint.userId), me = this; if (sid) { setTimeout(function () { me.onSuccess("{\"status\":0,\"userId\":\"" + RongIMLib.Navigation.Endpoint.userId + "\",\"headerCode\":32,\"messageId\":0,\"sessionid\":\"" + sid + "\"}"); me.connected = true; }, 500); return this; } this.getRequest(url, true); return this; }; PollingTransportation.prototype.requestFactory = function (url, method, multipart) { var reqest = this.XmlHttpRequest(); if (multipart) { reqest.multipart = true; } reqest.timeout = 60000; reqest.open(method || "GET", RongIMLib.RongIMClient._memoryStore.depend.protocol + url); if (method == "POST" && "setRequestHeader" in reqest) { reqest.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=utf-8"); } return reqest; }; PollingTransportation.prototype.getRequest = function (url, isconnect) { var me = this; me.xhr = this.requestFactory(url + "&pid=" + encodeURIComponent(me.pid), "GET"); if ("onload" in me.xhr) { me.xhr.onload = function () { me.xhr.onload = me.empty; if (this.responseText == "lost params") { me.onError(); } else { me.onSuccess(this.responseText, isconnect); } }; me.xhr.onerror = function () { me.disconnect(); }; } else { me.xhr.onreadystatechange = function () { if (me.xhr.readyState == 4) { me.xhr.onreadystatechange = me.empty; if (/^(200|202)$/.test(me.xhr.status)) { me.onSuccess(me.xhr.responseText, isconnect); } else if (/^(400|403)$/.test(me.xhr.status)) { me.onError(); } else { me.disconnect(); } } }; } me.xhr.send(); }; /** * [send 发送消息,Method:POST] * queue 为消息队列,待通道可用发送所有等待消息 * @param {string} data [需要传入comet格式数据,此处只负责通讯通道,数据转换在外层处理] */ PollingTransportation.prototype.send = function (data) { var me = this; var _send = me.sendxhr = this.requestFactory(RongIMLib.Navigation.Endpoint.host + "/websocket" + data.url + "&pid=" + encodeURIComponent(me.pid), "POST"); if ("onload" in _send) { _send.onload = function () { _send.onload = me.empty; me.onData(_send.responseText); }; _send.onerror = function () { _send.onerror = me.empty; }; } else { _send.onreadystatechange = function () { if (_send.readyState == 4) { this.onreadystatechange = this.empty; if (/^(202|200)$/.test(_send.status)) { me.onData(_send.responseText); } } }; } _send.send(JSON.stringify(data.data)); }; PollingTransportation.prototype.onData = function (data, header) { if (!data || data == "lost params") { return; } var self = this, val = JSON.parse(data); if (val.userId) { RongIMLib.Navigation.Endpoint.userId = val.userId; } if (header) { RongIMLib.RongIMClient._storageProvider.setItem("sId" + RongIMLib.Navigation.Endpoint.userId, header); } if (!RongIMLib.MessageUtil.isArray(val)) { val = [val]; } Array.forEach(val, function (m) { self.socket.fire("message", new RongIMLib.MessageInputStream(m, true).readMessage()); }); return ""; }; PollingTransportation.prototype.XmlHttpRequest = function () { var hasCORS = typeof XMLHttpRequest !== "undefined" && "withCredentials" in new XMLHttpRequest(), self = this; if ("undefined" != typeof XMLHttpRequest && hasCORS) { return new XMLHttpRequest(); } else if ("undefined" != typeof XDomainRequest) { return new XDomainRequest(); } else { return new ActiveXObject("Microsoft.XMLHTTP"); } }; PollingTransportation.prototype.onClose = function () { if (this.xhr) { if (this.xhr.onload) { this.xhr.onreadystatechange = this.xhr.onload = this.empty; } else { this.xhr.onreadystatechange = this.empty; } this.xhr.abort(); this.xhr = null; } if (this.sendxhr) { if (this.sendxhr.onload) { this.sendxhr.onreadystatechange = this.sendxhr.onload = this.empty; } else { this.sendxhr.onreadystatechange = this.empty; } this.sendxhr.abort(); this.sendxhr = null; } }; PollingTransportation.prototype.disconnect = function () { RongIMLib.RongIMClient._storageProvider.removeItem("sId" + RongIMLib.Navigation.Endpoint.userId); RongIMLib.RongIMClient._storageProvider.removeItem(RongIMLib.Navigation.Endpoint.userId + "msgId"); this.onClose(); }; PollingTransportation.prototype.reconnect = function () { this.disconnect(); this.createTransport(this.url); }; PollingTransportation.prototype.onSuccess = function (responseText, isconnect) { var txt = responseText.match(/"sessionid":"\S+?(?=")/); this.onData(responseText, txt ? txt[0].slice(13) : 0); if (/"headerCode":-32,/.test(responseText)) { RongIMLib.RongIMClient._storageProvider.removeItem("sId" + RongIMLib.Navigation.Endpoint.userId); RongIMLib.RongIMClient._storageProvider.removeItem(RongIMLib.Navigation.Endpoint.userId + "msgId"); return; } this.getRequest(RongIMLib.Navigation.Endpoint.host + "/pullmsg.js?sessionid=" + RongIMLib.RongIMClient._storageProvider.getItem("sId" + RongIMLib.Navigation.Endpoint.userId) + "×trap=" + encodeURIComponent(new Date().getTime() + Math.random() + "")); this.connected = true; isconnect && this.socket.fire("connect"); }; PollingTransportation.prototype.onError = function () { RongIMLib.RongIMClient._storageProvider.removeItem("sId" + RongIMLib.Navigation.Endpoint.userId); RongIMLib.RongIMClient._storageProvider.removeItem(RongIMLib.Navigation.Endpoint.userId + "msgId"); this.onClose(); this.connected = false; this.socket.fire("disconnect"); }; PollingTransportation.prototype.close = function () { this.xhr.abort(); this.sendxhr = null; }; return PollingTransportation; })(); RongIMLib.PollingTransportation = PollingTransportation; })(RongIMLib || (RongIMLib = {})); //objectname映射 var typeMapping = { "RC:TxtMsg": "TextMessage", "RC:ImgMsg": "ImageMessage", "RC:VcMsg": "VoiceMessage", "RC:ImgTextMsg": "RichContentMessage", "RC:FileMsg": "FileMessage", "RC:LBSMsg": "LocationMessage", "RC:InfoNtf": "InformationNotificationMessage", "RC:ContactNtf": "ContactNotificationMessage", "RC:ProfileNtf": "ProfileNotificationMessage", "RC:CmdNtf": "CommandNotificationMessage", "RC:DizNtf": "DiscussionNotificationMessage", "RC:CmdMsg": "CommandMessage", "RC:TypSts": "TypingStatusMessage", "RC:CsChaR": "ChangeModeResponseMessage", "RC:CsHsR": "HandShakeResponseMessage", "RC:CsEnd": "TerminateMessage", "RC:CsSp": "SuspendMessage", "RC:CsUpdate": "CustomerStatusUpdateMessage", "RC:ReadNtf": "ReadReceiptMessage", "RC:VCAccept": "AcceptMessage", "RC:VCRinging": "RingingMessage", "RC:VCSummary": "SummaryMessage", "RC:VCHangup": "HungupMessage", "RC:VCInvite": "InviteMessage", "RC:VCModifyMedia": "MediaModifyMessage", "RC:VCModifyMem": "MemberModifyMessage", "RC:CsContact": "CustomerContact", "RC:PSImgTxtMsg": "PublicServiceRichContentMessage", "RC:PSMultiImgTxtMsg": "PublicServiceMultiRichContentMessage", "RC:GrpNtf": "GroupNotificationMessage", "RC:PSCmd": "PublicServiceCommandMessage", "RC:RcCmd": "RecallCommandMessage", "RC:SRSMsg": "SyncReadStatusMessage", "RC:RRReqMsg": "ReadReceiptRequestMessage", "RC:RRRspMsg": "ReadReceiptResponseMessage", "RCJrmf:RpMsg": "JrmfRedPacketMessage", "RCJrmf:RpOpendMsg": "JrmfRedPacketOpenedMessage" }, //自定义消息类型 registerMessageTypeMapping = {}, HistoryMsgType = { 4: "qryCMsg", 2: "qryDMsg", 3: "qryGMsg", 1: "qryPMsg", 6: "qrySMsg", 7: "qryMCMsg", 8: "qryMPMsg", 5: "qryCMsg" }, disconnectStatus = { 1: 6 }; var RongIMLib; (function (RongIMLib) { /** * 通道标识类 */ var Transportations = (function () { function Transportations() { } Transportations._TransportType = RongIMLib.Socket.WEBSOCKET; return Transportations; })(); RongIMLib.Transportations = Transportations; var MessageUtil = (function () { function MessageUtil() { } /** *4680000 为localstorage最小容量5200000字节的90%,超过90%将删除之前过早的存储 */ MessageUtil.checkStorageSize = function () { return JSON.stringify(localStorage).length < 4680000; }; MessageUtil.getFirstKey = function (obj) { var str = ""; for (var key in obj) { str = key; break; } return str; }; MessageUtil.isEmpty = function (obj) { var empty = true; for (var key in obj) { empty = false; break; } return empty; }; MessageUtil.ArrayForm = function (typearray) { if (Object.prototype.toString.call(typearray) == "[object ArrayBuffer]") { var arr = new Int8Array(typearray); return [].slice.call(arr); } return typearray; }; MessageUtil.ArrayFormInput = function (typearray) { if (Object.prototype.toString.call(typearray) == "[object ArrayBuffer]") { var arr = new Uint8Array(typearray); return arr; } return typearray; }; MessageUtil.indexOf = function (arr, item, from) { for (var l = arr.length, i = (from < 0) ? Math.max(0, +from) : from || 0; i < l; i++) { if (arr[i] == item) { return i; } } return -1; }; MessageUtil.isArray = function (obj) { return Object.prototype.toString.call(obj) == "[object Array]"; }; //遍历,只能遍历数组 MessageUtil.forEach = function (arr, func) { if ([].forEach) { return function (arr, func) { [].forEach.call(arr, func); }; } else { return function (arr, func) { for (var i = 0; i < arr.length; i++) { func.call(arr, arr[i], i, arr); } }; } }; MessageUtil.remove = function (array, func) { for (var i = 0, len = array.length; i < len; i++) { if (func(array[i])) { return array.splice(i, 1)[0]; } } return null; }; MessageUtil.int64ToTimestamp = function (obj, isDate) { if (obj.low === undefined) { return obj; } var low = obj.low; if (low < 0) { low += 0xffffffff + 1; } low = low.toString(16); var timestamp = parseInt(obj.high.toString(16) + "00000000".replace(new RegExp("0{" + low.length + "}$"), low), 16); if (isDate) { return new Date(timestamp); } return timestamp; }; //消息转换方法 MessageUtil.messageParser = function (entity, onReceived, offlineMsg) { var message = new RongIMLib.Message(), content = entity.content, de, objectName = entity.classname, val, isUseDef = false; try { if (RongIMLib.RongIMClient._memoryStore.depend.isPolling) { val = new RongIMLib.BinaryHelper().readUTF(content.offset ? MessageUtil.ArrayForm(content.buffer).slice(content.offset, content.limit) : content); de = JSON.parse(val); } else { val = new RongIMLib.BinaryHelper().readUTF(content.offset ? MessageUtil.ArrayFormInput(content.buffer).subarray(content.offset, content.limit) : content); de = JSON.parse(val); } } catch (ex) { de = val; isUseDef = true; } //映射为具体消息对象 if (objectName in typeMapping) { var str = "new RongIMLib." + typeMapping[objectName] + "(de)"; message.content = eval(str); message.messageType = typeMapping[objectName]; } else if (objectName in registerMessageTypeMapping) { var str = "new RongIMLib.RongIMClient.RegisterMessage." + registerMessageTypeMapping[objectName] + "(de)"; if (isUseDef) { message.content = eval(str).decode(de); } else { message.content = eval(str); } message.messageType = registerMessageTypeMapping[objectName]; } else { message.content = new RongIMLib.UnknownMessage({ content: de, objectName: objectName }); message.messageType = "UnknownMessage"; } //根据实体对象设置message对象] var dateTime = MessageUtil.int64ToTimestamp(entity.dataTime); if (dateTime > 0) { message.sentTime = dateTime; } else { message.sentTime = +new Date; } message.senderUserId = entity.fromUserId; message.conversationType = entity.type; if (entity.fromUserId == RongIMLib.Bridge._client.userId) { message.targetId = entity.groupId; } else { message.targetId = (/^[234]$/.test(entity.type || entity.getType()) ? entity.groupId : message.senderUserId); } if (entity.direction == 1) { message.messageDirection = RongIMLib.MessageDirection.SEND; message.senderUserId = RongIMLib.Bridge._client.userId; } else { if (message.senderUserId == RongIMLib.Bridge._client.userId) { message.messageDirection = RongIMLib.MessageDirection.SEND; } else { message.messageDirection = RongIMLib.MessageDirection.RECEIVE; } } message.messageUId = entity.msgId; message.receivedTime = new Date().getTime(); message.messageId = (message.conversationType + "_" + ~~(Math.random() * 0xffffff)); message.objectName = objectName; message.receivedStatus = RongIMLib.ReceivedStatus.READ; if ((entity.status & 2) == 2) { message.receivedStatus = RongIMLib.ReceivedStatus.RETRIEVED; } message.offLineMessage = offlineMsg ? true : false; if (!offlineMsg) { if (RongIMLib.RongIMClient._memoryStore.connectAckTime > message.sentTime) { message.offLineMessage = true; } } return message; }; //适配SSL // static schemeArrs: Array = [["http", "ws"], ["https", "wss"]]; MessageUtil.sign = { converNum: 1, msgNum: 1, isMsgStart: true, isConvStart: true }; return MessageUtil; })(); RongIMLib.MessageUtil = MessageUtil; /** * 工具类 */ var MessageIdHandler = (function () { function MessageIdHandler() { } MessageIdHandler.init = function () { this.messageId = +(RongIMLib.RongIMClient._storageProvider.getItem(RongIMLib.Navigation.Endpoint.userId + "msgId") || RongIMLib.RongIMClient._storageProvider.setItem(RongIMLib.Navigation.Endpoint.userId + "msgId", 0) || 0); }; MessageIdHandler.messageIdPlus = function (method) { RongIMLib.RongIMClient._memoryStore.depend.isPolling && this.init(); if (this.messageId >= 65535) { method(); return false; } this.messageId++; RongIMLib.RongIMClient._memoryStore.depend.isPolling && RongIMLib.RongIMClient._storageProvider.setItem(RongIMLib.Navigation.Endpoint.userId + "msgId", this.messageId); return this.messageId; }; MessageIdHandler.clearMessageId = function () { this.messageId = 0; RongIMLib.RongIMClient._memoryStore.depend.isPolling && RongIMLib.RongIMClient._storageProvider.setItem(RongIMLib.Navigation.Endpoint.userId + "msgId", this.messageId); }; MessageIdHandler.getMessageId = function () { RongIMLib.RongIMClient._memoryStore.depend.isPolling && this.init(); return this.messageId; }; MessageIdHandler.messageId = 0; return MessageIdHandler; })(); RongIMLib.MessageIdHandler = MessageIdHandler; var RongInnerTools = (function () { function RongInnerTools() { } RongInnerTools.convertUserStatus = function (entity) { entity = RongIMLib.RongUtil.rename(entity, { subUserId: 'userId' }); var status = JSON.parse(entity.status); var us = status.us; if (!us) { return entity; } entity.status = RongIMLib.RongUtil.rename(us, { o: 'online', 'p': 'platform', s: 'status' }); return entity; }; return RongInnerTools; })(); RongIMLib.RongInnerTools = RongInnerTools; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var MessageContent = (function () { function MessageContent(data) { throw new Error("This method is abstract, you must implement this method in inherited class."); } MessageContent.obtain = function () { throw new Error("This method is abstract, you must implement this method in inherited class."); }; return MessageContent; })(); RongIMLib.MessageContent = MessageContent; var NotificationMessage = (function (_super) { __extends(NotificationMessage, _super); function NotificationMessage() { _super.apply(this, arguments); } return NotificationMessage; })(MessageContent); RongIMLib.NotificationMessage = NotificationMessage; var StatusMessage = (function (_super) { __extends(StatusMessage, _super); function StatusMessage() { _super.apply(this, arguments); } return StatusMessage; })(MessageContent); RongIMLib.StatusMessage = StatusMessage; var ModelUtil = (function () { function ModelUtil() { } ModelUtil.modelClone = function (object) { var obj = {}; for (var item in object) { if (item != "messageName" && "encode" != item) { obj[item] = object[item]; } } return obj; }; ModelUtil.modleCreate = function (fields, msgType) { if (fields.length < 1) { throw new Error("Array is empty -> registerMessageType.modleCreate"); } var Object = function (message) { var me = this; for (var index in fields) { me[fields[index]] = message[fields[index]]; } Object.prototype.messageName = msgType; Object.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; }; return Object; }; return ModelUtil; })(); RongIMLib.ModelUtil = ModelUtil; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var CustomerStatusMessage = (function () { function CustomerStatusMessage(message) { this.messageName = "CustomerStatusMessage"; this.status = message.status; } CustomerStatusMessage.obtain = function () { return null; }; CustomerStatusMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return CustomerStatusMessage; })(); RongIMLib.CustomerStatusMessage = CustomerStatusMessage; /** * 客服转换响应消息的类型名 */ var ChangeModeResponseMessage = (function () { function ChangeModeResponseMessage(message) { this.messageName = "ChangeModeResponseMessage"; this.code = message.code; this.data = message.data; this.msg = message.msg; } ChangeModeResponseMessage.obtain = function () { return null; }; ChangeModeResponseMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ChangeModeResponseMessage; })(); RongIMLib.ChangeModeResponseMessage = ChangeModeResponseMessage; /** * 客服转换消息的类型名 * 此消息不计入未读消息数 */ var ChangeModeMessage = (function () { function ChangeModeMessage(message) { this.messageName = "ChangeModeMessage"; this.uid = message.uid; this.sid = message.sid; this.pid = message.pid; } ChangeModeMessage.obtain = function () { return null; }; ChangeModeMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ChangeModeMessage; })(); RongIMLib.ChangeModeMessage = ChangeModeMessage; var CustomerStatusUpdateMessage = (function () { function CustomerStatusUpdateMessage(message) { this.messageName = "CustomerStatusUpdateMessage"; this.serviceStatus = message.serviceStatus; this.sid = message.sid; } CustomerStatusUpdateMessage.obtain = function () { return null; }; CustomerStatusUpdateMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return CustomerStatusUpdateMessage; })(); RongIMLib.CustomerStatusUpdateMessage = CustomerStatusUpdateMessage; var HandShakeMessage = (function () { function HandShakeMessage(message) { this.messageName = "HandShakeMessage"; message && (this.groupid = message.groupid); } HandShakeMessage.obtain = function () { return null; }; HandShakeMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return HandShakeMessage; })(); RongIMLib.HandShakeMessage = HandShakeMessage; var CustomerContact = (function () { function CustomerContact(message) { this.messageName = "CustomerContact"; this.page = message.page; this.nickName = message.nickName; this.routingInfo = message.routingInfo; this.info = message.info; this.requestInfo = message.requestInfo; } CustomerContact.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return CustomerContact; })(); RongIMLib.CustomerContact = CustomerContact; var EvaluateMessage = (function () { function EvaluateMessage(message) { this.messageName = "EvaluateMessage"; this.uid = message.uid; this.sid = message.sid; this.pid = message.pid; this.source = message.source; this.suggest = message.suggest; this.isresolve = message.isresolve; this.type = message.type; } EvaluateMessage.obtain = function () { return null; }; EvaluateMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return EvaluateMessage; })(); RongIMLib.EvaluateMessage = EvaluateMessage; /** * 客服握手响应消息的类型名 */ var HandShakeResponseMessage = (function () { function HandShakeResponseMessage(message) { this.messageName = "HandShakeResponseMessage"; this.msg = message.msg; this.status = message.status; this.data = message.data; } HandShakeResponseMessage.obtain = function () { return null; }; HandShakeResponseMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return HandShakeResponseMessage; })(); RongIMLib.HandShakeResponseMessage = HandShakeResponseMessage; var SuspendMessage = (function () { function SuspendMessage(message) { this.messageName = "SuspendMessage"; this.uid = message.uid; this.sid = message.sid; this.pid = message.pid; } SuspendMessage.obtain = function () { return null; }; SuspendMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return SuspendMessage; })(); RongIMLib.SuspendMessage = SuspendMessage; var TerminateMessage = (function () { function TerminateMessage(message) { this.messageName = "TerminateMessage"; this.code = message.code; this.msg = message.msg; this.sid = message.sid; } TerminateMessage.obtain = function () { return null; }; TerminateMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return TerminateMessage; })(); RongIMLib.TerminateMessage = TerminateMessage; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var IsTypingStatusMessage = (function () { function IsTypingStatusMessage(data) { this.messageName = "IsTypingStatusMessage"; var msg = data; } IsTypingStatusMessage.prototype.encode = function () { return undefined; }; IsTypingStatusMessage.prototype.getMessage = function () { return null; }; return IsTypingStatusMessage; })(); RongIMLib.IsTypingStatusMessage = IsTypingStatusMessage; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var InformationNotificationMessage = (function () { function InformationNotificationMessage(message) { this.messageName = "InformationNotificationMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> InformationNotificationMessage."); } this.message = message.message; this.extra = message.extra; if (message.user) { this.user = message.user; } } InformationNotificationMessage.obtain = function (message) { return new InformationNotificationMessage({ message: message, extra: "" }); }; InformationNotificationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return InformationNotificationMessage; })(); RongIMLib.InformationNotificationMessage = InformationNotificationMessage; var CommandMessage = (function () { function CommandMessage(message) { this.messageName = "CommandMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> CommandMessage."); } try { if (Object.prototype.toString.call(message.data) == "[object String]") { this.data = JSON.parse(message.data); } else { this.data = message.data; } } catch (e) { this.data = message.data; } this.name = message.name; this.extra = message.extra; } CommandMessage.obtain = function (data) { return new CommandMessage({ data: data, extra: "" }); }; CommandMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return CommandMessage; })(); RongIMLib.CommandMessage = CommandMessage; var ContactNotificationMessage = (function () { function ContactNotificationMessage(message) { this.messageName = "ContactNotificationMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> ContactNotificationMessage."); } this.operation = message.operation; this.targetUserId = message.targetUserId; this.message = message.message; this.extra = message.extra; this.sourceUserId = message.sourceUserId; if (message.user) { this.user = message.user; } } ContactNotificationMessage.obtain = function (operation, sourceUserId, targetUserId, message) { return new InformationNotificationMessage({ operation: operation, sourceUserId: sourceUserId, targetUserId: targetUserId, message: message }); }; ContactNotificationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; ContactNotificationMessage.CONTACT_OPERATION_ACCEPT_RESPONSE = "ContactOperationAcceptResponse"; ContactNotificationMessage.CONTACT_OPERATION_REJECT_RESPONSE = "ContactOperationRejectResponse"; ContactNotificationMessage.CONTACT_OPERATION_REQUEST = "ContactOperationRequest"; return ContactNotificationMessage; })(); RongIMLib.ContactNotificationMessage = ContactNotificationMessage; var ProfileNotificationMessage = (function () { function ProfileNotificationMessage(message) { this.messageName = "ProfileNotificationMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> ProfileNotificationMessage."); } this.operation = message.operation; try { if (Object.prototype.toString.call(message.data) == "[object String]") { this.data = JSON.parse(message.data); } else { this.data = message.data; } } catch (e) { this.data = message.data; } this.extra = message.extra; if (message.user) { this.user = message.user; } } ProfileNotificationMessage.obtain = function (operation, data) { return new ProfileNotificationMessage({ operation: operation, data: data }); }; ProfileNotificationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ProfileNotificationMessage; })(); RongIMLib.ProfileNotificationMessage = ProfileNotificationMessage; var CommandNotificationMessage = (function () { function CommandNotificationMessage(message) { this.messageName = "CommandNotificationMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> ProfileNotificationMessage."); } try { if (Object.prototype.toString.call(message.data) == "[object String]") { this.data = JSON.parse(message.data); } else { this.data = message.data; } } catch (e) { this.data = message.data; } this.name = message.name; this.extra = message.extra; if (message.user) { this.user = message.user; } } CommandNotificationMessage.obtain = function (name, data) { return new CommandNotificationMessage({ name: name, data: data, extra: "" }); }; CommandNotificationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return CommandNotificationMessage; })(); RongIMLib.CommandNotificationMessage = CommandNotificationMessage; var DiscussionNotificationMessage = (function () { function DiscussionNotificationMessage(message) { this.messageName = "DiscussionNotificationMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> DiscussionNotificationMessage."); } this.extra = message.extra; this.extension = message.extension; this.type = message.type; this.isHasReceived = message.isHasReceived; this.operation = message.operation; this.user = message.user; if (message.user) { this.user = message.user; } } DiscussionNotificationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return DiscussionNotificationMessage; })(); RongIMLib.DiscussionNotificationMessage = DiscussionNotificationMessage; var GroupNotificationMessage = (function () { function GroupNotificationMessage(msg) { this.messageName = "GroupNotificationMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> GroupNotificationMessage."); } msg.operatorUserId && (this.operatorUserId = msg.operatorUserId); msg.operation && (this.operation = msg.operation); msg.data && (this.data = msg.data); msg.message && (this.message = msg.message); msg.extra && (this.extra = msg.extra); } GroupNotificationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return GroupNotificationMessage; })(); RongIMLib.GroupNotificationMessage = GroupNotificationMessage; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var TextMessage = (function () { function TextMessage(message) { this.messageName = "TextMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> TextMessage."); } this.content = message.content; this.extra = message.extra; if (message.user) { this.user = message.user; } if (message.mentionedInfo) { this.mentionedInfo = message.mentionedInfo; } if (message.burnDuration) { this.burnDuration = message.burnDuration; } } TextMessage.obtain = function (text) { return new TextMessage({ extra: "", content: text }); }; TextMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return TextMessage; })(); RongIMLib.TextMessage = TextMessage; var TypingStatusMessage = (function () { function TypingStatusMessage(message) { this.messageName = "TypingStatusMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> TypingStatusMessage."); } this.typingContentType = message.typingContentType; this.data = message.data; } TypingStatusMessage.obtain = function (typingContentType, data) { return new TypingStatusMessage({ typingContentType: typingContentType, data: data }); }; TypingStatusMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return TypingStatusMessage; })(); RongIMLib.TypingStatusMessage = TypingStatusMessage; var ReadReceiptMessage = (function () { function ReadReceiptMessage(message) { this.messageName = "ReadReceiptMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> ReadReceiptMessage."); } this.lastMessageSendTime = message.lastMessageSendTime; this.messageUId = message.messageUId; this.type = message.type; } ReadReceiptMessage.obtain = function (messageUId, lastMessageSendTime, type) { return new ReadReceiptMessage({ messageUId: messageUId, lastMessageSendTime: lastMessageSendTime, type: type }); }; ReadReceiptMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ReadReceiptMessage; })(); RongIMLib.ReadReceiptMessage = ReadReceiptMessage; var VoiceMessage = (function () { function VoiceMessage(message) { this.messageName = "VoiceMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> VoiceMessage."); } this.content = message.content; this.duration = message.duration; this.extra = message.extra; if (message.user) { this.user = message.user; } if (message.mentionedInfo) { this.mentionedInfo = message.mentionedInfo; } if (message.burnDuration) { this.burnDuration = message.burnDuration; } } VoiceMessage.obtain = function (base64Content, duration) { return new VoiceMessage({ content: base64Content, duration: duration, extra: "" }); }; VoiceMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return VoiceMessage; })(); RongIMLib.VoiceMessage = VoiceMessage; var RecallCommandMessage = (function () { function RecallCommandMessage(message) { this.messageName = "RecallCommandMessage"; this.messageUId = message.messageUId; this.conversationType = message.conversationType; this.targetId = message.targetId; this.sentTime = message.sentTime; // RCE 增加 this.isDelete = message.isDelete; this.isAdmin = message.isAdmin; this.adminId = message.adminId; message.extra && (this.extra = message.extra); message.user && (this.user = message.user); } RecallCommandMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return RecallCommandMessage; })(); RongIMLib.RecallCommandMessage = RecallCommandMessage; var ImageMessage = (function () { function ImageMessage(message) { this.messageName = "ImageMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> ImageMessage."); } this.content = message.content; this.imageUri = message.imageUri; message.extra && (this.extra = message.extra); message.user && (this.user = message.user); if (message.mentionedInfo) { this.mentionedInfo = message.mentionedInfo; } if (message.burnDuration) { this.burnDuration = message.burnDuration; } } ImageMessage.obtain = function (content, imageUri) { return new ImageMessage({ content: content, imageUri: imageUri, extra: "" }); }; ImageMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ImageMessage; })(); RongIMLib.ImageMessage = ImageMessage; var LocationMessage = (function () { function LocationMessage(message) { this.messageName = "LocationMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> LocationMessage."); } this.latitude = message.latitude; this.longitude = message.longitude; this.poi = message.poi; this.content = message.content; this.extra = message.extra; if (message.user) { this.user = message.user; } if (message.mentionedInfo) { this.mentionedInfo = message.mentionedInfo; } } LocationMessage.obtain = function (latitude, longitude, poi, content) { return new LocationMessage({ latitude: latitude, longitude: longitude, poi: poi, content: content, extra: "" }); }; LocationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return LocationMessage; })(); RongIMLib.LocationMessage = LocationMessage; var RichContentMessage = (function () { function RichContentMessage(message) { this.messageName = "RichContentMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> RichContentMessage."); } this.title = message.title; this.content = message.content; this.imageUri = message.imageUri; this.extra = message.extra; this.url = message.url; if (message.user) { this.user = message.user; } } RichContentMessage.obtain = function (title, content, imageUri, url) { return new RichContentMessage({ title: title, content: content, imageUri: imageUri, url: url, extra: "" }); }; RichContentMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return RichContentMessage; })(); RongIMLib.RichContentMessage = RichContentMessage; var JrmfRedPacketMessage = (function () { function JrmfRedPacketMessage(message) { this.messageName = 'JrmfRedPacketMessage'; message && (this.message = message); } JrmfRedPacketMessage.prototype.encode = function () { return ""; }; return JrmfRedPacketMessage; })(); RongIMLib.JrmfRedPacketMessage = JrmfRedPacketMessage; var JrmfRedPacketOpenedMessage = (function () { function JrmfRedPacketOpenedMessage(message) { this.messageName = 'JrmfRedPacketOpenedMessage'; message && (this.message = message); } JrmfRedPacketOpenedMessage.prototype.encode = function () { return ""; }; return JrmfRedPacketOpenedMessage; })(); RongIMLib.JrmfRedPacketOpenedMessage = JrmfRedPacketOpenedMessage; var UnknownMessage = (function () { function UnknownMessage(message) { this.messageName = "UnknownMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> UnknownMessage."); } this.message = message; } UnknownMessage.prototype.encode = function () { return ""; }; return UnknownMessage; })(); RongIMLib.UnknownMessage = UnknownMessage; var PublicServiceCommandMessage = (function () { function PublicServiceCommandMessage(message) { this.messageName = "PublicServiceCommandMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> PublicServiceCommandMessage."); } this.content = message.content; this.extra = message.extra; this.menuItem = message.menuItem; if (message.user) { this.user = message.user; } if (message.mentionedInfo) { this.mentionedInfo = message.mentionedInfo; } } PublicServiceCommandMessage.obtain = function (item) { return new PublicServiceCommandMessage({ content: "", command: "", menuItem: item, extra: "" }); }; PublicServiceCommandMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return PublicServiceCommandMessage; })(); RongIMLib.PublicServiceCommandMessage = PublicServiceCommandMessage; var PublicServiceMultiRichContentMessage = (function () { function PublicServiceMultiRichContentMessage(messages) { this.messageName = "PublicServiceMultiRichContentMessage"; this.richContentMessages = messages; } PublicServiceMultiRichContentMessage.prototype.encode = function () { return null; }; return PublicServiceMultiRichContentMessage; })(); RongIMLib.PublicServiceMultiRichContentMessage = PublicServiceMultiRichContentMessage; var SyncReadStatusMessage = (function () { function SyncReadStatusMessage(message) { this.messageName = "SyncReadStatusMessage"; message.lastMessageSendTime && (this.lastMessageSendTime = message.lastMessageSendTime); } SyncReadStatusMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return SyncReadStatusMessage; })(); RongIMLib.SyncReadStatusMessage = SyncReadStatusMessage; var ReadReceiptRequestMessage = (function () { function ReadReceiptRequestMessage(message) { this.messageName = "ReadReceiptRequestMessage"; message.messageUId && (this.messageUId = message.messageUId); } ReadReceiptRequestMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ReadReceiptRequestMessage; })(); RongIMLib.ReadReceiptRequestMessage = ReadReceiptRequestMessage; var ReadReceiptResponseMessage = (function () { function ReadReceiptResponseMessage(message) { this.messageName = "ReadReceiptResponseMessage"; message.receiptMessageDic && (this.receiptMessageDic = message.receiptMessageDic); } ReadReceiptResponseMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ReadReceiptResponseMessage; })(); RongIMLib.ReadReceiptResponseMessage = ReadReceiptResponseMessage; var PublicServiceRichContentMessage = (function () { function PublicServiceRichContentMessage(message) { this.messageName = "PublicServiceRichContentMessage"; this.richContentMessage = message; } PublicServiceRichContentMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return PublicServiceRichContentMessage; })(); RongIMLib.PublicServiceRichContentMessage = PublicServiceRichContentMessage; var FileMessage = (function () { function FileMessage(message) { this.messageName = "FileMessage"; message.name && (this.name = message.name); message.size && (this.size = message.size); message.type && (this.type = message.type); message.fileUrl && (this.fileUrl = message.fileUrl); message.extra && (this.extra = message.extra); message.user && (this.user = message.user); } FileMessage.obtain = function (msg) { return new FileMessage({ name: msg.name, size: msg.size, type: msg.type, fileUrl: msg.fileUrl }); }; FileMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return FileMessage; })(); RongIMLib.FileMessage = FileMessage; var AcceptMessage = (function () { function AcceptMessage(message) { this.messageName = "AcceptMessage"; this.mediaId = message.mediaId; this.callId = message.callId; this.mediaType = message.mediaType; } AcceptMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return AcceptMessage; })(); RongIMLib.AcceptMessage = AcceptMessage; var RingingMessage = (function () { function RingingMessage(message) { this.messageName = "RingingMessage"; this.callId = message.callId; } RingingMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return RingingMessage; })(); RongIMLib.RingingMessage = RingingMessage; var SummaryMessage = (function () { function SummaryMessage(message) { this.messageName = "SummaryMessage"; this.caller = message.caller; this.inviter = message.inviter; this.mediaType = message.mediaType; this.memberIdList = message.memberIdList; this.startTime = message.startTime; this.connectedTime = message.connectedTime; this.duration = message.duration; this.status = message.status; } SummaryMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return SummaryMessage; })(); RongIMLib.SummaryMessage = SummaryMessage; var HungupMessage = (function () { function HungupMessage(message) { this.messageName = "HungupMessage"; this.callId = message.callId; this.reason = message.reason; } HungupMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return HungupMessage; })(); RongIMLib.HungupMessage = HungupMessage; var InviteMessage = (function () { function InviteMessage(message) { this.messageName = "InviteMessage"; this.mediaId = message.mediaId; this.callId = message.callId; this.engineType = message.engineType; this.channelInfo = message.channelInfo; this.mediaType = message.mediaType; this.extra = message.extra; this.inviteUserIds = message.inviteUserIds; this.observerUserIds = message.observerUserIds; } InviteMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return InviteMessage; })(); RongIMLib.InviteMessage = InviteMessage; var MediaModifyMessage = (function () { function MediaModifyMessage(message) { this.messageName = "MediaModifyMessage"; this.callId = message.callId; this.mediaType = message.mediaType; } MediaModifyMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return MediaModifyMessage; })(); RongIMLib.MediaModifyMessage = MediaModifyMessage; var MemberModifyMessage = (function () { function MemberModifyMessage(message) { this.messageName = "MemberModifyMessage"; this.modifyMemType = message.modifyMemType; this.callId = message.callId; this.caller = message.caller; this.engineType = message.engineType; this.channelInfo = message.channelInfo; this.mediaType = message.mediaType; this.extra = message.extra; this.inviteUserIds = message.inviteUserIds; this.existedMemberStatusList = message.existedMemberStatusList; this.existedUserPofiles = message.existedUserPofiles; this.observerUserIds = message.observerUserIds; } MemberModifyMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return MemberModifyMessage; })(); RongIMLib.MemberModifyMessage = MemberModifyMessage; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var ChannelInfo = (function () { function ChannelInfo(Id, Key) { this.Id = Id; this.Key = Key; } return ChannelInfo; })(); RongIMLib.ChannelInfo = ChannelInfo; var UserStatus = (function () { function UserStatus(platform, online, status) { this.platform = platform; this.online = online; this.status = status; } return UserStatus; })(); RongIMLib.UserStatus = UserStatus; var MentionedInfo = (function () { function MentionedInfo(type, userIdList, mentionedContent) { } return MentionedInfo; })(); RongIMLib.MentionedInfo = MentionedInfo; var DeleteMessage = (function () { function DeleteMessage(msgId, msgDataTime, direct) { this.msgId = msgId; this.msgDataTime = msgDataTime; this.direct = direct; } return DeleteMessage; })(); RongIMLib.DeleteMessage = DeleteMessage; var CustomServiceConfig = (function () { function CustomServiceConfig(isBlack, companyName, companyUrl) { } return CustomServiceConfig; })(); RongIMLib.CustomServiceConfig = CustomServiceConfig; var CustomServiceSession = (function () { function CustomServiceSession(uid, cid, pid, isQuited, type, adminHelloWord, adminOfflineWord) { } return CustomServiceSession; })(); RongIMLib.CustomServiceSession = CustomServiceSession; var Conversation = (function () { function Conversation(conversationTitle, conversationType, draft, isTop, latestMessage, latestMessageId, notificationStatus, objectName, receivedStatus, receivedTime, senderUserId, senderUserName, sentStatus, sentTime, targetId, unreadMessageCount, senderPortraitUri, isHidden, mentionedMsg, hasUnreadMention, _readTime) { this.conversationTitle = conversationTitle; this.conversationType = conversationType; this.draft = draft; this.isTop = isTop; this.latestMessage = latestMessage; this.latestMessageId = latestMessageId; this.notificationStatus = notificationStatus; this.objectName = objectName; this.receivedStatus = receivedStatus; this.receivedTime = receivedTime; this.senderUserId = senderUserId; this.senderUserName = senderUserName; this.sentStatus = sentStatus; this.sentTime = sentTime; this.targetId = targetId; this.unreadMessageCount = unreadMessageCount; this.senderPortraitUri = senderPortraitUri; this.isHidden = isHidden; this.mentionedMsg = mentionedMsg; this.hasUnreadMention = hasUnreadMention; this._readTime = _readTime; } Conversation.prototype.setTop = function () { RongIMLib.RongIMClient._dataAccessProvider.addConversation(this, { onSuccess: function (data) { } }); }; return Conversation; })(); RongIMLib.Conversation = Conversation; var Discussion = (function () { function Discussion(creatorId, id, memberIdList, name, isOpen) { this.creatorId = creatorId; this.id = id; this.memberIdList = memberIdList; this.name = name; this.isOpen = isOpen; } return Discussion; })(); RongIMLib.Discussion = Discussion; var Group = (function () { function Group(id, name, portraitUri) { this.id = id; this.name = name; this.portraitUri = portraitUri; } return Group; })(); RongIMLib.Group = Group; var Message = (function () { function Message(content, conversationType, extra, objectName, messageDirection, messageId, receivedStatus, receivedTime, senderUserId, sentStatus, sentTime, targetId, messageType, messageUId, isLocalMessage, offLineMessage, receiptResponse) { this.content = content; this.conversationType = conversationType; this.extra = extra; this.objectName = objectName; this.messageDirection = messageDirection; this.messageId = messageId; this.receivedStatus = receivedStatus; this.receivedTime = receivedTime; this.senderUserId = senderUserId; this.sentStatus = sentStatus; this.sentTime = sentTime; this.targetId = targetId; this.messageType = messageType; this.messageUId = messageUId; this.isLocalMessage = isLocalMessage; this.offLineMessage = offLineMessage; this.receiptResponse = receiptResponse; } return Message; })(); RongIMLib.Message = Message; var MessageTag = (function () { function MessageTag(isCounted, isPersited) { this.isCounted = isCounted; this.isPersited = isPersited; } MessageTag.prototype.getMessageTag = function () { if (this.isCounted && this.isPersited) { return 3; } else if (this.isCounted) { return 2; } else if (this.isPersited) { return 1; } else if (!this.isCounted && !this.isPersited) { return 0; } }; return MessageTag; })(); RongIMLib.MessageTag = MessageTag; var PublicServiceMenuItem = (function () { function PublicServiceMenuItem(id, name, type, sunMenuItems, url) { this.id = id; this.name = name; this.type = type; this.sunMenuItems = sunMenuItems; this.url = url; } return PublicServiceMenuItem; })(); RongIMLib.PublicServiceMenuItem = PublicServiceMenuItem; // TODO: TBD var PublicServiceProfile = (function () { function PublicServiceProfile(conversationType, introduction, menu, name, portraitUri, publicServiceId, hasFollowed, isGlobal) { this.conversationType = conversationType; this.introduction = introduction; this.menu = menu; this.name = name; this.portraitUri = portraitUri; this.publicServiceId = publicServiceId; this.hasFollowed = hasFollowed; this.isGlobal = isGlobal; } return PublicServiceProfile; })(); RongIMLib.PublicServiceProfile = PublicServiceProfile; var UserInfo = (function () { function UserInfo(id, name, portraitUri) { this.id = id; this.name = name; this.portraitUri = portraitUri; } return UserInfo; })(); RongIMLib.UserInfo = UserInfo; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var ServerDataProvider = (function () { function ServerDataProvider() { this.userStatusListener = null; } ServerDataProvider.prototype.init = function (appKey, options) { new RongIMLib.FeatureDectector(options.appCallback); }; ServerDataProvider.prototype.connect = function (token, callback) { RongIMLib.RongIMClient.bridge = RongIMLib.Bridge.getInstance(); RongIMLib.RongIMClient._memoryStore.token = token; RongIMLib.RongIMClient._memoryStore.callback = callback; var isConnecting = false, isConnected = false; if (RongIMLib.Bridge._client && RongIMLib.Bridge._client.channel) { isConnecting = (RongIMLib.Bridge._client.channel.connectionStatus == RongIMLib.ConnectionStatus.CONNECTING); isConnected = (RongIMLib.Bridge._client.channel.connectionStatus == RongIMLib.ConnectionStatus.CONNECTED); } if (isConnected || isConnecting) { return; } var isGreater = (RongIMLib.RongIMClient.otherDeviceLoginCount > 5); if (isGreater) { callback.onError(RongIMLib.ConnectionStatus.ULTRALIMIT); return; } //循环设置监听事件,追加之后清空存放事件数据 for (var i = 0, len = RongIMLib.RongIMClient._memoryStore.listenerList.length; i < len; i++) { RongIMLib.RongIMClient.bridge["setListener"](RongIMLib.RongIMClient._memoryStore.listenerList[i]); } RongIMLib.RongIMClient._memoryStore.listenerList.length = 0; RongIMLib.RongIMClient.bridge.connect(RongIMLib.RongIMClient._memoryStore.appKey, token, { onSuccess: function (data) { setTimeout(function () { callback.onSuccess(data); }); }, onError: function (e) { if (e == RongIMLib.ConnectionState.TOKEN_INCORRECT || !e) { setTimeout(function () { callback.onTokenIncorrect(); }); } else { setTimeout(function () { callback.onError(e); }); } } }); }; /* config.auto: 默认 false, true 启用自动重连,启用则为必选参数 config.rate: 重试频率 [100, 1000, 3000, 6000, 10000, 18000] 单位为毫秒,可选 config.url: 网络嗅探地址 [http(s)://]cdn.ronghub.com/RongIMLib-2.2.6.min.js 可选 */ ServerDataProvider.prototype.reconnect = function (callback, config) { var store = RongIMLib.RongIMClient._memoryStore; var token = store.token; if (!token) { throw new Error('reconnect: token is empty.'); } if (RongIMLib.Bridge._client && RongIMLib.Bridge._client.channel && RongIMLib.Bridge._client.channel.connectionStatus != RongIMLib.ConnectionStatus.CONNECTED && RongIMLib.Bridge._client.channel.connectionStatus != RongIMLib.ConnectionStatus.CONNECTING) { config = config || {}; var key = config.auto ? 'auto' : 'custom'; var handler = { auto: function () { var repeatConnect = function (options) { var step = options.step(); var done = 'done'; var url = options.url; var ping = function () { RongIMLib.RongUtil.request({ url: url, success: function () { options.done(); }, error: function () { repeat(); } }); }; var repeat = function () { var next = step(); if (next == 'done') { var error = RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE; options.done(error); return; } setTimeout(ping, next); }; repeat(); }; var protocol = RongIMLib.RongIMClient._memoryStore.depend.protocol; var url = config.url || 'cdn.ronghub.com/RongIMLib-2.2.6.min.js'; var pathConfig = { protocol: protocol, path: url }; url = RongIMLib.RongUtil.formatProtoclPath(pathConfig); var rate = config.rate || [100, 1000, 3000, 6000, 10000, 18000]; //结束标识 rate.push('done'); var opts = { url: url, step: function () { var index = 0; return function () { var time = rate[index]; index++; return time; }; }, done: function (error) { if (error) { callback.onError(error); return; } RongIMLib.RongIMClient.connect(token, callback); } }; repeatConnect(opts); }, custom: function () { RongIMLib.RongIMClient.connect(token, callback); } }; handler[key](); } }; ServerDataProvider.prototype.clearData = function () { return true; }; ServerDataProvider.prototype.logout = function () { RongIMLib.RongIMClient.bridge.disconnect(); RongIMLib.RongIMClient.bridge = null; }; ServerDataProvider.prototype.disconnect = function () { RongIMLib.RongIMClient.bridge.disconnect(); }; ServerDataProvider.prototype.sendReceiptResponse = function (conversationType, targetId, sendCallback) { var rspkey = RongIMLib.Bridge._client.userId + conversationType + targetId + 'RECEIVED', me = this; if (RongIMLib.RongUtil.supportLocalStorage()) { var valObj = JSON.parse(RongIMLib.RongIMClient._storageProvider.getItem(rspkey)); if (valObj) { var vals = []; for (var key in valObj) { var tmp = {}; tmp[key] = valObj[key].uIds; valObj[key].isResponse || vals.push(tmp); } if (vals.length == 0) { sendCallback.onSuccess(); return; } var interval = setInterval(function () { if (vals.length == 1) { clearInterval(interval); } var obj = vals.splice(0, 1)[0]; var rspMsg = new RongIMLib.ReadReceiptResponseMessage({ receiptMessageDic: obj }); me.sendMessage(conversationType, targetId, rspMsg, { onSuccess: function (msg) { var senderUserId = RongIMLib.MessageUtil.getFirstKey(obj); valObj[senderUserId].isResponse = true; RongIMLib.RongIMClient._storageProvider.setItem(rspkey, JSON.stringify(valObj)); sendCallback.onSuccess(msg); }, onError: function (error, msg) { sendCallback.onError(error, msg); } }); }, 200); } else { sendCallback.onSuccess(); } } else { sendCallback.onSuccess(); } }; ServerDataProvider.prototype.sendTypingStatusMessage = function (conversationType, targetId, messageName, sendCallback) { var me = this; if (messageName in RongIMLib.RongIMClient.MessageParams) { me.sendMessage(conversationType, targetId, RongIMLib.TypingStatusMessage.obtain(RongIMLib.RongIMClient.MessageParams[messageName].objectName, ""), { onSuccess: function () { setTimeout(function () { sendCallback.onSuccess(); }); }, onError: function (errorCode) { setTimeout(function () { sendCallback.onError(errorCode, null); }); }, onBefore: function () { } }); } }; ServerDataProvider.prototype.sendRecallMessage = function (content, sendMessageCallback) { var msg = new RongIMLib.RecallCommandMessage({ conversationType: content.conversationType, targetId: content.targetId, sentTime: content.sentTime, messageUId: content.messageUId, extra: content.extra, user: content.user }); this.sendMessage(content.conversationType, content.senderUserId, msg, sendMessageCallback, false, null, null, 2); }; ServerDataProvider.prototype.sendTextMessage = function (conversationType, targetId, content, sendMessageCallback) { var msgContent = RongIMLib.TextMessage.obtain(content); this.sendMessage(conversationType, targetId, msgContent, sendMessageCallback); }; ServerDataProvider.prototype.getRemoteHistoryMessages = function (conversationType, targetId, timestamp, count, callback) { if (count <= 1) { throw new Error("the count must be greater than 1."); } var modules = new RongIMLib.RongIMClient.Protobuf.HistoryMessageInput(), self = this; modules.setTargetId(targetId); if (timestamp === 0 || timestamp > 0) { modules.setDataTime(timestamp); } else { modules.setDataTime(RongIMLib.RongIMClient._memoryStore.lastReadTime.get(conversationType + targetId)); } modules.setSize(count); RongIMLib.RongIMClient.bridge.queryMsg(HistoryMsgType[conversationType], RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), targetId, { onSuccess: function (data) { RongIMLib.RongIMClient._memoryStore.lastReadTime.set(conversationType + targetId, RongIMLib.MessageUtil.int64ToTimestamp(data.syncTime)); var list = data.list.reverse(), tempMsg = null, tempDir; var read = RongIMLib.SentStatus.READ; if (RongIMLib.RongUtil.supportLocalStorage()) { for (var i = 0, len = list.length; i < len; i++) { tempMsg = RongIMLib.MessageUtil.messageParser(list[i]); tempDir = JSON.parse(RongIMLib.RongIMClient._storageProvider.getItem(RongIMLib.Bridge._client.userId + tempMsg.messageUId + "SENT")); if (tempDir) { tempMsg.receiptResponse || (tempMsg.receiptResponse = {}); tempMsg.receiptResponse[tempMsg.messageUId] = tempDir.count; } tempMsg.sentStatus = read; tempMsg.targetId = targetId; list[i] = tempMsg; } } else { for (var i = 0, len = list.length; i < len; i++) { var tempMsg = RongIMLib.MessageUtil.messageParser(list[i]); tempMsg.sentStatus = read; list[i] = tempMsg; } } setTimeout(function () { callback.onSuccess(list, !!data.hasMsg); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }, "HistoryMessagesOuput"); }; ServerDataProvider.prototype.hasRemoteUnreadMessages = function (token, callback) { var xss = null; window.RCCallback = function (x) { setTimeout(function () { callback.onSuccess(!!+x.status); }); xss.parentNode.removeChild(xss); }; xss = document.createElement("script"); xss.src = RongIMLib.RongIMClient._memoryStore.depend.api + "/message/exist.js?appKey=" + encodeURIComponent(RongIMLib.RongIMClient._memoryStore.appKey) + "&token=" + encodeURIComponent(token) + "&callBack=RCCallback&_=" + Date.now(); document.body.appendChild(xss); xss.onerror = function () { setTimeout(function () { callback.onError(RongIMLib.ErrorCode.UNKNOWN); }); xss.parentNode.removeChild(xss); }; }; ServerDataProvider.prototype.getRemoteConversations = function(count, beginTime, order, callback){ callback.onSuccess(); }; ServerDataProvider.prototype.getRemoteConversationList = function (callback, conversationTypes, count) { var modules = new RongIMLib.RongIMClient.Protobuf.RelationsInput(), self = this; modules.setType(1); if (typeof count == 'undefined') { modules.setCount(0); } else { modules.setCount(count); } RongIMLib.RongIMClient.bridge.queryMsg(26, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (list) { if (list.info) { list.info = list.info.reverse(); for (var i = 0, len = list.info.length; i < len; i++) { RongIMLib.RongIMClient.getInstance().pottingConversation(list.info[i]); } } if (conversationTypes) { var convers = []; Array.forEach(conversationTypes, function (converType) { Array.forEach(RongIMLib.RongIMClient._memoryStore.conversationList, function (item) { if (item.conversationType == converType) { convers.push(item); } }); }); setTimeout(function () { callback.onSuccess(convers); }); } else { setTimeout(function () { callback.onSuccess(RongIMLib.RongIMClient._memoryStore.conversationList); }); } }, onError: function (error) { callback.onError(error); } }, "RelationsOutput"); }; ServerDataProvider.prototype.addMemberToDiscussion = function (discussionId, userIdList, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.ChannelInvitationInput(); modules.setUsers(userIdList); RongIMLib.RongIMClient.bridge.queryMsg(0, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), discussionId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.createDiscussion = function (name, userIdList, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.CreateDiscussionInput(), self = this; modules.setName(name); RongIMLib.RongIMClient.bridge.queryMsg(1, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (discussId) { if (userIdList.length > 0) { self.addMemberToDiscussion(discussId, userIdList, { onSuccess: function () { }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); } setTimeout(function () { callback.onSuccess(discussId); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }, "CreateDiscussionOutput"); }; ServerDataProvider.prototype.getDiscussion = function (discussionId, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.ChannelInfoInput(); modules.setNothing(1); RongIMLib.RongIMClient.bridge.queryMsg(4, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), discussionId, { onSuccess: function (data) { setTimeout(function () { callback.onSuccess(data); }); }, onError: function (errorCode) { setTimeout(function () { callback.onError(errorCode); }); } }, "ChannelInfoOutput"); }; ServerDataProvider.prototype.quitDiscussion = function (discussionId, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.LeaveChannelInput(); modules.setNothing(1); RongIMLib.RongIMClient.bridge.queryMsg(7, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), discussionId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (errorCode) { setTimeout(function () { callback.onError(errorCode); }); } }); }; ServerDataProvider.prototype.removeMemberFromDiscussion = function (discussionId, userId, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.ChannelEvictionInput(); modules.setUser(userId); RongIMLib.RongIMClient.bridge.queryMsg(9, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), discussionId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (errorCode) { setTimeout(function () { callback.onError(errorCode); }); } }); }; ServerDataProvider.prototype.setDiscussionInviteStatus = function (discussionId, status, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.ModifyPermissionInput(); modules.setOpenStatus(status.valueOf()); RongIMLib.RongIMClient.bridge.queryMsg(11, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), discussionId, { onSuccess: function (x) { setTimeout(function () { callback.onSuccess(); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.setDiscussionName = function (discussionId, name, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RenameChannelInput(); modules.setName(name); RongIMLib.RongIMClient.bridge.queryMsg(12, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), discussionId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (errcode) { callback.onError(errcode); } }); }; ServerDataProvider.prototype.joinChatRoom = function (chatroomId, messageCount, callback) { var e = new RongIMLib.RongIMClient.Protobuf.ChrmInput(); e.setNothing(1); RongIMLib.Bridge._client.chatroomId = chatroomId; RongIMLib.RongIMClient.bridge.queryMsg(19, RongIMLib.MessageUtil.ArrayForm(e.toArrayBuffer()), chatroomId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); var modules = new RongIMLib.RongIMClient.Protobuf.ChrmPullMsg(); messageCount == 0 && (messageCount = -1); modules.setCount(messageCount); modules.setSyncTime(0); RongIMLib.Bridge._client.queryMessage("chrmPull", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), chatroomId, 1, { onSuccess: function (collection) { var list = collection.list; var sync = RongIMLib.MessageUtil.int64ToTimestamp(collection.syncTime); var latestMessage = list[list.length - 1]; if (latestMessage) { latestMessage = RongIMLib.MessageUtil.messageParser(latestMessage); sync = latestMessage.sentTime; } RongIMLib.RongIMClient._memoryStore.lastReadTime.set(chatroomId + RongIMLib.Bridge._client.userId + "CST", sync); var _client = RongIMLib.Bridge._client; for (var i = 0, mlen = list.length; i < mlen; i++) { var uId = 'R' + list[i].msgId; if (!(uId in _client.cacheMessageIds)) { _client.cacheMessageIds[uId] = true; var cacheUIds = RongIMLib.RongUtil.keys(_client.cacheMessageIds); if (cacheUIds.length > 10) { uId = cacheUIds[0]; delete _client.cacheMessageIds[uId]; } if (RongIMLib.RongIMClient._memoryStore.filterMessages.length > 0) { for (var j = 0, flen = RongIMLib.RongIMClient._memoryStore.filterMessages.length; j < flen; j++) { if (RongIMLib.RongIMClient.MessageParams[RongIMLib.RongIMClient._memoryStore.filterMessages[j]].objectName != list[i].classname) { _client.handler.onReceived(list[i]); } } } else { _client.handler.onReceived(list[i]); } } } }, onError: function (x) { setTimeout(function () { callback.onError(RongIMLib.ErrorCode.CHATROOM_HISMESSAGE_ERROR); }); } }, "DownStreamMessages"); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }, "ChrmOutput"); }; ServerDataProvider.prototype.getChatRoomInfo = function (chatRoomId, count, order, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.QueryChatroomInfoInput(); modules.setCount(count); modules.setOrder(order); RongIMLib.RongIMClient.bridge.queryMsg("queryChrmI", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), chatRoomId, { onSuccess: function (ret) { var userInfos = ret.userInfos; userInfos.forEach(function (item) { item.time = RongIMLib.MessageUtil.int64ToTimestamp(item.time); }); setTimeout(function () { callback.onSuccess(ret); }); }, onError: function (errcode) { setTimeout(function () { callback.onError(errcode); }); } }, "QueryChatroomInfoOutput"); }; ServerDataProvider.prototype.quitChatRoom = function (chatroomId, callback) { var e = new RongIMLib.RongIMClient.Protobuf.ChrmInput(); e.setNothing(1); RongIMLib.RongIMClient.bridge.queryMsg(17, RongIMLib.MessageUtil.ArrayForm(e.toArrayBuffer()), chatroomId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (errcode) { setTimeout(function () { callback.onError(errcode); }); } }, "ChrmOutput"); }; ServerDataProvider.prototype.setChatroomHisMessageTimestamp = function (chatRoomId, timestamp) { RongIMLib.RongIMClient._memoryStore.lastReadTime.set('chrhis_' + chatRoomId, timestamp); }; ServerDataProvider.prototype.getChatRoomHistoryMessages = function (chatRoomId, count, order, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.HistoryMsgInput(); modules.setTargetId(chatRoomId); var timestamp = RongIMLib.RongIMClient._memoryStore.lastReadTime.get('chrhis_' + chatRoomId) || 0; modules.setTime(timestamp); modules.setCount(count); modules.setOrder(order); RongIMLib.RongIMClient.bridge.queryMsg(34, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (data) { RongIMLib.RongIMClient._memoryStore.lastReadTime.set('chrhis_' + chatRoomId, RongIMLib.MessageUtil.int64ToTimestamp(data.syncTime)); var list = data.list.reverse(); for (var i = 0, len = list.length; i < len; i++) { list[i] = RongIMLib.MessageUtil.messageParser(list[i]); } setTimeout(function () { callback.onSuccess(list, !!data.hasMsg); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }, "HistoryMsgOuput"); }; ServerDataProvider.prototype.setMessageStatus = function (conversationType, targetId, timestamp, status, callback) { setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.addToBlacklist = function (userId, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.Add2BlackListInput(); modules.setUserId(userId); RongIMLib.RongIMClient.bridge.queryMsg(21, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.getBlacklist = function (callback) { var modules = new RongIMLib.RongIMClient.Protobuf.QueryBlackListInput(); modules.setNothing(1); RongIMLib.RongIMClient.bridge.queryMsg(23, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (list) { setTimeout(function () { callback.onSuccess(list); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }, "QueryBlackListOutput"); }; ServerDataProvider.prototype.getBlacklistStatus = function (userId, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.BlackListStatusInput(); modules.setUserId(userId); RongIMLib.RongIMClient.bridge.queryMsg(24, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function (status) { setTimeout(function () { callback.onSuccess(RongIMLib.BlacklistStatus[status]); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.removeFromBlacklist = function (userId, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RemoveFromBlackListInput(); modules.setUserId(userId); RongIMLib.RongIMClient.bridge.queryMsg(22, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.getFileToken = function (fileType, callback) { if (!(/(1|2|3|4)/.test(fileType.toString()))) { setTimeout(function () { callback.onError(RongIMLib.ErrorCode.QNTKN_FILETYPE_ERROR); }); return; } var modules = new RongIMLib.RongIMClient.Protobuf.GetQNupTokenInput(); modules.setType(fileType); RongIMLib.RongIMClient.bridge.queryMsg(30, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (data) { setTimeout(function () { callback.onSuccess(data); }); }, onError: function (errcode) { setTimeout(function () { callback.onError(errcode); }); } }, "GetQNupTokenOutput"); }; ServerDataProvider.prototype.getFileUrl = function (fileType, fileName, oriName, callback) { if (!(/(1|2|3|4)/.test(fileType.toString()))) { setTimeout(function () { callback.onError(RongIMLib.ErrorCode.QNTKN_FILETYPE_ERROR); }); return; } var modules = new RongIMLib.RongIMClient.Protobuf.GetQNdownloadUrlInput(); modules.setType(fileType); modules.setKey(fileName); if (oriName) { modules.setFileName(oriName); } RongIMLib.RongIMClient.bridge.queryMsg(31, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (data) { setTimeout(function () { callback.onSuccess(data); }); }, onError: function (errcode) { setTimeout(function () { callback.onError(errcode); }); } }, "GetQNdownloadUrlOutput"); }; /* methodType 1 : 多客服(客服后台使用); 2 : 消息撤回 params.userIds : 定向消息接收者 */ ServerDataProvider.prototype.sendMessage = function (conversationType, targetId, messageContent, sendCallback, mentiondMsg, pushText, appData, methodType, params) { if (!RongIMLib.Bridge._client.channel) { setTimeout(function () { sendCallback.onError(RongIMLib.ErrorCode.RC_NET_UNAVAILABLE, null); }); return; } if (!RongIMLib.Bridge._client.channel.socket.socket.connected) { setTimeout(function () { sendCallback.onError(RongIMLib.ErrorCode.TIMEOUT, null); }); throw new Error("connect is timeout! postion:sendMessage"); } var isGroup = (conversationType == RongIMLib.ConversationType.DISCUSSION || conversationType == RongIMLib.ConversationType.GROUP); var modules = new RongIMLib.RongIMClient.Protobuf.UpStreamMessage(); if (mentiondMsg && isGroup) { modules.setSessionId(7); } else { modules.setSessionId(RongIMLib.RongIMClient.MessageParams[messageContent.messageName].msgTag.getMessageTag()); } pushText && modules.setPushText(pushText); appData && modules.setAppData(appData); if (isGroup && messageContent.messageName == RongIMLib.RongIMClient.MessageType["ReadReceiptResponseMessage"]) { var rspMsg = messageContent; if (rspMsg.receiptMessageDic) { var ids = []; for (var key in rspMsg.receiptMessageDic) { ids.push(key); } modules.setUserId(ids); } } if (isGroup && messageContent.messageName == RongIMLib.RongIMClient.MessageType["SyncReadStatusMessage"]) { modules.setUserId(RongIMLib.Bridge._client.userId); } params = params || {}; var userIds = params.userIds; if (isGroup && userIds) { modules.setUserId(userIds); } modules.setClassname(RongIMLib.RongIMClient.MessageParams[messageContent.messageName].objectName); modules.setContent(messageContent.encode()); var content = modules.toArrayBuffer(); if (Object.prototype.toString.call(content) == "[object ArrayBuffer]") { content = [].slice.call(new Int8Array(content)); } var me = this, msg = new RongIMLib.Message(); var c = this.getConversation(conversationType, targetId, { onSuccess: function (conver) {}, onError: function(){} }); if (RongIMLib.RongIMClient.MessageParams[messageContent.messageName].msgTag.getMessageTag() == 3) { if (!c) { c = RongIMLib.RongIMClient.getInstance().createConversation(conversationType, targetId, ""); } c.sentTime = new Date().getTime(); c.sentStatus = RongIMLib.SentStatus.SENDING; c.senderUserName = ""; c.senderUserId = RongIMLib.Bridge._client.userId; c.notificationStatus = RongIMLib.ConversationNotificationStatus.DO_NOT_DISTURB; c.latestMessage = msg; c.unreadMessageCount = 0; RongIMLib.RongIMClient._dataAccessProvider.addConversation(c, { onSuccess: function (data) { } }); } RongIMLib.RongIMClient._memoryStore.converStore = c; msg.content = messageContent; msg.conversationType = conversationType; msg.senderUserId = RongIMLib.Bridge._client.userId; msg.objectName = RongIMLib.RongIMClient.MessageParams[messageContent.messageName].objectName; msg.targetId = targetId; msg.sentTime = new Date().getTime(); msg.messageDirection = RongIMLib.MessageDirection.SEND; msg.sentStatus = RongIMLib.SentStatus.SENT; msg.messageType = messageContent.messageName; RongIMLib.RongIMClient.bridge.pubMsg(conversationType.valueOf(), content, targetId, { onSuccess: function (data, code) { if (data && data.timestamp) { RongIMLib.RongIMClient._memoryStore.lastReadTime.set('converST_' + RongIMLib.Bridge._client.userId + conversationType + targetId, data.timestamp); } if ((conversationType == RongIMLib.ConversationType.DISCUSSION || conversationType == RongIMLib.ConversationType.GROUP) && messageContent.messageName == RongIMLib.RongIMClient.MessageType["ReadReceiptRequestMessage"]) { var reqMsg = msg.content; var sentkey = RongIMLib.Bridge._client.userId + reqMsg.messageUId + "SENT"; RongIMLib.RongIMClient._storageProvider.setItem(sentkey, JSON.stringify({ count: 0, dealtime: data.timestamp, userIds: {} })); } if (RongIMLib.RongIMClient.MessageParams[msg.messageType].msgTag.getMessageTag() == 3) { var cacheConversation = c || {}; cacheConversation.sentStatus = msg.sentStatus; cacheConversation.latestMessage = msg; me.updateConversation(cacheConversation); RongIMLib.RongIMClient._dataAccessProvider.addMessage(conversationType, targetId, msg, { onSuccess: function (ret) { msg = ret; msg.messageUId = data.messageUId; msg.sentTime = data.timestamp; msg.sentStatus = RongIMLib.SentStatus.SENT; msg.messageId = data.messageId; RongIMLib.RongIMClient._dataAccessProvider.updateMessage(msg); }, onError: function () { } }); } setTimeout(function () { cacheConversation && me.updateConversation(cacheConversation); msg.sentTime = data.timestamp; msg.messageUId = data.messageUId; sendCallback.onSuccess(msg, code); }); }, onError: function (errorCode, data) { msg.messageUId = data.messageUId || msg.messageUId; msg.sentTime = data.timestamp || msg.sentTime; msg.sentStatus = RongIMLib.SentStatus.FAILED; if (RongIMLib.RongIMClient.MessageParams[msg.messageType].msgTag.getMessageTag() == 3) { (c || {}).latestMessage = msg; } RongIMLib.RongIMClient._dataAccessProvider.addMessage(conversationType, targetId, msg, { onSuccess: function (ret) { msg.messageId = ret.messageId; RongIMLib.RongIMClient._dataAccessProvider.updateMessage(msg); }, onError: function () { } }); setTimeout(function () { sendCallback.onError(errorCode, msg); }); } }, null, methodType); sendCallback.onBefore && sendCallback.onBefore(RongIMLib.MessageIdHandler.messageId); msg.messageId = RongIMLib.MessageIdHandler.messageId + ""; }; ServerDataProvider.prototype.setConnectionStatusListener = function (listener) { if (RongIMLib.RongIMClient.bridge) { RongIMLib.RongIMClient.bridge.setListener(listener); } else { RongIMLib.RongIMClient._memoryStore.listenerList.push(listener); } }; ServerDataProvider.prototype.setOnReceiveMessageListener = function (listener) { if (RongIMLib.RongIMClient.bridge) { RongIMLib.RongIMClient.bridge.setListener(listener); } else { RongIMLib.RongIMClient._memoryStore.listenerList.push(listener); } }; ServerDataProvider.prototype.registerMessageType = function (messageType, objectName, messageTag, messageContent) { if (!messageType) { throw new Error("messageType can't be empty,postion -> registerMessageType"); } if (!objectName) { throw new Error("objectName can't be empty,postion -> registerMessageType"); } if (Object.prototype.toString.call(messageContent) == "[object Array]") { var regMsg = RongIMLib.ModelUtil.modleCreate(messageContent, messageType); RongIMLib.RongIMClient.RegisterMessage[messageType] = regMsg; } else if (Object.prototype.toString.call(messageContent) == "[object Function]" || Object.prototype.toString.call(messageContent) == "[object Object]") { if (!messageContent.encode) { throw new Error("encode method has not realized or messageName is undefined-> registerMessageType"); } if (!messageContent.decode) { throw new Error("decode method has not realized -> registerMessageType"); } } else { throw new Error("The index of 3 parameter was wrong type must be object or function or array-> registerMessageType"); } registerMessageTypeMapping[objectName] = messageType; }; ServerDataProvider.prototype.addConversation = function (conversation, callback) { var isAdd = true; for (var i = 0, len = RongIMLib.RongIMClient._memoryStore.conversationList.length; i < len; i++) { if (RongIMLib.RongIMClient._memoryStore.conversationList[i].conversationType === conversation.conversationType && RongIMLib.RongIMClient._memoryStore.conversationList[i].targetId === conversation.targetId) { RongIMLib.RongIMClient._memoryStore.conversationList.unshift(RongIMLib.RongIMClient._memoryStore.conversationList.splice(i, 1)[0]); isAdd = false; break; } } if (isAdd) { RongIMLib.RongIMClient._memoryStore.conversationList.unshift(conversation); } callback && callback.onSuccess(true); }; ServerDataProvider.prototype.updateConversation = function (conversation) { var conver; for (var i = 0, len = RongIMLib.RongIMClient._memoryStore.conversationList.length; i < len; i++) { var item = RongIMLib.RongIMClient._memoryStore.conversationList[i]; if (conversation.conversationType === item.conversationType && conversation.targetId === item.targetId) { conversation.conversationTitle && (item.conversationTitle = conversation.conversationTitle); conversation.senderUserName && (item.senderUserName = conversation.senderUserName); conversation.senderPortraitUri && (item.senderPortraitUri = conversation.senderPortraitUri); conversation.latestMessage && (item.latestMessage = conversation.latestMessage); conversation.sentStatus && (item.sentStatus = conversation.sentStatus); break; } } return conver; }; ServerDataProvider.prototype.removeConversation = function (conversationType, targetId, callback) { var mod = new RongIMLib.RongIMClient.Protobuf.RelationsInput(); mod.setType(conversationType); RongIMLib.RongIMClient.bridge.queryMsg(27, RongIMLib.MessageUtil.ArrayForm(mod.toArrayBuffer()), targetId, { onSuccess: function () { var conversations = RongIMLib.RongIMClient._memoryStore.conversationList; var len = conversations.length; for (var i = 0; i < len; i++) { if (conversations[i].conversationType == conversationType && targetId == conversations[i].targetId) { conversations.splice(i, 1); break; } } callback.onSuccess(true); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.getMessage = function (messageId, callback) { callback.onSuccess(new RongIMLib.Message()); }; ServerDataProvider.prototype.addMessage = function (conversationType, targetId, message, callback) { if (callback) { callback.onSuccess(message); } }; ServerDataProvider.prototype.removeMessage = function (conversationType, targetId, messageIds, callback) { RongIMLib.RongIMClient.getInstance().deleteRemoteMessages(conversationType, targetId, messageIds, callback); }; ServerDataProvider.prototype.removeLocalMessage = function (conversationType, targetId, timestamps, callback) { callback.onSuccess(true); }; ServerDataProvider.prototype.updateMessage = function (message, callback) { if (callback) { callback.onSuccess(message); } }; ServerDataProvider.prototype.clearRemoteHistoryMessages = function (params, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.CleanHisMsgInput(); var conversationType = params.conversationType; var _topic = { 1: 'cleanPMsg', 2: 'cleanDMsg', 3: 'cleanGMsg', 5: 'cleanCMsg', 6: 'cleanSMsg' }; var topic = _topic[conversationType]; if (!topic) { callback.onError(RongIMLib.ErrorCode.CLEAR_HIS_TYPE_ERROR); return; } var timestamp = params.timestamp; if (typeof timestamp != 'number') { callback.onError(RongIMLib.ErrorCode.CLEAR_HIS_TIME_ERROR); return; } modules.setDataTime(timestamp); var targetId = params.targetId; modules.setTargetId(targetId); RongIMLib.RongIMClient.bridge.queryMsg(topic, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), targetId, { onSuccess: function (result) { callback.onSuccess(!result); }, onError: function (error) { // error 1 历史消息云存储没有开通、传入时间大于服务器时间 清除失败,1 与其他错误码冲突,所以自定义错误码返回 if (error == 1) { error = RongIMLib.ErrorCode.CLEAR_HIS_ERROR; } setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.clearHistoryMessages = function (params, callback) { this.clearRemoteHistoryMessages(params, callback); }; // 兼容老版本 ServerDataProvider.prototype.clearMessages = function (conversationType, targetId, callback) { }; ServerDataProvider.prototype.updateMessages = function (conversationType, targetId, key, value, callback) { var me = this; if (key == "readStatus") { if (RongIMLib.RongIMClient._memoryStore.conversationList.length > 0) { me.getConversationList({ onSuccess: function (list) { Array.forEach(list, function (conver) { if (conver.conversationType == conversationType && conver.targetId == targetId) { conver.unreadMessageCount = 0; } }); }, onError: function (errorCode) { setTimeout(function () { callback.onError(errorCode); }); } }, null); } } setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.getConversation = function (conversationType, targetId, callback) { var conver = null; for (var i = 0, len = RongIMLib.RongIMClient._memoryStore.conversationList.length; i < len; i++) { if (RongIMLib.RongIMClient._memoryStore.conversationList[i].conversationType == conversationType && RongIMLib.RongIMClient._memoryStore.conversationList[i].targetId == targetId) { conver = RongIMLib.RongIMClient._memoryStore.conversationList[i]; if (RongIMLib.RongUtil.supportLocalStorage()) { var count = RongIMLib.RongIMClient._storageProvider.getItem("cu" + RongIMLib.Bridge._client.userId + conversationType + targetId); if (conver.unreadMessageCount == 0) { conver.unreadMessageCount = Number(count); } } } } setTimeout(function () { callback.onSuccess(conver); }); return conver; }; /* WebSDK 不支持会话列表分页, 内部获取全量会话列表 */ ServerDataProvider.prototype.getConversationsByPage = function(conversation, callbacks){ var isSync = RongIMLib.RongIMClient._memoryStore.isSyncRemoteConverList; var list = RongIMLib.RongIMClient._memoryStore.conversationList; if (!isSync) { setTimeout(function () { callbacks.onSuccess(list); }); return; } var conversationTypes = null; var count = conversation.count; RongIMLib.RongIMClient.getInstance().getRemoteConversationList({ onSuccess: function (list) { if (RongIMLib.RongUtil.supportLocalStorage()) { Array.forEach(RongIMLib.RongIMClient._memoryStore.conversationList, function (item) { var count = RongIMLib.RongIMClient._storageProvider.getItem("cu" + RongIMLib.Bridge._client.userId + item.conversationType + item.targetId); if (item.unreadMessageCount == 0) { item.unreadMessageCount = Number(count); } }); } RongIMLib.RongIMClient._memoryStore.isSyncRemoteConverList = false; setTimeout(function () { callbacks.onSuccess(list); }); }, onError: function (errorcode) { setTimeout(function () { callbacks.onError(errorcode); }); } }, conversationTypes, count); }, ServerDataProvider.prototype.getConversationList = function (callback, conversationTypes, count, isHidden) { var isSync = RongIMLib.RongIMClient._memoryStore.isSyncRemoteConverList; var list = RongIMLib.RongIMClient._memoryStore.conversationList; if (!isSync) { setTimeout(function () { callback.onSuccess(list); }); return; } RongIMLib.RongIMClient.getInstance().getRemoteConversationList({ onSuccess: function (list) { if (RongIMLib.RongUtil.supportLocalStorage()) { Array.forEach(RongIMLib.RongIMClient._memoryStore.conversationList, function (item) { var count = RongIMLib.RongIMClient._storageProvider.getItem("cu" + RongIMLib.Bridge._client.userId + item.conversationType + item.targetId); if (item.unreadMessageCount == 0) { item.unreadMessageCount = Number(count); } }); } RongIMLib.RongIMClient._memoryStore.isSyncRemoteConverList = false; setTimeout(function () { callback.onSuccess(list); }); }, onError: function (errorcode) { setTimeout(function () { callback.onError(errorcode); }); } }, conversationTypes, count, isHidden); }; ServerDataProvider.prototype.clearCache = function () { var memoryStore = RongIMLib.RongIMClient._memoryStore || {}; memoryStore.conversationList = []; memoryStore.isSyncRemoteConverList = true; }; ServerDataProvider.prototype.clearConversations = function (conversationTypes, callback) { Array.forEach(conversationTypes, function (conversationType) { Array.forEach(RongIMLib.RongIMClient._memoryStore.conversationList, function (conver) { if (conversationType == conver.conversationType) { RongIMLib.RongIMClient.getInstance().removeConversation(conver.conversationType, conver.targetId, { onSuccess: function () { }, onError: function () { } }); } }); }); setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.setMessageContent = function (messageId, content, objectname) { }; ; ServerDataProvider.prototype.getHistoryMessages = function (conversationType, targetId, timestamp, count, callback) { RongIMLib.RongIMClient.getInstance().getRemoteHistoryMessages(conversationType, targetId, timestamp, count, callback); }; ServerDataProvider.prototype.getTotalUnreadCount = function (callback, conversationTypes) { var count = 0; if (conversationTypes) { for (var i = 0, len = conversationTypes.length; i < len; i++) { Array.forEach(RongIMLib.RongIMClient._memoryStore.conversationList, function (conver) { if (conver.conversationType == conversationTypes[i]) { count += conver.unreadMessageCount; } }); } } else { Array.forEach(RongIMLib.RongIMClient._memoryStore.conversationList, function (conver) { count += conver.unreadMessageCount; }); } callback.onSuccess(count); return count; }; ServerDataProvider.prototype.getConversationUnreadCount = function (conversationTypes, callback) { var count = 0; Array.forEach(conversationTypes, function (converType) { Array.forEach(RongIMLib.RongIMClient._memoryStore.conversationList, function (conver) { if (conver.conversationType == converType) { count += conver.unreadMessageCount; } }); }); setTimeout(function () { callback.onSuccess(count); }); }; ServerDataProvider.prototype.getUnreadCount = function (conversationType, targetId, callback) { var conversation = this.getConversation(conversationType, targetId, { onSuccess: function (conver) { setTimeout(function () { callback.onSuccess(conver ? conver.unreadMessageCount : 0); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); return conversation.unreadMessageCount || 0; }; ServerDataProvider.prototype.clearUnreadCountByTimestamp = function (conversationType, targetId, timestamp, callback) { setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.clearUnreadCount = function (conversationType, targetId, callback) { RongIMLib.RongIMClient._storageProvider.removeItem("cu" + RongIMLib.Bridge._client.userId + conversationType + targetId); this.getConversation(conversationType, targetId, { onSuccess: function (conver) { if (conver) { conver.unreadMessageCount = 0; conver.mentionedMsg = null; var mentioneds = RongIMLib.RongIMClient._storageProvider.getItem("mentioneds_" + RongIMLib.Bridge._client.userId + '_' + conversationType + '_' + targetId); if (mentioneds) { var info = JSON.parse(mentioneds); delete info[conversationType + "_" + targetId]; if (!RongIMLib.MessageUtil.isEmpty(info)) { RongIMLib.RongIMClient._storageProvider.setItem("mentioneds_" + RongIMLib.Bridge._client.userId + '_' + conversationType + '_' + targetId, JSON.stringify(info)); } else { RongIMLib.RongIMClient._storageProvider.removeItem("mentioneds_" + RongIMLib.Bridge._client.userId + '_' + conversationType + '_' + targetId); } } } setTimeout(function () { callback.onSuccess(true); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.setConversationToTop = function (conversationType, targetId, isTop, callback) { var me = this; this.getConversation(conversationType, targetId, { onSuccess: function (conver) { conver.isTop = isTop; me.addConversation(conver, callback); setTimeout(function () { callback.onSuccess(true); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.getConversationNotificationStatus = function (params, callback) { var targetId = params.targetId; var conversationType = params.conversationType; var notification = RongIMLib.RongIMClient._memoryStore.notification; var getKey = function () { return conversationType + '_' + targetId; }; var key = getKey(); var status = notification[key]; if (typeof status == 'number') { callback.onSuccess(status); return; } var topics = { 1: 'qryPPush', 3: 'qryDPush' }; var topic = topics[conversationType]; if (!topic) { var error = 8001; callback.onError(error); return; } var modules = new RongIMLib.RongIMClient.Protobuf.BlockPushInput(); modules.setBlockeeId(targetId); var userId = RongIMLib.Bridge._client.userId; var success = function (status) { notification[key] = status; setTimeout(function () { callback.onSuccess(status); }); }; RongIMLib.RongIMClient.bridge.queryMsg(topic, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function (status) { success(status); }, onError: function (e) { if (e == 1) { success(e); } else { setTimeout(function () { callback.onError(e); }); } } }); }; ServerDataProvider.prototype.setConversationNotificationStatus = function (params, callback) { var conversationType = params.conversationType; var targetId = params.targetId; var status = params.status; var getKey = function () { return conversationType + '_' + status; }; var topics = { '1_1': 'blkPPush', '3_1': 'blkDPush', '1_0': 'unblkPPush', '3_0': 'unblkDPush' }; var key = getKey(); var notification = RongIMLib.RongIMClient._memoryStore.notification; notification[key] = status; var topic = topics[key]; if (!topic) { var error = 8001; setTimeout(function () { callback.onError(error); }); return; } var modules = new RongIMLib.RongIMClient.Protobuf.BlockPushInput(); modules.setBlockeeId(targetId); var userId = RongIMLib.Bridge._client.userId; RongIMLib.RongIMClient.bridge.queryMsg(topic, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function (status) { setTimeout(function () { callback.onSuccess(status); }); }, onError: function (e) { setTimeout(function () { callback.onError(e); }); } }); }; ServerDataProvider.prototype.getUserStatus = function (userId, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.GetUserStatusInput(); userId = RongIMLib.Bridge._client.userId; RongIMLib.RongIMClient.bridge.queryMsg(35, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function (status) { status = RongIMLib.RongInnerTools.convertUserStatus(status); setTimeout(function () { callback.onSuccess(status); }); }, onError: function (e) { setTimeout(function () { callback.onError(e); }); } }, 'GetUserStatusOutput'); // callback.onSuccess(new UserStatus()); }; ServerDataProvider.prototype.setUserStatus = function (status, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.SetUserStatusInput(); var userId = RongIMLib.Bridge._client.userId; if (status) { modules.setStatus(status); } RongIMLib.RongIMClient.bridge.queryMsg(36, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function (status) { setTimeout(function () { callback.onSuccess(true); }); }, onError: function (e) { setTimeout(function () { callback.onError(e); }); } }, 'SetUserStatusOutput'); }; ServerDataProvider.prototype.subscribeUserStatus = function (userIds, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.SubUserStatusInput(); var userId = RongIMLib.Bridge._client.userId; modules.setUserid(userIds); RongIMLib.RongIMClient.bridge.queryMsg(37, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function (status) { setTimeout(function () { callback && callback.onSuccess(true); }); }, onError: function (e) { setTimeout(function () { callback && callback.onError(e); }); } }, 'SubUserStatusOutput'); }; ServerDataProvider.prototype.setUserStatusListener = function (params, callback) { RongIMLib.RongIMClient.userStatusListener = callback; var userIds = params.userIds || []; if (userIds.length) { RongIMLib.RongIMClient._dataAccessProvider.subscribeUserStatus(userIds); } }; ServerDataProvider.prototype.clearListeners = function () { }; ServerDataProvider.prototype.setServerInfo = function (info) { }; ServerDataProvider.prototype.getUnreadMentionedMessages = function (conversationType, targetId) { return null; }; ServerDataProvider.prototype.setConversationHidden = function (conversationType, targetId, isHidden) { }; ServerDataProvider.prototype.setMessageExtra = function (messageId, value, callback) { setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.setMessageReceivedStatus = function (messageId, receivedStatus, callback) { setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.setMessageSentStatus = function (messageId, sentStatus, callback) { setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.getAllConversations = function (callback) { setTimeout(function () { callback.onSuccess([]); }); }; ServerDataProvider.prototype.getConversationByContent = function (keywords, callback) { setTimeout(function () { callback.onSuccess([]); }); }; ServerDataProvider.prototype.getMessagesFromConversation = function (conversationType, targetId, keywords, callback) { setTimeout(function () { callback.onSuccess([]); }); }; ServerDataProvider.prototype.searchConversationByContent = function (keyword, callback, conversationTypes, customMsgTypes) { setTimeout(function () { callback.onSuccess([]); }); }; ServerDataProvider.prototype.searchMessageByContent = function (conversationType, targetId, keyword, timestamp, count, total, callback) { setTimeout(function () { callback.onSuccess([]); }); }; ServerDataProvider.prototype.getDelaTime = function () { return RongIMLib.RongIMClient._memoryStore.deltaTime; }; ServerDataProvider.prototype.getCurrentConnectionStatus = function () { var client = RongIMLib.Bridge._client || {}; var channel = client.channel || {}; var status = RongIMLib.ConnectionStatus.CONNECTION_CLOSED; if (typeof channel.connectionStatus == 'number') { status = channel.connectionStatus; } return status; }; ServerDataProvider.prototype.getAgoraDynamicKey = function (engineType, channelName, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.VoipDynamicInput(); modules.setEngineType(engineType); modules.setChannelName(channelName); RongIMLib.RongIMClient.bridge.queryMsg(32, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (result) { setTimeout(function () { callback.onSuccess(result); }); }, onError: function (errorCode) { setTimeout(function () { callback.onError(errorCode); }); } }, "VoipDynamicOutput"); }; ServerDataProvider.prototype.setDeviceInfo = function (deviceId) { }; ServerDataProvider.prototype.setEnvironment = function (isPrivate) { }; ServerDataProvider.prototype.getPublicServiceProfile = function (publicServiceType, publicServiceId, callback) { var profile = RongIMLib.RongIMClient._memoryStore.publicServiceMap.get(publicServiceType, publicServiceId); setTimeout(function () { callback.onSuccess(profile); }); }; ServerDataProvider.prototype.getRemotePublicServiceList = function (callback, pullMessageTime) { if (RongIMLib.RongIMClient._memoryStore.depend.openMp) { var modules = new RongIMLib.RongIMClient.Protobuf.PullMpInput(), self = this; if (!pullMessageTime) { modules.setTime(0); } else { modules.setTime(pullMessageTime); } modules.setMpid(""); RongIMLib.RongIMClient.bridge.queryMsg(28, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (data) { //TODO 找出最大时间 // self.lastReadTime.set(conversationType + targetId, MessageUtil.int64ToTimestamp(data.syncTime)); RongIMLib.RongIMClient._memoryStore.publicServiceMap.publicServiceList.length = 0; RongIMLib.RongIMClient._memoryStore.publicServiceMap.publicServiceList = data; setTimeout(function () { callback && callback.onSuccess(data); }); }, onError: function (errorCode) { setTimeout(function () { callback && callback.onError(errorCode); }); } }, "PullMpOutput"); } }; return ServerDataProvider; })(); RongIMLib.ServerDataProvider = ServerDataProvider; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var VCDataProvider = (function () { function VCDataProvider(addon) { this.userId = ""; this.useConsole = false; this.appKey = ""; this.token = ""; this.addon = addon; } VCDataProvider.prototype.init = function (appKey, config) { this.appKey = appKey; this.useConsole && console.log("init"); config = config || {}; var sdkInfo = this.addon.initWithAppkey(appKey, config.dbPath); if (sdkInfo) { sdkInfo = JSON.parse(sdkInfo); } // 0 不存不计数 1 只存不计数 3 存且计数 this.addon.registerMessageType("RC:VcMsg", 3); this.addon.registerMessageType("RC:ImgTextMsg", 3); this.addon.registerMessageType("RC:FileMsg", 3); this.addon.registerMessageType("RC:LBSMsg", 3); this.addon.registerMessageType("RC:PSImgTxtMsg", 3); this.addon.registerMessageType("RC:PSMultiImgTxtMsg", 3); this.addon.registerMessageType("RCJrmf:RpMsg", 3); this.addon.registerMessageType("RCJrmf:RpOpendMsg", 1); this.addon.registerMessageType("RC:GrpNtf", 1); this.addon.registerMessageType("RC:DizNtf", 0); this.addon.registerMessageType("RC:InfoNtf", 0); this.addon.registerMessageType("RC:ContactNtf", 0); this.addon.registerMessageType("RC:ProfileNtf", 0); this.addon.registerMessageType("RC:CmdNtf", 0); this.addon.registerMessageType("RC:CmdMsg", 0); this.addon.registerMessageType("RC:TypSts", 0); this.addon.registerMessageType("RC:CsChaR", 0); this.addon.registerMessageType("RC:CsHsR", 0); this.addon.registerMessageType("RC:CsEnd", 0); this.addon.registerMessageType("RC:CsSp", 0); this.addon.registerMessageType("RC:CsUpdate", 0); this.addon.registerMessageType("RC:CsContact", 0); this.addon.registerMessageType("RC:ReadNtf", 0); this.addon.registerMessageType("RC:VCAccept", 0); this.addon.registerMessageType("RC:VCRinging", 0); this.addon.registerMessageType("RC:VCSummary", 0); this.addon.registerMessageType("RC:VCHangup", 0); this.addon.registerMessageType("RC:VCInvite", 0); this.addon.registerMessageType("RC:VCModifyMedia", 0); this.addon.registerMessageType("RC:VCModifyMem", 0); this.addon.registerMessageType("RC:PSCmd", 0); this.addon.registerMessageType("RC:RcCmd", 0); this.addon.registerMessageType("RC:SRSMsg", 0); this.addon.registerMessageType("RC:RRReqMsg", 0); this.addon.registerMessageType("RC:RRRspMsg", 0); return sdkInfo; }; VCDataProvider.prototype.connect = function (token, callback, userId, serverConf) { this.useConsole && console.log("connect"); this.userId = userId; this.connectCallback = callback; RongIMLib.Bridge._client = { userId: userId }; serverConf = serverConf || {}; var openmp = !!serverConf.openMp; var openus = !!serverConf.openUS; if (serverConf.type) { this.addon.setEnvironment(true); } this.addon.connectWithToken(token, userId, serverConf.serverList, serverConf.version, openmp, openus); }; VCDataProvider.prototype.setServerInfo = function (info) { 'setServerInfo' in this.addon && this.addon.setServerInfo(info.navi); }; VCDataProvider.prototype.logout = function () { this.useConsole && console.log("logout"); this.disconnect(); }; VCDataProvider.prototype.disconnect = function () { this.useConsole && console.log("disconnect"); this.addon.disconnect(true); }; VCDataProvider.prototype.clearData = function () { this.useConsole && console.log("clearData"); return this.addon.clearData(); }; VCDataProvider.prototype.clearListeners = function () { this.addon.setOnReceiveStatusListener(); this.addon.setConnectionStatusListener(); this.addon.setOnReceiveMessageListener(); }; VCDataProvider.prototype.setConnectionStatusListener = function (listener) { var me = this; /** ConnectionStatus_TokenIncorrect = 31004, ConnectionStatus_Connected = 0, ConnectionStatus_KickedOff = 6, // 其他设备登录 ConnectionStatus_Connecting = 10,// 连接中 ConnectionStatus_SignUp = 12, // 未登录 ConnectionStatus_NetworkUnavailable = 1, // 连接断开 ConnectionStatus_ServerInvalid = 8, // 断开 ConnectionStatus_ValidateFailure = 9,//断开 ConnectionStatus_Unconnected = 11,//断开 ConnectionStatus_DisconnExecption = 31011 //断开 RC_NAVI_MALLOC_ERROR = 30000,//断开 RC_NAVI_NET_UNAVAILABLE= 30002,//断开 RC_NAVI_SEND_FAIL = 30004,//断开 RC_NAVI_REQ_TIMEOUT = 30005,//断开 RC_NAVI_RECV_FAIL = 30006,//断开 RC_NAVI_RESOURCE_ERROR = 30007,//断开 RC_NAVI_NODE_NOT_FOUND = 30008,//断开 RC_NAVI_DNS_ERROR = 30009,//断开 */ me.connectListener = listener; this.useConsole && console.log("setConnectionStatusListener"); me.addon && me.addon.setConnectionStatusListener(function (result) { switch (result) { case 10: setTimeout(function () { listener.onChanged(RongIMLib.ConnectionStatus.CONNECTING); }); break; case 31004: setTimeout(function () { me.connectCallback.onTokenIncorrect(); }); break; case 1: case 9: case 11: case 12: case 31011: case 30000: case 30002: case 30004: case 30005: case 30006: case 30007: case 30008: case 30009: setTimeout(function () { listener.onChanged(RongIMLib.ConnectionStatus.DISCONNECTED); }); break; case 0: case 33005: setTimeout(function () { me.connectCallback.onSuccess(me.userId); listener.onChanged(RongIMLib.ConnectionStatus.CONNECTED); }); break; case 6: setTimeout(function () { listener.onChanged(RongIMLib.ConnectionStatus.KICKED_OFFLINE_BY_OTHER_CLIENT); }); break; default: setTimeout(function () { listener.onChanged(result); }); break; } }); }; VCDataProvider.prototype.setOnReceiveMessageListener = function (listener) { var me = this; me.messageListener = listener; this.useConsole && console.log("setOnReceiveMessageListener"); me.addon && me.addon.setOnReceiveMessageListener(function (result, leftCount, offline, hasMore) { var message = me.buildMessage(result); message.offLineMessage = offline; setTimeout(function () { var voipMsgTypes = ['AcceptMessage', 'RingingMessage', 'HungupMessage', 'InviteMessage', 'MediaModifyMessage', 'MemberModifyMessage']; var isVoIPMsg = voipMsgTypes.indexOf(message.messageType) > -1; if (isVoIPMsg) { RongIMClient._voipProvider && RongIMClient._voipProvider.onReceived(message); }else{ listener.onReceived(message, leftCount, hasMore); } // listener.onReceived(message, leftCount); }); }); }; VCDataProvider.prototype.sendTypingStatusMessage = function (conversationType, targetId, messageName, sendCallback) { var me = this; this.useConsole && console.log("sendTypingStatusMessage"); if (messageName in RongIMLib.RongIMClient.MessageParams) { me.sendMessage(conversationType, targetId, RongIMLib.TypingStatusMessage.obtain(RongIMLib.RongIMClient.MessageParams[messageName].objectName, ""), { onSuccess: function () { setTimeout(function () { sendCallback.onSuccess(); }); }, onError: function (errorCode) { setTimeout(function () { sendCallback.onError(errorCode, null); }); }, onBefore: function () { } }); } }; VCDataProvider.prototype.setMessageStatus = function (conversationType, targetId, timestamp, status, callback) { this.addon.updateMessageReceiptStatus(conversationType, targetId, timestamp); callback.onSuccess(true); }; VCDataProvider.prototype.sendTextMessage = function (conversationType, targetId, content, sendMessageCallback) { var msgContent = RongIMLib.TextMessage.obtain(content); this.useConsole && console.log("sendTextMessage"); this.sendMessage(conversationType, targetId, msgContent, sendMessageCallback); }; VCDataProvider.prototype.getRemoteConversations = function(count, beginTime, order, callback){ this.addon.getRemoteConversations(count, beginTime, order, function(){ callback.onSuccess(); }, function(code){ callback.onError(code); }); }; VCDataProvider.prototype.getRemoteHistoryMessages = function (conversationType, targetId, timestamp, count, callback) { try { var me = this; me.useConsole && console.log("getRemoteHistoryMessages"); me.addon.getRemoteHistoryMessages(conversationType, targetId, timestamp ? timestamp : 0, count, function (ret, hasMore) { var list = ret ? JSON.parse(ret).list : [], msgs = []; list.reverse(); for (var i = 0, len = list.length; i < len; i++) { var message = me.buildMessage(list[i].obj); message.sentStatus = RongIMLib.SentStatus.READ; msgs[i] = message; } callback.onSuccess(msgs, hasMore ? true : false); }, function (errorCode) { callback.onError(errorCode); }); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.getRemoteConversationList = function (callback, conversationTypes, count, isGetHiddenConvers) { try { this.useConsole && console.log("getRemoteConversationList"); var converTypes = conversationTypes || [1, 2, 3, 4, 5, 6, 7, 8]; var result = this.addon.getConversationList(converTypes); var list = JSON.parse(result).list, convers = [], me = this; isGetHiddenConvers = typeof isGetHiddenConvers === 'boolean' ? isGetHiddenConvers : false; for (var i = 0, len = list.length; i < len; i++) { var tmpObj = list[i].obj, obj = JSON.parse(tmpObj); if (obj != "") { if (obj.isHidden == 1 && isGetHiddenConvers) { continue; } convers[i] = me.buildConversation(tmpObj); } } callback.onSuccess(convers); } catch (e) { callback.onError(e); } }; /* var conversation = { // 会话类型 types: [1, 2, 3, 4, 5, 6, 7, 8], // 获取会话的开始始时间, 0 ,按会话中最后一条消息最大 sentTime 倒序开始获取 sentTime: 0, // 获取条数 count: 100 }; var callbacks = { onSuccess: function(){ }, onError: function(){ } }; */ VCDataProvider.prototype.getConversationsByPage = function (conversation, callbacks) { var types = conversation.types || [1, 2, 3, 4, 5, 6, 7, 8]; var sentTime = conversation.sentTime || 0; var count = conversation.count || 50; var result = this.addon.getConversationListByPage(types, sentTime, count); var list = JSON.parse(result).list, conversations = []; for (var i = 0, len = list.length; i < len; i++) { var tmpObj = list[i].obj, obj = JSON.parse(tmpObj); if (obj != "") { conversations[i] = this.buildConversation(tmpObj); } } callbacks.onSuccess(conversations); }; VCDataProvider.prototype.removeConversation = function (conversationType, targetId, callback) { try { this.useConsole && console.log("removeConversation"); this.addon.removeConversation(conversationType, targetId); var conversations = RongIMLib.RongIMClient._memoryStore.conversationList; var len = conversations.length; for (var i = 0; i < len; i++) { if (conversations[i].conversationType == conversationType && targetId == conversations[i].targetId) { conversations.splice(i, 1); break; } } callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.joinChatRoom = function (chatRoomId, messageCount, callback) { this.useConsole && console.log("joinChatRoom"); this.addon.joinChatRoom(chatRoomId, messageCount, function () { callback.onSuccess(); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.quitChatRoom = function (chatRoomId, callback) { this.useConsole && console.log("quitChatRoom"); this.addon.quitChatRoom(chatRoomId, function () { callback.onSuccess(); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.addToBlacklist = function (userId, callback) { this.useConsole && console.log("addToBlacklist"); this.addon.addToBlacklist(userId, function () { callback.onSuccess(); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.getBlacklist = function (callback) { this.useConsole && console.log("getBlacklist"); this.addon.getBlacklist(function (blacklistors) { callback.onSuccess(blacklistors); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.getBlacklistStatus = function (userId, callback) { this.useConsole && console.log("getBlacklistStatus"); this.addon.getBlacklistStatus(userId, function (result) { callback.onSuccess(result); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.removeFromBlacklist = function (userId, callback) { this.useConsole && console.log("removeFromBlacklist"); this.addon.removeFromBlacklist(userId, function () { callback.onSuccess(); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.sendMessage = function (conversationType, targetId, messageContent, sendCallback, mentiondMsg, pushText, appData, methodType, params) { var me = this, users = []; me.useConsole && console.log("sendMessage"); params = params || {}; var isGroup = (conversationType == RongIMLib.ConversationType.DISCUSSION || conversationType == RongIMLib.ConversationType.GROUP); if (isGroup && messageContent.messageName == RongIMLib.RongIMClient.MessageType["ReadReceiptResponseMessage"]) { users = []; var rspMsg = messageContent; if (rspMsg.receiptMessageDic) { var ids = []; for (var key in rspMsg.receiptMessageDic) { ids.push(key); } users = ids; } } if (isGroup && messageContent.messageName == RongIMLib.RongIMClient.MessageType["SyncReadStatusMessage"]) { users = []; users.push(me.userId); } var userIds = params.userIds; if (isGroup && userIds) { users = userIds; } var msg = me.addon.sendMessage(conversationType, targetId, RongIMLib.RongIMClient.MessageParams[messageContent.messageName].objectName, messageContent.encode(), pushText || "", appData || "", function (progress) { }, function (message, code) { sendCallback.onSuccess(me.buildMessage(message), code); }, function (message, code) { sendCallback.onError(code, me.buildMessage(message)); }, users); var tempMessage = JSON.parse(msg); sendCallback.onBefore && sendCallback.onBefore(tempMessage.messageId); RongIMLib.MessageIdHandler.messageId = tempMessage.messageId; }; VCDataProvider.prototype.registerMessageType = function (messageType, objectName, messageTag, messageContent, searchProp) { this.useConsole && console.log("registerMessageType"); this.addon.registerMessageType(objectName, messageTag.getMessageTag(), searchProp); var regMsg = RongIMLib.ModelUtil.modleCreate(messageContent, messageType); RongIMLib.RongIMClient.RegisterMessage[messageType] = regMsg; RongIMLib.RongIMClient.RegisterMessage[messageType].messageName = messageType; registerMessageTypeMapping[objectName] = messageType; RongIMLib.RongIMClient.MessageType[messageType] = messageType; RongIMLib.RongIMClient.MessageParams[messageType] = { objectName: objectName, msgTag: messageTag }; typeMapping[objectName] = messageType; }; VCDataProvider.prototype.addMessage = function (conversationType, targetId, message, callback) { this.useConsole && console.log("addMessage"); var direction = message.direction; var msg = this.addon.insertMessage(conversationType, targetId, message.senderUserId, message.objectName, JSON.stringify(message.content), function () { callback.onSuccess(me.buildMessage(msg)); }, function () { callback.onError(RongIMLib.ErrorCode.MSG_INSERT_ERROR); }, direction), me = this; }; VCDataProvider.prototype.removeMessage = function (conversationType, targetId, delMsgs, callback) { }; VCDataProvider.prototype.removeLocalMessage = function (conversationType, targetId, timestamps, callback) { try { this.useConsole && console.log("removeLocalMessage"); this.addon.deleteMessages(timestamps); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.getMessage = function (messageId, callback) { try { this.useConsole && console.log("getMessage"); var msg = this.buildMessage(this.addon.getMessage(messageId)); callback.onSuccess(msg); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.clearMessages = function (conversationType, targetId, callback) { try { this.useConsole && console.log("clearMessages"); this.addon.clearMessages(conversationType, targetId); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.getConversation = function (conversationType, targetId, callback) { var conversation = null; try { this.useConsole && console.log("getConversation"); var ret = this.addon.getConversation(conversationType, targetId); conversation = this.buildConversation(ret); callback.onSuccess(conversation); } catch (e) { callback.onError(e); } return conversation; }; VCDataProvider.prototype.getConversationList = function (callback, conversationTypes, count, isGetHiddenConvers) { this.useConsole && console.log("getConversationList"); this.getRemoteConversationList(callback, conversationTypes, count, isGetHiddenConvers); }; VCDataProvider.prototype.clearCache = function () { var memoryStore = RongIMLib.RongIMClient._memoryStore || {}; memoryStore.conversationList = []; memoryStore.isSyncRemoteConverList; }; VCDataProvider.prototype.clearConversations = function (conversationTypes, callback) { try { this.useConsole && console.log("clearConversations"); this.addon.clearConversations(); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.setMessageContent = function (messageId, content, objectName) { content = JSON.stringify(content); this.addon.setMessageContent(messageId, content, objectName); }; VCDataProvider.prototype.getHistoryMessages = function (conversationType, targetId, timestamp, count, callback, objectname, direction) { this.useConsole && console.log("getHistoryMessages"); if (count <= 0) { callback.onError(RongIMLib.ErrorCode.TIMEOUT); return; } objectname = objectname || ''; direction = typeof direction == 'undefined' || direction; try { var ret = this.addon.getHistoryMessages(conversationType, targetId, timestamp ? timestamp : 0, count, objectname, direction); var list = ret ? JSON.parse(ret).list : [], msgs = [], me = this; list.reverse(); for (var i = 0, len = list.length; i < len; i++) { var message = me.buildMessage(list[i].obj); // message.sentStatus = RongIMLib.SentStatus.READ; msgs[i] = message; } callback.onSuccess(msgs, len == count); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.clearRemoteHistoryMessages = function (params, callback) { var conversationType = params.conversationType; var targetId = params.targetId; var timestamp = params.timestamp; var _topic = { 1: true, 2: true, 3: true, 5: true, 6: true }; var topic = _topic[conversationType]; if (!topic) { callback.onError(RongIMLib.ErrorCode.CLEAR_HIS_TYPE_ERROR); return; } if (typeof timestamp != 'number') { callback.onError(RongIMLib.ErrorCode.CLEAR_HIS_TIME_ERROR); return; } this.addon.clearRemoteHistoryMessages(+conversationType, targetId, timestamp, function () { callback.onSuccess(true); }, function (errorCode) { if (errorCode == 1) { // 没有开通历史消息云存储 errorCode = RongIMLib.ErrorCode.CLEAR_HIS_ERROR; } callback.onError(errorCode); }); }; VCDataProvider.prototype.clearHistoryMessages = function (params, callback) { var conversationType = +params.conversationType; var targetId = params.targetId; try { this.addon.clearMessages(conversationType, targetId); var isSuccess = true; callback.onSuccess(isSuccess); } catch (e) { console.log(e); callback.onError(RongIMLib.ErrorCode.CLEAR_HIS_ERROR); } }; VCDataProvider.prototype.getTotalUnreadCount = function (callback, conversationTypes) { var count = 0; try { this.useConsole && console.log("getTotalUnreadCount"); if (conversationTypes) { count = this.addon.getTotalUnreadCount(conversationTypes); } else { count = this.addon.getTotalUnreadCount(); } callback.onSuccess(count); } catch (e) { callback.onError(e); } return count; }; VCDataProvider.prototype.getConversationUnreadCount = function (conversationTypes, callback) { this.useConsole && console.log("getConversationUnreadCount"); this.getTotalUnreadCount(callback, conversationTypes); }; VCDataProvider.prototype.getUnreadCount = function (conversationType, targetId, callback) { var count = 0; try { this.useConsole && console.log("getUnreadCount"); count = this.addon.getUnreadCount(conversationType, targetId); callback.onSuccess(count); } catch (e) { callback.onError(e); } return count; }; VCDataProvider.prototype.clearUnreadCount = function (conversationType, targetId, callback) { try { this.useConsole && console.log("clearUnreadCount"); var result = this.addon.clearUnreadCount(conversationType, targetId); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.clearUnreadCountByTimestamp = function (conversationType, targetId, timestamp, callback) { try { this.useConsole && console.log("clearUnreadCountByTimestamp"); var result = this.addon.clearUnreadCountByTimestamp(conversationType, targetId, timestamp); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.setConversationToTop = function (conversationType, targetId, isTop, callback) { try { this.useConsole && console.log("setConversationToTop"); this.addon.setConversationToTop(conversationType, targetId, isTop); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.setConversationHidden = function (conversationType, targetId, isHidden) { this.addon.setConversationHidden(conversationType, targetId, isHidden); }; VCDataProvider.prototype.setMessageReceivedStatus = function (messageId, receivedStatus, callback) { try { this.useConsole && console.log("setMessageReceivedStatus"); this.addon.setMessageReceivedStatus(messageId, receivedStatus); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.setMessageSentStatus = function (messageId, sentStatus, callback) { try { this.useConsole && console.log("setMessageSentStatus"); this.addon.setMessageSentStatus(messageId, sentStatus); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.getFileToken = function (fileType, callback) { this.useConsole && console.log("getFileToken"); this.addon.getUploadToken(fileType, function (token) { callback.onSuccess({ token: token }); }, function (errorCode) { callback.onError(errorCode); }); }; VCDataProvider.prototype.getFileUrl = function (fileType, fileName, oriName, callback) { this.useConsole && console.log("getFileUrl"); this.addon.getDownloadUrl(fileType, fileName, oriName, function (url) { callback.onSuccess({ downloadUrl: url }); }, function (errorCode) { callback.onError(errorCode); }); }; VCDataProvider.prototype.searchConversationByContent = function (keyword, callback, conversationTypes, customMsgTypes) { var converTypes = []; if (typeof conversationTypes == 'undefined') { converTypes = [1, 2, 3, 4, 5, 6, 7]; } else { converTypes = conversationTypes; } this.useConsole && console.log("searchConversationByContent"); var me = this; this.addon.searchConversationByContent(converTypes, keyword, customMsgTypes, function(result){ var list = JSON.parse(result).list, convers = []; var index = 0; for (var i = list.length - 1; i >=0; i--) { convers[index] = me.buildConversation(list[i].obj); index++; } callback.onSuccess(convers); }, callback.onError); }; VCDataProvider.prototype.searchMessageByContent = function (conversationType, targetId, keyword, timestamp, count, total, callback) { var me = this; try { this.useConsole && console.log("searchMessageByContent"); this.addon.searchMessageByContent(conversationType, targetId, keyword, timestamp, count, total, function (ret, matched) { var list = ret ? JSON.parse(ret).list : [], msgs = []; list.reverse(); for (var i = 0, len = list.length; i < len; i++) { msgs[i] = me.buildMessage(list[i].obj); } callback.onSuccess(msgs, matched); }); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.getChatRoomInfo = function (chatRoomId, count, order, callback) { this.useConsole && console.log("getChatRoomInfo"); this.addon.getChatroomInfo(chatRoomId, count, order, function (ret, count) { var list = ret ? JSON.parse(ret).list : [], chatRoomInfo = { userInfos: [], userTotalNums: count }; if (list.length > 0) { for (var i = 0, len = list.length; i < len; i++) { chatRoomInfo.userInfos.push(JSON.parse(list[i].obj)); } } callback.onSuccess(chatRoomInfo); }, function (errcode) { callback.onError(errcode); }); }; VCDataProvider.prototype.setChatroomHisMessageTimestamp = function (chatRoomId, timestamp) { }; VCDataProvider.prototype.getChatRoomHistoryMessages = function (chatRoomId, count, order, callback) { }; VCDataProvider.prototype.getDelaTime = function () { return this.addon.getDeltaTime(); }; VCDataProvider.prototype.getUserStatus = function (userId, callback) { var me = this; this.addon.getUserStatus(userId, function (status) { var entity = RongIMLib.RongInnerTools.convertUserStatus({ status: status, userId: '' }); callback.onSuccess(entity); }, function (code) { callback.onError(code); }); }; VCDataProvider.prototype.setUserStatus = function (status, callback) { this.addon.setUserStatus(status, function () { callback.onSuccess(true); }, function (code) { callback.onError(code); }); }; VCDataProvider.prototype.subscribeUserStatus = function (userIds, callback) { this.addon.subscribeUserStatus(userIds, function () { callback && callback.onSuccess(true); }, function (code) { callback && callback.onError(code); }); }; VCDataProvider.prototype.setUserStatusListener = function (params, callback) { var me = this; this.addon.setOnReceiveStatusListener(function (userId, status) { var entity = RongIMLib.RongInnerTools.convertUserStatus({ userId: userId, status: status }); RongIMLib.RongIMClient.userStatusObserver.notify({ key: userId, entity: entity }); }); var userIds = params.userIds || []; if (userIds.length) { RongIMLib.RongIMClient._dataAccessProvider.subscribeUserStatus(userIds); } }; VCDataProvider.prototype.getUnreadMentionedMessages = function (conversationType, targetId) { var me = this; var mentions = JSON.parse(me.addon.getUnreadMentionedMessages(conversationType, targetId)).list; for (var i = 0, len = mentions.length; i < len; i++) { var temp = JSON.parse(mentions[i].obj); temp.content = JSON.parse(temp.content); mentions[i] = temp; } return mentions; }; VCDataProvider.prototype.hasRemoteUnreadMessages = function (token, callback) { callback.onSuccess(false); }; VCDataProvider.prototype.sendRecallMessage = function (content, sendMessageCallback) { var me = this; me.addon.recallMessage("RC:RcCmd", JSON.stringify(content), content.push || "", function () { content.objectName = 'RC:RcCmd'; sendMessageCallback.onSuccess(me.buildMessage(JSON.stringify(content))); }, function (errorCode) { sendMessageCallback.onError(errorCode); }); }; VCDataProvider.prototype.updateMessage = function (message, callback) { }; VCDataProvider.prototype.updateMessages = function (conversationType, targetId, key, value, callback) { }; VCDataProvider.prototype.reconnect = function (callback) { }; VCDataProvider.prototype.sendReceiptResponse = function (conversationType, targetId, sendCallback) { }; VCDataProvider.prototype.setMessageExtra = function (messageId, value, callback) { }; VCDataProvider.prototype.addMemberToDiscussion = function (discussionId, userIdList, callback) { }; VCDataProvider.prototype.createDiscussion = function (name, userIdList, callback) { }; VCDataProvider.prototype.getDiscussion = function (discussionId, callback) { }; VCDataProvider.prototype.quitDiscussion = function (discussionId, callback) { }; VCDataProvider.prototype.removeMemberFromDiscussion = function (discussionId, userId, callback) { }; VCDataProvider.prototype.setDiscussionInviteStatus = function (discussionId, status, callback) { }; VCDataProvider.prototype.setDiscussionName = function (discussionId, name, callback) { }; VCDataProvider.prototype.setEnvironment = function (isPrivate) { this.addon.setEnvironment(isPrivate); }; VCDataProvider.prototype.addConversation = function (conversation, callback) { }; VCDataProvider.prototype.updateConversation = function (conversation) { return null; }; VCDataProvider.prototype.getConversationNotificationStatus = function (params, callback) { var conversationType = params.conversationType; var targetId = params.targetId; var notification = RongIMLib.RongIMClient._memoryStore.notification; var key = conversationType + '_' + targetId; var status = notification[key]; if (typeof status == 'number') { callback.onSuccess(status); return; } this.addon.getConversationNotificationStatus(conversationType, targetId, function (status) { notification[key] = status; callback.onSuccess(status); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.setConversationNotificationStatus = function (params, callback) { var conversationType = params.conversationType; var targetId = params.targetId; var status = params.status; var notification = RongIMLib.RongIMClient._memoryStore.notification; var key = conversationType + '_' + targetId; notification[key] = status; var notify = !!status; this.addon.setConversationNotificationStatus(conversationType, targetId, notify, function () { callback.onSuccess(status); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.getCurrentConnectionStatus = function () { return this.addon.getConnectionStatus(); }; VCDataProvider.prototype.getAgoraDynamicKey = function (engineType, channelName, callback) { var extra = ""; this.addon.getVoIPKey(engineType, channelName, extra, function (token) { callback.onSuccess(token); }, function (errorCode) { callback.onError(errorCode); }); }; VCDataProvider.prototype.getPublicServiceProfile = function (publicServiceType, publicServiceId, callback) { var profile = RongIMLib.RongIMClient._memoryStore.publicServiceMap.get(publicServiceType, publicServiceId); callback.onSuccess(profile); }; VCDataProvider.prototype.setDeviceInfo = function (device) { var id = device.id || ''; this.addon.setDeviceId(id); }; VCDataProvider.prototype.getRemotePublicServiceList = function (callback, pullMessageTime) { var publicList = []; var ret = this.addon.getAccounts(); var transformProto = function (ret) { var result = { hasFollowed: false, isGlobal: false, menu: null }; if (!ret.obj) { var error = { error: ret }; throw new Error('公众账号数据格式错误: ' + JSON.stringify(error)); } var obj = JSON.parse(ret.obj); var protoMap = { aType: 'conversationType', aId: 'publicServiceId', aName: 'introduction', aUri: 'portraitUri', follow: 'hasFollowed', isGlobal: 'isGlobal' }; for (var key in obj) { var val = obj[key]; if (key == 'aExtra') { var extra = JSON.parse(val); result["hasFollowed"] = extra.follow; result["isGlobal"] = extra.isGlobal; result["menu"] = extra.menu; } var uId = protoMap[key]; if (uId) { result[uId] = val; } } return result; }; if (ret) { ret = JSON.parse(ret); var list = ret.list; for (var i = 0, len = list.length; i < len; i++) { var item = list[i]; item = transformProto(item); publicList.push(item); } } if (publicList.length > 0) { RongIMLib.RongIMClient._memoryStore.publicServiceMap.publicServiceList.length = 0; RongIMLib.RongIMClient._memoryStore.publicServiceMap.publicServiceList = publicList; } callback.onSuccess(RongIMLib.RongIMClient._memoryStore.publicServiceMap.publicServiceList); }; VCDataProvider.prototype.buildMessage = function (result) { var message = new RongIMLib.Message(), ret = JSON.parse(result); message.conversationType = ret.conversationType; message.targetId = ret.targetId; message.messageDirection = ret.direction; message.senderUserId = ret.senderUserId; if (ret.direction == RongIMLib.MessageDirection.RECEIVE) { message.receivedStatus = ret.status; } else if (ret.direction == RongIMLib.MessageDirection.SEND) { message.sentStatus = ret.status; } message.sentTime = ret.sentTime; message.objectName = ret.objectName; var content = ret.content ? JSON.parse(ret.content) : ret.content; var messageType = typeMapping[ret.objectName] || registerMessageTypeMapping[ret.objectName]; if (content) { content.messageName = messageType; } message.content = content; message.messageId = ret.messageId; message.messageUId = ret.messageUid; message.messageType = messageType; return message; }; VCDataProvider.prototype.buildConversation = function (val) { if (val === '') { return null; } var conver = new RongIMLib.Conversation(), c = JSON.parse(val), lastestMsg = c.lastestMsg ? this.buildMessage(c.lastestMsg) : {}; conver.conversationTitle = c.title; conver.conversationType = c.conversationType; conver.draft = c.draft; conver.isTop = c.isTop; conver.isHidden = c.isHidden; lastestMsg.conversationType = c.conversationType; lastestMsg.targetId = c.targetId; conver.latestMessage = lastestMsg; conver.latestMessageId = lastestMsg.messageId; conver.latestMessage.messageType = typeMapping[lastestMsg.objectName] || registerMessageTypeMapping[lastestMsg.objectName]; conver.objectName = lastestMsg.objectName; conver.receivedStatus = RongIMLib.ReceivedStatus.READ; conver.sentTime = lastestMsg.sentTime; conver.senderUserId = lastestMsg.senderUserId; conver.sentStatus = lastestMsg.status; conver.targetId = c.targetId; conver.unreadMessageCount = c.unreadCount; conver.hasUnreadMention = c.m_hasUnreadMention; conver.matchCount = c.matchCount; var mentions = this.getUnreadMentionedMessages(c.conversationType, c.targetId); if (mentions.length > 0) { // 取最后一条 @ 消息,原因:和 web 互相兼容 var mention = mentions.pop(); conver.mentionedMsg = { uid: mention.messageUid, time: mention.sentTime, mentionedInfo: mention.content.mentionedInfo, sendUserId: mention.senderUserId }; } return conver; }; return VCDataProvider; })(); RongIMLib.VCDataProvider = VCDataProvider; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var MemeoryProvider = (function () { function MemeoryProvider() { this._memeoryStore = {}; this.prefix = "rong_"; } MemeoryProvider.prototype.setItem = function (composedKey, object) { this._memeoryStore[composedKey] = decodeURIComponent(object); }; MemeoryProvider.prototype.getItem = function (composedKey) { return this._memeoryStore[composedKey]; }; MemeoryProvider.prototype.removeItem = function (composedKey) { if (this.getItem(composedKey)) { delete this._memeoryStore[composedKey]; } }; MemeoryProvider.prototype.getItemKey = function (regStr) { var me = this, item = null, reg = new RegExp(regStr + "\\w+"); for (var key in me._memeoryStore) { var arr = key.match(reg); if (arr) { item = key; } } return item; }; MemeoryProvider.prototype.clearItem = function () { var me = this; for (var key in me._memeoryStore) { delete me._memeoryStore[key]; } }; //单位:字节 MemeoryProvider.prototype.onOutOfQuota = function () { return 4 * 1024; }; return MemeoryProvider; })(); RongIMLib.MemeoryProvider = MemeoryProvider; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var LocalStorageProvider = (function () { // static _instance: LocalStorageProvider = new LocalStorageProvider(); function LocalStorageProvider() { this.prefix = 'rong_'; this._host = ""; var d = new Date(), m = d.getMonth() + 1, date = d.getFullYear() + '/' + (m.toString().length == 1 ? '0' + m : m) + '/' + d.getDate(), nowDate = new Date(date).getTime(); for (var key in localStorage) { if (key.lastIndexOf('RECEIVED') > -1) { var recObj = JSON.parse(localStorage.getItem(key)); for (var key_1 in recObj) { nowDate - recObj[key_1].dealtime > 0 && (delete recObj[key_1]); } if (RongIMLib.RongUtil.isEmpty(recObj)) { localStorage.removeItem(key); } else { localStorage.setItem(key, JSON.stringify(recObj)); } } if (key.lastIndexOf('SENT') > -1) { var sentObj = JSON.parse(localStorage.getItem(key)); nowDate - sentObj.dealtime > 0 && (localStorage.removeItem(key)); } } } LocalStorageProvider.prototype.setItem = function (composedKey, object) { if (composedKey) { composedKey.indexOf(this.prefix) == -1 && (composedKey = this.prefix + composedKey); localStorage.setItem(composedKey, object); } }; LocalStorageProvider.prototype.getItem = function (composedKey) { if (composedKey) { composedKey.indexOf(this.prefix) == -1 && (composedKey = this.prefix + composedKey); return localStorage.getItem(composedKey ? composedKey : ""); } return ""; }; LocalStorageProvider.prototype.getItemKey = function (composedStr) { var item = ""; var _key = this.prefix + composedStr; for (var key in localStorage) { if (key.indexOf(_key) == 0) { item = key; break; } } return item; }; LocalStorageProvider.prototype.removeItem = function (composedKey) { if (composedKey) { composedKey.indexOf(this.prefix) == -1 && (composedKey = this.prefix + composedKey); localStorage.removeItem(composedKey.toString()); } }; LocalStorageProvider.prototype.clearItem = function () { var me = this; for (var key in localStorage) { if (key.indexOf(me.prefix) > -1) { me.removeItem(key); } } }; //单位:字节 LocalStorageProvider.prototype.onOutOfQuota = function () { return JSON.stringify(localStorage).length; }; return LocalStorageProvider; })(); RongIMLib.LocalStorageProvider = LocalStorageProvider; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var UserDataProvider = (function () { function UserDataProvider() { this.opersistName = 'RongIMLib'; this.keyManager = 'RongUserDataKeyManager'; this._host = ""; this.prefix = "rong_"; this.oPersist = document.createElement("div"); this.oPersist.style.display = "none"; this.oPersist.style.behavior = "url('#default#userData')"; document.body.appendChild(this.oPersist); this.oPersist.load(this.opersistName); } UserDataProvider.prototype.setItem = function (key, value) { key && key.indexOf(this.prefix) == -1 && (key = this.prefix + key); this.oPersist.setAttribute(key, value); var keyNames = this.getItem(this.keyManager); keyNames ? keyNames.indexOf(key) == -1 && (keyNames += ',' + key) : (keyNames = key); this.oPersist.setAttribute(this.prefix + this.keyManager, keyNames); this.oPersist.save(this.opersistName); }; UserDataProvider.prototype.getItem = function (key) { key && key.indexOf(this.prefix) == -1 && (key = this.prefix + key); return key ? this.oPersist.getAttribute(key) : key; }; UserDataProvider.prototype.removeItem = function (key) { key && key.indexOf(this.prefix) == -1 && (key = this.prefix + key); this.oPersist.removeAttribute(key); this.oPersist.save(this.opersistName); var keyNames = this.getItem(this.keyManager), keyNameArray = keyNames && keyNames.split(',') || []; for (var i = 0, len = keyNameArray.length; i < len; i++) { if (keyNameArray[i] == key) { keyNameArray.splice(i, 1); } } this.oPersist.setAttribute(this.prefix + this.keyManager, keyNameArray.join(',')); this.oPersist.save(this.opersistName); }; UserDataProvider.prototype.getItemKey = function (composedStr) { var item = null, keyNames = this.getItem(this.keyManager), keyNameArray = keyNames && keyNames.split(',') || [], me = this; var _key = this.prefix + composedStr; if (keyNameArray.length) { for (var i = 0, len = keyNameArray.length; i < len; i++) { if (keyNameArray[i] && keyNameArray[i].indexOf(_key) == 0) { item = keyNameArray[i]; break; } } } return item; }; UserDataProvider.prototype.clearItem = function () { var keyNames = this.getItem(this.keyManager), keyNameArray = [], me = this; keyNames && (keyNameArray = keyNames.split(',')); if (keyNameArray.length) { for (var i = 0, len = keyNameArray.length; i < len; i++) { keyNameArray[i] && me.removeItem(keyNameArray[i]); } me.removeItem(me.keyManager); } }; UserDataProvider.prototype.onOutOfQuota = function () { return 10 * 1024 * 1024; }; return UserDataProvider; })(); RongIMLib.UserDataProvider = UserDataProvider; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var FeatureDectector = (function () { function FeatureDectector(callback) { this.script = document.createElement("script"); this.head = document.getElementsByTagName("head")[0]; if ("WebSocket" in window && "ArrayBuffer" in window && WebSocket.prototype.CLOSED === 3 && !RongIMLib.RongIMClient._memoryStore.depend.isPolling) { RongIMLib.Transportations._TransportType = RongIMLib.Socket.WEBSOCKET; if (!RongIMLib.RongIMClient.Protobuf) { var url = RongIMLib.RongIMClient._memoryStore.depend.protobuf; var script = this.script; script.src = url; this.head.appendChild(script); script.onload = script.onreadystatechange = function () { var isLoaded = (!this.readState || this.readyState == 'loaded' || this.readyState == 'complete'); if (isLoaded) { // 防止 IE6、7 下偶发触发两次 loaded script.onload = script.onreadystatechange = null; if (callback) { callback(); } if (!callback) { var token = RongIMLib.RongIMClient._memoryStore.token; var connectCallback = RongIMLib.RongIMClient._memoryStore.callback; token && RongIMLib.RongIMClient.connect(token, connectCallback); } } }; } } else { RongIMLib.Transportations._TransportType = "xhr-polling"; RongIMLib.RongIMClient.Protobuf = Polling; } } return FeatureDectector; })(); RongIMLib.FeatureDectector = FeatureDectector; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var FeaturePatcher = (function () { function FeaturePatcher() { } FeaturePatcher.prototype.patchAll = function () { this.patchJSON(); this.patchForEach(); }; FeaturePatcher.prototype.patchForEach = function () { if (!Array.forEach) { Array.forEach = function (arr, func) { for (var i = 0; i < arr.length; i++) { func.call(arr, arr[i], i, arr); } }; } }; FeaturePatcher.prototype.patchJSON = function () { if (!window["JSON"]) { window["JSON"] = (function () { function JSON() { } JSON.parse = function (sJSON) { return eval('(' + sJSON + ')'); }; JSON.stringify = function (value) { return this.str("", { "": value }); }; JSON.str = function (key, holder) { var i, k, v, length, mind = "", partial, value = holder[key], me = this; if (value && typeof value === "object" && typeof value.toJSON === "function") { value = value.toJSON(key); } switch (typeof value) { case "string": return me.quote(value); case "number": return isFinite(value) ? String(value) : "null"; case "boolean": case "null": return String(value); case "object": if (!value) { return "null"; } partial = []; if (Object.prototype.toString.apply(value) === "[object Array]") { length = value.length; for (i = 0; i < length; i += 1) { partial[i] = me.str(i, value) || "null"; } v = partial.length === 0 ? "[]" : "[" + partial.join(",") + "]"; return v; } for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = me.str(k, value); if (v) { partial.push(me.quote(k) + ":" + v); } } } v = partial.length === 0 ? "{}" : "{" + partial.join(",") + "}"; return v; } }; JSON.quote = function (string) { var me = this; me.rx_escapable.lastIndex = 0; return me.rx_escapable.test(string) ? '"' + string.replace(me.rx_escapable, function (a) { var c = me.meta[a]; return typeof c === "string" ? c : "\\u" + ("0000" + a.charCodeAt(0).toString(16)).slice(-4); }) + '"' : '"' + string + '"'; }; JSON.rx_escapable = new RegExp('[\\\"\\\\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]', "g"); JSON.meta = { "\b": "\\b", " ": "\\t", "\n": "\\n", "\f": "\\f", "\r": "\\r", '"': '\\"', "''": "\\''", "\\": "\\\\" }; return JSON; })(); } }; return FeaturePatcher; })(); RongIMLib.FeaturePatcher = FeaturePatcher; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var PublicServiceMap = (function () { function PublicServiceMap() { this.publicServiceList = []; } PublicServiceMap.prototype.get = function (publicServiceType, publicServiceId) { for (var i = 0, len = this.publicServiceList.length; i < len; i++) { if (this.publicServiceList[i].conversationType == publicServiceType && publicServiceId == this.publicServiceList[i].publicServiceId) { return this.publicServiceList[i]; } } }; PublicServiceMap.prototype.add = function (publicServiceProfile) { var isAdd = true, me = this; for (var i = 0, len = this.publicServiceList.length; i < len; i++) { if (me.publicServiceList[i].conversationType == publicServiceProfile.conversationType && publicServiceProfile.publicServiceId == me.publicServiceList[i].publicServiceId) { this.publicServiceList.unshift(this.publicServiceList.splice(i, 1)[0]); isAdd = false; break; } } if (isAdd) { this.publicServiceList.unshift(publicServiceProfile); } }; PublicServiceMap.prototype.replace = function (publicServiceProfile) { var me = this; for (var i = 0, len = this.publicServiceList.length; i < len; i++) { if (me.publicServiceList[i].conversationType == publicServiceProfile.conversationType && publicServiceProfile.publicServiceId == me.publicServiceList[i].publicServiceId) { me.publicServiceList.splice(i, 1, publicServiceProfile); break; } } }; PublicServiceMap.prototype.remove = function (conversationType, publicServiceId) { var me = this; for (var i = 0, len = this.publicServiceList.length; i < len; i++) { if (me.publicServiceList[i].conversationType == conversationType && publicServiceId == me.publicServiceList[i].publicServiceId) { this.publicServiceList.splice(i, 1); break; } } }; return PublicServiceMap; })(); RongIMLib.PublicServiceMap = PublicServiceMap; /** * 会话工具类。 */ var ConversationMap = (function () { function ConversationMap() { this.conversationList = []; } ConversationMap.prototype.get = function (conversavtionType, targetId) { for (var i = 0, len = this.conversationList.length; i < len; i++) { if (this.conversationList[i].conversationType == conversavtionType && this.conversationList[i].targetId == targetId) { return this.conversationList[i]; } } return null; }; ConversationMap.prototype.add = function (conversation) { var isAdd = true; for (var i = 0, len = this.conversationList.length; i < len; i++) { if (this.conversationList[i].conversationType === conversation.conversationType && this.conversationList[i].targetId === conversation.targetId) { this.conversationList.unshift(this.conversationList.splice(i, 1)[0]); isAdd = false; break; } } if (isAdd) { this.conversationList.unshift(conversation); } }; /** * [replace 替换会话] * 会话数组存在的情况下调用add方法会是当前会话被替换且返回到第一个位置,导致用户本地一些设置失效,所以提供replace方法 */ ConversationMap.prototype.replace = function (conversation) { for (var i = 0, len = this.conversationList.length; i < len; i++) { if (this.conversationList[i].conversationType === conversation.conversationType && this.conversationList[i].targetId === conversation.targetId) { this.conversationList.splice(i, 1, conversation); break; } } }; ConversationMap.prototype.remove = function (conversation) { for (var i = 0, len = this.conversationList.length; i < len; i++) { if (this.conversationList[i].conversationType === conversation.conversationType && this.conversationList[i].targetId === conversation.targetId) { this.conversationList.splice(i, 1); break; } } }; return ConversationMap; })(); RongIMLib.ConversationMap = ConversationMap; var CheckParam = (function () { function CheckParam() { } CheckParam.getInstance = function () { if (!CheckParam._instance) { CheckParam._instance = new CheckParam(); } return CheckParam._instance; }; CheckParam.prototype.logger = function (code, funcName, msg) { RongIMLib.RongIMClient.logger({ code: code, funcName: funcName, msg: msg }); }; CheckParam.prototype.check = function (f, position, d, c) { if (RongIMLib.RongIMClient._dataAccessProvider || d) { for (var g = 0, e = c.length; g < e; g++) { if (!new RegExp(this.getType(c[g])).test(f[g])) { // throw new Error("The index of " + g + " parameter was wrong type " + this.getType(c[g]) + " [" + f[g] + "] -> position:" + position); var msg = "第" + (g + 1) + "个参数错误, 错误类型:" + this.getType(c[g]) + " [" + f[g] + "] -> 位置:" + position; this.logger("-3", position, msg); } } } else { var msg = "该参数不正确或尚未实例化RongIMClient -> 位置:" + position; this.logger("-4", position, msg); } }; CheckParam.prototype.getType = function (str) { var temp = Object.prototype.toString.call(str).toLowerCase(); return temp.slice(8, temp.length - 1); }; CheckParam.prototype.checkCookieDisable = function () { document.cookie = "checkCookie=1"; var arr = document.cookie.match(new RegExp("(^| )checkCookie=([^;]*)(;|$)")), isDisable = false; if (!arr) { isDisable = true; } document.cookie = "checkCookie=1;expires=Thu, 01-Jan-1970 00:00:01 GMT"; return isDisable; }; return CheckParam; })(); RongIMLib.CheckParam = CheckParam; var LimitableMap = (function () { function LimitableMap(limit) { this.map = {}; this.keys = []; this.limit = limit || 10; } LimitableMap.prototype.set = function (key, value) { this.map[key] = value; }; LimitableMap.prototype.get = function (key) { return this.map[key] || 0; }; LimitableMap.prototype.remove = function (key) { delete this.map[key]; }; return LimitableMap; })(); RongIMLib.LimitableMap = LimitableMap; var RongAjax = (function () { function RongAjax(options) { var me = this; me.xmlhttp = null; me.options = options; var hasCORS = typeof XMLHttpRequest !== "undefined" && "withCredentials" in new XMLHttpRequest(); if ("undefined" != typeof XMLHttpRequest && hasCORS) { me.xmlhttp = new XMLHttpRequest(); } else if ("undefined" != typeof XDomainRequest) { me.xmlhttp = new XDomainRequest(); } else { me.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } } RongAjax.prototype.send = function (callback) { var me = this; me.options.url || (me.options.url = "http://upload.qiniu.com/putb64/-1"); me.xmlhttp.onreadystatechange = function () { if (me.xmlhttp.readyState == 4) { if (me.options.type) { callback(); } else { callback(JSON.parse(me.xmlhttp.responseText.replace(/'/g, '"'))); } } }; me.xmlhttp.open("POST", me.options.url, true); me.xmlhttp.withCredentials = false; if ("setRequestHeader" in me.xmlhttp) { if (me.options.type) { me.xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=utf-8"); } else { me.xmlhttp.setRequestHeader("Content-type", "application/octet-stream"); me.xmlhttp.setRequestHeader('Authorization', "UpToken " + me.options.token); } } me.xmlhttp.send(me.options.type ? "appKey=" + me.options.appKey + "&deviceId=" + me.options.deviceId + "×tamp=" + me.options.timestamp + "&deviceInfo=" + me.options.deviceInfo + "&privateInfo=" + JSON.stringify(me.options.privateInfo) : me.options.base64); }; return RongAjax; })(); RongIMLib.RongAjax = RongAjax; var RongUtil = (function () { function RongUtil() { } RongUtil.noop = function () { }; RongUtil.isEmpty = function (obj) { var empty = true; for (var key in obj) { empty = false; break; } return empty; }; RongUtil.MD5 = function (str, key, raw) { return md5(str, key, raw); }; RongUtil.isObject = function (obj) { return Object.prototype.toString.call(obj) == '[object Object]'; }; RongUtil.isArray = function (array) { return Object.prototype.toString.call(array) == '[object Array]'; }; RongUtil.isFunction = function (fun) { return Object.prototype.toString.call(fun) == '[object Function]'; }; ; RongUtil.stringFormat = function (tmpl, vals) { for (var i = 0, len = vals.length; i < len; i++) { var val = vals[i], reg = new RegExp("\\{" + (i) + "\\}", "g"); tmpl = tmpl.replace(reg, val); } return tmpl; }; RongUtil.tplEngine = function (temp, data, regexp) { if (!(Object.prototype.toString.call(data) === "[object Array]")) { data = [data]; } var ret = []; for (var i = 0, j = data.length; i < j; i++) { ret.push(replaceAction(data[i])); } return ret.join(""); function replaceAction(object) { return temp.replace(regexp || (/{([^}]+)}/g), function (match, name) { if (match.charAt(0) == '\\') { return match.slice(1); } return (object[name] != undefined) ? object[name] : '{' + name + '}'; }); } }; ; RongUtil.forEach = function (obj, callback) { callback = callback || RongUtil.noop; var loopObj = function () { for (var key in obj) { callback(obj[key], key, obj); } }; var loopArr = function () { for (var i = 0, len = obj.length; i < len; i++) { callback(obj[i], i); } }; if (RongUtil.isObject(obj)) { loopObj(); } if (RongUtil.isArray(obj)) { loopArr(); } }; RongUtil.extend = function (source, target, callback, force) { RongUtil.forEach(source, function (val, key) { var hasProto = (key in target); if (force && hasProto) { target[key] = val; } if (!hasProto) { target[key] = val; } }); return target; }; RongUtil.createXHR = function () { var item = { XMLHttpRequest: function () { return new XMLHttpRequest(); }, XDomainRequest: function () { return new XDomainRequest(); }, ActiveXObject: function () { return new ActiveXObject('Microsoft.XMLHTTP'); } }; var isXHR = (typeof XMLHttpRequest == 'function'); var isXDR = (typeof XDomainRequest == 'function'); var key = isXHR ? 'XMLHttpRequest' : isXDR ? 'XDomainRequest' : 'ActiveXObject'; return item[key](); }; RongUtil.request = function (opts) { var url = opts.url; var success = opts.success; var error = opts.error; var method = opts.method || 'GET'; var xhr = RongUtil.createXHR(); xhr.onreadystatechange = function () { if (xhr.readyState == 4) { if (xhr.status == 200) { success(); } else { error(); } } }; xhr.open(method, url, true); xhr.send(null); }; RongUtil.formatProtoclPath = function (config) { var path = config.path; var protocol = config.protocol; var tmpl = config.tmpl || '{0}{1}'; var sub = config.sub; var flag = '://'; var index = path.indexOf(flag); var hasProtocol = (index > -1); if (hasProtocol) { index += flag.length; path = path.substring(index); } if (sub) { index = path.indexOf('/'); var hasPath = (index > -1); if (hasPath) { path = path.substr(0, index); } } return RongUtil.stringFormat(tmpl, [protocol, path]); }; ; RongUtil.supportLocalStorage = function () { var support = false; if (typeof localStorage == 'object') { try { var key = 'RC_TMP_KEY', value = 'RC_TMP_VAL'; localStorage.setItem(key, value); var localVal = localStorage.getItem(key); if (localVal == value) { support = true; } } catch (err) { console.log('localStorage is disabled.'); } } return support; }; /* //返回新引用,不破坏原始对象 rename({n: 'martin'}, {n: 'name'}); => {name: 'martin'} rename([{n: 'martin'}, {a: 18}], {n: 'name', a: 'age'}); => [{name: 'martin'}, {age: 18}] */ RongUtil.rename = function (origin, newNames) { var isObject = RongUtil.isObject(origin); if (isObject) { origin = [origin]; } origin = JSON.parse(JSON.stringify(origin)); var updateProperty = function (val, key, obj) { delete obj[key]; key = newNames[key]; obj[key] = val; }; RongUtil.forEach(origin, function (item) { RongUtil.forEach(item, function (val, key, obj) { var isRename = (key in newNames); (isRename ? updateProperty : RongUtil.noop)(val, key, obj); }); }); return isObject ? origin[0] : origin; }; RongUtil.some = function (arrs, callback) { var has = false; for (var i = 0, len = arrs.length; i < len; i++) { if (callback(arrs[i])) { has = true; break; } } return has; }; RongUtil.keys = function (obj) { var props = []; for (var key in obj) { props.push(key); } return props; }; return RongUtil; })(); RongIMLib.RongUtil = RongUtil; /* var observer = new RongObserver(); observer.watch({ key: 'key', func: function(entity){ } }); */ var RongObserver = (function () { function RongObserver() { this.watchers = {}; } RongObserver.prototype.genUId = function (key) { var time = new Date().getTime(); return [key, time].join('_'); }; RongObserver.prototype.watch = function (params) { var me = this; var key = params.key; var multiple = params.multiple; key = RongUtil.isArray(key) ? key : [key]; var func = params.func; RongUtil.forEach(key, function (k) { k = multiple ? me.genUId(k) : k; me.watchers[k] = func; }); }; RongObserver.prototype.notify = function (params) { var me = this; var key = params.key; var entity = params.entity; for (var k in me.watchers) { var isNotify = (k.indexOf(key) == 0); if (isNotify) { me.watchers[k](entity); } } }; RongObserver.prototype.remove = function () { }; return RongObserver; })(); RongIMLib.RongObserver = RongObserver; var Timer = (function () { function Timer(config) { this.timeout = 0; this.timer = null; this.timeout = config.timeout; } Timer.prototype.resume = function (callback) { this.timer = setTimeout(callback, this.timeout); }; Timer.prototype.pause = function () { clearTimeout(this.timer); }; return Timer; })(); RongIMLib.Timer = Timer; var InnerUtil = (function () { function InnerUtil() { } InnerUtil.getUId = function (token) { return md5(token).slice(8, 16); }; return InnerUtil; })(); RongIMLib.InnerUtil = InnerUtil; })(RongIMLib || (RongIMLib = {})); /* 说明: 请勿修改 header.js 和 footer.js 用途: 自动拼接暴露方式 命令: grunt release 中 concat */ return RongIMLib; }); ================================================ FILE: api-test-v2/lib/js/RongIMLib-2.3.1-revise-20200311.js ================================================ /* 切换新版 SDK 检查记录:杨川 修改红包消息命名错误 JrmfReadPacketMessage => JrmfRedPacketMessage JrmfReadPacketOpenedMessage => JrmfRedPacketOpenedMessage 缺失方法 clearData C++ 消息监听 VCDataProvider.prototype.setOnReceiveMessageListener 缺失音视频消息过滤 _voipProvider.onReceived VCDataProvider.prototype.getRemoteConversationList obj 少了空字符串判断 VCDataProvider.prototype.sendReceiptResponse 方法为空 RCE 未用到 voip 2018-3-10 修改 InviteMessage MemberModifyMessage 消息体重增加 observerUserIds 属性 导航重定向修改 setConnectionStatusListener() 抛出一些状态码 注册消息时增加搜索项 addon.registerMessageType searchProp */ /* 说明: 请勿修改 header.js 和 footer.js 用途: 自动拼接暴露方式 命令: grunt release 中 concat */ /* date: 2018-07-02 auth: yangchuan bug: Web 端消息是否计数标识不生效 update: Web 接收消息时判断消息是否需要计数 date: 2018-07-10 auth: yangchuan update: 发送消息敏感词替换,触发成功回调并返回对应 code 码 以上已合并至 SDK ------------------------------------------------------ date: 2018-10-25 auth: yuhongda feat: 消息监听增加 `是否还有离线消息` feature: 用此属性区分是否还有离线消息,待会补偿消息拉取完成后更新一次会话 date: 2018-10-26 auth: yuhongda feat: addon.getUnreadCount 支持同步获取 date: 2018-10-27 auth: yuhongda feat: 会话列表增加分页 memo: 仅 c++ 支持会话列表分页 date: 2018-12-3 auth: yuhongda feat: 增加获取公众号历史消息的信令 memo: 仅 web 端生效 Date: 2019-05-05 Author: YuHongDa 增加获取服务端会话列表接口(getRemoteConversations),此接口参会成功失败,C++ 层做数据合并,此接口仅在 Electron 中有效 date: 2019-05-08 auth: LiuYuqi update: RCE 增加管理员撤回消息修改 RecallCommandMessage 增加属性 isDelete 是否仅删除不提示撤回消息 isAdmin 是否管理员撤回 adminId 管理员 Id Date: 2019-05-30 auth: KongCong update: 1. getRemoteConversations 暂时不可用,因 c++ 协议栈接口变更 2. searchConversationByContent 新增 customMsgTypes 参数,参数为数组,直接透传给 c++ 协议栈,用于修复获取到的会话中 matchCount 匹配消息数量与 searchMessageByContent 实际获取的消息数不相等 Date: 2019-06-05 auth: kongcong update: getRemoteConversations 适配 c++ 协议栈,此方法增加 beginTime, order 参数,用于获取指定时间点开始、向前或向后的会话 beginTime: 时间戳,若值为 0,则默认使用服务系统时间戳 order: 时间方向,0 获取指定时间点以前的会话,1 获取指定时间点以后的会话 Date: 2019-07-24 auth: LiuYuqi update: 增加 clearCache 方法,解决 web 端切换用户时,获取会话列表后,返回值为上一个用户的数据 Date: 2020-03-11 auth: WangYongHao update: 1. 根据导航协议头匹配 navi、cmp 2. 文字、图片、语音、高清语音消息增加阅后即焚 burnDuration 字段 */ (function(global, factory) { if (typeof exports === 'object' && typeof module !== 'undefined') { module.exports = factory(); } else if (typeof define === 'function' && define.amd) { define(factory); } else { var tempIMLib = factory(); var tempClient = tempIMLib.RongIMClient; var isExists = (!!global.RongIMLib); if (isExists) { var currentClient = RongIMLib.RongIMClient || {}; for(var key in currentClient){ tempClient[key] = currentClient[key]; } } global.RongIMLib = tempIMLib; global.RongIMClient = tempClient; } })(this, function(){ var Polling = { SetUserStatusInput: function(){ var a = {}; this.setStatus = function(b){ a.status = b; }; this.toArrayBuffer = function(){ return a; }; }, SetUserStatusOutput: function(){ var a = {}; this.setNothing = function(b){ a.nothing = b; }; this.toArrayBuffer = function(){ return a; }; }, GetUserStatusInput: function(){ var a = {}; this.setNothing = function(b){ a.nothing = b; }; this.toArrayBuffer = function(){ return a; }; }, GetUserStatusOutput: function(){ var a = {}; this.setStatus = function(b){ a.status = b; }; this.setSubUserId = function(b){ a.subUserId = b; }; this.toArrayBuffer = function(){ return a; }; }, SubUserStatusInput: function(){ var a = {}; this.setUserid = function(b){ a.userid = b; }; this.toArrayBuffer = function(){ return a; }; }, SubUserStatusOutput: function(){ var a = {}; this.setNothing = function(b){ a.nothing = b; }; this.toArrayBuffer = function(){ return a; }; }, CleanHisMsgInput: function(){ var a = {}; this.setTargetId = function(b){ a.targetId = b; }; this.setDataTime = function(b){ a.dataTime = b; }; this.setConversationType = function(b){ a.conversationType = b; }; this.toArrayBuffer = function(){ return a; }; }, DeleteMsgInput:function(){ var a = {}; this.setType = function(b){ a.type = b; }; this.setConversationId = function(b){ a.conversationId = b; }; this.setMsgs = function(b){ a.msgs = b; }; this.toArrayBuffer = function () { return a; } }, DeleteMsg:function(){ var a = {}; this.setMsgId = function(b){ a.msgId = b; }; this.setMsgDataTime = function(b){ a.msgDataTime = b; }; this.setDirect = function(b){ a.direct = b; }; this.toArrayBuffer = function () { return a; } }, DeleteMsgOutput:function(){ var a = {}; this.setNothing = function(b){ a.nothing = b; }; this.toArrayBuffer = function () { return a; } }, SearchMpInput:function(){ var a = {}; this.setType = function (b) { a.type = b; }; this.setId = function (b) { a.id = b; }; this.toArrayBuffer = function () { return a; } }, SearchMpOutput:function(){ var a = {}; this.setNothing = function (b) { a.nothing = b; }; this.setInfo = function (b) { a.info = b; }; this.toArrayBuffer = function () { return a; } }, MpInfo:function(){ var a = {}; this.setMpid = function(b){ a.mpid = b; }; this.setName = function(b){ a.name = b; }; this.setType = function(b){ a.type = b; }; this.setTime = function(b){ a.time = b; }; this.setPortraitUri = function(b){ a.portraitUrl = b; }; this.setExtra = function(b){ a.extra = b; }; this.toArrayBuffer = function () { return a; } }, PullMpInput:function(){ var a = {}; this.setMpid = function(b){ a.mpid = b; }; this.setTime = function(b){ a.time = b; }; this.toArrayBuffer = function () { return a; }; }, PullMpOutput:function(){ var a = {}; this.setStatus = function(b){ a.status = b; } this.setInfo = function(b){ a.info = b; }; this.toArrayBuffer = function () { return a; }; }, MPFollowInput:function(){ var a = {}; this.setId = function(b){ a.id = b; }; this.toArrayBuffer = function () { return a; }; }, MPFollowOutput:function(){ var a = {}; this.setNothing = function(b){ a.nothing = b; }; this.setInfo = function(b){ a.info = b; }; this.toArrayBuffer = function () { return a; }; }, NotifyMsg: function () { var a = {}; this.setType = function (b) { a.type = b; }; this.setTime = function (b) { a.time = b; }; this.setChrmId = function(b){ a.chrmId = b; }; this.toArrayBuffer = function () { return a; }; }, SyncRequestMsg: function () { var a = {}; this.setSyncTime = function (b) { a.syncTime = b || 0; }; this.setIspolling = function (b) { a.ispolling = !!b; }; this.setIsweb = function (b) { a.isweb = !!b; }; this.setIsPullSend = function (b) { a.isPullSend = !!b; }; this.toArrayBuffer = function () { return a; }; }, UpStreamMessage: function () { var a = {}; this.setSessionId = function (b) { a.sessionId = b }; this.setClassname = function (b) { a.classname = b }; this.setContent = function (b) { if (b) a.content = b; }; this.setPushText = function (b) { a.pushText = b }; this.setUserId = function(b){ a.userId = b; }; this.setAppData = function(b){ a.appData = b; }; this.toArrayBuffer = function () { return a }; }, DownStreamMessages: function () { var a = {}; this.setList = function (b) { a.list = b }; this.setSyncTime = function (b) { a.syncTime = b; }; this.toArrayBuffer = function () { return a }; }, DownStreamMessage: function () { var a = {}; this.setFromUserId = function (b) { a.fromUserId = b }; this.setType = function (b) { a.type = b }; this.setGroupId = function (b) { a.groupId = b }; this.setClassname = function (b) { a.classname = b }; this.setContent = function (b) { if (b) a.content = b }; this.setDataTime = function (b) { a.dataTime = b; }; this.setStatus = function (b) { a.status = b; }; this.setMsgId = function (b) { a.msgId = b; }; this.toArrayBuffer = function () { return a; }; }, CreateDiscussionInput: function () { var a = {}; this.setName = function (b) { a.name = b }; this.toArrayBuffer = function () { return a } }, CreateDiscussionOutput: function () { var a = {}; this.setId = function (b) { a.id = b }; this.toArrayBuffer = function () { return a }; }, ChannelInvitationInput: function () { var a = {}; this.setUsers = function (b) { a.users = b }; this.toArrayBuffer = function () { return a }; }, LeaveChannelInput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b }; this.toArrayBuffer = function () { return a }; }, QueryChatroomInfoInput:function(){ var a = {}; this.setCount = function (b) { a.count = b; }; this.setOrder = function (b) { a.order = b; }; this.toArrayBuffer = function () { return a }; }, QueryChatroomInfoOutput:function(){ var a = {}; this.setUserTotalNums = function (b) { a.userTotalNums = b; }; this.setUserInfos = function (b) { a.userInfos = b; }; this.toArrayBuffer = function () { return a; }; }, ChannelEvictionInput: function () { var a = {}; this.setUser = function (b) { a.user = b }; this.toArrayBuffer = function () { return a }; }, RenameChannelInput: function () { var a = {}; this.setName = function (b) { a.name = b }; this.toArrayBuffer = function () { return a } }, ChannelInfoInput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b }; this.toArrayBuffer = function () { return a } }, ChannelInfoOutput: function () { var a = {}; this.setType = function (b) { a.type = b }; this.setChannelId = function (b) { a.channelId = b }; this.setChannelName = function (b) { a.channelName = b }; this.setAdminUserId = function (b) { a.adminUserId = b }; this.setFirstTenUserIds = function (b) { a.firstTenUserIds = b }; this.setOpenStatus = function (b) { a.openStatus = b }; this.toArrayBuffer = function () { return a } }, ChannelInfosInput: function () { var a = {}; this.setPage = function (b) { a.page = b }; this.setNumber = function (b) { a.number = b }; this.toArrayBuffer = function () { return a }; }, ChannelInfosOutput: function () { var a = {}; this.setChannels = function (b) { a.channels = b }; this.setTotal = function (b) { a.total = b }; this.toArrayBuffer = function () { return a }; }, MemberInfo: function () { var a = {}; this.setUserId = function (b) { a.userId = b }; this.setUserName = function (b) { a.userName = b }; this.setUserPortrait = function (b) { a.userPortrait = b }; this.setExtension = function (b) { a.extension = b }; this.toArrayBuffer = function () { return a }; }, GroupMembersInput: function () { var a = {}; this.setPage = function (b) { a.page = b }; this.setNumber = function (b) { a.number = b }; this.toArrayBuffer = function () { return a }; }, GroupMembersOutput: function () { var a = {}; this.setMembers = function (b) { a.members = b }; this.setTotal = function (b) { a.total = b }; this.toArrayBuffer = function () { return a }; }, GetUserInfoInput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b }; this.toArrayBuffer = function () { return a }; }, GetUserInfoOutput: function () { var a = {}; this.setUserId = function (b) { a.userId = b }; this.setUserName = function (b) { a.userName = b }; this.setUserPortrait = function (b) { a.userPortrait = b }; this.toArrayBuffer = function () { return a }; }, GetSessionIdInput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b }; this.toArrayBuffer = function () { return a }; }, GetSessionIdOutput: function () { var a = {}; this.setSessionId = function (b) { a.sessionId = b }; this.toArrayBuffer = function () { return a }; }, GetQNupTokenInput: function () { var a = {}; this.setType = function (b) { a.type = b; } this.toArrayBuffer = function () { return a } }, GetQNupTokenOutput: function () { var a = {}; this.setDeadline = function (b) { a.deadline = b }; this.setToken = function (b) { a.token = b; }; this.toArrayBuffer = function () { return a } }, GetQNdownloadUrlInput: function () { var a = {}; this.setType = function (b) { a.type = b; }; this.setKey = function (b) { a.key = b; }; this.setFileName = function(b){ a.fileName = b; }; this.toArrayBuffer = function () { return a } }, GetQNdownloadUrlOutput: function () { var a = {}; this.setDownloadUrl = function (b) { a.downloadUrl = b; }; this.toArrayBuffer = function () { return a } }, Add2BlackListInput: function () { var a = {}; this.setUserId = function (b) { a.userId = b; }; this.toArrayBuffer = function () { return a } }, RemoveFromBlackListInput: function () { var a = {}; this.setUserId = function (b) { a.userId = b; }; this.toArrayBuffer = function () { return a } }, QueryBlackListInput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b; }; this.toArrayBuffer = function () { return a } }, QueryBlackListOutput: function () { var a = {}; this.setUserIds = function (b) { a.userIds = b; }; this.toArrayBuffer = function () { return a } }, BlackListStatusInput: function () { var a = {}; this.setUserId = function (b) { a.userId = b; }; this.toArrayBuffer = function () { return a } }, BlockPushInput: function () { var a = {}; this.setBlockeeId = function (b) { a.blockeeId = b; }; this.toArrayBuffer = function () { return a } }, ModifyPermissionInput: function () { var a = {}; this.setOpenStatus = function (b) { a.openStatus = b; }; this.toArrayBuffer = function () { return a }; }, GroupInput: function () { var a = {}; this.setGroupInfo = function (b) { for (var i = 0, arr = []; i < b.length; i++) { arr.push({id: b[i].getContent().id, name: b[i].getContent().name}) } a.groupInfo = arr; }; this.toArrayBuffer = function () { return a }; }, GroupOutput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b; }; this.toArrayBuffer = function () { return a }; }, GroupInfo: function () { var a = {}; this.setId = function (b) { a.id = b; }; this.setName = function (b) { a.name = b; }; this.getContent = function () { return a; }; this.toArrayBuffer = function () { return a }; }, GroupHashInput: function () { var a = {}; this.setUserId = function (b) { a.userId = b; }; this.setGroupHashCode = function (b) { a.groupHashCode = b; }; this.toArrayBuffer = function () { return a }; }, GroupHashOutput: function () { var a = {}; this.setResult = function (b) { a.result = b; }; this.toArrayBuffer = function () { return a }; }, ChrmInput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b; }; this.toArrayBuffer = function () { return a }; }, ChrmOutput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b; }; this.toArrayBuffer = function () { return a }; }, ChrmPullMsg: function () { var a = {}; this.setSyncTime = function (b) { a.syncTime = b }; this.setCount = function (b) { a.count = b; }; this.toArrayBuffer = function () { return a }; }, RelationsInput: function () { var a = {}; this.setType = function (b) { a.type = b; }; this.setMsg = function(b){ a.msg = b; }; this.setCount = function(b){ a.count = b; }; this.toArrayBuffer = function () { return a }; }, RelationsOutput: function () { var a = {}; this.setInfo = function (b) { a.info = b; }; this.toArrayBuffer = function () { return a } }, RelationInfo: function () { var a = {}; this.setType = function (b) { a.type = b; }; this.setUserId = function (b) { a.userId = b; }; this.setMsg = function(b){ a.msg = b; }; this.toArrayBuffer = function () { return a } }, HistoryMessageInput: function () { var a={}; this.setTargetId=function(b){ a.targetId=b; }; this.setDataTime=function(b){ a.dataTime=b; }; this.setSize=function(b){ a.size=b; }; this.toArrayBuffer = function () { return a } }, HistoryMessagesOuput: function () { var a={}; this.setList=function(b){ a.list=b; }; this.setSyncTime=function(b){ a.syncTime=b; }; this.setHasMsg=function(b){ a.hasMsg=b; }; this.toArrayBuffer = function () { return a } }, HistoryMsgInput: function(){ var a = {}; this.setTargetId = function(b){ a.targetId = b; }; this.setTime = function(b){ a.time = b; }; this.setCount = function(b){ a.count = b; }; this.setOrder = function(b){ a.order = b; }; this.toArrayBuffer = function(){ return a; }; }, HistoryMsgOuput: function(){ var a = {}; this.setList = function(b){ a.list = b; }; this.setSyncTime = function(b){ a.syncTime = b; }; this.setHasMsg = function(b){ a.hasMsg = b; }; this.toArrayBuffer = function(){ return a; }; } }; for (var f in Polling) { Polling[f].decode = function (b) { var back = {}, val = JSON.parse(b) || eval("(" + b + ")"); for (var i in val) { back[i]=val[i]; back["get"+ i.charAt(0).toUpperCase()+i.slice(1)]=function(){ return val[i]; } } return back; } } /* * JavaScript MD5 * https://github.com/blueimp/JavaScript-MD5 * * Copyright 2011, Sebastian Tschan * https://blueimp.net * * Licensed under the MIT license: * http://www.opensource.org/licenses/MIT * * Based on * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message * Digest Algorithm, as defined in RFC 1321. * Version 2.2 Copyright (C) Paul Johnston 1999 - 2009 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet * Distributed under the BSD License * See http://pajhome.org.uk/crypt/md5 for more info. */ /*jslint bitwise: true */ /*global unescape, define, module */ var md5 = (function () { 'use strict'; /* * Add integers, wrapping at 2^32. This uses 16-bit operations internally * to work around bugs in some JS interpreters. */ function safe_add(x, y) { var lsw = (x & 0xFFFF) + (y & 0xFFFF), msw = (x >> 16) + (y >> 16) + (lsw >> 16); return (msw << 16) | (lsw & 0xFFFF); } /* * Bitwise rotate a 32-bit number to the left. */ function bit_rol(num, cnt) { return (num << cnt) | (num >>> (32 - cnt)); } /* * These functions implement the four basic operations the algorithm uses. */ function md5_cmn(q, a, b, x, s, t) { return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s), b); } function md5_ff(a, b, c, d, x, s, t) { return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t); } function md5_gg(a, b, c, d, x, s, t) { return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t); } function md5_hh(a, b, c, d, x, s, t) { return md5_cmn(b ^ c ^ d, a, b, x, s, t); } function md5_ii(a, b, c, d, x, s, t) { return md5_cmn(c ^ (b | (~d)), a, b, x, s, t); } /* * Calculate the MD5 of an array of little-endian words, and a bit length. */ function binl_md5(x, len) { /* append padding */ x[len >> 5] |= 0x80 << (len % 32); x[(((len + 64) >>> 9) << 4) + 14] = len; var i, olda, oldb, oldc, oldd, a = 1732584193, b = -271733879, c = -1732584194, d = 271733878; for (i = 0; i < x.length; i += 16) { olda = a; oldb = b; oldc = c; oldd = d; a = md5_ff(a, b, c, d, x[i], 7, -680876936); d = md5_ff(d, a, b, c, x[i + 1], 12, -389564586); c = md5_ff(c, d, a, b, x[i + 2], 17, 606105819); b = md5_ff(b, c, d, a, x[i + 3], 22, -1044525330); a = md5_ff(a, b, c, d, x[i + 4], 7, -176418897); d = md5_ff(d, a, b, c, x[i + 5], 12, 1200080426); c = md5_ff(c, d, a, b, x[i + 6], 17, -1473231341); b = md5_ff(b, c, d, a, x[i + 7], 22, -45705983); a = md5_ff(a, b, c, d, x[i + 8], 7, 1770035416); d = md5_ff(d, a, b, c, x[i + 9], 12, -1958414417); c = md5_ff(c, d, a, b, x[i + 10], 17, -42063); b = md5_ff(b, c, d, a, x[i + 11], 22, -1990404162); a = md5_ff(a, b, c, d, x[i + 12], 7, 1804603682); d = md5_ff(d, a, b, c, x[i + 13], 12, -40341101); c = md5_ff(c, d, a, b, x[i + 14], 17, -1502002290); b = md5_ff(b, c, d, a, x[i + 15], 22, 1236535329); a = md5_gg(a, b, c, d, x[i + 1], 5, -165796510); d = md5_gg(d, a, b, c, x[i + 6], 9, -1069501632); c = md5_gg(c, d, a, b, x[i + 11], 14, 643717713); b = md5_gg(b, c, d, a, x[i], 20, -373897302); a = md5_gg(a, b, c, d, x[i + 5], 5, -701558691); d = md5_gg(d, a, b, c, x[i + 10], 9, 38016083); c = md5_gg(c, d, a, b, x[i + 15], 14, -660478335); b = md5_gg(b, c, d, a, x[i + 4], 20, -405537848); a = md5_gg(a, b, c, d, x[i + 9], 5, 568446438); d = md5_gg(d, a, b, c, x[i + 14], 9, -1019803690); c = md5_gg(c, d, a, b, x[i + 3], 14, -187363961); b = md5_gg(b, c, d, a, x[i + 8], 20, 1163531501); a = md5_gg(a, b, c, d, x[i + 13], 5, -1444681467); d = md5_gg(d, a, b, c, x[i + 2], 9, -51403784); c = md5_gg(c, d, a, b, x[i + 7], 14, 1735328473); b = md5_gg(b, c, d, a, x[i + 12], 20, -1926607734); a = md5_hh(a, b, c, d, x[i + 5], 4, -378558); d = md5_hh(d, a, b, c, x[i + 8], 11, -2022574463); c = md5_hh(c, d, a, b, x[i + 11], 16, 1839030562); b = md5_hh(b, c, d, a, x[i + 14], 23, -35309556); a = md5_hh(a, b, c, d, x[i + 1], 4, -1530992060); d = md5_hh(d, a, b, c, x[i + 4], 11, 1272893353); c = md5_hh(c, d, a, b, x[i + 7], 16, -155497632); b = md5_hh(b, c, d, a, x[i + 10], 23, -1094730640); a = md5_hh(a, b, c, d, x[i + 13], 4, 681279174); d = md5_hh(d, a, b, c, x[i], 11, -358537222); c = md5_hh(c, d, a, b, x[i + 3], 16, -722521979); b = md5_hh(b, c, d, a, x[i + 6], 23, 76029189); a = md5_hh(a, b, c, d, x[i + 9], 4, -640364487); d = md5_hh(d, a, b, c, x[i + 12], 11, -421815835); c = md5_hh(c, d, a, b, x[i + 15], 16, 530742520); b = md5_hh(b, c, d, a, x[i + 2], 23, -995338651); a = md5_ii(a, b, c, d, x[i], 6, -198630844); d = md5_ii(d, a, b, c, x[i + 7], 10, 1126891415); c = md5_ii(c, d, a, b, x[i + 14], 15, -1416354905); b = md5_ii(b, c, d, a, x[i + 5], 21, -57434055); a = md5_ii(a, b, c, d, x[i + 12], 6, 1700485571); d = md5_ii(d, a, b, c, x[i + 3], 10, -1894986606); c = md5_ii(c, d, a, b, x[i + 10], 15, -1051523); b = md5_ii(b, c, d, a, x[i + 1], 21, -2054922799); a = md5_ii(a, b, c, d, x[i + 8], 6, 1873313359); d = md5_ii(d, a, b, c, x[i + 15], 10, -30611744); c = md5_ii(c, d, a, b, x[i + 6], 15, -1560198380); b = md5_ii(b, c, d, a, x[i + 13], 21, 1309151649); a = md5_ii(a, b, c, d, x[i + 4], 6, -145523070); d = md5_ii(d, a, b, c, x[i + 11], 10, -1120210379); c = md5_ii(c, d, a, b, x[i + 2], 15, 718787259); b = md5_ii(b, c, d, a, x[i + 9], 21, -343485551); a = safe_add(a, olda); b = safe_add(b, oldb); c = safe_add(c, oldc); d = safe_add(d, oldd); } return [a, b, c, d]; } /* * Convert an array of little-endian words to a string */ function binl2rstr(input) { var i, output = ''; for (i = 0; i < input.length * 32; i += 8) { output += String.fromCharCode((input[i >> 5] >>> (i % 32)) & 0xFF); } return output; } /* * Convert a raw string to an array of little-endian words * Characters >255 have their high-byte silently ignored. */ function rstr2binl(input) { var i, output = []; output[(input.length >> 2) - 1] = undefined; for (i = 0; i < output.length; i += 1) { output[i] = 0; } for (i = 0; i < input.length * 8; i += 8) { output[i >> 5] |= (input.charCodeAt(i / 8) & 0xFF) << (i % 32); } return output; } /* * Calculate the MD5 of a raw string */ function rstr_md5(s) { return binl2rstr(binl_md5(rstr2binl(s), s.length * 8)); } /* * Calculate the HMAC-MD5, of a key and some data (raw strings) */ function rstr_hmac_md5(key, data) { var i, bkey = rstr2binl(key), ipad = [], opad = [], hash; ipad[15] = opad[15] = undefined; if (bkey.length > 16) { bkey = binl_md5(bkey, key.length * 8); } for (i = 0; i < 16; i += 1) { ipad[i] = bkey[i] ^ 0x36363636; opad[i] = bkey[i] ^ 0x5C5C5C5C; } hash = binl_md5(ipad.concat(rstr2binl(data)), 512 + data.length * 8); return binl2rstr(binl_md5(opad.concat(hash), 512 + 128)); } /* * Convert a raw string to a hex string */ function rstr2hex(input) { var hex_tab = '0123456789abcdef', output = '', x, i; for (i = 0; i < input.length; i += 1) { x = input.charCodeAt(i); output += hex_tab.charAt((x >>> 4) & 0x0F) + hex_tab.charAt(x & 0x0F); } return output; } /* * Encode a string as utf-8 */ function str2rstr_utf8(input) { return unescape(encodeURIComponent(input)); } /* * Take string arguments and return either raw or hex encoded strings */ function raw_md5(s) { return rstr_md5(str2rstr_utf8(s)); } function hex_md5(s) { return rstr2hex(raw_md5(s)); } function raw_hmac_md5(k, d) { return rstr_hmac_md5(str2rstr_utf8(k), str2rstr_utf8(d)); } function hex_hmac_md5(k, d) { return rstr2hex(raw_hmac_md5(k, d)); } function md5(string, key, raw) { if (!key) { if (!raw) { return hex_md5(string); } return raw_md5(string); } if (!raw) { return hex_hmac_md5(key, string); } return raw_hmac_md5(key, string); } return md5; }()); var RongIMLib; (function (RongIMLib) { (function (MentionedType) { MentionedType[MentionedType["ALL"] = 1] = "ALL"; MentionedType[MentionedType["PART"] = 2] = "PART"; })(RongIMLib.MentionedType || (RongIMLib.MentionedType = {})); var MentionedType = RongIMLib.MentionedType; (function (MethodType) { MethodType[MethodType["CUSTOMER_SERVICE"] = 1] = "CUSTOMER_SERVICE"; MethodType[MethodType["RECALL"] = 2] = "RECALL"; })(RongIMLib.MethodType || (RongIMLib.MethodType = {})); var MethodType = RongIMLib.MethodType; (function (BlacklistStatus) { /** * 在黑名单中。 */ BlacklistStatus[BlacklistStatus["IN_BLACK_LIST"] = 0] = "IN_BLACK_LIST"; /** * 不在黑名单中。 */ BlacklistStatus[BlacklistStatus["NOT_IN_BLACK_LIST"] = 1] = "NOT_IN_BLACK_LIST"; })(RongIMLib.BlacklistStatus || (RongIMLib.BlacklistStatus = {})); var BlacklistStatus = RongIMLib.BlacklistStatus; (function (ConnectionChannel) { ConnectionChannel[ConnectionChannel["XHR_POLLING"] = 0] = "XHR_POLLING"; ConnectionChannel[ConnectionChannel["WEBSOCKET"] = 1] = "WEBSOCKET"; //外部调用 ConnectionChannel[ConnectionChannel["HTTP"] = 0] = "HTTP"; //外部调用 ConnectionChannel[ConnectionChannel["HTTPS"] = 1] = "HTTPS"; })(RongIMLib.ConnectionChannel || (RongIMLib.ConnectionChannel = {})); var ConnectionChannel = RongIMLib.ConnectionChannel; (function (CustomerType) { CustomerType[CustomerType["ONLY_ROBOT"] = 1] = "ONLY_ROBOT"; CustomerType[CustomerType["ONLY_HUMAN"] = 2] = "ONLY_HUMAN"; CustomerType[CustomerType["ROBOT_FIRST"] = 3] = "ROBOT_FIRST"; CustomerType[CustomerType["HUMAN_FIRST"] = 4] = "HUMAN_FIRST"; })(RongIMLib.CustomerType || (RongIMLib.CustomerType = {})); var CustomerType = RongIMLib.CustomerType; (function (GetChatRoomType) { GetChatRoomType[GetChatRoomType["NONE"] = 0] = "NONE"; GetChatRoomType[GetChatRoomType["SQQUENCE"] = 1] = "SQQUENCE"; GetChatRoomType[GetChatRoomType["REVERSE"] = 2] = "REVERSE"; })(RongIMLib.GetChatRoomType || (RongIMLib.GetChatRoomType = {})); var GetChatRoomType = RongIMLib.GetChatRoomType; (function (ConnectionStatus) { /** * 连接成功。 */ ConnectionStatus[ConnectionStatus["CONNECTED"] = 0] = "CONNECTED"; /** * 连接中。 */ ConnectionStatus[ConnectionStatus["CONNECTING"] = 1] = "CONNECTING"; /** * 断开连接。 */ ConnectionStatus[ConnectionStatus["DISCONNECTED"] = 2] = "DISCONNECTED"; /** * 用户账户在其他设备登录,本机会被踢掉线。 */ ConnectionStatus[ConnectionStatus["KICKED_OFFLINE_BY_OTHER_CLIENT"] = 6] = "KICKED_OFFLINE_BY_OTHER_CLIENT"; /** * 网络不可用。 */ ConnectionStatus[ConnectionStatus["NETWORK_UNAVAILABLE"] = 3] = "NETWORK_UNAVAILABLE"; /** * 域名错误 */ ConnectionStatus[ConnectionStatus["DOMAIN_INCORRECT"] = 12] = "DOMAIN_INCORRECT"; /** * 连接关闭。 */ ConnectionStatus[ConnectionStatus["CONNECTION_CLOSED"] = 4] = "CONNECTION_CLOSED"; /* 互踢次数过多(count > 5),此时可能出现:在其它他设备登陆有 reconnect 逻辑 */ ConnectionStatus[ConnectionStatus["ULTRALIMIT"] = 1101] = "ULTRALIMIT"; })(RongIMLib.ConnectionStatus || (RongIMLib.ConnectionStatus = {})); var ConnectionStatus = RongIMLib.ConnectionStatus; (function (ConversationNotificationStatus) { /** * 免打扰状态,关闭对应会话的通知提醒。 */ ConversationNotificationStatus[ConversationNotificationStatus["DO_NOT_DISTURB"] = 0] = "DO_NOT_DISTURB"; /** * 提醒。 */ ConversationNotificationStatus[ConversationNotificationStatus["NOTIFY"] = 1] = "NOTIFY"; })(RongIMLib.ConversationNotificationStatus || (RongIMLib.ConversationNotificationStatus = {})); var ConversationNotificationStatus = RongIMLib.ConversationNotificationStatus; (function (ConversationType) { ConversationType[ConversationType["NONE"] = 0] = "NONE"; ConversationType[ConversationType["PRIVATE"] = 1] = "PRIVATE"; ConversationType[ConversationType["DISCUSSION"] = 2] = "DISCUSSION"; ConversationType[ConversationType["GROUP"] = 3] = "GROUP"; ConversationType[ConversationType["CHATROOM"] = 4] = "CHATROOM"; ConversationType[ConversationType["CUSTOMER_SERVICE"] = 5] = "CUSTOMER_SERVICE"; ConversationType[ConversationType["SYSTEM"] = 6] = "SYSTEM"; //默认关注 MC ConversationType[ConversationType["APP_PUBLIC_SERVICE"] = 7] = "APP_PUBLIC_SERVICE"; //手工关注 MP ConversationType[ConversationType["PUBLIC_SERVICE"] = 8] = "PUBLIC_SERVICE"; })(RongIMLib.ConversationType || (RongIMLib.ConversationType = {})); var ConversationType = RongIMLib.ConversationType; (function (DiscussionInviteStatus) { /** * 开放邀请。 */ DiscussionInviteStatus[DiscussionInviteStatus["OPENED"] = 0] = "OPENED"; /** * 关闭邀请。 */ DiscussionInviteStatus[DiscussionInviteStatus["CLOSED"] = 1] = "CLOSED"; })(RongIMLib.DiscussionInviteStatus || (RongIMLib.DiscussionInviteStatus = {})); var DiscussionInviteStatus = RongIMLib.DiscussionInviteStatus; (function (ErrorCode) { ErrorCode[ErrorCode["RECALL_MESSAGE"] = 25101] = "RECALL_MESSAGE"; /** * 发送频率过快 */ ErrorCode[ErrorCode["SEND_FREQUENCY_TOO_FAST"] = 20604] = "SEND_FREQUENCY_TOO_FAST"; ErrorCode[ErrorCode["RC_MSG_UNAUTHORIZED"] = 20406] = "RC_MSG_UNAUTHORIZED"; /** * 群组 Id 无效 */ ErrorCode[ErrorCode["RC_DISCUSSION_GROUP_ID_INVALID"] = 20407] = "RC_DISCUSSION_GROUP_ID_INVALID"; /** * 群组被禁言 */ ErrorCode[ErrorCode["FORBIDDEN_IN_GROUP"] = 22408] = "FORBIDDEN_IN_GROUP"; /** * 不在讨论组。 */ ErrorCode[ErrorCode["NOT_IN_DISCUSSION"] = 21406] = "NOT_IN_DISCUSSION"; /** * 不在群组。 */ ErrorCode[ErrorCode["NOT_IN_GROUP"] = 22406] = "NOT_IN_GROUP"; /** * 不在聊天室。 */ ErrorCode[ErrorCode["NOT_IN_CHATROOM"] = 23406] = "NOT_IN_CHATROOM"; /** *聊天室被禁言 */ ErrorCode[ErrorCode["FORBIDDEN_IN_CHATROOM"] = 23408] = "FORBIDDEN_IN_CHATROOM"; /** * 聊天室中成员被踢出 */ ErrorCode[ErrorCode["RC_CHATROOM_USER_KICKED"] = 23409] = "RC_CHATROOM_USER_KICKED"; /** * 聊天室不存在 */ ErrorCode[ErrorCode["RC_CHATROOM_NOT_EXIST"] = 23410] = "RC_CHATROOM_NOT_EXIST"; /** * 聊天室成员已满 */ ErrorCode[ErrorCode["RC_CHATROOM_IS_FULL"] = 23411] = "RC_CHATROOM_IS_FULL"; /** * 获取聊天室信息参数无效 */ ErrorCode[ErrorCode["RC_CHATROOM_PATAMETER_INVALID"] = 23412] = "RC_CHATROOM_PATAMETER_INVALID"; /** * 聊天室异常 */ ErrorCode[ErrorCode["CHATROOM_GET_HISTORYMSG_ERROR"] = 23413] = "CHATROOM_GET_HISTORYMSG_ERROR"; /** * 没有打开聊天室消息存储 */ ErrorCode[ErrorCode["CHATROOM_NOT_OPEN_HISTORYMSG_STORE"] = 23414] = "CHATROOM_NOT_OPEN_HISTORYMSG_STORE"; ErrorCode[ErrorCode["TIMEOUT"] = -1] = "TIMEOUT"; /** * 未知原因失败。 */ ErrorCode[ErrorCode["UNKNOWN"] = -2] = "UNKNOWN"; /** * 加入讨论失败 */ ErrorCode[ErrorCode["JOIN_IN_DISCUSSION"] = 21407] = "JOIN_IN_DISCUSSION"; /** * 创建讨论组失败 */ ErrorCode[ErrorCode["CREATE_DISCUSSION"] = 21408] = "CREATE_DISCUSSION"; /** * 设置讨论组邀请状态失败 */ ErrorCode[ErrorCode["INVITE_DICUSSION"] = 21409] = "INVITE_DICUSSION"; /** *获取用户失败 */ ErrorCode[ErrorCode["GET_USERINFO_ERROR"] = 23407] = "GET_USERINFO_ERROR"; /** * 在黑名单中。 */ ErrorCode[ErrorCode["REJECTED_BY_BLACKLIST"] = 405] = "REJECTED_BY_BLACKLIST"; /** * 通信过程中,当前 Socket 不存在。 */ ErrorCode[ErrorCode["RC_NET_CHANNEL_INVALID"] = 30001] = "RC_NET_CHANNEL_INVALID"; /** * Socket 连接不可用。 */ ErrorCode[ErrorCode["RC_NET_UNAVAILABLE"] = 30002] = "RC_NET_UNAVAILABLE"; /** * 通信超时。 */ ErrorCode[ErrorCode["RC_MSG_RESP_TIMEOUT"] = 30003] = "RC_MSG_RESP_TIMEOUT"; /** * 导航操作时,Http 请求失败。 */ ErrorCode[ErrorCode["RC_HTTP_SEND_FAIL"] = 30004] = "RC_HTTP_SEND_FAIL"; /** * HTTP 请求失败。 */ ErrorCode[ErrorCode["RC_HTTP_REQ_TIMEOUT"] = 30005] = "RC_HTTP_REQ_TIMEOUT"; /** * HTTP 接收失败。 */ ErrorCode[ErrorCode["RC_HTTP_RECV_FAIL"] = 30006] = "RC_HTTP_RECV_FAIL"; /** * 导航操作的 HTTP 请求,返回不是200。 */ ErrorCode[ErrorCode["RC_NAVI_RESOURCE_ERROR"] = 30007] = "RC_NAVI_RESOURCE_ERROR"; /** * 导航数据解析后,其中不存在有效数据。 */ ErrorCode[ErrorCode["RC_NODE_NOT_FOUND"] = 30008] = "RC_NODE_NOT_FOUND"; /** * 导航数据解析后,其中不存在有效 IP 地址。 */ ErrorCode[ErrorCode["RC_DOMAIN_NOT_RESOLVE"] = 30009] = "RC_DOMAIN_NOT_RESOLVE"; /** * 创建 Socket 失败。 */ ErrorCode[ErrorCode["RC_SOCKET_NOT_CREATED"] = 30010] = "RC_SOCKET_NOT_CREATED"; /** * Socket 被断开。 */ ErrorCode[ErrorCode["RC_SOCKET_DISCONNECTED"] = 30011] = "RC_SOCKET_DISCONNECTED"; /** * PING 操作失败。 */ ErrorCode[ErrorCode["RC_PING_SEND_FAIL"] = 30012] = "RC_PING_SEND_FAIL"; /** * PING 超时。 */ ErrorCode[ErrorCode["RC_PONG_RECV_FAIL"] = 30013] = "RC_PONG_RECV_FAIL"; /** * 消息发送失败。 */ ErrorCode[ErrorCode["RC_MSG_SEND_FAIL"] = 30014] = "RC_MSG_SEND_FAIL"; /** * 做 connect 连接时,收到的 ACK 超时。 */ ErrorCode[ErrorCode["RC_CONN_ACK_TIMEOUT"] = 31000] = "RC_CONN_ACK_TIMEOUT"; /** * 参数错误。 */ ErrorCode[ErrorCode["RC_CONN_PROTO_VERSION_ERROR"] = 31001] = "RC_CONN_PROTO_VERSION_ERROR"; /** * 参数错误,App Id 错误。 */ ErrorCode[ErrorCode["RC_CONN_ID_REJECT"] = 31002] = "RC_CONN_ID_REJECT"; /** * 服务器不可用。 */ ErrorCode[ErrorCode["RC_CONN_SERVER_UNAVAILABLE"] = 31003] = "RC_CONN_SERVER_UNAVAILABLE"; /** * Token 错误。 */ ErrorCode[ErrorCode["RC_CONN_USER_OR_PASSWD_ERROR"] = 31004] = "RC_CONN_USER_OR_PASSWD_ERROR"; /** * App Id 与 Token 不匹配。 */ ErrorCode[ErrorCode["RC_CONN_NOT_AUTHRORIZED"] = 31005] = "RC_CONN_NOT_AUTHRORIZED"; /** * 重定向,地址错误。 */ ErrorCode[ErrorCode["RC_CONN_REDIRECTED"] = 31006] = "RC_CONN_REDIRECTED"; /** * NAME 与后台注册信息不一致。 */ ErrorCode[ErrorCode["RC_CONN_PACKAGE_NAME_INVALID"] = 31007] = "RC_CONN_PACKAGE_NAME_INVALID"; /** * APP 被屏蔽、删除或不存在。 */ ErrorCode[ErrorCode["RC_CONN_APP_BLOCKED_OR_DELETED"] = 31008] = "RC_CONN_APP_BLOCKED_OR_DELETED"; /** * 用户被屏蔽。 */ ErrorCode[ErrorCode["RC_CONN_USER_BLOCKED"] = 31009] = "RC_CONN_USER_BLOCKED"; /** * Disconnect,由服务器返回,比如用户互踢。 */ ErrorCode[ErrorCode["RC_DISCONN_KICK"] = 31010] = "RC_DISCONN_KICK"; /** * Disconnect,由服务器返回,比如用户互踢。 */ ErrorCode[ErrorCode["RC_DISCONN_EXCEPTION"] = 31011] = "RC_DISCONN_EXCEPTION"; /** * 协议层内部错误。query,上传下载过程中数据错误。 */ ErrorCode[ErrorCode["RC_QUERY_ACK_NO_DATA"] = 32001] = "RC_QUERY_ACK_NO_DATA"; /** * 协议层内部错误。 */ ErrorCode[ErrorCode["RC_MSG_DATA_INCOMPLETE"] = 32002] = "RC_MSG_DATA_INCOMPLETE"; /** * 未调用 init 初始化函数。 */ ErrorCode[ErrorCode["BIZ_ERROR_CLIENT_NOT_INIT"] = 33001] = "BIZ_ERROR_CLIENT_NOT_INIT"; /** * 数据库初始化失败。 */ ErrorCode[ErrorCode["BIZ_ERROR_DATABASE_ERROR"] = 33002] = "BIZ_ERROR_DATABASE_ERROR"; /** * 传入参数无效。 */ ErrorCode[ErrorCode["BIZ_ERROR_INVALID_PARAMETER"] = 33003] = "BIZ_ERROR_INVALID_PARAMETER"; /** * 通道无效。 */ ErrorCode[ErrorCode["BIZ_ERROR_NO_CHANNEL"] = 33004] = "BIZ_ERROR_NO_CHANNEL"; /** * 重新连接成功。 */ ErrorCode[ErrorCode["BIZ_ERROR_RECONNECT_SUCCESS"] = 33005] = "BIZ_ERROR_RECONNECT_SUCCESS"; /** * 连接中,再调用 connect 被拒绝。 */ ErrorCode[ErrorCode["BIZ_ERROR_CONNECTING"] = 33006] = "BIZ_ERROR_CONNECTING"; /** * 消息漫游服务未开通 */ ErrorCode[ErrorCode["MSG_ROAMING_SERVICE_UNAVAILABLE"] = 33007] = "MSG_ROAMING_SERVICE_UNAVAILABLE"; ErrorCode[ErrorCode["MSG_INSERT_ERROR"] = 33008] = "MSG_INSERT_ERROR"; ErrorCode[ErrorCode["MSG_DEL_ERROR"] = 33009] = "MSG_DEL_ERROR"; /** * 删除会话失败 */ ErrorCode[ErrorCode["CONVER_REMOVE_ERROR"] = 34001] = "CONVER_REMOVE_ERROR"; /** *拉取历史消息 */ ErrorCode[ErrorCode["CONVER_GETLIST_ERROR"] = 34002] = "CONVER_GETLIST_ERROR"; /** * 会话指定异常 */ ErrorCode[ErrorCode["CONVER_SETOP_ERROR"] = 34003] = "CONVER_SETOP_ERROR"; /** * 获取会话未读消息总数失败 */ ErrorCode[ErrorCode["CONVER_TOTAL_UNREAD_ERROR"] = 34004] = "CONVER_TOTAL_UNREAD_ERROR"; /** * 获取指定会话类型未读消息数异常 */ ErrorCode[ErrorCode["CONVER_TYPE_UNREAD_ERROR"] = 34005] = "CONVER_TYPE_UNREAD_ERROR"; /** * 获取指定用户ID&会话类型未读消息数异常 */ ErrorCode[ErrorCode["CONVER_ID_TYPE_UNREAD_ERROR"] = 34006] = "CONVER_ID_TYPE_UNREAD_ERROR"; ErrorCode[ErrorCode["CONVER_CLEAR_ERROR"] = 34007] = "CONVER_CLEAR_ERROR"; ErrorCode[ErrorCode["CLEAR_HIS_ERROR"] = 34010] = "CLEAR_HIS_ERROR"; ErrorCode[ErrorCode["CLEAR_HIS_TYPE_ERROR"] = 34008] = "CLEAR_HIS_TYPE_ERROR"; ErrorCode[ErrorCode["CLEAR_HIS_TIME_ERROR"] = 34011] = "CLEAR_HIS_TIME_ERROR"; /* */ ErrorCode[ErrorCode["CONVER_GET_ERROR"] = 34009] = "CONVER_GET_ERROR"; //群组异常信息 /** * */ ErrorCode[ErrorCode["GROUP_SYNC_ERROR"] = 35001] = "GROUP_SYNC_ERROR"; /** * 匹配群信息异常 */ ErrorCode[ErrorCode["GROUP_MATCH_ERROR"] = 35002] = "GROUP_MATCH_ERROR"; //聊天室异常 /** * 加入聊天室Id为空 */ ErrorCode[ErrorCode["CHATROOM_ID_ISNULL"] = 36001] = "CHATROOM_ID_ISNULL"; /** * 加入聊天室失败 */ ErrorCode[ErrorCode["CHARTOOM_JOIN_ERROR"] = 36002] = "CHARTOOM_JOIN_ERROR"; /** * 拉取聊天室历史消息失败 */ ErrorCode[ErrorCode["CHATROOM_HISMESSAGE_ERROR"] = 36003] = "CHATROOM_HISMESSAGE_ERROR"; //黑名单异常 /** * 加入黑名单异常 */ ErrorCode[ErrorCode["BLACK_ADD_ERROR"] = 37001] = "BLACK_ADD_ERROR"; /** * 获得指定人员再黑名单中的状态异常 */ ErrorCode[ErrorCode["BLACK_GETSTATUS_ERROR"] = 37002] = "BLACK_GETSTATUS_ERROR"; /** * 移除黑名单异常 */ ErrorCode[ErrorCode["BLACK_REMOVE_ERROR"] = 37003] = "BLACK_REMOVE_ERROR"; /** * 获取草稿失败 */ ErrorCode[ErrorCode["DRAF_GET_ERROR"] = 38001] = "DRAF_GET_ERROR"; /** * 保存草稿失败 */ ErrorCode[ErrorCode["DRAF_SAVE_ERROR"] = 38002] = "DRAF_SAVE_ERROR"; /** * 删除草稿失败 */ ErrorCode[ErrorCode["DRAF_REMOVE_ERROR"] = 38003] = "DRAF_REMOVE_ERROR"; /** * 关注公众号失败 */ ErrorCode[ErrorCode["SUBSCRIBE_ERROR"] = 39001] = "SUBSCRIBE_ERROR"; /** * 关注公众号失败 */ ErrorCode[ErrorCode["QNTKN_FILETYPE_ERROR"] = 41001] = "QNTKN_FILETYPE_ERROR"; /** * 获取七牛token失败 */ ErrorCode[ErrorCode["QNTKN_GET_ERROR"] = 41002] = "QNTKN_GET_ERROR"; /** * cookie被禁用 */ ErrorCode[ErrorCode["COOKIE_ENABLE"] = 51001] = "COOKIE_ENABLE"; ErrorCode[ErrorCode["GET_MESSAGE_BY_ID_ERROR"] = 61001] = "GET_MESSAGE_BY_ID_ERROR"; // 没有注册DeviveId 也就是用户没有登陆 ErrorCode[ErrorCode["HAVNODEVICEID"] = 24001] = "HAVNODEVICEID"; // 已经存在 ErrorCode[ErrorCode["DEVICEIDISHAVE"] = 24002] = "DEVICEIDISHAVE"; // 成功 ErrorCode[ErrorCode["SUCCESS"] = 0] = "SUCCESS"; // 没有对应的用户或token ErrorCode[ErrorCode["FEILD"] = 24009] = "FEILD"; // voip为空 ErrorCode[ErrorCode["VOIPISNULL"] = 24013] = "VOIPISNULL"; // 不支持的Voip引擎 ErrorCode[ErrorCode["NOENGINETYPE"] = 24010] = "NOENGINETYPE"; // channleName 是空 ErrorCode[ErrorCode["NULLCHANNELNAME"] = 24011] = "NULLCHANNELNAME"; // 生成Voipkey失败 ErrorCode[ErrorCode["VOIPDYANMICERROR"] = 24012] = "VOIPDYANMICERROR"; // 没有配置voip ErrorCode[ErrorCode["NOVOIP"] = 24014] = "NOVOIP"; // 服务器内部错误 ErrorCode[ErrorCode["INTERNALERRROR"] = 24015] = "INTERNALERRROR"; //VOIP close ErrorCode[ErrorCode["VOIPCLOSE"] = 24016] = "VOIPCLOSE"; ErrorCode[ErrorCode["CLOSE_BEFORE_OPEN"] = 51001] = "CLOSE_BEFORE_OPEN"; ErrorCode[ErrorCode["ALREADY_IN_USE"] = 51002] = "ALREADY_IN_USE"; ErrorCode[ErrorCode["INVALID_CHANNEL_NAME"] = 51003] = "INVALID_CHANNEL_NAME"; ErrorCode[ErrorCode["VIDEO_CONTAINER_IS_NULL"] = 51004] = "VIDEO_CONTAINER_IS_NULL"; /** * 删除消息数组长度为 0 . */ ErrorCode[ErrorCode["DELETE_MESSAGE_ID_IS_NULL"] = 61001] = "DELETE_MESSAGE_ID_IS_NULL"; /*! 己方取消已发出的通话请求 */ ErrorCode[ErrorCode["CANCEL"] = 1] = "CANCEL"; /*! 己方拒绝收到的通话请求 */ ErrorCode[ErrorCode["REJECT"] = 2] = "REJECT"; /*! 己方挂断 */ ErrorCode[ErrorCode["HANGUP"] = 3] = "HANGUP"; /*! 己方忙碌 */ ErrorCode[ErrorCode["BUSYLINE"] = 4] = "BUSYLINE"; /*! 己方未接听 */ ErrorCode[ErrorCode["NO_RESPONSE"] = 5] = "NO_RESPONSE"; /*! 己方不支持当前引擎 */ ErrorCode[ErrorCode["ENGINE_UN_SUPPORTED"] = 6] = "ENGINE_UN_SUPPORTED"; /*! 己方网络出错 */ ErrorCode[ErrorCode["NETWORK_ERROR"] = 7] = "NETWORK_ERROR"; /*! 对方取消已发出的通话请求 */ ErrorCode[ErrorCode["REMOTE_CANCEL"] = 11] = "REMOTE_CANCEL"; /*! 对方拒绝收到的通话请求 */ ErrorCode[ErrorCode["REMOTE_REJECT"] = 12] = "REMOTE_REJECT"; /*! 通话过程对方挂断 */ ErrorCode[ErrorCode["REMOTE_HANGUP"] = 13] = "REMOTE_HANGUP"; /*! 对方忙碌 */ ErrorCode[ErrorCode["REMOTE_BUSYLINE"] = 14] = "REMOTE_BUSYLINE"; /*! 对方未接听 */ ErrorCode[ErrorCode["REMOTE_NO_RESPONSE"] = 15] = "REMOTE_NO_RESPONSE"; /*! 对方网络错误 */ ErrorCode[ErrorCode["REMOTE_ENGINE_UN_SUPPORTED"] = 16] = "REMOTE_ENGINE_UN_SUPPORTED"; /*! 对方网络错误 */ ErrorCode[ErrorCode["REMOTE_NETWORK_ERROR"] = 17] = "REMOTE_NETWORK_ERROR"; /*! VoIP 不可用 */ ErrorCode[ErrorCode["VOIP_NOT_AVALIABLE"] = 18] = "VOIP_NOT_AVALIABLE"; })(RongIMLib.ErrorCode || (RongIMLib.ErrorCode = {})); var ErrorCode = RongIMLib.ErrorCode; (function (VoIPMediaType) { VoIPMediaType[VoIPMediaType["MEDIA_AUDIO"] = 1] = "MEDIA_AUDIO"; VoIPMediaType[VoIPMediaType["MEDIA_VEDIO"] = 2] = "MEDIA_VEDIO"; })(RongIMLib.VoIPMediaType || (RongIMLib.VoIPMediaType = {})); var VoIPMediaType = RongIMLib.VoIPMediaType; (function (MediaType) { /** * 图片。 */ MediaType[MediaType["IMAGE"] = 1] = "IMAGE"; /** * 声音。 */ MediaType[MediaType["AUDIO"] = 2] = "AUDIO"; /** * 视频。 */ MediaType[MediaType["VIDEO"] = 3] = "VIDEO"; /** * 通用文件。 */ MediaType[MediaType["FILE"] = 100] = "FILE"; })(RongIMLib.MediaType || (RongIMLib.MediaType = {})); var MediaType = RongIMLib.MediaType; (function (MessageDirection) { /** * 发送消息。 */ MessageDirection[MessageDirection["SEND"] = 1] = "SEND"; /** * 接收消息。 */ MessageDirection[MessageDirection["RECEIVE"] = 2] = "RECEIVE"; })(RongIMLib.MessageDirection || (RongIMLib.MessageDirection = {})); var MessageDirection = RongIMLib.MessageDirection; (function (FileType) { FileType[FileType["IMAGE"] = 1] = "IMAGE"; FileType[FileType["AUDIO"] = 2] = "AUDIO"; FileType[FileType["VIDEO"] = 3] = "VIDEO"; FileType[FileType["FILE"] = 4] = "FILE"; })(RongIMLib.FileType || (RongIMLib.FileType = {})); var FileType = RongIMLib.FileType; (function (RealTimeLocationErrorCode) { /** * 未初始化 RealTimeLocation 实例 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_NOT_INIT"] = -1] = "RC_REAL_TIME_LOCATION_NOT_INIT"; /** * 执行成功。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_SUCCESS"] = 0] = "RC_REAL_TIME_LOCATION_SUCCESS"; /** * 获取 RealTimeLocation 实例时返回 * GPS 未打开。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_GPS_DISABLED"] = 1] = "RC_REAL_TIME_LOCATION_GPS_DISABLED"; /** * 获取 RealTimeLocation 实例时返回 * 当前会话不支持位置共享。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_CONVERSATION_NOT_SUPPORT"] = 2] = "RC_REAL_TIME_LOCATION_CONVERSATION_NOT_SUPPORT"; /** * 获取 RealTimeLocation 实例时返回 * 对方已发起位置共享。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_IS_ON_GOING"] = 3] = "RC_REAL_TIME_LOCATION_IS_ON_GOING"; /** * Join 时返回 * 当前位置共享已超过最大支持人数。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_EXCEED_MAX_PARTICIPANT"] = 4] = "RC_REAL_TIME_LOCATION_EXCEED_MAX_PARTICIPANT"; /** * Join 时返回 * 加入位置共享失败。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_JOIN_FAILURE"] = 5] = "RC_REAL_TIME_LOCATION_JOIN_FAILURE"; /** * Start 时返回 * 发起位置共享失败。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_START_FAILURE"] = 6] = "RC_REAL_TIME_LOCATION_START_FAILURE"; /** * 网络不可用。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_NETWORK_UNAVAILABLE"] = 7] = "RC_REAL_TIME_LOCATION_NETWORK_UNAVAILABLE"; })(RongIMLib.RealTimeLocationErrorCode || (RongIMLib.RealTimeLocationErrorCode = {})); var RealTimeLocationErrorCode = RongIMLib.RealTimeLocationErrorCode; (function (RealTimeLocationStatus) { /** * 空闲状态 (默认状态) * 对方或者自己都未发起位置共享业务,或者位置共享业务已结束。 */ RealTimeLocationStatus[RealTimeLocationStatus["RC_REAL_TIME_LOCATION_STATUS_IDLE"] = 0] = "RC_REAL_TIME_LOCATION_STATUS_IDLE"; /** * 呼入状态 (待加入) * 1. 对方发起了位置共享业务,此状态下,自己只能选择加入。 * 2. 自己从已连接的位置共享中退出。 */ RealTimeLocationStatus[RealTimeLocationStatus["RC_REAL_TIME_LOCATION_STATUS_INCOMING"] = 1] = "RC_REAL_TIME_LOCATION_STATUS_INCOMING"; /** * 呼出状态 =(自己创建) * 1. 自己发起位置共享业务,对方只能选择加入。 * 2. 对方从已连接的位置共享业务中退出。 */ RealTimeLocationStatus[RealTimeLocationStatus["RC_REAL_TIME_LOCATION_STATUS_OUTGOING"] = 2] = "RC_REAL_TIME_LOCATION_STATUS_OUTGOING"; /** * 连接状态 (自己加入) * 对方加入了自己发起的位置共享,或者自己加入了对方发起的位置共享。 */ RealTimeLocationStatus[RealTimeLocationStatus["RC_REAL_TIME_LOCATION_STATUS_CONNECTED"] = 3] = "RC_REAL_TIME_LOCATION_STATUS_CONNECTED"; })(RongIMLib.RealTimeLocationStatus || (RongIMLib.RealTimeLocationStatus = {})); var RealTimeLocationStatus = RongIMLib.RealTimeLocationStatus; (function (ReceivedStatus) { ReceivedStatus[ReceivedStatus["READ"] = 1] = "READ"; ReceivedStatus[ReceivedStatus["LISTENED"] = 2] = "LISTENED"; ReceivedStatus[ReceivedStatus["DOWNLOADED"] = 4] = "DOWNLOADED"; ReceivedStatus[ReceivedStatus["RETRIEVED"] = 8] = "RETRIEVED"; ReceivedStatus[ReceivedStatus["UNREAD"] = 0] = "UNREAD"; })(RongIMLib.ReceivedStatus || (RongIMLib.ReceivedStatus = {})); var ReceivedStatus = RongIMLib.ReceivedStatus; (function (ReadStatus) { ReadStatus[ReadStatus["READ"] = 1] = "READ"; ReadStatus[ReadStatus["LISTENED"] = 2] = "LISTENED"; ReadStatus[ReadStatus["DOWNLOADED"] = 4] = "DOWNLOADED"; ReadStatus[ReadStatus["RETRIEVED"] = 8] = "RETRIEVED"; ReadStatus[ReadStatus["UNREAD"] = 0] = "UNREAD"; })(RongIMLib.ReadStatus || (RongIMLib.ReadStatus = {})); var ReadStatus = RongIMLib.ReadStatus; (function (SearchType) { /** * 精确。 */ SearchType[SearchType["EXACT"] = 0] = "EXACT"; /** * 模糊。 */ SearchType[SearchType["FUZZY"] = 1] = "FUZZY"; })(RongIMLib.SearchType || (RongIMLib.SearchType = {})); var SearchType = RongIMLib.SearchType; (function (SentStatus) { /** * 发送中。 */ SentStatus[SentStatus["SENDING"] = 10] = "SENDING"; /** * 发送失败。 */ SentStatus[SentStatus["FAILED"] = 20] = "FAILED"; /** * 已发送。 */ SentStatus[SentStatus["SENT"] = 30] = "SENT"; /** * 对方已接收。 */ SentStatus[SentStatus["RECEIVED"] = 40] = "RECEIVED"; /** * 对方已读。 */ SentStatus[SentStatus["READ"] = 50] = "READ"; /** * 对方已销毁。 */ SentStatus[SentStatus["DESTROYED"] = 60] = "DESTROYED"; })(RongIMLib.SentStatus || (RongIMLib.SentStatus = {})); var SentStatus = RongIMLib.SentStatus; (function (ConnectionState) { ConnectionState[ConnectionState["ACCEPTED"] = 0] = "ACCEPTED"; ConnectionState[ConnectionState["UNACCEPTABLE_PROTOCOL_VERSION"] = 1] = "UNACCEPTABLE_PROTOCOL_VERSION"; ConnectionState[ConnectionState["IDENTIFIER_REJECTED"] = 2] = "IDENTIFIER_REJECTED"; ConnectionState[ConnectionState["SERVER_UNAVAILABLE"] = 3] = "SERVER_UNAVAILABLE"; /** * token无效 */ ConnectionState[ConnectionState["TOKEN_INCORRECT"] = 4] = "TOKEN_INCORRECT"; ConnectionState[ConnectionState["NOT_AUTHORIZED"] = 5] = "NOT_AUTHORIZED"; ConnectionState[ConnectionState["REDIRECT"] = 6] = "REDIRECT"; ConnectionState[ConnectionState["PACKAGE_ERROR"] = 7] = "PACKAGE_ERROR"; ConnectionState[ConnectionState["APP_BLOCK_OR_DELETE"] = 8] = "APP_BLOCK_OR_DELETE"; ConnectionState[ConnectionState["BLOCK"] = 9] = "BLOCK"; ConnectionState[ConnectionState["TOKEN_EXPIRE"] = 10] = "TOKEN_EXPIRE"; ConnectionState[ConnectionState["DEVICE_ERROR"] = 11] = "DEVICE_ERROR"; })(RongIMLib.ConnectionState || (RongIMLib.ConnectionState = {})); var ConnectionState = RongIMLib.ConnectionState; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var RongIMClient = (function () { function RongIMClient() { } RongIMClient.getInstance = function () { if (!RongIMClient._instance) { throw new Error("RongIMClient is not initialized. Call .init() method first."); } return RongIMClient._instance; }; RongIMClient.showError = function (errorInfo) { var hasConsole = (console && console.error); if (hasConsole) { console.error(JSON.stringify(errorInfo)); } }; RongIMClient.logger = function (params) { var code = params.code; var errorInfo = RongIMClient.LogFactory[code] || params; errorInfo.funcName = params.funcName; errorInfo.msg = params.msg || errorInfo.msg; if (RongIMClient._memoryStore.depend.showError) { RongIMClient.showError(errorInfo); } }; RongIMClient.logCallback = function (callback, funcName) { return { onSuccess: callback.onSuccess, onError: function (errorCode) { RongIMClient.logger({ code: errorCode, funcName: funcName }); callback.onError(errorCode); } }; }; ; RongIMClient.logSendCallback = function (callback, funcName) { return { onSuccess: callback.onSuccess, onError: function (errorCode, result) { RongIMClient.logger({ code: errorCode, funcName: funcName }); callback.onError(errorCode, result); }, onBefore: callback.onBefore }; }; ; /** * 初始化 SDK,在整个应用全局只需要调用一次。 * @param appKey 开发者后台申请的 AppKey,用来标识应用。 * @param dataAccessProvider 必须是DataAccessProvider的实例 */ RongIMClient.init = function (appKey, dataAccessProvider, options, callback) { if (RongIMClient._instance) { return RongIMClient._memoryStore.sdkInfo; } RongIMClient._instance = new RongIMClient(); options = options || {}; var protocol = "http://", wsScheme = 'ws://'; var protocols = 'http:,https:'; if (protocols.indexOf(location.protocol) == -1) { protocol = 'http://'; } if (location.protocol == 'https:') { protocol = 'https://'; wsScheme = 'wss://'; } var isPolling = false; if (typeof WebSocket != 'function') { isPolling = true; } var isIntegrity = function () { //iOS 9 var hasWS = (typeof WebSocket); var integrity = (typeof WebSocket.OPEN == 'number'); return (hasWS && integrity); }; if (typeof WebSocket == 'object' && isIntegrity()) { isPolling = false; } var supportUserData = function () { var element = document.documentElement; return element.addBehavior; }; if (RongIMLib.RongUtil.supportLocalStorage()) { RongIMClient._storageProvider = new RongIMLib.LocalStorageProvider(); } else if (supportUserData()) { RongIMClient._storageProvider = new RongIMLib.UserDataProvider(); } else { RongIMClient._storageProvider = new RongIMLib.MemeoryProvider(); } var serverIndex = RongIMClient._storageProvider.getItem('serverIndex'); RongIMClient.serverStore.index = serverIndex || 0; var pathTmpl = '{0}{1}'; var _serverPath = { navi: 'nav.cn.ronghub.com', api: 'api.cn.ronghub.com' }; // RongIMLib.RongUtil.forEach(_serverPath, function (path, key) { // _serverPath[key] = RongIMLib.RongUtil.stringFormat(pathTmpl, [protocol, path]); // }); RongIMLib.RongUtil.forEach(_serverPath, function (path, key) { var hasProto = (key in options) && options[key]; // var config = { // path: options[key], // tmpl: pathTmpl, // protocol: protocol, // sub: true // }; path = hasProto ? options[key] : path; options[key] = path; }); var _sourcePath = { protobuf: 'cdn.ronghub.com/protobuf-2.3.1.min.js' }; RongIMLib.RongUtil.forEach(_sourcePath, function (path, key) { _sourcePath[key] = RongIMLib.RongUtil.stringFormat(pathTmpl, [protocol, path]); }); RongIMLib.RongUtil.extend(_sourcePath, options); var _defaultOpts = { isPolling: isPolling, wsScheme: wsScheme, protocol: protocol, showError: true, openMp: true, snifferTime: 2000 }; RongIMLib.RongUtil.extend(_defaultOpts, options); if (RongIMLib.RongUtil.isFunction(options.protobuf)) { RongIMClient.Protobuf = options.protobuf; } RongIMClient.userStatusObserver = new RongIMLib.RongObserver(); var pather = new RongIMLib.FeaturePatcher(); pather.patchAll(); var tempStore = { token: "", callback: null, lastReadTime: new RongIMLib.LimitableMap(), conversationList: [], appKey: appKey, publicServiceMap: new RongIMLib.PublicServiceMap(), providerType: 1, deltaTime: 0, filterMessages: [], isSyncRemoteConverList: true, otherDevice: false, custStore: {}, converStore: { latestMessage: {} }, connectAckTime: 0, voipStategy: 0, isFirstPingMsg: true, depend: options, listenerList: RongIMClient._memoryStore.listenerList, notification: {} }; RongIMClient._memoryStore = tempStore; var memoryStoreNavi = RongIMClient._memoryStore.depend.navi; RongIMClient._memoryStore.depend.navi = RongIMLib.RongUtil.getValidNavi(memoryStoreNavi); if (dataAccessProvider && Object.prototype.toString.call(dataAccessProvider) == "[object Object]") { RongIMClient._dataAccessProvider = dataAccessProvider; } else { RongIMClient._dataAccessProvider = new RongIMLib.ServerDataProvider(); } options.appCallback = callback; var sdkInfo = RongIMClient._dataAccessProvider.init(appKey, options); RongIMClient._memoryStore.sdkInfo = sdkInfo; // 兼容 c++ 设置导航,Web 端不生效 RongIMClient._dataAccessProvider.setServerInfo({ navi: location.protocol + options.navi + '/navi.xml' }); RongIMClient.MessageParams = { TextMessage: { objectName: "RC:TxtMsg", msgTag: new RongIMLib.MessageTag(true, true) }, ImageMessage: { objectName: "RC:ImgMsg", msgTag: new RongIMLib.MessageTag(true, true) }, DiscussionNotificationMessage: { objectName: "RC:DizNtf", msgTag: new RongIMLib.MessageTag(false, true) }, VoiceMessage: { objectName: "RC:VcMsg", msgTag: new RongIMLib.MessageTag(true, true) }, RichContentMessage: { objectName: "RC:ImgTextMsg", msgTag: new RongIMLib.MessageTag(true, true) }, FileMessage: { objectName: "RC:FileMsg", msgTag: new RongIMLib.MessageTag(true, true) }, HandshakeMessage: { objectName: "", msgTag: new RongIMLib.MessageTag(true, true) }, UnknownMessage: { objectName: "", msgTag: new RongIMLib.MessageTag(true, true) }, LocationMessage: { objectName: "RC:LBSMsg", msgTag: new RongIMLib.MessageTag(true, true) }, InformationNotificationMessage: { objectName: "RC:InfoNtf", msgTag: new RongIMLib.MessageTag(false, true) }, ContactNotificationMessage: { objectName: "RC:ContactNtf", msgTag: new RongIMLib.MessageTag(false, true) }, ProfileNotificationMessage: { objectName: "RC:ProfileNtf", msgTag: new RongIMLib.MessageTag(false, true) }, CommandNotificationMessage: { objectName: "RC:CmdNtf", msgTag: new RongIMLib.MessageTag(true, true) }, PublicServiceRichContentMessage: { objectName: "RC:PSImgTxtMsg", msgTag: new RongIMLib.MessageTag(true, true) }, PublicServiceMultiRichContentMessage: { objectName: "RC:PSMultiImgTxtMsg", msgTag: new RongIMLib.MessageTag(true, true) }, JrmfRedPacketMessage: { objectName: "RCJrmf:RpMsg", msgTag: new RongIMLib.MessageTag(true, true) }, JrmfRedPacketOpenedMessage: { objectName: "RCJrmf:RpOpendMsg", msgTag: new RongIMLib.MessageTag(true, true) }, GroupNotificationMessage: { objectName: "RC:GrpNtf", msgTag: new RongIMLib.MessageTag(false, true) }, CommandMessage: { objectName: "RC:CmdMsg", msgTag: new RongIMLib.MessageTag(false, false) }, TypingStatusMessage: { objectName: "RC:TypSts", msgTag: new RongIMLib.MessageTag(false, false) }, PublicServiceCommandMessage: { objectName: "RC:PSCmd", msgTag: new RongIMLib.MessageTag(false, false) }, RecallCommandMessage: { objectName: "RC:RcCmd", msgTag: new RongIMLib.MessageTag(false, true) }, SyncReadStatusMessage: { objectName: "RC:SRSMsg", msgTag: new RongIMLib.MessageTag(false, false) }, ReadReceiptRequestMessage: { objectName: "RC:RRReqMsg", msgTag: new RongIMLib.MessageTag(false, false) }, ReadReceiptResponseMessage: { objectName: "RC:RRRspMsg", msgTag: new RongIMLib.MessageTag(false, false) }, ChangeModeResponseMessage: { objectName: "RC:CsChaR", msgTag: new RongIMLib.MessageTag(false, false) }, ChangeModeMessage: { objectName: "RC:CSCha", msgTag: new RongIMLib.MessageTag(false, false) }, EvaluateMessage: { objectName: "RC:CsEva", msgTag: new RongIMLib.MessageTag(false, false) }, CustomerContact: { objectName: "RC:CsContact", msgTag: new RongIMLib.MessageTag(false, false) }, HandShakeMessage: { objectName: "RC:CsHs", msgTag: new RongIMLib.MessageTag(false, false) }, HandShakeResponseMessage: { objectName: "RC:CsHsR", msgTag: new RongIMLib.MessageTag(false, false) }, SuspendMessage: { objectName: "RC:CsSp", msgTag: new RongIMLib.MessageTag(false, false) }, TerminateMessage: { objectName: "RC:CsEnd", msgTag: new RongIMLib.MessageTag(false, false) }, CustomerStatusUpdateMessage: { objectName: "RC:CsUpdate", msgTag: new RongIMLib.MessageTag(false, false) }, ReadReceiptMessage: { objectName: "RC:ReadNtf", msgTag: new RongIMLib.MessageTag(false, false) } }; RongIMClient.MessageParams["AcceptMessage"] = { objectName: "RC:VCAccept", msgTag: new RongIMLib.MessageTag(false, false) }; RongIMClient.MessageParams["RingingMessage"] = { objectName: "RC:VCRinging", msgTag: new RongIMLib.MessageTag(false, false) }; RongIMClient.MessageParams["SummaryMessage"] = { objectName: "RC:VCSummary", msgTag: new RongIMLib.MessageTag(false, false) }; RongIMClient.MessageParams["HungupMessage"] = { objectName: "RC:VCHangup", msgTag: new RongIMLib.MessageTag(false, false) }; RongIMClient.MessageParams["InviteMessage"] = { objectName: "RC:VCInvite", msgTag: new RongIMLib.MessageTag(false, false) }; RongIMClient.MessageParams["MediaModifyMessage"] = { objectName: "RC:VCModifyMedia", msgTag: new RongIMLib.MessageTag(false, false) }; RongIMClient.MessageParams["MemberModifyMessage"] = { objectName: "RC:VCModifyMem", msgTag: new RongIMLib.MessageTag(false, false) }; RongIMClient.MessageType = { TextMessage: "TextMessage", ImageMessage: "ImageMessage", DiscussionNotificationMessage: "DiscussionNotificationMessage", VoiceMessage: "VoiceMessage", RichContentMessage: "RichContentMessage", HandshakeMessage: "HandshakeMessage", UnknownMessage: "UnknownMessage", LocationMessage: "LocationMessage", InformationNotificationMessage: "InformationNotificationMessage", ContactNotificationMessage: "ContactNotificationMessage", ProfileNotificationMessage: "ProfileNotificationMessage", CommandNotificationMessage: "CommandNotificationMessage", CommandMessage: "CommandMessage", TypingStatusMessage: "TypingStatusMessage", ChangeModeResponseMessage: "ChangeModeResponseMessage", ChangeModeMessage: "ChangeModeMessage", EvaluateMessage: "EvaluateMessage", HandShakeMessage: "HandShakeMessage", HandShakeResponseMessage: "HandShakeResponseMessage", SuspendMessage: "SuspendMessage", TerminateMessage: "TerminateMessage", CustomerContact: "CustomerContact", CustomerStatusUpdateMessage: "CustomerStatusUpdateMessage", SyncReadStatusMessage: "SyncReadStatusMessage", ReadReceiptRequestMessage: "ReadReceiptRequestMessage", ReadReceiptResponseMessage: "ReadReceiptResponseMessage", FileMessage: 'FileMessage', AcceptMessage: "AcceptMessage", RingingMessage: "RingingMessage", SummaryMessage: "SummaryMessage", HungupMessage: "HungupMessage", InviteMessage: "InviteMessage", MediaModifyMessage: "MediaModifyMessage", MemberModifyMessage: "MemberModifyMessage", JrmfRedPacketMessage: "JrmfRedPacketMessage", JrmfRedPacketOpenedMessage: "JrmfRedPacketOpenedMessage", GroupNotificationMessage: "GroupNotificationMessage", PublicServiceRichContentMessage: "PublicServiceRichContentMessage", PublicServiceMultiRichContentMessage: "PublicServiceMultiRichContentMessage", PublicServiceCommandMessage: "PublicServiceCommandMessage", RecallCommandMessage: "RecallCommandMessage", ReadReceiptMessage: "ReadReceiptMessage" }; RongIMClient.LogFactory = { /** * 个人 */ "-1": { code: "-1", msg: "服务器超时" }, "-2": { code: "-2", msg: "未知原因失败" }, "-3": { code: "-3", msg: "参数错误" }, "-4": { code: "-4", msg: "参数不正确或尚未实例化" }, "25101": { code: "25101", msg: "撤回消息参数错误", desc: "请检查撤回消息参数 https://rongcloud.github.io/websdk-demo/api-test.html" }, "25102": { code: "25101", msg: "只能撤回自发发送的消息" }, "20604": { code: "20604", msg: "发送频率过快", desc: "https://developer.rongcloud.cn/ticket/info/9Q3L6vRKd1cLS7rycA==?type=1" }, "20406": { code: "20406", msg: "被禁言" }, "23407": { code: "23407", msg: "获取用户失败" }, /** * 群组 */ "20407": { code: "20407", msg: "群组Id无效" }, "22408": { code: "22408", msg: "群组被禁言" }, "22406": { code: "22406", msg: "不在群组" }, "35001": { code: "35001", msg: "群组同步异常" }, "35002": { code: "35002", msg: "匹配群信息异常" }, /** * 讨论组 */ "21406": { code: "21406", msg: "不在讨论组" }, "21407": { code: "21407", msg: "加入讨论失败" }, "21408": { code: "21408", msg: "创建讨论组失败" }, "21409": { code: "21409", msg: "设置讨论组邀请状态失败" }, /** * 聊天室 */ "23406": { code: "23406", msg: "不在聊天室" }, "23408": { code: "23408", msg: "聊天室被禁言" }, "23409": { code: "23409", msg: "聊天室中成员被踢出" }, "23410": { code: "23410", msg: "聊天室不存在" }, "23411": { code: "23411", msg: "聊天室成员已满" }, "23412": { code: "23412", msg: "获取聊天室信息参数无效" }, "23413": { code: "23413", msg: "聊天室异常" }, "23414": { code: "23414", msg: "没有打开聊天室消息存储" }, "36001": { code: "36001", msg: "加入聊天室Id为空" }, "36002": { code: "36002", msg: "加入聊天室失败" }, "36003": { code: "36003", msg: "拉取聊天室历史消息失败" }, /** * voip */ "24001": { code: "24001", msg: "没有注册DeviveId 也就是用户没有登陆" }, "24002": { code: "24002", msg: "用户已经存在" }, "0": { code: "0", msg: "成功" }, "24009": { code: "24009", msg: "没有对应的用户或token" }, "24013": { code: "24013", msg: "voip为空" }, "24010": { code: "24010", msg: "不支持的Voip引擎" }, "24011": { code: "24011", msg: "channelName 是空" }, "24012": { code: "24012", msg: "生成Voipkey失败" }, "24014": { code: "24014", msg: "没有配置voip" }, "24015": { code: "24015", msg: "服务器内部错误" }, "24016": { code: "24016", msg: "VOIP close" }, /** * 通讯、导航 */ "30001": { code: "30001", msg: "通信过程中,当前Socket不存在" }, "30002": { code: "30002", msg: "Socket连接不可用" }, "30003": { code: "30003", msg: "通信超时" }, "30004": { code: "30004", msg: "导航操作时,Http请求失败" }, "30005": { code: "30005", msg: "HTTP请求失败" }, "30006": { code: "30006", msg: "HTTP接收失败" }, "30007": { code: "30007", msg: "导航资源错误" }, "30008": { code: "30008", msg: "没有有效数据" }, "30009": { code: "30009", msg: "不存在有效 IP 地址" }, "30010": { code: "30010", msg: "创建 Socket 失败" }, "30011": { code: "30011", msg: " Socket 被断开" }, "30012": { code: "30012", msg: "PING 操作失败" }, "30013": { code: "30013", msg: "PING 超时" }, "30014": { code: "30014", msg: "消息发送失败" }, /** * 连接 */ "31000": { code: "31000", msg: "做 connect 连接时,收到的 ACK 超时" }, "31001": { code: "31001", msg: "参数错误" }, "31002": { code: "31002", msg: "参数错误,App Id 错误" }, "31003": { code: "31003", msg: "服务器不可用" }, "31004": { code: "31004", msg: "Token 错误" }, "31005": { code: "31005", msg: "App Id 与 Token 不匹配" }, "31006": { code: "31006", msg: "重定向,地址错误" }, "31007": { code: "31007", msg: "NAME 与后台注册信息不一致" }, "31008": { code: "31008", msg: "APP 被屏蔽、删除或不存在" }, "31009": { code: "31009", msg: "用户被屏蔽" }, "31010": { code: "31010", msg: "Disconnect,由服务器返回,比如用户互踢" }, "31011": { code: "31011", msg: "Disconnect,由服务器返回,比如用户互踢" }, /** * 协议 */ "32001": { code: "32001", msg: "协议层内部错误。query,上传下载过程中数据错误" }, "32002": { code: "32002", msg: "协议层内部错误" }, /** * BIZ */ "33001": { code: "33001", msg: "未调用 init 初始化函数" }, "33002": { code: "33002", msg: "数据库初始化失败" }, "33003": { code: "33003", msg: "传入参数无效" }, "33004": { code: "33004", msg: "通道无效" }, "33005": { code: "33005", msg: "重新连接成功" }, "33006": { code: "33006", msg: "连接中,再调用 connect 被拒绝" }, "33007": { code: "33007", msg: "消息漫游服务未开通" }, "33008": { code: "33008", msg: "消息添加失败" }, "33009": { code: "33009", msg: "消息删除失败" }, /** * 会话 */ "34001": { code: "34001", msg: "删除会话失败" }, "34002": { code: "34002", msg: "拉取历史消息失败" }, "34003": { code: "34003", msg: "会话指定异常" }, "34004": { code: "34004", msg: "获取会话未读消息总数失败" }, "34005": { code: "34005", msg: "获取指定会话类型未读消息数异常" }, "34006": { code: "34006", msg: "获取指定用户ID&会话类型未读消息数异常" }, "34007": { code: "34007", msg: "清除会话消息异常" }, "34008": { code: "34008", msg: "获取会话消息异常" }, "34009": { code: "34009", msg: "清除历史消息会话类型不正确" }, "34010": { code: "34010", msg: "清除历史消息失败,请检查传入参数" }, /** * 黑名单异常 */ "37001": { code: "37001", msg: "加入黑名单异常" }, "37002": { code: "37002", msg: "获得指定人员再黑名单中的状态异常" }, "37003": { code: "37003", msg: "移除黑名单异常" }, "405": { code: "405", msg: "在黑名单中" }, /** * 草稿 */ "38001": { code: "38001", msg: "获取草稿失败" }, "38002": { code: "38002", msg: "保存草稿失败" }, "38003": { code: "38003", msg: "删除草稿失败" }, /** * 公众号 */ "39001": { code: "39001", msg: "关注公众号失败" }, /** * 文件 */ "41001": { code: "41001", msg: "文件类型错误" }, "41002": { code: "41002", msg: "获取七牛token失败" }, /** * */ "51001": { code: "51001", msg: "未安装或未启动插件" }, "51002": { code: "51002", msg: "视频已经存在" }, "51003": { code: "51003", msg: "无效的channelName" }, "51004": { code: "51004", msg: "视频内容为空" }, /** * */ "61001": { code: "61001", msg: "删除消息数组长度为 0" } }; return sdkInfo; }; ; RongIMClient.setProtocol = function (protocol) { RongIMClient._memoryStore.depend = RongIMClient._memoryStore.depend || {}; var HttpProtocol = RongIMClient.HttpProtocol; var WsProtocol = RongIMClient.WsProtocol; if (protocol === HttpProtocol.http) { RongIMClient._memoryStore.depend.protocol = HttpProtocol.http; RongIMClient._memoryStore.depend.wsScheme = WsProtocol.ws; } else { RongIMClient._memoryStore.depend.protocol = HttpProtocol.https; RongIMClient._memoryStore.depend.wsScheme = WsProtocol.wss; } }; RongIMClient.getProtocol = function () { RongIMClient._memoryStore.depend = RongIMClient._memoryStore.depend || {}; var depend = RongIMClient._memoryStore.depend; var protocol = depend.protocol, wsScheme = depend.wsScheme; if (!protocol || !wsScheme) { protocol = RongIMClient.HttpProtocol.https; wsScheme = RongIMClient.WsProtocol.wss; } return { protocol: protocol, wsScheme: wsScheme }; }; /** var config = { appkey: appkey, token: token, dataAccessProvider:dataAccessProvider, opts: opts }; callback(_instance, userId); */ RongIMClient.initApp = function (config, callback) { RongIMClient.init(config.appkey, config.dataAccessProvider, config.opts, function () { var instance = RongIMClient._instance; //备用 var error = null; callback(error, instance); }); }; /** * 连接服务器,在整个应用全局只需要调用一次,断线后 SDK 会自动重连。 * * @param token 从服务端获取的用户身份令牌(Token)。 * @param callback 连接回调,返回连接的成功或者失败状态。 */ RongIMClient.connect = function (token, _callback, userId, serverConf) { RongIMLib.CheckParam.getInstance().check(["string", "object", "string|null|object|global|undefined", "object|null|global|undefined"], "connect", true, arguments); var connectCallback = { onSuccess: _callback.onSuccess, onTokenIncorrect: _callback.onTokenIncorrect, onError: function (errorCode) { RongIMClient.logger({ code: errorCode, funcName: "connect" }); _callback.onError(errorCode); } }; RongIMClient._dataAccessProvider.connect(token, connectCallback, userId, serverConf); }; RongIMClient.reconnect = function (callback, config) { var connectCallback = { onSuccess: callback.onSuccess, onTokenIncorrect: callback.onTokenIncorrect, onError: function (errorCode) { RongIMClient.logger({ code: errorCode, funcName: "connect" }); callback.onError(errorCode); } }; RongIMClient._dataAccessProvider.reconnect(connectCallback, config); }; /** * 注册消息类型,用于注册用户自定义的消息。 * 内建的消息类型已经注册过,不需要再次注册。 * 自定义消息声明需放在执行顺序最高的位置(在RongIMClient.init(appkey)之后即可) * @param objectName 消息内置名称 */ RongIMClient.registerMessageType = function (messageType, objectName, messageTag, messageContent, searchProp) { RongIMClient._dataAccessProvider.registerMessageType(messageType, objectName, messageTag, messageContent, searchProp); RongIMClient.RegisterMessage[messageType].messageName = messageType; RongIMClient.MessageType[messageType] = messageType; RongIMClient.MessageParams[messageType] = { objectName: objectName, msgTag: messageTag }; }; /** * 设置连接状态变化的监听器。 * * @param listener 连接状态变化的监听器。 */ RongIMClient.setConnectionStatusListener = function (listener) { if (RongIMClient._dataAccessProvider) { RongIMClient._dataAccessProvider.setConnectionStatusListener(listener); } else { RongIMClient._memoryStore.listenerList.push(listener); } }; /** * 设置接收消息的监听器。 * * @param listener 接收消息的监听器。 */ RongIMClient.setOnReceiveMessageListener = function (listener) { if (RongIMClient._dataAccessProvider) { RongIMClient._dataAccessProvider.setOnReceiveMessageListener(listener); } else { RongIMClient._memoryStore.listenerList.push(listener); } }; /** * 清理所有连接相关的变量 */ RongIMClient.prototype.logout = function () { RongIMClient._dataAccessProvider.logout(); }; /** * 断开连接。 */ RongIMClient.prototype.disconnect = function () { RongIMClient._dataAccessProvider.disconnect(); }; RongIMClient.prototype.startCustomService = function (custId, callback, groupId) { if (!custId || !callback) return; var msg; if (typeof groupId == 'undefined') { msg = new RongIMLib.HandShakeMessage(); } else { msg = new RongIMLib.HandShakeMessage({ groupid: groupId }); } var me = this; RongIMLib.RongIMClient._memoryStore.custStore["isInit"] = true; RongIMClient.getInstance().sendMessage(RongIMLib.ConversationType.CUSTOMER_SERVICE, custId, msg, { onSuccess: function (data) { if (data.isBlack) { callback.onError(); me.stopCustomeService(custId, { onSuccess: function () { }, onError: function () { } }); } else { callback.onSuccess(); } }, onError: function () { callback.onError(); }, onBefore: function () { } }); }; RongIMClient.prototype.stopCustomeService = function (custId, callback) { if (!custId || !callback) return; var session = RongIMClient._memoryStore.custStore[custId]; if (!session) return; var msg = new RongIMLib.SuspendMessage({ sid: session.sid, uid: session.uid, pid: session.pid }); this.sendCustMessage(custId, msg, { onSuccess: function () { // delete RongIMClient._memoryStore.custStore[custId]; setTimeout(function () { callback.onSuccess(); }); }, onError: function () { setTimeout(function () { callback.onError(); }); } }); }; RongIMClient.prototype.switchToHumanMode = function (custId, callback) { if (!custId || !callback) return; var session = RongIMClient._memoryStore.custStore[custId]; if (!session) return; var msg = new RongIMLib.ChangeModeMessage({ sid: session.sid, uid: session.uid, pid: session.pid }); this.sendCustMessage(custId, msg, callback); }; RongIMClient.prototype.evaluateRebotCustomService = function (custId, isRobotResolved, sugest, callback) { if (!custId || !callback) return; var session = RongIMClient._memoryStore.custStore[custId]; if (!session) return; var msg = new RongIMLib.EvaluateMessage({ sid: session.sid, uid: session.uid, pid: session.pid, isRobotResolved: isRobotResolved, sugest: sugest, type: 0 }); this.sendCustMessage(custId, msg, callback); }; RongIMClient.prototype.evaluateHumanCustomService = function (custId, humanValue, sugest, callback) { if (!custId || !callback) return; var session = RongIMClient._memoryStore.custStore[custId]; if (!session) return; var msg = new RongIMLib.EvaluateMessage({ sid: session.sid, uid: session.uid, pid: session.pid, humanValue: humanValue, sugest: sugest, type: 1 }); this.sendCustMessage(custId, msg, callback); }; RongIMClient.prototype.sendCustMessage = function (custId, msg, callback) { RongIMClient.getInstance().sendMessage(RongIMLib.ConversationType.CUSTOMER_SERVICE, custId, msg, { onSuccess: function (data) { callback.onSuccess(); }, onError: function () { callback.onError(); }, onBefore: function () { } }); }; /** * 获取当前连接的状态。 */ RongIMClient.prototype.getCurrentConnectionStatus = function () { return RongIMClient._dataAccessProvider.getCurrentConnectionStatus(); }; /** * 获取当前使用的连接通道。 */ RongIMClient.prototype.getConnectionChannel = function () { if (RongIMLib.Transportations._TransportType == RongIMLib.Socket.XHR_POLLING) { return RongIMLib.ConnectionChannel.XHR_POLLING; } else if (RongIMLib.Transportations._TransportType == RongIMLib.Socket.WEBSOCKET) { return RongIMLib.ConnectionChannel.WEBSOCKET; } }; /** * 获取当前使用的本地储存提供者。 TODO */ RongIMClient.prototype.getStorageProvider = function () { if (RongIMClient._memoryStore.providerType == 1) { return "ServerDataProvider"; } else { return "OtherDataProvider"; } }; /** * 过滤聊天室消息(拉取最近聊天消息) * @param {string[]} msgFilterNames */ RongIMClient.prototype.setFilterMessages = function (msgFilterNames) { if (Object.prototype.toString.call(msgFilterNames) == "[object Array]") { RongIMClient._memoryStore.filterMessages = msgFilterNames; } }; RongIMClient.prototype.getAgoraDynamicKey = function (engineType, channelName, callback) { RongIMClient._dataAccessProvider.getAgoraDynamicKey(engineType, channelName, callback); }; /** * 获取当前连接用户的 UserId。 */ RongIMClient.prototype.getCurrentUserId = function () { return RongIMLib.Bridge._client.userId; }; /** * 获取服务器时间与本地时间的差值,单位为毫秒。 * 计算公式:差值 = 本地时间毫秒数 - 服务器时间毫秒数 * @param callback 获取的回调,返回差值。 */ RongIMClient.prototype.getDeltaTime = function () { return RongIMClient._dataAccessProvider.getDelaTime(); }; // #region Message RongIMClient.prototype.getMessage = function (messageId, callback) { RongIMClient._dataAccessProvider.getMessage(messageId, RongIMClient.logCallback(callback, "getMessage")); }; RongIMClient.prototype.deleteLocalMessages = function (conversationType, targetId, messageIds, callback) { RongIMClient._dataAccessProvider.removeLocalMessage(conversationType, targetId, messageIds, RongIMClient.logCallback(callback, "deleteLocalMessages")); }; RongIMClient.prototype.updateMessage = function (message, callback) { RongIMClient._dataAccessProvider.updateMessage(message, RongIMClient.logCallback(callback, "updateMessage")); }; RongIMClient.prototype.clearMessages = function (conversationType, targetId, callback) { RongIMClient._dataAccessProvider.clearMessages(conversationType, targetId, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "clearMessages" }); callback.onError(errorCode); }); } }); }; /**TODO 清楚本地存储的未读消息,目前清空内存中的未读消息 * [clearMessagesUnreadStatus 清空指定会话未读消息] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [用户id] * @param {ResultCallback} callback [返回值,参数回调] */ RongIMClient.prototype.clearMessagesUnreadStatus = function (conversationType, targetId, callback) { RongIMClient._dataAccessProvider.updateMessages(conversationType, targetId, "readStatus", null, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "clearMessagesUnreadStatus" }); callback.onError(errorCode); }); } }); }; RongIMClient.prototype.deleteRemoteMessages = function (conversationType, targetId, delMsgs, callback) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "array", "object"], "deleteRemoteMessages", false, arguments); if (delMsgs.length == 0) { var errorCode = RongIMLib.ErrorCode.DELETE_MESSAGE_ID_IS_NULL; RongIMClient.logger({ code: errorCode, funcName: "deleteRemoteMessages" }); callback.onError(RongIMLib.ErrorCode.DELETE_MESSAGE_ID_IS_NULL); return; } else if (delMsgs.length > 100) { delMsgs.length = 100; } // 后续增加,去掉注释即可 callback.onSuccess(true); // var modules = new RongIMClient.Protobuf.DeleteMsgInput(); // modules.setType(conversationType); // modules.setConversationId(targetId); // modules.setMsgs(delMsgs); // RongIMClient.bridge.queryMsg(33, MessageUtil.ArrayForm(modules.toArrayBuffer()), Bridge._client.userId, { // onSuccess: function(info: any) { // callback.onSuccess(true); // }, // onError: function(err: any) { // callback.onError(err); // } // }, "DeleteMsgOutput"); }; /** * [deleteMessages 删除消息记录。] * @param {ConversationType} conversationType [description] * @param {string} targetId [description] * @param {number[]} messageIds [description] * @param {ResultCallback} callback [description] */ RongIMClient.prototype.deleteMessages = function (conversationType, targetId, delMsgs, callback) { RongIMClient._dataAccessProvider.removeMessage(conversationType, targetId, delMsgs, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "deleteMessages" }); callback.onError(errorCode); }); } }); }; RongIMClient.prototype.sendLocalMessage = function (message, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object"], "sendLocalMessage", false, arguments); RongIMClient._dataAccessProvider.updateMessage(message); this.sendMessage(message.conversationType, message.targetId, message.content, RongIMClient.logSendCallback(callback, "sendLocalMessage")); }; /** * [sendMessage 发送消息。] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [目标Id] * @param {MessageContent} messageContent [消息类型] * @param {SendMessageCallback} sendCallback [] * @param {ResultCallback} resultCallback [返回值,函数回调] * @param {string} pushContent [] * @param {string} pushData [] */ RongIMClient.prototype.sendMessage = function (conversationType, targetId, messageContent, sendCallback, mentiondMsg, pushText, appData, methodType, params) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object", "object", "undefined|object|null|global|boolean", "undefined|object|null|global|string", "undefined|object|null|global|string", "undefined|object|null|global|number", "undefined|object|null|global"], "sendMessage", false, arguments); RongIMClient._dataAccessProvider.sendMessage(conversationType, targetId, messageContent, RongIMClient.logSendCallback(sendCallback, "sendMessage"), mentiondMsg, pushText, appData, methodType, params); }; RongIMClient.prototype.sendReceiptResponse = function (conversationType, targetId, sendCallback) { RongIMClient._dataAccessProvider.sendReceiptResponse(conversationType, targetId, RongIMClient.logSendCallback(sendCallback, "sendReceiptResponse")); }; RongIMClient.prototype.sendTypingStatusMessage = function (conversationType, targetId, messageName, sendCallback) { RongIMClient._dataAccessProvider.sendTypingStatusMessage(conversationType, targetId, messageName, RongIMClient.logSendCallback(sendCallback, "sendTypingStatusMessage")); }; /** * [sendStatusMessage description] * @param {MessageContent} messageContent [description] * @param {SendMessageCallback} sendCallback [description] * @param {ResultCallback} resultCallback [description] */ RongIMClient.prototype.sendStatusMessage = function (messageContent, sendCallback, resultCallback) { throw new Error("Not implemented yet"); }; /** * [sendTextMessage 发送TextMessage快捷方式] * @param {string} content [消息内容] * @param {ResultCallback} resultCallback [返回值,参数回调] */ RongIMClient.prototype.sendTextMessage = function (conversationType, targetId, content, sendMessageCallback) { RongIMClient._dataAccessProvider.sendTextMessage(conversationType, targetId, content, RongIMClient.logSendCallback(sendMessageCallback, "sendTextMessage")); }; RongIMClient.prototype.sendRecallMessage = function (content, sendMessageCallback) { var callback = RongIMClient.logSendCallback(sendMessageCallback, "sendRecallMessage"); var senderUserId = content.senderUserId; var userId = RongIMLib.Bridge._client.userId; var isOther = (senderUserId != userId); if (isOther) { var callback = RongIMClient.logSendCallback(sendMessageCallback, "sendRecallMessage"); callback.onError(RongIMLib.ErrorCode.RECALL_MESSAGE, content); return; } RongIMClient._dataAccessProvider.sendRecallMessage(content, callback); }; /** * [insertMessage 向本地插入一条消息,不发送到服务器。] * @param {ConversationType} conversationType [description] * @param {string} targetId [description] * @param {string} senderUserId [description] * @param {MessageContent} content [description] * @param {ResultCallback} callback [description] */ RongIMClient.prototype.insertMessage = function (conversationType, targetId, content, callback) { RongIMClient._dataAccessProvider.addMessage(conversationType, targetId, content, RongIMClient.logCallback(callback, "insertMessage")); }; /** * [getHistoryMessages 拉取历史消息记录。] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [用户Id] * @param {number|null} pullMessageTime [拉取历史消息起始位置(格式为毫秒数),可以为null] * @param {number} count [历史消息数量] * @param {ResultCallback} callback [回调函数] * @param {string} objectName [objectName] */ RongIMClient.prototype.getHistoryMessages = function (conversationType, targetId, timestamp, count, callback, objectname, direction) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "number|null|global|object", "number", "object", "undefined|object|null|global|string", "boolean|null|global|object"], "getHistoryMessages", false, arguments); if (count > 20) { throw new Error("HistroyMessage count must be less than or equal to 20!"); } if (conversationType.valueOf() < 0) { throw new Error("ConversationType must be greater than -1"); } RongIMClient._dataAccessProvider.getHistoryMessages(conversationType, targetId, timestamp, count, RongIMClient.logCallback(callback, "getHistoryMessages"), objectname, direction); }; RongIMClient.prototype.setMessageContent = function (messageId, content, objectName) { RongIMClient._dataAccessProvider.setMessageContent(messageId, content, objectName); }; ; /** * [getRemoteHistoryMessages 拉取某个时间戳之前的消息] * @param {ConversationType} conversationType [description] * @param {string} targetId [description] * @param {Date} dateTime [description] * @param {number} count [description] * @param {ResultCallback} callback [description] */ RongIMClient.prototype.getRemoteHistoryMessages = function (conversationType, targetId, timestamp, count, callback) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "number|null|global|object", "number", "object"], "getRemoteHistoryMessages", false, arguments); var funcName = "getRemoteHistoryMessages"; var log = { errorCode: RongIMLib.ErrorCode.RC_CONN_PROTO_VERSION_ERROR, funcName: "getRemoteHistoryMessages" }; if (count > 20) { RongIMClient.logger(log); callback.onError(RongIMLib.ErrorCode.RC_CONN_PROTO_VERSION_ERROR); return; } if (conversationType.valueOf() < 0) { RongIMClient.logger(log); callback.onError(RongIMLib.ErrorCode.RC_CONN_PROTO_VERSION_ERROR); return; } RongIMClient._dataAccessProvider.getRemoteHistoryMessages(conversationType, targetId, timestamp, count, RongIMClient.logCallback(callback, funcName)); }; RongIMClient.prototype.clearHistoryMessages = function (params, callback) { RongIMClient._dataAccessProvider.clearHistoryMessages(params, callback); }; RongIMClient.prototype.clearRemoteHistoryMessages = function (params, callback) { RongIMClient._dataAccessProvider.clearRemoteHistoryMessages(params, RongIMClient.logCallback(callback, "clearRemoteHistoryMessages")); }; /** * [hasRemoteUnreadMessages 是否有未接收的消息,jsonp方法] * @param {string} appkey [appkey] * @param {string} token [token] * @param {ConnectCallback} callback [返回值,参数回调] */ RongIMClient.prototype.hasRemoteUnreadMessages = function (token, callback) { RongIMClient._dataAccessProvider.hasRemoteUnreadMessages(token, RongIMClient.logCallback(callback, "hasRemoteUnreadMessages")); }; RongIMClient.prototype.getTotalUnreadCount = function (callback, conversationTypes) { return RongIMClient._dataAccessProvider.getTotalUnreadCount({ onSuccess: function (count) { setTimeout(function () { callback.onSuccess(count); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "getTotalUnreadCount" }); callback.onError(errorCode); }); } }, conversationTypes); }; /** * [getConversationUnreadCount 指定多种会话类型获取未读消息数] * @param {ResultCallback} callback [返回值,参数回调。] * @param {ConversationType[]} ...conversationTypes [会话类型。] */ RongIMClient.prototype.getConversationUnreadCount = function (conversationTypes, callback) { RongIMClient._dataAccessProvider.getConversationUnreadCount(conversationTypes, { onSuccess: function (count) { setTimeout(function () { callback.onSuccess(count); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "getConversationUnreadCount" }); callback.onError(errorCode); }); } }); }; /** * [getUnreadCount 指定用户、会话类型的未读消息总数。] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [用户Id] */ RongIMClient.prototype.getUnreadCount = function (conversationType, targetId, callback) { callback = callback || function(){}; return RongIMClient._dataAccessProvider.getUnreadCount(conversationType, targetId, { onSuccess: function (count) { setTimeout(function () { callback.onSuccess(count); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "getUnreadCount" }); callback.onError(errorCode); }); } }); }; RongIMClient.prototype.clearUnreadCountByTimestamp = function (conversationType, targetId, timestamp, callback) { RongIMClient._dataAccessProvider.clearUnreadCountByTimestamp(conversationType, targetId, timestamp, RongIMClient.logCallback(callback, "clearUnreadCountByTimestamp")); }; /** * 清楚会话未读消息数 * @param {ConversationType} conversationType 会话类型 * @param {string} targetId 目标Id * @param {ResultCallback} callback 返回值,函数回调 */ RongIMClient.prototype.clearUnreadCount = function (conversationType, targetId, callback) { RongIMClient._dataAccessProvider.clearUnreadCount(conversationType, targetId, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "clearUnreadCount" }); callback.onError(errorCode); }); } }); }; RongIMClient.prototype.clearLocalStorage = function (callback) { RongIMClient._storageProvider.clearItem(); callback(); }; RongIMClient.prototype.setMessageExtra = function (messageId, value, callback) { RongIMClient._dataAccessProvider.setMessageExtra(messageId, value, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "setMessageExtra" }); callback.onError(errorCode); }); } }); }; RongIMClient.prototype.setMessageReceivedStatus = function (messageUId, receivedStatus, callback) { RongIMClient._dataAccessProvider.setMessageReceivedStatus(messageUId, receivedStatus, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "setMessageReceivedStatus" }); callback.onError(errorCode); }); } }); }; RongIMClient.prototype.setMessageStatus = function (conersationType, targetId, timestamp, status, callback) { RongIMClient._dataAccessProvider.setMessageStatus(conersationType, targetId, timestamp, status, RongIMClient.logCallback(callback, "setMessageStatus")); }; RongIMClient.prototype.setMessageSentStatus = function (messageId, sentStatus, callback) { RongIMClient._dataAccessProvider.setMessageSentStatus(messageId, sentStatus, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "setMessageSentStatus" }); callback.onError(errorCode); }); } }); }; // #endregion Message // #region TextMessage Draft /** * clearTextMessageDraft 清除指定会话和消息类型的草稿。 * @param {ConversationType} conversationType 会话类型 * @param {string} targetId 目标Id */ RongIMClient.prototype.clearTextMessageDraft = function (conversationType, targetId) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "clearTextMessageDraft", false, arguments); var key = "darf_" + conversationType + "_" + targetId; delete RongIMClient._memoryStore[key]; return true; }; /** * [getTextMessageDraft 获取指定消息和会话的草稿。] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [目标Id] */ RongIMClient.prototype.getTextMessageDraft = function (conversationType, targetId) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "getTextMessageDraft", false, arguments); if (targetId == "" || conversationType < 0) { throw new Error("params error : " + RongIMLib.ErrorCode.DRAF_GET_ERROR); } var key = "darf_" + conversationType + "_" + targetId; return RongIMClient._memoryStore[key]; }; /** * [saveTextMessageDraft description] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [目标Id] * @param {string} value [草稿值] */ RongIMClient.prototype.saveTextMessageDraft = function (conversationType, targetId, value) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "string", "object"], "saveTextMessageDraft", false, arguments); var key = "darf_" + conversationType + "_" + targetId; RongIMClient._memoryStore[key] = value; return true; }; // #endregion TextMessage Draft // #region Conversation RongIMClient.prototype.searchConversationByContent = function (keyword, callback, conversationTypes, customMsgTypes) { RongIMClient._dataAccessProvider.searchConversationByContent(keyword, RongIMClient.logCallback(callback, "searchConversationByContent"), conversationTypes, customMsgTypes); }; RongIMClient.prototype.searchMessageByContent = function (conversationType, targetId, keyword, timestamp, count, total, callback) { RongIMClient._dataAccessProvider.searchMessageByContent(conversationType, targetId, keyword, timestamp, count, total, RongIMClient.logCallback(callback, "searchMessageByContent")); }; RongIMClient.prototype.clearCache = function () { RongIMClient._dataAccessProvider.clearCache(); }; RongIMClient.prototype.clearConversations = function (callback) { var conversationTypes = []; for (var _i = 1; _i < arguments.length; _i++) { conversationTypes[_i - 1] = arguments[_i]; } if (conversationTypes.length == 0) { conversationTypes = [RongIMLib.ConversationType.CHATROOM, RongIMLib.ConversationType.CUSTOMER_SERVICE, RongIMLib.ConversationType.DISCUSSION, RongIMLib.ConversationType.GROUP, RongIMLib.ConversationType.PRIVATE, RongIMLib.ConversationType.SYSTEM, RongIMLib.ConversationType.PUBLIC_SERVICE, RongIMLib.ConversationType.APP_PUBLIC_SERVICE]; } RongIMClient._dataAccessProvider.clearConversations(conversationTypes, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "clearConversations" }); callback.onError(errorCode); }); } }); }; /** * [getConversation 获取指定会话,此方法需在getConversationList之后执行] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [目标Id] * @param {ResultCallback} callback [返回值,函数回调] */ RongIMClient.prototype.getConversation = function (conversationType, targetId, callback) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "getConversation", false, arguments); return RongIMClient._dataAccessProvider.getConversation(conversationType, targetId, { onSuccess: function (conver) { setTimeout(function () { callback.onSuccess(conver); }); }, onError: function (error) { setTimeout(function () { RongIMClient.logger({ code: error, funcName: "getConversation" }); callback.onError(error); }); } }); }; /** * [pottingConversation 组装会话列表] * @param {any} tempConver [临时会话] * conver_conversationType_targetId_no. * msg_conversationType_targetId_no. */ RongIMClient.prototype.pottingConversation = function (tempConver) { var self = this, isUseReplace = false; RongIMClient._dataAccessProvider.getConversation(tempConver.type, tempConver.userId, { onSuccess: function (conver) { if (!conver) { conver = new RongIMLib.Conversation(); } else { isUseReplace = true; } conver.conversationType = tempConver.type; conver.targetId = tempConver.userId; conver.latestMessage = RongIMLib.MessageUtil.messageParser(tempConver.msg); conver.latestMessageId = conver.latestMessage.messageId; conver.objectName = conver.latestMessage.objectName; conver.receivedStatus = conver.latestMessage.receivedStatus; conver.receivedTime = conver.latestMessage.receiveTime; conver.sentStatus = conver.latestMessage.sentStatus; conver.sentTime = conver.latestMessage.sentTime; var mentioneds = RongIMClient._storageProvider.getItem("mentioneds_" + RongIMLib.Bridge._client.userId + '_' + conver.conversationType + '_' + conver.targetId); if (mentioneds) { var info = JSON.parse(mentioneds); conver.mentionedMsg = info[tempConver.type + "_" + tempConver.userId]; } if (!isUseReplace) { if (RongIMLib.RongUtil.supportLocalStorage()) { var count = RongIMClient._storageProvider.getItem("cu" + RongIMLib.Bridge._client.userId + tempConver.type + tempConver.userId); conver.unreadMessageCount = Number(count); } else { conver.unreadMessageCount = 0; } } if (conver.conversationType == RongIMLib.ConversationType.DISCUSSION) { self.getDiscussion(tempConver.userId, { onSuccess: function (info) { conver.conversationTitle = info.name; }, onError: function (error) { } }); } RongIMClient._dataAccessProvider.addConversation(conver, { onSuccess: function (data) { } }); }, onError: function (error) { } }); }; RongIMClient.prototype.addConversation = function (conversation, callback) { RongIMClient._dataAccessProvider.addConversation(conversation, callback); }; RongIMClient.prototype.sortConversationList = function (conversationList) { var convers = []; for (var i = 0, len = conversationList.length; i < len; i++) { if (!conversationList[i]) { continue; } if (conversationList[i].isTop) { convers.push(conversationList[i]); conversationList.splice(i, 1); continue; } for (var j = 0; j < len - i - 1; j++) { if (conversationList[j].sentTime < conversationList[j + 1].sentTime) { var swap = conversationList[j]; conversationList[j] = conversationList[j + 1]; conversationList[j + 1] = swap; } } } return RongIMClient._memoryStore.conversationList = convers.concat(conversationList); }; /* var conversation = { // 会话类型 types: [1, 2, 3, 4, 5, 6, 7, 8], // 获取会话的开始始时间, 0 ,按会话中最后一条消息最大 sentTime 倒序开始获取 sentTime: 0, // 获取条数 count: 100 }; var callbacks = { onSuccess: function(){ }, onError: function(){ } }; */ RongIMClient.prototype.getConversationsByPage = function (conversation, callbacks) { return RongIMClient._dataAccessProvider.getConversationsByPage(conversation, callbacks); }; RongIMClient.prototype.getConversationList = function (callback, conversationTypes, count, isGetHiddenConvers) { RongIMLib.CheckParam.getInstance().check(["object", "null|undefined|array|object|global", "number|undefined|null|object|global", "boolean|undefined|null|object|global"], "getConversationList", false, arguments); var me = this; RongIMClient._dataAccessProvider.getConversationList({ onSuccess: function (data) { if (conversationTypes || RongIMClient._dataAccessProvider) { setTimeout(function () { callback.onSuccess(data); }); } else { setTimeout(function () { callback.onSuccess(RongIMClient._memoryStore.conversationList); }); } }, onError: function (error) { setTimeout(function () { RongIMClient.logger({ code: error, funcName: "getConversationList" }); callback.onError(error); }); } }, conversationTypes, count, isGetHiddenConvers); }; RongIMClient.prototype.getRemoteConversations = function(count, beginTime, order, callback){ RongIMLib.CheckParam.getInstance().check(["number", "number", "number", "object"], "getRemoteConversations", false, arguments); RongIMClient._dataAccessProvider.getRemoteConversations(count, beginTime, order, callback); }; RongIMClient.prototype.getRemoteConversationList = function (callback, conversationTypes, count, isGetHiddenConvers) { RongIMLib.CheckParam.getInstance().check(["object", "null|array|object|global", "number|undefined|null|object|global", "boolean|undefined|null|object|global"], "getRemoteConversationList", false, arguments); RongIMClient._dataAccessProvider.getRemoteConversationList(RongIMClient.logCallback(callback, "getRemoteConversationList"), conversationTypes, count, isGetHiddenConvers); }; RongIMClient.prototype.updateConversation = function (conversation) { return RongIMClient._dataAccessProvider.updateConversation(conversation); }; RongIMClient.prototype.clearData = function () { return RongIMClient._dataAccessProvider.clearData(); }; /** * [createConversation 创建会话。] * @param {number} conversationType [会话类型] * @param {string} targetId [目标Id] * @param {string} converTitle [会话标题] * @param {boolean} islocal [是否同步到服务器,ture:同步,false:不同步] */ RongIMClient.prototype.createConversation = function (conversationType, targetId, converTitle) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "string"], "createConversation", false, arguments); var conver = new RongIMLib.Conversation(); conver.targetId = targetId; conver.conversationType = conversationType; conver.conversationTitle = converTitle; conver.latestMessage = {}; conver.unreadMessageCount = 0; return conver; }; //TODO 删除本地和服务器、删除本地和服务器分开 RongIMClient.prototype.removeConversation = function (conversationType, targetId, callback) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "removeConversation", false, arguments); RongIMClient._dataAccessProvider.removeConversation(conversationType, targetId, RongIMClient.logCallback(callback, "removeConversation")); }; RongIMClient.prototype.setConversationHidden = function (conversationType, targetId, isHidden) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "boolean"], "setConversationHidden", false, arguments); RongIMClient._dataAccessProvider.setConversationHidden(conversationType, targetId, isHidden); }; RongIMClient.prototype.setConversationToTop = function (conversationType, targetId, isTop, callback) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "boolean", "object"], "setConversationToTop", false, arguments); RongIMClient._dataAccessProvider.setConversationToTop(conversationType, targetId, isTop, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "setConversationToTop" }); callback.onError(errorCode); }); } }); }; // #endregion Conversation // #region Notifications /** * [getConversationNotificationStatus 获取指定用户和会话类型免提醒。] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [目标Id] * @param {ResultCallback} callback [返回值,函数回调] */ RongIMClient.prototype.getConversationNotificationStatus = function (conversationType, targetId, callback) { var params = { conversationType: conversationType, targetId: targetId }; RongIMClient._dataAccessProvider.getConversationNotificationStatus(params, RongIMClient.logCallback(callback, "getConversationNotificationStatus")); }; /** * [setConversationNotificationStatus 设置指定用户和会话类型免提醒。] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [目标Id] * @param {ResultCallback} callback [返回值,函数回调] */ RongIMClient.prototype.setConversationNotificationStatus = function (conversationType, targetId, notificationStatus, callback) { var params = { conversationType: conversationType, targetId: targetId, status: status }; RongIMClient._dataAccessProvider.setConversationNotificationStatus(params, RongIMClient.logCallback(callback, "setConversationNotificationStatus")); }; /** * [getNotificationQuietHours 获取免提醒消息时间。] * @param {GetNotificationQuietHoursCallback} callback [返回值,函数回调] */ RongIMClient.prototype.getNotificationQuietHours = function (callback) { throw new Error("Not implemented yet"); }; /** * [removeNotificationQuietHours 移除免提醒消息时间。] * @param {GetNotificationQuietHoursCallback} callback [返回值,函数回调] */ RongIMClient.prototype.removeNotificationQuietHours = function (callback) { throw new Error("Not implemented yet"); }; /** * [setNotificationQuietHours 设置免提醒消息时间。] * @param {GetNotificationQuietHoursCallback} callback [返回值,函数回调] */ RongIMClient.prototype.setNotificationQuietHours = function (startTime, spanMinutes, callback) { throw new Error("Not implemented yet"); }; // #endregion Notifications // #region Discussion /** * [addMemberToDiscussion 加入讨论组] * @param {string} discussionId [讨论组Id] * @param {string[]} userIdList [讨论中成员] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.addMemberToDiscussion = function (discussionId, userIdList, callback) { RongIMLib.CheckParam.getInstance().check(["string", "array", "object"], "addMemberToDiscussion", false, arguments); RongIMClient._dataAccessProvider.addMemberToDiscussion(discussionId, userIdList, RongIMClient.logCallback(callback, "addMemberToDiscussion")); }; /** * [createDiscussion 创建讨论组] * @param {string} name [讨论组名称] * @param {string[]} userIdList [讨论组成员] * @param {CreateDiscussionCallback} callback [返回值,函数回调] */ RongIMClient.prototype.createDiscussion = function (name, userIdList, callback) { RongIMLib.CheckParam.getInstance().check(["string", "array", "object"], "createDiscussion", false, arguments); RongIMClient._dataAccessProvider.createDiscussion(name, userIdList, callback); }; /** * [getDiscussion 获取讨论组信息] * @param {string} discussionId [讨论组Id] * @param {ResultCallback} callback [返回值,函数回调] */ RongIMClient.prototype.getDiscussion = function (discussionId, callback) { RongIMLib.CheckParam.getInstance().check(["string", "object"], "getDiscussion", false, arguments); RongIMClient._dataAccessProvider.getDiscussion(discussionId, RongIMClient.logCallback(callback, "getDiscussion")); }; /** * [quitDiscussion 退出讨论组] * @param {string} discussionId [讨论组Id] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.quitDiscussion = function (discussionId, callback) { RongIMLib.CheckParam.getInstance().check(["string", "object"], "quitDiscussion", false, arguments); RongIMClient._dataAccessProvider.quitDiscussion(discussionId, RongIMClient.logCallback(callback, "quitDiscussion")); }; /** * [removeMemberFromDiscussion 将指定成员移除讨论租] * @param {string} discussionId [讨论组Id] * @param {string} userId [被移除的用户Id] * @param {OperationCallback} callback [返回值,参数回调] */ RongIMClient.prototype.removeMemberFromDiscussion = function (discussionId, userId, callback) { RongIMLib.CheckParam.getInstance().check(["string", "string", "object"], "removeMemberFromDiscussion", false, arguments); RongIMClient._dataAccessProvider.removeMemberFromDiscussion(discussionId, userId, RongIMClient.logCallback(callback, "removeMemberFromDiscussion")); }; /** * [setDiscussionInviteStatus 设置讨论组邀请状态] * @param {string} discussionId [讨论组Id] * @param {DiscussionInviteStatus} status [邀请状态] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.setDiscussionInviteStatus = function (discussionId, status, callback) { RongIMLib.CheckParam.getInstance().check(["string", "number", "object"], "setDiscussionInviteStatus", false, arguments); RongIMClient._dataAccessProvider.setDiscussionInviteStatus(discussionId, status, RongIMClient.logCallback(callback, "setDiscussionInviteStatus")); }; /** * [setDiscussionName 设置讨论组名称] * @param {string} discussionId [讨论组Id] * @param {string} name [讨论组名称] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.setDiscussionName = function (discussionId, name, callback) { RongIMLib.CheckParam.getInstance().check(["string", "string", "object"], "setDiscussionName", false, arguments); RongIMClient._dataAccessProvider.setDiscussionName(discussionId, name, RongIMClient.logCallback(callback, "setDiscussionName")); }; // #endregion Discussion // #region ChatRoom /** * [加入聊天室。] * @param {string} chatroomId [聊天室Id] * @param {number} messageCount [拉取消息数量,-1为不拉去消息] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.joinChatRoom = function (chatroomId, messageCount, callback) { RongIMLib.CheckParam.getInstance().check(["string|number", "number", "object"], "joinChatRoom", false, arguments); if (chatroomId == "") { setTimeout(function () { var errorCode = RongIMLib.ErrorCode.CHATROOM_ID_ISNULL; RongIMClient.logger({ code: errorCode, funcName: "joinChatRoom" }); callback.onError(RongIMLib.ErrorCode.CHATROOM_ID_ISNULL); }); return; } RongIMClient._dataAccessProvider.joinChatRoom(chatroomId, messageCount, RongIMClient.logCallback(callback, "joinChatRoom")); }; RongIMClient.prototype.setDeviceInfo = function (device) { RongIMClient._dataAccessProvider.setDeviceInfo(device); }; RongIMClient.prototype.setChatroomHisMessageTimestamp = function (chatRoomId, timestamp) { RongIMLib.CheckParam.getInstance().check(["string|number", "number"], "setChatroomHisMessageTimestamp", false, arguments); RongIMClient._dataAccessProvider.setChatroomHisMessageTimestamp(chatRoomId, timestamp); }; RongIMClient.prototype.getChatRoomHistoryMessages = function (chatRoomId, count, order, callback) { RongIMLib.CheckParam.getInstance().check(["string|number", "number", "number", "object"], "getChatRoomHistoryMessages", false, arguments); RongIMClient._dataAccessProvider.getChatRoomHistoryMessages(chatRoomId, count, order, RongIMClient.logCallback(callback, "getChatRoomHistoryMessages")); }; RongIMClient.prototype.getChatRoomInfo = function (chatRoomId, count, order, callback) { RongIMLib.CheckParam.getInstance().check(["string|number", "number", "number", "object"], "getChatRoomInfo", false, arguments); RongIMClient._dataAccessProvider.getChatRoomInfo(chatRoomId, count, order, RongIMClient.logCallback(callback, "getChatRoomInfo")); }; /** * [退出聊天室] * @param {string} chatroomId [聊天室Id] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.quitChatRoom = function (chatroomId, callback) { RongIMLib.CheckParam.getInstance().check(["string|number", "object"], "quitChatRoom", false, arguments); RongIMClient._dataAccessProvider.quitChatRoom(chatroomId, RongIMClient.logCallback(callback, "quitChatRoom")); }; // #endregion ChatRoom // #region Public Service RongIMClient.prototype.getRemotePublicServiceList = function (callback, pullMessageTime) { RongIMClient._dataAccessProvider.getRemotePublicServiceList(RongIMClient.logCallback(callback, "getRemotePublicServiceList"), pullMessageTime); }; /** * [getPublicServiceList ]获取本地的公共账号列表 * @param {ResultCallback} callback [返回值,参数回调] */ RongIMClient.prototype.getPublicServiceList = function (callback) { if (RongIMClient._memoryStore.depend.openMp) { RongIMLib.CheckParam.getInstance().check(["object"], "getPublicServiceList", false, arguments); this.getRemotePublicServiceList(RongIMClient.logCallback(callback, "getPublicServiceList")); } }; /** * [getPublicServiceProfile ] 获取某公共服务信息。 * @param {PublicServiceType} publicServiceType [公众服务类型。] * @param {string} publicServiceId [公共服务 Id。] * @param {ResultCallback} callback [公共账号信息回调。] */ RongIMClient.prototype.getPublicServiceProfile = function (publicServiceType, publicServiceId, callback) { if (RongIMClient._memoryStore.depend.openMp) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "getPublicServiceProfile", false, arguments); RongIMClient._dataAccessProvider.getPublicServiceProfile(publicServiceType, publicServiceId, RongIMClient.logCallback(callback, "getPublicServiceProfile")); } }; /** * [pottingPublicSearchType ] 公众好查询类型 * @param {number} bussinessType [ 0-all 1-mp 2-mc] * @param {number} searchType [0-exact 1-fuzzy] */ RongIMClient.prototype.pottingPublicSearchType = function (bussinessType, searchType) { if (RongIMClient._memoryStore.depend.openMp) { var bits = 0; if (bussinessType == 0) { bits |= 3; if (searchType == 0) { bits |= 12; } else { bits |= 48; } } else if (bussinessType == 1) { bits |= 1; if (searchType == 0) { bits |= 8; } else { bits |= 32; } } else { bits |= 2; if (bussinessType == 0) { bits |= 4; } else { bits |= 16; } } return bits; } }; /** * [searchPublicService ]按公众服务类型搜索公众服务。 * @param {SearchType} searchType [搜索类型枚举。] * @param {string} keywords [搜索关键字。] * @param {ResultCallback} callback [搜索结果回调。] */ RongIMClient.prototype.searchPublicService = function (searchType, keywords, callback) { if (RongIMClient._memoryStore.depend.openMp) { RongIMLib.CheckParam.getInstance().check(["number", "string", "object"], "searchPublicService", false, arguments); var modules = new RongIMClient.Protobuf.SearchMpInput(); modules.setType(this.pottingPublicSearchType(0, searchType)); modules.setId(keywords); RongIMClient.bridge.queryMsg(29, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, RongIMClient.logCallback(callback, "searchPublicService"), "SearchMpOutput"); } }; /** * [searchPublicServiceByType ]按公众服务类型搜索公众服务。 * @param {PublicServiceType} publicServiceType [公众服务类型。] * @param {SearchType} searchType [搜索类型枚举。] * @param {string} keywords [搜索关键字。] * @param {ResultCallback} callback [搜索结果回调。] */ RongIMClient.prototype.searchPublicServiceByType = function (publicServiceType, searchType, keywords, callback) { if (RongIMClient._memoryStore.depend.openMp) { RongIMLib.CheckParam.getInstance().check(["number", "number", "string", "object"], "searchPublicServiceByType", false, arguments); var type = publicServiceType == RongIMLib.ConversationType.APP_PUBLIC_SERVICE ? 2 : 1; var modules = new RongIMClient.Protobuf.SearchMpInput(); modules.setType(this.pottingPublicSearchType(type, searchType)); modules.setId(keywords); RongIMClient.bridge.queryMsg(29, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, RongIMClient.logCallback(callback, "searchPublicServiceByType"), "SearchMpOutput"); } }; /** * [subscribePublicService ] 订阅公众号。 * @param {PublicServiceType} publicServiceType [公众服务类型。] * @param {string} publicServiceId [公共服务 Id。] * @param {OperationCallback} callback [订阅公众号回调。] */ RongIMClient.prototype.subscribePublicService = function (publicServiceType, publicServiceId, callback) { if (RongIMClient._memoryStore.depend.openMp) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "subscribePublicService", false, arguments); var modules = new RongIMClient.Protobuf.MPFollowInput(), me = this, follow = publicServiceType == RongIMLib.ConversationType.APP_PUBLIC_SERVICE ? "mcFollow" : "mpFollow"; modules.setId(publicServiceId); RongIMClient.bridge.queryMsg(follow, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function () { me.getRemotePublicServiceList({ onSuccess: function () { }, onError: function () { } }); callback.onSuccess(); }, onError: function (code) { var errorCode = code; RongIMClient.logger({ code: errorCode, funcName: "subscribePublicService" }); callback.onError(code); } }, "MPFollowOutput"); } }; /** * [unsubscribePublicService ] 取消订阅公众号。 * @param {PublicServiceType} publicServiceType [公众服务类型。] * @param {string} publicServiceId [公共服务 Id。] * @param {OperationCallback} callback [取消订阅公众号回调。] */ RongIMClient.prototype.unsubscribePublicService = function (publicServiceType, publicServiceId, callback) { if (RongIMClient._memoryStore.depend.openMp) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "unsubscribePublicService", false, arguments); var modules = new RongIMClient.Protobuf.MPFollowInput(), me = this, follow = publicServiceType == RongIMLib.ConversationType.APP_PUBLIC_SERVICE ? "mcUnFollow" : "mpUnFollow"; modules.setId(publicServiceId); RongIMClient.bridge.queryMsg(follow, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function () { RongIMClient._memoryStore.publicServiceMap.remove(publicServiceType, publicServiceId); callback.onSuccess(); }, onError: function (code) { var errorCode = code; RongIMClient.logger({ code: errorCode, funcName: "unsubscribePublicService" }); callback.onError(code); } }, "MPFollowOutput"); } }; // #endregion Public Service // #region Blacklist /** * [加入黑名单] * @param {string} userId [将被加入黑名单的用户Id] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.addToBlacklist = function (userId, callback) { RongIMLib.CheckParam.getInstance().check(["string|number", "object"], "addToBlacklist", false, arguments); RongIMClient._dataAccessProvider.addToBlacklist(userId, RongIMClient.logCallback(callback, "addToBlacklist")); }; /** * [获取黑名单列表] * @param {GetBlacklistCallback} callback [返回值,函数回调] */ RongIMClient.prototype.getBlacklist = function (callback) { RongIMLib.CheckParam.getInstance().check(["object"], "getBlacklist", false, arguments); RongIMClient._dataAccessProvider.getBlacklist(callback); }; /** * [得到指定人员再黑名单中的状态] * @param {string} userId [description] * @param {ResultCallback} callback [返回值,函数回调] */ //TODO 如果人员不在黑名单中,获取状态会出现异常 RongIMClient.prototype.getBlacklistStatus = function (userId, callback) { RongIMLib.CheckParam.getInstance().check(["string|number", "object"], "getBlacklistStatus", false, arguments); RongIMClient._dataAccessProvider.getBlacklistStatus(userId, RongIMClient.logCallback(callback, "getBlacklistStatus")); }; /** * [将指定用户移除黑名单] * @param {string} userId [将被移除的用户Id] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.removeFromBlacklist = function (userId, callback) { RongIMLib.CheckParam.getInstance().check(["string|number", "object"], "removeFromBlacklist", false, arguments); RongIMClient._dataAccessProvider.removeFromBlacklist(userId, RongIMClient.logCallback(callback, "removeFromBlacklist")); }; RongIMClient.prototype.getFileToken = function (fileType, callback) { RongIMLib.CheckParam.getInstance().check(["number", "object"], "getQnTkn", false, arguments); RongIMClient._dataAccessProvider.getFileToken(fileType, RongIMClient.logCallback(callback, "getFileToken")); }; RongIMClient.prototype.getFileUrl = function (fileType, fileName, oriName, callback) { RongIMLib.CheckParam.getInstance().check(["number", "string", "string|global|object|null", "object"], "getQnTkn", false, arguments); RongIMClient._dataAccessProvider.getFileUrl(fileType, fileName, oriName, RongIMClient.logCallback(callback, "getFileUrl")); }; ; // #endregion Blacklist // #region Real-time Location Service RongIMClient.prototype.addRealTimeLocationListener = function (conversationType, targetId, listener) { throw new Error("Not implemented yet"); }; RongIMClient.prototype.getRealTimeLocation = function (conversationType, targetId) { throw new Error("Not implemented yet"); }; RongIMClient.prototype.getRealTimeLocationCurrentState = function (conversationType, targetId) { throw new Error("Not implemented yet"); }; RongIMClient.prototype.getRealTimeLocationParticipants = function (conversationType, targetId) { throw new Error("Not implemented yet"); }; RongIMClient.prototype.joinRealTimeLocation = function (conversationType, targetId) { throw new Error("Not implemented yet"); }; RongIMClient.prototype.quitRealTimeLocation = function (conversationType, targetId) { throw new Error("Not implemented yet"); }; RongIMClient.prototype.startRealTimeLocation = function (conversationType, targetId) { throw new Error("Not implemented yet"); }; RongIMClient.prototype.updateRealTimeLocationStatus = function (conversationType, targetId, latitude, longitude) { throw new Error("Not implemented yet"); }; // #endregion Real-time Location Service // # startVoIP RongIMClient.prototype.startCall = function (converType, targetId, userIds, mediaType, extra, callback) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "array", "number", "string", "object"], "startCall", false, arguments); if (RongIMClient._memoryStore.voipStategy) { RongIMClient._voipProvider.startCall(converType, targetId, userIds, mediaType, extra, RongIMClient.logCallback(callback, "startCall")); } else { var errorCode = RongIMLib.ErrorCode.VOIP_NOT_AVALIABLE; RongIMClient.logger({ code: errorCode, funcName: "startCall" }); callback.onError(RongIMLib.ErrorCode.VOIP_NOT_AVALIABLE); } }; RongIMClient.prototype.joinCall = function (mediaType, callback) { RongIMLib.CheckParam.getInstance().check(['number', 'object'], "joinCall", false, arguments); if (RongIMClient._memoryStore.voipStategy) { RongIMClient._voipProvider.joinCall(mediaType, RongIMClient.logCallback(callback, "joinCall")); } else { var errorCode = RongIMLib.ErrorCode.VOIP_NOT_AVALIABLE; RongIMClient.logger({ code: errorCode, funcName: "joinCall" }); callback.onError(RongIMLib.ErrorCode.VOIP_NOT_AVALIABLE); } }; RongIMClient.prototype.hungupCall = function (converType, targetId, reason) { RongIMLib.CheckParam.getInstance().check(["number", "string", "number"], "hungupCall", false, arguments); if (RongIMClient._memoryStore.voipStategy) { RongIMClient._voipProvider.hungupCall(converType, targetId, reason); } }; RongIMClient.prototype.changeMediaType = function (converType, targetId, mediaType, callback) { RongIMLib.CheckParam.getInstance().check(["number", "string", "number", "object"], "changeMediaType", false, arguments); if (RongIMClient._memoryStore.voipStategy) { RongIMClient._voipProvider.changeMediaType(converType, targetId, mediaType, RongIMClient.logCallback(callback, "changeMediaType")); } else { var errorCode = RongIMLib.ErrorCode.VOIP_NOT_AVALIABLE; RongIMClient.logger({ code: errorCode, funcName: "changeMediaType" }); callback.onError(RongIMLib.ErrorCode.VOIP_NOT_AVALIABLE); } }; // # endVoIP RongIMClient.prototype.getUnreadMentionedMessages = function (conversationType, targetId) { return RongIMClient._dataAccessProvider.getUnreadMentionedMessages(conversationType, targetId); }; RongIMClient.prototype.clearListeners = function () { RongIMClient._dataAccessProvider.clearListeners(); }; // UserStatus start RongIMClient.prototype.getUserStatus = function (userId, callback) { RongIMClient._dataAccessProvider.getUserStatus(userId, RongIMClient.logCallback(callback, "getUserStatus")); }; RongIMClient.prototype.setUserStatus = function (status, callback) { RongIMClient._dataAccessProvider.setUserStatus(status, RongIMClient.logCallback(callback, "setUserStatus")); }; RongIMClient.prototype.setUserStatusListener = function (params, callback) { var userIds = params.userIds; var multiple = params.multiple; RongIMClient.userStatusObserver.watch({ key: userIds, func: callback, multiple: multiple }); RongIMClient._dataAccessProvider.setUserStatusListener(params, callback); }; RongIMClient.HttpProtocol = { http: 'http://', https: 'https://' }; RongIMClient.WsProtocol = { ws: 'ws://', wss: 'wss://' }; RongIMClient.LogFactory = {}; RongIMClient.MessageType = {}; RongIMClient.RegisterMessage = {}; RongIMClient._memoryStore = { listenerList: [], isPullFinished: true, syncMsgQueue: [] }; RongIMClient.isNotPullMsg = false; RongIMClient.userStatusObserver = null; RongIMClient.sdkver = '2.3.1'; RongIMClient.otherDeviceLoginCount = 0; RongIMClient.serverStore = { index: 0 }; RongIMClient.userStatusListener = null; return RongIMClient; })(); RongIMLib.RongIMClient = RongIMClient; })(RongIMLib || (RongIMLib = {})); //用于连接通道 var RongIMLib; (function (RongIMLib) { (function (Qos) { Qos[Qos["AT_MOST_ONCE"] = 0] = "AT_MOST_ONCE"; Qos[Qos["AT_LEAST_ONCE"] = 1] = "AT_LEAST_ONCE"; Qos[Qos["EXACTLY_ONCE"] = 2] = "EXACTLY_ONCE"; Qos[Qos["DEFAULT"] = 3] = "DEFAULT"; })(RongIMLib.Qos || (RongIMLib.Qos = {})); var Qos = RongIMLib.Qos; (function (Type) { Type[Type["CONNECT"] = 1] = "CONNECT"; Type[Type["CONNACK"] = 2] = "CONNACK"; Type[Type["PUBLISH"] = 3] = "PUBLISH"; Type[Type["PUBACK"] = 4] = "PUBACK"; Type[Type["QUERY"] = 5] = "QUERY"; Type[Type["QUERYACK"] = 6] = "QUERYACK"; Type[Type["QUERYCON"] = 7] = "QUERYCON"; Type[Type["SUBSCRIBE"] = 8] = "SUBSCRIBE"; Type[Type["SUBACK"] = 9] = "SUBACK"; Type[Type["UNSUBSCRIBE"] = 10] = "UNSUBSCRIBE"; Type[Type["UNSUBACK"] = 11] = "UNSUBACK"; Type[Type["PINGREQ"] = 12] = "PINGREQ"; Type[Type["PINGRESP"] = 13] = "PINGRESP"; Type[Type["DISCONNECT"] = 14] = "DISCONNECT"; })(RongIMLib.Type || (RongIMLib.Type = {})); var Type = RongIMLib.Type; var _topic = ["invtDiz", "crDiz", "qnUrl", "userInf", "dizInf", "userInf", "joinGrp", "quitDiz", "exitGrp", "evctDiz", ["", "ppMsgP", "pdMsgP", "pgMsgP", "chatMsg", "pcMsgP", "", "pmcMsgN", "pmpMsgN"], "pdOpen", "rename", "uGcmpr", "qnTkn", "destroyChrm", "createChrm", "exitChrm", "queryChrm", "joinChrm", "pGrps", "addBlack", "rmBlack", "getBlack", "blackStat", "addRelation", "qryRelation", "delRelation", "pullMp", "schMp", "qnTkn", "qnUrl", "qryVoipK", "delMsg", "qryCHMsg", "getUserStatus", "setUserStatus", "subUserStatus", "cleanHisMsg"]; var Channel = (function () { function Channel(cb, self) { this.connectionStatus = -1; var appId = self.appId; var token = encodeURIComponent(self.token); var sdkVer = self.sdkVer; var apiVer = self.apiVer; this.self = self; this.socket = Socket.getInstance().createServer(); var that = this; var storage = RongIMLib.RongIMClient._storageProvider; var servers = storage.getItem('servers'); servers = JSON.parse(servers); var startConnect = function (host) { var tpl = '{host}/websocket?appId={appId}&token={token}&sdkVer={sdkVer}&apiVer={apiVer}'; that.url = RongIMLib.RongUtil.tplEngine(tpl, { host: host, appId: appId, token: token, sdkVer: sdkVer, apiVer: apiVer }); that.socket.connect(that.url, cb); // 临时兼容 Comet 逻辑,Comet 中用到 var userId = storage.getItem('rong_current_user'); RongIMLib.Navigation.Endpoint = { host: host, userId: userId }; }; var connectMap = { ws: function () { // 所有链接计算器,超过 15 秒后认为所有 CMP 地址均不可用 var totalTimer = new RongIMLib.Timer({ timeout: 1 * 1000 * 15 }); var timers = []; var elements = []; var isFinished = false; var clearHandler = function () { for (var i = 0; i < timers.length; i++) { var timer = timers[i]; clearTimeout(timer); } for (var i = 0; i < elements.length; i++) { var el = elements[i]; document.body.removeChild(el); } }; var request = function (config, callback) { var url = config.url; var time = config.time; if (isFinished) { return; } var timer = setTimeout(function () { var el = document.createElement("script"); el.src = url; document.body.appendChild(el); el.onerror = function () { if (isFinished) { return; } clearHandler(); isFinished = true; totalTimer.pause(); var url = el.src; callback(url); }; elements.push(el); }, time); timers.push(timer); }; var snifferCallback = function (url) { var reg = /(http|https):\/\/([^\/]+)/i; var host = url.match(reg)[2]; startConnect(host); }; var snifferTpl = '{protocol}{server}/{path}'; for (var i = 0; i < servers.length; i++) { var server = RongIMLib.RongUtil.tplEngine(snifferTpl, { protocol: RongIMLib.RongIMClient.getProtocol().protocol, server: servers[i], path: i }); if (server) { request({ url: server, time: i * 1000 }, snifferCallback); } } totalTimer.resume(function () { clearHandler(); that.socket.fire("StatusChanged", RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE); }); }, comet: function () { var host = servers[0]; startConnect(host); } }; var depend = RongIMLib.RongIMClient._memoryStore.depend; var isPolling = depend.isPolling; var type = isPolling ? 'comet' : 'ws'; connectMap[type](); //注册状态改变观察者 var StatusEvent = Channel._ConnectionStatusListener; var hasEvent = (typeof StatusEvent == "object"); var me = this; me.socket.on("StatusChanged", function (code) { if (!hasEvent) { throw new Error("setConnectStatusListener:Parameter format is incorrect"); } me.connectionStatus = code; setTimeout(function () { StatusEvent.onChanged(code); }); var isDisconnected = (code == RongIMLib.ConnectionStatus.DISCONNECTED); if (isDisconnected) { self.clearHeartbeat(); } var isOtherDevice = (code == RongIMLib.ConnectionStatus.KICKED_OFFLINE_BY_OTHER_CLIENT); if (isOtherDevice) { // 累计其他设备登陆次数,超过 5 次后,自动销毁内部对象 // 删除位置:ServerDataProivder.prototype.connect RongIMLib.RongIMClient.otherDeviceLoginCount++; } }); //注册message观察者 this.socket.on("message", self.handler.handleMessage); //注册断开连接观察者 this.socket.on("disconnect", function (status) { that.socket.fire("StatusChanged", status ? status : 2); }); } Channel.prototype.writeAndFlush = function (val) { this.socket.send(val); }; Channel.prototype.reconnect = function (callback) { RongIMLib.MessageIdHandler.clearMessageId(); this.socket = this.socket.reconnect(); if (callback) { this.self.reconnectObj = callback; } }; Channel.prototype.disconnect = function (status) { this.socket.disconnect(status); }; return Channel; })(); RongIMLib.Channel = Channel; var Socket = (function () { function Socket() { this.socket = null; this._events = {}; } Socket.getInstance = function () { return new Socket(); }; Socket.prototype.connect = function (url, cb) { if (this.socket) { if (url) { RongIMLib.RongIMClient._storageProvider.setItem("rongSDK", this.checkTransport()); this.on("connect", cb || new Function); } if (url) { this.currentURL = url; } this.socket.createTransport(url); } return this; }; Socket.prototype.createServer = function () { var transport = this.getTransport(this.checkTransport()); if (transport === null) { throw new Error("the channel was not supported"); } return transport; }; Socket.prototype.getTransport = function (transportType) { if (transportType == Socket.XHR_POLLING) { this.socket = new RongIMLib.PollingTransportation(this); } else if (transportType == Socket.WEBSOCKET) { this.socket = new RongIMLib.SocketTransportation(this); } return this; }; Socket.prototype.send = function (data) { if (this.socket) { if (this.checkTransport() == Socket.WEBSOCKET) { this.socket.send(data); } else { this.socket.send(this._encode(data)); } } }; Socket.prototype.onMessage = function (data) { this.fire("message", data); }; Socket.prototype.disconnect = function (status) { this.socket.disconnect(status); this.fire("disconnect", status); return this; }; Socket.prototype.reconnect = function () { if (this.currentURL && RongIMLib.RongIMClient._storageProvider.getItem("rongSDK")) { return this.connect(this.currentURL, null); } else { throw new Error("reconnect:no have URL"); } }; /** * [checkTransport 返回通道类型] */ Socket.prototype.checkTransport = function () { if (RongIMLib.RongIMClient._memoryStore.depend.isPolling) { RongIMLib.Transportations._TransportType = Socket.XHR_POLLING; } return RongIMLib.Transportations._TransportType; }; Socket.prototype.fire = function (x, args) { if (x in this._events) { for (var i = 0, ii = this._events[x].length; i < ii; i++) { this._events[x][i](args); } } return this; }; Socket.prototype.on = function (x, func) { if (!(typeof func == "function" && x)) { return this; } if (x in this._events) { RongIMLib.MessageUtil.indexOf(this._events, func) == -1 && this._events[x].push(func); } else { this._events[x] = [func]; } return this; }; Socket.prototype.removeEvent = function (x, fn) { if (x in this._events) { for (var a = 0, l = this._events[x].length; a < l; a++) { if (this._events[x][a] == fn) { this._events[x].splice(a, 1); } } } return this; }; Socket.prototype._encode = function (x) { var str = "?messageid=" + x.getMessageId() + "&header=" + x.getHeaderFlag() + "&sessionid=" + RongIMLib.RongIMClient._storageProvider.getItem("sId" + RongIMLib.Navigation.Endpoint.userId); if (!/(PubAckMessage|QueryConMessage)/.test(x._name)) { str += "&topic=" + x.getTopic() + "&targetid=" + (x.getTargetId() || ""); } return { url: str, data: "getData" in x ? x.getData() : "" }; }; //消息通道常量,所有和通道相关判断均用 XHR_POLLING WEBSOCKET两属性 Socket.XHR_POLLING = "xhr-polling"; Socket.WEBSOCKET = "websocket"; return Socket; })(); RongIMLib.Socket = Socket; //连接端消息累 var Client = (function () { function Client(token, appId) { this.timeoutMillis = 6000; this.timeout_ = 0; this.sdkVer = ''; this.apiVer = Math.floor(Math.random() * 1e6); this.channel = null; this.handler = null; this.userId = ""; this.reconnectObj = {}; this.heartbeat = 0; this.pullMsgHearbeat = 0; this.chatroomId = ""; this.SyncTimeQueue = []; this.cacheMessageIds = []; this.token = token; this.appId = appId; this.SyncTimeQueue.state = "complete"; this.sdkVer = RongIMLib.RongIMClient.sdkver; } Client.prototype.resumeTimer = function () { var me = this; this.timeout_ = setTimeout(function () { me.channel.disconnect(); }, this.timeoutMillis); }; Client.prototype.pauseTimer = function () { if (this.timeout_) { clearTimeout(this.timeout_); this.timeout_ = 0; } }; Client.prototype.connect = function (_callback) { //实例消息处理类 this.handler = new MessageHandler(this); //设置连接回调 this.handler.setConnectCallback(_callback); //实例通道类型 var me = this; this.channel = new Channel(function () { RongIMLib.Transportations._TransportType == Socket.WEBSOCKET && me.keepLive(); }, this); //触发状态改变观察者 this.channel.socket.fire("StatusChanged", RongIMLib.ConnectionStatus.CONNECTING); //没有返回地址就手动抛出错误 //_callback.onError(ConnectionState.NOT_AUTHORIZED); }; Client.prototype.checkSocket = function (callback) { var me = this; me.channel.writeAndFlush(new RongIMLib.PingReqMessage()); var count = 0; var checkTimeout = setInterval(function () { if (!RongIMLib.RongIMClient._memoryStore.isFirstPingMsg) { clearInterval(checkTimeout); callback.onSuccess(); } else { if (count > 15) { clearInterval(checkTimeout); callback.onError(); } } count++; }, 100); }; Client.prototype.keepLive = function () { if (this.heartbeat > 0) { clearInterval(this.heartbeat); } var me = this; me.heartbeat = setInterval(function () { me.resumeTimer(); me.channel.writeAndFlush(new RongIMLib.PingReqMessage()); }, 30000); if (me.pullMsgHearbeat > 0) { clearInterval(me.pullMsgHearbeat); } me.pullMsgHearbeat = setInterval(function () { me.syncTime(true, undefined, undefined, false); }, 180000); }; Client.prototype.clearHeartbeat = function () { clearInterval(this.heartbeat); this.heartbeat = 0; this.pauseTimer(); clearInterval(this.pullMsgHearbeat); this.pullMsgHearbeat = 0; }; Client.prototype.publishMessage = function (_topic, _data, _targetId, _callback, _msg) { var msgId = RongIMLib.MessageIdHandler.messageIdPlus(this.channel.reconnect); if (!msgId) { return; } var msg = new RongIMLib.PublishMessage(_topic, _data, _targetId); msg.setMessageId(msgId); if (_callback) { msg.setQos(Qos.AT_LEAST_ONCE); this.handler.putCallback(new RongIMLib.PublishCallback(_callback.onSuccess, _callback.onError), msg.getMessageId(), _msg); } else { msg.setQos(Qos.AT_MOST_ONCE); } this.channel.writeAndFlush(msg); }; Client.prototype.queryMessage = function (_topic, _data, _targetId, _qos, _callback, pbtype) { if (_topic == "userInf") { if (Client.userInfoMapping[_targetId]) { _callback.onSuccess(Client.userInfoMapping[_targetId]); return; } } var msgId = RongIMLib.MessageIdHandler.messageIdPlus(this.channel.reconnect); if (!msgId) { return; } var msg = new RongIMLib.QueryMessage(_topic, _data, _targetId); msg.setMessageId(msgId); msg.setQos(_qos); this.handler.putCallback(new RongIMLib.QueryCallback(_callback.onSuccess, _callback.onError), msg.getMessageId(), pbtype); this.channel.writeAndFlush(msg); }; Client.prototype.invoke = function (isPullMsg, chrmId, offlineMsg) { var time, modules, str, me = this, target, temp = this.SyncTimeQueue.shift(); if (temp == undefined) { return; } this.SyncTimeQueue.state = "pending"; if (temp.type != 2) { //普通消息 time = RongIMLib.RongIMClient._storageProvider.getItem(this.userId) || '0'; modules = new RongIMLib.RongIMClient.Protobuf.SyncRequestMsg(); modules.setIspolling(false); str = "pullMsg"; target = this.userId; } else { //聊天室消息 target = temp.chrmId || me.chatroomId; time = RongIMLib.RongIMClient._memoryStore.lastReadTime.get(target + Bridge._client.userId + "CST") || 0; modules = new RongIMLib.RongIMClient.Protobuf.ChrmPullMsg(); modules.setCount(0); str = "chrmPull"; if (!target) { throw new Error("syncTime:Received messages of chatroom but was not init"); } } //判断服务器给的时间是否消息本地存储的时间,小于的话不执行拉取操作,进行一下步队列操作 if (temp.pulltime <= time) { this.SyncTimeQueue.state = "complete"; this.invoke(isPullMsg, target); return; } if (isPullMsg && 'setIsPullSend' in modules) { modules.setIsPullSend(true); } modules.setSyncTime(time); //发送queryMessage请求 this.queryMessage(str, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), target, Qos.AT_LEAST_ONCE, { onSuccess: function (collection) { var sync = RongIMLib.MessageUtil.int64ToTimestamp(collection.syncTime), symbol = target; //把返回时间戳存入本地,普通消息key为userid,聊天室消息key为userid+'CST';value都为服务器返回的时间戳 if (str == "chrmPull") { symbol += Bridge._client.userId + "CST"; RongIMLib.RongIMClient._memoryStore.lastReadTime.set(symbol, sync); } else { var storage = RongIMLib.RongIMClient._storageProvider; if (sync > storage.getItem(symbol)) { storage.setItem(symbol, sync); } } //防止因离线消息造成会话列表不为空而无法从服务器拉取会话列表。 //offlineMsg && (RongIMClient._memoryStore.isSyncRemoteConverList = true); me.SyncTimeQueue.state = "complete"; me.invoke(isPullMsg, target); //把拉取到的消息逐条传给消息监听器 var list = collection.list; for (var i = 0, len = list.length, count = len; i < len; i++) { if (!(list[i].msgId in me.cacheMessageIds)) { count -= 1; var message = list[i]; var sentTime = RongIMLib.MessageUtil.int64ToTimestamp(message.dataTime); if (sentTime > time) { Bridge._client.handler.onReceived(message, undefined, offlineMsg, count); var arrLen = me.cacheMessageIds.unshift(list[i].msgId); if (arrLen > 20) { me.cacheMessageIds.length = 20; } } } } var isPullFinished = collection.finished; RongIMLib.RongIMClient._memoryStore.isPullFinished = isPullFinished; }, onError: function (error) { me.SyncTimeQueue.state = "complete"; me.invoke(isPullMsg, target); } }, "DownStreamMessages"); }; Client.prototype.syncTime = function (_type, pullTime, chrmId, offlineMsg) { this.SyncTimeQueue.push({ type: _type, pulltime: pullTime, chrmId: chrmId }); //如果队列中只有一个成员并且状态已经完成就执行invoke方法 if (this.SyncTimeQueue.length == 1 && this.SyncTimeQueue.state == "complete") { this.invoke(!_type, chrmId, offlineMsg); } }; Client.prototype.__init = function (f) { this.channel = new Channel(f, this); }; Client.userInfoMapping = {}; return Client; })(); RongIMLib.Client = Client; //连接类,实现imclient与connect_client的连接 var Bridge = (function () { function Bridge() { } Bridge.getInstance = function () { return new Bridge(); }; //连接服务器 Bridge.prototype.connect = function (appKey, token, callback) { if (!RongIMLib.RongIMClient.Protobuf) { return; } Bridge._client = new RongIMLib.Navigation().connect(appKey, token, callback); return Bridge._client; }; Bridge.prototype.setListener = function (_changer) { if (typeof _changer == "object") { if (typeof _changer.onChanged == "function") { Channel._ConnectionStatusListener = _changer; } else if (typeof _changer.onReceived == "function") { Channel._ReceiveMessageListener = _changer; } } }; Bridge.prototype.reconnect = function (callabck) { Bridge._client.channel.reconnect(callabck); }; Bridge.prototype.disconnect = function () { Bridge._client.channel.disconnect(2); }; //执行queryMessage请求 Bridge.prototype.queryMsg = function (topic, content, targetId, callback, pbname) { if (typeof topic != "string") { topic = _topic[topic]; } Bridge._client.queryMessage(topic, content, targetId, Qos.AT_MOST_ONCE, callback, pbname); }; //发送消息 执行publishMessage 请求 Bridge.prototype.pubMsg = function (topic, content, targetId, callback, msg, methodType) { if (typeof methodType == 'number') { if (methodType == RongIMLib.MethodType.CUSTOMER_SERVICE) { Bridge._client.publishMessage("pcuMsgP", content, targetId, callback, msg); } else if (methodType == RongIMLib.MethodType.RECALL) { Bridge._client.publishMessage("recallMsg", content, targetId, callback, msg); } } else { Bridge._client.publishMessage(_topic[10][topic], content, targetId, callback, msg); } }; return Bridge; })(); RongIMLib.Bridge = Bridge; var MessageHandler = (function () { function MessageHandler(client) { this.map = {}; this.connectCallback = null; if (!Channel._ReceiveMessageListener) { throw new Error("please set onReceiveMessageListener"); } this._onReceived = Channel._ReceiveMessageListener.onReceived; this._client = client; this.syncMsgMap = new Object; } //把对象推入回调对象队列中,并启动定时器 MessageHandler.prototype.putCallback = function (callbackObj, _publishMessageId, _msg) { var item = { Callback: callbackObj, Message: _msg }; item.Callback.resumeTimer(); this.map[_publishMessageId] = item; }; //设置连接回调对象,启动定时器 MessageHandler.prototype.setConnectCallback = function (_connectCallback) { if (_connectCallback) { this.connectCallback = new RongIMLib.ConnectAck(_connectCallback.onSuccess, _connectCallback.onError, this._client); } }; MessageHandler.prototype.onReceived = function (msg, pubAckItem, offlineMsg, leftCount, isSync) { //实体对象 var entity, //解析完成的消息对象 message, //会话对象 con; if (msg._name != "PublishMessage") { entity = msg; RongIMLib.RongIMClient._storageProvider.setItem(this._client.userId, RongIMLib.MessageUtil.int64ToTimestamp(entity.dataTime)); } else { if (msg.getTopic() == "s_ntf") { entity = RongIMLib.RongIMClient.Protobuf.NotifyMsg.decode(msg.getData()); this._client.syncTime(entity.type, RongIMLib.MessageUtil.int64ToTimestamp(entity.time), entity.chrmId); return; } else if (msg.getTopic() == "s_msg") { entity = RongIMLib.RongIMClient.Protobuf.DownStreamMessage.decode(msg.getData()); var timestamp = RongIMLib.MessageUtil.int64ToTimestamp(entity.dataTime); RongIMLib.RongIMClient._storageProvider.setItem(this._client.userId, timestamp); RongIMLib.RongIMClient._memoryStore.lastReadTime.get(this._client.userId, timestamp); } else if (msg.getTopic() == "s_stat") { entity = RongIMLib.RongIMClient.Protobuf.GetUserStatusOutput.decode(msg.getData()); entity = RongIMLib.RongInnerTools.convertUserStatus(entity); RongIMLib.RongIMClient.userStatusObserver.notify({ key: entity.userId, entity: entity }); return; } else { if (Bridge._client.sdkVer && Bridge._client.sdkVer == "1.0.0") { return; } if (!RongIMLib.RongIMClient._memoryStore.isPullFinished) { return; } entity = RongIMLib.RongIMClient.Protobuf.UpStreamMessage.decode(msg.getData()); var tmpTopic = msg.getTopic(); var tmpType = tmpTopic.substr(0, 2); if (tmpType == "pp") { entity.type = 1; } else if (tmpType == "pd") { entity.type = 2; } else if (tmpType == "pg") { entity.type = 3; } else if (tmpType == "ch") { entity.type = 4; } else if (tmpType == "pc") { entity.type = 5; } //复用字段,targetId 以此为准 entity.groupId = msg.getTargetId(); entity.fromUserId = this._client.userId; entity.dataTime = Date.parse(new Date().toString()); } if (!entity) { return; } } //解析实体对象为消息对象。 message = RongIMLib.MessageUtil.messageParser(entity, this._onReceived, offlineMsg); var isRecall = (msg.getTopic && msg.getTopic() == "recallMsg"); if (isRecall) { var content = message.content; message.conversationType = content.conversationType; message.targetId = content.targetId; message.messageId = null; } if (pubAckItem) { message.messageUId = pubAckItem.getMessageUId(); message.sentTime = pubAckItem.getTimestamp(); RongIMLib.RongIMClient._storageProvider.setItem(this._client.userId, message.sentTime); } if (message === null) { return; } var isSend = (message.messageDirection == RongIMLib.MessageDirection.SEND); if (isSend) { var storageProvider = RongIMLib.RongIMClient._storageProvider; var userId = RongIMLib.Bridge._client.userId; var lastSentTime = storageProvider.getItem('last_sentTime_' + userId) || 0; if (message.sentTime <= lastSentTime && !isSync) { return; } } // 设置会话时间戳并且判断是否传递 message 发送消息未处理会话时间戳 // key:'converST_' + 当前用户 + conversationType + targetId // RongIMClient._storageProvider.setItem('converST_' + Bridge._client.userId + message.conversationType + message.targetId, message.sentTime); var msgTag = RongIMLib.RongIMClient.MessageParams[message.messageType].msgTag; var isPersited = msgTag.isPersited; if (isPersited) { RongIMLib.RongIMClient._dataAccessProvider.getConversation(message.conversationType, message.targetId, { onSuccess: function (con) { if (!con) { con = RongIMLib.RongIMClient.getInstance().createConversation(message.conversationType, message.targetId, ""); } if (message.messageDirection == RongIMLib.MessageDirection.RECEIVE && (entity.status & 64) == 64) { var mentioneds = RongIMLib.RongIMClient._storageProvider.getItem("mentioneds_" + Bridge._client.userId + '_' + message.conversationType + '_' + message.targetId); var key = message.conversationType + '_' + message.targetId, info = {}; if (message.content && message.content.mentionedInfo) { info[key] = { uid: message.messageUId, time: message.sentTime, mentionedInfo: message.content.mentionedInfo }; RongIMLib.RongIMClient._storageProvider.setItem("mentioneds_" + Bridge._client.userId + '_' + message.conversationType + '_' + message.targetId, JSON.stringify(info)); mentioneds = JSON.stringify(info); } if (mentioneds) { var info = JSON.parse(mentioneds); con.mentionedMsg = info[key]; } } // var isCounted = con.conversationType != 0 && message.senderUserId != Bridge._client.userId && message.receivedStatus != RongIMLib.ReceivedStatus.RETRIEVED && message.messageType != RongIMLib.RongIMClient.MessageType["ReadReceiptRequestMessage"] && message.messageType != RongIMLib.RongIMClient.MessageType["ReadReceiptResponseMessage"] var isReceiver = message.messageDirection == 2; if (isReceiver && msgTag.getMessageTag() > 0) { con.unreadMessageCount = con.unreadMessageCount + 1; if (RongIMLib.RongUtil.supportLocalStorage()) { var count = RongIMLib.RongIMClient._storageProvider.getItem("cu" + Bridge._client.userId + con.conversationType + con.targetId); // 与本地存储会话合并 RongIMLib.RongIMClient._storageProvider.setItem("cu" + Bridge._client.userId + con.conversationType + message.targetId, Number(count) + 1); } } con.receivedTime = new Date().getTime(); con.receivedStatus = message.receivedStatus; con.senderUserId = message.sendUserId; con.notificationStatus = RongIMLib.ConversationNotificationStatus.DO_NOT_DISTURB; con.latestMessageId = message.messageId; con.latestMessage = message; con.sentTime = message.sentTime; RongIMLib.RongIMClient._dataAccessProvider.addConversation(con, { onSuccess: function (data) { }, onError: function () { } }); }, onError: function (error) { } }); } if (message.conversationType == RongIMLib.ConversationType.CUSTOMER_SERVICE && (message.messageType == "ChangeModeResponseMessage" || message.messageType == "SuspendMessage" || message.messageType == "HandShakeResponseMessage" || message.messageType == "TerminateMessage" || message.messageType == "CustomerStatusUpdateMessage" || message.messageType == "TextMessage" || message.messageType == "InformationNotificationMessage")) { if (!RongIMLib.RongIMClient._memoryStore.custStore["isInit"]) { return; } } if (message.conversationType == RongIMLib.ConversationType.CUSTOMER_SERVICE && message.messageType != "HandShakeResponseMessage") { if (!RongIMLib.RongIMClient._memoryStore.custStore[message.targetId]) { return; } if (message.messageType == "TerminateMessage") { if (RongIMLib.RongIMClient._memoryStore.custStore[message.targetId].sid != message.content.sid) { return; } } } if (message.messageType === RongIMLib.RongIMClient.MessageType["HandShakeResponseMessage"]) { var session = message.content.data; RongIMLib.RongIMClient._memoryStore.custStore[message.targetId] = session; if (session.serviceType == RongIMLib.CustomerType.ONLY_HUMAN || session.serviceType == RongIMLib.CustomerType.HUMAN_FIRST) { if (session.notAutoCha == "1") { RongIMLib.RongIMClient.getInstance().switchToHumanMode(message.targetId, { onSuccess: function () { }, onError: function () { } }); } } } var d = new Date(), m = d.getMonth() + 1, date = d.getFullYear() + '/' + (m.toString().length == 1 ? '0' + m : m) + '/' + d.getDate(); //new Date(date).getTime() - message.sentTime < 1 逻辑判断 超过 1 天未收的 ReadReceiptRequestMessage 离线消息自动忽略。 var dealtime = new Date(date).getTime() - message.sentTime < 0; if (RongIMLib.RongUtil.supportLocalStorage() && message.messageType === RongIMLib.RongIMClient.MessageType["ReadReceiptRequestMessage"] && dealtime && message.messageDirection == RongIMLib.MessageDirection.SEND) { var sentkey = Bridge._client.userId + message.content.messageUId + "SENT"; RongIMLib.RongIMClient._storageProvider.setItem(sentkey, JSON.stringify({ count: 0, dealtime: message.sentTime, userIds: {} })); } else if (RongIMLib.RongUtil.supportLocalStorage() && message.messageType === RongIMLib.RongIMClient.MessageType["ReadReceiptRequestMessage"] && dealtime) { var reckey = Bridge._client.userId + message.conversationType + message.targetId + 'RECEIVED', recData = JSON.parse(RongIMLib.RongIMClient._storageProvider.getItem(reckey)); if (recData) { if (message.senderUserId in recData) { if (recData[message.senderUserId].uIds && recData[message.senderUserId].uIds && recData[message.senderUserId].uIds.indexOf(message.content.messageUId) == -1) { recData[message.senderUserId].uIds.push(message.content.messageUId); recData[message.senderUserId].dealtime = message.sentTime; recData[message.senderUserId].isResponse = false; RongIMLib.RongIMClient._storageProvider.setItem(reckey, JSON.stringify(recData)); } else { return; } } else { var objSon = { uIds: [message.content.messageUId], dealtime: message.sentTime, isResponse: false }; recData[message.senderUserId] = objSon; RongIMLib.RongIMClient._storageProvider.setItem(reckey, JSON.stringify(recData)); } } else { var obj = {}; obj[message.senderUserId] = { uIds: [message.content.messageUId], dealtime: message.sentTime, isResponse: false }; RongIMLib.RongIMClient._storageProvider.setItem(reckey, JSON.stringify(obj)); } } if (RongIMLib.RongUtil.supportLocalStorage() && message.messageType === RongIMLib.RongIMClient.MessageType["ReadReceiptResponseMessage"] && dealtime) { var receiptResponseMsg = message.content, uIds = receiptResponseMsg.receiptMessageDic[Bridge._client.userId], sentkey = "", sentObj; message.receiptResponse || (message.receiptResponse = {}); if (uIds) { var cbuIds = []; for (var i = 0, len = uIds.length; i < len; i++) { sentkey = Bridge._client.userId + uIds[i] + "SENT"; sentObj = JSON.parse(RongIMLib.RongIMClient._storageProvider.getItem(sentkey)); if (sentObj && !(message.senderUserId in sentObj.userIds)) { cbuIds.push(uIds[i]); sentObj.count += 1; sentObj.userIds[message.senderUserId] = message.sentTime; message.receiptResponse[uIds[i]] = sentObj.count; RongIMLib.RongIMClient._storageProvider.setItem(sentkey, JSON.stringify(sentObj)); } } receiptResponseMsg.receiptMessageDic[Bridge._client.userId] = cbuIds; message.content = receiptResponseMsg; } } var that = this; if (RongIMLib.RongIMClient._voipProvider && ['AcceptMessage', 'RingingMessage', 'HungupMessage', 'InviteMessage', 'MediaModifyMessage', 'MemberModifyMessage'].indexOf(message.messageType) > -1) { setTimeout(function () { RongIMLib.RongIMClient._voipProvider.onReceived(message); }); } else { var lcount = leftCount || 0; // TODO: Web 暂时未获取是否还有更多离线消息,所以复制 false 默认没有更多离线消息 var hasMore = false; RongIMLib.RongIMClient._dataAccessProvider.addMessage(message.conversationType, message.targetId, message, { onSuccess: function (ret) { setTimeout(function () { that._onReceived(ret, lcount, hasMore); }); }, onError: function (error) { setTimeout(function () { that._onReceived(message, lcount, hasMore); }); } }); } }; MessageHandler.prototype.handleMessage = function (msg) { if (!msg) { return; } switch (msg._name) { case "ConnAckMessage": Bridge._client.handler.connectCallback.process(msg.getStatus(), msg.getUserId(), msg.getTimestamp()); break; case "PublishMessage": if (!msg.getSyncMsg() && msg.getQos() != 0) { Bridge._client.channel.writeAndFlush(new RongIMLib.PubAckMessage(msg.getMessageId())); } // TODO && -> if (msg.getSyncMsg() && !RongIMLib.RongIMClient._memoryStore.depend.isPolling) { Bridge._client.handler.syncMsgMap[msg.getMessageId()] = msg; } else { //如果是PublishMessage就把该对象给onReceived方法执行处理 Bridge._client.handler.onReceived(msg); } break; case "QueryAckMessage": if (msg.getQos() != 0) { Bridge._client.channel.writeAndFlush(new RongIMLib.QueryConMessage(msg.getMessageId())); } var temp = Bridge._client.handler.map[msg.getMessageId()]; if (temp) { //执行回调操作 temp.Callback.process(msg.getStatus(), msg.getData(), msg.getDate(), temp.Message); delete Bridge._client.handler.map[msg.getMessageId()]; } break; case "PubAckMessage": var item = Bridge._client.handler.map[msg.getMessageId()]; if (item) { item.Callback.process(msg.getStatus() || 0, msg.getMessageUId(), msg.getTimestamp(), item.Message, msg.getMessageId()); delete Bridge._client.handler.map[msg.getMessageId()]; } else { var userId = RongIMLib.Bridge._client.userId; RongIMLib.RongIMClient._storageProvider.setItem('last_sentTime_' + userId, msg.timestamp); Bridge._client.handler.onReceived(Bridge._client.handler.syncMsgMap[msg.messageId], msg, null, null, true); delete Bridge._client.handler.syncMsgMap[msg.getMessageId()]; } break; case "PingRespMessage": if (RongIMLib.RongIMClient._memoryStore.isFirstPingMsg) { RongIMLib.RongIMClient._memoryStore.isFirstPingMsg = false; } else { Bridge._client.pauseTimer(); } break; case "DisconnectMessage": Bridge._client.channel.disconnect(msg.getStatus()); break; default: } }; return MessageHandler; })(); RongIMLib.MessageHandler = MessageHandler; })(RongIMLib || (RongIMLib = {})); var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; /// var RongIMLib; (function (RongIMLib) { var MessageCallback = (function () { function MessageCallback(error) { this.timeout = null; this.onError = null; if (error && typeof error == "number") { this.timeoutMillis = error; } else { this.timeoutMillis = 30000; this.onError = error; } } MessageCallback.prototype.resumeTimer = function () { var me = this; if (this.timeoutMillis > 0 && !this.timeout) { this.timeout = setTimeout(function () { me.readTimeOut(true); }, this.timeoutMillis); } }; MessageCallback.prototype.pauseTimer = function () { if (this.timeout) { clearTimeout(this.timeout); this.timeout = null; } }; MessageCallback.prototype.readTimeOut = function (isTimeout) { if (isTimeout && this.onError) { this.onError(RongIMLib.ErrorCode.TIMEOUT); } else { this.pauseTimer(); } }; return MessageCallback; })(); RongIMLib.MessageCallback = MessageCallback; var CallbackMapping = (function () { function CallbackMapping() { this.publicServiceList = []; } CallbackMapping.getInstance = function () { return new CallbackMapping(); }; CallbackMapping.prototype.pottingProfile = function (item) { var temp; this.profile = new RongIMLib.PublicServiceProfile(); temp = JSON.parse(item.extra); this.profile.isGlobal = temp.isGlobal; this.profile.introduction = temp.introduction; this.profile.menu = temp.menu; this.profile.hasFollowed = temp.follow; this.profile.publicServiceId = item.mpid; this.profile.name = item.name; this.profile.portraitUri = item.portraitUrl; this.profile.conversationType = item.type == "mc" ? RongIMLib.ConversationType.APP_PUBLIC_SERVICE : RongIMLib.ConversationType.PUBLIC_SERVICE; this.publicServiceList.push(this.profile); }; CallbackMapping.prototype.mapping = function (entity, tag) { switch (tag) { case "GetUserInfoOutput": var userInfo = new RongIMLib.UserInfo(entity.userId, entity.userName, entity.userPortrait); return userInfo; case "GetQNupTokenOutput": return { deadline: RongIMLib.MessageUtil.int64ToTimestamp(entity.deadline), token: entity.token }; case "GetQNdownloadUrlOutput": return { downloadUrl: entity.downloadUrl }; case "CreateDiscussionOutput": return entity.id; case "ChannelInfoOutput": var disInfo = new RongIMLib.Discussion(); disInfo.creatorId = entity.adminUserId; disInfo.id = entity.channelId; disInfo.memberIdList = entity.firstTenUserIds; disInfo.name = entity.channelName; disInfo.isOpen = entity.openStatus; return disInfo; case "GroupHashOutput": return entity.result; case "QueryBlackListOutput": return entity.userIds; case "SearchMpOutput": case "PullMpOutput": if (entity.info) { var self = this; Array.forEach(entity.info, function (item) { setTimeout(self.pottingProfile(item), 100); }); } return this.publicServiceList; default: return entity; } }; return CallbackMapping; })(); RongIMLib.CallbackMapping = CallbackMapping; var PublishCallback = (function (_super) { __extends(PublishCallback, _super); function PublishCallback(_cb, _timeout) { _super.call(this, _timeout); this._cb = _cb; this._timeout = _timeout; } PublishCallback.prototype.process = function (_status, messageUId, timestamp, _msg, messageId) { this.readTimeOut(); if (_status == 0 || _status == 21502) { if (_msg) { _msg.setSentStatus = _status; } var userId = RongIMLib.Bridge._client.userId; var stroageProvider = RongIMLib.RongIMClient._storageProvider; stroageProvider.setItem(userId, timestamp); stroageProvider.setItem('last_sentTime_' + userId, timestamp); RongIMLib.RongIMClient._memoryStore.lastReadTime.get(userId, timestamp); this._cb({ messageUId: messageUId, timestamp: timestamp, messageId: messageId }, _status); } else { this._timeout(_status, { messageUId: messageUId, timestamp: timestamp, messageId: messageId }); } }; PublishCallback.prototype.readTimeOut = function (x) { MessageCallback.prototype.readTimeOut.call(this, x); }; return PublishCallback; })(MessageCallback); RongIMLib.PublishCallback = PublishCallback; var QueryCallback = (function (_super) { __extends(QueryCallback, _super); function QueryCallback(_cb, _timeout) { _super.call(this, _timeout); this._cb = _cb; this._timeout = _timeout; } QueryCallback.prototype.process = function (status, data, serverTime, pbtype) { this.readTimeOut(); if (pbtype && data && status == 0) { try { data = CallbackMapping.getInstance().mapping(RongIMLib.RongIMClient.Protobuf[pbtype].decode(data), pbtype); } catch (e) { this._timeout(RongIMLib.ErrorCode.UNKNOWN); return; } if ("GetUserInfoOutput" == pbtype) { //pb类型为GetUserInfoOutput的话就把data放入userinfo缓存队列 RongIMLib.Client.userInfoMapping[data.userId] = data; } this._cb(data); } else { status > 0 ? this._timeout(status) : this._cb(status); } }; QueryCallback.prototype.readTimeOut = function (x) { MessageCallback.prototype.readTimeOut.call(this, x); }; return QueryCallback; })(MessageCallback); RongIMLib.QueryCallback = QueryCallback; var ConnectAck = (function (_super) { __extends(ConnectAck, _super); function ConnectAck(_cb, _timeout, client) { _super.call(this, _timeout); this._client = client; this._cb = _cb; this._timeout = _timeout; } ConnectAck.prototype.process = function (status, userId, timestamp) { this.readTimeOut(); if (status == 0) { this._client.userId = userId; var self = this; if (!RongIMLib.RongIMClient._memoryStore.depend.isPolling && RongIMLib.RongIMClient._memoryStore.isFirstPingMsg) { RongIMLib.Bridge._client.checkSocket({ onSuccess: function () { if (!RongIMLib.RongIMClient.isNotPullMsg) { self._client.syncTime(undefined, undefined, undefined, true); } }, onError: function () { RongIMLib.RongIMClient._memoryStore.isFirstPingMsg = false; RongIMLib.RongIMClient.getInstance().disconnect(); RongIMLib.RongIMClient.connect(RongIMLib.RongIMClient._memoryStore.token, RongIMLib.RongIMClient._memoryStore.callback); } }); } else { if (!RongIMLib.RongIMClient.isNotPullMsg) { self._client.syncTime(undefined, undefined, undefined, true); } } if (this._client.reconnectObj.onSuccess) { this._client.reconnectObj.onSuccess(userId); delete this._client.reconnectObj.onSuccess; } else { var me = this; setTimeout(function () { me._cb(userId); }, 500); } RongIMLib.Bridge._client.channel.socket.fire("StatusChanged", 0); RongIMLib.RongIMClient._memoryStore.connectAckTime = timestamp; if (!(new Date().getTime() - timestamp)) { RongIMLib.RongIMClient._memoryStore.deltaTime = 0; } else { RongIMLib.RongIMClient._memoryStore.deltaTime = new Date().getTime() - timestamp; } } else if (status == 6) { //重定向 连错 CMP var x = {}; var me = this; new RongIMLib.Navigation().getServerEndpoint(this._client.token, this._client.appId, function () { me._client.clearHeartbeat(); new RongIMLib.Client(me._client.token, me._client.appId).__init.call(x, function () { RongIMLib.Transportations._TransportType == "websocket" && me._client.keepLive(); }); me._client.channel.socket.fire("StatusChanged", 2); }, me._timeout, false); } else { RongIMLib.Bridge._client.channel.socket.socket._status = status; if (this._client.reconnectObj.onError) { this._client.reconnectObj.onError(status); delete this._client.reconnectObj.onError; } else { this._timeout(status); } } }; ConnectAck.prototype.readTimeOut = function (x) { MessageCallback.prototype.readTimeOut.call(this, x); }; return ConnectAck; })(MessageCallback); RongIMLib.ConnectAck = ConnectAck; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var Navigation = (function () { function Navigation() { window.getServerEndpoint = function (result) { var storage = RongIMLib.RongIMClient._storageProvider; var successNavi = RongIMLib.RongIMClient._memoryStore.depend.navi; var successNaviProtocol = RongIMLib.RongUtil.getUrlProtocol(successNavi); RongIMLib.RongIMClient.setProtocol(successNaviProtocol); storage.setItem('navprotocol', successNaviProtocol); var server = result.server; if (server) { server += ','; } var backupServer = result.backupServer || ''; var tpl = '{server}{backupServer}'; var servers = RongIMLib.RongUtil.tplEngine(tpl, { server: server, backupServer: backupServer }); servers = servers.split(','); storage.setItem('servers', JSON.stringify(servers)); var token = RongIMLib.Bridge._client.token; var uid = RongIMLib.InnerUtil.getUId(token); storage.setItem('rc_uid', uid); var userId = result.userId; storage.setItem('current_user', userId); if (result.voipCallInfo) { var callInfo = JSON.parse(result.voipCallInfo); RongIMLib.RongIMClient._memoryStore.voipStategy = callInfo.strategy; storage.setItem("voipStrategy", callInfo.strategy); } //替换本地存储的导航信息 var openMp = result.openMp; storage.setItem('openMp' + uid, openMp); RongIMLib.RongIMClient._memoryStore.depend.openMp = openMp; }; } Navigation.clear = function () { var storage = RongIMLib.RongIMClient._storageProvider; storage.removeItem('rc_uid'); storage.removeItem('serverIndex'); }; Navigation.prototype.connect = function (appId, token, callback) { var oldAppId = RongIMLib.RongIMClient._storageProvider.getItem("appId"); //如果appid和本地存储的不一样,清空所有本地存储数据 if (oldAppId && oldAppId != appId) { RongIMLib.RongIMClient._storageProvider.clearItem(); RongIMLib.RongIMClient._storageProvider.setItem("appId", appId); } if (!oldAppId) { RongIMLib.RongIMClient._storageProvider.setItem("appId", appId); } var client = new RongIMLib.Client(token, appId); var me = this; this.getServerEndpoint(token, appId, function () { client.connect(callback); }, callback.onError, true); return client; }; Navigation.prototype.getServerEndpoint = function (token, appId, _onsuccess, _onerror, unignore) { if (unignore) { //根据token生成MD5截取8-16下标的数据与本地存储的导航信息进行比对 //如果信息和上次的通道类型都一样,不执行navi请求,用本地存储的导航信息连接服务器 var uId = md5(token).slice(8, 16); var storage = RongIMLib.RongIMClient._storageProvider; var transportType = storage.getItem("rongSDK"); var isSameType = (RongIMLib.Transportations._TransportType == transportType); var _old = storage.getItem('rc_uid'); var isSameUser = (_old == uId); if (isSameUser && isSameType) { RongIMLib.RongIMClient._memoryStore.voipStategy = storage.getItem("voipStrategy"); var openMp = storage.getItem('openMp' + uId); RongIMLib.RongIMClient._memoryStore.depend.openMp = openMp; var storageProtocol = storage.getItem('navprotocol'); storageProtocol && RongIMLib.RongIMClient.setProtocol(storageProtocol); setTimeout(function () { _onsuccess(); }, 300); return; } } Navigation.clear(); //导航信息,切换Url对象的key进行线上线下测试操作 var xss = document.createElement("script"); //进行jsonp请求 var depend = RongIMLib.RongIMClient._memoryStore.depend; var domain = depend.navi; var path = (depend.isPolling ? 'cometnavi' : 'navi'); token = encodeURIComponent(token); var sdkver = RongIMLib.RongIMClient.sdkver; var tpl = '{domain}/{path}.js?appId={appId}&token={token}&callBack=getServerEndpoint&v={sdkver}'; var url = RongIMLib.RongUtil.tplEngine(tpl, { domain: domain, path: path, appId: appId, token: token, sdkver: sdkver }); xss.src = url; document.body.appendChild(xss); xss.onerror = function () { _onerror(RongIMLib.ConnectionState.TOKEN_INCORRECT); }; if ("onload" in xss) { xss.onload = _onsuccess; } else { xss.onreadystatechange = function () { xss.readyState == "loaded" && _onsuccess(); }; } }; Navigation.Endpoint = new Object; return Navigation; })(); RongIMLib.Navigation = Navigation; })(RongIMLib || (RongIMLib = {})); // TODO: 统一变量、方法等命名规范 var RongIMLib; (function (RongIMLib) { /** * 消息基类 */ var BaseMessage = (function () { function BaseMessage(arg) { this._name = "BaseMessage"; this.lengthSize = 0; if (arg instanceof RongIMLib.Header) { this._header = arg; } else { this._header = new RongIMLib.Header(arg, false, RongIMLib.Qos.AT_MOST_ONCE, false); } } BaseMessage.prototype.read = function (In, length) { this.readMessage(In, length); }; BaseMessage.prototype.write = function (Out) { var binaryHelper = new RongIMLib.BinaryHelper(); var out = binaryHelper.convertStream(Out); this._headerCode = this.getHeaderFlag(); out.write(this._headerCode); this.writeMessage(out); return out; }; BaseMessage.prototype.getHeaderFlag = function () { return this._header.encode(); }; BaseMessage.prototype.getLengthSize = function () { return this.lengthSize; }; BaseMessage.prototype.toBytes = function () { return this.write([]).getBytesArray(); }; BaseMessage.prototype.isRetained = function () { return this._header.retain; }; BaseMessage.prototype.setRetained = function (retain) { this._header.retain = retain; }; BaseMessage.prototype.setQos = function (qos) { this._header.qos = Object.prototype.toString.call(qos) == "[object Object]" ? qos : RongIMLib.Qos[qos]; }; BaseMessage.prototype.setDup = function (dup) { this._header.dup = dup; }; BaseMessage.prototype.isDup = function () { return this._header.dup; }; BaseMessage.prototype.getType = function () { return this._header.type; }; BaseMessage.prototype.getQos = function () { return this._header.qos; }; BaseMessage.prototype.messageLength = function () { return 0; }; BaseMessage.prototype.writeMessage = function (out) { }; BaseMessage.prototype.readMessage = function (In, length) { }; BaseMessage.prototype.init = function (args) { var valName, nana, me = this; for (nana in args) { if (!args.hasOwnProperty(nana)) { continue; } valName = nana.replace(/^\w/, function (x) { var tt = x.charCodeAt(0); return "set" + (tt >= 0x61 ? String.fromCharCode(tt & ~32) : x); }); if (valName in me) { if (nana == "status") { me[valName](disconnectStatus[args[nana]] ? disconnectStatus[args[nana]] : args[nana]); } else { me[valName](args[nana]); } } } }; return BaseMessage; })(); RongIMLib.BaseMessage = BaseMessage; /** *连接消息类型 */ var ConnectMessage = (function (_super) { __extends(ConnectMessage, _super); function ConnectMessage(header) { _super.call(this, arguments.length == 0 || arguments.length == 3 ? RongIMLib.Type.CONNECT : arguments[0]); this._name = "ConnectMessage"; this.CONNECT_HEADER_SIZE = 12; this.protocolId = "RCloud"; this.binaryHelper = new RongIMLib.BinaryHelper(); this.protocolVersion = 3; switch (arguments.length) { case 0: case 1: case 3: if (!arguments[0] || arguments[0].length > 64) { throw new Error("ConnectMessage:Client Id cannot be null and must be at most 64 characters long: " + arguments[0]); } this.clientId = arguments[0]; this.cleanSession = arguments[1]; this.keepAlive = arguments[2]; break; } } ConnectMessage.prototype.messageLength = function () { var payloadSize = this.binaryHelper.toMQttString(this.clientId).length; payloadSize += this.binaryHelper.toMQttString(this.willTopic).length; payloadSize += this.binaryHelper.toMQttString(this.will).length; payloadSize += this.binaryHelper.toMQttString(this.appId).length; payloadSize += this.binaryHelper.toMQttString(this.token).length; return payloadSize + this.CONNECT_HEADER_SIZE; }; ConnectMessage.prototype.readMessage = function (stream) { this.protocolId = stream.readUTF(); this.protocolVersion = stream.readByte(); var cFlags = stream.readByte(); this.hasAppId = (cFlags & 128) > 0; this.hasToken = (cFlags & 64) > 0; this.retainWill = (cFlags & 32) > 0; this.willQos = cFlags >> 3 & 3; this.hasWill = (cFlags & 4) > 0; this.cleanSession = (cFlags & 32) > 0; this.keepAlive = stream.read() * 256 + stream.read(); this.clientId = stream.readUTF(); if (this.hasWill) { this.willTopic = stream.readUTF(); this.will = stream.readUTF(); } if (this.hasAppId) { try { this.appId = stream.readUTF(); } catch (ex) { throw new Error(ex); } } if (this.hasToken) { try { this.token = stream.readUTF(); } catch (ex) { throw new Error(ex); } } return stream; }; ConnectMessage.prototype.writeMessage = function (out) { var stream = this.binaryHelper.convertStream(out); stream.writeUTF(this.protocolId); stream.write(this.protocolVersion); var flags = this.cleanSession ? 2 : 0; flags |= this.hasWill ? 4 : 0; flags |= this.willQos ? this.willQos >> 3 : 0; flags |= this.retainWill ? 32 : 0; flags |= this.hasToken ? 64 : 0; flags |= this.hasAppId ? 128 : 0; stream.write(flags); stream.writeChar(this.keepAlive); stream.writeUTF(this.clientId); if (this.hasWill) { stream.writeUTF(this.willTopic); stream.writeUTF(this.will); } if (this.hasAppId) { stream.writeUTF(this.appId); } if (this.hasToken) { stream.writeUTF(this.token); } return stream; }; return ConnectMessage; })(BaseMessage); RongIMLib.ConnectMessage = ConnectMessage; /** *连接应答类型 */ var ConnAckMessage = (function (_super) { __extends(ConnAckMessage, _super); function ConnAckMessage(header) { _super.call(this, arguments.length == 0 ? RongIMLib.Type.CONNACK : arguments.length == 1 ? arguments[0] instanceof RongIMLib.Header ? arguments[0] : RongIMLib.Type.CONNACK : null); this._name = "ConnAckMessage"; this.MESSAGE_LENGTH = 2; this.binaryHelper = new RongIMLib.BinaryHelper(); var me = this; switch (arguments.length) { case 0: case 1: if (!(arguments[0] instanceof RongIMLib.Header)) { if (arguments[0] in RongIMLib.ConnectionState) { if (arguments[0] == null) { throw new Error("ConnAckMessage:The status of ConnAskMessage can't be null"); } me.setStatus(arguments[0]); } } break; } } ; ConnAckMessage.prototype.messageLength = function () { var length = this.MESSAGE_LENGTH; if (this.userId) { length += this.binaryHelper.toMQttString(this.userId).length; } return length; }; ; ConnAckMessage.prototype.readMessage = function (_in, msglength) { _in.read(); var result = +_in.read(); if (result >= 0 && result <= 12) { this.setStatus(result); } else { throw new Error("Unsupported CONNACK code:" + result); } if (msglength > this.MESSAGE_LENGTH) { this.setUserId(_in.readUTF()); var sessionId = _in.readUTF(); var timestamp = _in.readLong(); this.setTimestamp(timestamp); } }; ; ConnAckMessage.prototype.writeMessage = function (out) { var stream = this.binaryHelper.convertStream(out); stream.write(128); switch (+status) { case 0: case 1: case 2: case 5: case 6: stream.write(+status); break; case 3: case 4: stream.write(3); break; default: throw new Error("Unsupported CONNACK code:" + status); } if (this.userId) { stream.writeUTF(this.userId); } return stream; }; ; ConnAckMessage.prototype.setStatus = function (x) { this.status = x; }; ; ConnAckMessage.prototype.setUserId = function (_userId) { this.userId = _userId; }; ; ConnAckMessage.prototype.getStatus = function () { return this.status; }; ; ConnAckMessage.prototype.getUserId = function () { return this.userId; }; ; ConnAckMessage.prototype.setTimestamp = function (x) { this.timestrap = x; }; ; ConnAckMessage.prototype.getTimestamp = function () { return this.timestrap; }; return ConnAckMessage; })(BaseMessage); RongIMLib.ConnAckMessage = ConnAckMessage; /** *断开消息类型 */ var DisconnectMessage = (function (_super) { __extends(DisconnectMessage, _super); function DisconnectMessage(header) { _super.call(this, header instanceof RongIMLib.Header ? header : RongIMLib.Type.DISCONNECT); this._name = "DisconnectMessage"; this.MESSAGE_LENGTH = 2; this.binaryHelper = new RongIMLib.BinaryHelper(); if (!(header instanceof RongIMLib.Header)) { if (header in RongIMLib.ConnectionStatus) { this.status = header; } } } DisconnectMessage.prototype.messageLength = function () { return this.MESSAGE_LENGTH; }; DisconnectMessage.prototype.readMessage = function (_in) { _in.read(); var result = +_in.read(); if (result >= 0 && result <= 5) { this.setStatus(disconnectStatus[result] ? disconnectStatus[result] : result); } else { throw new Error("Unsupported CONNACK code:" + result); } }; DisconnectMessage.prototype.writeMessage = function (Out) { var out = this.binaryHelper.convertStream(Out); out.write(0); if (+status >= 1 && +status <= 3) { out.write((+status) - 1); } else { throw new Error("Unsupported CONNACK code:" + status); } }; DisconnectMessage.prototype.setStatus = function (x) { this.status = x; }; ; DisconnectMessage.prototype.getStatus = function () { return this.status; }; ; return DisconnectMessage; })(BaseMessage); RongIMLib.DisconnectMessage = DisconnectMessage; /** *请求消息信令 */ var PingReqMessage = (function (_super) { __extends(PingReqMessage, _super); function PingReqMessage(header) { _super.call(this, (header && header instanceof RongIMLib.Header) ? header : RongIMLib.Type.PINGREQ); this._name = "PingReqMessage"; } return PingReqMessage; })(BaseMessage); RongIMLib.PingReqMessage = PingReqMessage; /** *响应消息信令 */ var PingRespMessage = (function (_super) { __extends(PingRespMessage, _super); function PingRespMessage(header) { _super.call(this, (header && header instanceof RongIMLib.Header) ? header : RongIMLib.Type.PINGRESP); this._name = "PingRespMessage"; } return PingRespMessage; })(BaseMessage); RongIMLib.PingRespMessage = PingRespMessage; /** *封装MesssageId */ var RetryableMessage = (function (_super) { __extends(RetryableMessage, _super); function RetryableMessage(argu) { _super.call(this, argu); this._name = "RetryableMessage"; this.binaryHelper = new RongIMLib.BinaryHelper(); } RetryableMessage.prototype.messageLength = function () { return 2; }; RetryableMessage.prototype.writeMessage = function (Out) { var out = this.binaryHelper.convertStream(Out), Id = this.getMessageId(), lsb = Id & 255, msb = (Id & 65280) >> 8; out.write(msb); out.write(lsb); return out; }; RetryableMessage.prototype.readMessage = function (_in, msgLength) { var msgId = _in.read() * 256 + _in.read(); this.setMessageId(parseInt(msgId, 10)); }; RetryableMessage.prototype.setMessageId = function (_messageId) { this.messageId = _messageId; }; RetryableMessage.prototype.getMessageId = function () { return this.messageId; }; return RetryableMessage; })(BaseMessage); RongIMLib.RetryableMessage = RetryableMessage; /** *发送消息应答(双向) *qos为1必须给出应答(所有消息类型一样) */ var PubAckMessage = (function (_super) { __extends(PubAckMessage, _super); function PubAckMessage(header) { _super.call(this, (header instanceof RongIMLib.Header) ? header : RongIMLib.Type.PUBACK); this.msgLen = 2; this.date = 0; this.millisecond = 0; this.timestamp = 0; this.binaryHelper = new RongIMLib.BinaryHelper(); this._name = "PubAckMessage"; if (!(header instanceof RongIMLib.Header)) { _super.prototype.setMessageId.call(this, header); } } PubAckMessage.prototype.messageLength = function () { return this.msgLen; }; PubAckMessage.prototype.writeMessage = function (Out) { var out = this.binaryHelper.convertStream(Out); RetryableMessage.prototype.writeMessage.call(this, out); }; PubAckMessage.prototype.readMessage = function (_in, msgLength) { RetryableMessage.prototype.readMessage.call(this, _in); this.date = _in.readInt(); this.status = _in.read() * 256 + _in.read(); this.millisecond = _in.read() * 256 + _in.read(); this.timestamp = this.date * 1000 + this.millisecond; this.messageUId = _in.readUTF(); }; PubAckMessage.prototype.setStatus = function (x) { this.status = x; }; PubAckMessage.prototype.setTimestamp = function (timestamp) { this.timestamp = timestamp; }; PubAckMessage.prototype.setMessageUId = function (messageUId) { this.messageUId = messageUId; }; PubAckMessage.prototype.getStatus = function () { return this.status; }; PubAckMessage.prototype.getDate = function () { return this.date; }; PubAckMessage.prototype.getTimestamp = function () { return this.timestamp; }; PubAckMessage.prototype.getMessageUId = function () { return this.messageUId; }; return PubAckMessage; })(RetryableMessage); RongIMLib.PubAckMessage = PubAckMessage; /** *发布消息 */ var PublishMessage = (function (_super) { __extends(PublishMessage, _super); function PublishMessage(header, two, three) { _super.call(this, (arguments.length == 1 && header instanceof RongIMLib.Header) ? header : arguments.length == 3 ? RongIMLib.Type.PUBLISH : 0); this._name = "PublishMessage"; this.binaryHelper = new RongIMLib.BinaryHelper(); this.syncMsg = false; if (arguments.length == 3) { this.topic = header; this.targetId = three; this.data = typeof two == "string" ? this.binaryHelper.toMQttString(two) : two; } } PublishMessage.prototype.messageLength = function () { var length = 10; length += this.binaryHelper.toMQttString(this.topic).length; length += this.binaryHelper.toMQttString(this.targetId).length; length += this.data.length; return length; }; PublishMessage.prototype.writeMessage = function (Out) { var out = this.binaryHelper.convertStream(Out); out.writeUTF(this.topic); out.writeUTF(this.targetId); RetryableMessage.prototype.writeMessage.apply(this, arguments); out.write(this.data); }; ; PublishMessage.prototype.readMessage = function (_in, msgLength) { var pos = 6; this.date = _in.readInt(); this.topic = _in.readUTF(); pos += this.binaryHelper.toMQttString(this.topic).length; this.targetId = _in.readUTF(); pos += this.binaryHelper.toMQttString(this.targetId).length; RetryableMessage.prototype.readMessage.apply(this, arguments); this.data = new Array(msgLength - pos); this.data = _in.read(this.data); }; ; PublishMessage.prototype.setTopic = function (x) { this.topic = x; }; PublishMessage.prototype.setData = function (x) { this.data = x; }; PublishMessage.prototype.setTargetId = function (x) { this.targetId = x; }; PublishMessage.prototype.setDate = function (x) { this.date = x; }; PublishMessage.prototype.setSyncMsg = function (x) { this.syncMsg = x; }; //是否是其他端同步过来的消息 PublishMessage.prototype.getSyncMsg = function () { return this.syncMsg; }; PublishMessage.prototype.getTopic = function () { return this.topic; }; PublishMessage.prototype.getData = function () { return this.data; }; PublishMessage.prototype.getTargetId = function () { return this.targetId; }; PublishMessage.prototype.getDate = function () { return this.date; }; return PublishMessage; })(RetryableMessage); RongIMLib.PublishMessage = PublishMessage; /** *请求查询 */ var QueryMessage = (function (_super) { __extends(QueryMessage, _super); function QueryMessage(header, two, three) { _super.call(this, header instanceof RongIMLib.Header ? header : arguments.length == 3 ? RongIMLib.Type.QUERY : null); this.binaryHelper = new RongIMLib.BinaryHelper(); this._name = "QueryMessage"; if (arguments.length == 3) { this.data = typeof two == "string" ? this.binaryHelper.toMQttString(two) : two; this.topic = header; this.targetId = three; } } QueryMessage.prototype.messageLength = function () { var length = 0; length += this.binaryHelper.toMQttString(this.topic).length; length += this.binaryHelper.toMQttString(this.targetId).length; length += 2; length += this.data.length; return length; }; QueryMessage.prototype.writeMessage = function (Out) { var out = this.binaryHelper.convertStream(Out); out.writeUTF(this.topic); out.writeUTF(this.targetId); RetryableMessage.prototype.writeMessage.call(this, out); out.write(this.data); }; QueryMessage.prototype.readMessage = function (_in, msgLength) { var pos = 0; this.topic = _in.readUTF(); this.targetId = _in.readUTF(); pos += this.binaryHelper.toMQttString(this.topic).length; pos += this.binaryHelper.toMQttString(this.targetId).length; this.readMessage.apply(this, arguments); pos += 2; this.data = new Array(msgLength - pos); _in.read(this.data); }; QueryMessage.prototype.setTopic = function (x) { this.topic = x; }; QueryMessage.prototype.setData = function (x) { this.data = x; }; QueryMessage.prototype.setTargetId = function (x) { this.targetId = x; }; QueryMessage.prototype.getTopic = function () { return this.topic; }; QueryMessage.prototype.getData = function () { return this.data; }; QueryMessage.prototype.getTargetId = function () { return this.targetId; }; return QueryMessage; })(RetryableMessage); RongIMLib.QueryMessage = QueryMessage; /** *请求查询确认 */ var QueryConMessage = (function (_super) { __extends(QueryConMessage, _super); function QueryConMessage(messageId) { _super.call(this, (messageId instanceof RongIMLib.Header) ? messageId : RongIMLib.Type.QUERYCON); this._name = "QueryConMessage"; if (!(messageId instanceof RongIMLib.Header)) { _super.prototype.setMessageId.call(this, messageId); } } return QueryConMessage; })(RetryableMessage); RongIMLib.QueryConMessage = QueryConMessage; /** *请求查询应答 */ var QueryAckMessage = (function (_super) { __extends(QueryAckMessage, _super); function QueryAckMessage(header) { _super.call(this, header); this._name = "QueryAckMessage"; this.binaryHelper = new RongIMLib.BinaryHelper(); } QueryAckMessage.prototype.readMessage = function (In, msgLength) { RetryableMessage.prototype.readMessage.call(this, In); this.date = In.readInt(); this.setStatus(In.read() * 256 + In.read()); if (msgLength > 0) { this.data = new Array(msgLength - 8); this.data = In.read(this.data); } }; QueryAckMessage.prototype.getData = function () { return this.data; }; QueryAckMessage.prototype.getStatus = function () { return this.status; }; QueryAckMessage.prototype.getDate = function () { return this.date; }; QueryAckMessage.prototype.setDate = function (x) { this.date = x; }; QueryAckMessage.prototype.setStatus = function (x) { this.status = x; }; QueryAckMessage.prototype.setData = function (x) { this.data = x; }; return QueryAckMessage; })(RetryableMessage); RongIMLib.QueryAckMessage = QueryAckMessage; })(RongIMLib || (RongIMLib = {})); /// var RongIMLib; (function (RongIMLib) { /** * 把消息对象写入流中 * 发送消息时用到 */ var MessageOutputStream = (function () { function MessageOutputStream(_out) { var binaryHelper = new RongIMLib.BinaryHelper(); this.out = binaryHelper.convertStream(_out); } MessageOutputStream.prototype.writeMessage = function (msg) { if (msg instanceof RongIMLib.BaseMessage) { msg.write(this.out); } }; return MessageOutputStream; })(); RongIMLib.MessageOutputStream = MessageOutputStream; /** * 流转换为消息对象 * 服务器返回消息时用到 */ var MessageInputStream = (function () { function MessageInputStream(In, isPolling) { if (!isPolling) { var _in = new RongIMLib.BinaryHelper().convertStream(In); this.flags = _in.readByte(); this._in = _in; } else { this.flags = In["headerCode"]; } this.header = new RongIMLib.Header(this.flags); this.isPolling = isPolling; this.In = In; } MessageInputStream.prototype.readMessage = function () { switch (this.header.getType()) { case 1: this.msg = new RongIMLib.ConnectMessage(this.header); break; case 2: this.msg = new RongIMLib.ConnAckMessage(this.header); break; case 3: this.msg = new RongIMLib.PublishMessage(this.header); this.msg.setSyncMsg(this.header.getSyncMsg()); break; case 4: this.msg = new RongIMLib.PubAckMessage(this.header); break; case 5: this.msg = new RongIMLib.QueryMessage(this.header); break; case 6: this.msg = new RongIMLib.QueryAckMessage(this.header); break; case 7: this.msg = new RongIMLib.QueryConMessage(this.header); break; case 9: case 11: case 13: this.msg = new RongIMLib.PingRespMessage(this.header); break; case 8: case 10: case 12: this.msg = new RongIMLib.PingReqMessage(this.header); break; case 14: this.msg = new RongIMLib.DisconnectMessage(this.header); break; default: throw new Error("No support for deserializing " + this.header.getType() + " messages"); } if (this.isPolling) { this.msg.init(this.In); } else { this.msg.read(this._in, this.In.length - 1); } return this.msg; }; return MessageInputStream; })(); RongIMLib.MessageInputStream = MessageInputStream; var Header = (function () { function Header(_type, _retain, _qos, _dup) { this.retain = false; this.qos = RongIMLib.Qos.AT_LEAST_ONCE; this.dup = false; this.syncMsg = false; if (_type && +_type == _type && arguments.length == 1) { this.retain = (_type & 1) > 0; this.qos = (_type & 6) >> 1; this.dup = (_type & 8) > 0; this.type = (_type >> 4) & 15; this.syncMsg = (_type & 8) == 8; } else { this.type = _type; this.retain = _retain; this.qos = _qos; this.dup = _dup; } } Header.prototype.getSyncMsg = function () { return this.syncMsg; }; Header.prototype.getType = function () { return this.type; }; Header.prototype.encode = function () { var me = this; switch (this.qos) { case RongIMLib.Qos[0]: me.qos = RongIMLib.Qos.AT_MOST_ONCE; break; case RongIMLib.Qos[1]: me.qos = RongIMLib.Qos.AT_LEAST_ONCE; break; case RongIMLib.Qos[2]: me.qos = RongIMLib.Qos.EXACTLY_ONCE; break; case RongIMLib.Qos[3]: me.qos = RongIMLib.Qos.DEFAULT; break; } var _byte = (this.type << 4); _byte |= this.retain ? 1 : 0; _byte |= this.qos << 1; _byte |= this.dup ? 8 : 0; return _byte; }; Header.prototype.toString = function () { return "Header [type=" + this.type + ",retain=" + this.retain + ",qos=" + this.qos + ",dup=" + this.dup + "]"; }; return Header; })(); RongIMLib.Header = Header; /** * 二进制帮助对象 */ var BinaryHelper = (function () { function BinaryHelper() { } BinaryHelper.prototype.writeUTF = function (str, isGetBytes) { var back = [], byteSize = 0; for (var i = 0, len = str.length; i < len; i++) { var code = str.charCodeAt(i); if (code >= 0 && code <= 127) { byteSize += 1; back.push(code); } else if (code >= 128 && code <= 2047) { byteSize += 2; back.push((192 | (31 & (code >> 6)))); back.push((128 | (63 & code))); } else if (code >= 2048 && code <= 65535) { byteSize += 3; back.push((224 | (15 & (code >> 12)))); back.push((128 | (63 & (code >> 6)))); back.push((128 | (63 & code))); } } for (var i = 0, len = back.length; i < len; i++) { if (back[i] > 255) { back[i] &= 255; } } if (isGetBytes) { return back; } if (byteSize <= 255) { return [0, byteSize].concat(back); } else { return [byteSize >> 8, byteSize & 255].concat(back); } }; BinaryHelper.prototype.readUTF = function (arr) { if (Object.prototype.toString.call(arr) == "[object String]") { return arr; } var UTF = "", _arr = arr; for (var i = 0, len = _arr.length; i < len; i++) { if (_arr[i] < 0) { _arr[i] += 256; } ; var one = _arr[i].toString(2), v = one.match(/^1+?(?=0)/); if (v && one.length == 8) { var bytesLength = v[0].length, // store = _arr[i].toString(2).slice(7 - bytesLength); store = ''; for (var st = 0; st < bytesLength; st++) { store += _arr[st + i].toString(2).slice(2); } UTF += String.fromCharCode(parseInt(store, 2)); i += bytesLength - 1; } else { UTF += String.fromCharCode(_arr[i]); } } return UTF; }; /** * [convertStream 将参数x转化为RongIMStream对象] * @param {any} x [参数] */ BinaryHelper.prototype.convertStream = function (x) { if (x instanceof RongIMStream) { return x; } else { return new RongIMStream(x); } }; BinaryHelper.prototype.toMQttString = function (str) { return this.writeUTF(str); }; return BinaryHelper; })(); RongIMLib.BinaryHelper = BinaryHelper; var RongIMStream = (function () { function RongIMStream(arr) { //当前流执行的起始位置 this.position = 0; //当前流写入的多少字节 this.writen = 0; this.poolLen = 0; this.binaryHelper = new BinaryHelper(); this.pool = arr; this.poolLen = arr.length; } RongIMStream.prototype.check = function () { return this.position >= this.pool.length; }; RongIMStream.prototype.readInt = function () { if (this.check()) { return -1; } var end = ""; for (var i = 0; i < 4; i++) { var t = this.pool[this.position++].toString(16); if (t.length == 1) { t = "0" + t; } end += t.toString(16); } return parseInt(end, 16); }; RongIMStream.prototype.readLong = function () { if (this.check()) { return -1; } var end = ""; for (var i = 0; i < 8; i++) { var t = this.pool[this.position++].toString(16); if (t.length == 1) { t = "0" + t; } end += t; } return parseInt(end, 16); }; RongIMStream.prototype.readTimestamp = function () { if (this.check()) { return -1; } var end = ""; for (var i = 0; i < 8; i++) { end += this.pool[this.position++].toString(16); } end = end.substring(2, 8); return parseInt(end, 16); }; RongIMStream.prototype.readUTF = function () { if (this.check()) { return -1; } var big = (this.readByte() << 8) | this.readByte(); return this.binaryHelper.readUTF(this.pool.subarray(this.position, this.position += big)); }; RongIMStream.prototype.readByte = function () { if (this.check()) { return -1; } var val = this.pool[this.position++]; if (val > 255) { val &= 255; } return val; }; RongIMStream.prototype.read = function (bytesArray) { if (bytesArray) { return this.pool.subarray(this.position, this.poolLen); } else { return this.readByte(); } }; RongIMStream.prototype.write = function (_byte) { var b = _byte; if (Object.prototype.toString.call(b).toLowerCase() == "[object array]") { [].push.apply(this.pool, b); } else { if (+b == b) { if (b > 255) { b &= 255; } this.pool.push(b); this.writen++; } } return b; }; RongIMStream.prototype.writeChar = function (v) { if (+v != v) { throw new Error("writeChar:arguments type is error"); } this.write(v >> 8 & 255); this.write(v & 255); this.writen += 2; }; RongIMStream.prototype.writeUTF = function (str) { var val = this.binaryHelper.writeUTF(str); [].push.apply(this.pool, val); this.writen += val.length; }; RongIMStream.prototype.toComplements = function () { var _tPool = this.pool; for (var i = 0; i < this.poolLen; i++) { if (_tPool[i] > 128) { _tPool[i] -= 256; } } return _tPool; }; RongIMStream.prototype.getBytesArray = function (isCom) { if (isCom) { return this.toComplements(); } return this.pool; }; return RongIMStream; })(); RongIMLib.RongIMStream = RongIMStream; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var SocketTransportation = (function () { /** * [constructor] * @param {string} url [连接地址:包含token、version] */ function SocketTransportation(_socket) { //连接状态 true:已连接 false:未连接 this.connected = false; //是否关闭: true:已关闭 false:未关闭 this.isClose = false; //存放消息队列的临时变量 this.queue = []; this.empty = new Function; this._socket = _socket; return this; } /** * [createTransport 创建WebScoket对象] */ SocketTransportation.prototype.createTransport = function (url, method) { if (!url) { throw new Error("URL can't be empty"); } ; this.url = url; var depend = RongIMLib.RongIMClient._memoryStore.depend; var wsScheme = depend.wsScheme; var tpl = '{wsScheme}{url}'; url = RongIMLib.RongUtil.tplEngine(tpl, { wsScheme: wsScheme, url: url }); this.socket = new WebSocket(url); this.socket.binaryType = "arraybuffer"; this.addEvent(); return this.socket; }; /** * [send 传送消息流] * @param {ArrayBuffer} data [二进制消息流] */ SocketTransportation.prototype.send = function (data) { if (!this.connected && !this.isClose) { //当通道不可用时,加入消息队列 this.queue.push(data); return; } if (this.isClose) { this._socket.fire("StatusChanged", RongIMLib.ConnectionStatus.CONNECTION_CLOSED); return; } var stream = new RongIMLib.RongIMStream([]), msg = new RongIMLib.MessageOutputStream(stream); msg.writeMessage(data); var val = stream.getBytesArray(true); var binary = new Int8Array(val); this.socket.send(binary.buffer); return this; }; /** * [onData 通道返回数据时调用的方法,用来想上层传递服务器返回的二进制消息流] * @param {ArrayBuffer} data [二进制消息流] */ SocketTransportation.prototype.onData = function (data) { if (RongIMLib.MessageUtil.isArray(data)) { this._socket.onMessage(new RongIMLib.MessageInputStream(data).readMessage()); } else { this._socket.onMessage(new RongIMLib.MessageInputStream(RongIMLib.MessageUtil.ArrayFormInput(data)).readMessage()); } return ""; }; /** * [onClose 通道关闭时触发的方法] */ SocketTransportation.prototype.onClose = function (ev) { var me = this; me.isClose = true; me.socket = this.empty; RongIMLib.Bridge._client.clearHeartbeat(); if (ev.code == 1006 && !this._status) { me._socket.fire("StatusChanged", RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE); } else { me._status = 0; } }; /** * [onError 通道报错时触发的方法] * @param {any} error [抛出异常] */ SocketTransportation.prototype.onError = function (error) { throw new Error(error); }; /** * [addEvent 为通道绑定事件] */ SocketTransportation.prototype.addEvent = function () { var self = this; self.socket.onopen = function () { self.connected = true; self.isClose = false; //通道可以用后,调用发送队列方法,把所有等得发送的消息发出 self.doQueue(); self._socket.fire("connect"); }; self.socket.onmessage = function (ev) { //判断数据是不是字符串,如果是字符串那么就是flash传过来的。 if (typeof ev.data == "string") { self.onData(ev.data.split(",")); } else { self.onData(ev.data); } }; self.socket.onerror = function (ev) { self.onError(ev); }; self.socket.onclose = function (ev) { self.onClose(ev); }; }; /** * [doQueue 消息队列,把队列中消息发出] */ SocketTransportation.prototype.doQueue = function () { var self = this; for (var i = 0, len = self.queue.length; i < len; i++) { self.send(self.queue[i]); } }; /** * [disconnect 断开连接] */ SocketTransportation.prototype.disconnect = function (status) { var me = this; if (me.socket.readyState) { me.isClose = true; if (status) { me._status = status; } me.socket.close(); } }; /** * [reconnect 重新连接] */ SocketTransportation.prototype.reconnect = function () { this.disconnect(); this.createTransport(this.url); }; SocketTransportation.prototype.close = function () { this.socket.close(); }; return SocketTransportation; })(); RongIMLib.SocketTransportation = SocketTransportation; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var PollingTransportation = (function () { function PollingTransportation(socket) { this.empty = new Function; this.connected = false; this.pid = +new Date + Math.random() + ""; this.queue = []; this.socket = socket; return this; } PollingTransportation.prototype.createTransport = function (url, method) { if (!url) { throw new Error("Url is empty,Please check it!"); } ; this.url = url; var sid = RongIMLib.RongIMClient._storageProvider.getItem("sId" + RongIMLib.Navigation.Endpoint.userId), me = this; if (sid) { setTimeout(function () { me.onSuccess("{\"status\":0,\"userId\":\"" + RongIMLib.Navigation.Endpoint.userId + "\",\"headerCode\":32,\"messageId\":0,\"sessionid\":\"" + sid + "\"}"); me.connected = true; }, 500); return this; } this.getRequest(url, true); return this; }; PollingTransportation.prototype.requestFactory = function (url, method, multipart) { var reqest = this.XmlHttpRequest(); if (multipart) { reqest.multipart = true; } reqest.timeout = 60000; reqest.open(method || "GET", RongIMLib.RongIMClient._memoryStore.depend.protocol + url); if (method == "POST" && "setRequestHeader" in reqest) { reqest.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=utf-8"); } return reqest; }; PollingTransportation.prototype.getRequest = function (url, isconnect) { var me = this; me.xhr = this.requestFactory(url + "&pid=" + encodeURIComponent(me.pid), "GET"); if ("onload" in me.xhr) { me.xhr.onload = function () { me.xhr.onload = me.empty; if (this.responseText == "lost params") { me.onError(); } else { me.onSuccess(this.responseText, isconnect); } }; me.xhr.onerror = function () { me.disconnect(); }; } else { me.xhr.onreadystatechange = function () { if (me.xhr.readyState == 4) { me.xhr.onreadystatechange = me.empty; if (/^(200|202)$/.test(me.xhr.status)) { me.onSuccess(me.xhr.responseText, isconnect); } else if (/^(400|403)$/.test(me.xhr.status)) { me.onError(); } else { me.disconnect(); } } }; } me.xhr.send(); }; /** * [send 发送消息,Method:POST] * queue 为消息队列,待通道可用发送所有等待消息 * @param {string} data [需要传入comet格式数据,此处只负责通讯通道,数据转换在外层处理] */ PollingTransportation.prototype.send = function (data) { var me = this; var _send = me.sendxhr = this.requestFactory(RongIMLib.Navigation.Endpoint.host + "/websocket" + data.url + "&pid=" + encodeURIComponent(me.pid), "POST"); if ("onload" in _send) { _send.onload = function () { _send.onload = me.empty; me.onData(_send.responseText); }; _send.onerror = function () { _send.onerror = me.empty; }; } else { _send.onreadystatechange = function () { if (_send.readyState == 4) { this.onreadystatechange = this.empty; if (/^(202|200)$/.test(_send.status)) { me.onData(_send.responseText); } } }; } _send.send(JSON.stringify(data.data)); }; PollingTransportation.prototype.onData = function (data, header) { if (!data || data == "lost params") { return; } var self = this, val = JSON.parse(data); if (val.userId) { RongIMLib.Navigation.Endpoint.userId = val.userId; } if (header) { RongIMLib.RongIMClient._storageProvider.setItem("sId" + RongIMLib.Navigation.Endpoint.userId, header); } if (!RongIMLib.MessageUtil.isArray(val)) { val = [val]; } Array.forEach(val, function (m) { self.socket.fire("message", new RongIMLib.MessageInputStream(m, true).readMessage()); }); return ""; }; PollingTransportation.prototype.XmlHttpRequest = function () { var hasCORS = typeof XMLHttpRequest !== "undefined" && "withCredentials" in new XMLHttpRequest(), self = this; if ("undefined" != typeof XMLHttpRequest && hasCORS) { return new XMLHttpRequest(); } else if ("undefined" != typeof XDomainRequest) { return new XDomainRequest(); } else { return new ActiveXObject("Microsoft.XMLHTTP"); } }; PollingTransportation.prototype.onClose = function () { if (this.xhr) { if (this.xhr.onload) { this.xhr.onreadystatechange = this.xhr.onload = this.empty; } else { this.xhr.onreadystatechange = this.empty; } this.xhr.abort(); this.xhr = null; } if (this.sendxhr) { if (this.sendxhr.onload) { this.sendxhr.onreadystatechange = this.sendxhr.onload = this.empty; } else { this.sendxhr.onreadystatechange = this.empty; } this.sendxhr.abort(); this.sendxhr = null; } }; PollingTransportation.prototype.disconnect = function () { RongIMLib.RongIMClient._storageProvider.removeItem("sId" + RongIMLib.Navigation.Endpoint.userId); RongIMLib.RongIMClient._storageProvider.removeItem(RongIMLib.Navigation.Endpoint.userId + "msgId"); this.onClose(); }; PollingTransportation.prototype.reconnect = function () { this.disconnect(); this.createTransport(this.url); }; PollingTransportation.prototype.onSuccess = function (responseText, isconnect) { var txt = responseText.match(/"sessionid":"\S+?(?=")/); this.onData(responseText, txt ? txt[0].slice(13) : 0); if (/"headerCode":-32,/.test(responseText)) { RongIMLib.RongIMClient._storageProvider.removeItem("sId" + RongIMLib.Navigation.Endpoint.userId); RongIMLib.RongIMClient._storageProvider.removeItem(RongIMLib.Navigation.Endpoint.userId + "msgId"); return; } this.getRequest(RongIMLib.Navigation.Endpoint.host + "/pullmsg.js?sessionid=" + RongIMLib.RongIMClient._storageProvider.getItem("sId" + RongIMLib.Navigation.Endpoint.userId) + "×trap=" + encodeURIComponent(new Date().getTime() + Math.random() + "")); this.connected = true; isconnect && this.socket.fire("connect"); }; PollingTransportation.prototype.onError = function () { RongIMLib.RongIMClient._storageProvider.removeItem("sId" + RongIMLib.Navigation.Endpoint.userId); RongIMLib.RongIMClient._storageProvider.removeItem(RongIMLib.Navigation.Endpoint.userId + "msgId"); this.onClose(); this.connected = false; this.socket.fire("disconnect"); }; PollingTransportation.prototype.close = function () { this.xhr.abort(); this.sendxhr = null; }; return PollingTransportation; })(); RongIMLib.PollingTransportation = PollingTransportation; })(RongIMLib || (RongIMLib = {})); //objectname映射 var typeMapping = { "RC:TxtMsg": "TextMessage", "RC:ImgMsg": "ImageMessage", "RC:VcMsg": "VoiceMessage", "RC:ImgTextMsg": "RichContentMessage", "RC:FileMsg": "FileMessage", "RC:LBSMsg": "LocationMessage", "RC:InfoNtf": "InformationNotificationMessage", "RC:ContactNtf": "ContactNotificationMessage", "RC:ProfileNtf": "ProfileNotificationMessage", "RC:CmdNtf": "CommandNotificationMessage", "RC:DizNtf": "DiscussionNotificationMessage", "RC:CmdMsg": "CommandMessage", "RC:TypSts": "TypingStatusMessage", "RC:CsChaR": "ChangeModeResponseMessage", "RC:CsHsR": "HandShakeResponseMessage", "RC:CsEnd": "TerminateMessage", "RC:CsSp": "SuspendMessage", "RC:CsUpdate": "CustomerStatusUpdateMessage", "RC:ReadNtf": "ReadReceiptMessage", "RC:VCAccept": "AcceptMessage", "RC:VCRinging": "RingingMessage", "RC:VCSummary": "SummaryMessage", "RC:VCHangup": "HungupMessage", "RC:VCInvite": "InviteMessage", "RC:VCModifyMedia": "MediaModifyMessage", "RC:VCModifyMem": "MemberModifyMessage", "RC:CsContact": "CustomerContact", "RC:PSImgTxtMsg": "PublicServiceRichContentMessage", "RC:PSMultiImgTxtMsg": "PublicServiceMultiRichContentMessage", "RC:GrpNtf": "GroupNotificationMessage", "RC:PSCmd": "PublicServiceCommandMessage", "RC:RcCmd": "RecallCommandMessage", "RC:SRSMsg": "SyncReadStatusMessage", "RC:RRReqMsg": "ReadReceiptRequestMessage", "RC:RRRspMsg": "ReadReceiptResponseMessage", "RCJrmf:RpMsg": "JrmfRedPacketMessage", "RCJrmf:RpOpendMsg": "JrmfRedPacketOpenedMessage" }, //自定义消息类型 registerMessageTypeMapping = {}, HistoryMsgType = { 4: "qryCMsg", 2: "qryDMsg", 3: "qryGMsg", 1: "qryPMsg", 6: "qrySMsg", 7: "qryMCMsg", 8: "qryMPMsg", 5: "qryCMsg" }, disconnectStatus = { 1: 6 }; var RongIMLib; (function (RongIMLib) { /** * 通道标识类 */ var Transportations = (function () { function Transportations() { } Transportations._TransportType = RongIMLib.Socket.WEBSOCKET; return Transportations; })(); RongIMLib.Transportations = Transportations; var MessageUtil = (function () { function MessageUtil() { } /** *4680000 为localstorage最小容量5200000字节的90%,超过90%将删除之前过早的存储 */ MessageUtil.checkStorageSize = function () { return JSON.stringify(localStorage).length < 4680000; }; MessageUtil.getFirstKey = function (obj) { var str = ""; for (var key in obj) { str = key; break; } return str; }; MessageUtil.isEmpty = function (obj) { var empty = true; for (var key in obj) { empty = false; break; } return empty; }; MessageUtil.ArrayForm = function (typearray) { if (Object.prototype.toString.call(typearray) == "[object ArrayBuffer]") { var arr = new Int8Array(typearray); return [].slice.call(arr); } return typearray; }; MessageUtil.ArrayFormInput = function (typearray) { if (Object.prototype.toString.call(typearray) == "[object ArrayBuffer]") { var arr = new Uint8Array(typearray); return arr; } return typearray; }; MessageUtil.indexOf = function (arr, item, from) { for (var l = arr.length, i = (from < 0) ? Math.max(0, +from) : from || 0; i < l; i++) { if (arr[i] == item) { return i; } } return -1; }; MessageUtil.isArray = function (obj) { return Object.prototype.toString.call(obj) == "[object Array]"; }; //遍历,只能遍历数组 MessageUtil.forEach = function (arr, func) { if ([].forEach) { return function (arr, func) { [].forEach.call(arr, func); }; } else { return function (arr, func) { for (var i = 0; i < arr.length; i++) { func.call(arr, arr[i], i, arr); } }; } }; MessageUtil.remove = function (array, func) { for (var i = 0, len = array.length; i < len; i++) { if (func(array[i])) { return array.splice(i, 1)[0]; } } return null; }; MessageUtil.int64ToTimestamp = function (obj, isDate) { if (obj.low === undefined) { return obj; } var low = obj.low; if (low < 0) { low += 0xffffffff + 1; } low = low.toString(16); var timestamp = parseInt(obj.high.toString(16) + "00000000".replace(new RegExp("0{" + low.length + "}$"), low), 16); if (isDate) { return new Date(timestamp); } return timestamp; }; //消息转换方法 MessageUtil.messageParser = function (entity, onReceived, offlineMsg) { var message = new RongIMLib.Message(), content = entity.content, de, objectName = entity.classname, val, isUseDef = false; try { if (RongIMLib.RongIMClient._memoryStore.depend.isPolling) { val = new RongIMLib.BinaryHelper().readUTF(content.offset ? MessageUtil.ArrayForm(content.buffer).slice(content.offset, content.limit) : content); de = JSON.parse(val); } else { val = new RongIMLib.BinaryHelper().readUTF(content.offset ? MessageUtil.ArrayFormInput(content.buffer).subarray(content.offset, content.limit) : content); de = JSON.parse(val); } } catch (ex) { de = val; isUseDef = true; } //映射为具体消息对象 if (objectName in typeMapping) { var str = "new RongIMLib." + typeMapping[objectName] + "(de)"; message.content = eval(str); message.messageType = typeMapping[objectName]; } else if (objectName in registerMessageTypeMapping) { var str = "new RongIMLib.RongIMClient.RegisterMessage." + registerMessageTypeMapping[objectName] + "(de)"; if (isUseDef) { message.content = eval(str).decode(de); } else { message.content = eval(str); } message.messageType = registerMessageTypeMapping[objectName]; } else { message.content = new RongIMLib.UnknownMessage({ content: de, objectName: objectName }); message.messageType = "UnknownMessage"; } //根据实体对象设置message对象] var dateTime = MessageUtil.int64ToTimestamp(entity.dataTime); if (dateTime > 0) { message.sentTime = dateTime; } else { message.sentTime = +new Date; } message.senderUserId = entity.fromUserId; message.conversationType = entity.type; if (entity.fromUserId == RongIMLib.Bridge._client.userId) { message.targetId = entity.groupId; } else { message.targetId = (/^[234]$/.test(entity.type || entity.getType()) ? entity.groupId : message.senderUserId); } if (entity.direction == 1) { message.messageDirection = RongIMLib.MessageDirection.SEND; message.senderUserId = RongIMLib.Bridge._client.userId; } else { if (message.senderUserId == RongIMLib.Bridge._client.userId) { message.messageDirection = RongIMLib.MessageDirection.SEND; } else { message.messageDirection = RongIMLib.MessageDirection.RECEIVE; } } message.messageUId = entity.msgId; message.receivedTime = new Date().getTime(); message.messageId = (message.conversationType + "_" + ~~(Math.random() * 0xffffff)); message.objectName = objectName; message.receivedStatus = RongIMLib.ReceivedStatus.READ; if ((entity.status & 2) == 2) { message.receivedStatus = RongIMLib.ReceivedStatus.RETRIEVED; } message.offLineMessage = offlineMsg ? true : false; if (!offlineMsg) { if (RongIMLib.RongIMClient._memoryStore.connectAckTime > message.sentTime) { message.offLineMessage = true; } } return message; }; //适配SSL // static schemeArrs: Array = [["http", "ws"], ["https", "wss"]]; MessageUtil.sign = { converNum: 1, msgNum: 1, isMsgStart: true, isConvStart: true }; return MessageUtil; })(); RongIMLib.MessageUtil = MessageUtil; /** * 工具类 */ var MessageIdHandler = (function () { function MessageIdHandler() { } MessageIdHandler.init = function () { this.messageId = +(RongIMLib.RongIMClient._storageProvider.getItem(RongIMLib.Navigation.Endpoint.userId + "msgId") || RongIMLib.RongIMClient._storageProvider.setItem(RongIMLib.Navigation.Endpoint.userId + "msgId", 0) || 0); }; MessageIdHandler.messageIdPlus = function (method) { RongIMLib.RongIMClient._memoryStore.depend.isPolling && this.init(); if (this.messageId >= 65535) { method(); return false; } this.messageId++; RongIMLib.RongIMClient._memoryStore.depend.isPolling && RongIMLib.RongIMClient._storageProvider.setItem(RongIMLib.Navigation.Endpoint.userId + "msgId", this.messageId); return this.messageId; }; MessageIdHandler.clearMessageId = function () { this.messageId = 0; RongIMLib.RongIMClient._memoryStore.depend.isPolling && RongIMLib.RongIMClient._storageProvider.setItem(RongIMLib.Navigation.Endpoint.userId + "msgId", this.messageId); }; MessageIdHandler.getMessageId = function () { RongIMLib.RongIMClient._memoryStore.depend.isPolling && this.init(); return this.messageId; }; MessageIdHandler.messageId = 0; return MessageIdHandler; })(); RongIMLib.MessageIdHandler = MessageIdHandler; var RongInnerTools = (function () { function RongInnerTools() { } RongInnerTools.convertUserStatus = function (entity) { entity = RongIMLib.RongUtil.rename(entity, { subUserId: 'userId' }); var status = JSON.parse(entity.status); var us = status.us; if (!us) { return entity; } entity.status = RongIMLib.RongUtil.rename(us, { o: 'online', 'p': 'platform', s: 'status' }); return entity; }; return RongInnerTools; })(); RongIMLib.RongInnerTools = RongInnerTools; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var MessageContent = (function () { function MessageContent(data) { throw new Error("This method is abstract, you must implement this method in inherited class."); } MessageContent.obtain = function () { throw new Error("This method is abstract, you must implement this method in inherited class."); }; return MessageContent; })(); RongIMLib.MessageContent = MessageContent; var NotificationMessage = (function (_super) { __extends(NotificationMessage, _super); function NotificationMessage() { _super.apply(this, arguments); } return NotificationMessage; })(MessageContent); RongIMLib.NotificationMessage = NotificationMessage; var StatusMessage = (function (_super) { __extends(StatusMessage, _super); function StatusMessage() { _super.apply(this, arguments); } return StatusMessage; })(MessageContent); RongIMLib.StatusMessage = StatusMessage; var ModelUtil = (function () { function ModelUtil() { } ModelUtil.modelClone = function (object) { var obj = {}; for (var item in object) { if (item != "messageName" && "encode" != item) { obj[item] = object[item]; } } return obj; }; ModelUtil.modleCreate = function (fields, msgType) { if (fields.length < 1) { throw new Error("Array is empty -> registerMessageType.modleCreate"); } var Object = function (message) { var me = this; for (var index in fields) { me[fields[index]] = message[fields[index]]; } Object.prototype.messageName = msgType; Object.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; }; return Object; }; return ModelUtil; })(); RongIMLib.ModelUtil = ModelUtil; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var CustomerStatusMessage = (function () { function CustomerStatusMessage(message) { this.messageName = "CustomerStatusMessage"; this.status = message.status; } CustomerStatusMessage.obtain = function () { return null; }; CustomerStatusMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return CustomerStatusMessage; })(); RongIMLib.CustomerStatusMessage = CustomerStatusMessage; /** * 客服转换响应消息的类型名 */ var ChangeModeResponseMessage = (function () { function ChangeModeResponseMessage(message) { this.messageName = "ChangeModeResponseMessage"; this.code = message.code; this.data = message.data; this.msg = message.msg; } ChangeModeResponseMessage.obtain = function () { return null; }; ChangeModeResponseMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ChangeModeResponseMessage; })(); RongIMLib.ChangeModeResponseMessage = ChangeModeResponseMessage; /** * 客服转换消息的类型名 * 此消息不计入未读消息数 */ var ChangeModeMessage = (function () { function ChangeModeMessage(message) { this.messageName = "ChangeModeMessage"; this.uid = message.uid; this.sid = message.sid; this.pid = message.pid; } ChangeModeMessage.obtain = function () { return null; }; ChangeModeMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ChangeModeMessage; })(); RongIMLib.ChangeModeMessage = ChangeModeMessage; var CustomerStatusUpdateMessage = (function () { function CustomerStatusUpdateMessage(message) { this.messageName = "CustomerStatusUpdateMessage"; this.serviceStatus = message.serviceStatus; this.sid = message.sid; } CustomerStatusUpdateMessage.obtain = function () { return null; }; CustomerStatusUpdateMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return CustomerStatusUpdateMessage; })(); RongIMLib.CustomerStatusUpdateMessage = CustomerStatusUpdateMessage; var HandShakeMessage = (function () { function HandShakeMessage(message) { this.messageName = "HandShakeMessage"; message && (this.groupid = message.groupid); } HandShakeMessage.obtain = function () { return null; }; HandShakeMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return HandShakeMessage; })(); RongIMLib.HandShakeMessage = HandShakeMessage; var CustomerContact = (function () { function CustomerContact(message) { this.messageName = "CustomerContact"; this.page = message.page; this.nickName = message.nickName; this.routingInfo = message.routingInfo; this.info = message.info; this.requestInfo = message.requestInfo; } CustomerContact.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return CustomerContact; })(); RongIMLib.CustomerContact = CustomerContact; var EvaluateMessage = (function () { function EvaluateMessage(message) { this.messageName = "EvaluateMessage"; this.uid = message.uid; this.sid = message.sid; this.pid = message.pid; this.source = message.source; this.suggest = message.suggest; this.isresolve = message.isresolve; this.type = message.type; } EvaluateMessage.obtain = function () { return null; }; EvaluateMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return EvaluateMessage; })(); RongIMLib.EvaluateMessage = EvaluateMessage; /** * 客服握手响应消息的类型名 */ var HandShakeResponseMessage = (function () { function HandShakeResponseMessage(message) { this.messageName = "HandShakeResponseMessage"; this.msg = message.msg; this.status = message.status; this.data = message.data; } HandShakeResponseMessage.obtain = function () { return null; }; HandShakeResponseMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return HandShakeResponseMessage; })(); RongIMLib.HandShakeResponseMessage = HandShakeResponseMessage; var SuspendMessage = (function () { function SuspendMessage(message) { this.messageName = "SuspendMessage"; this.uid = message.uid; this.sid = message.sid; this.pid = message.pid; } SuspendMessage.obtain = function () { return null; }; SuspendMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return SuspendMessage; })(); RongIMLib.SuspendMessage = SuspendMessage; var TerminateMessage = (function () { function TerminateMessage(message) { this.messageName = "TerminateMessage"; this.code = message.code; this.msg = message.msg; this.sid = message.sid; } TerminateMessage.obtain = function () { return null; }; TerminateMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return TerminateMessage; })(); RongIMLib.TerminateMessage = TerminateMessage; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var IsTypingStatusMessage = (function () { function IsTypingStatusMessage(data) { this.messageName = "IsTypingStatusMessage"; var msg = data; } IsTypingStatusMessage.prototype.encode = function () { return undefined; }; IsTypingStatusMessage.prototype.getMessage = function () { return null; }; return IsTypingStatusMessage; })(); RongIMLib.IsTypingStatusMessage = IsTypingStatusMessage; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var InformationNotificationMessage = (function () { function InformationNotificationMessage(message) { this.messageName = "InformationNotificationMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> InformationNotificationMessage."); } this.message = message.message; this.extra = message.extra; if (message.user) { this.user = message.user; } } InformationNotificationMessage.obtain = function (message) { return new InformationNotificationMessage({ message: message, extra: "" }); }; InformationNotificationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return InformationNotificationMessage; })(); RongIMLib.InformationNotificationMessage = InformationNotificationMessage; var CommandMessage = (function () { function CommandMessage(message) { this.messageName = "CommandMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> CommandMessage."); } try { if (Object.prototype.toString.call(message.data) == "[object String]") { this.data = JSON.parse(message.data); } else { this.data = message.data; } } catch (e) { this.data = message.data; } this.name = message.name; this.extra = message.extra; } CommandMessage.obtain = function (data) { return new CommandMessage({ data: data, extra: "" }); }; CommandMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return CommandMessage; })(); RongIMLib.CommandMessage = CommandMessage; var ContactNotificationMessage = (function () { function ContactNotificationMessage(message) { this.messageName = "ContactNotificationMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> ContactNotificationMessage."); } this.operation = message.operation; this.targetUserId = message.targetUserId; this.message = message.message; this.extra = message.extra; this.sourceUserId = message.sourceUserId; if (message.user) { this.user = message.user; } } ContactNotificationMessage.obtain = function (operation, sourceUserId, targetUserId, message) { return new InformationNotificationMessage({ operation: operation, sourceUserId: sourceUserId, targetUserId: targetUserId, message: message }); }; ContactNotificationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; ContactNotificationMessage.CONTACT_OPERATION_ACCEPT_RESPONSE = "ContactOperationAcceptResponse"; ContactNotificationMessage.CONTACT_OPERATION_REJECT_RESPONSE = "ContactOperationRejectResponse"; ContactNotificationMessage.CONTACT_OPERATION_REQUEST = "ContactOperationRequest"; return ContactNotificationMessage; })(); RongIMLib.ContactNotificationMessage = ContactNotificationMessage; var ProfileNotificationMessage = (function () { function ProfileNotificationMessage(message) { this.messageName = "ProfileNotificationMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> ProfileNotificationMessage."); } this.operation = message.operation; try { if (Object.prototype.toString.call(message.data) == "[object String]") { this.data = JSON.parse(message.data); } else { this.data = message.data; } } catch (e) { this.data = message.data; } this.extra = message.extra; if (message.user) { this.user = message.user; } } ProfileNotificationMessage.obtain = function (operation, data) { return new ProfileNotificationMessage({ operation: operation, data: data }); }; ProfileNotificationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ProfileNotificationMessage; })(); RongIMLib.ProfileNotificationMessage = ProfileNotificationMessage; var CommandNotificationMessage = (function () { function CommandNotificationMessage(message) { this.messageName = "CommandNotificationMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> ProfileNotificationMessage."); } try { if (Object.prototype.toString.call(message.data) == "[object String]") { this.data = JSON.parse(message.data); } else { this.data = message.data; } } catch (e) { this.data = message.data; } this.name = message.name; this.extra = message.extra; if (message.user) { this.user = message.user; } } CommandNotificationMessage.obtain = function (name, data) { return new CommandNotificationMessage({ name: name, data: data, extra: "" }); }; CommandNotificationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return CommandNotificationMessage; })(); RongIMLib.CommandNotificationMessage = CommandNotificationMessage; var DiscussionNotificationMessage = (function () { function DiscussionNotificationMessage(message) { this.messageName = "DiscussionNotificationMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> DiscussionNotificationMessage."); } this.extra = message.extra; this.extension = message.extension; this.type = message.type; this.isHasReceived = message.isHasReceived; this.operation = message.operation; this.user = message.user; if (message.user) { this.user = message.user; } } DiscussionNotificationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return DiscussionNotificationMessage; })(); RongIMLib.DiscussionNotificationMessage = DiscussionNotificationMessage; var GroupNotificationMessage = (function () { function GroupNotificationMessage(msg) { this.messageName = "GroupNotificationMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> GroupNotificationMessage."); } msg.operatorUserId && (this.operatorUserId = msg.operatorUserId); msg.operation && (this.operation = msg.operation); msg.data && (this.data = msg.data); msg.message && (this.message = msg.message); msg.extra && (this.extra = msg.extra); } GroupNotificationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return GroupNotificationMessage; })(); RongIMLib.GroupNotificationMessage = GroupNotificationMessage; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var TextMessage = (function () { function TextMessage(message) { this.messageName = "TextMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> TextMessage."); } this.content = message.content; this.extra = message.extra; if (message.user) { this.user = message.user; } if (message.mentionedInfo) { this.mentionedInfo = message.mentionedInfo; } if (message.burnDuration) { this.burnDuration = message.burnDuration; } } TextMessage.obtain = function (text) { return new TextMessage({ extra: "", content: text }); }; TextMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return TextMessage; })(); RongIMLib.TextMessage = TextMessage; var TypingStatusMessage = (function () { function TypingStatusMessage(message) { this.messageName = "TypingStatusMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> TypingStatusMessage."); } this.typingContentType = message.typingContentType; this.data = message.data; } TypingStatusMessage.obtain = function (typingContentType, data) { return new TypingStatusMessage({ typingContentType: typingContentType, data: data }); }; TypingStatusMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return TypingStatusMessage; })(); RongIMLib.TypingStatusMessage = TypingStatusMessage; var ReadReceiptMessage = (function () { function ReadReceiptMessage(message) { this.messageName = "ReadReceiptMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> ReadReceiptMessage."); } this.lastMessageSendTime = message.lastMessageSendTime; this.messageUId = message.messageUId; this.type = message.type; } ReadReceiptMessage.obtain = function (messageUId, lastMessageSendTime, type) { return new ReadReceiptMessage({ messageUId: messageUId, lastMessageSendTime: lastMessageSendTime, type: type }); }; ReadReceiptMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ReadReceiptMessage; })(); RongIMLib.ReadReceiptMessage = ReadReceiptMessage; var VoiceMessage = (function () { function VoiceMessage(message) { this.messageName = "VoiceMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> VoiceMessage."); } this.content = message.content; this.duration = message.duration; this.extra = message.extra; if (message.user) { this.user = message.user; } if (message.mentionedInfo) { this.mentionedInfo = message.mentionedInfo; } if (message.burnDuration) { this.burnDuration = message.burnDuration; } } VoiceMessage.obtain = function (base64Content, duration) { return new VoiceMessage({ content: base64Content, duration: duration, extra: "" }); }; VoiceMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return VoiceMessage; })(); RongIMLib.VoiceMessage = VoiceMessage; var RecallCommandMessage = (function () { function RecallCommandMessage(message) { this.messageName = "RecallCommandMessage"; this.messageUId = message.messageUId; this.conversationType = message.conversationType; this.targetId = message.targetId; this.sentTime = message.sentTime; // RCE 增加 this.isDelete = message.isDelete; this.isAdmin = message.isAdmin; this.adminId = message.adminId; message.extra && (this.extra = message.extra); message.user && (this.user = message.user); } RecallCommandMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return RecallCommandMessage; })(); RongIMLib.RecallCommandMessage = RecallCommandMessage; var ImageMessage = (function () { function ImageMessage(message) { this.messageName = "ImageMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> ImageMessage."); } this.content = message.content; this.imageUri = message.imageUri; message.extra && (this.extra = message.extra); message.user && (this.user = message.user); if (message.mentionedInfo) { this.mentionedInfo = message.mentionedInfo; } if (message.burnDuration) { this.burnDuration = message.burnDuration; } } ImageMessage.obtain = function (content, imageUri) { return new ImageMessage({ content: content, imageUri: imageUri, extra: "" }); }; ImageMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ImageMessage; })(); RongIMLib.ImageMessage = ImageMessage; var LocationMessage = (function () { function LocationMessage(message) { this.messageName = "LocationMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> LocationMessage."); } this.latitude = message.latitude; this.longitude = message.longitude; this.poi = message.poi; this.content = message.content; this.extra = message.extra; if (message.user) { this.user = message.user; } if (message.mentionedInfo) { this.mentionedInfo = message.mentionedInfo; } } LocationMessage.obtain = function (latitude, longitude, poi, content) { return new LocationMessage({ latitude: latitude, longitude: longitude, poi: poi, content: content, extra: "" }); }; LocationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return LocationMessage; })(); RongIMLib.LocationMessage = LocationMessage; var RichContentMessage = (function () { function RichContentMessage(message) { this.messageName = "RichContentMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> RichContentMessage."); } this.title = message.title; this.content = message.content; this.imageUri = message.imageUri; this.extra = message.extra; this.url = message.url; if (message.user) { this.user = message.user; } } RichContentMessage.obtain = function (title, content, imageUri, url) { return new RichContentMessage({ title: title, content: content, imageUri: imageUri, url: url, extra: "" }); }; RichContentMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return RichContentMessage; })(); RongIMLib.RichContentMessage = RichContentMessage; var JrmfRedPacketMessage = (function () { function JrmfRedPacketMessage(message) { this.messageName = 'JrmfRedPacketMessage'; message && (this.message = message); } JrmfRedPacketMessage.prototype.encode = function () { return ""; }; return JrmfRedPacketMessage; })(); RongIMLib.JrmfRedPacketMessage = JrmfRedPacketMessage; var JrmfRedPacketOpenedMessage = (function () { function JrmfRedPacketOpenedMessage(message) { this.messageName = 'JrmfRedPacketOpenedMessage'; message && (this.message = message); } JrmfRedPacketOpenedMessage.prototype.encode = function () { return ""; }; return JrmfRedPacketOpenedMessage; })(); RongIMLib.JrmfRedPacketOpenedMessage = JrmfRedPacketOpenedMessage; var UnknownMessage = (function () { function UnknownMessage(message) { this.messageName = "UnknownMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> UnknownMessage."); } this.message = message; } UnknownMessage.prototype.encode = function () { return ""; }; return UnknownMessage; })(); RongIMLib.UnknownMessage = UnknownMessage; var PublicServiceCommandMessage = (function () { function PublicServiceCommandMessage(message) { this.messageName = "PublicServiceCommandMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> PublicServiceCommandMessage."); } this.content = message.content; this.extra = message.extra; this.menuItem = message.menuItem; if (message.user) { this.user = message.user; } if (message.mentionedInfo) { this.mentionedInfo = message.mentionedInfo; } } PublicServiceCommandMessage.obtain = function (item) { return new PublicServiceCommandMessage({ content: "", command: "", menuItem: item, extra: "" }); }; PublicServiceCommandMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return PublicServiceCommandMessage; })(); RongIMLib.PublicServiceCommandMessage = PublicServiceCommandMessage; var PublicServiceMultiRichContentMessage = (function () { function PublicServiceMultiRichContentMessage(messages) { this.messageName = "PublicServiceMultiRichContentMessage"; this.richContentMessages = messages; } PublicServiceMultiRichContentMessage.prototype.encode = function () { return null; }; return PublicServiceMultiRichContentMessage; })(); RongIMLib.PublicServiceMultiRichContentMessage = PublicServiceMultiRichContentMessage; var SyncReadStatusMessage = (function () { function SyncReadStatusMessage(message) { this.messageName = "SyncReadStatusMessage"; message.lastMessageSendTime && (this.lastMessageSendTime = message.lastMessageSendTime); } SyncReadStatusMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return SyncReadStatusMessage; })(); RongIMLib.SyncReadStatusMessage = SyncReadStatusMessage; var ReadReceiptRequestMessage = (function () { function ReadReceiptRequestMessage(message) { this.messageName = "ReadReceiptRequestMessage"; message.messageUId && (this.messageUId = message.messageUId); } ReadReceiptRequestMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ReadReceiptRequestMessage; })(); RongIMLib.ReadReceiptRequestMessage = ReadReceiptRequestMessage; var ReadReceiptResponseMessage = (function () { function ReadReceiptResponseMessage(message) { this.messageName = "ReadReceiptResponseMessage"; message.receiptMessageDic && (this.receiptMessageDic = message.receiptMessageDic); } ReadReceiptResponseMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ReadReceiptResponseMessage; })(); RongIMLib.ReadReceiptResponseMessage = ReadReceiptResponseMessage; var PublicServiceRichContentMessage = (function () { function PublicServiceRichContentMessage(message) { this.messageName = "PublicServiceRichContentMessage"; this.richContentMessage = message; } PublicServiceRichContentMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return PublicServiceRichContentMessage; })(); RongIMLib.PublicServiceRichContentMessage = PublicServiceRichContentMessage; var FileMessage = (function () { function FileMessage(message) { this.messageName = "FileMessage"; message.name && (this.name = message.name); message.size && (this.size = message.size); message.type && (this.type = message.type); message.fileUrl && (this.fileUrl = message.fileUrl); message.extra && (this.extra = message.extra); message.user && (this.user = message.user); } FileMessage.obtain = function (msg) { return new FileMessage({ name: msg.name, size: msg.size, type: msg.type, fileUrl: msg.fileUrl }); }; FileMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return FileMessage; })(); RongIMLib.FileMessage = FileMessage; var AcceptMessage = (function () { function AcceptMessage(message) { this.messageName = "AcceptMessage"; this.mediaId = message.mediaId; this.callId = message.callId; this.mediaType = message.mediaType; } AcceptMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return AcceptMessage; })(); RongIMLib.AcceptMessage = AcceptMessage; var RingingMessage = (function () { function RingingMessage(message) { this.messageName = "RingingMessage"; this.callId = message.callId; } RingingMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return RingingMessage; })(); RongIMLib.RingingMessage = RingingMessage; var SummaryMessage = (function () { function SummaryMessage(message) { this.messageName = "SummaryMessage"; this.caller = message.caller; this.inviter = message.inviter; this.mediaType = message.mediaType; this.memberIdList = message.memberIdList; this.startTime = message.startTime; this.connectedTime = message.connectedTime; this.duration = message.duration; this.status = message.status; } SummaryMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return SummaryMessage; })(); RongIMLib.SummaryMessage = SummaryMessage; var HungupMessage = (function () { function HungupMessage(message) { this.messageName = "HungupMessage"; this.callId = message.callId; this.reason = message.reason; } HungupMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return HungupMessage; })(); RongIMLib.HungupMessage = HungupMessage; var InviteMessage = (function () { function InviteMessage(message) { this.messageName = "InviteMessage"; this.mediaId = message.mediaId; this.callId = message.callId; this.engineType = message.engineType; this.channelInfo = message.channelInfo; this.mediaType = message.mediaType; this.extra = message.extra; this.inviteUserIds = message.inviteUserIds; this.observerUserIds = message.observerUserIds; } InviteMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return InviteMessage; })(); RongIMLib.InviteMessage = InviteMessage; var MediaModifyMessage = (function () { function MediaModifyMessage(message) { this.messageName = "MediaModifyMessage"; this.callId = message.callId; this.mediaType = message.mediaType; } MediaModifyMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return MediaModifyMessage; })(); RongIMLib.MediaModifyMessage = MediaModifyMessage; var MemberModifyMessage = (function () { function MemberModifyMessage(message) { this.messageName = "MemberModifyMessage"; this.modifyMemType = message.modifyMemType; this.callId = message.callId; this.caller = message.caller; this.engineType = message.engineType; this.channelInfo = message.channelInfo; this.mediaType = message.mediaType; this.extra = message.extra; this.inviteUserIds = message.inviteUserIds; this.existedMemberStatusList = message.existedMemberStatusList; this.existedUserPofiles = message.existedUserPofiles; this.observerUserIds = message.observerUserIds; } MemberModifyMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return MemberModifyMessage; })(); RongIMLib.MemberModifyMessage = MemberModifyMessage; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var ChannelInfo = (function () { function ChannelInfo(Id, Key) { this.Id = Id; this.Key = Key; } return ChannelInfo; })(); RongIMLib.ChannelInfo = ChannelInfo; var UserStatus = (function () { function UserStatus(platform, online, status) { this.platform = platform; this.online = online; this.status = status; } return UserStatus; })(); RongIMLib.UserStatus = UserStatus; var MentionedInfo = (function () { function MentionedInfo(type, userIdList, mentionedContent) { } return MentionedInfo; })(); RongIMLib.MentionedInfo = MentionedInfo; var DeleteMessage = (function () { function DeleteMessage(msgId, msgDataTime, direct) { this.msgId = msgId; this.msgDataTime = msgDataTime; this.direct = direct; } return DeleteMessage; })(); RongIMLib.DeleteMessage = DeleteMessage; var CustomServiceConfig = (function () { function CustomServiceConfig(isBlack, companyName, companyUrl) { } return CustomServiceConfig; })(); RongIMLib.CustomServiceConfig = CustomServiceConfig; var CustomServiceSession = (function () { function CustomServiceSession(uid, cid, pid, isQuited, type, adminHelloWord, adminOfflineWord) { } return CustomServiceSession; })(); RongIMLib.CustomServiceSession = CustomServiceSession; var Conversation = (function () { function Conversation(conversationTitle, conversationType, draft, isTop, latestMessage, latestMessageId, notificationStatus, objectName, receivedStatus, receivedTime, senderUserId, senderUserName, sentStatus, sentTime, targetId, unreadMessageCount, senderPortraitUri, isHidden, mentionedMsg, hasUnreadMention, _readTime) { this.conversationTitle = conversationTitle; this.conversationType = conversationType; this.draft = draft; this.isTop = isTop; this.latestMessage = latestMessage; this.latestMessageId = latestMessageId; this.notificationStatus = notificationStatus; this.objectName = objectName; this.receivedStatus = receivedStatus; this.receivedTime = receivedTime; this.senderUserId = senderUserId; this.senderUserName = senderUserName; this.sentStatus = sentStatus; this.sentTime = sentTime; this.targetId = targetId; this.unreadMessageCount = unreadMessageCount; this.senderPortraitUri = senderPortraitUri; this.isHidden = isHidden; this.mentionedMsg = mentionedMsg; this.hasUnreadMention = hasUnreadMention; this._readTime = _readTime; } Conversation.prototype.setTop = function () { RongIMLib.RongIMClient._dataAccessProvider.addConversation(this, { onSuccess: function (data) { } }); }; return Conversation; })(); RongIMLib.Conversation = Conversation; var Discussion = (function () { function Discussion(creatorId, id, memberIdList, name, isOpen) { this.creatorId = creatorId; this.id = id; this.memberIdList = memberIdList; this.name = name; this.isOpen = isOpen; } return Discussion; })(); RongIMLib.Discussion = Discussion; var Group = (function () { function Group(id, name, portraitUri) { this.id = id; this.name = name; this.portraitUri = portraitUri; } return Group; })(); RongIMLib.Group = Group; var Message = (function () { function Message(content, conversationType, extra, objectName, messageDirection, messageId, receivedStatus, receivedTime, senderUserId, sentStatus, sentTime, targetId, messageType, messageUId, isLocalMessage, offLineMessage, receiptResponse) { this.content = content; this.conversationType = conversationType; this.extra = extra; this.objectName = objectName; this.messageDirection = messageDirection; this.messageId = messageId; this.receivedStatus = receivedStatus; this.receivedTime = receivedTime; this.senderUserId = senderUserId; this.sentStatus = sentStatus; this.sentTime = sentTime; this.targetId = targetId; this.messageType = messageType; this.messageUId = messageUId; this.isLocalMessage = isLocalMessage; this.offLineMessage = offLineMessage; this.receiptResponse = receiptResponse; } return Message; })(); RongIMLib.Message = Message; var MessageTag = (function () { function MessageTag(isCounted, isPersited) { this.isCounted = isCounted; this.isPersited = isPersited; } MessageTag.prototype.getMessageTag = function () { if (this.isCounted && this.isPersited) { return 3; } else if (this.isCounted) { return 2; } else if (this.isPersited) { return 1; } else if (!this.isCounted && !this.isPersited) { return 0; } }; return MessageTag; })(); RongIMLib.MessageTag = MessageTag; var PublicServiceMenuItem = (function () { function PublicServiceMenuItem(id, name, type, sunMenuItems, url) { this.id = id; this.name = name; this.type = type; this.sunMenuItems = sunMenuItems; this.url = url; } return PublicServiceMenuItem; })(); RongIMLib.PublicServiceMenuItem = PublicServiceMenuItem; // TODO: TBD var PublicServiceProfile = (function () { function PublicServiceProfile(conversationType, introduction, menu, name, portraitUri, publicServiceId, hasFollowed, isGlobal) { this.conversationType = conversationType; this.introduction = introduction; this.menu = menu; this.name = name; this.portraitUri = portraitUri; this.publicServiceId = publicServiceId; this.hasFollowed = hasFollowed; this.isGlobal = isGlobal; } return PublicServiceProfile; })(); RongIMLib.PublicServiceProfile = PublicServiceProfile; var UserInfo = (function () { function UserInfo(id, name, portraitUri) { this.id = id; this.name = name; this.portraitUri = portraitUri; } return UserInfo; })(); RongIMLib.UserInfo = UserInfo; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var ServerDataProvider = (function () { function ServerDataProvider() { this.userStatusListener = null; } ServerDataProvider.prototype.init = function (appKey, options) { new RongIMLib.FeatureDectector(options.appCallback); }; ServerDataProvider.prototype.connect = function (token, callback) { RongIMLib.RongIMClient.bridge = RongIMLib.Bridge.getInstance(); RongIMLib.RongIMClient._memoryStore.token = token; RongIMLib.RongIMClient._memoryStore.callback = callback; var isConnecting = false, isConnected = false; if (RongIMLib.Bridge._client && RongIMLib.Bridge._client.channel) { isConnecting = (RongIMLib.Bridge._client.channel.connectionStatus == RongIMLib.ConnectionStatus.CONNECTING); isConnected = (RongIMLib.Bridge._client.channel.connectionStatus == RongIMLib.ConnectionStatus.CONNECTED); } if (isConnected || isConnecting) { return; } var isGreater = (RongIMLib.RongIMClient.otherDeviceLoginCount > 5); if (isGreater) { callback.onError(RongIMLib.ConnectionStatus.ULTRALIMIT); return; } //循环设置监听事件,追加之后清空存放事件数据 for (var i = 0, len = RongIMLib.RongIMClient._memoryStore.listenerList.length; i < len; i++) { RongIMLib.RongIMClient.bridge["setListener"](RongIMLib.RongIMClient._memoryStore.listenerList[i]); } RongIMLib.RongIMClient._memoryStore.listenerList.length = 0; RongIMLib.RongIMClient.bridge.connect(RongIMLib.RongIMClient._memoryStore.appKey, token, { onSuccess: function (data) { setTimeout(function () { callback.onSuccess(data); }); }, onError: function (e) { if (e == RongIMLib.ConnectionState.TOKEN_INCORRECT || !e) { setTimeout(function () { callback.onTokenIncorrect(); }); } else { setTimeout(function () { callback.onError(e); }); } } }); }; /* config.auto: 默认 false, true 启用自动重连,启用则为必选参数 config.rate: 重试频率 [100, 1000, 3000, 6000, 10000, 18000] 单位为毫秒,可选 config.url: 网络嗅探地址 [http(s)://]cdn.ronghub.com/RongIMLib-2.2.6.min.js 可选 */ ServerDataProvider.prototype.reconnect = function (callback, config) { var store = RongIMLib.RongIMClient._memoryStore; var token = store.token; if (!token) { throw new Error('reconnect: token is empty.'); } if (RongIMLib.Bridge._client && RongIMLib.Bridge._client.channel && RongIMLib.Bridge._client.channel.connectionStatus != RongIMLib.ConnectionStatus.CONNECTED && RongIMLib.Bridge._client.channel.connectionStatus != RongIMLib.ConnectionStatus.CONNECTING) { config = config || {}; var key = config.auto ? 'auto' : 'custom'; var handler = { auto: function () { var repeatConnect = function (options) { var step = options.step(); var done = 'done'; var url = options.url; var ping = function () { RongIMLib.RongUtil.request({ url: url, success: function () { options.done(); }, error: function () { repeat(); } }); }; var repeat = function () { var next = step(); if (next == 'done') { var error = RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE; options.done(error); return; } setTimeout(ping, next); }; repeat(); }; var protocol = RongIMLib.RongIMClient._memoryStore.depend.protocol; var url = config.url || 'cdn.ronghub.com/RongIMLib-2.2.6.min.js'; var pathConfig = { protocol: protocol, path: url }; url = RongIMLib.RongUtil.formatProtoclPath(pathConfig); var rate = config.rate || [100, 1000, 3000, 6000, 10000, 18000]; //结束标识 rate.push('done'); var opts = { url: url, step: function () { var index = 0; return function () { var time = rate[index]; index++; return time; }; }, done: function (error) { if (error) { callback.onError(error); return; } RongIMLib.RongIMClient.connect(token, callback); } }; repeatConnect(opts); }, custom: function () { RongIMLib.RongIMClient.connect(token, callback); } }; handler[key](); } }; ServerDataProvider.prototype.clearData = function () { return true; }; ServerDataProvider.prototype.logout = function () { RongIMLib.RongIMClient.bridge.disconnect(); RongIMLib.RongIMClient.bridge = null; }; ServerDataProvider.prototype.disconnect = function () { RongIMLib.RongIMClient.bridge.disconnect(); }; ServerDataProvider.prototype.sendReceiptResponse = function (conversationType, targetId, sendCallback) { var rspkey = RongIMLib.Bridge._client.userId + conversationType + targetId + 'RECEIVED', me = this; if (RongIMLib.RongUtil.supportLocalStorage()) { var valObj = JSON.parse(RongIMLib.RongIMClient._storageProvider.getItem(rspkey)); if (valObj) { var vals = []; for (var key in valObj) { var tmp = {}; tmp[key] = valObj[key].uIds; valObj[key].isResponse || vals.push(tmp); } if (vals.length == 0) { sendCallback.onSuccess(); return; } var interval = setInterval(function () { if (vals.length == 1) { clearInterval(interval); } var obj = vals.splice(0, 1)[0]; var rspMsg = new RongIMLib.ReadReceiptResponseMessage({ receiptMessageDic: obj }); me.sendMessage(conversationType, targetId, rspMsg, { onSuccess: function (msg) { var senderUserId = RongIMLib.MessageUtil.getFirstKey(obj); valObj[senderUserId].isResponse = true; RongIMLib.RongIMClient._storageProvider.setItem(rspkey, JSON.stringify(valObj)); sendCallback.onSuccess(msg); }, onError: function (error, msg) { sendCallback.onError(error, msg); } }); }, 200); } else { sendCallback.onSuccess(); } } else { sendCallback.onSuccess(); } }; ServerDataProvider.prototype.sendTypingStatusMessage = function (conversationType, targetId, messageName, sendCallback) { var me = this; if (messageName in RongIMLib.RongIMClient.MessageParams) { me.sendMessage(conversationType, targetId, RongIMLib.TypingStatusMessage.obtain(RongIMLib.RongIMClient.MessageParams[messageName].objectName, ""), { onSuccess: function () { setTimeout(function () { sendCallback.onSuccess(); }); }, onError: function (errorCode) { setTimeout(function () { sendCallback.onError(errorCode, null); }); }, onBefore: function () { } }); } }; ServerDataProvider.prototype.sendRecallMessage = function (content, sendMessageCallback) { var msg = new RongIMLib.RecallCommandMessage({ conversationType: content.conversationType, targetId: content.targetId, sentTime: content.sentTime, messageUId: content.messageUId, extra: content.extra, user: content.user }); this.sendMessage(content.conversationType, content.senderUserId, msg, sendMessageCallback, false, null, null, 2); }; ServerDataProvider.prototype.sendTextMessage = function (conversationType, targetId, content, sendMessageCallback) { var msgContent = RongIMLib.TextMessage.obtain(content); this.sendMessage(conversationType, targetId, msgContent, sendMessageCallback); }; ServerDataProvider.prototype.getRemoteHistoryMessages = function (conversationType, targetId, timestamp, count, callback) { if (count <= 1) { throw new Error("the count must be greater than 1."); } var modules = new RongIMLib.RongIMClient.Protobuf.HistoryMessageInput(), self = this; modules.setTargetId(targetId); if (timestamp === 0 || timestamp > 0) { modules.setDataTime(timestamp); } else { modules.setDataTime(RongIMLib.RongIMClient._memoryStore.lastReadTime.get(conversationType + targetId)); } modules.setSize(count); RongIMLib.RongIMClient.bridge.queryMsg(HistoryMsgType[conversationType], RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), targetId, { onSuccess: function (data) { RongIMLib.RongIMClient._memoryStore.lastReadTime.set(conversationType + targetId, RongIMLib.MessageUtil.int64ToTimestamp(data.syncTime)); var list = data.list.reverse(), tempMsg = null, tempDir; var read = RongIMLib.SentStatus.READ; if (RongIMLib.RongUtil.supportLocalStorage()) { for (var i = 0, len = list.length; i < len; i++) { tempMsg = RongIMLib.MessageUtil.messageParser(list[i]); tempDir = JSON.parse(RongIMLib.RongIMClient._storageProvider.getItem(RongIMLib.Bridge._client.userId + tempMsg.messageUId + "SENT")); if (tempDir) { tempMsg.receiptResponse || (tempMsg.receiptResponse = {}); tempMsg.receiptResponse[tempMsg.messageUId] = tempDir.count; } tempMsg.sentStatus = read; tempMsg.targetId = targetId; list[i] = tempMsg; } } else { for (var i = 0, len = list.length; i < len; i++) { var tempMsg = RongIMLib.MessageUtil.messageParser(list[i]); tempMsg.sentStatus = read; list[i] = tempMsg; } } setTimeout(function () { callback.onSuccess(list, !!data.hasMsg); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }, "HistoryMessagesOuput"); }; ServerDataProvider.prototype.hasRemoteUnreadMessages = function (token, callback) { var xss = null; window.RCCallback = function (x) { setTimeout(function () { callback.onSuccess(!!+x.status); }); xss.parentNode.removeChild(xss); }; xss = document.createElement("script"); xss.src = RongIMLib.RongIMClient._memoryStore.depend.api + "/message/exist.js?appKey=" + encodeURIComponent(RongIMLib.RongIMClient._memoryStore.appKey) + "&token=" + encodeURIComponent(token) + "&callBack=RCCallback&_=" + Date.now(); document.body.appendChild(xss); xss.onerror = function () { setTimeout(function () { callback.onError(RongIMLib.ErrorCode.UNKNOWN); }); xss.parentNode.removeChild(xss); }; }; ServerDataProvider.prototype.getRemoteConversations = function(count, beginTime, order, callback){ callback.onSuccess(); }; ServerDataProvider.prototype.getRemoteConversationList = function (callback, conversationTypes, count) { var modules = new RongIMLib.RongIMClient.Protobuf.RelationsInput(), self = this; modules.setType(1); if (typeof count == 'undefined') { modules.setCount(0); } else { modules.setCount(count); } RongIMLib.RongIMClient.bridge.queryMsg(26, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (list) { if (list.info) { list.info = list.info.reverse(); for (var i = 0, len = list.info.length; i < len; i++) { RongIMLib.RongIMClient.getInstance().pottingConversation(list.info[i]); } } if (conversationTypes) { var convers = []; Array.forEach(conversationTypes, function (converType) { Array.forEach(RongIMLib.RongIMClient._memoryStore.conversationList, function (item) { if (item.conversationType == converType) { convers.push(item); } }); }); setTimeout(function () { callback.onSuccess(convers); }); } else { setTimeout(function () { callback.onSuccess(RongIMLib.RongIMClient._memoryStore.conversationList); }); } }, onError: function (error) { callback.onError(error); } }, "RelationsOutput"); }; ServerDataProvider.prototype.addMemberToDiscussion = function (discussionId, userIdList, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.ChannelInvitationInput(); modules.setUsers(userIdList); RongIMLib.RongIMClient.bridge.queryMsg(0, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), discussionId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.createDiscussion = function (name, userIdList, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.CreateDiscussionInput(), self = this; modules.setName(name); RongIMLib.RongIMClient.bridge.queryMsg(1, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (discussId) { if (userIdList.length > 0) { self.addMemberToDiscussion(discussId, userIdList, { onSuccess: function () { }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); } setTimeout(function () { callback.onSuccess(discussId); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }, "CreateDiscussionOutput"); }; ServerDataProvider.prototype.getDiscussion = function (discussionId, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.ChannelInfoInput(); modules.setNothing(1); RongIMLib.RongIMClient.bridge.queryMsg(4, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), discussionId, { onSuccess: function (data) { setTimeout(function () { callback.onSuccess(data); }); }, onError: function (errorCode) { setTimeout(function () { callback.onError(errorCode); }); } }, "ChannelInfoOutput"); }; ServerDataProvider.prototype.quitDiscussion = function (discussionId, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.LeaveChannelInput(); modules.setNothing(1); RongIMLib.RongIMClient.bridge.queryMsg(7, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), discussionId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (errorCode) { setTimeout(function () { callback.onError(errorCode); }); } }); }; ServerDataProvider.prototype.removeMemberFromDiscussion = function (discussionId, userId, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.ChannelEvictionInput(); modules.setUser(userId); RongIMLib.RongIMClient.bridge.queryMsg(9, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), discussionId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (errorCode) { setTimeout(function () { callback.onError(errorCode); }); } }); }; ServerDataProvider.prototype.setDiscussionInviteStatus = function (discussionId, status, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.ModifyPermissionInput(); modules.setOpenStatus(status.valueOf()); RongIMLib.RongIMClient.bridge.queryMsg(11, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), discussionId, { onSuccess: function (x) { setTimeout(function () { callback.onSuccess(); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.setDiscussionName = function (discussionId, name, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RenameChannelInput(); modules.setName(name); RongIMLib.RongIMClient.bridge.queryMsg(12, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), discussionId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (errcode) { callback.onError(errcode); } }); }; ServerDataProvider.prototype.joinChatRoom = function (chatroomId, messageCount, callback) { var e = new RongIMLib.RongIMClient.Protobuf.ChrmInput(); e.setNothing(1); RongIMLib.Bridge._client.chatroomId = chatroomId; RongIMLib.RongIMClient.bridge.queryMsg(19, RongIMLib.MessageUtil.ArrayForm(e.toArrayBuffer()), chatroomId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); var modules = new RongIMLib.RongIMClient.Protobuf.ChrmPullMsg(); messageCount == 0 && (messageCount = -1); modules.setCount(messageCount); modules.setSyncTime(0); RongIMLib.Bridge._client.queryMessage("chrmPull", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), chatroomId, 1, { onSuccess: function (collection) { var list = collection.list; var sync = RongIMLib.MessageUtil.int64ToTimestamp(collection.syncTime); var latestMessage = list[list.length - 1]; if (latestMessage) { latestMessage = RongIMLib.MessageUtil.messageParser(latestMessage); sync = latestMessage.sentTime; } RongIMLib.RongIMClient._memoryStore.lastReadTime.set(chatroomId + RongIMLib.Bridge._client.userId + "CST", sync); var _client = RongIMLib.Bridge._client; for (var i = 0, mlen = list.length; i < mlen; i++) { var uId = 'R' + list[i].msgId; if (!(uId in _client.cacheMessageIds)) { _client.cacheMessageIds[uId] = true; var cacheUIds = RongIMLib.RongUtil.keys(_client.cacheMessageIds); if (cacheUIds.length > 10) { uId = cacheUIds[0]; delete _client.cacheMessageIds[uId]; } if (RongIMLib.RongIMClient._memoryStore.filterMessages.length > 0) { for (var j = 0, flen = RongIMLib.RongIMClient._memoryStore.filterMessages.length; j < flen; j++) { if (RongIMLib.RongIMClient.MessageParams[RongIMLib.RongIMClient._memoryStore.filterMessages[j]].objectName != list[i].classname) { _client.handler.onReceived(list[i]); } } } else { _client.handler.onReceived(list[i]); } } } }, onError: function (x) { setTimeout(function () { callback.onError(RongIMLib.ErrorCode.CHATROOM_HISMESSAGE_ERROR); }); } }, "DownStreamMessages"); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }, "ChrmOutput"); }; ServerDataProvider.prototype.getChatRoomInfo = function (chatRoomId, count, order, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.QueryChatroomInfoInput(); modules.setCount(count); modules.setOrder(order); RongIMLib.RongIMClient.bridge.queryMsg("queryChrmI", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), chatRoomId, { onSuccess: function (ret) { var userInfos = ret.userInfos; userInfos.forEach(function (item) { item.time = RongIMLib.MessageUtil.int64ToTimestamp(item.time); }); setTimeout(function () { callback.onSuccess(ret); }); }, onError: function (errcode) { setTimeout(function () { callback.onError(errcode); }); } }, "QueryChatroomInfoOutput"); }; ServerDataProvider.prototype.quitChatRoom = function (chatroomId, callback) { var e = new RongIMLib.RongIMClient.Protobuf.ChrmInput(); e.setNothing(1); RongIMLib.RongIMClient.bridge.queryMsg(17, RongIMLib.MessageUtil.ArrayForm(e.toArrayBuffer()), chatroomId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (errcode) { setTimeout(function () { callback.onError(errcode); }); } }, "ChrmOutput"); }; ServerDataProvider.prototype.setChatroomHisMessageTimestamp = function (chatRoomId, timestamp) { RongIMLib.RongIMClient._memoryStore.lastReadTime.set('chrhis_' + chatRoomId, timestamp); }; ServerDataProvider.prototype.getChatRoomHistoryMessages = function (chatRoomId, count, order, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.HistoryMsgInput(); modules.setTargetId(chatRoomId); var timestamp = RongIMLib.RongIMClient._memoryStore.lastReadTime.get('chrhis_' + chatRoomId) || 0; modules.setTime(timestamp); modules.setCount(count); modules.setOrder(order); RongIMLib.RongIMClient.bridge.queryMsg(34, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (data) { RongIMLib.RongIMClient._memoryStore.lastReadTime.set('chrhis_' + chatRoomId, RongIMLib.MessageUtil.int64ToTimestamp(data.syncTime)); var list = data.list.reverse(); for (var i = 0, len = list.length; i < len; i++) { list[i] = RongIMLib.MessageUtil.messageParser(list[i]); } setTimeout(function () { callback.onSuccess(list, !!data.hasMsg); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }, "HistoryMsgOuput"); }; ServerDataProvider.prototype.setMessageStatus = function (conversationType, targetId, timestamp, status, callback) { setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.addToBlacklist = function (userId, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.Add2BlackListInput(); modules.setUserId(userId); RongIMLib.RongIMClient.bridge.queryMsg(21, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.getBlacklist = function (callback) { var modules = new RongIMLib.RongIMClient.Protobuf.QueryBlackListInput(); modules.setNothing(1); RongIMLib.RongIMClient.bridge.queryMsg(23, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (list) { setTimeout(function () { callback.onSuccess(list); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }, "QueryBlackListOutput"); }; ServerDataProvider.prototype.getBlacklistStatus = function (userId, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.BlackListStatusInput(); modules.setUserId(userId); RongIMLib.RongIMClient.bridge.queryMsg(24, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function (status) { setTimeout(function () { callback.onSuccess(RongIMLib.BlacklistStatus[status]); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.removeFromBlacklist = function (userId, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RemoveFromBlackListInput(); modules.setUserId(userId); RongIMLib.RongIMClient.bridge.queryMsg(22, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.getFileToken = function (fileType, callback) { if (!(/(1|2|3|4)/.test(fileType.toString()))) { setTimeout(function () { callback.onError(RongIMLib.ErrorCode.QNTKN_FILETYPE_ERROR); }); return; } var modules = new RongIMLib.RongIMClient.Protobuf.GetQNupTokenInput(); modules.setType(fileType); RongIMLib.RongIMClient.bridge.queryMsg(30, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (data) { setTimeout(function () { callback.onSuccess(data); }); }, onError: function (errcode) { setTimeout(function () { callback.onError(errcode); }); } }, "GetQNupTokenOutput"); }; ServerDataProvider.prototype.getFileUrl = function (fileType, fileName, oriName, callback) { if (!(/(1|2|3|4)/.test(fileType.toString()))) { setTimeout(function () { callback.onError(RongIMLib.ErrorCode.QNTKN_FILETYPE_ERROR); }); return; } var modules = new RongIMLib.RongIMClient.Protobuf.GetQNdownloadUrlInput(); modules.setType(fileType); modules.setKey(fileName); if (oriName) { modules.setFileName(oriName); } RongIMLib.RongIMClient.bridge.queryMsg(31, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (data) { setTimeout(function () { callback.onSuccess(data); }); }, onError: function (errcode) { setTimeout(function () { callback.onError(errcode); }); } }, "GetQNdownloadUrlOutput"); }; /* methodType 1 : 多客服(客服后台使用); 2 : 消息撤回 params.userIds : 定向消息接收者 */ ServerDataProvider.prototype.sendMessage = function (conversationType, targetId, messageContent, sendCallback, mentiondMsg, pushText, appData, methodType, params) { if (!RongIMLib.Bridge._client.channel) { setTimeout(function () { sendCallback.onError(RongIMLib.ErrorCode.RC_NET_UNAVAILABLE, null); }); return; } if (!RongIMLib.Bridge._client.channel.socket.socket.connected) { setTimeout(function () { sendCallback.onError(RongIMLib.ErrorCode.TIMEOUT, null); }); throw new Error("connect is timeout! postion:sendMessage"); } var isGroup = (conversationType == RongIMLib.ConversationType.DISCUSSION || conversationType == RongIMLib.ConversationType.GROUP); var modules = new RongIMLib.RongIMClient.Protobuf.UpStreamMessage(); if (mentiondMsg && isGroup) { modules.setSessionId(7); } else { modules.setSessionId(RongIMLib.RongIMClient.MessageParams[messageContent.messageName].msgTag.getMessageTag()); } pushText && modules.setPushText(pushText); appData && modules.setAppData(appData); if (isGroup && messageContent.messageName == RongIMLib.RongIMClient.MessageType["ReadReceiptResponseMessage"]) { var rspMsg = messageContent; if (rspMsg.receiptMessageDic) { var ids = []; for (var key in rspMsg.receiptMessageDic) { ids.push(key); } modules.setUserId(ids); } } if (isGroup && messageContent.messageName == RongIMLib.RongIMClient.MessageType["SyncReadStatusMessage"]) { modules.setUserId(RongIMLib.Bridge._client.userId); } params = params || {}; var userIds = params.userIds; if (isGroup && userIds) { modules.setUserId(userIds); } modules.setClassname(RongIMLib.RongIMClient.MessageParams[messageContent.messageName].objectName); modules.setContent(messageContent.encode()); var content = modules.toArrayBuffer(); if (Object.prototype.toString.call(content) == "[object ArrayBuffer]") { content = [].slice.call(new Int8Array(content)); } var me = this, msg = new RongIMLib.Message(); var c = this.getConversation(conversationType, targetId, { onSuccess: function (conver) {}, onError: function(){} }); if (RongIMLib.RongIMClient.MessageParams[messageContent.messageName].msgTag.getMessageTag() == 3) { if (!c) { c = RongIMLib.RongIMClient.getInstance().createConversation(conversationType, targetId, ""); } c.sentTime = new Date().getTime(); c.sentStatus = RongIMLib.SentStatus.SENDING; c.senderUserName = ""; c.senderUserId = RongIMLib.Bridge._client.userId; c.notificationStatus = RongIMLib.ConversationNotificationStatus.DO_NOT_DISTURB; c.latestMessage = msg; c.unreadMessageCount = 0; RongIMLib.RongIMClient._dataAccessProvider.addConversation(c, { onSuccess: function (data) { } }); } RongIMLib.RongIMClient._memoryStore.converStore = c; msg.content = messageContent; msg.conversationType = conversationType; msg.senderUserId = RongIMLib.Bridge._client.userId; msg.objectName = RongIMLib.RongIMClient.MessageParams[messageContent.messageName].objectName; msg.targetId = targetId; msg.sentTime = new Date().getTime(); msg.messageDirection = RongIMLib.MessageDirection.SEND; msg.sentStatus = RongIMLib.SentStatus.SENT; msg.messageType = messageContent.messageName; RongIMLib.RongIMClient.bridge.pubMsg(conversationType.valueOf(), content, targetId, { onSuccess: function (data, code) { if (data && data.timestamp) { RongIMLib.RongIMClient._memoryStore.lastReadTime.set('converST_' + RongIMLib.Bridge._client.userId + conversationType + targetId, data.timestamp); } if ((conversationType == RongIMLib.ConversationType.DISCUSSION || conversationType == RongIMLib.ConversationType.GROUP) && messageContent.messageName == RongIMLib.RongIMClient.MessageType["ReadReceiptRequestMessage"]) { var reqMsg = msg.content; var sentkey = RongIMLib.Bridge._client.userId + reqMsg.messageUId + "SENT"; RongIMLib.RongIMClient._storageProvider.setItem(sentkey, JSON.stringify({ count: 0, dealtime: data.timestamp, userIds: {} })); } if (RongIMLib.RongIMClient.MessageParams[msg.messageType].msgTag.getMessageTag() == 3) { var cacheConversation = c || {}; cacheConversation.sentStatus = msg.sentStatus; cacheConversation.latestMessage = msg; me.updateConversation(cacheConversation); RongIMLib.RongIMClient._dataAccessProvider.addMessage(conversationType, targetId, msg, { onSuccess: function (ret) { msg = ret; msg.messageUId = data.messageUId; msg.sentTime = data.timestamp; msg.sentStatus = RongIMLib.SentStatus.SENT; msg.messageId = data.messageId; RongIMLib.RongIMClient._dataAccessProvider.updateMessage(msg); }, onError: function () { } }); } setTimeout(function () { cacheConversation && me.updateConversation(cacheConversation); msg.sentTime = data.timestamp; msg.messageUId = data.messageUId; sendCallback.onSuccess(msg, code); }); }, onError: function (errorCode, data) { msg.messageUId = data.messageUId || msg.messageUId; msg.sentTime = data.timestamp || msg.sentTime; msg.sentStatus = RongIMLib.SentStatus.FAILED; if (RongIMLib.RongIMClient.MessageParams[msg.messageType].msgTag.getMessageTag() == 3) { (c || {}).latestMessage = msg; } RongIMLib.RongIMClient._dataAccessProvider.addMessage(conversationType, targetId, msg, { onSuccess: function (ret) { msg.messageId = ret.messageId; RongIMLib.RongIMClient._dataAccessProvider.updateMessage(msg); }, onError: function () { } }); setTimeout(function () { sendCallback.onError(errorCode, msg); }); } }, null, methodType); sendCallback.onBefore && sendCallback.onBefore(RongIMLib.MessageIdHandler.messageId); msg.messageId = RongIMLib.MessageIdHandler.messageId + ""; }; ServerDataProvider.prototype.setConnectionStatusListener = function (listener) { if (RongIMLib.RongIMClient.bridge) { RongIMLib.RongIMClient.bridge.setListener(listener); } else { RongIMLib.RongIMClient._memoryStore.listenerList.push(listener); } }; ServerDataProvider.prototype.setOnReceiveMessageListener = function (listener) { if (RongIMLib.RongIMClient.bridge) { RongIMLib.RongIMClient.bridge.setListener(listener); } else { RongIMLib.RongIMClient._memoryStore.listenerList.push(listener); } }; ServerDataProvider.prototype.registerMessageType = function (messageType, objectName, messageTag, messageContent) { if (!messageType) { throw new Error("messageType can't be empty,postion -> registerMessageType"); } if (!objectName) { throw new Error("objectName can't be empty,postion -> registerMessageType"); } if (Object.prototype.toString.call(messageContent) == "[object Array]") { var regMsg = RongIMLib.ModelUtil.modleCreate(messageContent, messageType); RongIMLib.RongIMClient.RegisterMessage[messageType] = regMsg; } else if (Object.prototype.toString.call(messageContent) == "[object Function]" || Object.prototype.toString.call(messageContent) == "[object Object]") { if (!messageContent.encode) { throw new Error("encode method has not realized or messageName is undefined-> registerMessageType"); } if (!messageContent.decode) { throw new Error("decode method has not realized -> registerMessageType"); } } else { throw new Error("The index of 3 parameter was wrong type must be object or function or array-> registerMessageType"); } registerMessageTypeMapping[objectName] = messageType; }; ServerDataProvider.prototype.addConversation = function (conversation, callback) { var isAdd = true; for (var i = 0, len = RongIMLib.RongIMClient._memoryStore.conversationList.length; i < len; i++) { if (RongIMLib.RongIMClient._memoryStore.conversationList[i].conversationType === conversation.conversationType && RongIMLib.RongIMClient._memoryStore.conversationList[i].targetId === conversation.targetId) { RongIMLib.RongIMClient._memoryStore.conversationList.unshift(RongIMLib.RongIMClient._memoryStore.conversationList.splice(i, 1)[0]); isAdd = false; break; } } if (isAdd) { RongIMLib.RongIMClient._memoryStore.conversationList.unshift(conversation); } callback && callback.onSuccess(true); }; ServerDataProvider.prototype.updateConversation = function (conversation) { var conver; for (var i = 0, len = RongIMLib.RongIMClient._memoryStore.conversationList.length; i < len; i++) { var item = RongIMLib.RongIMClient._memoryStore.conversationList[i]; if (conversation.conversationType === item.conversationType && conversation.targetId === item.targetId) { conversation.conversationTitle && (item.conversationTitle = conversation.conversationTitle); conversation.senderUserName && (item.senderUserName = conversation.senderUserName); conversation.senderPortraitUri && (item.senderPortraitUri = conversation.senderPortraitUri); conversation.latestMessage && (item.latestMessage = conversation.latestMessage); conversation.sentStatus && (item.sentStatus = conversation.sentStatus); break; } } return conver; }; ServerDataProvider.prototype.removeConversation = function (conversationType, targetId, callback) { var mod = new RongIMLib.RongIMClient.Protobuf.RelationsInput(); mod.setType(conversationType); RongIMLib.RongIMClient.bridge.queryMsg(27, RongIMLib.MessageUtil.ArrayForm(mod.toArrayBuffer()), targetId, { onSuccess: function () { var conversations = RongIMLib.RongIMClient._memoryStore.conversationList; var len = conversations.length; for (var i = 0; i < len; i++) { if (conversations[i].conversationType == conversationType && targetId == conversations[i].targetId) { conversations.splice(i, 1); break; } } callback.onSuccess(true); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.getMessage = function (messageId, callback) { callback.onSuccess(new RongIMLib.Message()); }; ServerDataProvider.prototype.addMessage = function (conversationType, targetId, message, callback) { if (callback) { callback.onSuccess(message); } }; ServerDataProvider.prototype.removeMessage = function (conversationType, targetId, messageIds, callback) { RongIMLib.RongIMClient.getInstance().deleteRemoteMessages(conversationType, targetId, messageIds, callback); }; ServerDataProvider.prototype.removeLocalMessage = function (conversationType, targetId, timestamps, callback) { callback.onSuccess(true); }; ServerDataProvider.prototype.updateMessage = function (message, callback) { if (callback) { callback.onSuccess(message); } }; ServerDataProvider.prototype.clearRemoteHistoryMessages = function (params, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.CleanHisMsgInput(); var conversationType = params.conversationType; var _topic = { 1: 'cleanPMsg', 2: 'cleanDMsg', 3: 'cleanGMsg', 5: 'cleanCMsg', 6: 'cleanSMsg' }; var topic = _topic[conversationType]; if (!topic) { callback.onError(RongIMLib.ErrorCode.CLEAR_HIS_TYPE_ERROR); return; } var timestamp = params.timestamp; if (typeof timestamp != 'number') { callback.onError(RongIMLib.ErrorCode.CLEAR_HIS_TIME_ERROR); return; } modules.setDataTime(timestamp); var targetId = params.targetId; modules.setTargetId(targetId); RongIMLib.RongIMClient.bridge.queryMsg(topic, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), targetId, { onSuccess: function (result) { callback.onSuccess(!result); }, onError: function (error) { // error 1 历史消息云存储没有开通、传入时间大于服务器时间 清除失败,1 与其他错误码冲突,所以自定义错误码返回 if (error == 1) { error = RongIMLib.ErrorCode.CLEAR_HIS_ERROR; } setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.clearHistoryMessages = function (params, callback) { this.clearRemoteHistoryMessages(params, callback); }; // 兼容老版本 ServerDataProvider.prototype.clearMessages = function (conversationType, targetId, callback) { }; ServerDataProvider.prototype.updateMessages = function (conversationType, targetId, key, value, callback) { var me = this; if (key == "readStatus") { if (RongIMLib.RongIMClient._memoryStore.conversationList.length > 0) { me.getConversationList({ onSuccess: function (list) { Array.forEach(list, function (conver) { if (conver.conversationType == conversationType && conver.targetId == targetId) { conver.unreadMessageCount = 0; } }); }, onError: function (errorCode) { setTimeout(function () { callback.onError(errorCode); }); } }, null); } } setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.getConversation = function (conversationType, targetId, callback) { var conver = null; for (var i = 0, len = RongIMLib.RongIMClient._memoryStore.conversationList.length; i < len; i++) { if (RongIMLib.RongIMClient._memoryStore.conversationList[i].conversationType == conversationType && RongIMLib.RongIMClient._memoryStore.conversationList[i].targetId == targetId) { conver = RongIMLib.RongIMClient._memoryStore.conversationList[i]; if (RongIMLib.RongUtil.supportLocalStorage()) { var count = RongIMLib.RongIMClient._storageProvider.getItem("cu" + RongIMLib.Bridge._client.userId + conversationType + targetId); if (conver.unreadMessageCount == 0) { conver.unreadMessageCount = Number(count); } } } } setTimeout(function () { callback.onSuccess(conver); }); return conver; }; /* WebSDK 不支持会话列表分页, 内部获取全量会话列表 */ ServerDataProvider.prototype.getConversationsByPage = function(conversation, callbacks){ var isSync = RongIMLib.RongIMClient._memoryStore.isSyncRemoteConverList; var list = RongIMLib.RongIMClient._memoryStore.conversationList; if (!isSync) { setTimeout(function () { callbacks.onSuccess(list); }); return; } var conversationTypes = null; var count = conversation.count; RongIMLib.RongIMClient.getInstance().getRemoteConversationList({ onSuccess: function (list) { if (RongIMLib.RongUtil.supportLocalStorage()) { Array.forEach(RongIMLib.RongIMClient._memoryStore.conversationList, function (item) { var count = RongIMLib.RongIMClient._storageProvider.getItem("cu" + RongIMLib.Bridge._client.userId + item.conversationType + item.targetId); if (item.unreadMessageCount == 0) { item.unreadMessageCount = Number(count); } }); } RongIMLib.RongIMClient._memoryStore.isSyncRemoteConverList = false; setTimeout(function () { callbacks.onSuccess(list); }); }, onError: function (errorcode) { setTimeout(function () { callbacks.onError(errorcode); }); } }, conversationTypes, count); }, ServerDataProvider.prototype.getConversationList = function (callback, conversationTypes, count, isHidden) { var isSync = RongIMLib.RongIMClient._memoryStore.isSyncRemoteConverList; var list = RongIMLib.RongIMClient._memoryStore.conversationList; if (!isSync) { setTimeout(function () { callback.onSuccess(list); }); return; } RongIMLib.RongIMClient.getInstance().getRemoteConversationList({ onSuccess: function (list) { if (RongIMLib.RongUtil.supportLocalStorage()) { Array.forEach(RongIMLib.RongIMClient._memoryStore.conversationList, function (item) { var count = RongIMLib.RongIMClient._storageProvider.getItem("cu" + RongIMLib.Bridge._client.userId + item.conversationType + item.targetId); if (item.unreadMessageCount == 0) { item.unreadMessageCount = Number(count); } }); } RongIMLib.RongIMClient._memoryStore.isSyncRemoteConverList = false; setTimeout(function () { callback.onSuccess(list); }); }, onError: function (errorcode) { setTimeout(function () { callback.onError(errorcode); }); } }, conversationTypes, count, isHidden); }; ServerDataProvider.prototype.clearCache = function () { var memoryStore = RongIMLib.RongIMClient._memoryStore || {}; memoryStore.conversationList = []; memoryStore.isSyncRemoteConverList = true; }; ServerDataProvider.prototype.clearConversations = function (conversationTypes, callback) { Array.forEach(conversationTypes, function (conversationType) { Array.forEach(RongIMLib.RongIMClient._memoryStore.conversationList, function (conver) { if (conversationType == conver.conversationType) { RongIMLib.RongIMClient.getInstance().removeConversation(conver.conversationType, conver.targetId, { onSuccess: function () { }, onError: function () { } }); } }); }); setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.setMessageContent = function (messageId, content, objectname) { }; ; ServerDataProvider.prototype.getHistoryMessages = function (conversationType, targetId, timestamp, count, callback) { RongIMLib.RongIMClient.getInstance().getRemoteHistoryMessages(conversationType, targetId, timestamp, count, callback); }; ServerDataProvider.prototype.getTotalUnreadCount = function (callback, conversationTypes) { var count = 0; if (conversationTypes) { for (var i = 0, len = conversationTypes.length; i < len; i++) { Array.forEach(RongIMLib.RongIMClient._memoryStore.conversationList, function (conver) { if (conver.conversationType == conversationTypes[i]) { count += conver.unreadMessageCount; } }); } } else { Array.forEach(RongIMLib.RongIMClient._memoryStore.conversationList, function (conver) { count += conver.unreadMessageCount; }); } callback.onSuccess(count); return count; }; ServerDataProvider.prototype.getConversationUnreadCount = function (conversationTypes, callback) { var count = 0; Array.forEach(conversationTypes, function (converType) { Array.forEach(RongIMLib.RongIMClient._memoryStore.conversationList, function (conver) { if (conver.conversationType == converType) { count += conver.unreadMessageCount; } }); }); setTimeout(function () { callback.onSuccess(count); }); }; ServerDataProvider.prototype.getUnreadCount = function (conversationType, targetId, callback) { var conversation = this.getConversation(conversationType, targetId, { onSuccess: function (conver) { setTimeout(function () { callback.onSuccess(conver ? conver.unreadMessageCount : 0); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); return conversation.unreadMessageCount || 0; }; ServerDataProvider.prototype.clearUnreadCountByTimestamp = function (conversationType, targetId, timestamp, callback) { setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.clearUnreadCount = function (conversationType, targetId, callback) { RongIMLib.RongIMClient._storageProvider.removeItem("cu" + RongIMLib.Bridge._client.userId + conversationType + targetId); this.getConversation(conversationType, targetId, { onSuccess: function (conver) { if (conver) { conver.unreadMessageCount = 0; conver.mentionedMsg = null; var mentioneds = RongIMLib.RongIMClient._storageProvider.getItem("mentioneds_" + RongIMLib.Bridge._client.userId + '_' + conversationType + '_' + targetId); if (mentioneds) { var info = JSON.parse(mentioneds); delete info[conversationType + "_" + targetId]; if (!RongIMLib.MessageUtil.isEmpty(info)) { RongIMLib.RongIMClient._storageProvider.setItem("mentioneds_" + RongIMLib.Bridge._client.userId + '_' + conversationType + '_' + targetId, JSON.stringify(info)); } else { RongIMLib.RongIMClient._storageProvider.removeItem("mentioneds_" + RongIMLib.Bridge._client.userId + '_' + conversationType + '_' + targetId); } } } setTimeout(function () { callback.onSuccess(true); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.setConversationToTop = function (conversationType, targetId, isTop, callback) { var me = this; this.getConversation(conversationType, targetId, { onSuccess: function (conver) { conver.isTop = isTop; me.addConversation(conver, callback); setTimeout(function () { callback.onSuccess(true); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.getConversationNotificationStatus = function (params, callback) { var targetId = params.targetId; var conversationType = params.conversationType; var notification = RongIMLib.RongIMClient._memoryStore.notification; var getKey = function () { return conversationType + '_' + targetId; }; var key = getKey(); var status = notification[key]; if (typeof status == 'number') { callback.onSuccess(status); return; } var topics = { 1: 'qryPPush', 3: 'qryDPush' }; var topic = topics[conversationType]; if (!topic) { var error = 8001; callback.onError(error); return; } var modules = new RongIMLib.RongIMClient.Protobuf.BlockPushInput(); modules.setBlockeeId(targetId); var userId = RongIMLib.Bridge._client.userId; var success = function (status) { notification[key] = status; setTimeout(function () { callback.onSuccess(status); }); }; RongIMLib.RongIMClient.bridge.queryMsg(topic, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function (status) { success(status); }, onError: function (e) { if (e == 1) { success(e); } else { setTimeout(function () { callback.onError(e); }); } } }); }; ServerDataProvider.prototype.setConversationNotificationStatus = function (params, callback) { var conversationType = params.conversationType; var targetId = params.targetId; var status = params.status; var getKey = function () { return conversationType + '_' + status; }; var topics = { '1_1': 'blkPPush', '3_1': 'blkDPush', '1_0': 'unblkPPush', '3_0': 'unblkDPush' }; var key = getKey(); var notification = RongIMLib.RongIMClient._memoryStore.notification; notification[key] = status; var topic = topics[key]; if (!topic) { var error = 8001; setTimeout(function () { callback.onError(error); }); return; } var modules = new RongIMLib.RongIMClient.Protobuf.BlockPushInput(); modules.setBlockeeId(targetId); var userId = RongIMLib.Bridge._client.userId; RongIMLib.RongIMClient.bridge.queryMsg(topic, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function (status) { setTimeout(function () { callback.onSuccess(status); }); }, onError: function (e) { setTimeout(function () { callback.onError(e); }); } }); }; ServerDataProvider.prototype.getUserStatus = function (userId, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.GetUserStatusInput(); userId = RongIMLib.Bridge._client.userId; RongIMLib.RongIMClient.bridge.queryMsg(35, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function (status) { status = RongIMLib.RongInnerTools.convertUserStatus(status); setTimeout(function () { callback.onSuccess(status); }); }, onError: function (e) { setTimeout(function () { callback.onError(e); }); } }, 'GetUserStatusOutput'); // callback.onSuccess(new UserStatus()); }; ServerDataProvider.prototype.setUserStatus = function (status, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.SetUserStatusInput(); var userId = RongIMLib.Bridge._client.userId; if (status) { modules.setStatus(status); } RongIMLib.RongIMClient.bridge.queryMsg(36, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function (status) { setTimeout(function () { callback.onSuccess(true); }); }, onError: function (e) { setTimeout(function () { callback.onError(e); }); } }, 'SetUserStatusOutput'); }; ServerDataProvider.prototype.subscribeUserStatus = function (userIds, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.SubUserStatusInput(); var userId = RongIMLib.Bridge._client.userId; modules.setUserid(userIds); RongIMLib.RongIMClient.bridge.queryMsg(37, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function (status) { setTimeout(function () { callback && callback.onSuccess(true); }); }, onError: function (e) { setTimeout(function () { callback && callback.onError(e); }); } }, 'SubUserStatusOutput'); }; ServerDataProvider.prototype.setUserStatusListener = function (params, callback) { RongIMLib.RongIMClient.userStatusListener = callback; var userIds = params.userIds || []; if (userIds.length) { RongIMLib.RongIMClient._dataAccessProvider.subscribeUserStatus(userIds); } }; ServerDataProvider.prototype.clearListeners = function () { }; ServerDataProvider.prototype.setServerInfo = function (info) { }; ServerDataProvider.prototype.getUnreadMentionedMessages = function (conversationType, targetId) { return null; }; ServerDataProvider.prototype.setConversationHidden = function (conversationType, targetId, isHidden) { }; ServerDataProvider.prototype.setMessageExtra = function (messageId, value, callback) { setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.setMessageReceivedStatus = function (messageId, receivedStatus, callback) { setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.setMessageSentStatus = function (messageId, sentStatus, callback) { setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.getAllConversations = function (callback) { setTimeout(function () { callback.onSuccess([]); }); }; ServerDataProvider.prototype.getConversationByContent = function (keywords, callback) { setTimeout(function () { callback.onSuccess([]); }); }; ServerDataProvider.prototype.getMessagesFromConversation = function (conversationType, targetId, keywords, callback) { setTimeout(function () { callback.onSuccess([]); }); }; ServerDataProvider.prototype.searchConversationByContent = function (keyword, callback, conversationTypes, customMsgTypes) { setTimeout(function () { callback.onSuccess([]); }); }; ServerDataProvider.prototype.searchMessageByContent = function (conversationType, targetId, keyword, timestamp, count, total, callback) { setTimeout(function () { callback.onSuccess([]); }); }; ServerDataProvider.prototype.getDelaTime = function () { return RongIMLib.RongIMClient._memoryStore.deltaTime; }; ServerDataProvider.prototype.getCurrentConnectionStatus = function () { var client = RongIMLib.Bridge._client || {}; var channel = client.channel || {}; var status = RongIMLib.ConnectionStatus.CONNECTION_CLOSED; if (typeof channel.connectionStatus == 'number') { status = channel.connectionStatus; } return status; }; ServerDataProvider.prototype.getAgoraDynamicKey = function (engineType, channelName, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.VoipDynamicInput(); modules.setEngineType(engineType); modules.setChannelName(channelName); RongIMLib.RongIMClient.bridge.queryMsg(32, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (result) { setTimeout(function () { callback.onSuccess(result); }); }, onError: function (errorCode) { setTimeout(function () { callback.onError(errorCode); }); } }, "VoipDynamicOutput"); }; ServerDataProvider.prototype.setDeviceInfo = function (deviceId) { }; ServerDataProvider.prototype.setEnvironment = function (isPrivate) { }; ServerDataProvider.prototype.getPublicServiceProfile = function (publicServiceType, publicServiceId, callback) { var profile = RongIMLib.RongIMClient._memoryStore.publicServiceMap.get(publicServiceType, publicServiceId); setTimeout(function () { callback.onSuccess(profile); }); }; ServerDataProvider.prototype.getRemotePublicServiceList = function (callback, pullMessageTime) { if (RongIMLib.RongIMClient._memoryStore.depend.openMp) { var modules = new RongIMLib.RongIMClient.Protobuf.PullMpInput(), self = this; if (!pullMessageTime) { modules.setTime(0); } else { modules.setTime(pullMessageTime); } modules.setMpid(""); RongIMLib.RongIMClient.bridge.queryMsg(28, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (data) { //TODO 找出最大时间 // self.lastReadTime.set(conversationType + targetId, MessageUtil.int64ToTimestamp(data.syncTime)); RongIMLib.RongIMClient._memoryStore.publicServiceMap.publicServiceList.length = 0; RongIMLib.RongIMClient._memoryStore.publicServiceMap.publicServiceList = data; setTimeout(function () { callback && callback.onSuccess(data); }); }, onError: function (errorCode) { setTimeout(function () { callback && callback.onError(errorCode); }); } }, "PullMpOutput"); } }; return ServerDataProvider; })(); RongIMLib.ServerDataProvider = ServerDataProvider; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var VCDataProvider = (function () { function VCDataProvider(addon) { this.userId = ""; this.useConsole = false; this.appKey = ""; this.token = ""; this.addon = addon; } VCDataProvider.prototype.init = function (appKey, config) { this.appKey = appKey; this.useConsole && console.log("init"); config = config || {}; var sdkInfo = this.addon.initWithAppkey(appKey, config.dbPath); if (sdkInfo) { sdkInfo = JSON.parse(sdkInfo); } // 0 不存不计数 1 只存不计数 3 存且计数 this.addon.registerMessageType("RC:VcMsg", 3); this.addon.registerMessageType("RC:ImgTextMsg", 3); this.addon.registerMessageType("RC:FileMsg", 3); this.addon.registerMessageType("RC:LBSMsg", 3); this.addon.registerMessageType("RC:PSImgTxtMsg", 3); this.addon.registerMessageType("RC:PSMultiImgTxtMsg", 3); this.addon.registerMessageType("RCJrmf:RpMsg", 3); this.addon.registerMessageType("RCJrmf:RpOpendMsg", 1); this.addon.registerMessageType("RC:GrpNtf", 1); this.addon.registerMessageType("RC:DizNtf", 0); this.addon.registerMessageType("RC:InfoNtf", 0); this.addon.registerMessageType("RC:ContactNtf", 0); this.addon.registerMessageType("RC:ProfileNtf", 0); this.addon.registerMessageType("RC:CmdNtf", 0); this.addon.registerMessageType("RC:CmdMsg", 0); this.addon.registerMessageType("RC:TypSts", 0); this.addon.registerMessageType("RC:CsChaR", 0); this.addon.registerMessageType("RC:CsHsR", 0); this.addon.registerMessageType("RC:CsEnd", 0); this.addon.registerMessageType("RC:CsSp", 0); this.addon.registerMessageType("RC:CsUpdate", 0); this.addon.registerMessageType("RC:CsContact", 0); this.addon.registerMessageType("RC:ReadNtf", 0); this.addon.registerMessageType("RC:VCAccept", 0); this.addon.registerMessageType("RC:VCRinging", 0); this.addon.registerMessageType("RC:VCSummary", 0); this.addon.registerMessageType("RC:VCHangup", 0); this.addon.registerMessageType("RC:VCInvite", 0); this.addon.registerMessageType("RC:VCModifyMedia", 0); this.addon.registerMessageType("RC:VCModifyMem", 0); this.addon.registerMessageType("RC:PSCmd", 0); this.addon.registerMessageType("RC:RcCmd", 0); this.addon.registerMessageType("RC:SRSMsg", 0); this.addon.registerMessageType("RC:RRReqMsg", 0); this.addon.registerMessageType("RC:RRRspMsg", 0); return sdkInfo; }; VCDataProvider.prototype.connect = function (token, callback, userId, serverConf) { this.useConsole && console.log("connect"); this.userId = userId; this.connectCallback = callback; RongIMLib.Bridge._client = { userId: userId }; serverConf = serverConf || {}; var openmp = !!serverConf.openMp; var openus = !!serverConf.openUS; if (serverConf.type) { this.addon.setEnvironment(true); } this.addon.connectWithToken(token, userId, serverConf.serverList, serverConf.version, openmp, openus); }; VCDataProvider.prototype.setServerInfo = function (info) { 'setServerInfo' in this.addon && this.addon.setServerInfo(info.navi); }; VCDataProvider.prototype.logout = function () { this.useConsole && console.log("logout"); this.disconnect(); }; VCDataProvider.prototype.disconnect = function () { this.useConsole && console.log("disconnect"); this.addon.disconnect(true); }; VCDataProvider.prototype.clearData = function () { this.useConsole && console.log("clearData"); return this.addon.clearData(); }; VCDataProvider.prototype.clearListeners = function () { this.addon.setOnReceiveStatusListener(); this.addon.setConnectionStatusListener(); this.addon.setOnReceiveMessageListener(); }; VCDataProvider.prototype.setConnectionStatusListener = function (listener) { var me = this; /** ConnectionStatus_TokenIncorrect = 31004, ConnectionStatus_Connected = 0, ConnectionStatus_KickedOff = 6, // 其他设备登录 ConnectionStatus_Connecting = 10,// 连接中 ConnectionStatus_SignUp = 12, // 未登录 ConnectionStatus_NetworkUnavailable = 1, // 连接断开 ConnectionStatus_ServerInvalid = 8, // 断开 ConnectionStatus_ValidateFailure = 9,//断开 ConnectionStatus_Unconnected = 11,//断开 ConnectionStatus_DisconnExecption = 31011 //断开 RC_NAVI_MALLOC_ERROR = 30000,//断开 RC_NAVI_NET_UNAVAILABLE= 30002,//断开 RC_NAVI_SEND_FAIL = 30004,//断开 RC_NAVI_REQ_TIMEOUT = 30005,//断开 RC_NAVI_RECV_FAIL = 30006,//断开 RC_NAVI_RESOURCE_ERROR = 30007,//断开 RC_NAVI_NODE_NOT_FOUND = 30008,//断开 RC_NAVI_DNS_ERROR = 30009,//断开 */ me.connectListener = listener; this.useConsole && console.log("setConnectionStatusListener"); me.addon && me.addon.setConnectionStatusListener(function (result) { switch (result) { case 10: setTimeout(function () { listener.onChanged(RongIMLib.ConnectionStatus.CONNECTING); }); break; case 31004: setTimeout(function () { me.connectCallback.onTokenIncorrect(); }); break; case 1: case 9: case 11: case 12: case 31011: case 30000: case 30002: case 30004: case 30005: case 30006: case 30007: case 30008: case 30009: setTimeout(function () { listener.onChanged(RongIMLib.ConnectionStatus.DISCONNECTED); }); break; case 0: case 33005: setTimeout(function () { me.connectCallback.onSuccess(me.userId); listener.onChanged(RongIMLib.ConnectionStatus.CONNECTED); }); break; case 6: setTimeout(function () { listener.onChanged(RongIMLib.ConnectionStatus.KICKED_OFFLINE_BY_OTHER_CLIENT); }); break; default: setTimeout(function () { listener.onChanged(result); }); break; } }); }; VCDataProvider.prototype.setOnReceiveMessageListener = function (listener) { var me = this; me.messageListener = listener; this.useConsole && console.log("setOnReceiveMessageListener"); me.addon && me.addon.setOnReceiveMessageListener(function (result, leftCount, offline, hasMore) { var message = me.buildMessage(result); message.offLineMessage = offline; setTimeout(function () { var voipMsgTypes = ['AcceptMessage', 'RingingMessage', 'HungupMessage', 'InviteMessage', 'MediaModifyMessage', 'MemberModifyMessage']; var isVoIPMsg = voipMsgTypes.indexOf(message.messageType) > -1; if (isVoIPMsg) { RongIMClient._voipProvider && RongIMClient._voipProvider.onReceived(message); }else{ listener.onReceived(message, leftCount, hasMore); } // listener.onReceived(message, leftCount); }); }); }; VCDataProvider.prototype.sendTypingStatusMessage = function (conversationType, targetId, messageName, sendCallback) { var me = this; this.useConsole && console.log("sendTypingStatusMessage"); if (messageName in RongIMLib.RongIMClient.MessageParams) { me.sendMessage(conversationType, targetId, RongIMLib.TypingStatusMessage.obtain(RongIMLib.RongIMClient.MessageParams[messageName].objectName, ""), { onSuccess: function () { setTimeout(function () { sendCallback.onSuccess(); }); }, onError: function (errorCode) { setTimeout(function () { sendCallback.onError(errorCode, null); }); }, onBefore: function () { } }); } }; VCDataProvider.prototype.setMessageStatus = function (conversationType, targetId, timestamp, status, callback) { this.addon.updateMessageReceiptStatus(conversationType, targetId, timestamp); callback.onSuccess(true); }; VCDataProvider.prototype.sendTextMessage = function (conversationType, targetId, content, sendMessageCallback) { var msgContent = RongIMLib.TextMessage.obtain(content); this.useConsole && console.log("sendTextMessage"); this.sendMessage(conversationType, targetId, msgContent, sendMessageCallback); }; VCDataProvider.prototype.getRemoteConversations = function(count, beginTime, order, callback){ this.addon.getRemoteConversations(count, beginTime, order, function(){ callback.onSuccess(); }, function(code){ callback.onError(code); }); }; VCDataProvider.prototype.getRemoteHistoryMessages = function (conversationType, targetId, timestamp, count, callback) { try { var me = this; me.useConsole && console.log("getRemoteHistoryMessages"); me.addon.getRemoteHistoryMessages(conversationType, targetId, timestamp ? timestamp : 0, count, function (ret, hasMore) { var list = ret ? JSON.parse(ret).list : [], msgs = []; list.reverse(); for (var i = 0, len = list.length; i < len; i++) { var message = me.buildMessage(list[i].obj); message.sentStatus = RongIMLib.SentStatus.READ; msgs[i] = message; } callback.onSuccess(msgs, hasMore ? true : false); }, function (errorCode) { callback.onError(errorCode); }); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.getRemoteConversationList = function (callback, conversationTypes, count, isGetHiddenConvers) { try { this.useConsole && console.log("getRemoteConversationList"); var converTypes = conversationTypes || [1, 2, 3, 4, 5, 6, 7, 8]; var result = this.addon.getConversationList(converTypes); var list = JSON.parse(result).list, convers = [], me = this; isGetHiddenConvers = typeof isGetHiddenConvers === 'boolean' ? isGetHiddenConvers : false; for (var i = 0, len = list.length; i < len; i++) { var tmpObj = list[i].obj, obj = JSON.parse(tmpObj); if (obj != "") { if (obj.isHidden == 1 && isGetHiddenConvers) { continue; } convers[i] = me.buildConversation(tmpObj); } } callback.onSuccess(convers); } catch (e) { callback.onError(e); } }; /* var conversation = { // 会话类型 types: [1, 2, 3, 4, 5, 6, 7, 8], // 获取会话的开始始时间, 0 ,按会话中最后一条消息最大 sentTime 倒序开始获取 sentTime: 0, // 获取条数 count: 100 }; var callbacks = { onSuccess: function(){ }, onError: function(){ } }; */ VCDataProvider.prototype.getConversationsByPage = function (conversation, callbacks) { var types = conversation.types || [1, 2, 3, 4, 5, 6, 7, 8]; var sentTime = conversation.sentTime || 0; var count = conversation.count || 50; var result = this.addon.getConversationListByPage(types, sentTime, count); var list = JSON.parse(result).list, conversations = []; for (var i = 0, len = list.length; i < len; i++) { var tmpObj = list[i].obj, obj = JSON.parse(tmpObj); if (obj != "") { conversations[i] = this.buildConversation(tmpObj); } } callbacks.onSuccess(conversations); }; VCDataProvider.prototype.removeConversation = function (conversationType, targetId, callback) { try { this.useConsole && console.log("removeConversation"); this.addon.removeConversation(conversationType, targetId); var conversations = RongIMLib.RongIMClient._memoryStore.conversationList; var len = conversations.length; for (var i = 0; i < len; i++) { if (conversations[i].conversationType == conversationType && targetId == conversations[i].targetId) { conversations.splice(i, 1); break; } } callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.joinChatRoom = function (chatRoomId, messageCount, callback) { this.useConsole && console.log("joinChatRoom"); this.addon.joinChatRoom(chatRoomId, messageCount, function () { callback.onSuccess(); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.quitChatRoom = function (chatRoomId, callback) { this.useConsole && console.log("quitChatRoom"); this.addon.quitChatRoom(chatRoomId, function () { callback.onSuccess(); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.addToBlacklist = function (userId, callback) { this.useConsole && console.log("addToBlacklist"); this.addon.addToBlacklist(userId, function () { callback.onSuccess(); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.getBlacklist = function (callback) { this.useConsole && console.log("getBlacklist"); this.addon.getBlacklist(function (blacklistors) { callback.onSuccess(blacklistors); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.getBlacklistStatus = function (userId, callback) { this.useConsole && console.log("getBlacklistStatus"); this.addon.getBlacklistStatus(userId, function (result) { callback.onSuccess(result); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.removeFromBlacklist = function (userId, callback) { this.useConsole && console.log("removeFromBlacklist"); this.addon.removeFromBlacklist(userId, function () { callback.onSuccess(); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.sendMessage = function (conversationType, targetId, messageContent, sendCallback, mentiondMsg, pushText, appData, methodType, params) { var me = this, users = []; me.useConsole && console.log("sendMessage"); params = params || {}; var isGroup = (conversationType == RongIMLib.ConversationType.DISCUSSION || conversationType == RongIMLib.ConversationType.GROUP); if (isGroup && messageContent.messageName == RongIMLib.RongIMClient.MessageType["ReadReceiptResponseMessage"]) { users = []; var rspMsg = messageContent; if (rspMsg.receiptMessageDic) { var ids = []; for (var key in rspMsg.receiptMessageDic) { ids.push(key); } users = ids; } } if (isGroup && messageContent.messageName == RongIMLib.RongIMClient.MessageType["SyncReadStatusMessage"]) { users = []; users.push(me.userId); } var userIds = params.userIds; if (isGroup && userIds) { users = userIds; } var msg = me.addon.sendMessage(conversationType, targetId, RongIMLib.RongIMClient.MessageParams[messageContent.messageName].objectName, messageContent.encode(), pushText || "", appData || "", function (progress) { }, function (message, code) { sendCallback.onSuccess(me.buildMessage(message), code); }, function (message, code) { sendCallback.onError(code, me.buildMessage(message)); }, users); var tempMessage = JSON.parse(msg); sendCallback.onBefore && sendCallback.onBefore(tempMessage.messageId); RongIMLib.MessageIdHandler.messageId = tempMessage.messageId; }; VCDataProvider.prototype.registerMessageType = function (messageType, objectName, messageTag, messageContent, searchProp) { this.useConsole && console.log("registerMessageType"); this.addon.registerMessageType(objectName, messageTag.getMessageTag(), searchProp); var regMsg = RongIMLib.ModelUtil.modleCreate(messageContent, messageType); RongIMLib.RongIMClient.RegisterMessage[messageType] = regMsg; RongIMLib.RongIMClient.RegisterMessage[messageType].messageName = messageType; registerMessageTypeMapping[objectName] = messageType; RongIMLib.RongIMClient.MessageType[messageType] = messageType; RongIMLib.RongIMClient.MessageParams[messageType] = { objectName: objectName, msgTag: messageTag }; typeMapping[objectName] = messageType; }; VCDataProvider.prototype.addMessage = function (conversationType, targetId, message, callback) { this.useConsole && console.log("addMessage"); var direction = message.direction; var msg = this.addon.insertMessage(conversationType, targetId, message.senderUserId, message.objectName, JSON.stringify(message.content), function () { callback.onSuccess(me.buildMessage(msg)); }, function () { callback.onError(RongIMLib.ErrorCode.MSG_INSERT_ERROR); }, direction), me = this; }; VCDataProvider.prototype.removeMessage = function (conversationType, targetId, delMsgs, callback) { }; VCDataProvider.prototype.removeLocalMessage = function (conversationType, targetId, timestamps, callback) { try { this.useConsole && console.log("removeLocalMessage"); this.addon.deleteMessages(timestamps); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.getMessage = function (messageId, callback) { try { this.useConsole && console.log("getMessage"); var msg = this.buildMessage(this.addon.getMessage(messageId)); callback.onSuccess(msg); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.clearMessages = function (conversationType, targetId, callback) { try { this.useConsole && console.log("clearMessages"); this.addon.clearMessages(conversationType, targetId); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.getConversation = function (conversationType, targetId, callback) { var conversation = null; try { this.useConsole && console.log("getConversation"); var ret = this.addon.getConversation(conversationType, targetId); conversation = this.buildConversation(ret); callback.onSuccess(conversation); } catch (e) { callback.onError(e); } return conversation; }; VCDataProvider.prototype.getConversationList = function (callback, conversationTypes, count, isGetHiddenConvers) { this.useConsole && console.log("getConversationList"); this.getRemoteConversationList(callback, conversationTypes, count, isGetHiddenConvers); }; VCDataProvider.prototype.clearCache = function () { var memoryStore = RongIMLib.RongIMClient._memoryStore || {}; memoryStore.conversationList = []; memoryStore.isSyncRemoteConverList; }; VCDataProvider.prototype.clearConversations = function (conversationTypes, callback) { try { this.useConsole && console.log("clearConversations"); this.addon.clearConversations(); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.setMessageContent = function (messageId, content, objectName) { content = JSON.stringify(content); this.addon.setMessageContent(messageId, content, objectName); }; VCDataProvider.prototype.getHistoryMessages = function (conversationType, targetId, timestamp, count, callback, objectname, direction) { this.useConsole && console.log("getHistoryMessages"); if (count <= 0) { callback.onError(RongIMLib.ErrorCode.TIMEOUT); return; } objectname = objectname || ''; direction = typeof direction == 'undefined' || direction; try { var ret = this.addon.getHistoryMessages(conversationType, targetId, timestamp ? timestamp : 0, count, objectname, direction); var list = ret ? JSON.parse(ret).list : [], msgs = [], me = this; list.reverse(); for (var i = 0, len = list.length; i < len; i++) { var message = me.buildMessage(list[i].obj); // message.sentStatus = RongIMLib.SentStatus.READ; msgs[i] = message; } callback.onSuccess(msgs, len == count); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.clearRemoteHistoryMessages = function (params, callback) { var conversationType = params.conversationType; var targetId = params.targetId; var timestamp = params.timestamp; var _topic = { 1: true, 2: true, 3: true, 5: true, 6: true }; var topic = _topic[conversationType]; if (!topic) { callback.onError(RongIMLib.ErrorCode.CLEAR_HIS_TYPE_ERROR); return; } if (typeof timestamp != 'number') { callback.onError(RongIMLib.ErrorCode.CLEAR_HIS_TIME_ERROR); return; } this.addon.clearRemoteHistoryMessages(+conversationType, targetId, timestamp, function () { callback.onSuccess(true); }, function (errorCode) { if (errorCode == 1) { // 没有开通历史消息云存储 errorCode = RongIMLib.ErrorCode.CLEAR_HIS_ERROR; } callback.onError(errorCode); }); }; VCDataProvider.prototype.clearHistoryMessages = function (params, callback) { var conversationType = +params.conversationType; var targetId = params.targetId; try { this.addon.clearMessages(conversationType, targetId); var isSuccess = true; callback.onSuccess(isSuccess); } catch (e) { console.log(e); callback.onError(RongIMLib.ErrorCode.CLEAR_HIS_ERROR); } }; VCDataProvider.prototype.getTotalUnreadCount = function (callback, conversationTypes) { var count = 0; try { this.useConsole && console.log("getTotalUnreadCount"); if (conversationTypes) { count = this.addon.getTotalUnreadCount(conversationTypes); } else { count = this.addon.getTotalUnreadCount(); } callback.onSuccess(count); } catch (e) { callback.onError(e); } return count; }; VCDataProvider.prototype.getConversationUnreadCount = function (conversationTypes, callback) { this.useConsole && console.log("getConversationUnreadCount"); this.getTotalUnreadCount(callback, conversationTypes); }; VCDataProvider.prototype.getUnreadCount = function (conversationType, targetId, callback) { var count = 0; try { this.useConsole && console.log("getUnreadCount"); count = this.addon.getUnreadCount(conversationType, targetId); callback.onSuccess(count); } catch (e) { callback.onError(e); } return count; }; VCDataProvider.prototype.clearUnreadCount = function (conversationType, targetId, callback) { try { this.useConsole && console.log("clearUnreadCount"); var result = this.addon.clearUnreadCount(conversationType, targetId); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.clearUnreadCountByTimestamp = function (conversationType, targetId, timestamp, callback) { try { this.useConsole && console.log("clearUnreadCountByTimestamp"); var result = this.addon.clearUnreadCountByTimestamp(conversationType, targetId, timestamp); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.setConversationToTop = function (conversationType, targetId, isTop, callback) { try { this.useConsole && console.log("setConversationToTop"); this.addon.setConversationToTop(conversationType, targetId, isTop); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.setConversationHidden = function (conversationType, targetId, isHidden) { this.addon.setConversationHidden(conversationType, targetId, isHidden); }; VCDataProvider.prototype.setMessageReceivedStatus = function (messageId, receivedStatus, callback) { try { this.useConsole && console.log("setMessageReceivedStatus"); this.addon.setMessageReceivedStatus(messageId, receivedStatus); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.setMessageSentStatus = function (messageId, sentStatus, callback) { try { this.useConsole && console.log("setMessageSentStatus"); this.addon.setMessageSentStatus(messageId, sentStatus); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.getFileToken = function (fileType, callback) { this.useConsole && console.log("getFileToken"); this.addon.getUploadToken(fileType, function (token) { callback.onSuccess({ token: token }); }, function (errorCode) { callback.onError(errorCode); }); }; VCDataProvider.prototype.getFileUrl = function (fileType, fileName, oriName, callback) { this.useConsole && console.log("getFileUrl"); this.addon.getDownloadUrl(fileType, fileName, oriName, function (url) { callback.onSuccess({ downloadUrl: url }); }, function (errorCode) { callback.onError(errorCode); }); }; VCDataProvider.prototype.searchConversationByContent = function (keyword, callback, conversationTypes, customMsgTypes) { var converTypes = []; if (typeof conversationTypes == 'undefined') { converTypes = [1, 2, 3, 4, 5, 6, 7]; } else { converTypes = conversationTypes; } this.useConsole && console.log("searchConversationByContent"); var me = this; this.addon.searchConversationByContent(converTypes, keyword, customMsgTypes, function(result){ var list = JSON.parse(result).list, convers = []; var index = 0; for (var i = list.length - 1; i >=0; i--) { convers[index] = me.buildConversation(list[i].obj); index++; } callback.onSuccess(convers); }, callback.onError); }; VCDataProvider.prototype.searchMessageByContent = function (conversationType, targetId, keyword, timestamp, count, total, callback) { var me = this; try { this.useConsole && console.log("searchMessageByContent"); this.addon.searchMessageByContent(conversationType, targetId, keyword, timestamp, count, total, function (ret, matched) { var list = ret ? JSON.parse(ret).list : [], msgs = []; list.reverse(); for (var i = 0, len = list.length; i < len; i++) { msgs[i] = me.buildMessage(list[i].obj); } callback.onSuccess(msgs, matched); }); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.getChatRoomInfo = function (chatRoomId, count, order, callback) { this.useConsole && console.log("getChatRoomInfo"); this.addon.getChatroomInfo(chatRoomId, count, order, function (ret, count) { var list = ret ? JSON.parse(ret).list : [], chatRoomInfo = { userInfos: [], userTotalNums: count }; if (list.length > 0) { for (var i = 0, len = list.length; i < len; i++) { chatRoomInfo.userInfos.push(JSON.parse(list[i].obj)); } } callback.onSuccess(chatRoomInfo); }, function (errcode) { callback.onError(errcode); }); }; VCDataProvider.prototype.setChatroomHisMessageTimestamp = function (chatRoomId, timestamp) { }; VCDataProvider.prototype.getChatRoomHistoryMessages = function (chatRoomId, count, order, callback) { }; VCDataProvider.prototype.getDelaTime = function () { return this.addon.getDeltaTime(); }; VCDataProvider.prototype.getUserStatus = function (userId, callback) { var me = this; this.addon.getUserStatus(userId, function (status) { var entity = RongIMLib.RongInnerTools.convertUserStatus({ status: status, userId: '' }); callback.onSuccess(entity); }, function (code) { callback.onError(code); }); }; VCDataProvider.prototype.setUserStatus = function (status, callback) { this.addon.setUserStatus(status, function () { callback.onSuccess(true); }, function (code) { callback.onError(code); }); }; VCDataProvider.prototype.subscribeUserStatus = function (userIds, callback) { this.addon.subscribeUserStatus(userIds, function () { callback && callback.onSuccess(true); }, function (code) { callback && callback.onError(code); }); }; VCDataProvider.prototype.setUserStatusListener = function (params, callback) { var me = this; this.addon.setOnReceiveStatusListener(function (userId, status) { var entity = RongIMLib.RongInnerTools.convertUserStatus({ userId: userId, status: status }); RongIMLib.RongIMClient.userStatusObserver.notify({ key: userId, entity: entity }); }); var userIds = params.userIds || []; if (userIds.length) { RongIMLib.RongIMClient._dataAccessProvider.subscribeUserStatus(userIds); } }; VCDataProvider.prototype.getUnreadMentionedMessages = function (conversationType, targetId) { var me = this; var mentions = JSON.parse(me.addon.getUnreadMentionedMessages(conversationType, targetId)).list; for (var i = 0, len = mentions.length; i < len; i++) { var temp = JSON.parse(mentions[i].obj); temp.content = JSON.parse(temp.content); mentions[i] = temp; } return mentions; }; VCDataProvider.prototype.hasRemoteUnreadMessages = function (token, callback) { callback.onSuccess(false); }; VCDataProvider.prototype.sendRecallMessage = function (content, sendMessageCallback) { var me = this; me.addon.recallMessage("RC:RcCmd", JSON.stringify(content), content.push || "", function () { content.objectName = 'RC:RcCmd'; sendMessageCallback.onSuccess(me.buildMessage(JSON.stringify(content))); }, function (errorCode) { sendMessageCallback.onError(errorCode); }); }; VCDataProvider.prototype.updateMessage = function (message, callback) { }; VCDataProvider.prototype.updateMessages = function (conversationType, targetId, key, value, callback) { }; VCDataProvider.prototype.reconnect = function (callback) { }; VCDataProvider.prototype.sendReceiptResponse = function (conversationType, targetId, sendCallback) { }; VCDataProvider.prototype.setMessageExtra = function (messageId, value, callback) { }; VCDataProvider.prototype.addMemberToDiscussion = function (discussionId, userIdList, callback) { }; VCDataProvider.prototype.createDiscussion = function (name, userIdList, callback) { }; VCDataProvider.prototype.getDiscussion = function (discussionId, callback) { }; VCDataProvider.prototype.quitDiscussion = function (discussionId, callback) { }; VCDataProvider.prototype.removeMemberFromDiscussion = function (discussionId, userId, callback) { }; VCDataProvider.prototype.setDiscussionInviteStatus = function (discussionId, status, callback) { }; VCDataProvider.prototype.setDiscussionName = function (discussionId, name, callback) { }; VCDataProvider.prototype.setEnvironment = function (isPrivate) { this.addon.setEnvironment(isPrivate); }; VCDataProvider.prototype.addConversation = function (conversation, callback) { }; VCDataProvider.prototype.updateConversation = function (conversation) { return null; }; VCDataProvider.prototype.getConversationNotificationStatus = function (params, callback) { var conversationType = params.conversationType; var targetId = params.targetId; var notification = RongIMLib.RongIMClient._memoryStore.notification; var key = conversationType + '_' + targetId; var status = notification[key]; if (typeof status == 'number') { callback.onSuccess(status); return; } this.addon.getConversationNotificationStatus(conversationType, targetId, function (status) { notification[key] = status; callback.onSuccess(status); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.setConversationNotificationStatus = function (params, callback) { var conversationType = params.conversationType; var targetId = params.targetId; var status = params.status; var notification = RongIMLib.RongIMClient._memoryStore.notification; var key = conversationType + '_' + targetId; notification[key] = status; var notify = !!status; this.addon.setConversationNotificationStatus(conversationType, targetId, notify, function () { callback.onSuccess(status); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.getCurrentConnectionStatus = function () { return this.addon.getConnectionStatus(); }; VCDataProvider.prototype.getAgoraDynamicKey = function (engineType, channelName, callback) { var extra = ""; this.addon.getVoIPKey(engineType, channelName, extra, function (token) { callback.onSuccess(token); }, function (errorCode) { callback.onError(errorCode); }); }; VCDataProvider.prototype.getPublicServiceProfile = function (publicServiceType, publicServiceId, callback) { var profile = RongIMLib.RongIMClient._memoryStore.publicServiceMap.get(publicServiceType, publicServiceId); callback.onSuccess(profile); }; VCDataProvider.prototype.setDeviceInfo = function (device) { var id = device.id || ''; this.addon.setDeviceId(id); }; VCDataProvider.prototype.getRemotePublicServiceList = function (callback, pullMessageTime) { var publicList = []; var ret = this.addon.getAccounts(); var transformProto = function (ret) { var result = { hasFollowed: false, isGlobal: false, menu: null }; if (!ret.obj) { var error = { error: ret }; throw new Error('公众账号数据格式错误: ' + JSON.stringify(error)); } var obj = JSON.parse(ret.obj); var protoMap = { aType: 'conversationType', aId: 'publicServiceId', aName: 'introduction', aUri: 'portraitUri', follow: 'hasFollowed', isGlobal: 'isGlobal' }; for (var key in obj) { var val = obj[key]; if (key == 'aExtra') { var extra = JSON.parse(val); result["hasFollowed"] = extra.follow; result["isGlobal"] = extra.isGlobal; result["menu"] = extra.menu; } var uId = protoMap[key]; if (uId) { result[uId] = val; } } return result; }; if (ret) { ret = JSON.parse(ret); var list = ret.list; for (var i = 0, len = list.length; i < len; i++) { var item = list[i]; item = transformProto(item); publicList.push(item); } } if (publicList.length > 0) { RongIMLib.RongIMClient._memoryStore.publicServiceMap.publicServiceList.length = 0; RongIMLib.RongIMClient._memoryStore.publicServiceMap.publicServiceList = publicList; } callback.onSuccess(RongIMLib.RongIMClient._memoryStore.publicServiceMap.publicServiceList); }; VCDataProvider.prototype.buildMessage = function (result) { var message = new RongIMLib.Message(), ret = JSON.parse(result); message.conversationType = ret.conversationType; message.targetId = ret.targetId; message.messageDirection = ret.direction; message.senderUserId = ret.senderUserId; if (ret.direction == RongIMLib.MessageDirection.RECEIVE) { message.receivedStatus = ret.status; } else if (ret.direction == RongIMLib.MessageDirection.SEND) { message.sentStatus = ret.status; } message.sentTime = ret.sentTime; message.objectName = ret.objectName; var content = ret.content ? JSON.parse(ret.content) : ret.content; var messageType = typeMapping[ret.objectName] || registerMessageTypeMapping[ret.objectName]; if (content) { content.messageName = messageType; } message.content = content; message.messageId = ret.messageId; message.messageUId = ret.messageUid; message.messageType = messageType; return message; }; VCDataProvider.prototype.buildConversation = function (val) { if (val === '') { return null; } var conver = new RongIMLib.Conversation(), c = JSON.parse(val), lastestMsg = c.lastestMsg ? this.buildMessage(c.lastestMsg) : {}; conver.conversationTitle = c.title; conver.conversationType = c.conversationType; conver.draft = c.draft; conver.isTop = c.isTop; conver.isHidden = c.isHidden; lastestMsg.conversationType = c.conversationType; lastestMsg.targetId = c.targetId; conver.latestMessage = lastestMsg; conver.latestMessageId = lastestMsg.messageId; conver.latestMessage.messageType = typeMapping[lastestMsg.objectName] || registerMessageTypeMapping[lastestMsg.objectName]; conver.objectName = lastestMsg.objectName; conver.receivedStatus = RongIMLib.ReceivedStatus.READ; conver.sentTime = lastestMsg.sentTime; conver.senderUserId = lastestMsg.senderUserId; conver.sentStatus = lastestMsg.status; conver.targetId = c.targetId; conver.unreadMessageCount = c.unreadCount; conver.hasUnreadMention = c.m_hasUnreadMention; conver.matchCount = c.matchCount; var mentions = this.getUnreadMentionedMessages(c.conversationType, c.targetId); if (mentions.length > 0) { // 取最后一条 @ 消息,原因:和 web 互相兼容 var mention = mentions.pop(); conver.mentionedMsg = { uid: mention.messageUid, time: mention.sentTime, mentionedInfo: mention.content.mentionedInfo, sendUserId: mention.senderUserId }; } return conver; }; return VCDataProvider; })(); RongIMLib.VCDataProvider = VCDataProvider; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var MemeoryProvider = (function () { function MemeoryProvider() { this._memeoryStore = {}; this.prefix = "rong_"; } MemeoryProvider.prototype.setItem = function (composedKey, object) { this._memeoryStore[composedKey] = decodeURIComponent(object); }; MemeoryProvider.prototype.getItem = function (composedKey) { return this._memeoryStore[composedKey]; }; MemeoryProvider.prototype.removeItem = function (composedKey) { if (this.getItem(composedKey)) { delete this._memeoryStore[composedKey]; } }; MemeoryProvider.prototype.getItemKey = function (regStr) { var me = this, item = null, reg = new RegExp(regStr + "\\w+"); for (var key in me._memeoryStore) { var arr = key.match(reg); if (arr) { item = key; } } return item; }; MemeoryProvider.prototype.clearItem = function () { var me = this; for (var key in me._memeoryStore) { delete me._memeoryStore[key]; } }; //单位:字节 MemeoryProvider.prototype.onOutOfQuota = function () { return 4 * 1024; }; return MemeoryProvider; })(); RongIMLib.MemeoryProvider = MemeoryProvider; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var LocalStorageProvider = (function () { // static _instance: LocalStorageProvider = new LocalStorageProvider(); function LocalStorageProvider() { this.prefix = 'rong_'; this._host = ""; var d = new Date(), m = d.getMonth() + 1, date = d.getFullYear() + '/' + (m.toString().length == 1 ? '0' + m : m) + '/' + d.getDate(), nowDate = new Date(date).getTime(); for (var key in localStorage) { if (key.lastIndexOf('RECEIVED') > -1) { var recObj = JSON.parse(localStorage.getItem(key)); for (var key_1 in recObj) { nowDate - recObj[key_1].dealtime > 0 && (delete recObj[key_1]); } if (RongIMLib.RongUtil.isEmpty(recObj)) { localStorage.removeItem(key); } else { localStorage.setItem(key, JSON.stringify(recObj)); } } if (key.lastIndexOf('SENT') > -1) { var sentObj = JSON.parse(localStorage.getItem(key)); nowDate - sentObj.dealtime > 0 && (localStorage.removeItem(key)); } } } LocalStorageProvider.prototype.setItem = function (composedKey, object) { if (composedKey) { composedKey.indexOf(this.prefix) == -1 && (composedKey = this.prefix + composedKey); localStorage.setItem(composedKey, object); } }; LocalStorageProvider.prototype.getItem = function (composedKey) { if (composedKey) { composedKey.indexOf(this.prefix) == -1 && (composedKey = this.prefix + composedKey); return localStorage.getItem(composedKey ? composedKey : ""); } return ""; }; LocalStorageProvider.prototype.getItemKey = function (composedStr) { var item = ""; var _key = this.prefix + composedStr; for (var key in localStorage) { if (key.indexOf(_key) == 0) { item = key; break; } } return item; }; LocalStorageProvider.prototype.removeItem = function (composedKey) { if (composedKey) { composedKey.indexOf(this.prefix) == -1 && (composedKey = this.prefix + composedKey); localStorage.removeItem(composedKey.toString()); } }; LocalStorageProvider.prototype.clearItem = function () { var me = this; for (var key in localStorage) { if (key.indexOf(me.prefix) > -1) { me.removeItem(key); } } }; //单位:字节 LocalStorageProvider.prototype.onOutOfQuota = function () { return JSON.stringify(localStorage).length; }; return LocalStorageProvider; })(); RongIMLib.LocalStorageProvider = LocalStorageProvider; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var UserDataProvider = (function () { function UserDataProvider() { this.opersistName = 'RongIMLib'; this.keyManager = 'RongUserDataKeyManager'; this._host = ""; this.prefix = "rong_"; this.oPersist = document.createElement("div"); this.oPersist.style.display = "none"; this.oPersist.style.behavior = "url('#default#userData')"; document.body.appendChild(this.oPersist); this.oPersist.load(this.opersistName); } UserDataProvider.prototype.setItem = function (key, value) { key && key.indexOf(this.prefix) == -1 && (key = this.prefix + key); this.oPersist.setAttribute(key, value); var keyNames = this.getItem(this.keyManager); keyNames ? keyNames.indexOf(key) == -1 && (keyNames += ',' + key) : (keyNames = key); this.oPersist.setAttribute(this.prefix + this.keyManager, keyNames); this.oPersist.save(this.opersistName); }; UserDataProvider.prototype.getItem = function (key) { key && key.indexOf(this.prefix) == -1 && (key = this.prefix + key); return key ? this.oPersist.getAttribute(key) : key; }; UserDataProvider.prototype.removeItem = function (key) { key && key.indexOf(this.prefix) == -1 && (key = this.prefix + key); this.oPersist.removeAttribute(key); this.oPersist.save(this.opersistName); var keyNames = this.getItem(this.keyManager), keyNameArray = keyNames && keyNames.split(',') || []; for (var i = 0, len = keyNameArray.length; i < len; i++) { if (keyNameArray[i] == key) { keyNameArray.splice(i, 1); } } this.oPersist.setAttribute(this.prefix + this.keyManager, keyNameArray.join(',')); this.oPersist.save(this.opersistName); }; UserDataProvider.prototype.getItemKey = function (composedStr) { var item = null, keyNames = this.getItem(this.keyManager), keyNameArray = keyNames && keyNames.split(',') || [], me = this; var _key = this.prefix + composedStr; if (keyNameArray.length) { for (var i = 0, len = keyNameArray.length; i < len; i++) { if (keyNameArray[i] && keyNameArray[i].indexOf(_key) == 0) { item = keyNameArray[i]; break; } } } return item; }; UserDataProvider.prototype.clearItem = function () { var keyNames = this.getItem(this.keyManager), keyNameArray = [], me = this; keyNames && (keyNameArray = keyNames.split(',')); if (keyNameArray.length) { for (var i = 0, len = keyNameArray.length; i < len; i++) { keyNameArray[i] && me.removeItem(keyNameArray[i]); } me.removeItem(me.keyManager); } }; UserDataProvider.prototype.onOutOfQuota = function () { return 10 * 1024 * 1024; }; return UserDataProvider; })(); RongIMLib.UserDataProvider = UserDataProvider; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var FeatureDectector = (function () { function FeatureDectector(callback) { this.script = document.createElement("script"); this.head = document.getElementsByTagName("head")[0]; if ("WebSocket" in window && "ArrayBuffer" in window && WebSocket.prototype.CLOSED === 3 && !RongIMLib.RongIMClient._memoryStore.depend.isPolling) { RongIMLib.Transportations._TransportType = RongIMLib.Socket.WEBSOCKET; if (!RongIMLib.RongIMClient.Protobuf) { var url = RongIMLib.RongIMClient._memoryStore.depend.protobuf; var script = this.script; script.src = url; this.head.appendChild(script); script.onload = script.onreadystatechange = function () { var isLoaded = (!this.readState || this.readyState == 'loaded' || this.readyState == 'complete'); if (isLoaded) { // 防止 IE6、7 下偶发触发两次 loaded script.onload = script.onreadystatechange = null; if (callback) { callback(); } if (!callback) { var token = RongIMLib.RongIMClient._memoryStore.token; var connectCallback = RongIMLib.RongIMClient._memoryStore.callback; token && RongIMLib.RongIMClient.connect(token, connectCallback); } } }; } } else { RongIMLib.Transportations._TransportType = "xhr-polling"; RongIMLib.RongIMClient.Protobuf = Polling; } } return FeatureDectector; })(); RongIMLib.FeatureDectector = FeatureDectector; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var FeaturePatcher = (function () { function FeaturePatcher() { } FeaturePatcher.prototype.patchAll = function () { this.patchJSON(); this.patchForEach(); }; FeaturePatcher.prototype.patchForEach = function () { if (!Array.forEach) { Array.forEach = function (arr, func) { for (var i = 0; i < arr.length; i++) { func.call(arr, arr[i], i, arr); } }; } }; FeaturePatcher.prototype.patchJSON = function () { if (!window["JSON"]) { window["JSON"] = (function () { function JSON() { } JSON.parse = function (sJSON) { return eval('(' + sJSON + ')'); }; JSON.stringify = function (value) { return this.str("", { "": value }); }; JSON.str = function (key, holder) { var i, k, v, length, mind = "", partial, value = holder[key], me = this; if (value && typeof value === "object" && typeof value.toJSON === "function") { value = value.toJSON(key); } switch (typeof value) { case "string": return me.quote(value); case "number": return isFinite(value) ? String(value) : "null"; case "boolean": case "null": return String(value); case "object": if (!value) { return "null"; } partial = []; if (Object.prototype.toString.apply(value) === "[object Array]") { length = value.length; for (i = 0; i < length; i += 1) { partial[i] = me.str(i, value) || "null"; } v = partial.length === 0 ? "[]" : "[" + partial.join(",") + "]"; return v; } for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = me.str(k, value); if (v) { partial.push(me.quote(k) + ":" + v); } } } v = partial.length === 0 ? "{}" : "{" + partial.join(",") + "}"; return v; } }; JSON.quote = function (string) { var me = this; me.rx_escapable.lastIndex = 0; return me.rx_escapable.test(string) ? '"' + string.replace(me.rx_escapable, function (a) { var c = me.meta[a]; return typeof c === "string" ? c : "\\u" + ("0000" + a.charCodeAt(0).toString(16)).slice(-4); }) + '"' : '"' + string + '"'; }; JSON.rx_escapable = new RegExp('[\\\"\\\\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]', "g"); JSON.meta = { "\b": "\\b", " ": "\\t", "\n": "\\n", "\f": "\\f", "\r": "\\r", '"': '\\"', "''": "\\''", "\\": "\\\\" }; return JSON; })(); } }; return FeaturePatcher; })(); RongIMLib.FeaturePatcher = FeaturePatcher; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var PublicServiceMap = (function () { function PublicServiceMap() { this.publicServiceList = []; } PublicServiceMap.prototype.get = function (publicServiceType, publicServiceId) { for (var i = 0, len = this.publicServiceList.length; i < len; i++) { if (this.publicServiceList[i].conversationType == publicServiceType && publicServiceId == this.publicServiceList[i].publicServiceId) { return this.publicServiceList[i]; } } }; PublicServiceMap.prototype.add = function (publicServiceProfile) { var isAdd = true, me = this; for (var i = 0, len = this.publicServiceList.length; i < len; i++) { if (me.publicServiceList[i].conversationType == publicServiceProfile.conversationType && publicServiceProfile.publicServiceId == me.publicServiceList[i].publicServiceId) { this.publicServiceList.unshift(this.publicServiceList.splice(i, 1)[0]); isAdd = false; break; } } if (isAdd) { this.publicServiceList.unshift(publicServiceProfile); } }; PublicServiceMap.prototype.replace = function (publicServiceProfile) { var me = this; for (var i = 0, len = this.publicServiceList.length; i < len; i++) { if (me.publicServiceList[i].conversationType == publicServiceProfile.conversationType && publicServiceProfile.publicServiceId == me.publicServiceList[i].publicServiceId) { me.publicServiceList.splice(i, 1, publicServiceProfile); break; } } }; PublicServiceMap.prototype.remove = function (conversationType, publicServiceId) { var me = this; for (var i = 0, len = this.publicServiceList.length; i < len; i++) { if (me.publicServiceList[i].conversationType == conversationType && publicServiceId == me.publicServiceList[i].publicServiceId) { this.publicServiceList.splice(i, 1); break; } } }; return PublicServiceMap; })(); RongIMLib.PublicServiceMap = PublicServiceMap; /** * 会话工具类。 */ var ConversationMap = (function () { function ConversationMap() { this.conversationList = []; } ConversationMap.prototype.get = function (conversavtionType, targetId) { for (var i = 0, len = this.conversationList.length; i < len; i++) { if (this.conversationList[i].conversationType == conversavtionType && this.conversationList[i].targetId == targetId) { return this.conversationList[i]; } } return null; }; ConversationMap.prototype.add = function (conversation) { var isAdd = true; for (var i = 0, len = this.conversationList.length; i < len; i++) { if (this.conversationList[i].conversationType === conversation.conversationType && this.conversationList[i].targetId === conversation.targetId) { this.conversationList.unshift(this.conversationList.splice(i, 1)[0]); isAdd = false; break; } } if (isAdd) { this.conversationList.unshift(conversation); } }; /** * [replace 替换会话] * 会话数组存在的情况下调用add方法会是当前会话被替换且返回到第一个位置,导致用户本地一些设置失效,所以提供replace方法 */ ConversationMap.prototype.replace = function (conversation) { for (var i = 0, len = this.conversationList.length; i < len; i++) { if (this.conversationList[i].conversationType === conversation.conversationType && this.conversationList[i].targetId === conversation.targetId) { this.conversationList.splice(i, 1, conversation); break; } } }; ConversationMap.prototype.remove = function (conversation) { for (var i = 0, len = this.conversationList.length; i < len; i++) { if (this.conversationList[i].conversationType === conversation.conversationType && this.conversationList[i].targetId === conversation.targetId) { this.conversationList.splice(i, 1); break; } } }; return ConversationMap; })(); RongIMLib.ConversationMap = ConversationMap; var CheckParam = (function () { function CheckParam() { } CheckParam.getInstance = function () { if (!CheckParam._instance) { CheckParam._instance = new CheckParam(); } return CheckParam._instance; }; CheckParam.prototype.logger = function (code, funcName, msg) { RongIMLib.RongIMClient.logger({ code: code, funcName: funcName, msg: msg }); }; CheckParam.prototype.check = function (f, position, d, c) { if (RongIMLib.RongIMClient._dataAccessProvider || d) { for (var g = 0, e = c.length; g < e; g++) { if (!new RegExp(this.getType(c[g])).test(f[g])) { // throw new Error("The index of " + g + " parameter was wrong type " + this.getType(c[g]) + " [" + f[g] + "] -> position:" + position); var msg = "第" + (g + 1) + "个参数错误, 错误类型:" + this.getType(c[g]) + " [" + f[g] + "] -> 位置:" + position; this.logger("-3", position, msg); } } } else { var msg = "该参数不正确或尚未实例化RongIMClient -> 位置:" + position; this.logger("-4", position, msg); } }; CheckParam.prototype.getType = function (str) { var temp = Object.prototype.toString.call(str).toLowerCase(); return temp.slice(8, temp.length - 1); }; CheckParam.prototype.checkCookieDisable = function () { document.cookie = "checkCookie=1"; var arr = document.cookie.match(new RegExp("(^| )checkCookie=([^;]*)(;|$)")), isDisable = false; if (!arr) { isDisable = true; } document.cookie = "checkCookie=1;expires=Thu, 01-Jan-1970 00:00:01 GMT"; return isDisable; }; return CheckParam; })(); RongIMLib.CheckParam = CheckParam; var LimitableMap = (function () { function LimitableMap(limit) { this.map = {}; this.keys = []; this.limit = limit || 10; } LimitableMap.prototype.set = function (key, value) { this.map[key] = value; }; LimitableMap.prototype.get = function (key) { return this.map[key] || 0; }; LimitableMap.prototype.remove = function (key) { delete this.map[key]; }; return LimitableMap; })(); RongIMLib.LimitableMap = LimitableMap; var RongAjax = (function () { function RongAjax(options) { var me = this; me.xmlhttp = null; me.options = options; var hasCORS = typeof XMLHttpRequest !== "undefined" && "withCredentials" in new XMLHttpRequest(); if ("undefined" != typeof XMLHttpRequest && hasCORS) { me.xmlhttp = new XMLHttpRequest(); } else if ("undefined" != typeof XDomainRequest) { me.xmlhttp = new XDomainRequest(); } else { me.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } } RongAjax.prototype.send = function (callback) { var me = this; me.options.url || (me.options.url = "http://upload.qiniu.com/putb64/-1"); me.xmlhttp.onreadystatechange = function () { if (me.xmlhttp.readyState == 4) { if (me.options.type) { callback(); } else { callback(JSON.parse(me.xmlhttp.responseText.replace(/'/g, '"'))); } } }; me.xmlhttp.open("POST", me.options.url, true); me.xmlhttp.withCredentials = false; if ("setRequestHeader" in me.xmlhttp) { if (me.options.type) { me.xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=utf-8"); } else { me.xmlhttp.setRequestHeader("Content-type", "application/octet-stream"); me.xmlhttp.setRequestHeader('Authorization', "UpToken " + me.options.token); } } me.xmlhttp.send(me.options.type ? "appKey=" + me.options.appKey + "&deviceId=" + me.options.deviceId + "×tamp=" + me.options.timestamp + "&deviceInfo=" + me.options.deviceInfo + "&privateInfo=" + JSON.stringify(me.options.privateInfo) : me.options.base64); }; return RongAjax; })(); RongIMLib.RongAjax = RongAjax; var RongUtil = (function () { function RongUtil() { } RongUtil.noop = function () { }; RongUtil.isEmpty = function (obj) { var empty = true; for (var key in obj) { empty = false; break; } return empty; }; RongUtil.MD5 = function (str, key, raw) { return md5(str, key, raw); }; RongUtil.isObject = function (obj) { return Object.prototype.toString.call(obj) == '[object Object]'; }; RongUtil.isArray = function (array) { return Object.prototype.toString.call(array) == '[object Array]'; }; RongUtil.isFunction = function (fun) { return Object.prototype.toString.call(fun) == '[object Function]'; }; ; RongUtil.stringFormat = function (tmpl, vals) { for (var i = 0, len = vals.length; i < len; i++) { var val = vals[i], reg = new RegExp("\\{" + (i) + "\\}", "g"); tmpl = tmpl.replace(reg, val); } return tmpl; }; RongUtil.tplEngine = function (temp, data, regexp) { if (!(Object.prototype.toString.call(data) === "[object Array]")) { data = [data]; } var ret = []; for (var i = 0, j = data.length; i < j; i++) { ret.push(replaceAction(data[i])); } return ret.join(""); function replaceAction(object) { return temp.replace(regexp || (/{([^}]+)}/g), function (match, name) { if (match.charAt(0) == '\\') { return match.slice(1); } return (object[name] != undefined) ? object[name] : '{' + name + '}'; }); } }; ; RongUtil.forEach = function (obj, callback) { callback = callback || RongUtil.noop; var loopObj = function () { for (var key in obj) { callback(obj[key], key, obj); } }; var loopArr = function () { for (var i = 0, len = obj.length; i < len; i++) { callback(obj[i], i); } }; if (RongUtil.isObject(obj)) { loopObj(); } if (RongUtil.isArray(obj)) { loopArr(); } }; RongUtil.extend = function (source, target, callback, force) { RongUtil.forEach(source, function (val, key) { var hasProto = (key in target); if (force && hasProto) { target[key] = val; } if (!hasProto) { target[key] = val; } }); return target; }; RongUtil.createXHR = function () { var item = { XMLHttpRequest: function () { return new XMLHttpRequest(); }, XDomainRequest: function () { return new XDomainRequest(); }, ActiveXObject: function () { return new ActiveXObject('Microsoft.XMLHTTP'); } }; var isXHR = (typeof XMLHttpRequest == 'function'); var isXDR = (typeof XDomainRequest == 'function'); var key = isXHR ? 'XMLHttpRequest' : isXDR ? 'XDomainRequest' : 'ActiveXObject'; return item[key](); }; RongUtil.request = function (opts) { var url = opts.url; var success = opts.success; var error = opts.error; var method = opts.method || 'GET'; var xhr = RongUtil.createXHR(); xhr.onreadystatechange = function () { if (xhr.readyState == 4) { if (xhr.status == 200) { success(); } else { error(); } } }; xhr.open(method, url, true); xhr.send(null); }; RongUtil.getLocalProtocol = function () { var isLocationInvalid = typeof location !== 'object'; // 未找到全局 location 变量, 则协议为 https. 比如小程序 if (isLocationInvalid || location.protocol === 'https:') { return 'https://'; } else { return 'http://'; } }; RongUtil.getValidNavi = function (naviHost) { var HttpProtocol = RongIMLib.RongIMClient.HttpProtocol; var WsProtocol = RongIMLib.RongIMClient.WsProtocol; var flag = '://'; var index = naviHost.indexOf(flag); var hasProtocol = index > -1; var navi = naviHost; if (!hasProtocol) { var protocol = RongIMLib.RongIMClient.getProtocol().protocol; navi = protocol + naviHost; } var naviProtocol = RongUtil.getUrlProtocol(navi), localProtocol = RongUtil.getLocalProtocol(); // 本地为 https, 但却传入 http 时, 强制转化为 https if (naviProtocol === HttpProtocol.http && localProtocol === 'https://') { navi = RongUtil.formatProtoclPath({ path: navi, tmpl: '{0}{1}', protocol: HttpProtocol.https, sub: true }); } return navi; }; RongUtil.getUrlProtocol = function (url) { var flag = '://'; var index = url.indexOf(flag); if (index > -1) { return url.substring(0, index + flag.length); } else { return 'https://'; } ; }; RongUtil.formatProtoclPath = function (config) { var path = config.path; var protocol = config.protocol; var tmpl = config.tmpl || '{0}{1}'; var sub = config.sub; var flag = '://'; var index = path.indexOf(flag); var hasProtocol = (index > -1); if (hasProtocol) { index += flag.length; path = path.substring(index); } if (sub) { index = path.indexOf('/'); var hasPath = (index > -1); if (hasPath) { path = path.substr(0, index); } } return RongUtil.stringFormat(tmpl, [protocol, path]); }; ; RongUtil.supportLocalStorage = function () { var support = false; if (typeof localStorage == 'object') { try { var key = 'RC_TMP_KEY', value = 'RC_TMP_VAL'; localStorage.setItem(key, value); var localVal = localStorage.getItem(key); if (localVal == value) { support = true; } } catch (err) { console.log('localStorage is disabled.'); } } return support; }; /* //返回新引用,不破坏原始对象 rename({n: 'martin'}, {n: 'name'}); => {name: 'martin'} rename([{n: 'martin'}, {a: 18}], {n: 'name', a: 'age'}); => [{name: 'martin'}, {age: 18}] */ RongUtil.rename = function (origin, newNames) { var isObject = RongUtil.isObject(origin); if (isObject) { origin = [origin]; } origin = JSON.parse(JSON.stringify(origin)); var updateProperty = function (val, key, obj) { delete obj[key]; key = newNames[key]; obj[key] = val; }; RongUtil.forEach(origin, function (item) { RongUtil.forEach(item, function (val, key, obj) { var isRename = (key in newNames); (isRename ? updateProperty : RongUtil.noop)(val, key, obj); }); }); return isObject ? origin[0] : origin; }; RongUtil.some = function (arrs, callback) { var has = false; for (var i = 0, len = arrs.length; i < len; i++) { if (callback(arrs[i])) { has = true; break; } } return has; }; RongUtil.keys = function (obj) { var props = []; for (var key in obj) { props.push(key); } return props; }; return RongUtil; })(); RongIMLib.RongUtil = RongUtil; /* var observer = new RongObserver(); observer.watch({ key: 'key', func: function(entity){ } }); */ var RongObserver = (function () { function RongObserver() { this.watchers = {}; } RongObserver.prototype.genUId = function (key) { var time = new Date().getTime(); return [key, time].join('_'); }; RongObserver.prototype.watch = function (params) { var me = this; var key = params.key; var multiple = params.multiple; key = RongUtil.isArray(key) ? key : [key]; var func = params.func; RongUtil.forEach(key, function (k) { k = multiple ? me.genUId(k) : k; me.watchers[k] = func; }); }; RongObserver.prototype.notify = function (params) { var me = this; var key = params.key; var entity = params.entity; for (var k in me.watchers) { var isNotify = (k.indexOf(key) == 0); if (isNotify) { me.watchers[k](entity); } } }; RongObserver.prototype.remove = function () { }; return RongObserver; })(); RongIMLib.RongObserver = RongObserver; var Timer = (function () { function Timer(config) { this.timeout = 0; this.timer = null; this.timeout = config.timeout; } Timer.prototype.resume = function (callback) { this.timer = setTimeout(callback, this.timeout); }; Timer.prototype.pause = function () { clearTimeout(this.timer); }; return Timer; })(); RongIMLib.Timer = Timer; var InnerUtil = (function () { function InnerUtil() { } InnerUtil.getUId = function (token) { return md5(token).slice(8, 16); }; return InnerUtil; })(); RongIMLib.InnerUtil = InnerUtil; })(RongIMLib || (RongIMLib = {})); /* 说明: 请勿修改 header.js 和 footer.js 用途: 自动拼接暴露方式 命令: grunt release 中 concat */ return RongIMLib; }); ================================================ FILE: api-test-v2/lib/js/RongIMLib-2.3.5-bugfix-zhiyuan-20190408.js ================================================ /* 说明: 请勿修改 header.js 和 footer.js 用途: 自动拼接暴露方式 命令: grunt release 中 concat bugfix: 自己给自己发消息, targetId 为 ''(搜索此句能看到修改内容), 且会连续收到两条离线消息 */ (function(global, factory) { if (typeof exports === 'object' && typeof module !== 'undefined') { module.exports = factory(); } else if (typeof define === 'function' && (define.amd || define.cmd)) { define(factory); } else { var tempIMLib = factory(); var tempClient = tempIMLib.RongIMClient; var isExists = (!!global.RongIMLib); if (isExists) { var currentClient = RongIMLib.RongIMClient || {}; for(var key in currentClient){ tempClient[key] = currentClient[key]; } } global.RongIMLib = tempIMLib; global.RongIMClient = tempClient; } })(window, function(){ var Polling = { SetUserStatusInput: function(){ var a = {}; this.setStatus = function(b){ a.status = b; }; this.toArrayBuffer = function(){ return a; }; }, SetUserStatusOutput: function(){ var a = {}; this.setNothing = function(b){ a.nothing = b; }; this.toArrayBuffer = function(){ return a; }; }, GetUserStatusInput: function(){ var a = {}; this.setNothing = function(b){ a.nothing = b; }; this.toArrayBuffer = function(){ return a; }; }, GetUserStatusOutput: function(){ var a = {}; this.setStatus = function(b){ a.status = b; }; this.setSubUserId = function(b){ a.subUserId = b; }; this.toArrayBuffer = function(){ return a; }; }, VoipDynamicInput: function(){ var a = {}; this.setEngineType = function(b){ a.engineType = b; }; this.setChannelName = function(b){ a.channelName = b; }; this.setChannelExtra = function(b){ a.channelExtra = b; }; this.toArrayBuffer = function(){ return a; }; }, VoipDynamicOutput: function(){ var a = {}; this.setDynamicKey = function(b){ a.dynamicKey = b; }; this.toArrayBuffer = function(){ return a; }; }, SubUserStatusInput: function(){ var a = {}; this.setUserid = function(b){ a.userid = b; }; this.toArrayBuffer = function(){ return a; }; }, SubUserStatusOutput: function(){ var a = {}; this.setNothing = function(b){ a.nothing = b; }; this.toArrayBuffer = function(){ return a; }; }, CleanHisMsgInput: function(){ var a = {}; this.setTargetId = function(b){ a.targetId = b; }; this.setDataTime = function(b){ a.dataTime = b; }; this.setConversationType = function(b){ a.conversationType = b; }; this.toArrayBuffer = function(){ return a; }; }, DeleteMsgInput:function(){ var a = {}; this.setType = function(b){ a.type = b; }; this.setConversationId = function(b){ a.conversationId = b; }; this.setMsgs = function(b){ a.msgs = b; }; this.toArrayBuffer = function () { return a; } }, DeleteMsg:function(){ var a = {}; this.setMsgId = function(b){ a.msgId = b; }; this.setMsgDataTime = function(b){ a.msgDataTime = b; }; this.setDirect = function(b){ a.direct = b; }; this.toArrayBuffer = function () { return a; } }, DeleteMsgOutput:function(){ var a = {}; this.setNothing = function(b){ a.nothing = b; }; this.toArrayBuffer = function () { return a; } }, SearchMpInput:function(){ var a = {}; this.setType = function (b) { a.type = b; }; this.setId = function (b) { a.id = b; }; this.toArrayBuffer = function () { return a; } }, SearchMpOutput:function(){ var a = {}; this.setNothing = function (b) { a.nothing = b; }; this.setInfo = function (b) { a.info = b; }; this.toArrayBuffer = function () { return a; } }, MpInfo:function(){ var a = {}; this.setMpid = function(b){ a.mpid = b; }; this.setName = function(b){ a.name = b; }; this.setType = function(b){ a.type = b; }; this.setTime = function(b){ a.time = b; }; this.setPortraitUri = function(b){ a.portraitUrl = b; }; this.setExtra = function(b){ a.extra = b; }; this.toArrayBuffer = function () { return a; } }, PullMpInput:function(){ var a = {}; this.setMpid = function(b){ a.mpid = b; }; this.setTime = function(b){ a.time = b; }; this.toArrayBuffer = function () { return a; }; }, PullMpOutput:function(){ var a = {}; this.setStatus = function(b){ a.status = b; } this.setInfo = function(b){ a.info = b; }; this.toArrayBuffer = function () { return a; }; }, MPFollowInput:function(){ var a = {}; this.setId = function(b){ a.id = b; }; this.toArrayBuffer = function () { return a; }; }, MPFollowOutput:function(){ var a = {}; this.setNothing = function(b){ a.nothing = b; }; this.setInfo = function(b){ a.info = b; }; this.toArrayBuffer = function () { return a; }; }, NotifyMsg: function () { var a = {}; this.setType = function (b) { a.type = b; }; this.setTime = function (b) { a.time = b; }; this.setChrmId = function(b){ a.chrmId = b; }; this.toArrayBuffer = function () { return a; }; }, SyncRequestMsg: function () { var a = {}; this.setSyncTime = function (b) { a.syncTime = b || 0; }; this.setIspolling = function (b) { a.ispolling = !!b; }; this.setIsweb = function (b) { a.isweb = !!b; }; this.setIsPullSend = function (b) { a.isPullSend = !!b; }; this.setSendBoxSyncTime = function (b) { a.sendBoxSyncTime = b; }; this.toArrayBuffer = function () { return a; }; }, UpStreamMessage: function () { var a = {}; this.setSessionId = function (b) { a.sessionId = b }; this.setClassname = function (b) { a.classname = b }; this.setContent = function (b) { if (b) a.content = b; }; this.setPushText = function (b) { a.pushText = b }; this.setUserId = function(b){ a.userId = b; }; this.setAppData = function(b){ a.appData = b; }; this.toArrayBuffer = function () { return a }; }, DownStreamMessages: function () { var a = {}; this.setList = function (b) { a.list = b }; this.setSyncTime = function (b) { a.syncTime = b; }; this.setFinished = function(b){ a.finished = b; }; this.toArrayBuffer = function () { return a }; }, DownStreamMessage: function () { var a = {}; this.setFromUserId = function (b) { a.fromUserId = b }; this.setType = function (b) { a.type = b }; this.setGroupId = function (b) { a.groupId = b }; this.setClassname = function (b) { a.classname = b }; this.setContent = function (b) { if (b) a.content = b }; this.setDataTime = function (b) { a.dataTime = b; }; this.setStatus = function (b) { a.status = b; }; this.setMsgId = function (b) { a.msgId = b; }; this.toArrayBuffer = function () { return a; }; }, CreateDiscussionInput: function () { var a = {}; this.setName = function (b) { a.name = b }; this.toArrayBuffer = function () { return a } }, CreateDiscussionOutput: function () { var a = {}; this.setId = function (b) { a.id = b }; this.toArrayBuffer = function () { return a }; }, ChannelInvitationInput: function () { var a = {}; this.setUsers = function (b) { a.users = b }; this.toArrayBuffer = function () { return a }; }, LeaveChannelInput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b }; this.toArrayBuffer = function () { return a }; }, QueryChatroomInfoInput:function(){ var a = {}; this.setCount = function (b) { a.count = b; }; this.setOrder = function (b) { a.order = b; }; this.toArrayBuffer = function () { return a }; }, QueryChatroomInfoOutput:function(){ var a = {}; this.setUserTotalNums = function (b) { a.userTotalNums = b; }; this.setUserInfos = function (b) { a.userInfos = b; }; this.toArrayBuffer = function () { return a; }; }, ChannelEvictionInput: function () { var a = {}; this.setUser = function (b) { a.user = b }; this.toArrayBuffer = function () { return a }; }, RenameChannelInput: function () { var a = {}; this.setName = function (b) { a.name = b }; this.toArrayBuffer = function () { return a } }, ChannelInfoInput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b }; this.toArrayBuffer = function () { return a } }, ChannelInfoOutput: function () { var a = {}; this.setType = function (b) { a.type = b }; this.setChannelId = function (b) { a.channelId = b }; this.setChannelName = function (b) { a.channelName = b }; this.setAdminUserId = function (b) { a.adminUserId = b }; this.setFirstTenUserIds = function (b) { a.firstTenUserIds = b }; this.setOpenStatus = function (b) { a.openStatus = b }; this.toArrayBuffer = function () { return a } }, ChannelInfosInput: function () { var a = {}; this.setPage = function (b) { a.page = b }; this.setNumber = function (b) { a.number = b }; this.toArrayBuffer = function () { return a }; }, ChannelInfosOutput: function () { var a = {}; this.setChannels = function (b) { a.channels = b }; this.setTotal = function (b) { a.total = b }; this.toArrayBuffer = function () { return a }; }, MemberInfo: function () { var a = {}; this.setUserId = function (b) { a.userId = b }; this.setUserName = function (b) { a.userName = b }; this.setUserPortrait = function (b) { a.userPortrait = b }; this.setExtension = function (b) { a.extension = b }; this.toArrayBuffer = function () { return a }; }, GroupMembersInput: function () { var a = {}; this.setPage = function (b) { a.page = b }; this.setNumber = function (b) { a.number = b }; this.toArrayBuffer = function () { return a }; }, GroupMembersOutput: function () { var a = {}; this.setMembers = function (b) { a.members = b }; this.setTotal = function (b) { a.total = b }; this.toArrayBuffer = function () { return a }; }, GetUserInfoInput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b }; this.toArrayBuffer = function () { return a }; }, GetUserInfoOutput: function () { var a = {}; this.setUserId = function (b) { a.userId = b }; this.setUserName = function (b) { a.userName = b }; this.setUserPortrait = function (b) { a.userPortrait = b }; this.toArrayBuffer = function () { return a }; }, GetSessionIdInput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b }; this.toArrayBuffer = function () { return a }; }, GetSessionIdOutput: function () { var a = {}; this.setSessionId = function (b) { a.sessionId = b }; this.toArrayBuffer = function () { return a }; }, GetQNupTokenInput: function () { var a = {}; this.setType = function (b) { a.type = b; } this.toArrayBuffer = function () { return a } }, GetQNupTokenOutput: function () { var a = {}; this.setDeadline = function (b) { a.deadline = b }; this.setToken = function (b) { a.token = b; }; this.toArrayBuffer = function () { return a } }, GetQNdownloadUrlInput: function () { var a = {}; this.setType = function (b) { a.type = b; }; this.setKey = function (b) { a.key = b; }; this.setFileName = function(b){ a.fileName = b; }; this.toArrayBuffer = function () { return a } }, GetQNdownloadUrlOutput: function () { var a = {}; this.setDownloadUrl = function (b) { a.downloadUrl = b; }; this.toArrayBuffer = function () { return a } }, Add2BlackListInput: function () { var a = {}; this.setUserId = function (b) { a.userId = b; }; this.toArrayBuffer = function () { return a } }, RemoveFromBlackListInput: function () { var a = {}; this.setUserId = function (b) { a.userId = b; }; this.toArrayBuffer = function () { return a } }, QueryBlackListInput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b; }; this.toArrayBuffer = function () { return a } }, QueryBlackListOutput: function () { var a = {}; this.setUserIds = function (b) { a.userIds = b; }; this.toArrayBuffer = function () { return a } }, BlackListStatusInput: function () { var a = {}; this.setUserId = function (b) { a.userId = b; }; this.toArrayBuffer = function () { return a } }, BlockPushInput: function () { var a = {}; this.setBlockeeId = function (b) { a.blockeeId = b; }; this.toArrayBuffer = function () { return a } }, ModifyPermissionInput: function () { var a = {}; this.setOpenStatus = function (b) { a.openStatus = b; }; this.toArrayBuffer = function () { return a }; }, GroupInput: function () { var a = {}; this.setGroupInfo = function (b) { for (var i = 0, arr = []; i < b.length; i++) { arr.push({id: b[i].getContent().id, name: b[i].getContent().name}) } a.groupInfo = arr; }; this.toArrayBuffer = function () { return a }; }, GroupOutput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b; }; this.toArrayBuffer = function () { return a }; }, GroupInfo: function () { var a = {}; this.setId = function (b) { a.id = b; }; this.setName = function (b) { a.name = b; }; this.getContent = function () { return a; }; this.toArrayBuffer = function () { return a }; }, GroupHashInput: function () { var a = {}; this.setUserId = function (b) { a.userId = b; }; this.setGroupHashCode = function (b) { a.groupHashCode = b; }; this.toArrayBuffer = function () { return a }; }, GroupHashOutput: function () { var a = {}; this.setResult = function (b) { a.result = b; }; this.toArrayBuffer = function () { return a }; }, ChrmInput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b; }; this.toArrayBuffer = function () { return a }; }, ChrmOutput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b; }; this.toArrayBuffer = function () { return a }; }, ChrmPullMsg: function () { var a = {}; this.setSyncTime = function (b) { a.syncTime = b }; this.setCount = function (b) { a.count = b; }; this.toArrayBuffer = function () { return a }; }, RelationsInput: function () { var a = {}; this.setType = function (b) { a.type = b; }; this.setMsg = function(b){ a.msg = b; }; this.setCount = function(b){ a.count = b; }; this.toArrayBuffer = function () { return a }; }, RelationsOutput: function () { var a = {}; this.setInfo = function (b) { a.info = b; }; this.toArrayBuffer = function () { return a } }, RelationInfo: function () { var a = {}; this.setType = function (b) { a.type = b; }; this.setUserId = function (b) { a.userId = b; }; this.setMsg = function(b){ a.msg = b; }; this.toArrayBuffer = function () { return a } }, HistoryMessageInput: function () { var a={}; this.setTargetId=function(b){ a.targetId=b; }; this.setDataTime=function(b){ a.dataTime=b; }; this.setSize=function(b){ a.size=b; }; this.toArrayBuffer = function () { return a } }, HistoryMessagesOuput: function () { var a={}; this.setList=function(b){ a.list=b; }; this.setSyncTime=function(b){ a.syncTime=b; }; this.setHasMsg=function(b){ a.hasMsg=b; }; this.toArrayBuffer = function () { return a } }, HistoryMsgInput: function(){ var a = {}; this.setTargetId = function(b){ a.targetId = b; }; this.setTime = function(b){ a.time = b; }; this.setCount = function(b){ a.count = b; }; this.setOrder = function(b){ a.order = b; }; this.toArrayBuffer = function(){ return a; }; }, HistoryMsgOuput: function(){ var a = {}; this.setList = function(b){ a.list = b; }; this.setSyncTime = function(b){ a.syncTime = b; }; this.setHasMsg = function(b){ a.hasMsg = b; }; this.toArrayBuffer = function(){ return a; }; } }; for (var f in Polling) { Polling[f].decode = function (b) { var back = {}, val = JSON.parse(b) || eval("(" + b + ")"); for (var i in val) { back[i]=val[i]; back["get"+ i.charAt(0).toUpperCase()+i.slice(1)]=function(){ return val[i]; } } return back; } } /* * JavaScript MD5 * https://github.com/blueimp/JavaScript-MD5 * * Copyright 2011, Sebastian Tschan * https://blueimp.net * * Licensed under the MIT license: * http://www.opensource.org/licenses/MIT * * Based on * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message * Digest Algorithm, as defined in RFC 1321. * Version 2.2 Copyright (C) Paul Johnston 1999 - 2009 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet * Distributed under the BSD License * See http://pajhome.org.uk/crypt/md5 for more info. */ /*jslint bitwise: true */ /*global unescape, define, module */ var md5 = (function () { 'use strict'; /* * Add integers, wrapping at 2^32. This uses 16-bit operations internally * to work around bugs in some JS interpreters. */ function safe_add(x, y) { var lsw = (x & 0xFFFF) + (y & 0xFFFF), msw = (x >> 16) + (y >> 16) + (lsw >> 16); return (msw << 16) | (lsw & 0xFFFF); } /* * Bitwise rotate a 32-bit number to the left. */ function bit_rol(num, cnt) { return (num << cnt) | (num >>> (32 - cnt)); } /* * These functions implement the four basic operations the algorithm uses. */ function md5_cmn(q, a, b, x, s, t) { return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s), b); } function md5_ff(a, b, c, d, x, s, t) { return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t); } function md5_gg(a, b, c, d, x, s, t) { return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t); } function md5_hh(a, b, c, d, x, s, t) { return md5_cmn(b ^ c ^ d, a, b, x, s, t); } function md5_ii(a, b, c, d, x, s, t) { return md5_cmn(c ^ (b | (~d)), a, b, x, s, t); } /* * Calculate the MD5 of an array of little-endian words, and a bit length. */ function binl_md5(x, len) { /* append padding */ x[len >> 5] |= 0x80 << (len % 32); x[(((len + 64) >>> 9) << 4) + 14] = len; var i, olda, oldb, oldc, oldd, a = 1732584193, b = -271733879, c = -1732584194, d = 271733878; for (i = 0; i < x.length; i += 16) { olda = a; oldb = b; oldc = c; oldd = d; a = md5_ff(a, b, c, d, x[i], 7, -680876936); d = md5_ff(d, a, b, c, x[i + 1], 12, -389564586); c = md5_ff(c, d, a, b, x[i + 2], 17, 606105819); b = md5_ff(b, c, d, a, x[i + 3], 22, -1044525330); a = md5_ff(a, b, c, d, x[i + 4], 7, -176418897); d = md5_ff(d, a, b, c, x[i + 5], 12, 1200080426); c = md5_ff(c, d, a, b, x[i + 6], 17, -1473231341); b = md5_ff(b, c, d, a, x[i + 7], 22, -45705983); a = md5_ff(a, b, c, d, x[i + 8], 7, 1770035416); d = md5_ff(d, a, b, c, x[i + 9], 12, -1958414417); c = md5_ff(c, d, a, b, x[i + 10], 17, -42063); b = md5_ff(b, c, d, a, x[i + 11], 22, -1990404162); a = md5_ff(a, b, c, d, x[i + 12], 7, 1804603682); d = md5_ff(d, a, b, c, x[i + 13], 12, -40341101); c = md5_ff(c, d, a, b, x[i + 14], 17, -1502002290); b = md5_ff(b, c, d, a, x[i + 15], 22, 1236535329); a = md5_gg(a, b, c, d, x[i + 1], 5, -165796510); d = md5_gg(d, a, b, c, x[i + 6], 9, -1069501632); c = md5_gg(c, d, a, b, x[i + 11], 14, 643717713); b = md5_gg(b, c, d, a, x[i], 20, -373897302); a = md5_gg(a, b, c, d, x[i + 5], 5, -701558691); d = md5_gg(d, a, b, c, x[i + 10], 9, 38016083); c = md5_gg(c, d, a, b, x[i + 15], 14, -660478335); b = md5_gg(b, c, d, a, x[i + 4], 20, -405537848); a = md5_gg(a, b, c, d, x[i + 9], 5, 568446438); d = md5_gg(d, a, b, c, x[i + 14], 9, -1019803690); c = md5_gg(c, d, a, b, x[i + 3], 14, -187363961); b = md5_gg(b, c, d, a, x[i + 8], 20, 1163531501); a = md5_gg(a, b, c, d, x[i + 13], 5, -1444681467); d = md5_gg(d, a, b, c, x[i + 2], 9, -51403784); c = md5_gg(c, d, a, b, x[i + 7], 14, 1735328473); b = md5_gg(b, c, d, a, x[i + 12], 20, -1926607734); a = md5_hh(a, b, c, d, x[i + 5], 4, -378558); d = md5_hh(d, a, b, c, x[i + 8], 11, -2022574463); c = md5_hh(c, d, a, b, x[i + 11], 16, 1839030562); b = md5_hh(b, c, d, a, x[i + 14], 23, -35309556); a = md5_hh(a, b, c, d, x[i + 1], 4, -1530992060); d = md5_hh(d, a, b, c, x[i + 4], 11, 1272893353); c = md5_hh(c, d, a, b, x[i + 7], 16, -155497632); b = md5_hh(b, c, d, a, x[i + 10], 23, -1094730640); a = md5_hh(a, b, c, d, x[i + 13], 4, 681279174); d = md5_hh(d, a, b, c, x[i], 11, -358537222); c = md5_hh(c, d, a, b, x[i + 3], 16, -722521979); b = md5_hh(b, c, d, a, x[i + 6], 23, 76029189); a = md5_hh(a, b, c, d, x[i + 9], 4, -640364487); d = md5_hh(d, a, b, c, x[i + 12], 11, -421815835); c = md5_hh(c, d, a, b, x[i + 15], 16, 530742520); b = md5_hh(b, c, d, a, x[i + 2], 23, -995338651); a = md5_ii(a, b, c, d, x[i], 6, -198630844); d = md5_ii(d, a, b, c, x[i + 7], 10, 1126891415); c = md5_ii(c, d, a, b, x[i + 14], 15, -1416354905); b = md5_ii(b, c, d, a, x[i + 5], 21, -57434055); a = md5_ii(a, b, c, d, x[i + 12], 6, 1700485571); d = md5_ii(d, a, b, c, x[i + 3], 10, -1894986606); c = md5_ii(c, d, a, b, x[i + 10], 15, -1051523); b = md5_ii(b, c, d, a, x[i + 1], 21, -2054922799); a = md5_ii(a, b, c, d, x[i + 8], 6, 1873313359); d = md5_ii(d, a, b, c, x[i + 15], 10, -30611744); c = md5_ii(c, d, a, b, x[i + 6], 15, -1560198380); b = md5_ii(b, c, d, a, x[i + 13], 21, 1309151649); a = md5_ii(a, b, c, d, x[i + 4], 6, -145523070); d = md5_ii(d, a, b, c, x[i + 11], 10, -1120210379); c = md5_ii(c, d, a, b, x[i + 2], 15, 718787259); b = md5_ii(b, c, d, a, x[i + 9], 21, -343485551); a = safe_add(a, olda); b = safe_add(b, oldb); c = safe_add(c, oldc); d = safe_add(d, oldd); } return [a, b, c, d]; } /* * Convert an array of little-endian words to a string */ function binl2rstr(input) { var i, output = ''; for (i = 0; i < input.length * 32; i += 8) { output += String.fromCharCode((input[i >> 5] >>> (i % 32)) & 0xFF); } return output; } /* * Convert a raw string to an array of little-endian words * Characters >255 have their high-byte silently ignored. */ function rstr2binl(input) { var i, output = []; output[(input.length >> 2) - 1] = undefined; for (i = 0; i < output.length; i += 1) { output[i] = 0; } for (i = 0; i < input.length * 8; i += 8) { output[i >> 5] |= (input.charCodeAt(i / 8) & 0xFF) << (i % 32); } return output; } /* * Calculate the MD5 of a raw string */ function rstr_md5(s) { return binl2rstr(binl_md5(rstr2binl(s), s.length * 8)); } /* * Calculate the HMAC-MD5, of a key and some data (raw strings) */ function rstr_hmac_md5(key, data) { var i, bkey = rstr2binl(key), ipad = [], opad = [], hash; ipad[15] = opad[15] = undefined; if (bkey.length > 16) { bkey = binl_md5(bkey, key.length * 8); } for (i = 0; i < 16; i += 1) { ipad[i] = bkey[i] ^ 0x36363636; opad[i] = bkey[i] ^ 0x5C5C5C5C; } hash = binl_md5(ipad.concat(rstr2binl(data)), 512 + data.length * 8); return binl2rstr(binl_md5(opad.concat(hash), 512 + 128)); } /* * Convert a raw string to a hex string */ function rstr2hex(input) { var hex_tab = '0123456789abcdef', output = '', x, i; for (i = 0; i < input.length; i += 1) { x = input.charCodeAt(i); output += hex_tab.charAt((x >>> 4) & 0x0F) + hex_tab.charAt(x & 0x0F); } return output; } /* * Encode a string as utf-8 */ function str2rstr_utf8(input) { return unescape(encodeURIComponent(input)); } /* * Take string arguments and return either raw or hex encoded strings */ function raw_md5(s) { return rstr_md5(str2rstr_utf8(s)); } function hex_md5(s) { return rstr2hex(raw_md5(s)); } function raw_hmac_md5(k, d) { return rstr_hmac_md5(str2rstr_utf8(k), str2rstr_utf8(d)); } function hex_hmac_md5(k, d) { return rstr2hex(raw_hmac_md5(k, d)); } function md5(string, key, raw) { if (!key) { if (!raw) { return hex_md5(string); } return raw_md5(string); } if (!raw) { return hex_hmac_md5(key, string); } return raw_hmac_md5(key, string); } return md5; }()); var RongIMLib; (function (RongIMLib) { (function (MentionedType) { MentionedType[MentionedType["ALL"] = 1] = "ALL"; MentionedType[MentionedType["PART"] = 2] = "PART"; })(RongIMLib.MentionedType || (RongIMLib.MentionedType = {})); var MentionedType = RongIMLib.MentionedType; (function (MethodType) { MethodType[MethodType["CUSTOMER_SERVICE"] = 1] = "CUSTOMER_SERVICE"; MethodType[MethodType["RECALL"] = 2] = "RECALL"; })(RongIMLib.MethodType || (RongIMLib.MethodType = {})); var MethodType = RongIMLib.MethodType; (function (BlacklistStatus) { /** * 在黑名单中。 */ BlacklistStatus[BlacklistStatus["IN_BLACK_LIST"] = 0] = "IN_BLACK_LIST"; /** * 不在黑名单中。 */ BlacklistStatus[BlacklistStatus["NOT_IN_BLACK_LIST"] = 1] = "NOT_IN_BLACK_LIST"; })(RongIMLib.BlacklistStatus || (RongIMLib.BlacklistStatus = {})); var BlacklistStatus = RongIMLib.BlacklistStatus; (function (ConnectionChannel) { ConnectionChannel[ConnectionChannel["XHR_POLLING"] = 0] = "XHR_POLLING"; ConnectionChannel[ConnectionChannel["WEBSOCKET"] = 1] = "WEBSOCKET"; //外部调用 ConnectionChannel[ConnectionChannel["HTTP"] = 0] = "HTTP"; //外部调用 ConnectionChannel[ConnectionChannel["HTTPS"] = 1] = "HTTPS"; })(RongIMLib.ConnectionChannel || (RongIMLib.ConnectionChannel = {})); var ConnectionChannel = RongIMLib.ConnectionChannel; (function (CustomerType) { CustomerType[CustomerType["ONLY_ROBOT"] = 1] = "ONLY_ROBOT"; CustomerType[CustomerType["ONLY_HUMAN"] = 2] = "ONLY_HUMAN"; CustomerType[CustomerType["ROBOT_FIRST"] = 3] = "ROBOT_FIRST"; CustomerType[CustomerType["HUMAN_FIRST"] = 4] = "HUMAN_FIRST"; })(RongIMLib.CustomerType || (RongIMLib.CustomerType = {})); var CustomerType = RongIMLib.CustomerType; (function (GetChatRoomType) { GetChatRoomType[GetChatRoomType["NONE"] = 0] = "NONE"; GetChatRoomType[GetChatRoomType["SQQUENCE"] = 1] = "SQQUENCE"; GetChatRoomType[GetChatRoomType["REVERSE"] = 2] = "REVERSE"; })(RongIMLib.GetChatRoomType || (RongIMLib.GetChatRoomType = {})); var GetChatRoomType = RongIMLib.GetChatRoomType; (function (ConnectionStatus) { /** * 连接成功。 */ ConnectionStatus[ConnectionStatus["CONNECTED"] = 0] = "CONNECTED"; /** * 连接中。 */ ConnectionStatus[ConnectionStatus["CONNECTING"] = 1] = "CONNECTING"; /** * 断开连接。 */ ConnectionStatus[ConnectionStatus["DISCONNECTED"] = 2] = "DISCONNECTED"; /** * 用户账户在其他设备登录,本机会被踢掉线。 */ ConnectionStatus[ConnectionStatus["KICKED_OFFLINE_BY_OTHER_CLIENT"] = 6] = "KICKED_OFFLINE_BY_OTHER_CLIENT"; /** * websocket 连接失败 */ ConnectionStatus[ConnectionStatus["WEBSOCKET_UNAVAILABLE"] = 7] = "WEBSOCKET_UNAVAILABLE"; /** * 网络不可用。 */ ConnectionStatus[ConnectionStatus["NETWORK_UNAVAILABLE"] = 3] = "NETWORK_UNAVAILABLE"; /** * 域名错误 */ ConnectionStatus[ConnectionStatus["DOMAIN_INCORRECT"] = 12] = "DOMAIN_INCORRECT"; /** * 连接关闭。 */ ConnectionStatus[ConnectionStatus["CONNECTION_CLOSED"] = 4] = "CONNECTION_CLOSED"; /* 互踢次数过多(count > 5),此时可能出现:在其它他设备登陆有 reconnect 逻辑 */ ConnectionStatus[ConnectionStatus["ULTRALIMIT"] = 1101] = "ULTRALIMIT"; /* 开始请求导航 */ ConnectionStatus[ConnectionStatus["REQUEST_NAVI"] = 201] = "REQUEST_NAVI"; /* 请求导航结束 */ ConnectionStatus[ConnectionStatus["RESPONSE_NAVI"] = 202] = "RESPONSE_NAVI"; })(RongIMLib.ConnectionStatus || (RongIMLib.ConnectionStatus = {})); var ConnectionStatus = RongIMLib.ConnectionStatus; (function (ConversationNotificationStatus) { /** * 免打扰状态,关闭对应会话的通知提醒。 */ ConversationNotificationStatus[ConversationNotificationStatus["DO_NOT_DISTURB"] = 0] = "DO_NOT_DISTURB"; /** * 提醒。 */ ConversationNotificationStatus[ConversationNotificationStatus["NOTIFY"] = 1] = "NOTIFY"; })(RongIMLib.ConversationNotificationStatus || (RongIMLib.ConversationNotificationStatus = {})); var ConversationNotificationStatus = RongIMLib.ConversationNotificationStatus; (function (ConversationType) { ConversationType[ConversationType["NONE"] = 0] = "NONE"; ConversationType[ConversationType["PRIVATE"] = 1] = "PRIVATE"; ConversationType[ConversationType["DISCUSSION"] = 2] = "DISCUSSION"; ConversationType[ConversationType["GROUP"] = 3] = "GROUP"; ConversationType[ConversationType["CHATROOM"] = 4] = "CHATROOM"; ConversationType[ConversationType["CUSTOMER_SERVICE"] = 5] = "CUSTOMER_SERVICE"; ConversationType[ConversationType["SYSTEM"] = 6] = "SYSTEM"; //默认关注 MC ConversationType[ConversationType["APP_PUBLIC_SERVICE"] = 7] = "APP_PUBLIC_SERVICE"; //手工关注 MP ConversationType[ConversationType["PUBLIC_SERVICE"] = 8] = "PUBLIC_SERVICE"; })(RongIMLib.ConversationType || (RongIMLib.ConversationType = {})); var ConversationType = RongIMLib.ConversationType; (function (DiscussionInviteStatus) { /** * 开放邀请。 */ DiscussionInviteStatus[DiscussionInviteStatus["OPENED"] = 0] = "OPENED"; /** * 关闭邀请。 */ DiscussionInviteStatus[DiscussionInviteStatus["CLOSED"] = 1] = "CLOSED"; })(RongIMLib.DiscussionInviteStatus || (RongIMLib.DiscussionInviteStatus = {})); var DiscussionInviteStatus = RongIMLib.DiscussionInviteStatus; (function (ErrorCode) { ErrorCode[ErrorCode["RECALL_MESSAGE"] = 25101] = "RECALL_MESSAGE"; /** * 发送频率过快 */ ErrorCode[ErrorCode["SEND_FREQUENCY_TOO_FAST"] = 20604] = "SEND_FREQUENCY_TOO_FAST"; ErrorCode[ErrorCode["RC_MSG_UNAUTHORIZED"] = 20406] = "RC_MSG_UNAUTHORIZED"; /** * 群组 Id 无效 */ ErrorCode[ErrorCode["RC_DISCUSSION_GROUP_ID_INVALID"] = 20407] = "RC_DISCUSSION_GROUP_ID_INVALID"; /** * 群组被禁言 */ ErrorCode[ErrorCode["FORBIDDEN_IN_GROUP"] = 22408] = "FORBIDDEN_IN_GROUP"; /** * 不在讨论组。 */ ErrorCode[ErrorCode["NOT_IN_DISCUSSION"] = 21406] = "NOT_IN_DISCUSSION"; /** * 不在群组。 */ ErrorCode[ErrorCode["NOT_IN_GROUP"] = 22406] = "NOT_IN_GROUP"; /** * 不在聊天室。 */ ErrorCode[ErrorCode["NOT_IN_CHATROOM"] = 23406] = "NOT_IN_CHATROOM"; /** *聊天室被禁言 */ ErrorCode[ErrorCode["FORBIDDEN_IN_CHATROOM"] = 23408] = "FORBIDDEN_IN_CHATROOM"; /** * 聊天室中成员被踢出 */ ErrorCode[ErrorCode["RC_CHATROOM_USER_KICKED"] = 23409] = "RC_CHATROOM_USER_KICKED"; /** * 聊天室不存在 */ ErrorCode[ErrorCode["RC_CHATROOM_NOT_EXIST"] = 23410] = "RC_CHATROOM_NOT_EXIST"; /** * 聊天室成员已满 */ ErrorCode[ErrorCode["RC_CHATROOM_IS_FULL"] = 23411] = "RC_CHATROOM_IS_FULL"; /** * 获取聊天室信息参数无效 */ ErrorCode[ErrorCode["RC_CHATROOM_PATAMETER_INVALID"] = 23412] = "RC_CHATROOM_PATAMETER_INVALID"; /** * 聊天室异常 */ ErrorCode[ErrorCode["CHATROOM_GET_HISTORYMSG_ERROR"] = 23413] = "CHATROOM_GET_HISTORYMSG_ERROR"; /** * 没有打开聊天室消息存储 */ ErrorCode[ErrorCode["CHATROOM_NOT_OPEN_HISTORYMSG_STORE"] = 23414] = "CHATROOM_NOT_OPEN_HISTORYMSG_STORE"; /** * 敏感词屏蔽 */ ErrorCode[ErrorCode["SENSITIVE_SHIELD"] = 21501] = "SENSITIVE_SHIELD"; ErrorCode[ErrorCode["SENSITIVE_REPLACE"] = 21502] = "SENSITIVE_REPLACE"; ErrorCode[ErrorCode["TIMEOUT"] = -1] = "TIMEOUT"; /** * 未知原因失败。 */ ErrorCode[ErrorCode["UNKNOWN"] = -2] = "UNKNOWN"; /** * 加入讨论失败 */ ErrorCode[ErrorCode["JOIN_IN_DISCUSSION"] = 21407] = "JOIN_IN_DISCUSSION"; /** * 创建讨论组失败 */ ErrorCode[ErrorCode["CREATE_DISCUSSION"] = 21408] = "CREATE_DISCUSSION"; /** * 设置讨论组邀请状态失败 */ ErrorCode[ErrorCode["INVITE_DICUSSION"] = 21409] = "INVITE_DICUSSION"; /** *获取用户失败 */ ErrorCode[ErrorCode["GET_USERINFO_ERROR"] = 23407] = "GET_USERINFO_ERROR"; /** * 在黑名单中。 */ ErrorCode[ErrorCode["REJECTED_BY_BLACKLIST"] = 405] = "REJECTED_BY_BLACKLIST"; /** * 通信过程中,当前 Socket 不存在。 */ ErrorCode[ErrorCode["RC_NET_CHANNEL_INVALID"] = 30001] = "RC_NET_CHANNEL_INVALID"; /** * Socket 连接不可用。 */ ErrorCode[ErrorCode["RC_NET_UNAVAILABLE"] = 30002] = "RC_NET_UNAVAILABLE"; /** * 通信超时。 */ ErrorCode[ErrorCode["RC_MSG_RESP_TIMEOUT"] = 30003] = "RC_MSG_RESP_TIMEOUT"; /** * 导航操作时,Http 请求失败。 */ ErrorCode[ErrorCode["RC_HTTP_SEND_FAIL"] = 30004] = "RC_HTTP_SEND_FAIL"; /** * HTTP 请求失败。 */ ErrorCode[ErrorCode["RC_HTTP_REQ_TIMEOUT"] = 30005] = "RC_HTTP_REQ_TIMEOUT"; /** * HTTP 接收失败。 */ ErrorCode[ErrorCode["RC_HTTP_RECV_FAIL"] = 30006] = "RC_HTTP_RECV_FAIL"; /** * 导航操作的 HTTP 请求,返回不是200。 */ ErrorCode[ErrorCode["RC_NAVI_RESOURCE_ERROR"] = 30007] = "RC_NAVI_RESOURCE_ERROR"; /** * 导航数据解析后,其中不存在有效数据。 */ ErrorCode[ErrorCode["RC_NODE_NOT_FOUND"] = 30008] = "RC_NODE_NOT_FOUND"; /** * 导航数据解析后,其中不存在有效 IP 地址。 */ ErrorCode[ErrorCode["RC_DOMAIN_NOT_RESOLVE"] = 30009] = "RC_DOMAIN_NOT_RESOLVE"; /** * 创建 Socket 失败。 */ ErrorCode[ErrorCode["RC_SOCKET_NOT_CREATED"] = 30010] = "RC_SOCKET_NOT_CREATED"; /** * Socket 被断开。 */ ErrorCode[ErrorCode["RC_SOCKET_DISCONNECTED"] = 30011] = "RC_SOCKET_DISCONNECTED"; /** * PING 操作失败。 */ ErrorCode[ErrorCode["RC_PING_SEND_FAIL"] = 30012] = "RC_PING_SEND_FAIL"; /** * PING 超时。 */ ErrorCode[ErrorCode["RC_PONG_RECV_FAIL"] = 30013] = "RC_PONG_RECV_FAIL"; /** * 消息发送失败。 */ ErrorCode[ErrorCode["RC_MSG_SEND_FAIL"] = 30014] = "RC_MSG_SEND_FAIL"; /** * 做 connect 连接时,收到的 ACK 超时。 */ ErrorCode[ErrorCode["RC_CONN_ACK_TIMEOUT"] = 31000] = "RC_CONN_ACK_TIMEOUT"; /** * 参数错误。 */ ErrorCode[ErrorCode["RC_CONN_PROTO_VERSION_ERROR"] = 31001] = "RC_CONN_PROTO_VERSION_ERROR"; /** * 参数错误,App Id 错误。 */ ErrorCode[ErrorCode["RC_CONN_ID_REJECT"] = 31002] = "RC_CONN_ID_REJECT"; /** * 服务器不可用。 */ ErrorCode[ErrorCode["RC_CONN_SERVER_UNAVAILABLE"] = 31003] = "RC_CONN_SERVER_UNAVAILABLE"; /** * Token 错误。 */ ErrorCode[ErrorCode["RC_CONN_USER_OR_PASSWD_ERROR"] = 31004] = "RC_CONN_USER_OR_PASSWD_ERROR"; /** * App Id 与 Token 不匹配。 */ ErrorCode[ErrorCode["RC_CONN_NOT_AUTHRORIZED"] = 31005] = "RC_CONN_NOT_AUTHRORIZED"; /** * 重定向,地址错误。 */ ErrorCode[ErrorCode["RC_CONN_REDIRECTED"] = 31006] = "RC_CONN_REDIRECTED"; /** * NAME 与后台注册信息不一致。 */ ErrorCode[ErrorCode["RC_CONN_PACKAGE_NAME_INVALID"] = 31007] = "RC_CONN_PACKAGE_NAME_INVALID"; /** * APP 被屏蔽、删除或不存在。 */ ErrorCode[ErrorCode["RC_CONN_APP_BLOCKED_OR_DELETED"] = 31008] = "RC_CONN_APP_BLOCKED_OR_DELETED"; /** * 用户被屏蔽。 */ ErrorCode[ErrorCode["RC_CONN_USER_BLOCKED"] = 31009] = "RC_CONN_USER_BLOCKED"; /** * Disconnect,由服务器返回,比如用户互踢。 */ ErrorCode[ErrorCode["RC_DISCONN_KICK"] = 31010] = "RC_DISCONN_KICK"; /** * Disconnect,由服务器返回,比如用户互踢。 */ ErrorCode[ErrorCode["RC_DISCONN_EXCEPTION"] = 31011] = "RC_DISCONN_EXCEPTION"; /** * 协议层内部错误。query,上传下载过程中数据错误。 */ ErrorCode[ErrorCode["RC_QUERY_ACK_NO_DATA"] = 32001] = "RC_QUERY_ACK_NO_DATA"; /** * 协议层内部错误。 */ ErrorCode[ErrorCode["RC_MSG_DATA_INCOMPLETE"] = 32002] = "RC_MSG_DATA_INCOMPLETE"; /** * 未调用 init 初始化函数。 */ ErrorCode[ErrorCode["BIZ_ERROR_CLIENT_NOT_INIT"] = 33001] = "BIZ_ERROR_CLIENT_NOT_INIT"; /** * 数据库初始化失败。 */ ErrorCode[ErrorCode["BIZ_ERROR_DATABASE_ERROR"] = 33002] = "BIZ_ERROR_DATABASE_ERROR"; /** * 传入参数无效。 */ ErrorCode[ErrorCode["BIZ_ERROR_INVALID_PARAMETER"] = 33003] = "BIZ_ERROR_INVALID_PARAMETER"; /** * 通道无效。 */ ErrorCode[ErrorCode["BIZ_ERROR_NO_CHANNEL"] = 33004] = "BIZ_ERROR_NO_CHANNEL"; /** * 重新连接成功。 */ ErrorCode[ErrorCode["BIZ_ERROR_RECONNECT_SUCCESS"] = 33005] = "BIZ_ERROR_RECONNECT_SUCCESS"; /** * 连接中,再调用 connect 被拒绝。 */ ErrorCode[ErrorCode["BIZ_ERROR_CONNECTING"] = 33006] = "BIZ_ERROR_CONNECTING"; /** * 消息漫游服务未开通 */ ErrorCode[ErrorCode["MSG_ROAMING_SERVICE_UNAVAILABLE"] = 33007] = "MSG_ROAMING_SERVICE_UNAVAILABLE"; ErrorCode[ErrorCode["MSG_INSERT_ERROR"] = 33008] = "MSG_INSERT_ERROR"; ErrorCode[ErrorCode["MSG_DEL_ERROR"] = 33009] = "MSG_DEL_ERROR"; /** * 删除会话失败 */ ErrorCode[ErrorCode["CONVER_REMOVE_ERROR"] = 34001] = "CONVER_REMOVE_ERROR"; /** *拉取历史消息 */ ErrorCode[ErrorCode["CONVER_GETLIST_ERROR"] = 34002] = "CONVER_GETLIST_ERROR"; /** * 会话指定异常 */ ErrorCode[ErrorCode["CONVER_SETOP_ERROR"] = 34003] = "CONVER_SETOP_ERROR"; /** * 获取会话未读消息总数失败 */ ErrorCode[ErrorCode["CONVER_TOTAL_UNREAD_ERROR"] = 34004] = "CONVER_TOTAL_UNREAD_ERROR"; /** * 获取指定会话类型未读消息数异常 */ ErrorCode[ErrorCode["CONVER_TYPE_UNREAD_ERROR"] = 34005] = "CONVER_TYPE_UNREAD_ERROR"; /** * 获取指定用户ID&会话类型未读消息数异常 */ ErrorCode[ErrorCode["CONVER_ID_TYPE_UNREAD_ERROR"] = 34006] = "CONVER_ID_TYPE_UNREAD_ERROR"; ErrorCode[ErrorCode["CONVER_CLEAR_ERROR"] = 34007] = "CONVER_CLEAR_ERROR"; ErrorCode[ErrorCode["CLEAR_HIS_ERROR"] = 34010] = "CLEAR_HIS_ERROR"; ErrorCode[ErrorCode["CLEAR_HIS_TYPE_ERROR"] = 34008] = "CLEAR_HIS_TYPE_ERROR"; ErrorCode[ErrorCode["CLEAR_HIS_TIME_ERROR"] = 34011] = "CLEAR_HIS_TIME_ERROR"; /* */ ErrorCode[ErrorCode["CONVER_GET_ERROR"] = 34009] = "CONVER_GET_ERROR"; //群组异常信息 /** * */ ErrorCode[ErrorCode["GROUP_SYNC_ERROR"] = 35001] = "GROUP_SYNC_ERROR"; /** * 匹配群信息异常 */ ErrorCode[ErrorCode["GROUP_MATCH_ERROR"] = 35002] = "GROUP_MATCH_ERROR"; //聊天室异常 /** * 加入聊天室Id为空 */ ErrorCode[ErrorCode["CHATROOM_ID_ISNULL"] = 36001] = "CHATROOM_ID_ISNULL"; /** * 加入聊天室失败 */ ErrorCode[ErrorCode["CHARTOOM_JOIN_ERROR"] = 36002] = "CHARTOOM_JOIN_ERROR"; /** * 拉取聊天室历史消息失败 */ ErrorCode[ErrorCode["CHATROOM_HISMESSAGE_ERROR"] = 36003] = "CHATROOM_HISMESSAGE_ERROR"; //黑名单异常 /** * 加入黑名单异常 */ ErrorCode[ErrorCode["BLACK_ADD_ERROR"] = 37001] = "BLACK_ADD_ERROR"; /** * 获得指定人员再黑名单中的状态异常 */ ErrorCode[ErrorCode["BLACK_GETSTATUS_ERROR"] = 37002] = "BLACK_GETSTATUS_ERROR"; /** * 移除黑名单异常 */ ErrorCode[ErrorCode["BLACK_REMOVE_ERROR"] = 37003] = "BLACK_REMOVE_ERROR"; /** * 获取草稿失败 */ ErrorCode[ErrorCode["DRAF_GET_ERROR"] = 38001] = "DRAF_GET_ERROR"; /** * 保存草稿失败 */ ErrorCode[ErrorCode["DRAF_SAVE_ERROR"] = 38002] = "DRAF_SAVE_ERROR"; /** * 删除草稿失败 */ ErrorCode[ErrorCode["DRAF_REMOVE_ERROR"] = 38003] = "DRAF_REMOVE_ERROR"; /** * 关注公众号失败 */ ErrorCode[ErrorCode["SUBSCRIBE_ERROR"] = 39001] = "SUBSCRIBE_ERROR"; /** * 关注公众号失败 */ ErrorCode[ErrorCode["QNTKN_FILETYPE_ERROR"] = 41001] = "QNTKN_FILETYPE_ERROR"; /** * 获取七牛token失败 */ ErrorCode[ErrorCode["QNTKN_GET_ERROR"] = 41002] = "QNTKN_GET_ERROR"; /** * cookie被禁用 */ ErrorCode[ErrorCode["COOKIE_ENABLE"] = 51001] = "COOKIE_ENABLE"; ErrorCode[ErrorCode["GET_MESSAGE_BY_ID_ERROR"] = 61001] = "GET_MESSAGE_BY_ID_ERROR"; // 没有注册DeviveId 也就是用户没有登陆 ErrorCode[ErrorCode["HAVNODEVICEID"] = 24001] = "HAVNODEVICEID"; // 已经存在 ErrorCode[ErrorCode["DEVICEIDISHAVE"] = 24002] = "DEVICEIDISHAVE"; // 成功 ErrorCode[ErrorCode["SUCCESS"] = 0] = "SUCCESS"; // 没有对应的用户或token ErrorCode[ErrorCode["FEILD"] = 24009] = "FEILD"; // voip为空 ErrorCode[ErrorCode["VOIPISNULL"] = 24013] = "VOIPISNULL"; // 不支持的Voip引擎 ErrorCode[ErrorCode["NOENGINETYPE"] = 24010] = "NOENGINETYPE"; // channleName 是空 ErrorCode[ErrorCode["NULLCHANNELNAME"] = 24011] = "NULLCHANNELNAME"; // 生成Voipkey失败 ErrorCode[ErrorCode["VOIPDYANMICERROR"] = 24012] = "VOIPDYANMICERROR"; // 没有配置voip ErrorCode[ErrorCode["NOVOIP"] = 24014] = "NOVOIP"; // 服务器内部错误 ErrorCode[ErrorCode["INTERNALERRROR"] = 24015] = "INTERNALERRROR"; //VOIP close ErrorCode[ErrorCode["VOIPCLOSE"] = 24016] = "VOIPCLOSE"; ErrorCode[ErrorCode["CLOSE_BEFORE_OPEN"] = 51001] = "CLOSE_BEFORE_OPEN"; ErrorCode[ErrorCode["ALREADY_IN_USE"] = 51002] = "ALREADY_IN_USE"; ErrorCode[ErrorCode["INVALID_CHANNEL_NAME"] = 51003] = "INVALID_CHANNEL_NAME"; ErrorCode[ErrorCode["VIDEO_CONTAINER_IS_NULL"] = 51004] = "VIDEO_CONTAINER_IS_NULL"; /** * 删除消息数组长度为 0 . */ ErrorCode[ErrorCode["DELETE_MESSAGE_ID_IS_NULL"] = 61001] = "DELETE_MESSAGE_ID_IS_NULL"; /*! 己方取消已发出的通话请求 */ ErrorCode[ErrorCode["CANCEL"] = 1] = "CANCEL"; /*! 己方拒绝收到的通话请求 */ ErrorCode[ErrorCode["REJECT"] = 2] = "REJECT"; /*! 己方挂断 */ ErrorCode[ErrorCode["HANGUP"] = 3] = "HANGUP"; /*! 己方忙碌 */ ErrorCode[ErrorCode["BUSYLINE"] = 4] = "BUSYLINE"; /*! 己方未接听 */ ErrorCode[ErrorCode["NO_RESPONSE"] = 5] = "NO_RESPONSE"; /*! 己方不支持当前引擎 */ ErrorCode[ErrorCode["ENGINE_UN_SUPPORTED"] = 6] = "ENGINE_UN_SUPPORTED"; /*! 己方网络出错 */ ErrorCode[ErrorCode["NETWORK_ERROR"] = 7] = "NETWORK_ERROR"; /*! 对方取消已发出的通话请求 */ ErrorCode[ErrorCode["REMOTE_CANCEL"] = 11] = "REMOTE_CANCEL"; /*! 对方拒绝收到的通话请求 */ ErrorCode[ErrorCode["REMOTE_REJECT"] = 12] = "REMOTE_REJECT"; /*! 通话过程对方挂断 */ ErrorCode[ErrorCode["REMOTE_HANGUP"] = 13] = "REMOTE_HANGUP"; /*! 对方忙碌 */ ErrorCode[ErrorCode["REMOTE_BUSYLINE"] = 14] = "REMOTE_BUSYLINE"; /*! 对方未接听 */ ErrorCode[ErrorCode["REMOTE_NO_RESPONSE"] = 15] = "REMOTE_NO_RESPONSE"; /*! 对方网络错误 */ ErrorCode[ErrorCode["REMOTE_ENGINE_UN_SUPPORTED"] = 16] = "REMOTE_ENGINE_UN_SUPPORTED"; /*! 对方网络错误 */ ErrorCode[ErrorCode["REMOTE_NETWORK_ERROR"] = 17] = "REMOTE_NETWORK_ERROR"; /*! VoIP 不可用 */ ErrorCode[ErrorCode["VOIP_NOT_AVALIABLE"] = 18] = "VOIP_NOT_AVALIABLE"; })(RongIMLib.ErrorCode || (RongIMLib.ErrorCode = {})); var ErrorCode = RongIMLib.ErrorCode; (function (VoIPMediaType) { VoIPMediaType[VoIPMediaType["MEDIA_AUDIO"] = 1] = "MEDIA_AUDIO"; VoIPMediaType[VoIPMediaType["MEDIA_VEDIO"] = 2] = "MEDIA_VEDIO"; })(RongIMLib.VoIPMediaType || (RongIMLib.VoIPMediaType = {})); var VoIPMediaType = RongIMLib.VoIPMediaType; (function (MediaType) { /** * 图片。 */ MediaType[MediaType["IMAGE"] = 1] = "IMAGE"; /** * 声音。 */ MediaType[MediaType["AUDIO"] = 2] = "AUDIO"; /** * 视频。 */ MediaType[MediaType["VIDEO"] = 3] = "VIDEO"; /** * 通用文件。 */ MediaType[MediaType["FILE"] = 100] = "FILE"; })(RongIMLib.MediaType || (RongIMLib.MediaType = {})); var MediaType = RongIMLib.MediaType; (function (MessageDirection) { /** * 发送消息。 */ MessageDirection[MessageDirection["SEND"] = 1] = "SEND"; /** * 接收消息。 */ MessageDirection[MessageDirection["RECEIVE"] = 2] = "RECEIVE"; })(RongIMLib.MessageDirection || (RongIMLib.MessageDirection = {})); var MessageDirection = RongIMLib.MessageDirection; (function (FileType) { FileType[FileType["IMAGE"] = 1] = "IMAGE"; FileType[FileType["AUDIO"] = 2] = "AUDIO"; FileType[FileType["VIDEO"] = 3] = "VIDEO"; FileType[FileType["FILE"] = 4] = "FILE"; })(RongIMLib.FileType || (RongIMLib.FileType = {})); var FileType = RongIMLib.FileType; (function (RealTimeLocationErrorCode) { /** * 未初始化 RealTimeLocation 实例 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_NOT_INIT"] = -1] = "RC_REAL_TIME_LOCATION_NOT_INIT"; /** * 执行成功。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_SUCCESS"] = 0] = "RC_REAL_TIME_LOCATION_SUCCESS"; /** * 获取 RealTimeLocation 实例时返回 * GPS 未打开。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_GPS_DISABLED"] = 1] = "RC_REAL_TIME_LOCATION_GPS_DISABLED"; /** * 获取 RealTimeLocation 实例时返回 * 当前会话不支持位置共享。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_CONVERSATION_NOT_SUPPORT"] = 2] = "RC_REAL_TIME_LOCATION_CONVERSATION_NOT_SUPPORT"; /** * 获取 RealTimeLocation 实例时返回 * 对方已发起位置共享。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_IS_ON_GOING"] = 3] = "RC_REAL_TIME_LOCATION_IS_ON_GOING"; /** * Join 时返回 * 当前位置共享已超过最大支持人数。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_EXCEED_MAX_PARTICIPANT"] = 4] = "RC_REAL_TIME_LOCATION_EXCEED_MAX_PARTICIPANT"; /** * Join 时返回 * 加入位置共享失败。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_JOIN_FAILURE"] = 5] = "RC_REAL_TIME_LOCATION_JOIN_FAILURE"; /** * Start 时返回 * 发起位置共享失败。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_START_FAILURE"] = 6] = "RC_REAL_TIME_LOCATION_START_FAILURE"; /** * 网络不可用。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_NETWORK_UNAVAILABLE"] = 7] = "RC_REAL_TIME_LOCATION_NETWORK_UNAVAILABLE"; })(RongIMLib.RealTimeLocationErrorCode || (RongIMLib.RealTimeLocationErrorCode = {})); var RealTimeLocationErrorCode = RongIMLib.RealTimeLocationErrorCode; (function (RealTimeLocationStatus) { /** * 空闲状态 (默认状态) * 对方或者自己都未发起位置共享业务,或者位置共享业务已结束。 */ RealTimeLocationStatus[RealTimeLocationStatus["RC_REAL_TIME_LOCATION_STATUS_IDLE"] = 0] = "RC_REAL_TIME_LOCATION_STATUS_IDLE"; /** * 呼入状态 (待加入) * 1. 对方发起了位置共享业务,此状态下,自己只能选择加入。 * 2. 自己从已连接的位置共享中退出。 */ RealTimeLocationStatus[RealTimeLocationStatus["RC_REAL_TIME_LOCATION_STATUS_INCOMING"] = 1] = "RC_REAL_TIME_LOCATION_STATUS_INCOMING"; /** * 呼出状态 =(自己创建) * 1. 自己发起位置共享业务,对方只能选择加入。 * 2. 对方从已连接的位置共享业务中退出。 */ RealTimeLocationStatus[RealTimeLocationStatus["RC_REAL_TIME_LOCATION_STATUS_OUTGOING"] = 2] = "RC_REAL_TIME_LOCATION_STATUS_OUTGOING"; /** * 连接状态 (自己加入) * 对方加入了自己发起的位置共享,或者自己加入了对方发起的位置共享。 */ RealTimeLocationStatus[RealTimeLocationStatus["RC_REAL_TIME_LOCATION_STATUS_CONNECTED"] = 3] = "RC_REAL_TIME_LOCATION_STATUS_CONNECTED"; })(RongIMLib.RealTimeLocationStatus || (RongIMLib.RealTimeLocationStatus = {})); var RealTimeLocationStatus = RongIMLib.RealTimeLocationStatus; (function (ReceivedStatus) { ReceivedStatus[ReceivedStatus["READ"] = 1] = "READ"; ReceivedStatus[ReceivedStatus["LISTENED"] = 2] = "LISTENED"; ReceivedStatus[ReceivedStatus["DOWNLOADED"] = 4] = "DOWNLOADED"; ReceivedStatus[ReceivedStatus["RETRIEVED"] = 8] = "RETRIEVED"; ReceivedStatus[ReceivedStatus["UNREAD"] = 0] = "UNREAD"; })(RongIMLib.ReceivedStatus || (RongIMLib.ReceivedStatus = {})); var ReceivedStatus = RongIMLib.ReceivedStatus; (function (ReadStatus) { ReadStatus[ReadStatus["READ"] = 1] = "READ"; ReadStatus[ReadStatus["LISTENED"] = 2] = "LISTENED"; ReadStatus[ReadStatus["DOWNLOADED"] = 4] = "DOWNLOADED"; ReadStatus[ReadStatus["RETRIEVED"] = 8] = "RETRIEVED"; ReadStatus[ReadStatus["UNREAD"] = 0] = "UNREAD"; })(RongIMLib.ReadStatus || (RongIMLib.ReadStatus = {})); var ReadStatus = RongIMLib.ReadStatus; (function (SearchType) { /** * 精确。 */ SearchType[SearchType["EXACT"] = 0] = "EXACT"; /** * 模糊。 */ SearchType[SearchType["FUZZY"] = 1] = "FUZZY"; })(RongIMLib.SearchType || (RongIMLib.SearchType = {})); var SearchType = RongIMLib.SearchType; (function (SentStatus) { /** * 发送中。 */ SentStatus[SentStatus["SENDING"] = 10] = "SENDING"; /** * 发送失败。 */ SentStatus[SentStatus["FAILED"] = 20] = "FAILED"; /** * 已发送。 */ SentStatus[SentStatus["SENT"] = 30] = "SENT"; /** * 对方已接收。 */ SentStatus[SentStatus["RECEIVED"] = 40] = "RECEIVED"; /** * 对方已读。 */ SentStatus[SentStatus["READ"] = 50] = "READ"; /** * 对方已销毁。 */ SentStatus[SentStatus["DESTROYED"] = 60] = "DESTROYED"; })(RongIMLib.SentStatus || (RongIMLib.SentStatus = {})); var SentStatus = RongIMLib.SentStatus; (function (ConnectionState) { ConnectionState[ConnectionState["ACCEPTED"] = 0] = "ACCEPTED"; ConnectionState[ConnectionState["UNACCEPTABLE_PROTOCOL_VERSION"] = 1] = "UNACCEPTABLE_PROTOCOL_VERSION"; ConnectionState[ConnectionState["IDENTIFIER_REJECTED"] = 2] = "IDENTIFIER_REJECTED"; ConnectionState[ConnectionState["SERVER_UNAVAILABLE"] = 3] = "SERVER_UNAVAILABLE"; /** * token无效 */ ConnectionState[ConnectionState["TOKEN_INCORRECT"] = 4] = "TOKEN_INCORRECT"; ConnectionState[ConnectionState["NOT_AUTHORIZED"] = 5] = "NOT_AUTHORIZED"; ConnectionState[ConnectionState["REDIRECT"] = 6] = "REDIRECT"; ConnectionState[ConnectionState["PACKAGE_ERROR"] = 7] = "PACKAGE_ERROR"; ConnectionState[ConnectionState["APP_BLOCK_OR_DELETE"] = 8] = "APP_BLOCK_OR_DELETE"; ConnectionState[ConnectionState["BLOCK"] = 9] = "BLOCK"; ConnectionState[ConnectionState["TOKEN_EXPIRE"] = 10] = "TOKEN_EXPIRE"; ConnectionState[ConnectionState["DEVICE_ERROR"] = 11] = "DEVICE_ERROR"; })(RongIMLib.ConnectionState || (RongIMLib.ConnectionState = {})); var ConnectionState = RongIMLib.ConnectionState; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var RongIMClient = (function () { function RongIMClient() { } RongIMClient.getInstance = function () { if (!RongIMClient._instance) { throw new Error("RongIMClient is not initialized. Call .init() method first."); } return RongIMClient._instance; }; RongIMClient.showError = function (errorInfo) { var hasConsole = (console && console.error); if (hasConsole) { console.error(JSON.stringify(errorInfo)); } }; RongIMClient.logger = function (params) { var code = params.code; var errorInfo = RongIMClient.LogFactory[code] || params; errorInfo.funcName = params.funcName; errorInfo.msg = params.msg || errorInfo.msg; if (RongIMClient._memoryStore.depend.showError) { RongIMClient.showError(errorInfo); } }; RongIMClient.logCallback = function (callback, funcName) { return { onSuccess: callback.onSuccess, onError: function (errorCode) { RongIMClient.logger({ code: errorCode, funcName: funcName }); callback.onError(errorCode); } }; }; ; RongIMClient.logSendCallback = function (callback, funcName) { return { onSuccess: callback.onSuccess, onError: function (errorCode, result) { RongIMClient.logger({ code: errorCode, funcName: funcName }); callback.onError(errorCode, result); }, onBefore: callback.onBefore }; }; ; /** * 初始化 SDK,在整个应用全局只需要调用一次。 * @param appKey 开发者后台申请的 AppKey,用来标识应用。 * @param dataAccessProvider 必须是DataAccessProvider的实例 */ RongIMClient.init = function (appKey, dataAccessProvider, options, callback) { if (RongIMClient._instance) { return RongIMClient._memoryStore.sdkInfo; } RongIMClient._instance = new RongIMClient(); options = options || {}; var protocol = "http://", wsScheme = 'ws://'; if (location.protocol == 'https:') { wsScheme = 'wss://'; protocol = 'https://'; } var isPolling = false; if (typeof WebSocket != 'function') { isPolling = true; } var isIntegrity = function () { //iOS 9 var hasWS = (typeof WebSocket); var integrity = (typeof WebSocket.OPEN == 'number'); return (hasWS && integrity); }; if (typeof WebSocket == 'object' && isIntegrity()) { isPolling = false; } var supportUserData = function () { var element = document.documentElement; return element.addBehavior; }; if (RongIMLib.RongUtil.supportLocalStorage()) { RongIMClient._storageProvider = new RongIMLib.LocalStorageProvider(); } else if (supportUserData()) { RongIMClient._storageProvider = new RongIMLib.UserDataProvider(); } else { RongIMClient._storageProvider = new RongIMLib.MemeoryProvider(); } var serverIndex = RongIMClient._storageProvider.getItem('serverIndex'); RongIMClient.serverStore.index = serverIndex || 0; var pathTmpl = '{0}{1}'; var _serverPath = { navi: 'nav.cn.ronghub.com', api: 'api.cn.ronghub.com' }; RongIMLib.RongUtil.forEach(_serverPath, function (path, key) { _serverPath[key] = RongIMLib.RongUtil.stringFormat(pathTmpl, [protocol, path]); }); RongIMLib.RongUtil.forEach(_serverPath, function (path, key) { var hasProto = (key in options); var config = { path: options[key], tmpl: pathTmpl, protocol: protocol, sub: true }; path = hasProto ? RongIMLib.RongUtil.formatProtoclPath(config) : path; options[key] = path; }); var _sourcePath = { protobuf: 'cdn.ronghub.com/protobuf-2.3.3.min.js' }; RongIMLib.RongUtil.forEach(_sourcePath, function (path, key) { _sourcePath[key] = RongIMLib.RongUtil.stringFormat(pathTmpl, [protocol, path]); }); RongIMLib.RongUtil.extend(_sourcePath, options); var _defaultOpts = { isPolling: isPolling, wsScheme: wsScheme, protocol: protocol, showError: true, openMp: true, snifferTime: 2000 }; RongIMLib.RongUtil.extend(_defaultOpts, options); if (RongIMLib.RongUtil.isFunction(options.protobuf)) { RongIMClient.Protobuf = options.protobuf; } RongIMClient.userStatusObserver = new RongIMLib.RongObserver(); var pather = new RongIMLib.FeaturePatcher(); pather.patchAll(); var tempStore = { token: "", callback: null, lastReadTime: new RongIMLib.LimitableMap(), historyMessageLimit: new RongIMLib.MemoryCache(), conversationList: [], appKey: appKey, publicServiceMap: new RongIMLib.PublicServiceMap(), providerType: 1, deltaTime: 0, filterMessages: [], isSyncRemoteConverList: true, otherDevice: false, custStore: {}, converStore: { latestMessage: {} }, connectAckTime: 0, voipStategy: 0, isFirstPingMsg: true, depend: options, listenerList: RongIMClient._memoryStore.listenerList, notification: {} }; RongIMClient._memoryStore = tempStore; if (dataAccessProvider && Object.prototype.toString.call(dataAccessProvider) == "[object Object]") { RongIMClient._dataAccessProvider = dataAccessProvider; } else { RongIMClient._dataAccessProvider = new RongIMLib.ServerDataProvider(); } options.appCallback = callback; var sdkInfo = RongIMClient._dataAccessProvider.init(appKey, options); RongIMClient._memoryStore.sdkInfo = sdkInfo; // 兼容 c++ 设置导航,Web 端不生效 RongIMClient._dataAccessProvider.setServerInfo({ navi: location.protocol + options.navi + '/navi.xml' }); RongIMClient.MessageParams = { TextMessage: { objectName: "RC:TxtMsg", msgTag: new RongIMLib.MessageTag(true, true) }, ImageMessage: { objectName: "RC:ImgMsg", msgTag: new RongIMLib.MessageTag(true, true) }, DiscussionNotificationMessage: { objectName: "RC:DizNtf", msgTag: new RongIMLib.MessageTag(false, true) }, VoiceMessage: { objectName: "RC:VcMsg", msgTag: new RongIMLib.MessageTag(true, true) }, RichContentMessage: { objectName: "RC:ImgTextMsg", msgTag: new RongIMLib.MessageTag(true, true) }, FileMessage: { objectName: "RC:FileMsg", msgTag: new RongIMLib.MessageTag(true, true) }, HandshakeMessage: { objectName: "", msgTag: new RongIMLib.MessageTag(true, true) }, UnknownMessage: { objectName: "", msgTag: new RongIMLib.MessageTag(true, true) }, LocationMessage: { objectName: "RC:LBSMsg", msgTag: new RongIMLib.MessageTag(true, true) }, InformationNotificationMessage: { objectName: "RC:InfoNtf", msgTag: new RongIMLib.MessageTag(false, true) }, ContactNotificationMessage: { objectName: "RC:ContactNtf", msgTag: new RongIMLib.MessageTag(false, true) }, ProfileNotificationMessage: { objectName: "RC:ProfileNtf", msgTag: new RongIMLib.MessageTag(false, true) }, CommandNotificationMessage: { objectName: "RC:CmdNtf", msgTag: new RongIMLib.MessageTag(true, true) }, PublicServiceRichContentMessage: { objectName: "RC:PSImgTxtMsg", msgTag: new RongIMLib.MessageTag(true, true) }, PublicServiceMultiRichContentMessage: { objectName: "RC:PSMultiImgTxtMsg", msgTag: new RongIMLib.MessageTag(true, true) }, JrmfRedPacketMessage: { objectName: "RCJrmf:RpMsg", msgTag: new RongIMLib.MessageTag(true, true) }, JrmfRedPacketOpenedMessage: { objectName: "RCJrmf:RpOpendMsg", msgTag: new RongIMLib.MessageTag(true, true) }, GroupNotificationMessage: { objectName: "RC:GrpNtf", msgTag: new RongIMLib.MessageTag(false, true) }, CommandMessage: { objectName: "RC:CmdMsg", msgTag: new RongIMLib.MessageTag(false, false) }, TypingStatusMessage: { objectName: "RC:TypSts", msgTag: new RongIMLib.MessageTag(false, false) }, PublicServiceCommandMessage: { objectName: "RC:PSCmd", msgTag: new RongIMLib.MessageTag(false, false) }, RecallCommandMessage: { objectName: "RC:RcCmd", msgTag: new RongIMLib.MessageTag(false, true) }, SyncReadStatusMessage: { objectName: "RC:SRSMsg", msgTag: new RongIMLib.MessageTag(false, false) }, ReadReceiptRequestMessage: { objectName: "RC:RRReqMsg", msgTag: new RongIMLib.MessageTag(false, false) }, ReadReceiptResponseMessage: { objectName: "RC:RRRspMsg", msgTag: new RongIMLib.MessageTag(false, false) }, ChangeModeResponseMessage: { objectName: "RC:CsChaR", msgTag: new RongIMLib.MessageTag(false, false) }, ChangeModeMessage: { objectName: "RC:CSCha", msgTag: new RongIMLib.MessageTag(false, false) }, EvaluateMessage: { objectName: "RC:CsEva", msgTag: new RongIMLib.MessageTag(false, false) }, CustomerContact: { objectName: "RC:CsContact", msgTag: new RongIMLib.MessageTag(false, false) }, HandShakeMessage: { objectName: "RC:CsHs", msgTag: new RongIMLib.MessageTag(false, false) }, HandShakeResponseMessage: { objectName: "RC:CsHsR", msgTag: new RongIMLib.MessageTag(false, false) }, SuspendMessage: { objectName: "RC:CsSp", msgTag: new RongIMLib.MessageTag(false, false) }, TerminateMessage: { objectName: "RC:CsEnd", msgTag: new RongIMLib.MessageTag(false, false) }, CustomerStatusUpdateMessage: { objectName: "RC:CsUpdate", msgTag: new RongIMLib.MessageTag(false, false) }, ReadReceiptMessage: { objectName: "RC:ReadNtf", msgTag: new RongIMLib.MessageTag(false, false) } }; RongIMClient.MessageParams["AcceptMessage"] = { objectName: "RC:VCAccept", msgTag: new RongIMLib.MessageTag(false, false) }; RongIMClient.MessageParams["RingingMessage"] = { objectName: "RC:VCRinging", msgTag: new RongIMLib.MessageTag(false, false) }; RongIMClient.MessageParams["SummaryMessage"] = { objectName: "RC:VCSummary", msgTag: new RongIMLib.MessageTag(false, false) }; RongIMClient.MessageParams["HungupMessage"] = { objectName: "RC:VCHangup", msgTag: new RongIMLib.MessageTag(false, false) }; RongIMClient.MessageParams["InviteMessage"] = { objectName: "RC:VCInvite", msgTag: new RongIMLib.MessageTag(false, false) }; RongIMClient.MessageParams["MediaModifyMessage"] = { objectName: "RC:VCModifyMedia", msgTag: new RongIMLib.MessageTag(false, false) }; RongIMClient.MessageParams["MemberModifyMessage"] = { objectName: "RC:VCModifyMem", msgTag: new RongIMLib.MessageTag(false, false) }; RongIMClient.MessageType = { TextMessage: "TextMessage", ImageMessage: "ImageMessage", DiscussionNotificationMessage: "DiscussionNotificationMessage", VoiceMessage: "VoiceMessage", RichContentMessage: "RichContentMessage", HandshakeMessage: "HandshakeMessage", UnknownMessage: "UnknownMessage", LocationMessage: "LocationMessage", InformationNotificationMessage: "InformationNotificationMessage", ContactNotificationMessage: "ContactNotificationMessage", ProfileNotificationMessage: "ProfileNotificationMessage", CommandNotificationMessage: "CommandNotificationMessage", CommandMessage: "CommandMessage", TypingStatusMessage: "TypingStatusMessage", ChangeModeResponseMessage: "ChangeModeResponseMessage", ChangeModeMessage: "ChangeModeMessage", EvaluateMessage: "EvaluateMessage", HandShakeMessage: "HandShakeMessage", HandShakeResponseMessage: "HandShakeResponseMessage", SuspendMessage: "SuspendMessage", TerminateMessage: "TerminateMessage", CustomerContact: "CustomerContact", CustomerStatusUpdateMessage: "CustomerStatusUpdateMessage", SyncReadStatusMessage: "SyncReadStatusMessage", ReadReceiptRequestMessage: "ReadReceiptRequestMessage", ReadReceiptResponseMessage: "ReadReceiptResponseMessage", FileMessage: 'FileMessage', AcceptMessage: "AcceptMessage", RingingMessage: "RingingMessage", SummaryMessage: "SummaryMessage", HungupMessage: "HungupMessage", InviteMessage: "InviteMessage", MediaModifyMessage: "MediaModifyMessage", MemberModifyMessage: "MemberModifyMessage", JrmfRedPacketMessage: "JrmfRedPacketMessage", JrmfRedPacketOpenedMessage: "JrmfRedPacketOpenedMessage", GroupNotificationMessage: "GroupNotificationMessage", PublicServiceRichContentMessage: "PublicServiceRichContentMessage", PublicServiceMultiRichContentMessage: "PublicServiceMultiRichContentMessage", PublicServiceCommandMessage: "PublicServiceCommandMessage", RecallCommandMessage: "RecallCommandMessage", ReadReceiptMessage: "ReadReceiptMessage" }; RongIMClient.LogFactory = { /** * 个人 */ "-1": { code: "-1", msg: "服务器超时" }, "-2": { code: "-2", msg: "未知原因失败" }, "-3": { code: "-3", msg: "参数错误" }, "-4": { code: "-4", msg: "参数不正确或尚未实例化" }, "25101": { code: "25101", msg: "撤回消息参数错误", desc: "请检查撤回消息参数 https://rongcloud.github.io/websdk-demo/api-test.html" }, "25102": { code: "25101", msg: "只能撤回自发发送的消息" }, "20604": { code: "20604", msg: "发送频率过快", desc: "https://developer.rongcloud.cn/ticket/info/9Q3L6vRKd1cLS7rycA==?type=1" }, "20406": { code: "20406", msg: "被禁言" }, "23407": { code: "23407", msg: "获取用户失败" }, /** * 群组 */ "20407": { code: "20407", msg: "群组Id无效" }, "22408": { code: "22408", msg: "群组被禁言" }, "22406": { code: "22406", msg: "不在群组" }, "35001": { code: "35001", msg: "群组同步异常" }, "35002": { code: "35002", msg: "匹配群信息异常" }, /** * 讨论组 */ "21406": { code: "21406", msg: "不在讨论组" }, "21407": { code: "21407", msg: "加入讨论失败" }, "21408": { code: "21408", msg: "创建讨论组失败" }, "21409": { code: "21409", msg: "设置讨论组邀请状态失败" }, /** * 聊天室 */ "23406": { code: "23406", msg: "不在聊天室" }, "23408": { code: "23408", msg: "聊天室被禁言" }, "23409": { code: "23409", msg: "聊天室中成员被踢出" }, "23410": { code: "23410", msg: "聊天室不存在" }, "23411": { code: "23411", msg: "聊天室成员已满" }, "23412": { code: "23412", msg: "获取聊天室信息参数无效" }, "23413": { code: "23413", msg: "聊天室异常" }, "23414": { code: "23414", msg: "没有打开聊天室消息存储" }, "36001": { code: "36001", msg: "加入聊天室Id为空" }, "36002": { code: "36002", msg: "加入聊天室失败" }, "36003": { code: "36003", msg: "拉取聊天室历史消息失败" }, /** * voip */ "24001": { code: "24001", msg: "没有注册DeviveId 也就是用户没有登陆" }, "24002": { code: "24002", msg: "用户已经存在" }, "0": { code: "0", msg: "成功" }, "24009": { code: "24009", msg: "没有对应的用户或token" }, "24013": { code: "24013", msg: "voip为空" }, "24010": { code: "24010", msg: "不支持的Voip引擎" }, "24011": { code: "24011", msg: "channelName 是空" }, "24012": { code: "24012", msg: "生成Voipkey失败" }, "24014": { code: "24014", msg: "没有配置voip" }, "24015": { code: "24015", msg: "服务器内部错误" }, "24016": { code: "24016", msg: "VOIP close" }, /** * 通讯、导航 */ "30001": { code: "30001", msg: "通信过程中,当前Socket不存在" }, "30002": { code: "30002", msg: "Socket连接不可用" }, "30003": { code: "30003", msg: "通信超时" }, "30004": { code: "30004", msg: "导航操作时,Http请求失败" }, "30005": { code: "30005", msg: "HTTP请求失败" }, "30006": { code: "30006", msg: "HTTP接收失败" }, "30007": { code: "30007", msg: "导航资源错误" }, "30008": { code: "30008", msg: "没有有效数据" }, "30009": { code: "30009", msg: "不存在有效 IP 地址" }, "30010": { code: "30010", msg: "创建 Socket 失败" }, "30011": { code: "30011", msg: " Socket 被断开" }, "30012": { code: "30012", msg: "PING 操作失败" }, "30013": { code: "30013", msg: "PING 超时" }, "30014": { code: "30014", msg: "消息发送失败" }, "30016": { code: "30016", msg: "消息大小超限,最大 128 KB" }, /** * 连接 */ "31000": { code: "31000", msg: "做 connect 连接时,收到的 ACK 超时" }, "31001": { code: "31001", msg: "参数错误" }, "31002": { code: "31002", msg: "参数错误,App Id 错误" }, "31003": { code: "31003", msg: "服务器不可用" }, "31004": { code: "31004", msg: "Token 错误" }, "31005": { code: "31005", msg: "App Id 与 Token 不匹配" }, "31006": { code: "31006", msg: "重定向,地址错误" }, "31007": { code: "31007", msg: "NAME 与后台注册信息不一致" }, "31008": { code: "31008", msg: "APP 被屏蔽、删除或不存在" }, "31009": { code: "31009", msg: "用户被屏蔽" }, "31010": { code: "31010", msg: "Disconnect,由服务器返回,比如用户互踢" }, "31011": { code: "31011", msg: "Disconnect,由服务器返回,比如用户互踢" }, /** * 协议 */ "32001": { code: "32001", msg: "协议层内部错误。query,上传下载过程中数据错误" }, "32002": { code: "32002", msg: "协议层内部错误" }, /** * BIZ */ "33001": { code: "33001", msg: "未调用 init 初始化函数" }, "33002": { code: "33002", msg: "数据库初始化失败" }, "33003": { code: "33003", msg: "传入参数无效" }, "33004": { code: "33004", msg: "通道无效" }, "33005": { code: "33005", msg: "重新连接成功" }, "33006": { code: "33006", msg: "连接中,再调用 connect 被拒绝" }, "33007": { code: "33007", msg: "消息漫游服务未开通" }, "33008": { code: "33008", msg: "消息添加失败" }, "33009": { code: "33009", msg: "消息删除失败" }, /** * 会话 */ "34001": { code: "34001", msg: "删除会话失败" }, "34002": { code: "34002", msg: "拉取历史消息失败" }, "34003": { code: "34003", msg: "会话指定异常" }, "34004": { code: "34004", msg: "获取会话未读消息总数失败" }, "34005": { code: "34005", msg: "获取指定会话类型未读消息数异常" }, "34006": { code: "34006", msg: "获取指定用户ID&会话类型未读消息数异常" }, "34007": { code: "34007", msg: "清除会话消息异常" }, "34008": { code: "34008", msg: "获取会话消息异常" }, "34009": { code: "34009", msg: "清除历史消息会话类型不正确" }, "34010": { code: "34010", msg: "清除历史消息失败,请检查传入参数" }, /** * 黑名单异常 */ "37001": { code: "37001", msg: "加入黑名单异常" }, "37002": { code: "37002", msg: "获得指定人员再黑名单中的状态异常" }, "37003": { code: "37003", msg: "移除黑名单异常" }, "405": { code: "405", msg: "在黑名单中" }, /** * 草稿 */ "38001": { code: "38001", msg: "获取草稿失败" }, "38002": { code: "38002", msg: "保存草稿失败" }, "38003": { code: "38003", msg: "删除草稿失败" }, /** * 公众号 */ "39001": { code: "39001", msg: "关注公众号失败" }, /** * 文件 */ "41001": { code: "41001", msg: "文件类型错误" }, "41002": { code: "41002", msg: "获取七牛token失败" }, /** * */ "51001": { code: "51001", msg: "未安装或未启动插件" }, "51002": { code: "51002", msg: "视频已经存在" }, "51003": { code: "51003", msg: "无效的channelName" }, "51004": { code: "51004", msg: "视频内容为空" }, /** * */ "61001": { code: "61001", msg: "删除消息数组长度为 0" } }; return sdkInfo; }; ; /** var config = { appkey: appkey, token: token, dataAccessProvider:dataAccessProvider, opts: opts }; callback(_instance, userId); */ RongIMClient.initApp = function (config, callback) { RongIMClient.init(config.appkey, config.dataAccessProvider, config.opts, function () { var instance = RongIMClient._instance; //备用 var error = null; callback(error, instance); }); }; /** * 连接服务器,在整个应用全局只需要调用一次,断线后 SDK 会自动重连。 * * @param token 从服务端获取的用户身份令牌(Token)。 * @param callback 连接回调,返回连接的成功或者失败状态。 */ RongIMClient.connect = function (token, _callback, userId, serverConf) { RongIMLib.CheckParam.getInstance().check(["string", "object", "string|null|object|global|undefined", "object|null|global|undefined"], "connect", true, arguments); var connectCallback = { onSuccess: _callback.onSuccess, onTokenIncorrect: _callback.onTokenIncorrect, onError: function (errorCode) { RongIMClient.logger({ code: errorCode, funcName: "connect" }); _callback.onError(errorCode); } }; RongIMClient._dataAccessProvider.connect(token, connectCallback, userId, serverConf); }; RongIMClient.reconnect = function (callback, config) { var connectCallback = { onSuccess: callback.onSuccess, onTokenIncorrect: callback.onTokenIncorrect, onError: function (errorCode) { RongIMClient.logger({ code: errorCode, funcName: "connect" }); callback.onError(errorCode); } }; RongIMClient._dataAccessProvider.reconnect(connectCallback, config); }; /** * 注册消息类型,用于注册用户自定义的消息。 * 内建的消息类型已经注册过,不需要再次注册。 * 自定义消息声明需放在执行顺序最高的位置(在RongIMClient.init(appkey)之后即可) * @param objectName 消息内置名称 */ RongIMClient.registerMessageType = function (messageType, objectName, messageTag, messageContent, searchProps) { RongIMClient._dataAccessProvider.registerMessageType(messageType, objectName, messageTag, messageContent, searchProps); RongIMClient.RegisterMessage[messageType].messageName = messageType; RongIMClient.MessageType[messageType] = messageType; RongIMClient.MessageParams[messageType] = { objectName: objectName, msgTag: messageTag }; }; RongIMClient.prototype.registerMessageTypes = function (types) { types = types || {}; RongIMClient._dataAccessProvider.registerMessageTypes(types); }; /** * 设置连接状态变化的监听器。 * * @param listener 连接状态变化的监听器。 */ RongIMClient.setConnectionStatusListener = function (listener) { if (RongIMClient._dataAccessProvider) { RongIMClient._dataAccessProvider.setConnectionStatusListener(listener); } else { RongIMClient._memoryStore.listenerList.push(listener); } }; /** * 设置接收消息的监听器。 * * @param listener 接收消息的监听器。 */ RongIMClient.setOnReceiveMessageListener = function (listener) { if (RongIMClient._dataAccessProvider) { RongIMClient._dataAccessProvider.setOnReceiveMessageListener(listener); } else { RongIMClient._memoryStore.listenerList.push(listener); } }; /** * 清理所有连接相关的变量 */ RongIMClient.prototype.logout = function () { RongIMClient._dataAccessProvider.logout(); }; /** * 断开连接。 */ RongIMClient.prototype.disconnect = function () { RongIMClient._dataAccessProvider.disconnect(); }; RongIMClient.prototype.startCustomService = function (custId, callback, content) { if (!custId || !callback) return; var msg = new RongIMLib.HandShakeMessage(content); var me = this; RongIMLib.RongIMClient._memoryStore.custStore["isInit"] = true; RongIMClient.getInstance().sendMessage(RongIMLib.ConversationType.CUSTOMER_SERVICE, custId, msg, { onSuccess: function (data) { if (data.isBlack) { callback.onError(); me.stopCustomeService(custId, { onSuccess: function () { }, onError: function () { } }); } else { callback.onSuccess(); } }, onError: function () { callback.onError(); }, onBefore: function () { } }); }; RongIMClient.prototype.stopCustomeService = function (custId, callback) { if (!custId || !callback) return; var session = RongIMClient._memoryStore.custStore[custId]; if (!session) return; var msg = new RongIMLib.SuspendMessage({ sid: session.sid, uid: session.uid, pid: session.pid }); this.sendCustMessage(custId, msg, { onSuccess: function () { // delete RongIMClient._memoryStore.custStore[custId]; setTimeout(function () { callback.onSuccess(); }); }, onError: function () { setTimeout(function () { callback.onError(); }); } }); }; RongIMClient.prototype.switchToHumanMode = function (custId, callback) { if (!custId || !callback) return; var session = RongIMClient._memoryStore.custStore[custId]; if (!session) return; var msg = new RongIMLib.ChangeModeMessage({ sid: session.sid, uid: session.uid, pid: session.pid }); this.sendCustMessage(custId, msg, callback); }; RongIMClient.prototype.evaluateRebotCustomService = function (custId, isRobotResolved, sugest, callback) { if (!custId || !callback) return; var session = RongIMClient._memoryStore.custStore[custId]; if (!session) return; var msg = new RongIMLib.EvaluateMessage({ sid: session.sid, uid: session.uid, pid: session.pid, isRobotResolved: isRobotResolved, sugest: sugest, type: 0 }); this.sendCustMessage(custId, msg, callback); }; RongIMClient.prototype.evaluateHumanCustomService = function (custId, humanValue, sugest, callback) { if (!custId || !callback) return; var session = RongIMClient._memoryStore.custStore[custId]; if (!session) return; var msg = new RongIMLib.EvaluateMessage({ sid: session.sid, uid: session.uid, pid: session.pid, humanValue: humanValue, sugest: sugest, type: 1 }); this.sendCustMessage(custId, msg, callback); }; RongIMClient.prototype.sendCustMessage = function (custId, msg, callback) { RongIMClient.getInstance().sendMessage(RongIMLib.ConversationType.CUSTOMER_SERVICE, custId, msg, { onSuccess: function (data) { callback.onSuccess(); }, onError: function () { callback.onError(); }, onBefore: function () { } }); }; /** * 获取当前连接的状态。 */ RongIMClient.prototype.getCurrentConnectionStatus = function () { return RongIMClient._dataAccessProvider.getCurrentConnectionStatus(); }; /** * 获取当前使用的连接通道。 */ RongIMClient.prototype.getConnectionChannel = function () { if (RongIMLib.Transportations._TransportType == RongIMLib.Socket.XHR_POLLING) { return RongIMLib.ConnectionChannel.XHR_POLLING; } else if (RongIMLib.Transportations._TransportType == RongIMLib.Socket.WEBSOCKET) { return RongIMLib.ConnectionChannel.WEBSOCKET; } }; /** * 获取当前使用的本地储存提供者。 TODO */ RongIMClient.prototype.getStorageProvider = function () { if (RongIMClient._memoryStore.providerType == 1) { return "ServerDataProvider"; } else { return "OtherDataProvider"; } }; /** * 过滤聊天室消息(拉取最近聊天消息) * @param {string[]} msgFilterNames */ RongIMClient.prototype.setFilterMessages = function (msgFilterNames) { if (Object.prototype.toString.call(msgFilterNames) == "[object Array]") { RongIMClient._memoryStore.filterMessages = msgFilterNames; } }; RongIMClient.prototype.getAgoraDynamicKey = function (engineType, channelName, callback) { RongIMClient._dataAccessProvider.getAgoraDynamicKey(engineType, channelName, callback); }; /** * 获取当前连接用户的 UserId。 */ RongIMClient.prototype.getCurrentUserId = function () { return RongIMLib.Bridge._client.userId; }; /** * 获取服务器时间与本地时间的差值,单位为毫秒。 * 计算公式:差值 = 本地时间毫秒数 - 服务器时间毫秒数 * @param callback 获取的回调,返回差值。 */ RongIMClient.prototype.getDeltaTime = function () { return RongIMClient._dataAccessProvider.getDelaTime(); }; // #region Message RongIMClient.prototype.getMessage = function (messageId, callback) { RongIMClient._dataAccessProvider.getMessage(messageId, RongIMClient.logCallback(callback, "getMessage")); }; RongIMClient.prototype.deleteLocalMessages = function (conversationType, targetId, messageIds, callback) { RongIMClient._dataAccessProvider.removeLocalMessage(conversationType, targetId, messageIds, RongIMClient.logCallback(callback, "deleteLocalMessages")); }; RongIMClient.prototype.updateMessage = function (message, callback) { RongIMClient._dataAccessProvider.updateMessage(message, RongIMClient.logCallback(callback, "updateMessage")); }; RongIMClient.prototype.clearData = function () { return RongIMClient._dataAccessProvider.clearData(); }; RongIMClient.prototype.clearMessages = function (conversationType, targetId, callback) { RongIMClient._dataAccessProvider.clearMessages(conversationType, targetId, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "clearMessages" }); callback.onError(errorCode); }); } }); }; /**TODO 清楚本地存储的未读消息,目前清空内存中的未读消息 * [clearMessagesUnreadStatus 清空指定会话未读消息] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [用户id] * @param {ResultCallback} callback [返回值,参数回调] */ RongIMClient.prototype.clearMessagesUnreadStatus = function (conversationType, targetId, callback) { RongIMClient._dataAccessProvider.updateMessages(conversationType, targetId, "readStatus", null, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "clearMessagesUnreadStatus" }); callback.onError(errorCode); }); } }); }; RongIMClient.prototype.deleteRemoteMessages = function (conversationType, targetId, delMsgs, callback) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "array", "object"], "deleteRemoteMessages", false, arguments); if (delMsgs.length == 0) { var errorCode = RongIMLib.ErrorCode.DELETE_MESSAGE_ID_IS_NULL; RongIMClient.logger({ code: errorCode, funcName: "deleteRemoteMessages" }); callback.onError(RongIMLib.ErrorCode.DELETE_MESSAGE_ID_IS_NULL); return; } else if (delMsgs.length > 100) { delMsgs.length = 100; } // 后续增加,去掉注释即可 callback.onSuccess(true); // var modules = new RongIMClient.Protobuf.DeleteMsgInput(); // modules.setType(conversationType); // modules.setConversationId(targetId); // modules.setMsgs(delMsgs); // RongIMClient.bridge.queryMsg(33, MessageUtil.ArrayForm(modules.toArrayBuffer()), Bridge._client.userId, { // onSuccess: function(info: any) { // callback.onSuccess(true); // }, // onError: function(err: any) { // callback.onError(err); // } // }, "DeleteMsgOutput"); }; /** * [deleteMessages 删除消息记录。] * @param {ConversationType} conversationType [description] * @param {string} targetId [description] * @param {number[]} messageIds [description] * @param {ResultCallback} callback [description] */ RongIMClient.prototype.deleteMessages = function (conversationType, targetId, delMsgs, callback) { RongIMClient._dataAccessProvider.removeMessage(conversationType, targetId, delMsgs, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "deleteMessages" }); callback.onError(errorCode); }); } }); }; RongIMClient.prototype.sendLocalMessage = function (message, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object"], "sendLocalMessage", false, arguments); RongIMClient._dataAccessProvider.updateMessage(message); this.sendMessage(message.conversationType, message.targetId, message.content, RongIMClient.logSendCallback(callback, "sendLocalMessage")); }; /** * [sendMessage 发送消息。] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [目标Id] * @param {MessageContent} messageContent [消息类型] * @param {SendMessageCallback} sendCallback [] * @param {ResultCallback} resultCallback [返回值,函数回调] * @param {string} pushContent [] * @param {string} pushData [] */ RongIMClient.prototype.sendMessage = function (conversationType, targetId, messageContent, sendCallback, mentiondMsg, pushText, appData, methodType, params) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object", "object", "undefined|object|null|global|boolean", "undefined|object|null|global|string", "undefined|object|null|global|string", "undefined|object|null|global|number", "undefined|object|null|global"], "sendMessage", false, arguments); RongIMClient._dataAccessProvider.sendMessage(conversationType, targetId, messageContent, RongIMClient.logSendCallback(sendCallback, "sendMessage"), mentiondMsg, pushText, appData, methodType, params); }; RongIMClient.prototype.sendReceiptResponse = function (conversationType, targetId, sendCallback) { RongIMClient._dataAccessProvider.sendReceiptResponse(conversationType, targetId, RongIMClient.logSendCallback(sendCallback, "sendReceiptResponse")); }; RongIMClient.prototype.sendTypingStatusMessage = function (conversationType, targetId, messageName, sendCallback) { RongIMClient._dataAccessProvider.sendTypingStatusMessage(conversationType, targetId, messageName, RongIMClient.logSendCallback(sendCallback, "sendTypingStatusMessage")); }; /** * [sendStatusMessage description] * @param {MessageContent} messageContent [description] * @param {SendMessageCallback} sendCallback [description] * @param {ResultCallback} resultCallback [description] */ RongIMClient.prototype.sendStatusMessage = function (messageContent, sendCallback, resultCallback) { throw new Error("Not implemented yet"); }; /** * [sendTextMessage 发送TextMessage快捷方式] * @param {string} content [消息内容] * @param {ResultCallback} resultCallback [返回值,参数回调] */ RongIMClient.prototype.sendTextMessage = function (conversationType, targetId, content, sendMessageCallback) { RongIMClient._dataAccessProvider.sendTextMessage(conversationType, targetId, content, RongIMClient.logSendCallback(sendMessageCallback, "sendTextMessage")); }; RongIMClient.prototype.sendRecallMessage = function (content, sendMessageCallback) { var callback = RongIMClient.logSendCallback(sendMessageCallback, "sendRecallMessage"); var senderUserId = content.senderUserId; var userId = RongIMLib.Bridge._client.userId; var isOther = (senderUserId != userId); if (isOther) { var callback = RongIMClient.logSendCallback(sendMessageCallback, "sendRecallMessage"); callback.onError(RongIMLib.ErrorCode.RECALL_MESSAGE, content); return; } RongIMClient._dataAccessProvider.sendRecallMessage(content, callback); }; /** * [insertMessage 向本地插入一条消息,不发送到服务器。] * @param {ConversationType} conversationType [description] * @param {string} targetId [description] * @param {string} senderUserId [description] * @param {MessageContent} content [description] * @param {ResultCallback} callback [description] */ RongIMClient.prototype.insertMessage = function (conversationType, targetId, content, callback) { RongIMClient._dataAccessProvider.addMessage(conversationType, targetId, content, RongIMClient.logCallback(callback, "insertMessage")); }; RongIMClient.prototype.setMessageContent = function (messageId, content, objectName) { RongIMClient._dataAccessProvider.setMessageContent(messageId, content, objectName); }; ; /** * [getHistoryMessages 拉取历史消息记录。] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [用户Id] * @param {number|null} pullMessageTime [拉取历史消息起始位置(格式为毫秒数),可以为null] * @param {number} count [历史消息数量] * @param {ResultCallback} callback [回调函数] * @param {string} objectName [objectName] */ RongIMClient.prototype.getHistoryMessages = function (conversationType, targetId, timestamp, count, callback, objectname, order) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "number|null|global|object", "number", "object", "undefined|object|null|global|string", "number|null|global|object"], "getHistoryMessages", false, arguments); if (count > 20) { throw new Error("HistroyMessage count must be less than or equal to 20!"); } if (conversationType.valueOf() < 0) { throw new Error("ConversationType must be greater than -1"); } RongIMClient._dataAccessProvider.getHistoryMessages(conversationType, targetId, timestamp, count, RongIMClient.logCallback(callback, "getHistoryMessages"), objectname, order); }; /** * [getRemoteHistoryMessages 拉取某个时间戳之前的消息] * @param {ConversationType} conversationType [description] * @param {string} targetId [description] * @param {Date} dateTime [description] * @param {number} count [description] * @param {ResultCallback} callback [description] */ RongIMClient.prototype.getRemoteHistoryMessages = function (conversationType, targetId, timestamp, count, callback, config) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "number|null|global|object", "number", "object", "undefined|null|global|object"], "getRemoteHistoryMessages", false, arguments); var funcName = "getRemoteHistoryMessages"; var log = { errorCode: RongIMLib.ErrorCode.RC_CONN_PROTO_VERSION_ERROR, funcName: "getRemoteHistoryMessages" }; if (count > 20) { RongIMClient.logger(log); callback.onError(RongIMLib.ErrorCode.RC_CONN_PROTO_VERSION_ERROR); return; } if (conversationType.valueOf() < 0) { RongIMClient.logger(log); callback.onError(RongIMLib.ErrorCode.RC_CONN_PROTO_VERSION_ERROR); return; } RongIMClient._dataAccessProvider.getRemoteHistoryMessages(conversationType, targetId, timestamp, count, RongIMClient.logCallback(callback, funcName), config); }; RongIMClient.prototype.clearHistoryMessages = function (params, callback) { RongIMClient._dataAccessProvider.clearHistoryMessages(params, callback); }; RongIMClient.prototype.clearRemoteHistoryMessages = function (params, callback) { RongIMClient._dataAccessProvider.clearRemoteHistoryMessages(params, RongIMClient.logCallback(callback, "clearRemoteHistoryMessages")); }; /** * [hasRemoteUnreadMessages 是否有未接收的消息,jsonp方法] * @param {string} appkey [appkey] * @param {string} token [token] * @param {ConnectCallback} callback [返回值,参数回调] */ RongIMClient.prototype.hasRemoteUnreadMessages = function (token, callback) { RongIMClient._dataAccessProvider.hasRemoteUnreadMessages(token, RongIMClient.logCallback(callback, "hasRemoteUnreadMessages")); }; RongIMClient.prototype.getTotalUnreadCount = function (callback, conversationTypes) { RongIMClient._dataAccessProvider.getTotalUnreadCount({ onSuccess: function (count) { setTimeout(function () { callback.onSuccess(count); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "getTotalUnreadCount" }); callback.onError(errorCode); }); } }, conversationTypes); }; /** * [getConversationUnreadCount 指定多种会话类型获取未读消息数] * @param {ResultCallback} callback [返回值,参数回调。] * @param {ConversationType[]} ...conversationTypes [会话类型。] */ RongIMClient.prototype.getConversationUnreadCount = function (conversationTypes, callback) { RongIMClient._dataAccessProvider.getConversationUnreadCount(conversationTypes, { onSuccess: function (count) { setTimeout(function () { callback.onSuccess(count); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "getConversationUnreadCount" }); callback.onError(errorCode); }); } }); }; /** * [getUnreadCount 指定用户、会话类型的未读消息总数。] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [用户Id] */ RongIMClient.prototype.getUnreadCount = function (conversationType, targetId, callback) { RongIMClient._dataAccessProvider.getUnreadCount(conversationType, targetId, { onSuccess: function (count) { setTimeout(function () { callback.onSuccess(count); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "getUnreadCount" }); callback.onError(errorCode); }); } }); }; RongIMClient.prototype.setUnreadCount = function (conversationType, targetId, count) { RongIMLib.CheckParam.getInstance().check(["number", "string", "number"], "setUnreadCount", false, arguments); RongIMClient._dataAccessProvider.setUnreadCount(conversationType, targetId, count); }; RongIMClient.prototype.clearUnreadCountByTimestamp = function (conversationType, targetId, timestamp, callback) { RongIMClient._dataAccessProvider.clearUnreadCountByTimestamp(conversationType, targetId, timestamp, RongIMClient.logCallback(callback, "clearUnreadCountByTimestamp")); }; /** * 清楚会话未读消息数 * @param {ConversationType} conversationType 会话类型 * @param {string} targetId 目标Id * @param {ResultCallback} callback 返回值,函数回调 */ RongIMClient.prototype.clearUnreadCount = function (conversationType, targetId, callback) { RongIMClient._dataAccessProvider.clearUnreadCount(conversationType, targetId, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "clearUnreadCount" }); callback.onError(errorCode); }); } }); }; RongIMClient.prototype.clearTotalUnreadCount = function (callback) { RongIMClient._dataAccessProvider.clearTotalUnreadCount({ onSuccess: function (bool) { callback.onSuccess(bool); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: 'clearTotalUnreadCount' }); callback.onError(errorCode); }); } }); }; RongIMClient.prototype.clearLocalStorage = function (callback) { RongIMClient._storageProvider.clearItem(); callback(); }; RongIMClient.prototype.setMessageExtra = function (messageId, value, callback) { RongIMClient._dataAccessProvider.setMessageExtra(messageId, value, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "setMessageExtra" }); callback.onError(errorCode); }); } }); }; RongIMClient.prototype.setMessageReceivedStatus = function (messageUId, receivedStatus, callback) { RongIMClient._dataAccessProvider.setMessageReceivedStatus(messageUId, receivedStatus, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "setMessageReceivedStatus" }); callback.onError(errorCode); }); } }); }; RongIMClient.prototype.setMessageStatus = function (conersationType, targetId, timestamp, status, callback) { RongIMClient._dataAccessProvider.setMessageStatus(conersationType, targetId, timestamp, status, RongIMClient.logCallback(callback, "setMessageStatus")); }; RongIMClient.prototype.setMessageSentStatus = function (messageId, sentStatus, callback) { RongIMClient._dataAccessProvider.setMessageSentStatus(messageId, sentStatus, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "setMessageSentStatus" }); callback.onError(errorCode); }); } }); }; // #endregion Message // #region TextMessage Draft /** * clearTextMessageDraft 清除指定会话和消息类型的草稿。 * @param {ConversationType} conversationType 会话类型 * @param {string} targetId 目标Id */ RongIMClient.prototype.clearTextMessageDraft = function (conversationType, targetId) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "clearTextMessageDraft", false, arguments); var key = "darf_" + conversationType + "_" + targetId; delete RongIMClient._memoryStore[key]; return true; }; /** * [getTextMessageDraft 获取指定消息和会话的草稿。] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [目标Id] */ RongIMClient.prototype.getTextMessageDraft = function (conversationType, targetId) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "getTextMessageDraft", false, arguments); if (targetId == "" || conversationType < 0) { throw new Error("params error : " + RongIMLib.ErrorCode.DRAF_GET_ERROR); } var key = "darf_" + conversationType + "_" + targetId; return RongIMClient._memoryStore[key]; }; /** * [saveTextMessageDraft description] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [目标Id] * @param {string} value [草稿值] */ RongIMClient.prototype.saveTextMessageDraft = function (conversationType, targetId, value) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "string", "object"], "saveTextMessageDraft", false, arguments); var key = "darf_" + conversationType + "_" + targetId; RongIMClient._memoryStore[key] = value; return true; }; // #endregion TextMessage Draft // #region Conversation RongIMClient.prototype.searchConversationByContent = function (keyword, callback, conversationTypes) { RongIMClient._dataAccessProvider.searchConversationByContent(keyword, RongIMClient.logCallback(callback, "searchConversationByContent"), conversationTypes); }; RongIMClient.prototype.searchMessageByContent = function (conversationType, targetId, keyword, timestamp, count, total, callback) { RongIMClient._dataAccessProvider.searchMessageByContent(conversationType, targetId, keyword, timestamp, count, total, RongIMClient.logCallback(callback, "searchMessageByContent")); }; RongIMClient.prototype.clearCache = function () { RongIMClient._dataAccessProvider.clearCache(); }; RongIMClient.prototype.clearConversations = function (callback) { var conversationTypes = []; for (var _i = 1; _i < arguments.length; _i++) { conversationTypes[_i - 1] = arguments[_i]; } if (conversationTypes.length == 0) { conversationTypes = [RongIMLib.ConversationType.CHATROOM, RongIMLib.ConversationType.CUSTOMER_SERVICE, RongIMLib.ConversationType.DISCUSSION, RongIMLib.ConversationType.GROUP, RongIMLib.ConversationType.PRIVATE, RongIMLib.ConversationType.SYSTEM, RongIMLib.ConversationType.PUBLIC_SERVICE, RongIMLib.ConversationType.APP_PUBLIC_SERVICE]; } RongIMClient._dataAccessProvider.clearConversations(conversationTypes, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "clearConversations" }); callback.onError(errorCode); }); } }); }; /** * [getConversation 获取指定会话,此方法需在getConversationList之后执行] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [目标Id] * @param {ResultCallback} callback [返回值,函数回调] */ RongIMClient.prototype.getConversation = function (conversationType, targetId, callback) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "getConversation", false, arguments); RongIMClient._dataAccessProvider.getConversation(conversationType, targetId, { onSuccess: function (conver) { setTimeout(function () { callback.onSuccess(conver); }); }, onError: function (error) { setTimeout(function () { RongIMClient.logger({ code: error, funcName: "getConversation" }); callback.onError(error); }); } }); }; /** * [pottingConversation 组装会话列表] * @param {any} tempConver [临时会话] * conver_conversationType_targetId_no. * msg_conversationType_targetId_no. */ RongIMClient.prototype.pottingConversation = function (tempConver) { var self = this, isUseReplace = false; RongIMClient._dataAccessProvider.getConversation(tempConver.type, tempConver.userId, { onSuccess: function (conver) { if (!conver) { conver = new RongIMLib.Conversation(); } else { isUseReplace = true; } conver.conversationType = tempConver.type; conver.targetId = tempConver.userId; conver.latestMessage = RongIMLib.MessageUtil.messageParser(tempConver.msg); conver.latestMessageId = conver.latestMessage.messageId; conver.objectName = conver.latestMessage.objectName; conver.receivedStatus = conver.latestMessage.receivedStatus; conver.receivedTime = conver.latestMessage.receiveTime; conver.sentStatus = conver.latestMessage.sentStatus; conver.sentTime = conver.latestMessage.sentTime; var mentioneds = RongIMClient._storageProvider.getItem("mentioneds_" + RongIMLib.Bridge._client.userId + '_' + conver.conversationType + '_' + conver.targetId); if (mentioneds) { var info = JSON.parse(mentioneds); conver.mentionedMsg = info[tempConver.type + "_" + tempConver.userId]; } if (!isUseReplace) { if (RongIMLib.RongUtil.supportLocalStorage()) { var count = RongIMClient._storageProvider.getItem("cu" + RongIMLib.Bridge._client.userId + tempConver.type + tempConver.userId); conver.unreadMessageCount = Number(count); } else { conver.unreadMessageCount = 0; } } if (conver.conversationType == RongIMLib.ConversationType.DISCUSSION) { self.getDiscussion(tempConver.userId, { onSuccess: function (info) { conver.conversationTitle = info.name; }, onError: function (error) { } }); } RongIMClient._dataAccessProvider.addConversation(conver, { onSuccess: function (data) { } }); }, onError: function (error) { } }); }; RongIMClient.prototype.addConversation = function (conversation, callback) { RongIMClient._dataAccessProvider.addConversation(conversation, callback); }; RongIMClient.prototype.sortConversationList = function (conversationList) { var convers = []; for (var i = 0, len = conversationList.length; i < len; i++) { if (!conversationList[i]) { continue; } if (conversationList[i].isTop) { convers.push(conversationList[i]); conversationList.splice(i, 1); continue; } for (var j = 0; j < len - i - 1; j++) { if (conversationList[j].sentTime < conversationList[j + 1].sentTime) { var swap = conversationList[j]; conversationList[j] = conversationList[j + 1]; conversationList[j + 1] = swap; } } } return RongIMClient._memoryStore.conversationList = convers.concat(conversationList); }; RongIMClient.prototype.getConversationList = function (callback, conversationTypes, count, isGetHiddenConvers) { RongIMLib.CheckParam.getInstance().check(["object", "null|undefined|array|object|global", "number|undefined|null|object|global", "boolean|undefined|null|object|global"], "getConversationList", false, arguments); var me = this; RongIMClient._dataAccessProvider.getConversationList({ onSuccess: function (data) { if (conversationTypes || RongIMClient._dataAccessProvider) { setTimeout(function () { callback.onSuccess(data); }); } else { setTimeout(function () { callback.onSuccess(RongIMClient._memoryStore.conversationList); }); } }, onError: function (error) { setTimeout(function () { RongIMClient.logger({ code: error, funcName: "getConversationList" }); callback.onError(error); }); } }, conversationTypes, count, isGetHiddenConvers); }; RongIMClient.prototype.getRemoteConversationList = function (callback, conversationTypes, count, isGetHiddenConvers) { RongIMLib.CheckParam.getInstance().check(["object", "null|array|object|global", "number|undefined|null|object|global", "boolean|undefined|null|object|global"], "getRemoteConversationList", false, arguments); RongIMClient._dataAccessProvider.getRemoteConversationList(RongIMClient.logCallback(callback, "getRemoteConversationList"), conversationTypes, count, isGetHiddenConvers); }; RongIMClient.prototype.updateConversation = function (conversation) { return RongIMClient._dataAccessProvider.updateConversation(conversation); }; /** * [createConversation 创建会话。] * @param {number} conversationType [会话类型] * @param {string} targetId [目标Id] * @param {string} converTitle [会话标题] * @param {boolean} islocal [是否同步到服务器,ture:同步,false:不同步] */ RongIMClient.prototype.createConversation = function (conversationType, targetId, converTitle) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "string"], "createConversation", false, arguments); var conver = new RongIMLib.Conversation(); // var unreadContent: string = RongIMClient._storageProvider.getItem("cu" + Bridge._client.userId + conversationType + targetId); // var unreadCount = Number(unreadContent) || 0; conver.targetId = targetId; conver.conversationType = conversationType; conver.conversationTitle = converTitle; conver.latestMessage = {}; conver.unreadMessageCount = 0; return conver; }; //TODO 删除本地和服务器、删除本地和服务器分开 RongIMClient.prototype.removeConversation = function (conversationType, targetId, callback) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "removeConversation", false, arguments); RongIMClient._dataAccessProvider.removeConversation(conversationType, targetId, RongIMClient.logCallback(callback, "removeConversation")); }; RongIMClient.prototype.setConversationHidden = function (conversationType, targetId, isHidden) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "boolean"], "setConversationHidden", false, arguments); RongIMClient._dataAccessProvider.setConversationHidden(conversationType, targetId, isHidden); }; RongIMClient.prototype.setConversationToTop = function (conversationType, targetId, isTop, callback) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "boolean", "object"], "setConversationToTop", false, arguments); RongIMClient._dataAccessProvider.setConversationToTop(conversationType, targetId, isTop, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "setConversationToTop" }); callback.onError(errorCode); }); } }); }; // #endregion Conversation // #region Notifications /** * [getConversationNotificationStatus 获取指定用户和会话类型免提醒。] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [目标Id] * @param {ResultCallback} callback [返回值,函数回调] */ RongIMClient.prototype.getConversationNotificationStatus = function (conversationType, targetId, callback) { var params = { conversationType: conversationType, targetId: targetId }; RongIMClient._dataAccessProvider.getConversationNotificationStatus(params, RongIMClient.logCallback(callback, "getConversationNotificationStatus")); }; /** * [setConversationNotificationStatus 设置指定用户和会话类型免提醒。] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [目标Id] * @param {ResultCallback} callback [返回值,函数回调] */ RongIMClient.prototype.setConversationNotificationStatus = function (conversationType, targetId, notificationStatus, callback) { var params = { conversationType: conversationType, targetId: targetId, status: status }; RongIMClient._dataAccessProvider.setConversationNotificationStatus(params, RongIMClient.logCallback(callback, "setConversationNotificationStatus")); }; /** * [getNotificationQuietHours 获取免提醒消息时间。] * @param {GetNotificationQuietHoursCallback} callback [返回值,函数回调] */ RongIMClient.prototype.getNotificationQuietHours = function (callback) { throw new Error("Not implemented yet"); }; /** * [removeNotificationQuietHours 移除免提醒消息时间。] * @param {GetNotificationQuietHoursCallback} callback [返回值,函数回调] */ RongIMClient.prototype.removeNotificationQuietHours = function (callback) { throw new Error("Not implemented yet"); }; /** * [setNotificationQuietHours 设置免提醒消息时间。] * @param {GetNotificationQuietHoursCallback} callback [返回值,函数回调] */ RongIMClient.prototype.setNotificationQuietHours = function (startTime, spanMinutes, callback) { throw new Error("Not implemented yet"); }; // #endregion Notifications // #region Discussion /** * [addMemberToDiscussion 加入讨论组] * @param {string} discussionId [讨论组Id] * @param {string[]} userIdList [讨论中成员] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.addMemberToDiscussion = function (discussionId, userIdList, callback) { RongIMLib.CheckParam.getInstance().check(["string", "array", "object"], "addMemberToDiscussion", false, arguments); RongIMClient._dataAccessProvider.addMemberToDiscussion(discussionId, userIdList, RongIMClient.logCallback(callback, "addMemberToDiscussion")); }; /** * [createDiscussion 创建讨论组] * @param {string} name [讨论组名称] * @param {string[]} userIdList [讨论组成员] * @param {CreateDiscussionCallback} callback [返回值,函数回调] */ RongIMClient.prototype.createDiscussion = function (name, userIdList, callback) { RongIMLib.CheckParam.getInstance().check(["string", "array", "object"], "createDiscussion", false, arguments); RongIMClient._dataAccessProvider.createDiscussion(name, userIdList, callback); }; /** * [getDiscussion 获取讨论组信息] * @param {string} discussionId [讨论组Id] * @param {ResultCallback} callback [返回值,函数回调] */ RongIMClient.prototype.getDiscussion = function (discussionId, callback) { RongIMLib.CheckParam.getInstance().check(["string", "object"], "getDiscussion", false, arguments); RongIMClient._dataAccessProvider.getDiscussion(discussionId, RongIMClient.logCallback(callback, "getDiscussion")); }; /** * [quitDiscussion 退出讨论组] * @param {string} discussionId [讨论组Id] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.quitDiscussion = function (discussionId, callback) { RongIMLib.CheckParam.getInstance().check(["string", "object"], "quitDiscussion", false, arguments); RongIMClient._dataAccessProvider.quitDiscussion(discussionId, RongIMClient.logCallback(callback, "quitDiscussion")); }; /** * [removeMemberFromDiscussion 将指定成员移除讨论租] * @param {string} discussionId [讨论组Id] * @param {string} userId [被移除的用户Id] * @param {OperationCallback} callback [返回值,参数回调] */ RongIMClient.prototype.removeMemberFromDiscussion = function (discussionId, userId, callback) { RongIMLib.CheckParam.getInstance().check(["string", "string", "object"], "removeMemberFromDiscussion", false, arguments); RongIMClient._dataAccessProvider.removeMemberFromDiscussion(discussionId, userId, RongIMClient.logCallback(callback, "removeMemberFromDiscussion")); }; /** * [setDiscussionInviteStatus 设置讨论组邀请状态] * @param {string} discussionId [讨论组Id] * @param {DiscussionInviteStatus} status [邀请状态] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.setDiscussionInviteStatus = function (discussionId, status, callback) { RongIMLib.CheckParam.getInstance().check(["string", "number", "object"], "setDiscussionInviteStatus", false, arguments); RongIMClient._dataAccessProvider.setDiscussionInviteStatus(discussionId, status, RongIMClient.logCallback(callback, "setDiscussionInviteStatus")); }; /** * [setDiscussionName 设置讨论组名称] * @param {string} discussionId [讨论组Id] * @param {string} name [讨论组名称] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.setDiscussionName = function (discussionId, name, callback) { RongIMLib.CheckParam.getInstance().check(["string", "string", "object"], "setDiscussionName", false, arguments); RongIMClient._dataAccessProvider.setDiscussionName(discussionId, name, RongIMClient.logCallback(callback, "setDiscussionName")); }; // #endregion Discussion // #region ChatRoom /** * [加入聊天室。] * @param {string} chatroomId [聊天室Id] * @param {number} messageCount [拉取消息数量,-1为不拉去消息] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.joinChatRoom = function (chatroomId, messageCount, callback) { RongIMLib.CheckParam.getInstance().check(["string|number", "number", "object"], "joinChatRoom", false, arguments); if (chatroomId == "") { setTimeout(function () { var errorCode = RongIMLib.ErrorCode.CHATROOM_ID_ISNULL; RongIMClient.logger({ code: errorCode, funcName: "joinChatRoom" }); callback.onError(RongIMLib.ErrorCode.CHATROOM_ID_ISNULL); }); return; } RongIMClient._dataAccessProvider.joinChatRoom(chatroomId, messageCount, RongIMClient.logCallback(callback, "joinChatRoom")); }; RongIMClient.prototype.setDeviceInfo = function (device) { RongIMClient._dataAccessProvider.setDeviceInfo(device); }; RongIMClient.prototype.setChatroomHisMessageTimestamp = function (chatRoomId, timestamp) { RongIMLib.CheckParam.getInstance().check(["string|number", "number"], "setChatroomHisMessageTimestamp", false, arguments); RongIMClient._dataAccessProvider.setChatroomHisMessageTimestamp(chatRoomId, timestamp); }; RongIMClient.prototype.getChatRoomHistoryMessages = function (chatRoomId, count, order, callback) { RongIMLib.CheckParam.getInstance().check(["string|number", "number", "number", "object"], "getChatRoomHistoryMessages", false, arguments); RongIMClient._dataAccessProvider.getChatRoomHistoryMessages(chatRoomId, count, order, RongIMClient.logCallback(callback, "getChatRoomHistoryMessages")); }; RongIMClient.prototype.getChatRoomInfo = function (chatRoomId, count, order, callback) { RongIMLib.CheckParam.getInstance().check(["string|number", "number", "number", "object"], "getChatRoomInfo", false, arguments); RongIMClient._dataAccessProvider.getChatRoomInfo(chatRoomId, count, order, RongIMClient.logCallback(callback, "getChatRoomInfo")); }; /** * [退出聊天室] * @param {string} chatroomId [聊天室Id] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.quitChatRoom = function (chatroomId, callback) { RongIMLib.CheckParam.getInstance().check(["string|number", "object"], "quitChatRoom", false, arguments); RongIMClient._dataAccessProvider.quitChatRoom(chatroomId, RongIMClient.logCallback(callback, "quitChatRoom")); }; // #endregion ChatRoom // #region Public Service RongIMClient.prototype.getRemotePublicServiceList = function (callback, pullMessageTime) { RongIMClient._dataAccessProvider.getRemotePublicServiceList(RongIMClient.logCallback(callback, "getRemotePublicServiceList"), pullMessageTime); }; /** * [getPublicServiceList ]获取本地的公共账号列表 * @param {ResultCallback} callback [返回值,参数回调] */ RongIMClient.prototype.getPublicServiceList = function (callback) { if (RongIMClient._memoryStore.depend.openMp) { RongIMLib.CheckParam.getInstance().check(["object"], "getPublicServiceList", false, arguments); this.getRemotePublicServiceList(RongIMClient.logCallback(callback, "getPublicServiceList")); } }; /** * [getPublicServiceProfile ] 获取某公共服务信息。 * @param {PublicServiceType} publicServiceType [公众服务类型。] * @param {string} publicServiceId [公共服务 Id。] * @param {ResultCallback} callback [公共账号信息回调。] */ RongIMClient.prototype.getPublicServiceProfile = function (publicServiceType, publicServiceId, callback) { if (RongIMClient._memoryStore.depend.openMp) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "getPublicServiceProfile", false, arguments); RongIMClient._dataAccessProvider.getPublicServiceProfile(publicServiceType, publicServiceId, RongIMClient.logCallback(callback, "getPublicServiceProfile")); } }; /** * [pottingPublicSearchType ] 公众好查询类型 * @param {number} bussinessType [ 0-all 1-mp 2-mc] * @param {number} searchType [0-exact 1-fuzzy] */ RongIMClient.prototype.pottingPublicSearchType = function (bussinessType, searchType) { if (RongIMClient._memoryStore.depend.openMp) { var bits = 0; if (bussinessType == 0) { bits |= 3; if (searchType == 0) { bits |= 12; } else { bits |= 48; } } else if (bussinessType == 1) { bits |= 1; if (searchType == 0) { bits |= 8; } else { bits |= 32; } } else { bits |= 2; if (bussinessType == 0) { bits |= 4; } else { bits |= 16; } } return bits; } }; /** * [searchPublicService ]按公众服务类型搜索公众服务。 * @param {SearchType} searchType [搜索类型枚举。] * @param {string} keywords [搜索关键字。] * @param {ResultCallback} callback [搜索结果回调。] */ RongIMClient.prototype.searchPublicService = function (searchType, keywords, callback) { if (RongIMClient._memoryStore.depend.openMp) { RongIMLib.CheckParam.getInstance().check(["number", "string", "object"], "searchPublicService", false, arguments); var modules = new RongIMClient.Protobuf.SearchMpInput(); modules.setType(this.pottingPublicSearchType(0, searchType)); modules.setId(keywords); RongIMClient.bridge.queryMsg(29, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, RongIMClient.logCallback(callback, "searchPublicService"), "SearchMpOutput"); } }; /** * [searchPublicServiceByType ]按公众服务类型搜索公众服务。 * @param {PublicServiceType} publicServiceType [公众服务类型。] * @param {SearchType} searchType [搜索类型枚举。] * @param {string} keywords [搜索关键字。] * @param {ResultCallback} callback [搜索结果回调。] */ RongIMClient.prototype.searchPublicServiceByType = function (publicServiceType, searchType, keywords, callback) { if (RongIMClient._memoryStore.depend.openMp) { RongIMLib.CheckParam.getInstance().check(["number", "number", "string", "object"], "searchPublicServiceByType", false, arguments); var type = publicServiceType == RongIMLib.ConversationType.APP_PUBLIC_SERVICE ? 2 : 1; var modules = new RongIMClient.Protobuf.SearchMpInput(); modules.setType(this.pottingPublicSearchType(type, searchType)); modules.setId(keywords); RongIMClient.bridge.queryMsg(29, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, RongIMClient.logCallback(callback, "searchPublicServiceByType"), "SearchMpOutput"); } }; /** * [subscribePublicService ] 订阅公众号。 * @param {PublicServiceType} publicServiceType [公众服务类型。] * @param {string} publicServiceId [公共服务 Id。] * @param {OperationCallback} callback [订阅公众号回调。] */ RongIMClient.prototype.subscribePublicService = function (publicServiceType, publicServiceId, callback) { if (RongIMClient._memoryStore.depend.openMp) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "subscribePublicService", false, arguments); var modules = new RongIMClient.Protobuf.MPFollowInput(), me = this, follow = publicServiceType == RongIMLib.ConversationType.APP_PUBLIC_SERVICE ? "mcFollow" : "mpFollow"; modules.setId(publicServiceId); RongIMClient.bridge.queryMsg(follow, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function () { me.getRemotePublicServiceList({ onSuccess: function () { }, onError: function () { } }); callback.onSuccess(); }, onError: function (code) { var errorCode = code; RongIMClient.logger({ code: errorCode, funcName: "subscribePublicService" }); callback.onError(code); } }, "MPFollowOutput"); } }; /** * [unsubscribePublicService ] 取消订阅公众号。 * @param {PublicServiceType} publicServiceType [公众服务类型。] * @param {string} publicServiceId [公共服务 Id。] * @param {OperationCallback} callback [取消订阅公众号回调。] */ RongIMClient.prototype.unsubscribePublicService = function (publicServiceType, publicServiceId, callback) { if (RongIMClient._memoryStore.depend.openMp) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "unsubscribePublicService", false, arguments); var modules = new RongIMClient.Protobuf.MPFollowInput(), me = this, follow = publicServiceType == RongIMLib.ConversationType.APP_PUBLIC_SERVICE ? "mcUnFollow" : "mpUnFollow"; modules.setId(publicServiceId); RongIMClient.bridge.queryMsg(follow, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function () { RongIMClient._memoryStore.publicServiceMap.remove(publicServiceType, publicServiceId); callback.onSuccess(); }, onError: function (code) { var errorCode = code; RongIMClient.logger({ code: errorCode, funcName: "unsubscribePublicService" }); callback.onError(code); } }, "MPFollowOutput"); } }; // #endregion Public Service // #region Blacklist /** * [加入黑名单] * @param {string} userId [将被加入黑名单的用户Id] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.addToBlacklist = function (userId, callback) { RongIMLib.CheckParam.getInstance().check(["string|number", "object"], "addToBlacklist", false, arguments); RongIMClient._dataAccessProvider.addToBlacklist(userId, RongIMClient.logCallback(callback, "addToBlacklist")); }; /** * [获取黑名单列表] * @param {GetBlacklistCallback} callback [返回值,函数回调] */ RongIMClient.prototype.getBlacklist = function (callback) { RongIMLib.CheckParam.getInstance().check(["object"], "getBlacklist", false, arguments); RongIMClient._dataAccessProvider.getBlacklist(callback); }; /** * [得到指定人员再黑名单中的状态] * @param {string} userId [description] * @param {ResultCallback} callback [返回值,函数回调] */ //TODO 如果人员不在黑名单中,获取状态会出现异常 RongIMClient.prototype.getBlacklistStatus = function (userId, callback) { RongIMLib.CheckParam.getInstance().check(["string|number", "object"], "getBlacklistStatus", false, arguments); RongIMClient._dataAccessProvider.getBlacklistStatus(userId, RongIMClient.logCallback(callback, "getBlacklistStatus")); }; /** * [将指定用户移除黑名单] * @param {string} userId [将被移除的用户Id] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.removeFromBlacklist = function (userId, callback) { RongIMLib.CheckParam.getInstance().check(["string|number", "object"], "removeFromBlacklist", false, arguments); RongIMClient._dataAccessProvider.removeFromBlacklist(userId, RongIMClient.logCallback(callback, "removeFromBlacklist")); }; RongIMClient.prototype.getFileToken = function (fileType, callback) { RongIMLib.CheckParam.getInstance().check(["number", "object"], "getQngetFileTokenTkn", false, arguments); RongIMClient._dataAccessProvider.getFileToken(fileType, RongIMClient.logCallback(callback, "getFileToken")); }; RongIMClient.prototype.getFileUrl = function (fileType, fileName, oriName, callback) { RongIMLib.CheckParam.getInstance().check(["number", "string", "string|global|object|null", "object"], "getFileUrl", false, arguments); RongIMClient._dataAccessProvider.getFileUrl(fileType, fileName, oriName, RongIMClient.logCallback(callback, "getFileUrl")); }; ; // #endregion Blacklist // #region Real-time Location Service RongIMClient.prototype.addRealTimeLocationListener = function (conversationType, targetId, listener) { throw new Error("Not implemented yet"); }; RongIMClient.prototype.getRealTimeLocation = function (conversationType, targetId) { throw new Error("Not implemented yet"); }; RongIMClient.prototype.getRealTimeLocationCurrentState = function (conversationType, targetId) { throw new Error("Not implemented yet"); }; RongIMClient.prototype.getRealTimeLocationParticipants = function (conversationType, targetId) { throw new Error("Not implemented yet"); }; RongIMClient.prototype.joinRealTimeLocation = function (conversationType, targetId) { throw new Error("Not implemented yet"); }; RongIMClient.prototype.quitRealTimeLocation = function (conversationType, targetId) { throw new Error("Not implemented yet"); }; RongIMClient.prototype.startRealTimeLocation = function (conversationType, targetId) { throw new Error("Not implemented yet"); }; RongIMClient.prototype.updateRealTimeLocationStatus = function (conversationType, targetId, latitude, longitude) { throw new Error("Not implemented yet"); }; // #endregion Real-time Location Service // # startVoIP RongIMClient.prototype.startCall = function (converType, targetId, userIds, mediaType, extra, callback) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "array", "number", "string", "object"], "startCall", false, arguments); if (RongIMClient._memoryStore.voipStategy) { RongIMClient._voipProvider.startCall(converType, targetId, userIds, mediaType, extra, RongIMClient.logCallback(callback, "startCall")); } else { var errorCode = RongIMLib.ErrorCode.VOIP_NOT_AVALIABLE; RongIMClient.logger({ code: errorCode, funcName: "startCall" }); callback.onError(RongIMLib.ErrorCode.VOIP_NOT_AVALIABLE); } }; RongIMClient.prototype.joinCall = function (mediaType, callback) { RongIMLib.CheckParam.getInstance().check(['number', 'object'], "joinCall", false, arguments); if (RongIMClient._memoryStore.voipStategy) { RongIMClient._voipProvider.joinCall(mediaType, RongIMClient.logCallback(callback, "joinCall")); } else { var errorCode = RongIMLib.ErrorCode.VOIP_NOT_AVALIABLE; RongIMClient.logger({ code: errorCode, funcName: "joinCall" }); callback.onError(RongIMLib.ErrorCode.VOIP_NOT_AVALIABLE); } }; RongIMClient.prototype.hungupCall = function (converType, targetId, reason) { RongIMLib.CheckParam.getInstance().check(["number", "string", "number"], "hungupCall", false, arguments); if (RongIMClient._memoryStore.voipStategy) { RongIMClient._voipProvider.hungupCall(converType, targetId, reason); } }; RongIMClient.prototype.changeMediaType = function (converType, targetId, mediaType, callback) { RongIMLib.CheckParam.getInstance().check(["number", "string", "number", "object"], "changeMediaType", false, arguments); if (RongIMClient._memoryStore.voipStategy) { RongIMClient._voipProvider.changeMediaType(converType, targetId, mediaType, RongIMClient.logCallback(callback, "changeMediaType")); } else { var errorCode = RongIMLib.ErrorCode.VOIP_NOT_AVALIABLE; RongIMClient.logger({ code: errorCode, funcName: "changeMediaType" }); callback.onError(RongIMLib.ErrorCode.VOIP_NOT_AVALIABLE); } }; // # endVoIP RongIMClient.prototype.getUnreadMentionedMessages = function (conversationType, targetId) { return RongIMClient._dataAccessProvider.getUnreadMentionedMessages(conversationType, targetId); }; RongIMClient.prototype.clearListeners = function () { RongIMClient._dataAccessProvider.clearListeners(); }; // UserStatus start RongIMClient.prototype.getUserStatus = function (userId, callback) { RongIMClient._dataAccessProvider.getUserStatus(userId, RongIMClient.logCallback(callback, "getUserStatus")); }; RongIMClient.prototype.setUserStatus = function (status, callback) { RongIMClient._dataAccessProvider.setUserStatus(status, RongIMClient.logCallback(callback, "setUserStatus")); }; RongIMClient.prototype.setUserStatusListener = function (params, callback) { var userIds = params.userIds; var multiple = params.multiple; RongIMClient.userStatusObserver.watch({ key: userIds, func: callback, multiple: multiple }); RongIMClient._dataAccessProvider.setUserStatusListener(params, callback); }; RongIMClient.LogFactory = {}; RongIMClient.MessageType = {}; RongIMClient.RegisterMessage = {}; RongIMClient._memoryStore = { listenerList: [], isPullFinished: false, syncMsgQueue: [] }; RongIMClient.isNotPullMsg = false; RongIMClient.userStatusObserver = null; RongIMClient.sdkver = '2.3.5'; RongIMClient.otherDeviceLoginCount = 0; RongIMClient.serverStore = { index: 0 }; RongIMClient.userStatusListener = null; return RongIMClient; })(); RongIMLib.RongIMClient = RongIMClient; })(RongIMLib || (RongIMLib = {})); //用于连接通道 var RongIMLib; (function (RongIMLib) { (function (Qos) { Qos[Qos["AT_MOST_ONCE"] = 0] = "AT_MOST_ONCE"; Qos[Qos["AT_LEAST_ONCE"] = 1] = "AT_LEAST_ONCE"; Qos[Qos["EXACTLY_ONCE"] = 2] = "EXACTLY_ONCE"; Qos[Qos["DEFAULT"] = 3] = "DEFAULT"; })(RongIMLib.Qos || (RongIMLib.Qos = {})); var Qos = RongIMLib.Qos; (function (Type) { Type[Type["CONNECT"] = 1] = "CONNECT"; Type[Type["CONNACK"] = 2] = "CONNACK"; Type[Type["PUBLISH"] = 3] = "PUBLISH"; Type[Type["PUBACK"] = 4] = "PUBACK"; Type[Type["QUERY"] = 5] = "QUERY"; Type[Type["QUERYACK"] = 6] = "QUERYACK"; Type[Type["QUERYCON"] = 7] = "QUERYCON"; Type[Type["SUBSCRIBE"] = 8] = "SUBSCRIBE"; Type[Type["SUBACK"] = 9] = "SUBACK"; Type[Type["UNSUBSCRIBE"] = 10] = "UNSUBSCRIBE"; Type[Type["UNSUBACK"] = 11] = "UNSUBACK"; Type[Type["PINGREQ"] = 12] = "PINGREQ"; Type[Type["PINGRESP"] = 13] = "PINGRESP"; Type[Type["DISCONNECT"] = 14] = "DISCONNECT"; })(RongIMLib.Type || (RongIMLib.Type = {})); var Type = RongIMLib.Type; var _topic = ["invtDiz", "crDiz", "qnUrl", "userInf", "dizInf", "userInf", "joinGrp", "quitDiz", "exitGrp", "evctDiz", ["", "ppMsgP", "pdMsgP", "pgMsgP", "chatMsg", "pcMsgP", "", "pmcMsgN", "pmpMsgN"], "pdOpen", "rename", "uGcmpr", "qnTkn", "destroyChrm", "createChrm", "exitChrm", "queryChrm", "joinChrm", "pGrps", "addBlack", "rmBlack", "getBlack", "blackStat", "addRelation", "qryRelation", "delRelation", "pullMp", "schMp", "qnTkn", "qnUrl", "qryVoipK", "delMsg", "qryCHMsg", "getUserStatus", "setUserStatus", "subUserStatus", "cleanHisMsg"]; var Channel = (function () { function Channel(cb, self) { this.connectionStatus = -1; var appId = self.appId; var token = encodeURIComponent(self.token); var sdkVer = self.sdkVer; var apiVer = self.apiVer; this.self = self; this.socket = Socket.getInstance().createServer(); var that = this; var storage = RongIMLib.RongIMClient._storageProvider; var servers = storage.getItem('servers'); servers = JSON.parse(servers) || []; var depend = RongIMLib.RongIMClient._memoryStore.depend; var startConnect = function (host) { var tpl = '{host}/websocket?appId={appId}&token={token}&sdkVer={sdkVer}&apiVer={apiVer}'; that.url = RongIMLib.RongUtil.tplEngine(tpl, { host: host, appId: appId, token: token, sdkVer: sdkVer, apiVer: apiVer }); that.socket.connect(that.url, cb); // 临时兼容 Comet 逻辑,Comet 中用到 var userId = storage.getItem('rong_current_user'); RongIMLib.Navigation.Endpoint = { host: host, userId: userId }; }; var connectMap = { ws: function () { // 所有链接计算器,超过 15 秒后认为所有 CMP 地址均不可用 var totalTimer = new RongIMLib.Timer({ timeout: 1 * 1000 * 15 }); var timers = []; var elements = []; var isFinished = false; var clearHandler = function () { for (var i = 0; i < timers.length; i++) { var timer = timers[i]; clearTimeout(timer); } for (var i = 0; i < elements.length; i++) { var el = elements[i]; document.body.removeChild(el); } timers.length = 0; elements.length = 0; }; var request = function (config, callback) { var url = config.url; var time = config.time; if (isFinished) { return; } var timer = setTimeout(function () { var xss = document.createElement("script"); xss.src = url; document.body.appendChild(xss); var onSuccess = function () { if (isFinished) { return; } clearHandler(); isFinished = true; totalTimer.pause(); var url = xss.src; callback(url); }; xss.onload = onSuccess; xss.onerror = onSuccess; elements.push(xss); }, time); timers.push(timer); }; var snifferCallback = function (url) { var reg = /(http|https):\/\/([^\/]+)/i; var host = url.match(reg)[2]; startConnect(host); }; var snifferTpl = '{protocol}{server}/ping?r={random}'; for (var i = 0; i < servers.length; i++) { var server = servers[i]; if (server) { server = RongIMLib.RongUtil.tplEngine(snifferTpl, { protocol: depend.protocol, server: server, random: RongIMLib.RongUtil.getTimestamp() }); request({ url: server, time: i * 1000 }, snifferCallback); } } totalTimer.resume(function () { RongIMLib.Navigation.clear(); clearHandler(); that.socket.fire("StatusChanged", RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE); }); }, comet: function () { var host = servers[0]; startConnect(host); } }; var isPolling = depend.isPolling; var type = isPolling ? 'comet' : 'ws'; connectMap[type](); //注册状态改变观察者 var StatusEvent = Channel._ConnectionStatusListener; var hasEvent = (typeof StatusEvent == "object"); var me = this; var isFirstConnect = true; me.socket.on("StatusChanged", function (code) { if (!hasEvent) { throw new Error("setConnectStatusListener:Parameter format is incorrect"); } var isNetworkUnavailable = (code == RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE); var isWebSocket = !RongIMLib.RongIMClient._memoryStore.depend.isPolling; if (isFirstConnect && isNetworkUnavailable && isWebSocket) { code = RongIMLib.ConnectionStatus.WEBSOCKET_UNAVAILABLE; } me.connectionStatus = code; setTimeout(function () { StatusEvent.onChanged(code); }); var isDisconnected = (code == RongIMLib.ConnectionStatus.DISCONNECTED); if (isDisconnected) { self.clearHeartbeat(); } var isOtherDevice = (code == RongIMLib.ConnectionStatus.KICKED_OFFLINE_BY_OTHER_CLIENT); if (isOtherDevice) { // 累计其他设备登陆次数,超过 5 次后,自动销毁内部对象 // 删除位置:ServerDataProivder.prototype.connect RongIMLib.RongIMClient.otherDeviceLoginCount++; } var isConnected = (code == RongIMLib.ConnectionStatus.CONNECTED); if (isConnected) { isFirstConnect = false; } var isWebsocketUnAvailable = (code == RongIMLib.ConnectionStatus.WEBSOCKET_UNAVAILABLE); if (isWebsocketUnAvailable) { me.changeConnectType(); isFirstConnect = false; RongIMLib.RongIMClient.connect(self.token, RongIMLib.RongIMClient._memoryStore.callback); } }); //注册message观察者 this.socket.on("message", self.handler.handleMessage); //注册断开连接观察者 this.socket.on("disconnect", function (status) { that.socket.fire("StatusChanged", status ? status : 2); }); } Channel.prototype.changeConnectType = function () { RongIMLib.RongIMClient._memoryStore.depend.isPolling = !RongIMLib.RongIMClient._memoryStore.depend.isPolling; new RongIMLib.FeatureDectector(); }; Channel.prototype.writeAndFlush = function (val) { this.socket.send(val); }; Channel.prototype.reconnect = function (callback) { RongIMLib.MessageIdHandler.clearMessageId(); this.socket = this.socket.reconnect(); if (callback) { this.self.reconnectObj = callback; } }; Channel.prototype.disconnect = function (status) { this.socket.disconnect(status); }; return Channel; })(); RongIMLib.Channel = Channel; var Socket = (function () { function Socket() { this.socket = null; this._events = {}; } Socket.getInstance = function () { return new Socket(); }; Socket.prototype.connect = function (url, cb) { if (this.socket) { if (url) { RongIMLib.RongIMClient._storageProvider.setItem("rongSDK", this.checkTransport()); this.on("connect", cb || new Function); } if (url) { this.currentURL = url; } this.socket.createTransport(url); } return this; }; Socket.prototype.createServer = function () { var transport = this.getTransport(this.checkTransport()); if (transport === null) { throw new Error("the channel was not supported"); } return transport; }; Socket.prototype.getTransport = function (transportType) { if (transportType == Socket.XHR_POLLING) { this.socket = new RongIMLib.PollingTransportation(this); } else if (transportType == Socket.WEBSOCKET) { this.socket = new RongIMLib.SocketTransportation(this); } return this; }; Socket.prototype.send = function (data) { if (this.socket) { if (this.checkTransport() == Socket.WEBSOCKET) { this.socket.send(data); } else { this.socket.send(this._encode(data)); } } }; Socket.prototype.onMessage = function (data) { this.fire("message", data); }; Socket.prototype.disconnect = function (status) { this.socket.disconnect(status); this.fire("disconnect", status); return this; }; Socket.prototype.reconnect = function () { if (this.currentURL && RongIMLib.RongIMClient._storageProvider.getItem("rongSDK")) { return this.connect(this.currentURL, null); } else { throw new Error("reconnect:no have URL"); } }; /** * [checkTransport 返回通道类型] */ Socket.prototype.checkTransport = function () { if (RongIMLib.RongIMClient._memoryStore.depend.isPolling) { RongIMLib.Transportations._TransportType = Socket.XHR_POLLING; } return RongIMLib.Transportations._TransportType; }; Socket.prototype.fire = function (x, args) { if (x in this._events) { for (var i = 0, ii = this._events[x].length; i < ii; i++) { this._events[x][i](args); } } return this; }; Socket.prototype.on = function (x, func) { if (!(typeof func == "function" && x)) { return this; } if (x in this._events) { RongIMLib.MessageUtil.indexOf(this._events, func) == -1 && this._events[x].push(func); } else { this._events[x] = [func]; } return this; }; Socket.prototype.removeEvent = function (x, fn) { if (x in this._events) { for (var a = 0, l = this._events[x].length; a < l; a++) { if (this._events[x][a] == fn) { this._events[x].splice(a, 1); } } } return this; }; Socket.prototype._encode = function (x) { var str = "?messageid=" + x.getMessageId() + "&header=" + x.getHeaderFlag() + "&sessionid=" + RongIMLib.RongIMClient._storageProvider.getItem("sId" + RongIMLib.Navigation.Endpoint.userId); if (!/(PubAckMessage|QueryConMessage)/.test(x._name)) { str += "&topic=" + x.getTopic() + "&targetid=" + (x.getTargetId() || ""); } return { url: str, data: "getData" in x ? x.getData() : "" }; }; //消息通道常量,所有和通道相关判断均用 XHR_POLLING WEBSOCKET两属性 Socket.XHR_POLLING = "xhr-polling"; Socket.WEBSOCKET = "websocket"; return Socket; })(); RongIMLib.Socket = Socket; //连接端消息累 var Client = (function () { function Client(token, appId) { this.timeoutMillis = 6000; this.timeout_ = 0; this.sdkVer = ''; this.apiVer = Math.floor(Math.random() * 1e6); this.channel = null; this.handler = null; this.userId = ""; this.reconnectObj = {}; this.heartbeat = 0; this.pullMsgHearbeat = 0; this.chatroomId = ""; this.SyncTimeQueue = []; this.cacheMessageIds = []; this.token = token; this.appId = appId; this.SyncTimeQueue.state = "complete"; this.sdkVer = RongIMLib.RongIMClient.sdkver; } Client.prototype.resumeTimer = function () { var me = this; this.timeout_ = setTimeout(function () { me.channel.disconnect(); }, this.timeoutMillis); }; Client.prototype.pauseTimer = function () { if (this.timeout_) { clearTimeout(this.timeout_); this.timeout_ = 0; } }; Client.prototype.connect = function (_callback) { //实例消息处理类 this.handler = new MessageHandler(this); //设置连接回调 this.handler.setConnectCallback(_callback); //实例通道类型 var me = this; this.channel = new Channel(function () { RongIMLib.Transportations._TransportType == Socket.WEBSOCKET && me.keepLive(); }, this); //触发状态改变观察者 this.channel.socket.fire("StatusChanged", RongIMLib.ConnectionStatus.CONNECTING); //没有返回地址就手动抛出错误 //_callback.onError(ConnectionState.NOT_AUTHORIZED); }; Client.prototype.checkSocket = function (callback) { var me = this; me.channel.writeAndFlush(new RongIMLib.PingReqMessage()); var count = 0; var checkTimeout = setInterval(function () { if (!RongIMLib.RongIMClient._memoryStore.isFirstPingMsg) { clearInterval(checkTimeout); callback.onSuccess(); } else { if (count > 15) { clearInterval(checkTimeout); callback.onError(); } } count++; }, 100); }; Client.prototype.keepLive = function () { if (this.heartbeat > 0) { clearInterval(this.heartbeat); } var me = this; me.heartbeat = setInterval(function () { me.resumeTimer(); me.channel.writeAndFlush(new RongIMLib.PingReqMessage()); }, 30000); if (me.pullMsgHearbeat > 0) { clearInterval(me.pullMsgHearbeat); } me.pullMsgHearbeat = setInterval(function () { me.syncTime(true, undefined, undefined, false); }, 180000); }; Client.prototype.clearHeartbeat = function () { clearInterval(this.heartbeat); this.heartbeat = 0; this.pauseTimer(); clearInterval(this.pullMsgHearbeat); this.pullMsgHearbeat = 0; }; Client.prototype.publishMessage = function (_topic, _data, _targetId, _callback, _msg) { var msgId = RongIMLib.MessageIdHandler.messageIdPlus(this.channel.reconnect); if (!msgId) { return; } var msg = new RongIMLib.PublishMessage(_topic, _data, _targetId); msg.setMessageId(msgId); if (_callback) { msg.setQos(Qos.AT_LEAST_ONCE); this.handler.putCallback(new RongIMLib.PublishCallback(_callback.onSuccess, _callback.onError), msg.getMessageId(), _msg); } else { msg.setQos(Qos.AT_MOST_ONCE); } this.channel.writeAndFlush(msg); }; Client.prototype.queryMessage = function (_topic, _data, _targetId, _qos, _callback, pbtype) { if (_topic == "userInf") { if (Client.userInfoMapping[_targetId]) { _callback.onSuccess(Client.userInfoMapping[_targetId]); return; } } var msgId = RongIMLib.MessageIdHandler.messageIdPlus(this.channel.reconnect); if (!msgId) { return; } var msg = new RongIMLib.QueryMessage(_topic, _data, _targetId); msg.setMessageId(msgId); msg.setQos(_qos); this.handler.putCallback(new RongIMLib.QueryCallback(_callback.onSuccess, _callback.onError), msg.getMessageId(), pbtype); this.channel.writeAndFlush(msg); }; Client.prototype.invoke = function (isPullMsg, chrmId, offlineMsg) { var time, modules, str, me = this, target, temp = this.SyncTimeQueue.shift(); if (temp == undefined) { return; } this.SyncTimeQueue.state = "pending"; var localSyncTime = RongIMLib.SyncTimeUtil.get(); var sentBoxTime = localSyncTime.sent; if (temp.type != 2) { //普通消息 time = localSyncTime.received; modules = new RongIMLib.RongIMClient.Protobuf.SyncRequestMsg(); modules.setIspolling(false); str = "pullMsg"; target = this.userId; modules.setSendBoxSyncTime(sentBoxTime); } else { //聊天室消息 target = temp.chrmId || me.chatroomId; time = RongIMLib.RongIMClient._memoryStore.lastReadTime.get(target + Bridge._client.userId + "CST") || 0; modules = new RongIMLib.RongIMClient.Protobuf.ChrmPullMsg(); modules.setCount(0); str = "chrmPull"; if (!target) { throw new Error("syncTime:Received messages of chatroom but was not init"); } } //判断服务器给的时间是否消息本地存储的时间,小于的话不执行拉取操作,进行一下步队列操作 if (temp.pulltime <= time) { this.SyncTimeQueue.state = "complete"; this.invoke(isPullMsg, target); return; } if (isPullMsg && 'setIsPullSend' in modules) { modules.setIsPullSend(true); } modules.setSyncTime(time); //发送queryMessage请求 this.queryMessage(str, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), target, Qos.AT_LEAST_ONCE, { onSuccess: function (collection) { var sync = RongIMLib.MessageUtil.int64ToTimestamp(collection.syncTime), symbol = target; //把返回时间戳存入本地,普通消息key为userid,聊天室消息key为userid+'CST';value都为服务器返回的时间戳 var isChrmPull = str == 'chrmPull'; if (isChrmPull) { symbol += Bridge._client.userId + "CST"; RongIMLib.RongIMClient._memoryStore.lastReadTime.set(symbol, sync); } else { var storage = RongIMLib.RongIMClient._storageProvider; if (sync > storage.getItem(symbol)) { storage.setItem(symbol, sync); } } //把拉取到的消息逐条传给消息监听器 var list = collection.list; var isPullFinished = collection.finished; // chrmPull 没有 finished 字段,自动设置为拉取完成 if (isChrmPull) { isPullFinished = true; } var receivedMsgIdList = []; // 自己给自己发消息, 拉消息重复 RongIMLib.RongIMClient._memoryStore.isPullFinished = isPullFinished; for (var i = 0, len = list.length, count = len; i < len; i++) { count -= 1; var message = list[i]; var sentTime = RongIMLib.MessageUtil.int64ToTimestamp(message.dataTime); var isSender = message.fromUserId == Bridge._client.userId; var compareTime = isSender ? sentBoxTime : time; var msgId = message.msgId; var hasReceived = receivedMsgIdList.indexOf(msgId) !== -1; // 自己给自己发消息, 拉消息重复 if (sentTime > compareTime && !hasReceived) { // 自己给自己发消息, 拉消息重复 receivedMsgIdList.push(msgId); var isSyncMessage = false; Bridge._client.handler.onReceived(message, undefined, offlineMsg, count, isSyncMessage, isPullFinished); } } me.SyncTimeQueue.state = "complete"; me.invoke(isPullMsg, target); }, onError: function (error) { me.SyncTimeQueue.state = "complete"; me.invoke(isPullMsg, target); } }, "DownStreamMessages"); }; Client.prototype.syncTime = function (_type, pullTime, chrmId, offlineMsg) { this.SyncTimeQueue.push({ type: _type, pulltime: pullTime, chrmId: chrmId }); //如果队列中只有一个成员并且状态已经完成就执行invoke方法 if (this.SyncTimeQueue.length == 1 && this.SyncTimeQueue.state == "complete") { this.invoke(!_type, chrmId, offlineMsg); } }; Client.prototype.__init = function (f) { this.handler = new MessageHandler(this); //设置连接回调 this.handler.setConnectCallback(RongIMLib.RongIMClient._memoryStore.callback); this.channel = new Channel(f, this); }; Client.userInfoMapping = {}; return Client; })(); RongIMLib.Client = Client; //连接类,实现imclient与connect_client的连接 var Bridge = (function () { function Bridge() { } Bridge.getInstance = function () { return new Bridge(); }; //连接服务器 Bridge.prototype.connect = function (appKey, token, callback) { if (!RongIMLib.RongIMClient.Protobuf) { return; } Bridge._client = new RongIMLib.Navigation().connect(appKey, token, callback); return Bridge._client; }; Bridge.prototype.setListener = function (_changer) { if (typeof _changer == "object") { if (typeof _changer.onChanged == "function") { Channel._ConnectionStatusListener = _changer; } else if (typeof _changer.onReceived == "function") { Channel._ReceiveMessageListener = _changer; } } }; Bridge.prototype.reconnect = function (callabck) { Bridge._client.channel.reconnect(callabck); }; Bridge.prototype.disconnect = function () { Bridge._client.channel.disconnect(2); }; //执行queryMessage请求 Bridge.prototype.queryMsg = function (topic, content, targetId, callback, pbname) { if (typeof topic != "string") { topic = _topic[topic]; } Bridge._client.queryMessage(topic, content, targetId, Qos.AT_MOST_ONCE, callback, pbname); }; //发送消息 执行publishMessage 请求 Bridge.prototype.pubMsg = function (topic, content, targetId, callback, msg, methodType) { if (typeof methodType == 'number') { if (methodType == RongIMLib.MethodType.CUSTOMER_SERVICE) { Bridge._client.publishMessage("pcuMsgP", content, targetId, callback, msg); } else if (methodType == RongIMLib.MethodType.RECALL) { Bridge._client.publishMessage("recallMsg", content, targetId, callback, msg); } } else { Bridge._client.publishMessage(_topic[10][topic], content, targetId, callback, msg); } }; return Bridge; })(); RongIMLib.Bridge = Bridge; var MessageHandler = (function () { function MessageHandler(client) { this.map = {}; this.connectCallback = null; if (!Channel._ReceiveMessageListener) { throw new Error("please set onReceiveMessageListener"); } this._onReceived = Channel._ReceiveMessageListener.onReceived; this._client = client; this.syncMsgMap = new Object; } //把对象推入回调对象队列中,并启动定时器 MessageHandler.prototype.putCallback = function (callbackObj, _publishMessageId, _msg) { var item = { Callback: callbackObj, Message: _msg }; item.Callback.resumeTimer(); this.map[_publishMessageId] = item; }; //设置连接回调对象,启动定时器 MessageHandler.prototype.setConnectCallback = function (_connectCallback) { if (_connectCallback) { this.connectCallback = new RongIMLib.ConnectAck(_connectCallback.onSuccess, _connectCallback.onError, this._client); } }; MessageHandler.prototype.onReceived = function (msg, pubAckItem, offlineMsg, leftCount, isSync) { //实体对象 var entity, //解析完成的消息对象 message, //会话对象 con, isStraightMsg = false; if (msg._name != "PublishMessage") { entity = msg; RongIMLib.RongIMClient._storageProvider.setItem(this._client.userId, RongIMLib.MessageUtil.int64ToTimestamp(entity.dataTime)); } else { if (msg.getTopic() == "s_ntf") { entity = RongIMLib.RongIMClient.Protobuf.NotifyMsg.decode(msg.getData()); this._client.syncTime(entity.type, RongIMLib.MessageUtil.int64ToTimestamp(entity.time), entity.chrmId); return; } else if (msg.getTopic() == "s_msg") { isStraightMsg = true; entity = RongIMLib.RongIMClient.Protobuf.DownStreamMessage.decode(msg.getData()); var timestamp = RongIMLib.MessageUtil.int64ToTimestamp(entity.dataTime); RongIMLib.RongIMClient._storageProvider.setItem(this._client.userId, timestamp); RongIMLib.RongIMClient._memoryStore.lastReadTime.get(this._client.userId, timestamp); } else if (msg.getTopic() == "s_stat") { entity = RongIMLib.RongIMClient.Protobuf.GetUserStatusOutput.decode(msg.getData()); entity = RongIMLib.RongInnerTools.convertUserStatus(entity); RongIMLib.RongIMClient.userStatusObserver.notify({ key: entity.userId, entity: entity }); return; } else { if (Bridge._client.sdkVer && Bridge._client.sdkVer == "1.0.0") { return; } entity = RongIMLib.RongIMClient.Protobuf.UpStreamMessage.decode(msg.getData()); var tmpTopic = msg.getTopic(); var tmpType = tmpTopic.substr(0, 2); if (tmpType == "pp") { entity.type = 1; } else if (tmpType == "pd") { entity.type = 2; } else if (tmpType == "pg") { entity.type = 3; } else if (tmpType == "ch") { entity.type = 4; } else if (tmpType == "pc") { entity.type = 5; } //复用字段,targetId 以此为准 entity.groupId = msg.getTargetId(); entity.fromUserId = this._client.userId; entity.dataTime = Date.parse(new Date().toString()); } if (!entity) { return; } } var isPullFinished = RongIMLib.RongIMClient._memoryStore.isPullFinished; // PullMsg 没有拉取完成,抛弃所有消息,抛弃的消息会在 PullMsg 中返回 if (!isPullFinished && !offlineMsg && isStraightMsg) { return; } //解析实体对象为消息对象。 message = RongIMLib.MessageUtil.messageParser(entity, this._onReceived, offlineMsg); var isRecall = (msg.getTopic && msg.getTopic() == "recallMsg"); if (isRecall) { var content = message.content; message.conversationType = content.conversationType; message.targetId = content.targetId; message.messageId = null; } if (pubAckItem) { message.messageUId = pubAckItem.getMessageUId(); message.sentTime = pubAckItem.getTimestamp(); RongIMLib.RongIMClient._storageProvider.setItem(this._client.userId, message.sentTime); } if (message === null) { return; } var isChatroomMessage = message.conversationType == RongIMLib.ConversationType.CHATROOM; if (!isChatroomMessage) { var msgTag = RongIMLib.RongIMClient.MessageParams[message.messageType].msgTag.getMessageTag(); if (msgTag >= 0) { RongIMLib.SyncTimeUtil.set(message); } var isSend = (message.messageDirection == RongIMLib.MessageDirection.SEND); if (isSend) { var storageProvider = RongIMLib.RongIMClient._storageProvider; var userId = RongIMLib.Bridge._client.userId; var lastSentTime = storageProvider.getItem('last_sentTime_' + userId) || 0; if (message.sentTime <= lastSentTime && !isSync) { return; } } } // 设置会话时间戳并且判断是否传递 message 发送消息未处理会话时间戳 // key:'converST_' + 当前用户 + conversationType + targetId // RongIMClient._storageProvider.setItem('converST_' + Bridge._client.userId + message.conversationType + message.targetId, message.sentTime); var isPersited = (RongIMLib.RongIMClient.MessageParams[message.messageType].msgTag.getMessageTag() > 0); if (isPersited) { con = RongIMLib.RongIMClient._dataAccessProvider.getConversation(message.conversationType, message.targetId, { onSuccess: function () { }, onError: function () { } }); if (!con) { con = RongIMLib.RongIMClient.getInstance().createConversation(message.conversationType, message.targetId, ""); } if (message.messageDirection == RongIMLib.MessageDirection.RECEIVE && (entity.status & 64) == 64) { var mentioneds = RongIMLib.RongIMClient._storageProvider.getItem("mentioneds_" + Bridge._client.userId + '_' + message.conversationType + '_' + message.targetId); var key = message.conversationType + '_' + message.targetId, info = {}; if (message.content && message.content.mentionedInfo) { info[key] = { uid: message.messageUId, time: message.sentTime, mentionedInfo: message.content.mentionedInfo }; RongIMLib.RongIMClient._storageProvider.setItem("mentioneds_" + Bridge._client.userId + '_' + message.conversationType + '_' + message.targetId, JSON.stringify(info)); mentioneds = JSON.stringify(info); } if (mentioneds) { var info = JSON.parse(mentioneds); con.mentionedMsg = info[key]; } } var isReceiver = message.messageDirection == RongIMLib.MessageDirection.RECEIVE; if (isReceiver) { con.unreadMessageCount = con.unreadMessageCount + 1; if (RongIMLib.RongUtil.supportLocalStorage()) { var originUnreadCount = RongIMLib.RongIMClient._storageProvider.getItem("cu" + Bridge._client.userId + con.conversationType + con.targetId); // 与本地存储会话合并 var newUnreadCount = Number(originUnreadCount) + 1; RongIMLib.RongIMClient._storageProvider.setItem("cu" + Bridge._client.userId + con.conversationType + message.targetId, newUnreadCount); con.unreadMessageCount = newUnreadCount; } } con.receivedTime = new Date().getTime(); con.receivedStatus = message.receivedStatus; con.senderUserId = message.sendUserId; con.notificationStatus = RongIMLib.ConversationNotificationStatus.DO_NOT_DISTURB; con.latestMessageId = message.messageId; con.latestMessage = message; con.sentTime = message.sentTime; RongIMLib.RongIMClient._dataAccessProvider.addConversation(con, { onSuccess: function (data) { }, onError: function () { } }); } if (message.conversationType == RongIMLib.ConversationType.CUSTOMER_SERVICE && (message.messageType == "ChangeModeResponseMessage" || message.messageType == "SuspendMessage" || message.messageType == "HandShakeResponseMessage" || message.messageType == "TerminateMessage" || message.messageType == "CustomerStatusUpdateMessage" || message.messageType == "TextMessage" || message.messageType == "InformationNotificationMessage")) { if (!RongIMLib.RongIMClient._memoryStore.custStore["isInit"]) { return; } } if (message.conversationType == RongIMLib.ConversationType.CUSTOMER_SERVICE && message.messageType != "HandShakeResponseMessage") { if (!RongIMLib.RongIMClient._memoryStore.custStore[message.targetId]) { return; } if (message.messageType == "TerminateMessage") { if (RongIMLib.RongIMClient._memoryStore.custStore[message.targetId].sid != message.content.sid) { return; } } } if (message.messageType === RongIMLib.RongIMClient.MessageType["HandShakeResponseMessage"]) { var session = message.content.data; RongIMLib.RongIMClient._memoryStore.custStore[message.targetId] = session; if (session.serviceType == RongIMLib.CustomerType.ONLY_HUMAN || session.serviceType == RongIMLib.CustomerType.HUMAN_FIRST) { if (session.notAutoCha == "1") { RongIMLib.RongIMClient.getInstance().switchToHumanMode(message.targetId, { onSuccess: function () { }, onError: function () { } }); } } } var d = new Date(), m = d.getMonth() + 1, date = d.getFullYear() + '/' + (m.toString().length == 1 ? '0' + m : m) + '/' + d.getDate(); //new Date(date).getTime() - message.sentTime < 1 逻辑判断 超过 1 天未收的 ReadReceiptRequestMessage 离线消息自动忽略。 var dealtime = new Date(date).getTime() - message.sentTime < 0; if (RongIMLib.RongUtil.supportLocalStorage() && message.messageType === RongIMLib.RongIMClient.MessageType["ReadReceiptRequestMessage"] && dealtime && message.messageDirection == RongIMLib.MessageDirection.SEND) { var sentkey = Bridge._client.userId + message.content.messageUId + "SENT"; RongIMLib.RongIMClient._storageProvider.setItem(sentkey, JSON.stringify({ count: 0, dealtime: message.sentTime, userIds: {} })); } else if (RongIMLib.RongUtil.supportLocalStorage() && message.messageType === RongIMLib.RongIMClient.MessageType["ReadReceiptRequestMessage"] && dealtime) { var reckey = Bridge._client.userId + message.conversationType + message.targetId + 'RECEIVED', recData = JSON.parse(RongIMLib.RongIMClient._storageProvider.getItem(reckey)); if (recData) { if (message.senderUserId in recData) { if (recData[message.senderUserId].uIds && recData[message.senderUserId].uIds && recData[message.senderUserId].uIds.indexOf(message.content.messageUId) == -1) { recData[message.senderUserId].uIds.push(message.content.messageUId); recData[message.senderUserId].dealtime = message.sentTime; recData[message.senderUserId].isResponse = false; RongIMLib.RongIMClient._storageProvider.setItem(reckey, JSON.stringify(recData)); } else { return; } } else { var objSon = { uIds: [message.content.messageUId], dealtime: message.sentTime, isResponse: false }; recData[message.senderUserId] = objSon; RongIMLib.RongIMClient._storageProvider.setItem(reckey, JSON.stringify(recData)); } } else { var obj = {}; obj[message.senderUserId] = { uIds: [message.content.messageUId], dealtime: message.sentTime, isResponse: false }; RongIMLib.RongIMClient._storageProvider.setItem(reckey, JSON.stringify(obj)); } } if (RongIMLib.RongUtil.supportLocalStorage() && message.messageType === RongIMLib.RongIMClient.MessageType["ReadReceiptResponseMessage"] && dealtime) { var receiptResponseMsg = message.content, uIds = receiptResponseMsg.receiptMessageDic[Bridge._client.userId], sentkey = "", sentObj; message.receiptResponse || (message.receiptResponse = {}); if (uIds) { var cbuIds = []; for (var i = 0, len = uIds.length; i < len; i++) { sentkey = Bridge._client.userId + uIds[i] + "SENT"; sentObj = JSON.parse(RongIMLib.RongIMClient._storageProvider.getItem(sentkey)); if (sentObj && !(message.senderUserId in sentObj.userIds)) { cbuIds.push(uIds[i]); sentObj.count += 1; sentObj.userIds[message.senderUserId] = message.sentTime; message.receiptResponse[uIds[i]] = sentObj.count; RongIMLib.RongIMClient._storageProvider.setItem(sentkey, JSON.stringify(sentObj)); } } receiptResponseMsg.receiptMessageDic[Bridge._client.userId] = cbuIds; message.content = receiptResponseMsg; } } var that = this; if (RongIMLib.RongIMClient._voipProvider && ['AcceptMessage', 'RingingMessage', 'HungupMessage', 'InviteMessage', 'MediaModifyMessage', 'MemberModifyMessage'].indexOf(message.messageType) > -1) { setTimeout(function () { RongIMLib.RongIMClient._voipProvider.onReceived(message); }); } else { var count = leftCount || 0; var hasMore = !isPullFinished; setTimeout(function () { that._onReceived(message, count, hasMore); }); } }; MessageHandler.prototype.handleMessage = function (msg) { if (!msg) { return; } switch (msg._name) { case "ConnAckMessage": Bridge._client.handler.connectCallback.process(msg.getStatus(), msg.getUserId(), msg.getTimestamp()); break; case "PublishMessage": if (!msg.getSyncMsg() && msg.getQos() != 0) { Bridge._client.channel.writeAndFlush(new RongIMLib.PubAckMessage(msg.getMessageId())); } // TODO && -> if (msg.getSyncMsg() && !RongIMLib.RongIMClient._memoryStore.depend.isPolling) { Bridge._client.handler.syncMsgMap[msg.getMessageId()] = msg; } else { //如果是PublishMessage就把该对象给onReceived方法执行处理 Bridge._client.handler.onReceived(msg); } break; case "QueryAckMessage": if (msg.getQos() != 0) { Bridge._client.channel.writeAndFlush(new RongIMLib.QueryConMessage(msg.getMessageId())); } var temp = Bridge._client.handler.map[msg.getMessageId()]; if (temp) { //执行回调操作 temp.Callback.process(msg.getStatus(), msg.getData(), msg.getDate(), temp.Message); delete Bridge._client.handler.map[msg.getMessageId()]; } break; case "PubAckMessage": var item = Bridge._client.handler.map[msg.getMessageId()]; if (item) { item.Callback.process(msg.getStatus() || 0, msg.getMessageUId(), msg.getTimestamp(), item.Message, msg.getMessageId()); delete Bridge._client.handler.map[msg.getMessageId()]; } else { var userId = RongIMLib.Bridge._client.userId; RongIMLib.RongIMClient._storageProvider.setItem('last_sentTime_' + userId, msg.timestamp); Bridge._client.handler.onReceived(Bridge._client.handler.syncMsgMap[msg.messageId], msg, null, null, true); delete Bridge._client.handler.syncMsgMap[msg.getMessageId()]; } break; case "PingRespMessage": if (RongIMLib.RongIMClient._memoryStore.isFirstPingMsg) { RongIMLib.RongIMClient._memoryStore.isFirstPingMsg = false; } else { Bridge._client.pauseTimer(); } break; case "DisconnectMessage": Bridge._client.channel.disconnect(msg.getStatus()); break; default: } }; return MessageHandler; })(); RongIMLib.MessageHandler = MessageHandler; })(RongIMLib || (RongIMLib = {})); var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; /// var RongIMLib; (function (RongIMLib) { var MessageCallback = (function () { function MessageCallback(error) { this.timeout = null; this.onError = null; if (error && typeof error == "number") { this.timeoutMillis = error; } else { this.timeoutMillis = 30000; this.onError = error; } } MessageCallback.prototype.resumeTimer = function () { var me = this; if (this.timeoutMillis > 0 && !this.timeout) { this.timeout = setTimeout(function () { me.readTimeOut(true); }, this.timeoutMillis); } }; MessageCallback.prototype.pauseTimer = function () { if (this.timeout) { clearTimeout(this.timeout); this.timeout = null; } }; MessageCallback.prototype.readTimeOut = function (isTimeout) { if (isTimeout && this.onError) { this.onError(RongIMLib.ErrorCode.TIMEOUT); } else { this.pauseTimer(); } }; return MessageCallback; })(); RongIMLib.MessageCallback = MessageCallback; var CallbackMapping = (function () { function CallbackMapping() { this.publicServiceList = []; } CallbackMapping.getInstance = function () { return new CallbackMapping(); }; CallbackMapping.prototype.pottingProfile = function (item) { var temp; this.profile = new RongIMLib.PublicServiceProfile(); temp = JSON.parse(item.extra); this.profile.isGlobal = temp.isGlobal; this.profile.introduction = temp.introduction; this.profile.menu = temp.menu; this.profile.hasFollowed = temp.follow; this.profile.publicServiceId = item.mpid; this.profile.name = item.name; this.profile.portraitUri = item.portraitUrl; this.profile.conversationType = item.type == "mc" ? RongIMLib.ConversationType.APP_PUBLIC_SERVICE : RongIMLib.ConversationType.PUBLIC_SERVICE; this.publicServiceList.push(this.profile); }; CallbackMapping.prototype.mapping = function (entity, tag) { switch (tag) { case "GetUserInfoOutput": var userInfo = new RongIMLib.UserInfo(entity.userId, entity.userName, entity.userPortrait); return userInfo; case "GetQNupTokenOutput": return { deadline: RongIMLib.MessageUtil.int64ToTimestamp(entity.deadline), token: entity.token }; case "GetQNdownloadUrlOutput": return { downloadUrl: entity.downloadUrl }; case "CreateDiscussionOutput": return entity.id; case "ChannelInfoOutput": var disInfo = new RongIMLib.Discussion(); disInfo.creatorId = entity.adminUserId; disInfo.id = entity.channelId; disInfo.memberIdList = entity.firstTenUserIds; disInfo.name = entity.channelName; disInfo.isOpen = entity.openStatus; return disInfo; case "GroupHashOutput": return entity.result; case "QueryBlackListOutput": return entity.userIds; case "SearchMpOutput": case "PullMpOutput": if (entity.info) { var self = this; Array.forEach(entity.info, function (item) { setTimeout(function () { self.pottingProfile(item); }, 100); }); } return this.publicServiceList; default: return entity; } }; return CallbackMapping; })(); RongIMLib.CallbackMapping = CallbackMapping; var PublishCallback = (function (_super) { __extends(PublishCallback, _super); function PublishCallback(_cb, _timeout) { _super.call(this, _timeout); this._cb = _cb; this._timeout = _timeout; } PublishCallback.prototype.process = function (_status, messageUId, timestamp, _msg, messageId) { this.readTimeOut(); if (_status == 0) { if (_msg) { _msg.setSentStatus = _status; } var isPullFinished = RongIMLib.RongIMClient._memoryStore.isPullFinished; if (isPullFinished) { var userId = RongIMLib.Bridge._client.userId; var stroageProvider = RongIMLib.RongIMClient._storageProvider; stroageProvider.setItem('last_sentTime_' + userId, timestamp); RongIMLib.SyncTimeUtil.set({ messageDirection: RongIMLib.MessageDirection.SEND, sentTime: timestamp }); } this._cb({ messageUId: messageUId, timestamp: timestamp, messageId: messageId }); } else { this._timeout(_status, { messageUId: messageUId, sentTime: timestamp }); } }; PublishCallback.prototype.readTimeOut = function (x) { MessageCallback.prototype.readTimeOut.call(this, x); }; return PublishCallback; })(MessageCallback); RongIMLib.PublishCallback = PublishCallback; var QueryCallback = (function (_super) { __extends(QueryCallback, _super); function QueryCallback(_cb, _timeout) { _super.call(this, _timeout); this._cb = _cb; this._timeout = _timeout; } QueryCallback.prototype.process = function (status, data, serverTime, pbtype) { this.readTimeOut(); if (pbtype && data && status == 0) { try { data = CallbackMapping.getInstance().mapping(RongIMLib.RongIMClient.Protobuf[pbtype].decode(data), pbtype); } catch (e) { this._timeout(RongIMLib.ErrorCode.UNKNOWN); return; } if ("GetUserInfoOutput" == pbtype) { //pb类型为GetUserInfoOutput的话就把data放入userinfo缓存队列 RongIMLib.Client.userInfoMapping[data.userId] = data; } this._cb(data); } else { status > 0 ? this._timeout(status) : this._cb(status); } }; QueryCallback.prototype.readTimeOut = function (x) { MessageCallback.prototype.readTimeOut.call(this, x); }; return QueryCallback; })(MessageCallback); RongIMLib.QueryCallback = QueryCallback; var ConnectAck = (function (_super) { __extends(ConnectAck, _super); function ConnectAck(_cb, _timeout, client) { _super.call(this, _timeout); this._client = client; this._cb = _cb; this._timeout = _timeout; } ConnectAck.prototype.process = function (status, userId, timestamp) { this.readTimeOut(); if (status == 0) { this._client.userId = userId; var self = this; if (!RongIMLib.RongIMClient._memoryStore.depend.isPolling && RongIMLib.RongIMClient._memoryStore.isFirstPingMsg) { RongIMLib.Bridge._client.checkSocket({ onSuccess: function () { if (!RongIMLib.RongIMClient.isNotPullMsg) { self._client.syncTime(undefined, undefined, undefined, true); } }, onError: function () { RongIMLib.RongIMClient._memoryStore.isFirstPingMsg = false; RongIMLib.RongIMClient.getInstance().disconnect(); RongIMLib.RongIMClient.connect(RongIMLib.RongIMClient._memoryStore.token, RongIMLib.RongIMClient._memoryStore.callback); } }); } else { if (!RongIMLib.RongIMClient.isNotPullMsg) { self._client.syncTime(undefined, undefined, undefined, true); } } if (this._client.reconnectObj.onSuccess) { this._client.reconnectObj.onSuccess(userId); delete this._client.reconnectObj.onSuccess; } else { var me = this; setTimeout(function () { me._cb(userId); }, 500); } RongIMLib.Bridge._client.channel.socket.fire("StatusChanged", 0); RongIMLib.RongIMClient._memoryStore.connectAckTime = timestamp; if (!(new Date().getTime() - timestamp)) { RongIMLib.RongIMClient._memoryStore.deltaTime = 0; } else { RongIMLib.RongIMClient._memoryStore.deltaTime = new Date().getTime() - timestamp; } } else if (status == 6) { RongIMLib.RongIMClient.getInstance().disconnect(); //重定向 连错 CMP var me = this; var _client = me._client; var appId = _client.appId, token = _client.token; new RongIMLib.Navigation().getServerEndpoint(token, appId, function () { _client.clearHeartbeat(); var newClient = new RongIMLib.Client(token, appId); RongIMLib.Bridge._client = newClient; newClient.__init(function () { RongIMLib.Transportations._TransportType == "websocket" && newClient.keepLive(); }); }, me._timeout, false); } else { RongIMLib.Bridge._client.channel.socket.socket._status = status; if (this._client.reconnectObj.onError) { this._client.reconnectObj.onError(status); delete this._client.reconnectObj.onError; } else { this._timeout(status); } } }; ConnectAck.prototype.readTimeOut = function (x) { MessageCallback.prototype.readTimeOut.call(this, x); }; return ConnectAck; })(MessageCallback); RongIMLib.ConnectAck = ConnectAck; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var Navigation = (function () { function Navigation() { window.getServerEndpoint = function (result) { var server = result.server; if (server) { server += ','; } var backupServer = result.backupServer || ''; var tpl = '{server}{backupServer}'; var servers = RongIMLib.RongUtil.tplEngine(tpl, { server: server, backupServer: backupServer }); var storage = RongIMLib.RongIMClient._storageProvider; servers = servers.split(','); storage.setItem('servers', JSON.stringify(servers)); var token = RongIMLib.RongIMClient._memoryStore.token; var uid = RongIMLib.InnerUtil.getUId(token); storage.setItem('rc_uid', uid); var userId = result.userId; storage.setItem('current_user', userId); if (result.voipCallInfo) { var callInfo = JSON.parse(result.voipCallInfo); RongIMLib.RongIMClient._memoryStore.voipStategy = callInfo.strategy; storage.setItem("voipStrategy", callInfo.strategy); } //替换本地存储的导航信息 var openMp = result.openMp; storage.setItem('openMp' + uid, openMp); RongIMLib.RongIMClient._memoryStore.depend.openMp = openMp; var StatusEvent = RongIMLib.Channel._ConnectionStatusListener; StatusEvent.onChanged(RongIMLib.ConnectionStatus.RESPONSE_NAVI); }; } Navigation.clear = function () { var storage = RongIMLib.RongIMClient._storageProvider; storage.removeItem('rc_uid'); storage.removeItem('serverIndex'); storage.removeItem('rongSDK'); }; Navigation.prototype.connect = function (appId, token, callback) { var oldAppId = RongIMLib.RongIMClient._storageProvider.getItem("appId"); //如果appid和本地存储的不一样,清空所有本地存储数据 if (oldAppId && oldAppId != appId) { RongIMLib.RongIMClient._storageProvider.clearItem(); RongIMLib.RongIMClient._storageProvider.setItem("appId", appId); } if (!oldAppId) { RongIMLib.RongIMClient._storageProvider.setItem("appId", appId); } var client = new RongIMLib.Client(token, appId); var me = this; this.getServerEndpoint(token, appId, function () { client.connect(callback); }, callback.onError, true); return client; }; Navigation.prototype.getServerEndpoint = function (token, appId, _onsuccess, _onerror, unignore) { if (unignore) { //根据token生成MD5截取8-16下标的数据与本地存储的导航信息进行比对 //如果信息和上次的通道类型都一样,不执行navi请求,用本地存储的导航信息连接服务器 var uId = md5(token).slice(8, 16); var storage = RongIMLib.RongIMClient._storageProvider; var transportType = storage.getItem("rongSDK"); var isSameType = (RongIMLib.Transportations._TransportType == transportType); var _old = storage.getItem('rc_uid'); var isSameUser = (_old == uId); var servers = storage.getItem('servers'); var hasServers = (typeof servers == 'string'); if (isSameUser && isSameType && hasServers) { RongIMLib.RongIMClient._memoryStore.voipStategy = storage.getItem("voipStrategy"); var openMp = storage.getItem('openMp' + uId); RongIMLib.RongIMClient._memoryStore.depend.openMp = openMp; _onsuccess(); return; } } Navigation.clear(); var StatusEvent = RongIMLib.Channel._ConnectionStatusListener; StatusEvent.onChanged(RongIMLib.ConnectionStatus.REQUEST_NAVI); //导航信息,切换Url对象的key进行线上线下测试操作 var xss = document.createElement("script"); //进行jsonp请求 var depend = RongIMLib.RongIMClient._memoryStore.depend; var domain = depend.navi; var path = (depend.isPolling ? 'cometnavi' : 'navi'); token = encodeURIComponent(token); var sdkver = RongIMLib.RongIMClient.sdkver; var random = RongIMLib.RongUtil.getTimestamp(); var tpl = '{domain}/{path}.js?appId={appId}&token={token}&callBack=getServerEndpoint&v={sdkver}&r={random}'; var url = RongIMLib.RongUtil.tplEngine(tpl, { domain: domain, path: path, appId: appId, token: token, sdkver: sdkver, random: random }); xss.src = url; document.body.appendChild(xss); xss.onerror = function () { _onerror(RongIMLib.ConnectionState.TOKEN_INCORRECT); }; if ("onload" in xss) { xss.onload = _onsuccess; } else { xss.onreadystatechange = function () { xss.readyState == "loaded" && _onsuccess(); }; } }; Navigation.Endpoint = new Object; return Navigation; })(); RongIMLib.Navigation = Navigation; })(RongIMLib || (RongIMLib = {})); // TODO: 统一变量、方法等命名规范 var RongIMLib; (function (RongIMLib) { /** * 消息基类 */ var BaseMessage = (function () { function BaseMessage(arg) { this._name = "BaseMessage"; this.lengthSize = 0; if (arg instanceof RongIMLib.Header) { this._header = arg; } else { this._header = new RongIMLib.Header(arg, false, RongIMLib.Qos.AT_MOST_ONCE, false); } } BaseMessage.prototype.read = function (In, length) { this.readMessage(In, length); }; BaseMessage.prototype.write = function (Out) { var binaryHelper = new RongIMLib.BinaryHelper(); var out = binaryHelper.convertStream(Out); this._headerCode = this.getHeaderFlag(); out.write(this._headerCode); this.writeMessage(out); return out; }; BaseMessage.prototype.getHeaderFlag = function () { return this._header.encode(); }; BaseMessage.prototype.getLengthSize = function () { return this.lengthSize; }; BaseMessage.prototype.toBytes = function () { return this.write([]).getBytesArray(); }; BaseMessage.prototype.isRetained = function () { return this._header.retain; }; BaseMessage.prototype.setRetained = function (retain) { this._header.retain = retain; }; BaseMessage.prototype.setQos = function (qos) { this._header.qos = Object.prototype.toString.call(qos) == "[object Object]" ? qos : RongIMLib.Qos[qos]; }; BaseMessage.prototype.setDup = function (dup) { this._header.dup = dup; }; BaseMessage.prototype.isDup = function () { return this._header.dup; }; BaseMessage.prototype.getType = function () { return this._header.type; }; BaseMessage.prototype.getQos = function () { return this._header.qos; }; BaseMessage.prototype.messageLength = function () { return 0; }; BaseMessage.prototype.writeMessage = function (out) { }; BaseMessage.prototype.readMessage = function (In, length) { }; BaseMessage.prototype.init = function (args) { var valName, nana, me = this; for (nana in args) { if (!args.hasOwnProperty(nana)) { continue; } valName = nana.replace(/^\w/, function (x) { var tt = x.charCodeAt(0); return "set" + (tt >= 0x61 ? String.fromCharCode(tt & ~32) : x); }); if (valName in me) { if (nana == "status") { me[valName](disconnectStatus[args[nana]] ? disconnectStatus[args[nana]] : args[nana]); } else { me[valName](args[nana]); } } } }; return BaseMessage; })(); RongIMLib.BaseMessage = BaseMessage; /** *连接消息类型 */ var ConnectMessage = (function (_super) { __extends(ConnectMessage, _super); function ConnectMessage(header) { _super.call(this, arguments.length == 0 || arguments.length == 3 ? RongIMLib.Type.CONNECT : arguments[0]); this._name = "ConnectMessage"; this.CONNECT_HEADER_SIZE = 12; this.protocolId = "RCloud"; this.binaryHelper = new RongIMLib.BinaryHelper(); this.protocolVersion = 3; switch (arguments.length) { case 0: case 1: case 3: if (!arguments[0] || arguments[0].length > 64) { throw new Error("ConnectMessage:Client Id cannot be null and must be at most 64 characters long: " + arguments[0]); } this.clientId = arguments[0]; this.cleanSession = arguments[1]; this.keepAlive = arguments[2]; break; } } ConnectMessage.prototype.messageLength = function () { var payloadSize = this.binaryHelper.toMQttString(this.clientId).length; payloadSize += this.binaryHelper.toMQttString(this.willTopic).length; payloadSize += this.binaryHelper.toMQttString(this.will).length; payloadSize += this.binaryHelper.toMQttString(this.appId).length; payloadSize += this.binaryHelper.toMQttString(this.token).length; return payloadSize + this.CONNECT_HEADER_SIZE; }; ConnectMessage.prototype.readMessage = function (stream) { this.protocolId = stream.readUTF(); this.protocolVersion = stream.readByte(); var cFlags = stream.readByte(); this.hasAppId = (cFlags & 128) > 0; this.hasToken = (cFlags & 64) > 0; this.retainWill = (cFlags & 32) > 0; this.willQos = cFlags >> 3 & 3; this.hasWill = (cFlags & 4) > 0; this.cleanSession = (cFlags & 32) > 0; this.keepAlive = stream.read() * 256 + stream.read(); this.clientId = stream.readUTF(); if (this.hasWill) { this.willTopic = stream.readUTF(); this.will = stream.readUTF(); } if (this.hasAppId) { try { this.appId = stream.readUTF(); } catch (ex) { throw new Error(ex); } } if (this.hasToken) { try { this.token = stream.readUTF(); } catch (ex) { throw new Error(ex); } } return stream; }; ConnectMessage.prototype.writeMessage = function (out) { var stream = this.binaryHelper.convertStream(out); stream.writeUTF(this.protocolId); stream.write(this.protocolVersion); var flags = this.cleanSession ? 2 : 0; flags |= this.hasWill ? 4 : 0; flags |= this.willQos ? this.willQos >> 3 : 0; flags |= this.retainWill ? 32 : 0; flags |= this.hasToken ? 64 : 0; flags |= this.hasAppId ? 128 : 0; stream.write(flags); stream.writeChar(this.keepAlive); stream.writeUTF(this.clientId); if (this.hasWill) { stream.writeUTF(this.willTopic); stream.writeUTF(this.will); } if (this.hasAppId) { stream.writeUTF(this.appId); } if (this.hasToken) { stream.writeUTF(this.token); } return stream; }; return ConnectMessage; })(BaseMessage); RongIMLib.ConnectMessage = ConnectMessage; /** *连接应答类型 */ var ConnAckMessage = (function (_super) { __extends(ConnAckMessage, _super); function ConnAckMessage(header) { _super.call(this, arguments.length == 0 ? RongIMLib.Type.CONNACK : arguments.length == 1 ? arguments[0] instanceof RongIMLib.Header ? arguments[0] : RongIMLib.Type.CONNACK : null); this._name = "ConnAckMessage"; this.MESSAGE_LENGTH = 2; this.binaryHelper = new RongIMLib.BinaryHelper(); var me = this; switch (arguments.length) { case 0: case 1: if (!(arguments[0] instanceof RongIMLib.Header)) { if (arguments[0] in RongIMLib.ConnectionState) { if (arguments[0] == null) { throw new Error("ConnAckMessage:The status of ConnAskMessage can't be null"); } me.setStatus(arguments[0]); } } break; } } ; ConnAckMessage.prototype.messageLength = function () { var length = this.MESSAGE_LENGTH; if (this.userId) { length += this.binaryHelper.toMQttString(this.userId).length; } return length; }; ; ConnAckMessage.prototype.readMessage = function (_in, msglength) { _in.read(); var result = +_in.read(); if (result >= 0 && result <= 12) { this.setStatus(result); } else { throw new Error("Unsupported CONNACK code:" + result); } if (msglength > this.MESSAGE_LENGTH) { this.setUserId(_in.readUTF()); var sessionId = _in.readUTF(); var timestamp = _in.readLong(); this.setTimestamp(timestamp); } }; ; ConnAckMessage.prototype.writeMessage = function (out) { var stream = this.binaryHelper.convertStream(out); stream.write(128); switch (+status) { case 0: case 1: case 2: case 5: case 6: stream.write(+status); break; case 3: case 4: stream.write(3); break; default: throw new Error("Unsupported CONNACK code:" + status); } if (this.userId) { stream.writeUTF(this.userId); } return stream; }; ; ConnAckMessage.prototype.setStatus = function (x) { this.status = x; }; ; ConnAckMessage.prototype.setUserId = function (_userId) { this.userId = _userId; }; ; ConnAckMessage.prototype.getStatus = function () { return this.status; }; ; ConnAckMessage.prototype.getUserId = function () { return this.userId; }; ; ConnAckMessage.prototype.setTimestamp = function (x) { this.timestrap = x; }; ; ConnAckMessage.prototype.getTimestamp = function () { return this.timestrap; }; return ConnAckMessage; })(BaseMessage); RongIMLib.ConnAckMessage = ConnAckMessage; /** *断开消息类型 */ var DisconnectMessage = (function (_super) { __extends(DisconnectMessage, _super); function DisconnectMessage(header) { _super.call(this, header instanceof RongIMLib.Header ? header : RongIMLib.Type.DISCONNECT); this._name = "DisconnectMessage"; this.MESSAGE_LENGTH = 2; this.binaryHelper = new RongIMLib.BinaryHelper(); if (!(header instanceof RongIMLib.Header)) { if (header in RongIMLib.ConnectionStatus) { this.status = header; } } } DisconnectMessage.prototype.messageLength = function () { return this.MESSAGE_LENGTH; }; DisconnectMessage.prototype.readMessage = function (_in) { _in.read(); var result = +_in.read(); if (result >= 0 && result <= 5) { this.setStatus(disconnectStatus[result] ? disconnectStatus[result] : result); } else { throw new Error("Unsupported CONNACK code:" + result); } }; DisconnectMessage.prototype.writeMessage = function (Out) { var out = this.binaryHelper.convertStream(Out); out.write(0); if (+status >= 1 && +status <= 3) { out.write((+status) - 1); } else { throw new Error("Unsupported CONNACK code:" + status); } }; DisconnectMessage.prototype.setStatus = function (x) { this.status = x; }; ; DisconnectMessage.prototype.getStatus = function () { return this.status; }; ; return DisconnectMessage; })(BaseMessage); RongIMLib.DisconnectMessage = DisconnectMessage; /** *请求消息信令 */ var PingReqMessage = (function (_super) { __extends(PingReqMessage, _super); function PingReqMessage(header) { _super.call(this, (header && header instanceof RongIMLib.Header) ? header : RongIMLib.Type.PINGREQ); this._name = "PingReqMessage"; } return PingReqMessage; })(BaseMessage); RongIMLib.PingReqMessage = PingReqMessage; /** *响应消息信令 */ var PingRespMessage = (function (_super) { __extends(PingRespMessage, _super); function PingRespMessage(header) { _super.call(this, (header && header instanceof RongIMLib.Header) ? header : RongIMLib.Type.PINGRESP); this._name = "PingRespMessage"; } return PingRespMessage; })(BaseMessage); RongIMLib.PingRespMessage = PingRespMessage; /** *封装MesssageId */ var RetryableMessage = (function (_super) { __extends(RetryableMessage, _super); function RetryableMessage(argu) { _super.call(this, argu); this._name = "RetryableMessage"; this.binaryHelper = new RongIMLib.BinaryHelper(); } RetryableMessage.prototype.messageLength = function () { return 2; }; RetryableMessage.prototype.writeMessage = function (Out) { var out = this.binaryHelper.convertStream(Out), Id = this.getMessageId(), lsb = Id & 255, msb = (Id & 65280) >> 8; out.write(msb); out.write(lsb); return out; }; RetryableMessage.prototype.readMessage = function (_in, msgLength) { var msgId = _in.read() * 256 + _in.read(); this.setMessageId(parseInt(msgId, 10)); }; RetryableMessage.prototype.setMessageId = function (_messageId) { this.messageId = _messageId; }; RetryableMessage.prototype.getMessageId = function () { return this.messageId; }; return RetryableMessage; })(BaseMessage); RongIMLib.RetryableMessage = RetryableMessage; /** *发送消息应答(双向) *qos为1必须给出应答(所有消息类型一样) */ var PubAckMessage = (function (_super) { __extends(PubAckMessage, _super); function PubAckMessage(header) { _super.call(this, (header instanceof RongIMLib.Header) ? header : RongIMLib.Type.PUBACK); this.msgLen = 2; this.date = 0; this.millisecond = 0; this.timestamp = 0; this.binaryHelper = new RongIMLib.BinaryHelper(); this._name = "PubAckMessage"; if (!(header instanceof RongIMLib.Header)) { _super.prototype.setMessageId.call(this, header); } } PubAckMessage.prototype.messageLength = function () { return this.msgLen; }; PubAckMessage.prototype.writeMessage = function (Out) { var out = this.binaryHelper.convertStream(Out); RetryableMessage.prototype.writeMessage.call(this, out); }; PubAckMessage.prototype.readMessage = function (_in, msgLength) { RetryableMessage.prototype.readMessage.call(this, _in); this.date = _in.readInt(); this.status = _in.read() * 256 + _in.read(); this.millisecond = _in.read() * 256 + _in.read(); this.timestamp = this.date * 1000 + this.millisecond; this.messageUId = _in.readUTF(); }; PubAckMessage.prototype.setStatus = function (x) { this.status = x; }; PubAckMessage.prototype.setTimestamp = function (timestamp) { this.timestamp = timestamp; }; PubAckMessage.prototype.setMessageUId = function (messageUId) { this.messageUId = messageUId; }; PubAckMessage.prototype.getStatus = function () { return this.status; }; PubAckMessage.prototype.getDate = function () { return this.date; }; PubAckMessage.prototype.getTimestamp = function () { return this.timestamp; }; PubAckMessage.prototype.getMessageUId = function () { return this.messageUId; }; return PubAckMessage; })(RetryableMessage); RongIMLib.PubAckMessage = PubAckMessage; /** *发布消息 */ var PublishMessage = (function (_super) { __extends(PublishMessage, _super); function PublishMessage(header, two, three) { _super.call(this, (arguments.length == 1 && header instanceof RongIMLib.Header) ? header : arguments.length == 3 ? RongIMLib.Type.PUBLISH : 0); this._name = "PublishMessage"; this.binaryHelper = new RongIMLib.BinaryHelper(); this.syncMsg = false; if (arguments.length == 3) { this.topic = header; this.targetId = three; this.data = typeof two == "string" ? this.binaryHelper.toMQttString(two) : two; } } PublishMessage.prototype.messageLength = function () { var length = 10; length += this.binaryHelper.toMQttString(this.topic).length; length += this.binaryHelper.toMQttString(this.targetId).length; length += this.data.length; return length; }; PublishMessage.prototype.writeMessage = function (Out) { var out = this.binaryHelper.convertStream(Out); out.writeUTF(this.topic); out.writeUTF(this.targetId); RetryableMessage.prototype.writeMessage.apply(this, arguments); out.write(this.data); }; ; PublishMessage.prototype.readMessage = function (_in, msgLength) { var pos = 6; this.date = _in.readInt(); this.topic = _in.readUTF(); pos += this.binaryHelper.toMQttString(this.topic).length; this.targetId = _in.readUTF(); pos += this.binaryHelper.toMQttString(this.targetId).length; RetryableMessage.prototype.readMessage.apply(this, arguments); this.data = new Array(msgLength - pos); this.data = _in.read(this.data); }; ; PublishMessage.prototype.setTopic = function (x) { this.topic = x; }; PublishMessage.prototype.setData = function (x) { this.data = x; }; PublishMessage.prototype.setTargetId = function (x) { this.targetId = x; }; PublishMessage.prototype.setDate = function (x) { this.date = x; }; PublishMessage.prototype.setSyncMsg = function (x) { this.syncMsg = x; }; //是否是其他端同步过来的消息 PublishMessage.prototype.getSyncMsg = function () { return this.syncMsg; }; PublishMessage.prototype.getTopic = function () { return this.topic; }; PublishMessage.prototype.getData = function () { return this.data; }; PublishMessage.prototype.getTargetId = function () { return this.targetId; }; PublishMessage.prototype.getDate = function () { return this.date; }; return PublishMessage; })(RetryableMessage); RongIMLib.PublishMessage = PublishMessage; /** *请求查询 */ var QueryMessage = (function (_super) { __extends(QueryMessage, _super); function QueryMessage(header, two, three) { _super.call(this, header instanceof RongIMLib.Header ? header : arguments.length == 3 ? RongIMLib.Type.QUERY : null); this.binaryHelper = new RongIMLib.BinaryHelper(); this._name = "QueryMessage"; if (arguments.length == 3) { this.data = typeof two == "string" ? this.binaryHelper.toMQttString(two) : two; this.topic = header; this.targetId = three; } } QueryMessage.prototype.messageLength = function () { var length = 0; length += this.binaryHelper.toMQttString(this.topic).length; length += this.binaryHelper.toMQttString(this.targetId).length; length += 2; length += this.data.length; return length; }; QueryMessage.prototype.writeMessage = function (Out) { var out = this.binaryHelper.convertStream(Out); out.writeUTF(this.topic); out.writeUTF(this.targetId); RetryableMessage.prototype.writeMessage.call(this, out); out.write(this.data); }; QueryMessage.prototype.readMessage = function (_in, msgLength) { var pos = 0; this.topic = _in.readUTF(); this.targetId = _in.readUTF(); pos += this.binaryHelper.toMQttString(this.topic).length; pos += this.binaryHelper.toMQttString(this.targetId).length; this.readMessage.apply(this, arguments); pos += 2; this.data = new Array(msgLength - pos); _in.read(this.data); }; QueryMessage.prototype.setTopic = function (x) { this.topic = x; }; QueryMessage.prototype.setData = function (x) { this.data = x; }; QueryMessage.prototype.setTargetId = function (x) { this.targetId = x; }; QueryMessage.prototype.getTopic = function () { return this.topic; }; QueryMessage.prototype.getData = function () { return this.data; }; QueryMessage.prototype.getTargetId = function () { return this.targetId; }; return QueryMessage; })(RetryableMessage); RongIMLib.QueryMessage = QueryMessage; /** *请求查询确认 */ var QueryConMessage = (function (_super) { __extends(QueryConMessage, _super); function QueryConMessage(messageId) { _super.call(this, (messageId instanceof RongIMLib.Header) ? messageId : RongIMLib.Type.QUERYCON); this._name = "QueryConMessage"; if (!(messageId instanceof RongIMLib.Header)) { _super.prototype.setMessageId.call(this, messageId); } } return QueryConMessage; })(RetryableMessage); RongIMLib.QueryConMessage = QueryConMessage; /** *请求查询应答 */ var QueryAckMessage = (function (_super) { __extends(QueryAckMessage, _super); function QueryAckMessage(header) { _super.call(this, header); this._name = "QueryAckMessage"; this.binaryHelper = new RongIMLib.BinaryHelper(); } QueryAckMessage.prototype.readMessage = function (In, msgLength) { RetryableMessage.prototype.readMessage.call(this, In); this.date = In.readInt(); this.setStatus(In.read() * 256 + In.read()); if (msgLength > 0) { this.data = new Array(msgLength - 8); this.data = In.read(this.data); } }; QueryAckMessage.prototype.getData = function () { return this.data; }; QueryAckMessage.prototype.getStatus = function () { return this.status; }; QueryAckMessage.prototype.getDate = function () { return this.date; }; QueryAckMessage.prototype.setDate = function (x) { this.date = x; }; QueryAckMessage.prototype.setStatus = function (x) { this.status = x; }; QueryAckMessage.prototype.setData = function (x) { this.data = x; }; return QueryAckMessage; })(RetryableMessage); RongIMLib.QueryAckMessage = QueryAckMessage; })(RongIMLib || (RongIMLib = {})); /// var RongIMLib; (function (RongIMLib) { /** * 把消息对象写入流中 * 发送消息时用到 */ var MessageOutputStream = (function () { function MessageOutputStream(_out) { var binaryHelper = new RongIMLib.BinaryHelper(); this.out = binaryHelper.convertStream(_out); } MessageOutputStream.prototype.writeMessage = function (msg) { if (msg instanceof RongIMLib.BaseMessage) { msg.write(this.out); } }; return MessageOutputStream; })(); RongIMLib.MessageOutputStream = MessageOutputStream; /** * 流转换为消息对象 * 服务器返回消息时用到 */ var MessageInputStream = (function () { function MessageInputStream(In, isPolling) { if (!isPolling) { var _in = new RongIMLib.BinaryHelper().convertStream(In); this.flags = _in.readByte(); this._in = _in; } else { this.flags = In["headerCode"]; } this.header = new RongIMLib.Header(this.flags); this.isPolling = isPolling; this.In = In; } MessageInputStream.prototype.readMessage = function () { switch (this.header.getType()) { case 1: this.msg = new RongIMLib.ConnectMessage(this.header); break; case 2: this.msg = new RongIMLib.ConnAckMessage(this.header); break; case 3: this.msg = new RongIMLib.PublishMessage(this.header); this.msg.setSyncMsg(this.header.getSyncMsg()); break; case 4: this.msg = new RongIMLib.PubAckMessage(this.header); break; case 5: this.msg = new RongIMLib.QueryMessage(this.header); break; case 6: this.msg = new RongIMLib.QueryAckMessage(this.header); break; case 7: this.msg = new RongIMLib.QueryConMessage(this.header); break; case 9: case 11: case 13: this.msg = new RongIMLib.PingRespMessage(this.header); break; case 8: case 10: case 12: this.msg = new RongIMLib.PingReqMessage(this.header); break; case 14: this.msg = new RongIMLib.DisconnectMessage(this.header); break; default: throw new Error("No support for deserializing " + this.header.getType() + " messages"); } if (this.isPolling) { this.msg.init(this.In); } else { this.msg.read(this._in, this.In.length - 1); } return this.msg; }; return MessageInputStream; })(); RongIMLib.MessageInputStream = MessageInputStream; var Header = (function () { function Header(_type, _retain, _qos, _dup) { this.retain = false; this.qos = RongIMLib.Qos.AT_LEAST_ONCE; this.dup = false; this.syncMsg = false; if (_type && +_type == _type && arguments.length == 1) { this.retain = (_type & 1) > 0; this.qos = (_type & 6) >> 1; this.dup = (_type & 8) > 0; this.type = (_type >> 4) & 15; this.syncMsg = (_type & 8) == 8; } else { this.type = _type; this.retain = _retain; this.qos = _qos; this.dup = _dup; } } Header.prototype.getSyncMsg = function () { return this.syncMsg; }; Header.prototype.getType = function () { return this.type; }; Header.prototype.encode = function () { var me = this; switch (this.qos) { case RongIMLib.Qos[0]: me.qos = RongIMLib.Qos.AT_MOST_ONCE; break; case RongIMLib.Qos[1]: me.qos = RongIMLib.Qos.AT_LEAST_ONCE; break; case RongIMLib.Qos[2]: me.qos = RongIMLib.Qos.EXACTLY_ONCE; break; case RongIMLib.Qos[3]: me.qos = RongIMLib.Qos.DEFAULT; break; } var _byte = (this.type << 4); _byte |= this.retain ? 1 : 0; _byte |= this.qos << 1; _byte |= this.dup ? 8 : 0; return _byte; }; Header.prototype.toString = function () { return "Header [type=" + this.type + ",retain=" + this.retain + ",qos=" + this.qos + ",dup=" + this.dup + "]"; }; return Header; })(); RongIMLib.Header = Header; /** * 二进制帮助对象 */ var BinaryHelper = (function () { function BinaryHelper() { } BinaryHelper.prototype.writeUTF = function (str, isGetBytes) { var back = [], byteSize = 0; for (var i = 0, len = str.length; i < len; i++) { var code = str.charCodeAt(i); if (code >= 0 && code <= 127) { byteSize += 1; back.push(code); } else if (code >= 128 && code <= 2047) { byteSize += 2; back.push((192 | (31 & (code >> 6)))); back.push((128 | (63 & code))); } else if (code >= 2048 && code <= 65535) { byteSize += 3; back.push((224 | (15 & (code >> 12)))); back.push((128 | (63 & (code >> 6)))); back.push((128 | (63 & code))); } } for (var i = 0, len = back.length; i < len; i++) { if (back[i] > 255) { back[i] &= 255; } } if (isGetBytes) { return back; } if (byteSize <= 255) { return [0, byteSize].concat(back); } else { return [byteSize >> 8, byteSize & 255].concat(back); } }; BinaryHelper.prototype.readUTF = function (arr) { if (Object.prototype.toString.call(arr) == "[object String]") { return arr; } var UTF = "", _arr = arr; for (var i = 0, len = _arr.length; i < len; i++) { if (_arr[i] < 0) { _arr[i] += 256; } ; var one = _arr[i].toString(2), v = one.match(/^1+?(?=0)/); if (v && one.length == 8) { var bytesLength = v[0].length, // store = _arr[i].toString(2).slice(7 - bytesLength); store = ''; for (var st = 0; st < bytesLength; st++) { store += _arr[st + i].toString(2).slice(2); } UTF += String.fromCharCode(parseInt(store, 2)); i += bytesLength - 1; } else { UTF += String.fromCharCode(_arr[i]); } } return UTF; }; /** * [convertStream 将参数x转化为RongIMStream对象] * @param {any} x [参数] */ BinaryHelper.prototype.convertStream = function (x) { if (x instanceof RongIMStream) { return x; } else { return new RongIMStream(x); } }; BinaryHelper.prototype.toMQttString = function (str) { return this.writeUTF(str); }; return BinaryHelper; })(); RongIMLib.BinaryHelper = BinaryHelper; var RongIMStream = (function () { function RongIMStream(arr) { //当前流执行的起始位置 this.position = 0; //当前流写入的多少字节 this.writen = 0; this.poolLen = 0; this.binaryHelper = new BinaryHelper(); this.pool = arr; this.poolLen = arr.length; } RongIMStream.prototype.check = function () { return this.position >= this.pool.length; }; RongIMStream.prototype.readInt = function () { if (this.check()) { return -1; } var end = ""; for (var i = 0; i < 4; i++) { var t = this.pool[this.position++].toString(16); if (t.length == 1) { t = "0" + t; } end += t.toString(16); } return parseInt(end, 16); }; RongIMStream.prototype.readLong = function () { if (this.check()) { return -1; } var end = ""; for (var i = 0; i < 8; i++) { var t = this.pool[this.position++].toString(16); if (t.length == 1) { t = "0" + t; } end += t; } return parseInt(end, 16); }; RongIMStream.prototype.readTimestamp = function () { if (this.check()) { return -1; } var end = ""; for (var i = 0; i < 8; i++) { end += this.pool[this.position++].toString(16); } end = end.substring(2, 8); return parseInt(end, 16); }; RongIMStream.prototype.readUTF = function () { if (this.check()) { return -1; } var big = (this.readByte() << 8) | this.readByte(); return this.binaryHelper.readUTF(this.pool.subarray(this.position, this.position += big)); }; RongIMStream.prototype.readByte = function () { if (this.check()) { return -1; } var val = this.pool[this.position++]; if (val > 255) { val &= 255; } return val; }; RongIMStream.prototype.read = function (bytesArray) { if (bytesArray) { return this.pool.subarray(this.position, this.poolLen); } else { return this.readByte(); } }; RongIMStream.prototype.write = function (_byte) { var b = _byte; if (Object.prototype.toString.call(b).toLowerCase() == "[object array]") { [].push.apply(this.pool, b); } else { if (+b == b) { if (b > 255) { b &= 255; } this.pool.push(b); this.writen++; } } return b; }; RongIMStream.prototype.writeChar = function (v) { if (+v != v) { throw new Error("writeChar:arguments type is error"); } this.write(v >> 8 & 255); this.write(v & 255); this.writen += 2; }; RongIMStream.prototype.writeUTF = function (str) { var val = this.binaryHelper.writeUTF(str); [].push.apply(this.pool, val); this.writen += val.length; }; RongIMStream.prototype.toComplements = function () { var _tPool = this.pool; for (var i = 0; i < this.poolLen; i++) { if (_tPool[i] > 128) { _tPool[i] -= 256; } } return _tPool; }; RongIMStream.prototype.getBytesArray = function (isCom) { if (isCom) { return this.toComplements(); } return this.pool; }; return RongIMStream; })(); RongIMLib.RongIMStream = RongIMStream; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var SocketTransportation = (function () { /** * [constructor] * @param {string} url [连接地址:包含token、version] */ function SocketTransportation(_socket) { //连接状态 true:已连接 false:未连接 this.connected = false; //是否关闭: true:已关闭 false:未关闭 this.isClose = false; //存放消息队列的临时变量 this.queue = []; this.empty = new Function; this._socket = _socket; return this; } /** * [createTransport 创建WebScoket对象] */ SocketTransportation.prototype.createTransport = function (url, method) { if (!url) { throw new Error("URL can't be empty"); } ; this.url = url; var depend = RongIMLib.RongIMClient._memoryStore.depend; var wsScheme = depend.wsScheme; var tpl = '{wsScheme}{url}'; url = RongIMLib.RongUtil.tplEngine(tpl, { wsScheme: wsScheme, url: url }); this.socket = new WebSocket(url); this.socket.binaryType = "arraybuffer"; this.addEvent(); return this.socket; }; /** * [send 传送消息流] * @param {ArrayBuffer} data [二进制消息流] */ SocketTransportation.prototype.send = function (data) { if (!this.connected && !this.isClose) { //当通道不可用时,加入消息队列 this.queue.push(data); return; } if (this.isClose) { this._socket.fire("StatusChanged", RongIMLib.ConnectionStatus.CONNECTION_CLOSED); return; } var stream = new RongIMLib.RongIMStream([]), msg = new RongIMLib.MessageOutputStream(stream); msg.writeMessage(data); var val = stream.getBytesArray(true); var binary = new Int8Array(val); this.socket.send(binary.buffer); return this; }; /** * [onData 通道返回数据时调用的方法,用来想上层传递服务器返回的二进制消息流] * @param {ArrayBuffer} data [二进制消息流] */ SocketTransportation.prototype.onData = function (data) { if (RongIMLib.MessageUtil.isArray(data)) { this._socket.onMessage(new RongIMLib.MessageInputStream(data).readMessage()); } else { this._socket.onMessage(new RongIMLib.MessageInputStream(RongIMLib.MessageUtil.ArrayFormInput(data)).readMessage()); } return ""; }; /** * [onClose 通道关闭时触发的方法] */ SocketTransportation.prototype.onClose = function (ev) { var me = this; me.isClose = true; me.socket = this.empty; RongIMLib.Bridge._client.clearHeartbeat(); if (ev.code == 1006 && !this._status) { me._socket.fire("StatusChanged", RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE); } else { me._status = 0; } }; /** * [onError 通道报错时触发的方法] * @param {any} error [抛出异常] */ SocketTransportation.prototype.onError = function (error) { throw new Error(error); }; /** * [addEvent 为通道绑定事件] */ SocketTransportation.prototype.addEvent = function () { var self = this; self.socket.onopen = function () { self.connected = true; self.isClose = false; //通道可以用后,调用发送队列方法,把所有等得发送的消息发出 self.doQueue(); self._socket.fire("connect"); }; self.socket.onmessage = function (ev) { //判断数据是不是字符串,如果是字符串那么就是flash传过来的。 if (typeof ev.data == "string") { self.onData(ev.data.split(",")); } else { self.onData(ev.data); } }; self.socket.onerror = function (ev) { self.onError(ev); }; self.socket.onclose = function (ev) { self.onClose(ev); }; }; /** * [doQueue 消息队列,把队列中消息发出] */ SocketTransportation.prototype.doQueue = function () { var self = this; for (var i = 0, len = self.queue.length; i < len; i++) { self.send(self.queue[i]); } }; /** * [disconnect 断开连接] */ SocketTransportation.prototype.disconnect = function (status) { var me = this; if (me.socket.readyState) { me.isClose = true; if (status) { me._status = status; } me.socket.close(); } }; /** * [reconnect 重新连接] */ SocketTransportation.prototype.reconnect = function () { this.disconnect(); this.createTransport(this.url); }; SocketTransportation.prototype.close = function () { this.socket.close(); }; return SocketTransportation; })(); RongIMLib.SocketTransportation = SocketTransportation; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var PollingTransportation = (function () { function PollingTransportation(socket) { this.empty = new Function; this.connected = false; this.pid = +new Date + Math.random() + ""; this.queue = []; this.socket = socket; return this; } PollingTransportation.prototype.createTransport = function (url, method) { if (!url) { throw new Error("Url is empty,Please check it!"); } ; this.url = url; var sid = RongIMLib.RongIMClient._storageProvider.getItem("sId" + RongIMLib.Navigation.Endpoint.userId), me = this; if (sid) { setTimeout(function () { me.onSuccess("{\"status\":0,\"userId\":\"" + RongIMLib.Navigation.Endpoint.userId + "\",\"headerCode\":32,\"messageId\":0,\"sessionid\":\"" + sid + "\"}"); me.connected = true; }, 500); return this; } this.getRequest(url, true); return this; }; PollingTransportation.prototype.requestFactory = function (url, method, multipart) { var reqest = this.XmlHttpRequest(); if (multipart) { reqest.multipart = true; } reqest.timeout = 60000; reqest.open(method || "GET", RongIMLib.RongIMClient._memoryStore.depend.protocol + url); if (method == "POST" && "setRequestHeader" in reqest) { reqest.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=utf-8"); } return reqest; }; PollingTransportation.prototype.getRequest = function (url, isconnect) { var me = this; me.xhr = this.requestFactory(url + "&pid=" + encodeURIComponent(me.pid), "GET"); if ("onload" in me.xhr) { me.xhr.onload = function () { me.xhr.onload = me.empty; if (this.responseText == "lost params") { me.onError(); } else { me.onSuccess(this.responseText, isconnect); } }; me.xhr.onerror = function () { me.disconnect(); }; } else { me.xhr.onreadystatechange = function () { if (me.xhr.readyState == 4) { me.xhr.onreadystatechange = me.empty; if (/^(200|202)$/.test(me.xhr.status)) { me.onSuccess(me.xhr.responseText, isconnect); } else if (/^(400|403)$/.test(me.xhr.status)) { me.onError(); } else { me.disconnect(); } } }; } me.xhr.send(); }; /** * [send 发送消息,Method:POST] * queue 为消息队列,待通道可用发送所有等待消息 * @param {string} data [需要传入comet格式数据,此处只负责通讯通道,数据转换在外层处理] */ PollingTransportation.prototype.send = function (data) { var me = this; var _send = me.sendxhr = this.requestFactory(RongIMLib.Navigation.Endpoint.host + "/websocket" + data.url + "&pid=" + encodeURIComponent(me.pid), "POST"); if ("onload" in _send) { _send.onload = function () { _send.onload = me.empty; me.onData(_send.responseText); }; _send.onerror = function () { _send.onerror = me.empty; }; } else { _send.onreadystatechange = function () { if (_send.readyState == 4) { this.onreadystatechange = this.empty; if (/^(202|200)$/.test(_send.status)) { me.onData(_send.responseText); } } }; } _send.send(JSON.stringify(data.data)); }; PollingTransportation.prototype.onData = function (data, header) { if (!data || data == "lost params") { return; } var self = this, val = JSON.parse(data); if (val.userId) { RongIMLib.Navigation.Endpoint.userId = val.userId; } if (header) { RongIMLib.RongIMClient._storageProvider.setItem("sId" + RongIMLib.Navigation.Endpoint.userId, header); } if (!RongIMLib.MessageUtil.isArray(val)) { val = [val]; } Array.forEach(val, function (m) { self.socket.fire("message", new RongIMLib.MessageInputStream(m, true).readMessage()); }); return ""; }; PollingTransportation.prototype.XmlHttpRequest = function () { var hasCORS = typeof XMLHttpRequest !== "undefined" && "withCredentials" in new XMLHttpRequest(), self = this; if ("undefined" != typeof XMLHttpRequest && hasCORS) { return new XMLHttpRequest(); } else if ("undefined" != typeof XDomainRequest) { return new XDomainRequest(); } else { return new ActiveXObject("Microsoft.XMLHTTP"); } }; PollingTransportation.prototype.onClose = function () { if (this.xhr) { if (this.xhr.onload) { this.xhr.onreadystatechange = this.xhr.onload = this.empty; } else { this.xhr.onreadystatechange = this.empty; } this.xhr.abort(); this.xhr = null; } if (this.sendxhr) { if (this.sendxhr.onload) { this.sendxhr.onreadystatechange = this.sendxhr.onload = this.empty; } else { this.sendxhr.onreadystatechange = this.empty; } this.sendxhr.abort(); this.sendxhr = null; } }; PollingTransportation.prototype.disconnect = function () { RongIMLib.RongIMClient._storageProvider.removeItem("sId" + RongIMLib.Navigation.Endpoint.userId); RongIMLib.RongIMClient._storageProvider.removeItem(RongIMLib.Navigation.Endpoint.userId + "msgId"); this.onClose(); }; PollingTransportation.prototype.reconnect = function () { this.disconnect(); this.createTransport(this.url); }; PollingTransportation.prototype.onSuccess = function (responseText, isconnect) { var txt = responseText.match(/"sessionid":"\S+?(?=")/); this.onData(responseText, txt ? txt[0].slice(13) : 0); if (/"headerCode":-32,/.test(responseText)) { RongIMLib.RongIMClient._storageProvider.removeItem("sId" + RongIMLib.Navigation.Endpoint.userId); RongIMLib.RongIMClient._storageProvider.removeItem(RongIMLib.Navigation.Endpoint.userId + "msgId"); return; } this.getRequest(RongIMLib.Navigation.Endpoint.host + "/pullmsg.js?sessionid=" + RongIMLib.RongIMClient._storageProvider.getItem("sId" + RongIMLib.Navigation.Endpoint.userId) + "×trap=" + encodeURIComponent(new Date().getTime() + Math.random() + "")); this.connected = true; isconnect && this.socket.fire("connect"); }; PollingTransportation.prototype.onError = function () { RongIMLib.RongIMClient._storageProvider.removeItem("sId" + RongIMLib.Navigation.Endpoint.userId); RongIMLib.RongIMClient._storageProvider.removeItem(RongIMLib.Navigation.Endpoint.userId + "msgId"); this.onClose(); this.connected = false; this.socket.fire("disconnect"); }; PollingTransportation.prototype.close = function () { this.xhr.abort(); this.sendxhr = null; }; return PollingTransportation; })(); RongIMLib.PollingTransportation = PollingTransportation; })(RongIMLib || (RongIMLib = {})); //objectname映射 var typeMapping = { "RC:TxtMsg": "TextMessage", "RC:ImgMsg": "ImageMessage", "RC:VcMsg": "VoiceMessage", "RC:ImgTextMsg": "RichContentMessage", "RC:FileMsg": "FileMessage", "RC:LBSMsg": "LocationMessage", "RC:InfoNtf": "InformationNotificationMessage", "RC:ContactNtf": "ContactNotificationMessage", "RC:ProfileNtf": "ProfileNotificationMessage", "RC:CmdNtf": "CommandNotificationMessage", "RC:DizNtf": "DiscussionNotificationMessage", "RC:CmdMsg": "CommandMessage", "RC:TypSts": "TypingStatusMessage", "RC:CsChaR": "ChangeModeResponseMessage", "RC:CsHsR": "HandShakeResponseMessage", "RC:CsEnd": "TerminateMessage", "RC:CsSp": "SuspendMessage", "RC:CsUpdate": "CustomerStatusUpdateMessage", "RC:ReadNtf": "ReadReceiptMessage", "RC:VCAccept": "AcceptMessage", "RC:VCRinging": "RingingMessage", "RC:VCSummary": "SummaryMessage", "RC:VCHangup": "HungupMessage", "RC:VCInvite": "InviteMessage", "RC:VCModifyMedia": "MediaModifyMessage", "RC:VCModifyMem": "MemberModifyMessage", "RC:CsContact": "CustomerContact", "RC:PSImgTxtMsg": "PublicServiceRichContentMessage", "RC:PSMultiImgTxtMsg": "PublicServiceMultiRichContentMessage", "RC:GrpNtf": "GroupNotificationMessage", "RC:PSCmd": "PublicServiceCommandMessage", "RC:RcCmd": "RecallCommandMessage", "RC:SRSMsg": "SyncReadStatusMessage", "RC:RRReqMsg": "ReadReceiptRequestMessage", "RC:RRRspMsg": "ReadReceiptResponseMessage", "RCJrmf:RpMsg": "JrmfRedPacketMessage", "RCJrmf:RpOpendMsg": "JrmfRedPacketOpenedMessage" }, //自定义消息类型 registerMessageTypeMapping = {}, HistoryMsgType = { 4: "qryCMsg", 2: "qryDMsg", 3: "qryGMsg", 1: "qryPMsg", 6: "qrySMsg", 7: "qryPMsg", 8: "qryPMsg", 5: "qryCMsg" }, disconnectStatus = { 1: 6 }; var RongIMLib; (function (RongIMLib) { /** * 通道标识类 */ var Transportations = (function () { function Transportations() { } Transportations._TransportType = RongIMLib.Socket.WEBSOCKET; return Transportations; })(); RongIMLib.Transportations = Transportations; var SyncTimeUtil = (function () { function SyncTimeUtil() { } SyncTimeUtil.$getKey = function (message) { var client = RongIMLib.Bridge._client; var userId = client.userId; var direction = (message.messageDirection == 1 ? 'send' : 'receive'); var appkey = RongIMLib.RongIMClient._memoryStore.appKey; var tpl = '{appkey}_{userId}_{direction}box'; return RongIMLib.RongUtil.tplEngine(tpl, { appkey: appkey, userId: userId, direction: direction }); }; SyncTimeUtil.set = function (message) { var key = SyncTimeUtil.$getKey(message); var sentTime = message.sentTime; var storage = RongIMLib.RongIMClient._storageProvider; storage.setItem(key, sentTime); }; SyncTimeUtil.get = function () { var sent = SyncTimeUtil.$getKey({ messageDirection: RongIMLib.MessageDirection.SEND }); var received = SyncTimeUtil.$getKey({ messageDirection: RongIMLib.MessageDirection.RECEIVE }); var storage = RongIMLib.RongIMClient._storageProvider; return { sent: Number(storage.getItem(sent) || 0), received: Number(storage.getItem(received) || 0) }; }; return SyncTimeUtil; })(); RongIMLib.SyncTimeUtil = SyncTimeUtil; var MessageUtil = (function () { function MessageUtil() { } /** *4680000 为localstorage最小容量5200000字节的90%,超过90%将删除之前过早的存储 */ MessageUtil.checkStorageSize = function () { return JSON.stringify(localStorage).length < 4680000; }; MessageUtil.getFirstKey = function (obj) { var str = ""; for (var key in obj) { str = key; break; } return str; }; MessageUtil.isEmpty = function (obj) { var empty = true; for (var key in obj) { empty = false; break; } return empty; }; MessageUtil.ArrayForm = function (typearray) { if (Object.prototype.toString.call(typearray) == "[object ArrayBuffer]") { var arr = new Int8Array(typearray); return [].slice.call(arr); } return typearray; }; MessageUtil.ArrayFormInput = function (typearray) { if (Object.prototype.toString.call(typearray) == "[object ArrayBuffer]") { var arr = new Uint8Array(typearray); return arr; } return typearray; }; MessageUtil.indexOf = function (arr, item, from) { for (var l = arr.length, i = (from < 0) ? Math.max(0, +from) : from || 0; i < l; i++) { if (arr[i] == item) { return i; } } return -1; }; MessageUtil.isArray = function (obj) { return Object.prototype.toString.call(obj) == "[object Array]"; }; //遍历,只能遍历数组 MessageUtil.forEach = function (arr, func) { if ([].forEach) { return function (arr, func) { [].forEach.call(arr, func); }; } else { return function (arr, func) { for (var i = 0; i < arr.length; i++) { func.call(arr, arr[i], i, arr); } }; } }; MessageUtil.remove = function (array, func) { for (var i = 0, len = array.length; i < len; i++) { if (func(array[i])) { return array.splice(i, 1)[0]; } } return null; }; MessageUtil.int64ToTimestamp = function (obj, isDate) { if (obj.low === undefined) { return obj; } var low = obj.low; if (low < 0) { low += 0xffffffff + 1; } low = low.toString(16); var timestamp = parseInt(obj.high.toString(16) + "00000000".replace(new RegExp("0{" + low.length + "}$"), low), 16); if (isDate) { return new Date(timestamp); } return timestamp; }; //消息转换方法 MessageUtil.messageParser = function (entity, onReceived, offlineMsg) { var message = new RongIMLib.Message(), content = entity.content, de, objectName = entity.classname, val, isUseDef = false; try { if (RongIMLib.RongIMClient._memoryStore.depend.isPolling) { val = new RongIMLib.BinaryHelper().readUTF(content.offset ? MessageUtil.ArrayForm(content.buffer).slice(content.offset, content.limit) : content); de = JSON.parse(val); } else { val = new RongIMLib.BinaryHelper().readUTF(content.offset ? MessageUtil.ArrayFormInput(content.buffer).subarray(content.offset, content.limit) : content); de = JSON.parse(val); } } catch (ex) { de = val; isUseDef = true; } //映射为具体消息对象 if (objectName in typeMapping) { var str = "new RongIMLib." + typeMapping[objectName] + "(de)"; message.content = eval(str); message.messageType = typeMapping[objectName]; } else if (objectName in registerMessageTypeMapping) { var str = "new RongIMLib.RongIMClient.RegisterMessage." + registerMessageTypeMapping[objectName] + "(de)"; if (isUseDef) { message.content = eval(str).decode(de); } else { message.content = eval(str); } message.messageType = registerMessageTypeMapping[objectName]; } else { message.content = new RongIMLib.UnknownMessage({ content: de, objectName: objectName }); message.messageType = "UnknownMessage"; } //根据实体对象设置message对象] var dateTime = MessageUtil.int64ToTimestamp(entity.dataTime); if (dateTime > 0) { message.sentTime = dateTime; } else { message.sentTime = +new Date; } message.senderUserId = entity.fromUserId; message.conversationType = entity.type; if (entity.fromUserId == RongIMLib.Bridge._client.userId && !entity.groupId && entity.type !== RongIMLib.ConversationType.GROUP) { message.targetId = entity.fromUserId; } // 自己给自己发消息, targetId 为 '' else if (entity.fromUserId == RongIMLib.Bridge._client.userId) { message.targetId = entity.groupId; } else { message.targetId = (/^[234]$/.test(entity.type || entity.getType()) ? entity.groupId : message.senderUserId); } if (entity.direction == 1) { message.messageDirection = RongIMLib.MessageDirection.SEND; message.senderUserId = RongIMLib.Bridge._client.userId; } else { if (message.senderUserId == RongIMLib.Bridge._client.userId) { message.messageDirection = RongIMLib.MessageDirection.SEND; } else { message.messageDirection = RongIMLib.MessageDirection.RECEIVE; } } message.messageDirection = entity.direction === 1 || entity.direction === -1 ? 1 : 2; message.messageUId = entity.msgId; message.receivedTime = new Date().getTime(); message.messageId = (message.conversationType + "_" + ~~(Math.random() * 0xffffff)); message.objectName = objectName; message.receivedStatus = RongIMLib.ReceivedStatus.READ; if ((entity.status & 2) == 2) { message.receivedStatus = RongIMLib.ReceivedStatus.RETRIEVED; } message.offLineMessage = offlineMsg ? true : false; if (!offlineMsg) { if (RongIMLib.RongIMClient._memoryStore.connectAckTime > message.sentTime) { message.offLineMessage = true; } } return message; }; //适配SSL // static schemeArrs: Array = [["http", "ws"], ["https", "wss"]]; MessageUtil.sign = { converNum: 1, msgNum: 1, isMsgStart: true, isConvStart: true }; return MessageUtil; })(); RongIMLib.MessageUtil = MessageUtil; /** * 工具类 */ var MessageIdHandler = (function () { function MessageIdHandler() { } MessageIdHandler.init = function () { this.messageId = +(RongIMLib.RongIMClient._storageProvider.getItem(RongIMLib.Navigation.Endpoint.userId + "msgId") || RongIMLib.RongIMClient._storageProvider.setItem(RongIMLib.Navigation.Endpoint.userId + "msgId", 0) || 0); }; MessageIdHandler.messageIdPlus = function (method) { RongIMLib.RongIMClient._memoryStore.depend.isPolling && this.init(); if (this.messageId >= 65535) { method(); return false; } this.messageId++; RongIMLib.RongIMClient._memoryStore.depend.isPolling && RongIMLib.RongIMClient._storageProvider.setItem(RongIMLib.Navigation.Endpoint.userId + "msgId", this.messageId); return this.messageId; }; MessageIdHandler.clearMessageId = function () { this.messageId = 0; RongIMLib.RongIMClient._memoryStore.depend.isPolling && RongIMLib.RongIMClient._storageProvider.setItem(RongIMLib.Navigation.Endpoint.userId + "msgId", this.messageId); }; MessageIdHandler.getMessageId = function () { RongIMLib.RongIMClient._memoryStore.depend.isPolling && this.init(); return this.messageId; }; MessageIdHandler.messageId = 0; return MessageIdHandler; })(); RongIMLib.MessageIdHandler = MessageIdHandler; var RongInnerTools = (function () { function RongInnerTools() { } RongInnerTools.convertUserStatus = function (entity) { entity = RongIMLib.RongUtil.rename(entity, { subUserId: 'userId' }); var status = JSON.parse(entity.status); var us = status.us; if (!us) { return entity; } entity.status = RongIMLib.RongUtil.rename(us, { o: 'online', 'p': 'platform', s: 'status' }); return entity; }; return RongInnerTools; })(); RongIMLib.RongInnerTools = RongInnerTools; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var MessageContent = (function () { function MessageContent(data) { throw new Error("This method is abstract, you must implement this method in inherited class."); } MessageContent.obtain = function () { throw new Error("This method is abstract, you must implement this method in inherited class."); }; return MessageContent; })(); RongIMLib.MessageContent = MessageContent; var NotificationMessage = (function (_super) { __extends(NotificationMessage, _super); function NotificationMessage() { _super.apply(this, arguments); } return NotificationMessage; })(MessageContent); RongIMLib.NotificationMessage = NotificationMessage; var StatusMessage = (function (_super) { __extends(StatusMessage, _super); function StatusMessage() { _super.apply(this, arguments); } return StatusMessage; })(MessageContent); RongIMLib.StatusMessage = StatusMessage; var ModelUtil = (function () { function ModelUtil() { } ModelUtil.modelClone = function (object) { var obj = {}; for (var item in object) { if (item != "messageName" && "encode" != item) { obj[item] = object[item]; } } return obj; }; ModelUtil.modleCreate = function (fields, msgType) { if (fields.length < 1) { throw new Error("Array is empty -> registerMessageType.modleCreate"); } var Object = function (message) { var me = this; for (var index in fields) { me[fields[index]] = message[fields[index]]; } Object.prototype.messageName = msgType; Object.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; }; return Object; }; return ModelUtil; })(); RongIMLib.ModelUtil = ModelUtil; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var CustomerStatusMessage = (function () { function CustomerStatusMessage(message) { this.messageName = "CustomerStatusMessage"; this.status = message.status; } CustomerStatusMessage.obtain = function () { return null; }; CustomerStatusMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return CustomerStatusMessage; })(); RongIMLib.CustomerStatusMessage = CustomerStatusMessage; /** * 客服转换响应消息的类型名 */ var ChangeModeResponseMessage = (function () { function ChangeModeResponseMessage(message) { this.messageName = "ChangeModeResponseMessage"; this.code = message.code; this.data = message.data; this.msg = message.msg; } ChangeModeResponseMessage.obtain = function () { return null; }; ChangeModeResponseMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ChangeModeResponseMessage; })(); RongIMLib.ChangeModeResponseMessage = ChangeModeResponseMessage; /** * 客服转换消息的类型名 * 此消息不计入未读消息数 */ var ChangeModeMessage = (function () { function ChangeModeMessage(message) { this.messageName = "ChangeModeMessage"; this.uid = message.uid; this.sid = message.sid; this.pid = message.pid; } ChangeModeMessage.obtain = function () { return null; }; ChangeModeMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ChangeModeMessage; })(); RongIMLib.ChangeModeMessage = ChangeModeMessage; var CustomerStatusUpdateMessage = (function () { function CustomerStatusUpdateMessage(message) { this.messageName = "CustomerStatusUpdateMessage"; this.serviceStatus = message.serviceStatus; this.sid = message.sid; } CustomerStatusUpdateMessage.obtain = function () { return null; }; CustomerStatusUpdateMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return CustomerStatusUpdateMessage; })(); RongIMLib.CustomerStatusUpdateMessage = CustomerStatusUpdateMessage; var HandShakeMessage = (function () { function HandShakeMessage(message) { this.messageName = "HandShakeMessage"; if (message) { this.requestInfo = message.requestInfo; this.userInfo = message.userInfo; } } HandShakeMessage.obtain = function () { return null; }; HandShakeMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return HandShakeMessage; })(); RongIMLib.HandShakeMessage = HandShakeMessage; var CustomerContact = (function () { function CustomerContact(message) { this.messageName = "CustomerContact"; this.page = message.page; this.nickName = message.nickName; this.routingInfo = message.routingInfo; this.info = message.info; this.requestInfo = message.requestInfo; } CustomerContact.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return CustomerContact; })(); RongIMLib.CustomerContact = CustomerContact; var EvaluateMessage = (function () { function EvaluateMessage(message) { this.messageName = "EvaluateMessage"; this.uid = message.uid; this.sid = message.sid; this.pid = message.pid; this.source = message.source; this.suggest = message.suggest; this.isresolve = message.isresolve; this.type = message.type; } EvaluateMessage.obtain = function () { return null; }; EvaluateMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return EvaluateMessage; })(); RongIMLib.EvaluateMessage = EvaluateMessage; /** * 客服握手响应消息的类型名 */ var HandShakeResponseMessage = (function () { function HandShakeResponseMessage(message) { this.messageName = "HandShakeResponseMessage"; this.msg = message.msg; this.status = message.status; this.data = message.data; } HandShakeResponseMessage.obtain = function () { return null; }; HandShakeResponseMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return HandShakeResponseMessage; })(); RongIMLib.HandShakeResponseMessage = HandShakeResponseMessage; var SuspendMessage = (function () { function SuspendMessage(message) { this.messageName = "SuspendMessage"; this.uid = message.uid; this.sid = message.sid; this.pid = message.pid; } SuspendMessage.obtain = function () { return null; }; SuspendMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return SuspendMessage; })(); RongIMLib.SuspendMessage = SuspendMessage; var TerminateMessage = (function () { function TerminateMessage(message) { this.messageName = "TerminateMessage"; this.code = message.code; this.msg = message.msg; this.sid = message.sid; } TerminateMessage.obtain = function () { return null; }; TerminateMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return TerminateMessage; })(); RongIMLib.TerminateMessage = TerminateMessage; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var IsTypingStatusMessage = (function () { function IsTypingStatusMessage(data) { this.messageName = "IsTypingStatusMessage"; var msg = data; } IsTypingStatusMessage.prototype.encode = function () { return undefined; }; IsTypingStatusMessage.prototype.getMessage = function () { return null; }; return IsTypingStatusMessage; })(); RongIMLib.IsTypingStatusMessage = IsTypingStatusMessage; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var InformationNotificationMessage = (function () { function InformationNotificationMessage(message) { this.messageName = "InformationNotificationMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> InformationNotificationMessage."); } this.message = message.message; this.extra = message.extra; if (message.user) { this.user = message.user; } } InformationNotificationMessage.obtain = function (message) { return new InformationNotificationMessage({ message: message, extra: "" }); }; InformationNotificationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return InformationNotificationMessage; })(); RongIMLib.InformationNotificationMessage = InformationNotificationMessage; var CommandMessage = (function () { function CommandMessage(message) { this.messageName = "CommandMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> CommandMessage."); } try { if (Object.prototype.toString.call(message.data) == "[object String]") { this.data = JSON.parse(message.data); } else { this.data = message.data; } } catch (e) { this.data = message.data; } this.name = message.name; this.extra = message.extra; } CommandMessage.obtain = function (data) { return new CommandMessage({ data: data, extra: "" }); }; CommandMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return CommandMessage; })(); RongIMLib.CommandMessage = CommandMessage; var ContactNotificationMessage = (function () { function ContactNotificationMessage(message) { this.messageName = "ContactNotificationMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> ContactNotificationMessage."); } this.operation = message.operation; this.targetUserId = message.targetUserId; this.message = message.message; this.extra = message.extra; this.sourceUserId = message.sourceUserId; if (message.user) { this.user = message.user; } } ContactNotificationMessage.obtain = function (operation, sourceUserId, targetUserId, message) { return new InformationNotificationMessage({ operation: operation, sourceUserId: sourceUserId, targetUserId: targetUserId, message: message }); }; ContactNotificationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; ContactNotificationMessage.CONTACT_OPERATION_ACCEPT_RESPONSE = "ContactOperationAcceptResponse"; ContactNotificationMessage.CONTACT_OPERATION_REJECT_RESPONSE = "ContactOperationRejectResponse"; ContactNotificationMessage.CONTACT_OPERATION_REQUEST = "ContactOperationRequest"; return ContactNotificationMessage; })(); RongIMLib.ContactNotificationMessage = ContactNotificationMessage; var ProfileNotificationMessage = (function () { function ProfileNotificationMessage(message) { this.messageName = "ProfileNotificationMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> ProfileNotificationMessage."); } this.operation = message.operation; try { if (Object.prototype.toString.call(message.data) == "[object String]") { this.data = JSON.parse(message.data); } else { this.data = message.data; } } catch (e) { this.data = message.data; } this.extra = message.extra; if (message.user) { this.user = message.user; } } ProfileNotificationMessage.obtain = function (operation, data) { return new ProfileNotificationMessage({ operation: operation, data: data }); }; ProfileNotificationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ProfileNotificationMessage; })(); RongIMLib.ProfileNotificationMessage = ProfileNotificationMessage; var CommandNotificationMessage = (function () { function CommandNotificationMessage(message) { this.messageName = "CommandNotificationMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> ProfileNotificationMessage."); } try { if (Object.prototype.toString.call(message.data) == "[object String]") { this.data = JSON.parse(message.data); } else { this.data = message.data; } } catch (e) { this.data = message.data; } this.name = message.name; this.extra = message.extra; if (message.user) { this.user = message.user; } } CommandNotificationMessage.obtain = function (name, data) { return new CommandNotificationMessage({ name: name, data: data, extra: "" }); }; CommandNotificationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return CommandNotificationMessage; })(); RongIMLib.CommandNotificationMessage = CommandNotificationMessage; var DiscussionNotificationMessage = (function () { function DiscussionNotificationMessage(message) { this.messageName = "DiscussionNotificationMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> DiscussionNotificationMessage."); } this.extra = message.extra; this.extension = message.extension; this.type = message.type; this.isHasReceived = message.isHasReceived; this.operation = message.operation; this.user = message.user; if (message.user) { this.user = message.user; } } DiscussionNotificationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return DiscussionNotificationMessage; })(); RongIMLib.DiscussionNotificationMessage = DiscussionNotificationMessage; var GroupNotificationMessage = (function () { function GroupNotificationMessage(msg) { this.messageName = "GroupNotificationMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> GroupNotificationMessage."); } msg.operatorUserId && (this.operatorUserId = msg.operatorUserId); msg.operation && (this.operation = msg.operation); msg.data && (this.data = msg.data); msg.message && (this.message = msg.message); msg.extra && (this.extra = msg.extra); } GroupNotificationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return GroupNotificationMessage; })(); RongIMLib.GroupNotificationMessage = GroupNotificationMessage; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var TextMessage = (function () { function TextMessage(message) { this.messageName = "TextMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> TextMessage."); } this.content = message.content; this.extra = message.extra; if (message.user) { this.user = message.user; } if (message.mentionedInfo) { this.mentionedInfo = message.mentionedInfo; } } TextMessage.obtain = function (text) { return new TextMessage({ extra: "", content: text }); }; TextMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return TextMessage; })(); RongIMLib.TextMessage = TextMessage; var TypingStatusMessage = (function () { function TypingStatusMessage(message) { this.messageName = "TypingStatusMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> TypingStatusMessage."); } this.typingContentType = message.typingContentType; this.data = message.data; } TypingStatusMessage.obtain = function (typingContentType, data) { return new TypingStatusMessage({ typingContentType: typingContentType, data: data }); }; TypingStatusMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return TypingStatusMessage; })(); RongIMLib.TypingStatusMessage = TypingStatusMessage; var ReadReceiptMessage = (function () { function ReadReceiptMessage(message) { this.messageName = "ReadReceiptMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> ReadReceiptMessage."); } this.lastMessageSendTime = message.lastMessageSendTime; this.messageUId = message.messageUId; this.type = message.type; } ReadReceiptMessage.obtain = function (messageUId, lastMessageSendTime, type) { return new ReadReceiptMessage({ messageUId: messageUId, lastMessageSendTime: lastMessageSendTime, type: type }); }; ReadReceiptMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ReadReceiptMessage; })(); RongIMLib.ReadReceiptMessage = ReadReceiptMessage; var VoiceMessage = (function () { function VoiceMessage(message) { this.messageName = "VoiceMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> VoiceMessage."); } this.content = message.content; this.duration = message.duration; this.extra = message.extra; if (message.user) { this.user = message.user; } if (message.mentionedInfo) { this.mentionedInfo = message.mentionedInfo; } } VoiceMessage.obtain = function (base64Content, duration) { return new VoiceMessage({ content: base64Content, duration: duration, extra: "" }); }; VoiceMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return VoiceMessage; })(); RongIMLib.VoiceMessage = VoiceMessage; var RecallCommandMessage = (function () { function RecallCommandMessage(message) { this.messageName = "RecallCommandMessage"; this.messageUId = message.messageUId; this.conversationType = message.conversationType; this.targetId = message.targetId; this.sentTime = message.sentTime; message.extra && (this.extra = message.extra); message.user && (this.user = message.user); } RecallCommandMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return RecallCommandMessage; })(); RongIMLib.RecallCommandMessage = RecallCommandMessage; var ImageMessage = (function () { function ImageMessage(message) { this.messageName = "ImageMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> ImageMessage."); } this.content = message.content; this.imageUri = message.imageUri; message.extra && (this.extra = message.extra); message.user && (this.user = message.user); if (message.mentionedInfo) { this.mentionedInfo = message.mentionedInfo; } } ImageMessage.obtain = function (content, imageUri) { return new ImageMessage({ content: content, imageUri: imageUri, extra: "" }); }; ImageMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ImageMessage; })(); RongIMLib.ImageMessage = ImageMessage; var LocationMessage = (function () { function LocationMessage(message) { this.messageName = "LocationMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> LocationMessage."); } this.latitude = message.latitude; this.longitude = message.longitude; this.poi = message.poi; this.content = message.content; this.extra = message.extra; if (message.user) { this.user = message.user; } if (message.mentionedInfo) { this.mentionedInfo = message.mentionedInfo; } } LocationMessage.obtain = function (latitude, longitude, poi, content) { return new LocationMessage({ latitude: latitude, longitude: longitude, poi: poi, content: content, extra: "" }); }; LocationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return LocationMessage; })(); RongIMLib.LocationMessage = LocationMessage; var RichContentMessage = (function () { function RichContentMessage(message) { this.messageName = "RichContentMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> RichContentMessage."); } this.title = message.title; this.content = message.content; this.imageUri = message.imageUri; this.extra = message.extra; this.url = message.url; if (message.user) { this.user = message.user; } } RichContentMessage.obtain = function (title, content, imageUri, url) { return new RichContentMessage({ title: title, content: content, imageUri: imageUri, url: url, extra: "" }); }; RichContentMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return RichContentMessage; })(); RongIMLib.RichContentMessage = RichContentMessage; var JrmfRedPacketMessage = (function () { function JrmfRedPacketMessage(message) { this.messageName = 'JrmfRedPacketMessage'; message && (this.message = message); } JrmfRedPacketMessage.prototype.encode = function () { return ""; }; return JrmfRedPacketMessage; })(); RongIMLib.JrmfRedPacketMessage = JrmfRedPacketMessage; var JrmfRedPacketOpenedMessage = (function () { function JrmfRedPacketOpenedMessage(message) { this.messageName = 'JrmfRedPacketOpenedMessage'; message && (this.message = message); } JrmfRedPacketOpenedMessage.prototype.encode = function () { return ""; }; return JrmfRedPacketOpenedMessage; })(); RongIMLib.JrmfRedPacketOpenedMessage = JrmfRedPacketOpenedMessage; var UnknownMessage = (function () { function UnknownMessage(message) { this.messageName = "UnknownMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> UnknownMessage."); } this.message = message; } UnknownMessage.prototype.encode = function () { return ""; }; return UnknownMessage; })(); RongIMLib.UnknownMessage = UnknownMessage; var PublicServiceCommandMessage = (function () { function PublicServiceCommandMessage(message) { this.messageName = "PublicServiceCommandMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> PublicServiceCommandMessage."); } this.content = message.content; this.extra = message.extra; this.menuItem = message.menuItem; if (message.user) { this.user = message.user; } if (message.mentionedInfo) { this.mentionedInfo = message.mentionedInfo; } } PublicServiceCommandMessage.obtain = function (item) { return new PublicServiceCommandMessage({ content: "", command: "", menuItem: item, extra: "" }); }; PublicServiceCommandMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return PublicServiceCommandMessage; })(); RongIMLib.PublicServiceCommandMessage = PublicServiceCommandMessage; var PublicServiceMultiRichContentMessage = (function () { function PublicServiceMultiRichContentMessage(messages) { this.messageName = "PublicServiceMultiRichContentMessage"; this.richContentMessages = messages; } PublicServiceMultiRichContentMessage.prototype.encode = function () { return null; }; return PublicServiceMultiRichContentMessage; })(); RongIMLib.PublicServiceMultiRichContentMessage = PublicServiceMultiRichContentMessage; var SyncReadStatusMessage = (function () { function SyncReadStatusMessage(message) { this.messageName = "SyncReadStatusMessage"; message.lastMessageSendTime && (this.lastMessageSendTime = message.lastMessageSendTime); } SyncReadStatusMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return SyncReadStatusMessage; })(); RongIMLib.SyncReadStatusMessage = SyncReadStatusMessage; var ReadReceiptRequestMessage = (function () { function ReadReceiptRequestMessage(message) { this.messageName = "ReadReceiptRequestMessage"; message.messageUId && (this.messageUId = message.messageUId); } ReadReceiptRequestMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ReadReceiptRequestMessage; })(); RongIMLib.ReadReceiptRequestMessage = ReadReceiptRequestMessage; var ReadReceiptResponseMessage = (function () { function ReadReceiptResponseMessage(message) { this.messageName = "ReadReceiptResponseMessage"; message.receiptMessageDic && (this.receiptMessageDic = message.receiptMessageDic); } ReadReceiptResponseMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ReadReceiptResponseMessage; })(); RongIMLib.ReadReceiptResponseMessage = ReadReceiptResponseMessage; var PublicServiceRichContentMessage = (function () { function PublicServiceRichContentMessage(message) { this.messageName = "PublicServiceRichContentMessage"; this.richContentMessage = message; } PublicServiceRichContentMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return PublicServiceRichContentMessage; })(); RongIMLib.PublicServiceRichContentMessage = PublicServiceRichContentMessage; var FileMessage = (function () { function FileMessage(message) { this.messageName = "FileMessage"; message.name && (this.name = message.name); message.size && (this.size = message.size); message.type && (this.type = message.type); message.fileUrl && (this.fileUrl = message.fileUrl); message.extra && (this.extra = message.extra); message.user && (this.user = message.user); } FileMessage.obtain = function (msg) { return new FileMessage({ name: msg.name, size: msg.size, type: msg.type, fileUrl: msg.fileUrl }); }; FileMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return FileMessage; })(); RongIMLib.FileMessage = FileMessage; var AcceptMessage = (function () { function AcceptMessage(message) { this.messageName = "AcceptMessage"; this.mediaId = message.mediaId; this.callId = message.callId; this.mediaType = message.mediaType; this.mode = message.mode; this.subInfo = message.subInfo; } AcceptMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return AcceptMessage; })(); RongIMLib.AcceptMessage = AcceptMessage; var RingingMessage = (function () { function RingingMessage(message) { this.messageName = "RingingMessage"; this.callId = message.callId; } RingingMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return RingingMessage; })(); RongIMLib.RingingMessage = RingingMessage; var SummaryMessage = (function () { function SummaryMessage(message) { this.messageName = "SummaryMessage"; this.caller = message.caller; this.inviter = message.inviter; this.mediaType = message.mediaType; this.memberIdList = message.memberIdList; this.startTime = message.startTime; this.connectedTime = message.connectedTime; this.duration = message.duration; this.status = message.status; } SummaryMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return SummaryMessage; })(); RongIMLib.SummaryMessage = SummaryMessage; var HungupMessage = (function () { function HungupMessage(message) { this.messageName = "HungupMessage"; this.callId = message.callId; this.reason = message.reason; this.mode = message.mode; this.subInfo = message.subInfo; } HungupMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return HungupMessage; })(); RongIMLib.HungupMessage = HungupMessage; var InviteMessage = (function () { function InviteMessage(message) { this.messageName = "InviteMessage"; this.mediaId = message.mediaId; this.callId = message.callId; this.engineType = message.engineType; this.channelInfo = message.channelInfo; this.mediaType = message.mediaType; this.extra = message.extra; this.inviteUserIds = message.inviteUserIds; this.observerUserIds = message.observerUserIds; this.mode = message.mode; this.subInfo = message.subInfo; } InviteMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return InviteMessage; })(); RongIMLib.InviteMessage = InviteMessage; var MediaModifyMessage = (function () { function MediaModifyMessage(message) { this.messageName = "MediaModifyMessage"; this.callId = message.callId; this.mediaType = message.mediaType; this.mode = message.mode; this.subInfo = message.subInfo; } MediaModifyMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return MediaModifyMessage; })(); RongIMLib.MediaModifyMessage = MediaModifyMessage; var MemberModifyMessage = (function () { function MemberModifyMessage(message) { this.messageName = "MemberModifyMessage"; this.modifyMemType = message.modifyMemType; this.callId = message.callId; this.caller = message.caller; this.engineType = message.engineType; this.channelInfo = message.channelInfo; this.mediaType = message.mediaType; this.extra = message.extra; this.inviteUserIds = message.inviteUserIds; this.existedMemberStatusList = message.existedMemberStatusList; this.existedUserPofiles = message.existedUserPofiles; this.observerUserIds = message.observerUserIds; this.mode = message.mode; this.subInfo = message.subInfo; } MemberModifyMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return MemberModifyMessage; })(); RongIMLib.MemberModifyMessage = MemberModifyMessage; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var ChannelInfo = (function () { function ChannelInfo(Id, Key) { this.Id = Id; this.Key = Key; } return ChannelInfo; })(); RongIMLib.ChannelInfo = ChannelInfo; var UserStatus = (function () { function UserStatus(platform, online, status) { this.platform = platform; this.online = online; this.status = status; } return UserStatus; })(); RongIMLib.UserStatus = UserStatus; var MentionedInfo = (function () { function MentionedInfo(type, userIdList, mentionedContent) { } return MentionedInfo; })(); RongIMLib.MentionedInfo = MentionedInfo; var DeleteMessage = (function () { function DeleteMessage(msgId, msgDataTime, direct) { this.msgId = msgId; this.msgDataTime = msgDataTime; this.direct = direct; } return DeleteMessage; })(); RongIMLib.DeleteMessage = DeleteMessage; var CustomServiceConfig = (function () { function CustomServiceConfig(isBlack, companyName, companyUrl) { } return CustomServiceConfig; })(); RongIMLib.CustomServiceConfig = CustomServiceConfig; var CustomServiceSession = (function () { function CustomServiceSession(uid, cid, pid, isQuited, type, adminHelloWord, adminOfflineWord) { } return CustomServiceSession; })(); RongIMLib.CustomServiceSession = CustomServiceSession; var Conversation = (function () { function Conversation(conversationTitle, conversationType, draft, isTop, latestMessage, latestMessageId, notificationStatus, objectName, receivedStatus, receivedTime, senderUserId, senderUserName, sentStatus, sentTime, targetId, unreadMessageCount, senderPortraitUri, isHidden, mentionedMsg, hasUnreadMention, _readTime) { this.conversationTitle = conversationTitle; this.conversationType = conversationType; this.draft = draft; this.isTop = isTop; this.latestMessage = latestMessage; this.latestMessageId = latestMessageId; this.notificationStatus = notificationStatus; this.objectName = objectName; this.receivedStatus = receivedStatus; this.receivedTime = receivedTime; this.senderUserId = senderUserId; this.senderUserName = senderUserName; this.sentStatus = sentStatus; this.sentTime = sentTime; this.targetId = targetId; this.unreadMessageCount = unreadMessageCount; this.senderPortraitUri = senderPortraitUri; this.isHidden = isHidden; this.mentionedMsg = mentionedMsg; this.hasUnreadMention = hasUnreadMention; this._readTime = _readTime; } Conversation.prototype.setTop = function () { RongIMLib.RongIMClient._dataAccessProvider.addConversation(this, { onSuccess: function (data) { } }); }; return Conversation; })(); RongIMLib.Conversation = Conversation; var Discussion = (function () { function Discussion(creatorId, id, memberIdList, name, isOpen) { this.creatorId = creatorId; this.id = id; this.memberIdList = memberIdList; this.name = name; this.isOpen = isOpen; } return Discussion; })(); RongIMLib.Discussion = Discussion; var Group = (function () { function Group(id, name, portraitUri) { this.id = id; this.name = name; this.portraitUri = portraitUri; } return Group; })(); RongIMLib.Group = Group; var Message = (function () { function Message(content, conversationType, extra, objectName, messageDirection, messageId, receivedStatus, receivedTime, senderUserId, sentStatus, sentTime, targetId, messageType, messageUId, isLocalMessage, offLineMessage, receiptResponse) { this.content = content; this.conversationType = conversationType; this.extra = extra; this.objectName = objectName; this.messageDirection = messageDirection; this.messageId = messageId; this.receivedStatus = receivedStatus; this.receivedTime = receivedTime; this.senderUserId = senderUserId; this.sentStatus = sentStatus; this.sentTime = sentTime; this.targetId = targetId; this.messageType = messageType; this.messageUId = messageUId; this.isLocalMessage = isLocalMessage; this.offLineMessage = offLineMessage; this.receiptResponse = receiptResponse; } return Message; })(); RongIMLib.Message = Message; var MessageTag = (function () { function MessageTag(isCounted, isPersited) { this.isCounted = isCounted; this.isPersited = isPersited; } MessageTag.prototype.getMessageTag = function () { if (this.isCounted && this.isPersited) { return 3; } else if (this.isCounted) { return 2; } else if (this.isPersited) { return 1; } else if (!this.isCounted && !this.isPersited) { return 0; } }; MessageTag.getTagByStatus = function (status) { var statusMap = { 3: { isCounted: true, isPersited: true }, 2: { isCounted: true, isPersited: false }, 1: { isCounted: true, isPersited: true }, 0: { isCounted: true, isPersited: true } }; return statusMap[status] || statusMap[3]; }; return MessageTag; })(); RongIMLib.MessageTag = MessageTag; var PublicServiceMenuItem = (function () { function PublicServiceMenuItem(id, name, type, sunMenuItems, url) { this.id = id; this.name = name; this.type = type; this.sunMenuItems = sunMenuItems; this.url = url; } return PublicServiceMenuItem; })(); RongIMLib.PublicServiceMenuItem = PublicServiceMenuItem; // TODO: TBD var PublicServiceProfile = (function () { function PublicServiceProfile(conversationType, introduction, menu, name, portraitUri, publicServiceId, hasFollowed, isGlobal) { this.conversationType = conversationType; this.introduction = introduction; this.menu = menu; this.name = name; this.portraitUri = portraitUri; this.publicServiceId = publicServiceId; this.hasFollowed = hasFollowed; this.isGlobal = isGlobal; } return PublicServiceProfile; })(); RongIMLib.PublicServiceProfile = PublicServiceProfile; var UserInfo = (function () { function UserInfo(id, name, portraitUri) { this.id = id; this.name = name; this.portraitUri = portraitUri; } return UserInfo; })(); RongIMLib.UserInfo = UserInfo; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var ServerDataProvider = (function () { function ServerDataProvider() { this.userStatusListener = null; } ServerDataProvider.prototype.init = function (appKey, options) { new RongIMLib.FeatureDectector(options.appCallback); }; ServerDataProvider.prototype.connect = function (token, callback, userId, option) { RongIMLib.RongIMClient.bridge = RongIMLib.Bridge.getInstance(); RongIMLib.RongIMClient._memoryStore.token = token; RongIMLib.RongIMClient._memoryStore.callback = callback; userId = userId || ''; option = option || {}; var isConnecting = false, isConnected = false; if (RongIMLib.Bridge._client && RongIMLib.Bridge._client.channel) { isConnecting = (RongIMLib.Bridge._client.channel.connectionStatus == RongIMLib.ConnectionStatus.CONNECTING); isConnected = (RongIMLib.Bridge._client.channel.connectionStatus == RongIMLib.ConnectionStatus.CONNECTED); } if (isConnected || isConnecting) { return; } var isGreater = (RongIMLib.RongIMClient.otherDeviceLoginCount > 5); if (isGreater) { callback.onError(RongIMLib.ConnectionStatus.ULTRALIMIT); return; } // 清除本地导航缓存 if (option.force) { RongIMLib.RongIMClient._storageProvider.removeItem('servers'); } //循环设置监听事件,追加之后清空存放事件数据 for (var i = 0, len = RongIMLib.RongIMClient._memoryStore.listenerList.length; i < len; i++) { RongIMLib.RongIMClient.bridge["setListener"](RongIMLib.RongIMClient._memoryStore.listenerList[i]); } RongIMLib.RongIMClient._memoryStore.listenerList.length = 0; RongIMLib.RongIMClient.bridge.connect(RongIMLib.RongIMClient._memoryStore.appKey, token, { onSuccess: function (data) { setTimeout(function () { callback.onSuccess(data); }); }, onError: function (e) { if (e == RongIMLib.ConnectionState.TOKEN_INCORRECT || !e) { setTimeout(function () { callback.onTokenIncorrect(); }); } else { setTimeout(function () { callback.onError(e); }); } } }); }; /* config.auto: 默认 false, true 启用自动重连,启用则为必选参数 config.rate: 重试频率 [100, 1000, 3000, 6000, 10000, 18000] 单位为毫秒,可选 config.url: 网络嗅探地址 [http(s)://]cdn.ronghub.com/RongIMLib-2.2.6.min.js 可选 */ ServerDataProvider.prototype.reconnect = function (callback, config) { var store = RongIMLib.RongIMClient._memoryStore; var token = store.token; if (!token) { throw new Error('reconnect: token is empty.'); } if (RongIMLib.Bridge._client && RongIMLib.Bridge._client.channel && RongIMLib.Bridge._client.channel.connectionStatus != RongIMLib.ConnectionStatus.CONNECTED && RongIMLib.Bridge._client.channel.connectionStatus != RongIMLib.ConnectionStatus.CONNECTING) { config = config || {}; var key = config.auto ? 'auto' : 'custom'; var handler = { auto: function () { var repeatConnect = function (options) { var step = options.step(); var done = 'done'; var url = options.url; var ping = function () { RongIMLib.RongUtil.request({ url: url, success: function () { options.done(); }, error: function () { repeat(); } }); }; var repeat = function () { var next = step(); if (next == 'done') { var error = RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE; options.done(error); return; } setTimeout(ping, next); }; repeat(); }; var protocol = RongIMLib.RongIMClient._memoryStore.depend.protocol; var url = config.url || 'cdn.ronghub.com/RongIMLib-2.2.6.min.js'; var pathConfig = { protocol: protocol, path: url }; url = RongIMLib.RongUtil.formatProtoclPath(pathConfig); var rate = config.rate || [100, 1000, 3000, 6000, 10000, 18000]; //结束标识 rate.push('done'); var opts = { url: url, step: function () { var index = 0; return function () { var time = rate[index]; index++; return time; }; }, done: function (error) { if (error) { callback.onError(error); return; } RongIMLib.RongIMClient.connect(token, callback); } }; repeatConnect(opts); }, custom: function () { RongIMLib.RongIMClient.connect(token, callback); } }; handler[key](); } }; ServerDataProvider.prototype.logout = function () { RongIMLib.RongIMClient.bridge.disconnect(); RongIMLib.RongIMClient.bridge = null; }; ServerDataProvider.prototype.disconnect = function () { RongIMLib.RongIMClient.bridge.disconnect(); }; ServerDataProvider.prototype.sendReceiptResponse = function (conversationType, targetId, sendCallback) { var rspkey = RongIMLib.Bridge._client.userId + conversationType + targetId + 'RECEIVED', me = this; if (RongIMLib.RongUtil.supportLocalStorage()) { var valObj = JSON.parse(RongIMLib.RongIMClient._storageProvider.getItem(rspkey)); if (valObj) { var vals = []; for (var key in valObj) { var tmp = {}; tmp[key] = valObj[key].uIds; valObj[key].isResponse || vals.push(tmp); } if (vals.length == 0) { sendCallback.onSuccess(); return; } var interval = setInterval(function () { if (vals.length == 1) { clearInterval(interval); } var obj = vals.splice(0, 1)[0]; var rspMsg = new RongIMLib.ReadReceiptResponseMessage({ receiptMessageDic: obj }); me.sendMessage(conversationType, targetId, rspMsg, { onSuccess: function (msg) { var senderUserId = RongIMLib.MessageUtil.getFirstKey(obj); valObj[senderUserId].isResponse = true; RongIMLib.RongIMClient._storageProvider.setItem(rspkey, JSON.stringify(valObj)); sendCallback.onSuccess(msg); }, onError: function (error, msg) { sendCallback.onError(error, msg); } }); }, 200); } else { sendCallback.onSuccess(); } } else { sendCallback.onSuccess(); } }; ServerDataProvider.prototype.sendTypingStatusMessage = function (conversationType, targetId, messageName, sendCallback) { var me = this; if (messageName in RongIMLib.RongIMClient.MessageParams) { me.sendMessage(conversationType, targetId, RongIMLib.TypingStatusMessage.obtain(RongIMLib.RongIMClient.MessageParams[messageName].objectName, ""), { onSuccess: function () { setTimeout(function () { sendCallback.onSuccess(); }); }, onError: function (errorCode) { setTimeout(function () { sendCallback.onError(errorCode, null); }); }, onBefore: function () { } }); } }; ServerDataProvider.prototype.sendRecallMessage = function (content, sendMessageCallback) { var msg = new RongIMLib.RecallCommandMessage({ conversationType: content.conversationType, targetId: content.targetId, sentTime: content.sentTime, messageUId: content.messageUId, extra: content.extra, user: content.user }); this.sendMessage(content.conversationType, content.senderUserId, msg, sendMessageCallback, false, null, null, 2); }; ServerDataProvider.prototype.sendTextMessage = function (conversationType, targetId, content, sendMessageCallback) { var msgContent = RongIMLib.TextMessage.obtain(content); this.sendMessage(conversationType, targetId, msgContent, sendMessageCallback); }; ServerDataProvider.prototype.getRemoteHistoryMessages = function (conversationType, targetId, timestamp, count, callback, config) { if (count <= 1) { throw new Error("the count must be greater than 1."); } config = config || {}; var order = config.order || 0; var getKey = function () { return [conversationType, targetId, '_', order].join(''); }; var key = getKey(); if (!RongIMLib.RongUtil.isNumber(timestamp)) { timestamp = RongIMLib.RongIMClient._memoryStore.lastReadTime.get(key); } var memoryStore = RongIMLib.RongIMClient._memoryStore; var historyMessageLimit = memoryStore.historyMessageLimit; /* limit 属性: var limit = { time: '时间戳, 最后一次拉取时间', hasMore: '是否还有历史消息, bool 值' }; */ var limit = historyMessageLimit.get(key) || {}; var hasMore = limit.hasMore; var isFecth = (hasMore || limit.time != timestamp); // 正序获取消息时不做限制,防止有新消息导致无法获取 if (!isFecth && order == 0) { return callback.onSuccess([], hasMore); } var modules = new RongIMLib.RongIMClient.Protobuf.HistoryMsgInput(), self = this; modules.setTargetId(targetId); modules.setTime(timestamp); modules.setCount(count); modules.setOrder(order); RongIMLib.RongIMClient.bridge.queryMsg(HistoryMsgType[conversationType], RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), targetId, { onSuccess: function (data) { var fetchTime = RongIMLib.MessageUtil.int64ToTimestamp(data.syncTime); RongIMLib.RongIMClient._memoryStore.lastReadTime.set(key, fetchTime); historyMessageLimit.set(key, { hasMore: !!data.hasMsg, time: fetchTime }); var list = data.list.reverse(), tempMsg = null, tempDir; var read = RongIMLib.SentStatus.READ; if (RongIMLib.RongUtil.supportLocalStorage()) { for (var i = 0, len = list.length; i < len; i++) { tempMsg = RongIMLib.MessageUtil.messageParser(list[i]); tempDir = JSON.parse(RongIMLib.RongIMClient._storageProvider.getItem(RongIMLib.Bridge._client.userId + tempMsg.messageUId + "SENT")); if (tempDir) { tempMsg.receiptResponse || (tempMsg.receiptResponse = {}); tempMsg.receiptResponse[tempMsg.messageUId] = tempDir.count; } tempMsg.sentStatus = read; tempMsg.targetId = targetId; list[i] = tempMsg; } } else { for (var i = 0, len = list.length; i < len; i++) { var tempMsg = RongIMLib.MessageUtil.messageParser(list[i]); tempMsg.sentStatus = read; list[i] = tempMsg; } } setTimeout(function () { callback.onSuccess(list, !!data.hasMsg); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }, "HistoryMessagesOuput"); }; ServerDataProvider.prototype.hasRemoteUnreadMessages = function (token, callback) { var xss = null; window.RCCallback = function (x) { setTimeout(function () { callback.onSuccess(!!+x.status); }); xss.parentNode.removeChild(xss); }; xss = document.createElement("script"); xss.src = RongIMLib.RongIMClient._memoryStore.depend.api + "/message/exist.js?appKey=" + encodeURIComponent(RongIMLib.RongIMClient._memoryStore.appKey) + "&token=" + encodeURIComponent(token) + "&callBack=RCCallback&_=" + RongIMLib.RongUtil.getTimestamp(); document.body.appendChild(xss); xss.onerror = function () { setTimeout(function () { callback.onError(RongIMLib.ErrorCode.UNKNOWN); }); xss.parentNode.removeChild(xss); }; }; ServerDataProvider.prototype.getRemoteConversationList = function (callback, conversationTypes, count) { var modules = new RongIMLib.RongIMClient.Protobuf.RelationsInput(), self = this; modules.setType(1); if (typeof count == 'undefined') { modules.setCount(0); } else { modules.setCount(count); } RongIMLib.RongIMClient.bridge.queryMsg(26, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (list) { if (list.info) { list.info = list.info.reverse(); for (var i = 0, len = list.info.length; i < len; i++) { RongIMLib.RongIMClient.getInstance().pottingConversation(list.info[i]); } } var conversations = RongIMLib.RongIMClient._memoryStore.conversationList; setTimeout(function () { if (conversationTypes) { return callback.onSuccess(self.filterConversations(conversationTypes, conversations)); } callback.onSuccess(conversations); }); }, onError: function (error) { callback.onError(error); } }, "RelationsOutput"); }; ServerDataProvider.prototype.addMemberToDiscussion = function (discussionId, userIdList, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.ChannelInvitationInput(); modules.setUsers(userIdList); RongIMLib.RongIMClient.bridge.queryMsg(0, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), discussionId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.createDiscussion = function (name, userIdList, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.CreateDiscussionInput(), self = this; modules.setName(name); RongIMLib.RongIMClient.bridge.queryMsg(1, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (discussId) { if (userIdList.length > 0) { self.addMemberToDiscussion(discussId, userIdList, { onSuccess: function () { }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); } setTimeout(function () { callback.onSuccess(discussId); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }, "CreateDiscussionOutput"); }; ServerDataProvider.prototype.getDiscussion = function (discussionId, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.ChannelInfoInput(); modules.setNothing(1); RongIMLib.RongIMClient.bridge.queryMsg(4, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), discussionId, { onSuccess: function (data) { setTimeout(function () { callback.onSuccess(data); }); }, onError: function (errorCode) { setTimeout(function () { callback.onError(errorCode); }); } }, "ChannelInfoOutput"); }; ServerDataProvider.prototype.quitDiscussion = function (discussionId, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.LeaveChannelInput(); modules.setNothing(1); RongIMLib.RongIMClient.bridge.queryMsg(7, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), discussionId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (errorCode) { setTimeout(function () { callback.onError(errorCode); }); } }); }; ServerDataProvider.prototype.removeMemberFromDiscussion = function (discussionId, userId, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.ChannelEvictionInput(); modules.setUser(userId); RongIMLib.RongIMClient.bridge.queryMsg(9, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), discussionId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (errorCode) { setTimeout(function () { callback.onError(errorCode); }); } }); }; ServerDataProvider.prototype.setDiscussionInviteStatus = function (discussionId, status, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.ModifyPermissionInput(); modules.setOpenStatus(status.valueOf()); RongIMLib.RongIMClient.bridge.queryMsg(11, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), discussionId, { onSuccess: function (x) { setTimeout(function () { callback.onSuccess(); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.setDiscussionName = function (discussionId, name, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RenameChannelInput(); modules.setName(name); RongIMLib.RongIMClient.bridge.queryMsg(12, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), discussionId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (errcode) { callback.onError(errcode); } }); }; ServerDataProvider.prototype.joinChatRoom = function (chatroomId, messageCount, callback) { var e = new RongIMLib.RongIMClient.Protobuf.ChrmInput(); e.setNothing(1); RongIMLib.Bridge._client.chatroomId = chatroomId; RongIMLib.RongIMClient.bridge.queryMsg(19, RongIMLib.MessageUtil.ArrayForm(e.toArrayBuffer()), chatroomId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); var modules = new RongIMLib.RongIMClient.Protobuf.ChrmPullMsg(); messageCount == 0 && (messageCount = -1); modules.setCount(messageCount); modules.setSyncTime(0); RongIMLib.Bridge._client.queryMessage("chrmPull", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), chatroomId, 1, { onSuccess: function (collection) { var list = collection.list; var sync = RongIMLib.MessageUtil.int64ToTimestamp(collection.syncTime); var latestMessage = list[list.length - 1]; if (latestMessage) { latestMessage = RongIMLib.MessageUtil.messageParser(latestMessage); sync = latestMessage.sentTime; } RongIMLib.RongIMClient._memoryStore.lastReadTime.set(chatroomId + RongIMLib.Bridge._client.userId + "CST", sync); var _client = RongIMLib.Bridge._client; for (var i = 0, mlen = list.length; i < mlen; i++) { var uId = 'R' + list[i].msgId; if (!(uId in _client.cacheMessageIds)) { _client.cacheMessageIds[uId] = true; var cacheUIds = RongIMLib.RongUtil.keys(_client.cacheMessageIds); if (cacheUIds.length > 10) { uId = cacheUIds[0]; delete _client.cacheMessageIds[uId]; } if (RongIMLib.RongIMClient._memoryStore.filterMessages.length > 0) { for (var j = 0, flen = RongIMLib.RongIMClient._memoryStore.filterMessages.length; j < flen; j++) { if (RongIMLib.RongIMClient.MessageParams[RongIMLib.RongIMClient._memoryStore.filterMessages[j]].objectName != list[i].classname) { _client.handler.onReceived(list[i]); } } } else { _client.handler.onReceived(list[i]); } } } }, onError: function (x) { setTimeout(function () { callback.onError(RongIMLib.ErrorCode.CHATROOM_HISMESSAGE_ERROR); }); } }, "DownStreamMessages"); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }, "ChrmOutput"); }; ServerDataProvider.prototype.getChatRoomInfo = function (chatRoomId, count, order, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.QueryChatroomInfoInput(); modules.setCount(count); modules.setOrder(order); RongIMLib.RongIMClient.bridge.queryMsg("queryChrmI", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), chatRoomId, { onSuccess: function (ret) { var userInfos = ret.userInfos; userInfos.forEach(function (item) { item.time = RongIMLib.MessageUtil.int64ToTimestamp(item.time); }); setTimeout(function () { callback.onSuccess(ret); }); }, onError: function (errcode) { setTimeout(function () { callback.onError(errcode); }); } }, "QueryChatroomInfoOutput"); }; ServerDataProvider.prototype.quitChatRoom = function (chatroomId, callback) { var e = new RongIMLib.RongIMClient.Protobuf.ChrmInput(); e.setNothing(1); RongIMLib.RongIMClient.bridge.queryMsg(17, RongIMLib.MessageUtil.ArrayForm(e.toArrayBuffer()), chatroomId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (errcode) { setTimeout(function () { callback.onError(errcode); }); } }, "ChrmOutput"); }; ServerDataProvider.prototype.setChatroomHisMessageTimestamp = function (chatRoomId, timestamp) { RongIMLib.RongIMClient._memoryStore.lastReadTime.set('chrhis_' + chatRoomId, timestamp); }; ServerDataProvider.prototype.getChatRoomHistoryMessages = function (chatRoomId, count, order, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.HistoryMsgInput(); modules.setTargetId(chatRoomId); var timestamp = RongIMLib.RongIMClient._memoryStore.lastReadTime.get('chrhis_' + chatRoomId) || 0; modules.setTime(timestamp); modules.setCount(count); modules.setOrder(order); RongIMLib.RongIMClient.bridge.queryMsg(34, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (data) { RongIMLib.RongIMClient._memoryStore.lastReadTime.set('chrhis_' + chatRoomId, RongIMLib.MessageUtil.int64ToTimestamp(data.syncTime)); var list = data.list.reverse(); for (var i = 0, len = list.length; i < len; i++) { list[i] = RongIMLib.MessageUtil.messageParser(list[i]); } setTimeout(function () { callback.onSuccess(list, !!data.hasMsg); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }, "HistoryMsgOuput"); }; ServerDataProvider.prototype.setMessageStatus = function (conversationType, targetId, timestamp, status, callback) { setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.addToBlacklist = function (userId, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.Add2BlackListInput(); modules.setUserId(userId); RongIMLib.RongIMClient.bridge.queryMsg(21, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.getBlacklist = function (callback) { var modules = new RongIMLib.RongIMClient.Protobuf.QueryBlackListInput(); modules.setNothing(1); RongIMLib.RongIMClient.bridge.queryMsg(23, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (list) { setTimeout(function () { callback.onSuccess(list); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }, "QueryBlackListOutput"); }; ServerDataProvider.prototype.getBlacklistStatus = function (userId, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.BlackListStatusInput(); modules.setUserId(userId); RongIMLib.RongIMClient.bridge.queryMsg(24, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function (status) { setTimeout(function () { callback.onSuccess(RongIMLib.BlacklistStatus[status]); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.removeFromBlacklist = function (userId, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RemoveFromBlackListInput(); modules.setUserId(userId); RongIMLib.RongIMClient.bridge.queryMsg(22, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.getFileToken = function (fileType, callback) { if (!(/(1|2|3|4)/.test(fileType.toString()))) { setTimeout(function () { callback.onError(RongIMLib.ErrorCode.QNTKN_FILETYPE_ERROR); }); return; } var modules = new RongIMLib.RongIMClient.Protobuf.GetQNupTokenInput(); modules.setType(fileType); RongIMLib.RongIMClient.bridge.queryMsg(30, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (data) { setTimeout(function () { callback.onSuccess(data); }); }, onError: function (errcode) { setTimeout(function () { callback.onError(errcode); }); } }, "GetQNupTokenOutput"); }; ServerDataProvider.prototype.getFileUrl = function (fileType, fileName, oriName, callback) { if (!(/(1|2|3|4)/.test(fileType.toString()))) { setTimeout(function () { callback.onError(RongIMLib.ErrorCode.QNTKN_FILETYPE_ERROR); }); return; } var modules = new RongIMLib.RongIMClient.Protobuf.GetQNdownloadUrlInput(); modules.setType(fileType); modules.setKey(fileName); if (oriName) { modules.setFileName(oriName); } RongIMLib.RongIMClient.bridge.queryMsg(31, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (data) { setTimeout(function () { callback.onSuccess(data); }); }, onError: function (errcode) { setTimeout(function () { callback.onError(errcode); }); } }, "GetQNdownloadUrlOutput"); }; /* methodType 1 : 多客服(客服后台使用); 2 : 消息撤回 params.userIds : 定向消息接收者 */ ServerDataProvider.prototype.sendMessage = function (conversationType, targetId, messageContent, sendCallback, mentiondMsg, pushText, appData, methodType, params) { if (!RongIMLib.Bridge._client.channel) { setTimeout(function () { sendCallback.onError(RongIMLib.ErrorCode.RC_NET_UNAVAILABLE, null); }); return; } if (!RongIMLib.Bridge._client.channel.socket.socket.connected) { setTimeout(function () { sendCallback.onError(RongIMLib.ErrorCode.TIMEOUT, null); }); throw new Error("connect is timeout! postion:sendMessage"); } var isGroup = (conversationType == RongIMLib.ConversationType.DISCUSSION || conversationType == RongIMLib.ConversationType.GROUP); var modules = new RongIMLib.RongIMClient.Protobuf.UpStreamMessage(); if (mentiondMsg && isGroup) { modules.setSessionId(7); } else { modules.setSessionId(RongIMLib.RongIMClient.MessageParams[messageContent.messageName].msgTag.getMessageTag()); } pushText && modules.setPushText(pushText); appData && modules.setAppData(appData); if (isGroup && messageContent.messageName == RongIMLib.RongIMClient.MessageType["ReadReceiptResponseMessage"]) { var rspMsg = messageContent; if (rspMsg.receiptMessageDic) { var ids = []; for (var key in rspMsg.receiptMessageDic) { ids.push(key); } modules.setUserId(ids); } } if (isGroup && messageContent.messageName == RongIMLib.RongIMClient.MessageType["SyncReadStatusMessage"]) { modules.setUserId(RongIMLib.Bridge._client.userId); } params = params || {}; var userIds = params.userIds; if (isGroup && userIds) { modules.setUserId(userIds); } modules.setClassname(RongIMLib.RongIMClient.MessageParams[messageContent.messageName].objectName); modules.setContent(messageContent.encode()); var content = modules.toArrayBuffer(); if (Object.prototype.toString.call(content) == "[object ArrayBuffer]") { content = [].slice.call(new Int8Array(content)); } var me = this, msg = new RongIMLib.Message(); var c = this.getConversation(conversationType, targetId); if (RongIMLib.RongIMClient.MessageParams[messageContent.messageName].msgTag.getMessageTag() == 3) { if (!c) { c = RongIMLib.RongIMClient.getInstance().createConversation(conversationType, targetId, ""); } c.sentTime = new Date().getTime(); c.sentStatus = RongIMLib.SentStatus.SENDING; c.senderUserName = ""; c.senderUserId = RongIMLib.Bridge._client.userId; c.notificationStatus = RongIMLib.ConversationNotificationStatus.DO_NOT_DISTURB; c.latestMessage = msg; c.unreadMessageCount = 0; RongIMLib.RongIMClient._dataAccessProvider.addConversation(c, { onSuccess: function (data) { } }); } RongIMLib.RongIMClient._memoryStore.converStore = c; msg.content = messageContent; msg.conversationType = conversationType; msg.senderUserId = RongIMLib.Bridge._client.userId; msg.objectName = RongIMLib.RongIMClient.MessageParams[messageContent.messageName].objectName; msg.targetId = targetId; msg.sentTime = new Date().getTime(); msg.messageDirection = RongIMLib.MessageDirection.SEND; msg.sentStatus = RongIMLib.SentStatus.SENT; msg.messageType = messageContent.messageName; RongIMLib.RongIMClient.bridge.pubMsg(conversationType.valueOf(), content, targetId, { onSuccess: function (data) { if (data && data.timestamp) { RongIMLib.RongIMClient._memoryStore.lastReadTime.set('converST_' + RongIMLib.Bridge._client.userId + conversationType + targetId, data.timestamp); } if ((conversationType == RongIMLib.ConversationType.DISCUSSION || conversationType == RongIMLib.ConversationType.GROUP) && messageContent.messageName == RongIMLib.RongIMClient.MessageType["ReadReceiptRequestMessage"]) { var reqMsg = msg.content; var sentkey = RongIMLib.Bridge._client.userId + reqMsg.messageUId + "SENT"; RongIMLib.RongIMClient._storageProvider.setItem(sentkey, JSON.stringify({ count: 0, dealtime: data.timestamp, userIds: {} })); } if (RongIMLib.RongIMClient.MessageParams[msg.messageType].msgTag.getMessageTag() == 3) { var cacheConversation = RongIMLib.RongIMClient._memoryStore.converStore; cacheConversation.sentStatus = msg.sentStatus; cacheConversation.latestMessage = msg; me.updateConversation(cacheConversation); RongIMLib.RongIMClient._dataAccessProvider.addMessage(conversationType, targetId, msg, { onSuccess: function (ret) { msg = ret; msg.messageUId = data.messageUId; msg.sentTime = data.timestamp; msg.sentStatus = RongIMLib.SentStatus.SENT; msg.messageId = data.messageId; RongIMLib.RongIMClient._dataAccessProvider.updateMessage(msg); }, onError: function () { } }); } setTimeout(function () { cacheConversation && me.updateConversation(cacheConversation); msg.sentTime = data.timestamp; msg.messageUId = data.messageUId; sendCallback.onSuccess(msg); }); }, onError: function (errorCode, _msg) { msg.sentStatus = RongIMLib.SentStatus.FAILED; msg.messageUId = _msg.messageUId; msg.sentTime = _msg.sentTime; if (RongIMLib.RongIMClient.MessageParams[msg.messageType].msgTag.getMessageTag() == 3) { RongIMLib.RongIMClient._memoryStore.converStore.latestMessage = msg; } RongIMLib.RongIMClient._dataAccessProvider.addMessage(conversationType, targetId, msg, { onSuccess: function (ret) { msg.messageId = ret.messageId; RongIMLib.RongIMClient._dataAccessProvider.updateMessage(msg); }, onError: function () { } }); setTimeout(function () { sendCallback.onError(errorCode, msg); }); } }, null, methodType); sendCallback.onBefore && sendCallback.onBefore(RongIMLib.MessageIdHandler.messageId); msg.messageId = RongIMLib.MessageIdHandler.messageId + ""; }; ServerDataProvider.prototype.setConnectionStatusListener = function (listener) { if (RongIMLib.RongIMClient.bridge) { RongIMLib.RongIMClient.bridge.setListener(listener); } else { RongIMLib.RongIMClient._memoryStore.listenerList.push(listener); } }; ServerDataProvider.prototype.setOnReceiveMessageListener = function (listener) { if (RongIMLib.RongIMClient.bridge) { RongIMLib.RongIMClient.bridge.setListener(listener); } else { RongIMLib.RongIMClient._memoryStore.listenerList.push(listener); } }; ServerDataProvider.prototype.registerMessageType = function (messageType, objectName, messageTag, messageContent, searchProps) { if (!messageType) { throw new Error("messageType can't be empty,postion -> registerMessageType"); } if (!objectName) { throw new Error("objectName can't be empty,postion -> registerMessageType"); } if (Object.prototype.toString.call(messageContent) == "[object Array]") { var regMsg = RongIMLib.ModelUtil.modleCreate(messageContent, messageType); RongIMLib.RongIMClient.RegisterMessage[messageType] = regMsg; } else if (Object.prototype.toString.call(messageContent) == "[object Function]" || Object.prototype.toString.call(messageContent) == "[object Object]") { if (!messageContent.encode) { throw new Error("encode method has not realized or messageName is undefined-> registerMessageType"); } if (!messageContent.decode) { throw new Error("decode method has not realized -> registerMessageType"); } } else { throw new Error("The index of 3 parameter was wrong type must be object or function or array-> registerMessageType"); } registerMessageTypeMapping[objectName] = messageType; }; ServerDataProvider.prototype.registerMessageTypes = function (messages) { var types = []; var getProtos = function (proto) { var protos = []; for (var p in proto) { protos.push(p); } return protos; }; //转换消息为自定义消息参数格式 for (var name in messages) { var message = messages[name]; var proto = message.proto; var protos = getProtos(proto); var flag = message.flag || 3; var tag = RongIMLib.MessageTag.getTagByStatus(flag); flag = new RongIMLib.MessageTag(tag.isCounted, tag.isPersited); types.push({ type: name, name: message.name, flag: flag, protos: protos }); } var register = function (message) { var type = message.type; var name = message.name; var flag = message.flag; var protos = message.protos; RongIMLib.RongIMClient.registerMessageType(type, name, flag, protos); }; for (var i = 0, len = types.length; i < len; i++) { var message = types[i]; register(message); } }; ServerDataProvider.prototype.addConversation = function (conversation, callback) { var isAdd = true; for (var i = 0, len = RongIMLib.RongIMClient._memoryStore.conversationList.length; i < len; i++) { if (RongIMLib.RongIMClient._memoryStore.conversationList[i].conversationType === conversation.conversationType && RongIMLib.RongIMClient._memoryStore.conversationList[i].targetId === conversation.targetId) { // RongIMClient._memoryStore.conversationList[i] = conversation; RongIMLib.RongIMClient._memoryStore.conversationList.unshift(RongIMLib.RongIMClient._memoryStore.conversationList.splice(i, 1)[0]); isAdd = false; break; } } if (isAdd) { RongIMLib.RongIMClient._memoryStore.conversationList.unshift(conversation); } callback && callback.onSuccess(true); }; ServerDataProvider.prototype.updateConversation = function (conversation) { var conver; for (var i = 0, len = RongIMLib.RongIMClient._memoryStore.conversationList.length; i < len; i++) { var item = RongIMLib.RongIMClient._memoryStore.conversationList[i]; if (conversation.conversationType === item.conversationType && conversation.targetId === item.targetId) { conversation.conversationTitle && (item.conversationTitle = conversation.conversationTitle); conversation.senderUserName && (item.senderUserName = conversation.senderUserName); conversation.senderPortraitUri && (item.senderPortraitUri = conversation.senderPortraitUri); conversation.latestMessage && (item.latestMessage = conversation.latestMessage); conversation.sentStatus && (item.sentStatus = conversation.sentStatus); break; } } return conver; }; ServerDataProvider.prototype.removeConversation = function (conversationType, targetId, callback) { var mod = new RongIMLib.RongIMClient.Protobuf.RelationsInput(); mod.setType(conversationType); RongIMLib.RongIMClient.bridge.queryMsg(27, RongIMLib.MessageUtil.ArrayForm(mod.toArrayBuffer()), targetId, { onSuccess: function () { var conversations = RongIMLib.RongIMClient._memoryStore.conversationList; var len = conversations.length; for (var i = 0; i < len; i++) { if (conversations[i].conversationType == conversationType && targetId == conversations[i].targetId) { conversations.splice(i, 1); break; } } callback.onSuccess(true); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.getMessage = function (messageId, callback) { callback.onSuccess(new RongIMLib.Message()); }; ServerDataProvider.prototype.addMessage = function (conversationType, targetId, message, callback) { if (callback) { callback.onSuccess(message); } }; ServerDataProvider.prototype.removeMessage = function (conversationType, targetId, messageIds, callback) { RongIMLib.RongIMClient.getInstance().deleteRemoteMessages(conversationType, targetId, messageIds, callback); }; ServerDataProvider.prototype.removeLocalMessage = function (conversationType, targetId, timestamps, callback) { callback.onSuccess(true); }; ServerDataProvider.prototype.updateMessage = function (message, callback) { if (callback) { callback.onSuccess(message); } }; ServerDataProvider.prototype.clearRemoteHistoryMessages = function (params, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.CleanHisMsgInput(); var conversationType = params.conversationType; var _topic = { 1: 'cleanPMsg', 2: 'cleanDMsg', 3: 'cleanGMsg', 5: 'cleanCMsg', 6: 'cleanSMsg' }; var topic = _topic[conversationType]; if (!topic) { callback.onError(RongIMLib.ErrorCode.CLEAR_HIS_TYPE_ERROR); return; } var timestamp = params.timestamp; if (typeof timestamp != 'number') { callback.onError(RongIMLib.ErrorCode.CLEAR_HIS_TIME_ERROR); return; } modules.setDataTime(timestamp); var targetId = params.targetId; modules.setTargetId(targetId); RongIMLib.RongIMClient.bridge.queryMsg(topic, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), targetId, { onSuccess: function (result) { callback.onSuccess(!result); }, onError: function (error) { // error 1 历史消息云存储没有开通、传入时间大于服务器时间 清除失败,1 与其他错误码冲突,所以自定义错误码返回 if (error == 1) { error = RongIMLib.ErrorCode.CLEAR_HIS_ERROR; } setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.clearHistoryMessages = function (params, callback) { this.clearRemoteHistoryMessages(params, callback); }; // 兼容老版本 ServerDataProvider.prototype.clearMessages = function (conversationType, targetId, callback) { }; ServerDataProvider.prototype.updateMessages = function (conversationType, targetId, key, value, callback) { var me = this; if (key == "readStatus") { if (RongIMLib.RongIMClient._memoryStore.conversationList.length > 0) { me.getConversationList({ onSuccess: function (list) { Array.forEach(list, function (conver) { if (conver.conversationType == conversationType && conver.targetId == targetId) { conver.unreadMessageCount = 0; } }); }, onError: function (errorCode) { setTimeout(function () { callback.onError(errorCode); }); } }, null); } } setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.getConversation = function (conversationType, targetId, callback) { var conver = null; for (var i = 0, len = RongIMLib.RongIMClient._memoryStore.conversationList.length; i < len; i++) { if (RongIMLib.RongIMClient._memoryStore.conversationList[i].conversationType == conversationType && RongIMLib.RongIMClient._memoryStore.conversationList[i].targetId == targetId) { conver = RongIMLib.RongIMClient._memoryStore.conversationList[i]; if (RongIMLib.RongUtil.supportLocalStorage()) { var count = RongIMLib.RongIMClient._storageProvider.getItem("cu" + RongIMLib.Bridge._client.userId + conversationType + targetId); if (conver.unreadMessageCount == 0) { conver.unreadMessageCount = Number(count); } } } } setTimeout(function () { callback && callback.onSuccess(conver); }); return conver; }; ServerDataProvider.prototype.filterConversations = function (types, list) { var conversaions = []; RongIMLib.RongUtil.forEach(types, function (type) { RongIMLib.RongUtil.forEach(list, function (conversation) { if (conversation.conversationType == type) { conversaions.push(conversation); } }); }); return conversaions; }; ServerDataProvider.prototype.getConversationList = function (callback, conversationTypes, count, isHidden) { var that = this; var isSync = RongIMLib.RongIMClient._memoryStore.isSyncRemoteConverList; var list = RongIMLib.RongIMClient._memoryStore.conversationList; var isLocalInclude = list.length > count; if (!isSync && isLocalInclude) { setTimeout(function () { var localList = list.slice(0, count); if (conversationTypes) { localList = that.filterConversations(conversationTypes, localList); } callback.onSuccess(localList); }); return; } RongIMLib.RongIMClient.getInstance().getRemoteConversationList({ onSuccess: function (list) { if (RongIMLib.RongUtil.supportLocalStorage()) { Array.forEach(RongIMLib.RongIMClient._memoryStore.conversationList, function (item) { var count = RongIMLib.RongIMClient._storageProvider.getItem("cu" + RongIMLib.Bridge._client.userId + item.conversationType + item.targetId); if (item.unreadMessageCount == 0) { item.unreadMessageCount = Number(count); } }); } RongIMLib.RongIMClient._memoryStore.isSyncRemoteConverList = false; setTimeout(function () { callback.onSuccess(list); }); }, onError: function (errorcode) { setTimeout(function () { callback.onError(errorcode); }); } }, conversationTypes, count, isHidden); }; ServerDataProvider.prototype.clearCache = function () { var memoryStore = RongIMLib.RongIMClient._memoryStore || {}; memoryStore.conversationList = []; memoryStore.isSyncRemoteConverList = true; }; ServerDataProvider.prototype.clearConversations = function (conversationTypes, callback) { Array.forEach(conversationTypes, function (conversationType) { Array.forEach(RongIMLib.RongIMClient._memoryStore.conversationList, function (conver) { if (conversationType == conver.conversationType) { RongIMLib.RongIMClient.getInstance().removeConversation(conver.conversationType, conver.targetId, { onSuccess: function () { }, onError: function () { } }); } }); }); setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.setMessageContent = function (messageId, content, objectname) { }; ; ServerDataProvider.prototype.getHistoryMessages = function (conversationType, targetId, timestamp, count, callback, objectname, order) { var config = { objectname: objectname, order: order }; RongIMLib.RongIMClient.getInstance().getRemoteHistoryMessages(conversationType, targetId, timestamp, count, callback, config); }; ServerDataProvider.prototype.getTotalUnreadCount = function (callback, conversationTypes) { var count = 0; var storageProvider = RongIMLib.RongIMClient._storageProvider; if (conversationTypes) { RongIMLib.RongUtil.forEach(conversationTypes, function (type) { var unreadKeys = storageProvider.getItemKeyList("cu" + RongIMLib.Bridge._client.userId + type); RongIMLib.RongUtil.forEach(unreadKeys, function (key) { var unread = storageProvider.getItem(key); var unreadCount = Number(unread) || 0; count += unreadCount; }); }); } else { var unreadKeys = storageProvider.getItemKeyList("cu" + RongIMLib.Bridge._client.userId); RongIMLib.RongUtil.forEach(unreadKeys, function (key) { var unread = storageProvider.getItem(key); var unreadCount = Number(unread) || 0; count += unreadCount; }); } callback.onSuccess(count); }; ServerDataProvider.prototype.getConversationUnreadCount = function (conversationTypes, callback) { var count = 0; Array.forEach(conversationTypes, function (converType) { Array.forEach(RongIMLib.RongIMClient._memoryStore.conversationList, function (conver) { if (conver.conversationType == converType) { count += conver.unreadMessageCount; } }); }); setTimeout(function () { callback.onSuccess(count); }); }; //由于 Web 端未读消息数按会话统计,撤回消息会导致未读数不准确,提供设置未读数接口,桌面版不实现此方法 ServerDataProvider.prototype.setUnreadCount = function (conversationType, targetId, count) { var storageProvider = RongIMLib.RongIMClient._storageProvider; var key = "cu" + RongIMLib.Bridge._client.userId + conversationType + targetId; storageProvider.setItem(key, count); }; ServerDataProvider.prototype.getUnreadCount = function (conversationType, targetId, callback) { var key = "cu" + RongIMLib.Bridge._client.userId + conversationType + targetId; var unread = RongIMLib.RongIMClient._storageProvider.getItem(key); var unreadCount = Number(unread); setTimeout(function () { callback.onSuccess(unreadCount || 0); }); }; ServerDataProvider.prototype.cleanMentioneds = function (conver) { if (conver) { conver.mentionedMsg = null; var targetId = conver.targetId; var conversationType = conver.conversationType; var mentioneds = RongIMLib.RongIMClient._storageProvider.getItem("mentioneds_" + RongIMLib.Bridge._client.userId + '_' + conversationType + '_' + targetId); if (mentioneds) { var info = JSON.parse(mentioneds); delete info[conversationType + "_" + targetId]; if (!RongIMLib.MessageUtil.isEmpty(info)) { RongIMLib.RongIMClient._storageProvider.setItem("mentioneds_" + RongIMLib.Bridge._client.userId + '_' + conversationType + '_' + targetId, JSON.stringify(info)); } else { RongIMLib.RongIMClient._storageProvider.removeItem("mentioneds_" + RongIMLib.Bridge._client.userId + '_' + conversationType + '_' + targetId); } } } }; ServerDataProvider.prototype.clearUnreadCountByTimestamp = function (conversationType, targetId, timestamp, callback) { setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.clearUnreadCount = function (conversationType, targetId, callback) { var me = this; RongIMLib.RongIMClient._storageProvider.removeItem("cu" + RongIMLib.Bridge._client.userId + conversationType + targetId); this.getConversation(conversationType, targetId, { onSuccess: function (conver) { if (conver) { conver.unreadMessageCount = 0; me.cleanMentioneds(conver); } setTimeout(function () { callback.onSuccess(true); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.clearTotalUnreadCount = function (callback) { var list = RongIMLib.RongIMClient._memoryStore.conversationList; var me = this; if (list) { // 清除 mentioneds、清除 list 中的 unreadMessageCount for (var i = 0; i < list.length; i++) { var conver = list[i]; if (conver) { conver.unreadMessageCount = 0; me.cleanMentioneds(conver); } } } // 1. 获取所有 key 2. 清除 var unreadKeys = RongIMLib.RongIMClient._storageProvider.getItemKeyList("cu" + RongIMLib.Bridge._client.userId); RongIMLib.RongUtil.forEach(unreadKeys, function (key) { RongIMLib.RongIMClient._storageProvider.removeItem(key); }); setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.setConversationToTop = function (conversationType, targetId, isTop, callback) { var me = this; this.getConversation(conversationType, targetId, { onSuccess: function (conver) { conver.isTop = isTop; me.addConversation(conver, callback); setTimeout(function () { callback.onSuccess(true); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.getConversationNotificationStatus = function (params, callback) { var targetId = params.targetId; var conversationType = params.conversationType; var notification = RongIMLib.RongIMClient._memoryStore.notification; var getKey = function () { return conversationType + '_' + targetId; }; var key = getKey(); var status = notification[key]; if (typeof status == 'number') { callback.onSuccess(status); return; } var topics = { 1: 'qryPPush', 3: 'qryDPush' }; var topic = topics[conversationType]; if (!topic) { var error = 8001; callback.onError(error); return; } var modules = new RongIMLib.RongIMClient.Protobuf.BlockPushInput(); modules.setBlockeeId(targetId); var userId = RongIMLib.Bridge._client.userId; var success = function (status) { notification[key] = status; setTimeout(function () { callback.onSuccess(status); }); }; RongIMLib.RongIMClient.bridge.queryMsg(topic, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function (status) { success(status); }, onError: function (e) { if (e == 1) { success(e); } else { setTimeout(function () { callback.onError(e); }); } } }); }; ServerDataProvider.prototype.setConversationNotificationStatus = function (params, callback) { var conversationType = params.conversationType; var targetId = params.targetId; var status = params.status; var getKey = function () { return conversationType + '_' + status; }; var topics = { '1_1': 'blkPPush', '3_1': 'blkDPush', '1_0': 'unblkPPush', '3_0': 'unblkDPush' }; var key = getKey(); var notification = RongIMLib.RongIMClient._memoryStore.notification; notification[key] = status; var topic = topics[key]; if (!topic) { var error = 8001; setTimeout(function () { callback.onError(error); }); return; } var modules = new RongIMLib.RongIMClient.Protobuf.BlockPushInput(); modules.setBlockeeId(targetId); var userId = RongIMLib.Bridge._client.userId; RongIMLib.RongIMClient.bridge.queryMsg(topic, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function (status) { setTimeout(function () { callback.onSuccess(status); }); }, onError: function (e) { setTimeout(function () { callback.onError(e); }); } }); }; ServerDataProvider.prototype.getUserStatus = function (userId, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.GetUserStatusInput(); userId = RongIMLib.Bridge._client.userId; RongIMLib.RongIMClient.bridge.queryMsg(35, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function (status) { status = RongIMLib.RongInnerTools.convertUserStatus(status); setTimeout(function () { callback.onSuccess(status); }); }, onError: function (e) { setTimeout(function () { callback.onError(e); }); } }, 'GetUserStatusOutput'); // callback.onSuccess(new UserStatus()); }; ServerDataProvider.prototype.setUserStatus = function (status, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.SetUserStatusInput(); var userId = RongIMLib.Bridge._client.userId; if (status) { modules.setStatus(status); } RongIMLib.RongIMClient.bridge.queryMsg(36, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function (status) { setTimeout(function () { callback.onSuccess(true); }); }, onError: function (e) { setTimeout(function () { callback.onError(e); }); } }, 'SetUserStatusOutput'); }; ServerDataProvider.prototype.subscribeUserStatus = function (userIds, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.SubUserStatusInput(); var userId = RongIMLib.Bridge._client.userId; modules.setUserid(userIds); RongIMLib.RongIMClient.bridge.queryMsg(37, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function (status) { setTimeout(function () { callback && callback.onSuccess(true); }); }, onError: function (e) { setTimeout(function () { callback && callback.onError(e); }); } }, 'SubUserStatusOutput'); }; ServerDataProvider.prototype.setUserStatusListener = function (params, callback) { RongIMLib.RongIMClient.userStatusListener = callback; var userIds = params.userIds || []; if (userIds.length) { RongIMLib.RongIMClient._dataAccessProvider.subscribeUserStatus(userIds); } }; ServerDataProvider.prototype.clearListeners = function () { }; ServerDataProvider.prototype.setServerInfo = function (info) { }; ServerDataProvider.prototype.getUnreadMentionedMessages = function (conversationType, targetId) { return null; }; ServerDataProvider.prototype.setConversationHidden = function (conversationType, targetId, isHidden) { }; ServerDataProvider.prototype.setMessageExtra = function (messageId, value, callback) { setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.setMessageReceivedStatus = function (messageId, receivedStatus, callback) { setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.setMessageSentStatus = function (messageId, sentStatus, callback) { setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.getAllConversations = function (callback) { setTimeout(function () { callback.onSuccess([]); }); }; ServerDataProvider.prototype.getConversationByContent = function (keywords, callback) { setTimeout(function () { callback.onSuccess([]); }); }; ServerDataProvider.prototype.getMessagesFromConversation = function (conversationType, targetId, keywords, callback) { setTimeout(function () { callback.onSuccess([]); }); }; ServerDataProvider.prototype.searchConversationByContent = function (keyword, callback, conversationTypes) { setTimeout(function () { callback.onSuccess([]); }); }; ServerDataProvider.prototype.searchMessageByContent = function (conversationType, targetId, keyword, timestamp, count, total, callback) { setTimeout(function () { callback.onSuccess([]); }); }; ServerDataProvider.prototype.getDelaTime = function () { return RongIMLib.RongIMClient._memoryStore.deltaTime; }; ServerDataProvider.prototype.getCurrentConnectionStatus = function () { var client = RongIMLib.Bridge._client || {}; var channel = client.channel || {}; var status = RongIMLib.ConnectionStatus.CONNECTION_CLOSED; if (typeof channel.connectionStatus == 'number') { status = channel.connectionStatus; } return status; }; ServerDataProvider.prototype.getAgoraDynamicKey = function (engineType, channelName, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.VoipDynamicInput(); modules.setEngineType(engineType); modules.setChannelName(channelName); RongIMLib.RongIMClient.bridge.queryMsg(32, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (result) { setTimeout(function () { callback.onSuccess(result); }); }, onError: function (errorCode) { setTimeout(function () { callback.onError(errorCode); }); } }, "VoipDynamicOutput"); }; ServerDataProvider.prototype.setDeviceInfo = function (deviceId) { }; ServerDataProvider.prototype.setEnvironment = function (isPrivate) { }; ServerDataProvider.prototype.clearData = function () { return true; }; ServerDataProvider.prototype.getPublicServiceProfile = function (publicServiceType, publicServiceId, callback) { var profile = RongIMLib.RongIMClient._memoryStore.publicServiceMap.get(publicServiceType, publicServiceId); setTimeout(function () { callback.onSuccess(profile); }); }; ServerDataProvider.prototype.getRemotePublicServiceList = function (callback, pullMessageTime) { if (RongIMLib.RongIMClient._memoryStore.depend.openMp) { var modules = new RongIMLib.RongIMClient.Protobuf.PullMpInput(), self = this; if (!pullMessageTime) { modules.setTime(0); } else { modules.setTime(pullMessageTime); } modules.setMpid(""); RongIMLib.RongIMClient.bridge.queryMsg(28, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (data) { //TODO 找出最大时间 // self.lastReadTime.set(conversationType + targetId, MessageUtil.int64ToTimestamp(data.syncTime)); RongIMLib.RongIMClient._memoryStore.publicServiceMap.publicServiceList.length = 0; RongIMLib.RongIMClient._memoryStore.publicServiceMap.publicServiceList = data; setTimeout(function () { callback && callback.onSuccess(data); }); }, onError: function (errorCode) { setTimeout(function () { callback && callback.onError(errorCode); }); } }, "PullMpOutput"); } }; return ServerDataProvider; })(); RongIMLib.ServerDataProvider = ServerDataProvider; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var VCDataProvider = (function () { function VCDataProvider(addon) { // C++ 需要的 SDK 版本号 this.version = '2.8.27'; this.userId = ""; this.useConsole = false; this.appKey = ""; this.token = ""; this.addon = addon; } VCDataProvider.prototype.init = function (appKey, config) { this.appKey = appKey; this.useConsole && console.log("init"); config = config || {}; config.version = this.version; var sdkInfo = this.addon.initWithAppkey(appKey, config.dbPath, config); if (sdkInfo) { sdkInfo = JSON.parse(sdkInfo); } // 0 不存不计数 1 只存不计数 3 存且计数 this.addon.registerMessageType("RC:VcMsg", 3); this.addon.registerMessageType("RC:ImgTextMsg", 3); this.addon.registerMessageType("RC:FileMsg", 3); this.addon.registerMessageType("RC:LBSMsg", 3); this.addon.registerMessageType("RC:PSImgTxtMsg", 3); this.addon.registerMessageType("RC:PSMultiImgTxtMsg", 3); this.addon.registerMessageType("RCJrmf:RpMsg", 3); this.addon.registerMessageType("RCJrmf:RpOpendMsg", 1); this.addon.registerMessageType("RC:GrpNtf", 1); this.addon.registerMessageType("RC:DizNtf", 0); this.addon.registerMessageType("RC:InfoNtf", 0); this.addon.registerMessageType("RC:ContactNtf", 0); this.addon.registerMessageType("RC:ProfileNtf", 0); this.addon.registerMessageType("RC:CmdNtf", 0); this.addon.registerMessageType("RC:CmdMsg", 0); this.addon.registerMessageType("RC:TypSts", 0); this.addon.registerMessageType("RC:CsChaR", 0); this.addon.registerMessageType("RC:CsHsR", 0); this.addon.registerMessageType("RC:CsEnd", 0); this.addon.registerMessageType("RC:CsSp", 0); this.addon.registerMessageType("RC:CsUpdate", 0); this.addon.registerMessageType("RC:CsContact", 0); this.addon.registerMessageType("RC:ReadNtf", 0); this.addon.registerMessageType("RC:VCAccept", 0); this.addon.registerMessageType("RC:VCRinging", 0); this.addon.registerMessageType("RC:VCSummary", 0); this.addon.registerMessageType("RC:VCHangup", 0); this.addon.registerMessageType("RC:VCInvite", 0); this.addon.registerMessageType("RC:VCModifyMedia", 0); this.addon.registerMessageType("RC:VCModifyMem", 0); this.addon.registerMessageType("RC:PSCmd", 0); this.addon.registerMessageType("RC:RcCmd", 0); this.addon.registerMessageType("RC:SRSMsg", 0); this.addon.registerMessageType("RC:RRReqMsg", 0); this.addon.registerMessageType("RC:RRRspMsg", 0); return sdkInfo; }; VCDataProvider.prototype.connect = function (token, callback, userId, serverConf) { this.useConsole && console.log("connect"); this.userId = userId; this.connectCallback = callback; RongIMLib.Bridge._client = { userId: userId }; serverConf = serverConf || {}; var openmp = !!serverConf.openMp; var openus = !!serverConf.openUS; if (serverConf.type) { this.addon.setEnvironment(true); } this.addon.connectWithToken(token, userId, serverConf.serverList, openmp, openus); }; VCDataProvider.prototype.setServerInfo = function (info) { 'setServerInfo' in this.addon && this.addon.setServerInfo(info.navi); }; VCDataProvider.prototype.logout = function () { this.useConsole && console.log("logout"); this.disconnect(); }; VCDataProvider.prototype.disconnect = function () { this.useConsole && console.log("disconnect"); this.addon.disconnect(true); }; VCDataProvider.prototype.clearListeners = function () { this.addon.setOnReceiveStatusListener(); this.addon.setConnectionStatusListener(); this.addon.setOnReceiveMessageListener(); }; VCDataProvider.prototype.clearData = function () { this.useConsole && console.log("clearData"); return this.addon.clearData(); }; VCDataProvider.prototype.setConnectionStatusListener = function (listener) { var me = this; /** ConnectionStatus_TokenIncorrect = 31004, ConnectionStatus_Connected = 0, ConnectionStatus_KickedOff = 6, // 其他设备登录 ConnectionStatus_Connecting = 10,// 连接中 ConnectionStatus_SignUp = 12, // 未登录 ConnectionStatus_NetworkUnavailable = 1, // 连接断开 ConnectionStatus_ServerInvalid = 8, // 断开 ConnectionStatus_ValidateFailure = 9,//断开 ConnectionStatus_Unconnected = 11,//断开 ConnectionStatus_DisconnExecption = 31011 //断开 RC_NAVI_MALLOC_ERROR = 30000,//断开 RC_NAVI_NET_UNAVAILABLE= 30002,//断开 RC_NAVI_SEND_FAIL = 30004,//断开 RC_NAVI_REQ_TIMEOUT = 30005,//断开 RC_NAVI_RECV_FAIL = 30006,//断开 RC_NAVI_RESOURCE_ERROR = 30007,//断开 RC_NAVI_NODE_NOT_FOUND = 30008,//断开 RC_NAVI_DNS_ERROR = 30009,//断开 */ me.connectListener = listener; this.useConsole && console.log("setConnectionStatusListener"); me.addon && me.addon.setConnectionStatusListener(function (result) { switch (result) { case 10: setTimeout(function () { listener.onChanged(RongIMLib.ConnectionStatus.CONNECTING); }); break; case 31004: setTimeout(function () { me.connectCallback.onTokenIncorrect(); }); break; case 1: case 8: case 9: case 11: case 12: case 31011: case 30000: case 30002: setTimeout(function () { listener.onChanged(RongIMLib.ConnectionStatus.DISCONNECTED); }); break; case 0: case 33005: setTimeout(function () { me.connectCallback.onSuccess(me.userId); listener.onChanged(RongIMLib.ConnectionStatus.CONNECTED); }); break; case 6: setTimeout(function () { listener.onChanged(RongIMLib.ConnectionStatus.KICKED_OFFLINE_BY_OTHER_CLIENT); }); break; default: setTimeout(function () { listener.onChanged(result); }); break; } }); }; VCDataProvider.prototype.setOnReceiveMessageListener = function (listener) { var me = this, localCount = 0; me.messageListener = listener; this.useConsole && console.log("setOnReceiveMessageListener"); me.addon && me.addon.setOnReceiveMessageListener(function (result, leftCount, offline, hasMore) { var message = me.buildMessage(result); message.offLineMessage = offline; setTimeout(function () { var voipMsgTypes = ['AcceptMessage', 'RingingMessage', 'HungupMessage', 'InviteMessage', 'MediaModifyMessage', 'MemberModifyMessage']; var isVoIPMsg = voipMsgTypes.indexOf(message.messageType) > -1; if (isVoIPMsg) { RongIMLib.RongIMClient._voipProvider && RongIMLib.RongIMClient._voipProvider.onReceived(message); } else { listener.onReceived(message, leftCount, hasMore); } }); }); }; VCDataProvider.prototype.sendTypingStatusMessage = function (conversationType, targetId, messageName, sendCallback) { var me = this; this.useConsole && console.log("sendTypingStatusMessage"); if (messageName in RongIMLib.RongIMClient.MessageParams) { me.sendMessage(conversationType, targetId, RongIMLib.TypingStatusMessage.obtain(RongIMLib.RongIMClient.MessageParams[messageName].objectName, ""), { onSuccess: function () { setTimeout(function () { sendCallback.onSuccess(); }); }, onError: function (errorCode) { setTimeout(function () { sendCallback.onError(errorCode, null); }); }, onBefore: function () { } }); } }; VCDataProvider.prototype.setMessageStatus = function (conversationType, targetId, timestamp, status, callback) { this.addon.updateMessageReceiptStatus(conversationType, targetId, timestamp); callback.onSuccess(true); }; VCDataProvider.prototype.sendTextMessage = function (conversationType, targetId, content, sendMessageCallback) { var msgContent = RongIMLib.TextMessage.obtain(content); this.useConsole && console.log("sendTextMessage"); this.sendMessage(conversationType, targetId, msgContent, sendMessageCallback); }; VCDataProvider.prototype.getRemoteHistoryMessages = function (conversationType, targetId, timestamp, count, callback, config) { try { var me = this; me.useConsole && console.log("getRemoteHistoryMessages"); me.addon.getRemoteHistoryMessages(conversationType, targetId, timestamp ? timestamp : 0, count, function (ret, hasMore) { var list = ret ? JSON.parse(ret).list : [], msgs = []; list.reverse(); for (var i = 0, len = list.length; i < len; i++) { var message = me.buildMessage(list[i].obj); message.sentStatus = RongIMLib.SentStatus.READ; msgs[i] = message; } callback.onSuccess(msgs, hasMore ? true : false); }, function (errorCode) { callback.onError(errorCode); }); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.getRemoteConversationList = function (callback, conversationTypes, count, isGetHiddenConvers) { try { this.useConsole && console.log("getRemoteConversationList"); var converTypes = conversationTypes || [1, 2, 3, 4, 5, 6, 7, 8]; var result = this.addon.getConversationList(converTypes); var list = JSON.parse(result).list, convers = [], me = this, index = 0; list.reverse(); isGetHiddenConvers = typeof isGetHiddenConvers === 'boolean' ? isGetHiddenConvers : false; for (var i = 0, len_1 = list.length; i < len_1; i++) { var tmpObj = list[i].obj, obj = JSON.parse(tmpObj); if (obj != "") { if (obj.isHidden == 1 && isGetHiddenConvers) { continue; } convers[index] = me.buildConversation(tmpObj); index++; } } convers.reverse(); var len = convers.length; count = count || len; if (len > count) { convers.length = count; } callback.onSuccess(convers); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.removeConversation = function (conversationType, targetId, callback) { try { this.useConsole && console.log("removeConversation"); this.addon.removeConversation(conversationType, targetId); var conversations = RongIMLib.RongIMClient._memoryStore.conversationList; var len = conversations.length; for (var i = 0; i < len; i++) { if (conversations[i].conversationType == conversationType && targetId == conversations[i].targetId) { conversations.splice(i, 1); break; } } callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.joinChatRoom = function (chatRoomId, messageCount, callback) { this.useConsole && console.log("joinChatRoom"); this.addon.joinChatRoom(chatRoomId, messageCount, function () { callback.onSuccess(); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.quitChatRoom = function (chatRoomId, callback) { this.useConsole && console.log("quitChatRoom"); this.addon.quitChatRoom(chatRoomId, function () { callback.onSuccess(); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.addToBlacklist = function (userId, callback) { this.useConsole && console.log("addToBlacklist"); this.addon.addToBlacklist(userId, function () { callback.onSuccess(); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.getBlacklist = function (callback) { this.useConsole && console.log("getBlacklist"); this.addon.getBlacklist(function (blacklistors) { callback.onSuccess(blacklistors); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.getBlacklistStatus = function (userId, callback) { this.useConsole && console.log("getBlacklistStatus"); this.addon.getBlacklistStatus(userId, function (result) { callback.onSuccess(result); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.removeFromBlacklist = function (userId, callback) { this.useConsole && console.log("removeFromBlacklist"); this.addon.removeFromBlacklist(userId, function () { callback.onSuccess(); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.sendMessage = function (conversationType, targetId, messageContent, sendCallback, mentiondMsg, pushText, appData, methodType, params) { var me = this, users = []; me.useConsole && console.log("sendMessage"); params = params || {}; var isGroup = (conversationType == RongIMLib.ConversationType.DISCUSSION || conversationType == RongIMLib.ConversationType.GROUP); if (isGroup && messageContent.messageName == RongIMLib.RongIMClient.MessageType["ReadReceiptResponseMessage"]) { users = []; var rspMsg = messageContent; if (rspMsg.receiptMessageDic) { var ids = []; for (var key in rspMsg.receiptMessageDic) { ids.push(key); } users = ids; } } if (isGroup && messageContent.messageName == RongIMLib.RongIMClient.MessageType["SyncReadStatusMessage"]) { users = []; users.push(me.userId); } var userIds = params.userIds; if (isGroup && userIds) { users = userIds; } var msg = me.addon.sendMessage(conversationType, targetId, RongIMLib.RongIMClient.MessageParams[messageContent.messageName].objectName, messageContent.encode(), pushText || "", appData || "", function (progress) { }, function (message, code) { var msg = me.buildMessage(message); var errorCode = RongIMLib.ErrorCode.SENSITIVE_REPLACE; if (code == errorCode) { return sendCallback.onError(errorCode, msg); } sendCallback.onSuccess(msg); }, function (message, code) { sendCallback.onError(code, me.buildMessage(message)); }, users); var tempMessage = JSON.parse(msg); sendCallback.onBefore && sendCallback.onBefore(tempMessage.messageId); RongIMLib.MessageIdHandler.messageId = tempMessage.messageId; }; VCDataProvider.prototype.registerMessageType = function (messageType, objectName, messageTag, messageContent, searchProps) { this.useConsole && console.log("registerMessageType"); this.addon.registerMessageType(objectName, messageTag.getMessageTag(), searchProps); var regMsg = RongIMLib.ModelUtil.modleCreate(messageContent, messageType); RongIMLib.RongIMClient.RegisterMessage[messageType] = regMsg; RongIMLib.RongIMClient.RegisterMessage[messageType].messageName = messageType; registerMessageTypeMapping[objectName] = messageType; RongIMLib.RongIMClient.MessageType[messageType] = messageType; RongIMLib.RongIMClient.MessageParams[messageType] = { objectName: objectName, msgTag: messageTag }; typeMapping[objectName] = messageType; }; VCDataProvider.prototype.registerMessageTypes = function (messages) { var types = []; var getProtos = function (proto) { var protos = []; for (var p in proto) { protos.push(p); } return protos; }; //转换消息为自定义消息参数格式 for (var name in messages) { var message = messages[name]; var proto = message.proto; var protos = getProtos(proto); var flag = message.flag || 3; var tag = RongIMLib.MessageTag.getTagByStatus(flag); flag = new RongIMLib.MessageTag(tag.isCounted, tag.isPersited); types.push({ type: name, name: message.name, flag: flag, protos: protos }); } var register = function (message) { var type = message.type; var name = message.name; var flag = message.flag; var protos = message.protos; RongIMLib.RongIMClient.registerMessageType(type, name, flag, protos); }; for (var i = 0, len = types.length; i < len; i++) { var message = types[i]; register(message); } }; VCDataProvider.prototype.addMessage = function (conversationType, targetId, message, callback) { this.useConsole && console.log("addMessage"); var direction = message.direction; var msg = this.addon.insertMessage(conversationType, targetId, message.senderUserId, message.objectName, JSON.stringify(message.content), function () { callback.onSuccess(me.buildMessage(msg)); }, function () { callback.onError(RongIMLib.ErrorCode.MSG_INSERT_ERROR); }, direction), me = this; }; VCDataProvider.prototype.removeMessage = function (conversationType, targetId, delMsgs, callback) { }; VCDataProvider.prototype.removeLocalMessage = function (conversationType, targetId, timestamps, callback) { try { this.useConsole && console.log("removeLocalMessage"); this.addon.deleteMessages(timestamps); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.getMessage = function (messageId, callback) { try { this.useConsole && console.log("getMessage"); var msg = this.buildMessage(this.addon.getMessage(messageId)); callback.onSuccess(msg); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.clearMessages = function (conversationType, targetId, callback) { try { this.useConsole && console.log("clearMessages"); this.addon.clearMessages(conversationType, targetId); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; // Web 端接口,桌面版无需实现 VCDataProvider.prototype.setUnreadCount = function (conversationType, targetId, count) { }; VCDataProvider.prototype.getConversation = function (conversationType, targetId, callback) { try { this.useConsole && console.log("getConversation"); var ret = this.addon.getConversation(conversationType, targetId); callback.onSuccess(this.buildConversation(ret)); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.getConversationList = function (callback, conversationTypes, count, isGetHiddenConvers) { this.useConsole && console.log("getConversationList"); this.getRemoteConversationList(callback, conversationTypes, count, isGetHiddenConvers); }; VCDataProvider.prototype.clearCache = function () { var memoryStore = RongIMLib.RongIMClient._memoryStore || {}; memoryStore.conversationList = []; memoryStore.isSyncRemoteConverList; }; VCDataProvider.prototype.clearConversations = function (conversationTypes, callback) { try { this.useConsole && console.log("clearConversations"); this.addon.clearConversations(); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.setMessageContent = function (messageId, content, objectName) { content = JSON.stringify(content); this.addon.setMessageContent(messageId, content, objectName); }; VCDataProvider.prototype.getHistoryMessages = function (conversationType, targetId, timestamp, count, callback, objectname, direction) { this.useConsole && console.log("getHistoryMessages"); if (count <= 0) { callback.onError(RongIMLib.ErrorCode.TIMEOUT); return; } objectname = objectname || ''; direction = typeof direction == 'undefined' || direction; try { var ret = this.addon.getHistoryMessages(conversationType, targetId, timestamp ? timestamp : 0, count, objectname, direction); var list = ret ? JSON.parse(ret).list : [], msgs = [], me = this; list.reverse(); for (var i = 0, len = list.length; i < len; i++) { var message = me.buildMessage(list[i].obj); msgs[i] = message; } callback.onSuccess(msgs, len == count); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.clearRemoteHistoryMessages = function (params, callback) { var conversationType = params.conversationType; var targetId = params.targetId; var timestamp = params.timestamp; var _topic = { 1: true, 2: true, 3: true, 5: true, 6: true }; var topic = _topic[conversationType]; if (!topic) { callback.onError(RongIMLib.ErrorCode.CLEAR_HIS_TYPE_ERROR); return; } if (typeof timestamp != 'number') { callback.onError(RongIMLib.ErrorCode.CLEAR_HIS_TIME_ERROR); return; } this.addon.clearRemoteHistoryMessages(+conversationType, targetId, timestamp, function () { callback.onSuccess(true); }, function (errorCode) { if (errorCode == 1) { // 没有开通历史消息云存储 errorCode = RongIMLib.ErrorCode.CLEAR_HIS_ERROR; } callback.onError(errorCode); }); }; VCDataProvider.prototype.clearHistoryMessages = function (params, callback) { var conversationType = +params.conversationType; var targetId = params.targetId; try { this.addon.clearMessages(conversationType, targetId); var isSuccess = true; callback.onSuccess(isSuccess); } catch (e) { console.log(e); callback.onError(RongIMLib.ErrorCode.CLEAR_HIS_ERROR); } }; VCDataProvider.prototype.getTotalUnreadCount = function (callback, conversationTypes) { try { var result; this.useConsole && console.log("getTotalUnreadCount"); if (conversationTypes) { result = this.addon.getTotalUnreadCount(conversationTypes); } else { result = this.addon.getTotalUnreadCount(); } callback.onSuccess(result); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.getConversationUnreadCount = function (conversationTypes, callback) { this.useConsole && console.log("getConversationUnreadCount"); this.getTotalUnreadCount(callback, conversationTypes); }; VCDataProvider.prototype.getUnreadCount = function (conversationType, targetId, callback) { try { this.useConsole && console.log("getUnreadCount"); var result = this.addon.getUnreadCount(conversationType, targetId); callback.onSuccess(result); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.clearUnreadCount = function (conversationType, targetId, callback) { try { this.useConsole && console.log("clearUnreadCount"); var result = this.addon.clearUnreadCount(conversationType, targetId); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.clearTotalUnreadCount = function (callback) { this.useConsole && console.log("clearTotalUnreadCount"); }; VCDataProvider.prototype.clearUnreadCountByTimestamp = function (conversationType, targetId, timestamp, callback) { try { this.useConsole && console.log("clearUnreadCountByTimestamp"); var result = this.addon.clearUnreadCountByTimestamp(conversationType, targetId, timestamp); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.setConversationToTop = function (conversationType, targetId, isTop, callback) { try { this.useConsole && console.log("setConversationToTop"); this.addon.setConversationToTop(conversationType, targetId, isTop); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.setConversationHidden = function (conversationType, targetId, isHidden) { this.addon.setConversationHidden(conversationType, targetId, isHidden); }; VCDataProvider.prototype.setMessageReceivedStatus = function (messageId, receivedStatus, callback) { try { this.useConsole && console.log("setMessageReceivedStatus"); this.addon.setMessageReceivedStatus(messageId, receivedStatus); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.setMessageSentStatus = function (messageId, sentStatus, callback) { try { this.useConsole && console.log("setMessageSentStatus"); this.addon.setMessageSentStatus(messageId, sentStatus); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.getFileToken = function (fileType, callback) { this.useConsole && console.log("getFileToken"); this.addon.getUploadToken(fileType, function (token) { callback.onSuccess({ token: token }); }, function (errorCode) { callback.onError(errorCode); }); }; VCDataProvider.prototype.getFileUrl = function (fileType, fileName, oriName, callback) { this.useConsole && console.log("getFileUrl"); this.addon.getDownloadUrl(fileType, fileName, oriName, function (url) { callback.onSuccess({ downloadUrl: url }); }, function (errorCode) { callback.onError(errorCode); }); }; VCDataProvider.prototype.searchConversationByContent = function (keyword, callback, conversationTypes) { var converTypes = []; if (typeof conversationTypes == 'undefined') { converTypes = [1, 2, 3, 4, 5, 6, 7]; } else { converTypes = conversationTypes; } try { this.useConsole && console.log("searchConversationByContent"); var result = this.addon.searchConversationByContent(converTypes, keyword); var list = JSON.parse(result).list, convers = [], me = this; list.reverse(); for (var i = 0, len = list.length; i < len; i++) { convers[i] = me.buildConversation(list[i].obj); } callback.onSuccess(convers); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.searchMessageByContent = function (conversationType, targetId, keyword, timestamp, count, total, callback) { var me = this; try { this.useConsole && console.log("searchMessageByContent"); this.addon.searchMessageByContent(conversationType, targetId, keyword, timestamp, count, total, function (ret, matched) { var list = ret ? JSON.parse(ret).list : [], msgs = []; list.reverse(); for (var i = 0, len = list.length; i < len; i++) { msgs[i] = me.buildMessage(list[i].obj); } callback.onSuccess(msgs, matched); }); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.getChatRoomInfo = function (chatRoomId, count, order, callback) { this.useConsole && console.log("getChatRoomInfo"); this.addon.getChatroomInfo(chatRoomId, count, order, function (ret, count) { var list = ret ? JSON.parse(ret).list : [], chatRoomInfo = { userInfos: [], userTotalNums: count }; if (list.length > 0) { for (var i = 0, len = list.length; i < len; i++) { chatRoomInfo.userInfos.push(JSON.parse(list[i].obj)); } } callback.onSuccess(chatRoomInfo); }, function (errcode) { callback.onError(errcode); }); }; VCDataProvider.prototype.setChatroomHisMessageTimestamp = function (chatRoomId, timestamp) { }; VCDataProvider.prototype.getChatRoomHistoryMessages = function (chatRoomId, count, order, callback) { }; VCDataProvider.prototype.getDelaTime = function () { return this.addon.getDeltaTime(); }; VCDataProvider.prototype.getUserStatus = function (userId, callback) { var me = this; this.addon.getUserStatus(userId, function (status) { var entity = RongIMLib.RongInnerTools.convertUserStatus({ status: status, userId: '' }); callback.onSuccess(entity); }, function (code) { callback.onError(code); }); }; VCDataProvider.prototype.setUserStatus = function (status, callback) { this.addon.setUserStatus(status, function () { callback.onSuccess(true); }, function (code) { callback.onError(code); }); }; VCDataProvider.prototype.subscribeUserStatus = function (userIds, callback) { this.addon.subscribeUserStatus(userIds, function () { callback && callback.onSuccess(true); }, function (code) { callback && callback.onError(code); }); }; VCDataProvider.prototype.setUserStatusListener = function (params, callback) { var me = this; this.addon.setOnReceiveStatusListener(function (userId, status) { var entity = RongIMLib.RongInnerTools.convertUserStatus({ userId: userId, status: status }); RongIMLib.RongIMClient.userStatusObserver.notify({ key: userId, entity: entity }); }); var userIds = params.userIds || []; if (userIds.length) { RongIMLib.RongIMClient._dataAccessProvider.subscribeUserStatus(userIds); } }; VCDataProvider.prototype.getUnreadMentionedMessages = function (conversationType, targetId) { var me = this; var mentions = JSON.parse(me.addon.getUnreadMentionedMessages(conversationType, targetId)).list; for (var i = 0, len = mentions.length; i < len; i++) { var temp = JSON.parse(mentions[i].obj); temp.content = JSON.parse(temp.content); mentions[i] = temp; } return mentions; }; VCDataProvider.prototype.hasRemoteUnreadMessages = function (token, callback) { callback.onSuccess(false); }; VCDataProvider.prototype.sendRecallMessage = function (content, sendMessageCallback) { var me = this; me.addon.recallMessage("RC:RcCmd", JSON.stringify(content), content.push || "", function () { content.objectName = 'RC:RcCmd'; sendMessageCallback.onSuccess(me.buildMessage(JSON.stringify(content))); }, function (errorCode) { sendMessageCallback.onError(errorCode); }); }; VCDataProvider.prototype.updateMessage = function (message, callback) { }; VCDataProvider.prototype.updateMessages = function (conversationType, targetId, key, value, callback) { }; VCDataProvider.prototype.reconnect = function (callback) { }; VCDataProvider.prototype.sendReceiptResponse = function (conversationType, targetId, sendCallback) { }; VCDataProvider.prototype.setMessageExtra = function (messageId, value, callback) { }; VCDataProvider.prototype.addMemberToDiscussion = function (discussionId, userIdList, callback) { }; VCDataProvider.prototype.createDiscussion = function (name, userIdList, callback) { }; VCDataProvider.prototype.getDiscussion = function (discussionId, callback) { }; VCDataProvider.prototype.quitDiscussion = function (discussionId, callback) { }; VCDataProvider.prototype.removeMemberFromDiscussion = function (discussionId, userId, callback) { }; VCDataProvider.prototype.setDiscussionInviteStatus = function (discussionId, status, callback) { }; VCDataProvider.prototype.setDiscussionName = function (discussionId, name, callback) { }; VCDataProvider.prototype.setEnvironment = function (isPrivate) { this.addon.setEnvironment(isPrivate); }; VCDataProvider.prototype.addConversation = function (conversation, callback) { }; VCDataProvider.prototype.updateConversation = function (conversation) { return null; }; VCDataProvider.prototype.getConversationNotificationStatus = function (params, callback) { var conversationType = params.conversationType; var targetId = params.targetId; var notification = RongIMLib.RongIMClient._memoryStore.notification; var key = conversationType + '_' + targetId; var status = notification[key]; if (typeof status == 'number') { callback.onSuccess(status); return; } this.addon.getConversationNotificationStatus(conversationType, targetId, function (status) { notification[key] = status; callback.onSuccess(status); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.setConversationNotificationStatus = function (params, callback) { var conversationType = params.conversationType; var targetId = params.targetId; var status = params.status; var notification = RongIMLib.RongIMClient._memoryStore.notification; var key = conversationType + '_' + targetId; notification[key] = status; var notify = !!status; this.addon.setConversationNotificationStatus(conversationType, targetId, notify, function () { callback.onSuccess(status); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.getCurrentConnectionStatus = function () { return this.addon.getConnectionStatus(); }; VCDataProvider.prototype.getAgoraDynamicKey = function (engineType, channelName, callback) { var extra = ""; this.addon.getVoIPKey(engineType, channelName, extra, function (token) { callback.onSuccess(token); }, function (errorCode) { callback.onError(errorCode); }); }; VCDataProvider.prototype.getPublicServiceProfile = function (publicServiceType, publicServiceId, callback) { var profile = RongIMLib.RongIMClient._memoryStore.publicServiceMap.get(publicServiceType, publicServiceId); callback.onSuccess(profile); }; VCDataProvider.prototype.setDeviceInfo = function (device) { var id = device.id || ''; this.addon.setDeviceId(id); }; VCDataProvider.prototype.getRemotePublicServiceList = function (callback, pullMessageTime) { var publicList = []; var ret = this.addon.getAccounts(); var transformProto = function (ret) { var result = { hasFollowed: false, isGlobal: false, menu: null }; if (!ret.obj) { var error = { error: ret }; throw new Error('公众账号数据格式错误: ' + JSON.stringify(error)); } var obj = JSON.parse(ret.obj); var protoMap = { aType: 'conversationType', aId: 'publicServiceId', aName: 'introduction', aUri: 'portraitUri', follow: 'hasFollowed', isGlobal: 'isGlobal' }; for (var key in obj) { var val = obj[key]; if (key == 'aExtra') { var extra = JSON.parse(val); result["hasFollowed"] = extra.follow; result["isGlobal"] = extra.isGlobal; result["menu"] = extra.menu; } var uId = protoMap[key]; if (uId) { result[uId] = val; } } return result; }; if (ret) { ret = JSON.parse(ret); var list = ret.list; for (var i = 0, len = list.length; i < len; i++) { var item = list[i]; item = transformProto(item); publicList.push(item); } } if (publicList.length > 0) { RongIMLib.RongIMClient._memoryStore.publicServiceMap.publicServiceList.length = 0; RongIMLib.RongIMClient._memoryStore.publicServiceMap.publicServiceList = publicList; } callback.onSuccess(RongIMLib.RongIMClient._memoryStore.publicServiceMap.publicServiceList); }; VCDataProvider.prototype.buildMessage = function (result) { var message = new RongIMLib.Message(), ret = JSON.parse(result); message.conversationType = ret.conversationType; message.targetId = ret.targetId; message.messageDirection = ret.direction; message.senderUserId = ret.senderUserId; if (ret.direction == RongIMLib.MessageDirection.RECEIVE) { message.receivedStatus = ret.status; } else if (ret.direction == RongIMLib.MessageDirection.SEND) { message.sentStatus = ret.status; } message.sentTime = ret.sentTime; message.objectName = ret.objectName; var content = ret.content ? JSON.parse(ret.content) : ret.content; var messageType = typeMapping[ret.objectName] || registerMessageTypeMapping[ret.objectName]; if (content) { content.messageName = messageType; } message.content = content; message.messageId = ret.messageId; message.messageUId = ret.messageUid; message.messageType = messageType; return message; }; VCDataProvider.prototype.buildConversation = function (val) { if (val === '') { return null; } var conver = new RongIMLib.Conversation(), c = JSON.parse(val), lastestMsg = c.lastestMsg ? this.buildMessage(c.lastestMsg) : {}; conver.conversationTitle = c.title; conver.conversationType = c.conversationType; conver.draft = c.draft; conver.isTop = c.isTop; conver.isHidden = c.isHidden; lastestMsg.conversationType = c.conversationType; lastestMsg.targetId = c.targetId; conver.latestMessage = lastestMsg; conver.latestMessageId = lastestMsg.messageId; conver.latestMessage.messageType = typeMapping[lastestMsg.objectName] || registerMessageTypeMapping[lastestMsg.objectName]; conver.objectName = lastestMsg.objectName; conver.receivedStatus = RongIMLib.ReceivedStatus.READ; conver.sentTime = lastestMsg.sentTime; conver.senderUserId = lastestMsg.senderUserId; conver.sentStatus = lastestMsg.status; conver.targetId = c.targetId; conver.unreadMessageCount = c.unreadCount; conver.hasUnreadMention = c.m_hasUnreadMention; var mentions = this.getUnreadMentionedMessages(c.conversationType, c.targetId); if (mentions.length > 0) { // 取最后一条 @ 消息,原因:和 web 互相兼容 var mention = mentions.pop(); conver.mentionedMsg = { uid: mention.messageUid, time: mention.sentTime, mentionedInfo: mention.content.mentionedInfo, sendUserId: mention.senderUserId }; } return conver; }; return VCDataProvider; })(); RongIMLib.VCDataProvider = VCDataProvider; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var MemeoryProvider = (function () { function MemeoryProvider() { this._memeoryStore = {}; this.prefix = "rong_"; } MemeoryProvider.prototype.setItem = function (composedKey, object) { this._memeoryStore[composedKey] = decodeURIComponent(object); }; MemeoryProvider.prototype.getItem = function (composedKey) { return this._memeoryStore[composedKey]; }; MemeoryProvider.prototype.removeItem = function (composedKey) { if (this.getItem(composedKey)) { delete this._memeoryStore[composedKey]; } }; MemeoryProvider.prototype.getItemKey = function (regStr) { var me = this, item = null, reg = new RegExp(regStr + "\\w+"); for (var key in me._memeoryStore) { var arr = key.match(reg); if (arr) { item = key; } } return item; }; MemeoryProvider.prototype.getItemKeyList = function (regStr) { var prefix = this.prefix; var me = this, itemList = [], reg = new RegExp(regStr + "\\w+"); for (var key in me._memeoryStore) { var arr = key.match(reg); if (arr) { key = key.substring(prefix.length); itemList.push(key); } } return itemList; }; MemeoryProvider.prototype.clearItem = function () { var me = this; for (var key in me._memeoryStore) { delete me._memeoryStore[key]; } }; //单位:字节 MemeoryProvider.prototype.onOutOfQuota = function () { return 4 * 1024; }; return MemeoryProvider; })(); RongIMLib.MemeoryProvider = MemeoryProvider; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var LocalStorageProvider = (function () { // static _instance: LocalStorageProvider = new LocalStorageProvider(); function LocalStorageProvider() { this.prefix = 'rong_'; this._host = ""; var d = new Date(), m = d.getMonth() + 1, date = d.getFullYear() + '/' + (m.toString().length == 1 ? '0' + m : m) + '/' + d.getDate(), nowDate = new Date(date).getTime(); for (var key in localStorage) { if (key.lastIndexOf('RECEIVED') > -1) { var recObj = JSON.parse(localStorage.getItem(key)); for (var key_1 in recObj) { nowDate - recObj[key_1].dealtime > 0 && (delete recObj[key_1]); } if (RongIMLib.RongUtil.isEmpty(recObj)) { localStorage.removeItem(key); } else { localStorage.setItem(key, JSON.stringify(recObj)); } } if (key.lastIndexOf('SENT') > -1) { var sentObj = JSON.parse(localStorage.getItem(key)); nowDate - sentObj.dealtime > 0 && (localStorage.removeItem(key)); } } } LocalStorageProvider.prototype.setItem = function (composedKey, object) { if (composedKey) { composedKey.indexOf(this.prefix) == -1 && (composedKey = this.prefix + composedKey); localStorage.setItem(composedKey, object); } }; LocalStorageProvider.prototype.getItem = function (composedKey) { if (composedKey) { composedKey.indexOf(this.prefix) == -1 && (composedKey = this.prefix + composedKey); return localStorage.getItem(composedKey ? composedKey : ""); } return ""; }; LocalStorageProvider.prototype.getItemKey = function (composedStr) { var item = ""; var _key = this.prefix + composedStr; for (var key in localStorage) { if (key.indexOf(_key) == 0) { item = key; break; } } return item; }; LocalStorageProvider.prototype.getItemKeyList = function (composedStr) { var itemList = []; var prefix = this.prefix; var _key = prefix + composedStr; for (var key in localStorage) { if (key.indexOf(_key) == 0) { key = key.substring(prefix.length); itemList.push(key); } } return itemList; }; LocalStorageProvider.prototype.removeItem = function (composedKey) { if (composedKey) { composedKey.indexOf(this.prefix) == -1 && (composedKey = this.prefix + composedKey); localStorage.removeItem(composedKey.toString()); } }; LocalStorageProvider.prototype.clearItem = function () { var me = this; for (var key in localStorage) { if (key.indexOf(me.prefix) > -1) { me.removeItem(key); } } }; //单位:字节 LocalStorageProvider.prototype.onOutOfQuota = function () { return JSON.stringify(localStorage).length; }; return LocalStorageProvider; })(); RongIMLib.LocalStorageProvider = LocalStorageProvider; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var UserDataProvider = (function () { function UserDataProvider() { this.opersistName = 'RongIMLib'; this.keyManager = 'RongUserDataKeyManager'; this._host = ""; this.prefix = "rong_"; this.oPersist = document.createElement("div"); this.oPersist.style.display = "none"; this.oPersist.style.behavior = "url('#default#userData')"; document.body.appendChild(this.oPersist); this.oPersist.load(this.opersistName); } UserDataProvider.prototype.setItem = function (key, value) { key && key.indexOf(this.prefix) == -1 && (key = this.prefix + key); this.oPersist.setAttribute(key, value); var keyNames = this.getItem(this.keyManager); keyNames ? keyNames.indexOf(key) == -1 && (keyNames += ',' + key) : (keyNames = key); this.oPersist.setAttribute(this.prefix + this.keyManager, keyNames); this.oPersist.save(this.opersistName); }; UserDataProvider.prototype.getItem = function (key) { key && key.indexOf(this.prefix) == -1 && (key = this.prefix + key); return key ? this.oPersist.getAttribute(key) : key; }; UserDataProvider.prototype.removeItem = function (key) { key && key.indexOf(this.prefix) == -1 && (key = this.prefix + key); this.oPersist.removeAttribute(key); this.oPersist.save(this.opersistName); var keyNames = this.getItem(this.keyManager), keyNameArray = keyNames && keyNames.split(',') || []; for (var i = 0, len = keyNameArray.length; i < len; i++) { if (keyNameArray[i] == key) { keyNameArray.splice(i, 1); } } this.oPersist.setAttribute(this.prefix + this.keyManager, keyNameArray.join(',')); this.oPersist.save(this.opersistName); }; UserDataProvider.prototype.getItemKey = function (composedStr) { var item = null, keyNames = this.getItem(this.keyManager), keyNameArray = keyNames && keyNames.split(',') || [], me = this; var _key = this.prefix + composedStr; if (keyNameArray.length) { for (var i = 0, len = keyNameArray.length; i < len; i++) { if (keyNameArray[i] && keyNameArray[i].indexOf(_key) == 0) { item = keyNameArray[i]; break; } } } return item; }; UserDataProvider.prototype.getItemKeyList = function (composedStr) { var itemList = [], keyNames = this.getItem(this.keyManager), keyNameArray = keyNames && keyNames.split(',') || []; var prefix = this.prefix; var _key = prefix + composedStr; if (keyNameArray.length) { for (var i = 0, len = keyNameArray.length; i < len; i++) { if (keyNameArray[i] && keyNameArray[i].indexOf(_key) == 0) { var keyName = keyNameArray[i]; keyName = keyName.substring(prefix.length); itemList.push(keyNameArray[i]); } } } return itemList; }; UserDataProvider.prototype.clearItem = function () { var keyNames = this.getItem(this.keyManager), keyNameArray = [], me = this; keyNames && (keyNameArray = keyNames.split(',')); if (keyNameArray.length) { for (var i = 0, len = keyNameArray.length; i < len; i++) { keyNameArray[i] && me.removeItem(keyNameArray[i]); } me.removeItem(me.keyManager); } }; UserDataProvider.prototype.onOutOfQuota = function () { return 10 * 1024 * 1024; }; return UserDataProvider; })(); RongIMLib.UserDataProvider = UserDataProvider; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var FeatureDectector = (function () { function FeatureDectector(callback) { this.script = document.createElement("script"); this.head = document.getElementsByTagName("head")[0]; if ("WebSocket" in window && "ArrayBuffer" in window && WebSocket.prototype.CLOSED === 3 && !RongIMLib.RongIMClient._memoryStore.depend.isPolling) { RongIMLib.Transportations._TransportType = RongIMLib.Socket.WEBSOCKET; if (!RongIMLib.RongIMClient.Protobuf) { var url = RongIMLib.RongIMClient._memoryStore.depend.protobuf; var script = this.script; script.src = url; this.head.appendChild(script); script.onload = script.onreadystatechange = function () { var isLoaded = (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete'); if (isLoaded) { // 防止 IE6、7 下偶发触发两次 loaded script.onload = script.onreadystatechange = null; if (callback) { callback(); } if (!callback) { var token = RongIMLib.RongIMClient._memoryStore.token; var connectCallback = RongIMLib.RongIMClient._memoryStore.callback; token && RongIMLib.RongIMClient.connect(token, connectCallback); } } }; } } else { RongIMLib.Transportations._TransportType = "xhr-polling"; RongIMLib.RongIMClient.Protobuf = Polling; } } return FeatureDectector; })(); RongIMLib.FeatureDectector = FeatureDectector; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var FeaturePatcher = (function () { function FeaturePatcher() { } FeaturePatcher.prototype.patchAll = function () { this.patchJSON(); this.patchForEach(); }; FeaturePatcher.prototype.patchForEach = function () { if (!Array.forEach) { Array.forEach = function (arr, func) { for (var i = 0; i < arr.length; i++) { func.call(arr, arr[i], i, arr); } }; } }; FeaturePatcher.prototype.patchJSON = function () { if (!window["JSON"]) { window["JSON"] = (function () { function JSON() { } JSON.parse = function (sJSON) { return eval('(' + sJSON + ')'); }; JSON.stringify = function (value) { return this.str("", { "": value }); }; JSON.str = function (key, holder) { var i, k, v, length, mind = "", partial, value = holder[key], me = this; if (value && typeof value === "object" && typeof value.toJSON === "function") { value = value.toJSON(key); } switch (typeof value) { case "string": return me.quote(value); case "number": return isFinite(value) ? String(value) : "null"; case "boolean": case "null": return String(value); case "object": if (!value) { return "null"; } partial = []; if (Object.prototype.toString.apply(value) === "[object Array]") { length = value.length; for (i = 0; i < length; i += 1) { partial[i] = me.str(i, value) || "null"; } v = partial.length === 0 ? "[]" : "[" + partial.join(",") + "]"; return v; } for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = me.str(k, value); if (v) { partial.push(me.quote(k) + ":" + v); } } } v = partial.length === 0 ? "{}" : "{" + partial.join(",") + "}"; return v; } }; JSON.quote = function (string) { var me = this; me.rx_escapable.lastIndex = 0; return me.rx_escapable.test(string) ? '"' + string.replace(me.rx_escapable, function (a) { var c = me.meta[a]; return typeof c === "string" ? c : "\\u" + ("0000" + a.charCodeAt(0).toString(16)).slice(-4); }) + '"' : '"' + string + '"'; }; JSON.rx_escapable = new RegExp('[\\\"\\\\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]', "g"); JSON.meta = { "\b": "\\b", " ": "\\t", "\n": "\\n", "\f": "\\f", "\r": "\\r", '"': '\\"', "''": "\\''", "\\": "\\\\" }; return JSON; })(); } }; return FeaturePatcher; })(); RongIMLib.FeaturePatcher = FeaturePatcher; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var ScriptLoader = (function () { function ScriptLoader() { } ScriptLoader.prototype.load = function (src, onLoad, onError) { var script = document.createElement("script"); script.async = true; if (onLoad) { if (script.addEventListener) { script.addEventListener("load", function (event) { var target = event.target || event.srcElement; onLoad(target.src); }, false); } else if (script.readyState) { script.onreadystatechange = function (event) { var target = event.srcElement; onLoad(target.src); }; } } if (onError) { script.onerror = function (event) { var target = event.target || event.srcElement; onError(target.src); }; } (document.head || document.getElementsByTagName("head")[0]).appendChild(script); script.src = src; }; return ScriptLoader; })(); })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var PublicServiceMap = (function () { function PublicServiceMap() { this.publicServiceList = []; } PublicServiceMap.prototype.get = function (publicServiceType, publicServiceId) { for (var i = 0, len = this.publicServiceList.length; i < len; i++) { if (this.publicServiceList[i].conversationType == publicServiceType && publicServiceId == this.publicServiceList[i].publicServiceId) { return this.publicServiceList[i]; } } }; PublicServiceMap.prototype.add = function (publicServiceProfile) { var isAdd = true, me = this; for (var i = 0, len = this.publicServiceList.length; i < len; i++) { if (me.publicServiceList[i].conversationType == publicServiceProfile.conversationType && publicServiceProfile.publicServiceId == me.publicServiceList[i].publicServiceId) { this.publicServiceList.unshift(this.publicServiceList.splice(i, 1)[0]); isAdd = false; break; } } if (isAdd) { this.publicServiceList.unshift(publicServiceProfile); } }; PublicServiceMap.prototype.replace = function (publicServiceProfile) { var me = this; for (var i = 0, len = this.publicServiceList.length; i < len; i++) { if (me.publicServiceList[i].conversationType == publicServiceProfile.conversationType && publicServiceProfile.publicServiceId == me.publicServiceList[i].publicServiceId) { me.publicServiceList.splice(i, 1, publicServiceProfile); break; } } }; PublicServiceMap.prototype.remove = function (conversationType, publicServiceId) { var me = this; for (var i = 0, len = this.publicServiceList.length; i < len; i++) { if (me.publicServiceList[i].conversationType == conversationType && publicServiceId == me.publicServiceList[i].publicServiceId) { this.publicServiceList.splice(i, 1); break; } } }; return PublicServiceMap; })(); RongIMLib.PublicServiceMap = PublicServiceMap; /** * 会话工具类。 */ var ConversationMap = (function () { function ConversationMap() { this.conversationList = []; } ConversationMap.prototype.get = function (conversavtionType, targetId) { for (var i = 0, len = this.conversationList.length; i < len; i++) { if (this.conversationList[i].conversationType == conversavtionType && this.conversationList[i].targetId == targetId) { return this.conversationList[i]; } } return null; }; ConversationMap.prototype.add = function (conversation) { var isAdd = true; for (var i = 0, len = this.conversationList.length; i < len; i++) { if (this.conversationList[i].conversationType === conversation.conversationType && this.conversationList[i].targetId === conversation.targetId) { this.conversationList.unshift(this.conversationList.splice(i, 1)[0]); isAdd = false; break; } } if (isAdd) { this.conversationList.unshift(conversation); } }; /** * [replace 替换会话] * 会话数组存在的情况下调用add方法会是当前会话被替换且返回到第一个位置,导致用户本地一些设置失效,所以提供replace方法 */ ConversationMap.prototype.replace = function (conversation) { for (var i = 0, len = this.conversationList.length; i < len; i++) { if (this.conversationList[i].conversationType === conversation.conversationType && this.conversationList[i].targetId === conversation.targetId) { this.conversationList.splice(i, 1, conversation); break; } } }; ConversationMap.prototype.remove = function (conversation) { for (var i = 0, len = this.conversationList.length; i < len; i++) { if (this.conversationList[i].conversationType === conversation.conversationType && this.conversationList[i].targetId === conversation.targetId) { this.conversationList.splice(i, 1); break; } } }; return ConversationMap; })(); RongIMLib.ConversationMap = ConversationMap; var CheckParam = (function () { function CheckParam() { } CheckParam.getInstance = function () { if (!CheckParam._instance) { CheckParam._instance = new CheckParam(); } return CheckParam._instance; }; CheckParam.prototype.logger = function (code, funcName, msg) { RongIMLib.RongIMClient.logger({ code: code, funcName: funcName, msg: msg }); }; CheckParam.prototype.check = function (f, position, d, c) { if (RongIMLib.RongIMClient._dataAccessProvider || d) { for (var g = 0, e = c.length; g < e; g++) { if (!new RegExp(this.getType(c[g])).test(f[g])) { // throw new Error("The index of " + g + " parameter was wrong type " + this.getType(c[g]) + " [" + f[g] + "] -> position:" + position); var msg = "第" + (g + 1) + "个参数错误, 错误类型:" + this.getType(c[g]) + " [" + f[g] + "] -> 位置:" + position; this.logger("-3", position, msg); } } } else { var msg = "该参数不正确或尚未实例化RongIMClient -> 位置:" + position; this.logger("-4", position, msg); } }; CheckParam.prototype.getType = function (str) { var temp = Object.prototype.toString.call(str).toLowerCase(); return temp.slice(8, temp.length - 1); }; CheckParam.prototype.checkCookieDisable = function () { document.cookie = "checkCookie=1"; var arr = document.cookie.match(new RegExp("(^| )checkCookie=([^;]*)(;|$)")), isDisable = false; if (!arr) { isDisable = true; } document.cookie = "checkCookie=1;expires=Thu, 01-Jan-1970 00:00:01 GMT"; return isDisable; }; return CheckParam; })(); RongIMLib.CheckParam = CheckParam; var LimitableMap = (function () { function LimitableMap(limit) { this.map = {}; this.keys = []; this.limit = limit || 10; } LimitableMap.prototype.set = function (key, value) { this.map[key] = value; }; LimitableMap.prototype.get = function (key) { return this.map[key] || 0; }; LimitableMap.prototype.remove = function (key) { delete this.map[key]; }; return LimitableMap; })(); RongIMLib.LimitableMap = LimitableMap; var MemoryCache = (function () { function MemoryCache() { this.cache = {}; } MemoryCache.prototype.set = function (key, value) { this.cache[key] = value; }; MemoryCache.prototype.get = function (key) { return this.cache[key]; }; MemoryCache.prototype.remove = function (key) { delete this.cache[key]; }; return MemoryCache; })(); RongIMLib.MemoryCache = MemoryCache; var RongAjax = (function () { function RongAjax(options) { var me = this; me.xmlhttp = null; me.options = options; var hasCORS = typeof XMLHttpRequest !== "undefined" && "withCredentials" in new XMLHttpRequest(); if ("undefined" != typeof XMLHttpRequest && hasCORS) { me.xmlhttp = new XMLHttpRequest(); } else if ("undefined" != typeof XDomainRequest) { me.xmlhttp = new XDomainRequest(); } else { me.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } } RongAjax.prototype.send = function (callback) { var me = this; me.options.url || (me.options.url = "http://upload.qiniu.com/putb64/-1"); me.xmlhttp.onreadystatechange = function () { if (me.xmlhttp.readyState == 4) { if (me.options.type) { callback(); } else { callback(JSON.parse(me.xmlhttp.responseText.replace(/'/g, '"'))); } } }; me.xmlhttp.open("POST", me.options.url, true); me.xmlhttp.withCredentials = false; if ("setRequestHeader" in me.xmlhttp) { if (me.options.type) { me.xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=utf-8"); } else { me.xmlhttp.setRequestHeader("Content-type", "application/octet-stream"); me.xmlhttp.setRequestHeader('Authorization', "UpToken " + me.options.token); } } me.xmlhttp.send(me.options.type ? "appKey=" + me.options.appKey + "&deviceId=" + me.options.deviceId + "×tamp=" + me.options.timestamp + "&deviceInfo=" + me.options.deviceInfo + "&privateInfo=" + JSON.stringify(me.options.privateInfo) : me.options.base64); }; return RongAjax; })(); RongIMLib.RongAjax = RongAjax; var RongUtil = (function () { function RongUtil() { } RongUtil.noop = function () { }; RongUtil.isEmpty = function (obj) { var empty = true; for (var key in obj) { empty = false; break; } return empty; }; RongUtil.MD5 = function (str, key, raw) { return md5(str, key, raw); }; RongUtil.isObject = function (obj) { return Object.prototype.toString.call(obj) == '[object Object]'; }; RongUtil.isArray = function (array) { return Object.prototype.toString.call(array) == '[object Array]'; }; RongUtil.isFunction = function (fun) { return Object.prototype.toString.call(fun) == '[object Function]'; }; ; RongUtil.stringFormat = function (tmpl, vals) { for (var i = 0, len = vals.length; i < len; i++) { var val = vals[i], reg = new RegExp("\\{" + (i) + "\\}", "g"); tmpl = tmpl.replace(reg, val); } return tmpl; }; RongUtil.tplEngine = function (temp, data, regexp) { if (!(Object.prototype.toString.call(data) === "[object Array]")) { data = [data]; } var ret = []; for (var i = 0, j = data.length; i < j; i++) { ret.push(replaceAction(data[i])); } return ret.join(""); function replaceAction(object) { return temp.replace(regexp || (/{([^}]+)}/g), function (match, name) { if (match.charAt(0) == '\\') { return match.slice(1); } return (object[name] != undefined) ? object[name] : '{' + name + '}'; }); } }; ; RongUtil.forEach = function (obj, callback) { callback = callback || RongUtil.noop; var loopObj = function () { for (var key in obj) { callback(obj[key], key, obj); } }; var loopArr = function () { for (var i = 0, len = obj.length; i < len; i++) { callback(obj[i], i); } }; if (RongUtil.isObject(obj)) { loopObj(); } if (RongUtil.isArray(obj)) { loopArr(); } }; RongUtil.extend = function (source, target, callback, force) { RongUtil.forEach(source, function (val, key) { var hasProto = (key in target); if (force && hasProto) { target[key] = val; } if (!hasProto) { target[key] = val; } }); return target; }; RongUtil.createXHR = function () { var item = { XMLHttpRequest: function () { return new XMLHttpRequest(); }, XDomainRequest: function () { return new XDomainRequest(); }, ActiveXObject: function () { return new ActiveXObject('Microsoft.XMLHTTP'); } }; var isXHR = (typeof XMLHttpRequest == 'function'); var isXDR = (typeof XDomainRequest == 'function'); var key = isXHR ? 'XMLHttpRequest' : isXDR ? 'XDomainRequest' : 'ActiveXObject'; return item[key](); }; RongUtil.request = function (opts) { var url = opts.url; var success = opts.success; var error = opts.error; var method = opts.method || 'GET'; var xhr = RongUtil.createXHR(); xhr.onreadystatechange = function () { if (xhr.readyState == 4) { if (xhr.status == 200) { success(); } else { error(); } } }; xhr.open(method, url, true); xhr.send(null); }; RongUtil.formatProtoclPath = function (config) { var path = config.path; var protocol = config.protocol; var tmpl = config.tmpl || '{0}{1}'; var sub = config.sub; var flag = '://'; var index = path.indexOf(flag); var hasProtocol = (index > -1); if (hasProtocol) { index += flag.length; path = path.substring(index); } if (sub) { index = path.indexOf('/'); var hasPath = (index > -1); if (hasPath) { path = path.substr(0, index); } } return RongUtil.stringFormat(tmpl, [protocol, path]); }; ; RongUtil.supportLocalStorage = function () { var support = false; if (typeof localStorage == 'object') { try { var key = 'RC_TMP_KEY', value = 'RC_TMP_VAL'; localStorage.setItem(key, value); var localVal = localStorage.getItem(key); if (localVal == value) { support = true; } } catch (err) { console.log('localStorage is disabled.'); } } return support; }; /* //返回新引用,不破坏原始对象 rename({n: 'martin'}, {n: 'name'}); => {name: 'martin'} rename([{n: 'martin'}, {a: 18}], {n: 'name', a: 'age'}); => [{name: 'martin'}, {age: 18}] */ RongUtil.rename = function (origin, newNames) { var isObject = RongUtil.isObject(origin); if (isObject) { origin = [origin]; } origin = JSON.parse(JSON.stringify(origin)); var updateProperty = function (val, key, obj) { delete obj[key]; key = newNames[key]; obj[key] = val; }; RongUtil.forEach(origin, function (item) { RongUtil.forEach(item, function (val, key, obj) { var isRename = (key in newNames); (isRename ? updateProperty : RongUtil.noop)(val, key, obj); }); }); return isObject ? origin[0] : origin; }; RongUtil.some = function (arrs, callback) { var has = false; for (var i = 0, len = arrs.length; i < len; i++) { if (callback(arrs[i])) { has = true; break; } } return has; }; RongUtil.keys = function (obj) { var props = []; for (var key in obj) { props.push(key); } return props; }; RongUtil.isNumber = function (num) { return Object.prototype.toString.call(num) == '[object Number]'; }; RongUtil.getTimestamp = function () { var date = new Date(); return date.getTime(); }; return RongUtil; })(); RongIMLib.RongUtil = RongUtil; /* var observer = new RongObserver(); observer.watch({ key: 'key', func: function(entity){ } }); */ var RongObserver = (function () { function RongObserver() { this.watchers = {}; } RongObserver.prototype.genUId = function (key) { var time = new Date().getTime(); return [key, time].join('_'); }; RongObserver.prototype.watch = function (params) { var me = this; var key = params.key; var multiple = params.multiple; key = RongUtil.isArray(key) ? key : [key]; var func = params.func; RongUtil.forEach(key, function (k) { k = multiple ? me.genUId(k) : k; me.watchers[k] = func; }); }; RongObserver.prototype.notify = function (params) { var me = this; var key = params.key; var entity = params.entity; for (var k in me.watchers) { var isNotify = (k.indexOf(key) == 0); if (isNotify) { me.watchers[k](entity); } } }; RongObserver.prototype.remove = function () { }; return RongObserver; })(); RongIMLib.RongObserver = RongObserver; var Timer = (function () { function Timer(config) { this.timeout = 0; this.timer = null; this.timeout = config.timeout; } Timer.prototype.resume = function (callback) { this.timer = setTimeout(callback, this.timeout); }; Timer.prototype.pause = function () { clearTimeout(this.timer); }; return Timer; })(); RongIMLib.Timer = Timer; var InnerUtil = (function () { function InnerUtil() { } InnerUtil.getUId = function (token) { return md5(token).slice(8, 16); }; return InnerUtil; })(); RongIMLib.InnerUtil = InnerUtil; })(RongIMLib || (RongIMLib = {})); /* 说明: 请勿修改 header.js 和 footer.js 用途: 自动拼接暴露方式 命令: grunt release 中 concat */ return RongIMLib; }); ================================================ FILE: api-test-v2/lib/js/RongIMLib-2.5.1.js ================================================ /* 说明: 请勿修改 header.js 和 footer.js 用途: 自动拼接暴露方式 命令: grunt release 中 concat */ (function(global, factory) { if (typeof exports === 'object' && typeof module !== 'undefined') { module.exports = factory(); } else if (typeof define === 'function' && (define.amd || define.cmd)) { define(factory); } else { var tempIMLib = factory(); var tempClient = tempIMLib.RongIMClient; var isExists = (!!global.RongIMLib); if (isExists) { var currentClient = RongIMLib.RongIMClient || {}; for(var key in currentClient){ tempClient[key] = currentClient[key]; } } global.RongIMLib = tempIMLib; global.RongIMClient = tempClient; } })(window, function(){ var Polling = { SetUserStatusInput: function(){ var a = {}; this.setStatus = function(b){ a.status = b; }; this.toArrayBuffer = function(){ return a; }; }, SetUserStatusOutput: function(){ var a = {}; this.setNothing = function(b){ a.nothing = b; }; this.toArrayBuffer = function(){ return a; }; }, GetUserStatusInput: function(){ var a = {}; this.setNothing = function(b){ a.nothing = b; }; this.toArrayBuffer = function(){ return a; }; }, GetUserStatusOutput: function(){ var a = {}; this.setStatus = function(b){ a.status = b; }; this.setSubUserId = function(b){ a.subUserId = b; }; this.toArrayBuffer = function(){ return a; }; }, VoipDynamicInput: function(){ var a = {}; this.setEngineType = function(b){ a.engineType = b; }; this.setChannelName = function(b){ a.channelName = b; }; this.setChannelExtra = function(b){ a.channelExtra = b; }; this.toArrayBuffer = function(){ return a; }; }, VoipDynamicOutput: function(){ var a = {}; this.setDynamicKey = function(b){ a.dynamicKey = b; }; this.toArrayBuffer = function(){ return a; }; }, SubUserStatusInput: function(){ var a = {}; this.setUserid = function(b){ a.userid = b; }; this.toArrayBuffer = function(){ return a; }; }, SubUserStatusOutput: function(){ var a = {}; this.setNothing = function(b){ a.nothing = b; }; this.toArrayBuffer = function(){ return a; }; }, CleanHisMsgInput: function(){ var a = {}; this.setTargetId = function(b){ a.targetId = b; }; this.setDataTime = function(b){ a.dataTime = b; }; this.setConversationType = function(b){ a.conversationType = b; }; this.toArrayBuffer = function(){ return a; }; }, DeleteMsgInput:function(){ var a = {}; this.setType = function(b){ a.type = b; }; this.setConversationId = function(b){ a.conversationId = b; }; this.setMsgs = function(b){ a.msgs = b; }; this.toArrayBuffer = function () { return a; } }, DeleteMsg:function(){ var a = {}; this.setMsgId = function(b){ a.msgId = b; }; this.setMsgDataTime = function(b){ a.msgDataTime = b; }; this.setDirect = function(b){ a.direct = b; }; this.toArrayBuffer = function () { return a; } }, DeleteMsgOutput:function(){ var a = {}; this.setNothing = function(b){ a.nothing = b; }; this.toArrayBuffer = function () { return a; } }, SearchMpInput:function(){ var a = {}; this.setType = function (b) { a.type = b; }; this.setId = function (b) { a.id = b; }; this.toArrayBuffer = function () { return a; } }, SearchMpOutput:function(){ var a = {}; this.setNothing = function (b) { a.nothing = b; }; this.setInfo = function (b) { a.info = b; }; this.toArrayBuffer = function () { return a; } }, MpInfo:function(){ var a = {}; this.setMpid = function(b){ a.mpid = b; }; this.setName = function(b){ a.name = b; }; this.setType = function(b){ a.type = b; }; this.setTime = function(b){ a.time = b; }; this.setPortraitUri = function(b){ a.portraitUrl = b; }; this.setExtra = function(b){ a.extra = b; }; this.toArrayBuffer = function () { return a; } }, PullMpInput:function(){ var a = {}; this.setMpid = function(b){ a.mpid = b; }; this.setTime = function(b){ a.time = b; }; this.toArrayBuffer = function () { return a; }; }, PullMpOutput:function(){ var a = {}; this.setStatus = function(b){ a.status = b; } this.setInfo = function(b){ a.info = b; }; this.toArrayBuffer = function () { return a; }; }, MPFollowInput:function(){ var a = {}; this.setId = function(b){ a.id = b; }; this.toArrayBuffer = function () { return a; }; }, MPFollowOutput:function(){ var a = {}; this.setNothing = function(b){ a.nothing = b; }; this.setInfo = function(b){ a.info = b; }; this.toArrayBuffer = function () { return a; }; }, NotifyMsg: function () { var a = {}; this.setType = function (b) { a.type = b; }; this.setTime = function (b) { a.time = b; }; this.setChrmId = function(b){ a.chrmId = b; }; this.toArrayBuffer = function () { return a; }; }, SyncRequestMsg: function () { var a = {}; this.setSyncTime = function (b) { a.syncTime = b || 0; }; this.setIspolling = function (b) { a.ispolling = !!b; }; this.setIsweb = function (b) { a.isweb = !!b; }; this.setIsPullSend = function (b) { a.isPullSend = !!b; }; this.setSendBoxSyncTime = function (b) { a.sendBoxSyncTime = b; }; this.toArrayBuffer = function () { return a; }; }, UpStreamMessage: function () { var a = {}; this.setSessionId = function (b) { a.sessionId = b }; this.setClassname = function (b) { a.classname = b }; this.setContent = function (b) { if (b) a.content = b; }; this.setPushText = function (b) { a.pushText = b }; this.setUserId = function(b){ a.userId = b; }; this.setAppData = function(b){ a.appData = b; }; this.toArrayBuffer = function () { return a }; }, DownStreamMessages: function () { var a = {}; this.setList = function (b) { a.list = b }; this.setSyncTime = function (b) { a.syncTime = b; }; this.setFinished = function(b){ a.finished = b; }; this.toArrayBuffer = function () { return a }; }, DownStreamMessage: function () { var a = {}; this.setFromUserId = function (b) { a.fromUserId = b }; this.setType = function (b) { a.type = b }; this.setGroupId = function (b) { a.groupId = b }; this.setClassname = function (b) { a.classname = b }; this.setContent = function (b) { if (b) a.content = b }; this.setDataTime = function (b) { a.dataTime = b; }; this.setStatus = function (b) { a.status = b; }; this.setMsgId = function (b) { a.msgId = b; }; this.toArrayBuffer = function () { return a; }; }, CreateDiscussionInput: function () { var a = {}; this.setName = function (b) { a.name = b }; this.toArrayBuffer = function () { return a } }, CreateDiscussionOutput: function () { var a = {}; this.setId = function (b) { a.id = b }; this.toArrayBuffer = function () { return a }; }, ChannelInvitationInput: function () { var a = {}; this.setUsers = function (b) { a.users = b }; this.toArrayBuffer = function () { return a }; }, LeaveChannelInput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b }; this.toArrayBuffer = function () { return a }; }, QueryChatroomInfoInput:function(){ var a = {}; this.setCount = function (b) { a.count = b; }; this.setOrder = function (b) { a.order = b; }; this.toArrayBuffer = function () { return a }; }, QueryChatroomInfoOutput:function(){ var a = {}; this.setUserTotalNums = function (b) { a.userTotalNums = b; }; this.setUserInfos = function (b) { a.userInfos = b; }; this.toArrayBuffer = function () { return a; }; }, ChannelEvictionInput: function () { var a = {}; this.setUser = function (b) { a.user = b }; this.toArrayBuffer = function () { return a }; }, RenameChannelInput: function () { var a = {}; this.setName = function (b) { a.name = b }; this.toArrayBuffer = function () { return a } }, ChannelInfoInput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b }; this.toArrayBuffer = function () { return a } }, ChannelInfoOutput: function () { var a = {}; this.setType = function (b) { a.type = b }; this.setChannelId = function (b) { a.channelId = b }; this.setChannelName = function (b) { a.channelName = b }; this.setAdminUserId = function (b) { a.adminUserId = b }; this.setFirstTenUserIds = function (b) { a.firstTenUserIds = b }; this.setOpenStatus = function (b) { a.openStatus = b }; this.toArrayBuffer = function () { return a } }, ChannelInfosInput: function () { var a = {}; this.setPage = function (b) { a.page = b }; this.setNumber = function (b) { a.number = b }; this.toArrayBuffer = function () { return a }; }, ChannelInfosOutput: function () { var a = {}; this.setChannels = function (b) { a.channels = b }; this.setTotal = function (b) { a.total = b }; this.toArrayBuffer = function () { return a }; }, MemberInfo: function () { var a = {}; this.setUserId = function (b) { a.userId = b }; this.setUserName = function (b) { a.userName = b }; this.setUserPortrait = function (b) { a.userPortrait = b }; this.setExtension = function (b) { a.extension = b }; this.toArrayBuffer = function () { return a }; }, GroupMembersInput: function () { var a = {}; this.setPage = function (b) { a.page = b }; this.setNumber = function (b) { a.number = b }; this.toArrayBuffer = function () { return a }; }, GroupMembersOutput: function () { var a = {}; this.setMembers = function (b) { a.members = b }; this.setTotal = function (b) { a.total = b }; this.toArrayBuffer = function () { return a }; }, GetUserInfoInput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b }; this.toArrayBuffer = function () { return a }; }, GetUserInfoOutput: function () { var a = {}; this.setUserId = function (b) { a.userId = b }; this.setUserName = function (b) { a.userName = b }; this.setUserPortrait = function (b) { a.userPortrait = b }; this.toArrayBuffer = function () { return a }; }, GetSessionIdInput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b }; this.toArrayBuffer = function () { return a }; }, GetSessionIdOutput: function () { var a = {}; this.setSessionId = function (b) { a.sessionId = b }; this.toArrayBuffer = function () { return a }; }, GetQNupTokenInput: function () { var a = {}; this.setType = function (b) { a.type = b; } this.toArrayBuffer = function () { return a } }, GetQNupTokenOutput: function () { var a = {}; this.setDeadline = function (b) { a.deadline = b }; this.setToken = function (b) { a.token = b; }; this.toArrayBuffer = function () { return a } }, GetQNdownloadUrlInput: function () { var a = {}; this.setType = function (b) { a.type = b; }; this.setKey = function (b) { a.key = b; }; this.setFileName = function(b){ a.fileName = b; }; this.toArrayBuffer = function () { return a } }, GetQNdownloadUrlOutput: function () { var a = {}; this.setDownloadUrl = function (b) { a.downloadUrl = b; }; this.toArrayBuffer = function () { return a } }, Add2BlackListInput: function () { var a = {}; this.setUserId = function (b) { a.userId = b; }; this.toArrayBuffer = function () { return a } }, RemoveFromBlackListInput: function () { var a = {}; this.setUserId = function (b) { a.userId = b; }; this.toArrayBuffer = function () { return a } }, QueryBlackListInput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b; }; this.toArrayBuffer = function () { return a } }, QueryBlackListOutput: function () { var a = {}; this.setUserIds = function (b) { a.userIds = b; }; this.toArrayBuffer = function () { return a } }, BlackListStatusInput: function () { var a = {}; this.setUserId = function (b) { a.userId = b; }; this.toArrayBuffer = function () { return a } }, BlockPushInput: function () { var a = {}; this.setBlockeeId = function (b) { a.blockeeId = b; }; this.toArrayBuffer = function () { return a } }, ModifyPermissionInput: function () { var a = {}; this.setOpenStatus = function (b) { a.openStatus = b; }; this.toArrayBuffer = function () { return a }; }, GroupInput: function () { var a = {}; this.setGroupInfo = function (b) { for (var i = 0, arr = []; i < b.length; i++) { arr.push({id: b[i].getContent().id, name: b[i].getContent().name}) } a.groupInfo = arr; }; this.toArrayBuffer = function () { return a }; }, GroupOutput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b; }; this.toArrayBuffer = function () { return a }; }, GroupInfo: function () { var a = {}; this.setId = function (b) { a.id = b; }; this.setName = function (b) { a.name = b; }; this.getContent = function () { return a; }; this.toArrayBuffer = function () { return a }; }, GroupHashInput: function () { var a = {}; this.setUserId = function (b) { a.userId = b; }; this.setGroupHashCode = function (b) { a.groupHashCode = b; }; this.toArrayBuffer = function () { return a }; }, GroupHashOutput: function () { var a = {}; this.setResult = function (b) { a.result = b; }; this.toArrayBuffer = function () { return a }; }, ChrmInput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b; }; this.toArrayBuffer = function () { return a }; }, ChrmOutput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b; }; this.toArrayBuffer = function () { return a }; }, ChrmPullMsg: function () { var a = {}; this.setSyncTime = function (b) { a.syncTime = b }; this.setCount = function (b) { a.count = b; }; this.toArrayBuffer = function () { return a }; }, RelationsInput: function () { var a = {}; this.setType = function (b) { a.type = b; }; this.setMsg = function(b){ a.msg = b; }; this.setCount = function(b){ a.count = b; }; this.toArrayBuffer = function () { return a }; }, RelationsOutput: function () { var a = {}; this.setInfo = function (b) { a.info = b; }; this.toArrayBuffer = function () { return a } }, RelationInfo: function () { var a = {}; this.setType = function (b) { a.type = b; }; this.setUserId = function (b) { a.userId = b; }; this.setMsg = function(b){ a.msg = b; }; this.toArrayBuffer = function () { return a } }, HistoryMessageInput: function () { var a={}; this.setTargetId=function(b){ a.targetId=b; }; this.setDataTime=function(b){ a.dataTime=b; }; this.setSize=function(b){ a.size=b; }; this.toArrayBuffer = function () { return a } }, HistoryMessagesOuput: function () { var a={}; this.setList=function(b){ a.list=b; }; this.setSyncTime=function(b){ a.syncTime=b; }; this.setHasMsg=function(b){ a.hasMsg=b; }; this.toArrayBuffer = function () { return a } }, HistoryMsgInput: function(){ var a = {}; this.setTargetId = function(b){ a.targetId = b; }; this.setTime = function(b){ a.time = b; }; this.setCount = function(b){ a.count = b; }; this.setOrder = function(b){ a.order = b; }; this.toArrayBuffer = function(){ return a; }; }, HistoryMsgOuput: function(){ var a = {}; this.setList = function(b){ a.list = b; }; this.setSyncTime = function(b){ a.syncTime = b; }; this.setHasMsg = function(b){ a.hasMsg = b; }; this.toArrayBuffer = function(){ return a; }; }, RtcQueryListInput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setOrder = function (b) { a.order = b; }; }, RtcKeyDeleteInput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setKey = function (b) { a.key = b; }; }, RtcValueInfo: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setKey = function (b) { a.key = b; }; this.setValue = function (b) { a.value = b; }; }, // RtcUserInfo: function () { // var a = {}; // }, RtcUserListOutput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setList = function (b) { a.list = b; }; this.setToken = function (b) { a.token = b; }; }, RtcRoomInfoOutput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setRoomId = function (b) { a.roomId = b; }; this.setRoomData = function (b) { a.roomData = b; }; this.setUserCount = function (b) { a.userCount = b; }; this.setList = function (b) { a.list = b; } }, RtcInput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setRoomType = function (b) { a.roomType = b; }; this.setBroadcastType = function (b) { a.broadcastType = b; } }, // RtcQryInput: function () { // var a = {}; // }, RtcQryOutput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setOutInfo = function (b) { a.outInfo = b; }; }, // RtcDelDataInput: function () { // var a = {}; // }, RtcDataInput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setInterior = function (b) { a.interior = b; }; this.setTarget = function (b) { a.target = b; }; this.setKey = function (b) { a.key = b; }; this.setObjectName = function (b) { a.objectName = b; }; this.setContent = function (b) { a.content = b; }; }, RtcSetDataInput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setInterior = function (b) { a.interior = b; }; this.setTarget = function (b) { a.target = b; }; this.setKey = function (b) { a.key = b; }; this.setValue = function (b) { a.value = b; }; this.setObjectName = function (b) { a.objectName = b; }; this.setContent = function (b) { a.content = b; }; }, RtcOutput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setNothing = function (b) { a.nothing = b; }; }, RtcTokenOutput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setRtcToken = function (b) { a.rtcToken = b; } } }; for (var f in Polling) { Polling[f].decode = function (b) { var back = {}, val = JSON.parse(b) || eval("(" + b + ")"); for (var i in val) { back[i]=val[i]; back["get"+ i.charAt(0).toUpperCase()+i.slice(1)]=function(){ return val[i]; } } return back; } } /* * JavaScript MD5 * https://github.com/blueimp/JavaScript-MD5 * * Copyright 2011, Sebastian Tschan * https://blueimp.net * * Licensed under the MIT license: * http://www.opensource.org/licenses/MIT * * Based on * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message * Digest Algorithm, as defined in RFC 1321. * Version 2.2 Copyright (C) Paul Johnston 1999 - 2009 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet * Distributed under the BSD License * See http://pajhome.org.uk/crypt/md5 for more info. */ /*jslint bitwise: true */ /*global unescape, define, module */ var md5 = (function () { 'use strict'; /* * Add integers, wrapping at 2^32. This uses 16-bit operations internally * to work around bugs in some JS interpreters. */ function safe_add(x, y) { var lsw = (x & 0xFFFF) + (y & 0xFFFF), msw = (x >> 16) + (y >> 16) + (lsw >> 16); return (msw << 16) | (lsw & 0xFFFF); } /* * Bitwise rotate a 32-bit number to the left. */ function bit_rol(num, cnt) { return (num << cnt) | (num >>> (32 - cnt)); } /* * These functions implement the four basic operations the algorithm uses. */ function md5_cmn(q, a, b, x, s, t) { return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s), b); } function md5_ff(a, b, c, d, x, s, t) { return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t); } function md5_gg(a, b, c, d, x, s, t) { return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t); } function md5_hh(a, b, c, d, x, s, t) { return md5_cmn(b ^ c ^ d, a, b, x, s, t); } function md5_ii(a, b, c, d, x, s, t) { return md5_cmn(c ^ (b | (~d)), a, b, x, s, t); } /* * Calculate the MD5 of an array of little-endian words, and a bit length. */ function binl_md5(x, len) { /* append padding */ x[len >> 5] |= 0x80 << (len % 32); x[(((len + 64) >>> 9) << 4) + 14] = len; var i, olda, oldb, oldc, oldd, a = 1732584193, b = -271733879, c = -1732584194, d = 271733878; for (i = 0; i < x.length; i += 16) { olda = a; oldb = b; oldc = c; oldd = d; a = md5_ff(a, b, c, d, x[i], 7, -680876936); d = md5_ff(d, a, b, c, x[i + 1], 12, -389564586); c = md5_ff(c, d, a, b, x[i + 2], 17, 606105819); b = md5_ff(b, c, d, a, x[i + 3], 22, -1044525330); a = md5_ff(a, b, c, d, x[i + 4], 7, -176418897); d = md5_ff(d, a, b, c, x[i + 5], 12, 1200080426); c = md5_ff(c, d, a, b, x[i + 6], 17, -1473231341); b = md5_ff(b, c, d, a, x[i + 7], 22, -45705983); a = md5_ff(a, b, c, d, x[i + 8], 7, 1770035416); d = md5_ff(d, a, b, c, x[i + 9], 12, -1958414417); c = md5_ff(c, d, a, b, x[i + 10], 17, -42063); b = md5_ff(b, c, d, a, x[i + 11], 22, -1990404162); a = md5_ff(a, b, c, d, x[i + 12], 7, 1804603682); d = md5_ff(d, a, b, c, x[i + 13], 12, -40341101); c = md5_ff(c, d, a, b, x[i + 14], 17, -1502002290); b = md5_ff(b, c, d, a, x[i + 15], 22, 1236535329); a = md5_gg(a, b, c, d, x[i + 1], 5, -165796510); d = md5_gg(d, a, b, c, x[i + 6], 9, -1069501632); c = md5_gg(c, d, a, b, x[i + 11], 14, 643717713); b = md5_gg(b, c, d, a, x[i], 20, -373897302); a = md5_gg(a, b, c, d, x[i + 5], 5, -701558691); d = md5_gg(d, a, b, c, x[i + 10], 9, 38016083); c = md5_gg(c, d, a, b, x[i + 15], 14, -660478335); b = md5_gg(b, c, d, a, x[i + 4], 20, -405537848); a = md5_gg(a, b, c, d, x[i + 9], 5, 568446438); d = md5_gg(d, a, b, c, x[i + 14], 9, -1019803690); c = md5_gg(c, d, a, b, x[i + 3], 14, -187363961); b = md5_gg(b, c, d, a, x[i + 8], 20, 1163531501); a = md5_gg(a, b, c, d, x[i + 13], 5, -1444681467); d = md5_gg(d, a, b, c, x[i + 2], 9, -51403784); c = md5_gg(c, d, a, b, x[i + 7], 14, 1735328473); b = md5_gg(b, c, d, a, x[i + 12], 20, -1926607734); a = md5_hh(a, b, c, d, x[i + 5], 4, -378558); d = md5_hh(d, a, b, c, x[i + 8], 11, -2022574463); c = md5_hh(c, d, a, b, x[i + 11], 16, 1839030562); b = md5_hh(b, c, d, a, x[i + 14], 23, -35309556); a = md5_hh(a, b, c, d, x[i + 1], 4, -1530992060); d = md5_hh(d, a, b, c, x[i + 4], 11, 1272893353); c = md5_hh(c, d, a, b, x[i + 7], 16, -155497632); b = md5_hh(b, c, d, a, x[i + 10], 23, -1094730640); a = md5_hh(a, b, c, d, x[i + 13], 4, 681279174); d = md5_hh(d, a, b, c, x[i], 11, -358537222); c = md5_hh(c, d, a, b, x[i + 3], 16, -722521979); b = md5_hh(b, c, d, a, x[i + 6], 23, 76029189); a = md5_hh(a, b, c, d, x[i + 9], 4, -640364487); d = md5_hh(d, a, b, c, x[i + 12], 11, -421815835); c = md5_hh(c, d, a, b, x[i + 15], 16, 530742520); b = md5_hh(b, c, d, a, x[i + 2], 23, -995338651); a = md5_ii(a, b, c, d, x[i], 6, -198630844); d = md5_ii(d, a, b, c, x[i + 7], 10, 1126891415); c = md5_ii(c, d, a, b, x[i + 14], 15, -1416354905); b = md5_ii(b, c, d, a, x[i + 5], 21, -57434055); a = md5_ii(a, b, c, d, x[i + 12], 6, 1700485571); d = md5_ii(d, a, b, c, x[i + 3], 10, -1894986606); c = md5_ii(c, d, a, b, x[i + 10], 15, -1051523); b = md5_ii(b, c, d, a, x[i + 1], 21, -2054922799); a = md5_ii(a, b, c, d, x[i + 8], 6, 1873313359); d = md5_ii(d, a, b, c, x[i + 15], 10, -30611744); c = md5_ii(c, d, a, b, x[i + 6], 15, -1560198380); b = md5_ii(b, c, d, a, x[i + 13], 21, 1309151649); a = md5_ii(a, b, c, d, x[i + 4], 6, -145523070); d = md5_ii(d, a, b, c, x[i + 11], 10, -1120210379); c = md5_ii(c, d, a, b, x[i + 2], 15, 718787259); b = md5_ii(b, c, d, a, x[i + 9], 21, -343485551); a = safe_add(a, olda); b = safe_add(b, oldb); c = safe_add(c, oldc); d = safe_add(d, oldd); } return [a, b, c, d]; } /* * Convert an array of little-endian words to a string */ function binl2rstr(input) { var i, output = ''; for (i = 0; i < input.length * 32; i += 8) { output += String.fromCharCode((input[i >> 5] >>> (i % 32)) & 0xFF); } return output; } /* * Convert a raw string to an array of little-endian words * Characters >255 have their high-byte silently ignored. */ function rstr2binl(input) { var i, output = []; output[(input.length >> 2) - 1] = undefined; for (i = 0; i < output.length; i += 1) { output[i] = 0; } for (i = 0; i < input.length * 8; i += 8) { output[i >> 5] |= (input.charCodeAt(i / 8) & 0xFF) << (i % 32); } return output; } /* * Calculate the MD5 of a raw string */ function rstr_md5(s) { return binl2rstr(binl_md5(rstr2binl(s), s.length * 8)); } /* * Calculate the HMAC-MD5, of a key and some data (raw strings) */ function rstr_hmac_md5(key, data) { var i, bkey = rstr2binl(key), ipad = [], opad = [], hash; ipad[15] = opad[15] = undefined; if (bkey.length > 16) { bkey = binl_md5(bkey, key.length * 8); } for (i = 0; i < 16; i += 1) { ipad[i] = bkey[i] ^ 0x36363636; opad[i] = bkey[i] ^ 0x5C5C5C5C; } hash = binl_md5(ipad.concat(rstr2binl(data)), 512 + data.length * 8); return binl2rstr(binl_md5(opad.concat(hash), 512 + 128)); } /* * Convert a raw string to a hex string */ function rstr2hex(input) { var hex_tab = '0123456789abcdef', output = '', x, i; for (i = 0; i < input.length; i += 1) { x = input.charCodeAt(i); output += hex_tab.charAt((x >>> 4) & 0x0F) + hex_tab.charAt(x & 0x0F); } return output; } /* * Encode a string as utf-8 */ function str2rstr_utf8(input) { return unescape(encodeURIComponent(input)); } /* * Take string arguments and return either raw or hex encoded strings */ function raw_md5(s) { return rstr_md5(str2rstr_utf8(s)); } function hex_md5(s) { return rstr2hex(raw_md5(s)); } function raw_hmac_md5(k, d) { return rstr_hmac_md5(str2rstr_utf8(k), str2rstr_utf8(d)); } function hex_hmac_md5(k, d) { return rstr2hex(raw_hmac_md5(k, d)); } function md5(string, key, raw) { if (!key) { if (!raw) { return hex_md5(string); } return raw_md5(string); } if (!raw) { return hex_hmac_md5(key, string); } return raw_hmac_md5(key, string); } return md5; }()); var RongIMLib; (function (RongIMLib) { (function (MentionedType) { MentionedType[MentionedType["ALL"] = 1] = "ALL"; MentionedType[MentionedType["PART"] = 2] = "PART"; })(RongIMLib.MentionedType || (RongIMLib.MentionedType = {})); var MentionedType = RongIMLib.MentionedType; (function (MethodType) { MethodType[MethodType["CUSTOMER_SERVICE"] = 1] = "CUSTOMER_SERVICE"; MethodType[MethodType["RECALL"] = 2] = "RECALL"; })(RongIMLib.MethodType || (RongIMLib.MethodType = {})); var MethodType = RongIMLib.MethodType; (function (BlacklistStatus) { /** * 在黑名单中。 */ BlacklistStatus[BlacklistStatus["IN_BLACK_LIST"] = 0] = "IN_BLACK_LIST"; /** * 不在黑名单中。 */ BlacklistStatus[BlacklistStatus["NOT_IN_BLACK_LIST"] = 1] = "NOT_IN_BLACK_LIST"; })(RongIMLib.BlacklistStatus || (RongIMLib.BlacklistStatus = {})); var BlacklistStatus = RongIMLib.BlacklistStatus; (function (ConnectionChannel) { ConnectionChannel[ConnectionChannel["XHR_POLLING"] = 0] = "XHR_POLLING"; ConnectionChannel[ConnectionChannel["WEBSOCKET"] = 1] = "WEBSOCKET"; //外部调用 ConnectionChannel[ConnectionChannel["HTTP"] = 0] = "HTTP"; //外部调用 ConnectionChannel[ConnectionChannel["HTTPS"] = 1] = "HTTPS"; })(RongIMLib.ConnectionChannel || (RongIMLib.ConnectionChannel = {})); var ConnectionChannel = RongIMLib.ConnectionChannel; (function (CustomerType) { CustomerType[CustomerType["ONLY_ROBOT"] = 1] = "ONLY_ROBOT"; CustomerType[CustomerType["ONLY_HUMAN"] = 2] = "ONLY_HUMAN"; CustomerType[CustomerType["ROBOT_FIRST"] = 3] = "ROBOT_FIRST"; CustomerType[CustomerType["HUMAN_FIRST"] = 4] = "HUMAN_FIRST"; })(RongIMLib.CustomerType || (RongIMLib.CustomerType = {})); var CustomerType = RongIMLib.CustomerType; (function (GetChatRoomType) { GetChatRoomType[GetChatRoomType["NONE"] = 0] = "NONE"; GetChatRoomType[GetChatRoomType["SQQUENCE"] = 1] = "SQQUENCE"; GetChatRoomType[GetChatRoomType["REVERSE"] = 2] = "REVERSE"; })(RongIMLib.GetChatRoomType || (RongIMLib.GetChatRoomType = {})); var GetChatRoomType = RongIMLib.GetChatRoomType; (function (ConnectionStatus) { /** * 连接成功。 */ ConnectionStatus[ConnectionStatus["CONNECTED"] = 0] = "CONNECTED"; /** * 连接中。 */ ConnectionStatus[ConnectionStatus["CONNECTING"] = 1] = "CONNECTING"; /** * 断开连接。 */ ConnectionStatus[ConnectionStatus["DISCONNECTED"] = 2] = "DISCONNECTED"; /** * 用户账户在其他设备登录,本机会被踢掉线。 */ ConnectionStatus[ConnectionStatus["KICKED_OFFLINE_BY_OTHER_CLIENT"] = 6] = "KICKED_OFFLINE_BY_OTHER_CLIENT"; /** * websocket 连接失败 */ ConnectionStatus[ConnectionStatus["WEBSOCKET_UNAVAILABLE"] = 7] = "WEBSOCKET_UNAVAILABLE"; /** * websocket 报错 */ ConnectionStatus[ConnectionStatus["WEBSOCKET_ERROR"] = 8] = "WEBSOCKET_ERROR"; /** * 网络不可用。 */ ConnectionStatus[ConnectionStatus["NETWORK_UNAVAILABLE"] = 3] = "NETWORK_UNAVAILABLE"; /** * 域名错误 */ ConnectionStatus[ConnectionStatus["DOMAIN_INCORRECT"] = 12] = "DOMAIN_INCORRECT"; /** * appkey 不正确 */ ConnectionStatus[ConnectionStatus["APPKEY_IS_FAKE"] = 20] = "APPKEY_IS_FAKE"; /** * 连接关闭。 */ ConnectionStatus[ConnectionStatus["CONNECTION_CLOSED"] = 4] = "CONNECTION_CLOSED"; /* 互踢次数过多(count > 5),此时可能出现:在其它他设备登陆有 reconnect 逻辑 */ ConnectionStatus[ConnectionStatus["ULTRALIMIT"] = 1101] = "ULTRALIMIT"; /* 开始请求导航 */ ConnectionStatus[ConnectionStatus["REQUEST_NAVI"] = 201] = "REQUEST_NAVI"; /* 请求导航结束 */ ConnectionStatus[ConnectionStatus["RESPONSE_NAVI"] = 202] = "RESPONSE_NAVI"; /* 请求导航失败 */ ConnectionStatus[ConnectionStatus["RESPONSE_NAVI_ERROR"] = 203] = "RESPONSE_NAVI_ERROR"; /* 请求导航超时 */ ConnectionStatus[ConnectionStatus["RESPONSE_NAVI_TIMEOUT"] = 204] = "RESPONSE_NAVI_TIMEOUT"; })(RongIMLib.ConnectionStatus || (RongIMLib.ConnectionStatus = {})); var ConnectionStatus = RongIMLib.ConnectionStatus; (function (ConversationNotificationStatus) { /** * 免打扰状态,关闭对应会话的通知提醒。 */ ConversationNotificationStatus[ConversationNotificationStatus["DO_NOT_DISTURB"] = 0] = "DO_NOT_DISTURB"; /** * 提醒。 */ ConversationNotificationStatus[ConversationNotificationStatus["NOTIFY"] = 1] = "NOTIFY"; })(RongIMLib.ConversationNotificationStatus || (RongIMLib.ConversationNotificationStatus = {})); var ConversationNotificationStatus = RongIMLib.ConversationNotificationStatus; (function (ConversationType) { ConversationType[ConversationType["NONE"] = 0] = "NONE"; ConversationType[ConversationType["PRIVATE"] = 1] = "PRIVATE"; ConversationType[ConversationType["DISCUSSION"] = 2] = "DISCUSSION"; ConversationType[ConversationType["GROUP"] = 3] = "GROUP"; ConversationType[ConversationType["CHATROOM"] = 4] = "CHATROOM"; ConversationType[ConversationType["CUSTOMER_SERVICE"] = 5] = "CUSTOMER_SERVICE"; ConversationType[ConversationType["SYSTEM"] = 6] = "SYSTEM"; //默认关注 MC ConversationType[ConversationType["APP_PUBLIC_SERVICE"] = 7] = "APP_PUBLIC_SERVICE"; //手工关注 MP ConversationType[ConversationType["PUBLIC_SERVICE"] = 8] = "PUBLIC_SERVICE"; })(RongIMLib.ConversationType || (RongIMLib.ConversationType = {})); var ConversationType = RongIMLib.ConversationType; (function (DiscussionInviteStatus) { /** * 开放邀请。 */ DiscussionInviteStatus[DiscussionInviteStatus["OPENED"] = 0] = "OPENED"; /** * 关闭邀请。 */ DiscussionInviteStatus[DiscussionInviteStatus["CLOSED"] = 1] = "CLOSED"; })(RongIMLib.DiscussionInviteStatus || (RongIMLib.DiscussionInviteStatus = {})); var DiscussionInviteStatus = RongIMLib.DiscussionInviteStatus; (function (ErrorCode) { ErrorCode[ErrorCode["RECALL_MESSAGE"] = 25101] = "RECALL_MESSAGE"; /** * 发送频率过快 */ ErrorCode[ErrorCode["SEND_FREQUENCY_TOO_FAST"] = 20604] = "SEND_FREQUENCY_TOO_FAST"; ErrorCode[ErrorCode["RC_MSG_UNAUTHORIZED"] = 20406] = "RC_MSG_UNAUTHORIZED"; /** * 群组 Id 无效 */ ErrorCode[ErrorCode["RC_DISCUSSION_GROUP_ID_INVALID"] = 20407] = "RC_DISCUSSION_GROUP_ID_INVALID"; /** * 群组被禁言 */ ErrorCode[ErrorCode["FORBIDDEN_IN_GROUP"] = 22408] = "FORBIDDEN_IN_GROUP"; /** * 不在讨论组。 */ ErrorCode[ErrorCode["NOT_IN_DISCUSSION"] = 21406] = "NOT_IN_DISCUSSION"; /** * 不在群组。 */ ErrorCode[ErrorCode["NOT_IN_GROUP"] = 22406] = "NOT_IN_GROUP"; /** * 不在聊天室。 */ ErrorCode[ErrorCode["NOT_IN_CHATROOM"] = 23406] = "NOT_IN_CHATROOM"; /** *聊天室被禁言 */ ErrorCode[ErrorCode["FORBIDDEN_IN_CHATROOM"] = 23408] = "FORBIDDEN_IN_CHATROOM"; /** * 聊天室中成员被踢出 */ ErrorCode[ErrorCode["RC_CHATROOM_USER_KICKED"] = 23409] = "RC_CHATROOM_USER_KICKED"; /** * 聊天室不存在 */ ErrorCode[ErrorCode["RC_CHATROOM_NOT_EXIST"] = 23410] = "RC_CHATROOM_NOT_EXIST"; /** * 聊天室成员已满 */ ErrorCode[ErrorCode["RC_CHATROOM_IS_FULL"] = 23411] = "RC_CHATROOM_IS_FULL"; /** * 获取聊天室信息参数无效 */ ErrorCode[ErrorCode["RC_CHATROOM_PATAMETER_INVALID"] = 23412] = "RC_CHATROOM_PATAMETER_INVALID"; /** * 聊天室异常 */ ErrorCode[ErrorCode["CHATROOM_GET_HISTORYMSG_ERROR"] = 23413] = "CHATROOM_GET_HISTORYMSG_ERROR"; /** * 没有打开聊天室消息存储 */ ErrorCode[ErrorCode["CHATROOM_NOT_OPEN_HISTORYMSG_STORE"] = 23414] = "CHATROOM_NOT_OPEN_HISTORYMSG_STORE"; /** * 敏感词屏蔽 */ ErrorCode[ErrorCode["SENSITIVE_SHIELD"] = 21501] = "SENSITIVE_SHIELD"; ErrorCode[ErrorCode["SENSITIVE_REPLACE"] = 21502] = "SENSITIVE_REPLACE"; ErrorCode[ErrorCode["TIMEOUT"] = -1] = "TIMEOUT"; /** * 未知原因失败。 */ ErrorCode[ErrorCode["UNKNOWN"] = -2] = "UNKNOWN"; /** * 加入讨论失败 */ ErrorCode[ErrorCode["JOIN_IN_DISCUSSION"] = 21407] = "JOIN_IN_DISCUSSION"; /** * 创建讨论组失败 */ ErrorCode[ErrorCode["CREATE_DISCUSSION"] = 21408] = "CREATE_DISCUSSION"; /** * 设置讨论组邀请状态失败 */ ErrorCode[ErrorCode["INVITE_DICUSSION"] = 21409] = "INVITE_DICUSSION"; /** *获取用户失败 */ ErrorCode[ErrorCode["GET_USERINFO_ERROR"] = 23407] = "GET_USERINFO_ERROR"; /** * 在黑名单中。 */ ErrorCode[ErrorCode["REJECTED_BY_BLACKLIST"] = 405] = "REJECTED_BY_BLACKLIST"; /** * 通信过程中,当前 Socket 不存在。 */ ErrorCode[ErrorCode["RC_NET_CHANNEL_INVALID"] = 30001] = "RC_NET_CHANNEL_INVALID"; /** * Socket 连接不可用。 */ ErrorCode[ErrorCode["RC_NET_UNAVAILABLE"] = 30002] = "RC_NET_UNAVAILABLE"; /** * 通信超时。 */ ErrorCode[ErrorCode["RC_MSG_RESP_TIMEOUT"] = 30003] = "RC_MSG_RESP_TIMEOUT"; /** * 导航操作时,Http 请求失败。 */ ErrorCode[ErrorCode["RC_HTTP_SEND_FAIL"] = 30004] = "RC_HTTP_SEND_FAIL"; /** * HTTP 请求失败。 */ ErrorCode[ErrorCode["RC_HTTP_REQ_TIMEOUT"] = 30005] = "RC_HTTP_REQ_TIMEOUT"; /** * HTTP 接收失败。 */ ErrorCode[ErrorCode["RC_HTTP_RECV_FAIL"] = 30006] = "RC_HTTP_RECV_FAIL"; /** * 导航操作的 HTTP 请求,返回不是200。 */ ErrorCode[ErrorCode["RC_NAVI_RESOURCE_ERROR"] = 30007] = "RC_NAVI_RESOURCE_ERROR"; /** * 导航数据解析后,其中不存在有效数据。 */ ErrorCode[ErrorCode["RC_NODE_NOT_FOUND"] = 30008] = "RC_NODE_NOT_FOUND"; /** * 导航数据解析后,其中不存在有效 IP 地址。 */ ErrorCode[ErrorCode["RC_DOMAIN_NOT_RESOLVE"] = 30009] = "RC_DOMAIN_NOT_RESOLVE"; /** * 创建 Socket 失败。 */ ErrorCode[ErrorCode["RC_SOCKET_NOT_CREATED"] = 30010] = "RC_SOCKET_NOT_CREATED"; /** * Socket 被断开。 */ ErrorCode[ErrorCode["RC_SOCKET_DISCONNECTED"] = 30011] = "RC_SOCKET_DISCONNECTED"; /** * PING 操作失败。 */ ErrorCode[ErrorCode["RC_PING_SEND_FAIL"] = 30012] = "RC_PING_SEND_FAIL"; /** * PING 超时。 */ ErrorCode[ErrorCode["RC_PONG_RECV_FAIL"] = 30013] = "RC_PONG_RECV_FAIL"; /** * 消息发送失败。 */ ErrorCode[ErrorCode["RC_MSG_SEND_FAIL"] = 30014] = "RC_MSG_SEND_FAIL"; /** * 做 connect 连接时,收到的 ACK 超时。 */ ErrorCode[ErrorCode["RC_CONN_ACK_TIMEOUT"] = 31000] = "RC_CONN_ACK_TIMEOUT"; /** * 参数错误。 */ ErrorCode[ErrorCode["RC_CONN_PROTO_VERSION_ERROR"] = 31001] = "RC_CONN_PROTO_VERSION_ERROR"; /** * 参数错误,App Id 错误。 */ ErrorCode[ErrorCode["RC_CONN_ID_REJECT"] = 31002] = "RC_CONN_ID_REJECT"; /** * 服务器不可用。 */ ErrorCode[ErrorCode["RC_CONN_SERVER_UNAVAILABLE"] = 31003] = "RC_CONN_SERVER_UNAVAILABLE"; /** * Token 错误。 */ ErrorCode[ErrorCode["RC_CONN_USER_OR_PASSWD_ERROR"] = 31004] = "RC_CONN_USER_OR_PASSWD_ERROR"; /** * App Id 与 Token 不匹配。 */ ErrorCode[ErrorCode["RC_CONN_NOT_AUTHRORIZED"] = 31005] = "RC_CONN_NOT_AUTHRORIZED"; /** * 重定向,地址错误。 */ ErrorCode[ErrorCode["RC_CONN_REDIRECTED"] = 31006] = "RC_CONN_REDIRECTED"; /** * NAME 与后台注册信息不一致。 */ ErrorCode[ErrorCode["RC_CONN_PACKAGE_NAME_INVALID"] = 31007] = "RC_CONN_PACKAGE_NAME_INVALID"; /** * APP 被屏蔽、删除或不存在。 */ ErrorCode[ErrorCode["RC_CONN_APP_BLOCKED_OR_DELETED"] = 31008] = "RC_CONN_APP_BLOCKED_OR_DELETED"; /** * 用户被屏蔽。 */ ErrorCode[ErrorCode["RC_CONN_USER_BLOCKED"] = 31009] = "RC_CONN_USER_BLOCKED"; /** * Disconnect,由服务器返回,比如用户互踢。 */ ErrorCode[ErrorCode["RC_DISCONN_KICK"] = 31010] = "RC_DISCONN_KICK"; /** * Disconnect,由服务器返回,比如用户互踢。 */ ErrorCode[ErrorCode["RC_DISCONN_EXCEPTION"] = 31011] = "RC_DISCONN_EXCEPTION"; /** * 协议层内部错误。query,上传下载过程中数据错误。 */ ErrorCode[ErrorCode["RC_QUERY_ACK_NO_DATA"] = 32001] = "RC_QUERY_ACK_NO_DATA"; /** * 协议层内部错误。 */ ErrorCode[ErrorCode["RC_MSG_DATA_INCOMPLETE"] = 32002] = "RC_MSG_DATA_INCOMPLETE"; /** * 未调用 init 初始化函数。 */ ErrorCode[ErrorCode["BIZ_ERROR_CLIENT_NOT_INIT"] = 33001] = "BIZ_ERROR_CLIENT_NOT_INIT"; /** * 数据库初始化失败。 */ ErrorCode[ErrorCode["BIZ_ERROR_DATABASE_ERROR"] = 33002] = "BIZ_ERROR_DATABASE_ERROR"; /** * 传入参数无效。 */ ErrorCode[ErrorCode["BIZ_ERROR_INVALID_PARAMETER"] = 33003] = "BIZ_ERROR_INVALID_PARAMETER"; /** * 通道无效。 */ ErrorCode[ErrorCode["BIZ_ERROR_NO_CHANNEL"] = 33004] = "BIZ_ERROR_NO_CHANNEL"; /** * 重新连接成功。 */ ErrorCode[ErrorCode["BIZ_ERROR_RECONNECT_SUCCESS"] = 33005] = "BIZ_ERROR_RECONNECT_SUCCESS"; /** * 连接中,再调用 connect 被拒绝。 */ ErrorCode[ErrorCode["BIZ_ERROR_CONNECTING"] = 33006] = "BIZ_ERROR_CONNECTING"; /** * 消息漫游服务未开通 */ ErrorCode[ErrorCode["MSG_ROAMING_SERVICE_UNAVAILABLE"] = 33007] = "MSG_ROAMING_SERVICE_UNAVAILABLE"; ErrorCode[ErrorCode["MSG_INSERT_ERROR"] = 33008] = "MSG_INSERT_ERROR"; ErrorCode[ErrorCode["MSG_DEL_ERROR"] = 33009] = "MSG_DEL_ERROR"; /** * 删除会话失败 */ ErrorCode[ErrorCode["CONVER_REMOVE_ERROR"] = 34001] = "CONVER_REMOVE_ERROR"; /** *拉取历史消息 */ ErrorCode[ErrorCode["CONVER_GETLIST_ERROR"] = 34002] = "CONVER_GETLIST_ERROR"; /** * 会话指定异常 */ ErrorCode[ErrorCode["CONVER_SETOP_ERROR"] = 34003] = "CONVER_SETOP_ERROR"; /** * 获取会话未读消息总数失败 */ ErrorCode[ErrorCode["CONVER_TOTAL_UNREAD_ERROR"] = 34004] = "CONVER_TOTAL_UNREAD_ERROR"; /** * 获取指定会话类型未读消息数异常 */ ErrorCode[ErrorCode["CONVER_TYPE_UNREAD_ERROR"] = 34005] = "CONVER_TYPE_UNREAD_ERROR"; /** * 获取指定用户ID&会话类型未读消息数异常 */ ErrorCode[ErrorCode["CONVER_ID_TYPE_UNREAD_ERROR"] = 34006] = "CONVER_ID_TYPE_UNREAD_ERROR"; ErrorCode[ErrorCode["CONVER_CLEAR_ERROR"] = 34007] = "CONVER_CLEAR_ERROR"; ErrorCode[ErrorCode["CLEAR_HIS_ERROR"] = 34010] = "CLEAR_HIS_ERROR"; ErrorCode[ErrorCode["CLEAR_HIS_TYPE_ERROR"] = 34008] = "CLEAR_HIS_TYPE_ERROR"; ErrorCode[ErrorCode["CLEAR_HIS_TIME_ERROR"] = 34011] = "CLEAR_HIS_TIME_ERROR"; /* */ ErrorCode[ErrorCode["CONVER_GET_ERROR"] = 34009] = "CONVER_GET_ERROR"; //群组异常信息 /** * */ ErrorCode[ErrorCode["GROUP_SYNC_ERROR"] = 35001] = "GROUP_SYNC_ERROR"; /** * 匹配群信息异常 */ ErrorCode[ErrorCode["GROUP_MATCH_ERROR"] = 35002] = "GROUP_MATCH_ERROR"; //聊天室异常 /** * 加入聊天室Id为空 */ ErrorCode[ErrorCode["CHATROOM_ID_ISNULL"] = 36001] = "CHATROOM_ID_ISNULL"; /** * 加入聊天室失败 */ ErrorCode[ErrorCode["CHARTOOM_JOIN_ERROR"] = 36002] = "CHARTOOM_JOIN_ERROR"; /** * 拉取聊天室历史消息失败 */ ErrorCode[ErrorCode["CHATROOM_HISMESSAGE_ERROR"] = 36003] = "CHATROOM_HISMESSAGE_ERROR"; //黑名单异常 /** * 加入黑名单异常 */ ErrorCode[ErrorCode["BLACK_ADD_ERROR"] = 37001] = "BLACK_ADD_ERROR"; /** * 获得指定人员再黑名单中的状态异常 */ ErrorCode[ErrorCode["BLACK_GETSTATUS_ERROR"] = 37002] = "BLACK_GETSTATUS_ERROR"; /** * 移除黑名单异常 */ ErrorCode[ErrorCode["BLACK_REMOVE_ERROR"] = 37003] = "BLACK_REMOVE_ERROR"; /** * 获取草稿失败 */ ErrorCode[ErrorCode["DRAF_GET_ERROR"] = 38001] = "DRAF_GET_ERROR"; /** * 保存草稿失败 */ ErrorCode[ErrorCode["DRAF_SAVE_ERROR"] = 38002] = "DRAF_SAVE_ERROR"; /** * 删除草稿失败 */ ErrorCode[ErrorCode["DRAF_REMOVE_ERROR"] = 38003] = "DRAF_REMOVE_ERROR"; /** * 关注公众号失败 */ ErrorCode[ErrorCode["SUBSCRIBE_ERROR"] = 39001] = "SUBSCRIBE_ERROR"; /** * 关注公众号失败 */ ErrorCode[ErrorCode["QNTKN_FILETYPE_ERROR"] = 41001] = "QNTKN_FILETYPE_ERROR"; /** * 获取七牛token失败 */ ErrorCode[ErrorCode["QNTKN_GET_ERROR"] = 41002] = "QNTKN_GET_ERROR"; /** * cookie被禁用 */ ErrorCode[ErrorCode["COOKIE_ENABLE"] = 51001] = "COOKIE_ENABLE"; ErrorCode[ErrorCode["GET_MESSAGE_BY_ID_ERROR"] = 61001] = "GET_MESSAGE_BY_ID_ERROR"; // 没有注册DeviveId 也就是用户没有登陆 ErrorCode[ErrorCode["HAVNODEVICEID"] = 24001] = "HAVNODEVICEID"; // 已经存在 ErrorCode[ErrorCode["DEVICEIDISHAVE"] = 24002] = "DEVICEIDISHAVE"; // 成功 ErrorCode[ErrorCode["SUCCESS"] = 0] = "SUCCESS"; // 没有对应的用户或token ErrorCode[ErrorCode["FEILD"] = 24009] = "FEILD"; // voip为空 ErrorCode[ErrorCode["VOIPISNULL"] = 24013] = "VOIPISNULL"; // 不支持的Voip引擎 ErrorCode[ErrorCode["NOENGINETYPE"] = 24010] = "NOENGINETYPE"; // channleName 是空 ErrorCode[ErrorCode["NULLCHANNELNAME"] = 24011] = "NULLCHANNELNAME"; // 生成Voipkey失败 ErrorCode[ErrorCode["VOIPDYANMICERROR"] = 24012] = "VOIPDYANMICERROR"; // 没有配置voip ErrorCode[ErrorCode["NOVOIP"] = 24014] = "NOVOIP"; // 服务器内部错误 ErrorCode[ErrorCode["INTERNALERRROR"] = 24015] = "INTERNALERRROR"; //VOIP close ErrorCode[ErrorCode["VOIPCLOSE"] = 24016] = "VOIPCLOSE"; ErrorCode[ErrorCode["CLOSE_BEFORE_OPEN"] = 51001] = "CLOSE_BEFORE_OPEN"; ErrorCode[ErrorCode["ALREADY_IN_USE"] = 51002] = "ALREADY_IN_USE"; ErrorCode[ErrorCode["INVALID_CHANNEL_NAME"] = 51003] = "INVALID_CHANNEL_NAME"; ErrorCode[ErrorCode["VIDEO_CONTAINER_IS_NULL"] = 51004] = "VIDEO_CONTAINER_IS_NULL"; /** * 删除消息数组长度为 0 . */ ErrorCode[ErrorCode["DELETE_MESSAGE_ID_IS_NULL"] = 61001] = "DELETE_MESSAGE_ID_IS_NULL"; /*! 己方取消已发出的通话请求 */ ErrorCode[ErrorCode["CANCEL"] = 1] = "CANCEL"; /*! 己方拒绝收到的通话请求 */ ErrorCode[ErrorCode["REJECT"] = 2] = "REJECT"; /*! 己方挂断 */ ErrorCode[ErrorCode["HANGUP"] = 3] = "HANGUP"; /*! 己方忙碌 */ ErrorCode[ErrorCode["BUSYLINE"] = 4] = "BUSYLINE"; /*! 己方未接听 */ ErrorCode[ErrorCode["NO_RESPONSE"] = 5] = "NO_RESPONSE"; /*! 己方不支持当前引擎 */ ErrorCode[ErrorCode["ENGINE_UN_SUPPORTED"] = 6] = "ENGINE_UN_SUPPORTED"; /*! 己方网络出错 */ ErrorCode[ErrorCode["NETWORK_ERROR"] = 7] = "NETWORK_ERROR"; /*! 对方取消已发出的通话请求 */ ErrorCode[ErrorCode["REMOTE_CANCEL"] = 11] = "REMOTE_CANCEL"; /*! 对方拒绝收到的通话请求 */ ErrorCode[ErrorCode["REMOTE_REJECT"] = 12] = "REMOTE_REJECT"; /*! 通话过程对方挂断 */ ErrorCode[ErrorCode["REMOTE_HANGUP"] = 13] = "REMOTE_HANGUP"; /*! 对方忙碌 */ ErrorCode[ErrorCode["REMOTE_BUSYLINE"] = 14] = "REMOTE_BUSYLINE"; /*! 对方未接听 */ ErrorCode[ErrorCode["REMOTE_NO_RESPONSE"] = 15] = "REMOTE_NO_RESPONSE"; /*! 对方网络错误 */ ErrorCode[ErrorCode["REMOTE_ENGINE_UN_SUPPORTED"] = 16] = "REMOTE_ENGINE_UN_SUPPORTED"; /*! 对方网络错误 */ ErrorCode[ErrorCode["REMOTE_NETWORK_ERROR"] = 17] = "REMOTE_NETWORK_ERROR"; /*! VoIP 不可用 */ ErrorCode[ErrorCode["VOIP_NOT_AVALIABLE"] = 18] = "VOIP_NOT_AVALIABLE"; })(RongIMLib.ErrorCode || (RongIMLib.ErrorCode = {})); var ErrorCode = RongIMLib.ErrorCode; (function (VoIPMediaType) { VoIPMediaType[VoIPMediaType["MEDIA_AUDIO"] = 1] = "MEDIA_AUDIO"; VoIPMediaType[VoIPMediaType["MEDIA_VEDIO"] = 2] = "MEDIA_VEDIO"; VoIPMediaType[VoIPMediaType["MEDIA_VIDEO"] = 2] = "MEDIA_VIDEO"; })(RongIMLib.VoIPMediaType || (RongIMLib.VoIPMediaType = {})); var VoIPMediaType = RongIMLib.VoIPMediaType; (function (MediaType) { /** * 图片。 */ MediaType[MediaType["IMAGE"] = 1] = "IMAGE"; /** * 声音。 */ MediaType[MediaType["AUDIO"] = 2] = "AUDIO"; /** * 视频。 */ MediaType[MediaType["VIDEO"] = 3] = "VIDEO"; /** * 通用文件。 */ MediaType[MediaType["FILE"] = 100] = "FILE"; })(RongIMLib.MediaType || (RongIMLib.MediaType = {})); var MediaType = RongIMLib.MediaType; (function (MessageDirection) { /** * 发送消息。 */ MessageDirection[MessageDirection["SEND"] = 1] = "SEND"; /** * 接收消息。 */ MessageDirection[MessageDirection["RECEIVE"] = 2] = "RECEIVE"; })(RongIMLib.MessageDirection || (RongIMLib.MessageDirection = {})); var MessageDirection = RongIMLib.MessageDirection; (function (FileType) { FileType[FileType["IMAGE"] = 1] = "IMAGE"; FileType[FileType["AUDIO"] = 2] = "AUDIO"; FileType[FileType["VIDEO"] = 3] = "VIDEO"; FileType[FileType["FILE"] = 4] = "FILE"; })(RongIMLib.FileType || (RongIMLib.FileType = {})); var FileType = RongIMLib.FileType; (function (RealTimeLocationErrorCode) { /** * 未初始化 RealTimeLocation 实例 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_NOT_INIT"] = -1] = "RC_REAL_TIME_LOCATION_NOT_INIT"; /** * 执行成功。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_SUCCESS"] = 0] = "RC_REAL_TIME_LOCATION_SUCCESS"; /** * 获取 RealTimeLocation 实例时返回 * GPS 未打开。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_GPS_DISABLED"] = 1] = "RC_REAL_TIME_LOCATION_GPS_DISABLED"; /** * 获取 RealTimeLocation 实例时返回 * 当前会话不支持位置共享。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_CONVERSATION_NOT_SUPPORT"] = 2] = "RC_REAL_TIME_LOCATION_CONVERSATION_NOT_SUPPORT"; /** * 获取 RealTimeLocation 实例时返回 * 对方已发起位置共享。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_IS_ON_GOING"] = 3] = "RC_REAL_TIME_LOCATION_IS_ON_GOING"; /** * Join 时返回 * 当前位置共享已超过最大支持人数。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_EXCEED_MAX_PARTICIPANT"] = 4] = "RC_REAL_TIME_LOCATION_EXCEED_MAX_PARTICIPANT"; /** * Join 时返回 * 加入位置共享失败。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_JOIN_FAILURE"] = 5] = "RC_REAL_TIME_LOCATION_JOIN_FAILURE"; /** * Start 时返回 * 发起位置共享失败。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_START_FAILURE"] = 6] = "RC_REAL_TIME_LOCATION_START_FAILURE"; /** * 网络不可用。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_NETWORK_UNAVAILABLE"] = 7] = "RC_REAL_TIME_LOCATION_NETWORK_UNAVAILABLE"; })(RongIMLib.RealTimeLocationErrorCode || (RongIMLib.RealTimeLocationErrorCode = {})); var RealTimeLocationErrorCode = RongIMLib.RealTimeLocationErrorCode; (function (RealTimeLocationStatus) { /** * 空闲状态 (默认状态) * 对方或者自己都未发起位置共享业务,或者位置共享业务已结束。 */ RealTimeLocationStatus[RealTimeLocationStatus["RC_REAL_TIME_LOCATION_STATUS_IDLE"] = 0] = "RC_REAL_TIME_LOCATION_STATUS_IDLE"; /** * 呼入状态 (待加入) * 1. 对方发起了位置共享业务,此状态下,自己只能选择加入。 * 2. 自己从已连接的位置共享中退出。 */ RealTimeLocationStatus[RealTimeLocationStatus["RC_REAL_TIME_LOCATION_STATUS_INCOMING"] = 1] = "RC_REAL_TIME_LOCATION_STATUS_INCOMING"; /** * 呼出状态 =(自己创建) * 1. 自己发起位置共享业务,对方只能选择加入。 * 2. 对方从已连接的位置共享业务中退出。 */ RealTimeLocationStatus[RealTimeLocationStatus["RC_REAL_TIME_LOCATION_STATUS_OUTGOING"] = 2] = "RC_REAL_TIME_LOCATION_STATUS_OUTGOING"; /** * 连接状态 (自己加入) * 对方加入了自己发起的位置共享,或者自己加入了对方发起的位置共享。 */ RealTimeLocationStatus[RealTimeLocationStatus["RC_REAL_TIME_LOCATION_STATUS_CONNECTED"] = 3] = "RC_REAL_TIME_LOCATION_STATUS_CONNECTED"; })(RongIMLib.RealTimeLocationStatus || (RongIMLib.RealTimeLocationStatus = {})); var RealTimeLocationStatus = RongIMLib.RealTimeLocationStatus; (function (ReceivedStatus) { ReceivedStatus[ReceivedStatus["READ"] = 1] = "READ"; ReceivedStatus[ReceivedStatus["LISTENED"] = 2] = "LISTENED"; ReceivedStatus[ReceivedStatus["DOWNLOADED"] = 4] = "DOWNLOADED"; ReceivedStatus[ReceivedStatus["RETRIEVED"] = 8] = "RETRIEVED"; ReceivedStatus[ReceivedStatus["UNREAD"] = 0] = "UNREAD"; })(RongIMLib.ReceivedStatus || (RongIMLib.ReceivedStatus = {})); var ReceivedStatus = RongIMLib.ReceivedStatus; (function (ReadStatus) { ReadStatus[ReadStatus["READ"] = 1] = "READ"; ReadStatus[ReadStatus["LISTENED"] = 2] = "LISTENED"; ReadStatus[ReadStatus["DOWNLOADED"] = 4] = "DOWNLOADED"; ReadStatus[ReadStatus["RETRIEVED"] = 8] = "RETRIEVED"; ReadStatus[ReadStatus["UNREAD"] = 0] = "UNREAD"; })(RongIMLib.ReadStatus || (RongIMLib.ReadStatus = {})); var ReadStatus = RongIMLib.ReadStatus; (function (SearchType) { /** * 精确。 */ SearchType[SearchType["EXACT"] = 0] = "EXACT"; /** * 模糊。 */ SearchType[SearchType["FUZZY"] = 1] = "FUZZY"; })(RongIMLib.SearchType || (RongIMLib.SearchType = {})); var SearchType = RongIMLib.SearchType; (function (SentStatus) { /** * 发送中。 */ SentStatus[SentStatus["SENDING"] = 10] = "SENDING"; /** * 发送失败。 */ SentStatus[SentStatus["FAILED"] = 20] = "FAILED"; /** * 已发送。 */ SentStatus[SentStatus["SENT"] = 30] = "SENT"; /** * 对方已接收。 */ SentStatus[SentStatus["RECEIVED"] = 40] = "RECEIVED"; /** * 对方已读。 */ SentStatus[SentStatus["READ"] = 50] = "READ"; /** * 对方已销毁。 */ SentStatus[SentStatus["DESTROYED"] = 60] = "DESTROYED"; })(RongIMLib.SentStatus || (RongIMLib.SentStatus = {})); var SentStatus = RongIMLib.SentStatus; (function (ConnectionState) { ConnectionState[ConnectionState["ACCEPTED"] = 0] = "ACCEPTED"; ConnectionState[ConnectionState["UNACCEPTABLE_PROTOCOL_VERSION"] = 1] = "UNACCEPTABLE_PROTOCOL_VERSION"; ConnectionState[ConnectionState["IDENTIFIER_REJECTED"] = 2] = "IDENTIFIER_REJECTED"; ConnectionState[ConnectionState["SERVER_UNAVAILABLE"] = 3] = "SERVER_UNAVAILABLE"; /** * token无效 */ ConnectionState[ConnectionState["TOKEN_INCORRECT"] = 4] = "TOKEN_INCORRECT"; ConnectionState[ConnectionState["NOT_AUTHORIZED"] = 5] = "NOT_AUTHORIZED"; ConnectionState[ConnectionState["REDIRECT"] = 6] = "REDIRECT"; ConnectionState[ConnectionState["PACKAGE_ERROR"] = 7] = "PACKAGE_ERROR"; ConnectionState[ConnectionState["APP_BLOCK_OR_DELETE"] = 8] = "APP_BLOCK_OR_DELETE"; ConnectionState[ConnectionState["BLOCK"] = 9] = "BLOCK"; ConnectionState[ConnectionState["TOKEN_EXPIRE"] = 10] = "TOKEN_EXPIRE"; ConnectionState[ConnectionState["DEVICE_ERROR"] = 11] = "DEVICE_ERROR"; })(RongIMLib.ConnectionState || (RongIMLib.ConnectionState = {})); var ConnectionState = RongIMLib.ConnectionState; (function (RTCAPIType) { RTCAPIType[RTCAPIType["ROOM"] = 1] = "ROOM"; RTCAPIType[RTCAPIType["PERSON"] = 2] = "PERSON"; })(RongIMLib.RTCAPIType || (RongIMLib.RTCAPIType = {})); var RTCAPIType = RongIMLib.RTCAPIType; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var RongIMClient = (function () { function RongIMClient() { } RongIMClient.getInstance = function () { if (!RongIMClient._instance) { throw new Error("RongIMClient is not initialized. Call .init() method first."); } return RongIMClient._instance; }; RongIMClient.showError = function (errorInfo) { var hasConsole = (console && console.error); if (hasConsole) { console.error(JSON.stringify(errorInfo)); } }; RongIMClient.logger = function (params) { var code = params.code; var errorInfo = RongIMClient.LogFactory[code] || params; errorInfo.funcName = params.funcName; errorInfo.msg = params.msg || errorInfo.msg; if (RongIMClient._memoryStore.depend.showError) { RongIMClient.showError(errorInfo); } }; RongIMClient.logCallback = function (callback, funcName) { return { onSuccess: callback.onSuccess, onError: function (errorCode) { RongIMClient.logger({ code: errorCode, funcName: funcName }); callback.onError(errorCode); } }; }; ; RongIMClient.logSendCallback = function (callback, funcName) { return { onSuccess: callback.onSuccess, onError: function (errorCode, result) { RongIMClient.logger({ code: errorCode, funcName: funcName }); callback.onError(errorCode, result); }, onBefore: callback.onBefore }; }; ; /** * 初始化 SDK,在整个应用全局只需要调用一次。 * @param appKey 开发者后台申请的 AppKey,用来标识应用。 * @param dataAccessProvider 必须是DataAccessProvider的实例 */ RongIMClient.init = function (appKey, dataAccessProvider, options, callback) { if (RongIMClient._instance) { return RongIMClient._memoryStore.sdkInfo; } RongIMClient._instance = new RongIMClient(); options = options || {}; var protocol = "http://", wsScheme = 'ws://'; if (location.protocol == 'https:') { wsScheme = 'wss://'; protocol = 'https://'; } var isPolling = false; if (typeof WebSocket != 'function') { isPolling = true; } var isIntegrity = function () { //iOS 9 var hasWS = (typeof WebSocket); var integrity = (typeof WebSocket.OPEN == 'number'); return (hasWS && integrity); }; if (typeof WebSocket == 'object' && isIntegrity()) { isPolling = false; } var supportUserData = function () { var element = document.documentElement; return element.addBehavior; }; if (RongIMLib.RongUtil.supportLocalStorage()) { RongIMClient._storageProvider = new RongIMLib.LocalStorageProvider(); } else if (supportUserData()) { RongIMClient._storageProvider = new RongIMLib.UserDataProvider(); } else { RongIMClient._storageProvider = new RongIMLib.MemeoryProvider(); } var serverIndex = RongIMClient._storageProvider.getItem('serverIndex'); RongIMClient.serverStore.index = serverIndex || 0; var pathTmpl = '{0}{1}'; var _serverPath = { api: 'api.cn.ronghub.com' }; RongIMLib.RongUtil.forEach(_serverPath, function (path, key) { _serverPath[key] = RongIMLib.RongUtil.stringFormat(pathTmpl, [protocol, path]); }); RongIMLib.RongUtil.forEach(_serverPath, function (path, key) { var hasProto = (key in options); var config = { path: options[key], tmpl: pathTmpl, protocol: protocol, sub: true }; path = hasProto ? RongIMLib.RongUtil.formatProtoclPath(config) : path; options[key] = path; }); var navigaters = options.navigaters || []; if (options.navi) { navigaters = [options.navi]; } if (!options.navi && RongIMLib.RongUtil.isEqual(navigaters.length, 0)) { navigaters = ['nav.cn.ronghub.com', 'nav2-cn.ronghub.com']; } RongIMLib.RongUtil.forEach(navigaters, function (navi, index) { var config = { path: navi, tmpl: pathTmpl, protocol: protocol, sub: true }; navi = RongIMLib.RongUtil.formatProtoclPath(config); navigaters[index] = navi; }); var _sourcePath = { protobuf: 'cdn.ronghub.com/protobuf-2.3.6.min.js' }; RongIMLib.RongUtil.forEach(_sourcePath, function (path, key) { _sourcePath[key] = RongIMLib.RongUtil.stringFormat(pathTmpl, [protocol, path]); }); RongIMLib.RongUtil.extend(_sourcePath, options); var _defaultOpts = { isPolling: isPolling, wsScheme: wsScheme, protocol: protocol, showError: true, openMp: true, snifferTime: 2000, naviTimeout: 5000, navigaters: navigaters, maxNaviRetry: 10, isNaviJSONP: false }; delete options.navigaters; RongIMLib.RongUtil.extend(_defaultOpts, options); if (RongIMLib.RongUtil.isFunction(options.protobuf)) { RongIMClient.Protobuf = options.protobuf; } RongIMClient.userStatusObserver = new RongIMLib.RongObserver(); var pather = new RongIMLib.FeaturePatcher(); pather.patchAll(); var tempStore = { token: "", callback: null, lastReadTime: new RongIMLib.LimitableMap(), historyMessageLimit: new RongIMLib.MemoryCache(), conversationList: [], appKey: appKey, publicServiceMap: new RongIMLib.PublicServiceMap(), providerType: 1, deltaTime: 0, filterMessages: [], isSyncRemoteConverList: true, otherDevice: false, custStore: {}, converStore: { latestMessage: {} }, connectAckTime: 0, voipStategy: 0, isFirstPingMsg: true, depend: options, listenerList: RongIMClient._memoryStore.listenerList, notification: {} }; RongIMClient._memoryStore = tempStore; if (dataAccessProvider && Object.prototype.toString.call(dataAccessProvider) == "[object Object]") { RongIMClient._dataAccessProvider = dataAccessProvider; } else { RongIMClient._dataAccessProvider = new RongIMLib.ServerDataProvider(); } options.appCallback = callback; var sdkInfo = RongIMClient._dataAccessProvider.init(appKey, options); RongIMClient._memoryStore.sdkInfo = sdkInfo; // 兼容 c++ 设置导航,Web 端不生效 RongIMClient._dataAccessProvider.setServerInfo({ navi: location.protocol + options.navi + '/navi.xml' }); RongIMClient.MessageParams = { TextMessage: { objectName: "RC:TxtMsg", msgTag: new RongIMLib.MessageTag(true, true) }, ImageMessage: { objectName: "RC:ImgMsg", msgTag: new RongIMLib.MessageTag(true, true) }, DiscussionNotificationMessage: { objectName: "RC:DizNtf", msgTag: new RongIMLib.MessageTag(false, true) }, VoiceMessage: { objectName: "RC:VcMsg", msgTag: new RongIMLib.MessageTag(true, true) }, RichContentMessage: { objectName: "RC:ImgTextMsg", msgTag: new RongIMLib.MessageTag(true, true) }, FileMessage: { objectName: "RC:FileMsg", msgTag: new RongIMLib.MessageTag(true, true) }, HQVoiceMessage: { objectName: "RC:HQVCMsg", msgTag: new RongIMLib.MessageTag(true, true) }, HandshakeMessage: { objectName: "", msgTag: new RongIMLib.MessageTag(true, true) }, UnknownMessage: { objectName: "", msgTag: new RongIMLib.MessageTag(true, true) }, LocationMessage: { objectName: "RC:LBSMsg", msgTag: new RongIMLib.MessageTag(true, true) }, InformationNotificationMessage: { objectName: "RC:InfoNtf", msgTag: new RongIMLib.MessageTag(false, true) }, ContactNotificationMessage: { objectName: "RC:ContactNtf", msgTag: new RongIMLib.MessageTag(false, true) }, ProfileNotificationMessage: { objectName: "RC:ProfileNtf", msgTag: new RongIMLib.MessageTag(false, true) }, CommandNotificationMessage: { objectName: "RC:CmdNtf", msgTag: new RongIMLib.MessageTag(true, true) }, PublicServiceRichContentMessage: { objectName: "RC:PSImgTxtMsg", msgTag: new RongIMLib.MessageTag(true, true) }, PublicServiceMultiRichContentMessage: { objectName: "RC:PSMultiImgTxtMsg", msgTag: new RongIMLib.MessageTag(true, true) }, JrmfRedPacketMessage: { objectName: "RCJrmf:RpMsg", msgTag: new RongIMLib.MessageTag(true, true) }, JrmfRedPacketOpenedMessage: { objectName: "RCJrmf:RpOpendMsg", msgTag: new RongIMLib.MessageTag(true, true) }, GroupNotificationMessage: { objectName: "RC:GrpNtf", msgTag: new RongIMLib.MessageTag(false, true) }, CommandMessage: { objectName: "RC:CmdMsg", msgTag: new RongIMLib.MessageTag(false, false) }, TypingStatusMessage: { objectName: "RC:TypSts", msgTag: new RongIMLib.MessageTag(false, false) }, PublicServiceCommandMessage: { objectName: "RC:PSCmd", msgTag: new RongIMLib.MessageTag(false, false) }, RecallCommandMessage: { objectName: "RC:RcCmd", msgTag: new RongIMLib.MessageTag(false, true) }, SyncReadStatusMessage: { objectName: "RC:SRSMsg", msgTag: new RongIMLib.MessageTag(false, false) }, ReadReceiptRequestMessage: { objectName: "RC:RRReqMsg", msgTag: new RongIMLib.MessageTag(false, false) }, ReadReceiptResponseMessage: { objectName: "RC:RRRspMsg", msgTag: new RongIMLib.MessageTag(false, false) }, ChangeModeResponseMessage: { objectName: "RC:CsChaR", msgTag: new RongIMLib.MessageTag(false, false) }, ChangeModeMessage: { objectName: "RC:CSCha", msgTag: new RongIMLib.MessageTag(false, false) }, EvaluateMessage: { objectName: "RC:CsEva", msgTag: new RongIMLib.MessageTag(false, false) }, CustomerContact: { objectName: "RC:CsContact", msgTag: new RongIMLib.MessageTag(false, false) }, HandShakeMessage: { objectName: "RC:CsHs", msgTag: new RongIMLib.MessageTag(false, false) }, HandShakeResponseMessage: { objectName: "RC:CsHsR", msgTag: new RongIMLib.MessageTag(false, false) }, SuspendMessage: { objectName: "RC:CsSp", msgTag: new RongIMLib.MessageTag(false, false) }, TerminateMessage: { objectName: "RC:CsEnd", msgTag: new RongIMLib.MessageTag(false, false) }, CustomerStatusUpdateMessage: { objectName: "RC:CsUpdate", msgTag: new RongIMLib.MessageTag(false, false) }, ReadReceiptMessage: { objectName: "RC:ReadNtf", msgTag: new RongIMLib.MessageTag(false, false) }, RCCombineMessage: { objectName: "RC:CombineMsg", msgTag: new RongIMLib.MessageTag(true, true) } }; RongIMClient.MessageParams["AcceptMessage"] = { objectName: "RC:VCAccept", msgTag: new RongIMLib.MessageTag(false, false) }; RongIMClient.MessageParams["RingingMessage"] = { objectName: "RC:VCRinging", msgTag: new RongIMLib.MessageTag(false, false) }; RongIMClient.MessageParams["SummaryMessage"] = { objectName: "RC:VCSummary", msgTag: new RongIMLib.MessageTag(false, false) }; RongIMClient.MessageParams["HungupMessage"] = { objectName: "RC:VCHangup", msgTag: new RongIMLib.MessageTag(false, false) }; RongIMClient.MessageParams["InviteMessage"] = { objectName: "RC:VCInvite", msgTag: new RongIMLib.MessageTag(false, false) }; RongIMClient.MessageParams["MediaModifyMessage"] = { objectName: "RC:VCModifyMedia", msgTag: new RongIMLib.MessageTag(false, false) }; RongIMClient.MessageParams["MemberModifyMessage"] = { objectName: "RC:VCModifyMem", msgTag: new RongIMLib.MessageTag(false, false) }; RongIMClient.MessageType = { TextMessage: "TextMessage", ImageMessage: "ImageMessage", DiscussionNotificationMessage: "DiscussionNotificationMessage", VoiceMessage: "VoiceMessage", RichContentMessage: "RichContentMessage", HandshakeMessage: "HandshakeMessage", UnknownMessage: "UnknownMessage", LocationMessage: "LocationMessage", InformationNotificationMessage: "InformationNotificationMessage", ContactNotificationMessage: "ContactNotificationMessage", ProfileNotificationMessage: "ProfileNotificationMessage", CommandNotificationMessage: "CommandNotificationMessage", CommandMessage: "CommandMessage", TypingStatusMessage: "TypingStatusMessage", ChangeModeResponseMessage: "ChangeModeResponseMessage", ChangeModeMessage: "ChangeModeMessage", EvaluateMessage: "EvaluateMessage", HandShakeMessage: "HandShakeMessage", HandShakeResponseMessage: "HandShakeResponseMessage", SuspendMessage: "SuspendMessage", TerminateMessage: "TerminateMessage", CustomerContact: "CustomerContact", CustomerStatusUpdateMessage: "CustomerStatusUpdateMessage", SyncReadStatusMessage: "SyncReadStatusMessage", ReadReceiptRequestMessage: "ReadReceiptRequestMessage", ReadReceiptResponseMessage: "ReadReceiptResponseMessage", FileMessage: 'FileMessage', HQVoiceMessage: 'HQVoiceMessage', AcceptMessage: "AcceptMessage", RingingMessage: "RingingMessage", SummaryMessage: "SummaryMessage", HungupMessage: "HungupMessage", InviteMessage: "InviteMessage", MediaModifyMessage: "MediaModifyMessage", MemberModifyMessage: "MemberModifyMessage", JrmfRedPacketMessage: "JrmfRedPacketMessage", JrmfRedPacketOpenedMessage: "JrmfRedPacketOpenedMessage", GroupNotificationMessage: "GroupNotificationMessage", PublicServiceRichContentMessage: "PublicServiceRichContentMessage", PublicServiceMultiRichContentMessage: "PublicServiceMultiRichContentMessage", PublicServiceCommandMessage: "PublicServiceCommandMessage", RecallCommandMessage: "RecallCommandMessage", ReadReceiptMessage: "ReadReceiptMessage", RCCombineMessage: "RCCombineMessage" }; RongIMClient.LogFactory = { /** * 个人 */ "-1": { code: "-1", msg: "服务器超时" }, "-2": { code: "-2", msg: "未知原因失败" }, "-3": { code: "-3", msg: "参数错误" }, "-4": { code: "-4", msg: "参数不正确或尚未实例化" }, "25101": { code: "25101", msg: "撤回消息参数错误", desc: "请检查撤回消息参数 https://rongcloud.github.io/websdk-demo/api-test.html" }, "25102": { code: "25101", msg: "只能撤回自发发送的消息" }, "20604": { code: "20604", msg: "发送频率过快", desc: "https://developer.rongcloud.cn/ticket/info/9Q3L6vRKd1cLS7rycA==?type=1" }, "20406": { code: "20406", msg: "被禁言" }, "23407": { code: "23407", msg: "获取用户失败" }, /** * 群组 */ "20407": { code: "20407", msg: "群组Id无效" }, "22408": { code: "22408", msg: "群组被禁言" }, "22406": { code: "22406", msg: "不在群组" }, "35001": { code: "35001", msg: "群组同步异常" }, "35002": { code: "35002", msg: "匹配群信息异常" }, /** * 讨论组 */ "21406": { code: "21406", msg: "不在讨论组" }, "21407": { code: "21407", msg: "加入讨论失败" }, "21408": { code: "21408", msg: "创建讨论组失败" }, "21409": { code: "21409", msg: "设置讨论组邀请状态失败" }, /** * 聊天室 */ "23406": { code: "23406", msg: "不在聊天室" }, "23408": { code: "23408", msg: "聊天室被禁言" }, "23409": { code: "23409", msg: "聊天室中成员被踢出" }, "23410": { code: "23410", msg: "聊天室不存在" }, "23411": { code: "23411", msg: "聊天室成员已满" }, "23412": { code: "23412", msg: "获取聊天室信息参数无效" }, "23413": { code: "23413", msg: "聊天室异常" }, "23414": { code: "23414", msg: "没有打开聊天室消息存储" }, "36001": { code: "36001", msg: "加入聊天室Id为空" }, "36002": { code: "36002", msg: "加入聊天室失败" }, "36003": { code: "36003", msg: "拉取聊天室历史消息失败" }, /** * voip */ "24001": { code: "24001", msg: "没有注册DeviveId 也就是用户没有登陆" }, "24002": { code: "24002", msg: "用户已经存在" }, "0": { code: "0", msg: "成功" }, "24009": { code: "24009", msg: "没有对应的用户或token" }, "24013": { code: "24013", msg: "voip为空" }, "24010": { code: "24010", msg: "不支持的Voip引擎" }, "24011": { code: "24011", msg: "channelName 是空" }, "24012": { code: "24012", msg: "生成Voipkey失败" }, "24014": { code: "24014", msg: "没有配置voip" }, "24015": { code: "24015", msg: "服务器内部错误" }, "24016": { code: "24016", msg: "VOIP close" }, /** * 通讯、导航 */ "30001": { code: "30001", msg: "通信过程中,当前Socket不存在" }, "30002": { code: "30002", msg: "Socket连接不可用" }, "30003": { code: "30003", msg: "通信超时" }, "30004": { code: "30004", msg: "导航操作时,Http请求失败" }, "30005": { code: "30005", msg: "HTTP请求失败" }, "30006": { code: "30006", msg: "HTTP接收失败" }, "30007": { code: "30007", msg: "导航资源错误" }, "30008": { code: "30008", msg: "没有有效数据" }, "30009": { code: "30009", msg: "不存在有效 IP 地址" }, "30010": { code: "30010", msg: "创建 Socket 失败" }, "30011": { code: "30011", msg: " Socket 被断开" }, "30012": { code: "30012", msg: "PING 操作失败" }, "30013": { code: "30013", msg: "PING 超时" }, "30014": { code: "30014", msg: "消息发送失败" }, "30016": { code: "30016", msg: "消息大小超限,最大 128 KB" }, /** * 连接 */ "31000": { code: "31000", msg: "做 connect 连接时,收到的 ACK 超时" }, "31001": { code: "31001", msg: "参数错误" }, "31002": { code: "31002", msg: "参数错误,App Id 错误" }, "31003": { code: "31003", msg: "服务器不可用" }, "31004": { code: "31004", msg: "Token 错误" }, "31005": { code: "31005", msg: "App Id 与 Token 不匹配" }, "31006": { code: "31006", msg: "重定向,地址错误" }, "31007": { code: "31007", msg: "NAME 与后台注册信息不一致" }, "31008": { code: "31008", msg: "APP 被屏蔽、删除或不存在" }, "31009": { code: "31009", msg: "用户被屏蔽" }, "31010": { code: "31010", msg: "Disconnect,由服务器返回,比如用户互踢" }, "31011": { code: "31011", msg: "Disconnect,由服务器返回,比如用户互踢" }, /** * 协议 */ "32001": { code: "32001", msg: "协议层内部错误。query,上传下载过程中数据错误" }, "32002": { code: "32002", msg: "协议层内部错误" }, /** * BIZ */ "33001": { code: "33001", msg: "未调用 init 初始化函数" }, "33002": { code: "33002", msg: "数据库初始化失败" }, "33003": { code: "33003", msg: "传入参数无效" }, "33004": { code: "33004", msg: "通道无效" }, "33005": { code: "33005", msg: "重新连接成功" }, "33006": { code: "33006", msg: "连接中,再调用 connect 被拒绝" }, "33007": { code: "33007", msg: "消息漫游服务未开通" }, "33008": { code: "33008", msg: "消息添加失败" }, "33009": { code: "33009", msg: "消息删除失败" }, /** * 会话 */ "34001": { code: "34001", msg: "删除会话失败" }, "34002": { code: "34002", msg: "拉取历史消息失败" }, "34003": { code: "34003", msg: "会话指定异常" }, "34004": { code: "34004", msg: "获取会话未读消息总数失败" }, "34005": { code: "34005", msg: "获取指定会话类型未读消息数异常" }, "34006": { code: "34006", msg: "获取指定用户ID&会话类型未读消息数异常" }, "34007": { code: "34007", msg: "清除会话消息异常" }, "34008": { code: "34008", msg: "获取会话消息异常" }, "34009": { code: "34009", msg: "清除历史消息会话类型不正确" }, "34010": { code: "34010", msg: "清除历史消息失败,请检查传入参数" }, /** * 黑名单异常 */ "37001": { code: "37001", msg: "加入黑名单异常" }, "37002": { code: "37002", msg: "获得指定人员再黑名单中的状态异常" }, "37003": { code: "37003", msg: "移除黑名单异常" }, "405": { code: "405", msg: "在黑名单中" }, /** * 草稿 */ "38001": { code: "38001", msg: "获取草稿失败" }, "38002": { code: "38002", msg: "保存草稿失败" }, "38003": { code: "38003", msg: "删除草稿失败" }, /** * 公众号 */ "39001": { code: "39001", msg: "关注公众号失败" }, /** * 文件 */ "41001": { code: "41001", msg: "文件类型错误" }, "41002": { code: "41002", msg: "获取七牛token失败" }, /** * */ "51001": { code: "51001", msg: "未安装或未启动插件" }, "51002": { code: "51002", msg: "视频已经存在" }, "51003": { code: "51003", msg: "无效的channelName" }, "51004": { code: "51004", msg: "视频内容为空" }, /** * */ "61001": { code: "61001", msg: "删除消息数组长度为 0" } }; var handler = function (message, uris, callback) { var userId = message.senderUserId; var _uris = RongIMClient.roomInfo.users[userId].uris || '[]'; if (RongIMLib.RongUtil.isString(_uris)) { _uris = JSON.parse(_uris); } var tUris = JSON.parse(JSON.stringify(_uris)); RongIMLib.RongUtil.forEach(tUris, function (_uri, index) { RongIMLib.RongUtil.forEach(uris, function (uri) { if (uri.uri == _uri.uri) { callback(_uri, uri, _uris, index); } }); }); RongIMClient.roomInfo.users[userId].uris = JSON.stringify(_uris); }; var RTCMessage = { RTCPublishResourceMessage: function (message, uris) { var userId = message.senderUserId; var user = RongIMClient.roomInfo.users[userId]; if (!user) { user = {}; RongIMClient.roomInfo.users[userId] = {}; } var _uris = user.uris || '[]'; if (RongIMLib.RongUtil.isString(_uris)) { _uris = JSON.parse(_uris); } _uris = _uris.concat(uris); RongIMClient.roomInfo.users[userId].uris = JSON.stringify(_uris); }, RTCUnpublishResourceMessage: function (message, uris) { handler(message, uris, function (_uri, uri, _uris, index) { _uris.splice(index, 1); }); }, RTCModifyResourceMessage: function (message, uris) { handler(message, uris, function (_uri, uri) { _uri.state = uri.state; }); }, RTCUserChangeMessage: function (message) { var content = message.content; var users = content.users; var UserState = { JOINED: 0, LEFT: 1, OFFLINE: 2 }; RongIMLib.RongUtil.forEach(users, function (user) { var state = user.state; var userId = user.userId; switch (+state) { case UserState.JOINED: RongIMClient.roomInfo.users[userId] = {}; break; case UserState.LEFT: case UserState.OFFLINE: delete RongIMClient.roomInfo.users[userId]; break; } }); } }; RongIMClient.RTCInnerListener = function (message) { var func = RTCMessage[message.messageType] || function () { }; var content = message.content; var uris = content.uris; func(message, uris); }; return sdkInfo; }; ; /** var config = { appkey: appkey, token: token, dataAccessProvider:dataAccessProvider, opts: opts }; callback(_instance, userId); */ RongIMClient.initApp = function (config, callback) { RongIMClient.init(config.appkey, config.dataAccessProvider, config.opts, function () { var instance = RongIMClient._instance; //备用 var error = null; callback(error, instance); }); }; /** * 连接服务器,在整个应用全局只需要调用一次,断线后 SDK 会自动重连。 * * @param token 从服务端获取的用户身份令牌(Token)。 * @param callback 连接回调,返回连接的成功或者失败状态。 */ RongIMClient.connect = function (token, _callback, userId, serverConf) { RongIMLib.CheckParam.getInstance().check(["string", "object", "string|null|object|global|undefined", "object|null|global|undefined"], "connect", true, arguments); var connectCallback = { onSuccess: _callback.onSuccess, onTokenIncorrect: _callback.onTokenIncorrect, onError: function (errorCode) { RongIMClient.logger({ code: errorCode, funcName: "connect" }); _callback.onError(errorCode); } }; RongIMClient._dataAccessProvider.connect(token, connectCallback, userId, serverConf); }; RongIMClient.reconnect = function (callback, config) { var connectCallback = { onSuccess: callback.onSuccess, onTokenIncorrect: callback.onTokenIncorrect, onError: function (errorCode) { RongIMClient.logger({ code: errorCode, funcName: "connect" }); callback.onError(errorCode); } }; RongIMClient._dataAccessProvider.reconnect(connectCallback, config); }; /** * 注册消息类型,用于注册用户自定义的消息。 * 内建的消息类型已经注册过,不需要再次注册。 * 自定义消息声明需放在执行顺序最高的位置(在RongIMClient.init(appkey)之后即可) * @param objectName 消息内置名称 */ RongIMClient.registerMessageType = function (messageType, objectName, messageTag, messageContent, searchProps) { RongIMClient._dataAccessProvider.registerMessageType(messageType, objectName, messageTag, messageContent, searchProps); RongIMClient.RegisterMessage[messageType].messageName = messageType; RongIMClient.MessageType[messageType] = messageType; RongIMClient.MessageParams[messageType] = { objectName: objectName, msgTag: messageTag }; }; RongIMClient.prototype.registerMessageTypes = function (types) { types = types || {}; RongIMClient._dataAccessProvider.registerMessageTypes(types); }; /** * 设置连接状态变化的监听器。 * * @param listener 连接状态变化的监听器。 */ RongIMClient.setConnectionStatusListener = function (listener) { if (RongIMClient._dataAccessProvider) { RongIMClient._dataAccessProvider.setConnectionStatusListener(listener); } else { RongIMClient._memoryStore.listenerList.push(listener); } }; RongIMClient.statusWatch = function (watcher) { if (typeof watcher == 'function') { RongIMClient.statusListeners.push(watcher); } }; /** * 设置接收消息的监听器。 * * @param listener 接收消息的监听器。 */ RongIMClient.setOnReceiveMessageListener = function (listener) { if (RongIMClient._dataAccessProvider) { RongIMClient._dataAccessProvider.setOnReceiveMessageListener(listener); } else { RongIMClient._memoryStore.listenerList.push(listener); } }; /** * 清理所有连接相关的变量 */ RongIMClient.prototype.logout = function () { RongIMClient._dataAccessProvider.logout(); }; /** * 断开连接。 */ RongIMClient.prototype.disconnect = function () { RongIMClient._dataAccessProvider.disconnect(); }; RongIMClient.prototype.startCustomService = function (custId, callback, content) { if (!custId || !callback) return; var msg = new RongIMLib.HandShakeMessage(content); var me = this; RongIMLib.RongIMClient._memoryStore.custStore["isInit"] = true; RongIMClient.getInstance().sendMessage(RongIMLib.ConversationType.CUSTOMER_SERVICE, custId, msg, { onSuccess: function (data) { if (data.isBlack) { callback.onError(); me.stopCustomeService(custId, { onSuccess: function () { }, onError: function () { } }); } else { callback.onSuccess(); } }, onError: function () { callback.onError(); }, onBefore: function () { } }); }; RongIMClient.prototype.stopCustomeService = function (custId, callback) { if (!custId || !callback) return; var session = RongIMClient._memoryStore.custStore[custId]; if (!session) return; var msg = new RongIMLib.SuspendMessage({ sid: session.sid, uid: session.uid, pid: session.pid }); this.sendCustMessage(custId, msg, { onSuccess: function () { // delete RongIMClient._memoryStore.custStore[custId]; setTimeout(function () { callback.onSuccess(); }); }, onError: function () { setTimeout(function () { callback.onError(); }); } }); }; RongIMClient.prototype.switchToHumanMode = function (custId, callback) { if (!custId || !callback) return; var session = RongIMClient._memoryStore.custStore[custId]; if (!session) return; var msg = new RongIMLib.ChangeModeMessage({ sid: session.sid, uid: session.uid, pid: session.pid }); this.sendCustMessage(custId, msg, callback); }; RongIMClient.prototype.evaluateRebotCustomService = function (custId, isRobotResolved, sugest, callback) { if (!custId || !callback) return; var session = RongIMClient._memoryStore.custStore[custId]; if (!session) return; var msg = new RongIMLib.EvaluateMessage({ sid: session.sid, uid: session.uid, pid: session.pid, isRobotResolved: isRobotResolved, sugest: sugest, type: 0 }); this.sendCustMessage(custId, msg, callback); }; RongIMClient.prototype.evaluateHumanCustomService = function (custId, humanValue, sugest, callback) { if (!custId || !callback) return; var session = RongIMClient._memoryStore.custStore[custId]; if (!session) return; var msg = new RongIMLib.EvaluateMessage({ sid: session.sid, uid: session.uid, pid: session.pid, humanValue: humanValue, sugest: sugest, type: 1 }); this.sendCustMessage(custId, msg, callback); }; RongIMClient.prototype.sendCustMessage = function (custId, msg, callback) { RongIMClient.getInstance().sendMessage(RongIMLib.ConversationType.CUSTOMER_SERVICE, custId, msg, { onSuccess: function (data) { callback.onSuccess(); }, onError: function () { callback.onError(); }, onBefore: function () { } }); }; /** * 获取当前连接的状态。 */ RongIMClient.prototype.getCurrentConnectionStatus = function () { return RongIMClient._dataAccessProvider.getCurrentConnectionStatus(); }; /** * 获取当前使用的连接通道。 */ RongIMClient.prototype.getConnectionChannel = function () { if (RongIMLib.Transportations._TransportType == RongIMLib.Socket.XHR_POLLING) { return RongIMLib.ConnectionChannel.XHR_POLLING; } else if (RongIMLib.Transportations._TransportType == RongIMLib.Socket.WEBSOCKET) { return RongIMLib.ConnectionChannel.WEBSOCKET; } }; /** * 获取当前使用的本地储存提供者。 TODO */ RongIMClient.prototype.getStorageProvider = function () { if (RongIMClient._memoryStore.providerType == 1) { return "ServerDataProvider"; } else { return "OtherDataProvider"; } }; /** * 过滤聊天室消息(拉取最近聊天消息) * @param {string[]} msgFilterNames */ RongIMClient.prototype.setFilterMessages = function (msgFilterNames) { if (Object.prototype.toString.call(msgFilterNames) == "[object Array]") { RongIMClient._memoryStore.filterMessages = msgFilterNames; } }; RongIMClient.prototype.getAgoraDynamicKey = function (engineType, channelName, callback) { RongIMClient._dataAccessProvider.getAgoraDynamicKey(engineType, channelName, callback); }; /** * 获取当前连接用户的 UserId。 */ RongIMClient.prototype.getCurrentUserId = function () { return RongIMLib.Bridge._client.userId; }; /** * 获取服务器时间与本地时间的差值,单位为毫秒。 * 计算公式:差值 = 本地时间毫秒数 - 服务器时间毫秒数 * @param callback 获取的回调,返回差值。 */ RongIMClient.prototype.getDeltaTime = function () { return RongIMClient._dataAccessProvider.getDelaTime(); }; // #region Message RongIMClient.prototype.getMessage = function (messageId, callback) { RongIMClient._dataAccessProvider.getMessage(messageId, RongIMClient.logCallback(callback, "getMessage")); }; RongIMClient.prototype.deleteLocalMessages = function (conversationType, targetId, messageIds, callback) { RongIMClient._dataAccessProvider.removeLocalMessage(conversationType, targetId, messageIds, RongIMClient.logCallback(callback, "deleteLocalMessages")); }; RongIMClient.prototype.updateMessage = function (message, callback) { RongIMClient._dataAccessProvider.updateMessage(message, RongIMClient.logCallback(callback, "updateMessage")); }; RongIMClient.prototype.clearData = function () { return RongIMClient._dataAccessProvider.clearData(); }; RongIMClient.prototype.clearMessages = function (conversationType, targetId, callback) { RongIMClient._dataAccessProvider.clearMessages(conversationType, targetId, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "clearMessages" }); callback.onError(errorCode); }); } }); }; /**TODO 清楚本地存储的未读消息,目前清空内存中的未读消息 * [clearMessagesUnreadStatus 清空指定会话未读消息] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [用户id] * @param {ResultCallback} callback [返回值,参数回调] */ RongIMClient.prototype.clearMessagesUnreadStatus = function (conversationType, targetId, callback) { RongIMClient._dataAccessProvider.updateMessages(conversationType, targetId, "readStatus", null, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "clearMessagesUnreadStatus" }); callback.onError(errorCode); }); } }); }; RongIMClient.prototype.deleteRemoteMessages = function (conversationType, targetId, delMsgs, callback) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "array", "object"], "deleteRemoteMessages", false, arguments); if (delMsgs.length == 0) { var errorCode = RongIMLib.ErrorCode.DELETE_MESSAGE_ID_IS_NULL; RongIMClient.logger({ code: errorCode, funcName: "deleteRemoteMessages" }); callback.onError(RongIMLib.ErrorCode.DELETE_MESSAGE_ID_IS_NULL); return; } else if (delMsgs.length > 100) { delMsgs.length = 100; } // 后续增加,去掉注释即可 callback.onSuccess(true); // var modules = new RongIMClient.Protobuf.DeleteMsgInput(); // modules.setType(conversationType); // modules.setConversationId(targetId); // modules.setMsgs(delMsgs); // RongIMClient.bridge.queryMsg(33, MessageUtil.ArrayForm(modules.toArrayBuffer()), Bridge._client.userId, { // onSuccess: function(info: any) { // callback.onSuccess(true); // }, // onError: function(err: any) { // callback.onError(err); // } // }, "DeleteMsgOutput"); }; /** * [deleteMessages 删除消息记录。] * @param {ConversationType} conversationType [description] * @param {string} targetId [description] * @param {number[]} messageIds [description] * @param {ResultCallback} callback [description] */ RongIMClient.prototype.deleteMessages = function (conversationType, targetId, delMsgs, callback) { RongIMClient._dataAccessProvider.removeMessage(conversationType, targetId, delMsgs, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "deleteMessages" }); callback.onError(errorCode); }); } }); }; RongIMClient.prototype.sendLocalMessage = function (message, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object"], "sendLocalMessage", false, arguments); RongIMClient._dataAccessProvider.updateMessage(message); this.sendMessage(message.conversationType, message.targetId, message.content, RongIMClient.logSendCallback(callback, "sendLocalMessage")); }; /** * [sendMessage 发送消息。] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [目标Id] * @param {MessageContent} messageContent [消息类型] * @param {SendMessageCallback} sendCallback [] * @param {ResultCallback} resultCallback [返回值,函数回调] * @param {string} pushContent [] * @param {string} pushData [] */ RongIMClient.prototype.sendMessage = function (conversationType, targetId, messageContent, sendCallback, mentiondMsg, pushText, appData, methodType, params) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object", "object", "undefined|object|null|global|boolean", "undefined|object|null|global|string", "undefined|object|null|global|string", "undefined|object|null|global|number", "undefined|object|null|global"], "sendMessage", false, arguments); RongIMClient._dataAccessProvider.sendMessage(conversationType, targetId, messageContent, RongIMClient.logSendCallback(sendCallback, "sendMessage"), mentiondMsg, pushText, appData, methodType, params); }; RongIMClient.prototype.sendReceiptResponse = function (conversationType, targetId, sendCallback) { RongIMClient._dataAccessProvider.sendReceiptResponse(conversationType, targetId, RongIMClient.logSendCallback(sendCallback, "sendReceiptResponse")); }; RongIMClient.prototype.sendTypingStatusMessage = function (conversationType, targetId, messageName, sendCallback) { RongIMClient._dataAccessProvider.sendTypingStatusMessage(conversationType, targetId, messageName, RongIMClient.logSendCallback(sendCallback, "sendTypingStatusMessage")); }; /** * [sendStatusMessage description] * @param {MessageContent} messageContent [description] * @param {SendMessageCallback} sendCallback [description] * @param {ResultCallback} resultCallback [description] */ RongIMClient.prototype.sendStatusMessage = function (messageContent, sendCallback, resultCallback) { throw new Error("Not implemented yet"); }; /** * [sendTextMessage 发送TextMessage快捷方式] * @param {string} content [消息内容] * @param {ResultCallback} resultCallback [返回值,参数回调] */ RongIMClient.prototype.sendTextMessage = function (conversationType, targetId, content, sendMessageCallback) { RongIMClient._dataAccessProvider.sendTextMessage(conversationType, targetId, content, RongIMClient.logSendCallback(sendMessageCallback, "sendTextMessage")); }; RongIMClient.prototype.sendRecallMessage = function (content, sendMessageCallback) { var callback = RongIMClient.logSendCallback(sendMessageCallback, "sendRecallMessage"); var senderUserId = content.senderUserId; var userId = RongIMLib.Bridge._client.userId; var isOther = (senderUserId != userId); if (isOther) { var callback = RongIMClient.logSendCallback(sendMessageCallback, "sendRecallMessage"); callback.onError(RongIMLib.ErrorCode.RECALL_MESSAGE, content); return; } RongIMClient._dataAccessProvider.sendRecallMessage(content, callback); }; /** * [insertMessage 向本地插入一条消息,不发送到服务器。] * @param {ConversationType} conversationType [description] * @param {string} targetId [description] * @param {string} senderUserId [description] * @param {MessageContent} content [description] * @param {ResultCallback} callback [description] */ RongIMClient.prototype.insertMessage = function (conversationType, targetId, content, callback) { RongIMClient._dataAccessProvider.addMessage(conversationType, targetId, content, RongIMClient.logCallback(callback, "insertMessage")); }; RongIMClient.prototype.setMessageContent = function (messageId, content, objectName) { RongIMClient._dataAccessProvider.setMessageContent(messageId, content, objectName); }; ; RongIMClient.prototype.setMessageSearchField = function (messageId, content, searchFiles) { RongIMClient._dataAccessProvider.setMessageContent(messageId, content, searchFiles); }; ; /** * [getHistoryMessages 拉取历史消息记录。] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [用户Id] * @param {number|null} pullMessageTime [拉取历史消息起始位置(格式为毫秒数),可以为null] * @param {number} count [历史消息数量] * @param {ResultCallback} callback [回调函数] * @param {string} objectName [objectName] */ RongIMClient.prototype.getHistoryMessages = function (conversationType, targetId, timestamp, count, callback, objectname, order) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "number|null|global|object", "number", "object", "undefined|object|null|global|string", "number|null|global|object"], "getHistoryMessages", false, arguments); if (count > 20) { throw new Error("HistroyMessage count must be less than or equal to 20!"); } if (conversationType.valueOf() < 0) { throw new Error("ConversationType must be greater than -1"); } RongIMClient._dataAccessProvider.getHistoryMessages(conversationType, targetId, timestamp, count, RongIMClient.logCallback(callback, "getHistoryMessages"), objectname, order); }; /** * [getRemoteHistoryMessages 拉取某个时间戳之前的消息] * @param {ConversationType} conversationType [description] * @param {string} targetId [description] * @param {Date} dateTime [description] * @param {number} count [description] * @param {ResultCallback} callback [description] */ RongIMClient.prototype.getRemoteHistoryMessages = function (conversationType, targetId, timestamp, count, callback, config) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "number|null|global|object", "number", "object", "undefined|null|global|object"], "getRemoteHistoryMessages", false, arguments); var funcName = "getRemoteHistoryMessages"; var log = { errorCode: RongIMLib.ErrorCode.RC_CONN_PROTO_VERSION_ERROR, funcName: "getRemoteHistoryMessages" }; if (count > 20) { RongIMClient.logger(log); callback.onError(RongIMLib.ErrorCode.RC_CONN_PROTO_VERSION_ERROR); return; } if (conversationType.valueOf() < 0) { RongIMClient.logger(log); callback.onError(RongIMLib.ErrorCode.RC_CONN_PROTO_VERSION_ERROR); return; } RongIMClient._dataAccessProvider.getRemoteHistoryMessages(conversationType, targetId, timestamp, count, RongIMClient.logCallback(callback, funcName), config); }; RongIMClient.prototype.clearHistoryMessages = function (params, callback) { RongIMClient._dataAccessProvider.clearHistoryMessages(params, callback); }; RongIMClient.prototype.clearRemoteHistoryMessages = function (params, callback) { RongIMClient._dataAccessProvider.clearRemoteHistoryMessages(params, RongIMClient.logCallback(callback, "clearRemoteHistoryMessages")); }; /** * [hasRemoteUnreadMessages 是否有未接收的消息,jsonp方法] * @param {string} appkey [appkey] * @param {string} token [token] * @param {ConnectCallback} callback [返回值,参数回调] */ RongIMClient.prototype.hasRemoteUnreadMessages = function (token, callback) { RongIMClient._dataAccessProvider.hasRemoteUnreadMessages(token, RongIMClient.logCallback(callback, "hasRemoteUnreadMessages")); }; RongIMClient.prototype.getTotalUnreadCount = function (callback, conversationTypes) { RongIMClient._dataAccessProvider.getTotalUnreadCount({ onSuccess: function (count) { setTimeout(function () { callback.onSuccess(count); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "getTotalUnreadCount" }); callback.onError(errorCode); }); } }, conversationTypes); }; /** * [getConversationUnreadCount 指定多种会话类型获取未读消息数] * @param {ResultCallback} callback [返回值,参数回调。] * @param {ConversationType[]} ...conversationTypes [会话类型。] */ RongIMClient.prototype.getConversationUnreadCount = function (conversationTypes, callback) { RongIMClient._dataAccessProvider.getConversationUnreadCount(conversationTypes, { onSuccess: function (count) { setTimeout(function () { callback.onSuccess(count); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "getConversationUnreadCount" }); callback.onError(errorCode); }); } }); }; /** * [getUnreadCount 指定用户、会话类型的未读消息总数。] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [用户Id] */ RongIMClient.prototype.getUnreadCount = function (conversationType, targetId, callback) { RongIMClient._dataAccessProvider.getUnreadCount(conversationType, targetId, { onSuccess: function (count) { setTimeout(function () { callback.onSuccess(count); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "getUnreadCount" }); callback.onError(errorCode); }); } }); }; RongIMClient.prototype.setUnreadCount = function (conversationType, targetId, count) { RongIMLib.CheckParam.getInstance().check(["number", "string", "number"], "setUnreadCount", false, arguments); RongIMClient._dataAccessProvider.setUnreadCount(conversationType, targetId, count); }; RongIMClient.prototype.clearUnreadCountByTimestamp = function (conversationType, targetId, timestamp, callback) { RongIMClient._dataAccessProvider.clearUnreadCountByTimestamp(conversationType, targetId, timestamp, RongIMClient.logCallback(callback, "clearUnreadCountByTimestamp")); }; /** * 清楚会话未读消息数 * @param {ConversationType} conversationType 会话类型 * @param {string} targetId 目标Id * @param {ResultCallback} callback 返回值,函数回调 */ RongIMClient.prototype.clearUnreadCount = function (conversationType, targetId, callback) { RongIMClient._dataAccessProvider.clearUnreadCount(conversationType, targetId, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "clearUnreadCount" }); callback.onError(errorCode); }); } }); }; RongIMClient.prototype.clearTotalUnreadCount = function (callback) { RongIMClient._dataAccessProvider.clearTotalUnreadCount({ onSuccess: function (bool) { callback.onSuccess(bool); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: 'clearTotalUnreadCount' }); callback.onError(errorCode); }); } }); }; RongIMClient.prototype.clearLocalStorage = function (callback) { RongIMClient._storageProvider.clearItem(); callback(); }; RongIMClient.prototype.setMessageExtra = function (messageId, value, callback) { RongIMClient._dataAccessProvider.setMessageExtra(messageId, value, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "setMessageExtra" }); callback.onError(errorCode); }); } }); }; RongIMClient.prototype.setMessageReceivedStatus = function (messageUId, receivedStatus, callback) { RongIMClient._dataAccessProvider.setMessageReceivedStatus(messageUId, receivedStatus, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "setMessageReceivedStatus" }); callback.onError(errorCode); }); } }); }; RongIMClient.prototype.setMessageStatus = function (conersationType, targetId, timestamp, status, callback) { RongIMClient._dataAccessProvider.setMessageStatus(conersationType, targetId, timestamp, status, RongIMClient.logCallback(callback, "setMessageStatus")); }; RongIMClient.prototype.setMessageSentStatus = function (messageId, sentStatus, callback) { RongIMClient._dataAccessProvider.setMessageSentStatus(messageId, sentStatus, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "setMessageSentStatus" }); callback.onError(errorCode); }); } }); }; // #endregion Message // #region TextMessage Draft /** * clearTextMessageDraft 清除指定会话和消息类型的草稿。 * @param {ConversationType} conversationType 会话类型 * @param {string} targetId 目标Id */ RongIMClient.prototype.clearTextMessageDraft = function (conversationType, targetId) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "clearTextMessageDraft", false, arguments); var key = "darf_" + conversationType + "_" + targetId; delete RongIMClient._memoryStore[key]; return true; }; /** * [getTextMessageDraft 获取指定消息和会话的草稿。] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [目标Id] */ RongIMClient.prototype.getTextMessageDraft = function (conversationType, targetId) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "getTextMessageDraft", false, arguments); if (targetId == "" || conversationType < 0) { throw new Error("params error : " + RongIMLib.ErrorCode.DRAF_GET_ERROR); } var key = "darf_" + conversationType + "_" + targetId; return RongIMClient._memoryStore[key]; }; /** * [saveTextMessageDraft description] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [目标Id] * @param {string} value [草稿值] */ RongIMClient.prototype.saveTextMessageDraft = function (conversationType, targetId, value) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "string", "object"], "saveTextMessageDraft", false, arguments); var key = "darf_" + conversationType + "_" + targetId; RongIMClient._memoryStore[key] = value; return true; }; // #endregion TextMessage Draft // #region Conversation RongIMClient.prototype.searchConversationByContent = function (keyword, callback, conversationTypes) { RongIMClient._dataAccessProvider.searchConversationByContent(keyword, RongIMClient.logCallback(callback, "searchConversationByContent"), conversationTypes); }; RongIMClient.prototype.searchMessageByContent = function (conversationType, targetId, keyword, timestamp, count, total, callback) { RongIMClient._dataAccessProvider.searchMessageByContent(conversationType, targetId, keyword, timestamp, count, total, RongIMClient.logCallback(callback, "searchMessageByContent")); }; RongIMClient.prototype.clearCache = function () { RongIMClient._dataAccessProvider.clearCache(); }; RongIMClient.prototype.clearConversations = function (callback) { var conversationTypes = []; for (var _i = 1; _i < arguments.length; _i++) { conversationTypes[_i - 1] = arguments[_i]; } if (conversationTypes.length == 0) { conversationTypes = [RongIMLib.ConversationType.CHATROOM, RongIMLib.ConversationType.CUSTOMER_SERVICE, RongIMLib.ConversationType.DISCUSSION, RongIMLib.ConversationType.GROUP, RongIMLib.ConversationType.PRIVATE, RongIMLib.ConversationType.SYSTEM, RongIMLib.ConversationType.PUBLIC_SERVICE, RongIMLib.ConversationType.APP_PUBLIC_SERVICE]; } RongIMClient._dataAccessProvider.clearConversations(conversationTypes, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "clearConversations" }); callback.onError(errorCode); }); } }); }; /** * [getConversation 获取指定会话,此方法需在getConversationList之后执行] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [目标Id] * @param {ResultCallback} callback [返回值,函数回调] */ RongIMClient.prototype.getConversation = function (conversationType, targetId, callback) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "getConversation", false, arguments); RongIMClient._dataAccessProvider.getConversation(conversationType, targetId, { onSuccess: function (conver) { setTimeout(function () { callback.onSuccess(conver); }); }, onError: function (error) { setTimeout(function () { RongIMClient.logger({ code: error, funcName: "getConversation" }); callback.onError(error); }); } }); }; /** * [pottingConversation 组装会话列表] * @param {any} tempConver [临时会话] * conver_conversationType_targetId_no. * msg_conversationType_targetId_no. */ RongIMClient.prototype.pottingConversation = function (tempConver) { var self = this, isUseReplace = false; RongIMClient._dataAccessProvider.getConversation(tempConver.type, tempConver.userId, { onSuccess: function (conver) { if (!conver) { conver = new RongIMLib.Conversation(); } else { isUseReplace = true; } conver.conversationType = tempConver.type; conver.targetId = tempConver.userId; conver.latestMessage = RongIMLib.MessageUtil.messageParser(tempConver.msg); conver.latestMessageId = conver.latestMessage.messageId; conver.objectName = conver.latestMessage.objectName; conver.receivedStatus = conver.latestMessage.receivedStatus; conver.receivedTime = conver.latestMessage.receiveTime; conver.sentStatus = conver.latestMessage.sentStatus; conver.sentTime = conver.latestMessage.sentTime; var mentioneds = RongIMClient._storageProvider.getItem("mentioneds_" + RongIMLib.Bridge._client.userId + '_' + conver.conversationType + '_' + conver.targetId); if (mentioneds) { var info = JSON.parse(mentioneds); conver.mentionedMsg = info[tempConver.type + "_" + tempConver.userId]; } if (!isUseReplace) { if (RongIMLib.RongUtil.supportLocalStorage()) { var count = RongIMClient._storageProvider.getItem("cu" + RongIMLib.Bridge._client.userId + tempConver.type + tempConver.userId); conver.unreadMessageCount = Number(count); } else { conver.unreadMessageCount = 0; } } if (conver.conversationType == RongIMLib.ConversationType.DISCUSSION) { self.getDiscussion(tempConver.userId, { onSuccess: function (info) { conver.conversationTitle = info.name; }, onError: function (error) { } }); } RongIMClient._dataAccessProvider.addConversation(conver, { onSuccess: function (data) { } }); }, onError: function (error) { } }); }; RongIMClient.prototype.addConversation = function (conversation, callback) { RongIMClient._dataAccessProvider.addConversation(conversation, callback); }; RongIMClient.prototype.sortConversationList = function (conversationList) { var convers = []; for (var i = 0, len = conversationList.length; i < len; i++) { if (!conversationList[i]) { continue; } if (conversationList[i].isTop) { convers.push(conversationList[i]); conversationList.splice(i, 1); continue; } for (var j = 0; j < len - i - 1; j++) { if (conversationList[j].sentTime < conversationList[j + 1].sentTime) { var swap = conversationList[j]; conversationList[j] = conversationList[j + 1]; conversationList[j + 1] = swap; } } } return RongIMClient._memoryStore.conversationList = convers.concat(conversationList); }; RongIMClient.prototype.getConversationList = function (callback, conversationTypes, count, isGetHiddenConvers) { RongIMLib.CheckParam.getInstance().check(["object", "null|undefined|array|object|global", "number|undefined|null|object|global", "boolean|undefined|null|object|global"], "getConversationList", false, arguments); var me = this; RongIMClient._dataAccessProvider.getConversationList({ onSuccess: function (data) { if (conversationTypes || RongIMClient._dataAccessProvider) { setTimeout(function () { callback.onSuccess(data); }); } else { setTimeout(function () { callback.onSuccess(RongIMClient._memoryStore.conversationList); }); } }, onError: function (error) { setTimeout(function () { RongIMClient.logger({ code: error, funcName: "getConversationList" }); callback.onError(error); }); } }, conversationTypes, count, isGetHiddenConvers); }; RongIMClient.prototype.getRemoteConversationList = function (callback, conversationTypes, count, isGetHiddenConvers) { RongIMLib.CheckParam.getInstance().check(["object", "null|array|object|global", "number|undefined|null|object|global", "boolean|undefined|null|object|global"], "getRemoteConversationList", false, arguments); RongIMClient._dataAccessProvider.getRemoteConversationList(RongIMClient.logCallback(callback, "getRemoteConversationList"), conversationTypes, count, isGetHiddenConvers); }; RongIMClient.prototype.updateConversation = function (conversation) { return RongIMClient._dataAccessProvider.updateConversation(conversation); }; /** * [createConversation 创建会话。] * @param {number} conversationType [会话类型] * @param {string} targetId [目标Id] * @param {string} converTitle [会话标题] * @param {boolean} islocal [是否同步到服务器,ture:同步,false:不同步] */ RongIMClient.prototype.createConversation = function (conversationType, targetId, converTitle) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "string"], "createConversation", false, arguments); var conver = new RongIMLib.Conversation(); // var unreadContent: string = RongIMClient._storageProvider.getItem("cu" + Bridge._client.userId + conversationType + targetId); // var unreadCount = Number(unreadContent) || 0; conver.targetId = targetId; conver.conversationType = conversationType; conver.conversationTitle = converTitle; conver.latestMessage = {}; conver.unreadMessageCount = 0; return conver; }; //TODO 删除本地和服务器、删除本地和服务器分开 RongIMClient.prototype.removeConversation = function (conversationType, targetId, callback) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "removeConversation", false, arguments); RongIMClient._dataAccessProvider.removeConversation(conversationType, targetId, RongIMClient.logCallback(callback, "removeConversation")); }; RongIMClient.prototype.setConversationHidden = function (conversationType, targetId, isHidden) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "boolean"], "setConversationHidden", false, arguments); RongIMClient._dataAccessProvider.setConversationHidden(conversationType, targetId, isHidden); }; RongIMClient.prototype.setConversationToTop = function (conversationType, targetId, isTop, callback) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "boolean", "object"], "setConversationToTop", false, arguments); RongIMClient._dataAccessProvider.setConversationToTop(conversationType, targetId, isTop, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "setConversationToTop" }); callback.onError(errorCode); }); } }); }; // #endregion Conversation // #region Notifications /** * [getConversationNotificationStatus 获取指定用户和会话类型免提醒。] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [目标Id] * @param {ResultCallback} callback [返回值,函数回调] */ RongIMClient.prototype.getConversationNotificationStatus = function (conversationType, targetId, callback) { var params = { conversationType: conversationType, targetId: targetId }; RongIMClient._dataAccessProvider.getConversationNotificationStatus(params, RongIMClient.logCallback(callback, "getConversationNotificationStatus")); }; /** * [setConversationNotificationStatus 设置指定用户和会话类型免提醒。] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [目标Id] * @param {ResultCallback} callback [返回值,函数回调] */ RongIMClient.prototype.setConversationNotificationStatus = function (conversationType, targetId, notificationStatus, callback) { var params = { conversationType: conversationType, targetId: targetId, status: status }; RongIMClient._dataAccessProvider.setConversationNotificationStatus(params, RongIMClient.logCallback(callback, "setConversationNotificationStatus")); }; /** * [getNotificationQuietHours 获取免提醒消息时间。] * @param {GetNotificationQuietHoursCallback} callback [返回值,函数回调] */ RongIMClient.prototype.getNotificationQuietHours = function (callback) { throw new Error("Not implemented yet"); }; /** * [removeNotificationQuietHours 移除免提醒消息时间。] * @param {GetNotificationQuietHoursCallback} callback [返回值,函数回调] */ RongIMClient.prototype.removeNotificationQuietHours = function (callback) { throw new Error("Not implemented yet"); }; /** * [setNotificationQuietHours 设置免提醒消息时间。] * @param {GetNotificationQuietHoursCallback} callback [返回值,函数回调] */ RongIMClient.prototype.setNotificationQuietHours = function (startTime, spanMinutes, callback) { throw new Error("Not implemented yet"); }; // #endregion Notifications // #region Discussion /** * [addMemberToDiscussion 加入讨论组] * @param {string} discussionId [讨论组Id] * @param {string[]} userIdList [讨论中成员] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.addMemberToDiscussion = function (discussionId, userIdList, callback) { RongIMLib.CheckParam.getInstance().check(["string", "array", "object"], "addMemberToDiscussion", false, arguments); RongIMClient._dataAccessProvider.addMemberToDiscussion(discussionId, userIdList, RongIMClient.logCallback(callback, "addMemberToDiscussion")); }; /** * [createDiscussion 创建讨论组] * @param {string} name [讨论组名称] * @param {string[]} userIdList [讨论组成员] * @param {CreateDiscussionCallback} callback [返回值,函数回调] */ RongIMClient.prototype.createDiscussion = function (name, userIdList, callback) { RongIMLib.CheckParam.getInstance().check(["string", "array", "object"], "createDiscussion", false, arguments); RongIMClient._dataAccessProvider.createDiscussion(name, userIdList, callback); }; /** * [getDiscussion 获取讨论组信息] * @param {string} discussionId [讨论组Id] * @param {ResultCallback} callback [返回值,函数回调] */ RongIMClient.prototype.getDiscussion = function (discussionId, callback) { RongIMLib.CheckParam.getInstance().check(["string", "object"], "getDiscussion", false, arguments); RongIMClient._dataAccessProvider.getDiscussion(discussionId, RongIMClient.logCallback(callback, "getDiscussion")); }; /** * [quitDiscussion 退出讨论组] * @param {string} discussionId [讨论组Id] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.quitDiscussion = function (discussionId, callback) { RongIMLib.CheckParam.getInstance().check(["string", "object"], "quitDiscussion", false, arguments); RongIMClient._dataAccessProvider.quitDiscussion(discussionId, RongIMClient.logCallback(callback, "quitDiscussion")); }; /** * [removeMemberFromDiscussion 将指定成员移除讨论租] * @param {string} discussionId [讨论组Id] * @param {string} userId [被移除的用户Id] * @param {OperationCallback} callback [返回值,参数回调] */ RongIMClient.prototype.removeMemberFromDiscussion = function (discussionId, userId, callback) { RongIMLib.CheckParam.getInstance().check(["string", "string", "object"], "removeMemberFromDiscussion", false, arguments); RongIMClient._dataAccessProvider.removeMemberFromDiscussion(discussionId, userId, RongIMClient.logCallback(callback, "removeMemberFromDiscussion")); }; /** * [setDiscussionInviteStatus 设置讨论组邀请状态] * @param {string} discussionId [讨论组Id] * @param {DiscussionInviteStatus} status [邀请状态] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.setDiscussionInviteStatus = function (discussionId, status, callback) { RongIMLib.CheckParam.getInstance().check(["string", "number", "object"], "setDiscussionInviteStatus", false, arguments); RongIMClient._dataAccessProvider.setDiscussionInviteStatus(discussionId, status, RongIMClient.logCallback(callback, "setDiscussionInviteStatus")); }; /** * [setDiscussionName 设置讨论组名称] * @param {string} discussionId [讨论组Id] * @param {string} name [讨论组名称] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.setDiscussionName = function (discussionId, name, callback) { RongIMLib.CheckParam.getInstance().check(["string", "string", "object"], "setDiscussionName", false, arguments); RongIMClient._dataAccessProvider.setDiscussionName(discussionId, name, RongIMClient.logCallback(callback, "setDiscussionName")); }; // #endregion Discussion // #region ChatRoom /** * [加入聊天室。] * @param {string} chatroomId [聊天室Id] * @param {number} messageCount [拉取消息数量,-1为不拉去消息] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.joinChatRoom = function (chatroomId, messageCount, callback) { RongIMLib.CheckParam.getInstance().check(["string|number", "number", "object"], "joinChatRoom", false, arguments); if (chatroomId == "") { setTimeout(function () { var errorCode = RongIMLib.ErrorCode.CHATROOM_ID_ISNULL; RongIMClient.logger({ code: errorCode, funcName: "joinChatRoom" }); callback.onError(RongIMLib.ErrorCode.CHATROOM_ID_ISNULL); }); return; } RongIMClient._dataAccessProvider.joinChatRoom(chatroomId, messageCount, RongIMClient.logCallback(callback, "joinChatRoom")); }; RongIMClient.prototype.setDeviceInfo = function (device) { RongIMClient._dataAccessProvider.setDeviceInfo(device); }; RongIMClient.prototype.setChatroomHisMessageTimestamp = function (chatRoomId, timestamp) { RongIMLib.CheckParam.getInstance().check(["string|number", "number"], "setChatroomHisMessageTimestamp", false, arguments); RongIMClient._dataAccessProvider.setChatroomHisMessageTimestamp(chatRoomId, timestamp); }; RongIMClient.prototype.getChatRoomHistoryMessages = function (chatRoomId, count, order, callback) { RongIMLib.CheckParam.getInstance().check(["string|number", "number", "number", "object"], "getChatRoomHistoryMessages", false, arguments); RongIMClient._dataAccessProvider.getChatRoomHistoryMessages(chatRoomId, count, order, RongIMClient.logCallback(callback, "getChatRoomHistoryMessages")); }; RongIMClient.prototype.getChatRoomInfo = function (chatRoomId, count, order, callback) { RongIMLib.CheckParam.getInstance().check(["string|number", "number", "number", "object"], "getChatRoomInfo", false, arguments); RongIMClient._dataAccessProvider.getChatRoomInfo(chatRoomId, count, order, RongIMClient.logCallback(callback, "getChatRoomInfo")); }; /** * [退出聊天室] * @param {string} chatroomId [聊天室Id] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.quitChatRoom = function (chatroomId, callback) { RongIMLib.CheckParam.getInstance().check(["string|number", "object"], "quitChatRoom", false, arguments); RongIMClient._dataAccessProvider.quitChatRoom(chatroomId, RongIMClient.logCallback(callback, "quitChatRoom")); }; // #endregion ChatRoom // #region Public Service RongIMClient.prototype.getRemotePublicServiceList = function (callback, pullMessageTime) { RongIMClient._dataAccessProvider.getRemotePublicServiceList(RongIMClient.logCallback(callback, "getRemotePublicServiceList"), pullMessageTime); }; /** * [getPublicServiceList ]获取本地的公共账号列表 * @param {ResultCallback} callback [返回值,参数回调] */ RongIMClient.prototype.getPublicServiceList = function (callback) { if (RongIMClient._memoryStore.depend.openMp) { RongIMLib.CheckParam.getInstance().check(["object"], "getPublicServiceList", false, arguments); this.getRemotePublicServiceList(RongIMClient.logCallback(callback, "getPublicServiceList")); } }; /** * [getPublicServiceProfile ] 获取某公共服务信息。 * @param {PublicServiceType} publicServiceType [公众服务类型。] * @param {string} publicServiceId [公共服务 Id。] * @param {ResultCallback} callback [公共账号信息回调。] */ RongIMClient.prototype.getPublicServiceProfile = function (publicServiceType, publicServiceId, callback) { if (RongIMClient._memoryStore.depend.openMp) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "getPublicServiceProfile", false, arguments); RongIMClient._dataAccessProvider.getPublicServiceProfile(publicServiceType, publicServiceId, RongIMClient.logCallback(callback, "getPublicServiceProfile")); } }; /** * [pottingPublicSearchType ] 公众好查询类型 * @param {number} bussinessType [ 0-all 1-mp 2-mc] * @param {number} searchType [0-exact 1-fuzzy] */ RongIMClient.prototype.pottingPublicSearchType = function (bussinessType, searchType) { if (RongIMClient._memoryStore.depend.openMp) { var bits = 0; if (bussinessType == 0) { bits |= 3; if (searchType == 0) { bits |= 12; } else { bits |= 48; } } else if (bussinessType == 1) { bits |= 1; if (searchType == 0) { bits |= 8; } else { bits |= 32; } } else { bits |= 2; if (bussinessType == 0) { bits |= 4; } else { bits |= 16; } } return bits; } }; /** * [searchPublicService ]按公众服务类型搜索公众服务。 * @param {SearchType} searchType [搜索类型枚举。] * @param {string} keywords [搜索关键字。] * @param {ResultCallback} callback [搜索结果回调。] */ RongIMClient.prototype.searchPublicService = function (searchType, keywords, callback) { if (RongIMClient._memoryStore.depend.openMp) { RongIMLib.CheckParam.getInstance().check(["number", "string", "object"], "searchPublicService", false, arguments); var modules = new RongIMClient.Protobuf.SearchMpInput(); modules.setType(this.pottingPublicSearchType(0, searchType)); modules.setId(keywords); RongIMClient.bridge.queryMsg(29, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, RongIMClient.logCallback(callback, "searchPublicService"), "SearchMpOutput"); } }; /** * [searchPublicServiceByType ]按公众服务类型搜索公众服务。 * @param {PublicServiceType} publicServiceType [公众服务类型。] * @param {SearchType} searchType [搜索类型枚举。] * @param {string} keywords [搜索关键字。] * @param {ResultCallback} callback [搜索结果回调。] */ RongIMClient.prototype.searchPublicServiceByType = function (publicServiceType, searchType, keywords, callback) { if (RongIMClient._memoryStore.depend.openMp) { RongIMLib.CheckParam.getInstance().check(["number", "number", "string", "object"], "searchPublicServiceByType", false, arguments); var type = publicServiceType == RongIMLib.ConversationType.APP_PUBLIC_SERVICE ? 2 : 1; var modules = new RongIMClient.Protobuf.SearchMpInput(); modules.setType(this.pottingPublicSearchType(type, searchType)); modules.setId(keywords); RongIMClient.bridge.queryMsg(29, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, RongIMClient.logCallback(callback, "searchPublicServiceByType"), "SearchMpOutput"); } }; /** * [subscribePublicService ] 订阅公众号。 * @param {PublicServiceType} publicServiceType [公众服务类型。] * @param {string} publicServiceId [公共服务 Id。] * @param {OperationCallback} callback [订阅公众号回调。] */ RongIMClient.prototype.subscribePublicService = function (publicServiceType, publicServiceId, callback) { if (RongIMClient._memoryStore.depend.openMp) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "subscribePublicService", false, arguments); var modules = new RongIMClient.Protobuf.MPFollowInput(), me = this, follow = publicServiceType == RongIMLib.ConversationType.APP_PUBLIC_SERVICE ? "mcFollow" : "mpFollow"; modules.setId(publicServiceId); RongIMClient.bridge.queryMsg(follow, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function () { me.getRemotePublicServiceList({ onSuccess: function () { }, onError: function () { } }); callback.onSuccess(); }, onError: function (code) { var errorCode = code; RongIMClient.logger({ code: errorCode, funcName: "subscribePublicService" }); callback.onError(code); } }, "MPFollowOutput"); } }; /** * [unsubscribePublicService ] 取消订阅公众号。 * @param {PublicServiceType} publicServiceType [公众服务类型。] * @param {string} publicServiceId [公共服务 Id。] * @param {OperationCallback} callback [取消订阅公众号回调。] */ RongIMClient.prototype.unsubscribePublicService = function (publicServiceType, publicServiceId, callback) { if (RongIMClient._memoryStore.depend.openMp) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "unsubscribePublicService", false, arguments); var modules = new RongIMClient.Protobuf.MPFollowInput(), me = this, follow = publicServiceType == RongIMLib.ConversationType.APP_PUBLIC_SERVICE ? "mcUnFollow" : "mpUnFollow"; modules.setId(publicServiceId); RongIMClient.bridge.queryMsg(follow, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function () { RongIMClient._memoryStore.publicServiceMap.remove(publicServiceType, publicServiceId); callback.onSuccess(); }, onError: function (code) { var errorCode = code; RongIMClient.logger({ code: errorCode, funcName: "unsubscribePublicService" }); callback.onError(code); } }, "MPFollowOutput"); } }; // #endregion Public Service // #region Blacklist /** * [加入黑名单] * @param {string} userId [将被加入黑名单的用户Id] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.addToBlacklist = function (userId, callback) { RongIMLib.CheckParam.getInstance().check(["string|number", "object"], "addToBlacklist", false, arguments); RongIMClient._dataAccessProvider.addToBlacklist(userId, RongIMClient.logCallback(callback, "addToBlacklist")); }; /** * [获取黑名单列表] * @param {GetBlacklistCallback} callback [返回值,函数回调] */ RongIMClient.prototype.getBlacklist = function (callback) { RongIMLib.CheckParam.getInstance().check(["object"], "getBlacklist", false, arguments); RongIMClient._dataAccessProvider.getBlacklist(callback); }; /** * [得到指定人员再黑名单中的状态] * @param {string} userId [description] * @param {ResultCallback} callback [返回值,函数回调] */ //TODO 如果人员不在黑名单中,获取状态会出现异常 RongIMClient.prototype.getBlacklistStatus = function (userId, callback) { RongIMLib.CheckParam.getInstance().check(["string|number", "object"], "getBlacklistStatus", false, arguments); RongIMClient._dataAccessProvider.getBlacklistStatus(userId, RongIMClient.logCallback(callback, "getBlacklistStatus")); }; /** * [将指定用户移除黑名单] * @param {string} userId [将被移除的用户Id] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.removeFromBlacklist = function (userId, callback) { RongIMLib.CheckParam.getInstance().check(["string|number", "object"], "removeFromBlacklist", false, arguments); RongIMClient._dataAccessProvider.removeFromBlacklist(userId, RongIMClient.logCallback(callback, "removeFromBlacklist")); }; RongIMClient.prototype.getFileToken = function (fileType, callback) { RongIMLib.CheckParam.getInstance().check(["number", "object"], "getQngetFileTokenTkn", false, arguments); RongIMClient._dataAccessProvider.getFileToken(fileType, RongIMClient.logCallback(callback, "getFileToken")); }; RongIMClient.prototype.getFileUrl = function (fileType, fileName, oriName, callback) { RongIMLib.CheckParam.getInstance().check(["number", "string", "string|global|object|null", "object"], "getFileUrl", false, arguments); RongIMClient._dataAccessProvider.getFileUrl(fileType, fileName, oriName, RongIMClient.logCallback(callback, "getFileUrl")); }; ; // #endregion Blacklist // #region Real-time Location Service RongIMClient.prototype.addRealTimeLocationListener = function (conversationType, targetId, listener) { throw new Error("Not implemented yet"); }; RongIMClient.prototype.getRealTimeLocation = function (conversationType, targetId) { throw new Error("Not implemented yet"); }; RongIMClient.prototype.getRealTimeLocationCurrentState = function (conversationType, targetId) { throw new Error("Not implemented yet"); }; RongIMClient.prototype.getRealTimeLocationParticipants = function (conversationType, targetId) { throw new Error("Not implemented yet"); }; RongIMClient.prototype.joinRealTimeLocation = function (conversationType, targetId) { throw new Error("Not implemented yet"); }; RongIMClient.prototype.quitRealTimeLocation = function (conversationType, targetId) { throw new Error("Not implemented yet"); }; RongIMClient.prototype.startRealTimeLocation = function (conversationType, targetId) { throw new Error("Not implemented yet"); }; RongIMClient.prototype.updateRealTimeLocationStatus = function (conversationType, targetId, latitude, longitude) { throw new Error("Not implemented yet"); }; // #endregion Real-time Location Service // # startVoIP RongIMClient.prototype.startCall = function (converType, targetId, userIds, mediaType, extra, callback) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "array", "number", "string", "object"], "startCall", false, arguments); if (RongIMClient._memoryStore.voipStategy) { RongIMClient._voipProvider.startCall(converType, targetId, userIds, mediaType, extra, RongIMClient.logCallback(callback, "startCall")); } else { var errorCode = RongIMLib.ErrorCode.VOIP_NOT_AVALIABLE; RongIMClient.logger({ code: errorCode, funcName: "startCall" }); callback.onError(RongIMLib.ErrorCode.VOIP_NOT_AVALIABLE); } }; RongIMClient.prototype.joinCall = function (mediaType, callback) { RongIMLib.CheckParam.getInstance().check(['number', 'object'], "joinCall", false, arguments); if (RongIMClient._memoryStore.voipStategy) { RongIMClient._voipProvider.joinCall(mediaType, RongIMClient.logCallback(callback, "joinCall")); } else { var errorCode = RongIMLib.ErrorCode.VOIP_NOT_AVALIABLE; RongIMClient.logger({ code: errorCode, funcName: "joinCall" }); callback.onError(RongIMLib.ErrorCode.VOIP_NOT_AVALIABLE); } }; RongIMClient.prototype.hungupCall = function (converType, targetId, reason) { RongIMLib.CheckParam.getInstance().check(["number", "string", "number"], "hungupCall", false, arguments); if (RongIMClient._memoryStore.voipStategy) { RongIMClient._voipProvider.hungupCall(converType, targetId, reason); } }; RongIMClient.prototype.changeMediaType = function (converType, targetId, mediaType, callback) { RongIMLib.CheckParam.getInstance().check(["number", "string", "number", "object"], "changeMediaType", false, arguments); if (RongIMClient._memoryStore.voipStategy) { RongIMClient._voipProvider.changeMediaType(converType, targetId, mediaType, RongIMClient.logCallback(callback, "changeMediaType")); } else { var errorCode = RongIMLib.ErrorCode.VOIP_NOT_AVALIABLE; RongIMClient.logger({ code: errorCode, funcName: "changeMediaType" }); callback.onError(RongIMLib.ErrorCode.VOIP_NOT_AVALIABLE); } }; // # endVoIP RongIMClient.prototype.getUnreadMentionedMessages = function (conversationType, targetId) { return RongIMClient._dataAccessProvider.getUnreadMentionedMessages(conversationType, targetId); }; RongIMClient.prototype.clearListeners = function () { RongIMClient._dataAccessProvider.clearListeners(); }; // UserStatus start RongIMClient.prototype.getUserStatus = function (userId, callback) { RongIMClient._dataAccessProvider.getUserStatus(userId, RongIMClient.logCallback(callback, "getUserStatus")); }; RongIMClient.prototype.setUserStatus = function (status, callback) { RongIMClient._dataAccessProvider.setUserStatus(status, RongIMClient.logCallback(callback, "setUserStatus")); }; RongIMClient.prototype.setUserStatusListener = function (params, callback) { var userIds = params.userIds; var multiple = params.multiple; RongIMClient.userStatusObserver.watch({ key: userIds, func: callback, multiple: multiple }); RongIMClient._dataAccessProvider.setUserStatusListener(params, callback); }; // UserStaus end // RTC start RongIMClient.messageWatch = function (watcher) { RongIMClient.RTCListener = watcher; }; RongIMClient.messageSignalWatch = function (watcher) { RongIMClient.RTCSignalLisener = watcher; }; /* var data = { key1: 123, key2: 345 }; */ RongIMClient.prototype.getRTCUserInfoList = function (room, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object"], "getRTCUserInfoList", false, arguments); RongIMClient._dataAccessProvider.getRTCUserInfoList(room, callback); }; RongIMClient.prototype.getRTCUserList = function (room, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object"], "getRTCUserList", false, arguments); RongIMClient._dataAccessProvider.getRTCUserList(room, callback); }; RongIMClient.prototype.setRTCUserInfo = function (room, info, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object", "object"], "setRTCUserInfo", false, arguments); RongIMClient._dataAccessProvider.setRTCUserInfo(room, info, callback); }; RongIMClient.prototype.removeRTCUserInfo = function (room, info, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object", "object"], "removeRTCUserInfo", false, arguments); RongIMClient._dataAccessProvider.removeRTCUserInfo(room, info, callback); }; RongIMClient.prototype.getRTCRoomInfo = function (room, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object"], "getRTCRoomInfo", false, arguments); RongIMClient._dataAccessProvider.getRTCRoomInfo(room, callback); }; RongIMClient.prototype.setRTCRoomInfo = function (room, info, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object", "object"], "setRTCRoomInfo", false, arguments); RongIMClient._dataAccessProvider.setRTCRoomInfo(room, info, callback); }; RongIMClient.prototype.removeRTCRoomInfo = function (room, info, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object", "object"], "removeRTCRoomInfo", false, arguments); RongIMClient._dataAccessProvider.removeRTCRoomInfo(room, info, callback); }; RongIMClient.prototype.joinRTCRoom = function (room, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object"], "joinRTCRoom", false, arguments); if (RongIMClient.isJoinedRTCRoom) { return callback.onSuccess(RongIMClient.roomInfo); } RongIMClient._dataAccessProvider.joinRTCRoom(room, { onSuccess: function (result) { RongIMClient.roomInfo = result; RongIMClient.isJoinedRTCRoom = true; callback.onSuccess(result); }, onError: callback.onError }); }; RongIMClient.prototype.quitRTCRoom = function (room, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object"], "quitRTCRoom", false, arguments); RongIMClient.isJoinedRTCRoom = false; RongIMClient._dataAccessProvider.quitRTCRoom(room, { onSuccess: function () { RongIMClient.roomInfo = { users: {}, token: '' }; callback.onSuccess(true); }, onError: callback.onError }); }; RongIMClient.prototype.RTCPing = function (room, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object"], "RTCPing", false, arguments); RongIMClient._dataAccessProvider.RTCPing(room, callback); }; RongIMClient.prototype.setRTCUserData = function (roomId, key, value, isInner, callback, message) { RongIMLib.CheckParam.getInstance().check(["string", "string", "string", "boolean", "object", "global|object|null|undefined"], "setRTCUserData", false, arguments); RongIMClient._dataAccessProvider.setRTCUserData(roomId, key, value, isInner, callback, message); }; RongIMClient.prototype.getRTCUserData = function (roomId, keys, isInner, callback) { RongIMLib.CheckParam.getInstance().check(["string", "array", "boolean", "object", "global|object|null"], "getRTCUserData", false, arguments); RongIMClient._dataAccessProvider.getRTCUserData(roomId, keys, isInner, callback); }; RongIMClient.prototype.removeRTCUserData = function (roomId, keys, isInner, callback, message) { RongIMLib.CheckParam.getInstance().check(["string", "array", "boolean", "object", "global|object|null|undefined"], "removeRTCUserData", false, arguments); RongIMClient._dataAccessProvider.removeRTCUserData(roomId, keys, isInner, callback, message); }; RongIMClient.prototype.setRTCRoomData = function (roomId, key, value, isInner, callback, message) { RongIMLib.CheckParam.getInstance().check(["string", "string", "string", "boolean", "object", "global|object|null|undefined"], "setRTCRoomData", false, arguments); RongIMClient._dataAccessProvider.setRTCRoomData(roomId, key, value, isInner, callback, message); }; RongIMClient.prototype.getRTCRoomData = function (roomId, keys, isInner, callback) { RongIMLib.CheckParam.getInstance().check(["string", "array", "boolean", "object"], "getRTCRoomData", false, arguments); RongIMClient._dataAccessProvider.getRTCRoomData(roomId, keys, isInner, callback); }; RongIMClient.prototype.removeRTCRoomData = function (roomId, keys, isInner, callback, message) { RongIMLib.CheckParam.getInstance().check(["string", "array", "boolean", "object", "global|object|null|undefined"], "removeRTCRoomData", false, arguments); RongIMClient._dataAccessProvider.removeRTCRoomData(roomId, keys, isInner, callback, message); }; RongIMClient.prototype.setRTCOutData = function (roomId, data, type, callback, message) { RongIMClient._dataAccessProvider.setRTCOutData(roomId, data, type, callback, message); }; // 信令 SDK 新增 RongIMClient.prototype.getRTCOutData = function (roomId, userIds, callback) { RongIMClient._dataAccessProvider.getRTCOutData(roomId, userIds, callback); }; RongIMClient.prototype.getNavi = function () { return RongIMClient._dataAccessProvider.getNavi(); }; RongIMClient.prototype.getRTCToken = function (room, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object"], "getRTCToken", false, arguments); return RongIMClient._dataAccessProvider.getRTCToken(room, callback); }; RongIMClient.prototype.setRTCState = function (room, content, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object", "object"], "setRTCState", false, arguments); return RongIMClient._dataAccessProvider.setRTCState(room, content, callback); }; RongIMClient.prototype.getAppInfo = function () { var appKey = RongIMClient._memoryStore.appKey; return { appKey: appKey }; }; RongIMClient.prototype.getSDKInfo = function () { return { version: RongIMClient.sdkver }; }; RongIMClient.RTCListener = function () { }; RongIMClient.RTCInnerListener = function () { }; RongIMClient.RTCSignalLisener = function () { }; RongIMClient.currentServer = ''; RongIMClient.LogFactory = {}; RongIMClient.MessageType = {}; RongIMClient.RegisterMessage = {}; RongIMClient._memoryStore = { listenerList: [], isPullFinished: false, syncMsgQueue: [] }; RongIMClient.isNotPullMsg = false; RongIMClient.userStatusObserver = null; RongIMClient.sdkver = '2.5.1'; RongIMClient.otherDeviceLoginCount = 0; RongIMClient.serverStore = { index: 0 }; RongIMClient.isFirstConnect = true; RongIMClient.roomInfo = { users: {}, token: '' }; RongIMClient.isJoinedRTCRoom = false; RongIMClient.statusListeners = []; RongIMClient.userStatusListener = null; return RongIMClient; })(); RongIMLib.RongIMClient = RongIMClient; })(RongIMLib || (RongIMLib = {})); //用于连接通道 var RongIMLib; (function (RongIMLib) { (function (Qos) { Qos[Qos["AT_MOST_ONCE"] = 0] = "AT_MOST_ONCE"; Qos[Qos["AT_LEAST_ONCE"] = 1] = "AT_LEAST_ONCE"; Qos[Qos["EXACTLY_ONCE"] = 2] = "EXACTLY_ONCE"; Qos[Qos["DEFAULT"] = 3] = "DEFAULT"; })(RongIMLib.Qos || (RongIMLib.Qos = {})); var Qos = RongIMLib.Qos; (function (Type) { Type[Type["CONNECT"] = 1] = "CONNECT"; Type[Type["CONNACK"] = 2] = "CONNACK"; Type[Type["PUBLISH"] = 3] = "PUBLISH"; Type[Type["PUBACK"] = 4] = "PUBACK"; Type[Type["QUERY"] = 5] = "QUERY"; Type[Type["QUERYACK"] = 6] = "QUERYACK"; Type[Type["QUERYCON"] = 7] = "QUERYCON"; Type[Type["SUBSCRIBE"] = 8] = "SUBSCRIBE"; Type[Type["SUBACK"] = 9] = "SUBACK"; Type[Type["UNSUBSCRIBE"] = 10] = "UNSUBSCRIBE"; Type[Type["UNSUBACK"] = 11] = "UNSUBACK"; Type[Type["PINGREQ"] = 12] = "PINGREQ"; Type[Type["PINGRESP"] = 13] = "PINGRESP"; Type[Type["DISCONNECT"] = 14] = "DISCONNECT"; })(RongIMLib.Type || (RongIMLib.Type = {})); var Type = RongIMLib.Type; var _topic = [ "invtDiz", "crDiz", "qnUrl", "userInf", "dizInf", "userInf", "joinGrp", "quitDiz", "exitGrp", "evctDiz", ["", "ppMsgP", "pdMsgP", "pgMsgP", "chatMsg", "pcMsgP", "", "pmcMsgN", "pmpMsgN", "", "", "", "prMsgS", "prMsgP"], "pdOpen", "rename", "uGcmpr", "qnTkn", "destroyChrm", "createChrm", "exitChrm", "queryChrm", "joinChrm", "pGrps", "addBlack", "rmBlack", "getBlack", "blackStat", "addRelation", "qryRelation", "delRelation", "pullMp", "schMp", "qnTkn", "qnUrl", "qryVoipK", "delMsg", "qryCHMsg", "getUserStatus", "setUserStatus", "subUserStatus", "cleanHisMsg" ]; var Channel = (function () { function Channel(cb, self) { this.connectionStatus = -1; var appId = self.appId; var token = encodeURIComponent(self.token); var sdkVer = self.sdkVer; var apiVer = self.apiVer; this.self = self; this.socket = Socket.getInstance().createServer(); var that = this; var storage = RongIMLib.RongIMClient._storageProvider; var servers = storage.getItem('servers'); servers = JSON.parse(servers) || []; var depend = RongIMLib.RongIMClient._memoryStore.depend; var startConnect = function (host) { var tpl = '{host}/websocket?appId={appId}&token={token}&sdkVer={sdkVer}&apiVer={apiVer}'; that.url = RongIMLib.RongUtil.tplEngine(tpl, { host: host, appId: appId, token: token, sdkVer: sdkVer, apiVer: apiVer }); that.socket.connect(that.url, cb); // 临时兼容 Comet 逻辑,Comet 中用到 var userId = storage.getItem('rong_current_user'); RongIMLib.Navigation.Endpoint = { host: host, userId: userId }; }; var connectMap = { ws: function () { // 所有链接计算器,超过 15 秒后认为所有 CMP 地址均不可用 var totalTimer = new RongIMLib.Timer({ timeout: 1 * 1000 * 15 }); var timers = []; var xhrs = []; var isFinished = false; var clearHandler = function () { for (var i = 0; i < timers.length; i++) { var timer = timers[i]; clearTimeout(timer); } for (var i = 0; i < xhrs.length; i++) { var xhr = xhrs[i]; xhr.abort(); } timers.length = 0; xhrs.length = 0; }; var request = function (config, callback) { var url = config.url; var time = config.time; if (isFinished) { return; } var timer = setTimeout(function () { var onSuccess = function () { if (isFinished) { return; } clearHandler(); isFinished = true; totalTimer.pause(); callback(url); }; var xhr = RongIMLib.MessageUtil.detectCMP({ url: url, success: onSuccess, fail: function (code) { console.log(code); } }); xhrs.push(xhr); }, time); timers.push(timer); }; var snifferCallback = function (url) { var reg = /(http|https):\/\/([^\/]+)/i; var host = url.match(reg)[2]; RongIMLib.RongIMClient.currentServer = host; startConnect(host); }; var snifferTpl = '{protocol}{server}/ping?r={random}'; for (var i = 0; i < servers.length; i++) { var server = servers[i]; if (server) { server = RongIMLib.RongUtil.tplEngine(snifferTpl, { protocol: depend.protocol, server: server, random: RongIMLib.RongUtil.getTimestamp() }); request({ url: server, time: i * 1000 }, snifferCallback); } } totalTimer.resume(function () { RongIMLib.Navigation.clear(); clearHandler(); that.socket.fire("StatusChanged", RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE); }); }, comet: function () { var host = servers[0]; startConnect(host); } }; var isPolling = depend.isPolling; var type = isPolling ? 'comet' : 'ws'; connectMap[type](); //注册状态改变观察者 var StatusEvent = Channel._ConnectionStatusListener; var hasEvent = (typeof StatusEvent == "object"); var me = this; me.socket.on("StatusChanged", function (code) { if (RongIMLib.Bridge && RongIMLib.Bridge._client && RongIMLib.Bridge._client.channel && me !== RongIMLib.Bridge._client.channel) { return; } if (!hasEvent) { throw new Error("setConnectStatusListener:Parameter format is incorrect"); } var isNetworkUnavailable = (code == RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE); var isWebSocket = !RongIMLib.RongIMClient._memoryStore.depend.isPolling; if (RongIMLib.RongIMClient.isFirstConnect && isNetworkUnavailable && isWebSocket) { code = RongIMLib.ConnectionStatus.WEBSOCKET_UNAVAILABLE; } if (isNetworkUnavailable) { var storage = RongIMLib.RongIMClient._storageProvider; var servers = storage.getItem('servers'); servers = JSON.parse(servers); var currentServer = RongIMLib.RongIMClient.currentServer; if (currentServer) { var index = RongIMLib.RongUtil.indexOf(servers, currentServer); // 如果 currentServer 是 servers 的最后一个,不再替换位置 if (!RongIMLib.RongUtil.isEqual(index, -1)) { var server = servers.splice(index, 1)[0]; servers.push(server); storage.setItem('servers', JSON.stringify(servers)); } } } me.connectionStatus = code; setTimeout(function () { StatusEvent.onChanged(code); }); var isDisconnected = (code == RongIMLib.ConnectionStatus.DISCONNECTED); if (isDisconnected) { self.clearHeartbeat(); } var isOtherDevice = (code == RongIMLib.ConnectionStatus.KICKED_OFFLINE_BY_OTHER_CLIENT); if (isOtherDevice) { // 累计其他设备登陆次数,超过 5 次后,自动销毁内部对象 // 删除位置:ServerDataProivder.prototype.connect RongIMLib.RongIMClient.otherDeviceLoginCount++; } var isConnected = (code == RongIMLib.ConnectionStatus.CONNECTED); if (isConnected) { RongIMLib.RongIMClient.isFirstConnect = false; } var isWebsocketUnAvailable = (code == RongIMLib.ConnectionStatus.WEBSOCKET_UNAVAILABLE); if (isWebsocketUnAvailable) { me.changeConnectType(); RongIMLib.RongIMClient.isFirstConnect = false; RongIMLib.RongIMClient.connect(self.token, RongIMLib.RongIMClient._memoryStore.callback); } }); //注册message观察者 this.socket.on("message", self.handler.handleMessage); //注册断开连接观察者 this.socket.on("disconnect", function (status) { that.socket.fire("StatusChanged", status ? status : 2); }); } Channel.prototype.changeConnectType = function () { RongIMLib.RongIMClient._memoryStore.depend.isPolling = !RongIMLib.RongIMClient._memoryStore.depend.isPolling; new RongIMLib.FeatureDectector(); }; Channel.prototype.writeAndFlush = function (val) { this.socket.send(val); }; Channel.prototype.reconnect = function (callback) { RongIMLib.MessageIdHandler.clearMessageId(); this.socket = this.socket.reconnect(); if (callback) { this.self.reconnectObj = callback; } }; Channel.prototype.disconnect = function (status) { this.socket.disconnect(status); }; return Channel; })(); RongIMLib.Channel = Channel; var Socket = (function () { function Socket() { this.socket = null; this._events = {}; } Socket.getInstance = function () { return new Socket(); }; Socket.prototype.connect = function (url, cb) { if (this.socket) { if (url) { RongIMLib.RongIMClient._storageProvider.setItem("rongSDK", this.checkTransport()); this.on("connect", cb || new Function); } if (url) { this.currentURL = url; } this.socket.createTransport(url); } return this; }; Socket.prototype.createServer = function () { var transport = this.getTransport(this.checkTransport()); if (transport === null) { throw new Error("the channel was not supported"); } return transport; }; Socket.prototype.getTransport = function (transportType) { if (transportType == Socket.XHR_POLLING) { this.socket = new RongIMLib.PollingTransportation(this); } else if (transportType == Socket.WEBSOCKET) { this.socket = new RongIMLib.SocketTransportation(this); } return this; }; Socket.prototype.send = function (data) { if (this.socket) { if (this.checkTransport() == Socket.WEBSOCKET) { this.socket.send(data); } else { this.socket.send(this._encode(data)); } } }; Socket.prototype.onMessage = function (data) { this.fire("message", data); }; Socket.prototype.disconnect = function (status) { this.socket.disconnect(status); this.fire("disconnect", status); return this; }; Socket.prototype.reconnect = function () { if (this.currentURL && RongIMLib.RongIMClient._storageProvider.getItem("rongSDK")) { return this.connect(this.currentURL, null); } else { throw new Error("reconnect:no have URL"); } }; /** * [checkTransport 返回通道类型] */ Socket.prototype.checkTransport = function () { if (RongIMLib.RongIMClient._memoryStore.depend.isPolling) { RongIMLib.Transportations._TransportType = Socket.XHR_POLLING; } return RongIMLib.Transportations._TransportType; }; Socket.prototype.fire = function (x, args) { if (x in this._events) { for (var i = 0, ii = this._events[x].length; i < ii; i++) { this._events[x][i](args); } } return this; }; Socket.prototype.on = function (x, func) { if (!(typeof func == "function" && x)) { return this; } if (x in this._events) { RongIMLib.MessageUtil.indexOf(this._events, func) == -1 && this._events[x].push(func); } else { this._events[x] = [func]; } return this; }; Socket.prototype.removeEvent = function (x, fn) { if (x in this._events) { for (var a = 0, l = this._events[x].length; a < l; a++) { if (this._events[x][a] == fn) { this._events[x].splice(a, 1); } } } return this; }; Socket.prototype._encode = function (x) { var str = "?messageid=" + x.getMessageId() + "&header=" + x.getHeaderFlag() + "&sessionid=" + RongIMLib.RongIMClient._storageProvider.getItem("sId" + RongIMLib.Navigation.Endpoint.userId); if (!/(PubAckMessage|QueryConMessage)/.test(x._name)) { str += "&topic=" + x.getTopic() + "&targetid=" + (x.getTargetId() || ""); } return { url: str, data: "getData" in x ? x.getData() : "" }; }; //消息通道常量,所有和通道相关判断均用 XHR_POLLING WEBSOCKET两属性 Socket.XHR_POLLING = "xhr-polling"; Socket.WEBSOCKET = "websocket"; return Socket; })(); RongIMLib.Socket = Socket; //连接端消息累 var Client = (function () { function Client(token, appId) { this.timeoutMillis = 6000; this.timeout_ = 0; this.sdkVer = ''; this.apiVer = Math.floor(Math.random() * 1e6); this.channel = null; this.handler = null; this.userId = ""; this.reconnectObj = {}; this.heartbeat = 0; this.pullMsgHearbeat = 0; this.chatroomId = ""; this.SyncTimeQueue = []; this.cacheMessageIds = []; this.token = token; this.appId = appId; this.SyncTimeQueue.state = "complete"; this.sdkVer = RongIMLib.RongIMClient.sdkver; } Client.prototype.resumeTimer = function () { var me = this; this.timeout_ = setTimeout(function () { me.channel.disconnect(RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE); }, this.timeoutMillis); }; Client.prototype.pauseTimer = function () { if (this.timeout_) { clearTimeout(this.timeout_); this.timeout_ = 0; } }; Client.prototype.connect = function (_callback) { //实例消息处理类 this.handler = new MessageHandler(this); //设置连接回调 this.handler.setConnectCallback(_callback); //实例通道类型 var me = this; this.channel = new Channel(function () { RongIMLib.Transportations._TransportType == Socket.WEBSOCKET && me.keepLive(); }, this); //触发状态改变观察者 this.channel.socket.fire("StatusChanged", RongIMLib.ConnectionStatus.CONNECTING); //没有返回地址就手动抛出错误 //_callback.onError(ConnectionState.NOT_AUTHORIZED); }; Client.prototype.checkSocket = function (callback) { var me = this; me.channel.writeAndFlush(new RongIMLib.PingReqMessage()); var count = 0; var checkTimeout = setInterval(function () { if (!RongIMLib.RongIMClient._memoryStore.isFirstPingMsg) { clearInterval(checkTimeout); callback.onSuccess(); } else { if (count > 15) { clearInterval(checkTimeout); callback.onError(); } } count++; }, 100); }; Client.prototype.keepLive = function () { if (this.heartbeat > 0) { clearInterval(this.heartbeat); } var me = this; me.heartbeat = setInterval(function () { me.resumeTimer(); me.channel.writeAndFlush(new RongIMLib.PingReqMessage()); }, 30000); if (me.pullMsgHearbeat > 0) { clearInterval(me.pullMsgHearbeat); } me.pullMsgHearbeat = setInterval(function () { me.syncTime(true, undefined, undefined, false); }, 180000); }; Client.prototype.clearHeartbeat = function () { clearInterval(this.heartbeat); this.heartbeat = 0; this.pauseTimer(); clearInterval(this.pullMsgHearbeat); this.pullMsgHearbeat = 0; }; Client.prototype.publishMessage = function (_topic, _data, _targetId, _callback, _msg) { var msgId = RongIMLib.MessageIdHandler.messageIdPlus(this.channel.reconnect); if (!msgId) { return; } var msg = new RongIMLib.PublishMessage(_topic, _data, _targetId); msg.setMessageId(msgId); if (_callback) { msg.setQos(Qos.AT_LEAST_ONCE); this.handler.putCallback(new RongIMLib.PublishCallback(_callback.onSuccess, _callback.onError), msg.getMessageId(), _msg); } else { msg.setQos(Qos.AT_MOST_ONCE); } this.channel.writeAndFlush(msg); }; Client.prototype.queryMessage = function (_topic, _data, _targetId, _qos, _callback, pbtype) { if (_topic == "userInf") { if (Client.userInfoMapping[_targetId]) { _callback.onSuccess(Client.userInfoMapping[_targetId]); return; } } var msgId = RongIMLib.MessageIdHandler.messageIdPlus(this.channel.reconnect); if (!msgId) { return; } var msg = new RongIMLib.QueryMessage(_topic, _data, _targetId); msg.setMessageId(msgId); msg.setQos(_qos); this.handler.putCallback(new RongIMLib.QueryCallback(_callback.onSuccess, _callback.onError), msg.getMessageId(), pbtype); this.channel.writeAndFlush(msg); }; Client.prototype.invoke = function (isPullMsg, chrmId, offlineMsg) { var time, modules, str, me = this, target, temp = this.SyncTimeQueue.shift(); if (temp == undefined) { return; } this.SyncTimeQueue.state = "pending"; var localSyncTime = RongIMLib.SyncTimeUtil.get(); var sentBoxTime = localSyncTime.sent; if (temp.type != 2) { //普通消息 time = localSyncTime.received; modules = new RongIMLib.RongIMClient.Protobuf.SyncRequestMsg(); modules.setIspolling(false); str = "pullMsg"; target = this.userId; modules.setSendBoxSyncTime(sentBoxTime); } else { //聊天室消息 target = temp.chrmId || me.chatroomId; time = RongIMLib.RongIMClient._memoryStore.lastReadTime.get(target + Bridge._client.userId + "CST") || 0; modules = new RongIMLib.RongIMClient.Protobuf.ChrmPullMsg(); modules.setCount(0); str = "chrmPull"; if (!target) { throw new Error("syncTime:Received messages of chatroom but was not init"); } } //判断服务器给的时间是否消息本地存储的时间,小于的话不执行拉取操作,进行一下步队列操作 if (temp.pulltime <= time) { this.SyncTimeQueue.state = "complete"; this.invoke(isPullMsg, target, offlineMsg); return; } if (isPullMsg && 'setIsPullSend' in modules) { modules.setIsPullSend(true); } modules.setSyncTime(time); //发送queryMessage请求 this.queryMessage(str, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), target, Qos.AT_LEAST_ONCE, { onSuccess: function (collection) { var sync = RongIMLib.MessageUtil.int64ToTimestamp(collection.syncTime), symbol = target; //把返回时间戳存入本地,普通消息key为userid,聊天室消息key为userid+'CST';value都为服务器返回的时间戳 var isChrmPull = str == 'chrmPull'; if (isChrmPull) { symbol += Bridge._client.userId + "CST"; RongIMLib.RongIMClient._memoryStore.lastReadTime.set(symbol, sync); } else { var storage = RongIMLib.RongIMClient._storageProvider; if (sync > storage.getItem(symbol)) { storage.setItem(symbol, sync); } } //把拉取到的消息逐条传给消息监听器 var list = collection.list; var isPullFinished = collection.finished; // chrmPull 没有 finished 字段,自动设置为拉取完成 if (isChrmPull) { isPullFinished = true; } // 兼容长轮训 finished 为空的造成丢消息情况 if (typeof isPullFinished == 'undefined') { isPullFinished = true; } RongIMLib.RongIMClient._memoryStore.isPullFinished = isPullFinished; var connectAckTime = RongIMLib.RongIMClient._memoryStore.connectAckTime; for (var i = 0, len = list.length, count = len; i < len; i++) { count -= 1; var message = list[i]; var sentTime = RongIMLib.MessageUtil.int64ToTimestamp(message.dataTime); var isSender = message.direction == RongIMLib.MessageDirection.SEND; var compareTime = isSender ? sentBoxTime : time; if (sentTime > compareTime) { var isSyncMessage = false; var isOffLineMessage = sentTime < connectAckTime; Bridge._client.handler.onReceived(message, undefined, isOffLineMessage, count, isSyncMessage, isPullFinished); } } me.SyncTimeQueue.state = "complete"; me.invoke(isPullMsg, target, offlineMsg); }, onError: function (error) { me.SyncTimeQueue.state = "complete"; me.invoke(isPullMsg, target, offlineMsg); } }, "DownStreamMessages"); }; Client.prototype.syncTime = function (_type, pullTime, chrmId, offlineMsg) { this.SyncTimeQueue.push({ type: _type, pulltime: pullTime, chrmId: chrmId }); //如果队列中只有一个成员并且状态已经完成就执行invoke方法 if (this.SyncTimeQueue.length == 1 && this.SyncTimeQueue.state == "complete") { this.invoke(!_type, chrmId, offlineMsg); } }; Client.prototype.__init = function (f) { this.handler = new MessageHandler(this); //设置连接回调 this.handler.setConnectCallback(RongIMLib.RongIMClient._memoryStore.callback); this.channel = new Channel(f, this); }; Client.userInfoMapping = {}; return Client; })(); RongIMLib.Client = Client; //连接类,实现imclient与connect_client的连接 var Bridge = (function () { function Bridge() { } Bridge.getInstance = function () { return new Bridge(); }; //连接服务器 Bridge.prototype.connect = function (appKey, token, callback) { if (!RongIMLib.RongIMClient.Protobuf) { return; } Bridge._client = new RongIMLib.Navigation().connect(appKey, token, callback); return Bridge._client; }; Bridge.prototype.setListener = function (_changer) { if (typeof _changer == "object") { if (typeof _changer.onChanged == "function") { Channel._ConnectionStatusListener = _changer; } else if (typeof _changer.onReceived == "function") { Channel._ReceiveMessageListener = _changer; } } }; Bridge.prototype.reconnect = function (callabck) { Bridge._client.channel.reconnect(callabck); }; Bridge.prototype.disconnect = function () { Bridge._client.channel.disconnect(2); }; //执行queryMessage请求 Bridge.prototype.queryMsg = function (topic, content, targetId, callback, pbname) { if (typeof topic != "string") { topic = _topic[topic]; } Bridge._client.queryMessage(topic, content, targetId, Qos.AT_MOST_ONCE, callback, pbname); }; //发送消息 执行publishMessage 请求 Bridge.prototype.pubMsg = function (topic, content, targetId, callback, msg, methodType) { if (typeof methodType == 'number') { if (methodType == RongIMLib.MethodType.CUSTOMER_SERVICE) { Bridge._client.publishMessage("pcuMsgP", content, targetId, callback, msg); } else if (methodType == RongIMLib.MethodType.RECALL) { Bridge._client.publishMessage("recallMsg", content, targetId, callback, msg); } } else { Bridge._client.publishMessage(_topic[10][topic], content, targetId, callback, msg); } }; return Bridge; })(); RongIMLib.Bridge = Bridge; var MessageHandler = (function () { function MessageHandler(client) { this.map = {}; this.connectCallback = null; if (!Channel._ReceiveMessageListener) { throw new Error("please set onReceiveMessageListener"); } this._onReceived = Channel._ReceiveMessageListener.onReceived; this._client = client; this.syncMsgMap = new Object; } //把对象推入回调对象队列中,并启动定时器 MessageHandler.prototype.putCallback = function (callbackObj, _publishMessageId, _msg) { var item = { Callback: callbackObj, Message: _msg }; item.Callback.resumeTimer(); this.map[_publishMessageId] = item; }; //设置连接回调对象,启动定时器 MessageHandler.prototype.setConnectCallback = function (_connectCallback) { if (_connectCallback) { this.connectCallback = new RongIMLib.ConnectAck(_connectCallback.onSuccess, _connectCallback.onError, this._client); } }; MessageHandler.prototype.onReceived = function (msg, pubAckItem, offlineMsg, leftCount, isSync) { //实体对象 var entity, //解析完成的消息对象 message, //会话对象 con, // 是否为直发消息 isStraightMsg = false; if (msg._name != "PublishMessage") { entity = msg; RongIMLib.RongIMClient._storageProvider.setItem(this._client.userId, RongIMLib.MessageUtil.int64ToTimestamp(entity.dataTime)); } else { if (msg.getTopic() == "s_ntf") { entity = RongIMLib.RongIMClient.Protobuf.NotifyMsg.decode(msg.getData()); this._client.syncTime(entity.type, RongIMLib.MessageUtil.int64ToTimestamp(entity.time), entity.chrmId); return; } else if (msg.getTopic() == "s_msg") { isStraightMsg = true; entity = RongIMLib.RongIMClient.Protobuf.DownStreamMessage.decode(msg.getData()); var timestamp = RongIMLib.MessageUtil.int64ToTimestamp(entity.dataTime); RongIMLib.RongIMClient._storageProvider.setItem(this._client.userId, timestamp); RongIMLib.RongIMClient._memoryStore.lastReadTime.get(this._client.userId, timestamp); } else if (msg.getTopic() == "s_stat") { entity = RongIMLib.RongIMClient.Protobuf.GetUserStatusOutput.decode(msg.getData()); entity = RongIMLib.RongInnerTools.convertUserStatus(entity); RongIMLib.RongIMClient.userStatusObserver.notify({ key: entity.userId, entity: entity }); return; } else { if (Bridge._client.sdkVer && Bridge._client.sdkVer == "1.0.0") { return; } entity = RongIMLib.RongIMClient.Protobuf.UpStreamMessage.decode(msg.getData()); var tmpTopic = msg.getTopic(); var tmpType = tmpTopic.substr(0, 2); if (tmpType == "pp") { entity.type = 1; } else if (tmpType == "pd") { entity.type = 2; } else if (tmpType == "pg") { entity.type = 3; } else if (tmpType == "ch") { entity.type = 4; } else if (tmpType == "pc") { entity.type = 5; } //复用字段,targetId 以此为准 entity.groupId = msg.getTargetId(); entity.fromUserId = this._client.userId; entity.dataTime = Date.parse(new Date().toString()); } if (!entity) { return; } } var isPullFinished = RongIMLib.RongIMClient._memoryStore.isPullFinished; // PullMsg 没有拉取完成,抛弃所有直发在线消息,抛弃的消息会在 PullMsg 中返回 if (!isPullFinished && !offlineMsg && isStraightMsg) { return; } //解析实体对象为消息对象。 message = RongIMLib.MessageUtil.messageParser(entity, this._onReceived, offlineMsg); var isRTCMessage = message.conversationType == 12; if (isRTCMessage) { RongIMLib.RongIMClient.RTCListener(message); RongIMLib.RongIMClient.RTCInnerListener(message); RongIMLib.RongIMClient.RTCSignalLisener(message); return; } var isRecall = (msg.getTopic && msg.getTopic() == "recallMsg"); if (isRecall) { var content = message.content; message.conversationType = content.conversationType; message.targetId = content.targetId; message.messageId = null; } if (pubAckItem) { message.messageUId = pubAckItem.getMessageUId(); message.sentTime = pubAckItem.getTimestamp(); RongIMLib.RongIMClient._storageProvider.setItem(this._client.userId, message.sentTime); } if (message === null) { return; } var isChatroomMessage = message.conversationType == RongIMLib.ConversationType.CHATROOM; if (!isChatroomMessage) { var msgTag = RongIMLib.RongIMClient.MessageParams[message.messageType].msgTag.getMessageTag(); if (msgTag >= 0) { RongIMLib.SyncTimeUtil.set(message); } var isSend = (message.messageDirection == RongIMLib.MessageDirection.SEND); if (isSend) { var storageProvider = RongIMLib.RongIMClient._storageProvider; var userId = RongIMLib.Bridge._client.userId; var lastSentTime = storageProvider.getItem('last_sentTime_' + userId) || 0; if (message.sentTime <= lastSentTime && !isSync) { return; } } } // 设置会话时间戳并且判断是否传递 message 发送消息未处理会话时间戳 // key:'converST_' + 当前用户 + conversationType + targetId // RongIMClient._storageProvider.setItem('converST_' + Bridge._client.userId + message.conversationType + message.targetId, message.sentTime); var isPersited = (RongIMLib.RongIMClient.MessageParams[message.messageType].msgTag.getMessageTag() > 0); if (isPersited) { con = RongIMLib.RongIMClient._dataAccessProvider.getConversation(message.conversationType, message.targetId, { onSuccess: function () { }, onError: function () { } }); if (!con) { con = RongIMLib.RongIMClient.getInstance().createConversation(message.conversationType, message.targetId, ""); } if (message.messageDirection == RongIMLib.MessageDirection.RECEIVE && (entity.status & 64) == 64) { var mentioneds = RongIMLib.RongIMClient._storageProvider.getItem("mentioneds_" + Bridge._client.userId + '_' + message.conversationType + '_' + message.targetId); var key = message.conversationType + '_' + message.targetId, info = {}; if (message.content && message.content.mentionedInfo) { info[key] = { uid: message.messageUId, time: message.sentTime, mentionedInfo: message.content.mentionedInfo }; RongIMLib.RongIMClient._storageProvider.setItem("mentioneds_" + Bridge._client.userId + '_' + message.conversationType + '_' + message.targetId, JSON.stringify(info)); mentioneds = JSON.stringify(info); } if (mentioneds) { var info = JSON.parse(mentioneds); con.mentionedMsg = info[key]; } } var isReceiver = message.messageDirection == RongIMLib.MessageDirection.RECEIVE; if (isReceiver && message.senderUserId != Bridge._client.userId) { con.unreadMessageCount = con.unreadMessageCount + 1; if (RongIMLib.RongUtil.supportLocalStorage()) { var originUnreadCount = RongIMLib.RongIMClient._storageProvider.getItem("cu" + Bridge._client.userId + con.conversationType + con.targetId); // 与本地存储会话合并 var newUnreadCount = Number(originUnreadCount) + 1; RongIMLib.RongIMClient._storageProvider.setItem("cu" + Bridge._client.userId + con.conversationType + message.targetId, newUnreadCount); con.unreadMessageCount = newUnreadCount; } } con.receivedTime = new Date().getTime(); con.receivedStatus = message.receivedStatus; con.senderUserId = message.sendUserId; con.notificationStatus = RongIMLib.ConversationNotificationStatus.DO_NOT_DISTURB; con.latestMessageId = message.messageId; con.latestMessage = message; con.sentTime = message.sentTime; RongIMLib.RongIMClient._dataAccessProvider.addConversation(con, { onSuccess: function (data) { }, onError: function () { } }); } if (message.conversationType == RongIMLib.ConversationType.CUSTOMER_SERVICE && (message.messageType == "ChangeModeResponseMessage" || message.messageType == "SuspendMessage" || message.messageType == "HandShakeResponseMessage" || message.messageType == "TerminateMessage" || message.messageType == "CustomerStatusUpdateMessage" || message.messageType == "TextMessage" || message.messageType == "InformationNotificationMessage")) { if (!RongIMLib.RongIMClient._memoryStore.custStore["isInit"]) { return; } } if (message.conversationType == RongIMLib.ConversationType.CUSTOMER_SERVICE && message.messageType != "HandShakeResponseMessage") { if (!RongIMLib.RongIMClient._memoryStore.custStore[message.targetId]) { return; } if (message.messageType == "TerminateMessage") { if (RongIMLib.RongIMClient._memoryStore.custStore[message.targetId].sid != message.content.sid) { return; } } } if (message.messageType === RongIMLib.RongIMClient.MessageType["HandShakeResponseMessage"]) { var session = message.content.data; RongIMLib.RongIMClient._memoryStore.custStore[message.targetId] = session; if (session.serviceType == RongIMLib.CustomerType.ONLY_HUMAN || session.serviceType == RongIMLib.CustomerType.HUMAN_FIRST) { if (session.notAutoCha == "1") { RongIMLib.RongIMClient.getInstance().switchToHumanMode(message.targetId, { onSuccess: function () { }, onError: function () { } }); } } } var d = new Date(), m = d.getMonth() + 1, date = d.getFullYear() + '/' + (m.toString().length == 1 ? '0' + m : m) + '/' + d.getDate(); //new Date(date).getTime() - message.sentTime < 1 逻辑判断 超过 1 天未收的 ReadReceiptRequestMessage 离线消息自动忽略。 var dealtime = new Date(date).getTime() - message.sentTime < 0; if (RongIMLib.RongUtil.supportLocalStorage() && message.messageType === RongIMLib.RongIMClient.MessageType["ReadReceiptRequestMessage"] && dealtime && message.messageDirection == RongIMLib.MessageDirection.SEND) { var sentkey = Bridge._client.userId + message.content.messageUId + "SENT"; RongIMLib.RongIMClient._storageProvider.setItem(sentkey, JSON.stringify({ count: 0, dealtime: message.sentTime, userIds: {} })); } else if (RongIMLib.RongUtil.supportLocalStorage() && message.messageType === RongIMLib.RongIMClient.MessageType["ReadReceiptRequestMessage"] && dealtime) { var reckey = Bridge._client.userId + message.conversationType + message.targetId + 'RECEIVED', recData = JSON.parse(RongIMLib.RongIMClient._storageProvider.getItem(reckey)); if (recData) { if (message.senderUserId in recData) { if (recData[message.senderUserId].uIds && recData[message.senderUserId].uIds && recData[message.senderUserId].uIds.indexOf(message.content.messageUId) == -1) { recData[message.senderUserId].uIds.push(message.content.messageUId); recData[message.senderUserId].dealtime = message.sentTime; recData[message.senderUserId].isResponse = false; RongIMLib.RongIMClient._storageProvider.setItem(reckey, JSON.stringify(recData)); } else { return; } } else { var objSon = { uIds: [message.content.messageUId], dealtime: message.sentTime, isResponse: false }; recData[message.senderUserId] = objSon; RongIMLib.RongIMClient._storageProvider.setItem(reckey, JSON.stringify(recData)); } } else { var obj = {}; obj[message.senderUserId] = { uIds: [message.content.messageUId], dealtime: message.sentTime, isResponse: false }; RongIMLib.RongIMClient._storageProvider.setItem(reckey, JSON.stringify(obj)); } } if (RongIMLib.RongUtil.supportLocalStorage() && message.messageType === RongIMLib.RongIMClient.MessageType["ReadReceiptResponseMessage"] && dealtime) { var receiptResponseMsg = message.content, uIds = receiptResponseMsg.receiptMessageDic[Bridge._client.userId], sentkey = "", sentObj; message.receiptResponse || (message.receiptResponse = {}); if (uIds) { var cbuIds = []; for (var i = 0, len = uIds.length; i < len; i++) { sentkey = Bridge._client.userId + uIds[i] + "SENT"; sentObj = JSON.parse(RongIMLib.RongIMClient._storageProvider.getItem(sentkey)); if (sentObj && !(message.senderUserId in sentObj.userIds)) { cbuIds.push(uIds[i]); sentObj.count += 1; sentObj.userIds[message.senderUserId] = message.sentTime; message.receiptResponse[uIds[i]] = sentObj.count; RongIMLib.RongIMClient._storageProvider.setItem(sentkey, JSON.stringify(sentObj)); } } receiptResponseMsg.receiptMessageDic[Bridge._client.userId] = cbuIds; message.content = receiptResponseMsg; } } var that = this; if (RongIMLib.RongIMClient._voipProvider && ['AcceptMessage', 'RingingMessage', 'HungupMessage', 'InviteMessage', 'MediaModifyMessage', 'MemberModifyMessage'].indexOf(message.messageType) > -1) { setTimeout(function () { RongIMLib.RongIMClient._voipProvider.onReceived(message); }); } else { var count = leftCount || 0; var hasMore = !isPullFinished; setTimeout(function () { that._onReceived(message, count, hasMore); }); } }; MessageHandler.prototype.handleMessage = function (msg) { if (!msg) { return; } switch (msg._name) { case "ConnAckMessage": Bridge._client.handler.connectCallback.process(msg.getStatus(), msg.getUserId(), msg.getTimestamp()); break; case "PublishMessage": if (!msg.getSyncMsg() && msg.getQos() != 0) { Bridge._client.channel.writeAndFlush(new RongIMLib.PubAckMessage(msg.getMessageId())); } // TODO && -> if (msg.getSyncMsg() && !RongIMLib.RongIMClient._memoryStore.depend.isPolling) { Bridge._client.handler.syncMsgMap[msg.getMessageId()] = msg; } else { //如果是PublishMessage就把该对象给onReceived方法执行处理 Bridge._client.handler.onReceived(msg); } break; case "QueryAckMessage": if (msg.getQos() != 0) { Bridge._client.channel.writeAndFlush(new RongIMLib.QueryConMessage(msg.getMessageId())); } var temp = Bridge._client.handler.map[msg.getMessageId()]; if (temp) { //执行回调操作 temp.Callback.process(msg.getStatus(), msg.getData(), msg.getDate(), temp.Message); delete Bridge._client.handler.map[msg.getMessageId()]; } break; case "PubAckMessage": var item = Bridge._client.handler.map[msg.getMessageId()]; if (item) { item.Callback.process(msg.getStatus() || 0, msg.getMessageUId(), msg.getTimestamp(), item.Message, msg.getMessageId()); delete Bridge._client.handler.map[msg.getMessageId()]; } else { var userId = RongIMLib.Bridge._client.userId; RongIMLib.RongIMClient._storageProvider.setItem('last_sentTime_' + userId, msg.timestamp); Bridge._client.handler.onReceived(Bridge._client.handler.syncMsgMap[msg.messageId], msg, null, null, true); delete Bridge._client.handler.syncMsgMap[msg.getMessageId()]; } break; case "PingRespMessage": if (RongIMLib.RongIMClient._memoryStore.isFirstPingMsg) { RongIMLib.RongIMClient._memoryStore.isFirstPingMsg = false; } else { Bridge._client.pauseTimer(); } break; case "DisconnectMessage": Bridge._client.channel.disconnect(msg.getStatus()); break; default: } }; return MessageHandler; })(); RongIMLib.MessageHandler = MessageHandler; })(RongIMLib || (RongIMLib = {})); var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; /// var RongIMLib; (function (RongIMLib) { var MessageCallback = (function () { function MessageCallback(error) { this.timeout = null; this.onError = null; if (error && typeof error == "number") { this.timeoutMillis = error; } else { this.timeoutMillis = 30000; this.onError = error; } } MessageCallback.prototype.resumeTimer = function () { var me = this; if (this.timeoutMillis > 0 && !this.timeout) { this.timeout = setTimeout(function () { me.readTimeOut(true); }, this.timeoutMillis); } }; MessageCallback.prototype.pauseTimer = function () { if (this.timeout) { clearTimeout(this.timeout); this.timeout = null; } }; MessageCallback.prototype.readTimeOut = function (isTimeout) { if (isTimeout && this.onError) { this.onError(RongIMLib.ErrorCode.TIMEOUT); } else { this.pauseTimer(); } }; return MessageCallback; })(); RongIMLib.MessageCallback = MessageCallback; var CallbackMapping = (function () { function CallbackMapping() { this.publicServiceList = []; } CallbackMapping.getInstance = function () { return new CallbackMapping(); }; CallbackMapping.prototype.pottingProfile = function (item) { var temp; this.profile = new RongIMLib.PublicServiceProfile(); temp = JSON.parse(item.extra); this.profile.isGlobal = temp.isGlobal; this.profile.introduction = temp.introduction; this.profile.menu = temp.menu; this.profile.hasFollowed = temp.follow; this.profile.publicServiceId = item.mpid; this.profile.name = item.name; this.profile.portraitUri = item.portraitUrl; this.profile.conversationType = item.type == "mc" ? RongIMLib.ConversationType.APP_PUBLIC_SERVICE : RongIMLib.ConversationType.PUBLIC_SERVICE; this.publicServiceList.push(this.profile); }; CallbackMapping.prototype.mapping = function (entity, tag) { switch (tag) { case "GetUserInfoOutput": var userInfo = new RongIMLib.UserInfo(entity.userId, entity.userName, entity.userPortrait); return userInfo; case "GetQNupTokenOutput": return { deadline: RongIMLib.MessageUtil.int64ToTimestamp(entity.deadline), token: entity.token }; case "GetQNdownloadUrlOutput": return { downloadUrl: entity.downloadUrl }; case "CreateDiscussionOutput": return entity.id; case "ChannelInfoOutput": var disInfo = new RongIMLib.Discussion(); disInfo.creatorId = entity.adminUserId; disInfo.id = entity.channelId; disInfo.memberIdList = entity.firstTenUserIds; disInfo.name = entity.channelName; disInfo.isOpen = entity.openStatus; return disInfo; case "GroupHashOutput": return entity.result; case "QueryBlackListOutput": return entity.userIds; case "SearchMpOutput": case "PullMpOutput": if (entity.info) { var self = this; Array.forEach(entity.info, function (item) { setTimeout(function () { self.pottingProfile(item); }, 100); }); } return this.publicServiceList; default: return entity; } }; return CallbackMapping; })(); RongIMLib.CallbackMapping = CallbackMapping; var PublishCallback = (function (_super) { __extends(PublishCallback, _super); function PublishCallback(_cb, _timeout) { _super.call(this, _timeout); this._cb = _cb; this._timeout = _timeout; } PublishCallback.prototype.process = function (_status, messageUId, timestamp, _msg, messageId) { this.readTimeOut(); if (_status == 0) { if (_msg) { _msg.setSentStatus = _status; } var isPullFinished = RongIMLib.RongIMClient._memoryStore.isPullFinished; if (isPullFinished) { var userId = RongIMLib.Bridge._client.userId; var stroageProvider = RongIMLib.RongIMClient._storageProvider; stroageProvider.setItem('last_sentTime_' + userId, timestamp); RongIMLib.SyncTimeUtil.set({ messageDirection: RongIMLib.MessageDirection.SEND, sentTime: timestamp }); } this._cb({ messageUId: messageUId, timestamp: timestamp, messageId: messageId }); } else { this._timeout(_status, { messageUId: messageUId, sentTime: timestamp }); } }; PublishCallback.prototype.readTimeOut = function (x) { MessageCallback.prototype.readTimeOut.call(this, x); }; return PublishCallback; })(MessageCallback); RongIMLib.PublishCallback = PublishCallback; var QueryCallback = (function (_super) { __extends(QueryCallback, _super); function QueryCallback(_cb, _timeout) { _super.call(this, _timeout); this._cb = _cb; this._timeout = _timeout; } QueryCallback.prototype.process = function (status, data, serverTime, pbtype) { this.readTimeOut(); if (pbtype && data && status == 0) { try { data = CallbackMapping.getInstance().mapping(RongIMLib.RongIMClient.Protobuf[pbtype].decode(data), pbtype); } catch (e) { this._timeout(RongIMLib.ErrorCode.UNKNOWN); return; } if ("GetUserInfoOutput" == pbtype) { //pb类型为GetUserInfoOutput的话就把data放入userinfo缓存队列 RongIMLib.Client.userInfoMapping[data.userId] = data; } this._cb(data); } else { status > 0 ? this._timeout(status) : this._cb(status); } }; QueryCallback.prototype.readTimeOut = function (x) { MessageCallback.prototype.readTimeOut.call(this, x); }; return QueryCallback; })(MessageCallback); RongIMLib.QueryCallback = QueryCallback; var ConnectAck = (function (_super) { __extends(ConnectAck, _super); function ConnectAck(_cb, _timeout, client) { _super.call(this, _timeout); this._client = client; this._cb = _cb; this._timeout = _timeout; } ConnectAck.prototype.process = function (status, userId, timestamp) { this.readTimeOut(); if (status == 0) { this._client.userId = userId; var self = this; if (!RongIMLib.RongIMClient._memoryStore.depend.isPolling && RongIMLib.RongIMClient._memoryStore.isFirstPingMsg) { RongIMLib.Bridge._client.checkSocket({ onSuccess: function () { if (!RongIMLib.RongIMClient.isNotPullMsg) { self._client.syncTime(undefined, undefined, undefined, true); } }, onError: function () { RongIMLib.RongIMClient._memoryStore.isFirstPingMsg = false; RongIMLib.RongIMClient.getInstance().disconnect(); RongIMLib.RongIMClient.connect(RongIMLib.RongIMClient._memoryStore.token, RongIMLib.RongIMClient._memoryStore.callback); } }); } else { if (!RongIMLib.RongIMClient.isNotPullMsg) { self._client.syncTime(undefined, undefined, undefined, true); } } RongIMLib.Bridge._client.channel.socket.fire("StatusChanged", 0); if (this._client.reconnectObj.onSuccess) { this._client.reconnectObj.onSuccess(userId); delete this._client.reconnectObj.onSuccess; } else { var me = this; setTimeout(function () { me._cb(userId); }, 500); } RongIMLib.RongIMClient._memoryStore.connectAckTime = timestamp; console.log('[RongCloud] ConnectAckTime:', timestamp); console.log('[RongCloud] Local Time:', +new Date()); if (!(new Date().getTime() - timestamp)) { RongIMLib.RongIMClient._memoryStore.deltaTime = 0; console.log('[RongCloud] Delta Time:', 0); } else { RongIMLib.RongIMClient._memoryStore.deltaTime = new Date().getTime() - timestamp; console.log('[RongCloud] Delta Time:', RongIMLib.RongIMClient._memoryStore.deltaTime); } } else if (status == 6) { RongIMLib.RongIMClient.getInstance().disconnect(); //重定向 连错 CMP var me = this; var _client = me._client; var appId = _client.appId, token = _client.token; new RongIMLib.Navigation().requestNavi(token, appId, function () { _client.clearHeartbeat(); var newClient = new RongIMLib.Client(token, appId); RongIMLib.Bridge._client = newClient; newClient.__init(function () { RongIMLib.Transportations._TransportType == "websocket" && newClient.keepLive(); }); }, me._timeout, false); } else { RongIMLib.Bridge._client.channel.socket.socket._status = status; if (this._client.reconnectObj.onError) { this._client.reconnectObj.onError(status); delete this._client.reconnectObj.onError; } else { this._timeout(status); } } }; ConnectAck.prototype.readTimeOut = function (x) { MessageCallback.prototype.readTimeOut.call(this, x); }; return ConnectAck; })(MessageCallback); RongIMLib.ConnectAck = ConnectAck; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var Navigation = (function () { function Navigation() { } Navigation.clear = function () { var storage = RongIMLib.RongIMClient._storageProvider; storage.removeItem('rc_uid'); storage.removeItem('serverIndex'); storage.removeItem('rongSDK'); }; Navigation.prototype.getNaviSuccess = function (result) { var storage = RongIMLib.RongIMClient._storageProvider; storage.setItem('fullnavi', JSON.stringify(result)); var server = result.server; if (server) { server += ','; } var backupServer = result.backupServer || ''; var tpl = '{server}{backupServer}'; var servers = RongIMLib.RongUtil.tplEngine(tpl, { server: server, backupServer: backupServer }); servers = servers.split(','); storage.setItem('servers', JSON.stringify(servers)); var token = RongIMLib.RongIMClient._memoryStore.token; var uid = RongIMLib.InnerUtil.getUId(token); storage.setItem('rc_uid', uid); var userId = result.userId; storage.setItem('current_user', userId); if (result.voipCallInfo) { var callInfo = JSON.parse(result.voipCallInfo); RongIMLib.RongIMClient._memoryStore.voipStategy = callInfo.strategy; storage.setItem("voipStrategy", callInfo.strategy); } //替换本地存储的导航信息 var openMp = result.openMp; storage.setItem('openMp' + uid, openMp); RongIMLib.RongIMClient._memoryStore.depend.openMp = openMp; }; ; Navigation.prototype.connect = function (appId, token, callback) { var oldAppId = RongIMLib.RongIMClient._storageProvider.getItem("appId"); //如果appid和本地存储的不一样,清空所有本地存储数据 if (oldAppId && oldAppId != appId) { RongIMLib.RongIMClient._storageProvider.clearItem(); RongIMLib.RongIMClient._storageProvider.setItem("appId", appId); } if (!oldAppId) { RongIMLib.RongIMClient._storageProvider.setItem("appId", appId); } var client = new RongIMLib.Client(token, appId); this.requestNavi(token, appId, function () { client.connect(callback); }, callback.onError, true); return client; }; Navigation.prototype.requestNavi = function (token, appId, _onsuccess, _onerror, unignore) { if (unignore) { //根据token生成MD5截取8-16下标的数据与本地存储的导航信息进行比对 //如果信息和上次的通道类型都一样,不执行navi请求,用本地存储的导航信息连接服务器 var uId = md5(token).slice(8, 16); var storage = RongIMLib.RongIMClient._storageProvider; var transportType = storage.getItem("rongSDK"); var isSameType = (RongIMLib.Transportations._TransportType == transportType); var _old = storage.getItem('rc_uid'); var isSameUser = (_old == uId); var servers = storage.getItem('servers'); var hasServers = (typeof servers == 'string'); if (isSameUser && isSameType && hasServers) { RongIMLib.RongIMClient._memoryStore.voipStategy = storage.getItem("voipStrategy"); var openMp = storage.getItem('openMp' + uId); RongIMLib.RongIMClient._memoryStore.depend.openMp = openMp; _onsuccess(); return; } } Navigation.clear(); var context = this; var StatusEvent = RongIMLib.Channel._ConnectionStatusListener; var depend = RongIMLib.RongIMClient._memoryStore.depend; var navigaters = depend.navigaters; var naviTimeout = depend.naviTimeout; var maxNaviRetry = depend.maxNaviRetry; var isNaviJSONP = depend.isNaviJSONP; var isSupportRequestHeaders = RongIMLib.RongUtil.isSupportRequestHeaders(); var isRequestJSONP = !isSupportRequestHeaders || isNaviJSONP; var requestFunc = isRequestJSONP ? context.requestJSONP : context.request; var timer = new RongIMLib.Timer({ timeout: naviTimeout }); var internalRetry = 1; var isRange = function () { return internalRetry >= maxNaviRetry; }; var indexTools = new RongIMLib.IndexTools({ items: navigaters, onwheel: function () { internalRetry += 1; } }); var consume = function () { if (isRange()) { _onerror(RongIMLib.ConnectionStatus.RESPONSE_NAVI_ERROR); return; } var index = indexTools.get(); var navi = navigaters[index]; indexTools.add(); var success = function (result) { timer.pause(); StatusEvent.onChanged(RongIMLib.ConnectionStatus.RESPONSE_NAVI); var code = result.code; if (RongIMLib.RongUtil.isEqual(code, 200)) { context.getNaviSuccess(result); _onsuccess(); } if (RongIMLib.RongUtil.isEqual(code, 401)) { _onerror(RongIMLib.ConnectionState.TOKEN_INCORRECT); } if (RongIMLib.RongUtil.isEqual(code, 403)) { StatusEvent.onChanged(RongIMLib.ConnectionStatus.APPKEY_IS_FAKE); } }; var error = function (status) { if (RongIMLib.RongUtil.isEqual(status, 0)) { return; } timer.pause(); StatusEvent.onChanged(RongIMLib.ConnectionStatus.RESPONSE_NAVI_ERROR); consume(); }; StatusEvent.onChanged(RongIMLib.ConnectionStatus.REQUEST_NAVI); var xhr = requestFunc.call(context, navi, appId, token, success, error); timer.resume(function () { StatusEvent.onChanged(RongIMLib.ConnectionStatus.RESPONSE_NAVI_TIMEOUT); xhr.abort(); consume(); }); }; consume(); }; Navigation.prototype.getPath = function (navi, appId, token, callbackName) { var depend = RongIMLib.RongIMClient._memoryStore.depend; var path = (depend.isPolling ? 'cometnavi' : 'navi'); token = encodeURIComponent(token); var sdkver = RongIMLib.RongIMClient.sdkver; var random = RongIMLib.RongUtil.getTimestamp(); var tpl = '{navi}/{path}.js?appId={appId}&token={token}&callBack={callback}&v={sdkver}&r={random}'; var url = RongIMLib.RongUtil.tplEngine(tpl, { navi: navi, path: path, appId: appId, token: token, sdkver: sdkver, random: random, callback: callbackName }); return url; }; Navigation.prototype.request = function (navi, appId, token, success, error) { var url = this.getPath(navi, appId, token, 'getServerEndpoint'); return RongIMLib.RongUtil.request({ url: url, success: function (result) { result = result.replace('getServerEndpoint(', '').replace(');', ''); // 兼容私有云无分号 var lastIndex = result.lastIndexOf(')'); var maxIndex = result.length - 1; if (lastIndex == maxIndex) { result = result.substr(0, lastIndex); } success(JSON.parse(result)); }, error: function (status, result) { if (status == 401 || status == 403) { success(JSON.parse(result)); } else { error(status); } } }); }; Navigation.prototype.requestJSONP = function (navi, appId, token, success, error) { var callbackName = 'getServerEndpoint'; window.getServerEndpoint = function (result) { var code = result.code; if (code !== 200) { return error(RongIMLib.ConnectionState.TOKEN_INCORRECT); } success(result); }; var url = this.getPath(navi, appId, token, callbackName); var xss = document.createElement('script'); xss.src = url; document.body.appendChild(xss); xss.onerror = function () { error(RongIMLib.ConnectionState.TOKEN_INCORRECT); }; }; Navigation.Endpoint = new Object; return Navigation; })(); RongIMLib.Navigation = Navigation; })(RongIMLib || (RongIMLib = {})); // TODO: 统一变量、方法等命名规范 var RongIMLib; (function (RongIMLib) { /** * 消息基类 */ var BaseMessage = (function () { function BaseMessage(arg) { this._name = "BaseMessage"; this.lengthSize = 0; if (arg instanceof RongIMLib.Header) { this._header = arg; } else { this._header = new RongIMLib.Header(arg, false, RongIMLib.Qos.AT_MOST_ONCE, false); } } BaseMessage.prototype.read = function (In, length) { this.readMessage(In, length); }; BaseMessage.prototype.write = function (Out) { var binaryHelper = new RongIMLib.BinaryHelper(); var out = binaryHelper.convertStream(Out); this._headerCode = this.getHeaderFlag(); out.write(this._headerCode); this.writeMessage(out); return out; }; BaseMessage.prototype.getHeaderFlag = function () { return this._header.encode(); }; BaseMessage.prototype.getLengthSize = function () { return this.lengthSize; }; BaseMessage.prototype.toBytes = function () { return this.write([]).getBytesArray(); }; BaseMessage.prototype.isRetained = function () { return this._header.retain; }; BaseMessage.prototype.setRetained = function (retain) { this._header.retain = retain; }; BaseMessage.prototype.setQos = function (qos) { this._header.qos = Object.prototype.toString.call(qos) == "[object Object]" ? qos : RongIMLib.Qos[qos]; }; BaseMessage.prototype.setDup = function (dup) { this._header.dup = dup; }; BaseMessage.prototype.isDup = function () { return this._header.dup; }; BaseMessage.prototype.getType = function () { return this._header.type; }; BaseMessage.prototype.getQos = function () { return this._header.qos; }; BaseMessage.prototype.messageLength = function () { return 0; }; BaseMessage.prototype.writeMessage = function (out) { }; BaseMessage.prototype.readMessage = function (In, length) { }; BaseMessage.prototype.init = function (args) { var valName, nana, me = this; for (nana in args) { if (!args.hasOwnProperty(nana)) { continue; } valName = nana.replace(/^\w/, function (x) { var tt = x.charCodeAt(0); return "set" + (tt >= 0x61 ? String.fromCharCode(tt & ~32) : x); }); if (valName in me) { if (nana == "status") { me[valName](disconnectStatus[args[nana]] ? disconnectStatus[args[nana]] : args[nana]); } else { me[valName](args[nana]); } } } }; return BaseMessage; })(); RongIMLib.BaseMessage = BaseMessage; /** *连接消息类型 */ var ConnectMessage = (function (_super) { __extends(ConnectMessage, _super); function ConnectMessage(header) { _super.call(this, arguments.length == 0 || arguments.length == 3 ? RongIMLib.Type.CONNECT : arguments[0]); this._name = "ConnectMessage"; this.CONNECT_HEADER_SIZE = 12; this.protocolId = "RCloud"; this.binaryHelper = new RongIMLib.BinaryHelper(); this.protocolVersion = 3; switch (arguments.length) { case 0: case 1: case 3: if (!arguments[0] || arguments[0].length > 64) { throw new Error("ConnectMessage:Client Id cannot be null and must be at most 64 characters long: " + arguments[0]); } this.clientId = arguments[0]; this.cleanSession = arguments[1]; this.keepAlive = arguments[2]; break; } } ConnectMessage.prototype.messageLength = function () { var payloadSize = this.binaryHelper.toMQttString(this.clientId).length; payloadSize += this.binaryHelper.toMQttString(this.willTopic).length; payloadSize += this.binaryHelper.toMQttString(this.will).length; payloadSize += this.binaryHelper.toMQttString(this.appId).length; payloadSize += this.binaryHelper.toMQttString(this.token).length; return payloadSize + this.CONNECT_HEADER_SIZE; }; ConnectMessage.prototype.readMessage = function (stream) { this.protocolId = stream.readUTF(); this.protocolVersion = stream.readByte(); var cFlags = stream.readByte(); this.hasAppId = (cFlags & 128) > 0; this.hasToken = (cFlags & 64) > 0; this.retainWill = (cFlags & 32) > 0; this.willQos = cFlags >> 3 & 3; this.hasWill = (cFlags & 4) > 0; this.cleanSession = (cFlags & 32) > 0; this.keepAlive = stream.read() * 256 + stream.read(); this.clientId = stream.readUTF(); if (this.hasWill) { this.willTopic = stream.readUTF(); this.will = stream.readUTF(); } if (this.hasAppId) { try { this.appId = stream.readUTF(); } catch (ex) { throw new Error(ex); } } if (this.hasToken) { try { this.token = stream.readUTF(); } catch (ex) { throw new Error(ex); } } return stream; }; ConnectMessage.prototype.writeMessage = function (out) { var stream = this.binaryHelper.convertStream(out); stream.writeUTF(this.protocolId); stream.write(this.protocolVersion); var flags = this.cleanSession ? 2 : 0; flags |= this.hasWill ? 4 : 0; flags |= this.willQos ? this.willQos >> 3 : 0; flags |= this.retainWill ? 32 : 0; flags |= this.hasToken ? 64 : 0; flags |= this.hasAppId ? 128 : 0; stream.write(flags); stream.writeChar(this.keepAlive); stream.writeUTF(this.clientId); if (this.hasWill) { stream.writeUTF(this.willTopic); stream.writeUTF(this.will); } if (this.hasAppId) { stream.writeUTF(this.appId); } if (this.hasToken) { stream.writeUTF(this.token); } return stream; }; return ConnectMessage; })(BaseMessage); RongIMLib.ConnectMessage = ConnectMessage; /** *连接应答类型 */ var ConnAckMessage = (function (_super) { __extends(ConnAckMessage, _super); function ConnAckMessage(header) { _super.call(this, arguments.length == 0 ? RongIMLib.Type.CONNACK : arguments.length == 1 ? arguments[0] instanceof RongIMLib.Header ? arguments[0] : RongIMLib.Type.CONNACK : null); this._name = "ConnAckMessage"; this.MESSAGE_LENGTH = 2; this.binaryHelper = new RongIMLib.BinaryHelper(); var me = this; switch (arguments.length) { case 0: case 1: if (!(arguments[0] instanceof RongIMLib.Header)) { if (arguments[0] in RongIMLib.ConnectionState) { if (arguments[0] == null) { throw new Error("ConnAckMessage:The status of ConnAskMessage can't be null"); } me.setStatus(arguments[0]); } } break; } } ; ConnAckMessage.prototype.messageLength = function () { var length = this.MESSAGE_LENGTH; if (this.userId) { length += this.binaryHelper.toMQttString(this.userId).length; } return length; }; ; ConnAckMessage.prototype.readMessage = function (_in, msglength) { _in.read(); var result = +_in.read(); if (result >= 0 && result <= 12) { this.setStatus(result); } else { throw new Error("Unsupported CONNACK code:" + result); } if (msglength > this.MESSAGE_LENGTH) { this.setUserId(_in.readUTF()); var sessionId = _in.readUTF(); var timestamp = _in.readLong(); this.setTimestamp(timestamp); } }; ; ConnAckMessage.prototype.writeMessage = function (out) { var stream = this.binaryHelper.convertStream(out); stream.write(128); switch (+status) { case 0: case 1: case 2: case 5: case 6: stream.write(+status); break; case 3: case 4: stream.write(3); break; default: throw new Error("Unsupported CONNACK code:" + status); } if (this.userId) { stream.writeUTF(this.userId); } return stream; }; ; ConnAckMessage.prototype.setStatus = function (x) { this.status = x; }; ; ConnAckMessage.prototype.setUserId = function (_userId) { this.userId = _userId; }; ; ConnAckMessage.prototype.getStatus = function () { return this.status; }; ; ConnAckMessage.prototype.getUserId = function () { return this.userId; }; ; ConnAckMessage.prototype.setTimestamp = function (x) { this.timestrap = x; }; ; ConnAckMessage.prototype.getTimestamp = function () { return this.timestrap; }; return ConnAckMessage; })(BaseMessage); RongIMLib.ConnAckMessage = ConnAckMessage; /** *断开消息类型 */ var DisconnectMessage = (function (_super) { __extends(DisconnectMessage, _super); function DisconnectMessage(header) { _super.call(this, header instanceof RongIMLib.Header ? header : RongIMLib.Type.DISCONNECT); this._name = "DisconnectMessage"; this.MESSAGE_LENGTH = 2; this.binaryHelper = new RongIMLib.BinaryHelper(); if (!(header instanceof RongIMLib.Header)) { if (header in RongIMLib.ConnectionStatus) { this.status = header; } } } DisconnectMessage.prototype.messageLength = function () { return this.MESSAGE_LENGTH; }; DisconnectMessage.prototype.readMessage = function (_in) { _in.read(); var result = +_in.read(); if (result >= 0 && result <= 5) { this.setStatus(disconnectStatus[result] ? disconnectStatus[result] : result); } else { throw new Error("Unsupported CONNACK code:" + result); } }; DisconnectMessage.prototype.writeMessage = function (Out) { var out = this.binaryHelper.convertStream(Out); out.write(0); if (+status >= 1 && +status <= 3) { out.write((+status) - 1); } else { throw new Error("Unsupported CONNACK code:" + status); } }; DisconnectMessage.prototype.setStatus = function (x) { this.status = x; }; ; DisconnectMessage.prototype.getStatus = function () { return this.status; }; ; return DisconnectMessage; })(BaseMessage); RongIMLib.DisconnectMessage = DisconnectMessage; /** *请求消息信令 */ var PingReqMessage = (function (_super) { __extends(PingReqMessage, _super); function PingReqMessage(header) { _super.call(this, (header && header instanceof RongIMLib.Header) ? header : RongIMLib.Type.PINGREQ); this._name = "PingReqMessage"; } return PingReqMessage; })(BaseMessage); RongIMLib.PingReqMessage = PingReqMessage; /** *响应消息信令 */ var PingRespMessage = (function (_super) { __extends(PingRespMessage, _super); function PingRespMessage(header) { _super.call(this, (header && header instanceof RongIMLib.Header) ? header : RongIMLib.Type.PINGRESP); this._name = "PingRespMessage"; } return PingRespMessage; })(BaseMessage); RongIMLib.PingRespMessage = PingRespMessage; /** *封装MesssageId */ var RetryableMessage = (function (_super) { __extends(RetryableMessage, _super); function RetryableMessage(argu) { _super.call(this, argu); this._name = "RetryableMessage"; this.binaryHelper = new RongIMLib.BinaryHelper(); } RetryableMessage.prototype.messageLength = function () { return 2; }; RetryableMessage.prototype.writeMessage = function (Out) { var out = this.binaryHelper.convertStream(Out), Id = this.getMessageId(), lsb = Id & 255, msb = (Id & 65280) >> 8; out.write(msb); out.write(lsb); return out; }; RetryableMessage.prototype.readMessage = function (_in, msgLength) { var msgId = _in.read() * 256 + _in.read(); this.setMessageId(parseInt(msgId, 10)); }; RetryableMessage.prototype.setMessageId = function (_messageId) { this.messageId = _messageId; }; RetryableMessage.prototype.getMessageId = function () { return this.messageId; }; return RetryableMessage; })(BaseMessage); RongIMLib.RetryableMessage = RetryableMessage; /** *发送消息应答(双向) *qos为1必须给出应答(所有消息类型一样) */ var PubAckMessage = (function (_super) { __extends(PubAckMessage, _super); function PubAckMessage(header) { _super.call(this, (header instanceof RongIMLib.Header) ? header : RongIMLib.Type.PUBACK); this.msgLen = 2; this.date = 0; this.millisecond = 0; this.timestamp = 0; this.binaryHelper = new RongIMLib.BinaryHelper(); this._name = "PubAckMessage"; if (!(header instanceof RongIMLib.Header)) { _super.prototype.setMessageId.call(this, header); } } PubAckMessage.prototype.messageLength = function () { return this.msgLen; }; PubAckMessage.prototype.writeMessage = function (Out) { var out = this.binaryHelper.convertStream(Out); RetryableMessage.prototype.writeMessage.call(this, out); }; PubAckMessage.prototype.readMessage = function (_in, msgLength) { RetryableMessage.prototype.readMessage.call(this, _in); this.date = _in.readInt(); this.status = _in.read() * 256 + _in.read(); this.millisecond = _in.read() * 256 + _in.read(); this.timestamp = this.date * 1000 + this.millisecond; this.messageUId = _in.readUTF(); }; PubAckMessage.prototype.setStatus = function (x) { this.status = x; }; PubAckMessage.prototype.setTimestamp = function (timestamp) { this.timestamp = timestamp; }; PubAckMessage.prototype.setMessageUId = function (messageUId) { this.messageUId = messageUId; }; PubAckMessage.prototype.getStatus = function () { return this.status; }; PubAckMessage.prototype.getDate = function () { return this.date; }; PubAckMessage.prototype.getTimestamp = function () { return this.timestamp; }; PubAckMessage.prototype.getMessageUId = function () { return this.messageUId; }; return PubAckMessage; })(RetryableMessage); RongIMLib.PubAckMessage = PubAckMessage; /** *发布消息 */ var PublishMessage = (function (_super) { __extends(PublishMessage, _super); function PublishMessage(header, two, three) { _super.call(this, (arguments.length == 1 && header instanceof RongIMLib.Header) ? header : arguments.length == 3 ? RongIMLib.Type.PUBLISH : 0); this._name = "PublishMessage"; this.binaryHelper = new RongIMLib.BinaryHelper(); this.syncMsg = false; if (arguments.length == 3) { this.topic = header; this.targetId = three; this.data = typeof two == "string" ? this.binaryHelper.toMQttString(two) : two; } } PublishMessage.prototype.messageLength = function () { var length = 10; length += this.binaryHelper.toMQttString(this.topic).length; length += this.binaryHelper.toMQttString(this.targetId).length; length += this.data.length; return length; }; PublishMessage.prototype.writeMessage = function (Out) { var out = this.binaryHelper.convertStream(Out); out.writeUTF(this.topic); out.writeUTF(this.targetId); RetryableMessage.prototype.writeMessage.apply(this, arguments); out.write(this.data); }; ; PublishMessage.prototype.readMessage = function (_in, msgLength) { var pos = 6; this.date = _in.readInt(); this.topic = _in.readUTF(); pos += this.binaryHelper.toMQttString(this.topic).length; this.targetId = _in.readUTF(); pos += this.binaryHelper.toMQttString(this.targetId).length; RetryableMessage.prototype.readMessage.apply(this, arguments); this.data = new Array(msgLength - pos); this.data = _in.read(this.data); }; ; PublishMessage.prototype.setTopic = function (x) { this.topic = x; }; PublishMessage.prototype.setData = function (x) { this.data = x; }; PublishMessage.prototype.setTargetId = function (x) { this.targetId = x; }; PublishMessage.prototype.setDate = function (x) { this.date = x; }; PublishMessage.prototype.setSyncMsg = function (x) { this.syncMsg = x; }; //是否是其他端同步过来的消息 PublishMessage.prototype.getSyncMsg = function () { return this.syncMsg; }; PublishMessage.prototype.getTopic = function () { return this.topic; }; PublishMessage.prototype.getData = function () { return this.data; }; PublishMessage.prototype.getTargetId = function () { return this.targetId; }; PublishMessage.prototype.getDate = function () { return this.date; }; return PublishMessage; })(RetryableMessage); RongIMLib.PublishMessage = PublishMessage; /** *请求查询 */ var QueryMessage = (function (_super) { __extends(QueryMessage, _super); function QueryMessage(header, two, three) { _super.call(this, header instanceof RongIMLib.Header ? header : arguments.length == 3 ? RongIMLib.Type.QUERY : null); this.binaryHelper = new RongIMLib.BinaryHelper(); this._name = "QueryMessage"; if (arguments.length == 3) { this.data = typeof two == "string" ? this.binaryHelper.toMQttString(two) : two; this.topic = header; this.targetId = three; } } QueryMessage.prototype.messageLength = function () { var length = 0; length += this.binaryHelper.toMQttString(this.topic).length; length += this.binaryHelper.toMQttString(this.targetId).length; length += 2; length += this.data.length; return length; }; QueryMessage.prototype.writeMessage = function (Out) { var out = this.binaryHelper.convertStream(Out); out.writeUTF(this.topic); out.writeUTF(this.targetId); RetryableMessage.prototype.writeMessage.call(this, out); out.write(this.data); }; QueryMessage.prototype.readMessage = function (_in, msgLength) { var pos = 0; this.topic = _in.readUTF(); this.targetId = _in.readUTF(); pos += this.binaryHelper.toMQttString(this.topic).length; pos += this.binaryHelper.toMQttString(this.targetId).length; this.readMessage.apply(this, arguments); pos += 2; this.data = new Array(msgLength - pos); _in.read(this.data); }; QueryMessage.prototype.setTopic = function (x) { this.topic = x; }; QueryMessage.prototype.setData = function (x) { this.data = x; }; QueryMessage.prototype.setTargetId = function (x) { this.targetId = x; }; QueryMessage.prototype.getTopic = function () { return this.topic; }; QueryMessage.prototype.getData = function () { return this.data; }; QueryMessage.prototype.getTargetId = function () { return this.targetId; }; return QueryMessage; })(RetryableMessage); RongIMLib.QueryMessage = QueryMessage; /** *请求查询确认 */ var QueryConMessage = (function (_super) { __extends(QueryConMessage, _super); function QueryConMessage(messageId) { _super.call(this, (messageId instanceof RongIMLib.Header) ? messageId : RongIMLib.Type.QUERYCON); this._name = "QueryConMessage"; if (!(messageId instanceof RongIMLib.Header)) { _super.prototype.setMessageId.call(this, messageId); } } return QueryConMessage; })(RetryableMessage); RongIMLib.QueryConMessage = QueryConMessage; /** *请求查询应答 */ var QueryAckMessage = (function (_super) { __extends(QueryAckMessage, _super); function QueryAckMessage(header) { _super.call(this, header); this._name = "QueryAckMessage"; this.binaryHelper = new RongIMLib.BinaryHelper(); } QueryAckMessage.prototype.readMessage = function (In, msgLength) { RetryableMessage.prototype.readMessage.call(this, In); this.date = In.readInt(); this.setStatus(In.read() * 256 + In.read()); if (msgLength > 0) { this.data = new Array(msgLength - 8); this.data = In.read(this.data); } }; QueryAckMessage.prototype.getData = function () { return this.data; }; QueryAckMessage.prototype.getStatus = function () { return this.status; }; QueryAckMessage.prototype.getDate = function () { return this.date; }; QueryAckMessage.prototype.setDate = function (x) { this.date = x; }; QueryAckMessage.prototype.setStatus = function (x) { this.status = x; }; QueryAckMessage.prototype.setData = function (x) { this.data = x; }; return QueryAckMessage; })(RetryableMessage); RongIMLib.QueryAckMessage = QueryAckMessage; })(RongIMLib || (RongIMLib = {})); /// var RongIMLib; (function (RongIMLib) { /** * 把消息对象写入流中 * 发送消息时用到 */ var MessageOutputStream = (function () { function MessageOutputStream(_out) { var binaryHelper = new RongIMLib.BinaryHelper(); this.out = binaryHelper.convertStream(_out); } MessageOutputStream.prototype.writeMessage = function (msg) { if (msg instanceof RongIMLib.BaseMessage) { msg.write(this.out); } }; return MessageOutputStream; })(); RongIMLib.MessageOutputStream = MessageOutputStream; /** * 流转换为消息对象 * 服务器返回消息时用到 */ var MessageInputStream = (function () { function MessageInputStream(In, isPolling) { if (!isPolling) { var _in = new RongIMLib.BinaryHelper().convertStream(In); this.flags = _in.readByte(); this._in = _in; } else { this.flags = In["headerCode"]; } this.header = new RongIMLib.Header(this.flags); this.isPolling = isPolling; this.In = In; } MessageInputStream.prototype.readMessage = function () { switch (this.header.getType()) { case 1: this.msg = new RongIMLib.ConnectMessage(this.header); break; case 2: this.msg = new RongIMLib.ConnAckMessage(this.header); break; case 3: this.msg = new RongIMLib.PublishMessage(this.header); this.msg.setSyncMsg(this.header.getSyncMsg()); break; case 4: this.msg = new RongIMLib.PubAckMessage(this.header); break; case 5: this.msg = new RongIMLib.QueryMessage(this.header); break; case 6: this.msg = new RongIMLib.QueryAckMessage(this.header); break; case 7: this.msg = new RongIMLib.QueryConMessage(this.header); break; case 9: case 11: case 13: this.msg = new RongIMLib.PingRespMessage(this.header); break; case 8: case 10: case 12: this.msg = new RongIMLib.PingReqMessage(this.header); break; case 14: this.msg = new RongIMLib.DisconnectMessage(this.header); break; default: throw new Error("No support for deserializing " + this.header.getType() + " messages"); } if (this.isPolling) { this.msg.init(this.In); } else { this.msg.read(this._in, this.In.length - 1); } return this.msg; }; return MessageInputStream; })(); RongIMLib.MessageInputStream = MessageInputStream; var Header = (function () { function Header(_type, _retain, _qos, _dup) { this.retain = false; this.qos = RongIMLib.Qos.AT_LEAST_ONCE; this.dup = false; this.syncMsg = false; if (_type && +_type == _type && arguments.length == 1) { this.retain = (_type & 1) > 0; this.qos = (_type & 6) >> 1; this.dup = (_type & 8) > 0; this.type = (_type >> 4) & 15; this.syncMsg = (_type & 8) == 8; } else { this.type = _type; this.retain = _retain; this.qos = _qos; this.dup = _dup; } } Header.prototype.getSyncMsg = function () { return this.syncMsg; }; Header.prototype.getType = function () { return this.type; }; Header.prototype.encode = function () { var me = this; switch (this.qos) { case RongIMLib.Qos[0]: me.qos = RongIMLib.Qos.AT_MOST_ONCE; break; case RongIMLib.Qos[1]: me.qos = RongIMLib.Qos.AT_LEAST_ONCE; break; case RongIMLib.Qos[2]: me.qos = RongIMLib.Qos.EXACTLY_ONCE; break; case RongIMLib.Qos[3]: me.qos = RongIMLib.Qos.DEFAULT; break; } var _byte = (this.type << 4); _byte |= this.retain ? 1 : 0; _byte |= this.qos << 1; _byte |= this.dup ? 8 : 0; return _byte; }; Header.prototype.toString = function () { return "Header [type=" + this.type + ",retain=" + this.retain + ",qos=" + this.qos + ",dup=" + this.dup + "]"; }; return Header; })(); RongIMLib.Header = Header; /** * 二进制帮助对象 */ var BinaryHelper = (function () { function BinaryHelper() { } BinaryHelper.prototype.writeUTF = function (str, isGetBytes) { var back = [], byteSize = 0; for (var i = 0, len = str.length; i < len; i++) { var code = str.charCodeAt(i); if (code >= 0 && code <= 127) { byteSize += 1; back.push(code); } else if (code >= 128 && code <= 2047) { byteSize += 2; back.push((192 | (31 & (code >> 6)))); back.push((128 | (63 & code))); } else if (code >= 2048 && code <= 65535) { byteSize += 3; back.push((224 | (15 & (code >> 12)))); back.push((128 | (63 & (code >> 6)))); back.push((128 | (63 & code))); } } for (var i = 0, len = back.length; i < len; i++) { if (back[i] > 255) { back[i] &= 255; } } if (isGetBytes) { return back; } if (byteSize <= 255) { return [0, byteSize].concat(back); } else { return [byteSize >> 8, byteSize & 255].concat(back); } }; BinaryHelper.prototype.readUTF = function (arr) { if (Object.prototype.toString.call(arr) == "[object String]") { return arr; } var UTF = "", _arr = arr; for (var i = 0, len = _arr.length; i < len; i++) { if (_arr[i] < 0) { _arr[i] += 256; } ; var one = _arr[i].toString(2), v = one.match(/^1+?(?=0)/); if (v && one.length == 8) { var bytesLength = v[0].length, // store = _arr[i].toString(2).slice(7 - bytesLength); store = ''; for (var st = 0; st < bytesLength; st++) { store += _arr[st + i].toString(2).slice(2); } UTF += String.fromCharCode(parseInt(store, 2)); i += bytesLength - 1; } else { UTF += String.fromCharCode(_arr[i]); } } return UTF; }; /** * [convertStream 将参数x转化为RongIMStream对象] * @param {any} x [参数] */ BinaryHelper.prototype.convertStream = function (x) { if (x instanceof RongIMStream) { return x; } else { return new RongIMStream(x); } }; BinaryHelper.prototype.toMQttString = function (str) { return this.writeUTF(str); }; return BinaryHelper; })(); RongIMLib.BinaryHelper = BinaryHelper; var RongIMStream = (function () { function RongIMStream(arr) { //当前流执行的起始位置 this.position = 0; //当前流写入的多少字节 this.writen = 0; this.poolLen = 0; this.binaryHelper = new BinaryHelper(); this.pool = arr; this.poolLen = arr.length; } RongIMStream.prototype.check = function () { return this.position >= this.pool.length; }; RongIMStream.prototype.readInt = function () { if (this.check()) { return -1; } var end = ""; for (var i = 0; i < 4; i++) { var t = this.pool[this.position++].toString(16); if (t.length == 1) { t = "0" + t; } end += t.toString(16); } return parseInt(end, 16); }; RongIMStream.prototype.readLong = function () { if (this.check()) { return -1; } var end = ""; for (var i = 0; i < 8; i++) { var t = this.pool[this.position++].toString(16); if (t.length == 1) { t = "0" + t; } end += t; } return parseInt(end, 16); }; RongIMStream.prototype.readTimestamp = function () { if (this.check()) { return -1; } var end = ""; for (var i = 0; i < 8; i++) { end += this.pool[this.position++].toString(16); } end = end.substring(2, 8); return parseInt(end, 16); }; RongIMStream.prototype.readUTF = function () { if (this.check()) { return -1; } var big = (this.readByte() << 8) | this.readByte(); return this.binaryHelper.readUTF(this.pool.subarray(this.position, this.position += big)); }; RongIMStream.prototype.readByte = function () { if (this.check()) { return -1; } var val = this.pool[this.position++]; if (val > 255) { val &= 255; } return val; }; RongIMStream.prototype.read = function (bytesArray) { if (bytesArray) { return this.pool.subarray(this.position, this.poolLen); } else { return this.readByte(); } }; RongIMStream.prototype.write = function (_byte) { var b = _byte; if (Object.prototype.toString.call(b).toLowerCase() == "[object array]") { [].push.apply(this.pool, b); } else { if (+b == b) { if (b > 255) { b &= 255; } this.pool.push(b); this.writen++; } } return b; }; RongIMStream.prototype.writeChar = function (v) { if (+v != v) { throw new Error("writeChar:arguments type is error"); } this.write(v >> 8 & 255); this.write(v & 255); this.writen += 2; }; RongIMStream.prototype.writeUTF = function (str) { var val = this.binaryHelper.writeUTF(str); [].push.apply(this.pool, val); this.writen += val.length; }; RongIMStream.prototype.toComplements = function () { var _tPool = this.pool; for (var i = 0; i < this.poolLen; i++) { if (_tPool[i] > 128) { _tPool[i] -= 256; } } return _tPool; }; RongIMStream.prototype.getBytesArray = function (isCom) { if (isCom) { return this.toComplements(); } return this.pool; }; return RongIMStream; })(); RongIMLib.RongIMStream = RongIMStream; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var SocketTransportation = (function () { /** * [constructor] * @param {string} url [连接地址:包含token、version] */ function SocketTransportation(_socket) { //连接状态 true:已连接 false:未连接 this.connected = false; //是否关闭: true:已关闭 false:未关闭 this.isClose = false; //存放消息队列的临时变量 this.queue = []; this.empty = new Function; this._socket = _socket; return this; } /** * [createTransport 创建WebScoket对象] */ SocketTransportation.prototype.createTransport = function (url, method) { if (!url) { throw new Error("URL can't be empty"); } ; this.url = url; var depend = RongIMLib.RongIMClient._memoryStore.depend; var wsScheme = depend.wsScheme; var tpl = '{wsScheme}{url}'; url = RongIMLib.RongUtil.tplEngine(tpl, { wsScheme: wsScheme, url: url }); this.socket = new WebSocket(url); this.socket.binaryType = "arraybuffer"; this.addEvent(); return this.socket; }; /** * [send 传送消息流] * @param {ArrayBuffer} data [二进制消息流] */ SocketTransportation.prototype.send = function (data) { if (!this.connected && !this.isClose) { //当通道不可用时,加入消息队列 this.queue.push(data); return; } if (this.isClose) { this._socket.fire("StatusChanged", RongIMLib.ConnectionStatus.CONNECTION_CLOSED); return; } var stream = new RongIMLib.RongIMStream([]), msg = new RongIMLib.MessageOutputStream(stream); msg.writeMessage(data); var val = stream.getBytesArray(true); var binary = new Int8Array(val); this.socket.send(binary.buffer); return this; }; /** * [onData 通道返回数据时调用的方法,用来想上层传递服务器返回的二进制消息流] * @param {ArrayBuffer} data [二进制消息流] */ SocketTransportation.prototype.onData = function (data) { if (RongIMLib.MessageUtil.isArray(data)) { this._socket.onMessage(new RongIMLib.MessageInputStream(data).readMessage()); } else { this._socket.onMessage(new RongIMLib.MessageInputStream(RongIMLib.MessageUtil.ArrayFormInput(data)).readMessage()); } return ""; }; /** * [onClose 通道关闭时触发的方法] */ SocketTransportation.prototype.onClose = function (ev) { var me = this; me.isClose = true; me.socket = this.empty; RongIMLib.Bridge._client.clearHeartbeat(); if (ev.code == 1006 && !this._status) { me._socket.fire("StatusChanged", RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE); } else { me._status = 0; } }; /** * [onError 通道报错时触发的方法] * @param {any} error [抛出异常] */ SocketTransportation.prototype.onError = function (error) { this._socket.fire("StatusChanged", RongIMLib.ConnectionStatus.WEBSOCKET_ERROR); throw new Error(error); }; /** * [addEvent 为通道绑定事件] */ SocketTransportation.prototype.addEvent = function () { var self = this; self.socket.onopen = function () { self.connected = true; self.isClose = false; //通道可以用后,调用发送队列方法,把所有等得发送的消息发出 self.doQueue(); self._socket.fire("connect"); }; self.socket.onmessage = function (ev) { //判断数据是不是字符串,如果是字符串那么就是flash传过来的。 if (typeof ev.data == "string") { self.onData(ev.data.split(",")); } else { self.onData(ev.data); } }; self.socket.onerror = function (ev) { self.onError(ev); }; self.socket.onclose = function (ev) { self.onClose(ev); }; }; /** * [doQueue 消息队列,把队列中消息发出] */ SocketTransportation.prototype.doQueue = function () { var self = this; for (var i = 0, len = self.queue.length; i < len; i++) { self.send(self.queue[i]); } }; /** * [disconnect 断开连接] */ SocketTransportation.prototype.disconnect = function (status) { var me = this; if (me.socket.readyState) { me.isClose = true; if (status) { me._status = status; } me.socket.close(); } }; /** * [reconnect 重新连接] */ SocketTransportation.prototype.reconnect = function () { this.disconnect(); this.createTransport(this.url); }; SocketTransportation.prototype.close = function () { this.socket.close(); }; return SocketTransportation; })(); RongIMLib.SocketTransportation = SocketTransportation; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var PollingTransportation = (function () { function PollingTransportation(socket) { this.empty = new Function; this.connected = false; this.pid = +new Date + Math.random() + ""; this.queue = []; this.socket = socket; return this; } PollingTransportation.prototype.createTransport = function (url, method) { if (!url) { throw new Error("Url is empty,Please check it!"); } ; this.url = url; var sid = RongIMLib.RongIMClient._storageProvider.getItem("sId" + RongIMLib.Navigation.Endpoint.userId), me = this; if (sid) { setTimeout(function () { me.onSuccess("{\"status\":0,\"userId\":\"" + RongIMLib.Navigation.Endpoint.userId + "\",\"headerCode\":32,\"messageId\":0,\"sessionid\":\"" + sid + "\"}"); me.connected = true; }, 500); return this; } this.getRequest(url, true); return this; }; PollingTransportation.prototype.requestFactory = function (url, method, multipart) { var reqest = this.XmlHttpRequest(); if (multipart) { reqest.multipart = true; } // reqest.timeout = 60000; reqest.open(method || "GET", RongIMLib.RongIMClient._memoryStore.depend.protocol + url); if (method == "POST" && "setRequestHeader" in reqest) { reqest.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=utf-8"); } return reqest; }; PollingTransportation.prototype.getRequest = function (url, isconnect) { var me = this; me.xhr = this.requestFactory(url + "&pid=" + encodeURIComponent(me.pid), "GET"); var timer = new RongIMLib.Timer({ timeout: 45000 }); if ("onload" in me.xhr) { me.xhr.onload = function () { timer.pause(); me.xhr.onload = me.empty; if (this.responseText == "lost params") { me.onError(); } else { me.onSuccess(this.responseText, isconnect); } }; me.xhr.onerror = function () { timer.pause(); me.disconnect(); }; } else { me.xhr.onreadystatechange = function () { timer.pause(); if (me.xhr.readyState == 4) { me.xhr.onreadystatechange = me.empty; if (/^(200|202)$/.test(me.xhr.status)) { me.onSuccess(me.xhr.responseText, isconnect); } else if (/^(400|403)$/.test(me.xhr.status)) { me.onError(); } else { me.disconnect(); } } }; } timer.resume(function () { me.onError(); }); me.xhr.send(); }; /** * [send 发送消息,Method:POST] * queue 为消息队列,待通道可用发送所有等待消息 * @param {string} data [需要传入comet格式数据,此处只负责通讯通道,数据转换在外层处理] */ PollingTransportation.prototype.send = function (data) { var me = this; var _send = me.sendxhr = this.requestFactory(RongIMLib.Navigation.Endpoint.host + "/websocket" + data.url + "&pid=" + encodeURIComponent(me.pid), "POST"); if ("onload" in _send) { _send.onload = function () { _send.onload = me.empty; me.onData(_send.responseText); }; _send.onerror = function () { _send.onerror = me.empty; }; } else { _send.onreadystatechange = function () { if (_send.readyState == 4) { this.onreadystatechange = this.empty; if (/^(202|200)$/.test(_send.status)) { me.onData(_send.responseText); } } }; } _send.send(JSON.stringify(data.data)); }; PollingTransportation.prototype.onData = function (data, header) { if (!data || data == "lost params") { return; } var self = this, val = JSON.parse(data); if (val.userId) { RongIMLib.Navigation.Endpoint.userId = val.userId; } if (header) { RongIMLib.RongIMClient._storageProvider.setItem("sId" + RongIMLib.Navigation.Endpoint.userId, header); } if (!RongIMLib.MessageUtil.isArray(val)) { val = [val]; } Array.forEach(val, function (m) { self.socket.fire("message", new RongIMLib.MessageInputStream(m, true).readMessage()); }); return ""; }; PollingTransportation.prototype.XmlHttpRequest = function () { var hasCORS = typeof XMLHttpRequest !== "undefined" && "withCredentials" in new XMLHttpRequest(), self = this; if ("undefined" != typeof XMLHttpRequest && hasCORS) { return new XMLHttpRequest(); } else if ("undefined" != typeof XDomainRequest) { return new XDomainRequest(); } else { return new ActiveXObject("Microsoft.XMLHTTP"); } }; PollingTransportation.prototype.onClose = function () { if (this.xhr) { if (this.xhr.onload) { this.xhr.onreadystatechange = this.xhr.onload = this.empty; } else { this.xhr.onreadystatechange = this.empty; } this.xhr.abort(); this.xhr = null; } if (this.sendxhr) { if (this.sendxhr.onload) { this.sendxhr.onreadystatechange = this.sendxhr.onload = this.empty; } else { this.sendxhr.onreadystatechange = this.empty; } this.sendxhr.abort(); this.sendxhr = null; } }; PollingTransportation.prototype.disconnect = function () { RongIMLib.RongIMClient._storageProvider.removeItem("sId" + RongIMLib.Navigation.Endpoint.userId); RongIMLib.RongIMClient._storageProvider.removeItem(RongIMLib.Navigation.Endpoint.userId + "msgId"); this.onClose(); }; PollingTransportation.prototype.reconnect = function () { this.disconnect(); this.createTransport(this.url); }; PollingTransportation.prototype.onSuccess = function (responseText, isconnect) { var txt = responseText.match(/"sessionid":"\S+?(?=")/); this.onData(responseText, txt ? txt[0].slice(13) : 0); if (/"headerCode":-32,/.test(responseText)) { RongIMLib.RongIMClient._storageProvider.removeItem("sId" + RongIMLib.Navigation.Endpoint.userId); RongIMLib.RongIMClient._storageProvider.removeItem(RongIMLib.Navigation.Endpoint.userId + "msgId"); return; } this.getRequest(RongIMLib.Navigation.Endpoint.host + "/pullmsg.js?sessionid=" + RongIMLib.RongIMClient._storageProvider.getItem("sId" + RongIMLib.Navigation.Endpoint.userId) + "×trap=" + encodeURIComponent(new Date().getTime() + Math.random() + "")); this.connected = true; isconnect && this.socket.fire("connect"); }; PollingTransportation.prototype.onError = function () { RongIMLib.RongIMClient._storageProvider.removeItem("sId" + RongIMLib.Navigation.Endpoint.userId); RongIMLib.RongIMClient._storageProvider.removeItem(RongIMLib.Navigation.Endpoint.userId + "msgId"); this.onClose(); this.connected = false; var code = RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE; this.socket.fire("disconnect", code); }; PollingTransportation.prototype.close = function () { this.xhr.abort(); this.sendxhr = null; }; return PollingTransportation; })(); RongIMLib.PollingTransportation = PollingTransportation; })(RongIMLib || (RongIMLib = {})); //objectname映射 var typeMapping = { "RC:TxtMsg": "TextMessage", "RC:ImgMsg": "ImageMessage", "RC:VcMsg": "VoiceMessage", "RC:ImgTextMsg": "RichContentMessage", "RC:FileMsg": "FileMessage", "RC:HQVCMsg": "HQVoiceMessage", "RC:LBSMsg": "LocationMessage", "RC:InfoNtf": "InformationNotificationMessage", "RC:ContactNtf": "ContactNotificationMessage", "RC:ProfileNtf": "ProfileNotificationMessage", "RC:CmdNtf": "CommandNotificationMessage", "RC:DizNtf": "DiscussionNotificationMessage", "RC:CmdMsg": "CommandMessage", "RC:TypSts": "TypingStatusMessage", "RC:CsChaR": "ChangeModeResponseMessage", "RC:CsHsR": "HandShakeResponseMessage", "RC:CsEnd": "TerminateMessage", "RC:CsSp": "SuspendMessage", "RC:CsUpdate": "CustomerStatusUpdateMessage", "RC:ReadNtf": "ReadReceiptMessage", "RC:VCAccept": "AcceptMessage", "RC:VCRinging": "RingingMessage", "RC:VCSummary": "SummaryMessage", "RC:VCHangup": "HungupMessage", "RC:VCInvite": "InviteMessage", "RC:VCModifyMedia": "MediaModifyMessage", "RC:VCModifyMem": "MemberModifyMessage", "RC:CsContact": "CustomerContact", "RC:PSImgTxtMsg": "PublicServiceRichContentMessage", "RC:PSMultiImgTxtMsg": "PublicServiceMultiRichContentMessage", "RC:GrpNtf": "GroupNotificationMessage", "RC:PSCmd": "PublicServiceCommandMessage", "RC:RcCmd": "RecallCommandMessage", "RC:SRSMsg": "SyncReadStatusMessage", "RC:RRReqMsg": "ReadReceiptRequestMessage", "RC:RRRspMsg": "ReadReceiptResponseMessage", "RCJrmf:RpMsg": "JrmfRedPacketMessage", "RCJrmf:RpOpendMsg": "JrmfRedPacketOpenedMessage", "RC:CombineMsg": "RCCombineMessage" }, //自定义消息类型 registerMessageTypeMapping = {}, HistoryMsgType = { 4: "qryCMsg", 2: "qryDMsg", 3: "qryGMsg", 1: "qryPMsg", 6: "qrySMsg", 7: "qryPMsg", 8: "qryPMsg", 5: "qryCMsg" }, disconnectStatus = { 1: 6 }; var RongIMLib; (function (RongIMLib) { /** * 通道标识类 */ var Transportations = (function () { function Transportations() { } Transportations._TransportType = RongIMLib.Socket.WEBSOCKET; return Transportations; })(); RongIMLib.Transportations = Transportations; var SyncTimeUtil = (function () { function SyncTimeUtil() { } SyncTimeUtil.$getKey = function (message) { var client = RongIMLib.Bridge._client; var userId = client.userId; var direction = (message.messageDirection == 1 ? 'send' : 'receive'); var appkey = RongIMLib.RongIMClient._memoryStore.appKey; var tpl = '{appkey}_{userId}_{direction}box'; return RongIMLib.RongUtil.tplEngine(tpl, { appkey: appkey, userId: userId, direction: direction }); }; SyncTimeUtil.set = function (message) { var key = SyncTimeUtil.$getKey(message); var sentTime = message.sentTime; var storage = RongIMLib.RongIMClient._storageProvider; storage.setItem(key, sentTime); }; SyncTimeUtil.get = function () { var sent = SyncTimeUtil.$getKey({ messageDirection: RongIMLib.MessageDirection.SEND }); var received = SyncTimeUtil.$getKey({ messageDirection: RongIMLib.MessageDirection.RECEIVE }); var storage = RongIMLib.RongIMClient._storageProvider; return { sent: Number(storage.getItem(sent) || 0), received: Number(storage.getItem(received) || 0) }; }; return SyncTimeUtil; })(); RongIMLib.SyncTimeUtil = SyncTimeUtil; var MessageUtil = (function () { function MessageUtil() { } /** *4680000 为localstorage最小容量5200000字节的90%,超过90%将删除之前过早的存储 */ MessageUtil.checkStorageSize = function () { return JSON.stringify(localStorage).length < 4680000; }; MessageUtil.getFirstKey = function (obj) { var str = ""; for (var key in obj) { str = key; break; } return str; }; MessageUtil.isEmpty = function (obj) { var empty = true; for (var key in obj) { empty = false; break; } return empty; }; MessageUtil.ArrayForm = function (typearray) { if (Object.prototype.toString.call(typearray) == "[object ArrayBuffer]") { var arr = new Int8Array(typearray); return [].slice.call(arr); } return typearray; }; MessageUtil.ArrayFormInput = function (typearray) { if (Object.prototype.toString.call(typearray) == "[object ArrayBuffer]") { var arr = new Uint8Array(typearray); return arr; } return typearray; }; MessageUtil.indexOf = function (arr, item, from) { for (var l = arr.length, i = (from < 0) ? Math.max(0, +from) : from || 0; i < l; i++) { if (arr[i] == item) { return i; } } return -1; }; MessageUtil.isArray = function (obj) { return Object.prototype.toString.call(obj) == "[object Array]"; }; //遍历,只能遍历数组 MessageUtil.forEach = function (arr, func) { if ([].forEach) { return function (arr, func) { [].forEach.call(arr, func); }; } else { return function (arr, func) { for (var i = 0; i < arr.length; i++) { func.call(arr, arr[i], i, arr); } }; } }; MessageUtil.remove = function (array, func) { for (var i = 0, len = array.length; i < len; i++) { if (func(array[i])) { return array.splice(i, 1)[0]; } } return null; }; MessageUtil.int64ToTimestamp = function (obj, isDate) { if (obj.low === undefined) { return obj; } var low = obj.low; if (low < 0) { low += 0xffffffff + 1; } low = low.toString(16); var timestamp = parseInt(obj.high.toString(16) + "00000000".replace(new RegExp("0{" + low.length + "}$"), low), 16); if (isDate) { return new Date(timestamp); } return timestamp; }; //消息转换方法 MessageUtil.messageParser = function (entity, onReceived, offlineMsg) { var message = new RongIMLib.Message(), content = entity.content, de, objectName = entity.classname, val, isUseDef = false; try { if (RongIMLib.RongIMClient._memoryStore.depend.isPolling) { val = new RongIMLib.BinaryHelper().readUTF(content.offset ? MessageUtil.ArrayForm(content.buffer).slice(content.offset, content.limit) : content); de = JSON.parse(val); } else { val = new RongIMLib.BinaryHelper().readUTF(content.offset ? MessageUtil.ArrayFormInput(content.buffer).subarray(content.offset, content.limit) : content); de = JSON.parse(val); } } catch (ex) { de = val; isUseDef = true; } //映射为具体消息对象 if (objectName in typeMapping) { var str = "new RongIMLib." + typeMapping[objectName] + "(de)"; message.content = eval(str); message.messageType = typeMapping[objectName]; } else if (objectName in registerMessageTypeMapping) { var str = "new RongIMLib.RongIMClient.RegisterMessage." + registerMessageTypeMapping[objectName] + "(de)"; if (isUseDef) { message.content = eval(str).decode(de); } else { message.content = eval(str); } message.messageType = registerMessageTypeMapping[objectName]; } else { message.content = new RongIMLib.UnknownMessage({ content: de, objectName: objectName }); message.messageType = "UnknownMessage"; } //根据实体对象设置message对象] var dateTime = MessageUtil.int64ToTimestamp(entity.dataTime); if (dateTime > 0) { message.sentTime = dateTime; } else { message.sentTime = +new Date; } message.senderUserId = entity.fromUserId; message.conversationType = entity.type; if (entity.fromUserId == RongIMLib.Bridge._client.userId) { message.targetId = entity.groupId; } else { message.targetId = (/^[234]$/.test(entity.type || entity.getType()) ? entity.groupId : message.senderUserId); } var selfUserId = RongIMLib.Bridge._client.userId; // 解决多端在线收自己发的消息时, messageDirection 为 2(接收), 导致未读数增加 var isSelfSend = entity.direction == 1 || message.senderUserId === selfUserId; if (isSelfSend) { message.messageDirection = RongIMLib.MessageDirection.SEND; message.senderUserId = RongIMLib.Bridge._client.userId; } else { message.messageDirection = RongIMLib.MessageDirection.RECEIVE; } // 自己给自己发的消息, messageDirection 为 2(接收) var isSelfToSelf = message.senderUserId === selfUserId && message.targetId === selfUserId; if (isSelfToSelf) { message.messageDirection = RongIMLib.MessageDirection.RECEIVE; } message.messageUId = entity.msgId; message.receivedTime = new Date().getTime(); message.messageId = (message.conversationType + "_" + ~~(Math.random() * 0xffffff)); message.objectName = objectName; message.receivedStatus = RongIMLib.ReceivedStatus.READ; if ((entity.status & 2) == 2) { message.receivedStatus = RongIMLib.ReceivedStatus.RETRIEVED; } message.offLineMessage = offlineMsg ? true : false; if (!offlineMsg) { if (RongIMLib.RongIMClient._memoryStore.connectAckTime > message.sentTime) { message.offLineMessage = true; } } return message; }; MessageUtil.detectCMP = function (options) { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function () { if (xhr.readyState == 4) { var status = xhr.status; if (status == 200) { options.success(); } else { options.fail(xhr.status); } } }; var method = options.url; var url = options.url; var method = options.method || 'GET'; xhr.open(method, url); var headers = options.headers; for (var key in headers) { var value = headers[key]; xhr.setRequestHeader(key, value); } var body = JSON.stringify(options.body || {}); xhr.send(body); return xhr; }; //适配SSL // static schemeArrs: Array = [["http", "ws"], ["https", "wss"]]; MessageUtil.sign = { converNum: 1, msgNum: 1, isMsgStart: true, isConvStart: true }; return MessageUtil; })(); RongIMLib.MessageUtil = MessageUtil; /** * 工具类 */ var MessageIdHandler = (function () { function MessageIdHandler() { } MessageIdHandler.init = function () { this.messageId = +(RongIMLib.RongIMClient._storageProvider.getItem(RongIMLib.Navigation.Endpoint.userId + "msgId") || RongIMLib.RongIMClient._storageProvider.setItem(RongIMLib.Navigation.Endpoint.userId + "msgId", 0) || 0); }; MessageIdHandler.messageIdPlus = function (method) { RongIMLib.RongIMClient._memoryStore.depend.isPolling && this.init(); if (this.messageId >= 65535) { method(); return false; } this.messageId++; RongIMLib.RongIMClient._memoryStore.depend.isPolling && RongIMLib.RongIMClient._storageProvider.setItem(RongIMLib.Navigation.Endpoint.userId + "msgId", this.messageId); return this.messageId; }; MessageIdHandler.clearMessageId = function () { this.messageId = 0; RongIMLib.RongIMClient._memoryStore.depend.isPolling && RongIMLib.RongIMClient._storageProvider.setItem(RongIMLib.Navigation.Endpoint.userId + "msgId", this.messageId); }; MessageIdHandler.getMessageId = function () { RongIMLib.RongIMClient._memoryStore.depend.isPolling && this.init(); return this.messageId; }; MessageIdHandler.messageId = 0; return MessageIdHandler; })(); RongIMLib.MessageIdHandler = MessageIdHandler; var RongInnerTools = (function () { function RongInnerTools() { } RongInnerTools.convertUserStatus = function (entity) { entity = RongIMLib.RongUtil.rename(entity, { subUserId: 'userId' }); var status = JSON.parse(entity.status); var us = status.us; if (!us) { return entity; } entity.status = RongIMLib.RongUtil.rename(us, { o: 'online', 'p': 'platform', s: 'status' }); return entity; }; return RongInnerTools; })(); RongIMLib.RongInnerTools = RongInnerTools; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var MessageContent = (function () { function MessageContent(data) { throw new Error("This method is abstract, you must implement this method in inherited class."); } MessageContent.obtain = function () { throw new Error("This method is abstract, you must implement this method in inherited class."); }; return MessageContent; })(); RongIMLib.MessageContent = MessageContent; var NotificationMessage = (function (_super) { __extends(NotificationMessage, _super); function NotificationMessage() { _super.apply(this, arguments); } return NotificationMessage; })(MessageContent); RongIMLib.NotificationMessage = NotificationMessage; var StatusMessage = (function (_super) { __extends(StatusMessage, _super); function StatusMessage() { _super.apply(this, arguments); } return StatusMessage; })(MessageContent); RongIMLib.StatusMessage = StatusMessage; var ModelUtil = (function () { function ModelUtil() { } ModelUtil.modelClone = function (object) { var obj = {}; for (var item in object) { if (item != "messageName" && "encode" != item) { obj[item] = object[item]; } } return obj; }; ModelUtil.modleCreate = function (fields, msgType) { // if (fields.length < 1) { // throw new Error("Array is empty -> registerMessageType.modleCreate"); // } var Object = function (message) { var me = this; for (var index in fields) { me[fields[index]] = message[fields[index]]; } Object.prototype.messageName = msgType; Object.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; }; return Object; }; return ModelUtil; })(); RongIMLib.ModelUtil = ModelUtil; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var CustomerStatusMessage = (function () { function CustomerStatusMessage(message) { this.messageName = "CustomerStatusMessage"; this.status = message.status; } CustomerStatusMessage.obtain = function () { return null; }; CustomerStatusMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return CustomerStatusMessage; })(); RongIMLib.CustomerStatusMessage = CustomerStatusMessage; /** * 客服转换响应消息的类型名 */ var ChangeModeResponseMessage = (function () { function ChangeModeResponseMessage(message) { this.messageName = "ChangeModeResponseMessage"; this.code = message.code; this.data = message.data; this.msg = message.msg; } ChangeModeResponseMessage.obtain = function () { return null; }; ChangeModeResponseMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ChangeModeResponseMessage; })(); RongIMLib.ChangeModeResponseMessage = ChangeModeResponseMessage; /** * 客服转换消息的类型名 * 此消息不计入未读消息数 */ var ChangeModeMessage = (function () { function ChangeModeMessage(message) { this.messageName = "ChangeModeMessage"; this.uid = message.uid; this.sid = message.sid; this.pid = message.pid; } ChangeModeMessage.obtain = function () { return null; }; ChangeModeMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ChangeModeMessage; })(); RongIMLib.ChangeModeMessage = ChangeModeMessage; var CustomerStatusUpdateMessage = (function () { function CustomerStatusUpdateMessage(message) { this.messageName = "CustomerStatusUpdateMessage"; this.serviceStatus = message.serviceStatus; this.sid = message.sid; } CustomerStatusUpdateMessage.obtain = function () { return null; }; CustomerStatusUpdateMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return CustomerStatusUpdateMessage; })(); RongIMLib.CustomerStatusUpdateMessage = CustomerStatusUpdateMessage; var HandShakeMessage = (function () { function HandShakeMessage(message) { this.messageName = "HandShakeMessage"; if (message) { this.requestInfo = message.requestInfo; this.userInfo = message.userInfo; } } HandShakeMessage.obtain = function () { return null; }; HandShakeMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return HandShakeMessage; })(); RongIMLib.HandShakeMessage = HandShakeMessage; var CustomerContact = (function () { function CustomerContact(message) { this.messageName = "CustomerContact"; this.page = message.page; this.nickName = message.nickName; this.routingInfo = message.routingInfo; this.info = message.info; this.requestInfo = message.requestInfo; } CustomerContact.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return CustomerContact; })(); RongIMLib.CustomerContact = CustomerContact; var EvaluateMessage = (function () { function EvaluateMessage(message) { this.messageName = "EvaluateMessage"; this.uid = message.uid; this.sid = message.sid; this.pid = message.pid; this.source = message.source; this.suggest = message.suggest; this.isresolve = message.isresolve; this.type = message.type; } EvaluateMessage.obtain = function () { return null; }; EvaluateMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return EvaluateMessage; })(); RongIMLib.EvaluateMessage = EvaluateMessage; /** * 客服握手响应消息的类型名 */ var HandShakeResponseMessage = (function () { function HandShakeResponseMessage(message) { this.messageName = "HandShakeResponseMessage"; this.msg = message.msg; this.status = message.status; this.data = message.data; } HandShakeResponseMessage.obtain = function () { return null; }; HandShakeResponseMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return HandShakeResponseMessage; })(); RongIMLib.HandShakeResponseMessage = HandShakeResponseMessage; var SuspendMessage = (function () { function SuspendMessage(message) { this.messageName = "SuspendMessage"; this.uid = message.uid; this.sid = message.sid; this.pid = message.pid; } SuspendMessage.obtain = function () { return null; }; SuspendMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return SuspendMessage; })(); RongIMLib.SuspendMessage = SuspendMessage; var TerminateMessage = (function () { function TerminateMessage(message) { this.messageName = "TerminateMessage"; this.code = message.code; this.msg = message.msg; this.sid = message.sid; } TerminateMessage.obtain = function () { return null; }; TerminateMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return TerminateMessage; })(); RongIMLib.TerminateMessage = TerminateMessage; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var IsTypingStatusMessage = (function () { function IsTypingStatusMessage(data) { this.messageName = "IsTypingStatusMessage"; var msg = data; } IsTypingStatusMessage.prototype.encode = function () { return undefined; }; IsTypingStatusMessage.prototype.getMessage = function () { return null; }; return IsTypingStatusMessage; })(); RongIMLib.IsTypingStatusMessage = IsTypingStatusMessage; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var InformationNotificationMessage = (function () { function InformationNotificationMessage(message) { this.messageName = "InformationNotificationMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> InformationNotificationMessage."); } this.message = message.message; this.extra = message.extra; if (message.user) { this.user = message.user; } } InformationNotificationMessage.obtain = function (message) { return new InformationNotificationMessage({ message: message, extra: "" }); }; InformationNotificationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return InformationNotificationMessage; })(); RongIMLib.InformationNotificationMessage = InformationNotificationMessage; var CommandMessage = (function () { function CommandMessage(message) { this.messageName = "CommandMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> CommandMessage."); } try { if (Object.prototype.toString.call(message.data) == "[object String]") { this.data = JSON.parse(message.data); } else { this.data = message.data; } } catch (e) { this.data = message.data; } this.name = message.name; this.extra = message.extra; } CommandMessage.obtain = function (data) { return new CommandMessage({ data: data, extra: "" }); }; CommandMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return CommandMessage; })(); RongIMLib.CommandMessage = CommandMessage; var ContactNotificationMessage = (function () { function ContactNotificationMessage(message) { this.messageName = "ContactNotificationMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> ContactNotificationMessage."); } this.operation = message.operation; this.targetUserId = message.targetUserId; this.message = message.message; this.extra = message.extra; this.sourceUserId = message.sourceUserId; if (message.user) { this.user = message.user; } } ContactNotificationMessage.obtain = function (operation, sourceUserId, targetUserId, message) { return new InformationNotificationMessage({ operation: operation, sourceUserId: sourceUserId, targetUserId: targetUserId, message: message }); }; ContactNotificationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; ContactNotificationMessage.CONTACT_OPERATION_ACCEPT_RESPONSE = "ContactOperationAcceptResponse"; ContactNotificationMessage.CONTACT_OPERATION_REJECT_RESPONSE = "ContactOperationRejectResponse"; ContactNotificationMessage.CONTACT_OPERATION_REQUEST = "ContactOperationRequest"; return ContactNotificationMessage; })(); RongIMLib.ContactNotificationMessage = ContactNotificationMessage; var ProfileNotificationMessage = (function () { function ProfileNotificationMessage(message) { this.messageName = "ProfileNotificationMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> ProfileNotificationMessage."); } this.operation = message.operation; try { if (Object.prototype.toString.call(message.data) == "[object String]") { this.data = JSON.parse(message.data); } else { this.data = message.data; } } catch (e) { this.data = message.data; } this.extra = message.extra; if (message.user) { this.user = message.user; } } ProfileNotificationMessage.obtain = function (operation, data) { return new ProfileNotificationMessage({ operation: operation, data: data }); }; ProfileNotificationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ProfileNotificationMessage; })(); RongIMLib.ProfileNotificationMessage = ProfileNotificationMessage; var CommandNotificationMessage = (function () { function CommandNotificationMessage(message) { this.messageName = "CommandNotificationMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> ProfileNotificationMessage."); } try { if (Object.prototype.toString.call(message.data) == "[object String]") { this.data = JSON.parse(message.data); } else { this.data = message.data; } } catch (e) { this.data = message.data; } this.name = message.name; this.extra = message.extra; if (message.user) { this.user = message.user; } } CommandNotificationMessage.obtain = function (name, data) { return new CommandNotificationMessage({ name: name, data: data, extra: "" }); }; CommandNotificationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return CommandNotificationMessage; })(); RongIMLib.CommandNotificationMessage = CommandNotificationMessage; var DiscussionNotificationMessage = (function () { function DiscussionNotificationMessage(message) { this.messageName = "DiscussionNotificationMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> DiscussionNotificationMessage."); } this.extra = message.extra; this.extension = message.extension; this.type = message.type; this.isHasReceived = message.isHasReceived; this.operation = message.operation; this.user = message.user; if (message.user) { this.user = message.user; } } DiscussionNotificationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return DiscussionNotificationMessage; })(); RongIMLib.DiscussionNotificationMessage = DiscussionNotificationMessage; var GroupNotificationMessage = (function () { function GroupNotificationMessage(msg) { this.messageName = "GroupNotificationMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> GroupNotificationMessage."); } msg.operatorUserId && (this.operatorUserId = msg.operatorUserId); msg.operation && (this.operation = msg.operation); msg.data && (this.data = msg.data); msg.message && (this.message = msg.message); msg.extra && (this.extra = msg.extra); } GroupNotificationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return GroupNotificationMessage; })(); RongIMLib.GroupNotificationMessage = GroupNotificationMessage; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var TextMessage = (function () { function TextMessage(message) { this.messageName = "TextMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> TextMessage."); } this.content = message.content; this.extra = message.extra; if (message.user) { this.user = message.user; } if (message.mentionedInfo) { this.mentionedInfo = message.mentionedInfo; } } TextMessage.obtain = function (text) { return new TextMessage({ extra: "", content: text }); }; TextMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return TextMessage; })(); RongIMLib.TextMessage = TextMessage; var TypingStatusMessage = (function () { function TypingStatusMessage(message) { this.messageName = "TypingStatusMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> TypingStatusMessage."); } this.typingContentType = message.typingContentType; this.data = message.data; } TypingStatusMessage.obtain = function (typingContentType, data) { return new TypingStatusMessage({ typingContentType: typingContentType, data: data }); }; TypingStatusMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return TypingStatusMessage; })(); RongIMLib.TypingStatusMessage = TypingStatusMessage; var ReadReceiptMessage = (function () { function ReadReceiptMessage(message) { this.messageName = "ReadReceiptMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> ReadReceiptMessage."); } this.lastMessageSendTime = message.lastMessageSendTime; this.messageUId = message.messageUId; this.type = message.type; } ReadReceiptMessage.obtain = function (messageUId, lastMessageSendTime, type) { return new ReadReceiptMessage({ messageUId: messageUId, lastMessageSendTime: lastMessageSendTime, type: type }); }; ReadReceiptMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ReadReceiptMessage; })(); RongIMLib.ReadReceiptMessage = ReadReceiptMessage; var VoiceMessage = (function () { function VoiceMessage(message) { this.messageName = "VoiceMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> VoiceMessage."); } this.content = message.content; this.duration = message.duration; this.extra = message.extra; if (message.user) { this.user = message.user; } if (message.mentionedInfo) { this.mentionedInfo = message.mentionedInfo; } } VoiceMessage.obtain = function (base64Content, duration) { return new VoiceMessage({ content: base64Content, duration: duration, extra: "" }); }; VoiceMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return VoiceMessage; })(); RongIMLib.VoiceMessage = VoiceMessage; var RecallCommandMessage = (function () { function RecallCommandMessage(message) { this.messageName = "RecallCommandMessage"; this.messageUId = message.messageUId; this.conversationType = message.conversationType; this.targetId = message.targetId; this.sentTime = message.sentTime; message.extra && (this.extra = message.extra); message.user && (this.user = message.user); } RecallCommandMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return RecallCommandMessage; })(); RongIMLib.RecallCommandMessage = RecallCommandMessage; var ImageMessage = (function () { function ImageMessage(message) { this.messageName = "ImageMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> ImageMessage."); } this.content = message.content; this.imageUri = message.imageUri; message.extra && (this.extra = message.extra); message.user && (this.user = message.user); if (message.mentionedInfo) { this.mentionedInfo = message.mentionedInfo; } } ImageMessage.obtain = function (content, imageUri) { return new ImageMessage({ content: content, imageUri: imageUri, extra: "" }); }; ImageMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ImageMessage; })(); RongIMLib.ImageMessage = ImageMessage; var LocationMessage = (function () { function LocationMessage(message) { this.messageName = "LocationMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> LocationMessage."); } this.latitude = message.latitude; this.longitude = message.longitude; this.poi = message.poi; this.content = message.content; this.extra = message.extra; if (message.user) { this.user = message.user; } if (message.mentionedInfo) { this.mentionedInfo = message.mentionedInfo; } } LocationMessage.obtain = function (latitude, longitude, poi, content) { return new LocationMessage({ latitude: latitude, longitude: longitude, poi: poi, content: content, extra: "" }); }; LocationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return LocationMessage; })(); RongIMLib.LocationMessage = LocationMessage; var RichContentMessage = (function () { function RichContentMessage(message) { this.messageName = "RichContentMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> RichContentMessage."); } this.title = message.title; this.content = message.content; this.imageUri = message.imageUri; this.extra = message.extra; this.url = message.url; if (message.user) { this.user = message.user; } } RichContentMessage.obtain = function (title, content, imageUri, url) { return new RichContentMessage({ title: title, content: content, imageUri: imageUri, url: url, extra: "" }); }; RichContentMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return RichContentMessage; })(); RongIMLib.RichContentMessage = RichContentMessage; var JrmfRedPacketMessage = (function () { function JrmfRedPacketMessage(message) { this.messageName = 'JrmfRedPacketMessage'; message && (this.message = message); } JrmfRedPacketMessage.prototype.encode = function () { return ""; }; return JrmfRedPacketMessage; })(); RongIMLib.JrmfRedPacketMessage = JrmfRedPacketMessage; var JrmfRedPacketOpenedMessage = (function () { function JrmfRedPacketOpenedMessage(message) { this.messageName = 'JrmfRedPacketOpenedMessage'; message && (this.message = message); } JrmfRedPacketOpenedMessage.prototype.encode = function () { return ""; }; return JrmfRedPacketOpenedMessage; })(); RongIMLib.JrmfRedPacketOpenedMessage = JrmfRedPacketOpenedMessage; var UnknownMessage = (function () { function UnknownMessage(message) { this.messageName = "UnknownMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> UnknownMessage."); } this.message = message; } UnknownMessage.prototype.encode = function () { return ""; }; return UnknownMessage; })(); RongIMLib.UnknownMessage = UnknownMessage; var PublicServiceCommandMessage = (function () { function PublicServiceCommandMessage(message) { this.messageName = "PublicServiceCommandMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> PublicServiceCommandMessage."); } this.content = message.content; this.extra = message.extra; this.menuItem = message.menuItem; if (message.user) { this.user = message.user; } if (message.mentionedInfo) { this.mentionedInfo = message.mentionedInfo; } } PublicServiceCommandMessage.obtain = function (item) { return new PublicServiceCommandMessage({ content: "", command: "", menuItem: item, extra: "" }); }; PublicServiceCommandMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return PublicServiceCommandMessage; })(); RongIMLib.PublicServiceCommandMessage = PublicServiceCommandMessage; var PublicServiceMultiRichContentMessage = (function () { function PublicServiceMultiRichContentMessage(messages) { this.messageName = "PublicServiceMultiRichContentMessage"; this.richContentMessages = messages; } PublicServiceMultiRichContentMessage.prototype.encode = function () { return null; }; return PublicServiceMultiRichContentMessage; })(); RongIMLib.PublicServiceMultiRichContentMessage = PublicServiceMultiRichContentMessage; var SyncReadStatusMessage = (function () { function SyncReadStatusMessage(message) { this.messageName = "SyncReadStatusMessage"; message.lastMessageSendTime && (this.lastMessageSendTime = message.lastMessageSendTime); } SyncReadStatusMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return SyncReadStatusMessage; })(); RongIMLib.SyncReadStatusMessage = SyncReadStatusMessage; var ReadReceiptRequestMessage = (function () { function ReadReceiptRequestMessage(message) { this.messageName = "ReadReceiptRequestMessage"; message.messageUId && (this.messageUId = message.messageUId); } ReadReceiptRequestMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ReadReceiptRequestMessage; })(); RongIMLib.ReadReceiptRequestMessage = ReadReceiptRequestMessage; var ReadReceiptResponseMessage = (function () { function ReadReceiptResponseMessage(message) { this.messageName = "ReadReceiptResponseMessage"; message.receiptMessageDic && (this.receiptMessageDic = message.receiptMessageDic); } ReadReceiptResponseMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ReadReceiptResponseMessage; })(); RongIMLib.ReadReceiptResponseMessage = ReadReceiptResponseMessage; var PublicServiceRichContentMessage = (function () { function PublicServiceRichContentMessage(message) { this.messageName = "PublicServiceRichContentMessage"; this.richContentMessage = message; } PublicServiceRichContentMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return PublicServiceRichContentMessage; })(); RongIMLib.PublicServiceRichContentMessage = PublicServiceRichContentMessage; var FileMessage = (function () { function FileMessage(message) { this.messageName = "FileMessage"; message.name && (this.name = message.name); message.size && (this.size = message.size); message.type && (this.type = message.type); message.fileUrl && (this.fileUrl = message.fileUrl); message.extra && (this.extra = message.extra); message.user && (this.user = message.user); } FileMessage.obtain = function (msg) { return new FileMessage({ name: msg.name, size: msg.size, type: msg.type, fileUrl: msg.fileUrl }); }; FileMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return FileMessage; })(); RongIMLib.FileMessage = FileMessage; var HQVoiceMessage = (function () { function HQVoiceMessage(message) { this.messageName = "HQVoiceMessage"; this.type = message.type || 'aac'; message.localPath && (this.localPath = message.localPath); message.remoteUrl && (this.remoteUrl = message.remoteUrl); message.duration && (this.duration = message.duration); message.extra && (this.extra = message.extra); message.user && (this.user = message.user); } HQVoiceMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return HQVoiceMessage; })(); RongIMLib.HQVoiceMessage = HQVoiceMessage; var AcceptMessage = (function () { function AcceptMessage(message) { this.messageName = "AcceptMessage"; this.mediaId = message.mediaId; this.callId = message.callId; this.mediaType = message.mediaType; this.mode = message.mode; this.subInfo = message.subInfo; } AcceptMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return AcceptMessage; })(); RongIMLib.AcceptMessage = AcceptMessage; var RingingMessage = (function () { function RingingMessage(message) { this.messageName = "RingingMessage"; this.callId = message.callId; } RingingMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return RingingMessage; })(); RongIMLib.RingingMessage = RingingMessage; var SummaryMessage = (function () { function SummaryMessage(message) { this.messageName = "SummaryMessage"; this.caller = message.caller; this.inviter = message.inviter; this.mediaType = message.mediaType; this.memberIdList = message.memberIdList; this.startTime = message.startTime; this.connectedTime = message.connectedTime; this.duration = message.duration; this.status = message.status; } SummaryMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return SummaryMessage; })(); RongIMLib.SummaryMessage = SummaryMessage; var HungupMessage = (function () { function HungupMessage(message) { this.messageName = "HungupMessage"; this.callId = message.callId; this.reason = message.reason; this.mode = message.mode; this.subInfo = message.subInfo; } HungupMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return HungupMessage; })(); RongIMLib.HungupMessage = HungupMessage; var InviteMessage = (function () { function InviteMessage(message) { this.messageName = "InviteMessage"; this.mediaId = message.mediaId; this.callId = message.callId; this.engineType = message.engineType; this.channelInfo = message.channelInfo; this.mediaType = message.mediaType; this.extra = message.extra; this.inviteUserIds = message.inviteUserIds; this.observerUserIds = message.observerUserIds; this.mode = message.mode; this.subInfo = message.subInfo; } InviteMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return InviteMessage; })(); RongIMLib.InviteMessage = InviteMessage; var MediaModifyMessage = (function () { function MediaModifyMessage(message) { this.messageName = "MediaModifyMessage"; this.callId = message.callId; this.mediaType = message.mediaType; this.mode = message.mode; this.subInfo = message.subInfo; } MediaModifyMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return MediaModifyMessage; })(); RongIMLib.MediaModifyMessage = MediaModifyMessage; var MemberModifyMessage = (function () { function MemberModifyMessage(message) { this.messageName = "MemberModifyMessage"; this.modifyMemType = message.modifyMemType; this.callId = message.callId; this.caller = message.caller; this.engineType = message.engineType; this.channelInfo = message.channelInfo; this.mediaType = message.mediaType; this.extra = message.extra; this.inviteUserIds = message.inviteUserIds; this.existedMemberStatusList = message.existedMemberStatusList; this.existedUserPofiles = message.existedUserPofiles; this.observerUserIds = message.observerUserIds; this.mode = message.mode; this.subInfo = message.subInfo; } MemberModifyMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return MemberModifyMessage; })(); RongIMLib.MemberModifyMessage = MemberModifyMessage; var RCCombineMessage = (function () { function RCCombineMessage(message) { this.messageName = "RCCombineMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> RCCombineMessage."); } this.nameList = message.nameList; this.remoteUrl = message.remoteUrl; if (message.user) { this.user = message.user; } this.summaryList = message.summaryList; } RCCombineMessage.obtain = function (remoteUrl, nameList, summaryList) { return new RCCombineMessage({ extra: "", content: remoteUrl, nameList: nameList, summaryList: summaryList }); }; RCCombineMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return RCCombineMessage; })(); RongIMLib.RCCombineMessage = RCCombineMessage; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var ChannelInfo = (function () { function ChannelInfo(Id, Key) { this.Id = Id; this.Key = Key; } return ChannelInfo; })(); RongIMLib.ChannelInfo = ChannelInfo; var UserStatus = (function () { function UserStatus(platform, online, status) { this.platform = platform; this.online = online; this.status = status; } return UserStatus; })(); RongIMLib.UserStatus = UserStatus; var MentionedInfo = (function () { function MentionedInfo(type, userIdList, mentionedContent) { } return MentionedInfo; })(); RongIMLib.MentionedInfo = MentionedInfo; var DeleteMessage = (function () { function DeleteMessage(msgId, msgDataTime, direct) { this.msgId = msgId; this.msgDataTime = msgDataTime; this.direct = direct; } return DeleteMessage; })(); RongIMLib.DeleteMessage = DeleteMessage; var CustomServiceConfig = (function () { function CustomServiceConfig(isBlack, companyName, companyUrl) { } return CustomServiceConfig; })(); RongIMLib.CustomServiceConfig = CustomServiceConfig; var CustomServiceSession = (function () { function CustomServiceSession(uid, cid, pid, isQuited, type, adminHelloWord, adminOfflineWord) { } return CustomServiceSession; })(); RongIMLib.CustomServiceSession = CustomServiceSession; var Conversation = (function () { function Conversation(conversationTitle, conversationType, draft, isTop, latestMessage, latestMessageId, notificationStatus, objectName, receivedStatus, receivedTime, senderUserId, senderUserName, sentStatus, sentTime, targetId, unreadMessageCount, senderPortraitUri, isHidden, mentionedMsg, hasUnreadMention, _readTime) { this.conversationTitle = conversationTitle; this.conversationType = conversationType; this.draft = draft; this.isTop = isTop; this.latestMessage = latestMessage; this.latestMessageId = latestMessageId; this.notificationStatus = notificationStatus; this.objectName = objectName; this.receivedStatus = receivedStatus; this.receivedTime = receivedTime; this.senderUserId = senderUserId; this.senderUserName = senderUserName; this.sentStatus = sentStatus; this.sentTime = sentTime; this.targetId = targetId; this.unreadMessageCount = unreadMessageCount; this.senderPortraitUri = senderPortraitUri; this.isHidden = isHidden; this.mentionedMsg = mentionedMsg; this.hasUnreadMention = hasUnreadMention; this._readTime = _readTime; } Conversation.prototype.setTop = function () { RongIMLib.RongIMClient._dataAccessProvider.addConversation(this, { onSuccess: function (data) { } }); }; return Conversation; })(); RongIMLib.Conversation = Conversation; var Discussion = (function () { function Discussion(creatorId, id, memberIdList, name, isOpen) { this.creatorId = creatorId; this.id = id; this.memberIdList = memberIdList; this.name = name; this.isOpen = isOpen; } return Discussion; })(); RongIMLib.Discussion = Discussion; var Group = (function () { function Group(id, name, portraitUri) { this.id = id; this.name = name; this.portraitUri = portraitUri; } return Group; })(); RongIMLib.Group = Group; var Message = (function () { function Message(content, conversationType, extra, objectName, messageDirection, messageId, receivedStatus, receivedTime, senderUserId, sentStatus, sentTime, targetId, messageType, messageUId, isLocalMessage, offLineMessage, receiptResponse) { this.content = content; this.conversationType = conversationType; this.extra = extra; this.objectName = objectName; this.messageDirection = messageDirection; this.messageId = messageId; this.receivedStatus = receivedStatus; this.receivedTime = receivedTime; this.senderUserId = senderUserId; this.sentStatus = sentStatus; this.sentTime = sentTime; this.targetId = targetId; this.messageType = messageType; this.messageUId = messageUId; this.isLocalMessage = isLocalMessage; this.offLineMessage = offLineMessage; this.receiptResponse = receiptResponse; } return Message; })(); RongIMLib.Message = Message; var MessageTag = (function () { function MessageTag(isCounted, isPersited) { this.isCounted = isCounted; this.isPersited = isPersited; } MessageTag.prototype.getMessageTag = function () { if (this.isCounted && this.isPersited) { return 3; } else if (this.isCounted) { return 2; } else if (this.isPersited) { return 1; } else if (!this.isCounted && !this.isPersited) { return 0; } }; MessageTag.getTagByStatus = function (status) { var statusMap = { 3: { isCounted: true, isPersited: true }, 2: { isCounted: true, isPersited: false }, 1: { isCounted: true, isPersited: true }, 0: { isCounted: true, isPersited: true } }; return statusMap[status] || statusMap[3]; }; return MessageTag; })(); RongIMLib.MessageTag = MessageTag; var PublicServiceMenuItem = (function () { function PublicServiceMenuItem(id, name, type, sunMenuItems, url) { this.id = id; this.name = name; this.type = type; this.sunMenuItems = sunMenuItems; this.url = url; } return PublicServiceMenuItem; })(); RongIMLib.PublicServiceMenuItem = PublicServiceMenuItem; // TODO: TBD var PublicServiceProfile = (function () { function PublicServiceProfile(conversationType, introduction, menu, name, portraitUri, publicServiceId, hasFollowed, isGlobal) { this.conversationType = conversationType; this.introduction = introduction; this.menu = menu; this.name = name; this.portraitUri = portraitUri; this.publicServiceId = publicServiceId; this.hasFollowed = hasFollowed; this.isGlobal = isGlobal; } return PublicServiceProfile; })(); RongIMLib.PublicServiceProfile = PublicServiceProfile; var UserInfo = (function () { function UserInfo(id, name, portraitUri) { this.id = id; this.name = name; this.portraitUri = portraitUri; } return UserInfo; })(); RongIMLib.UserInfo = UserInfo; var User = (function () { function User(id, token) { this.id = id; this.token = token; } return User; })(); RongIMLib.User = User; var Room = (function () { function Room(id, user, mode, broadcastType, type) { this.id = id; this.user = user; this.mode = mode; this.broadcastType = broadcastType; this.type = type; } return Room; })(); RongIMLib.Room = Room; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var ServerDataProvider = (function () { function ServerDataProvider() { this.userStatusListener = null; } ServerDataProvider.prototype.init = function (appKey, options) { new RongIMLib.FeatureDectector(options.appCallback); }; ServerDataProvider.prototype.connect = function (token, callback, userId, option) { RongIMLib.RongIMClient.bridge = RongIMLib.Bridge.getInstance(); RongIMLib.RongIMClient._memoryStore.token = token; RongIMLib.RongIMClient._memoryStore.callback = callback; userId = userId || ''; option = option || {}; var isConnecting = false, isConnected = false; if (RongIMLib.Bridge._client && RongIMLib.Bridge._client.channel) { isConnecting = (RongIMLib.Bridge._client.channel.connectionStatus == RongIMLib.ConnectionStatus.CONNECTING); isConnected = (RongIMLib.Bridge._client.channel.connectionStatus == RongIMLib.ConnectionStatus.CONNECTED); } if (isConnected || isConnecting) { return; } var isGreater = (RongIMLib.RongIMClient.otherDeviceLoginCount > 5); if (isGreater) { callback.onError(RongIMLib.ConnectionStatus.ULTRALIMIT); return; } // 清除本地导航缓存 if (option.force) { RongIMLib.RongIMClient._storageProvider.removeItem('servers'); } //循环设置监听事件,追加之后清空存放事件数据 for (var i = 0, len = RongIMLib.RongIMClient._memoryStore.listenerList.length; i < len; i++) { RongIMLib.RongIMClient.bridge["setListener"](RongIMLib.RongIMClient._memoryStore.listenerList[i]); } RongIMLib.RongIMClient._memoryStore.listenerList.length = 0; RongIMLib.RongIMClient.bridge.connect(RongIMLib.RongIMClient._memoryStore.appKey, token, { onSuccess: function (data) { setTimeout(function () { callback.onSuccess(data); }); }, onError: function (e) { if (e == RongIMLib.ConnectionState.TOKEN_INCORRECT || !e) { setTimeout(function () { callback.onTokenIncorrect(); }); } else { setTimeout(function () { callback.onError(e); }); } } }); }; /* config.auto: 默认 false, true 启用自动重连,启用则为必选参数 config.rate: 重试频率 [100, 1000, 3000, 6000, 10000, 18000] 单位为毫秒,可选 config.url: 网络嗅探地址 [http(s)://]cdn.ronghub.com/RongIMLib-2.2.6.min.js 可选 */ ServerDataProvider.prototype.reconnect = function (callback, config) { var store = RongIMLib.RongIMClient._memoryStore; var token = store.token; if (!token) { throw new Error('reconnect: token is empty.'); } if (RongIMLib.Bridge._client && RongIMLib.Bridge._client.channel && RongIMLib.Bridge._client.channel.connectionStatus != RongIMLib.ConnectionStatus.CONNECTED && RongIMLib.Bridge._client.channel.connectionStatus != RongIMLib.ConnectionStatus.CONNECTING) { config = config || {}; var key = config.auto ? 'auto' : 'custom'; var handler = { auto: function () { var repeatConnect = function (options) { var step = options.step(); var done = 'done'; var url = options.url; var ping = function () { RongIMLib.RongUtil.request({ url: url, success: function () { options.done(); }, error: function () { repeat(); } }); }; var repeat = function () { var next = step(); if (next == 'done') { var error = RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE; options.done(error); return; } setTimeout(ping, next); }; repeat(); }; var protocol = RongIMLib.RongIMClient._memoryStore.depend.protocol; var url = config.url || 'cdn.ronghub.com/RongIMLib-2.2.6.min.js'; var pathConfig = { protocol: protocol, path: url }; url = RongIMLib.RongUtil.formatProtoclPath(pathConfig); var rate = config.rate || [100, 1000, 3000, 6000, 10000, 18000]; //结束标识 rate.push('done'); var opts = { url: url, step: function () { var index = 0; return function () { var time = rate[index]; index++; return time; }; }, done: function (error) { if (error) { callback.onError(error); return; } RongIMLib.RongIMClient.connect(token, callback); } }; repeatConnect(opts); }, custom: function () { RongIMLib.RongIMClient.connect(token, callback); } }; handler[key](); } }; ServerDataProvider.prototype.logout = function () { RongIMLib.RongIMClient.bridge.disconnect(); RongIMLib.RongIMClient.bridge = null; }; ServerDataProvider.prototype.disconnect = function () { RongIMLib.RongIMClient.bridge.disconnect(); }; ServerDataProvider.prototype.sendReceiptResponse = function (conversationType, targetId, sendCallback) { var rspkey = RongIMLib.Bridge._client.userId + conversationType + targetId + 'RECEIVED', me = this; if (RongIMLib.RongUtil.supportLocalStorage()) { var valObj = JSON.parse(RongIMLib.RongIMClient._storageProvider.getItem(rspkey)); if (valObj) { var vals = []; for (var key in valObj) { var tmp = {}; tmp[key] = valObj[key].uIds; valObj[key].isResponse || vals.push(tmp); } if (vals.length == 0) { sendCallback.onSuccess(); return; } var interval = setInterval(function () { if (vals.length == 1) { clearInterval(interval); } var obj = vals.splice(0, 1)[0]; var rspMsg = new RongIMLib.ReadReceiptResponseMessage({ receiptMessageDic: obj }); me.sendMessage(conversationType, targetId, rspMsg, { onSuccess: function (msg) { var senderUserId = RongIMLib.MessageUtil.getFirstKey(obj); valObj[senderUserId].isResponse = true; RongIMLib.RongIMClient._storageProvider.setItem(rspkey, JSON.stringify(valObj)); sendCallback.onSuccess(msg); }, onError: function (error, msg) { sendCallback.onError(error, msg); } }); }, 200); } else { sendCallback.onSuccess(); } } else { sendCallback.onSuccess(); } }; ServerDataProvider.prototype.sendTypingStatusMessage = function (conversationType, targetId, messageName, sendCallback) { var me = this; if (messageName in RongIMLib.RongIMClient.MessageParams) { me.sendMessage(conversationType, targetId, RongIMLib.TypingStatusMessage.obtain(RongIMLib.RongIMClient.MessageParams[messageName].objectName, ""), { onSuccess: function () { setTimeout(function () { sendCallback.onSuccess(); }); }, onError: function (errorCode) { setTimeout(function () { sendCallback.onError(errorCode, null); }); }, onBefore: function () { } }); } }; ServerDataProvider.prototype.sendRecallMessage = function (content, sendMessageCallback) { var msg = new RongIMLib.RecallCommandMessage({ conversationType: content.conversationType, targetId: content.targetId, sentTime: content.sentTime, messageUId: content.messageUId, extra: content.extra, user: content.user }); this.sendMessage(content.conversationType, content.senderUserId, msg, sendMessageCallback, false, null, null, 2); }; ServerDataProvider.prototype.sendTextMessage = function (conversationType, targetId, content, sendMessageCallback) { var msgContent = RongIMLib.TextMessage.obtain(content); this.sendMessage(conversationType, targetId, msgContent, sendMessageCallback); }; ServerDataProvider.prototype.getRemoteHistoryMessages = function (conversationType, targetId, timestamp, count, callback, config) { if (count <= 1) { throw new Error("the count must be greater than 1."); } config = config || {}; var order = config.order || 0; var getKey = function () { return [conversationType, targetId, '_', order].join(''); }; var key = getKey(); if (!RongIMLib.RongUtil.isNumber(timestamp)) { timestamp = RongIMLib.RongIMClient._memoryStore.lastReadTime.get(key); } var memoryStore = RongIMLib.RongIMClient._memoryStore; var historyMessageLimit = memoryStore.historyMessageLimit; /* limit 属性: var limit = { time: '时间戳, 最后一次拉取时间', hasMore: '是否还有历史消息, bool 值' }; */ var limit = historyMessageLimit.get(key) || {}; var hasMore = limit.hasMore; var isFecth = (hasMore || limit.time != timestamp); // 正序获取消息时不做限制,防止有新消息导致无法获取 if (!isFecth && order == 0) { return callback.onSuccess([], hasMore); } var modules = new RongIMLib.RongIMClient.Protobuf.HistoryMsgInput(), self = this; modules.setTargetId(targetId); modules.setTime(timestamp); modules.setCount(count); modules.setOrder(order); RongIMLib.RongIMClient.bridge.queryMsg(HistoryMsgType[conversationType], RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), targetId, { onSuccess: function (data) { var fetchTime = RongIMLib.MessageUtil.int64ToTimestamp(data.syncTime); RongIMLib.RongIMClient._memoryStore.lastReadTime.set(key, fetchTime); historyMessageLimit.set(key, { hasMore: !!data.hasMsg, time: fetchTime }); var list = data.list.reverse(), tempMsg = null, tempDir; var read = RongIMLib.SentStatus.READ; if (RongIMLib.RongUtil.supportLocalStorage()) { for (var i = 0, len = list.length; i < len; i++) { tempMsg = RongIMLib.MessageUtil.messageParser(list[i]); tempDir = JSON.parse(RongIMLib.RongIMClient._storageProvider.getItem(RongIMLib.Bridge._client.userId + tempMsg.messageUId + "SENT")); if (tempDir) { tempMsg.receiptResponse || (tempMsg.receiptResponse = {}); tempMsg.receiptResponse[tempMsg.messageUId] = tempDir.count; } tempMsg.sentStatus = read; tempMsg.targetId = targetId; list[i] = tempMsg; } } else { for (var i = 0, len = list.length; i < len; i++) { var tempMsg = RongIMLib.MessageUtil.messageParser(list[i]); tempMsg.sentStatus = read; list[i] = tempMsg; } } setTimeout(function () { callback.onSuccess(list, !!data.hasMsg); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }, "HistoryMessagesOuput"); }; ServerDataProvider.prototype.hasRemoteUnreadMessages = function (token, callback) { var xss = null; window.RCCallback = function (x) { setTimeout(function () { callback.onSuccess(!!+x.status); }); xss.parentNode.removeChild(xss); }; xss = document.createElement("script"); xss.src = RongIMLib.RongIMClient._memoryStore.depend.api + "/message/exist.js?appKey=" + encodeURIComponent(RongIMLib.RongIMClient._memoryStore.appKey) + "&token=" + encodeURIComponent(token) + "&callBack=RCCallback&_=" + RongIMLib.RongUtil.getTimestamp(); document.body.appendChild(xss); xss.onerror = function () { setTimeout(function () { callback.onError(RongIMLib.ErrorCode.UNKNOWN); }); xss.parentNode.removeChild(xss); }; }; ServerDataProvider.prototype.getRemoteConversationList = function (callback, conversationTypes, count) { var modules = new RongIMLib.RongIMClient.Protobuf.RelationsInput(), self = this; modules.setType(1); if (typeof count == 'undefined') { modules.setCount(0); } else { modules.setCount(count); } RongIMLib.RongIMClient.bridge.queryMsg(26, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (list) { if (list.info) { list.info = list.info.reverse(); for (var i = 0, len = list.info.length; i < len; i++) { RongIMLib.RongIMClient.getInstance().pottingConversation(list.info[i]); } } var conversations = RongIMLib.RongIMClient._memoryStore.conversationList; setTimeout(function () { if (conversationTypes) { return callback.onSuccess(self.filterConversations(conversationTypes, conversations)); } callback.onSuccess(conversations); }); }, onError: function (error) { callback.onError(error); } }, "RelationsOutput"); }; ServerDataProvider.prototype.addMemberToDiscussion = function (discussionId, userIdList, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.ChannelInvitationInput(); modules.setUsers(userIdList); RongIMLib.RongIMClient.bridge.queryMsg(0, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), discussionId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.createDiscussion = function (name, userIdList, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.CreateDiscussionInput(), self = this; modules.setName(name); RongIMLib.RongIMClient.bridge.queryMsg(1, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (discussId) { if (userIdList.length > 0) { self.addMemberToDiscussion(discussId, userIdList, { onSuccess: function () { }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); } setTimeout(function () { callback.onSuccess(discussId); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }, "CreateDiscussionOutput"); }; ServerDataProvider.prototype.getDiscussion = function (discussionId, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.ChannelInfoInput(); modules.setNothing(1); RongIMLib.RongIMClient.bridge.queryMsg(4, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), discussionId, { onSuccess: function (data) { setTimeout(function () { callback.onSuccess(data); }); }, onError: function (errorCode) { setTimeout(function () { callback.onError(errorCode); }); } }, "ChannelInfoOutput"); }; ServerDataProvider.prototype.quitDiscussion = function (discussionId, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.LeaveChannelInput(); modules.setNothing(1); RongIMLib.RongIMClient.bridge.queryMsg(7, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), discussionId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (errorCode) { setTimeout(function () { callback.onError(errorCode); }); } }); }; ServerDataProvider.prototype.removeMemberFromDiscussion = function (discussionId, userId, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.ChannelEvictionInput(); modules.setUser(userId); RongIMLib.RongIMClient.bridge.queryMsg(9, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), discussionId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (errorCode) { setTimeout(function () { callback.onError(errorCode); }); } }); }; ServerDataProvider.prototype.setDiscussionInviteStatus = function (discussionId, status, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.ModifyPermissionInput(); modules.setOpenStatus(status.valueOf()); RongIMLib.RongIMClient.bridge.queryMsg(11, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), discussionId, { onSuccess: function (x) { setTimeout(function () { callback.onSuccess(); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.setDiscussionName = function (discussionId, name, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RenameChannelInput(); modules.setName(name); RongIMLib.RongIMClient.bridge.queryMsg(12, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), discussionId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (errcode) { callback.onError(errcode); } }); }; ServerDataProvider.prototype.joinChatRoom = function (chatroomId, messageCount, callback) { var e = new RongIMLib.RongIMClient.Protobuf.ChrmInput(); e.setNothing(1); RongIMLib.Bridge._client.chatroomId = chatroomId; RongIMLib.RongIMClient.bridge.queryMsg(19, RongIMLib.MessageUtil.ArrayForm(e.toArrayBuffer()), chatroomId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); var modules = new RongIMLib.RongIMClient.Protobuf.ChrmPullMsg(); messageCount == 0 && (messageCount = -1); modules.setCount(messageCount); modules.setSyncTime(0); RongIMLib.Bridge._client.queryMessage("chrmPull", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), chatroomId, 1, { onSuccess: function (collection) { var list = collection.list; var sync = RongIMLib.MessageUtil.int64ToTimestamp(collection.syncTime); var latestMessage = list[list.length - 1]; if (latestMessage) { latestMessage = RongIMLib.MessageUtil.messageParser(latestMessage); sync = latestMessage.sentTime; } RongIMLib.RongIMClient._memoryStore.lastReadTime.set(chatroomId + RongIMLib.Bridge._client.userId + "CST", sync); var _client = RongIMLib.Bridge._client; for (var i = 0, mlen = list.length; i < mlen; i++) { var uId = 'R' + list[i].msgId; if (!(uId in _client.cacheMessageIds)) { _client.cacheMessageIds[uId] = true; var cacheUIds = RongIMLib.RongUtil.keys(_client.cacheMessageIds); if (cacheUIds.length > 10) { uId = cacheUIds[0]; delete _client.cacheMessageIds[uId]; } if (RongIMLib.RongIMClient._memoryStore.filterMessages.length > 0) { for (var j = 0, flen = RongIMLib.RongIMClient._memoryStore.filterMessages.length; j < flen; j++) { if (RongIMLib.RongIMClient.MessageParams[RongIMLib.RongIMClient._memoryStore.filterMessages[j]].objectName != list[i].classname) { _client.handler.onReceived(list[i]); } } } else { _client.handler.onReceived(list[i]); } } } }, onError: function (x) { setTimeout(function () { callback.onError(RongIMLib.ErrorCode.CHATROOM_HISMESSAGE_ERROR); }); } }, "DownStreamMessages"); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }, "ChrmOutput"); }; ServerDataProvider.prototype.getChatRoomInfo = function (chatRoomId, count, order, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.QueryChatroomInfoInput(); modules.setCount(count); modules.setOrder(order); RongIMLib.RongIMClient.bridge.queryMsg("queryChrmI", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), chatRoomId, { onSuccess: function (ret) { var userInfos = ret.userInfos; userInfos.forEach(function (item) { item.time = RongIMLib.MessageUtil.int64ToTimestamp(item.time); }); setTimeout(function () { callback.onSuccess(ret); }); }, onError: function (errcode) { setTimeout(function () { callback.onError(errcode); }); } }, "QueryChatroomInfoOutput"); }; ServerDataProvider.prototype.quitChatRoom = function (chatroomId, callback) { var e = new RongIMLib.RongIMClient.Protobuf.ChrmInput(); e.setNothing(1); RongIMLib.RongIMClient.bridge.queryMsg(17, RongIMLib.MessageUtil.ArrayForm(e.toArrayBuffer()), chatroomId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (errcode) { setTimeout(function () { callback.onError(errcode); }); } }, "ChrmOutput"); }; ServerDataProvider.prototype.setChatroomHisMessageTimestamp = function (chatRoomId, timestamp) { RongIMLib.RongIMClient._memoryStore.lastReadTime.set('chrhis_' + chatRoomId, timestamp); }; ServerDataProvider.prototype.getChatRoomHistoryMessages = function (chatRoomId, count, order, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.HistoryMsgInput(); modules.setTargetId(chatRoomId); var timestamp = RongIMLib.RongIMClient._memoryStore.lastReadTime.get('chrhis_' + chatRoomId) || 0; modules.setTime(timestamp); modules.setCount(count); modules.setOrder(order); RongIMLib.RongIMClient.bridge.queryMsg(34, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (data) { RongIMLib.RongIMClient._memoryStore.lastReadTime.set('chrhis_' + chatRoomId, RongIMLib.MessageUtil.int64ToTimestamp(data.syncTime)); var list = data.list.reverse(); for (var i = 0, len = list.length; i < len; i++) { list[i] = RongIMLib.MessageUtil.messageParser(list[i]); } setTimeout(function () { callback.onSuccess(list, !!data.hasMsg); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }, "HistoryMsgOuput"); }; ServerDataProvider.prototype.setMessageStatus = function (conversationType, targetId, timestamp, status, callback) { setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.addToBlacklist = function (userId, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.Add2BlackListInput(); modules.setUserId(userId); RongIMLib.RongIMClient.bridge.queryMsg(21, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.getBlacklist = function (callback) { var modules = new RongIMLib.RongIMClient.Protobuf.QueryBlackListInput(); modules.setNothing(1); RongIMLib.RongIMClient.bridge.queryMsg(23, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (list) { setTimeout(function () { callback.onSuccess(list); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }, "QueryBlackListOutput"); }; ServerDataProvider.prototype.getBlacklistStatus = function (userId, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.BlackListStatusInput(); modules.setUserId(userId); RongIMLib.RongIMClient.bridge.queryMsg(24, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function (status) { setTimeout(function () { callback.onSuccess(RongIMLib.BlacklistStatus[status]); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.removeFromBlacklist = function (userId, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RemoveFromBlackListInput(); modules.setUserId(userId); RongIMLib.RongIMClient.bridge.queryMsg(22, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.getFileToken = function (fileType, callback) { if (!(/(1|2|3|4)/.test(fileType.toString()))) { setTimeout(function () { callback.onError(RongIMLib.ErrorCode.QNTKN_FILETYPE_ERROR); }); return; } var modules = new RongIMLib.RongIMClient.Protobuf.GetQNupTokenInput(); modules.setType(fileType); RongIMLib.RongIMClient.bridge.queryMsg(30, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (data) { setTimeout(function () { callback.onSuccess(data); }); }, onError: function (errcode) { setTimeout(function () { callback.onError(errcode); }); } }, "GetQNupTokenOutput"); }; ServerDataProvider.prototype.getFileUrl = function (fileType, fileName, oriName, callback) { if (!(/(1|2|3|4)/.test(fileType.toString()))) { setTimeout(function () { callback.onError(RongIMLib.ErrorCode.QNTKN_FILETYPE_ERROR); }); return; } var modules = new RongIMLib.RongIMClient.Protobuf.GetQNdownloadUrlInput(); modules.setType(fileType); modules.setKey(fileName); if (oriName) { modules.setFileName(oriName); } RongIMLib.RongIMClient.bridge.queryMsg(31, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (data) { setTimeout(function () { callback.onSuccess(data); }); }, onError: function (errcode) { setTimeout(function () { callback.onError(errcode); }); } }, "GetQNdownloadUrlOutput"); }; /* methodType 1 : 多客服(客服后台使用); 2 : 消息撤回 params.userIds : 定向消息接收者 */ ServerDataProvider.prototype.sendMessage = function (conversationType, targetId, messageContent, sendCallback, mentiondMsg, pushText, appData, methodType, params) { if (!RongIMLib.Bridge._client.channel) { setTimeout(function () { sendCallback.onError(RongIMLib.ErrorCode.RC_NET_UNAVAILABLE, null); }); return; } if (!RongIMLib.Bridge._client.channel.socket.socket.connected) { setTimeout(function () { sendCallback.onError(RongIMLib.ErrorCode.TIMEOUT, null); }); throw new Error("connect is timeout! postion:sendMessage"); } var isGroup = (conversationType == RongIMLib.ConversationType.DISCUSSION || conversationType == RongIMLib.ConversationType.GROUP); var modules = new RongIMLib.RongIMClient.Protobuf.UpStreamMessage(); if (mentiondMsg && isGroup) { modules.setSessionId(7); } else { modules.setSessionId(RongIMLib.RongIMClient.MessageParams[messageContent.messageName].msgTag.getMessageTag()); } pushText && modules.setPushText(pushText); appData && modules.setAppData(appData); if (isGroup && messageContent.messageName == RongIMLib.RongIMClient.MessageType["ReadReceiptResponseMessage"]) { var rspMsg = messageContent; if (rspMsg.receiptMessageDic) { var ids = []; for (var key in rspMsg.receiptMessageDic) { ids.push(key); } modules.setUserId(ids); } } if (isGroup && messageContent.messageName == RongIMLib.RongIMClient.MessageType["SyncReadStatusMessage"]) { modules.setUserId(RongIMLib.Bridge._client.userId); } params = params || {}; var userIds = params.userIds; if (userIds) { modules.setUserId(userIds); } var flag = 0; if (params.isPush) { flag |= 0x01; } if (params.isFilerWhiteBlacklist) { flag |= 0x02; } modules.setConfigFlag(flag); modules.setClassname(RongIMLib.RongIMClient.MessageParams[messageContent.messageName].objectName); modules.setContent(messageContent.encode()); var content = modules.toArrayBuffer(); if (Object.prototype.toString.call(content) == "[object ArrayBuffer]") { content = [].slice.call(new Int8Array(content)); } var me = this, msg = new RongIMLib.Message(); var c = this.getConversation(conversationType, targetId); if (RongIMLib.RongIMClient.MessageParams[messageContent.messageName].msgTag.getMessageTag() == 3) { if (!c) { c = RongIMLib.RongIMClient.getInstance().createConversation(conversationType, targetId, ""); } c.sentTime = new Date().getTime(); c.sentStatus = RongIMLib.SentStatus.SENDING; c.senderUserName = ""; c.senderUserId = RongIMLib.Bridge._client.userId; c.notificationStatus = RongIMLib.ConversationNotificationStatus.DO_NOT_DISTURB; c.latestMessage = msg; c.unreadMessageCount = 0; RongIMLib.RongIMClient._dataAccessProvider.addConversation(c, { onSuccess: function (data) { } }); } RongIMLib.RongIMClient._memoryStore.converStore = c; msg.content = messageContent; msg.conversationType = conversationType; msg.senderUserId = RongIMLib.Bridge._client.userId; msg.objectName = RongIMLib.RongIMClient.MessageParams[messageContent.messageName].objectName; msg.targetId = targetId; msg.sentTime = new Date().getTime(); msg.messageDirection = RongIMLib.MessageDirection.SEND; msg.sentStatus = RongIMLib.SentStatus.SENT; msg.messageType = messageContent.messageName; RongIMLib.RongIMClient.bridge.pubMsg(conversationType.valueOf(), content, targetId, { onSuccess: function (data) { if (data && data.timestamp) { RongIMLib.RongIMClient._memoryStore.lastReadTime.set('converST_' + RongIMLib.Bridge._client.userId + conversationType + targetId, data.timestamp); } if ((conversationType == RongIMLib.ConversationType.DISCUSSION || conversationType == RongIMLib.ConversationType.GROUP) && messageContent.messageName == RongIMLib.RongIMClient.MessageType["ReadReceiptRequestMessage"]) { var reqMsg = msg.content; var sentkey = RongIMLib.Bridge._client.userId + reqMsg.messageUId + "SENT"; RongIMLib.RongIMClient._storageProvider.setItem(sentkey, JSON.stringify({ count: 0, dealtime: data.timestamp, userIds: {} })); } if (RongIMLib.RongIMClient.MessageParams[msg.messageType].msgTag.getMessageTag() == 3) { var cacheConversation = RongIMLib.RongIMClient._memoryStore.converStore; cacheConversation.sentStatus = msg.sentStatus; cacheConversation.latestMessage = msg; me.updateConversation(cacheConversation); RongIMLib.RongIMClient._dataAccessProvider.addMessage(conversationType, targetId, msg, { onSuccess: function (ret) { msg = ret; msg.messageUId = data.messageUId; msg.sentTime = data.timestamp; msg.sentStatus = RongIMLib.SentStatus.SENT; msg.messageId = data.messageId; RongIMLib.RongIMClient._dataAccessProvider.updateMessage(msg); }, onError: function () { } }); } setTimeout(function () { cacheConversation && me.updateConversation(cacheConversation); msg.sentTime = data.timestamp; msg.messageUId = data.messageUId; sendCallback.onSuccess(msg); }); }, onError: function (errorCode, _msg) { msg.sentStatus = RongIMLib.SentStatus.FAILED; if (_msg) { msg.messageUId = _msg.messageUId; msg.sentTime = _msg.sentTime; } if (RongIMLib.RongIMClient.MessageParams[msg.messageType].msgTag.getMessageTag() == 3) { RongIMLib.RongIMClient._memoryStore.converStore.latestMessage = msg; } RongIMLib.RongIMClient._dataAccessProvider.addMessage(conversationType, targetId, msg, { onSuccess: function (ret) { msg.messageId = ret.messageId; RongIMLib.RongIMClient._dataAccessProvider.updateMessage(msg); }, onError: function () { } }); setTimeout(function () { sendCallback.onError(errorCode, msg); }); } }, null, methodType); sendCallback.onBefore && sendCallback.onBefore(RongIMLib.MessageIdHandler.messageId); msg.messageId = RongIMLib.MessageIdHandler.messageId + ""; }; ServerDataProvider.prototype.setConnectionStatusListener = function (listener) { var watcher = { onChanged: function (status) { listener.onChanged(status); RongIMLib.RongUtil.forEach(RongIMLib.RongIMClient.statusListeners, function (watch) { watch(status); }); } }; if (RongIMLib.RongIMClient.bridge) { RongIMLib.RongIMClient.bridge.setListener(watcher); } else { RongIMLib.RongIMClient._memoryStore.listenerList.push(watcher); } }; ServerDataProvider.prototype.setOnReceiveMessageListener = function (listener) { if (RongIMLib.RongIMClient.bridge) { RongIMLib.RongIMClient.bridge.setListener(listener); } else { RongIMLib.RongIMClient._memoryStore.listenerList.push(listener); } }; ServerDataProvider.prototype.registerMessageType = function (messageType, objectName, messageTag, messageContent, searchProps) { if (!messageType) { throw new Error("messageType can't be empty,postion -> registerMessageType"); } if (!objectName) { throw new Error("objectName can't be empty,postion -> registerMessageType"); } if (Object.prototype.toString.call(messageContent) == "[object Array]") { var regMsg = RongIMLib.ModelUtil.modleCreate(messageContent, messageType); RongIMLib.RongIMClient.RegisterMessage[messageType] = regMsg; } else if (Object.prototype.toString.call(messageContent) == "[object Function]" || Object.prototype.toString.call(messageContent) == "[object Object]") { if (!messageContent.encode) { throw new Error("encode method has not realized or messageName is undefined-> registerMessageType"); } if (!messageContent.decode) { throw new Error("decode method has not realized -> registerMessageType"); } } else { throw new Error("The index of 3 parameter was wrong type must be object or function or array-> registerMessageType"); } registerMessageTypeMapping[objectName] = messageType; }; ServerDataProvider.prototype.registerMessageTypes = function (messages) { var types = []; var getProtos = function (proto) { var protos = []; for (var p in proto) { protos.push(p); } return protos; }; //转换消息为自定义消息参数格式 for (var name in messages) { var message = messages[name]; var proto = message.proto; var protos = getProtos(proto); var flag = message.flag || 3; var tag = RongIMLib.MessageTag.getTagByStatus(flag); flag = new RongIMLib.MessageTag(tag.isCounted, tag.isPersited); types.push({ type: name, name: message.name, flag: flag, protos: protos }); } var register = function (message) { var type = message.type; var name = message.name; var flag = message.flag; var protos = message.protos; RongIMLib.RongIMClient.registerMessageType(type, name, flag, protos); }; for (var i = 0, len = types.length; i < len; i++) { var message = types[i]; register(message); } }; ServerDataProvider.prototype.addConversation = function (conversation, callback) { var isAdd = true; for (var i = 0, len = RongIMLib.RongIMClient._memoryStore.conversationList.length; i < len; i++) { if (RongIMLib.RongIMClient._memoryStore.conversationList[i].conversationType === conversation.conversationType && RongIMLib.RongIMClient._memoryStore.conversationList[i].targetId === conversation.targetId) { // RongIMClient._memoryStore.conversationList[i] = conversation; RongIMLib.RongIMClient._memoryStore.conversationList.unshift(RongIMLib.RongIMClient._memoryStore.conversationList.splice(i, 1)[0]); isAdd = false; break; } } if (isAdd) { RongIMLib.RongIMClient._memoryStore.conversationList.unshift(conversation); } callback && callback.onSuccess(true); }; ServerDataProvider.prototype.updateConversation = function (conversation) { var conver; for (var i = 0, len = RongIMLib.RongIMClient._memoryStore.conversationList.length; i < len; i++) { var item = RongIMLib.RongIMClient._memoryStore.conversationList[i]; if (conversation.conversationType === item.conversationType && conversation.targetId === item.targetId) { conversation.conversationTitle && (item.conversationTitle = conversation.conversationTitle); conversation.senderUserName && (item.senderUserName = conversation.senderUserName); conversation.senderPortraitUri && (item.senderPortraitUri = conversation.senderPortraitUri); conversation.latestMessage && (item.latestMessage = conversation.latestMessage); conversation.sentStatus && (item.sentStatus = conversation.sentStatus); break; } } return conver; }; ServerDataProvider.prototype.removeConversation = function (conversationType, targetId, callback) { var mod = new RongIMLib.RongIMClient.Protobuf.RelationsInput(); mod.setType(conversationType); RongIMLib.RongIMClient.bridge.queryMsg(27, RongIMLib.MessageUtil.ArrayForm(mod.toArrayBuffer()), targetId, { onSuccess: function () { var conversations = RongIMLib.RongIMClient._memoryStore.conversationList; var len = conversations.length; for (var i = 0; i < len; i++) { if (conversations[i].conversationType == conversationType && targetId == conversations[i].targetId) { conversations.splice(i, 1); break; } } callback.onSuccess(true); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.getMessage = function (messageId, callback) { callback.onSuccess(new RongIMLib.Message()); }; ServerDataProvider.prototype.addMessage = function (conversationType, targetId, message, callback) { if (callback) { callback.onSuccess(message); } }; ServerDataProvider.prototype.removeMessage = function (conversationType, targetId, messageIds, callback) { RongIMLib.RongIMClient.getInstance().deleteRemoteMessages(conversationType, targetId, messageIds, callback); }; ServerDataProvider.prototype.removeLocalMessage = function (conversationType, targetId, timestamps, callback) { callback.onSuccess(true); }; ServerDataProvider.prototype.updateMessage = function (message, callback) { if (callback) { callback.onSuccess(message); } }; ServerDataProvider.prototype.clearRemoteHistoryMessages = function (params, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.CleanHisMsgInput(); var conversationType = params.conversationType; var _topic = { 1: 'cleanPMsg', 2: 'cleanDMsg', 3: 'cleanGMsg', 5: 'cleanCMsg', 6: 'cleanSMsg' }; var topic = _topic[conversationType]; if (!topic) { callback.onError(RongIMLib.ErrorCode.CLEAR_HIS_TYPE_ERROR); return; } var timestamp = params.timestamp; if (typeof timestamp != 'number') { callback.onError(RongIMLib.ErrorCode.CLEAR_HIS_TIME_ERROR); return; } modules.setDataTime(timestamp); var targetId = params.targetId; modules.setTargetId(targetId); RongIMLib.RongIMClient.bridge.queryMsg(topic, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), targetId, { onSuccess: function (result) { callback.onSuccess(!result); }, onError: function (error) { // error 1 历史消息云存储没有开通、传入时间大于服务器时间 清除失败,1 与其他错误码冲突,所以自定义错误码返回 if (error == 1) { error = RongIMLib.ErrorCode.CLEAR_HIS_ERROR; } setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.clearHistoryMessages = function (params, callback) { this.clearRemoteHistoryMessages(params, callback); }; // 兼容老版本 ServerDataProvider.prototype.clearMessages = function (conversationType, targetId, callback) { }; ServerDataProvider.prototype.updateMessages = function (conversationType, targetId, key, value, callback) { var me = this; if (key == "readStatus") { if (RongIMLib.RongIMClient._memoryStore.conversationList.length > 0) { me.getConversationList({ onSuccess: function (list) { Array.forEach(list, function (conver) { if (conver.conversationType == conversationType && conver.targetId == targetId) { conver.unreadMessageCount = 0; } }); }, onError: function (errorCode) { setTimeout(function () { callback.onError(errorCode); }); } }, null); } } setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.getConversation = function (conversationType, targetId, callback) { var conver = null; for (var i = 0, len = RongIMLib.RongIMClient._memoryStore.conversationList.length; i < len; i++) { if (RongIMLib.RongIMClient._memoryStore.conversationList[i].conversationType == conversationType && RongIMLib.RongIMClient._memoryStore.conversationList[i].targetId == targetId) { conver = RongIMLib.RongIMClient._memoryStore.conversationList[i]; if (RongIMLib.RongUtil.supportLocalStorage()) { var count = RongIMLib.RongIMClient._storageProvider.getItem("cu" + RongIMLib.Bridge._client.userId + conversationType + targetId); if (conver.unreadMessageCount == 0) { conver.unreadMessageCount = Number(count); } } } } setTimeout(function () { callback && callback.onSuccess(conver); }); return conver; }; ServerDataProvider.prototype.filterConversations = function (types, list) { var conversaions = []; RongIMLib.RongUtil.forEach(types, function (type) { RongIMLib.RongUtil.forEach(list, function (conversation) { if (conversation.conversationType == type) { conversaions.push(conversation); } }); }); return conversaions; }; ServerDataProvider.prototype.getConversationList = function (callback, conversationTypes, count, isHidden) { var that = this; var isSync = RongIMLib.RongIMClient._memoryStore.isSyncRemoteConverList; var list = RongIMLib.RongIMClient._memoryStore.conversationList; var isLocalInclude = list.length > count; if (!isSync && isLocalInclude) { setTimeout(function () { var localList = list.slice(0, count); if (conversationTypes) { localList = that.filterConversations(conversationTypes, localList); } callback.onSuccess(localList); }); return; } RongIMLib.RongIMClient.getInstance().getRemoteConversationList({ onSuccess: function (list) { if (RongIMLib.RongUtil.supportLocalStorage()) { Array.forEach(RongIMLib.RongIMClient._memoryStore.conversationList, function (item) { var count = RongIMLib.RongIMClient._storageProvider.getItem("cu" + RongIMLib.Bridge._client.userId + item.conversationType + item.targetId); if (item.unreadMessageCount == 0) { item.unreadMessageCount = Number(count); } }); } RongIMLib.RongIMClient._memoryStore.isSyncRemoteConverList = false; setTimeout(function () { callback.onSuccess(list); }); }, onError: function (errorcode) { setTimeout(function () { callback.onError(errorcode); }); } }, conversationTypes, count, isHidden); }; ServerDataProvider.prototype.clearCache = function () { var memoryStore = RongIMLib.RongIMClient._memoryStore || {}; memoryStore.conversationList = []; memoryStore.isSyncRemoteConverList = true; }; ServerDataProvider.prototype.clearConversations = function (conversationTypes, callback) { Array.forEach(conversationTypes, function (conversationType) { Array.forEach(RongIMLib.RongIMClient._memoryStore.conversationList, function (conver) { if (conversationType == conver.conversationType) { RongIMLib.RongIMClient.getInstance().removeConversation(conver.conversationType, conver.targetId, { onSuccess: function () { }, onError: function () { } }); } }); }); setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.setMessageContent = function (messageId, content, objectname) { }; ; ServerDataProvider.prototype.setMessageSearchField = function (messageId, content, searchFiles) { }; ; ServerDataProvider.prototype.getHistoryMessages = function (conversationType, targetId, timestamp, count, callback, objectname, order) { var config = { objectname: objectname, order: order }; RongIMLib.RongIMClient.getInstance().getRemoteHistoryMessages(conversationType, targetId, timestamp, count, callback, config); }; ServerDataProvider.prototype.getTotalUnreadCount = function (callback, conversationTypes) { var count = 0; var storageProvider = RongIMLib.RongIMClient._storageProvider; if (conversationTypes) { RongIMLib.RongUtil.forEach(conversationTypes, function (type) { var unreadKeys = storageProvider.getItemKeyList("cu" + RongIMLib.Bridge._client.userId + type); RongIMLib.RongUtil.forEach(unreadKeys, function (key) { var unread = storageProvider.getItem(key); var unreadCount = Number(unread) || 0; count += unreadCount; }); }); } else { var unreadKeys = storageProvider.getItemKeyList("cu" + RongIMLib.Bridge._client.userId); RongIMLib.RongUtil.forEach(unreadKeys, function (key) { var unread = storageProvider.getItem(key); var unreadCount = Number(unread) || 0; count += unreadCount; }); } callback.onSuccess(count); }; ServerDataProvider.prototype.getConversationUnreadCount = function (conversationTypes, callback) { var count = 0; Array.forEach(conversationTypes, function (converType) { Array.forEach(RongIMLib.RongIMClient._memoryStore.conversationList, function (conver) { if (conver.conversationType == converType) { count += conver.unreadMessageCount; } }); }); setTimeout(function () { callback.onSuccess(count); }); }; //由于 Web 端未读消息数按会话统计,撤回消息会导致未读数不准确,提供设置未读数接口,桌面版不实现此方法 ServerDataProvider.prototype.setUnreadCount = function (conversationType, targetId, count) { var storageProvider = RongIMLib.RongIMClient._storageProvider; var key = "cu" + RongIMLib.Bridge._client.userId + conversationType + targetId; storageProvider.setItem(key, count); }; ServerDataProvider.prototype.getUnreadCount = function (conversationType, targetId, callback) { var key = "cu" + RongIMLib.Bridge._client.userId + conversationType + targetId; var unread = RongIMLib.RongIMClient._storageProvider.getItem(key); var unreadCount = Number(unread); setTimeout(function () { callback.onSuccess(unreadCount || 0); }); }; ServerDataProvider.prototype.cleanMentioneds = function (conver) { if (conver) { conver.mentionedMsg = null; var targetId = conver.targetId; var conversationType = conver.conversationType; var mentioneds = RongIMLib.RongIMClient._storageProvider.getItem("mentioneds_" + RongIMLib.Bridge._client.userId + '_' + conversationType + '_' + targetId); if (mentioneds) { var info = JSON.parse(mentioneds); delete info[conversationType + "_" + targetId]; if (!RongIMLib.MessageUtil.isEmpty(info)) { RongIMLib.RongIMClient._storageProvider.setItem("mentioneds_" + RongIMLib.Bridge._client.userId + '_' + conversationType + '_' + targetId, JSON.stringify(info)); } else { RongIMLib.RongIMClient._storageProvider.removeItem("mentioneds_" + RongIMLib.Bridge._client.userId + '_' + conversationType + '_' + targetId); } } } }; ServerDataProvider.prototype.clearUnreadCountByTimestamp = function (conversationType, targetId, timestamp, callback) { setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.clearUnreadCount = function (conversationType, targetId, callback) { var me = this; RongIMLib.RongIMClient._storageProvider.removeItem("cu" + RongIMLib.Bridge._client.userId + conversationType + targetId); this.getConversation(conversationType, targetId, { onSuccess: function (conver) { if (conver) { conver.unreadMessageCount = 0; me.cleanMentioneds(conver); } setTimeout(function () { callback.onSuccess(true); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.clearTotalUnreadCount = function (callback) { var list = RongIMLib.RongIMClient._memoryStore.conversationList; var me = this; if (list) { // 清除 mentioneds、清除 list 中的 unreadMessageCount for (var i = 0; i < list.length; i++) { var conver = list[i]; if (conver) { conver.unreadMessageCount = 0; me.cleanMentioneds(conver); } } } // 1. 获取所有 key 2. 清除 var unreadKeys = RongIMLib.RongIMClient._storageProvider.getItemKeyList("cu" + RongIMLib.Bridge._client.userId); RongIMLib.RongUtil.forEach(unreadKeys, function (key) { RongIMLib.RongIMClient._storageProvider.removeItem(key); }); setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.setConversationToTop = function (conversationType, targetId, isTop, callback) { var me = this; this.getConversation(conversationType, targetId, { onSuccess: function (conver) { conver.isTop = isTop; me.addConversation(conver, callback); setTimeout(function () { callback.onSuccess(true); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.getConversationNotificationStatus = function (params, callback) { var targetId = params.targetId; var conversationType = params.conversationType; var notification = RongIMLib.RongIMClient._memoryStore.notification; var getKey = function () { return conversationType + '_' + targetId; }; var key = getKey(); var status = notification[key]; if (typeof status == 'number') { callback.onSuccess(status); return; } var topics = { 1: 'qryPPush', 3: 'qryDPush' }; var topic = topics[conversationType]; if (!topic) { var error = 8001; callback.onError(error); return; } var modules = new RongIMLib.RongIMClient.Protobuf.BlockPushInput(); modules.setBlockeeId(targetId); var userId = RongIMLib.Bridge._client.userId; var success = function (status) { notification[key] = status; setTimeout(function () { callback.onSuccess(status); }); }; RongIMLib.RongIMClient.bridge.queryMsg(topic, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function (status) { success(status); }, onError: function (e) { if (e == 1) { success(e); } else { setTimeout(function () { callback.onError(e); }); } } }); }; ServerDataProvider.prototype.setConversationNotificationStatus = function (params, callback) { var conversationType = params.conversationType; var targetId = params.targetId; var status = params.status; var getKey = function () { return conversationType + '_' + status; }; var topics = { '1_1': 'blkPPush', '3_1': 'blkDPush', '1_0': 'unblkPPush', '3_0': 'unblkDPush' }; var key = getKey(); var notification = RongIMLib.RongIMClient._memoryStore.notification; notification[key] = status; var topic = topics[key]; if (!topic) { var error = 8001; setTimeout(function () { callback.onError(error); }); return; } var modules = new RongIMLib.RongIMClient.Protobuf.BlockPushInput(); modules.setBlockeeId(targetId); var userId = RongIMLib.Bridge._client.userId; RongIMLib.RongIMClient.bridge.queryMsg(topic, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function (status) { setTimeout(function () { callback.onSuccess(status); }); }, onError: function (e) { setTimeout(function () { callback.onError(e); }); } }); }; ServerDataProvider.prototype.getUserStatus = function (userId, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.GetUserStatusInput(); userId = RongIMLib.Bridge._client.userId; RongIMLib.RongIMClient.bridge.queryMsg(35, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function (status) { status = RongIMLib.RongInnerTools.convertUserStatus(status); setTimeout(function () { callback.onSuccess(status); }); }, onError: function (e) { setTimeout(function () { callback.onError(e); }); } }, 'GetUserStatusOutput'); // callback.onSuccess(new UserStatus()); }; ServerDataProvider.prototype.setUserStatus = function (status, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.SetUserStatusInput(); var userId = RongIMLib.Bridge._client.userId; if (status) { modules.setStatus(status); } RongIMLib.RongIMClient.bridge.queryMsg(36, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function (status) { setTimeout(function () { callback.onSuccess(true); }); }, onError: function (e) { setTimeout(function () { callback.onError(e); }); } }, 'SetUserStatusOutput'); }; ServerDataProvider.prototype.subscribeUserStatus = function (userIds, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.SubUserStatusInput(); var userId = RongIMLib.Bridge._client.userId; modules.setUserid(userIds); RongIMLib.RongIMClient.bridge.queryMsg(37, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function (status) { setTimeout(function () { callback && callback.onSuccess(true); }); }, onError: function (e) { setTimeout(function () { callback && callback.onError(e); }); } }, 'SubUserStatusOutput'); }; ServerDataProvider.prototype.setUserStatusListener = function (params, callback) { RongIMLib.RongIMClient.userStatusListener = callback; var userIds = params.userIds || []; if (userIds.length) { RongIMLib.RongIMClient._dataAccessProvider.subscribeUserStatus(userIds); } }; ServerDataProvider.prototype.clearListeners = function () { }; ServerDataProvider.prototype.setServerInfo = function (info) { }; ServerDataProvider.prototype.getUnreadMentionedMessages = function (conversationType, targetId) { return null; }; ServerDataProvider.prototype.setConversationHidden = function (conversationType, targetId, isHidden) { }; ServerDataProvider.prototype.setMessageExtra = function (messageId, value, callback) { setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.setMessageReceivedStatus = function (messageId, receivedStatus, callback) { setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.setMessageSentStatus = function (messageId, sentStatus, callback) { setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.getAllConversations = function (callback) { setTimeout(function () { callback.onSuccess([]); }); }; ServerDataProvider.prototype.getConversationByContent = function (keywords, callback) { setTimeout(function () { callback.onSuccess([]); }); }; ServerDataProvider.prototype.getMessagesFromConversation = function (conversationType, targetId, keywords, callback) { setTimeout(function () { callback.onSuccess([]); }); }; ServerDataProvider.prototype.searchConversationByContent = function (keyword, callback, conversationTypes) { setTimeout(function () { callback.onSuccess([]); }); }; ServerDataProvider.prototype.searchMessageByContent = function (conversationType, targetId, keyword, timestamp, count, total, callback) { setTimeout(function () { callback.onSuccess([]); }); }; ServerDataProvider.prototype.getDelaTime = function () { return RongIMLib.RongIMClient._memoryStore.deltaTime; }; ServerDataProvider.prototype.getCurrentConnectionStatus = function () { var client = RongIMLib.Bridge._client || {}; var channel = client.channel || {}; var status = RongIMLib.ConnectionStatus.CONNECTION_CLOSED; if (typeof channel.connectionStatus == 'number') { status = channel.connectionStatus; } return status; }; ServerDataProvider.prototype.getAgoraDynamicKey = function (engineType, channelName, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.VoipDynamicInput(); modules.setEngineType(engineType); modules.setChannelName(channelName); RongIMLib.RongIMClient.bridge.queryMsg(32, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (result) { setTimeout(function () { callback.onSuccess(result); }); }, onError: function (errorCode) { setTimeout(function () { callback.onError(errorCode); }); } }, "VoipDynamicOutput"); }; ServerDataProvider.prototype.setDeviceInfo = function (deviceId) { }; ServerDataProvider.prototype.setEnvironment = function (isPrivate) { }; ServerDataProvider.prototype.clearData = function () { return true; }; ServerDataProvider.prototype.getPublicServiceProfile = function (publicServiceType, publicServiceId, callback) { var profile = RongIMLib.RongIMClient._memoryStore.publicServiceMap.get(publicServiceType, publicServiceId); setTimeout(function () { callback.onSuccess(profile); }); }; ServerDataProvider.prototype.getRemotePublicServiceList = function (callback, pullMessageTime) { if (RongIMLib.RongIMClient._memoryStore.depend.openMp) { var modules = new RongIMLib.RongIMClient.Protobuf.PullMpInput(), self = this; if (!pullMessageTime) { modules.setTime(0); } else { modules.setTime(pullMessageTime); } modules.setMpid(""); RongIMLib.RongIMClient.bridge.queryMsg(28, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (data) { //TODO 找出最大时间 // self.lastReadTime.set(conversationType + targetId, MessageUtil.int64ToTimestamp(data.syncTime)); RongIMLib.RongIMClient._memoryStore.publicServiceMap.publicServiceList.length = 0; RongIMLib.RongIMClient._memoryStore.publicServiceMap.publicServiceList = data; setTimeout(function () { callback && callback.onSuccess(data); }); }, onError: function (errorCode) { setTimeout(function () { callback && callback.onError(errorCode); }); } }, "PullMpOutput"); } }; ServerDataProvider.prototype.getRTCUserInfoList = function (room, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcQueryListInput(); // 1 是正序,2是倒序 modules.setOrder(2); RongIMLib.RongIMClient.bridge.queryMsg("rtcUData", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function (result) { var users = {}; var list = result.list; RongIMLib.RongUtil.forEach(list, function (item) { var userId = item.userId; var tmpData = {}; RongIMLib.RongUtil.forEach(item.userData, function (data) { var key = data.key; var value = data.value; tmpData[key] = value; }); users[userId] = tmpData; }); callback.onSuccess(users); }, onError: function (errorCode) { callback.onError(errorCode); } }, "RtcUserListOutput"); }; ServerDataProvider.prototype.getRTCUserList = function (room, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcQueryListInput(); modules.setOrder(2); RongIMLib.RongIMClient.bridge.queryMsg("rtcUList", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function (result) { callback.onSuccess({ users: result.list }); }, onError: function (errorCode) { callback.onError(errorCode); } }, "RtcUserListOutput"); }; ServerDataProvider.prototype.setRTCUserInfo = function (room, info, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcValueInfo(); modules.setKey(info.key); modules.setValue(info.value); RongIMLib.RongIMClient.bridge.queryMsg("rtcUPut", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function () { callback.onSuccess(true); }, onError: function (errorCode) { callback.onError(errorCode); } }); }; ServerDataProvider.prototype.removeRTCUserInfo = function (room, info, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcKeyDeleteInput(); var keys = info.keys || []; if (!RongIMLib.RongUtil.isArray(keys)) { keys = [keys]; } modules.setKey(keys); RongIMLib.RongIMClient.bridge.queryMsg("rtcUDel", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function () { callback.onSuccess(true); }, onError: function (errorCode) { callback.onError(errorCode); } }); }; ServerDataProvider.prototype.getRTCRoomInfo = function (room, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcQueryListInput(); modules.setOrder(2); RongIMLib.RongIMClient.bridge.queryMsg("rtcRInfo", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function (result) { var room = { id: result.roomId, total: result.userCount }; RongIMLib.RongUtil.forEach(result.roomData, function (data) { room[data.key] = data.value; }); callback.onSuccess(room); }, onError: function (errorCode) { callback.onError(errorCode); } }, "RtcRoomInfoOutput"); }; ServerDataProvider.prototype.setRTCRoomInfo = function (room, info, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcValueInfo(); modules.setKey(info.key); modules.setValue(info.value); RongIMLib.RongIMClient.bridge.queryMsg("rtcRPut", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function () { callback.onSuccess(true); }, onError: function (errorCode) { callback.onError(errorCode); } }); }; ServerDataProvider.prototype.removeRTCRoomInfo = function (room, info, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcKeyDeleteInput(); var keys = info.keys || []; if (!RongIMLib.RongUtil.isArray(keys)) { keys = [keys]; } modules.setKey(keys); RongIMLib.RongIMClient.bridge.queryMsg("rtcRDel", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function () { callback.onSuccess(true); }, onError: function (errorCode) { callback.onError(errorCode); } }); }; ServerDataProvider.prototype.joinRTCRoom = function (room, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcInput(); var mode = room.mode || 0; modules.setRoomType(mode); if (room.broadcastType) { modules.setBroadcastType(room.broadcastType); } RongIMLib.RongIMClient.bridge.queryMsg("rtcRJoin_data", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function (result) { var users = {}; var list = result.list, token = result.token; RongIMLib.RongUtil.forEach(list, function (item) { var userId = item.userId; var tmpData = {}; RongIMLib.RongUtil.forEach(item.userData, function (data) { var key = data.key; var value = data.value; tmpData[key] = value; }); users[userId] = tmpData; }); callback.onSuccess({ users: users, token: token }); }, onError: function (errorCode) { callback.onError(errorCode); } }, "RtcUserListOutput"); }; ServerDataProvider.prototype.quitRTCRoom = function (room, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.SetUserStatusInput(); RongIMLib.RongIMClient.bridge.queryMsg("rtcRExit", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function () { callback.onSuccess(true); }, onError: function (errorCode) { callback.onError(errorCode); } }); }; ServerDataProvider.prototype.RTCPing = function (room, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcInput(); var mode = room.mode || 0; modules.setRoomType(mode); if (room.broadcastType) { modules.setBroadcastType(room.broadcastType); } RongIMLib.RongIMClient.bridge.queryMsg("rtcPing", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, callback); }; ServerDataProvider.prototype.setRTCData = function (roomId, key, value, isInner, apiType, callback, message) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcSetDataInput(); modules.setInterior(isInner); modules.setTarget(apiType); modules.setKey(key); modules.setValue(value); message = message || {}; var name = message.name; var content = message.content; if (name) { modules.setObjectName(name); } if (content) { if (!RongIMLib.RongUtil.isString(content)) { content = JSON.stringify(content); } modules.setContent(content); } RongIMLib.RongIMClient.bridge.queryMsg("rtcSetData", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), roomId, callback, "RtcOutput"); }; ServerDataProvider.prototype.getRTCData = function (roomId, keys, isInner, apiType, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcDataInput(); modules.setInterior(isInner); modules.setTarget(apiType); modules.setKey(keys); RongIMLib.RongIMClient.bridge.queryMsg("rtcQryData", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), roomId, { onSuccess: function (result) { var props = {}; var list = result.outInfo; RongIMLib.RongUtil.forEach(list, function (item) { props[item.key] = item.value; }); callback.onSuccess(props); }, onError: callback.onError }, "RtcQryOutput"); }; ServerDataProvider.prototype.removeRTCData = function (roomId, keys, isInner, apiType, callback, message) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcDataInput(); modules.setInterior(isInner); modules.setTarget(apiType); modules.setKey(keys); message = message || {}; var name = message.name; var content = message.content; if (name) { modules.setObjectName(name); } if (content) { if (!RongIMLib.RongUtil.isString(content)) { content = JSON.stringify(content); } modules.setContent(content); } RongIMLib.RongIMClient.bridge.queryMsg("rtcDelData", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), roomId, callback, "RtcOutput"); }; ServerDataProvider.prototype.setRTCUserData = function (roomId, key, value, isInner, callback, message) { this.setRTCData(roomId, key, value, isInner, RongIMLib.RTCAPIType.PERSON, callback, message); }; ServerDataProvider.prototype.getRTCUserData = function (roomId, keys, isInner, callback, message) { this.getRTCData(roomId, keys, isInner, RongIMLib.RTCAPIType.PERSON, callback); }; ServerDataProvider.prototype.removeRTCUserData = function (roomId, keys, isInner, callback, message) { this.removeRTCData(roomId, keys, isInner, RongIMLib.RTCAPIType.PERSON, callback, message); }; ServerDataProvider.prototype.setRTCRoomData = function (roomId, key, value, isInner, callback, message) { this.setRTCData(roomId, key, value, isInner, RongIMLib.RTCAPIType.ROOM, callback, message); }; ServerDataProvider.prototype.getRTCRoomData = function (roomId, keys, isInner, callback, message) { this.getRTCData(roomId, keys, isInner, RongIMLib.RTCAPIType.ROOM, callback); }; ServerDataProvider.prototype.removeRTCRoomData = function (roomId, keys, isInner, callback, message) { this.removeRTCData(roomId, keys, isInner, RongIMLib.RTCAPIType.ROOM, callback, message); }; // 信令 SDK 新增 ServerDataProvider.prototype.setRTCOutData = function (roomId, data, type, callback, message) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcSetOutDataInput(); modules.setTarget(type); if (!RongIMLib.RongUtil.isArray(data)) { data = [data]; } for (var i = 0; i < data.length; i++) { var item = data[i]; if (item.key) { item.key = item.key.toString(); } if (item.value) { item.value = item.value.toString(); } } modules.setValueInfo(data); message = message || {}; var name = message.name; var content = message.content; if (name) { modules.setObjectName(name); } if (content) { if (!RongIMLib.RongUtil.isString(content)) { content = JSON.stringify(content); } modules.setContent(content); } RongIMLib.RongIMClient.bridge.queryMsg("rtcSetOutData", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), roomId, callback, "RtcOutput"); }; // 信令 SDK 新增 ServerDataProvider.prototype.getRTCOutData = function (roomId, userIds, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcQryUserOutDataInput(); modules.setUserId(userIds); RongIMLib.RongIMClient.bridge.queryMsg("rtcQryUserOutData", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), roomId, callback, "RtcUserOutDataOutput"); }; ServerDataProvider.prototype.getNavi = function () { var navi = RongIMLib.RongIMClient._storageProvider.getItem("fullnavi") || "{}"; return JSON.parse(navi); }; ServerDataProvider.prototype.getRTCToken = function (room, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcInput(); modules.setRoomType(0); RongIMLib.RongIMClient.bridge.queryMsg("rtcToken", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function (result) { callback.onSuccess(result); }, onError: function (errorCode) { callback.onError(errorCode); } }, "RtcTokenOutput"); }; ServerDataProvider.prototype.setRTCState = function (room, content, callback) { // MCFollowInput 为 PB 复用,字段:一个必传 string(第一位) var modules = new RongIMLib.RongIMClient.Protobuf.MCFollowInput(); var report = content.report; modules.setId(report); RongIMLib.RongIMClient.bridge.queryMsg("rtcUserState", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function (result) { callback.onSuccess(result); }, onError: function (errorCode) { callback.onError(errorCode); } }, "RtcOutput"); }; return ServerDataProvider; })(); RongIMLib.ServerDataProvider = ServerDataProvider; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var VCDataProvider = (function () { function VCDataProvider(addon) { // C++ 需要的 SDK 版本号 this.version = '2.8.27'; this.userId = ""; this.useConsole = false; this.appKey = ""; this.token = ""; this.addon = addon; } VCDataProvider.prototype.init = function (appKey, config) { this.appKey = appKey; this.useConsole && console.log("init"); config = config || {}; config.version = this.version; var sdkInfo = this.addon.initWithAppkey(appKey, config.dbPath, config); if (sdkInfo) { sdkInfo = JSON.parse(sdkInfo); } // 0 不存不计数 1 只存不计数 3 存且计数 this.addon.registerMessageType("RC:VcMsg", 3); this.addon.registerMessageType("RC:ImgTextMsg", 3); this.addon.registerMessageType("RC:FileMsg", 3); this.addon.registerMessageType("RC:LBSMsg", 3); this.addon.registerMessageType("RC:PSImgTxtMsg", 3); this.addon.registerMessageType("RC:PSMultiImgTxtMsg", 3); this.addon.registerMessageType("RCJrmf:RpMsg", 3); this.addon.registerMessageType("RCJrmf:RpOpendMsg", 1); this.addon.registerMessageType("RC:GrpNtf", 1); this.addon.registerMessageType("RC:DizNtf", 0); this.addon.registerMessageType("RC:InfoNtf", 0); this.addon.registerMessageType("RC:ContactNtf", 0); this.addon.registerMessageType("RC:ProfileNtf", 0); this.addon.registerMessageType("RC:CmdNtf", 0); this.addon.registerMessageType("RC:CmdMsg", 0); this.addon.registerMessageType("RC:TypSts", 0); this.addon.registerMessageType("RC:CsChaR", 0); this.addon.registerMessageType("RC:CsHsR", 0); this.addon.registerMessageType("RC:CsEnd", 0); this.addon.registerMessageType("RC:CsSp", 0); this.addon.registerMessageType("RC:CsUpdate", 0); this.addon.registerMessageType("RC:CsContact", 0); this.addon.registerMessageType("RC:ReadNtf", 0); this.addon.registerMessageType("RC:VCAccept", 0); this.addon.registerMessageType("RC:VCRinging", 0); this.addon.registerMessageType("RC:VCSummary", 0); this.addon.registerMessageType("RC:VCHangup", 0); this.addon.registerMessageType("RC:VCInvite", 0); this.addon.registerMessageType("RC:VCModifyMedia", 0); this.addon.registerMessageType("RC:VCModifyMem", 0); this.addon.registerMessageType("RC:PSCmd", 0); this.addon.registerMessageType("RC:RcCmd", 0); this.addon.registerMessageType("RC:SRSMsg", 0); this.addon.registerMessageType("RC:RRReqMsg", 0); this.addon.registerMessageType("RC:RRRspMsg", 0); return sdkInfo; }; VCDataProvider.prototype.connect = function (token, callback, userId, serverConf) { this.useConsole && console.log("connect"); this.userId = userId; this.connectCallback = callback; RongIMLib.Bridge._client = { userId: userId }; serverConf = serverConf || {}; var openmp = !!serverConf.openMp; var openus = !!serverConf.openUS; if (serverConf.type) { this.addon.setEnvironment(true); } this.addon.connectWithToken(token, userId, serverConf.serverList, openmp, openus); }; VCDataProvider.prototype.setServerInfo = function (info) { 'setServerInfo' in this.addon && this.addon.setServerInfo(info.navi); }; VCDataProvider.prototype.logout = function () { this.useConsole && console.log("logout"); this.disconnect(); }; VCDataProvider.prototype.disconnect = function () { this.useConsole && console.log("disconnect"); this.addon.disconnect(true); }; VCDataProvider.prototype.clearListeners = function () { this.addon.setOnReceiveStatusListener(); this.addon.setConnectionStatusListener(); this.addon.setOnReceiveMessageListener(); }; VCDataProvider.prototype.clearData = function () { this.useConsole && console.log("clearData"); return this.addon.clearData(); }; VCDataProvider.prototype.setConnectionStatusListener = function (listener) { var me = this; /** ConnectionStatus_TokenIncorrect = 31004, ConnectionStatus_Connected = 0, ConnectionStatus_KickedOff = 6, // 其他设备登录 ConnectionStatus_Connecting = 10,// 连接中 ConnectionStatus_SignUp = 12, // 未登录 ConnectionStatus_NetworkUnavailable = 1, // 连接断开 ConnectionStatus_ServerInvalid = 8, // 断开 ConnectionStatus_ValidateFailure = 9,//断开 ConnectionStatus_Unconnected = 11,//断开 ConnectionStatus_DisconnExecption = 31011 //断开 RC_NAVI_MALLOC_ERROR = 30000,//断开 RC_NAVI_NET_UNAVAILABLE= 30002,//断开 RC_NAVI_SEND_FAIL = 30004,//断开 RC_NAVI_REQ_TIMEOUT = 30005,//断开 RC_NAVI_RECV_FAIL = 30006,//断开 RC_NAVI_RESOURCE_ERROR = 30007,//断开 RC_NAVI_NODE_NOT_FOUND = 30008,//断开 RC_NAVI_DNS_ERROR = 30009,//断开 */ me.connectListener = listener; this.useConsole && console.log("setConnectionStatusListener"); me.addon && me.addon.setConnectionStatusListener(function (result) { switch (result) { case 10: setTimeout(function () { listener.onChanged(RongIMLib.ConnectionStatus.CONNECTING); }); break; case 31004: setTimeout(function () { me.connectCallback.onTokenIncorrect(); }); break; case 1: case 8: case 9: case 11: case 12: case 31011: case 30000: case 30002: setTimeout(function () { listener.onChanged(RongIMLib.ConnectionStatus.DISCONNECTED); }); break; case 0: case 33005: setTimeout(function () { me.connectCallback.onSuccess(me.userId); listener.onChanged(RongIMLib.ConnectionStatus.CONNECTED); }); break; case 6: setTimeout(function () { listener.onChanged(RongIMLib.ConnectionStatus.KICKED_OFFLINE_BY_OTHER_CLIENT); }); break; default: setTimeout(function () { listener.onChanged(result); }); break; } }); }; VCDataProvider.prototype.setOnReceiveMessageListener = function (listener) { var me = this, localCount = 0; me.messageListener = listener; this.useConsole && console.log("setOnReceiveMessageListener"); me.addon && me.addon.setOnReceiveMessageListener(function (result, leftCount, offline, hasMore) { var message = me.buildMessage(result); message.offLineMessage = offline; setTimeout(function () { var voipMsgTypes = ['AcceptMessage', 'RingingMessage', 'HungupMessage', 'InviteMessage', 'MediaModifyMessage', 'MemberModifyMessage']; var isVoIPMsg = voipMsgTypes.indexOf(message.messageType) > -1; if (isVoIPMsg) { RongIMLib.RongIMClient._voipProvider && RongIMLib.RongIMClient._voipProvider.onReceived(message); } else if (message.conversationType == 12) { RongIMLib.RongIMClient.RTCListener(message); RongIMLib.RongIMClient.RTCInnerListener(message); RongIMLib.RongIMClient.RTCSignalLisener(message); } else { listener.onReceived(message, leftCount, hasMore); } }); }); }; VCDataProvider.prototype.sendTypingStatusMessage = function (conversationType, targetId, messageName, sendCallback) { var me = this; this.useConsole && console.log("sendTypingStatusMessage"); if (messageName in RongIMLib.RongIMClient.MessageParams) { me.sendMessage(conversationType, targetId, RongIMLib.TypingStatusMessage.obtain(RongIMLib.RongIMClient.MessageParams[messageName].objectName, ""), { onSuccess: function () { setTimeout(function () { sendCallback.onSuccess(); }); }, onError: function (errorCode) { setTimeout(function () { sendCallback.onError(errorCode, null); }); }, onBefore: function () { } }); } }; VCDataProvider.prototype.setMessageStatus = function (conversationType, targetId, timestamp, status, callback) { this.addon.updateMessageReceiptStatus(conversationType, targetId, timestamp); callback.onSuccess(true); }; VCDataProvider.prototype.sendTextMessage = function (conversationType, targetId, content, sendMessageCallback) { var msgContent = RongIMLib.TextMessage.obtain(content); this.useConsole && console.log("sendTextMessage"); this.sendMessage(conversationType, targetId, msgContent, sendMessageCallback); }; VCDataProvider.prototype.getRemoteHistoryMessages = function (conversationType, targetId, timestamp, count, callback, config) { try { var me = this; me.useConsole && console.log("getRemoteHistoryMessages"); me.addon.getRemoteHistoryMessages(conversationType, targetId, timestamp ? timestamp : 0, count, function (ret, hasMore) { var list = ret ? JSON.parse(ret).list : [], msgs = []; list.reverse(); for (var i = 0, len = list.length; i < len; i++) { var message = me.buildMessage(list[i].obj); message.sentStatus = RongIMLib.SentStatus.READ; msgs[i] = message; } callback.onSuccess(msgs, hasMore ? true : false); }, function (errorCode) { callback.onError(errorCode); }); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.getRemoteConversationList = function (callback, conversationTypes, count, isGetHiddenConvers) { try { this.useConsole && console.log("getRemoteConversationList"); var converTypes = conversationTypes || [1, 2, 3, 4, 5, 6, 7, 8]; var result = this.addon.getConversationList(converTypes); var list = JSON.parse(result).list, convers = [], me = this, index = 0; list.reverse(); isGetHiddenConvers = typeof isGetHiddenConvers === 'boolean' ? isGetHiddenConvers : false; for (var i = 0, len_1 = list.length; i < len_1; i++) { var tmpObj = list[i].obj, obj = JSON.parse(tmpObj); if (obj != "") { if (obj.isHidden == 1 && isGetHiddenConvers) { continue; } convers[index] = me.buildConversation(tmpObj); index++; } } convers.reverse(); var len = convers.length; count = count || len; if (len > count) { convers.length = count; } callback.onSuccess(convers); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.removeConversation = function (conversationType, targetId, callback) { try { this.useConsole && console.log("removeConversation"); this.addon.removeConversation(conversationType, targetId); var conversations = RongIMLib.RongIMClient._memoryStore.conversationList; var len = conversations.length; for (var i = 0; i < len; i++) { if (conversations[i].conversationType == conversationType && targetId == conversations[i].targetId) { conversations.splice(i, 1); break; } } callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.joinChatRoom = function (chatRoomId, messageCount, callback) { this.useConsole && console.log("joinChatRoom"); this.addon.joinChatRoom(chatRoomId, messageCount, function () { callback.onSuccess(); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.quitChatRoom = function (chatRoomId, callback) { this.useConsole && console.log("quitChatRoom"); this.addon.quitChatRoom(chatRoomId, function () { callback.onSuccess(); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.addToBlacklist = function (userId, callback) { this.useConsole && console.log("addToBlacklist"); this.addon.addToBlacklist(userId, function () { callback.onSuccess(); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.getBlacklist = function (callback) { this.useConsole && console.log("getBlacklist"); this.addon.getBlacklist(function (blacklistors) { callback.onSuccess(blacklistors); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.getBlacklistStatus = function (userId, callback) { this.useConsole && console.log("getBlacklistStatus"); this.addon.getBlacklistStatus(userId, function (result) { callback.onSuccess(result); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.removeFromBlacklist = function (userId, callback) { this.useConsole && console.log("removeFromBlacklist"); this.addon.removeFromBlacklist(userId, function () { callback.onSuccess(); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.sendMessage = function (conversationType, targetId, messageContent, sendCallback, mentiondMsg, pushText, appData, methodType, params) { var me = this, users = []; me.useConsole && console.log("sendMessage"); params = params || {}; var isGroup = (conversationType == RongIMLib.ConversationType.DISCUSSION || conversationType == RongIMLib.ConversationType.GROUP); if (isGroup && messageContent.messageName == RongIMLib.RongIMClient.MessageType["ReadReceiptResponseMessage"]) { users = []; var rspMsg = messageContent; if (rspMsg.receiptMessageDic) { var ids = []; for (var key in rspMsg.receiptMessageDic) { ids.push(key); } users = ids; } } if (isGroup && messageContent.messageName == RongIMLib.RongIMClient.MessageType["SyncReadStatusMessage"]) { users = []; users.push(me.userId); } var userIds = params.userIds; if (isGroup && userIds) { users = userIds; } var msg = me.addon.sendMessage(conversationType, targetId, RongIMLib.RongIMClient.MessageParams[messageContent.messageName].objectName, messageContent.encode(), pushText || "", appData || "", function (progress) { }, function (message, code) { var msg = me.buildMessage(message); var errorCode = RongIMLib.ErrorCode.SENSITIVE_REPLACE; if (code == errorCode) { return sendCallback.onError(errorCode, msg); } sendCallback.onSuccess(msg); }, function (message, code) { sendCallback.onError(code, me.buildMessage(message)); }, users, mentiondMsg); var tempMessage = JSON.parse(msg); sendCallback.onBefore && sendCallback.onBefore(tempMessage.messageId); RongIMLib.MessageIdHandler.messageId = tempMessage.messageId; }; VCDataProvider.prototype.registerMessageType = function (messageType, objectName, messageTag, messageContent, searchProps) { this.useConsole && console.log("registerMessageType"); this.addon.registerMessageType(objectName, messageTag.getMessageTag(), searchProps); var regMsg = RongIMLib.ModelUtil.modleCreate(messageContent, messageType); RongIMLib.RongIMClient.RegisterMessage[messageType] = regMsg; RongIMLib.RongIMClient.RegisterMessage[messageType].messageName = messageType; registerMessageTypeMapping[objectName] = messageType; RongIMLib.RongIMClient.MessageType[messageType] = messageType; RongIMLib.RongIMClient.MessageParams[messageType] = { objectName: objectName, msgTag: messageTag }; typeMapping[objectName] = messageType; }; VCDataProvider.prototype.registerMessageTypes = function (messages) { var types = []; var getProtos = function (proto) { var protos = []; for (var p in proto) { protos.push(p); } return protos; }; //转换消息为自定义消息参数格式 for (var name in messages) { var message = messages[name]; var proto = message.proto; var protos = getProtos(proto); var flag = message.flag || 3; var tag = RongIMLib.MessageTag.getTagByStatus(flag); flag = new RongIMLib.MessageTag(tag.isCounted, tag.isPersited); types.push({ type: name, name: message.name, flag: flag, protos: protos }); } var register = function (message) { var type = message.type; var name = message.name; var flag = message.flag; var protos = message.protos; RongIMLib.RongIMClient.registerMessageType(type, name, flag, protos); }; for (var i = 0, len = types.length; i < len; i++) { var message = types[i]; register(message); } }; VCDataProvider.prototype.addMessage = function (conversationType, targetId, message, callback) { this.useConsole && console.log("addMessage"); var direction = message.direction; var msg = this.addon.insertMessage(conversationType, targetId, message.senderUserId, message.objectName, JSON.stringify(message.content), function () { callback.onSuccess(me.buildMessage(msg)); }, function () { callback.onError(RongIMLib.ErrorCode.MSG_INSERT_ERROR); }, direction), me = this; }; VCDataProvider.prototype.removeMessage = function (conversationType, targetId, delMsgs, callback) { }; VCDataProvider.prototype.removeLocalMessage = function (conversationType, targetId, timestamps, callback) { try { this.useConsole && console.log("removeLocalMessage"); this.addon.deleteMessages(timestamps); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.getMessage = function (messageId, callback) { try { this.useConsole && console.log("getMessage"); var msg = this.buildMessage(this.addon.getMessage(messageId)); callback.onSuccess(msg); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.clearMessages = function (conversationType, targetId, callback) { try { this.useConsole && console.log("clearMessages"); this.addon.clearMessages(conversationType, targetId); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; // Web 端接口,桌面版无需实现 VCDataProvider.prototype.setUnreadCount = function (conversationType, targetId, count) { }; VCDataProvider.prototype.getConversation = function (conversationType, targetId, callback) { try { this.useConsole && console.log("getConversation"); var ret = this.addon.getConversation(conversationType, targetId); callback.onSuccess(this.buildConversation(ret)); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.getConversationList = function (callback, conversationTypes, count, isGetHiddenConvers) { this.useConsole && console.log("getConversationList"); this.getRemoteConversationList(callback, conversationTypes, count, isGetHiddenConvers); }; VCDataProvider.prototype.clearCache = function () { var memoryStore = RongIMLib.RongIMClient._memoryStore || {}; memoryStore.conversationList = []; memoryStore.isSyncRemoteConverList; }; VCDataProvider.prototype.clearConversations = function (conversationTypes, callback) { try { this.useConsole && console.log("clearConversations"); this.addon.clearConversations(); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.setMessageContent = function (messageId, content, objectName) { content = JSON.stringify(content); this.addon.setMessageContent(messageId, content, objectName); }; VCDataProvider.prototype.setMessageSearchField = function (messageId, content, searchFiles) { content = JSON.stringify(content); this.addon.setMessageContent(messageId, content, searchFiles); }; VCDataProvider.prototype.getHistoryMessages = function (conversationType, targetId, timestamp, count, callback, objectname, direction) { this.useConsole && console.log("getHistoryMessages"); if (count <= 0) { callback.onError(RongIMLib.ErrorCode.TIMEOUT); return; } objectname = objectname || ''; direction = typeof direction == 'undefined' || direction; try { var ret = this.addon.getHistoryMessages(conversationType, targetId, timestamp ? timestamp : 0, count, objectname, direction); var list = ret ? JSON.parse(ret).list : [], msgs = [], me = this; list.reverse(); for (var i = 0, len = list.length; i < len; i++) { var message = me.buildMessage(list[i].obj); msgs[i] = message; } callback.onSuccess(msgs, len == count); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.clearRemoteHistoryMessages = function (params, callback) { var conversationType = params.conversationType; var targetId = params.targetId; var timestamp = params.timestamp; var _topic = { 1: true, 2: true, 3: true, 5: true, 6: true }; var topic = _topic[conversationType]; if (!topic) { callback.onError(RongIMLib.ErrorCode.CLEAR_HIS_TYPE_ERROR); return; } if (typeof timestamp != 'number') { callback.onError(RongIMLib.ErrorCode.CLEAR_HIS_TIME_ERROR); return; } this.addon.clearRemoteHistoryMessages(+conversationType, targetId, timestamp, function () { callback.onSuccess(true); }, function (errorCode) { if (errorCode == 1) { // 没有开通历史消息云存储 errorCode = RongIMLib.ErrorCode.CLEAR_HIS_ERROR; } callback.onError(errorCode); }); }; VCDataProvider.prototype.clearHistoryMessages = function (params, callback) { var conversationType = +params.conversationType; var targetId = params.targetId; try { this.addon.clearMessages(conversationType, targetId); var isSuccess = true; callback.onSuccess(isSuccess); } catch (e) { console.log(e); callback.onError(RongIMLib.ErrorCode.CLEAR_HIS_ERROR); } }; VCDataProvider.prototype.getTotalUnreadCount = function (callback, conversationTypes) { try { var result; this.useConsole && console.log("getTotalUnreadCount"); if (conversationTypes) { result = this.addon.getTotalUnreadCount(conversationTypes); } else { result = this.addon.getTotalUnreadCount(); } callback.onSuccess(result); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.getConversationUnreadCount = function (conversationTypes, callback) { this.useConsole && console.log("getConversationUnreadCount"); this.getTotalUnreadCount(callback, conversationTypes); }; VCDataProvider.prototype.getUnreadCount = function (conversationType, targetId, callback) { try { this.useConsole && console.log("getUnreadCount"); var result = this.addon.getUnreadCount(conversationType, targetId); callback.onSuccess(result); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.clearUnreadCount = function (conversationType, targetId, callback) { try { this.useConsole && console.log("clearUnreadCount"); var result = this.addon.clearUnreadCount(conversationType, targetId); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.clearTotalUnreadCount = function (callback) { this.useConsole && console.log("clearTotalUnreadCount"); }; VCDataProvider.prototype.clearUnreadCountByTimestamp = function (conversationType, targetId, timestamp, callback) { try { this.useConsole && console.log("clearUnreadCountByTimestamp"); var result = this.addon.clearUnreadCountByTimestamp(conversationType, targetId, timestamp); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.setConversationToTop = function (conversationType, targetId, isTop, callback) { try { this.useConsole && console.log("setConversationToTop"); this.addon.setConversationToTop(conversationType, targetId, isTop); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.setConversationHidden = function (conversationType, targetId, isHidden) { this.addon.setConversationHidden(conversationType, targetId, isHidden); }; VCDataProvider.prototype.setMessageReceivedStatus = function (messageId, receivedStatus, callback) { try { this.useConsole && console.log("setMessageReceivedStatus"); this.addon.setMessageReceivedStatus(messageId, receivedStatus); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.setMessageSentStatus = function (messageId, sentStatus, callback) { try { this.useConsole && console.log("setMessageSentStatus"); this.addon.setMessageSentStatus(messageId, sentStatus); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.getFileToken = function (fileType, callback) { this.useConsole && console.log("getFileToken"); this.addon.getUploadToken(fileType, function (token) { callback.onSuccess({ token: token }); }, function (errorCode) { callback.onError(errorCode); }); }; VCDataProvider.prototype.getFileUrl = function (fileType, fileName, oriName, callback) { this.useConsole && console.log("getFileUrl"); this.addon.getDownloadUrl(fileType, fileName, oriName, function (url) { callback.onSuccess({ downloadUrl: url }); }, function (errorCode) { callback.onError(errorCode); }); }; VCDataProvider.prototype.searchConversationByContent = function (keyword, callback, conversationTypes) { var converTypes = []; if (typeof conversationTypes == 'undefined') { converTypes = [1, 2, 3, 4, 5, 6, 7]; } else { converTypes = conversationTypes; } try { this.useConsole && console.log("searchConversationByContent"); var result = this.addon.searchConversationByContent(converTypes, keyword); var list = JSON.parse(result).list, convers = [], me = this; list.reverse(); for (var i = 0, len = list.length; i < len; i++) { convers[i] = me.buildConversation(list[i].obj); } callback.onSuccess(convers); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.searchMessageByContent = function (conversationType, targetId, keyword, timestamp, count, total, callback) { var me = this; try { this.useConsole && console.log("searchMessageByContent"); this.addon.searchMessageByContent(conversationType, targetId, keyword, timestamp, count, total, function (ret, matched) { var list = ret ? JSON.parse(ret).list : [], msgs = []; list.reverse(); for (var i = 0, len = list.length; i < len; i++) { msgs[i] = me.buildMessage(list[i].obj); } callback.onSuccess(msgs, matched); }); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.getChatRoomInfo = function (chatRoomId, count, order, callback) { this.useConsole && console.log("getChatRoomInfo"); this.addon.getChatroomInfo(chatRoomId, count, order, function (ret, count) { var list = ret ? JSON.parse(ret).list : [], chatRoomInfo = { userInfos: [], userTotalNums: count }; if (list.length > 0) { for (var i = 0, len = list.length; i < len; i++) { chatRoomInfo.userInfos.push(JSON.parse(list[i].obj)); } } callback.onSuccess(chatRoomInfo); }, function (errcode) { callback.onError(errcode); }); }; VCDataProvider.prototype.setChatroomHisMessageTimestamp = function (chatRoomId, timestamp) { }; VCDataProvider.prototype.getChatRoomHistoryMessages = function (chatRoomId, count, order, callback) { }; VCDataProvider.prototype.getDelaTime = function () { return this.addon.getDeltaTime(); }; VCDataProvider.prototype.getUserStatus = function (userId, callback) { var me = this; this.addon.getUserStatus(userId, function (status) { var entity = RongIMLib.RongInnerTools.convertUserStatus({ status: status, userId: '' }); callback.onSuccess(entity); }, function (code) { callback.onError(code); }); }; VCDataProvider.prototype.setUserStatus = function (status, callback) { this.addon.setUserStatus(status, function () { callback.onSuccess(true); }, function (code) { callback.onError(code); }); }; VCDataProvider.prototype.subscribeUserStatus = function (userIds, callback) { this.addon.subscribeUserStatus(userIds, function () { callback && callback.onSuccess(true); }, function (code) { callback && callback.onError(code); }); }; VCDataProvider.prototype.setUserStatusListener = function (params, callback) { var me = this; this.addon.setOnReceiveStatusListener(function (userId, status) { var entity = RongIMLib.RongInnerTools.convertUserStatus({ userId: userId, status: status }); RongIMLib.RongIMClient.userStatusObserver.notify({ key: userId, entity: entity }); }); var userIds = params.userIds || []; if (userIds.length) { RongIMLib.RongIMClient._dataAccessProvider.subscribeUserStatus(userIds); } }; VCDataProvider.prototype.getUnreadMentionedMessages = function (conversationType, targetId) { var me = this; var mentions = JSON.parse(me.addon.getUnreadMentionedMessages(conversationType, targetId)).list; for (var i = 0, len = mentions.length; i < len; i++) { var temp = JSON.parse(mentions[i].obj); temp.content = JSON.parse(temp.content); mentions[i] = temp; } return mentions; }; VCDataProvider.prototype.hasRemoteUnreadMessages = function (token, callback) { callback.onSuccess(false); }; VCDataProvider.prototype.sendRecallMessage = function (content, sendMessageCallback) { var me = this; me.addon.recallMessage("RC:RcCmd", JSON.stringify(content), content.push || "", function () { content.objectName = 'RC:RcCmd'; sendMessageCallback.onSuccess(me.buildMessage(JSON.stringify(content))); }, function (errorCode) { sendMessageCallback.onError(errorCode); }); }; VCDataProvider.prototype.updateMessage = function (message, callback) { }; VCDataProvider.prototype.updateMessages = function (conversationType, targetId, key, value, callback) { }; VCDataProvider.prototype.reconnect = function (callback) { }; VCDataProvider.prototype.sendReceiptResponse = function (conversationType, targetId, sendCallback) { }; VCDataProvider.prototype.setMessageExtra = function (messageId, value, callback) { }; VCDataProvider.prototype.addMemberToDiscussion = function (discussionId, userIdList, callback) { }; VCDataProvider.prototype.createDiscussion = function (name, userIdList, callback) { }; VCDataProvider.prototype.getDiscussion = function (discussionId, callback) { }; VCDataProvider.prototype.quitDiscussion = function (discussionId, callback) { }; VCDataProvider.prototype.removeMemberFromDiscussion = function (discussionId, userId, callback) { }; VCDataProvider.prototype.setDiscussionInviteStatus = function (discussionId, status, callback) { }; VCDataProvider.prototype.setDiscussionName = function (discussionId, name, callback) { }; VCDataProvider.prototype.setEnvironment = function (isPrivate) { this.addon.setEnvironment(isPrivate); }; VCDataProvider.prototype.addConversation = function (conversation, callback) { }; VCDataProvider.prototype.updateConversation = function (conversation) { return null; }; VCDataProvider.prototype.getConversationNotificationStatus = function (params, callback) { var conversationType = params.conversationType; var targetId = params.targetId; var notification = RongIMLib.RongIMClient._memoryStore.notification; var key = conversationType + '_' + targetId; var status = notification[key]; if (typeof status == 'number') { callback.onSuccess(status); return; } this.addon.getConversationNotificationStatus(conversationType, targetId, function (status) { notification[key] = status; callback.onSuccess(status); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.setConversationNotificationStatus = function (params, callback) { var conversationType = params.conversationType; var targetId = params.targetId; var status = params.status; var notification = RongIMLib.RongIMClient._memoryStore.notification; var key = conversationType + '_' + targetId; notification[key] = status; var notify = !!status; this.addon.setConversationNotificationStatus(conversationType, targetId, notify, function () { callback.onSuccess(status); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.getCurrentConnectionStatus = function () { return this.addon.getConnectionStatus(); }; VCDataProvider.prototype.getAgoraDynamicKey = function (engineType, channelName, callback) { var extra = ""; this.addon.getVoIPKey(engineType, channelName, extra, function (token) { callback.onSuccess(token); }, function (errorCode) { callback.onError(errorCode); }); }; VCDataProvider.prototype.getPublicServiceProfile = function (publicServiceType, publicServiceId, callback) { var profile = RongIMLib.RongIMClient._memoryStore.publicServiceMap.get(publicServiceType, publicServiceId); callback.onSuccess(profile); }; VCDataProvider.prototype.setDeviceInfo = function (device) { var id = device.id || ''; this.addon.setDeviceId(id); }; VCDataProvider.prototype.getRemotePublicServiceList = function (callback, pullMessageTime) { var publicList = []; var ret = this.addon.getAccounts(); var transformProto = function (ret) { var result = { hasFollowed: false, isGlobal: false, menu: null }; if (!ret.obj) { var error = { error: ret }; throw new Error('公众账号数据格式错误: ' + JSON.stringify(error)); } var obj = JSON.parse(ret.obj); var protoMap = { aType: 'conversationType', aId: 'publicServiceId', aName: 'introduction', aUri: 'portraitUri', follow: 'hasFollowed', isGlobal: 'isGlobal' }; for (var key in obj) { var val = obj[key]; if (key == 'aExtra') { var extra = JSON.parse(val); result["hasFollowed"] = extra.follow; result["isGlobal"] = extra.isGlobal; result["menu"] = extra.menu; } var uId = protoMap[key]; if (uId) { result[uId] = val; } } return result; }; if (ret) { ret = JSON.parse(ret); var list = ret.list; for (var i = 0, len = list.length; i < len; i++) { var item = list[i]; item = transformProto(item); publicList.push(item); } } if (publicList.length > 0) { RongIMLib.RongIMClient._memoryStore.publicServiceMap.publicServiceList.length = 0; RongIMLib.RongIMClient._memoryStore.publicServiceMap.publicServiceList = publicList; } callback.onSuccess(RongIMLib.RongIMClient._memoryStore.publicServiceMap.publicServiceList); }; VCDataProvider.prototype.buildMessage = function (result) { var message = new RongIMLib.Message(), ret = JSON.parse(result); message.conversationType = ret.conversationType; message.targetId = ret.targetId; message.messageDirection = ret.direction; message.senderUserId = ret.senderUserId; if (ret.direction == RongIMLib.MessageDirection.RECEIVE) { message.receivedStatus = ret.status; } else if (ret.direction == RongIMLib.MessageDirection.SEND) { message.sentStatus = ret.status; } message.sentTime = ret.sentTime; message.objectName = ret.objectName; var content = ret.content ? JSON.parse(ret.content) : ret.content; var messageType = typeMapping[ret.objectName] || registerMessageTypeMapping[ret.objectName]; if (content) { content.messageName = messageType; } message.content = content; message.messageId = ret.messageId; message.messageUId = ret.messageUid; message.messageType = messageType; return message; }; VCDataProvider.prototype.buildConversation = function (val) { if (val === '') { return null; } var conver = new RongIMLib.Conversation(), c = JSON.parse(val), lastestMsg = c.lastestMsg ? this.buildMessage(c.lastestMsg) : {}; conver.conversationTitle = c.title; conver.conversationType = c.conversationType; conver.draft = c.draft; conver.isTop = c.isTop; conver.isHidden = c.isHidden; lastestMsg.conversationType = c.conversationType; lastestMsg.targetId = c.targetId; conver.latestMessage = lastestMsg; conver.latestMessageId = lastestMsg.messageId; conver.latestMessage.messageType = typeMapping[lastestMsg.objectName] || registerMessageTypeMapping[lastestMsg.objectName]; conver.objectName = lastestMsg.objectName; conver.receivedStatus = RongIMLib.ReceivedStatus.READ; conver.sentTime = lastestMsg.sentTime; conver.senderUserId = lastestMsg.senderUserId; conver.sentStatus = lastestMsg.status; conver.targetId = c.targetId; conver.unreadMessageCount = c.unreadCount; conver.hasUnreadMention = c.m_hasUnreadMention; var mentions = this.getUnreadMentionedMessages(c.conversationType, c.targetId); if (mentions.length > 0) { // 取最后一条 @ 消息,原因:和 web 互相兼容 var mention = mentions.pop(); conver.mentionedMsg = { uid: mention.messageUid, time: mention.sentTime, mentionedInfo: mention.content.mentionedInfo, sendUserId: mention.senderUserId }; } return conver; }; VCDataProvider.prototype.getRTCUserInfoList = function (room, callback) { this.addon.getRTCUsers(room.id, 1, function (result) { callback.onSuccess(result); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.getRTCRoomInfo = function (room, callback) { var order = 2; this.addon.getRTCResouce(room.id, order, function (result) { callback.onSuccess(JSON.parse(result)); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.joinRTCRoom = function (room, callback) { var id = room.id; var type = room.type || 0; this.addon.joinRTCRoom(id, type, function (result, token) { var res = JSON.parse(result); var users = {}; var list = res.list; RongIMLib.RongUtil.forEach(list, function (item) { var userId = item.id; var tmpData = {}; RongIMLib.RongUtil.forEach(item.data, function (data) { var key = data.key; var value = data.value; tmpData[key] = value; }); users[userId] = tmpData; }); callback.onSuccess({ users: users, token: token }); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.quitRTCRoom = function (room, callback) { this.addon.exitRTCRoom(room.id, function () { callback.onSuccess(true); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.RTCPing = function (room, callback) { this.addon.sendRTCPing(room.id, function () { callback.onSuccess(true); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.setRTCData = function (roomId, key, value, isInner, apiType, callback, message) { var context = this; var hanlders = { room_inner: function (roomId, key, value, name, content, success, error) { context.addon.setRTCInnerData(roomId, RongIMLib.RTCAPIType.ROOM, key, value, name, content, success, error); }, room_outer: function (roomId, key, value, name, content, success, error) { context.addon.setRTCOuterData(roomId, RongIMLib.RTCAPIType.ROOM, key, value, name, content, success, error); }, user_inner: function (roomId, key, value, name, content, success, error) { context.addon.setRTCInnerData(roomId, RongIMLib.RTCAPIType.PERSON, key, value, name, content, success, error); }, user_outer: function (roomId, key, value, name, content, success, error) { context.addon.setRTCOuterData(roomId, RongIMLib.RTCAPIType.PERSON, key, value, name, content, success, error); } }; var type = RongIMLib.RTCAPIType.PERSON == apiType ? 'user' : 'room'; var direction = isInner ? 'inner' : 'outer'; var tpl = '{type}_{direction}'; var name = RongIMLib.RongUtil.tplEngine(tpl, { type: type, direction: direction }); var handler = hanlders[name]; if (handler) { message = message || {}; var name = message.name; var content = message.content; handler(roomId, key, value, name, content, function () { callback.onSuccess(true); }, function (code) { callback.onError(code); }); } }; VCDataProvider.prototype.setRTCRoomData = function (roomId, key, value, isInner, callback, message) { this.setRTCData(roomId, key, value, isInner, RongIMLib.RTCAPIType.ROOM, callback, message); }; VCDataProvider.prototype.getRTCData = function (roomId, keys, isInner, apiType, callback) { var context = this; var hanlders = { room_inner: function (roomId, keys, success, error) { context.addon.getRTCInnerData(roomId, RongIMLib.RTCAPIType.ROOM, keys, success, error); }, room_outer: function (roomId, keys, success, error) { context.addon.getRTCOuterData(roomId, RongIMLib.RTCAPIType.ROOM, keys, success, error); } }; var type = RongIMLib.RTCAPIType.PERSON == apiType ? 'user' : 'room'; var direction = isInner ? 'inner' : 'outer'; var tpl = '{type}_{direction}'; var name = RongIMLib.RongUtil.tplEngine(tpl, { type: type, direction: direction }); var handler = hanlders[name]; if (handler) { handler(roomId, keys, function (result) { var res = JSON.parse(result); var props = {}; var list = res.list; RongIMLib.RongUtil.forEach(list, function (item) { props[item.key] = item.value; }); callback.onSuccess(props); }, function (code) { callback.onError(code); }); } }; VCDataProvider.prototype.getRTCRoomData = function (roomId, keys, isInner, callback, message) { this.getRTCData(roomId, keys, isInner, RongIMLib.RTCAPIType.ROOM, callback); }; VCDataProvider.prototype.removeRTCData = function (roomId, keys, isInner, apiType, callback, message) { var context = this; var hanlders = { room_inner: function (roomId, keys, name, content, success, error) { context.addon.deleteRTCInnerData(roomId, RongIMLib.RTCAPIType.ROOM, keys, name, content, success, error); }, room_outer: function (roomId, keys, name, content, success, error) { context.addon.deleteRTCOuterData(roomId, RongIMLib.RTCAPIType.ROOM, keys, name, content, success, error); }, user_inner: function (roomId, keys, name, content, success, error) { }, user_outer: function (roomId, keys, name, content, success, error) { } }; var type = RongIMLib.RTCAPIType.PERSON == apiType ? 'user' : 'room'; var direction = isInner ? 'inner' : 'outer'; var tpl = '{type}_{direction}'; var name = RongIMLib.RongUtil.tplEngine(tpl, { type: type, direction: direction }); var handler = hanlders[name]; if (handler) { message = message || {}; var name = message.name || ''; var content = message.content || ''; handler(roomId, keys, name, content, function () { callback.onSuccess(true); }, function (code) { callback.onError(code); }); } }; VCDataProvider.prototype.removeRTCRoomData = function (roomId, keys, isInner, callback, message) { this.removeRTCData(roomId, keys, isInner, RongIMLib.RTCAPIType.ROOM, callback); }; VCDataProvider.prototype.getNavi = function () { var nav = this.addon.getNav(); return nav[this.userId]; }; // 信令 SDK 新增 VCDataProvider.prototype.setRTCOutData = function (roomId, data, type, callback, message) { }; // 信令 SDK 新增 VCDataProvider.prototype.getRTCOutData = function (roomId, userId, callback) { }; VCDataProvider.prototype.setRTCUserInfo = function (room, info, callback) { }; VCDataProvider.prototype.removeRTCUserInfo = function (room, info, callback) { }; VCDataProvider.prototype.getRTCUserList = function (room, callback) { }; VCDataProvider.prototype.setRTCRoomInfo = function (room, data, callback) { }; VCDataProvider.prototype.removeRTCRoomInfo = function (room, data, callback) { }; VCDataProvider.prototype.setRTCUserData = function (roomId, key, value, isInner, callback, message) { this.setRTCData(roomId, key, value, isInner, RongIMLib.RTCAPIType.PERSON, callback, message); }; VCDataProvider.prototype.getRTCUserData = function (roomId, key, isInner, callback, message) { }; VCDataProvider.prototype.removeRTCUserData = function (roomId, key, isInner, callback, message) { }; VCDataProvider.prototype.getRTCToken = function (room, callback) { }; VCDataProvider.prototype.setRTCState = function (room, content, callback) { }; return VCDataProvider; })(); RongIMLib.VCDataProvider = VCDataProvider; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var MemeoryProvider = (function () { function MemeoryProvider() { this._memeoryStore = {}; this.prefix = "rong_"; } MemeoryProvider.prototype.setItem = function (composedKey, object) { this._memeoryStore[composedKey] = decodeURIComponent(object); }; MemeoryProvider.prototype.getItem = function (composedKey) { return this._memeoryStore[composedKey]; }; MemeoryProvider.prototype.removeItem = function (composedKey) { if (this.getItem(composedKey)) { delete this._memeoryStore[composedKey]; } }; MemeoryProvider.prototype.getItemKey = function (regStr) { var me = this, item = null, reg = new RegExp(regStr + "\\w+"); for (var key in me._memeoryStore) { var arr = key.match(reg); if (arr) { item = key; } } return item; }; MemeoryProvider.prototype.getItemKeyList = function (regStr) { var prefix = this.prefix; var me = this, itemList = [], reg = new RegExp(regStr + "\\w+"); for (var key in me._memeoryStore) { var arr = key.match(reg); if (arr) { key = key.substring(prefix.length); itemList.push(key); } } return itemList; }; MemeoryProvider.prototype.clearItem = function () { var me = this; for (var key in me._memeoryStore) { delete me._memeoryStore[key]; } }; //单位:字节 MemeoryProvider.prototype.onOutOfQuota = function () { return 4 * 1024; }; return MemeoryProvider; })(); RongIMLib.MemeoryProvider = MemeoryProvider; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var LocalStorageProvider = (function () { // static _instance: LocalStorageProvider = new LocalStorageProvider(); function LocalStorageProvider() { this.prefix = 'rong_'; this._host = ""; var d = new Date(), m = d.getMonth() + 1, date = d.getFullYear() + '/' + (m.toString().length == 1 ? '0' + m : m) + '/' + d.getDate(), nowDate = new Date(date).getTime(); for (var key in localStorage) { if (key.lastIndexOf('RECEIVED') > -1) { var recObj = JSON.parse(localStorage.getItem(key)); for (var key_1 in recObj) { nowDate - recObj[key_1].dealtime > 0 && (delete recObj[key_1]); } if (RongIMLib.RongUtil.isEmpty(recObj)) { localStorage.removeItem(key); } else { localStorage.setItem(key, JSON.stringify(recObj)); } } if (key.lastIndexOf('SENT') > -1) { var sentObj = JSON.parse(localStorage.getItem(key)); nowDate - sentObj.dealtime > 0 && (localStorage.removeItem(key)); } } } LocalStorageProvider.prototype.setItem = function (composedKey, object) { if (composedKey) { composedKey.indexOf(this.prefix) == -1 && (composedKey = this.prefix + composedKey); localStorage.setItem(composedKey, object); } }; LocalStorageProvider.prototype.getItem = function (composedKey) { if (composedKey) { composedKey.indexOf(this.prefix) == -1 && (composedKey = this.prefix + composedKey); return localStorage.getItem(composedKey ? composedKey : ""); } return ""; }; LocalStorageProvider.prototype.getItemKey = function (composedStr) { var item = ""; var _key = this.prefix + composedStr; for (var key in localStorage) { if (key.indexOf(_key) == 0) { item = key; break; } } return item; }; LocalStorageProvider.prototype.getItemKeyList = function (composedStr) { var itemList = []; var prefix = this.prefix; var _key = prefix + composedStr; for (var key in localStorage) { if (key.indexOf(_key) == 0) { key = key.substring(prefix.length); itemList.push(key); } } return itemList; }; LocalStorageProvider.prototype.removeItem = function (composedKey) { if (composedKey) { composedKey.indexOf(this.prefix) == -1 && (composedKey = this.prefix + composedKey); localStorage.removeItem(composedKey.toString()); } }; LocalStorageProvider.prototype.clearItem = function () { var me = this; for (var key in localStorage) { if (key.indexOf(me.prefix) > -1) { me.removeItem(key); } } }; //单位:字节 LocalStorageProvider.prototype.onOutOfQuota = function () { return JSON.stringify(localStorage).length; }; return LocalStorageProvider; })(); RongIMLib.LocalStorageProvider = LocalStorageProvider; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var UserDataProvider = (function () { function UserDataProvider() { this.opersistName = 'RongIMLib'; this.keyManager = 'RongUserDataKeyManager'; this._host = ""; this.prefix = "rong_"; this.oPersist = document.createElement("div"); this.oPersist.style.display = "none"; this.oPersist.style.behavior = "url('#default#userData')"; document.body.appendChild(this.oPersist); this.oPersist.load(this.opersistName); } UserDataProvider.prototype.setItem = function (key, value) { key && key.indexOf(this.prefix) == -1 && (key = this.prefix + key); this.oPersist.setAttribute(key, value); var keyNames = this.getItem(this.keyManager); keyNames ? keyNames.indexOf(key) == -1 && (keyNames += ',' + key) : (keyNames = key); this.oPersist.setAttribute(this.prefix + this.keyManager, keyNames); this.oPersist.save(this.opersistName); }; UserDataProvider.prototype.getItem = function (key) { key && key.indexOf(this.prefix) == -1 && (key = this.prefix + key); return key ? this.oPersist.getAttribute(key) : key; }; UserDataProvider.prototype.removeItem = function (key) { key && key.indexOf(this.prefix) == -1 && (key = this.prefix + key); this.oPersist.removeAttribute(key); this.oPersist.save(this.opersistName); var keyNames = this.getItem(this.keyManager), keyNameArray = keyNames && keyNames.split(',') || []; for (var i = 0, len = keyNameArray.length; i < len; i++) { if (keyNameArray[i] == key) { keyNameArray.splice(i, 1); } } this.oPersist.setAttribute(this.prefix + this.keyManager, keyNameArray.join(',')); this.oPersist.save(this.opersistName); }; UserDataProvider.prototype.getItemKey = function (composedStr) { var item = null, keyNames = this.getItem(this.keyManager), keyNameArray = keyNames && keyNames.split(',') || [], me = this; var _key = this.prefix + composedStr; if (keyNameArray.length) { for (var i = 0, len = keyNameArray.length; i < len; i++) { if (keyNameArray[i] && keyNameArray[i].indexOf(_key) == 0) { item = keyNameArray[i]; break; } } } return item; }; UserDataProvider.prototype.getItemKeyList = function (composedStr) { var itemList = [], keyNames = this.getItem(this.keyManager), keyNameArray = keyNames && keyNames.split(',') || []; var prefix = this.prefix; var _key = prefix + composedStr; if (keyNameArray.length) { for (var i = 0, len = keyNameArray.length; i < len; i++) { if (keyNameArray[i] && keyNameArray[i].indexOf(_key) == 0) { var keyName = keyNameArray[i]; keyName = keyName.substring(prefix.length); itemList.push(keyNameArray[i]); } } } return itemList; }; UserDataProvider.prototype.clearItem = function () { var keyNames = this.getItem(this.keyManager), keyNameArray = [], me = this; keyNames && (keyNameArray = keyNames.split(',')); if (keyNameArray.length) { for (var i = 0, len = keyNameArray.length; i < len; i++) { keyNameArray[i] && me.removeItem(keyNameArray[i]); } me.removeItem(me.keyManager); } }; UserDataProvider.prototype.onOutOfQuota = function () { return 10 * 1024 * 1024; }; return UserDataProvider; })(); RongIMLib.UserDataProvider = UserDataProvider; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var FeatureDectector = (function () { function FeatureDectector(callback) { this.script = document.createElement("script"); this.head = document.getElementsByTagName("head")[0]; if ("WebSocket" in window && "ArrayBuffer" in window && WebSocket.prototype.CLOSED === 3 && !RongIMLib.RongIMClient._memoryStore.depend.isPolling) { RongIMLib.Transportations._TransportType = RongIMLib.Socket.WEBSOCKET; if (!RongIMLib.RongIMClient.Protobuf) { var url = RongIMLib.RongIMClient._memoryStore.depend.protobuf; var script = this.script; script.src = url; this.head.appendChild(script); script.onload = script.onreadystatechange = function () { var isLoaded = (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete'); if (isLoaded) { // 防止 IE6、7 下偶发触发两次 loaded script.onload = script.onreadystatechange = null; if (callback) { callback(); } if (!callback) { var token = RongIMLib.RongIMClient._memoryStore.token; var connectCallback = RongIMLib.RongIMClient._memoryStore.callback; token && RongIMLib.RongIMClient.connect(token, connectCallback); } } }; } } else { RongIMLib.Transportations._TransportType = "xhr-polling"; RongIMLib.RongIMClient.Protobuf = Polling; } } return FeatureDectector; })(); RongIMLib.FeatureDectector = FeatureDectector; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var FeaturePatcher = (function () { function FeaturePatcher() { } FeaturePatcher.prototype.patchAll = function () { this.patchJSON(); this.patchForEach(); }; FeaturePatcher.prototype.patchForEach = function () { if (!Array.forEach) { Array.forEach = function (arr, func) { for (var i = 0; i < arr.length; i++) { func.call(arr, arr[i], i, arr); } }; } }; FeaturePatcher.prototype.patchJSON = function () { if (!window["JSON"]) { window["JSON"] = (function () { function JSON() { } JSON.parse = function (sJSON) { return eval('(' + sJSON + ')'); }; JSON.stringify = function (value) { return this.str("", { "": value }); }; JSON.str = function (key, holder) { var i, k, v, length, mind = "", partial, value = holder[key], me = this; if (value && typeof value === "object" && typeof value.toJSON === "function") { value = value.toJSON(key); } switch (typeof value) { case "string": return me.quote(value); case "number": return isFinite(value) ? String(value) : "null"; case "boolean": case "null": return String(value); case "object": if (!value) { return "null"; } partial = []; if (Object.prototype.toString.apply(value) === "[object Array]") { length = value.length; for (i = 0; i < length; i += 1) { partial[i] = me.str(i, value) || "null"; } v = partial.length === 0 ? "[]" : "[" + partial.join(",") + "]"; return v; } for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = me.str(k, value); if (v) { partial.push(me.quote(k) + ":" + v); } } } v = partial.length === 0 ? "{}" : "{" + partial.join(",") + "}"; return v; } }; JSON.quote = function (string) { var me = this; me.rx_escapable.lastIndex = 0; return me.rx_escapable.test(string) ? '"' + string.replace(me.rx_escapable, function (a) { var c = me.meta[a]; return typeof c === "string" ? c : "\\u" + ("0000" + a.charCodeAt(0).toString(16)).slice(-4); }) + '"' : '"' + string + '"'; }; JSON.rx_escapable = new RegExp('[\\\"\\\\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]', "g"); JSON.meta = { "\b": "\\b", " ": "\\t", "\n": "\\n", "\f": "\\f", "\r": "\\r", '"': '\\"', "''": "\\''", "\\": "\\\\" }; return JSON; })(); } }; return FeaturePatcher; })(); RongIMLib.FeaturePatcher = FeaturePatcher; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var ScriptLoader = (function () { function ScriptLoader() { } ScriptLoader.prototype.load = function (src, onLoad, onError) { var script = document.createElement("script"); script.async = true; if (onLoad) { if (script.addEventListener) { script.addEventListener("load", function (event) { var target = event.target || event.srcElement; onLoad(target.src); }, false); } else if (script.readyState) { script.onreadystatechange = function (event) { var target = event.srcElement; onLoad(target.src); }; } } if (onError) { script.onerror = function (event) { var target = event.target || event.srcElement; onError(target.src); }; } (document.head || document.getElementsByTagName("head")[0]).appendChild(script); script.src = src; }; return ScriptLoader; })(); })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var PublicServiceMap = (function () { function PublicServiceMap() { this.publicServiceList = []; } PublicServiceMap.prototype.get = function (publicServiceType, publicServiceId) { for (var i = 0, len = this.publicServiceList.length; i < len; i++) { if (this.publicServiceList[i].conversationType == publicServiceType && publicServiceId == this.publicServiceList[i].publicServiceId) { return this.publicServiceList[i]; } } }; PublicServiceMap.prototype.add = function (publicServiceProfile) { var isAdd = true, me = this; for (var i = 0, len = this.publicServiceList.length; i < len; i++) { if (me.publicServiceList[i].conversationType == publicServiceProfile.conversationType && publicServiceProfile.publicServiceId == me.publicServiceList[i].publicServiceId) { this.publicServiceList.unshift(this.publicServiceList.splice(i, 1)[0]); isAdd = false; break; } } if (isAdd) { this.publicServiceList.unshift(publicServiceProfile); } }; PublicServiceMap.prototype.replace = function (publicServiceProfile) { var me = this; for (var i = 0, len = this.publicServiceList.length; i < len; i++) { if (me.publicServiceList[i].conversationType == publicServiceProfile.conversationType && publicServiceProfile.publicServiceId == me.publicServiceList[i].publicServiceId) { me.publicServiceList.splice(i, 1, publicServiceProfile); break; } } }; PublicServiceMap.prototype.remove = function (conversationType, publicServiceId) { var me = this; for (var i = 0, len = this.publicServiceList.length; i < len; i++) { if (me.publicServiceList[i].conversationType == conversationType && publicServiceId == me.publicServiceList[i].publicServiceId) { this.publicServiceList.splice(i, 1); break; } } }; return PublicServiceMap; })(); RongIMLib.PublicServiceMap = PublicServiceMap; /** * 会话工具类。 */ var ConversationMap = (function () { function ConversationMap() { this.conversationList = []; } ConversationMap.prototype.get = function (conversavtionType, targetId) { for (var i = 0, len = this.conversationList.length; i < len; i++) { if (this.conversationList[i].conversationType == conversavtionType && this.conversationList[i].targetId == targetId) { return this.conversationList[i]; } } return null; }; ConversationMap.prototype.add = function (conversation) { var isAdd = true; for (var i = 0, len = this.conversationList.length; i < len; i++) { if (this.conversationList[i].conversationType === conversation.conversationType && this.conversationList[i].targetId === conversation.targetId) { this.conversationList.unshift(this.conversationList.splice(i, 1)[0]); isAdd = false; break; } } if (isAdd) { this.conversationList.unshift(conversation); } }; /** * [replace 替换会话] * 会话数组存在的情况下调用add方法会是当前会话被替换且返回到第一个位置,导致用户本地一些设置失效,所以提供replace方法 */ ConversationMap.prototype.replace = function (conversation) { for (var i = 0, len = this.conversationList.length; i < len; i++) { if (this.conversationList[i].conversationType === conversation.conversationType && this.conversationList[i].targetId === conversation.targetId) { this.conversationList.splice(i, 1, conversation); break; } } }; ConversationMap.prototype.remove = function (conversation) { for (var i = 0, len = this.conversationList.length; i < len; i++) { if (this.conversationList[i].conversationType === conversation.conversationType && this.conversationList[i].targetId === conversation.targetId) { this.conversationList.splice(i, 1); break; } } }; return ConversationMap; })(); RongIMLib.ConversationMap = ConversationMap; var CheckParam = (function () { function CheckParam() { } CheckParam.getInstance = function () { if (!CheckParam._instance) { CheckParam._instance = new CheckParam(); } return CheckParam._instance; }; CheckParam.prototype.logger = function (code, funcName, msg) { RongIMLib.RongIMClient.logger({ code: code, funcName: funcName, msg: msg }); }; CheckParam.prototype.check = function (f, position, d, c) { if (RongIMLib.RongIMClient._dataAccessProvider || d) { for (var g = 0, e = c.length; g < e; g++) { if (!new RegExp(this.getType(c[g])).test(f[g])) { // throw new Error("The index of " + g + " parameter was wrong type " + this.getType(c[g]) + " [" + f[g] + "] -> position:" + position); var msg = "第" + (g + 1) + "个参数错误, 错误类型:" + this.getType(c[g]) + " [" + f[g] + "] -> 位置:" + position; this.logger("-3", position, msg); } } } else { var msg = "该参数不正确或尚未实例化RongIMClient -> 位置:" + position; this.logger("-4", position, msg); } }; CheckParam.prototype.getType = function (str) { var temp = Object.prototype.toString.call(str).toLowerCase(); return temp.slice(8, temp.length - 1); }; CheckParam.prototype.checkCookieDisable = function () { document.cookie = "checkCookie=1"; var arr = document.cookie.match(new RegExp("(^| )checkCookie=([^;]*)(;|$)")), isDisable = false; if (!arr) { isDisable = true; } document.cookie = "checkCookie=1;expires=Thu, 01-Jan-1970 00:00:01 GMT"; return isDisable; }; return CheckParam; })(); RongIMLib.CheckParam = CheckParam; var LimitableMap = (function () { function LimitableMap(limit) { this.map = {}; this.keys = []; this.limit = limit || 10; } LimitableMap.prototype.set = function (key, value) { this.map[key] = value; }; LimitableMap.prototype.get = function (key) { return this.map[key] || 0; }; LimitableMap.prototype.remove = function (key) { delete this.map[key]; }; return LimitableMap; })(); RongIMLib.LimitableMap = LimitableMap; var MemoryCache = (function () { function MemoryCache() { this.cache = {}; } MemoryCache.prototype.set = function (key, value) { this.cache[key] = value; }; MemoryCache.prototype.get = function (key) { return this.cache[key]; }; MemoryCache.prototype.remove = function (key) { delete this.cache[key]; }; return MemoryCache; })(); RongIMLib.MemoryCache = MemoryCache; var RongAjax = (function () { function RongAjax(options) { var me = this; me.xmlhttp = null; me.options = options; var hasCORS = typeof XMLHttpRequest !== "undefined" && "withCredentials" in new XMLHttpRequest(); if ("undefined" != typeof XMLHttpRequest && hasCORS) { me.xmlhttp = new XMLHttpRequest(); } else if ("undefined" != typeof XDomainRequest) { me.xmlhttp = new XDomainRequest(); } else { me.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } } RongAjax.prototype.send = function (callback) { var me = this; me.options.url || (me.options.url = "http://upload.qiniu.com/putb64/-1"); me.xmlhttp.onreadystatechange = function () { if (me.xmlhttp.readyState == 4) { if (me.options.type) { callback(); } else { callback(JSON.parse(me.xmlhttp.responseText.replace(/'/g, '"'))); } } }; me.xmlhttp.open("POST", me.options.url, true); me.xmlhttp.withCredentials = false; if ("setRequestHeader" in me.xmlhttp) { if (me.options.type) { me.xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=utf-8"); } else { me.xmlhttp.setRequestHeader("Content-type", "application/octet-stream"); me.xmlhttp.setRequestHeader('Authorization', "UpToken " + me.options.token); } } me.xmlhttp.send(me.options.type ? "appKey=" + me.options.appKey + "&deviceId=" + me.options.deviceId + "×tamp=" + me.options.timestamp + "&deviceInfo=" + me.options.deviceInfo + "&privateInfo=" + JSON.stringify(me.options.privateInfo) : me.options.base64); }; return RongAjax; })(); RongIMLib.RongAjax = RongAjax; var RongUtil = (function () { function RongUtil() { } RongUtil.noop = function () { }; RongUtil.isEmpty = function (obj) { var empty = true; for (var key in obj) { empty = false; break; } return empty; }; RongUtil.MD5 = function (str, key, raw) { return md5(str, key, raw); }; RongUtil.isObject = function (obj) { return Object.prototype.toString.call(obj) == '[object Object]'; }; RongUtil.isArray = function (array) { return Object.prototype.toString.call(array) == '[object Array]'; }; RongUtil.isString = function (array) { return Object.prototype.toString.call(array) == '[object String]'; }; RongUtil.isFunction = function (fun) { return Object.prototype.toString.call(fun) == '[object Function]'; }; ; RongUtil.isUndefined = function (str) { return Object.prototype.toString.call(str) == '[object Undefined]'; }; ; RongUtil.isEqual = function (a, b) { return a === b; }; ; RongUtil.indexOf = function (arrs, item) { var index = -1; for (var i = 0; i < arrs.length; i++) { if (item === arrs[i]) { index = i; break; } } return index; }; RongUtil.stringFormat = function (tmpl, vals) { for (var i = 0, len = vals.length; i < len; i++) { var val = vals[i], reg = new RegExp("\\{" + (i) + "\\}", "g"); tmpl = tmpl.replace(reg, val); } return tmpl; }; RongUtil.tplEngine = function (temp, data, regexp) { if (!(Object.prototype.toString.call(data) === "[object Array]")) { data = [data]; } var ret = []; for (var i = 0, j = data.length; i < j; i++) { ret.push(replaceAction(data[i])); } return ret.join(""); function replaceAction(object) { return temp.replace(regexp || (/{([^}]+)}/g), function (match, name) { if (match.charAt(0) == '\\') { return match.slice(1); } return (object[name] != undefined) ? object[name] : '{' + name + '}'; }); } }; ; RongUtil.forEach = function (obj, callback) { callback = callback || RongUtil.noop; var loopObj = function () { for (var key in obj) { if (obj.hasOwnProperty(key)) { callback(obj[key], key, obj); } } }; var loopArr = function () { for (var i = 0, len = obj.length; i < len; i++) { callback(obj[i], i); } }; if (RongUtil.isObject(obj)) { loopObj(); } if (RongUtil.isArray(obj)) { loopArr(); } }; RongUtil.extend = function (source, target, callback, force) { RongUtil.forEach(source, function (val, key) { var hasProto = (key in target); if (force && hasProto) { target[key] = val; } if (!hasProto) { target[key] = val; } }); return target; }; RongUtil.createXHR = function () { var item = { XMLHttpRequest: function () { return new XMLHttpRequest(); }, XDomainRequest: function () { return new XDomainRequest(); }, ActiveXObject: function () { return new ActiveXObject('Microsoft.XMLHTTP'); } }; var isXHR = (typeof XMLHttpRequest == 'function'); var isXDR = (typeof XDomainRequest == 'function'); var key = isXHR ? 'XMLHttpRequest' : isXDR ? 'XDomainRequest' : 'ActiveXObject'; return item[key](); }; RongUtil.request = function (opts) { var url = opts.url; var success = opts.success; var error = opts.error; var method = opts.method || 'GET'; var xhr = RongUtil.createXHR(); xhr.onreadystatechange = function () { if (xhr.readyState == 4) { var status = xhr.status; if (status == 200) { success(xhr.responseText); } else { error(status, xhr.responseText); } } }; xhr.open(method, url, true); xhr.send(null); return xhr; }; RongUtil.formatProtoclPath = function (config) { var path = config.path; var protocol = config.protocol; var tmpl = config.tmpl || '{0}{1}'; var sub = config.sub; var flag = '://'; var index = path.indexOf(flag); var hasProtocol = (index > -1); if (hasProtocol) { index += flag.length; path = path.substring(index); } if (sub) { index = path.indexOf('/'); var hasPath = (index > -1); if (hasPath) { path = path.substr(0, index); } } return RongUtil.stringFormat(tmpl, [protocol, path]); }; ; RongUtil.supportLocalStorage = function () { var support = false; if (typeof localStorage == 'object') { try { var key = 'RC_TMP_KEY', value = 'RC_TMP_VAL'; localStorage.setItem(key, value); var localVal = localStorage.getItem(key); if (localVal == value) { support = true; } } catch (err) { console.log('localStorage is disabled.'); } } return support; }; /* //返回新引用,不破坏原始对象 rename({n: 'martin'}, {n: 'name'}); => {name: 'martin'} rename([{n: 'martin'}, {a: 18}], {n: 'name', a: 'age'}); => [{name: 'martin'}, {age: 18}] */ RongUtil.rename = function (origin, newNames) { var isObject = RongUtil.isObject(origin); if (isObject) { origin = [origin]; } origin = JSON.parse(JSON.stringify(origin)); var updateProperty = function (val, key, obj) { delete obj[key]; key = newNames[key]; obj[key] = val; }; RongUtil.forEach(origin, function (item) { RongUtil.forEach(item, function (val, key, obj) { var isRename = (key in newNames); (isRename ? updateProperty : RongUtil.noop)(val, key, obj); }); }); return isObject ? origin[0] : origin; }; RongUtil.some = function (arrs, callback) { var has = false; for (var i = 0, len = arrs.length; i < len; i++) { if (callback(arrs[i])) { has = true; break; } } return has; }; RongUtil.keys = function (obj) { var props = []; for (var key in obj) { props.push(key); } return props; }; RongUtil.isNumber = function (num) { return Object.prototype.toString.call(num) == '[object Number]'; }; RongUtil.getTimestamp = function () { var date = new Date(); return date.getTime(); }; RongUtil.isSupportRequestHeaders = function () { var userAgent = navigator.userAgent; var isIE = window.ActiveXObject || 'ActiveXObject' in window; if (isIE) { var reIE = new RegExp('MSIE (\\d+\\.\\d+);'); reIE.test(userAgent); var fIEVersion = parseFloat(RegExp['$1']); return fIEVersion > 9; } return true; }; return RongUtil; })(); RongIMLib.RongUtil = RongUtil; /* var observer = new RongObserver(); observer.watch({ key: 'key', func: function(entity){ } }); */ var RongObserver = (function () { function RongObserver() { this.watchers = {}; } RongObserver.prototype.genUId = function (key) { var time = new Date().getTime(); return [key, time].join('_'); }; RongObserver.prototype.watch = function (params) { var me = this; var key = params.key; var multiple = params.multiple; key = RongUtil.isArray(key) ? key : [key]; var func = params.func; RongUtil.forEach(key, function (k) { k = multiple ? me.genUId(k) : k; me.watchers[k] = func; }); }; RongObserver.prototype.notify = function (params) { var me = this; var key = params.key; var entity = params.entity; for (var k in me.watchers) { var isNotify = (k.indexOf(key) == 0); if (isNotify) { me.watchers[k](entity); } } }; RongObserver.prototype.remove = function () { }; return RongObserver; })(); RongIMLib.RongObserver = RongObserver; var Observer = (function () { function Observer() { this.observers = []; } Observer.prototype.add = function (observer, force) { if (force) { this.observers = [observer]; } this.observers.push(observer); }; Observer.prototype.clear = function () { this.observers = []; }; Observer.prototype.emit = function (data) { RongUtil.forEach(this.observers, function (observer) { observer(data); }); }; return Observer; })(); RongIMLib.Observer = Observer; var Timer = (function () { function Timer(config) { this.timeout = 0; this.timers = []; this.timeout = config.timeout; } Timer.prototype.resume = function (callback) { var timer = setTimeout(callback, this.timeout); this.timers.push(timer); }; Timer.prototype.pause = function () { RongUtil.forEach(this.timers, function (timer) { clearTimeout(timer); }); }; return Timer; })(); RongIMLib.Timer = Timer; var IndexTools = (function () { function IndexTools(config) { this.items = []; this.index = 0; this.onwheel = function () { }; this.items = config.items; this.onwheel = config.onwheel; } IndexTools.prototype.get = function () { var context = this; var items = context.items; var index = context.index; var isWheel = index >= items.length; if (isWheel) { context.onwheel(); } return isWheel ? 0 : index; }; IndexTools.prototype.add = function () { this.index += 1; }; return IndexTools; })(); RongIMLib.IndexTools = IndexTools; var InnerUtil = (function () { function InnerUtil() { } InnerUtil.getUId = function (token) { return md5(token).slice(8, 16); }; return InnerUtil; })(); RongIMLib.InnerUtil = InnerUtil; })(RongIMLib || (RongIMLib = {})); /* 说明: 请勿修改 header.js 和 footer.js 用途: 自动拼接暴露方式 命令: grunt release 中 concat */ return RongIMLib; }); ================================================ FILE: api-test-v2/lib/js/RongIMLib-2.5.3.js ================================================ /* 说明: 请勿修改 header.js 和 footer.js 用途: 自动拼接暴露方式 命令: grunt release 中 concat 修改: 只走 wss 和 https */ (function(global, factory) { if (typeof exports === 'object' && typeof module !== 'undefined') { module.exports = factory(); } else if (typeof define === 'function' && (define.amd || define.cmd)) { define(factory); } else { var tempIMLib = factory(); var tempClient = tempIMLib.RongIMClient; var isExists = (!!global.RongIMLib); if (isExists) { var currentClient = RongIMLib.RongIMClient || {}; for(var key in currentClient){ tempClient[key] = currentClient[key]; } } global.RongIMLib = tempIMLib; global.RongIMClient = tempClient; } })(window, function(){ // {WebStart} WebSDK 内容开始的标识, 方便小程序 SDK 定位 var Polling = { SetUserStatusInput: function(){ var a = {}; this.setStatus = function(b){ a.status = b; }; this.toArrayBuffer = function(){ return a; }; }, SetUserStatusOutput: function(){ var a = {}; this.setNothing = function(b){ a.nothing = b; }; this.toArrayBuffer = function(){ return a; }; }, GetUserStatusInput: function(){ var a = {}; this.setNothing = function(b){ a.nothing = b; }; this.toArrayBuffer = function(){ return a; }; }, GetUserStatusOutput: function(){ var a = {}; this.setStatus = function(b){ a.status = b; }; this.setSubUserId = function(b){ a.subUserId = b; }; this.toArrayBuffer = function(){ return a; }; }, VoipDynamicInput: function(){ var a = {}; this.setEngineType = function(b){ a.engineType = b; }; this.setChannelName = function(b){ a.channelName = b; }; this.setChannelExtra = function(b){ a.channelExtra = b; }; this.toArrayBuffer = function(){ return a; }; }, VoipDynamicOutput: function(){ var a = {}; this.setDynamicKey = function(b){ a.dynamicKey = b; }; this.toArrayBuffer = function(){ return a; }; }, SubUserStatusInput: function(){ var a = {}; this.setUserid = function(b){ a.userid = b; }; this.toArrayBuffer = function(){ return a; }; }, SubUserStatusOutput: function(){ var a = {}; this.setNothing = function(b){ a.nothing = b; }; this.toArrayBuffer = function(){ return a; }; }, CleanHisMsgInput: function(){ var a = {}; this.setTargetId = function(b){ a.targetId = b; }; this.setDataTime = function(b){ a.dataTime = b; }; this.setConversationType = function(b){ a.conversationType = b; }; this.toArrayBuffer = function(){ return a; }; }, DeleteMsgInput:function(){ var a = {}; this.setType = function(b){ a.type = b; }; this.setConversationId = function(b){ a.conversationId = b; }; this.setMsgs = function(b){ a.msgs = b; }; this.toArrayBuffer = function () { return a; } }, DeleteMsg:function(){ var a = {}; this.setMsgId = function(b){ a.msgId = b; }; this.setMsgDataTime = function(b){ a.msgDataTime = b; }; this.setDirect = function(b){ a.direct = b; }; this.toArrayBuffer = function () { return a; } }, DeleteMsgOutput:function(){ var a = {}; this.setNothing = function(b){ a.nothing = b; }; this.toArrayBuffer = function () { return a; } }, SearchMpInput:function(){ var a = {}; this.setType = function (b) { a.type = b; }; this.setId = function (b) { a.id = b; }; this.toArrayBuffer = function () { return a; } }, SearchMpOutput:function(){ var a = {}; this.setNothing = function (b) { a.nothing = b; }; this.setInfo = function (b) { a.info = b; }; this.toArrayBuffer = function () { return a; } }, MpInfo:function(){ var a = {}; this.setMpid = function(b){ a.mpid = b; }; this.setName = function(b){ a.name = b; }; this.setType = function(b){ a.type = b; }; this.setTime = function(b){ a.time = b; }; this.setPortraitUri = function(b){ a.portraitUrl = b; }; this.setExtra = function(b){ a.extra = b; }; this.toArrayBuffer = function () { return a; } }, PullMpInput:function(){ var a = {}; this.setMpid = function(b){ a.mpid = b; }; this.setTime = function(b){ a.time = b; }; this.toArrayBuffer = function () { return a; }; }, PullMpOutput:function(){ var a = {}; this.setStatus = function(b){ a.status = b; } this.setInfo = function(b){ a.info = b; }; this.toArrayBuffer = function () { return a; }; }, MPFollowInput:function(){ var a = {}; this.setId = function(b){ a.id = b; }; this.toArrayBuffer = function () { return a; }; }, MPFollowOutput:function(){ var a = {}; this.setNothing = function(b){ a.nothing = b; }; this.setInfo = function(b){ a.info = b; }; this.toArrayBuffer = function () { return a; }; }, NotifyMsg: function () { var a = {}; this.setType = function (b) { a.type = b; }; this.setTime = function (b) { a.time = b; }; this.setChrmId = function(b){ a.chrmId = b; }; this.toArrayBuffer = function () { return a; }; }, SyncRequestMsg: function () { var a = {}; this.setSyncTime = function (b) { a.syncTime = b || 0; }; this.setIspolling = function (b) { a.ispolling = !!b; }; this.setIsweb = function (b) { a.isweb = !!b; }; this.setIsPullSend = function (b) { a.isPullSend = !!b; }; this.setSendBoxSyncTime = function (b) { a.sendBoxSyncTime = b; }; this.toArrayBuffer = function () { return a; }; }, UpStreamMessage: function () { var a = {}; this.setSessionId = function (b) { a.sessionId = b }; this.setClassname = function (b) { a.classname = b }; this.setContent = function (b) { if (b) a.content = b; }; this.setPushText = function (b) { a.pushText = b }; this.setUserId = function(b){ a.userId = b; }; this.setConfigFlag = function (b) { a.configFlag = b; }; this.setAppData = function(b){ a.appData = b; }; this.toArrayBuffer = function () { return a }; }, DownStreamMessages: function () { var a = {}; this.setList = function (b) { a.list = b }; this.setSyncTime = function (b) { a.syncTime = b; }; this.setFinished = function(b){ a.finished = b; }; this.toArrayBuffer = function () { return a }; }, DownStreamMessage: function () { var a = {}; this.setFromUserId = function (b) { a.fromUserId = b }; this.setType = function (b) { a.type = b }; this.setGroupId = function (b) { a.groupId = b }; this.setClassname = function (b) { a.classname = b }; this.setContent = function (b) { if (b) a.content = b }; this.setDataTime = function (b) { a.dataTime = b; }; this.setStatus = function (b) { a.status = b; }; this.setMsgId = function (b) { a.msgId = b; }; this.toArrayBuffer = function () { return a; }; }, CreateDiscussionInput: function () { var a = {}; this.setName = function (b) { a.name = b }; this.toArrayBuffer = function () { return a } }, CreateDiscussionOutput: function () { var a = {}; this.setId = function (b) { a.id = b }; this.toArrayBuffer = function () { return a }; }, ChannelInvitationInput: function () { var a = {}; this.setUsers = function (b) { a.users = b }; this.toArrayBuffer = function () { return a }; }, LeaveChannelInput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b }; this.toArrayBuffer = function () { return a }; }, QueryChatroomInfoInput:function(){ var a = {}; this.setCount = function (b) { a.count = b; }; this.setOrder = function (b) { a.order = b; }; this.toArrayBuffer = function () { return a }; }, QueryChatroomInfoOutput:function(){ var a = {}; this.setUserTotalNums = function (b) { a.userTotalNums = b; }; this.setUserInfos = function (b) { a.userInfos = b; }; this.toArrayBuffer = function () { return a; }; }, ChannelEvictionInput: function () { var a = {}; this.setUser = function (b) { a.user = b }; this.toArrayBuffer = function () { return a }; }, RenameChannelInput: function () { var a = {}; this.setName = function (b) { a.name = b }; this.toArrayBuffer = function () { return a } }, ChannelInfoInput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b }; this.toArrayBuffer = function () { return a } }, ChannelInfoOutput: function () { var a = {}; this.setType = function (b) { a.type = b }; this.setChannelId = function (b) { a.channelId = b }; this.setChannelName = function (b) { a.channelName = b }; this.setAdminUserId = function (b) { a.adminUserId = b }; this.setFirstTenUserIds = function (b) { a.firstTenUserIds = b }; this.setOpenStatus = function (b) { a.openStatus = b }; this.toArrayBuffer = function () { return a } }, ChannelInfosInput: function () { var a = {}; this.setPage = function (b) { a.page = b }; this.setNumber = function (b) { a.number = b }; this.toArrayBuffer = function () { return a }; }, ChannelInfosOutput: function () { var a = {}; this.setChannels = function (b) { a.channels = b }; this.setTotal = function (b) { a.total = b }; this.toArrayBuffer = function () { return a }; }, MemberInfo: function () { var a = {}; this.setUserId = function (b) { a.userId = b }; this.setUserName = function (b) { a.userName = b }; this.setUserPortrait = function (b) { a.userPortrait = b }; this.setExtension = function (b) { a.extension = b }; this.toArrayBuffer = function () { return a }; }, GroupMembersInput: function () { var a = {}; this.setPage = function (b) { a.page = b }; this.setNumber = function (b) { a.number = b }; this.toArrayBuffer = function () { return a }; }, GroupMembersOutput: function () { var a = {}; this.setMembers = function (b) { a.members = b }; this.setTotal = function (b) { a.total = b }; this.toArrayBuffer = function () { return a }; }, GetUserInfoInput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b }; this.toArrayBuffer = function () { return a }; }, GetUserInfoOutput: function () { var a = {}; this.setUserId = function (b) { a.userId = b }; this.setUserName = function (b) { a.userName = b }; this.setUserPortrait = function (b) { a.userPortrait = b }; this.toArrayBuffer = function () { return a }; }, GetSessionIdInput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b }; this.toArrayBuffer = function () { return a }; }, GetSessionIdOutput: function () { var a = {}; this.setSessionId = function (b) { a.sessionId = b }; this.toArrayBuffer = function () { return a }; }, GetQNupTokenInput: function () { var a = {}; this.setType = function (b) { a.type = b; } this.toArrayBuffer = function () { return a } }, GetQNupTokenOutput: function () { var a = {}; this.setDeadline = function (b) { a.deadline = b }; this.setToken = function (b) { a.token = b; }; this.toArrayBuffer = function () { return a } }, GetQNdownloadUrlInput: function () { var a = {}; this.setType = function (b) { a.type = b; }; this.setKey = function (b) { a.key = b; }; this.setFileName = function(b){ a.fileName = b; }; this.toArrayBuffer = function () { return a } }, GetQNdownloadUrlOutput: function () { var a = {}; this.setDownloadUrl = function (b) { a.downloadUrl = b; }; this.toArrayBuffer = function () { return a } }, Add2BlackListInput: function () { var a = {}; this.setUserId = function (b) { a.userId = b; }; this.toArrayBuffer = function () { return a } }, RemoveFromBlackListInput: function () { var a = {}; this.setUserId = function (b) { a.userId = b; }; this.toArrayBuffer = function () { return a } }, QueryBlackListInput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b; }; this.toArrayBuffer = function () { return a } }, QueryBlackListOutput: function () { var a = {}; this.setUserIds = function (b) { a.userIds = b; }; this.toArrayBuffer = function () { return a } }, BlackListStatusInput: function () { var a = {}; this.setUserId = function (b) { a.userId = b; }; this.toArrayBuffer = function () { return a } }, BlockPushInput: function () { var a = {}; this.setBlockeeId = function (b) { a.blockeeId = b; }; this.toArrayBuffer = function () { return a } }, ModifyPermissionInput: function () { var a = {}; this.setOpenStatus = function (b) { a.openStatus = b; }; this.toArrayBuffer = function () { return a }; }, GroupInput: function () { var a = {}; this.setGroupInfo = function (b) { for (var i = 0, arr = []; i < b.length; i++) { arr.push({id: b[i].getContent().id, name: b[i].getContent().name}) } a.groupInfo = arr; }; this.toArrayBuffer = function () { return a }; }, GroupOutput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b; }; this.toArrayBuffer = function () { return a }; }, GroupInfo: function () { var a = {}; this.setId = function (b) { a.id = b; }; this.setName = function (b) { a.name = b; }; this.getContent = function () { return a; }; this.toArrayBuffer = function () { return a }; }, GroupHashInput: function () { var a = {}; this.setUserId = function (b) { a.userId = b; }; this.setGroupHashCode = function (b) { a.groupHashCode = b; }; this.toArrayBuffer = function () { return a }; }, GroupHashOutput: function () { var a = {}; this.setResult = function (b) { a.result = b; }; this.toArrayBuffer = function () { return a }; }, ChrmInput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b; }; this.toArrayBuffer = function () { return a }; }, ChrmOutput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b; }; this.toArrayBuffer = function () { return a }; }, ChrmPullMsg: function () { var a = {}; this.setSyncTime = function (b) { a.syncTime = b }; this.setCount = function (b) { a.count = b; }; this.toArrayBuffer = function () { return a }; }, RelationsInput: function () { var a = {}; this.setType = function (b) { a.type = b; }; this.setMsg = function(b){ a.msg = b; }; this.setCount = function(b){ a.count = b; }; this.toArrayBuffer = function () { return a }; }, RelationsOutput: function () { var a = {}; this.setInfo = function (b) { a.info = b; }; this.toArrayBuffer = function () { return a } }, RelationInfo: function () { var a = {}; this.setType = function (b) { a.type = b; }; this.setUserId = function (b) { a.userId = b; }; this.setMsg = function(b){ a.msg = b; }; this.toArrayBuffer = function () { return a } }, HistoryMessageInput: function () { var a={}; this.setTargetId=function(b){ a.targetId=b; }; this.setDataTime=function(b){ a.dataTime=b; }; this.setSize=function(b){ a.size=b; }; this.toArrayBuffer = function () { return a } }, HistoryMessagesOuput: function () { var a={}; this.setList=function(b){ a.list=b; }; this.setSyncTime=function(b){ a.syncTime=b; }; this.setHasMsg=function(b){ a.hasMsg=b; }; this.toArrayBuffer = function () { return a } }, HistoryMsgInput: function(){ var a = {}; this.setTargetId = function(b){ a.targetId = b; }; this.setTime = function(b){ a.time = b; }; this.setCount = function(b){ a.count = b; }; this.setOrder = function(b){ a.order = b; }; this.toArrayBuffer = function(){ return a; }; }, HistoryMsgOuput: function(){ var a = {}; this.setList = function(b){ a.list = b; }; this.setSyncTime = function(b){ a.syncTime = b; }; this.setHasMsg = function(b){ a.hasMsg = b; }; this.toArrayBuffer = function(){ return a; }; }, RtcQueryListInput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setOrder = function (b) { a.order = b; }; }, RtcKeyDeleteInput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setKey = function (b) { a.key = b; }; }, RtcValueInfo: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setKey = function (b) { a.key = b; }; this.setValue = function (b) { a.value = b; }; }, // RtcUserInfo: function () { // var a = {}; // }, RtcUserListOutput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setList = function (b) { a.list = b; }; this.setToken = function (b) { a.token = b; }; }, RtcRoomInfoOutput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setRoomId = function (b) { a.roomId = b; }; this.setRoomData = function (b) { a.roomData = b; }; this.setUserCount = function (b) { a.userCount = b; }; this.setList = function (b) { a.list = b; } }, RtcInput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setRoomType = function (b) { a.roomType = b; }; this.setBroadcastType = function (b) { a.broadcastType = b; } }, // RtcQryInput: function () { // var a = {}; // }, RtcQryOutput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setOutInfo = function (b) { a.outInfo = b; }; }, // RtcDelDataInput: function () { // var a = {}; // }, RtcDataInput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setInterior = function (b) { a.interior = b; }; this.setTarget = function (b) { a.target = b; }; this.setKey = function (b) { a.key = b; }; this.setObjectName = function (b) { a.objectName = b; }; this.setContent = function (b) { a.content = b; }; }, RtcSetDataInput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setInterior = function (b) { a.interior = b; }; this.setTarget = function (b) { a.target = b; }; this.setKey = function (b) { a.key = b; }; this.setValue = function (b) { a.value = b; }; this.setObjectName = function (b) { a.objectName = b; }; this.setContent = function (b) { a.content = b; }; }, RtcOutput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setNothing = function (b) { a.nothing = b; }; }, RtcTokenOutput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setRtcToken = function (b) { a.rtcToken = b; } }, /** * 聊天室 KV 存储 */ ChrmNotifyMsg: function () { var a = {}; this.toArrayBuffer = function () { return a; }; this.setType = function (b) { a.type = b; }; this.setTime = function (b) { a.time = b; }; this.setChrmId = function (b) { a.chrmId = b; }; }, ChrmKVEntity: function () { var a = {}; this.toArrayBuffer = function () { return a; }; this.setKey = function (key) { a.key = key; }; this.setValue = function (value) { a.value = value; }; this.setStatus = function (b) { a.status = b; }; this.setTimestamp = function (b) { a.timestamp = b; }; this.setUid = function (b) { a.uid = b; }; }, SetChrmKV: function () { var a = {}; this.toArrayBuffer = function () { return a; }; this.setEntry = function (b) { a.entry = b; }; this.setNotification = function (b) { a.notification = b.toArrayBuffer(); }; this.setBNotify = function (b) { a.bNotify = b; }; this.setType = function (b) { a.type = b; }; }, ChrmKVOutput: function () { var a = {}; this.toArrayBuffer = function () { return a; }; this.setEntries = function (b) { this.entries = b; }; this.setBFullUpdate = function (b) { this.bFullUpdate = b; }; this.setSyncTime = function (b) { this.syncTime = b; }; }, QueryChrmKV: function () { var a = {}; this.toArrayBuffer = function () { return a; }; this.setTimestamp = function (b) { a.timestamp = b; }; }, DeleteChrmKV: function () { var a = {}; this.toArrayBuffer = function () { return a; }; this.setEntry = function (b) { a.entry = b; }; this.setBNotify = function (b) { a.bNotify = b; }; this.setNotification = function (b) { a.notification = b; }; this.setType = function (b) { a.type = b; }; } }; for (var f in Polling) { Polling[f].decode = function (b) { var back = {}, val = JSON.parse(b) || eval("(" + b + ")"); for (var i in val) { back[i]=val[i]; back["get"+ i.charAt(0).toUpperCase()+i.slice(1)]=function(){ return val[i]; } } return back; } } /* * JavaScript MD5 * https://github.com/blueimp/JavaScript-MD5 * * Copyright 2011, Sebastian Tschan * https://blueimp.net * * Licensed under the MIT license: * http://www.opensource.org/licenses/MIT * * Based on * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message * Digest Algorithm, as defined in RFC 1321. * Version 2.2 Copyright (C) Paul Johnston 1999 - 2009 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet * Distributed under the BSD License * See http://pajhome.org.uk/crypt/md5 for more info. */ /*jslint bitwise: true */ /*global unescape, define, module */ var md5 = (function () { 'use strict'; /* * Add integers, wrapping at 2^32. This uses 16-bit operations internally * to work around bugs in some JS interpreters. */ function safe_add(x, y) { var lsw = (x & 0xFFFF) + (y & 0xFFFF), msw = (x >> 16) + (y >> 16) + (lsw >> 16); return (msw << 16) | (lsw & 0xFFFF); } /* * Bitwise rotate a 32-bit number to the left. */ function bit_rol(num, cnt) { return (num << cnt) | (num >>> (32 - cnt)); } /* * These functions implement the four basic operations the algorithm uses. */ function md5_cmn(q, a, b, x, s, t) { return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s), b); } function md5_ff(a, b, c, d, x, s, t) { return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t); } function md5_gg(a, b, c, d, x, s, t) { return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t); } function md5_hh(a, b, c, d, x, s, t) { return md5_cmn(b ^ c ^ d, a, b, x, s, t); } function md5_ii(a, b, c, d, x, s, t) { return md5_cmn(c ^ (b | (~d)), a, b, x, s, t); } /* * Calculate the MD5 of an array of little-endian words, and a bit length. */ function binl_md5(x, len) { /* append padding */ x[len >> 5] |= 0x80 << (len % 32); x[(((len + 64) >>> 9) << 4) + 14] = len; var i, olda, oldb, oldc, oldd, a = 1732584193, b = -271733879, c = -1732584194, d = 271733878; for (i = 0; i < x.length; i += 16) { olda = a; oldb = b; oldc = c; oldd = d; a = md5_ff(a, b, c, d, x[i], 7, -680876936); d = md5_ff(d, a, b, c, x[i + 1], 12, -389564586); c = md5_ff(c, d, a, b, x[i + 2], 17, 606105819); b = md5_ff(b, c, d, a, x[i + 3], 22, -1044525330); a = md5_ff(a, b, c, d, x[i + 4], 7, -176418897); d = md5_ff(d, a, b, c, x[i + 5], 12, 1200080426); c = md5_ff(c, d, a, b, x[i + 6], 17, -1473231341); b = md5_ff(b, c, d, a, x[i + 7], 22, -45705983); a = md5_ff(a, b, c, d, x[i + 8], 7, 1770035416); d = md5_ff(d, a, b, c, x[i + 9], 12, -1958414417); c = md5_ff(c, d, a, b, x[i + 10], 17, -42063); b = md5_ff(b, c, d, a, x[i + 11], 22, -1990404162); a = md5_ff(a, b, c, d, x[i + 12], 7, 1804603682); d = md5_ff(d, a, b, c, x[i + 13], 12, -40341101); c = md5_ff(c, d, a, b, x[i + 14], 17, -1502002290); b = md5_ff(b, c, d, a, x[i + 15], 22, 1236535329); a = md5_gg(a, b, c, d, x[i + 1], 5, -165796510); d = md5_gg(d, a, b, c, x[i + 6], 9, -1069501632); c = md5_gg(c, d, a, b, x[i + 11], 14, 643717713); b = md5_gg(b, c, d, a, x[i], 20, -373897302); a = md5_gg(a, b, c, d, x[i + 5], 5, -701558691); d = md5_gg(d, a, b, c, x[i + 10], 9, 38016083); c = md5_gg(c, d, a, b, x[i + 15], 14, -660478335); b = md5_gg(b, c, d, a, x[i + 4], 20, -405537848); a = md5_gg(a, b, c, d, x[i + 9], 5, 568446438); d = md5_gg(d, a, b, c, x[i + 14], 9, -1019803690); c = md5_gg(c, d, a, b, x[i + 3], 14, -187363961); b = md5_gg(b, c, d, a, x[i + 8], 20, 1163531501); a = md5_gg(a, b, c, d, x[i + 13], 5, -1444681467); d = md5_gg(d, a, b, c, x[i + 2], 9, -51403784); c = md5_gg(c, d, a, b, x[i + 7], 14, 1735328473); b = md5_gg(b, c, d, a, x[i + 12], 20, -1926607734); a = md5_hh(a, b, c, d, x[i + 5], 4, -378558); d = md5_hh(d, a, b, c, x[i + 8], 11, -2022574463); c = md5_hh(c, d, a, b, x[i + 11], 16, 1839030562); b = md5_hh(b, c, d, a, x[i + 14], 23, -35309556); a = md5_hh(a, b, c, d, x[i + 1], 4, -1530992060); d = md5_hh(d, a, b, c, x[i + 4], 11, 1272893353); c = md5_hh(c, d, a, b, x[i + 7], 16, -155497632); b = md5_hh(b, c, d, a, x[i + 10], 23, -1094730640); a = md5_hh(a, b, c, d, x[i + 13], 4, 681279174); d = md5_hh(d, a, b, c, x[i], 11, -358537222); c = md5_hh(c, d, a, b, x[i + 3], 16, -722521979); b = md5_hh(b, c, d, a, x[i + 6], 23, 76029189); a = md5_hh(a, b, c, d, x[i + 9], 4, -640364487); d = md5_hh(d, a, b, c, x[i + 12], 11, -421815835); c = md5_hh(c, d, a, b, x[i + 15], 16, 530742520); b = md5_hh(b, c, d, a, x[i + 2], 23, -995338651); a = md5_ii(a, b, c, d, x[i], 6, -198630844); d = md5_ii(d, a, b, c, x[i + 7], 10, 1126891415); c = md5_ii(c, d, a, b, x[i + 14], 15, -1416354905); b = md5_ii(b, c, d, a, x[i + 5], 21, -57434055); a = md5_ii(a, b, c, d, x[i + 12], 6, 1700485571); d = md5_ii(d, a, b, c, x[i + 3], 10, -1894986606); c = md5_ii(c, d, a, b, x[i + 10], 15, -1051523); b = md5_ii(b, c, d, a, x[i + 1], 21, -2054922799); a = md5_ii(a, b, c, d, x[i + 8], 6, 1873313359); d = md5_ii(d, a, b, c, x[i + 15], 10, -30611744); c = md5_ii(c, d, a, b, x[i + 6], 15, -1560198380); b = md5_ii(b, c, d, a, x[i + 13], 21, 1309151649); a = md5_ii(a, b, c, d, x[i + 4], 6, -145523070); d = md5_ii(d, a, b, c, x[i + 11], 10, -1120210379); c = md5_ii(c, d, a, b, x[i + 2], 15, 718787259); b = md5_ii(b, c, d, a, x[i + 9], 21, -343485551); a = safe_add(a, olda); b = safe_add(b, oldb); c = safe_add(c, oldc); d = safe_add(d, oldd); } return [a, b, c, d]; } /* * Convert an array of little-endian words to a string */ function binl2rstr(input) { var i, output = ''; for (i = 0; i < input.length * 32; i += 8) { output += String.fromCharCode((input[i >> 5] >>> (i % 32)) & 0xFF); } return output; } /* * Convert a raw string to an array of little-endian words * Characters >255 have their high-byte silently ignored. */ function rstr2binl(input) { var i, output = []; output[(input.length >> 2) - 1] = undefined; for (i = 0; i < output.length; i += 1) { output[i] = 0; } for (i = 0; i < input.length * 8; i += 8) { output[i >> 5] |= (input.charCodeAt(i / 8) & 0xFF) << (i % 32); } return output; } /* * Calculate the MD5 of a raw string */ function rstr_md5(s) { return binl2rstr(binl_md5(rstr2binl(s), s.length * 8)); } /* * Calculate the HMAC-MD5, of a key and some data (raw strings) */ function rstr_hmac_md5(key, data) { var i, bkey = rstr2binl(key), ipad = [], opad = [], hash; ipad[15] = opad[15] = undefined; if (bkey.length > 16) { bkey = binl_md5(bkey, key.length * 8); } for (i = 0; i < 16; i += 1) { ipad[i] = bkey[i] ^ 0x36363636; opad[i] = bkey[i] ^ 0x5C5C5C5C; } hash = binl_md5(ipad.concat(rstr2binl(data)), 512 + data.length * 8); return binl2rstr(binl_md5(opad.concat(hash), 512 + 128)); } /* * Convert a raw string to a hex string */ function rstr2hex(input) { var hex_tab = '0123456789abcdef', output = '', x, i; for (i = 0; i < input.length; i += 1) { x = input.charCodeAt(i); output += hex_tab.charAt((x >>> 4) & 0x0F) + hex_tab.charAt(x & 0x0F); } return output; } /* * Encode a string as utf-8 */ function str2rstr_utf8(input) { return unescape(encodeURIComponent(input)); } /* * Take string arguments and return either raw or hex encoded strings */ function raw_md5(s) { return rstr_md5(str2rstr_utf8(s)); } function hex_md5(s) { return rstr2hex(raw_md5(s)); } function raw_hmac_md5(k, d) { return rstr_hmac_md5(str2rstr_utf8(k), str2rstr_utf8(d)); } function hex_hmac_md5(k, d) { return rstr2hex(raw_hmac_md5(k, d)); } function md5(string, key, raw) { if (!key) { if (!raw) { return hex_md5(string); } return raw_md5(string); } if (!raw) { return hex_hmac_md5(key, string); } return raw_hmac_md5(key, string); } return md5; }()); var RongIMLib; (function (RongIMLib) { (function (MentionedType) { MentionedType[MentionedType["ALL"] = 1] = "ALL"; MentionedType[MentionedType["PART"] = 2] = "PART"; })(RongIMLib.MentionedType || (RongIMLib.MentionedType = {})); var MentionedType = RongIMLib.MentionedType; (function (MethodType) { MethodType[MethodType["CUSTOMER_SERVICE"] = 1] = "CUSTOMER_SERVICE"; MethodType[MethodType["RECALL"] = 2] = "RECALL"; })(RongIMLib.MethodType || (RongIMLib.MethodType = {})); var MethodType = RongIMLib.MethodType; (function (BlacklistStatus) { /** * 在黑名单中。 */ BlacklistStatus[BlacklistStatus["IN_BLACK_LIST"] = 0] = "IN_BLACK_LIST"; /** * 不在黑名单中。 */ BlacklistStatus[BlacklistStatus["NOT_IN_BLACK_LIST"] = 1] = "NOT_IN_BLACK_LIST"; })(RongIMLib.BlacklistStatus || (RongIMLib.BlacklistStatus = {})); var BlacklistStatus = RongIMLib.BlacklistStatus; (function (ConnectionChannel) { ConnectionChannel[ConnectionChannel["XHR_POLLING"] = 0] = "XHR_POLLING"; ConnectionChannel[ConnectionChannel["WEBSOCKET"] = 1] = "WEBSOCKET"; //外部调用 ConnectionChannel[ConnectionChannel["HTTP"] = 0] = "HTTP"; //外部调用 ConnectionChannel[ConnectionChannel["HTTPS"] = 1] = "HTTPS"; })(RongIMLib.ConnectionChannel || (RongIMLib.ConnectionChannel = {})); var ConnectionChannel = RongIMLib.ConnectionChannel; (function (CustomerType) { CustomerType[CustomerType["ONLY_ROBOT"] = 1] = "ONLY_ROBOT"; CustomerType[CustomerType["ONLY_HUMAN"] = 2] = "ONLY_HUMAN"; CustomerType[CustomerType["ROBOT_FIRST"] = 3] = "ROBOT_FIRST"; CustomerType[CustomerType["HUMAN_FIRST"] = 4] = "HUMAN_FIRST"; })(RongIMLib.CustomerType || (RongIMLib.CustomerType = {})); var CustomerType = RongIMLib.CustomerType; (function (GetChatRoomType) { GetChatRoomType[GetChatRoomType["NONE"] = 0] = "NONE"; GetChatRoomType[GetChatRoomType["SQQUENCE"] = 1] = "SQQUENCE"; GetChatRoomType[GetChatRoomType["REVERSE"] = 2] = "REVERSE"; })(RongIMLib.GetChatRoomType || (RongIMLib.GetChatRoomType = {})); var GetChatRoomType = RongIMLib.GetChatRoomType; (function (ConnectionStatus) { /** * 连接成功。 */ ConnectionStatus[ConnectionStatus["CONNECTED"] = 0] = "CONNECTED"; /** * 连接中。 */ ConnectionStatus[ConnectionStatus["CONNECTING"] = 1] = "CONNECTING"; /** * 断开连接。 */ ConnectionStatus[ConnectionStatus["DISCONNECTED"] = 2] = "DISCONNECTED"; /** * 用户账户在其他设备登录,本机会被踢掉线。 */ ConnectionStatus[ConnectionStatus["KICKED_OFFLINE_BY_OTHER_CLIENT"] = 6] = "KICKED_OFFLINE_BY_OTHER_CLIENT"; /** * websocket 连接失败 */ ConnectionStatus[ConnectionStatus["WEBSOCKET_UNAVAILABLE"] = 7] = "WEBSOCKET_UNAVAILABLE"; /** * websocket 报错 */ ConnectionStatus[ConnectionStatus["WEBSOCKET_ERROR"] = 8] = "WEBSOCKET_ERROR"; /** * 网络不可用。 */ ConnectionStatus[ConnectionStatus["NETWORK_UNAVAILABLE"] = 3] = "NETWORK_UNAVAILABLE"; /** * 域名错误 */ ConnectionStatus[ConnectionStatus["DOMAIN_INCORRECT"] = 12] = "DOMAIN_INCORRECT"; /** * appkey 不正确 */ ConnectionStatus[ConnectionStatus["APPKEY_IS_FAKE"] = 20] = "APPKEY_IS_FAKE"; /** * 连接关闭。 */ ConnectionStatus[ConnectionStatus["CONNECTION_CLOSED"] = 4] = "CONNECTION_CLOSED"; /* 互踢次数过多(count > 5),此时可能出现:在其它他设备登陆有 reconnect 逻辑 */ ConnectionStatus[ConnectionStatus["ULTRALIMIT"] = 1101] = "ULTRALIMIT"; /* 开始请求导航 */ ConnectionStatus[ConnectionStatus["REQUEST_NAVI"] = 201] = "REQUEST_NAVI"; /* 请求导航结束 */ ConnectionStatus[ConnectionStatus["RESPONSE_NAVI"] = 202] = "RESPONSE_NAVI"; /* 请求导航失败 */ ConnectionStatus[ConnectionStatus["RESPONSE_NAVI_ERROR"] = 203] = "RESPONSE_NAVI_ERROR"; /* 请求导航超时 */ ConnectionStatus[ConnectionStatus["RESPONSE_NAVI_TIMEOUT"] = 204] = "RESPONSE_NAVI_TIMEOUT"; })(RongIMLib.ConnectionStatus || (RongIMLib.ConnectionStatus = {})); var ConnectionStatus = RongIMLib.ConnectionStatus; (function (ConversationNotificationStatus) { /** * 免打扰状态,关闭对应会话的通知提醒。 */ ConversationNotificationStatus[ConversationNotificationStatus["DO_NOT_DISTURB"] = 0] = "DO_NOT_DISTURB"; /** * 提醒。 */ ConversationNotificationStatus[ConversationNotificationStatus["NOTIFY"] = 1] = "NOTIFY"; })(RongIMLib.ConversationNotificationStatus || (RongIMLib.ConversationNotificationStatus = {})); var ConversationNotificationStatus = RongIMLib.ConversationNotificationStatus; (function (ConversationType) { ConversationType[ConversationType["NONE"] = 0] = "NONE"; ConversationType[ConversationType["PRIVATE"] = 1] = "PRIVATE"; ConversationType[ConversationType["DISCUSSION"] = 2] = "DISCUSSION"; ConversationType[ConversationType["GROUP"] = 3] = "GROUP"; ConversationType[ConversationType["CHATROOM"] = 4] = "CHATROOM"; ConversationType[ConversationType["CUSTOMER_SERVICE"] = 5] = "CUSTOMER_SERVICE"; ConversationType[ConversationType["SYSTEM"] = 6] = "SYSTEM"; //默认关注 MC ConversationType[ConversationType["APP_PUBLIC_SERVICE"] = 7] = "APP_PUBLIC_SERVICE"; //手工关注 MP ConversationType[ConversationType["PUBLIC_SERVICE"] = 8] = "PUBLIC_SERVICE"; })(RongIMLib.ConversationType || (RongIMLib.ConversationType = {})); var ConversationType = RongIMLib.ConversationType; (function (DiscussionInviteStatus) { /** * 开放邀请。 */ DiscussionInviteStatus[DiscussionInviteStatus["OPENED"] = 0] = "OPENED"; /** * 关闭邀请。 */ DiscussionInviteStatus[DiscussionInviteStatus["CLOSED"] = 1] = "CLOSED"; })(RongIMLib.DiscussionInviteStatus || (RongIMLib.DiscussionInviteStatus = {})); var DiscussionInviteStatus = RongIMLib.DiscussionInviteStatus; (function (ErrorCode) { /* 超时 */ ErrorCode[ErrorCode["TIMEOUT"] = -1] = "TIMEOUT"; /** * 未知原因失败。 */ ErrorCode[ErrorCode["UNKNOWN"] = -2] = "UNKNOWN"; /* 参数错误 */ ErrorCode[ErrorCode["PARAMETER_ERROR"] = -3] = "PARAMETER_ERROR"; ErrorCode[ErrorCode["RECALL_MESSAGE"] = 25101] = "RECALL_MESSAGE"; /** * 发送频率过快 */ ErrorCode[ErrorCode["SEND_FREQUENCY_TOO_FAST"] = 20604] = "SEND_FREQUENCY_TOO_FAST"; ErrorCode[ErrorCode["RC_MSG_UNAUTHORIZED"] = 20406] = "RC_MSG_UNAUTHORIZED"; /** * 群组 Id 无效 */ ErrorCode[ErrorCode["RC_DISCUSSION_GROUP_ID_INVALID"] = 20407] = "RC_DISCUSSION_GROUP_ID_INVALID"; /** * 群组被禁言 */ ErrorCode[ErrorCode["FORBIDDEN_IN_GROUP"] = 22408] = "FORBIDDEN_IN_GROUP"; /** * 不在讨论组。 */ ErrorCode[ErrorCode["NOT_IN_DISCUSSION"] = 21406] = "NOT_IN_DISCUSSION"; /** * 不在群组。 */ ErrorCode[ErrorCode["NOT_IN_GROUP"] = 22406] = "NOT_IN_GROUP"; /** * 不在聊天室。 */ ErrorCode[ErrorCode["NOT_IN_CHATROOM"] = 23406] = "NOT_IN_CHATROOM"; /** *聊天室被禁言 */ ErrorCode[ErrorCode["FORBIDDEN_IN_CHATROOM"] = 23408] = "FORBIDDEN_IN_CHATROOM"; /** * 聊天室中成员被踢出 */ ErrorCode[ErrorCode["RC_CHATROOM_USER_KICKED"] = 23409] = "RC_CHATROOM_USER_KICKED"; /** * 聊天室不存在 */ ErrorCode[ErrorCode["RC_CHATROOM_NOT_EXIST"] = 23410] = "RC_CHATROOM_NOT_EXIST"; /** * 聊天室成员已满 */ ErrorCode[ErrorCode["RC_CHATROOM_IS_FULL"] = 23411] = "RC_CHATROOM_IS_FULL"; /** * 获取聊天室信息参数无效 */ ErrorCode[ErrorCode["RC_CHATROOM_PATAMETER_INVALID"] = 23412] = "RC_CHATROOM_PATAMETER_INVALID"; /** * 聊天室异常 */ ErrorCode[ErrorCode["CHATROOM_GET_HISTORYMSG_ERROR"] = 23413] = "CHATROOM_GET_HISTORYMSG_ERROR"; /** * 没有打开聊天室消息存储 */ ErrorCode[ErrorCode["CHATROOM_NOT_OPEN_HISTORYMSG_STORE"] = 23414] = "CHATROOM_NOT_OPEN_HISTORYMSG_STORE"; /** * 聊天室 KV 设置超出最大值(已满, 默认最多设置 100 个) */ ErrorCode[ErrorCode["CHATROOM_KV_EXCEED"] = 23423] = "CHATROOM_KV_EXCEED"; /** * 聊天室 KV 设置失败(kv 已存在, 需覆盖设置) */ ErrorCode[ErrorCode["CHATROOM_KV_OVERWRITE_INVALID"] = 23424] = "CHATROOM_KV_OVERWRITE_INVALID"; /** * 聊天室 KV 存储功能没有开通 */ ErrorCode[ErrorCode["CHATROOM_KV_STORE_NOT_OPEN"] = 23426] = "CHATROOM_KV_STORE_NOT_OPEN"; /** * 聊天室Key不存在 */ ErrorCode[ErrorCode["CHATROOM_KEY_NOT_EXIST"] = 23427] = "CHATROOM_KEY_NOT_EXIST"; /** * 敏感词屏蔽 */ ErrorCode[ErrorCode["SENSITIVE_SHIELD"] = 21501] = "SENSITIVE_SHIELD"; ErrorCode[ErrorCode["SENSITIVE_REPLACE"] = 21502] = "SENSITIVE_REPLACE"; /** * 加入讨论失败 */ ErrorCode[ErrorCode["JOIN_IN_DISCUSSION"] = 21407] = "JOIN_IN_DISCUSSION"; /** * 创建讨论组失败 */ ErrorCode[ErrorCode["CREATE_DISCUSSION"] = 21408] = "CREATE_DISCUSSION"; /** * 设置讨论组邀请状态失败 */ ErrorCode[ErrorCode["INVITE_DICUSSION"] = 21409] = "INVITE_DICUSSION"; /** *获取用户失败 */ ErrorCode[ErrorCode["GET_USERINFO_ERROR"] = 23407] = "GET_USERINFO_ERROR"; /** * 在黑名单中。 */ ErrorCode[ErrorCode["REJECTED_BY_BLACKLIST"] = 405] = "REJECTED_BY_BLACKLIST"; /** * 通信过程中,当前 Socket 不存在。 */ ErrorCode[ErrorCode["RC_NET_CHANNEL_INVALID"] = 30001] = "RC_NET_CHANNEL_INVALID"; /** * Socket 连接不可用。 */ ErrorCode[ErrorCode["RC_NET_UNAVAILABLE"] = 30002] = "RC_NET_UNAVAILABLE"; /** * 通信超时。 */ ErrorCode[ErrorCode["RC_MSG_RESP_TIMEOUT"] = 30003] = "RC_MSG_RESP_TIMEOUT"; /** * 导航操作时,Http 请求失败。 */ ErrorCode[ErrorCode["RC_HTTP_SEND_FAIL"] = 30004] = "RC_HTTP_SEND_FAIL"; /** * HTTP 请求失败。 */ ErrorCode[ErrorCode["RC_HTTP_REQ_TIMEOUT"] = 30005] = "RC_HTTP_REQ_TIMEOUT"; /** * HTTP 接收失败。 */ ErrorCode[ErrorCode["RC_HTTP_RECV_FAIL"] = 30006] = "RC_HTTP_RECV_FAIL"; /** * 导航操作的 HTTP 请求,返回不是200。 */ ErrorCode[ErrorCode["RC_NAVI_RESOURCE_ERROR"] = 30007] = "RC_NAVI_RESOURCE_ERROR"; /** * 导航数据解析后,其中不存在有效数据。 */ ErrorCode[ErrorCode["RC_NODE_NOT_FOUND"] = 30008] = "RC_NODE_NOT_FOUND"; /** * 导航数据解析后,其中不存在有效 IP 地址。 */ ErrorCode[ErrorCode["RC_DOMAIN_NOT_RESOLVE"] = 30009] = "RC_DOMAIN_NOT_RESOLVE"; /** * 创建 Socket 失败。 */ ErrorCode[ErrorCode["RC_SOCKET_NOT_CREATED"] = 30010] = "RC_SOCKET_NOT_CREATED"; /** * Socket 被断开。 */ ErrorCode[ErrorCode["RC_SOCKET_DISCONNECTED"] = 30011] = "RC_SOCKET_DISCONNECTED"; /** * PING 操作失败。 */ ErrorCode[ErrorCode["RC_PING_SEND_FAIL"] = 30012] = "RC_PING_SEND_FAIL"; /** * PING 超时。 */ ErrorCode[ErrorCode["RC_PONG_RECV_FAIL"] = 30013] = "RC_PONG_RECV_FAIL"; /** * 消息发送失败。 */ ErrorCode[ErrorCode["RC_MSG_SEND_FAIL"] = 30014] = "RC_MSG_SEND_FAIL"; /** * 做 connect 连接时,收到的 ACK 超时。 */ ErrorCode[ErrorCode["RC_CONN_ACK_TIMEOUT"] = 31000] = "RC_CONN_ACK_TIMEOUT"; /** * 参数错误。 */ ErrorCode[ErrorCode["RC_CONN_PROTO_VERSION_ERROR"] = 31001] = "RC_CONN_PROTO_VERSION_ERROR"; /** * 参数错误,App Id 错误。 */ ErrorCode[ErrorCode["RC_CONN_ID_REJECT"] = 31002] = "RC_CONN_ID_REJECT"; /** * 服务器不可用。 */ ErrorCode[ErrorCode["RC_CONN_SERVER_UNAVAILABLE"] = 31003] = "RC_CONN_SERVER_UNAVAILABLE"; /** * Token 错误。 */ ErrorCode[ErrorCode["RC_CONN_USER_OR_PASSWD_ERROR"] = 31004] = "RC_CONN_USER_OR_PASSWD_ERROR"; /** * App Id 与 Token 不匹配。 */ ErrorCode[ErrorCode["RC_CONN_NOT_AUTHRORIZED"] = 31005] = "RC_CONN_NOT_AUTHRORIZED"; /** * 重定向,地址错误。 */ ErrorCode[ErrorCode["RC_CONN_REDIRECTED"] = 31006] = "RC_CONN_REDIRECTED"; /** * NAME 与后台注册信息不一致。 */ ErrorCode[ErrorCode["RC_CONN_PACKAGE_NAME_INVALID"] = 31007] = "RC_CONN_PACKAGE_NAME_INVALID"; /** * APP 被屏蔽、删除或不存在。 */ ErrorCode[ErrorCode["RC_CONN_APP_BLOCKED_OR_DELETED"] = 31008] = "RC_CONN_APP_BLOCKED_OR_DELETED"; /** * 用户被屏蔽。 */ ErrorCode[ErrorCode["RC_CONN_USER_BLOCKED"] = 31009] = "RC_CONN_USER_BLOCKED"; /** * Disconnect,由服务器返回,比如用户互踢。 */ ErrorCode[ErrorCode["RC_DISCONN_KICK"] = 31010] = "RC_DISCONN_KICK"; /** * Disconnect,由服务器返回,比如用户互踢。 */ ErrorCode[ErrorCode["RC_DISCONN_EXCEPTION"] = 31011] = "RC_DISCONN_EXCEPTION"; /** * 协议层内部错误。query,上传下载过程中数据错误。 */ ErrorCode[ErrorCode["RC_QUERY_ACK_NO_DATA"] = 32001] = "RC_QUERY_ACK_NO_DATA"; /** * 协议层内部错误。 */ ErrorCode[ErrorCode["RC_MSG_DATA_INCOMPLETE"] = 32002] = "RC_MSG_DATA_INCOMPLETE"; /** * 未调用 init 初始化函数。 */ ErrorCode[ErrorCode["BIZ_ERROR_CLIENT_NOT_INIT"] = 33001] = "BIZ_ERROR_CLIENT_NOT_INIT"; /** * 数据库初始化失败。 */ ErrorCode[ErrorCode["BIZ_ERROR_DATABASE_ERROR"] = 33002] = "BIZ_ERROR_DATABASE_ERROR"; /** * 传入参数无效。 */ ErrorCode[ErrorCode["BIZ_ERROR_INVALID_PARAMETER"] = 33003] = "BIZ_ERROR_INVALID_PARAMETER"; /** * 通道无效。 */ ErrorCode[ErrorCode["BIZ_ERROR_NO_CHANNEL"] = 33004] = "BIZ_ERROR_NO_CHANNEL"; /** * 重新连接成功。 */ ErrorCode[ErrorCode["BIZ_ERROR_RECONNECT_SUCCESS"] = 33005] = "BIZ_ERROR_RECONNECT_SUCCESS"; /** * 连接中,再调用 connect 被拒绝。 */ ErrorCode[ErrorCode["BIZ_ERROR_CONNECTING"] = 33006] = "BIZ_ERROR_CONNECTING"; /** * 消息漫游服务未开通 */ ErrorCode[ErrorCode["MSG_ROAMING_SERVICE_UNAVAILABLE"] = 33007] = "MSG_ROAMING_SERVICE_UNAVAILABLE"; ErrorCode[ErrorCode["MSG_INSERT_ERROR"] = 33008] = "MSG_INSERT_ERROR"; ErrorCode[ErrorCode["MSG_DEL_ERROR"] = 33009] = "MSG_DEL_ERROR"; /** * 删除会话失败 */ ErrorCode[ErrorCode["CONVER_REMOVE_ERROR"] = 34001] = "CONVER_REMOVE_ERROR"; /** *拉取历史消息 */ ErrorCode[ErrorCode["CONVER_GETLIST_ERROR"] = 34002] = "CONVER_GETLIST_ERROR"; /** * 会话指定异常 */ ErrorCode[ErrorCode["CONVER_SETOP_ERROR"] = 34003] = "CONVER_SETOP_ERROR"; /** * 获取会话未读消息总数失败 */ ErrorCode[ErrorCode["CONVER_TOTAL_UNREAD_ERROR"] = 34004] = "CONVER_TOTAL_UNREAD_ERROR"; /** * 获取指定会话类型未读消息数异常 */ ErrorCode[ErrorCode["CONVER_TYPE_UNREAD_ERROR"] = 34005] = "CONVER_TYPE_UNREAD_ERROR"; /** * 获取指定用户ID&会话类型未读消息数异常 */ ErrorCode[ErrorCode["CONVER_ID_TYPE_UNREAD_ERROR"] = 34006] = "CONVER_ID_TYPE_UNREAD_ERROR"; ErrorCode[ErrorCode["CONVER_CLEAR_ERROR"] = 34007] = "CONVER_CLEAR_ERROR"; ErrorCode[ErrorCode["CLEAR_HIS_ERROR"] = 34010] = "CLEAR_HIS_ERROR"; ErrorCode[ErrorCode["CLEAR_HIS_TYPE_ERROR"] = 34008] = "CLEAR_HIS_TYPE_ERROR"; ErrorCode[ErrorCode["CLEAR_HIS_TIME_ERROR"] = 34011] = "CLEAR_HIS_TIME_ERROR"; /* */ ErrorCode[ErrorCode["CONVER_GET_ERROR"] = 34009] = "CONVER_GET_ERROR"; //群组异常信息 /** * */ ErrorCode[ErrorCode["GROUP_SYNC_ERROR"] = 35001] = "GROUP_SYNC_ERROR"; /** * 匹配群信息异常 */ ErrorCode[ErrorCode["GROUP_MATCH_ERROR"] = 35002] = "GROUP_MATCH_ERROR"; //聊天室异常 /** * 加入聊天室Id为空 */ ErrorCode[ErrorCode["CHATROOM_ID_ISNULL"] = 36001] = "CHATROOM_ID_ISNULL"; /** * 加入聊天室失败 */ ErrorCode[ErrorCode["CHARTOOM_JOIN_ERROR"] = 36002] = "CHARTOOM_JOIN_ERROR"; /** * 拉取聊天室历史消息失败 */ ErrorCode[ErrorCode["CHATROOM_HISMESSAGE_ERROR"] = 36003] = "CHATROOM_HISMESSAGE_ERROR"; /** * 聊天室 kv 未找到 * */ ErrorCode[ErrorCode["CHATROOM_KV_NOT_FOUND"] = 36004] = "CHATROOM_KV_NOT_FOUND"; //黑名单异常 /** * 加入黑名单异常 */ ErrorCode[ErrorCode["BLACK_ADD_ERROR"] = 37001] = "BLACK_ADD_ERROR"; /** * 获得指定人员再黑名单中的状态异常 */ ErrorCode[ErrorCode["BLACK_GETSTATUS_ERROR"] = 37002] = "BLACK_GETSTATUS_ERROR"; /** * 移除黑名单异常 */ ErrorCode[ErrorCode["BLACK_REMOVE_ERROR"] = 37003] = "BLACK_REMOVE_ERROR"; /** * 获取草稿失败 */ ErrorCode[ErrorCode["DRAF_GET_ERROR"] = 38001] = "DRAF_GET_ERROR"; /** * 保存草稿失败 */ ErrorCode[ErrorCode["DRAF_SAVE_ERROR"] = 38002] = "DRAF_SAVE_ERROR"; /** * 删除草稿失败 */ ErrorCode[ErrorCode["DRAF_REMOVE_ERROR"] = 38003] = "DRAF_REMOVE_ERROR"; /** * 关注公众号失败 */ ErrorCode[ErrorCode["SUBSCRIBE_ERROR"] = 39001] = "SUBSCRIBE_ERROR"; /** * 关注公众号失败 */ ErrorCode[ErrorCode["QNTKN_FILETYPE_ERROR"] = 41001] = "QNTKN_FILETYPE_ERROR"; /** * 获取七牛token失败 */ ErrorCode[ErrorCode["QNTKN_GET_ERROR"] = 41002] = "QNTKN_GET_ERROR"; /** * cookie被禁用 */ ErrorCode[ErrorCode["COOKIE_ENABLE"] = 51001] = "COOKIE_ENABLE"; ErrorCode[ErrorCode["GET_MESSAGE_BY_ID_ERROR"] = 61001] = "GET_MESSAGE_BY_ID_ERROR"; // 没有注册DeviveId 也就是用户没有登陆 ErrorCode[ErrorCode["HAVNODEVICEID"] = 24001] = "HAVNODEVICEID"; // 已经存在 ErrorCode[ErrorCode["DEVICEIDISHAVE"] = 24002] = "DEVICEIDISHAVE"; // 成功 ErrorCode[ErrorCode["SUCCESS"] = 0] = "SUCCESS"; // 没有对应的用户或token ErrorCode[ErrorCode["FEILD"] = 24009] = "FEILD"; // voip为空 ErrorCode[ErrorCode["VOIPISNULL"] = 24013] = "VOIPISNULL"; // 不支持的Voip引擎 ErrorCode[ErrorCode["NOENGINETYPE"] = 24010] = "NOENGINETYPE"; // channleName 是空 ErrorCode[ErrorCode["NULLCHANNELNAME"] = 24011] = "NULLCHANNELNAME"; // 生成Voipkey失败 ErrorCode[ErrorCode["VOIPDYANMICERROR"] = 24012] = "VOIPDYANMICERROR"; // 没有配置voip ErrorCode[ErrorCode["NOVOIP"] = 24014] = "NOVOIP"; // 服务器内部错误 ErrorCode[ErrorCode["INTERNALERRROR"] = 24015] = "INTERNALERRROR"; //VOIP close ErrorCode[ErrorCode["VOIPCLOSE"] = 24016] = "VOIPCLOSE"; ErrorCode[ErrorCode["CLOSE_BEFORE_OPEN"] = 51001] = "CLOSE_BEFORE_OPEN"; ErrorCode[ErrorCode["ALREADY_IN_USE"] = 51002] = "ALREADY_IN_USE"; ErrorCode[ErrorCode["INVALID_CHANNEL_NAME"] = 51003] = "INVALID_CHANNEL_NAME"; ErrorCode[ErrorCode["VIDEO_CONTAINER_IS_NULL"] = 51004] = "VIDEO_CONTAINER_IS_NULL"; /** * 删除消息数组长度为 0 . */ ErrorCode[ErrorCode["DELETE_MESSAGE_ID_IS_NULL"] = 61001] = "DELETE_MESSAGE_ID_IS_NULL"; /*! 己方取消已发出的通话请求 */ ErrorCode[ErrorCode["CANCEL"] = 1] = "CANCEL"; /*! 己方拒绝收到的通话请求 */ ErrorCode[ErrorCode["REJECT"] = 2] = "REJECT"; /*! 己方挂断 */ ErrorCode[ErrorCode["HANGUP"] = 3] = "HANGUP"; /*! 己方忙碌 */ ErrorCode[ErrorCode["BUSYLINE"] = 4] = "BUSYLINE"; /*! 己方未接听 */ ErrorCode[ErrorCode["NO_RESPONSE"] = 5] = "NO_RESPONSE"; /*! 己方不支持当前引擎 */ ErrorCode[ErrorCode["ENGINE_UN_SUPPORTED"] = 6] = "ENGINE_UN_SUPPORTED"; /*! 己方网络出错 */ ErrorCode[ErrorCode["NETWORK_ERROR"] = 7] = "NETWORK_ERROR"; /*! 对方取消已发出的通话请求 */ ErrorCode[ErrorCode["REMOTE_CANCEL"] = 11] = "REMOTE_CANCEL"; /*! 对方拒绝收到的通话请求 */ ErrorCode[ErrorCode["REMOTE_REJECT"] = 12] = "REMOTE_REJECT"; /*! 通话过程对方挂断 */ ErrorCode[ErrorCode["REMOTE_HANGUP"] = 13] = "REMOTE_HANGUP"; /*! 对方忙碌 */ ErrorCode[ErrorCode["REMOTE_BUSYLINE"] = 14] = "REMOTE_BUSYLINE"; /*! 对方未接听 */ ErrorCode[ErrorCode["REMOTE_NO_RESPONSE"] = 15] = "REMOTE_NO_RESPONSE"; /*! 对方网络错误 */ ErrorCode[ErrorCode["REMOTE_ENGINE_UN_SUPPORTED"] = 16] = "REMOTE_ENGINE_UN_SUPPORTED"; /*! 对方网络错误 */ ErrorCode[ErrorCode["REMOTE_NETWORK_ERROR"] = 17] = "REMOTE_NETWORK_ERROR"; /*! VoIP 不可用 */ ErrorCode[ErrorCode["VOIP_NOT_AVALIABLE"] = 18] = "VOIP_NOT_AVALIABLE"; })(RongIMLib.ErrorCode || (RongIMLib.ErrorCode = {})); var ErrorCode = RongIMLib.ErrorCode; (function (VoIPMediaType) { VoIPMediaType[VoIPMediaType["MEDIA_AUDIO"] = 1] = "MEDIA_AUDIO"; VoIPMediaType[VoIPMediaType["MEDIA_VEDIO"] = 2] = "MEDIA_VEDIO"; VoIPMediaType[VoIPMediaType["MEDIA_VIDEO"] = 2] = "MEDIA_VIDEO"; })(RongIMLib.VoIPMediaType || (RongIMLib.VoIPMediaType = {})); var VoIPMediaType = RongIMLib.VoIPMediaType; (function (MediaType) { /** * 图片。 */ MediaType[MediaType["IMAGE"] = 1] = "IMAGE"; /** * 声音。 */ MediaType[MediaType["AUDIO"] = 2] = "AUDIO"; /** * 视频。 */ MediaType[MediaType["VIDEO"] = 3] = "VIDEO"; /** * 通用文件。 */ MediaType[MediaType["FILE"] = 100] = "FILE"; })(RongIMLib.MediaType || (RongIMLib.MediaType = {})); var MediaType = RongIMLib.MediaType; (function (MessageDirection) { /** * 发送消息。 */ MessageDirection[MessageDirection["SEND"] = 1] = "SEND"; /** * 接收消息。 */ MessageDirection[MessageDirection["RECEIVE"] = 2] = "RECEIVE"; })(RongIMLib.MessageDirection || (RongIMLib.MessageDirection = {})); var MessageDirection = RongIMLib.MessageDirection; (function (FileType) { FileType[FileType["IMAGE"] = 1] = "IMAGE"; FileType[FileType["AUDIO"] = 2] = "AUDIO"; FileType[FileType["VIDEO"] = 3] = "VIDEO"; FileType[FileType["FILE"] = 4] = "FILE"; })(RongIMLib.FileType || (RongIMLib.FileType = {})); var FileType = RongIMLib.FileType; (function (RealTimeLocationErrorCode) { /** * 未初始化 RealTimeLocation 实例 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_NOT_INIT"] = -1] = "RC_REAL_TIME_LOCATION_NOT_INIT"; /** * 执行成功。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_SUCCESS"] = 0] = "RC_REAL_TIME_LOCATION_SUCCESS"; /** * 获取 RealTimeLocation 实例时返回 * GPS 未打开。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_GPS_DISABLED"] = 1] = "RC_REAL_TIME_LOCATION_GPS_DISABLED"; /** * 获取 RealTimeLocation 实例时返回 * 当前会话不支持位置共享。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_CONVERSATION_NOT_SUPPORT"] = 2] = "RC_REAL_TIME_LOCATION_CONVERSATION_NOT_SUPPORT"; /** * 获取 RealTimeLocation 实例时返回 * 对方已发起位置共享。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_IS_ON_GOING"] = 3] = "RC_REAL_TIME_LOCATION_IS_ON_GOING"; /** * Join 时返回 * 当前位置共享已超过最大支持人数。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_EXCEED_MAX_PARTICIPANT"] = 4] = "RC_REAL_TIME_LOCATION_EXCEED_MAX_PARTICIPANT"; /** * Join 时返回 * 加入位置共享失败。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_JOIN_FAILURE"] = 5] = "RC_REAL_TIME_LOCATION_JOIN_FAILURE"; /** * Start 时返回 * 发起位置共享失败。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_START_FAILURE"] = 6] = "RC_REAL_TIME_LOCATION_START_FAILURE"; /** * 网络不可用。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_NETWORK_UNAVAILABLE"] = 7] = "RC_REAL_TIME_LOCATION_NETWORK_UNAVAILABLE"; })(RongIMLib.RealTimeLocationErrorCode || (RongIMLib.RealTimeLocationErrorCode = {})); var RealTimeLocationErrorCode = RongIMLib.RealTimeLocationErrorCode; (function (RealTimeLocationStatus) { /** * 空闲状态 (默认状态) * 对方或者自己都未发起位置共享业务,或者位置共享业务已结束。 */ RealTimeLocationStatus[RealTimeLocationStatus["RC_REAL_TIME_LOCATION_STATUS_IDLE"] = 0] = "RC_REAL_TIME_LOCATION_STATUS_IDLE"; /** * 呼入状态 (待加入) * 1. 对方发起了位置共享业务,此状态下,自己只能选择加入。 * 2. 自己从已连接的位置共享中退出。 */ RealTimeLocationStatus[RealTimeLocationStatus["RC_REAL_TIME_LOCATION_STATUS_INCOMING"] = 1] = "RC_REAL_TIME_LOCATION_STATUS_INCOMING"; /** * 呼出状态 =(自己创建) * 1. 自己发起位置共享业务,对方只能选择加入。 * 2. 对方从已连接的位置共享业务中退出。 */ RealTimeLocationStatus[RealTimeLocationStatus["RC_REAL_TIME_LOCATION_STATUS_OUTGOING"] = 2] = "RC_REAL_TIME_LOCATION_STATUS_OUTGOING"; /** * 连接状态 (自己加入) * 对方加入了自己发起的位置共享,或者自己加入了对方发起的位置共享。 */ RealTimeLocationStatus[RealTimeLocationStatus["RC_REAL_TIME_LOCATION_STATUS_CONNECTED"] = 3] = "RC_REAL_TIME_LOCATION_STATUS_CONNECTED"; })(RongIMLib.RealTimeLocationStatus || (RongIMLib.RealTimeLocationStatus = {})); var RealTimeLocationStatus = RongIMLib.RealTimeLocationStatus; (function (ReceivedStatus) { ReceivedStatus[ReceivedStatus["READ"] = 1] = "READ"; ReceivedStatus[ReceivedStatus["LISTENED"] = 2] = "LISTENED"; ReceivedStatus[ReceivedStatus["DOWNLOADED"] = 4] = "DOWNLOADED"; ReceivedStatus[ReceivedStatus["RETRIEVED"] = 8] = "RETRIEVED"; ReceivedStatus[ReceivedStatus["UNREAD"] = 0] = "UNREAD"; })(RongIMLib.ReceivedStatus || (RongIMLib.ReceivedStatus = {})); var ReceivedStatus = RongIMLib.ReceivedStatus; (function (ReadStatus) { ReadStatus[ReadStatus["READ"] = 1] = "READ"; ReadStatus[ReadStatus["LISTENED"] = 2] = "LISTENED"; ReadStatus[ReadStatus["DOWNLOADED"] = 4] = "DOWNLOADED"; ReadStatus[ReadStatus["RETRIEVED"] = 8] = "RETRIEVED"; ReadStatus[ReadStatus["UNREAD"] = 0] = "UNREAD"; })(RongIMLib.ReadStatus || (RongIMLib.ReadStatus = {})); var ReadStatus = RongIMLib.ReadStatus; (function (SearchType) { /** * 精确。 */ SearchType[SearchType["EXACT"] = 0] = "EXACT"; /** * 模糊。 */ SearchType[SearchType["FUZZY"] = 1] = "FUZZY"; })(RongIMLib.SearchType || (RongIMLib.SearchType = {})); var SearchType = RongIMLib.SearchType; (function (SentStatus) { /** * 发送中。 */ SentStatus[SentStatus["SENDING"] = 10] = "SENDING"; /** * 发送失败。 */ SentStatus[SentStatus["FAILED"] = 20] = "FAILED"; /** * 已发送。 */ SentStatus[SentStatus["SENT"] = 30] = "SENT"; /** * 对方已接收。 */ SentStatus[SentStatus["RECEIVED"] = 40] = "RECEIVED"; /** * 对方已读。 */ SentStatus[SentStatus["READ"] = 50] = "READ"; /** * 对方已销毁。 */ SentStatus[SentStatus["DESTROYED"] = 60] = "DESTROYED"; })(RongIMLib.SentStatus || (RongIMLib.SentStatus = {})); var SentStatus = RongIMLib.SentStatus; (function (ConnectionState) { ConnectionState[ConnectionState["ACCEPTED"] = 0] = "ACCEPTED"; ConnectionState[ConnectionState["UNACCEPTABLE_PROTOCOL_VERSION"] = 1] = "UNACCEPTABLE_PROTOCOL_VERSION"; ConnectionState[ConnectionState["IDENTIFIER_REJECTED"] = 2] = "IDENTIFIER_REJECTED"; ConnectionState[ConnectionState["SERVER_UNAVAILABLE"] = 3] = "SERVER_UNAVAILABLE"; /** * token无效 */ ConnectionState[ConnectionState["TOKEN_INCORRECT"] = 4] = "TOKEN_INCORRECT"; ConnectionState[ConnectionState["NOT_AUTHORIZED"] = 5] = "NOT_AUTHORIZED"; ConnectionState[ConnectionState["REDIRECT"] = 6] = "REDIRECT"; ConnectionState[ConnectionState["PACKAGE_ERROR"] = 7] = "PACKAGE_ERROR"; ConnectionState[ConnectionState["APP_BLOCK_OR_DELETE"] = 8] = "APP_BLOCK_OR_DELETE"; ConnectionState[ConnectionState["BLOCK"] = 9] = "BLOCK"; ConnectionState[ConnectionState["TOKEN_EXPIRE"] = 10] = "TOKEN_EXPIRE"; ConnectionState[ConnectionState["DEVICE_ERROR"] = 11] = "DEVICE_ERROR"; })(RongIMLib.ConnectionState || (RongIMLib.ConnectionState = {})); var ConnectionState = RongIMLib.ConnectionState; (function (RTCAPIType) { RTCAPIType[RTCAPIType["ROOM"] = 1] = "ROOM"; RTCAPIType[RTCAPIType["PERSON"] = 2] = "PERSON"; })(RongIMLib.RTCAPIType || (RongIMLib.RTCAPIType = {})); var RTCAPIType = RongIMLib.RTCAPIType; (function (ChatroomEntityOpt) { ChatroomEntityOpt[ChatroomEntityOpt["UPDATE"] = 1] = "UPDATE"; ChatroomEntityOpt[ChatroomEntityOpt["DELETE"] = 2] = "DELETE"; })(RongIMLib.ChatroomEntityOpt || (RongIMLib.ChatroomEntityOpt = {})); var ChatroomEntityOpt = RongIMLib.ChatroomEntityOpt; (function (ChatroomEntityLimit) { ChatroomEntityLimit[ChatroomEntityLimit["KEY"] = 128] = "KEY"; ChatroomEntityLimit[ChatroomEntityLimit["VALUE"] = 4096] = "VALUE"; })(RongIMLib.ChatroomEntityLimit || (RongIMLib.ChatroomEntityLimit = {})); var ChatroomEntityLimit = RongIMLib.ChatroomEntityLimit; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var RongIMClient = (function () { function RongIMClient() { } RongIMClient.getInstance = function () { if (!RongIMClient._instance) { throw new Error("RongIMClient is not initialized. Call .init() method first."); } return RongIMClient._instance; }; RongIMClient.showError = function (errorInfo) { var hasConsole = (console && console.error); if (hasConsole) { console.error(JSON.stringify(errorInfo)); } }; RongIMClient.logger = function (params) { var code = params.code; var errorInfo = RongIMClient.LogFactory[code] || params; errorInfo.funcName = params.funcName; errorInfo.msg = params.msg || errorInfo.msg; if (RongIMClient._memoryStore.depend.showError) { RongIMClient.showError(errorInfo); } }; RongIMClient.logCallback = function (callback, funcName) { return { onSuccess: callback.onSuccess, onError: function (errorCode) { RongIMClient.logger({ code: errorCode, funcName: funcName }); callback.onError(errorCode); } }; }; ; RongIMClient.logSendCallback = function (callback, funcName) { return { onSuccess: callback.onSuccess, onError: function (errorCode, result) { RongIMClient.logger({ code: errorCode, funcName: funcName }); callback.onError(errorCode, result); }, onBefore: callback.onBefore }; }; ; /** * 初始化 SDK,在整个应用全局只需要调用一次。 * @param appKey 开发者后台申请的 AppKey,用来标识应用。 * @param dataAccessProvider 必须是DataAccessProvider的实例 */ RongIMClient.init = function (appKey, dataAccessProvider, options, callback) { RongIMClient.statusListeners = []; RongIMClient.messageListeners = []; if (RongIMClient._instance) { return RongIMClient._memoryStore.sdkInfo; } RongIMClient._instance = new RongIMClient(); options = options || {}; var protocol = "http://", wsScheme = 'ws://'; var isLocationInvalid = typeof location !== 'object'; // 未找到全局 location 变量, 则协议为 https. 比如小程序 if (isLocationInvalid || location.protocol == 'https:') { wsScheme = 'wss://'; protocol = 'https://'; } var isPolling = false; if (typeof WebSocket != 'function') { isPolling = true; } var isIntegrity = function () { //iOS 9 var hasWS = (typeof WebSocket); var integrity = (typeof WebSocket.OPEN == 'number'); return (hasWS && integrity); }; if (typeof WebSocket == 'object' && isIntegrity()) { isPolling = false; } var supportUserData = function () { var element = document.documentElement; return element.addBehavior; }; if (RongIMLib.RongUtil.supportLocalStorage()) { RongIMClient._storageProvider = new RongIMLib.LocalStorageProvider(); } else if (supportUserData()) { RongIMClient._storageProvider = new RongIMLib.UserDataProvider(); } else { RongIMClient._storageProvider = new RongIMLib.MemeoryProvider(); } var serverIndex = RongIMClient._storageProvider.getItem('serverIndex'); RongIMClient.serverStore.index = serverIndex || 0; var pathTmpl = '{0}{1}'; var _serverPath = { api: 'api.cn.ronghub.com' }; RongIMLib.RongUtil.forEach(_serverPath, function (path, key) { _serverPath[key] = RongIMLib.RongUtil.stringFormat(pathTmpl, [protocol, path]); }); RongIMLib.RongUtil.forEach(_serverPath, function (path, key) { var hasProto = (key in options); var config = { path: options[key], tmpl: pathTmpl, protocol: protocol, sub: true }; path = hasProto ? RongIMLib.RongUtil.formatProtoclPath(config) : path; options[key] = path; }); var navigaters = options.navigaters || []; if (options.navi) { navigaters = [options.navi]; } if (!options.navi && RongIMLib.RongUtil.isEqual(navigaters.length, 0)) { navigaters = ['nav.cn.ronghub.com', 'nav2-cn.ronghub.com']; } RongIMLib.RongUtil.forEach(navigaters, function (navi, index) { var config = { path: navi, tmpl: pathTmpl, protocol: protocol, sub: true }; navi = RongIMLib.RongUtil.formatProtoclPath(config); navigaters[index] = navi; }); var _sourcePath = { protobuf: 'cdn.ronghub.com/protobuf-2.3.7.min.js' }; RongIMLib.RongUtil.forEach(_sourcePath, function (path, key) { _sourcePath[key] = RongIMLib.RongUtil.stringFormat(pathTmpl, [protocol, path]); }); RongIMLib.RongUtil.extend(_sourcePath, options); var _defaultOpts = { isPolling: isPolling, wsScheme: wsScheme, protocol: protocol, showError: true, openMp: true, snifferTime: 2000, naviTimeout: 5000, navigaters: navigaters, maxNaviRetry: 10, isNaviJSONP: false, isWSPingJSONP: false, isNotifyConversationList: false, maxConversationCount: 300 }; delete options.navigaters; RongIMLib.RongUtil.extend(_defaultOpts, options); if (RongIMLib.RongUtil.isFunction(options.protobuf)) { RongIMClient.Protobuf = options.protobuf; } RongIMClient.userStatusObserver = new RongIMLib.RongObserver(); var pather = new RongIMLib.FeaturePatcher(); pather.patchAll(); var tempStore = { token: "", callback: null, lastReadTime: new RongIMLib.LimitableMap(), historyMessageLimit: new RongIMLib.MemoryCache(), conversationList: [], appKey: appKey, publicServiceMap: new RongIMLib.PublicServiceMap(), providerType: 1, deltaTime: 0, filterMessages: [], isSyncRemoteConverList: true, otherDevice: false, custStore: {}, converStore: { latestMessage: {} }, connectAckTime: 0, voipStategy: 0, isFirstPingMsg: true, depend: options, notification: {} }; RongIMClient._memoryStore = tempStore; var isCPlusSDK = dataAccessProvider && Object.prototype.toString.call(dataAccessProvider) == "[object Object]"; if (isCPlusSDK) { RongIMClient._dataAccessProvider = dataAccessProvider; } else { RongIMClient._dataAccessProvider = new RongIMLib.ServerDataProvider(); } options.appCallback = callback; var sdkInfo = RongIMClient._dataAccessProvider.init(appKey, options); RongIMClient._memoryStore.sdkInfo = sdkInfo; if (isCPlusSDK) { // 兼容 c++ 设置导航,Web 端不生效 RongIMClient._dataAccessProvider.setServerInfo({ navi: location.protocol + options.navi + '/navi.xml' }); } RongIMClient.MessageParams = { TextMessage: { objectName: "RC:TxtMsg", msgTag: new RongIMLib.MessageTag(true, true) }, ImageMessage: { objectName: "RC:ImgMsg", msgTag: new RongIMLib.MessageTag(true, true) }, DiscussionNotificationMessage: { objectName: "RC:DizNtf", msgTag: new RongIMLib.MessageTag(false, true) }, VoiceMessage: { objectName: "RC:VcMsg", msgTag: new RongIMLib.MessageTag(true, true) }, RichContentMessage: { objectName: "RC:ImgTextMsg", msgTag: new RongIMLib.MessageTag(true, true) }, FileMessage: { objectName: "RC:FileMsg", msgTag: new RongIMLib.MessageTag(true, true) }, HQVoiceMessage: { objectName: "RC:HQVCMsg", msgTag: new RongIMLib.MessageTag(true, true) }, HandshakeMessage: { objectName: "", msgTag: new RongIMLib.MessageTag(true, true) }, UnknownMessage: { objectName: "", msgTag: new RongIMLib.MessageTag(true, true) }, LocationMessage: { objectName: "RC:LBSMsg", msgTag: new RongIMLib.MessageTag(true, true) }, InformationNotificationMessage: { objectName: "RC:InfoNtf", msgTag: new RongIMLib.MessageTag(false, true) }, ContactNotificationMessage: { objectName: "RC:ContactNtf", msgTag: new RongIMLib.MessageTag(false, true) }, ProfileNotificationMessage: { objectName: "RC:ProfileNtf", msgTag: new RongIMLib.MessageTag(false, true) }, CommandNotificationMessage: { objectName: "RC:CmdNtf", msgTag: new RongIMLib.MessageTag(false, true) }, PublicServiceRichContentMessage: { objectName: "RC:PSImgTxtMsg", msgTag: new RongIMLib.MessageTag(true, true) }, PublicServiceMultiRichContentMessage: { objectName: "RC:PSMultiImgTxtMsg", msgTag: new RongIMLib.MessageTag(true, true) }, JrmfRedPacketMessage: { objectName: "RCJrmf:RpMsg", msgTag: new RongIMLib.MessageTag(true, true) }, JrmfRedPacketOpenedMessage: { objectName: "RCJrmf:RpOpendMsg", msgTag: new RongIMLib.MessageTag(true, true) }, GroupNotificationMessage: { objectName: "RC:GrpNtf", msgTag: new RongIMLib.MessageTag(false, true) }, CommandMessage: { objectName: "RC:CmdMsg", msgTag: new RongIMLib.MessageTag(false, false) }, TypingStatusMessage: { objectName: "RC:TypSts", msgTag: new RongIMLib.MessageTag(false, false) }, PublicServiceCommandMessage: { objectName: "RC:PSCmd", msgTag: new RongIMLib.MessageTag(false, false) }, RecallCommandMessage: { objectName: "RC:RcCmd", msgTag: new RongIMLib.MessageTag(false, true) }, SyncReadStatusMessage: { objectName: "RC:SRSMsg", msgTag: new RongIMLib.MessageTag(false, false) }, ReadReceiptRequestMessage: { objectName: "RC:RRReqMsg", msgTag: new RongIMLib.MessageTag(false, false) }, ReadReceiptResponseMessage: { objectName: "RC:RRRspMsg", msgTag: new RongIMLib.MessageTag(false, false) }, ChangeModeResponseMessage: { objectName: "RC:CsChaR", msgTag: new RongIMLib.MessageTag(false, false) }, ChangeModeMessage: { objectName: "RC:CSCha", msgTag: new RongIMLib.MessageTag(false, false) }, EvaluateMessage: { objectName: "RC:CsEva", msgTag: new RongIMLib.MessageTag(false, false) }, CustomerContact: { objectName: "RC:CsContact", msgTag: new RongIMLib.MessageTag(false, false) }, HandShakeMessage: { objectName: "RC:CsHs", msgTag: new RongIMLib.MessageTag(false, false) }, HandShakeResponseMessage: { objectName: "RC:CsHsR", msgTag: new RongIMLib.MessageTag(false, false) }, SuspendMessage: { objectName: "RC:CsSp", msgTag: new RongIMLib.MessageTag(false, false) }, TerminateMessage: { objectName: "RC:CsEnd", msgTag: new RongIMLib.MessageTag(false, false) }, CustomerStatusUpdateMessage: { objectName: "RC:CsUpdate", msgTag: new RongIMLib.MessageTag(false, false) }, ReadReceiptMessage: { objectName: "RC:ReadNtf", msgTag: new RongIMLib.MessageTag(false, false) }, RCCombineMessage: { objectName: "RC:CombineMsg", msgTag: new RongIMLib.MessageTag(true, true) }, ChrmKVNotificationMessage: { objectName: 'RC:chrmKVNotiMsg', msgTag: new RongIMLib.MessageTag(false, false) } }; RongIMClient.MessageParams["AcceptMessage"] = { objectName: "RC:VCAccept", msgTag: new RongIMLib.MessageTag(false, false) }; RongIMClient.MessageParams["RingingMessage"] = { objectName: "RC:VCRinging", msgTag: new RongIMLib.MessageTag(false, false) }; RongIMClient.MessageParams["SummaryMessage"] = { objectName: "RC:VCSummary", msgTag: new RongIMLib.MessageTag(false, false) }; RongIMClient.MessageParams["HungupMessage"] = { objectName: "RC:VCHangup", msgTag: new RongIMLib.MessageTag(false, false) }; RongIMClient.MessageParams["InviteMessage"] = { objectName: "RC:VCInvite", msgTag: new RongIMLib.MessageTag(false, false) }; RongIMClient.MessageParams["MediaModifyMessage"] = { objectName: "RC:VCModifyMedia", msgTag: new RongIMLib.MessageTag(false, false) }; RongIMClient.MessageParams["MemberModifyMessage"] = { objectName: "RC:VCModifyMem", msgTag: new RongIMLib.MessageTag(false, false) }; RongIMClient.MessageType = { TextMessage: "TextMessage", ImageMessage: "ImageMessage", DiscussionNotificationMessage: "DiscussionNotificationMessage", VoiceMessage: "VoiceMessage", RichContentMessage: "RichContentMessage", HandshakeMessage: "HandshakeMessage", UnknownMessage: "UnknownMessage", LocationMessage: "LocationMessage", InformationNotificationMessage: "InformationNotificationMessage", ContactNotificationMessage: "ContactNotificationMessage", ProfileNotificationMessage: "ProfileNotificationMessage", CommandNotificationMessage: "CommandNotificationMessage", CommandMessage: "CommandMessage", TypingStatusMessage: "TypingStatusMessage", ChangeModeResponseMessage: "ChangeModeResponseMessage", ChangeModeMessage: "ChangeModeMessage", EvaluateMessage: "EvaluateMessage", HandShakeMessage: "HandShakeMessage", HandShakeResponseMessage: "HandShakeResponseMessage", SuspendMessage: "SuspendMessage", TerminateMessage: "TerminateMessage", CustomerContact: "CustomerContact", CustomerStatusUpdateMessage: "CustomerStatusUpdateMessage", SyncReadStatusMessage: "SyncReadStatusMessage", ReadReceiptRequestMessage: "ReadReceiptRequestMessage", ReadReceiptResponseMessage: "ReadReceiptResponseMessage", FileMessage: 'FileMessage', HQVoiceMessage: 'HQVoiceMessage', AcceptMessage: "AcceptMessage", RingingMessage: "RingingMessage", SummaryMessage: "SummaryMessage", HungupMessage: "HungupMessage", InviteMessage: "InviteMessage", MediaModifyMessage: "MediaModifyMessage", MemberModifyMessage: "MemberModifyMessage", JrmfRedPacketMessage: "JrmfRedPacketMessage", JrmfRedPacketOpenedMessage: "JrmfRedPacketOpenedMessage", GroupNotificationMessage: "GroupNotificationMessage", PublicServiceRichContentMessage: "PublicServiceRichContentMessage", PublicServiceMultiRichContentMessage: "PublicServiceMultiRichContentMessage", PublicServiceCommandMessage: "PublicServiceCommandMessage", RecallCommandMessage: "RecallCommandMessage", ReadReceiptMessage: "ReadReceiptMessage", RCCombineMessage: "RCCombineMessage", ChrmKVNotificationMessage: 'ChrmKVNotificationMessage' }; RongIMClient.LogFactory = { /** * 个人 */ "-1": { code: "-1", msg: "服务器超时" }, "-2": { code: "-2", msg: "未知原因失败" }, "-3": { code: "-3", msg: "参数错误" }, "-4": { code: "-4", msg: "参数不正确或尚未实例化" }, "25101": { code: "25101", msg: "撤回消息参数错误", desc: "请检查撤回消息参数 https://rongcloud.github.io/websdk-demo/api-test.html" }, "25102": { code: "25101", msg: "只能撤回自发发送的消息" }, "20604": { code: "20604", msg: "发送频率过快", desc: "https://developer.rongcloud.cn/ticket/info/9Q3L6vRKd1cLS7rycA==?type=1" }, "20406": { code: "20406", msg: "被禁言" }, "23407": { code: "23407", msg: "获取用户失败" }, /** * 群组 */ "20407": { code: "20407", msg: "群组Id无效" }, "22408": { code: "22408", msg: "群组被禁言" }, "22406": { code: "22406", msg: "不在群组" }, "35001": { code: "35001", msg: "群组同步异常" }, "35002": { code: "35002", msg: "匹配群信息异常" }, /** * 讨论组 */ "21406": { code: "21406", msg: "不在讨论组" }, "21407": { code: "21407", msg: "加入讨论失败" }, "21408": { code: "21408", msg: "创建讨论组失败" }, "21409": { code: "21409", msg: "设置讨论组邀请状态失败" }, /** * 聊天室 */ "23406": { code: "23406", msg: "不在聊天室" }, "23408": { code: "23408", msg: "聊天室被禁言" }, "23409": { code: "23409", msg: "聊天室中成员被踢出" }, "23410": { code: "23410", msg: "聊天室不存在" }, "23411": { code: "23411", msg: "聊天室成员已满" }, "23412": { code: "23412", msg: "获取聊天室信息参数无效" }, "23413": { code: "23413", msg: "聊天室异常" }, "23414": { code: "23414", msg: "没有打开聊天室消息存储" }, "36001": { code: "36001", msg: "加入聊天室Id为空" }, "36002": { code: "36002", msg: "加入聊天室失败" }, "36003": { code: "36003", msg: "拉取聊天室历史消息失败" }, /** * voip */ "24001": { code: "24001", msg: "没有注册DeviveId 也就是用户没有登陆" }, "24002": { code: "24002", msg: "用户已经存在" }, "0": { code: "0", msg: "成功" }, "24009": { code: "24009", msg: "没有对应的用户或token" }, "24013": { code: "24013", msg: "voip为空" }, "24010": { code: "24010", msg: "不支持的Voip引擎" }, "24011": { code: "24011", msg: "channelName 是空" }, "24012": { code: "24012", msg: "生成Voipkey失败" }, "24014": { code: "24014", msg: "没有配置voip" }, "24015": { code: "24015", msg: "服务器内部错误" }, "24016": { code: "24016", msg: "VOIP close" }, /** * 通讯、导航 */ "30001": { code: "30001", msg: "通信过程中,当前Socket不存在" }, "30002": { code: "30002", msg: "Socket连接不可用" }, "30003": { code: "30003", msg: "通信超时" }, "30004": { code: "30004", msg: "导航操作时,Http请求失败" }, "30005": { code: "30005", msg: "HTTP请求失败" }, "30006": { code: "30006", msg: "HTTP接收失败" }, "30007": { code: "30007", msg: "导航资源错误" }, "30008": { code: "30008", msg: "没有有效数据" }, "30009": { code: "30009", msg: "不存在有效 IP 地址" }, "30010": { code: "30010", msg: "创建 Socket 失败" }, "30011": { code: "30011", msg: " Socket 被断开" }, "30012": { code: "30012", msg: "PING 操作失败" }, "30013": { code: "30013", msg: "PING 超时" }, "30014": { code: "30014", msg: "消息发送失败" }, "30016": { code: "30016", msg: "消息大小超限,最大 128 KB" }, /** * 连接 */ "31000": { code: "31000", msg: "做 connect 连接时,收到的 ACK 超时" }, "31001": { code: "31001", msg: "参数错误" }, "31002": { code: "31002", msg: "参数错误,App Id 错误" }, "31003": { code: "31003", msg: "服务器不可用" }, "31004": { code: "31004", msg: "Token 错误" }, "31005": { code: "31005", msg: "App Id 与 Token 不匹配" }, "31006": { code: "31006", msg: "重定向,地址错误" }, "31007": { code: "31007", msg: "NAME 与后台注册信息不一致" }, "31008": { code: "31008", msg: "APP 被屏蔽、删除或不存在" }, "31009": { code: "31009", msg: "用户被屏蔽" }, "31010": { code: "31010", msg: "Disconnect,由服务器返回,比如用户互踢" }, "31011": { code: "31011", msg: "Disconnect,由服务器返回,比如用户互踢" }, /** * 协议 */ "32001": { code: "32001", msg: "协议层内部错误。query,上传下载过程中数据错误" }, "32002": { code: "32002", msg: "协议层内部错误" }, /** * BIZ */ "33001": { code: "33001", msg: "未调用 init 初始化函数" }, "33002": { code: "33002", msg: "数据库初始化失败" }, "33003": { code: "33003", msg: "传入参数无效" }, "33004": { code: "33004", msg: "通道无效" }, "33005": { code: "33005", msg: "重新连接成功" }, "33006": { code: "33006", msg: "连接中,再调用 connect 被拒绝" }, "33007": { code: "33007", msg: "消息漫游服务未开通" }, "33008": { code: "33008", msg: "消息添加失败" }, "33009": { code: "33009", msg: "消息删除失败" }, /** * 会话 */ "34001": { code: "34001", msg: "删除会话失败" }, "34002": { code: "34002", msg: "拉取历史消息失败" }, "34003": { code: "34003", msg: "会话指定异常" }, "34004": { code: "34004", msg: "获取会话未读消息总数失败" }, "34005": { code: "34005", msg: "获取指定会话类型未读消息数异常" }, "34006": { code: "34006", msg: "获取指定用户ID&会话类型未读消息数异常" }, "34007": { code: "34007", msg: "清除会话消息异常" }, "34008": { code: "34008", msg: "获取会话消息异常" }, "34009": { code: "34009", msg: "清除历史消息会话类型不正确" }, "34010": { code: "34010", msg: "清除历史消息失败,请检查传入参数" }, /** * 黑名单异常 */ "37001": { code: "37001", msg: "加入黑名单异常" }, "37002": { code: "37002", msg: "获得指定人员再黑名单中的状态异常" }, "37003": { code: "37003", msg: "移除黑名单异常" }, "405": { code: "405", msg: "在黑名单中" }, /** * 草稿 */ "38001": { code: "38001", msg: "获取草稿失败" }, "38002": { code: "38002", msg: "保存草稿失败" }, "38003": { code: "38003", msg: "删除草稿失败" }, /** * 公众号 */ "39001": { code: "39001", msg: "关注公众号失败" }, /** * 文件 */ "41001": { code: "41001", msg: "文件类型错误" }, "41002": { code: "41002", msg: "获取七牛token失败" }, /** * */ "51001": { code: "51001", msg: "未安装或未启动插件" }, "51002": { code: "51002", msg: "视频已经存在" }, "51003": { code: "51003", msg: "无效的channelName" }, "51004": { code: "51004", msg: "视频内容为空" }, /** * */ "61001": { code: "61001", msg: "删除消息数组长度为 0" } }; var handler = function (message, uris, callback) { var userId = message.senderUserId; var _uris = RongIMClient.roomInfo.users[userId].uris || '[]'; if (RongIMLib.RongUtil.isString(_uris)) { _uris = JSON.parse(_uris); } var tUris = JSON.parse(JSON.stringify(_uris)); RongIMLib.RongUtil.forEach(tUris, function (_uri, index) { RongIMLib.RongUtil.forEach(uris, function (uri) { if (uri.uri == _uri.uri) { callback(_uri, uri, _uris, index); } }); }); RongIMClient.roomInfo.users[userId].uris = JSON.stringify(_uris); }; var RTCMessage = { RTCPublishResourceMessage: function (message, uris) { var userId = message.senderUserId; var user = RongIMClient.roomInfo.users[userId]; if (!user) { user = {}; RongIMClient.roomInfo.users[userId] = {}; } var _uris = user.uris || '[]'; if (RongIMLib.RongUtil.isString(_uris)) { _uris = JSON.parse(_uris); } _uris = _uris.concat(uris); RongIMClient.roomInfo.users[userId].uris = JSON.stringify(_uris); }, RTCUnpublishResourceMessage: function (message, uris) { handler(message, uris, function (_uri, uri, _uris, index) { _uris.splice(index, 1); }); }, RTCModifyResourceMessage: function (message, uris) { handler(message, uris, function (_uri, uri) { _uri.state = uri.state; }); }, RTCUserChangeMessage: function (message) { var content = message.content; var users = content.users; var UserState = { JOINED: 0, LEFT: 1, OFFLINE: 2 }; RongIMLib.RongUtil.forEach(users, function (user) { var state = user.state; var userId = user.userId; switch (+state) { case UserState.JOINED: RongIMClient.roomInfo.users[userId] = {}; break; case UserState.LEFT: case UserState.OFFLINE: delete RongIMClient.roomInfo.users[userId]; break; } }); } }; RongIMClient.RTCInnerListener = function (message) { var func = RTCMessage[message.messageType] || function () { }; var content = message.content; var uris = content.uris; func(message, uris); }; RongIMClient.Conversation = RongIMClient._dataAccessProvider.Conversation; return sdkInfo; }; ; /** var config = { appkey: appkey, token: token, dataAccessProvider:dataAccessProvider, opts: opts }; callback(_instance, userId); */ RongIMClient.initApp = function (config, callback) { RongIMClient.init(config.appkey, config.dataAccessProvider, config.opts, function () { var instance = RongIMClient._instance; //备用 var error = null; callback(error, instance); }); }; /** * 连接服务器,在整个应用全局只需要调用一次,断线后 SDK 会自动重连。 * * @param token 从服务端获取的用户身份令牌(Token)。 * @param callback 连接回调,返回连接的成功或者失败状态。 */ RongIMClient.connect = function (token, _callback, userId, serverConf) { RongIMLib.CheckParam.getInstance().check(["string", "object", "string|null|object|global|undefined", "object|null|global|undefined"], "connect", true, arguments); var connectCallback = { onSuccess: _callback.onSuccess, onTokenIncorrect: _callback.onTokenIncorrect, onError: function (errorCode) { RongIMClient.logger({ code: errorCode, funcName: "connect" }); _callback.onError(errorCode); } }; RongIMClient._dataAccessProvider.connect(token, connectCallback, userId, serverConf); }; RongIMClient.reconnect = function (callback, config) { var connectCallback = { onSuccess: callback.onSuccess, onTokenIncorrect: callback.onTokenIncorrect, onError: function (errorCode) { RongIMClient.logger({ code: errorCode, funcName: "connect" }); callback.onError(errorCode); } }; RongIMClient._dataAccessProvider.reconnect(connectCallback, config); }; /** * 注册消息类型,用于注册用户自定义的消息。 * 内建的消息类型已经注册过,不需要再次注册。 * 自定义消息声明需放在执行顺序最高的位置(在RongIMClient.init(appkey)之后即可) * @param objectName 消息内置名称 */ RongIMClient.registerMessageType = function (messageType, objectName, messageTag, messageContent, searchProps) { RongIMClient._dataAccessProvider.registerMessageType(messageType, objectName, messageTag, messageContent, searchProps); RongIMClient.RegisterMessage[messageType].messageName = messageType; RongIMClient.MessageType[messageType] = messageType; RongIMClient.MessageParams[messageType] = { objectName: objectName, msgTag: messageTag }; }; RongIMClient.prototype.registerMessageTypes = function (types) { types = types || {}; RongIMClient._dataAccessProvider.registerMessageTypes(types); }; /** * 设置连接状态变化的监听器。 * * @param listener 连接状态变化的监听器。 */ RongIMClient.setConnectionStatusListener = function (listener) { if (RongIMLib.RongUtil.isObject(listener) && RongIMLib.RongUtil.isFunction(listener.onChanged)) { RongIMClient.statusListeners.push(listener.onChanged); } }; RongIMClient.statusWatch = function (watcher) { if (RongIMLib.RongUtil.isFunction(watcher)) { RongIMClient.statusListeners.push(watcher); } }; /** * 设置接收消息的监听器。 * * @param listener 接收消息的监听器。 */ RongIMClient.setOnReceiveMessageListener = function (listener) { if (RongIMLib.RongUtil.isObject(listener) && RongIMLib.RongUtil.isFunction(listener.onReceived)) { RongIMClient.messageListeners.push(listener.onReceived); } }; /** * 清理所有连接相关的变量 */ RongIMClient.prototype.logout = function () { RongIMClient._dataAccessProvider.logout(); }; /** * 断开连接。 */ RongIMClient.prototype.disconnect = function () { RongIMClient._dataAccessProvider.disconnect(); }; RongIMClient.prototype.startCustomService = function (custId, callback, content) { if (!custId || !callback) return; var msg = new RongIMLib.HandShakeMessage(content); var me = this; RongIMLib.RongIMClient._memoryStore.custStore["isInit"] = true; RongIMClient.getInstance().sendMessage(RongIMLib.ConversationType.CUSTOMER_SERVICE, custId, msg, { onSuccess: function (data) { if (data.isBlack) { callback.onError(); me.stopCustomeService(custId, { onSuccess: function () { }, onError: function () { } }); } else { callback.onSuccess(); } }, onError: function () { callback.onError(); }, onBefore: function () { } }); }; RongIMClient.prototype.stopCustomeService = function (custId, callback) { if (!custId || !callback) return; var session = RongIMClient._memoryStore.custStore[custId]; if (!session) return; var msg = new RongIMLib.SuspendMessage({ sid: session.sid, uid: session.uid, pid: session.pid }); this.sendCustMessage(custId, msg, { onSuccess: function () { // delete RongIMClient._memoryStore.custStore[custId]; setTimeout(function () { callback.onSuccess(); }); }, onError: function () { setTimeout(function () { callback.onError(); }); } }); }; RongIMClient.prototype.switchToHumanMode = function (custId, callback) { if (!custId || !callback) return; var session = RongIMClient._memoryStore.custStore[custId]; if (!session) return; var msg = new RongIMLib.ChangeModeMessage({ sid: session.sid, uid: session.uid, pid: session.pid }); this.sendCustMessage(custId, msg, callback); }; RongIMClient.prototype.evaluateRebotCustomService = function (custId, isRobotResolved, sugest, callback) { if (!custId || !callback) return; var session = RongIMClient._memoryStore.custStore[custId]; if (!session) return; var msg = new RongIMLib.EvaluateMessage({ sid: session.sid, uid: session.uid, pid: session.pid, isRobotResolved: isRobotResolved, sugest: sugest, type: 0 }); this.sendCustMessage(custId, msg, callback); }; RongIMClient.prototype.evaluateHumanCustomService = function (custId, humanValue, sugest, callback) { if (!custId || !callback) return; var session = RongIMClient._memoryStore.custStore[custId]; if (!session) return; var msg = new RongIMLib.EvaluateMessage({ sid: session.sid, uid: session.uid, pid: session.pid, humanValue: humanValue, sugest: sugest, type: 1 }); this.sendCustMessage(custId, msg, callback); }; RongIMClient.prototype.sendCustMessage = function (custId, msg, callback) { RongIMClient.getInstance().sendMessage(RongIMLib.ConversationType.CUSTOMER_SERVICE, custId, msg, { onSuccess: function (data) { callback.onSuccess(); }, onError: function () { callback.onError(); }, onBefore: function () { } }); }; /** * 获取当前连接的状态。 */ RongIMClient.prototype.getCurrentConnectionStatus = function () { return RongIMClient._dataAccessProvider.getCurrentConnectionStatus(); }; /** * 获取当前使用的连接通道。 */ RongIMClient.prototype.getConnectionChannel = function () { if (RongIMLib.Transportations._TransportType == RongIMLib.Socket.XHR_POLLING) { return RongIMLib.ConnectionChannel.XHR_POLLING; } else if (RongIMLib.Transportations._TransportType == RongIMLib.Socket.WEBSOCKET) { return RongIMLib.ConnectionChannel.WEBSOCKET; } }; /** * 获取当前使用的本地储存提供者。 TODO */ RongIMClient.prototype.getStorageProvider = function () { if (RongIMClient._memoryStore.providerType == 1) { return "ServerDataProvider"; } else { return "OtherDataProvider"; } }; /** * 过滤聊天室消息(拉取最近聊天消息) * @param {string[]} msgFilterNames */ RongIMClient.prototype.setFilterMessages = function (msgFilterNames) { if (Object.prototype.toString.call(msgFilterNames) == "[object Array]") { RongIMClient._memoryStore.filterMessages = msgFilterNames; } }; RongIMClient.prototype.getAgoraDynamicKey = function (engineType, channelName, callback) { RongIMClient._dataAccessProvider.getAgoraDynamicKey(engineType, channelName, callback); }; /** * 获取当前连接用户的 UserId。 */ RongIMClient.prototype.getCurrentUserId = function () { return RongIMLib.Bridge._client.userId; }; /** * 获取服务器时间与本地时间的差值,单位为毫秒。 * 计算公式:差值 = 本地时间毫秒数 - 服务器时间毫秒数 * @param callback 获取的回调,返回差值。 */ RongIMClient.prototype.getDeltaTime = function () { return RongIMClient._dataAccessProvider.getDelaTime(); }; // #region Message RongIMClient.prototype.getMessage = function (messageId, callback) { RongIMClient._dataAccessProvider.getMessage(messageId, RongIMClient.logCallback(callback, "getMessage")); }; RongIMClient.prototype.deleteLocalMessages = function (conversationType, targetId, messageIds, callback) { RongIMClient._dataAccessProvider.removeLocalMessage(conversationType, targetId, messageIds, RongIMClient.logCallback(callback, "deleteLocalMessages")); }; RongIMClient.prototype.updateMessage = function (message, callback) { RongIMClient._dataAccessProvider.updateMessage(message, RongIMClient.logCallback(callback, "updateMessage")); }; RongIMClient.prototype.clearData = function () { return RongIMClient._dataAccessProvider.clearData(); }; RongIMClient.prototype.clearMessages = function (conversationType, targetId, callback) { RongIMClient._dataAccessProvider.clearMessages(conversationType, targetId, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "clearMessages" }); callback.onError(errorCode); }); } }); }; /**TODO 清楚本地存储的未读消息,目前清空内存中的未读消息 * [clearMessagesUnreadStatus 清空指定会话未读消息] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [用户id] * @param {ResultCallback} callback [返回值,参数回调] */ RongIMClient.prototype.clearMessagesUnreadStatus = function (conversationType, targetId, callback) { RongIMClient._dataAccessProvider.updateMessages(conversationType, targetId, "readStatus", null, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "clearMessagesUnreadStatus" }); callback.onError(errorCode); }); } }); }; // deleteRemoteMessages(conversationType: ConversationType, targetId: string, delMsgs: DeleteMessage[], callback: ResultCallback) { // CheckParam.getInstance().check(["number", "string|number", "array", "object"], "deleteRemoteMessages", false, arguments); // if (delMsgs.length == 0) { // var errorCode = ErrorCode.DELETE_MESSAGE_ID_IS_NULL; // RongIMClient.logger({ // code: errorCode, // funcName: "deleteRemoteMessages" // }); // callback.onError(ErrorCode.DELETE_MESSAGE_ID_IS_NULL); // return; // } else if (delMsgs.length > 100) { // delMsgs.length = 100; // } // // 后续增加,去掉注释即可 // callback.onSuccess(true); // // var modules = new RongIMClient.Protobuf.DeleteMsgInput(); // // modules.setType(conversationType); // // modules.setConversationId(targetId); // // modules.setMsgs(delMsgs); // // RongIMClient.bridge.queryMsg(33, MessageUtil.ArrayForm(modules.toArrayBuffer()), Bridge._client.userId, { // // onSuccess: function(info: any) { // // callback.onSuccess(true); // // }, // // onError: function(err: any) { // // callback.onError(err); // // } // // }, "DeleteMsgOutput"); // } /** * [deleteMessages 删除消息记录。] * @param {ConversationType} conversationType [description] * @param {string} targetId [description] * @param {number[]} messageIds [description] * @param {ResultCallback} callback [description] */ RongIMClient.prototype.deleteMessages = function (conversationType, targetId, messages, callback) { RongIMClient._dataAccessProvider.removeMessage(conversationType, targetId, messages, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "deleteMessages" }); callback.onError(errorCode); }); } }); }; RongIMClient.prototype.sendLocalMessage = function (message, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object"], "sendLocalMessage", false, arguments); RongIMClient._dataAccessProvider.updateMessage(message); this.sendMessage(message.conversationType, message.targetId, message.content, RongIMClient.logSendCallback(callback, "sendLocalMessage")); }; RongIMClient.prototype.getPullSetting = function (callback) { RongIMClient._dataAccessProvider.getPullSetting(callback); }; RongIMClient.prototype.setOfflineMessageDuration = function (duration, callback) { RongIMLib.CheckParam.getInstance().check(["number", "object"], "setOfflineMessageDuration", true, arguments); RongIMClient._dataAccessProvider.setOfflineMessageDuration(duration, callback); }; /** * [sendMessage 发送消息。] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [目标Id] * @param {MessageContent} messageContent [消息类型] * @param {SendMessageCallback} sendCallback [] * @param {ResultCallback} resultCallback [返回值,函数回调] * @param {string} pushContent [] * @param {string} pushData [] */ RongIMClient.prototype.sendMessage = function (conversationType, targetId, messageContent, sendCallback, mentiondMsg, pushText, appData, methodType, params) { RongIMLib.CheckParam.getInstance().check(["number", "string", "object", "object", "undefined|object|null|global|boolean", "undefined|object|null|global|string", "undefined|object|null|global|string", "undefined|object|null|global|number", "undefined|object|null|global"], "sendMessage", false, arguments); if (!RongIMLib.RongUtil.isString(targetId)) { return sendCallback.onError(RongIMLib.ErrorCode.PARAMETER_ERROR); } RongIMClient._dataAccessProvider.sendMessage(conversationType, targetId, messageContent, RongIMClient.logSendCallback(sendCallback, "sendMessage"), mentiondMsg, pushText, appData, methodType, params); }; RongIMClient.prototype.sendReceiptResponse = function (conversationType, targetId, sendCallback) { RongIMClient._dataAccessProvider.sendReceiptResponse(conversationType, targetId, RongIMClient.logSendCallback(sendCallback, "sendReceiptResponse")); }; RongIMClient.prototype.sendTypingStatusMessage = function (conversationType, targetId, messageName, sendCallback) { RongIMClient._dataAccessProvider.sendTypingStatusMessage(conversationType, targetId, messageName, RongIMClient.logSendCallback(sendCallback, "sendTypingStatusMessage")); }; /** * [sendStatusMessage description] * @param {MessageContent} messageContent [description] * @param {SendMessageCallback} sendCallback [description] * @param {ResultCallback} resultCallback [description] */ RongIMClient.prototype.sendStatusMessage = function (messageContent, sendCallback, resultCallback) { throw new Error("Not implemented yet"); }; /** * [sendTextMessage 发送TextMessage快捷方式] * @param {string} content [消息内容] * @param {ResultCallback} resultCallback [返回值,参数回调] */ RongIMClient.prototype.sendTextMessage = function (conversationType, targetId, content, sendMessageCallback) { RongIMClient._dataAccessProvider.sendTextMessage(conversationType, targetId, content, RongIMClient.logSendCallback(sendMessageCallback, "sendTextMessage")); }; RongIMClient.prototype.sendRecallMessage = function (content, sendMessageCallback) { var callback = RongIMClient.logSendCallback(sendMessageCallback, "sendRecallMessage"); var senderUserId = content.senderUserId; var userId = RongIMLib.Bridge._client.userId; var isOther = (senderUserId != userId); if (isOther) { var callback = RongIMClient.logSendCallback(sendMessageCallback, "sendRecallMessage"); callback.onError(RongIMLib.ErrorCode.RECALL_MESSAGE, content); return; } RongIMClient._dataAccessProvider.sendRecallMessage(content, callback); }; /** * [insertMessage 向本地插入一条消息,不发送到服务器。] * @param {ConversationType} conversationType [description] * @param {string} targetId [description] * @param {string} senderUserId [description] * @param {MessageContent} content [description] * @param {ResultCallback} callback [description] */ RongIMClient.prototype.insertMessage = function (conversationType, targetId, content, callback) { RongIMClient._dataAccessProvider.addMessage(conversationType, targetId, content, RongIMClient.logCallback(callback, "insertMessage")); }; RongIMClient.prototype.setMessageContent = function (messageId, content, objectName) { RongIMClient._dataAccessProvider.setMessageContent(messageId, content, objectName); }; ; RongIMClient.prototype.setMessageSearchField = function (messageId, content, searchFiles) { RongIMClient._dataAccessProvider.setMessageContent(messageId, content, searchFiles); }; ; /** * [getHistoryMessages 拉取历史消息记录。] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [用户Id] * @param {number|null} pullMessageTime [拉取历史消息起始位置(格式为毫秒数),可以为null] * @param {number} count [历史消息数量] * @param {ResultCallback} callback [回调函数] * @param {string} objectName [objectName] */ RongIMClient.prototype.getHistoryMessages = function (conversationType, targetId, timestamp, count, callback, objectname, order) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "number|null|global|object", "number", "object", "undefined|object|null|global|string", "number|null|global|object"], "getHistoryMessages", false, arguments); if (count > 20) { throw new Error("HistroyMessage count must be less than or equal to 20!"); } if (conversationType.valueOf() < 0) { throw new Error("ConversationType must be greater than -1"); } RongIMClient._dataAccessProvider.getHistoryMessages(conversationType, targetId, timestamp, count, RongIMClient.logCallback(callback, "getHistoryMessages"), objectname, order); }; /** * [getRemoteHistoryMessages 拉取某个时间戳之前的消息] * @param {ConversationType} conversationType [description] * @param {string} targetId [description] * @param {Date} dateTime [description] * @param {number} count [description] * @param {ResultCallback} callback [description] */ RongIMClient.prototype.getRemoteHistoryMessages = function (conversationType, targetId, timestamp, count, callback, config) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "number|null|global|object", "number", "object", "undefined|null|global|object"], "getRemoteHistoryMessages", false, arguments); var funcName = "getRemoteHistoryMessages"; var log = { errorCode: RongIMLib.ErrorCode.RC_CONN_PROTO_VERSION_ERROR, funcName: "getRemoteHistoryMessages" }; if (count > 20) { RongIMClient.logger(log); callback.onError(RongIMLib.ErrorCode.RC_CONN_PROTO_VERSION_ERROR); return; } if (conversationType.valueOf() < 0) { RongIMClient.logger(log); callback.onError(RongIMLib.ErrorCode.RC_CONN_PROTO_VERSION_ERROR); return; } RongIMClient._dataAccessProvider.getRemoteHistoryMessages(conversationType, targetId, timestamp, count, RongIMClient.logCallback(callback, funcName), config); }; RongIMClient.prototype.clearHistoryMessages = function (params, callback) { RongIMClient._dataAccessProvider.clearHistoryMessages(params, callback); }; RongIMClient.prototype.clearRemoteHistoryMessages = function (params, callback) { RongIMClient._dataAccessProvider.clearRemoteHistoryMessages(params, RongIMClient.logCallback(callback, "clearRemoteHistoryMessages")); }; RongIMClient.prototype.deleteRemoteMessages = function (conversationType, targetId, messages, callback) { RongIMClient._dataAccessProvider.deleteRemoteMessages(conversationType, targetId, messages, RongIMClient.logCallback(callback, "deleteRemoteMessages")); }; /** * [hasRemoteUnreadMessages 是否有未接收的消息,jsonp方法] * @param {string} appkey [appkey] * @param {string} token [token] * @param {ConnectCallback} callback [返回值,参数回调] */ RongIMClient.prototype.hasRemoteUnreadMessages = function (token, callback) { RongIMClient._dataAccessProvider.hasRemoteUnreadMessages(token, RongIMClient.logCallback(callback, "hasRemoteUnreadMessages")); }; RongIMClient.prototype.getTotalUnreadCount = function (callback, conversationTypes) { RongIMClient._dataAccessProvider.getTotalUnreadCount({ onSuccess: function (count) { setTimeout(function () { callback.onSuccess(count); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "getTotalUnreadCount" }); callback.onError(errorCode); }); } }, conversationTypes); }; /** * [getConversationUnreadCount 指定多种会话类型获取未读消息数] * @param {ResultCallback} callback [返回值,参数回调。] * @param {ConversationType[]} ...conversationTypes [会话类型。] */ RongIMClient.prototype.getConversationUnreadCount = function (conversationTypes, callback) { RongIMClient._dataAccessProvider.getConversationUnreadCount(conversationTypes, { onSuccess: function (count) { setTimeout(function () { callback.onSuccess(count); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "getConversationUnreadCount" }); callback.onError(errorCode); }); } }); }; /** * [getUnreadCount 指定用户、会话类型的未读消息总数。] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [用户Id] */ RongIMClient.prototype.getUnreadCount = function (conversationType, targetId, callback) { RongIMClient._dataAccessProvider.getUnreadCount(conversationType, targetId, { onSuccess: function (count) { setTimeout(function () { callback.onSuccess(count); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "getUnreadCount" }); callback.onError(errorCode); }); } }); }; RongIMClient.prototype.setUnreadCount = function (conversationType, targetId, count) { RongIMLib.CheckParam.getInstance().check(["number", "string", "number"], "setUnreadCount", false, arguments); RongIMClient._dataAccessProvider.setUnreadCount(conversationType, targetId, count); }; RongIMClient.prototype.clearUnreadCountByTimestamp = function (conversationType, targetId, timestamp, callback) { RongIMClient._dataAccessProvider.clearUnreadCountByTimestamp(conversationType, targetId, timestamp, RongIMClient.logCallback(callback, "clearUnreadCountByTimestamp")); }; /** * 清楚会话未读消息数 * @param {ConversationType} conversationType 会话类型 * @param {string} targetId 目标Id * @param {ResultCallback} callback 返回值,函数回调 */ RongIMClient.prototype.clearUnreadCount = function (conversationType, targetId, callback) { RongIMClient._dataAccessProvider.clearUnreadCount(conversationType, targetId, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "clearUnreadCount" }); callback.onError(errorCode); }); } }); }; RongIMClient.prototype.clearTotalUnreadCount = function (callback) { RongIMClient._dataAccessProvider.clearTotalUnreadCount({ onSuccess: function (bool) { callback.onSuccess(bool); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: 'clearTotalUnreadCount' }); callback.onError(errorCode); }); } }); }; RongIMClient.prototype.clearLocalStorage = function (callback) { RongIMClient._storageProvider.clearItem(); callback(); }; RongIMClient.prototype.setMessageExtra = function (messageId, value, callback) { RongIMClient._dataAccessProvider.setMessageExtra(messageId, value, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "setMessageExtra" }); callback.onError(errorCode); }); } }); }; RongIMClient.prototype.setMessageReceivedStatus = function (messageUId, receivedStatus, callback) { RongIMClient._dataAccessProvider.setMessageReceivedStatus(messageUId, receivedStatus, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "setMessageReceivedStatus" }); callback.onError(errorCode); }); } }); }; RongIMClient.prototype.setMessageStatus = function (conersationType, targetId, timestamp, status, callback) { RongIMClient._dataAccessProvider.setMessageStatus(conersationType, targetId, timestamp, status, RongIMClient.logCallback(callback, "setMessageStatus")); }; RongIMClient.prototype.setMessageSentStatus = function (messageId, sentStatus, callback) { RongIMClient._dataAccessProvider.setMessageSentStatus(messageId, sentStatus, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "setMessageSentStatus" }); callback.onError(errorCode); }); } }); }; // #endregion Message // #region TextMessage Draft /** * clearTextMessageDraft 清除指定会话和消息类型的草稿。 * @param {ConversationType} conversationType 会话类型 * @param {string} targetId 目标Id */ RongIMClient.prototype.clearTextMessageDraft = function (conversationType, targetId) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "clearTextMessageDraft", false, arguments); var key = "darf_" + conversationType + "_" + targetId; delete RongIMClient._memoryStore[key]; return true; }; /** * [getTextMessageDraft 获取指定消息和会话的草稿。] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [目标Id] */ RongIMClient.prototype.getTextMessageDraft = function (conversationType, targetId) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "getTextMessageDraft", false, arguments); if (targetId == "" || conversationType < 0) { throw new Error("params error : " + RongIMLib.ErrorCode.DRAF_GET_ERROR); } var key = "darf_" + conversationType + "_" + targetId; return RongIMClient._memoryStore[key]; }; /** * [saveTextMessageDraft description] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [目标Id] * @param {string} value [草稿值] */ RongIMClient.prototype.saveTextMessageDraft = function (conversationType, targetId, value) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "string", "object"], "saveTextMessageDraft", false, arguments); var key = "darf_" + conversationType + "_" + targetId; RongIMClient._memoryStore[key] = value; return true; }; // #endregion TextMessage Draft // #region Conversation RongIMClient.prototype.searchConversationByContent = function (keyword, callback, conversationTypes) { RongIMClient._dataAccessProvider.searchConversationByContent(keyword, RongIMClient.logCallback(callback, "searchConversationByContent"), conversationTypes); }; RongIMClient.prototype.searchMessageByContent = function (conversationType, targetId, keyword, timestamp, count, total, callback) { RongIMClient._dataAccessProvider.searchMessageByContent(conversationType, targetId, keyword, timestamp, count, total, RongIMClient.logCallback(callback, "searchMessageByContent")); }; RongIMClient.prototype.clearCache = function () { RongIMClient._dataAccessProvider.clearCache(); }; RongIMClient.prototype.clearConversations = function (callback) { var conversationTypes = []; for (var _i = 1; _i < arguments.length; _i++) { conversationTypes[_i - 1] = arguments[_i]; } if (conversationTypes.length == 0) { conversationTypes = [RongIMLib.ConversationType.CHATROOM, RongIMLib.ConversationType.CUSTOMER_SERVICE, RongIMLib.ConversationType.DISCUSSION, RongIMLib.ConversationType.GROUP, RongIMLib.ConversationType.PRIVATE, RongIMLib.ConversationType.SYSTEM, RongIMLib.ConversationType.PUBLIC_SERVICE, RongIMLib.ConversationType.APP_PUBLIC_SERVICE]; } RongIMClient._dataAccessProvider.clearConversations(conversationTypes, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "clearConversations" }); callback.onError(errorCode); }); } }); }; /** * [getConversation 获取指定会话,此方法需在getConversationList之后执行] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [目标Id] * @param {ResultCallback} callback [返回值,函数回调] */ RongIMClient.prototype.getConversation = function (conversationType, targetId, callback) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "getConversation", false, arguments); RongIMClient._dataAccessProvider.getConversation(conversationType, targetId, { onSuccess: function (conver) { setTimeout(function () { callback.onSuccess(conver); }); }, onError: function (error) { setTimeout(function () { RongIMClient.logger({ code: error, funcName: "getConversation" }); callback.onError(error); }); } }); }; /** * [pottingConversation 组装会话列表] * @param {any} tempConver [临时会话] * conver_conversationType_targetId_no. * msg_conversationType_targetId_no. */ RongIMClient.prototype.pottingConversation = function (tempConver) { var self = this, isUseReplace = false; RongIMClient._dataAccessProvider.getConversation(tempConver.type, tempConver.userId, { onSuccess: function (conver) { if (!conver) { conver = new RongIMLib.Conversation(); } else { isUseReplace = true; } conver.conversationType = tempConver.type; conver.targetId = tempConver.userId; conver.latestMessage = RongIMLib.MessageUtil.messageParser(tempConver.msg); conver.latestMessageId = conver.latestMessage.messageId; conver.objectName = conver.latestMessage.objectName; conver.receivedStatus = conver.latestMessage.receivedStatus; conver.receivedTime = conver.latestMessage.receiveTime; conver.sentStatus = conver.latestMessage.sentStatus; conver.sentTime = conver.latestMessage.sentTime; var mentioneds = RongIMClient._storageProvider.getItem("mentioneds_" + RongIMLib.Bridge._client.userId + '_' + conver.conversationType + '_' + conver.targetId); if (mentioneds) { var info = JSON.parse(mentioneds); conver.mentionedMsg = info[tempConver.type + "_" + tempConver.userId]; } if (!isUseReplace) { if (RongIMLib.RongUtil.supportLocalStorage()) { // var count = RongIMClient._storageProvider.getItem("cu" + Bridge._client.userId + tempConver.type + tempConver.userId); conver.unreadMessageCount = RongIMLib.UnreadCountHandler.get(tempConver.type, tempConver.userId); } else { conver.unreadMessageCount = 0; } } if (conver.conversationType == RongIMLib.ConversationType.DISCUSSION) { self.getDiscussion(tempConver.userId, { onSuccess: function (info) { conver.conversationTitle = info.name; }, onError: function (error) { } }); } RongIMClient._dataAccessProvider.addConversation(conver, { onSuccess: function (data) { } }); }, onError: function (error) { } }); }; RongIMClient.prototype.addConversation = function (conversation, callback) { RongIMClient._dataAccessProvider.addConversation(conversation, callback); }; RongIMClient.prototype.sortConversationList = function (conversationList) { var convers = []; for (var i = 0, len = conversationList.length; i < len; i++) { if (!conversationList[i]) { continue; } if (conversationList[i].isTop) { convers.push(conversationList[i]); conversationList.splice(i, 1); continue; } for (var j = 0; j < len - i - 1; j++) { if (conversationList[j].sentTime < conversationList[j + 1].sentTime) { var swap = conversationList[j]; conversationList[j] = conversationList[j + 1]; conversationList[j + 1] = swap; } } } return RongIMClient._memoryStore.conversationList = convers.concat(conversationList); }; RongIMClient.prototype.getConversationList = function (callback, conversationTypes, count, isGetHiddenConvers) { RongIMLib.CheckParam.getInstance().check(["object", "null|undefined|array|object|global", "number|undefined|null|object|global", "boolean|undefined|null|object|global"], "getConversationList", false, arguments); var me = this; RongIMClient._dataAccessProvider.getConversationList({ onSuccess: function (data) { if (conversationTypes || RongIMClient._dataAccessProvider) { setTimeout(function () { callback.onSuccess(data); }); } else { setTimeout(function () { callback.onSuccess(RongIMClient._memoryStore.conversationList); }); } }, onError: function (error) { setTimeout(function () { RongIMClient.logger({ code: error, funcName: "getConversationList" }); callback.onError(error); }); } }, conversationTypes, count, isGetHiddenConvers); }; RongIMClient.prototype.getRemoteConversationList = function (callback, conversationTypes, count, isGetHiddenConvers) { RongIMLib.CheckParam.getInstance().check(["object", "null|array|object|global", "number|undefined|null|object|global", "boolean|undefined|null|object|global"], "getRemoteConversationList", false, arguments); RongIMClient._dataAccessProvider.getRemoteConversationList(RongIMClient.logCallback(callback, "getRemoteConversationList"), conversationTypes, count, isGetHiddenConvers); }; RongIMClient.prototype.updateConversation = function (conversation) { return RongIMClient._dataAccessProvider.updateConversation(conversation); }; /** * [createConversation 创建会话。] * @param {number} conversationType [会话类型] * @param {string} targetId [目标Id] * @param {string} converTitle [会话标题] * @param {boolean} islocal [是否同步到服务器,ture:同步,false:不同步] */ RongIMClient.prototype.createConversation = function (conversationType, targetId, converTitle) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "string"], "createConversation", false, arguments); var conver = new RongIMLib.Conversation(); // var unreadContent: string = RongIMClient._storageProvider.getItem("cu" + Bridge._client.userId + conversationType + targetId); // var unreadCount = Number(unreadContent) || 0; conver.targetId = targetId; conver.conversationType = conversationType; conver.conversationTitle = converTitle; conver.latestMessage = {}; conver.unreadMessageCount = 0; return conver; }; //TODO 删除本地和服务器、删除本地和服务器分开 RongIMClient.prototype.removeConversation = function (conversationType, targetId, callback) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "removeConversation", false, arguments); RongIMClient._dataAccessProvider.removeConversation(conversationType, targetId, RongIMClient.logCallback(callback, "removeConversation")); }; RongIMClient.prototype.setConversationHidden = function (conversationType, targetId, isHidden) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "boolean"], "setConversationHidden", false, arguments); RongIMClient._dataAccessProvider.setConversationHidden(conversationType, targetId, isHidden); }; RongIMClient.prototype.setConversationToTop = function (conversationType, targetId, isTop, callback) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "boolean", "object"], "setConversationToTop", false, arguments); RongIMClient._dataAccessProvider.setConversationToTop(conversationType, targetId, isTop, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "setConversationToTop" }); callback.onError(errorCode); }); } }); }; // #endregion Conversation // #region Notifications /** * [getConversationNotificationStatus 获取指定用户和会话类型免提醒。] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [目标Id] * @param {ResultCallback} callback [返回值,函数回调] */ RongIMClient.prototype.getConversationNotificationStatus = function (conversationType, targetId, callback) { var params = { conversationType: conversationType, targetId: targetId }; RongIMClient._dataAccessProvider.getConversationNotificationStatus(params, RongIMClient.logCallback(callback, "getConversationNotificationStatus")); }; /** * [setConversationNotificationStatus 设置指定用户和会话类型免提醒。] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [目标Id] * @param {ResultCallback} callback [返回值,函数回调] */ RongIMClient.prototype.setConversationNotificationStatus = function (conversationType, targetId, notificationStatus, callback) { var params = { conversationType: conversationType, targetId: targetId, status: status }; RongIMClient._dataAccessProvider.setConversationNotificationStatus(params, RongIMClient.logCallback(callback, "setConversationNotificationStatus")); }; /** * [getNotificationQuietHours 获取免提醒消息时间。] * @param {GetNotificationQuietHoursCallback} callback [返回值,函数回调] */ RongIMClient.prototype.getNotificationQuietHours = function (callback) { throw new Error("Not implemented yet"); }; /** * [removeNotificationQuietHours 移除免提醒消息时间。] * @param {GetNotificationQuietHoursCallback} callback [返回值,函数回调] */ RongIMClient.prototype.removeNotificationQuietHours = function (callback) { throw new Error("Not implemented yet"); }; /** * [setNotificationQuietHours 设置免提醒消息时间。] * @param {GetNotificationQuietHoursCallback} callback [返回值,函数回调] */ RongIMClient.prototype.setNotificationQuietHours = function (startTime, spanMinutes, callback) { throw new Error("Not implemented yet"); }; // #endregion Notifications // #region Discussion /** * [addMemberToDiscussion 加入讨论组] * @param {string} discussionId [讨论组Id] * @param {string[]} userIdList [讨论中成员] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.addMemberToDiscussion = function (discussionId, userIdList, callback) { RongIMLib.CheckParam.getInstance().check(["string", "array", "object"], "addMemberToDiscussion", false, arguments); RongIMClient._dataAccessProvider.addMemberToDiscussion(discussionId, userIdList, RongIMClient.logCallback(callback, "addMemberToDiscussion")); }; /** * [createDiscussion 创建讨论组] * @param {string} name [讨论组名称] * @param {string[]} userIdList [讨论组成员] * @param {CreateDiscussionCallback} callback [返回值,函数回调] */ RongIMClient.prototype.createDiscussion = function (name, userIdList, callback) { RongIMLib.CheckParam.getInstance().check(["string", "array", "object"], "createDiscussion", false, arguments); RongIMClient._dataAccessProvider.createDiscussion(name, userIdList, callback); }; /** * [getDiscussion 获取讨论组信息] * @param {string} discussionId [讨论组Id] * @param {ResultCallback} callback [返回值,函数回调] */ RongIMClient.prototype.getDiscussion = function (discussionId, callback) { RongIMLib.CheckParam.getInstance().check(["string", "object"], "getDiscussion", false, arguments); RongIMClient._dataAccessProvider.getDiscussion(discussionId, RongIMClient.logCallback(callback, "getDiscussion")); }; /** * [quitDiscussion 退出讨论组] * @param {string} discussionId [讨论组Id] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.quitDiscussion = function (discussionId, callback) { RongIMLib.CheckParam.getInstance().check(["string", "object"], "quitDiscussion", false, arguments); RongIMClient._dataAccessProvider.quitDiscussion(discussionId, RongIMClient.logCallback(callback, "quitDiscussion")); }; /** * [removeMemberFromDiscussion 将指定成员移除讨论租] * @param {string} discussionId [讨论组Id] * @param {string} userId [被移除的用户Id] * @param {OperationCallback} callback [返回值,参数回调] */ RongIMClient.prototype.removeMemberFromDiscussion = function (discussionId, userId, callback) { RongIMLib.CheckParam.getInstance().check(["string", "string", "object"], "removeMemberFromDiscussion", false, arguments); RongIMClient._dataAccessProvider.removeMemberFromDiscussion(discussionId, userId, RongIMClient.logCallback(callback, "removeMemberFromDiscussion")); }; /** * [setDiscussionInviteStatus 设置讨论组邀请状态] * @param {string} discussionId [讨论组Id] * @param {DiscussionInviteStatus} status [邀请状态] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.setDiscussionInviteStatus = function (discussionId, status, callback) { RongIMLib.CheckParam.getInstance().check(["string", "number", "object"], "setDiscussionInviteStatus", false, arguments); RongIMClient._dataAccessProvider.setDiscussionInviteStatus(discussionId, status, RongIMClient.logCallback(callback, "setDiscussionInviteStatus")); }; /** * [setDiscussionName 设置讨论组名称] * @param {string} discussionId [讨论组Id] * @param {string} name [讨论组名称] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.setDiscussionName = function (discussionId, name, callback) { RongIMLib.CheckParam.getInstance().check(["string", "string", "object"], "setDiscussionName", false, arguments); RongIMClient._dataAccessProvider.setDiscussionName(discussionId, name, RongIMClient.logCallback(callback, "setDiscussionName")); }; // #endregion Discussion // #region ChatRoom /** * [加入聊天室。] * @param {string} chatroomId [聊天室Id] * @param {number} messageCount [拉取消息数量,-1为不拉去消息] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.joinChatRoom = function (chatroomId, messageCount, callback) { RongIMLib.CheckParam.getInstance().check(["string", "number", "object"], "joinChatRoom", false, arguments); if (chatroomId == "") { setTimeout(function () { var errorCode = RongIMLib.ErrorCode.CHATROOM_ID_ISNULL; RongIMClient.logger({ code: errorCode, funcName: "joinChatRoom" }); callback.onError(RongIMLib.ErrorCode.CHATROOM_ID_ISNULL); }); return; } RongIMClient._dataAccessProvider.joinChatRoom(chatroomId, messageCount, RongIMClient.logCallback(callback, "joinChatRoom")); }; RongIMClient.prototype.setDeviceInfo = function (device) { RongIMClient._dataAccessProvider.setDeviceInfo(device); }; RongIMClient.prototype.setChatroomHisMessageTimestamp = function (chatRoomId, timestamp) { RongIMLib.CheckParam.getInstance().check(["string", "number"], "setChatroomHisMessageTimestamp", false, arguments); RongIMClient._dataAccessProvider.setChatroomHisMessageTimestamp(chatRoomId, timestamp); }; RongIMClient.prototype.getChatRoomHistoryMessages = function (chatRoomId, count, order, callback) { RongIMLib.CheckParam.getInstance().check(["string", "number", "number", "object"], "getChatRoomHistoryMessages", false, arguments); RongIMClient._dataAccessProvider.getChatRoomHistoryMessages(chatRoomId, count, order, RongIMClient.logCallback(callback, "getChatRoomHistoryMessages")); }; RongIMClient.prototype.getChatRoomInfo = function (chatRoomId, count, order, callback) { RongIMLib.CheckParam.getInstance().check(["string", "number", "number", "object"], "getChatRoomInfo", false, arguments); RongIMClient._dataAccessProvider.getChatRoomInfo(chatRoomId, count, order, RongIMClient.logCallback(callback, "getChatRoomInfo")); }; /** * [退出聊天室] * @param {string} chatroomId [聊天室Id] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.quitChatRoom = function (chatroomId, callback) { RongIMLib.CheckParam.getInstance().check(["string", "object"], "quitChatRoom", false, arguments); RongIMClient._dataAccessProvider.quitChatRoom(chatroomId, RongIMClient.logCallback(callback, "quitChatRoom")); }; RongIMClient.prototype.setChatroomEntry = function (chatroomId, chatroomEntry, callback) { RongIMLib.CheckParam.getInstance().check(['string', 'object', 'object'], 'setChatroomEntry', false, arguments); RongIMClient._dataAccessProvider.setChatroomEntry(chatroomId, chatroomEntry, RongIMClient.logCallback(callback, "setChatroomEntry")); }; RongIMClient.prototype.forceSetChatroomEntry = function (chatroomId, chatroomEntry, callback) { RongIMLib.CheckParam.getInstance().check(['string', 'object', 'object'], 'setChatroomEntry', false, arguments); RongIMClient._dataAccessProvider.forceSetChatroomEntry(chatroomId, chatroomEntry, RongIMClient.logCallback(callback, "setChatroomEntry")); }; RongIMClient.prototype.getChatroomEntry = function (chatroomId, key, callback) { RongIMLib.CheckParam.getInstance().check(['string', 'string', 'object'], 'getChatroomEntry', false, arguments); RongIMClient._dataAccessProvider.getChatroomEntry(chatroomId, key, RongIMClient.logCallback(callback, "setChatroomEntry")); }; RongIMClient.prototype.getAllChatroomEntries = function (chatroomId, callback) { RongIMLib.CheckParam.getInstance().check(['string', 'object'], 'getAllChatroomEntries', false, arguments); RongIMClient._dataAccessProvider.getAllChatroomEntries(chatroomId, RongIMClient.logCallback(callback, "setChatroomEntry")); }; RongIMClient.prototype.removeChatroomEntry = function (chatroomId, chatroomEntry, callback) { RongIMLib.CheckParam.getInstance().check(['string', 'object', 'object'], 'removeChatroomEntry', false, arguments); RongIMClient._dataAccessProvider.removeChatroomEntry(chatroomId, chatroomEntry, RongIMClient.logCallback(callback, "setChatroomEntry")); }; RongIMClient.prototype.forceRemoveChatroomEntry = function (chatroomId, chatroomEntry, callback) { RongIMLib.CheckParam.getInstance().check(['string', 'object', 'object'], 'removeChatroomEntry', false, arguments); RongIMClient._dataAccessProvider.forceRemoveChatroomEntry(chatroomId, chatroomEntry, RongIMClient.logCallback(callback, "setChatroomEntry")); }; // #endregion ChatRoom // #region Public Service RongIMClient.prototype.getRemotePublicServiceList = function (callback, pullMessageTime) { RongIMClient._dataAccessProvider.getRemotePublicServiceList(RongIMClient.logCallback(callback, "getRemotePublicServiceList"), pullMessageTime); }; /** * [getPublicServiceList ]获取本地的公共账号列表 * @param {ResultCallback} callback [返回值,参数回调] */ RongIMClient.prototype.getPublicServiceList = function (callback) { if (RongIMClient._memoryStore.depend.openMp) { RongIMLib.CheckParam.getInstance().check(["object"], "getPublicServiceList", false, arguments); this.getRemotePublicServiceList(RongIMClient.logCallback(callback, "getPublicServiceList")); } }; /** * [getPublicServiceProfile ] 获取某公共服务信息。 * @param {PublicServiceType} publicServiceType [公众服务类型。] * @param {string} publicServiceId [公共服务 Id。] * @param {ResultCallback} callback [公共账号信息回调。] */ RongIMClient.prototype.getPublicServiceProfile = function (publicServiceType, publicServiceId, callback) { if (RongIMClient._memoryStore.depend.openMp) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "getPublicServiceProfile", false, arguments); RongIMClient._dataAccessProvider.getPublicServiceProfile(publicServiceType, publicServiceId, RongIMClient.logCallback(callback, "getPublicServiceProfile")); } }; /** * [pottingPublicSearchType ] 公众好查询类型 * @param {number} bussinessType [ 0-all 1-mp 2-mc] * @param {number} searchType [0-exact 1-fuzzy] */ RongIMClient.prototype.pottingPublicSearchType = function (bussinessType, searchType) { if (RongIMClient._memoryStore.depend.openMp) { var bits = 0; if (bussinessType == 0) { bits |= 3; if (searchType == 0) { bits |= 12; } else { bits |= 48; } } else if (bussinessType == 1) { bits |= 1; if (searchType == 0) { bits |= 8; } else { bits |= 32; } } else { bits |= 2; if (bussinessType == 0) { bits |= 4; } else { bits |= 16; } } return bits; } }; /** * [searchPublicService ]按公众服务类型搜索公众服务。 * @param {SearchType} searchType [搜索类型枚举。] * @param {string} keywords [搜索关键字。] * @param {ResultCallback} callback [搜索结果回调。] */ RongIMClient.prototype.searchPublicService = function (searchType, keywords, callback) { if (RongIMClient._memoryStore.depend.openMp) { RongIMLib.CheckParam.getInstance().check(["number", "string", "object"], "searchPublicService", false, arguments); var modules = new RongIMClient.Protobuf.SearchMpInput(); modules.setType(this.pottingPublicSearchType(0, searchType)); modules.setId(keywords); RongIMClient.bridge.queryMsg(29, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, RongIMClient.logCallback(callback, "searchPublicService"), "SearchMpOutput"); } }; /** * [searchPublicServiceByType ]按公众服务类型搜索公众服务。 * @param {PublicServiceType} publicServiceType [公众服务类型。] * @param {SearchType} searchType [搜索类型枚举。] * @param {string} keywords [搜索关键字。] * @param {ResultCallback} callback [搜索结果回调。] */ RongIMClient.prototype.searchPublicServiceByType = function (publicServiceType, searchType, keywords, callback) { if (RongIMClient._memoryStore.depend.openMp) { RongIMLib.CheckParam.getInstance().check(["number", "number", "string", "object"], "searchPublicServiceByType", false, arguments); var type = publicServiceType == RongIMLib.ConversationType.APP_PUBLIC_SERVICE ? 2 : 1; var modules = new RongIMClient.Protobuf.SearchMpInput(); modules.setType(this.pottingPublicSearchType(type, searchType)); modules.setId(keywords); RongIMClient.bridge.queryMsg(29, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, RongIMClient.logCallback(callback, "searchPublicServiceByType"), "SearchMpOutput"); } }; /** * [subscribePublicService ] 订阅公众号。 * @param {PublicServiceType} publicServiceType [公众服务类型。] * @param {string} publicServiceId [公共服务 Id。] * @param {OperationCallback} callback [订阅公众号回调。] */ RongIMClient.prototype.subscribePublicService = function (publicServiceType, publicServiceId, callback) { if (RongIMClient._memoryStore.depend.openMp) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "subscribePublicService", false, arguments); var modules = new RongIMClient.Protobuf.MPFollowInput(), me = this, follow = publicServiceType == RongIMLib.ConversationType.APP_PUBLIC_SERVICE ? "mcFollow" : "mpFollow"; modules.setId(publicServiceId); RongIMClient.bridge.queryMsg(follow, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function () { me.getRemotePublicServiceList({ onSuccess: function () { }, onError: function () { } }); callback.onSuccess(); }, onError: function (code) { var errorCode = code; RongIMClient.logger({ code: errorCode, funcName: "subscribePublicService" }); callback.onError(code); } }, "MPFollowOutput"); } }; /** * [unsubscribePublicService ] 取消订阅公众号。 * @param {PublicServiceType} publicServiceType [公众服务类型。] * @param {string} publicServiceId [公共服务 Id。] * @param {OperationCallback} callback [取消订阅公众号回调。] */ RongIMClient.prototype.unsubscribePublicService = function (publicServiceType, publicServiceId, callback) { if (RongIMClient._memoryStore.depend.openMp) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "unsubscribePublicService", false, arguments); var modules = new RongIMClient.Protobuf.MPFollowInput(), me = this, follow = publicServiceType == RongIMLib.ConversationType.APP_PUBLIC_SERVICE ? "mcUnFollow" : "mpUnFollow"; modules.setId(publicServiceId); RongIMClient.bridge.queryMsg(follow, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function () { RongIMClient._memoryStore.publicServiceMap.remove(publicServiceType, publicServiceId); callback.onSuccess(); }, onError: function (code) { var errorCode = code; RongIMClient.logger({ code: errorCode, funcName: "unsubscribePublicService" }); callback.onError(code); } }, "MPFollowOutput"); } }; // #endregion Public Service // #region Blacklist /** * [加入黑名单] * @param {string} userId [将被加入黑名单的用户Id] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.addToBlacklist = function (userId, callback) { RongIMLib.CheckParam.getInstance().check(["string|number", "object"], "addToBlacklist", false, arguments); RongIMClient._dataAccessProvider.addToBlacklist(userId, RongIMClient.logCallback(callback, "addToBlacklist")); }; /** * [获取黑名单列表] * @param {GetBlacklistCallback} callback [返回值,函数回调] */ RongIMClient.prototype.getBlacklist = function (callback) { RongIMLib.CheckParam.getInstance().check(["object"], "getBlacklist", false, arguments); RongIMClient._dataAccessProvider.getBlacklist(callback); }; /** * [得到指定人员再黑名单中的状态] * @param {string} userId [description] * @param {ResultCallback} callback [返回值,函数回调] */ //TODO 如果人员不在黑名单中,获取状态会出现异常 RongIMClient.prototype.getBlacklistStatus = function (userId, callback) { RongIMLib.CheckParam.getInstance().check(["string|number", "object"], "getBlacklistStatus", false, arguments); RongIMClient._dataAccessProvider.getBlacklistStatus(userId, RongIMClient.logCallback(callback, "getBlacklistStatus")); }; /** * [将指定用户移除黑名单] * @param {string} userId [将被移除的用户Id] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.removeFromBlacklist = function (userId, callback) { RongIMLib.CheckParam.getInstance().check(["string|number", "object"], "removeFromBlacklist", false, arguments); RongIMClient._dataAccessProvider.removeFromBlacklist(userId, RongIMClient.logCallback(callback, "removeFromBlacklist")); }; RongIMClient.prototype.getFileToken = function (fileType, callback) { RongIMLib.CheckParam.getInstance().check(["number", "object"], "getQngetFileTokenTkn", false, arguments); RongIMClient._dataAccessProvider.getFileToken(fileType, RongIMClient.logCallback(callback, "getFileToken")); }; RongIMClient.prototype.getFileUrl = function (fileType, fileName, oriName, callback) { RongIMLib.CheckParam.getInstance().check(["number", "string", "string|global|object|null", "object"], "getFileUrl", false, arguments); RongIMClient._dataAccessProvider.getFileUrl(fileType, fileName, oriName, RongIMClient.logCallback(callback, "getFileUrl")); }; ; // #endregion Blacklist // #region Real-time Location Service RongIMClient.prototype.addRealTimeLocationListener = function (conversationType, targetId, listener) { throw new Error("Not implemented yet"); }; RongIMClient.prototype.getRealTimeLocation = function (conversationType, targetId) { throw new Error("Not implemented yet"); }; RongIMClient.prototype.getRealTimeLocationCurrentState = function (conversationType, targetId) { throw new Error("Not implemented yet"); }; RongIMClient.prototype.getRealTimeLocationParticipants = function (conversationType, targetId) { throw new Error("Not implemented yet"); }; RongIMClient.prototype.joinRealTimeLocation = function (conversationType, targetId) { throw new Error("Not implemented yet"); }; RongIMClient.prototype.quitRealTimeLocation = function (conversationType, targetId) { throw new Error("Not implemented yet"); }; RongIMClient.prototype.startRealTimeLocation = function (conversationType, targetId) { throw new Error("Not implemented yet"); }; RongIMClient.prototype.updateRealTimeLocationStatus = function (conversationType, targetId, latitude, longitude) { throw new Error("Not implemented yet"); }; // #endregion Real-time Location Service // # startVoIP RongIMClient.prototype.startCall = function (converType, targetId, userIds, mediaType, extra, callback) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "array", "number", "string", "object"], "startCall", false, arguments); if (RongIMClient._memoryStore.voipStategy) { RongIMClient._voipProvider.startCall(converType, targetId, userIds, mediaType, extra, RongIMClient.logCallback(callback, "startCall")); } else { var errorCode = RongIMLib.ErrorCode.VOIP_NOT_AVALIABLE; RongIMClient.logger({ code: errorCode, funcName: "startCall" }); callback.onError(RongIMLib.ErrorCode.VOIP_NOT_AVALIABLE); } }; RongIMClient.prototype.joinCall = function (mediaType, callback) { RongIMLib.CheckParam.getInstance().check(['number', 'object'], "joinCall", false, arguments); if (RongIMClient._memoryStore.voipStategy) { RongIMClient._voipProvider.joinCall(mediaType, RongIMClient.logCallback(callback, "joinCall")); } else { var errorCode = RongIMLib.ErrorCode.VOIP_NOT_AVALIABLE; RongIMClient.logger({ code: errorCode, funcName: "joinCall" }); callback.onError(RongIMLib.ErrorCode.VOIP_NOT_AVALIABLE); } }; RongIMClient.prototype.hungupCall = function (converType, targetId, reason) { RongIMLib.CheckParam.getInstance().check(["number", "string", "number"], "hungupCall", false, arguments); if (RongIMClient._memoryStore.voipStategy) { RongIMClient._voipProvider.hungupCall(converType, targetId, reason); } }; RongIMClient.prototype.changeMediaType = function (converType, targetId, mediaType, callback) { RongIMLib.CheckParam.getInstance().check(["number", "string", "number", "object"], "changeMediaType", false, arguments); if (RongIMClient._memoryStore.voipStategy) { RongIMClient._voipProvider.changeMediaType(converType, targetId, mediaType, RongIMClient.logCallback(callback, "changeMediaType")); } else { var errorCode = RongIMLib.ErrorCode.VOIP_NOT_AVALIABLE; RongIMClient.logger({ code: errorCode, funcName: "changeMediaType" }); callback.onError(RongIMLib.ErrorCode.VOIP_NOT_AVALIABLE); } }; // # endVoIP RongIMClient.prototype.getUnreadMentionedMessages = function (conversationType, targetId) { return RongIMClient._dataAccessProvider.getUnreadMentionedMessages(conversationType, targetId); }; RongIMClient.prototype.clearListeners = function () { RongIMClient._dataAccessProvider.clearListeners(); }; // UserStatus start RongIMClient.prototype.getUserStatus = function (userId, callback) { RongIMClient._dataAccessProvider.getUserStatus(userId, RongIMClient.logCallback(callback, "getUserStatus")); }; RongIMClient.prototype.setUserStatus = function (status, callback) { RongIMClient._dataAccessProvider.setUserStatus(status, RongIMClient.logCallback(callback, "setUserStatus")); }; RongIMClient.prototype.setUserStatusListener = function (params, callback) { var userIds = params.userIds; var multiple = params.multiple; RongIMClient.userStatusObserver.watch({ key: userIds, func: callback, multiple: multiple }); RongIMClient._dataAccessProvider.setUserStatusListener(params, callback); }; // UserStaus end // RTC start RongIMClient.messageWatch = function (watcher) { RongIMClient.RTCListener = watcher; }; RongIMClient.messageSignalWatch = function (watcher) { RongIMClient.RTCSignalLisener = watcher; }; /* var data = { key1: 123, key2: 345 }; */ RongIMClient.prototype.getRTCUserInfoList = function (room, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object"], "getRTCUserInfoList", false, arguments); RongIMClient._dataAccessProvider.getRTCUserInfoList(room, callback); }; RongIMClient.prototype.getRTCUserList = function (room, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object"], "getRTCUserList", false, arguments); RongIMClient._dataAccessProvider.getRTCUserList(room, callback); }; RongIMClient.prototype.setRTCUserInfo = function (room, info, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object", "object"], "setRTCUserInfo", false, arguments); RongIMClient._dataAccessProvider.setRTCUserInfo(room, info, callback); }; RongIMClient.prototype.removeRTCUserInfo = function (room, info, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object", "object"], "removeRTCUserInfo", false, arguments); RongIMClient._dataAccessProvider.removeRTCUserInfo(room, info, callback); }; RongIMClient.prototype.getRTCRoomInfo = function (room, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object"], "getRTCRoomInfo", false, arguments); RongIMClient._dataAccessProvider.getRTCRoomInfo(room, callback); }; RongIMClient.prototype.setRTCRoomInfo = function (room, info, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object", "object"], "setRTCRoomInfo", false, arguments); RongIMClient._dataAccessProvider.setRTCRoomInfo(room, info, callback); }; RongIMClient.prototype.removeRTCRoomInfo = function (room, info, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object", "object"], "removeRTCRoomInfo", false, arguments); RongIMClient._dataAccessProvider.removeRTCRoomInfo(room, info, callback); }; RongIMClient.prototype.joinRTCRoom = function (room, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object"], "joinRTCRoom", false, arguments); if (RongIMClient.isJoinedRTCRoom) { return callback.onSuccess(RongIMClient.roomInfo); } RongIMClient._dataAccessProvider.joinRTCRoom(room, { onSuccess: function (result) { RongIMClient.roomInfo = result; RongIMClient.isJoinedRTCRoom = true; callback.onSuccess(result); }, onError: callback.onError }); }; RongIMClient.prototype.quitRTCRoom = function (room, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object"], "quitRTCRoom", false, arguments); RongIMClient.isJoinedRTCRoom = false; RongIMClient._dataAccessProvider.quitRTCRoom(room, { onSuccess: function () { RongIMClient.roomInfo = { users: {}, token: '' }; callback.onSuccess(true); }, onError: callback.onError }); }; RongIMClient.prototype.RTCPing = function (room, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object"], "RTCPing", false, arguments); RongIMClient._dataAccessProvider.RTCPing(room, callback); }; RongIMClient.prototype.setRTCUserData = function (roomId, key, value, isInner, callback, message) { RongIMLib.CheckParam.getInstance().check(["string", "string", "string", "boolean", "object", "global|object|null|undefined"], "setRTCUserData", false, arguments); RongIMClient._dataAccessProvider.setRTCUserData(roomId, key, value, isInner, callback, message); }; RongIMClient.prototype.getRTCUserData = function (roomId, keys, isInner, callback) { RongIMLib.CheckParam.getInstance().check(["string", "array", "boolean", "object", "global|object|null"], "getRTCUserData", false, arguments); RongIMClient._dataAccessProvider.getRTCUserData(roomId, keys, isInner, callback); }; RongIMClient.prototype.removeRTCUserData = function (roomId, keys, isInner, callback, message) { RongIMLib.CheckParam.getInstance().check(["string", "array", "boolean", "object", "global|object|null|undefined"], "removeRTCUserData", false, arguments); RongIMClient._dataAccessProvider.removeRTCUserData(roomId, keys, isInner, callback, message); }; RongIMClient.prototype.setRTCRoomData = function (roomId, key, value, isInner, callback, message) { RongIMLib.CheckParam.getInstance().check(["string", "string", "string", "boolean", "object", "global|object|null|undefined"], "setRTCRoomData", false, arguments); RongIMClient._dataAccessProvider.setRTCRoomData(roomId, key, value, isInner, callback, message); }; RongIMClient.prototype.getRTCRoomData = function (roomId, keys, isInner, callback) { RongIMLib.CheckParam.getInstance().check(["string", "array", "boolean", "object"], "getRTCRoomData", false, arguments); RongIMClient._dataAccessProvider.getRTCRoomData(roomId, keys, isInner, callback); }; RongIMClient.prototype.removeRTCRoomData = function (roomId, keys, isInner, callback, message) { RongIMLib.CheckParam.getInstance().check(["string", "array", "boolean", "object", "global|object|null|undefined"], "removeRTCRoomData", false, arguments); RongIMClient._dataAccessProvider.removeRTCRoomData(roomId, keys, isInner, callback, message); }; RongIMClient.prototype.setRTCOutData = function (roomId, data, type, callback, message) { RongIMClient._dataAccessProvider.setRTCOutData(roomId, data, type, callback, message); }; // 信令 SDK 新增 RongIMClient.prototype.getRTCOutData = function (roomId, userIds, callback) { RongIMClient._dataAccessProvider.getRTCOutData(roomId, userIds, callback); }; RongIMClient.prototype.getNavi = function () { return RongIMClient._dataAccessProvider.getNavi(); }; RongIMClient.prototype.getRTCToken = function (room, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object"], "getRTCToken", false, arguments); return RongIMClient._dataAccessProvider.getRTCToken(room, callback); }; RongIMClient.prototype.setRTCState = function (room, content, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object", "object"], "setRTCState", false, arguments); return RongIMClient._dataAccessProvider.setRTCState(room, content, callback); }; RongIMClient.prototype.getAppInfo = function () { var appKey = RongIMClient._memoryStore.appKey; return { appKey: appKey }; }; RongIMClient.prototype.getSDKInfo = function () { return { version: RongIMClient.sdkver }; }; RongIMClient.RTCListener = function () { }; RongIMClient.RTCInnerListener = function () { }; RongIMClient.RTCSignalLisener = function () { }; RongIMClient.currentServer = ''; RongIMClient.LogFactory = {}; RongIMClient.MessageType = {}; RongIMClient.RegisterMessage = {}; RongIMClient._memoryStore = { isPullFinished: false, syncMsgQueue: [] }; RongIMClient.isNotPullMsg = false; RongIMClient.userStatusObserver = null; RongIMClient.sdkver = '2.5.3'; RongIMClient.otherDeviceLoginCount = 0; RongIMClient.serverStore = { index: 0 }; RongIMClient.isFirstConnect = true; RongIMClient.roomInfo = { users: {}, token: '' }; RongIMClient.invalidWsUrls = []; RongIMClient.isJoinedRTCRoom = false; RongIMClient.statusListeners = []; RongIMClient.messageListeners = []; RongIMClient.userStatusListener = null; return RongIMClient; })(); RongIMLib.RongIMClient = RongIMClient; })(RongIMLib || (RongIMLib = {})); //用于连接通道 var RongIMLib; (function (RongIMLib) { (function (Qos) { Qos[Qos["AT_MOST_ONCE"] = 0] = "AT_MOST_ONCE"; Qos[Qos["AT_LEAST_ONCE"] = 1] = "AT_LEAST_ONCE"; Qos[Qos["EXACTLY_ONCE"] = 2] = "EXACTLY_ONCE"; Qos[Qos["DEFAULT"] = 3] = "DEFAULT"; })(RongIMLib.Qos || (RongIMLib.Qos = {})); var Qos = RongIMLib.Qos; (function (Type) { Type[Type["CONNECT"] = 1] = "CONNECT"; Type[Type["CONNACK"] = 2] = "CONNACK"; Type[Type["PUBLISH"] = 3] = "PUBLISH"; Type[Type["PUBACK"] = 4] = "PUBACK"; Type[Type["QUERY"] = 5] = "QUERY"; Type[Type["QUERYACK"] = 6] = "QUERYACK"; Type[Type["QUERYCON"] = 7] = "QUERYCON"; Type[Type["SUBSCRIBE"] = 8] = "SUBSCRIBE"; Type[Type["SUBACK"] = 9] = "SUBACK"; Type[Type["UNSUBSCRIBE"] = 10] = "UNSUBSCRIBE"; Type[Type["UNSUBACK"] = 11] = "UNSUBACK"; Type[Type["PINGREQ"] = 12] = "PINGREQ"; Type[Type["PINGRESP"] = 13] = "PINGRESP"; Type[Type["DISCONNECT"] = 14] = "DISCONNECT"; })(RongIMLib.Type || (RongIMLib.Type = {})); var Type = RongIMLib.Type; var _topic = [ "invtDiz", "crDiz", "qnUrl", "userInf", "dizInf", "userInf", "joinGrp", "quitDiz", "exitGrp", "evctDiz", ["", "ppMsgP", "pdMsgP", "pgMsgP", "chatMsg", "pcMsgP", "", "pmcMsgN", "pmpMsgN", "", "", "", "prMsgS", "prMsgP"], "pdOpen", "rename", "uGcmpr", "qnTkn", "destroyChrm", "createChrm", "exitChrm", "queryChrm", "joinChrm", "pGrps", "addBlack", "rmBlack", "getBlack", "blackStat", "addRelation", "qryRelation", "delRelation", "pullMp", "schMp", "qnTkn", "qnUrl", "qryVoipK", "delMsg", "qryCHMsg", "getUserStatus", "setUserStatus", "subUserStatus", "cleanHisMsg" ]; var Channel = (function () { function Channel(cb, self) { this.connectionStatus = -1; var appId = self.appId; var token = encodeURIComponent(self.token); var sdkVer = self.sdkVer; var apiVer = self.apiVer; this.self = self; this.socket = Socket.getInstance().createServer(); var that = this; var storage = RongIMLib.RongIMClient._storageProvider; var servers = storage.getItem('servers'); servers = JSON.parse(servers) || []; servers = RongIMLib.RongUtil.getValidWsUrlList(servers); var depend = RongIMLib.RongIMClient._memoryStore.depend; var startConnect = function (host) { var tpl = '{host}/websocket?appId={appId}&token={token}&sdkVer={sdkVer}&apiVer={apiVer}'; that.url = RongIMLib.RongUtil.tplEngine(tpl, { host: host, appId: appId, token: token, sdkVer: sdkVer, apiVer: apiVer }); that.socket.connect(that.url, cb); // 临时兼容 Comet 逻辑,Comet 中用到 var userId = storage.getItem('rong_current_user'); RongIMLib.Navigation.Endpoint = { host: host, userId: userId }; }; var connectMap = { wsFromGet: function () { // 所有链接计算器,超过 15 秒后认为所有 CMP 地址均不可用 var totalTimer = new RongIMLib.Timer({ timeout: 1 * 1000 * 15 }); var timers = []; var xhrs = []; var isFinished = false; var clearHandler = function () { for (var i = 0; i < timers.length; i++) { var timer = timers[i]; clearTimeout(timer); } for (var i = 0; i < xhrs.length; i++) { var xhr = xhrs[i]; xhr.abort(); } timers.length = 0; xhrs.length = 0; }; var request = function (config, callback) { var url = config.url; var time = config.time; if (isFinished) { return; } var timer = setTimeout(function () { var onSuccess = function () { if (isFinished) { return; } clearHandler(); isFinished = true; totalTimer.pause(); callback(url); }; var xhr = RongIMLib.MessageUtil.detectCMP({ url: url, success: onSuccess, fail: function (code) { console.log(code); } }); xhrs.push(xhr); }, time); timers.push(timer); }; var snifferCallback = function (url) { var reg = /(http|https):\/\/([^\/]+)/i; var host = url.match(reg)[2]; RongIMLib.RongIMClient.currentServer = host; startConnect(host); }; var snifferTpl = '{protocol}{server}/ping?r={random}'; for (var i = 0; i < servers.length; i++) { var server = servers[i]; if (server) { server = RongIMLib.RongUtil.tplEngine(snifferTpl, { protocol: depend.protocol, server: server, random: RongIMLib.RongUtil.getTimestamp() }); request({ url: server, time: i * 1000 }, snifferCallback); } } totalTimer.resume(function () { RongIMLib.Navigation.clear(); clearHandler(); that.socket.fire("StatusChanged", RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE); }); }, wsFromEl: function () { var totalTimer = new RongIMLib.Timer({ timeout: 1 * 1000 * 15 }); var timers = []; var elements = []; var isFinished = false; var clearHandler = function () { for (var i = 0; i < timers.length; i++) { var timer = timers[i]; clearTimeout(timer); } for (var i = 0; i < elements.length; i++) { var el = elements[i]; document.body.removeChild(el); } }; var request = function (config, callback) { var url = config.url; var time = config.time; if (isFinished) { return; } var timer = setTimeout(function () { var el = document.createElement('script'); el.src = url; document.body.appendChild(el); el.onerror = function () { if (isFinished) { return; } clearHandler(); isFinished = true; totalTimer.pause(); var url = el.src; callback(url); }; elements.push(el); }, time); timers.push(timer); }; var snifferCallback = function (url) { var reg = /(http|https):\/\/([^\/]+)/i; var host = url.match(reg)[2]; startConnect(host); }; var snifferTpl = '//{server}/{path}'; for (var i = 0; i < servers.length; i++) { var server = RongIMLib.RongUtil.tplEngine(snifferTpl, { server: servers[i], path: i }); request({ url: server, time: i * 1000 }, snifferCallback); } totalTimer.resume(function () { clearHandler(); that.socket.fire("StatusChanged", RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE); }); }, comet: function () { var host = servers[0]; startConnect(host); } }; var isPolling = depend.isPolling; var isWSPingJSONP = depend.isWSPingJSONP; if (isPolling) { connectMap['comet'](); } else { var connectType = isWSPingJSONP ? 'wsFromEl' : 'wsFromGet'; connectMap[connectType](); } //注册状态改变观察者 var StatusEvent = Channel._ConnectionStatusListener; var hasEvent = (typeof StatusEvent == "object"); var me = this; me.socket.on("StatusChanged", function (code) { if (RongIMLib.Bridge && RongIMLib.Bridge._client && RongIMLib.Bridge._client.channel && me !== RongIMLib.Bridge._client.channel) { return; } if (!hasEvent) { throw new Error("setConnectStatusListener:Parameter format is incorrect"); } var isNetworkUnavailable = (code == RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE); var isWebSocket = !RongIMLib.RongIMClient._memoryStore.depend.isPolling; if (RongIMLib.RongIMClient.isFirstConnect && isNetworkUnavailable && isWebSocket) { code = RongIMLib.ConnectionStatus.WEBSOCKET_UNAVAILABLE; } if (isNetworkUnavailable) { var storage = RongIMLib.RongIMClient._storageProvider; var servers = storage.getItem('servers'); servers = JSON.parse(servers); var currentServer = RongIMLib.RongIMClient.currentServer; if (currentServer) { var index = RongIMLib.RongUtil.indexOf(servers, currentServer); // 如果 currentServer 是 servers 的最后一个,不再替换位置 if (!RongIMLib.RongUtil.isEqual(index, -1)) { var server = servers.splice(index, 1)[0]; servers.push(server); storage.setItem('servers', JSON.stringify(servers)); } } } me.connectionStatus = code; setTimeout(function () { StatusEvent.onChanged(code); }); var isDisconnected = (code == RongIMLib.ConnectionStatus.DISCONNECTED); if (isDisconnected) { self.clearHeartbeat(); } var isOtherDevice = (code == RongIMLib.ConnectionStatus.KICKED_OFFLINE_BY_OTHER_CLIENT); if (isOtherDevice) { // 累计其他设备登陆次数,超过 5 次后,自动销毁内部对象 // 删除位置:ServerDataProivder.prototype.connect RongIMLib.RongIMClient.otherDeviceLoginCount++; } var isConnected = (code == RongIMLib.ConnectionStatus.CONNECTED); if (isConnected) { RongIMLib.RongIMClient.isFirstConnect = false; } var isWebsocketUnAvailable = (code == RongIMLib.ConnectionStatus.WEBSOCKET_UNAVAILABLE); if (isWebsocketUnAvailable) { me.changeConnectType(); RongIMLib.RongIMClient.isFirstConnect = false; RongIMLib.RongIMClient.connect(self.token, RongIMLib.RongIMClient._memoryStore.callback); } }); //注册message观察者 this.socket.on("message", self.handler.handleMessage); //注册断开连接观察者 this.socket.on("disconnect", function (status) { that.socket.fire("StatusChanged", status ? status : 2); }); } Channel.prototype.changeConnectType = function () { RongIMLib.RongIMClient._memoryStore.depend.isPolling = !RongIMLib.RongIMClient._memoryStore.depend.isPolling; new RongIMLib.FeatureDectector(); }; Channel.prototype.writeAndFlush = function (val) { this.socket.send(val); }; Channel.prototype.reconnect = function (callback) { RongIMLib.MessageIdHandler.clearMessageId(); this.socket = this.socket.reconnect(); if (callback) { this.self.reconnectObj = callback; } }; Channel.prototype.disconnect = function (status) { this.socket.disconnect(status); }; return Channel; })(); RongIMLib.Channel = Channel; var Socket = (function () { function Socket() { this.socket = null; this._events = {}; } Socket.getInstance = function () { return new Socket(); }; Socket.prototype.connect = function (url, cb) { if (this.socket) { if (url) { RongIMLib.RongIMClient._storageProvider.setItem("rongSDK", this.checkTransport()); this.on("connect", cb || new Function); } if (url) { this.currentURL = url; } this.socket.createTransport(url); } return this; }; Socket.prototype.createServer = function () { var transport = this.getTransport(this.checkTransport()); if (transport === null) { throw new Error("the channel was not supported"); } return transport; }; Socket.prototype.getTransport = function (transportType) { if (transportType == Socket.XHR_POLLING) { this.socket = new RongIMLib.PollingTransportation(this); } else if (transportType == Socket.WEBSOCKET) { this.socket = new RongIMLib.SocketTransportation(this); } return this; }; Socket.prototype.send = function (data) { if (this.socket) { if (this.checkTransport() == Socket.WEBSOCKET) { this.socket.send(data); } else { this.socket.send(this._encode(data)); } } }; Socket.prototype.onMessage = function (data) { this.fire("message", data); }; Socket.prototype.disconnect = function (status) { this.socket.disconnect(status); this.fire("disconnect", status); return this; }; Socket.prototype.reconnect = function () { if (this.currentURL && RongIMLib.RongIMClient._storageProvider.getItem("rongSDK")) { return this.connect(this.currentURL, null); } else { throw new Error("reconnect:no have URL"); } }; /** * [checkTransport 返回通道类型] */ Socket.prototype.checkTransport = function () { if (RongIMLib.RongIMClient._memoryStore.depend.isPolling) { RongIMLib.Transportations._TransportType = Socket.XHR_POLLING; } return RongIMLib.Transportations._TransportType; }; Socket.prototype.fire = function (x, args) { if (x in this._events) { for (var i = 0, ii = this._events[x].length; i < ii; i++) { this._events[x][i](args); } } return this; }; Socket.prototype.on = function (x, func) { if (!(typeof func == "function" && x)) { return this; } if (x in this._events) { RongIMLib.MessageUtil.indexOf(this._events, func) == -1 && this._events[x].push(func); } else { this._events[x] = [func]; } return this; }; Socket.prototype.removeEvent = function (x, fn) { if (x in this._events) { for (var a = 0, l = this._events[x].length; a < l; a++) { if (this._events[x][a] == fn) { this._events[x].splice(a, 1); } } } return this; }; Socket.prototype._encode = function (x) { var str = "?messageid=" + x.getMessageId() + "&header=" + x.getHeaderFlag() + "&sessionid=" + RongIMLib.RongIMClient._storageProvider.getItem("sId" + RongIMLib.Navigation.Endpoint.userId); if (!/(PubAckMessage|QueryConMessage)/.test(x._name)) { str += "&topic=" + x.getTopic() + "&targetid=" + (x.getTargetId() || ""); } return { url: str, data: "getData" in x ? x.getData() : "" }; }; //消息通道常量,所有和通道相关判断均用 XHR_POLLING WEBSOCKET两属性 Socket.XHR_POLLING = "xhr-polling"; Socket.WEBSOCKET = "websocket"; return Socket; })(); RongIMLib.Socket = Socket; //连接端消息累 var Client = (function () { function Client(token, appId) { this.timeoutMillis = 6000; this.timeout_ = 0; this.sdkVer = ''; this.apiVer = Math.floor(Math.random() * 1e6); this.channel = null; this.handler = null; this.userId = ""; this.reconnectObj = {}; this.heartbeat = 0; this.pullMsgHearbeat = 0; this.chatroomId = ""; this.SyncTimeQueue = []; this.cacheMessageIds = []; this.token = token; this.appId = appId; this.SyncTimeQueue.state = "complete"; this.sdkVer = RongIMLib.RongIMClient.sdkver; } Client.prototype.resumeTimer = function () { var me = this; this.timeout_ = setTimeout(function () { me.channel.disconnect(RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE); }, this.timeoutMillis); }; Client.prototype.pauseTimer = function () { if (this.timeout_) { clearTimeout(this.timeout_); this.timeout_ = 0; } }; Client.prototype.connect = function (_callback) { //实例消息处理类 this.handler = new MessageHandler(this); //设置连接回调 this.handler.setConnectCallback(_callback); //实例通道类型 var me = this; this.channel = new Channel(function () { RongIMLib.Transportations._TransportType == Socket.WEBSOCKET && me.keepLive(); }, this); //触发状态改变观察者 this.channel.socket.fire("StatusChanged", RongIMLib.ConnectionStatus.CONNECTING); //没有返回地址就手动抛出错误 //_callback.onError(ConnectionState.NOT_AUTHORIZED); }; Client.prototype.checkSocket = function (callback) { var me = this; me.channel.writeAndFlush(new RongIMLib.PingReqMessage()); var count = 0; var checkTimeout = setInterval(function () { if (!RongIMLib.RongIMClient._memoryStore.isFirstPingMsg) { clearInterval(checkTimeout); callback.onSuccess(); } else { if (count > 15) { clearInterval(checkTimeout); callback.onError(); } } count++; }, 100); }; Client.prototype.keepLive = function () { if (this.heartbeat > 0) { clearInterval(this.heartbeat); } var me = this; me.heartbeat = setInterval(function () { me.resumeTimer(); me.channel.writeAndFlush(new RongIMLib.PingReqMessage()); }, 30000); if (me.pullMsgHearbeat > 0) { clearInterval(me.pullMsgHearbeat); } me.pullMsgHearbeat = setInterval(function () { me.syncTime(true, undefined, undefined, false); }, 180000); }; Client.prototype.clearHeartbeat = function () { clearInterval(this.heartbeat); this.heartbeat = 0; this.pauseTimer(); clearInterval(this.pullMsgHearbeat); this.pullMsgHearbeat = 0; }; Client.prototype.publishMessage = function (_topic, _data, _targetId, _callback, _msg) { var msgId = RongIMLib.MessageIdHandler.messageIdPlus(this.channel.reconnect); if (!msgId) { return; } var msg = new RongIMLib.PublishMessage(_topic, _data, _targetId); msg.setMessageId(msgId); if (_callback) { msg.setQos(Qos.AT_LEAST_ONCE); this.handler.putCallback(new RongIMLib.PublishCallback(_callback.onSuccess, _callback.onError), msg.getMessageId(), _msg); } else { msg.setQos(Qos.AT_MOST_ONCE); } this.channel.writeAndFlush(msg); }; Client.prototype.queryMessage = function (_topic, _data, _targetId, _qos, _callback, pbtype) { if (_topic == "userInf") { if (Client.userInfoMapping[_targetId]) { _callback.onSuccess(Client.userInfoMapping[_targetId]); return; } } var msgId = RongIMLib.MessageIdHandler.messageIdPlus(this.channel.reconnect); if (!msgId) { return; } var msg = new RongIMLib.QueryMessage(_topic, _data, _targetId); msg.setMessageId(msgId); msg.setQos(_qos); this.handler.putCallback(new RongIMLib.QueryCallback(_callback.onSuccess, _callback.onError), msg.getMessageId(), pbtype); this.channel.writeAndFlush(msg); }; Client.prototype.invoke = function (isPullMsg, chrmId, offlineMsg) { var time, modules, str, me = this, target, temp = this.SyncTimeQueue.shift(); if (temp == undefined) { return; } this.SyncTimeQueue.state = "pending"; var localSyncTime = RongIMLib.SyncTimeUtil.get(); var sentBoxTime = localSyncTime.sent; if (temp.type != 2) { //普通消息 time = localSyncTime.received; modules = new RongIMLib.RongIMClient.Protobuf.SyncRequestMsg(); modules.setIspolling(false); str = "pullMsg"; target = this.userId; modules.setSendBoxSyncTime(sentBoxTime); } else { //聊天室消息 target = temp.chrmId || me.chatroomId; time = RongIMLib.RongIMClient._memoryStore.lastReadTime.get(target + Bridge._client.userId + "CST") || 0; modules = new RongIMLib.RongIMClient.Protobuf.ChrmPullMsg(); modules.setCount(0); str = "chrmPull"; if (!target) { throw new Error("syncTime:Received messages of chatroom but was not init"); } } //判断服务器给的时间是否消息本地存储的时间,小于的话不执行拉取操作,进行一下步队列操作 if (temp.pulltime <= time) { this.SyncTimeQueue.state = "complete"; this.invoke(isPullMsg, target, offlineMsg); return; } if (isPullMsg && 'setIsPullSend' in modules) { modules.setIsPullSend(true); } modules.setSyncTime(time); //发送queryMessage请求 this.queryMessage(str, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), target, Qos.AT_LEAST_ONCE, { onSuccess: function (collection) { var sync = RongIMLib.MessageUtil.int64ToTimestamp(collection.syncTime), symbol = target; //把返回时间戳存入本地,普通消息key为userid,聊天室消息key为userid+'CST';value都为服务器返回的时间戳 var isChrmPull = str == 'chrmPull'; if (isChrmPull) { symbol += Bridge._client.userId + "CST"; RongIMLib.RongIMClient._memoryStore.lastReadTime.set(symbol, sync); } else { var storage = RongIMLib.RongIMClient._storageProvider; if (sync > storage.getItem(symbol)) { storage.setItem(symbol, sync); } } //把拉取到的消息逐条传给消息监听器 var list = collection.list; var isPullFinished = collection.finished; // chrmPull 没有 finished 字段,自动设置为拉取完成 if (isChrmPull) { isPullFinished = true; } // 兼容长轮训 finished 为空的造成丢消息情况 if (typeof isPullFinished == 'undefined') { isPullFinished = true; } RongIMLib.RongIMClient._memoryStore.isPullFinished = isPullFinished; var connectAckTime = RongIMLib.RongIMClient._memoryStore.connectAckTime; var len = list.length; for (var i = 0, count = len; i < len; i++) { count -= 1; var message = list[i]; var sentTime = RongIMLib.MessageUtil.int64ToTimestamp(message.dataTime); var isSender = message.direction == RongIMLib.MessageDirection.SEND; var compareTime = isSender ? sentBoxTime : time; if (sentTime > compareTime) { var isSyncMessage = false; var isOffLineMessage = sentTime < connectAckTime; Bridge._client.handler.onReceived(message, undefined, isOffLineMessage, count, isSyncMessage, isPullFinished); } } if (len <= 200 && str == 'pullMsg') { var Conversation = RongIMLib.RongIMClient._dataAccessProvider.Conversation; var conversationList = RongIMLib.RongIMClient._memoryStore.conversationList; Conversation._notify(conversationList); } me.SyncTimeQueue.state = "complete"; me.invoke(isPullMsg, target, offlineMsg); }, onError: function (error) { me.SyncTimeQueue.state = "complete"; me.invoke(isPullMsg, target, offlineMsg); } }, "DownStreamMessages"); }; Client.prototype.syncTime = function (_type, pullTime, chrmId, offlineMsg) { this.SyncTimeQueue.push({ type: _type, pulltime: pullTime, chrmId: chrmId }); //如果队列中只有一个成员并且状态已经完成就执行invoke方法 if (this.SyncTimeQueue.length == 1 && this.SyncTimeQueue.state == "complete") { this.invoke(!_type, chrmId, offlineMsg); } }; Client.prototype.__init = function (f) { this.handler = new MessageHandler(this); //设置连接回调 this.handler.setConnectCallback(RongIMLib.RongIMClient._memoryStore.callback); this.channel = new Channel(f, this); }; Client.userInfoMapping = {}; return Client; })(); RongIMLib.Client = Client; //连接类,实现imclient与connect_client的连接 var Bridge = (function () { function Bridge() { } Bridge.getInstance = function () { return new Bridge(); }; //连接服务器 Bridge.prototype.connect = function (appKey, token, callback) { if (!RongIMLib.RongIMClient.Protobuf) { return; } Bridge._client = new RongIMLib.Navigation().connect(appKey, token, callback); return Bridge._client; }; Bridge.prototype.setListener = function () { Channel._ConnectionStatusListener = { onChanged: function (status) { RongIMLib.RongUtil.forEach(RongIMLib.RongIMClient.statusListeners, function (watch) { RongIMLib.RongUtil.isFunction(watch) && watch(status); }); } }; Channel._ReceiveMessageListener = { onReceived: function (msg, count, hasMore) { RongIMLib.RongUtil.forEach(RongIMLib.RongIMClient.messageListeners, function (watch) { RongIMLib.RongUtil.isFunction(watch) && watch(msg, count, hasMore); }); } }; }; Bridge.prototype.reconnect = function (callabck) { Bridge._client.channel.reconnect(callabck); }; Bridge.prototype.disconnect = function () { Bridge._client.channel.disconnect(2); }; //执行queryMessage请求 Bridge.prototype.queryMsg = function (topic, content, targetId, callback, pbname) { if (typeof topic != "string") { topic = _topic[topic]; } Bridge._client.queryMessage(topic, content, targetId, Qos.AT_MOST_ONCE, callback, pbname); }; //发送消息 执行publishMessage 请求 Bridge.prototype.pubMsg = function (topic, content, targetId, callback, msg, methodType) { if (typeof methodType == 'number') { if (methodType == RongIMLib.MethodType.CUSTOMER_SERVICE) { Bridge._client.publishMessage("pcuMsgP", content, targetId, callback, msg); } else if (methodType == RongIMLib.MethodType.RECALL) { Bridge._client.publishMessage("recallMsg", content, targetId, callback, msg); } } else { Bridge._client.publishMessage(_topic[10][topic], content, targetId, callback, msg); } }; return Bridge; })(); RongIMLib.Bridge = Bridge; var MessageHandler = (function () { function MessageHandler(client) { this.map = {}; this.connectCallback = null; if (!Channel._ReceiveMessageListener) { throw new Error("please set onReceiveMessageListener"); } this._onReceived = Channel._ReceiveMessageListener.onReceived; this._client = client; this.syncMsgMap = new Object; } //把对象推入回调对象队列中,并启动定时器 MessageHandler.prototype.putCallback = function (callbackObj, _publishMessageId, _msg) { var item = { Callback: callbackObj, Message: _msg }; item.Callback.resumeTimer(); this.map[_publishMessageId] = item; }; //设置连接回调对象,启动定时器 MessageHandler.prototype.setConnectCallback = function (_connectCallback) { if (_connectCallback) { this.connectCallback = new RongIMLib.ConnectAck(_connectCallback.onSuccess, _connectCallback.onError, this._client); } }; MessageHandler.prototype.handleChrmKVPullMsg = function (msg) { try { var pbtype = 'ChrmNotifyMsg'; var data = RongIMLib.CallbackMapping.getInstance().mapping(RongIMLib.RongIMClient.Protobuf[pbtype].decode(msg.data), pbtype); if (data.type === 2) { var timestamp = RongIMLib.MessageUtil.int64ToTimestamp(data.time); RongIMLib.ChrmKVHandler.pull(data.chrmId, timestamp); } } catch (e) { } }; MessageHandler.prototype.onReceived = function (msg, pubAckItem, offlineMsg, leftCount, isSync) { //实体对象 var entity, //解析完成的消息对象 message, //会话对象 con, // 是否为直发消息 isStraightMsg = false; if (msg._name != "PublishMessage") { entity = msg; RongIMLib.RongIMClient._storageProvider.setItem(this._client.userId, RongIMLib.MessageUtil.int64ToTimestamp(entity.dataTime)); } else { if (msg.getTopic() == "s_ntf") { entity = RongIMLib.RongIMClient.Protobuf.NotifyMsg.decode(msg.getData()); this._client.syncTime(entity.type, RongIMLib.MessageUtil.int64ToTimestamp(entity.time), entity.chrmId); return; } else if (msg.getTopic() == "s_msg") { isStraightMsg = true; entity = RongIMLib.RongIMClient.Protobuf.DownStreamMessage.decode(msg.getData()); var timestamp = RongIMLib.MessageUtil.int64ToTimestamp(entity.dataTime); RongIMLib.RongIMClient._storageProvider.setItem(this._client.userId, timestamp); RongIMLib.RongIMClient._memoryStore.lastReadTime.get(this._client.userId, timestamp); } else if (msg.getTopic() == "s_stat") { entity = RongIMLib.RongIMClient.Protobuf.GetUserStatusOutput.decode(msg.getData()); entity = RongIMLib.RongInnerTools.convertUserStatus(entity); RongIMLib.RongIMClient.userStatusObserver.notify({ key: entity.userId, entity: entity }); return; } else if (msg.getTopic() === 's_cmd') { this.handleChrmKVPullMsg(msg); return; } else { if (Bridge._client.sdkVer && Bridge._client.sdkVer == "1.0.0") { return; } entity = RongIMLib.RongIMClient.Protobuf.UpStreamMessage.decode(msg.getData()); var tmpTopic = msg.getTopic(); var tmpType = tmpTopic.substr(0, 2); if (tmpType == "pp") { entity.type = 1; } else if (tmpType == "pd") { entity.type = 2; } else if (tmpType == "pg") { entity.type = 3; } else if (tmpType == "ch") { entity.type = 4; } else if (tmpType == "pc") { entity.type = 5; } //复用字段,targetId 以此为准 entity.groupId = msg.getTargetId(); entity.fromUserId = this._client.userId; entity.dataTime = Date.parse(new Date().toString()); } if (!entity) { return; } } var isPullFinished = RongIMLib.RongIMClient._memoryStore.isPullFinished; // PullMsg 没有拉取完成,抛弃所有直发在线消息,抛弃的消息会在 PullMsg 中返回 if (!isPullFinished && !offlineMsg && isStraightMsg) { return; } //解析实体对象为消息对象。 message = RongIMLib.MessageUtil.messageParser(entity, this._onReceived, offlineMsg); var isRTCMessage = message.conversationType == 12; if (isRTCMessage) { RongIMLib.RongIMClient.RTCListener(message); RongIMLib.RongIMClient.RTCInnerListener(message); RongIMLib.RongIMClient.RTCSignalLisener(message); return; } var isRecall = (msg.getTopic && msg.getTopic() == "recallMsg"); if (isRecall) { var content = message.content; message.conversationType = content.conversationType; message.targetId = content.targetId; message.messageId = null; } if (pubAckItem) { message.messageUId = pubAckItem.getMessageUId(); message.sentTime = pubAckItem.getTimestamp(); RongIMLib.RongIMClient._storageProvider.setItem(this._client.userId, message.sentTime); } if (message === null) { return; } var isChatroomMessage = message.conversationType == RongIMLib.ConversationType.CHATROOM; if (!isChatroomMessage) { var msgTag = RongIMLib.RongIMClient.MessageParams[message.messageType].msgTag.getMessageTag(); if (msgTag >= 0) { RongIMLib.SyncTimeUtil.set(message); } var isSend = (message.messageDirection == RongIMLib.MessageDirection.SEND); if (isSend) { var storageProvider = RongIMLib.RongIMClient._storageProvider; var userId = RongIMLib.Bridge._client.userId; var lastSentTime = storageProvider.getItem('last_sentTime_' + userId) || 0; if (message.sentTime <= lastSentTime && !isSync) { return; } } } // 设置会话时间戳并且判断是否传递 message 发送消息未处理会话时间戳 // key:'converST_' + 当前用户 + conversationType + targetId // RongIMClient._storageProvider.setItem('converST_' + Bridge._client.userId + message.conversationType + message.targetId, message.sentTime); // var isPersited = (RongIMClient.MessageParams[message.messageType].msgTag.getMessageTag() > 0); var msgTag = RongIMLib.RongIMClient.MessageParams[message.messageType].msgTag.getMessageTag(); var isPersited = msgTag === 3 || msgTag === 2; if (isPersited) { con = RongIMLib.RongIMClient._dataAccessProvider.getConversation(message.conversationType, message.targetId, { onSuccess: function () { }, onError: function () { } }); if (!con) { con = RongIMLib.RongIMClient.getInstance().createConversation(message.conversationType, message.targetId, ""); } if (message.messageDirection == RongIMLib.MessageDirection.RECEIVE && (entity.status & 64) == 64) { var mentioneds = RongIMLib.RongIMClient._storageProvider.getItem("mentioneds_" + Bridge._client.userId + '_' + message.conversationType + '_' + message.targetId); var key = message.conversationType + '_' + message.targetId, info = {}; if (message.content && message.content.mentionedInfo) { info[key] = { uid: message.messageUId, time: message.sentTime, mentionedInfo: message.content.mentionedInfo }; RongIMLib.RongIMClient._storageProvider.setItem("mentioneds_" + Bridge._client.userId + '_' + message.conversationType + '_' + message.targetId, JSON.stringify(info)); mentioneds = JSON.stringify(info); } if (mentioneds) { var info = JSON.parse(mentioneds); con.mentionedMsg = info[key]; } } var isReceiver = message.messageDirection == RongIMLib.MessageDirection.RECEIVE; if (isReceiver && message.senderUserId != Bridge._client.userId) { con.unreadMessageCount = con.unreadMessageCount + 1; if (RongIMLib.RongUtil.supportLocalStorage()) { // var originUnreadCount = RongIMClient._storageProvider.getItem("cu" + Bridge._client.userId + con.conversationType + con.targetId); // 与本地存储会话合并 // var newUnreadCount = Number(originUnreadCount) + 1; // RongIMClient._storageProvider.setItem("cu" + Bridge._client.userId + con.conversationType + message.targetId, newUnreadCount); var newUnreadCount = RongIMLib.UnreadCountHandler.add(con.conversationType, message.targetId, 1, message.sentTime); con.unreadMessageCount = newUnreadCount; } } con.receivedTime = new Date().getTime(); con.receivedStatus = message.receivedStatus; con.senderUserId = message.sendUserId; con.notificationStatus = RongIMLib.ConversationNotificationStatus.DO_NOT_DISTURB; con.latestMessageId = message.messageId; con.latestMessage = message; con.sentTime = message.sentTime; RongIMLib.RongIMClient._dataAccessProvider.addConversation(con, { onSuccess: function (data) { if (!offlineMsg) { var Conversation_1 = RongIMLib.RongIMClient._dataAccessProvider.Conversation; var conversationList = RongIMLib.RongIMClient._memoryStore.conversationList; Conversation_1._notify(conversationList); } }, onError: function () { } }); } if (message.conversationType == RongIMLib.ConversationType.CUSTOMER_SERVICE && (message.messageType == "ChangeModeResponseMessage" || message.messageType == "SuspendMessage" || message.messageType == "HandShakeResponseMessage" || message.messageType == "TerminateMessage" || message.messageType == "CustomerStatusUpdateMessage" || message.messageType == "TextMessage" || message.messageType == "InformationNotificationMessage")) { if (!RongIMLib.RongIMClient._memoryStore.custStore["isInit"]) { return; } } if (message.conversationType == RongIMLib.ConversationType.CUSTOMER_SERVICE && message.messageType != "HandShakeResponseMessage") { if (!RongIMLib.RongIMClient._memoryStore.custStore[message.targetId]) { return; } if (message.messageType == "TerminateMessage") { if (RongIMLib.RongIMClient._memoryStore.custStore[message.targetId].sid != message.content.sid) { return; } } } if (message.messageType === RongIMLib.RongIMClient.MessageType["HandShakeResponseMessage"]) { var session = message.content.data; RongIMLib.RongIMClient._memoryStore.custStore[message.targetId] = session; if (session.serviceType == RongIMLib.CustomerType.ONLY_HUMAN || session.serviceType == RongIMLib.CustomerType.HUMAN_FIRST) { if (session.notAutoCha == "1") { RongIMLib.RongIMClient.getInstance().switchToHumanMode(message.targetId, { onSuccess: function () { }, onError: function () { } }); } } } var d = new Date(), m = d.getMonth() + 1, date = d.getFullYear() + '/' + (m.toString().length == 1 ? '0' + m : m) + '/' + d.getDate(); //new Date(date).getTime() - message.sentTime < 1 逻辑判断 超过 1 天未收的 ReadReceiptRequestMessage 离线消息自动忽略。 var dealtime = new Date(date).getTime() - message.sentTime < 0; if (RongIMLib.RongUtil.supportLocalStorage() && message.messageType === RongIMLib.RongIMClient.MessageType["ReadReceiptRequestMessage"] && dealtime && message.messageDirection == RongIMLib.MessageDirection.SEND) { var sentkey = Bridge._client.userId + message.content.messageUId + "SENT"; RongIMLib.RongIMClient._storageProvider.setItem(sentkey, JSON.stringify({ count: 0, dealtime: message.sentTime, userIds: {} })); } else if (RongIMLib.RongUtil.supportLocalStorage() && message.messageType === RongIMLib.RongIMClient.MessageType["ReadReceiptRequestMessage"] && dealtime) { var reckey = Bridge._client.userId + message.conversationType + message.targetId + 'RECEIVED', recData = JSON.parse(RongIMLib.RongIMClient._storageProvider.getItem(reckey)); if (recData) { if (message.senderUserId in recData) { if (recData[message.senderUserId].uIds && recData[message.senderUserId].uIds && recData[message.senderUserId].uIds.indexOf(message.content.messageUId) == -1) { recData[message.senderUserId].uIds.push(message.content.messageUId); recData[message.senderUserId].dealtime = message.sentTime; recData[message.senderUserId].isResponse = false; RongIMLib.RongIMClient._storageProvider.setItem(reckey, JSON.stringify(recData)); } else { return; } } else { var objSon = { uIds: [message.content.messageUId], dealtime: message.sentTime, isResponse: false }; recData[message.senderUserId] = objSon; RongIMLib.RongIMClient._storageProvider.setItem(reckey, JSON.stringify(recData)); } } else { var obj = {}; obj[message.senderUserId] = { uIds: [message.content.messageUId], dealtime: message.sentTime, isResponse: false }; RongIMLib.RongIMClient._storageProvider.setItem(reckey, JSON.stringify(obj)); } } if (RongIMLib.RongUtil.supportLocalStorage() && message.messageType === RongIMLib.RongIMClient.MessageType["ReadReceiptResponseMessage"] && dealtime) { var receiptResponseMsg = message.content, uIds = receiptResponseMsg.receiptMessageDic[Bridge._client.userId], sentkey = "", sentObj; message.receiptResponse || (message.receiptResponse = {}); if (uIds) { var cbuIds = []; for (var i = 0, len = uIds.length; i < len; i++) { sentkey = Bridge._client.userId + uIds[i] + "SENT"; sentObj = JSON.parse(RongIMLib.RongIMClient._storageProvider.getItem(sentkey)); if (sentObj && !(message.senderUserId in sentObj.userIds)) { cbuIds.push(uIds[i]); sentObj.count += 1; sentObj.userIds[message.senderUserId] = message.sentTime; message.receiptResponse[uIds[i]] = sentObj.count; RongIMLib.RongIMClient._storageProvider.setItem(sentkey, JSON.stringify(sentObj)); } } receiptResponseMsg.receiptMessageDic[Bridge._client.userId] = cbuIds; message.content = receiptResponseMsg; } } var that = this; if (RongIMLib.RongIMClient._voipProvider && ['AcceptMessage', 'RingingMessage', 'HungupMessage', 'InviteMessage', 'MediaModifyMessage', 'MemberModifyMessage'].indexOf(message.messageType) > -1) { setTimeout(function () { RongIMLib.RongIMClient._voipProvider.onReceived(message); }); } else { var count = leftCount || 0; var hasMore = !isPullFinished; that._onReceived(message, count, hasMore); } }; MessageHandler.prototype.handleMessage = function (msg) { if (!msg) { return; } switch (msg._name) { case "ConnAckMessage": Bridge._client.handler.connectCallback.process(msg.getStatus(), msg.getUserId(), msg.getTimestamp()); break; case "PublishMessage": if (!msg.getSyncMsg() && msg.getQos() != 0) { Bridge._client.channel.writeAndFlush(new RongIMLib.PubAckMessage(msg.getMessageId())); } // TODO && -> if (msg.getSyncMsg() && !RongIMLib.RongIMClient._memoryStore.depend.isPolling) { Bridge._client.handler.syncMsgMap[msg.getMessageId()] = msg; } else { //如果是PublishMessage就把该对象给onReceived方法执行处理 Bridge._client.handler.onReceived(msg); } break; case "QueryAckMessage": if (msg.getQos() != 0) { Bridge._client.channel.writeAndFlush(new RongIMLib.QueryConMessage(msg.getMessageId())); } var temp = Bridge._client.handler.map[msg.getMessageId()]; if (temp) { //执行回调操作 temp.Callback.process(msg.getStatus(), msg.getData(), msg.getDate(), temp.Message); delete Bridge._client.handler.map[msg.getMessageId()]; } break; case "PubAckMessage": var item = Bridge._client.handler.map[msg.getMessageId()]; if (item) { item.Callback.process(msg.getStatus() || 0, msg.getMessageUId(), msg.getTimestamp(), item.Message, msg.getMessageId()); delete Bridge._client.handler.map[msg.getMessageId()]; } else { var userId = RongIMLib.Bridge._client.userId; RongIMLib.RongIMClient._storageProvider.setItem('last_sentTime_' + userId, msg.timestamp); Bridge._client.handler.onReceived(Bridge._client.handler.syncMsgMap[msg.messageId], msg, null, null, true); delete Bridge._client.handler.syncMsgMap[msg.getMessageId()]; } break; case "PingRespMessage": if (RongIMLib.RongIMClient._memoryStore.isFirstPingMsg) { RongIMLib.RongIMClient._memoryStore.isFirstPingMsg = false; } else { Bridge._client.pauseTimer(); } break; case "DisconnectMessage": Bridge._client.channel.disconnect(msg.getStatus()); break; default: } }; return MessageHandler; })(); RongIMLib.MessageHandler = MessageHandler; })(RongIMLib || (RongIMLib = {})); var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; /// var RongIMLib; (function (RongIMLib) { var MessageCallback = (function () { function MessageCallback(error) { this.timeout = null; this.onError = null; if (error && typeof error == "number") { this.timeoutMillis = error; } else { this.timeoutMillis = 30000; this.onError = error; } } MessageCallback.prototype.resumeTimer = function () { var me = this; if (this.timeoutMillis > 0 && !this.timeout) { this.timeout = setTimeout(function () { me.readTimeOut(true); }, this.timeoutMillis); } }; MessageCallback.prototype.pauseTimer = function () { if (this.timeout) { clearTimeout(this.timeout); this.timeout = null; } }; MessageCallback.prototype.readTimeOut = function (isTimeout) { if (isTimeout && this.onError) { this.onError(RongIMLib.ErrorCode.TIMEOUT); } else { this.pauseTimer(); } }; return MessageCallback; })(); RongIMLib.MessageCallback = MessageCallback; var CallbackMapping = (function () { function CallbackMapping() { this.publicServiceList = []; } CallbackMapping.getInstance = function () { return new CallbackMapping(); }; CallbackMapping.prototype.pottingProfile = function (item) { var temp; this.profile = new RongIMLib.PublicServiceProfile(); temp = JSON.parse(item.extra); this.profile.isGlobal = temp.isGlobal; this.profile.introduction = temp.introduction; this.profile.menu = temp.menu; this.profile.hasFollowed = temp.follow; this.profile.publicServiceId = item.mpid; this.profile.name = item.name; this.profile.portraitUri = item.portraitUrl; this.profile.conversationType = item.type == "mc" ? RongIMLib.ConversationType.APP_PUBLIC_SERVICE : RongIMLib.ConversationType.PUBLIC_SERVICE; this.publicServiceList.push(this.profile); }; CallbackMapping.prototype.mapping = function (entity, tag) { switch (tag) { case "GetUserInfoOutput": var userInfo = new RongIMLib.UserInfo(entity.userId, entity.userName, entity.userPortrait); return userInfo; case "GetQNupTokenOutput": return { deadline: RongIMLib.MessageUtil.int64ToTimestamp(entity.deadline), token: entity.token }; case "GetQNdownloadUrlOutput": return { downloadUrl: entity.downloadUrl }; case "CreateDiscussionOutput": return entity.id; case "ChannelInfoOutput": var disInfo = new RongIMLib.Discussion(); disInfo.creatorId = entity.adminUserId; disInfo.id = entity.channelId; disInfo.memberIdList = entity.firstTenUserIds; disInfo.name = entity.channelName; disInfo.isOpen = entity.openStatus; return disInfo; case "GroupHashOutput": return entity.result; case "QueryBlackListOutput": return entity.userIds; case "SearchMpOutput": case "PullMpOutput": if (entity.info) { var self = this; Array.forEach(entity.info, function (item) { setTimeout(function () { self.pottingProfile(item); }, 100); }); } return this.publicServiceList; default: return entity; } }; return CallbackMapping; })(); RongIMLib.CallbackMapping = CallbackMapping; var PublishCallback = (function (_super) { __extends(PublishCallback, _super); function PublishCallback(_cb, _timeout) { _super.call(this, _timeout); this._cb = _cb; this._timeout = _timeout; } PublishCallback.prototype.process = function (_status, messageUId, timestamp, _msg, messageId) { this.readTimeOut(); if (_status == 0) { if (_msg) { _msg.setSentStatus = _status; } var isPullFinished = RongIMLib.RongIMClient._memoryStore.isPullFinished; if (isPullFinished) { var userId = RongIMLib.Bridge._client.userId; var stroageProvider = RongIMLib.RongIMClient._storageProvider; stroageProvider.setItem('last_sentTime_' + userId, timestamp); RongIMLib.SyncTimeUtil.set({ messageDirection: RongIMLib.MessageDirection.SEND, sentTime: timestamp }); } this._cb({ messageUId: messageUId, timestamp: timestamp, messageId: messageId }); } else { this._timeout(_status, { messageUId: messageUId, sentTime: timestamp }); } }; PublishCallback.prototype.readTimeOut = function (x) { MessageCallback.prototype.readTimeOut.call(this, x); }; return PublishCallback; })(MessageCallback); RongIMLib.PublishCallback = PublishCallback; var QueryCallback = (function (_super) { __extends(QueryCallback, _super); function QueryCallback(_cb, _timeout) { _super.call(this, _timeout); this._cb = _cb; this._timeout = _timeout; } QueryCallback.prototype.process = function (status, data, serverTime, pbtype) { this.readTimeOut(); if (pbtype && data && status == 0) { try { data = CallbackMapping.getInstance().mapping(RongIMLib.RongIMClient.Protobuf[pbtype].decode(data), pbtype); } catch (e) { this._timeout(RongIMLib.ErrorCode.UNKNOWN); return; } if ("GetUserInfoOutput" == pbtype) { //pb类型为GetUserInfoOutput的话就把data放入userinfo缓存队列 RongIMLib.Client.userInfoMapping[data.userId] = data; } this._cb(data); } else { status > 0 ? this._timeout(status) : this._cb(status); } }; QueryCallback.prototype.readTimeOut = function (x) { MessageCallback.prototype.readTimeOut.call(this, x); }; return QueryCallback; })(MessageCallback); RongIMLib.QueryCallback = QueryCallback; var ConnectAck = (function (_super) { __extends(ConnectAck, _super); function ConnectAck(_cb, _timeout, client) { _super.call(this, _timeout); this._client = client; this._cb = _cb; this._timeout = _timeout; } ConnectAck.prototype.process = function (status, userId, timestamp) { this.readTimeOut(); if (status == 0) { this._client.userId = userId; var self = this; if (!RongIMLib.RongIMClient._memoryStore.depend.isPolling && RongIMLib.RongIMClient._memoryStore.isFirstPingMsg) { RongIMLib.Bridge._client.checkSocket({ onSuccess: function () { if (!RongIMLib.RongIMClient.isNotPullMsg) { self._client.syncTime(undefined, undefined, undefined, true); } }, onError: function () { RongIMLib.RongIMClient._memoryStore.isFirstPingMsg = false; RongIMLib.RongIMClient.getInstance().disconnect(); RongIMLib.RongIMClient.connect(RongIMLib.RongIMClient._memoryStore.token, RongIMLib.RongIMClient._memoryStore.callback); } }); } else { if (!RongIMLib.RongIMClient.isNotPullMsg) { self._client.syncTime(undefined, undefined, undefined, true); } } RongIMLib.Bridge._client.channel.socket.fire("StatusChanged", 0); if (this._client.reconnectObj.onSuccess) { this._client.reconnectObj.onSuccess(userId); delete this._client.reconnectObj.onSuccess; } else { var me = this; me._cb(userId); // setTimeout(function() { me._cb(userId); }, 500); var depend = RongIMLib.RongIMClient._memoryStore.depend; var maxConversationCount = depend.maxConversationCount; var isNotifyConversationList = depend.isNotifyConversationList; isNotifyConversationList && RongIMLib.RongIMClient._dataAccessProvider.getRemoteConversationList({ onSuccess: function (conversationList) { var Conversation = RongIMLib.RongIMClient._dataAccessProvider.Conversation; Conversation._notify(conversationList); }, onError: function (code) { console.log('内部获取列表失败: %d', code); } }, null, maxConversationCount); } RongIMLib.RongIMClient._memoryStore.connectAckTime = timestamp; if (!(new Date().getTime() - timestamp)) { RongIMLib.RongIMClient._memoryStore.deltaTime = 0; } else { RongIMLib.RongIMClient._memoryStore.deltaTime = new Date().getTime() - timestamp; } } else if (status == 6) { RongIMLib.RongIMClient.getInstance().disconnect(); //重定向 连错 CMP var me = this; var _client = me._client; var appId = _client.appId, token = _client.token; new RongIMLib.Navigation().requestNavi(token, appId, function () { _client.clearHeartbeat(); var newClient = new RongIMLib.Client(token, appId); RongIMLib.Bridge._client = newClient; newClient.__init(function () { RongIMLib.Transportations._TransportType == "websocket" && newClient.keepLive(); }); }, me._timeout, false); } else { RongIMLib.Bridge._client.channel.socket.socket._status = status; if (this._client.reconnectObj.onError) { this._client.reconnectObj.onError(status); delete this._client.reconnectObj.onError; } else { this._timeout(status); } } }; ConnectAck.prototype.readTimeOut = function (x) { MessageCallback.prototype.readTimeOut.call(this, x); }; return ConnectAck; })(MessageCallback); RongIMLib.ConnectAck = ConnectAck; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var Navigation = (function () { function Navigation() { } Navigation.clear = function () { var storage = RongIMLib.RongIMClient._storageProvider; storage.removeItem('rc_uid'); storage.removeItem('serverIndex'); storage.removeItem('rongSDK'); }; Navigation.prototype.getNaviSuccess = function (result) { var storage = RongIMLib.RongIMClient._storageProvider; storage.setItem('fullnavi', JSON.stringify(result)); var server = result.server; if (server) { server += ','; } var backupServer = result.backupServer || ''; var tpl = '{server}{backupServer}'; var servers = RongIMLib.RongUtil.tplEngine(tpl, { server: server, backupServer: backupServer }); servers = servers.split(','); storage.setItem('servers', JSON.stringify(servers)); var token = RongIMLib.RongIMClient._memoryStore.token; var uid = RongIMLib.InnerUtil.getUId(token); storage.setItem('rc_uid', uid); var userId = result.userId; storage.setItem('current_user', userId); if (result.voipCallInfo) { var callInfo = JSON.parse(result.voipCallInfo); RongIMLib.RongIMClient._memoryStore.voipStategy = callInfo.strategy; storage.setItem("voipStrategy", callInfo.strategy); } //替换本地存储的导航信息 var openMp = result.openMp; storage.setItem('openMp' + uid, openMp); RongIMLib.RongIMClient._memoryStore.depend.openMp = openMp; }; ; Navigation.prototype.connect = function (appId, token, callback) { var oldAppId = RongIMLib.RongIMClient._storageProvider.getItem("appId"); //如果appid和本地存储的不一样,清空所有本地存储数据 if (oldAppId && oldAppId != appId) { RongIMLib.RongIMClient._storageProvider.clearItem(); RongIMLib.RongIMClient._storageProvider.setItem("appId", appId); } if (!oldAppId) { RongIMLib.RongIMClient._storageProvider.setItem("appId", appId); } var client = new RongIMLib.Client(token, appId); this.requestNavi(token, appId, function () { client.connect(callback); }, callback.onError, true); return client; }; Navigation.prototype.requestNavi = function (token, appId, _onsuccess, _onerror, unignore) { if (unignore) { //根据token生成MD5截取8-16下标的数据与本地存储的导航信息进行比对 //如果信息和上次的通道类型都一样,不执行navi请求,用本地存储的导航信息连接服务器 var uId = md5(token).slice(8, 16); var storage = RongIMLib.RongIMClient._storageProvider; var transportType = storage.getItem("rongSDK"); var isSameType = (RongIMLib.Transportations._TransportType == transportType); var _old = storage.getItem('rc_uid'); var isSameUser = (_old == uId); var servers = storage.getItem('servers'); var hasServers = (typeof servers == 'string'); if (isSameUser && isSameType && hasServers && RongIMLib.RongUtil.hasValidWsUrl(servers)) { RongIMLib.RongIMClient._memoryStore.voipStategy = storage.getItem("voipStrategy"); var openMp = storage.getItem('openMp' + uId); RongIMLib.RongIMClient._memoryStore.depend.openMp = openMp; _onsuccess(); return; } } Navigation.clear(); RongIMLib.RongIMClient.invalidWsUrls = []; var context = this; var StatusEvent = RongIMLib.Channel._ConnectionStatusListener; var depend = RongIMLib.RongIMClient._memoryStore.depend; var navigaters = depend.navigaters; var naviTimeout = depend.naviTimeout; var maxNaviRetry = depend.maxNaviRetry; var isNaviJSONP = depend.isNaviJSONP; var isSupportRequestHeaders = RongIMLib.RongUtil.isSupportRequestHeaders(); var isRequestJSONP = !isSupportRequestHeaders || isNaviJSONP; var requestFunc = isRequestJSONP ? context.requestJSONP : context.request; var timer = new RongIMLib.Timer({ timeout: naviTimeout }); var internalRetry = 1; var isRange = function () { return internalRetry >= maxNaviRetry; }; var indexTools = new RongIMLib.IndexTools({ items: navigaters, onwheel: function () { internalRetry += 1; } }); var consume = function () { if (isRange()) { _onerror(RongIMLib.ConnectionStatus.RESPONSE_NAVI_ERROR); return; } var index = indexTools.get(); var navi = navigaters[index]; indexTools.add(); var success = function (result) { timer.pause(); StatusEvent.onChanged(RongIMLib.ConnectionStatus.RESPONSE_NAVI); var code = result.code; if (RongIMLib.RongUtil.isEqual(code, 200)) { context.getNaviSuccess(result); _onsuccess(); } if (RongIMLib.RongUtil.isEqual(code, 401)) { _onerror(RongIMLib.ConnectionState.TOKEN_INCORRECT); } if (RongIMLib.RongUtil.isEqual(code, 403)) { StatusEvent.onChanged(RongIMLib.ConnectionStatus.APPKEY_IS_FAKE); } }; var error = function (status) { if (RongIMLib.RongUtil.isEqual(status, 0)) { return; } timer.pause(); StatusEvent.onChanged(RongIMLib.ConnectionStatus.RESPONSE_NAVI_ERROR); consume(); }; StatusEvent.onChanged(RongIMLib.ConnectionStatus.REQUEST_NAVI); var xhr = requestFunc.call(context, navi, appId, token, success, error); timer.resume(function () { StatusEvent.onChanged(RongIMLib.ConnectionStatus.RESPONSE_NAVI_TIMEOUT); xhr.abort(); consume(); }); }; consume(); }; Navigation.prototype.getPath = function (navi, appId, token, callbackName) { var depend = RongIMLib.RongIMClient._memoryStore.depend; var path = (depend.isPolling ? 'cometnavi' : 'navi'); token = encodeURIComponent(token); var sdkver = RongIMLib.RongIMClient.sdkver; var random = RongIMLib.RongUtil.getTimestamp(); var tpl = '{navi}/{path}.js?appId={appId}&token={token}&callBack={callback}&v={sdkver}&r={random}'; var url = RongIMLib.RongUtil.tplEngine(tpl, { navi: navi, path: path, appId: appId, token: token, sdkver: sdkver, random: random, callback: callbackName }); return url; }; Navigation.prototype.request = function (navi, appId, token, success, error) { var url = this.getPath(navi, appId, token, 'getServerEndpoint'); return RongIMLib.RongUtil.request({ url: url, success: function (result) { result = result.replace('getServerEndpoint(', '').replace(');', ''); // 兼容私有云无分号 var lastIndex = result.lastIndexOf(')'); var maxIndex = result.length - 1; if (lastIndex == maxIndex) { result = result.substr(0, lastIndex); } success(JSON.parse(result)); }, error: function (status, result) { if (status == 401 || status == 403) { success(JSON.parse(result)); } else { error(status); } } }); }; Navigation.prototype.requestJSONP = function (navi, appId, token, success, error) { var callbackName = 'getServerEndpoint'; window.getServerEndpoint = function (result) { var code = result.code; if (code !== 200) { return error(RongIMLib.ConnectionState.TOKEN_INCORRECT); } success(result); }; var url = this.getPath(navi, appId, token, callbackName); var xss = document.createElement('script'); xss.src = url; document.body.appendChild(xss); xss.onerror = function () { error(RongIMLib.ConnectionState.TOKEN_INCORRECT); }; }; Navigation.Endpoint = new Object; return Navigation; })(); RongIMLib.Navigation = Navigation; })(RongIMLib || (RongIMLib = {})); // TODO: 统一变量、方法等命名规范 var RongIMLib; (function (RongIMLib) { /** * 消息基类 */ var BaseMessage = (function () { function BaseMessage(arg) { this._name = "BaseMessage"; this.lengthSize = 0; if (arg instanceof RongIMLib.Header) { this._header = arg; } else { this._header = new RongIMLib.Header(arg, false, RongIMLib.Qos.AT_MOST_ONCE, false); } } BaseMessage.prototype.read = function (In, length) { this.readMessage(In, length); }; BaseMessage.prototype.write = function (Out) { var binaryHelper = new RongIMLib.BinaryHelper(); var out = binaryHelper.convertStream(Out); this._headerCode = this.getHeaderFlag(); out.write(this._headerCode); this.writeMessage(out); return out; }; BaseMessage.prototype.getHeaderFlag = function () { return this._header.encode(); }; BaseMessage.prototype.getLengthSize = function () { return this.lengthSize; }; BaseMessage.prototype.toBytes = function () { return this.write([]).getBytesArray(); }; BaseMessage.prototype.isRetained = function () { return this._header.retain; }; BaseMessage.prototype.setRetained = function (retain) { this._header.retain = retain; }; BaseMessage.prototype.setQos = function (qos) { this._header.qos = Object.prototype.toString.call(qos) == "[object Object]" ? qos : RongIMLib.Qos[qos]; }; BaseMessage.prototype.setDup = function (dup) { this._header.dup = dup; }; BaseMessage.prototype.isDup = function () { return this._header.dup; }; BaseMessage.prototype.getType = function () { return this._header.type; }; BaseMessage.prototype.getQos = function () { return this._header.qos; }; BaseMessage.prototype.messageLength = function () { return 0; }; BaseMessage.prototype.writeMessage = function (out) { }; BaseMessage.prototype.readMessage = function (In, length) { }; BaseMessage.prototype.init = function (args) { var valName, nana, me = this; for (nana in args) { if (!args.hasOwnProperty(nana)) { continue; } valName = nana.replace(/^\w/, function (x) { var tt = x.charCodeAt(0); return "set" + (tt >= 0x61 ? String.fromCharCode(tt & ~32) : x); }); if (valName in me) { if (nana == "status") { me[valName](disconnectStatus[args[nana]] ? disconnectStatus[args[nana]] : args[nana]); } else { me[valName](args[nana]); } } } }; return BaseMessage; })(); RongIMLib.BaseMessage = BaseMessage; /** *连接消息类型 */ var ConnectMessage = (function (_super) { __extends(ConnectMessage, _super); function ConnectMessage(header) { _super.call(this, arguments.length == 0 || arguments.length == 3 ? RongIMLib.Type.CONNECT : arguments[0]); this._name = "ConnectMessage"; this.CONNECT_HEADER_SIZE = 12; this.protocolId = "RCloud"; this.binaryHelper = new RongIMLib.BinaryHelper(); this.protocolVersion = 3; switch (arguments.length) { case 0: case 1: case 3: if (!arguments[0] || arguments[0].length > 64) { throw new Error("ConnectMessage:Client Id cannot be null and must be at most 64 characters long: " + arguments[0]); } this.clientId = arguments[0]; this.cleanSession = arguments[1]; this.keepAlive = arguments[2]; break; } } ConnectMessage.prototype.messageLength = function () { var payloadSize = this.binaryHelper.toMQttString(this.clientId).length; payloadSize += this.binaryHelper.toMQttString(this.willTopic).length; payloadSize += this.binaryHelper.toMQttString(this.will).length; payloadSize += this.binaryHelper.toMQttString(this.appId).length; payloadSize += this.binaryHelper.toMQttString(this.token).length; return payloadSize + this.CONNECT_HEADER_SIZE; }; ConnectMessage.prototype.readMessage = function (stream) { this.protocolId = stream.readUTF(); this.protocolVersion = stream.readByte(); var cFlags = stream.readByte(); this.hasAppId = (cFlags & 128) > 0; this.hasToken = (cFlags & 64) > 0; this.retainWill = (cFlags & 32) > 0; this.willQos = cFlags >> 3 & 3; this.hasWill = (cFlags & 4) > 0; this.cleanSession = (cFlags & 32) > 0; this.keepAlive = stream.read() * 256 + stream.read(); this.clientId = stream.readUTF(); if (this.hasWill) { this.willTopic = stream.readUTF(); this.will = stream.readUTF(); } if (this.hasAppId) { try { this.appId = stream.readUTF(); } catch (ex) { throw new Error(ex); } } if (this.hasToken) { try { this.token = stream.readUTF(); } catch (ex) { throw new Error(ex); } } return stream; }; ConnectMessage.prototype.writeMessage = function (out) { var stream = this.binaryHelper.convertStream(out); stream.writeUTF(this.protocolId); stream.write(this.protocolVersion); var flags = this.cleanSession ? 2 : 0; flags |= this.hasWill ? 4 : 0; flags |= this.willQos ? this.willQos >> 3 : 0; flags |= this.retainWill ? 32 : 0; flags |= this.hasToken ? 64 : 0; flags |= this.hasAppId ? 128 : 0; stream.write(flags); stream.writeChar(this.keepAlive); stream.writeUTF(this.clientId); if (this.hasWill) { stream.writeUTF(this.willTopic); stream.writeUTF(this.will); } if (this.hasAppId) { stream.writeUTF(this.appId); } if (this.hasToken) { stream.writeUTF(this.token); } return stream; }; return ConnectMessage; })(BaseMessage); RongIMLib.ConnectMessage = ConnectMessage; /** *连接应答类型 */ var ConnAckMessage = (function (_super) { __extends(ConnAckMessage, _super); function ConnAckMessage(header) { _super.call(this, arguments.length == 0 ? RongIMLib.Type.CONNACK : arguments.length == 1 ? arguments[0] instanceof RongIMLib.Header ? arguments[0] : RongIMLib.Type.CONNACK : null); this._name = "ConnAckMessage"; this.MESSAGE_LENGTH = 2; this.binaryHelper = new RongIMLib.BinaryHelper(); var me = this; switch (arguments.length) { case 0: case 1: if (!(arguments[0] instanceof RongIMLib.Header)) { if (arguments[0] in RongIMLib.ConnectionState) { if (arguments[0] == null) { throw new Error("ConnAckMessage:The status of ConnAskMessage can't be null"); } me.setStatus(arguments[0]); } } break; } } ; ConnAckMessage.prototype.messageLength = function () { var length = this.MESSAGE_LENGTH; if (this.userId) { length += this.binaryHelper.toMQttString(this.userId).length; } return length; }; ; ConnAckMessage.prototype.readMessage = function (_in, msglength) { _in.read(); var result = +_in.read(); if (result >= 0 && result <= 12) { this.setStatus(result); } else { throw new Error("Unsupported CONNACK code:" + result); } if (msglength > this.MESSAGE_LENGTH) { this.setUserId(_in.readUTF()); var sessionId = _in.readUTF(); var timestamp = _in.readLong(); this.setTimestamp(timestamp); } }; ; ConnAckMessage.prototype.writeMessage = function (out) { var stream = this.binaryHelper.convertStream(out); stream.write(128); switch (+status) { case 0: case 1: case 2: case 5: case 6: stream.write(+status); break; case 3: case 4: stream.write(3); break; default: throw new Error("Unsupported CONNACK code:" + status); } if (this.userId) { stream.writeUTF(this.userId); } return stream; }; ; ConnAckMessage.prototype.setStatus = function (x) { this.status = x; }; ; ConnAckMessage.prototype.setUserId = function (_userId) { this.userId = _userId; }; ; ConnAckMessage.prototype.getStatus = function () { return this.status; }; ; ConnAckMessage.prototype.getUserId = function () { return this.userId; }; ; ConnAckMessage.prototype.setTimestamp = function (x) { this.timestrap = x; }; ; ConnAckMessage.prototype.getTimestamp = function () { return this.timestrap; }; return ConnAckMessage; })(BaseMessage); RongIMLib.ConnAckMessage = ConnAckMessage; /** *断开消息类型 */ var DisconnectMessage = (function (_super) { __extends(DisconnectMessage, _super); function DisconnectMessage(header) { _super.call(this, header instanceof RongIMLib.Header ? header : RongIMLib.Type.DISCONNECT); this._name = "DisconnectMessage"; this.MESSAGE_LENGTH = 2; this.binaryHelper = new RongIMLib.BinaryHelper(); if (!(header instanceof RongIMLib.Header)) { if (header in RongIMLib.ConnectionStatus) { this.status = header; } } } DisconnectMessage.prototype.messageLength = function () { return this.MESSAGE_LENGTH; }; DisconnectMessage.prototype.readMessage = function (_in) { _in.read(); var result = +_in.read(); if (result >= 0 && result <= 5) { this.setStatus(disconnectStatus[result] ? disconnectStatus[result] : result); } else { throw new Error("Unsupported CONNACK code:" + result); } }; DisconnectMessage.prototype.writeMessage = function (Out) { var out = this.binaryHelper.convertStream(Out); out.write(0); if (+status >= 1 && +status <= 3) { out.write((+status) - 1); } else { throw new Error("Unsupported CONNACK code:" + status); } }; DisconnectMessage.prototype.setStatus = function (x) { this.status = x; }; ; DisconnectMessage.prototype.getStatus = function () { return this.status; }; ; return DisconnectMessage; })(BaseMessage); RongIMLib.DisconnectMessage = DisconnectMessage; /** *请求消息信令 */ var PingReqMessage = (function (_super) { __extends(PingReqMessage, _super); function PingReqMessage(header) { _super.call(this, (header && header instanceof RongIMLib.Header) ? header : RongIMLib.Type.PINGREQ); this._name = "PingReqMessage"; } return PingReqMessage; })(BaseMessage); RongIMLib.PingReqMessage = PingReqMessage; /** *响应消息信令 */ var PingRespMessage = (function (_super) { __extends(PingRespMessage, _super); function PingRespMessage(header) { _super.call(this, (header && header instanceof RongIMLib.Header) ? header : RongIMLib.Type.PINGRESP); this._name = "PingRespMessage"; } return PingRespMessage; })(BaseMessage); RongIMLib.PingRespMessage = PingRespMessage; /** *封装MesssageId */ var RetryableMessage = (function (_super) { __extends(RetryableMessage, _super); function RetryableMessage(argu) { _super.call(this, argu); this._name = "RetryableMessage"; this.binaryHelper = new RongIMLib.BinaryHelper(); } RetryableMessage.prototype.messageLength = function () { return 2; }; RetryableMessage.prototype.writeMessage = function (Out) { var out = this.binaryHelper.convertStream(Out), Id = this.getMessageId(), lsb = Id & 255, msb = (Id & 65280) >> 8; out.write(msb); out.write(lsb); return out; }; RetryableMessage.prototype.readMessage = function (_in, msgLength) { var msgId = _in.read() * 256 + _in.read(); this.setMessageId(parseInt(msgId, 10)); }; RetryableMessage.prototype.setMessageId = function (_messageId) { this.messageId = _messageId; }; RetryableMessage.prototype.getMessageId = function () { return this.messageId; }; return RetryableMessage; })(BaseMessage); RongIMLib.RetryableMessage = RetryableMessage; /** *发送消息应答(双向) *qos为1必须给出应答(所有消息类型一样) */ var PubAckMessage = (function (_super) { __extends(PubAckMessage, _super); function PubAckMessage(header) { _super.call(this, (header instanceof RongIMLib.Header) ? header : RongIMLib.Type.PUBACK); this.msgLen = 2; this.date = 0; this.millisecond = 0; this.timestamp = 0; this.binaryHelper = new RongIMLib.BinaryHelper(); this._name = "PubAckMessage"; if (!(header instanceof RongIMLib.Header)) { _super.prototype.setMessageId.call(this, header); } } PubAckMessage.prototype.messageLength = function () { return this.msgLen; }; PubAckMessage.prototype.writeMessage = function (Out) { var out = this.binaryHelper.convertStream(Out); RetryableMessage.prototype.writeMessage.call(this, out); }; PubAckMessage.prototype.readMessage = function (_in, msgLength) { RetryableMessage.prototype.readMessage.call(this, _in); this.date = _in.readInt(); this.status = _in.read() * 256 + _in.read(); this.millisecond = _in.read() * 256 + _in.read(); this.timestamp = this.date * 1000 + this.millisecond; this.messageUId = _in.readUTF(); }; PubAckMessage.prototype.setStatus = function (x) { this.status = x; }; PubAckMessage.prototype.setTimestamp = function (timestamp) { this.timestamp = timestamp; }; PubAckMessage.prototype.setMessageUId = function (messageUId) { this.messageUId = messageUId; }; PubAckMessage.prototype.getStatus = function () { return this.status; }; PubAckMessage.prototype.getDate = function () { return this.date; }; PubAckMessage.prototype.getTimestamp = function () { return this.timestamp; }; PubAckMessage.prototype.getMessageUId = function () { return this.messageUId; }; return PubAckMessage; })(RetryableMessage); RongIMLib.PubAckMessage = PubAckMessage; /** *发布消息 */ var PublishMessage = (function (_super) { __extends(PublishMessage, _super); function PublishMessage(header, two, three) { _super.call(this, (arguments.length == 1 && header instanceof RongIMLib.Header) ? header : arguments.length == 3 ? RongIMLib.Type.PUBLISH : 0); this._name = "PublishMessage"; this.binaryHelper = new RongIMLib.BinaryHelper(); this.syncMsg = false; if (arguments.length == 3) { this.topic = header; this.targetId = three; this.data = typeof two == "string" ? this.binaryHelper.toMQttString(two) : two; } } PublishMessage.prototype.messageLength = function () { var length = 10; length += this.binaryHelper.toMQttString(this.topic).length; length += this.binaryHelper.toMQttString(this.targetId).length; length += this.data.length; return length; }; PublishMessage.prototype.writeMessage = function (Out) { var out = this.binaryHelper.convertStream(Out); out.writeUTF(this.topic); out.writeUTF(this.targetId); RetryableMessage.prototype.writeMessage.apply(this, arguments); out.write(this.data); }; ; PublishMessage.prototype.readMessage = function (_in, msgLength) { var pos = 6; this.date = _in.readInt(); this.topic = _in.readUTF(); pos += this.binaryHelper.toMQttString(this.topic).length; this.targetId = _in.readUTF(); pos += this.binaryHelper.toMQttString(this.targetId).length; RetryableMessage.prototype.readMessage.apply(this, arguments); this.data = new Array(msgLength - pos); this.data = _in.read(this.data); }; ; PublishMessage.prototype.setTopic = function (x) { this.topic = x; }; PublishMessage.prototype.setData = function (x) { this.data = x; }; PublishMessage.prototype.setTargetId = function (x) { this.targetId = x; }; PublishMessage.prototype.setDate = function (x) { this.date = x; }; PublishMessage.prototype.setSyncMsg = function (x) { this.syncMsg = x; }; //是否是其他端同步过来的消息 PublishMessage.prototype.getSyncMsg = function () { return this.syncMsg; }; PublishMessage.prototype.getTopic = function () { return this.topic; }; PublishMessage.prototype.getData = function () { return this.data; }; PublishMessage.prototype.getTargetId = function () { return this.targetId; }; PublishMessage.prototype.getDate = function () { return this.date; }; return PublishMessage; })(RetryableMessage); RongIMLib.PublishMessage = PublishMessage; /** *请求查询 */ var QueryMessage = (function (_super) { __extends(QueryMessage, _super); function QueryMessage(header, two, three) { _super.call(this, header instanceof RongIMLib.Header ? header : arguments.length == 3 ? RongIMLib.Type.QUERY : null); this.binaryHelper = new RongIMLib.BinaryHelper(); this._name = "QueryMessage"; if (arguments.length == 3) { this.data = typeof two == "string" ? this.binaryHelper.toMQttString(two) : two; this.topic = header; this.targetId = three; } } QueryMessage.prototype.messageLength = function () { var length = 0; length += this.binaryHelper.toMQttString(this.topic).length; length += this.binaryHelper.toMQttString(this.targetId).length; length += 2; length += this.data.length; return length; }; QueryMessage.prototype.writeMessage = function (Out) { var out = this.binaryHelper.convertStream(Out); out.writeUTF(this.topic); out.writeUTF(this.targetId); RetryableMessage.prototype.writeMessage.call(this, out); out.write(this.data); }; QueryMessage.prototype.readMessage = function (_in, msgLength) { var pos = 0; this.topic = _in.readUTF(); this.targetId = _in.readUTF(); pos += this.binaryHelper.toMQttString(this.topic).length; pos += this.binaryHelper.toMQttString(this.targetId).length; this.readMessage.apply(this, arguments); pos += 2; this.data = new Array(msgLength - pos); _in.read(this.data); }; QueryMessage.prototype.setTopic = function (x) { this.topic = x; }; QueryMessage.prototype.setData = function (x) { this.data = x; }; QueryMessage.prototype.setTargetId = function (x) { this.targetId = x; }; QueryMessage.prototype.getTopic = function () { return this.topic; }; QueryMessage.prototype.getData = function () { return this.data; }; QueryMessage.prototype.getTargetId = function () { return this.targetId; }; return QueryMessage; })(RetryableMessage); RongIMLib.QueryMessage = QueryMessage; /** *请求查询确认 */ var QueryConMessage = (function (_super) { __extends(QueryConMessage, _super); function QueryConMessage(messageId) { _super.call(this, (messageId instanceof RongIMLib.Header) ? messageId : RongIMLib.Type.QUERYCON); this._name = "QueryConMessage"; if (!(messageId instanceof RongIMLib.Header)) { _super.prototype.setMessageId.call(this, messageId); } } return QueryConMessage; })(RetryableMessage); RongIMLib.QueryConMessage = QueryConMessage; /** *请求查询应答 */ var QueryAckMessage = (function (_super) { __extends(QueryAckMessage, _super); function QueryAckMessage(header) { _super.call(this, header); this._name = "QueryAckMessage"; this.binaryHelper = new RongIMLib.BinaryHelper(); } QueryAckMessage.prototype.readMessage = function (In, msgLength) { RetryableMessage.prototype.readMessage.call(this, In); this.date = In.readInt(); this.setStatus(In.read() * 256 + In.read()); if (msgLength > 0) { this.data = new Array(msgLength - 8); this.data = In.read(this.data); } }; QueryAckMessage.prototype.getData = function () { return this.data; }; QueryAckMessage.prototype.getStatus = function () { return this.status; }; QueryAckMessage.prototype.getDate = function () { return this.date; }; QueryAckMessage.prototype.setDate = function (x) { this.date = x; }; QueryAckMessage.prototype.setStatus = function (x) { this.status = x; }; QueryAckMessage.prototype.setData = function (x) { this.data = x; }; return QueryAckMessage; })(RetryableMessage); RongIMLib.QueryAckMessage = QueryAckMessage; })(RongIMLib || (RongIMLib = {})); /// var RongIMLib; (function (RongIMLib) { /** * 把消息对象写入流中 * 发送消息时用到 */ var MessageOutputStream = (function () { function MessageOutputStream(_out) { var binaryHelper = new RongIMLib.BinaryHelper(); this.out = binaryHelper.convertStream(_out); } MessageOutputStream.prototype.writeMessage = function (msg) { if (msg instanceof RongIMLib.BaseMessage) { msg.write(this.out); } }; return MessageOutputStream; })(); RongIMLib.MessageOutputStream = MessageOutputStream; /** * 流转换为消息对象 * 服务器返回消息时用到 */ var MessageInputStream = (function () { function MessageInputStream(In, isPolling) { if (!isPolling) { var _in = new RongIMLib.BinaryHelper().convertStream(In); this.flags = _in.readByte(); this._in = _in; } else { this.flags = In["headerCode"]; } this.header = new RongIMLib.Header(this.flags); this.isPolling = isPolling; this.In = In; } MessageInputStream.prototype.readMessage = function () { switch (this.header.getType()) { case 1: this.msg = new RongIMLib.ConnectMessage(this.header); break; case 2: this.msg = new RongIMLib.ConnAckMessage(this.header); break; case 3: this.msg = new RongIMLib.PublishMessage(this.header); this.msg.setSyncMsg(this.header.getSyncMsg()); break; case 4: this.msg = new RongIMLib.PubAckMessage(this.header); break; case 5: this.msg = new RongIMLib.QueryMessage(this.header); break; case 6: this.msg = new RongIMLib.QueryAckMessage(this.header); break; case 7: this.msg = new RongIMLib.QueryConMessage(this.header); break; case 9: case 11: case 13: this.msg = new RongIMLib.PingRespMessage(this.header); break; case 8: case 10: case 12: this.msg = new RongIMLib.PingReqMessage(this.header); break; case 14: this.msg = new RongIMLib.DisconnectMessage(this.header); break; default: throw new Error("No support for deserializing " + this.header.getType() + " messages"); } if (this.isPolling) { this.msg.init(this.In); } else { this.msg.read(this._in, this.In.length - 1); } return this.msg; }; return MessageInputStream; })(); RongIMLib.MessageInputStream = MessageInputStream; var Header = (function () { function Header(_type, _retain, _qos, _dup) { this.retain = false; this.qos = RongIMLib.Qos.AT_LEAST_ONCE; this.dup = false; this.syncMsg = false; if (_type && +_type == _type && arguments.length == 1) { this.retain = (_type & 1) > 0; this.qos = (_type & 6) >> 1; this.dup = (_type & 8) > 0; this.type = (_type >> 4) & 15; this.syncMsg = (_type & 8) == 8; } else { this.type = _type; this.retain = _retain; this.qos = _qos; this.dup = _dup; } } Header.prototype.getSyncMsg = function () { return this.syncMsg; }; Header.prototype.getType = function () { return this.type; }; Header.prototype.encode = function () { var me = this; switch (this.qos) { case RongIMLib.Qos[0]: me.qos = RongIMLib.Qos.AT_MOST_ONCE; break; case RongIMLib.Qos[1]: me.qos = RongIMLib.Qos.AT_LEAST_ONCE; break; case RongIMLib.Qos[2]: me.qos = RongIMLib.Qos.EXACTLY_ONCE; break; case RongIMLib.Qos[3]: me.qos = RongIMLib.Qos.DEFAULT; break; } var _byte = (this.type << 4); _byte |= this.retain ? 1 : 0; _byte |= this.qos << 1; _byte |= this.dup ? 8 : 0; return _byte; }; Header.prototype.toString = function () { return "Header [type=" + this.type + ",retain=" + this.retain + ",qos=" + this.qos + ",dup=" + this.dup + "]"; }; return Header; })(); RongIMLib.Header = Header; /** * 二进制帮助对象 */ var BinaryHelper = (function () { function BinaryHelper() { } BinaryHelper.prototype.writeUTF = function (str, isGetBytes) { var back = [], byteSize = 0; for (var i = 0, len = str.length; i < len; i++) { var code = str.charCodeAt(i); if (code >= 0 && code <= 127) { byteSize += 1; back.push(code); } else if (code >= 128 && code <= 2047) { byteSize += 2; back.push((192 | (31 & (code >> 6)))); back.push((128 | (63 & code))); } else if (code >= 2048 && code <= 65535) { byteSize += 3; back.push((224 | (15 & (code >> 12)))); back.push((128 | (63 & (code >> 6)))); back.push((128 | (63 & code))); } } for (var i = 0, len = back.length; i < len; i++) { if (back[i] > 255) { back[i] &= 255; } } if (isGetBytes) { return back; } if (byteSize <= 255) { return [0, byteSize].concat(back); } else { return [byteSize >> 8, byteSize & 255].concat(back); } }; BinaryHelper.prototype.readUTF = function (arr) { if (Object.prototype.toString.call(arr) == "[object String]") { return arr; } var UTF = "", _arr = arr; for (var i = 0, len = _arr.length; i < len; i++) { if (_arr[i] < 0) { _arr[i] += 256; } ; var one = _arr[i].toString(2), v = one.match(/^1+?(?=0)/); if (v && one.length == 8) { var bytesLength = v[0].length, // store = _arr[i].toString(2).slice(7 - bytesLength); store = ''; for (var st = 0; st < bytesLength; st++) { store += _arr[st + i].toString(2).slice(2); } UTF += String.fromCharCode(parseInt(store, 2)); i += bytesLength - 1; } else { UTF += String.fromCharCode(_arr[i]); } } return UTF; }; /** * [convertStream 将参数x转化为RongIMStream对象] * @param {any} x [参数] */ BinaryHelper.prototype.convertStream = function (x) { if (x instanceof RongIMStream) { return x; } else { return new RongIMStream(x); } }; BinaryHelper.prototype.toMQttString = function (str) { return this.writeUTF(str); }; return BinaryHelper; })(); RongIMLib.BinaryHelper = BinaryHelper; var RongIMStream = (function () { function RongIMStream(arr) { //当前流执行的起始位置 this.position = 0; //当前流写入的多少字节 this.writen = 0; this.poolLen = 0; this.binaryHelper = new BinaryHelper(); this.pool = arr; this.poolLen = arr.length; } RongIMStream.prototype.check = function () { return this.position >= this.pool.length; }; RongIMStream.prototype.readInt = function () { if (this.check()) { return -1; } var end = ""; for (var i = 0; i < 4; i++) { var t = this.pool[this.position++].toString(16); if (t.length == 1) { t = "0" + t; } end += t.toString(16); } return parseInt(end, 16); }; RongIMStream.prototype.readLong = function () { if (this.check()) { return -1; } var end = ""; for (var i = 0; i < 8; i++) { var t = this.pool[this.position++].toString(16); if (t.length == 1) { t = "0" + t; } end += t; } return parseInt(end, 16); }; RongIMStream.prototype.readTimestamp = function () { if (this.check()) { return -1; } var end = ""; for (var i = 0; i < 8; i++) { end += this.pool[this.position++].toString(16); } end = end.substring(2, 8); return parseInt(end, 16); }; RongIMStream.prototype.readUTF = function () { if (this.check()) { return -1; } var big = (this.readByte() << 8) | this.readByte(); return this.binaryHelper.readUTF(this.pool.subarray(this.position, this.position += big)); }; RongIMStream.prototype.readByte = function () { if (this.check()) { return -1; } var val = this.pool[this.position++]; if (val > 255) { val &= 255; } return val; }; RongIMStream.prototype.read = function (bytesArray) { if (bytesArray) { return this.pool.subarray(this.position, this.poolLen); } else { return this.readByte(); } }; RongIMStream.prototype.write = function (_byte) { var b = _byte; if (Object.prototype.toString.call(b).toLowerCase() == "[object array]") { [].push.apply(this.pool, b); } else { if (+b == b) { if (b > 255) { b &= 255; } this.pool.push(b); this.writen++; } } return b; }; RongIMStream.prototype.writeChar = function (v) { if (+v != v) { throw new Error("writeChar:arguments type is error"); } this.write(v >> 8 & 255); this.write(v & 255); this.writen += 2; }; RongIMStream.prototype.writeUTF = function (str) { var val = this.binaryHelper.writeUTF(str); [].push.apply(this.pool, val); this.writen += val.length; }; RongIMStream.prototype.toComplements = function () { var _tPool = this.pool; for (var i = 0; i < this.poolLen; i++) { if (_tPool[i] > 128) { _tPool[i] -= 256; } } return _tPool; }; RongIMStream.prototype.getBytesArray = function (isCom) { if (isCom) { return this.toComplements(); } return this.pool; }; return RongIMStream; })(); RongIMLib.RongIMStream = RongIMStream; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var SocketTransportation = (function () { /** * [constructor] * @param {string} url [连接地址:包含token、version] */ function SocketTransportation(_socket) { //连接状态 true:已连接 false:未连接 this.connected = false; //是否关闭: true:已关闭 false:未关闭 this.isClose = false; //存放消息队列的临时变量 this.queue = []; this.empty = new Function; this._socket = _socket; return this; } /** * [createTransport 创建WebScoket对象] */ SocketTransportation.prototype.createTransport = function (url, method) { if (!url) { throw new Error("URL can't be empty"); } ; this.url = url; var depend = RongIMLib.RongIMClient._memoryStore.depend; var wsScheme = depend.wsScheme; var tpl = '{wsScheme}{url}'; console.log('url', url); url = RongIMLib.RongUtil.tplEngine(tpl, { wsScheme: wsScheme, url: url }); this.socket = new WebSocket(url); this.socket.binaryType = "arraybuffer"; this.addEvent(); return this.socket; }; /** * [send 传送消息流] * @param {ArrayBuffer} data [二进制消息流] */ SocketTransportation.prototype.send = function (data) { if (!this.connected && !this.isClose) { //当通道不可用时,加入消息队列 this.queue.push(data); return; } if (this.isClose) { this._socket.fire("StatusChanged", RongIMLib.ConnectionStatus.CONNECTION_CLOSED); return; } var stream = new RongIMLib.RongIMStream([]), msg = new RongIMLib.MessageOutputStream(stream); msg.writeMessage(data); var val = stream.getBytesArray(true); var binary = new Int8Array(val); this.socket.send(binary.buffer); return this; }; /** * [onData 通道返回数据时调用的方法,用来想上层传递服务器返回的二进制消息流] * @param {ArrayBuffer} data [二进制消息流] */ SocketTransportation.prototype.onData = function (data) { if (RongIMLib.MessageUtil.isArray(data)) { this._socket.onMessage(new RongIMLib.MessageInputStream(data).readMessage()); } else { this._socket.onMessage(new RongIMLib.MessageInputStream(RongIMLib.MessageUtil.ArrayFormInput(data)).readMessage()); } return ""; }; /** * [onClose 通道关闭时触发的方法] */ SocketTransportation.prototype.onClose = function (ev) { var me = this; me.isClose = true; me.socket = this.empty; RongIMLib.Bridge._client.clearHeartbeat(); if (ev.code == 1006 && !this._status) { var currentTime = new Date().getTime(); if (currentTime - me.connectedTime <= SocketTransportation.MinConnectTime) { var host = RongIMLib.RongUtil.getUrlHost(me.url); RongIMLib.RongIMClient.invalidWsUrls.push(host); } me._socket.fire("StatusChanged", RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE); } else { me._status = 0; } }; /** * [onError 通道报错时触发的方法] * @param {any} error [抛出异常] */ SocketTransportation.prototype.onError = function (error) { this._socket.fire("StatusChanged", RongIMLib.ConnectionStatus.WEBSOCKET_ERROR); throw new Error(error); }; /** * [addEvent 为通道绑定事件] */ SocketTransportation.prototype.addEvent = function () { var self = this; self.socket.onopen = function () { self.connected = true; self.isClose = false; //通道可以用后,调用发送队列方法,把所有等得发送的消息发出 self.doQueue(); self._socket.fire("connect"); self.connectedTime = new Date().getTime(); }; self.socket.onmessage = function (ev) { //判断数据是不是字符串,如果是字符串那么就是flash传过来的。 if (typeof ev.data == "string") { self.onData(ev.data.split(",")); } else { self.onData(ev.data); } }; self.socket.onerror = function (ev) { self.onError(ev); }; self.socket.onclose = function (ev) { self.onClose(ev); }; }; /** * [doQueue 消息队列,把队列中消息发出] */ SocketTransportation.prototype.doQueue = function () { var self = this; for (var i = 0, len = self.queue.length; i < len; i++) { self.send(self.queue[i]); } }; /** * [disconnect 断开连接] */ SocketTransportation.prototype.disconnect = function (status) { var me = this; if (me.socket.readyState) { me.isClose = true; if (status) { me._status = status; } me.socket.close(); } }; /** * [reconnect 重新连接] */ SocketTransportation.prototype.reconnect = function () { this.disconnect(); this.createTransport(this.url); }; SocketTransportation.prototype.close = function () { this.socket.close(); }; // 最短链接时长(若 5000ms 内, ws 自动断开, 此 ws 地址置为不可用) SocketTransportation.MinConnectTime = 5000; return SocketTransportation; })(); RongIMLib.SocketTransportation = SocketTransportation; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var PollingTransportation = (function () { function PollingTransportation(socket) { this.empty = new Function; this.connected = false; this.pid = +new Date + Math.random() + ""; this.queue = []; this.socket = socket; return this; } PollingTransportation.prototype.createTransport = function (url, method) { if (!url) { throw new Error("Url is empty,Please check it!"); } ; this.url = url; var sid = RongIMLib.RongIMClient._storageProvider.getItem("sId" + RongIMLib.Navigation.Endpoint.userId), me = this; if (sid) { setTimeout(function () { me.onSuccess("{\"status\":0,\"userId\":\"" + RongIMLib.Navigation.Endpoint.userId + "\",\"headerCode\":32,\"messageId\":0,\"sessionid\":\"" + sid + "\"}"); me.connected = true; }, 500); return this; } this.getRequest(url, true); return this; }; PollingTransportation.prototype.requestFactory = function (url, method, multipart) { var reqest = this.XmlHttpRequest(); if (multipart) { reqest.multipart = true; } // reqest.timeout = 60000; reqest.open(method || "GET", RongIMLib.RongIMClient._memoryStore.depend.protocol + url); if (method == "POST" && "setRequestHeader" in reqest) { reqest.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=utf-8"); } return reqest; }; PollingTransportation.prototype.getRequest = function (url, isconnect) { var me = this; me.xhr = this.requestFactory(url + "&pid=" + encodeURIComponent(me.pid), "GET"); var timer = new RongIMLib.Timer({ timeout: 45000 }); if ("onload" in me.xhr) { me.xhr.onload = function () { timer.pause(); me.xhr.onload = me.empty; if (this.responseText == "lost params") { me.onError(); } else { me.onSuccess(this.responseText, isconnect); } }; me.xhr.onerror = function () { timer.pause(); me.disconnect(); }; } else { me.xhr.onreadystatechange = function () { timer.pause(); if (me.xhr.readyState == 4) { me.xhr.onreadystatechange = me.empty; if (/^(200|202)$/.test(me.xhr.status)) { me.onSuccess(me.xhr.responseText, isconnect); } else if (/^(400|403)$/.test(me.xhr.status)) { me.onError(); } else { me.disconnect(); } } }; } timer.resume(function () { me.onError(); }); me.xhr.send(); }; /** * [send 发送消息,Method:POST] * queue 为消息队列,待通道可用发送所有等待消息 * @param {string} data [需要传入comet格式数据,此处只负责通讯通道,数据转换在外层处理] */ PollingTransportation.prototype.send = function (data) { var me = this; var _send = me.sendxhr = this.requestFactory(RongIMLib.Navigation.Endpoint.host + "/websocket" + data.url + "&pid=" + encodeURIComponent(me.pid), "POST"); if ("onload" in _send) { _send.onload = function () { _send.onload = me.empty; me.onData(_send.responseText); }; _send.onerror = function () { _send.onerror = me.empty; }; } else { _send.onreadystatechange = function () { if (_send.readyState == 4) { this.onreadystatechange = this.empty; if (/^(202|200)$/.test(_send.status)) { me.onData(_send.responseText); } } }; } _send.send(JSON.stringify(data.data)); }; PollingTransportation.prototype.onData = function (data, header) { if (!data || data == "lost params") { return; } var self = this, val = JSON.parse(data); if (val.userId) { RongIMLib.Navigation.Endpoint.userId = val.userId; } if (header) { RongIMLib.RongIMClient._storageProvider.setItem("sId" + RongIMLib.Navigation.Endpoint.userId, header); } if (!RongIMLib.MessageUtil.isArray(val)) { val = [val]; } Array.forEach(val, function (m) { self.socket.fire("message", new RongIMLib.MessageInputStream(m, true).readMessage()); }); return ""; }; PollingTransportation.prototype.XmlHttpRequest = function () { var hasCORS = typeof XMLHttpRequest !== "undefined" && "withCredentials" in new XMLHttpRequest(), self = this; if ("undefined" != typeof XMLHttpRequest && hasCORS) { return new XMLHttpRequest(); } else if ("undefined" != typeof XDomainRequest) { return new XDomainRequest(); } else { return new ActiveXObject("Microsoft.XMLHTTP"); } }; PollingTransportation.prototype.onClose = function () { if (this.xhr) { if (this.xhr.onload) { this.xhr.onreadystatechange = this.xhr.onload = this.empty; } else { this.xhr.onreadystatechange = this.empty; } this.xhr.abort(); this.xhr = null; } if (this.sendxhr) { if (this.sendxhr.onload) { this.sendxhr.onreadystatechange = this.sendxhr.onload = this.empty; } else { this.sendxhr.onreadystatechange = this.empty; } this.sendxhr.abort(); this.sendxhr = null; } }; PollingTransportation.prototype.disconnect = function () { RongIMLib.RongIMClient._storageProvider.removeItem("sId" + RongIMLib.Navigation.Endpoint.userId); RongIMLib.RongIMClient._storageProvider.removeItem(RongIMLib.Navigation.Endpoint.userId + "msgId"); this.onClose(); }; PollingTransportation.prototype.reconnect = function () { this.disconnect(); this.createTransport(this.url); }; PollingTransportation.prototype.onSuccess = function (responseText, isconnect) { var txt = responseText.match(/"sessionid":"\S+?(?=")/); this.onData(responseText, txt ? txt[0].slice(13) : 0); if (/"headerCode":-32,/.test(responseText)) { RongIMLib.RongIMClient._storageProvider.removeItem("sId" + RongIMLib.Navigation.Endpoint.userId); RongIMLib.RongIMClient._storageProvider.removeItem(RongIMLib.Navigation.Endpoint.userId + "msgId"); return; } this.getRequest(RongIMLib.Navigation.Endpoint.host + "/pullmsg.js?sessionid=" + RongIMLib.RongIMClient._storageProvider.getItem("sId" + RongIMLib.Navigation.Endpoint.userId) + "×trap=" + encodeURIComponent(new Date().getTime() + Math.random() + "")); this.connected = true; isconnect && this.socket.fire("connect"); }; PollingTransportation.prototype.onError = function () { RongIMLib.RongIMClient._storageProvider.removeItem("sId" + RongIMLib.Navigation.Endpoint.userId); RongIMLib.RongIMClient._storageProvider.removeItem(RongIMLib.Navigation.Endpoint.userId + "msgId"); this.onClose(); if (this.connected) { this.connected = false; var code = RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE; this.socket.fire("disconnect", code); } }; PollingTransportation.prototype.close = function () { this.xhr.abort(); this.sendxhr = null; }; return PollingTransportation; })(); RongIMLib.PollingTransportation = PollingTransportation; })(RongIMLib || (RongIMLib = {})); //objectname映射 var typeMapping = { "RC:TxtMsg": "TextMessage", "RC:ImgMsg": "ImageMessage", "RC:VcMsg": "VoiceMessage", "RC:ImgTextMsg": "RichContentMessage", "RC:FileMsg": "FileMessage", "RC:HQVCMsg": "HQVoiceMessage", "RC:LBSMsg": "LocationMessage", "RC:InfoNtf": "InformationNotificationMessage", "RC:ContactNtf": "ContactNotificationMessage", "RC:ProfileNtf": "ProfileNotificationMessage", "RC:CmdNtf": "CommandNotificationMessage", "RC:DizNtf": "DiscussionNotificationMessage", "RC:CmdMsg": "CommandMessage", "RC:TypSts": "TypingStatusMessage", "RC:CsChaR": "ChangeModeResponseMessage", "RC:CsHsR": "HandShakeResponseMessage", "RC:CsEnd": "TerminateMessage", "RC:CsSp": "SuspendMessage", "RC:CsUpdate": "CustomerStatusUpdateMessage", "RC:ReadNtf": "ReadReceiptMessage", "RC:VCAccept": "AcceptMessage", "RC:VCRinging": "RingingMessage", "RC:VCSummary": "SummaryMessage", "RC:VCHangup": "HungupMessage", "RC:VCInvite": "InviteMessage", "RC:VCModifyMedia": "MediaModifyMessage", "RC:VCModifyMem": "MemberModifyMessage", "RC:CsContact": "CustomerContact", "RC:PSImgTxtMsg": "PublicServiceRichContentMessage", "RC:PSMultiImgTxtMsg": "PublicServiceMultiRichContentMessage", "RC:GrpNtf": "GroupNotificationMessage", "RC:PSCmd": "PublicServiceCommandMessage", "RC:RcCmd": "RecallCommandMessage", "RC:SRSMsg": "SyncReadStatusMessage", "RC:RRReqMsg": "ReadReceiptRequestMessage", "RC:RRRspMsg": "ReadReceiptResponseMessage", "RCJrmf:RpMsg": "JrmfRedPacketMessage", "RCJrmf:RpOpendMsg": "JrmfRedPacketOpenedMessage", "RC:CombineMsg": "RCCombineMessage", "RC:chrmKVNotiMsg": "ChrmKVNotificationMessage" }, //自定义消息类型 registerMessageTypeMapping = {}, HistoryMsgType = { 4: "qryCMsg", 2: "qryDMsg", 3: "qryGMsg", 1: "qryPMsg", 6: "qrySMsg", 7: "qryPMsg", 8: "qryPMsg", 5: "qryCMsg" }, disconnectStatus = { 1: 6 }; var RongIMLib; (function (RongIMLib) { /** * 通道标识类 */ var Transportations = (function () { function Transportations() { } Transportations._TransportType = RongIMLib.Socket.WEBSOCKET; return Transportations; })(); RongIMLib.Transportations = Transportations; var SyncTimeUtil = (function () { function SyncTimeUtil() { } SyncTimeUtil.$getKey = function (message) { var client = RongIMLib.Bridge._client; var userId = client.userId; var direction = (message.messageDirection == 1 ? 'send' : 'receive'); var appkey = RongIMLib.RongIMClient._memoryStore.appKey; var tpl = '{appkey}_{userId}_{direction}box'; return RongIMLib.RongUtil.tplEngine(tpl, { appkey: appkey, userId: userId, direction: direction }); }; SyncTimeUtil.set = function (message) { var key = SyncTimeUtil.$getKey(message); var sentTime = message.sentTime; var storage = RongIMLib.RongIMClient._storageProvider; storage.setItem(key, sentTime); }; SyncTimeUtil.get = function () { var sent = SyncTimeUtil.$getKey({ messageDirection: RongIMLib.MessageDirection.SEND }); var received = SyncTimeUtil.$getKey({ messageDirection: RongIMLib.MessageDirection.RECEIVE }); var storage = RongIMLib.RongIMClient._storageProvider; return { sent: Number(storage.getItem(sent) || 0), received: Number(storage.getItem(received) || 0) }; }; return SyncTimeUtil; })(); RongIMLib.SyncTimeUtil = SyncTimeUtil; var MessageUtil = (function () { function MessageUtil() { } /** *4680000 为localstorage最小容量5200000字节的90%,超过90%将删除之前过早的存储 */ MessageUtil.checkStorageSize = function () { return JSON.stringify(localStorage).length < 4680000; }; MessageUtil.getFirstKey = function (obj) { var str = ""; for (var key in obj) { str = key; break; } return str; }; MessageUtil.isEmpty = function (obj) { var empty = true; for (var key in obj) { empty = false; break; } return empty; }; MessageUtil.ArrayForm = function (typearray) { if (Object.prototype.toString.call(typearray) == "[object ArrayBuffer]") { var arr = new Int8Array(typearray); return [].slice.call(arr); } return typearray; }; MessageUtil.ArrayFormInput = function (typearray) { if (Object.prototype.toString.call(typearray) == "[object ArrayBuffer]") { var arr = new Uint8Array(typearray); return arr; } return typearray; }; MessageUtil.indexOf = function (arr, item, from) { for (var l = arr.length, i = (from < 0) ? Math.max(0, +from) : from || 0; i < l; i++) { if (arr[i] == item) { return i; } } return -1; }; MessageUtil.isArray = function (obj) { return Object.prototype.toString.call(obj) == "[object Array]"; }; //遍历,只能遍历数组 MessageUtil.forEach = function (arr, func) { if ([].forEach) { return function (arr, func) { [].forEach.call(arr, func); }; } else { return function (arr, func) { for (var i = 0; i < arr.length; i++) { func.call(arr, arr[i], i, arr); } }; } }; MessageUtil.remove = function (array, func) { for (var i = 0, len = array.length; i < len; i++) { if (func(array[i])) { return array.splice(i, 1)[0]; } } return null; }; MessageUtil.int64ToTimestamp = function (obj, isDate) { if (obj.low === undefined) { return obj; } var low = obj.low; if (low < 0) { low += 0xffffffff + 1; } low = low.toString(16); var timestamp = parseInt(obj.high.toString(16) + "00000000".replace(new RegExp("0{" + low.length + "}$"), low), 16); if (isDate) { return new Date(timestamp); } return timestamp; }; //消息转换方法 MessageUtil.messageParser = function (entity, onReceived, offlineMsg) { var message = new RongIMLib.Message(), content = entity.content, de, objectName = entity.classname, val, isUseDef = false; try { if (RongIMLib.RongIMClient._memoryStore.depend.isPolling) { val = new RongIMLib.BinaryHelper().readUTF(content.offset ? MessageUtil.ArrayForm(content.buffer).slice(content.offset, content.limit) : content); de = JSON.parse(val); } else { val = new RongIMLib.BinaryHelper().readUTF(content.offset ? MessageUtil.ArrayFormInput(content.buffer).subarray(content.offset, content.limit) : content); de = JSON.parse(val); } } catch (ex) { de = val; isUseDef = true; } var IMLib = RongIMLib; //映射为具体消息对象 if (objectName in typeMapping) { var typeName = typeMapping[objectName]; message.content = new IMLib[typeName](de); message.messageType = typeMapping[objectName]; } else if (objectName in registerMessageTypeMapping) { var typeName = registerMessageTypeMapping[objectName]; var regMsg = new IMLib.RongIMClient.RegisterMessage[typeName](de); if (isUseDef) { message.content = regMsg.decode(de); } else { message.content = regMsg; } message.messageType = registerMessageTypeMapping[objectName]; } else { message.content = new RongIMLib.UnknownMessage({ content: de, objectName: objectName }); message.messageType = "UnknownMessage"; } //根据实体对象设置message对象] var dateTime = MessageUtil.int64ToTimestamp(entity.dataTime); if (dateTime > 0) { message.sentTime = dateTime; } else { message.sentTime = +new Date; } message.senderUserId = entity.fromUserId; message.conversationType = entity.type; if (entity.fromUserId == RongIMLib.Bridge._client.userId) { message.targetId = entity.groupId; } else { message.targetId = (/^[234]$/.test(entity.type || entity.getType()) ? entity.groupId : message.senderUserId); } var selfUserId = RongIMLib.Bridge._client.userId; // 解决多端在线收自己发的消息时, messageDirection 为 2(接收), 导致未读数增加 var isSelfSend = entity.direction == 1 || message.senderUserId === selfUserId; if (isSelfSend) { message.messageDirection = RongIMLib.MessageDirection.SEND; message.senderUserId = RongIMLib.Bridge._client.userId; } else { message.messageDirection = RongIMLib.MessageDirection.RECEIVE; } // 自己给自己发的消息, messageDirection 为 2(接收) var isSelfToSelf = message.senderUserId === selfUserId && message.targetId === selfUserId; if (isSelfToSelf) { message.messageDirection = RongIMLib.MessageDirection.RECEIVE; } message.messageUId = entity.msgId; message.receivedTime = new Date().getTime(); message.messageId = (message.conversationType + "_" + ~~(Math.random() * 0xffffff)); message.objectName = objectName; message.receivedStatus = RongIMLib.ReceivedStatus.READ; if ((entity.status & 2) == 2) { message.receivedStatus = RongIMLib.ReceivedStatus.RETRIEVED; } message.offLineMessage = offlineMsg ? true : false; if (!offlineMsg) { if (RongIMLib.RongIMClient._memoryStore.connectAckTime > message.sentTime) { message.offLineMessage = true; } } return message; }; MessageUtil.detectCMP = function (options) { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function () { if (xhr.readyState == 4) { var status = xhr.status; if (status == 200) { options.success(); } else { options.fail(xhr.status); } } }; var method = options.url; var url = options.url; var method = options.method || 'GET'; xhr.open(method, url); var headers = options.headers; for (var key in headers) { var value = headers[key]; xhr.setRequestHeader(key, value); } var body = JSON.stringify(options.body || {}); xhr.send(body); return xhr; }; //适配SSL // static schemeArrs: Array = [["http", "ws"], ["https", "wss"]]; MessageUtil.sign = { converNum: 1, msgNum: 1, isMsgStart: true, isConvStart: true }; return MessageUtil; })(); RongIMLib.MessageUtil = MessageUtil; /** * 工具类 */ var MessageIdHandler = (function () { function MessageIdHandler() { } MessageIdHandler.init = function () { this.messageId = +(RongIMLib.RongIMClient._storageProvider.getItem(RongIMLib.Navigation.Endpoint.userId + "msgId") || RongIMLib.RongIMClient._storageProvider.setItem(RongIMLib.Navigation.Endpoint.userId + "msgId", 0) || 0); }; MessageIdHandler.messageIdPlus = function (method) { RongIMLib.RongIMClient._memoryStore.depend.isPolling && this.init(); if (this.messageId >= 65535) { this.messageId = 0; } this.messageId++; RongIMLib.RongIMClient._memoryStore.depend.isPolling && RongIMLib.RongIMClient._storageProvider.setItem(RongIMLib.Navigation.Endpoint.userId + "msgId", this.messageId); return this.messageId; }; MessageIdHandler.clearMessageId = function () { this.messageId = 0; RongIMLib.RongIMClient._memoryStore.depend.isPolling && RongIMLib.RongIMClient._storageProvider.setItem(RongIMLib.Navigation.Endpoint.userId + "msgId", this.messageId); }; MessageIdHandler.getMessageId = function () { RongIMLib.RongIMClient._memoryStore.depend.isPolling && this.init(); return this.messageId; }; MessageIdHandler.messageId = 0; return MessageIdHandler; })(); RongIMLib.MessageIdHandler = MessageIdHandler; var ChrmKVCaches = (function () { function ChrmKVCaches() { this.time = 0; this.cache = {}; } ChrmKVCaches.prototype.setTime = function (time) { this.time = time; }; ChrmKVCaches.prototype.getTime = function () { return this.time; }; ChrmKVCaches.prototype.setValue = function (kvContent) { var key = kvContent.key, timestamp = kvContent.timestamp; this.cache[key] = this.cache[key] || {}; this.cache[key] = { value: kvContent.value, userId: kvContent.userId, isDeleted: false, timestamp: timestamp }; }; ChrmKVCaches.prototype.removeValue = function (kvContent) { var key = kvContent.key, timestamp = kvContent.timestamp; this.cache[key] = this.cache[key] || {}; var cache = this.cache[key]; this.cache[key] = RongIMLib.RongUtil.extend(cache, { isDeleted: true, userId: kvContent.userId, timestamp: timestamp }); }; ChrmKVCaches.prototype.getValue = function (key) { this.cache[key] = this.cache[key] || {}; var cache = this.cache[key]; return cache.isDeleted ? null : cache.value; }; ChrmKVCaches.prototype.getAllKV = function () { var kv = {}; RongIMLib.RongUtil.forEach(this.cache, function (item, key) { if (!item.isDeleted) { kv[key] = item.value; } }); return kv; }; ChrmKVCaches.prototype.getSetUserId = function (key) { this.cache[key] = this.cache[key] || {}; return this.cache[key].userId; }; ChrmKVCaches.prototype.isKeyExisted = function (key) { this.cache[key] = this.cache[key] || {}; var cache = this.cache[key]; var hasValue = !RongIMLib.RongUtil.isEmpty(cache.value); return hasValue && !cache.isDeleted; }; ChrmKVCaches.prototype.clear = function () { this.cache = {}; }; return ChrmKVCaches; })(); var chrmKVCaches = {}; var chrmKVProsumerCaches = {}; var getKVCache = function (chrmId) { var chrmKVCache = chrmKVCaches[chrmId]; if (!chrmKVCache) { chrmKVCache = chrmKVCaches[chrmId] = new ChrmKVCaches(); } return chrmKVCache; }; var getKVProsumer = function (chrmId) { var kvProsumer = chrmKVProsumerCaches[chrmId]; if (!kvProsumer) { kvProsumer = chrmKVProsumerCaches[chrmId] = new RongIMLib.RongUtil.Prosumer(); } return kvProsumer; }; var ChrmKVHandler = (function () { function ChrmKVHandler() { } ChrmKVHandler.pull = function (chrmId, time) { var prosumer = getKVProsumer(chrmId); var event = RongIMLib.RongIMClient._dataAccessProvider.pullChatroomEntry; prosumer.produce({ event: event, chrmId: chrmId, time: time }); prosumer.consume(function (params, next) { var event = params.event, chrmId = params.chrmId, time = params.time; var kvCache = getKVCache(chrmId); var currentTime = kvCache.getTime(); var isKVNeedUpdated = currentTime < time; if (isKVNeedUpdated) { event(chrmId, currentTime, { onSuccess: function (result) { ChrmKVHandler.setEntries(chrmId, result); next(); }, onError: next }); } else { next(); } }); }; ChrmKVHandler.setEntries = function (chrmId, entity) { var entries = entity.entries, isFullUpdate = entity.bFullUpdate, syncTime = entity.syncTime; var event = isFullUpdate ? ChrmKVHandler.setFullEntries : ChrmKVHandler.setIncreEntries; var kvCache = getKVCache(chrmId); syncTime = MessageUtil.int64ToTimestamp(syncTime); if (RongIMLib.RongUtil.isArray(entries)) { RongIMLib.RongUtil.forEach(entries, function (item) { var setTime = item.timestamp; if (!RongIMLib.RongUtil.isNumber(setTime)) { item.timestamp = MessageUtil.int64ToTimestamp(setTime); } }); } kvCache.setTime(syncTime); // 更新拉取时间 event(chrmId, entries); // 更新 kv 值 }; ChrmKVHandler.setEntry = function (chrmId, chatroomEntry, status, userId) { var kvCache = getKVCache(chrmId); var timestamp = chatroomEntry.timestamp || +new Date(); var isDelete = RongInnerTools.getChrmEntityByStatus(status).isDelete; var eventName = isDelete ? 'removeValue' : 'setValue'; kvCache[eventName]({ key: chatroomEntry.key, value: chatroomEntry.value, userId: userId, timestamp: timestamp }); }; ChrmKVHandler.setFullEntries = function (chrmId, entries) { var kvCache = getKVCache(chrmId); kvCache.clear(); RongIMLib.RongUtil.forEach(entries, function (entity) { entity.timestamp = MessageUtil.int64ToTimestamp(entity.timestamp); kvCache.setValue({ key: entity.key, value: entity.value, userId: entity.uid, timestamp: entity.timestamp }); }); }; ChrmKVHandler.setIncreEntries = function (chrmId, entries) { var kvCache = getKVCache(chrmId); var currentUserId = RongIMLib.RongIMClient.getInstance().getCurrentUserId(); var optEvent = function (entity, isOverwrite, eventName) { var key = entity.key, value = entity.value; var isLatestedKeySetBySelf = kvCache.getSetUserId(key) === currentUserId; var isKeyNotExist = !kvCache.isKeyExisted(key); /* 1. 需覆盖时, 不管 key 是否已存在, 都直接设置 2. 不覆盖时, 必须最后一次 key 为自己设置的或此 key 还未设置过, 才能继续 */ if (isOverwrite || isLatestedKeySetBySelf || isKeyNotExist) { kvCache[eventName]({ key: key, value: value, userId: entity.uid, timestamp: entity.timestamp }); } }; RongIMLib.RongUtil.forEach(entries, function (entity) { var entityContent = RongInnerTools.getChrmEntityByStatus(entity.status); var eventName = entityContent.isDelete ? 'removeValue' : 'setValue'; optEvent(entity, entityContent.isOverwrite, eventName); }); }; ChrmKVHandler.getEntityValue = function (chrmId, key) { var kvCache = getKVCache(chrmId); return kvCache.getValue(key); }; ChrmKVHandler.getAllEntityValue = function (chrmId) { var kvCache = getKVCache(chrmId); return kvCache.getAllKV(); }; ChrmKVHandler.isKeyValid = function (key) { return /^[A-Za-z0-9_=+-]+$/.test(key); }; return ChrmKVHandler; })(); RongIMLib.ChrmKVHandler = ChrmKVHandler; var AutoDeleteCode = 0x0001; var OverwriteCode = 0x0002; var DeleteOperationCode = 0x0004; var RongInnerTools = (function () { function RongInnerTools() { } RongInnerTools.convertUserStatus = function (entity) { entity = RongIMLib.RongUtil.rename(entity, { subUserId: 'userId' }); var status = JSON.parse(entity.status); var us = status.us; if (!us) { return entity; } entity.status = RongIMLib.RongUtil.rename(us, { o: 'online', 'p': 'platform', s: 'status' }); return entity; }; RongInnerTools.getChrmEntityStatus = function (entity, chatroomOpt) { var status = 0; // 是否自动清理 if (entity.isAutoDelete) { status = status | AutoDeleteCode; } // 是否覆盖 if (entity.isOverwrite) { status = status | OverwriteCode; } // 操作类型 switch (chatroomOpt) { case RongIMLib.ChatroomEntityOpt.DELETE: status = status | DeleteOperationCode; break; default: break; } return status; }; RongInnerTools.getChrmEntityByStatus = function (status) { var isDelete = !!(status & DeleteOperationCode); var entityOpt = isDelete ? RongIMLib.ChatroomEntityOpt.DELETE : RongIMLib.ChatroomEntityOpt.UPDATE; return { isAutoDelete: !!(status & AutoDeleteCode), isOverwrite: !!(status & OverwriteCode), entityOpt: entityOpt, isDelete: isDelete }; }; return RongInnerTools; })(); RongIMLib.RongInnerTools = RongInnerTools; var UnreadCountHandler = (function () { function UnreadCountHandler() { } UnreadCountHandler.getKey = function (type, targetId) { var selfId = RongIMLib.RongIMClient.getInstance().getCurrentUserId(); return RongIMLib.RongUtil.tplEngine(UnreadCountHandler.KeyTemp, { selfId: selfId, type: type, targetId: targetId }); }; UnreadCountHandler.getDetailByKey = function (key) { var detail = { count: 0, sentTime: 0 }; var value = RongIMLib.RongIMClient._storageProvider.getItem(key); if (!value) { return detail; } value += ''; var unreadItems = value.split('_'); var hasUnderline = unreadItems.length > 1; detail.count = Number(unreadItems[0]); if (hasUnderline) { detail.sentTime = Number(unreadItems[1]); } return detail; }; UnreadCountHandler.getDetail = function (type, targetId) { var key = UnreadCountHandler.getKey(type, targetId); var detail = UnreadCountHandler.getDetailByKey(key); return detail; }; UnreadCountHandler.set = function (type, id, count, sentTime) { var key = UnreadCountHandler.getKey(type, id); var value = sentTime ? RongIMLib.RongUtil.tplEngine(UnreadCountHandler.ValueTemp, { count: count, sentTime: sentTime }) : count; RongIMLib.RongIMClient._storageProvider.setItem(key, value); return count; }; UnreadCountHandler.add = function (type, id, plusCount, sentTime) { var detail = UnreadCountHandler.getDetail(type, id), count = detail.count, oldSentTime = detail.sentTime; if (sentTime && sentTime > oldSentTime) { count = count + plusCount; UnreadCountHandler.set(type, id, count, sentTime); } return count; }; UnreadCountHandler.get = function (type, id) { var detail = UnreadCountHandler.getDetail(type, id); return detail.count; }; UnreadCountHandler.getAll = function (types) { var total = 0; var selfId = RongIMLib.RongIMClient.getInstance().getCurrentUserId(); var setTotal = function (keyList) { RongIMLib.RongUtil.forEach(keyList, function (key) { var detail = UnreadCountHandler.getDetailByKey(key); total += detail.count; }); }; if (types) { RongIMLib.RongUtil.forEach(types, function (type) { var key = UnreadCountHandler.getKey(type, ''); var unreadKeys = RongIMLib.RongIMClient._storageProvider.getItemKeyList(key); setTotal(unreadKeys); }); } else { var key = UnreadCountHandler.getKey('', ''); var unreadKeys = RongIMLib.RongIMClient._storageProvider.getItemKeyList(key); setTotal(unreadKeys); } return total; }; UnreadCountHandler.remove = function (type, targetId) { var key = UnreadCountHandler.getKey(type, targetId); RongIMLib.RongIMClient._storageProvider.removeItem(key); }; UnreadCountHandler.clear = function () { var key = UnreadCountHandler.getKey('', ''); var keyList = RongIMLib.RongIMClient._storageProvider.getItemKeyList(key); RongIMLib.RongUtil.forEach(keyList, function (key) { RongIMLib.RongIMClient._storageProvider.removeItem(key); }); }; UnreadCountHandler.KeyTemp = 'cu{selfId}{type}{targetId}'; UnreadCountHandler.ValueTemp = '{count}_{sentTime}'; return UnreadCountHandler; })(); RongIMLib.UnreadCountHandler = UnreadCountHandler; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var MessageContent = (function () { function MessageContent(data) { throw new Error("This method is abstract, you must implement this method in inherited class."); } MessageContent.obtain = function () { throw new Error("This method is abstract, you must implement this method in inherited class."); }; return MessageContent; })(); RongIMLib.MessageContent = MessageContent; var NotificationMessage = (function (_super) { __extends(NotificationMessage, _super); function NotificationMessage() { _super.apply(this, arguments); } return NotificationMessage; })(MessageContent); RongIMLib.NotificationMessage = NotificationMessage; var StatusMessage = (function (_super) { __extends(StatusMessage, _super); function StatusMessage() { _super.apply(this, arguments); } return StatusMessage; })(MessageContent); RongIMLib.StatusMessage = StatusMessage; var ModelUtil = (function () { function ModelUtil() { } ModelUtil.modelClone = function (object) { var obj = {}; for (var item in object) { if (item != "messageName" && "encode" != item) { obj[item] = object[item]; } } return obj; }; ModelUtil.modleCreate = function (fields, msgType) { // if (fields.length < 1) { // throw new Error("Array is empty -> registerMessageType.modleCreate"); // } var Object = function (message) { var me = this; for (var index in fields) { me[fields[index]] = message[fields[index]]; } Object.prototype.messageName = msgType; Object.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; }; return Object; }; return ModelUtil; })(); RongIMLib.ModelUtil = ModelUtil; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var CustomerStatusMessage = (function () { function CustomerStatusMessage(message) { this.messageName = "CustomerStatusMessage"; this.status = message.status; } CustomerStatusMessage.obtain = function () { return null; }; CustomerStatusMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return CustomerStatusMessage; })(); RongIMLib.CustomerStatusMessage = CustomerStatusMessage; /** * 客服转换响应消息的类型名 */ var ChangeModeResponseMessage = (function () { function ChangeModeResponseMessage(message) { this.messageName = "ChangeModeResponseMessage"; this.code = message.code; this.data = message.data; this.msg = message.msg; } ChangeModeResponseMessage.obtain = function () { return null; }; ChangeModeResponseMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ChangeModeResponseMessage; })(); RongIMLib.ChangeModeResponseMessage = ChangeModeResponseMessage; /** * 客服转换消息的类型名 * 此消息不计入未读消息数 */ var ChangeModeMessage = (function () { function ChangeModeMessage(message) { this.messageName = "ChangeModeMessage"; this.uid = message.uid; this.sid = message.sid; this.pid = message.pid; } ChangeModeMessage.obtain = function () { return null; }; ChangeModeMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ChangeModeMessage; })(); RongIMLib.ChangeModeMessage = ChangeModeMessage; var CustomerStatusUpdateMessage = (function () { function CustomerStatusUpdateMessage(message) { this.messageName = "CustomerStatusUpdateMessage"; this.serviceStatus = message.serviceStatus; this.sid = message.sid; } CustomerStatusUpdateMessage.obtain = function () { return null; }; CustomerStatusUpdateMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return CustomerStatusUpdateMessage; })(); RongIMLib.CustomerStatusUpdateMessage = CustomerStatusUpdateMessage; var HandShakeMessage = (function () { function HandShakeMessage(message) { this.messageName = "HandShakeMessage"; if (message) { this.requestInfo = message.requestInfo; this.userInfo = message.userInfo; } } HandShakeMessage.obtain = function () { return null; }; HandShakeMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return HandShakeMessage; })(); RongIMLib.HandShakeMessage = HandShakeMessage; var CustomerContact = (function () { function CustomerContact(message) { this.messageName = "CustomerContact"; this.page = message.page; this.nickName = message.nickName; this.routingInfo = message.routingInfo; this.info = message.info; this.requestInfo = message.requestInfo; } CustomerContact.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return CustomerContact; })(); RongIMLib.CustomerContact = CustomerContact; var EvaluateMessage = (function () { function EvaluateMessage(message) { this.messageName = "EvaluateMessage"; this.uid = message.uid; this.sid = message.sid; this.pid = message.pid; this.source = message.source; this.suggest = message.suggest; this.isresolve = message.isresolve; this.type = message.type; } EvaluateMessage.obtain = function () { return null; }; EvaluateMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return EvaluateMessage; })(); RongIMLib.EvaluateMessage = EvaluateMessage; /** * 客服握手响应消息的类型名 */ var HandShakeResponseMessage = (function () { function HandShakeResponseMessage(message) { this.messageName = "HandShakeResponseMessage"; this.msg = message.msg; this.status = message.status; this.data = message.data; } HandShakeResponseMessage.obtain = function () { return null; }; HandShakeResponseMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return HandShakeResponseMessage; })(); RongIMLib.HandShakeResponseMessage = HandShakeResponseMessage; var SuspendMessage = (function () { function SuspendMessage(message) { this.messageName = "SuspendMessage"; this.uid = message.uid; this.sid = message.sid; this.pid = message.pid; } SuspendMessage.obtain = function () { return null; }; SuspendMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return SuspendMessage; })(); RongIMLib.SuspendMessage = SuspendMessage; var TerminateMessage = (function () { function TerminateMessage(message) { this.messageName = "TerminateMessage"; this.code = message.code; this.msg = message.msg; this.sid = message.sid; } TerminateMessage.obtain = function () { return null; }; TerminateMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return TerminateMessage; })(); RongIMLib.TerminateMessage = TerminateMessage; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var IsTypingStatusMessage = (function () { function IsTypingStatusMessage(data) { this.messageName = "IsTypingStatusMessage"; var msg = data; } IsTypingStatusMessage.prototype.encode = function () { return undefined; }; IsTypingStatusMessage.prototype.getMessage = function () { return null; }; return IsTypingStatusMessage; })(); RongIMLib.IsTypingStatusMessage = IsTypingStatusMessage; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var InformationNotificationMessage = (function () { function InformationNotificationMessage(message) { this.messageName = "InformationNotificationMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> InformationNotificationMessage."); } this.message = message.message; this.extra = message.extra; if (message.user) { this.user = message.user; } } InformationNotificationMessage.obtain = function (message) { return new InformationNotificationMessage({ message: message, extra: "" }); }; InformationNotificationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return InformationNotificationMessage; })(); RongIMLib.InformationNotificationMessage = InformationNotificationMessage; var CommandMessage = (function () { function CommandMessage(message) { this.messageName = "CommandMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> CommandMessage."); } try { if (Object.prototype.toString.call(message.data) == "[object String]") { this.data = JSON.parse(message.data); } else { this.data = message.data; } } catch (e) { this.data = message.data; } this.name = message.name; this.extra = message.extra; } CommandMessage.obtain = function (data) { return new CommandMessage({ data: data, extra: "" }); }; CommandMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return CommandMessage; })(); RongIMLib.CommandMessage = CommandMessage; var ContactNotificationMessage = (function () { function ContactNotificationMessage(message) { this.messageName = "ContactNotificationMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> ContactNotificationMessage."); } this.operation = message.operation; this.targetUserId = message.targetUserId; this.message = message.message; this.extra = message.extra; this.sourceUserId = message.sourceUserId; if (message.user) { this.user = message.user; } } ContactNotificationMessage.obtain = function (operation, sourceUserId, targetUserId, message) { return new InformationNotificationMessage({ operation: operation, sourceUserId: sourceUserId, targetUserId: targetUserId, message: message }); }; ContactNotificationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; ContactNotificationMessage.CONTACT_OPERATION_ACCEPT_RESPONSE = "ContactOperationAcceptResponse"; ContactNotificationMessage.CONTACT_OPERATION_REJECT_RESPONSE = "ContactOperationRejectResponse"; ContactNotificationMessage.CONTACT_OPERATION_REQUEST = "ContactOperationRequest"; return ContactNotificationMessage; })(); RongIMLib.ContactNotificationMessage = ContactNotificationMessage; var ProfileNotificationMessage = (function () { function ProfileNotificationMessage(message) { this.messageName = "ProfileNotificationMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> ProfileNotificationMessage."); } this.operation = message.operation; try { if (Object.prototype.toString.call(message.data) == "[object String]") { this.data = JSON.parse(message.data); } else { this.data = message.data; } } catch (e) { this.data = message.data; } this.extra = message.extra; if (message.user) { this.user = message.user; } } ProfileNotificationMessage.obtain = function (operation, data) { return new ProfileNotificationMessage({ operation: operation, data: data }); }; ProfileNotificationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ProfileNotificationMessage; })(); RongIMLib.ProfileNotificationMessage = ProfileNotificationMessage; var CommandNotificationMessage = (function () { function CommandNotificationMessage(message) { this.messageName = "CommandNotificationMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> ProfileNotificationMessage."); } try { if (Object.prototype.toString.call(message.data) == "[object String]") { this.data = JSON.parse(message.data); } else { this.data = message.data; } } catch (e) { this.data = message.data; } this.name = message.name; this.extra = message.extra; if (message.user) { this.user = message.user; } } CommandNotificationMessage.obtain = function (name, data) { return new CommandNotificationMessage({ name: name, data: data, extra: "" }); }; CommandNotificationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return CommandNotificationMessage; })(); RongIMLib.CommandNotificationMessage = CommandNotificationMessage; var DiscussionNotificationMessage = (function () { function DiscussionNotificationMessage(message) { this.messageName = "DiscussionNotificationMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> DiscussionNotificationMessage."); } this.extra = message.extra; this.extension = message.extension; this.type = message.type; this.isHasReceived = message.isHasReceived; this.operation = message.operation; this.user = message.user; if (message.user) { this.user = message.user; } } DiscussionNotificationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return DiscussionNotificationMessage; })(); RongIMLib.DiscussionNotificationMessage = DiscussionNotificationMessage; var GroupNotificationMessage = (function () { function GroupNotificationMessage(msg) { this.messageName = "GroupNotificationMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> GroupNotificationMessage."); } msg.operatorUserId && (this.operatorUserId = msg.operatorUserId); msg.operation && (this.operation = msg.operation); msg.data && (this.data = msg.data); msg.message && (this.message = msg.message); msg.extra && (this.extra = msg.extra); } GroupNotificationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return GroupNotificationMessage; })(); RongIMLib.GroupNotificationMessage = GroupNotificationMessage; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var TextMessage = (function () { function TextMessage(message) { this.messageName = "TextMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> TextMessage."); } this.content = message.content; this.extra = message.extra; if (message.user) { this.user = message.user; } if (message.mentionedInfo) { this.mentionedInfo = message.mentionedInfo; } } TextMessage.obtain = function (text) { return new TextMessage({ extra: "", content: text }); }; TextMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return TextMessage; })(); RongIMLib.TextMessage = TextMessage; var TypingStatusMessage = (function () { function TypingStatusMessage(message) { this.messageName = "TypingStatusMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> TypingStatusMessage."); } this.typingContentType = message.typingContentType; this.data = message.data; } TypingStatusMessage.obtain = function (typingContentType, data) { return new TypingStatusMessage({ typingContentType: typingContentType, data: data }); }; TypingStatusMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return TypingStatusMessage; })(); RongIMLib.TypingStatusMessage = TypingStatusMessage; var ReadReceiptMessage = (function () { function ReadReceiptMessage(message) { this.messageName = "ReadReceiptMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> ReadReceiptMessage."); } this.lastMessageSendTime = message.lastMessageSendTime; this.messageUId = message.messageUId; this.type = message.type; } ReadReceiptMessage.obtain = function (messageUId, lastMessageSendTime, type) { return new ReadReceiptMessage({ messageUId: messageUId, lastMessageSendTime: lastMessageSendTime, type: type }); }; ReadReceiptMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ReadReceiptMessage; })(); RongIMLib.ReadReceiptMessage = ReadReceiptMessage; var VoiceMessage = (function () { function VoiceMessage(message) { this.messageName = "VoiceMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> VoiceMessage."); } this.content = message.content; this.duration = message.duration; this.extra = message.extra; if (message.user) { this.user = message.user; } if (message.mentionedInfo) { this.mentionedInfo = message.mentionedInfo; } } VoiceMessage.obtain = function (base64Content, duration) { return new VoiceMessage({ content: base64Content, duration: duration, extra: "" }); }; VoiceMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return VoiceMessage; })(); RongIMLib.VoiceMessage = VoiceMessage; var RecallCommandMessage = (function () { function RecallCommandMessage(message) { this.messageName = "RecallCommandMessage"; this.messageUId = message.messageUId; this.conversationType = message.conversationType; this.targetId = message.targetId; this.sentTime = message.sentTime; message.extra && (this.extra = message.extra); message.user && (this.user = message.user); } RecallCommandMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return RecallCommandMessage; })(); RongIMLib.RecallCommandMessage = RecallCommandMessage; var ImageMessage = (function () { function ImageMessage(message) { this.messageName = "ImageMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> ImageMessage."); } this.content = message.content; this.imageUri = message.imageUri; message.extra && (this.extra = message.extra); message.user && (this.user = message.user); if (message.mentionedInfo) { this.mentionedInfo = message.mentionedInfo; } } ImageMessage.obtain = function (content, imageUri) { return new ImageMessage({ content: content, imageUri: imageUri, extra: "" }); }; ImageMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ImageMessage; })(); RongIMLib.ImageMessage = ImageMessage; var LocationMessage = (function () { function LocationMessage(message) { this.messageName = "LocationMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> LocationMessage."); } this.latitude = message.latitude; this.longitude = message.longitude; this.poi = message.poi; this.content = message.content; this.extra = message.extra; if (message.user) { this.user = message.user; } if (message.mentionedInfo) { this.mentionedInfo = message.mentionedInfo; } } LocationMessage.obtain = function (latitude, longitude, poi, content) { return new LocationMessage({ latitude: latitude, longitude: longitude, poi: poi, content: content, extra: "" }); }; LocationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return LocationMessage; })(); RongIMLib.LocationMessage = LocationMessage; var RichContentMessage = (function () { function RichContentMessage(message) { this.messageName = "RichContentMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> RichContentMessage."); } this.title = message.title; this.content = message.content; this.imageUri = message.imageUri; this.extra = message.extra; this.url = message.url; if (message.user) { this.user = message.user; } } RichContentMessage.obtain = function (title, content, imageUri, url) { return new RichContentMessage({ title: title, content: content, imageUri: imageUri, url: url, extra: "" }); }; RichContentMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return RichContentMessage; })(); RongIMLib.RichContentMessage = RichContentMessage; var JrmfRedPacketMessage = (function () { function JrmfRedPacketMessage(message) { this.messageName = 'JrmfRedPacketMessage'; message && (this.message = message); } JrmfRedPacketMessage.prototype.encode = function () { return ""; }; return JrmfRedPacketMessage; })(); RongIMLib.JrmfRedPacketMessage = JrmfRedPacketMessage; var JrmfRedPacketOpenedMessage = (function () { function JrmfRedPacketOpenedMessage(message) { this.messageName = 'JrmfRedPacketOpenedMessage'; message && (this.message = message); } JrmfRedPacketOpenedMessage.prototype.encode = function () { return ""; }; return JrmfRedPacketOpenedMessage; })(); RongIMLib.JrmfRedPacketOpenedMessage = JrmfRedPacketOpenedMessage; var UnknownMessage = (function () { function UnknownMessage(message) { this.messageName = "UnknownMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> UnknownMessage."); } this.message = message; } UnknownMessage.prototype.encode = function () { return ""; }; return UnknownMessage; })(); RongIMLib.UnknownMessage = UnknownMessage; var PublicServiceCommandMessage = (function () { function PublicServiceCommandMessage(message) { this.messageName = "PublicServiceCommandMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> PublicServiceCommandMessage."); } this.content = message.content; this.extra = message.extra; this.menuItem = message.menuItem; if (message.user) { this.user = message.user; } if (message.mentionedInfo) { this.mentionedInfo = message.mentionedInfo; } } PublicServiceCommandMessage.obtain = function (item) { return new PublicServiceCommandMessage({ content: "", command: "", menuItem: item, extra: "" }); }; PublicServiceCommandMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return PublicServiceCommandMessage; })(); RongIMLib.PublicServiceCommandMessage = PublicServiceCommandMessage; var PublicServiceMultiRichContentMessage = (function () { function PublicServiceMultiRichContentMessage(messages) { this.messageName = "PublicServiceMultiRichContentMessage"; this.richContentMessages = messages; } PublicServiceMultiRichContentMessage.prototype.encode = function () { return null; }; return PublicServiceMultiRichContentMessage; })(); RongIMLib.PublicServiceMultiRichContentMessage = PublicServiceMultiRichContentMessage; var SyncReadStatusMessage = (function () { function SyncReadStatusMessage(message) { this.messageName = "SyncReadStatusMessage"; message.lastMessageSendTime && (this.lastMessageSendTime = message.lastMessageSendTime); } SyncReadStatusMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return SyncReadStatusMessage; })(); RongIMLib.SyncReadStatusMessage = SyncReadStatusMessage; var ReadReceiptRequestMessage = (function () { function ReadReceiptRequestMessage(message) { this.messageName = "ReadReceiptRequestMessage"; message.messageUId && (this.messageUId = message.messageUId); } ReadReceiptRequestMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ReadReceiptRequestMessage; })(); RongIMLib.ReadReceiptRequestMessage = ReadReceiptRequestMessage; var ReadReceiptResponseMessage = (function () { function ReadReceiptResponseMessage(message) { this.messageName = "ReadReceiptResponseMessage"; message.receiptMessageDic && (this.receiptMessageDic = message.receiptMessageDic); } ReadReceiptResponseMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ReadReceiptResponseMessage; })(); RongIMLib.ReadReceiptResponseMessage = ReadReceiptResponseMessage; var PublicServiceRichContentMessage = (function () { function PublicServiceRichContentMessage(message) { this.messageName = "PublicServiceRichContentMessage"; this.richContentMessage = message; } PublicServiceRichContentMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return PublicServiceRichContentMessage; })(); RongIMLib.PublicServiceRichContentMessage = PublicServiceRichContentMessage; var FileMessage = (function () { function FileMessage(message) { this.messageName = "FileMessage"; message.name && (this.name = message.name); message.size && (this.size = message.size); message.type && (this.type = message.type); message.fileUrl && (this.fileUrl = message.fileUrl); message.extra && (this.extra = message.extra); message.user && (this.user = message.user); } FileMessage.obtain = function (msg) { return new FileMessage({ name: msg.name, size: msg.size, type: msg.type, fileUrl: msg.fileUrl }); }; FileMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return FileMessage; })(); RongIMLib.FileMessage = FileMessage; var HQVoiceMessage = (function () { function HQVoiceMessage(message) { this.messageName = "HQVoiceMessage"; this.type = message.type || 'aac'; message.localPath && (this.localPath = message.localPath); message.remoteUrl && (this.remoteUrl = message.remoteUrl); message.duration && (this.duration = message.duration); message.extra && (this.extra = message.extra); message.user && (this.user = message.user); } HQVoiceMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return HQVoiceMessage; })(); RongIMLib.HQVoiceMessage = HQVoiceMessage; var AcceptMessage = (function () { function AcceptMessage(message) { this.messageName = "AcceptMessage"; this.mediaId = message.mediaId; this.callId = message.callId; this.mediaType = message.mediaType; this.mode = message.mode; this.subInfo = message.subInfo; } AcceptMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return AcceptMessage; })(); RongIMLib.AcceptMessage = AcceptMessage; var RingingMessage = (function () { function RingingMessage(message) { this.messageName = "RingingMessage"; this.callId = message.callId; } RingingMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return RingingMessage; })(); RongIMLib.RingingMessage = RingingMessage; var SummaryMessage = (function () { function SummaryMessage(message) { this.messageName = "SummaryMessage"; this.caller = message.caller; this.inviter = message.inviter; this.mediaType = message.mediaType; this.memberIdList = message.memberIdList; this.startTime = message.startTime; this.connectedTime = message.connectedTime; this.duration = message.duration; this.status = message.status; } SummaryMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return SummaryMessage; })(); RongIMLib.SummaryMessage = SummaryMessage; var HungupMessage = (function () { function HungupMessage(message) { this.messageName = "HungupMessage"; this.callId = message.callId; this.reason = message.reason; this.mode = message.mode; this.subInfo = message.subInfo; } HungupMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return HungupMessage; })(); RongIMLib.HungupMessage = HungupMessage; var InviteMessage = (function () { function InviteMessage(message) { this.messageName = "InviteMessage"; this.mediaId = message.mediaId; this.callId = message.callId; this.engineType = message.engineType; this.channelInfo = message.channelInfo; this.mediaType = message.mediaType; this.extra = message.extra; this.inviteUserIds = message.inviteUserIds; this.observerUserIds = message.observerUserIds; this.mode = message.mode; this.subInfo = message.subInfo; } InviteMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return InviteMessage; })(); RongIMLib.InviteMessage = InviteMessage; var MediaModifyMessage = (function () { function MediaModifyMessage(message) { this.messageName = "MediaModifyMessage"; this.callId = message.callId; this.mediaType = message.mediaType; this.mode = message.mode; this.subInfo = message.subInfo; } MediaModifyMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return MediaModifyMessage; })(); RongIMLib.MediaModifyMessage = MediaModifyMessage; var MemberModifyMessage = (function () { function MemberModifyMessage(message) { this.messageName = "MemberModifyMessage"; this.modifyMemType = message.modifyMemType; this.callId = message.callId; this.caller = message.caller; this.engineType = message.engineType; this.channelInfo = message.channelInfo; this.mediaType = message.mediaType; this.extra = message.extra; this.inviteUserIds = message.inviteUserIds; this.existedMemberStatusList = message.existedMemberStatusList; this.existedUserPofiles = message.existedUserPofiles; this.observerUserIds = message.observerUserIds; this.mode = message.mode; this.subInfo = message.subInfo; } MemberModifyMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return MemberModifyMessage; })(); RongIMLib.MemberModifyMessage = MemberModifyMessage; var RCCombineMessage = (function () { function RCCombineMessage(message) { this.messageName = "RCCombineMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> RCCombineMessage."); } this.nameList = message.nameList; this.remoteUrl = message.remoteUrl; if (message.user) { this.user = message.user; } this.summaryList = message.summaryList; } RCCombineMessage.obtain = function (remoteUrl, nameList, summaryList) { return new RCCombineMessage({ extra: "", content: remoteUrl, nameList: nameList, summaryList: summaryList }); }; RCCombineMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return RCCombineMessage; })(); RongIMLib.RCCombineMessage = RCCombineMessage; var ChrmKVNotificationMessage = (function () { function ChrmKVNotificationMessage(message) { this.messageName = "ChrmKVNotificationMessage"; message.key && (this.key = message.key); message.value && (this.value = message.value); message.type && (this.type = message.type); message.extra && (this.extra = message.extra); message.user && (this.user = message.user); } ChrmKVNotificationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ChrmKVNotificationMessage; })(); RongIMLib.ChrmKVNotificationMessage = ChrmKVNotificationMessage; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var ChannelInfo = (function () { function ChannelInfo(Id, Key) { this.Id = Id; this.Key = Key; } return ChannelInfo; })(); RongIMLib.ChannelInfo = ChannelInfo; var UserStatus = (function () { function UserStatus(platform, online, status) { this.platform = platform; this.online = online; this.status = status; } return UserStatus; })(); RongIMLib.UserStatus = UserStatus; var MentionedInfo = (function () { function MentionedInfo(type, userIdList, mentionedContent) { } return MentionedInfo; })(); RongIMLib.MentionedInfo = MentionedInfo; var DeleteMessage = (function () { function DeleteMessage(msgId, msgDataTime, direct) { this.msgId = msgId; this.msgDataTime = msgDataTime; this.direct = direct; } return DeleteMessage; })(); RongIMLib.DeleteMessage = DeleteMessage; var CustomServiceConfig = (function () { function CustomServiceConfig(isBlack, companyName, companyUrl) { } return CustomServiceConfig; })(); RongIMLib.CustomServiceConfig = CustomServiceConfig; var CustomServiceSession = (function () { function CustomServiceSession(uid, cid, pid, isQuited, type, adminHelloWord, adminOfflineWord) { } return CustomServiceSession; })(); RongIMLib.CustomServiceSession = CustomServiceSession; var Conversation = (function () { function Conversation(conversationTitle, conversationType, draft, isTop, latestMessage, latestMessageId, notificationStatus, objectName, receivedStatus, receivedTime, senderUserId, senderUserName, sentStatus, sentTime, targetId, unreadMessageCount, senderPortraitUri, isHidden, mentionedMsg, hasUnreadMention, _readTime) { this.conversationTitle = conversationTitle; this.conversationType = conversationType; this.draft = draft; this.isTop = isTop; this.latestMessage = latestMessage; this.latestMessageId = latestMessageId; this.notificationStatus = notificationStatus; this.objectName = objectName; this.receivedStatus = receivedStatus; this.receivedTime = receivedTime; this.senderUserId = senderUserId; this.senderUserName = senderUserName; this.sentStatus = sentStatus; this.sentTime = sentTime; this.targetId = targetId; this.unreadMessageCount = unreadMessageCount; this.senderPortraitUri = senderPortraitUri; this.isHidden = isHidden; this.mentionedMsg = mentionedMsg; this.hasUnreadMention = hasUnreadMention; this._readTime = _readTime; } Conversation.prototype.setTop = function () { RongIMLib.RongIMClient._dataAccessProvider.addConversation(this, { onSuccess: function (data) { } }); }; return Conversation; })(); RongIMLib.Conversation = Conversation; var Discussion = (function () { function Discussion(creatorId, id, memberIdList, name, isOpen) { this.creatorId = creatorId; this.id = id; this.memberIdList = memberIdList; this.name = name; this.isOpen = isOpen; } return Discussion; })(); RongIMLib.Discussion = Discussion; var Group = (function () { function Group(id, name, portraitUri) { this.id = id; this.name = name; this.portraitUri = portraitUri; } return Group; })(); RongIMLib.Group = Group; var Message = (function () { function Message(content, conversationType, extra, objectName, messageDirection, messageId, receivedStatus, receivedTime, senderUserId, sentStatus, sentTime, targetId, messageType, messageUId, isLocalMessage, offLineMessage, receiptResponse) { this.content = content; this.conversationType = conversationType; this.extra = extra; this.objectName = objectName; this.messageDirection = messageDirection; this.messageId = messageId; this.receivedStatus = receivedStatus; this.receivedTime = receivedTime; this.senderUserId = senderUserId; this.sentStatus = sentStatus; this.sentTime = sentTime; this.targetId = targetId; this.messageType = messageType; this.messageUId = messageUId; this.isLocalMessage = isLocalMessage; this.offLineMessage = offLineMessage; this.receiptResponse = receiptResponse; } return Message; })(); RongIMLib.Message = Message; var MessageTag = (function () { function MessageTag(isCounted, isPersited) { this.isCounted = isCounted; this.isPersited = isPersited; } MessageTag.prototype.getMessageTag = function () { if (this.isCounted && this.isPersited) { return 3; } else if (this.isCounted) { return 2; } else if (this.isPersited) { return 1; } else if (!this.isCounted && !this.isPersited) { return 0; } }; MessageTag.getTagByStatus = function (status) { var statusMap = { 3: { isCounted: true, isPersited: true }, 2: { isCounted: true, isPersited: false }, 1: { isCounted: true, isPersited: true }, 0: { isCounted: true, isPersited: true } }; return statusMap[status] || statusMap[3]; }; return MessageTag; })(); RongIMLib.MessageTag = MessageTag; var PublicServiceMenuItem = (function () { function PublicServiceMenuItem(id, name, type, sunMenuItems, url) { this.id = id; this.name = name; this.type = type; this.sunMenuItems = sunMenuItems; this.url = url; } return PublicServiceMenuItem; })(); RongIMLib.PublicServiceMenuItem = PublicServiceMenuItem; // TODO: TBD var PublicServiceProfile = (function () { function PublicServiceProfile(conversationType, introduction, menu, name, portraitUri, publicServiceId, hasFollowed, isGlobal) { this.conversationType = conversationType; this.introduction = introduction; this.menu = menu; this.name = name; this.portraitUri = portraitUri; this.publicServiceId = publicServiceId; this.hasFollowed = hasFollowed; this.isGlobal = isGlobal; } return PublicServiceProfile; })(); RongIMLib.PublicServiceProfile = PublicServiceProfile; var UserInfo = (function () { function UserInfo(id, name, portraitUri) { this.id = id; this.name = name; this.portraitUri = portraitUri; } return UserInfo; })(); RongIMLib.UserInfo = UserInfo; var User = (function () { function User(id, token) { this.id = id; this.token = token; } return User; })(); RongIMLib.User = User; var Room = (function () { function Room(id, user, mode, broadcastType, type) { this.id = id; this.user = user; this.mode = mode; this.broadcastType = broadcastType; this.type = type; } return Room; })(); RongIMLib.Room = Room; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var ServerDataProvider = (function () { function ServerDataProvider() { this.userStatusListener = null; this.Conversation = { watcher: new RongIMLib.Observer(), watch: function (_watcher) { this.watcher.add(_watcher); var conversationList = RongIMLib.RongIMClient._memoryStore.conversationList; this.watcher.emit(conversationList); }, unwatch: function (_watcher) { this.watcher.remove(_watcher); }, _notify: function (conversationList) { this.watcher.emit(conversationList); } }; } ServerDataProvider.prototype.init = function (appKey, options) { new RongIMLib.FeatureDectector(options.appCallback); }; ServerDataProvider.prototype.connect = function (token, callback, userId, option) { RongIMLib.RongIMClient.bridge = RongIMLib.Bridge.getInstance(); RongIMLib.RongIMClient._memoryStore.token = token; RongIMLib.RongIMClient._memoryStore.callback = callback; userId = userId || ''; option = option || {}; var isConnecting = false, isConnected = false; if (RongIMLib.Bridge._client && RongIMLib.Bridge._client.channel) { isConnecting = (RongIMLib.Bridge._client.channel.connectionStatus == RongIMLib.ConnectionStatus.CONNECTING); isConnected = (RongIMLib.Bridge._client.channel.connectionStatus == RongIMLib.ConnectionStatus.CONNECTED); } if (isConnected || isConnecting) { return; } var isGreater = (RongIMLib.RongIMClient.otherDeviceLoginCount > 5); if (isGreater) { callback.onError(RongIMLib.ConnectionStatus.ULTRALIMIT); return; } // 清除本地导航缓存 if (option.force) { RongIMLib.RongIMClient._storageProvider.removeItem('servers'); } RongIMLib.RongIMClient.bridge.setListener(); RongIMLib.RongIMClient.bridge.connect(RongIMLib.RongIMClient._memoryStore.appKey, token, { onSuccess: function (data) { setTimeout(function () { callback.onSuccess(data); }); }, onError: function (e) { if (e == RongIMLib.ConnectionState.TOKEN_INCORRECT || !e) { setTimeout(function () { callback.onTokenIncorrect(); }); } else { setTimeout(function () { callback.onError(e); }); } } }); }; /* config.auto: 默认 false, true 启用自动重连,启用则为必选参数 config.rate: 重试频率 [100, 1000, 3000, 6000, 10000, 18000] 单位为毫秒,可选 config.url: 网络嗅探地址 [http(s)://]cdn.ronghub.com/RongIMLib-2.2.6.min.js 可选 */ ServerDataProvider.prototype.reconnect = function (callback, config) { var store = RongIMLib.RongIMClient._memoryStore; var token = store.token; if (!token) { throw new Error('reconnect: token is empty.'); } if (RongIMLib.Bridge._client && RongIMLib.Bridge._client.channel && RongIMLib.Bridge._client.channel.connectionStatus != RongIMLib.ConnectionStatus.CONNECTED && RongIMLib.Bridge._client.channel.connectionStatus != RongIMLib.ConnectionStatus.CONNECTING) { config = config || {}; var key = config.auto ? 'auto' : 'custom'; var handler = { auto: function () { var repeatConnect = function (options) { var step = options.step(); var done = 'done'; var url = options.url; var ping = function () { RongIMLib.RongUtil.request({ url: url, success: function () { options.done(); }, error: function () { repeat(); } }); }; var repeat = function () { var next = step(); if (next == 'done') { var error = RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE; options.done(error); return; } setTimeout(ping, next); }; repeat(); }; var protocol = RongIMLib.RongIMClient._memoryStore.depend.protocol; var url = config.url || 'cdn.ronghub.com/RongIMLib-2.2.6.min.js'; var pathConfig = { protocol: protocol, path: url }; url = RongIMLib.RongUtil.formatProtoclPath(pathConfig); var rate = config.rate || [100, 1000, 3000, 6000, 10000, 18000]; //结束标识 rate.push('done'); var opts = { url: url, step: function () { var index = 0; return function () { var time = rate[index]; index++; return time; }; }, done: function (error) { if (error) { callback.onError(error); return; } RongIMLib.RongIMClient.connect(token, callback); } }; repeatConnect(opts); }, custom: function () { RongIMLib.RongIMClient.connect(token, callback); } }; handler[key](); } }; ServerDataProvider.prototype.logout = function () { RongIMLib.RongIMClient.bridge.disconnect(); RongIMLib.RongIMClient.bridge = null; }; ServerDataProvider.prototype.disconnect = function () { RongIMLib.RongIMClient.bridge.disconnect(); }; ServerDataProvider.prototype.sendReceiptResponse = function (conversationType, targetId, sendCallback) { var rspkey = RongIMLib.Bridge._client.userId + conversationType + targetId + 'RECEIVED', me = this; if (RongIMLib.RongUtil.supportLocalStorage()) { var valObj = JSON.parse(RongIMLib.RongIMClient._storageProvider.getItem(rspkey)); if (valObj) { var vals = []; for (var key in valObj) { var tmp = {}; tmp[key] = valObj[key].uIds; valObj[key].isResponse || vals.push(tmp); } if (vals.length == 0) { sendCallback.onSuccess(); return; } var interval = setInterval(function () { if (vals.length == 1) { clearInterval(interval); } var obj = vals.splice(0, 1)[0]; var rspMsg = new RongIMLib.ReadReceiptResponseMessage({ receiptMessageDic: obj }); me.sendMessage(conversationType, targetId, rspMsg, { onSuccess: function (msg) { var senderUserId = RongIMLib.MessageUtil.getFirstKey(obj); valObj[senderUserId].isResponse = true; RongIMLib.RongIMClient._storageProvider.setItem(rspkey, JSON.stringify(valObj)); sendCallback.onSuccess(msg); }, onError: function (error, msg) { sendCallback.onError(error, msg); } }); }, 200); } else { sendCallback.onSuccess(); } } else { sendCallback.onSuccess(); } }; ServerDataProvider.prototype.sendTypingStatusMessage = function (conversationType, targetId, messageName, sendCallback) { var me = this; if (messageName in RongIMLib.RongIMClient.MessageParams) { me.sendMessage(conversationType, targetId, RongIMLib.TypingStatusMessage.obtain(RongIMLib.RongIMClient.MessageParams[messageName].objectName, ""), { onSuccess: function () { setTimeout(function () { sendCallback.onSuccess(); }); }, onError: function (errorCode) { setTimeout(function () { sendCallback.onError(errorCode, null); }); }, onBefore: function () { } }); } }; ServerDataProvider.prototype.sendRecallMessage = function (content, sendMessageCallback) { var msg = new RongIMLib.RecallCommandMessage({ conversationType: content.conversationType, targetId: content.targetId, sentTime: content.sentTime, messageUId: content.messageUId, extra: content.extra, user: content.user }); this.sendMessage(content.conversationType, content.senderUserId, msg, sendMessageCallback, false, null, null, 2); }; ServerDataProvider.prototype.sendTextMessage = function (conversationType, targetId, content, sendMessageCallback) { var msgContent = RongIMLib.TextMessage.obtain(content); this.sendMessage(conversationType, targetId, msgContent, sendMessageCallback); }; ServerDataProvider.prototype.getRemoteHistoryMessages = function (conversationType, targetId, timestamp, count, callback, config) { if (count <= 1) { throw new Error("the count must be greater than 1."); } config = config || {}; var order = config.order || 0; var getKey = function () { return [conversationType, targetId, '_', order].join(''); }; var key = getKey(); if (!RongIMLib.RongUtil.isNumber(timestamp)) { timestamp = RongIMLib.RongIMClient._memoryStore.lastReadTime.get(key); } var memoryStore = RongIMLib.RongIMClient._memoryStore; var historyMessageLimit = memoryStore.historyMessageLimit; /* limit 属性: var limit = { time: '时间戳, 最后一次拉取时间', hasMore: '是否还有历史消息, bool 值' }; */ var limit = historyMessageLimit.get(key) || {}; var hasMore = limit.hasMore; var isFecth = (hasMore || limit.time != timestamp); // 正序获取消息时不做限制,防止有新消息导致无法获取 if (!isFecth && order == 0) { return callback.onSuccess([], hasMore); } var modules = new RongIMLib.RongIMClient.Protobuf.HistoryMsgInput(), self = this; modules.setTargetId(targetId); modules.setTime(timestamp); modules.setCount(count); modules.setOrder(order); var topic = HistoryMsgType[conversationType] || HistoryMsgType[RongIMLib.ConversationType.PRIVATE]; RongIMLib.RongIMClient.bridge.queryMsg(topic, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), targetId, { onSuccess: function (data) { var fetchTime = RongIMLib.MessageUtil.int64ToTimestamp(data.syncTime); RongIMLib.RongIMClient._memoryStore.lastReadTime.set(key, fetchTime); historyMessageLimit.set(key, { hasMore: !!data.hasMsg, time: fetchTime }); var list = data.list.reverse(), tempMsg = null, tempDir; var read = RongIMLib.SentStatus.READ; if (RongIMLib.RongUtil.supportLocalStorage()) { for (var i = 0, len = list.length; i < len; i++) { tempMsg = RongIMLib.MessageUtil.messageParser(list[i]); tempDir = JSON.parse(RongIMLib.RongIMClient._storageProvider.getItem(RongIMLib.Bridge._client.userId + tempMsg.messageUId + "SENT")); if (tempDir) { tempMsg.receiptResponse || (tempMsg.receiptResponse = {}); tempMsg.receiptResponse[tempMsg.messageUId] = tempDir.count; } tempMsg.sentStatus = read; tempMsg.targetId = targetId; list[i] = tempMsg; } } else { for (var i = 0, len = list.length; i < len; i++) { var tempMsg = RongIMLib.MessageUtil.messageParser(list[i]); tempMsg.sentStatus = read; list[i] = tempMsg; } } setTimeout(function () { callback.onSuccess(list, !!data.hasMsg); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }, "HistoryMessagesOuput"); }; ServerDataProvider.prototype.hasRemoteUnreadMessages = function (token, callback) { var xss = null; window.RCCallback = function (x) { setTimeout(function () { callback.onSuccess(!!+x.status); }); xss.parentNode.removeChild(xss); }; xss = document.createElement("script"); xss.src = RongIMLib.RongIMClient._memoryStore.depend.api + "/message/exist.js?appKey=" + encodeURIComponent(RongIMLib.RongIMClient._memoryStore.appKey) + "&token=" + encodeURIComponent(token) + "&callBack=RCCallback&_=" + RongIMLib.RongUtil.getTimestamp(); document.body.appendChild(xss); xss.onerror = function () { setTimeout(function () { callback.onError(RongIMLib.ErrorCode.UNKNOWN); }); xss.parentNode.removeChild(xss); }; }; ServerDataProvider.prototype.getRemoteConversationList = function (callback, conversationTypes, count) { var modules = new RongIMLib.RongIMClient.Protobuf.RelationsInput(), self = this; modules.setType(1); if (typeof count == 'undefined') { modules.setCount(0); } else { modules.setCount(count); } RongIMLib.RongIMClient.bridge.queryMsg(26, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (list) { if (list.info) { list.info = list.info.reverse(); for (var i = 0, len = list.info.length; i < len; i++) { RongIMLib.RongIMClient.getInstance().pottingConversation(list.info[i]); } } var conversations = RongIMLib.RongIMClient._memoryStore.conversationList; setTimeout(function () { if (conversationTypes) { return callback.onSuccess(self.filterConversations(conversationTypes, conversations)); } callback.onSuccess(conversations); }); }, onError: function (error) { callback.onError(error); } }, "RelationsOutput"); }; ServerDataProvider.prototype.addMemberToDiscussion = function (discussionId, userIdList, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.ChannelInvitationInput(); modules.setUsers(userIdList); RongIMLib.RongIMClient.bridge.queryMsg(0, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), discussionId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.createDiscussion = function (name, userIdList, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.CreateDiscussionInput(), self = this; modules.setName(name); RongIMLib.RongIMClient.bridge.queryMsg(1, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (discussId) { if (userIdList.length > 0) { self.addMemberToDiscussion(discussId, userIdList, { onSuccess: function () { }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); } setTimeout(function () { callback.onSuccess(discussId); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }, "CreateDiscussionOutput"); }; ServerDataProvider.prototype.getDiscussion = function (discussionId, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.ChannelInfoInput(); modules.setNothing(1); RongIMLib.RongIMClient.bridge.queryMsg(4, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), discussionId, { onSuccess: function (data) { setTimeout(function () { callback.onSuccess(data); }); }, onError: function (errorCode) { setTimeout(function () { callback.onError(errorCode); }); } }, "ChannelInfoOutput"); }; ServerDataProvider.prototype.quitDiscussion = function (discussionId, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.LeaveChannelInput(); modules.setNothing(1); RongIMLib.RongIMClient.bridge.queryMsg(7, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), discussionId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (errorCode) { setTimeout(function () { callback.onError(errorCode); }); } }); }; ServerDataProvider.prototype.removeMemberFromDiscussion = function (discussionId, userId, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.ChannelEvictionInput(); modules.setUser(userId); RongIMLib.RongIMClient.bridge.queryMsg(9, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), discussionId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (errorCode) { setTimeout(function () { callback.onError(errorCode); }); } }); }; ServerDataProvider.prototype.setDiscussionInviteStatus = function (discussionId, status, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.ModifyPermissionInput(); modules.setOpenStatus(status.valueOf()); RongIMLib.RongIMClient.bridge.queryMsg(11, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), discussionId, { onSuccess: function (x) { setTimeout(function () { callback.onSuccess(); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.setDiscussionName = function (discussionId, name, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RenameChannelInput(); modules.setName(name); RongIMLib.RongIMClient.bridge.queryMsg(12, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), discussionId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (errcode) { callback.onError(errcode); } }); }; ServerDataProvider.prototype.joinChatRoom = function (chatroomId, messageCount, callback) { var e = new RongIMLib.RongIMClient.Protobuf.ChrmInput(); e.setNothing(1); RongIMLib.Bridge._client.chatroomId = chatroomId; RongIMLib.RongIMClient.bridge.queryMsg(19, RongIMLib.MessageUtil.ArrayForm(e.toArrayBuffer()), chatroomId, { onSuccess: function () { var navi = RongIMLib.RongIMClient.getInstance().getNavi(); var isOpenKVStorage = navi.kvStorage; if (isOpenKVStorage) { RongIMLib.RongIMClient._dataAccessProvider.pullChatroomEntry(chatroomId, 0, { onSuccess: function (result) { RongIMLib.ChrmKVHandler.setEntries(chatroomId, result); setTimeout(function () { callback.onSuccess(); }); }, onError: function (errorCode) { setTimeout(function () { callback.onError(errorCode); }); } }); } else { setTimeout(function () { callback.onSuccess(); }); } var modules = new RongIMLib.RongIMClient.Protobuf.ChrmPullMsg(); messageCount == 0 && (messageCount = -1); modules.setCount(messageCount); modules.setSyncTime(0); RongIMLib.Bridge._client.queryMessage("chrmPull", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), chatroomId, 1, { onSuccess: function (collection) { var list = collection.list; var sync = RongIMLib.MessageUtil.int64ToTimestamp(collection.syncTime); var latestMessage = list[list.length - 1]; if (latestMessage) { latestMessage = RongIMLib.MessageUtil.messageParser(latestMessage); sync = latestMessage.sentTime; } RongIMLib.RongIMClient._memoryStore.lastReadTime.set(chatroomId + RongIMLib.Bridge._client.userId + "CST", sync); var _client = RongIMLib.Bridge._client; for (var i = 0, mlen = list.length; i < mlen; i++) { var uId = 'R' + list[i].msgId; if (!(uId in _client.cacheMessageIds)) { _client.cacheMessageIds[uId] = true; var cacheUIds = RongIMLib.RongUtil.keys(_client.cacheMessageIds); if (cacheUIds.length > 10) { uId = cacheUIds[0]; delete _client.cacheMessageIds[uId]; } if (RongIMLib.RongIMClient._memoryStore.filterMessages.length > 0) { for (var j = 0, flen = RongIMLib.RongIMClient._memoryStore.filterMessages.length; j < flen; j++) { if (RongIMLib.RongIMClient.MessageParams[RongIMLib.RongIMClient._memoryStore.filterMessages[j]].objectName != list[i].classname) { _client.handler.onReceived(list[i]); } } } else { _client.handler.onReceived(list[i]); } } } }, onError: function (x) { setTimeout(function () { callback.onError(RongIMLib.ErrorCode.CHATROOM_HISMESSAGE_ERROR); }); } }, "DownStreamMessages"); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }, "ChrmOutput"); }; ServerDataProvider.prototype.getChatRoomInfo = function (chatRoomId, count, order, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.QueryChatroomInfoInput(); modules.setCount(count); modules.setOrder(order); RongIMLib.RongIMClient.bridge.queryMsg("queryChrmI", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), chatRoomId, { onSuccess: function (ret) { var userInfos = ret.userInfos; userInfos.forEach(function (item) { item.time = RongIMLib.MessageUtil.int64ToTimestamp(item.time); }); setTimeout(function () { callback.onSuccess(ret); }); }, onError: function (errcode) { setTimeout(function () { callback.onError(errcode); }); } }, "QueryChatroomInfoOutput"); }; ServerDataProvider.prototype.quitChatRoom = function (chatroomId, callback) { var e = new RongIMLib.RongIMClient.Protobuf.ChrmInput(); e.setNothing(1); RongIMLib.RongIMClient.bridge.queryMsg(17, RongIMLib.MessageUtil.ArrayForm(e.toArrayBuffer()), chatroomId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (errcode) { setTimeout(function () { callback.onError(errcode); }); } }, "ChrmOutput"); }; ServerDataProvider.prototype.setChatroomHisMessageTimestamp = function (chatRoomId, timestamp) { RongIMLib.RongIMClient._memoryStore.lastReadTime.set('chrhis_' + chatRoomId, timestamp); }; ServerDataProvider.prototype.getChatRoomHistoryMessages = function (chatRoomId, count, order, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.HistoryMsgInput(); modules.setTargetId(chatRoomId); var timestamp = RongIMLib.RongIMClient._memoryStore.lastReadTime.get('chrhis_' + chatRoomId) || 0; modules.setTime(timestamp); modules.setCount(count); modules.setOrder(order); RongIMLib.RongIMClient.bridge.queryMsg(34, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (data) { RongIMLib.RongIMClient._memoryStore.lastReadTime.set('chrhis_' + chatRoomId, RongIMLib.MessageUtil.int64ToTimestamp(data.syncTime)); var list = data.list.reverse(); for (var i = 0, len = list.length; i < len; i++) { list[i] = RongIMLib.MessageUtil.messageParser(list[i]); } setTimeout(function () { callback.onSuccess(list, !!data.hasMsg); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }, "HistoryMsgOuput"); }; ServerDataProvider.prototype.setChatroomEntry = function (chatroomId, chatroomEntry, callback) { var opt = RongIMLib.ChatroomEntityOpt.UPDATE; var key = chatroomEntry.key, value = chatroomEntry.value; var isKeyInValid = !RongIMLib.RongUtil.isLengthLimit(key, RongIMLib.ChatroomEntityLimit.KEY, 1) || !RongIMLib.ChrmKVHandler.isKeyValid(key); var isValueInValid = !RongIMLib.RongUtil.isLengthLimit(value, RongIMLib.ChatroomEntityLimit.VALUE, 1); if (isKeyInValid || isValueInValid) { setTimeout(function () { callback.onError(RongIMLib.ErrorCode.BIZ_ERROR_INVALID_PARAMETER); }); } else { this.refreshChatroomEntry(chatroomId, chatroomEntry, opt, callback); } }; ServerDataProvider.prototype.forceSetChatroomEntry = function (chatroomId, chatroomEntry, callback) { chatroomEntry.isOverwrite = true; this.setChatroomEntry(chatroomId, chatroomEntry, callback); }; ServerDataProvider.prototype.removeChatroomEntry = function (chatroomId, chatroomEntry, callback) { var opt = RongIMLib.ChatroomEntityOpt.DELETE; var key = chatroomEntry.key; var isKeyInValid = !RongIMLib.RongUtil.isLengthLimit(key, RongIMLib.ChatroomEntityLimit.KEY, 1) || !RongIMLib.ChrmKVHandler.isKeyValid(key); if (isKeyInValid) { setTimeout(function () { callback.onError(RongIMLib.ErrorCode.BIZ_ERROR_INVALID_PARAMETER); }); } else { this.refreshChatroomEntry(chatroomId, chatroomEntry, opt, callback); } }; ServerDataProvider.prototype.forceRemoveChatroomEntry = function (chatroomId, chatroomEntry, callback) { chatroomEntry.isOverwrite = true; this.removeChatroomEntry(chatroomId, chatroomEntry, callback); }; ServerDataProvider.prototype.refreshChatroomEntry = function (chatroomId, chatroomEntry, chatroomEntryOpt, callback) { var modules, topic; var key = chatroomEntry.key, value = chatroomEntry.value || '', extra = chatroomEntry.notificationExtra; if (chatroomEntryOpt === RongIMLib.ChatroomEntityOpt.DELETE) { modules = new RongIMLib.RongIMClient.Protobuf.DeleteChrmKV(); topic = 'delKV'; } else { modules = new RongIMLib.RongIMClient.Protobuf.SetChrmKV(); topic = 'setKV'; } var status = RongIMLib.RongInnerTools.getChrmEntityStatus(chatroomEntry, chatroomEntryOpt); var currentUserId = RongIMLib.RongIMClient.getInstance().getCurrentUserId(); var entry = { key: key, value: value, uid: currentUserId }; if (status) { entry.status = status; } modules.setEntry(entry); if (chatroomEntry.isSendNotification) { modules.setBNotify(true); var msgModules = new RongIMLib.RongIMClient.Protobuf.UpStreamMessage(); var msg = new RongIMLib.ChrmKVNotificationMessage({ key: key, value: value, extra: extra, type: chatroomEntryOpt }); msgModules.setSessionId(RongIMLib.RongIMClient.MessageParams[msg.messageName].msgTag.getMessageTag()); msgModules.setClassname(RongIMLib.RongIMClient.MessageParams[msg.messageName].objectName); msgModules.setContent(msg.encode()); modules.setNotification(msgModules); // 默认设置为 聊天室消息 modules.setType(RongIMLib.ConversationType.CHATROOM); } RongIMLib.RongIMClient.bridge.queryMsg(topic, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), chatroomId, { onSuccess: function (ret) { var currentUserId = RongIMLib.RongIMClient.getInstance().getCurrentUserId(); RongIMLib.ChrmKVHandler.setEntry(chatroomId, chatroomEntry, status, currentUserId); setTimeout(function () { callback.onSuccess(ret); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }, 'ChrmOutput'); }; ServerDataProvider.prototype.getChatroomEntry = function (chatroomId, key, callback) { var value = RongIMLib.ChrmKVHandler.getEntityValue(chatroomId, key); setTimeout(function () { if (RongIMLib.RongUtil.isEmpty(value)) { callback.onError(RongIMLib.ErrorCode.CHATROOM_KEY_NOT_EXIST); } else { callback.onSuccess(value); } }); }; ServerDataProvider.prototype.getAllChatroomEntries = function (chatroomId, callback) { setTimeout(function () { var entries = RongIMLib.ChrmKVHandler.getAllEntityValue(chatroomId); callback.onSuccess(entries); }); }; ServerDataProvider.prototype.pullChatroomEntry = function (chatroomId, time, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.QueryChrmKV(); modules.setTimestamp(time); RongIMLib.RongIMClient.bridge.queryMsg('pullKV', RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), chatroomId, { onSuccess: function (data) { setTimeout(function () { callback.onSuccess(data); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }, "ChrmKVOutput"); }; ServerDataProvider.prototype.setMessageStatus = function (conversationType, targetId, timestamp, status, callback) { setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.addToBlacklist = function (userId, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.Add2BlackListInput(); modules.setUserId(userId); RongIMLib.RongIMClient.bridge.queryMsg(21, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.getBlacklist = function (callback) { var modules = new RongIMLib.RongIMClient.Protobuf.QueryBlackListInput(); modules.setNothing(1); RongIMLib.RongIMClient.bridge.queryMsg(23, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (list) { setTimeout(function () { callback.onSuccess(list); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }, "QueryBlackListOutput"); }; ServerDataProvider.prototype.getBlacklistStatus = function (userId, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.BlackListStatusInput(); modules.setUserId(userId); RongIMLib.RongIMClient.bridge.queryMsg(24, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function (status) { setTimeout(function () { callback.onSuccess(RongIMLib.BlacklistStatus[status]); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.removeFromBlacklist = function (userId, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RemoveFromBlackListInput(); modules.setUserId(userId); RongIMLib.RongIMClient.bridge.queryMsg(22, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.getFileToken = function (fileType, callback) { if (!(/(1|2|3|4)/.test(fileType.toString()))) { setTimeout(function () { callback.onError(RongIMLib.ErrorCode.QNTKN_FILETYPE_ERROR); }); return; } var modules = new RongIMLib.RongIMClient.Protobuf.GetQNupTokenInput(); modules.setType(fileType); RongIMLib.RongIMClient.bridge.queryMsg(30, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (data) { setTimeout(function () { callback.onSuccess(data); }); }, onError: function (errcode) { setTimeout(function () { callback.onError(errcode); }); } }, "GetQNupTokenOutput"); }; ServerDataProvider.prototype.getFileUrl = function (fileType, fileName, oriName, callback) { if (!(/(1|2|3|4)/.test(fileType.toString()))) { setTimeout(function () { callback.onError(RongIMLib.ErrorCode.QNTKN_FILETYPE_ERROR); }); return; } var modules = new RongIMLib.RongIMClient.Protobuf.GetQNdownloadUrlInput(); modules.setType(fileType); modules.setKey(fileName); if (oriName) { modules.setFileName(oriName); } RongIMLib.RongIMClient.bridge.queryMsg(31, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (data) { setTimeout(function () { callback.onSuccess(data); }); }, onError: function (errcode) { setTimeout(function () { callback.onError(errcode); }); } }, "GetQNdownloadUrlOutput"); }; ServerDataProvider.prototype.getPullSetting = function (callback) { var modules = new RongIMLib.RongIMClient.Protobuf.PullUserSettingInput(); var version = parseInt(RongIMLib.RongIMClient.sdkver); modules.setVersion(version); RongIMLib.RongIMClient.bridge.queryMsg('pullUS', RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (result) { result = result || {}; result.version = RongIMLib.MessageUtil.int64ToTimestamp(result.version); setTimeout(function () { callback.onSuccess(result); }); }, onError: function (errcode) { setTimeout(function () { callback.onError(errcode); }); } }, 'PullUserSettingOutput'); }; ServerDataProvider.prototype.setOfflineMessageDuration = function (duration, callback) { this.getPullSetting({ onSuccess: function (result) { /** * GetQNupTokenOutput 第一位为 int64, 第二位为 string, 与设置离线消息一致 * 为避免修改 Protobuf 带来的更新成本. 仅复用, 不重新命名 */ var modules = new RongIMLib.RongIMClient.Protobuf.GetQNupTokenOutput(); var version = result.version; modules.setDeadline(version); modules.setToken(duration + ''); RongIMLib.RongIMClient.bridge.queryMsg('setOfflineMsgDur', RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (data) { setTimeout(function () { callback.onSuccess(data); }); }, onError: function (errcode) { setTimeout(function () { callback.onError(errcode); }); } }); }, onError: callback.onError }); }; /* methodType 1 : 多客服(客服后台使用); 2 : 消息撤回 params.userIds : 定向消息接收者 */ ServerDataProvider.prototype.sendMessage = function (conversationType, targetId, messageContent, sendCallback, mentiondMsg, pushText, appData, methodType, params) { if (!RongIMLib.Bridge._client.channel) { setTimeout(function () { sendCallback.onError(RongIMLib.ErrorCode.RC_NET_UNAVAILABLE, null); }); return; } if (!RongIMLib.Bridge._client.channel.socket.socket.connected) { setTimeout(function () { sendCallback.onError(RongIMLib.ErrorCode.TIMEOUT, null); }); throw new Error("connect is timeout! postion:sendMessage"); } var isGroup = (conversationType == RongIMLib.ConversationType.DISCUSSION || conversationType == RongIMLib.ConversationType.GROUP); var modules = new RongIMLib.RongIMClient.Protobuf.UpStreamMessage(); if (mentiondMsg && isGroup) { modules.setSessionId(7); } else { modules.setSessionId(RongIMLib.RongIMClient.MessageParams[messageContent.messageName].msgTag.getMessageTag()); } pushText && modules.setPushText(pushText); appData && modules.setAppData(appData); if (isGroup && messageContent.messageName == RongIMLib.RongIMClient.MessageType["ReadReceiptResponseMessage"]) { var rspMsg = messageContent; if (rspMsg.receiptMessageDic) { var ids = []; for (var key in rspMsg.receiptMessageDic) { ids.push(key); } modules.setUserId(ids); } } if (isGroup && messageContent.messageName == RongIMLib.RongIMClient.MessageType["SyncReadStatusMessage"]) { modules.setUserId(RongIMLib.Bridge._client.userId); } params = params || {}; var userIds = params.userIds; if (userIds) { modules.setUserId(userIds); } var flag = 0; if (params.isPush || params.isVoipPush) { flag |= 0x01; } if (params.isFilerWhiteBlacklist) { flag |= 0x02; } modules.setConfigFlag(flag); modules.setClassname(RongIMLib.RongIMClient.MessageParams[messageContent.messageName].objectName); modules.setContent(messageContent.encode()); var content = modules.toArrayBuffer(); if (Object.prototype.toString.call(content) == "[object ArrayBuffer]") { content = [].slice.call(new Int8Array(content)); } var me = this, msg = new RongIMLib.Message(); var c = this.getConversation(conversationType, targetId); if (RongIMLib.RongIMClient.MessageParams[messageContent.messageName].msgTag.getMessageTag() == 3) { if (!c) { c = RongIMLib.RongIMClient.getInstance().createConversation(conversationType, targetId, ""); } c.sentTime = new Date().getTime(); c.sentStatus = RongIMLib.SentStatus.SENDING; c.senderUserName = ""; c.senderUserId = RongIMLib.Bridge._client.userId; c.notificationStatus = RongIMLib.ConversationNotificationStatus.DO_NOT_DISTURB; c.latestMessage = msg; c.unreadMessageCount = 0; RongIMLib.RongIMClient._dataAccessProvider.addConversation(c, { onSuccess: function (data) { } }); } RongIMLib.RongIMClient._memoryStore.converStore = c; msg.content = messageContent; msg.conversationType = conversationType; msg.senderUserId = RongIMLib.Bridge._client.userId; msg.objectName = RongIMLib.RongIMClient.MessageParams[messageContent.messageName].objectName; msg.targetId = targetId; msg.sentTime = new Date().getTime(); msg.messageDirection = RongIMLib.MessageDirection.SEND; msg.sentStatus = RongIMLib.SentStatus.SENT; msg.messageType = messageContent.messageName; RongIMLib.RongIMClient.bridge.pubMsg(conversationType.valueOf(), content, targetId, { onSuccess: function (data) { if (data && data.timestamp) { RongIMLib.RongIMClient._memoryStore.lastReadTime.set('converST_' + RongIMLib.Bridge._client.userId + conversationType + targetId, data.timestamp); } if ((conversationType == RongIMLib.ConversationType.DISCUSSION || conversationType == RongIMLib.ConversationType.GROUP) && messageContent.messageName == RongIMLib.RongIMClient.MessageType["ReadReceiptRequestMessage"]) { var reqMsg = msg.content; var sentkey = RongIMLib.Bridge._client.userId + reqMsg.messageUId + "SENT"; RongIMLib.RongIMClient._storageProvider.setItem(sentkey, JSON.stringify({ count: 0, dealtime: data.timestamp, userIds: {} })); } if (RongIMLib.RongIMClient.MessageParams[msg.messageType].msgTag.getMessageTag() == 3) { var cacheConversation = RongIMLib.RongIMClient._memoryStore.converStore; cacheConversation.sentStatus = msg.sentStatus; cacheConversation.latestMessage = msg; me.updateConversation(cacheConversation); var Conversation = RongIMLib.RongIMClient._dataAccessProvider.Conversation; Conversation._notify(RongIMLib.RongIMClient._memoryStore.conversationList); RongIMLib.RongIMClient._dataAccessProvider.addMessage(conversationType, targetId, msg, { onSuccess: function (ret) { msg = ret; msg.messageUId = data.messageUId; msg.sentTime = data.timestamp; msg.sentStatus = RongIMLib.SentStatus.SENT; msg.messageId = data.messageId; RongIMLib.RongIMClient._dataAccessProvider.updateMessage(msg); }, onError: function () { } }); } setTimeout(function () { cacheConversation && me.updateConversation(cacheConversation); msg.sentTime = data.timestamp; msg.messageUId = data.messageUId; sendCallback.onSuccess(msg); }); }, onError: function (errorCode, _msg) { msg.sentStatus = RongIMLib.SentStatus.FAILED; if (_msg) { msg.messageUId = _msg.messageUId; msg.sentTime = _msg.sentTime; } if (RongIMLib.RongIMClient.MessageParams[msg.messageType].msgTag.getMessageTag() == 3) { RongIMLib.RongIMClient._memoryStore.converStore.latestMessage = msg; } RongIMLib.RongIMClient._dataAccessProvider.addMessage(conversationType, targetId, msg, { onSuccess: function (ret) { msg.messageId = ret.messageId; RongIMLib.RongIMClient._dataAccessProvider.updateMessage(msg); }, onError: function () { } }); setTimeout(function () { sendCallback.onError(errorCode, msg); }); } }, null, methodType); sendCallback.onBefore && sendCallback.onBefore(RongIMLib.MessageIdHandler.messageId); msg.messageId = RongIMLib.MessageIdHandler.messageId + ""; }; ServerDataProvider.prototype.setConnectionStatusListener = function (listener) { if (RongIMLib.RongUtil.isObject(listener) && RongIMLib.RongUtil.isFunction(listener.onChanged)) { RongIMLib.RongIMClient.statusListeners.push(listener.onChanged); } }; ServerDataProvider.prototype.setOnReceiveMessageListener = function (listener) { if (RongIMLib.RongUtil.isObject(listener) && RongIMLib.RongUtil.isFunction(listener.onReceived)) { RongIMLib.RongIMClient.messageListeners.push(listener.onReceived); } }; ServerDataProvider.prototype.registerMessageType = function (messageType, objectName, messageTag, messageContent, searchProps) { if (!messageType) { throw new Error("messageType can't be empty,postion -> registerMessageType"); } if (!objectName) { throw new Error("objectName can't be empty,postion -> registerMessageType"); } if (Object.prototype.toString.call(messageContent) == "[object Array]") { var regMsg = RongIMLib.ModelUtil.modleCreate(messageContent, messageType); RongIMLib.RongIMClient.RegisterMessage[messageType] = regMsg; } else if (Object.prototype.toString.call(messageContent) == "[object Function]" || Object.prototype.toString.call(messageContent) == "[object Object]") { if (!messageContent.encode) { throw new Error("encode method has not realized or messageName is undefined-> registerMessageType"); } if (!messageContent.decode) { throw new Error("decode method has not realized -> registerMessageType"); } } else { throw new Error("The index of 3 parameter was wrong type must be object or function or array-> registerMessageType"); } registerMessageTypeMapping[objectName] = messageType; }; ServerDataProvider.prototype.registerMessageTypes = function (messages) { var types = []; var getProtos = function (proto) { var protos = []; for (var p in proto) { protos.push(p); } return protos; }; //转换消息为自定义消息参数格式 for (var name in messages) { var message = messages[name]; var proto = message.proto; var protos = getProtos(proto); var flag = message.flag || 3; var tag = RongIMLib.MessageTag.getTagByStatus(flag); flag = new RongIMLib.MessageTag(tag.isCounted, tag.isPersited); types.push({ type: name, name: message.name, flag: flag, protos: protos }); } var register = function (message) { var type = message.type; var name = message.name; var flag = message.flag; var protos = message.protos; RongIMLib.RongIMClient.registerMessageType(type, name, flag, protos); }; for (var i = 0, len = types.length; i < len; i++) { var message = types[i]; register(message); } }; ServerDataProvider.prototype.addConversation = function (conversation, callback) { var isAdd = true; for (var i = 0, len = RongIMLib.RongIMClient._memoryStore.conversationList.length; i < len; i++) { if (RongIMLib.RongIMClient._memoryStore.conversationList[i].conversationType === conversation.conversationType && RongIMLib.RongIMClient._memoryStore.conversationList[i].targetId === conversation.targetId) { // RongIMClient._memoryStore.conversationList[i] = conversation; RongIMLib.RongIMClient._memoryStore.conversationList.unshift(RongIMLib.RongIMClient._memoryStore.conversationList.splice(i, 1)[0]); isAdd = false; break; } } if (isAdd) { RongIMLib.RongIMClient._memoryStore.conversationList.unshift(conversation); } callback && callback.onSuccess(true); }; ServerDataProvider.prototype.updateConversation = function (conversation) { var conver; for (var i = 0, len = RongIMLib.RongIMClient._memoryStore.conversationList.length; i < len; i++) { var item = RongIMLib.RongIMClient._memoryStore.conversationList[i]; if (conversation.conversationType === item.conversationType && conversation.targetId === item.targetId) { conversation.conversationTitle && (item.conversationTitle = conversation.conversationTitle); conversation.senderUserName && (item.senderUserName = conversation.senderUserName); conversation.senderPortraitUri && (item.senderPortraitUri = conversation.senderPortraitUri); conversation.latestMessage && (item.latestMessage = conversation.latestMessage); conversation.sentStatus && (item.sentStatus = conversation.sentStatus); break; } } return conver; }; ServerDataProvider.prototype.removeConversation = function (conversationType, targetId, callback) { var mod = new RongIMLib.RongIMClient.Protobuf.RelationsInput(); mod.setType(conversationType); RongIMLib.RongIMClient.bridge.queryMsg(27, RongIMLib.MessageUtil.ArrayForm(mod.toArrayBuffer()), targetId, { onSuccess: function () { var isRemoved = false; var conversations = RongIMLib.RongIMClient._memoryStore.conversationList; var len = conversations.length; for (var i = 0; i < len; i++) { if (conversations[i].conversationType == conversationType && targetId == conversations[i].targetId) { conversations.splice(i, 1); isRemoved = true; break; } } isRemoved && RongIMLib.RongIMClient._dataAccessProvider.Conversation._notify(RongIMLib.RongIMClient._memoryStore.conversationList); callback.onSuccess(true); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.getMessage = function (messageId, callback) { callback.onSuccess(new RongIMLib.Message()); }; ServerDataProvider.prototype.addMessage = function (conversationType, targetId, message, callback) { if (callback) { callback.onSuccess(message); } }; ServerDataProvider.prototype.removeMessage = function (conversationType, targetId, messages, callback) { RongIMLib.RongIMClient.getInstance().deleteRemoteMessages(conversationType, targetId, messages, callback); }; ServerDataProvider.prototype.removeLocalMessage = function (conversationType, targetId, timestamps, callback) { callback.onSuccess(true); }; ServerDataProvider.prototype.updateMessage = function (message, callback) { if (callback) { callback.onSuccess(message); } }; ServerDataProvider.prototype.deleteRemoteMessages = function (conversationType, targetId, messages, callback) { if (!RongIMLib.RongIMClient.Protobuf.DeleteMsgInput) { throw new Error('SDK Protobuf version is too low'); } var modules = new RongIMLib.RongIMClient.Protobuf.DeleteMsgInput(); var msgs = []; RongIMLib.RongUtil.forEach(messages, function (msg) { msgs.push({ msgId: msg.messageUId, msgDataTime: msg.sentTime, direct: msg.messageDirection }); }); modules.setType(conversationType); modules.setConversationId(targetId); modules.setMsgs(msgs); RongIMLib.RongIMClient.bridge.queryMsg('delMsg', RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), targetId, { onSuccess: function (result) { callback.onSuccess(result); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }, 'DeleteMsgOutput'); }; ServerDataProvider.prototype.clearRemoteHistoryMessages = function (params, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.CleanHisMsgInput(); var conversationType = params.conversationType; var _topic = { 1: 'cleanPMsg', 2: 'cleanDMsg', 3: 'cleanGMsg', 5: 'cleanCMsg', 6: 'cleanSMsg' }; var topic = _topic[conversationType]; if (!topic) { callback.onError(RongIMLib.ErrorCode.CLEAR_HIS_TYPE_ERROR); return; } var timestamp = params.timestamp; if (typeof timestamp != 'number') { callback.onError(RongIMLib.ErrorCode.CLEAR_HIS_TIME_ERROR); return; } modules.setDataTime(timestamp); var targetId = params.targetId; modules.setTargetId(targetId); RongIMLib.RongIMClient.bridge.queryMsg(topic, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), targetId, { onSuccess: function (result) { callback.onSuccess(!result); }, onError: function (error) { // error 1 历史消息云存储没有开通、传入时间大于服务器时间 清除失败,1 与其他错误码冲突,所以自定义错误码返回 if (error == 1) { error = RongIMLib.ErrorCode.CLEAR_HIS_ERROR; } setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.clearHistoryMessages = function (params, callback) { this.clearRemoteHistoryMessages(params, callback); }; // 兼容老版本 ServerDataProvider.prototype.clearMessages = function (conversationType, targetId, callback) { }; ServerDataProvider.prototype.updateMessages = function (conversationType, targetId, key, value, callback) { var me = this; if (key == "readStatus") { if (RongIMLib.RongIMClient._memoryStore.conversationList.length > 0) { me.getConversationList({ onSuccess: function (list) { Array.forEach(list, function (conver) { if (conver.conversationType == conversationType && conver.targetId == targetId) { conver.unreadMessageCount = 0; } }); }, onError: function (errorCode) { setTimeout(function () { callback.onError(errorCode); }); } }, null); } } setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.getConversation = function (conversationType, targetId, callback) { var conver = null; for (var i = 0, len = RongIMLib.RongIMClient._memoryStore.conversationList.length; i < len; i++) { if (RongIMLib.RongIMClient._memoryStore.conversationList[i].conversationType == conversationType && RongIMLib.RongIMClient._memoryStore.conversationList[i].targetId == targetId) { conver = RongIMLib.RongIMClient._memoryStore.conversationList[i]; if (RongIMLib.RongUtil.supportLocalStorage()) { // var count = RongIMClient._storageProvider.getItem("cu" + Bridge._client.userId + conversationType + targetId); var count = RongIMLib.UnreadCountHandler.get(conversationType, targetId); if (conver.unreadMessageCount == 0) { conver.unreadMessageCount = Number(count); } } } } setTimeout(function () { callback && callback.onSuccess(conver); }); return conver; }; ServerDataProvider.prototype.filterConversations = function (types, list) { var conversaions = []; RongIMLib.RongUtil.forEach(types, function (type) { RongIMLib.RongUtil.forEach(list, function (conversation) { if (conversation.conversationType == type) { conversaions.push(conversation); } }); }); return conversaions; }; ServerDataProvider.prototype.getConversationList = function (callback, conversationTypes, count, isHidden) { var that = this; var isSync = RongIMLib.RongIMClient._memoryStore.isSyncRemoteConverList; var list = RongIMLib.RongIMClient._memoryStore.conversationList; var isLocalInclude = list.length > count; if (!isSync && isLocalInclude) { setTimeout(function () { var localList = list.slice(0, count); if (conversationTypes) { localList = that.filterConversations(conversationTypes, localList); } callback.onSuccess(localList); }); return; } RongIMLib.RongIMClient.getInstance().getRemoteConversationList({ onSuccess: function (list) { if (RongIMLib.RongUtil.supportLocalStorage()) { Array.forEach(RongIMLib.RongIMClient._memoryStore.conversationList, function (item) { // var count = RongIMClient._storageProvider.getItem("cu" + Bridge._client.userId + item.conversationType + item.targetId); var count = RongIMLib.UnreadCountHandler.get(item.conversationType, item.targetId); if (item.unreadMessageCount == 0) { item.unreadMessageCount = Number(count); } }); } RongIMLib.RongIMClient._memoryStore.isSyncRemoteConverList = false; setTimeout(function () { callback.onSuccess(list); }); }, onError: function (errorcode) { setTimeout(function () { callback.onError(errorcode); }); } }, conversationTypes, count, isHidden); }; ServerDataProvider.prototype.clearCache = function () { var memoryStore = RongIMLib.RongIMClient._memoryStore || {}; memoryStore.conversationList = []; memoryStore.isSyncRemoteConverList = true; }; ServerDataProvider.prototype.clearConversations = function (conversationTypes, callback) { Array.forEach(conversationTypes, function (conversationType) { Array.forEach(RongIMLib.RongIMClient._memoryStore.conversationList, function (conver) { if (conversationType == conver.conversationType) { RongIMLib.RongIMClient.getInstance().removeConversation(conver.conversationType, conver.targetId, { onSuccess: function () { }, onError: function () { } }); } }); }); setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.setMessageContent = function (messageId, content, objectname) { }; ; ServerDataProvider.prototype.setMessageSearchField = function (messageId, content, searchFiles) { }; ; ServerDataProvider.prototype.getHistoryMessages = function (conversationType, targetId, timestamp, count, callback, objectname, order) { var config = { objectname: objectname, order: order }; RongIMLib.RongIMClient.getInstance().getRemoteHistoryMessages(conversationType, targetId, timestamp, count, callback, config); }; ServerDataProvider.prototype.getTotalUnreadCount = function (callback, conversationTypes) { var count = RongIMLib.UnreadCountHandler.getAll(conversationTypes); callback.onSuccess(count); }; ServerDataProvider.prototype.getConversationUnreadCount = function (conversationTypes, callback) { var count = 0; Array.forEach(conversationTypes, function (converType) { Array.forEach(RongIMLib.RongIMClient._memoryStore.conversationList, function (conver) { if (conver.conversationType == converType) { count += conver.unreadMessageCount; } }); }); setTimeout(function () { callback.onSuccess(count); }); }; //由于 Web 端未读消息数按会话统计,撤回消息会导致未读数不准确,提供设置未读数接口,桌面版不实现此方法 ServerDataProvider.prototype.setUnreadCount = function (conversationType, targetId, count, sentTime) { sentTime = sentTime || new Date().getTime(); RongIMLib.UnreadCountHandler.set(conversationType, targetId, count, sentTime); }; ServerDataProvider.prototype.getUnreadCount = function (conversationType, targetId, callback) { var unreadCount = RongIMLib.UnreadCountHandler.get(conversationType, targetId); setTimeout(function () { callback.onSuccess(unreadCount || 0); }); }; ServerDataProvider.prototype.cleanMentioneds = function (conver) { if (conver) { conver.mentionedMsg = null; var targetId = conver.targetId; var conversationType = conver.conversationType; var mentioneds = RongIMLib.RongIMClient._storageProvider.getItem("mentioneds_" + RongIMLib.Bridge._client.userId + '_' + conversationType + '_' + targetId); if (mentioneds) { var info = JSON.parse(mentioneds); delete info[conversationType + "_" + targetId]; if (!RongIMLib.MessageUtil.isEmpty(info)) { RongIMLib.RongIMClient._storageProvider.setItem("mentioneds_" + RongIMLib.Bridge._client.userId + '_' + conversationType + '_' + targetId, JSON.stringify(info)); } else { RongIMLib.RongIMClient._storageProvider.removeItem("mentioneds_" + RongIMLib.Bridge._client.userId + '_' + conversationType + '_' + targetId); } } } }; ServerDataProvider.prototype.clearUnreadCountByTimestamp = function (conversationType, targetId, timestamp, callback) { setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.clearUnreadCount = function (conversationType, targetId, callback) { var me = this; // RongIMClient._storageProvider.removeItem("cu" + Bridge._client.userId + conversationType + targetId); RongIMLib.UnreadCountHandler.remove(conversationType, targetId); this.getConversation(conversationType, targetId, { onSuccess: function (conver) { conver = conver || new RongIMLib.Conversation(); var isNotifyConversation = conver.unreadMessageCount; if (conver) { conver.unreadMessageCount = 0; me.cleanMentioneds(conver); } setTimeout(function () { callback.onSuccess(true); isNotifyConversation && RongIMLib.RongIMClient._dataAccessProvider.Conversation._notify(RongIMLib.RongIMClient._memoryStore.conversationList); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.clearTotalUnreadCount = function (callback) { var list = RongIMLib.RongIMClient._memoryStore.conversationList; var me = this; var isNotifyConversation = false; if (list) { // 清除 mentioneds、清除 list 中的 unreadMessageCount for (var i = 0; i < list.length; i++) { var conver = list[i]; if (conver) { isNotifyConversation = conver.unreadMessageCount ? true : isNotifyConversation; conver.unreadMessageCount = 0; me.cleanMentioneds(conver); } } } RongIMLib.UnreadCountHandler.clear(); setTimeout(function () { callback.onSuccess(true); isNotifyConversation && RongIMLib.RongIMClient._dataAccessProvider.Conversation._notify(RongIMLib.RongIMClient._memoryStore.conversationList); }); }; ServerDataProvider.prototype.setConversationToTop = function (conversationType, targetId, isTop, callback) { var me = this; this.getConversation(conversationType, targetId, { onSuccess: function (conver) { conver.isTop = isTop; me.addConversation(conver, callback); setTimeout(function () { callback.onSuccess(true); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.getConversationNotificationStatus = function (params, callback) { var targetId = params.targetId; var conversationType = params.conversationType; var notification = RongIMLib.RongIMClient._memoryStore.notification; var getKey = function () { return conversationType + '_' + targetId; }; var key = getKey(); var status = notification[key]; if (typeof status == 'number') { callback.onSuccess(status); return; } var topics = { 1: 'qryPPush', 3: 'qryDPush' }; var topic = topics[conversationType]; if (!topic) { var error = 8001; callback.onError(error); return; } var modules = new RongIMLib.RongIMClient.Protobuf.BlockPushInput(); modules.setBlockeeId(targetId); var userId = RongIMLib.Bridge._client.userId; var success = function (status) { notification[key] = status; setTimeout(function () { callback.onSuccess(status); }); }; RongIMLib.RongIMClient.bridge.queryMsg(topic, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function (status) { success(status); }, onError: function (e) { if (e == 1) { success(e); } else { setTimeout(function () { callback.onError(e); }); } } }); }; ServerDataProvider.prototype.setConversationNotificationStatus = function (params, callback) { var conversationType = params.conversationType; var targetId = params.targetId; var status = params.status; var getKey = function () { return conversationType + '_' + status; }; var topics = { '1_1': 'blkPPush', '3_1': 'blkDPush', '1_0': 'unblkPPush', '3_0': 'unblkDPush' }; var key = getKey(); var notification = RongIMLib.RongIMClient._memoryStore.notification; notification[key] = status; var topic = topics[key]; if (!topic) { var error = 8001; setTimeout(function () { callback.onError(error); }); return; } var modules = new RongIMLib.RongIMClient.Protobuf.BlockPushInput(); modules.setBlockeeId(targetId); var userId = RongIMLib.Bridge._client.userId; RongIMLib.RongIMClient.bridge.queryMsg(topic, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function (status) { setTimeout(function () { callback.onSuccess(status); }); }, onError: function (e) { setTimeout(function () { callback.onError(e); }); } }); }; ServerDataProvider.prototype.getUserStatus = function (userId, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.GetUserStatusInput(); userId = RongIMLib.Bridge._client.userId; RongIMLib.RongIMClient.bridge.queryMsg(35, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function (status) { status = RongIMLib.RongInnerTools.convertUserStatus(status); setTimeout(function () { callback.onSuccess(status); }); }, onError: function (e) { setTimeout(function () { callback.onError(e); }); } }, 'GetUserStatusOutput'); // callback.onSuccess(new UserStatus()); }; ServerDataProvider.prototype.setUserStatus = function (status, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.SetUserStatusInput(); var userId = RongIMLib.Bridge._client.userId; if (status) { modules.setStatus(status); } RongIMLib.RongIMClient.bridge.queryMsg(36, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function (status) { setTimeout(function () { callback.onSuccess(true); }); }, onError: function (e) { setTimeout(function () { callback.onError(e); }); } }, 'SetUserStatusOutput'); }; ServerDataProvider.prototype.subscribeUserStatus = function (userIds, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.SubUserStatusInput(); var userId = RongIMLib.Bridge._client.userId; modules.setUserid(userIds); RongIMLib.RongIMClient.bridge.queryMsg(37, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function (status) { setTimeout(function () { callback && callback.onSuccess(true); }); }, onError: function (e) { setTimeout(function () { callback && callback.onError(e); }); } }, 'SubUserStatusOutput'); }; ServerDataProvider.prototype.setUserStatusListener = function (params, callback) { RongIMLib.RongIMClient.userStatusListener = callback; var userIds = params.userIds || []; if (userIds.length) { RongIMLib.RongIMClient._dataAccessProvider.subscribeUserStatus(userIds); } }; ServerDataProvider.prototype.clearListeners = function () { }; ServerDataProvider.prototype.setServerInfo = function (info) { }; ServerDataProvider.prototype.getUnreadMentionedMessages = function (conversationType, targetId) { return null; }; ServerDataProvider.prototype.setConversationHidden = function (conversationType, targetId, isHidden) { }; ServerDataProvider.prototype.setMessageExtra = function (messageId, value, callback) { setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.setMessageReceivedStatus = function (messageId, receivedStatus, callback) { setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.setMessageSentStatus = function (messageId, sentStatus, callback) { setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.getAllConversations = function (callback) { setTimeout(function () { callback.onSuccess([]); }); }; ServerDataProvider.prototype.getConversationByContent = function (keywords, callback) { setTimeout(function () { callback.onSuccess([]); }); }; ServerDataProvider.prototype.getMessagesFromConversation = function (conversationType, targetId, keywords, callback) { setTimeout(function () { callback.onSuccess([]); }); }; ServerDataProvider.prototype.searchConversationByContent = function (keyword, callback, conversationTypes) { setTimeout(function () { callback.onSuccess([]); }); }; ServerDataProvider.prototype.searchMessageByContent = function (conversationType, targetId, keyword, timestamp, count, total, callback) { setTimeout(function () { callback.onSuccess([]); }); }; ServerDataProvider.prototype.getDelaTime = function () { return RongIMLib.RongIMClient._memoryStore.deltaTime; }; ServerDataProvider.prototype.getCurrentConnectionStatus = function () { var client = RongIMLib.Bridge._client || {}; var channel = client.channel || {}; var status = RongIMLib.ConnectionStatus.CONNECTION_CLOSED; if (typeof channel.connectionStatus == 'number') { status = channel.connectionStatus; } return status; }; ServerDataProvider.prototype.getAgoraDynamicKey = function (engineType, channelName, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.VoipDynamicInput(); modules.setEngineType(engineType); modules.setChannelName(channelName); RongIMLib.RongIMClient.bridge.queryMsg(32, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (result) { setTimeout(function () { callback.onSuccess(result); }); }, onError: function (errorCode) { setTimeout(function () { callback.onError(errorCode); }); } }, "VoipDynamicOutput"); }; ServerDataProvider.prototype.setDeviceInfo = function (deviceId) { }; ServerDataProvider.prototype.setEnvironment = function (isPrivate) { }; ServerDataProvider.prototype.clearData = function () { return true; }; ServerDataProvider.prototype.getPublicServiceProfile = function (publicServiceType, publicServiceId, callback) { var profile = RongIMLib.RongIMClient._memoryStore.publicServiceMap.get(publicServiceType, publicServiceId); setTimeout(function () { callback.onSuccess(profile); }); }; ServerDataProvider.prototype.getRemotePublicServiceList = function (callback, pullMessageTime) { if (RongIMLib.RongIMClient._memoryStore.depend.openMp) { var modules = new RongIMLib.RongIMClient.Protobuf.PullMpInput(), self = this; if (!pullMessageTime) { modules.setTime(0); } else { modules.setTime(pullMessageTime); } modules.setMpid(""); RongIMLib.RongIMClient.bridge.queryMsg(28, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (data) { //TODO 找出最大时间 // self.lastReadTime.set(conversationType + targetId, MessageUtil.int64ToTimestamp(data.syncTime)); RongIMLib.RongIMClient._memoryStore.publicServiceMap.publicServiceList.length = 0; RongIMLib.RongIMClient._memoryStore.publicServiceMap.publicServiceList = data; setTimeout(function () { callback && callback.onSuccess(data); }); }, onError: function (errorCode) { setTimeout(function () { callback && callback.onError(errorCode); }); } }, "PullMpOutput"); } }; ServerDataProvider.prototype.getRTCUserInfoList = function (room, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcQueryListInput(); // 1 是正序,2是倒序 modules.setOrder(2); RongIMLib.RongIMClient.bridge.queryMsg("rtcUData", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function (result) { var users = {}; var list = result.list; RongIMLib.RongUtil.forEach(list, function (item) { var userId = item.userId; var tmpData = {}; RongIMLib.RongUtil.forEach(item.userData, function (data) { var key = data.key; var value = data.value; tmpData[key] = value; }); users[userId] = tmpData; }); callback.onSuccess(users); }, onError: function (errorCode) { callback.onError(errorCode); } }, "RtcUserListOutput"); }; ServerDataProvider.prototype.getRTCUserList = function (room, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcQueryListInput(); modules.setOrder(2); RongIMLib.RongIMClient.bridge.queryMsg("rtcUList", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function (result) { callback.onSuccess({ users: result.list }); }, onError: function (errorCode) { callback.onError(errorCode); } }, "RtcUserListOutput"); }; ServerDataProvider.prototype.setRTCUserInfo = function (room, info, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcValueInfo(); modules.setKey(info.key); modules.setValue(info.value); RongIMLib.RongIMClient.bridge.queryMsg("rtcUPut", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function () { callback.onSuccess(true); }, onError: function (errorCode) { callback.onError(errorCode); } }); }; ServerDataProvider.prototype.removeRTCUserInfo = function (room, info, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcKeyDeleteInput(); var keys = info.keys || []; if (!RongIMLib.RongUtil.isArray(keys)) { keys = [keys]; } modules.setKey(keys); RongIMLib.RongIMClient.bridge.queryMsg("rtcUDel", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function () { callback.onSuccess(true); }, onError: function (errorCode) { callback.onError(errorCode); } }); }; ServerDataProvider.prototype.getRTCRoomInfo = function (room, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcQueryListInput(); modules.setOrder(2); RongIMLib.RongIMClient.bridge.queryMsg("rtcRInfo", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function (result) { var room = { id: result.roomId, total: result.userCount }; RongIMLib.RongUtil.forEach(result.roomData, function (data) { room[data.key] = data.value; }); callback.onSuccess(room); }, onError: function (errorCode) { callback.onError(errorCode); } }, "RtcRoomInfoOutput"); }; ServerDataProvider.prototype.setRTCRoomInfo = function (room, info, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcValueInfo(); modules.setKey(info.key); modules.setValue(info.value); RongIMLib.RongIMClient.bridge.queryMsg("rtcRPut", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function () { callback.onSuccess(true); }, onError: function (errorCode) { callback.onError(errorCode); } }); }; ServerDataProvider.prototype.removeRTCRoomInfo = function (room, info, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcKeyDeleteInput(); var keys = info.keys || []; if (!RongIMLib.RongUtil.isArray(keys)) { keys = [keys]; } modules.setKey(keys); RongIMLib.RongIMClient.bridge.queryMsg("rtcRDel", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function () { callback.onSuccess(true); }, onError: function (errorCode) { callback.onError(errorCode); } }); }; ServerDataProvider.prototype.joinRTCRoom = function (room, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcInput(); var mode = room.mode || 0; modules.setRoomType(mode); if (room.broadcastType) { modules.setBroadcastType(room.broadcastType); } RongIMLib.RongIMClient.bridge.queryMsg("rtcRJoin_data", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function (result) { var users = {}; var list = result.list, token = result.token, sessionId = result.sessionId; RongIMLib.RongUtil.forEach(list, function (item) { var userId = item.userId; var tmpData = {}; RongIMLib.RongUtil.forEach(item.userData, function (data) { var key = data.key; var value = data.value; tmpData[key] = value; }); users[userId] = tmpData; }); callback.onSuccess({ users: users, token: token, sessionId: sessionId }); }, onError: function (errorCode) { callback.onError(errorCode); } }, "RtcUserListOutput"); }; ServerDataProvider.prototype.quitRTCRoom = function (room, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.SetUserStatusInput(); RongIMLib.RongIMClient.bridge.queryMsg("rtcRExit", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function () { callback.onSuccess(true); }, onError: function (errorCode) { callback.onError(errorCode); } }); }; ServerDataProvider.prototype.RTCPing = function (room, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcInput(); var mode = room.mode || 0; modules.setRoomType(mode); if (room.broadcastType) { modules.setBroadcastType(room.broadcastType); } RongIMLib.RongIMClient.bridge.queryMsg("rtcPing", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, callback); }; ServerDataProvider.prototype.setRTCData = function (roomId, key, value, isInner, apiType, callback, message) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcSetDataInput(); modules.setInterior(isInner); modules.setTarget(apiType); modules.setKey(key); modules.setValue(value); message = message || {}; var name = message.name; var content = message.content; if (name) { modules.setObjectName(name); } if (content) { if (!RongIMLib.RongUtil.isString(content)) { content = JSON.stringify(content); } modules.setContent(content); } RongIMLib.RongIMClient.bridge.queryMsg("rtcSetData", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), roomId, callback, "RtcOutput"); }; ServerDataProvider.prototype.getRTCData = function (roomId, keys, isInner, apiType, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcDataInput(); modules.setInterior(isInner); modules.setTarget(apiType); modules.setKey(keys); RongIMLib.RongIMClient.bridge.queryMsg("rtcQryData", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), roomId, { onSuccess: function (result) { var props = {}; var list = result.outInfo; RongIMLib.RongUtil.forEach(list, function (item) { props[item.key] = item.value; }); callback.onSuccess(props); }, onError: callback.onError }, "RtcQryOutput"); }; ServerDataProvider.prototype.removeRTCData = function (roomId, keys, isInner, apiType, callback, message) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcDataInput(); modules.setInterior(isInner); modules.setTarget(apiType); modules.setKey(keys); message = message || {}; var name = message.name; var content = message.content; if (name) { modules.setObjectName(name); } if (content) { if (!RongIMLib.RongUtil.isString(content)) { content = JSON.stringify(content); } modules.setContent(content); } RongIMLib.RongIMClient.bridge.queryMsg("rtcDelData", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), roomId, callback, "RtcOutput"); }; ServerDataProvider.prototype.setRTCUserData = function (roomId, key, value, isInner, callback, message) { this.setRTCData(roomId, key, value, isInner, RongIMLib.RTCAPIType.PERSON, callback, message); }; ServerDataProvider.prototype.getRTCUserData = function (roomId, keys, isInner, callback, message) { this.getRTCData(roomId, keys, isInner, RongIMLib.RTCAPIType.PERSON, callback); }; ServerDataProvider.prototype.removeRTCUserData = function (roomId, keys, isInner, callback, message) { this.removeRTCData(roomId, keys, isInner, RongIMLib.RTCAPIType.PERSON, callback, message); }; ServerDataProvider.prototype.setRTCRoomData = function (roomId, key, value, isInner, callback, message) { this.setRTCData(roomId, key, value, isInner, RongIMLib.RTCAPIType.ROOM, callback, message); }; ServerDataProvider.prototype.getRTCRoomData = function (roomId, keys, isInner, callback, message) { this.getRTCData(roomId, keys, isInner, RongIMLib.RTCAPIType.ROOM, callback); }; ServerDataProvider.prototype.removeRTCRoomData = function (roomId, keys, isInner, callback, message) { this.removeRTCData(roomId, keys, isInner, RongIMLib.RTCAPIType.ROOM, callback, message); }; // 信令 SDK 新增 ServerDataProvider.prototype.setRTCOutData = function (roomId, data, type, callback, message) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcSetOutDataInput(); modules.setTarget(type); if (!RongIMLib.RongUtil.isArray(data)) { data = [data]; } for (var i = 0; i < data.length; i++) { var item = data[i]; if (item.key) { item.key = item.key.toString(); } if (item.value) { item.value = item.value.toString(); } } modules.setValueInfo(data); message = message || {}; var name = message.name; var content = message.content; if (name) { modules.setObjectName(name); } if (content) { if (!RongIMLib.RongUtil.isString(content)) { content = JSON.stringify(content); } modules.setContent(content); } RongIMLib.RongIMClient.bridge.queryMsg("rtcSetOutData", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), roomId, callback, "RtcOutput"); }; // 信令 SDK 新增 ServerDataProvider.prototype.getRTCOutData = function (roomId, userIds, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcQryUserOutDataInput(); modules.setUserId(userIds); RongIMLib.RongIMClient.bridge.queryMsg("rtcQryUserOutData", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), roomId, callback, "RtcUserOutDataOutput"); }; ServerDataProvider.prototype.getNavi = function () { var navi = RongIMLib.RongIMClient._storageProvider.getItem("fullnavi") || "{}"; return JSON.parse(navi); }; ServerDataProvider.prototype.getRTCToken = function (room, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcInput(); var mode = room.mode || 0; modules.setRoomType(mode); if (room.broadcastType) { modules.setBroadcastType(room.broadcastType); } RongIMLib.RongIMClient.bridge.queryMsg("rtcToken", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function (result) { callback.onSuccess(result); }, onError: function (errorCode) { callback.onError(errorCode); } }, "RtcTokenOutput"); }; ServerDataProvider.prototype.setRTCState = function (room, content, callback) { // MCFollowInput 为 PB 复用,字段:一个必传 string(第一位) var modules = new RongIMLib.RongIMClient.Protobuf.MCFollowInput(); var report = content.report; modules.setId(report); RongIMLib.RongIMClient.bridge.queryMsg("rtcUserState", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function (result) { callback.onSuccess(result); }, onError: function (errorCode) { callback.onError(errorCode); } }, "RtcOutput"); }; return ServerDataProvider; })(); RongIMLib.ServerDataProvider = ServerDataProvider; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var VCDataProvider = (function () { function VCDataProvider(addon) { this.Conversation = { watcher: new RongIMLib.Observer(), watch: function (_watcher) { }, unwatch: function (_watcher) { }, _notify: function (conversationList) { } }; // C++ 需要的 SDK 版本号 this.version = '2.8.27'; this.userId = ""; this.useConsole = false; this.appKey = ""; this.token = ""; this.addon = addon; } VCDataProvider.prototype.init = function (appKey, config) { this.appKey = appKey; this.useConsole && console.log("init"); config = config || {}; config.version = this.version; var sdkInfo = this.addon.initWithAppkey(appKey, config.dbPath, config); if (sdkInfo) { sdkInfo = JSON.parse(sdkInfo); } // 0 不存不计数 1 只存不计数 3 存且计数 this.addon.registerMessageType("RC:VcMsg", 3); this.addon.registerMessageType("RC:ImgTextMsg", 3); this.addon.registerMessageType("RC:FileMsg", 3); this.addon.registerMessageType("RC:LBSMsg", 3); this.addon.registerMessageType("RC:PSImgTxtMsg", 3); this.addon.registerMessageType("RC:PSMultiImgTxtMsg", 3); this.addon.registerMessageType("RCJrmf:RpMsg", 3); this.addon.registerMessageType("RCJrmf:RpOpendMsg", 1); this.addon.registerMessageType("RC:GrpNtf", 1); this.addon.registerMessageType("RC:DizNtf", 0); this.addon.registerMessageType("RC:InfoNtf", 0); this.addon.registerMessageType("RC:ContactNtf", 0); this.addon.registerMessageType("RC:ProfileNtf", 0); this.addon.registerMessageType("RC:CmdNtf", 0); this.addon.registerMessageType("RC:CmdMsg", 0); this.addon.registerMessageType("RC:TypSts", 0); this.addon.registerMessageType("RC:CsChaR", 0); this.addon.registerMessageType("RC:CsHsR", 0); this.addon.registerMessageType("RC:CsEnd", 0); this.addon.registerMessageType("RC:CsSp", 0); this.addon.registerMessageType("RC:CsUpdate", 0); this.addon.registerMessageType("RC:CsContact", 0); this.addon.registerMessageType("RC:ReadNtf", 0); this.addon.registerMessageType("RC:VCAccept", 0); this.addon.registerMessageType("RC:VCRinging", 0); this.addon.registerMessageType("RC:VCSummary", 0); this.addon.registerMessageType("RC:VCHangup", 0); this.addon.registerMessageType("RC:VCInvite", 0); this.addon.registerMessageType("RC:VCModifyMedia", 0); this.addon.registerMessageType("RC:VCModifyMem", 0); this.addon.registerMessageType("RC:PSCmd", 0); this.addon.registerMessageType("RC:RcCmd", 0); this.addon.registerMessageType("RC:SRSMsg", 0); this.addon.registerMessageType("RC:RRReqMsg", 0); this.addon.registerMessageType("RC:RRRspMsg", 0); return sdkInfo; }; VCDataProvider.prototype.connect = function (token, callback, userId, serverConf) { this.useConsole && console.log("connect"); this.userId = userId; this.connectCallback = callback; RongIMLib.Bridge._client = { userId: userId }; serverConf = serverConf || {}; var openmp = !!serverConf.openMp; var openus = !!serverConf.openUS; if (serverConf.type) { this.addon.setEnvironment(true); } this.addon.connectWithToken(token, userId, serverConf.serverList, openmp, openus); }; VCDataProvider.prototype.setServerInfo = function (info) { 'setServerInfo' in this.addon && this.addon.setServerInfo(info.navi); }; VCDataProvider.prototype.logout = function () { this.useConsole && console.log("logout"); this.disconnect(); }; VCDataProvider.prototype.disconnect = function () { this.useConsole && console.log("disconnect"); this.addon.disconnect(true); }; VCDataProvider.prototype.clearListeners = function () { this.addon.setOnReceiveStatusListener(); this.addon.setConnectionStatusListener(); this.addon.setOnReceiveMessageListener(); }; VCDataProvider.prototype.clearData = function () { this.useConsole && console.log("clearData"); return this.addon.clearData(); }; VCDataProvider.prototype.setConnectionStatusListener = function (listener) { var me = this; /** ConnectionStatus_TokenIncorrect = 31004, ConnectionStatus_Connected = 0, ConnectionStatus_KickedOff = 6, // 其他设备登录 ConnectionStatus_Connecting = 10,// 连接中 ConnectionStatus_SignUp = 12, // 未登录 ConnectionStatus_NetworkUnavailable = 1, // 连接断开 ConnectionStatus_ServerInvalid = 8, // 断开 ConnectionStatus_ValidateFailure = 9,//断开 ConnectionStatus_Unconnected = 11,//断开 ConnectionStatus_DisconnExecption = 31011 //断开 RC_NAVI_MALLOC_ERROR = 30000,//断开 RC_NAVI_NET_UNAVAILABLE= 30002,//断开 RC_NAVI_SEND_FAIL = 30004,//断开 RC_NAVI_REQ_TIMEOUT = 30005,//断开 RC_NAVI_RECV_FAIL = 30006,//断开 RC_NAVI_RESOURCE_ERROR = 30007,//断开 RC_NAVI_NODE_NOT_FOUND = 30008,//断开 RC_NAVI_DNS_ERROR = 30009,//断开 */ me.connectListener = listener; this.useConsole && console.log("setConnectionStatusListener"); me.addon && me.addon.setConnectionStatusListener(function (result) { switch (result) { case 10: setTimeout(function () { listener.onChanged(RongIMLib.ConnectionStatus.CONNECTING); }); break; case 31004: setTimeout(function () { me.connectCallback.onTokenIncorrect(); }); break; case 1: case 8: case 9: case 11: case 12: case 31011: case 30000: case 30002: setTimeout(function () { listener.onChanged(RongIMLib.ConnectionStatus.DISCONNECTED); }); break; case 0: case 33005: setTimeout(function () { me.connectCallback.onSuccess(me.userId); listener.onChanged(RongIMLib.ConnectionStatus.CONNECTED); }); break; case 6: setTimeout(function () { listener.onChanged(RongIMLib.ConnectionStatus.KICKED_OFFLINE_BY_OTHER_CLIENT); }); break; default: setTimeout(function () { listener.onChanged(result); }); break; } }); }; VCDataProvider.prototype.setOnReceiveMessageListener = function (listener) { var me = this, localCount = 0; me.messageListener = listener; this.useConsole && console.log("setOnReceiveMessageListener"); me.addon && me.addon.setOnReceiveMessageListener(function (result, leftCount, offline, hasMore) { var message = me.buildMessage(result); message.offLineMessage = offline; setTimeout(function () { var voipMsgTypes = ['AcceptMessage', 'RingingMessage', 'HungupMessage', 'InviteMessage', 'MediaModifyMessage', 'MemberModifyMessage']; var isVoIPMsg = voipMsgTypes.indexOf(message.messageType) > -1; if (isVoIPMsg) { RongIMLib.RongIMClient._voipProvider && RongIMLib.RongIMClient._voipProvider.onReceived(message); } else if (message.conversationType == 12) { RongIMLib.RongIMClient.RTCListener(message); RongIMLib.RongIMClient.RTCInnerListener(message); RongIMLib.RongIMClient.RTCSignalLisener(message); } else { listener.onReceived(message, leftCount, hasMore); } }); }); }; VCDataProvider.prototype.sendTypingStatusMessage = function (conversationType, targetId, messageName, sendCallback) { var me = this; this.useConsole && console.log("sendTypingStatusMessage"); if (messageName in RongIMLib.RongIMClient.MessageParams) { me.sendMessage(conversationType, targetId, RongIMLib.TypingStatusMessage.obtain(RongIMLib.RongIMClient.MessageParams[messageName].objectName, ""), { onSuccess: function () { setTimeout(function () { sendCallback.onSuccess(); }); }, onError: function (errorCode) { setTimeout(function () { sendCallback.onError(errorCode, null); }); }, onBefore: function () { } }); } }; VCDataProvider.prototype.setMessageStatus = function (conversationType, targetId, timestamp, status, callback) { this.addon.updateMessageReceiptStatus(conversationType, targetId, timestamp); callback.onSuccess(true); }; VCDataProvider.prototype.sendTextMessage = function (conversationType, targetId, content, sendMessageCallback) { var msgContent = RongIMLib.TextMessage.obtain(content); this.useConsole && console.log("sendTextMessage"); this.sendMessage(conversationType, targetId, msgContent, sendMessageCallback); }; VCDataProvider.prototype.getRemoteHistoryMessages = function (conversationType, targetId, timestamp, count, callback, config) { try { var me = this; me.useConsole && console.log("getRemoteHistoryMessages"); me.addon.getRemoteHistoryMessages(conversationType, targetId, timestamp ? timestamp : 0, count, function (ret, hasMore) { var list = ret ? JSON.parse(ret).list : [], msgs = []; list.reverse(); for (var i = 0, len = list.length; i < len; i++) { var message = me.buildMessage(list[i].obj); message.sentStatus = RongIMLib.SentStatus.READ; msgs[i] = message; } callback.onSuccess(msgs, hasMore ? true : false); }, function (errorCode) { callback.onError(errorCode); }); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.getRemoteConversationList = function (callback, conversationTypes, count, isGetHiddenConvers) { try { this.useConsole && console.log("getRemoteConversationList"); var converTypes = conversationTypes || [1, 2, 3, 4, 5, 6, 7, 8]; var result = this.addon.getConversationList(converTypes); var list = JSON.parse(result).list, convers = [], me = this, index = 0; list.reverse(); isGetHiddenConvers = typeof isGetHiddenConvers === 'boolean' ? isGetHiddenConvers : false; for (var i = 0, len_1 = list.length; i < len_1; i++) { var tmpObj = list[i].obj, obj = JSON.parse(tmpObj); if (obj != "") { if (obj.isHidden == 1 && isGetHiddenConvers) { continue; } convers[index] = me.buildConversation(tmpObj); index++; } } convers.reverse(); var len = convers.length; count = count || len; if (len > count) { convers.length = count; } callback.onSuccess(convers); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.removeConversation = function (conversationType, targetId, callback) { try { this.useConsole && console.log("removeConversation"); this.addon.removeConversation(conversationType, targetId); var conversations = RongIMLib.RongIMClient._memoryStore.conversationList; var len = conversations.length; for (var i = 0; i < len; i++) { if (conversations[i].conversationType == conversationType && targetId == conversations[i].targetId) { conversations.splice(i, 1); break; } } callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.joinChatRoom = function (chatRoomId, messageCount, callback) { this.useConsole && console.log("joinChatRoom"); this.addon.joinChatRoom(chatRoomId, messageCount, function () { callback.onSuccess(); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.quitChatRoom = function (chatRoomId, callback) { this.useConsole && console.log("quitChatRoom"); this.addon.quitChatRoom(chatRoomId, function () { callback.onSuccess(); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.setChatroomEntry = function (chatroomId, chatroomEntry, callback) { }; VCDataProvider.prototype.forceSetChatroomEntry = function (chatroomId, chatroomEntry, callback) { }; VCDataProvider.prototype.getChatroomEntry = function (chatroomId, key, callback) { }; VCDataProvider.prototype.getAllChatroomEntries = function (chatroomId, callback) { }; VCDataProvider.prototype.removeChatroomEntry = function (chatroomId, chatroomEntry, callback) { }; VCDataProvider.prototype.forceRemoveChatroomEntry = function (chatroomId, chatroomEntry, callback) { }; VCDataProvider.prototype.pullChatroomEntry = function (chatroomId, time, callback) { }; VCDataProvider.prototype.addToBlacklist = function (userId, callback) { this.useConsole && console.log("addToBlacklist"); this.addon.addToBlacklist(userId, function () { callback.onSuccess(); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.getBlacklist = function (callback) { this.useConsole && console.log("getBlacklist"); this.addon.getBlacklist(function (blacklistors) { callback.onSuccess(blacklistors); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.getBlacklistStatus = function (userId, callback) { this.useConsole && console.log("getBlacklistStatus"); this.addon.getBlacklistStatus(userId, function (result) { callback.onSuccess(result); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.removeFromBlacklist = function (userId, callback) { this.useConsole && console.log("removeFromBlacklist"); this.addon.removeFromBlacklist(userId, function () { callback.onSuccess(); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.sendMessage = function (conversationType, targetId, messageContent, sendCallback, mentiondMsg, pushText, appData, methodType, params) { var me = this, users = []; me.useConsole && console.log("sendMessage"); params = params || {}; var isGroup = (conversationType == RongIMLib.ConversationType.DISCUSSION || conversationType == RongIMLib.ConversationType.GROUP); if (isGroup && messageContent.messageName == RongIMLib.RongIMClient.MessageType["ReadReceiptResponseMessage"]) { users = []; var rspMsg = messageContent; if (rspMsg.receiptMessageDic) { var ids = []; for (var key in rspMsg.receiptMessageDic) { ids.push(key); } users = ids; } } if (isGroup && messageContent.messageName == RongIMLib.RongIMClient.MessageType["SyncReadStatusMessage"]) { users = []; users.push(me.userId); } var userIds = params.userIds; if (isGroup && userIds) { users = userIds; } var msg = me.addon.sendMessage(conversationType, targetId, RongIMLib.RongIMClient.MessageParams[messageContent.messageName].objectName, messageContent.encode(), pushText || "", appData || "", function (progress) { }, function (message, code) { var msg = me.buildMessage(message); var errorCode = RongIMLib.ErrorCode.SENSITIVE_REPLACE; if (code == errorCode) { return sendCallback.onError(errorCode, msg); } sendCallback.onSuccess(msg); }, function (message, code) { sendCallback.onError(code, me.buildMessage(message)); }, users, mentiondMsg); var tempMessage = JSON.parse(msg); sendCallback.onBefore && sendCallback.onBefore(tempMessage.messageId); RongIMLib.MessageIdHandler.messageId = tempMessage.messageId; }; VCDataProvider.prototype.registerMessageType = function (messageType, objectName, messageTag, messageContent, searchProps) { this.useConsole && console.log("registerMessageType"); this.addon.registerMessageType(objectName, messageTag.getMessageTag(), searchProps); var regMsg = RongIMLib.ModelUtil.modleCreate(messageContent, messageType); RongIMLib.RongIMClient.RegisterMessage[messageType] = regMsg; RongIMLib.RongIMClient.RegisterMessage[messageType].messageName = messageType; registerMessageTypeMapping[objectName] = messageType; RongIMLib.RongIMClient.MessageType[messageType] = messageType; RongIMLib.RongIMClient.MessageParams[messageType] = { objectName: objectName, msgTag: messageTag }; typeMapping[objectName] = messageType; }; VCDataProvider.prototype.registerMessageTypes = function (messages) { var types = []; var getProtos = function (proto) { var protos = []; for (var p in proto) { protos.push(p); } return protos; }; //转换消息为自定义消息参数格式 for (var name in messages) { var message = messages[name]; var proto = message.proto; var protos = getProtos(proto); var flag = message.flag || 3; var tag = RongIMLib.MessageTag.getTagByStatus(flag); flag = new RongIMLib.MessageTag(tag.isCounted, tag.isPersited); types.push({ type: name, name: message.name, flag: flag, protos: protos }); } var register = function (message) { var type = message.type; var name = message.name; var flag = message.flag; var protos = message.protos; RongIMLib.RongIMClient.registerMessageType(type, name, flag, protos); }; for (var i = 0, len = types.length; i < len; i++) { var message = types[i]; register(message); } }; VCDataProvider.prototype.addMessage = function (conversationType, targetId, message, callback) { this.useConsole && console.log("addMessage"); var direction = message.direction; var msg = this.addon.insertMessage(conversationType, targetId, message.senderUserId, message.objectName, JSON.stringify(message.content), function () { callback.onSuccess(me.buildMessage(msg)); }, function () { callback.onError(RongIMLib.ErrorCode.MSG_INSERT_ERROR); }, direction), me = this; }; VCDataProvider.prototype.removeMessage = function (conversationType, targetId, messages, callback) { }; VCDataProvider.prototype.deleteRemoteMessages = function (conversationType, targetId, messages, callback) { }; VCDataProvider.prototype.removeLocalMessage = function (conversationType, targetId, timestamps, callback) { try { this.useConsole && console.log("removeLocalMessage"); this.addon.deleteMessages(timestamps); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.getMessage = function (messageId, callback) { try { this.useConsole && console.log("getMessage"); var msg = this.buildMessage(this.addon.getMessage(messageId)); callback.onSuccess(msg); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.clearMessages = function (conversationType, targetId, callback) { try { this.useConsole && console.log("clearMessages"); this.addon.clearMessages(conversationType, targetId); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; // Web 端接口,桌面版无需实现 VCDataProvider.prototype.setUnreadCount = function (conversationType, targetId, count) { }; VCDataProvider.prototype.getConversation = function (conversationType, targetId, callback) { try { this.useConsole && console.log("getConversation"); var ret = this.addon.getConversation(conversationType, targetId); callback.onSuccess(this.buildConversation(ret)); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.getConversationList = function (callback, conversationTypes, count, isGetHiddenConvers) { this.useConsole && console.log("getConversationList"); this.getRemoteConversationList(callback, conversationTypes, count, isGetHiddenConvers); }; VCDataProvider.prototype.clearCache = function () { var memoryStore = RongIMLib.RongIMClient._memoryStore || {}; memoryStore.conversationList = []; memoryStore.isSyncRemoteConverList; }; VCDataProvider.prototype.clearConversations = function (conversationTypes, callback) { try { this.useConsole && console.log("clearConversations"); this.addon.clearConversations(); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.setMessageContent = function (messageId, content, objectName) { content = JSON.stringify(content); this.addon.setMessageContent(messageId, content, objectName); }; VCDataProvider.prototype.setMessageSearchField = function (messageId, content, searchFiles) { content = JSON.stringify(content); this.addon.setMessageContent(messageId, content, searchFiles); }; VCDataProvider.prototype.getHistoryMessages = function (conversationType, targetId, timestamp, count, callback, objectname, direction) { this.useConsole && console.log("getHistoryMessages"); if (count <= 0) { callback.onError(RongIMLib.ErrorCode.TIMEOUT); return; } objectname = objectname || ''; direction = typeof direction == 'undefined' || direction; try { var ret = this.addon.getHistoryMessages(conversationType, targetId, timestamp ? timestamp : 0, count, objectname, direction); var list = ret ? JSON.parse(ret).list : [], msgs = [], me = this; list.reverse(); for (var i = 0, len = list.length; i < len; i++) { var message = me.buildMessage(list[i].obj); msgs[i] = message; } callback.onSuccess(msgs, len == count); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.clearRemoteHistoryMessages = function (params, callback) { var conversationType = params.conversationType; var targetId = params.targetId; var timestamp = params.timestamp; var _topic = { 1: true, 2: true, 3: true, 5: true, 6: true }; var topic = _topic[conversationType]; if (!topic) { callback.onError(RongIMLib.ErrorCode.CLEAR_HIS_TYPE_ERROR); return; } if (typeof timestamp != 'number') { callback.onError(RongIMLib.ErrorCode.CLEAR_HIS_TIME_ERROR); return; } this.addon.clearRemoteHistoryMessages(+conversationType, targetId, timestamp, function () { callback.onSuccess(true); }, function (errorCode) { if (errorCode == 1) { // 没有开通历史消息云存储 errorCode = RongIMLib.ErrorCode.CLEAR_HIS_ERROR; } callback.onError(errorCode); }); }; VCDataProvider.prototype.clearHistoryMessages = function (params, callback) { var conversationType = +params.conversationType; var targetId = params.targetId; try { this.addon.clearMessages(conversationType, targetId); var isSuccess = true; callback.onSuccess(isSuccess); } catch (e) { console.log(e); callback.onError(RongIMLib.ErrorCode.CLEAR_HIS_ERROR); } }; VCDataProvider.prototype.getTotalUnreadCount = function (callback, conversationTypes) { try { var result; this.useConsole && console.log("getTotalUnreadCount"); if (conversationTypes) { result = this.addon.getTotalUnreadCount(conversationTypes); } else { result = this.addon.getTotalUnreadCount(); } callback.onSuccess(result); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.getConversationUnreadCount = function (conversationTypes, callback) { this.useConsole && console.log("getConversationUnreadCount"); this.getTotalUnreadCount(callback, conversationTypes); }; VCDataProvider.prototype.getUnreadCount = function (conversationType, targetId, callback) { try { this.useConsole && console.log("getUnreadCount"); var result = this.addon.getUnreadCount(conversationType, targetId); callback.onSuccess(result); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.clearUnreadCount = function (conversationType, targetId, callback) { try { this.useConsole && console.log("clearUnreadCount"); var result = this.addon.clearUnreadCount(conversationType, targetId); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.clearTotalUnreadCount = function (callback) { this.useConsole && console.log("clearTotalUnreadCount"); }; VCDataProvider.prototype.clearUnreadCountByTimestamp = function (conversationType, targetId, timestamp, callback) { try { this.useConsole && console.log("clearUnreadCountByTimestamp"); var result = this.addon.clearUnreadCountByTimestamp(conversationType, targetId, timestamp); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.setConversationToTop = function (conversationType, targetId, isTop, callback) { try { this.useConsole && console.log("setConversationToTop"); this.addon.setConversationToTop(conversationType, targetId, isTop); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.setConversationHidden = function (conversationType, targetId, isHidden) { this.addon.setConversationHidden(conversationType, targetId, isHidden); }; VCDataProvider.prototype.setMessageReceivedStatus = function (messageId, receivedStatus, callback) { try { this.useConsole && console.log("setMessageReceivedStatus"); this.addon.setMessageReceivedStatus(messageId, receivedStatus); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.setMessageSentStatus = function (messageId, sentStatus, callback) { try { this.useConsole && console.log("setMessageSentStatus"); this.addon.setMessageSentStatus(messageId, sentStatus); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.getFileToken = function (fileType, callback) { this.useConsole && console.log("getFileToken"); this.addon.getUploadToken(fileType, function (token) { callback.onSuccess({ token: token }); }, function (errorCode) { callback.onError(errorCode); }); }; VCDataProvider.prototype.getFileUrl = function (fileType, fileName, oriName, callback) { this.useConsole && console.log("getFileUrl"); this.addon.getDownloadUrl(fileType, fileName, oriName, function (url) { callback.onSuccess({ downloadUrl: url }); }, function (errorCode) { callback.onError(errorCode); }); }; VCDataProvider.prototype.getPullSetting = function (callback) { this.useConsole && console.log("getPullSetting"); }; VCDataProvider.prototype.setOfflineMessageDuration = function (duration, callback) { this.useConsole && console.log("setOfflineMessageDuration"); }; VCDataProvider.prototype.searchConversationByContent = function (keyword, callback, conversationTypes) { var converTypes = []; if (typeof conversationTypes == 'undefined') { converTypes = [1, 2, 3, 4, 5, 6, 7]; } else { converTypes = conversationTypes; } try { this.useConsole && console.log("searchConversationByContent"); var result = this.addon.searchConversationByContent(converTypes, keyword); var list = JSON.parse(result).list, convers = [], me = this; list.reverse(); for (var i = 0, len = list.length; i < len; i++) { convers[i] = me.buildConversation(list[i].obj); } callback.onSuccess(convers); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.searchMessageByContent = function (conversationType, targetId, keyword, timestamp, count, total, callback) { var me = this; try { this.useConsole && console.log("searchMessageByContent"); this.addon.searchMessageByContent(conversationType, targetId, keyword, timestamp, count, total, function (ret, matched) { var list = ret ? JSON.parse(ret).list : [], msgs = []; list.reverse(); for (var i = 0, len = list.length; i < len; i++) { msgs[i] = me.buildMessage(list[i].obj); } callback.onSuccess(msgs, matched); }); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.getChatRoomInfo = function (chatRoomId, count, order, callback) { this.useConsole && console.log("getChatRoomInfo"); this.addon.getChatroomInfo(chatRoomId, count, order, function (ret, count) { var list = ret ? JSON.parse(ret).list : [], chatRoomInfo = { userInfos: [], userTotalNums: count }; if (list.length > 0) { for (var i = 0, len = list.length; i < len; i++) { chatRoomInfo.userInfos.push(JSON.parse(list[i].obj)); } } callback.onSuccess(chatRoomInfo); }, function (errcode) { callback.onError(errcode); }); }; VCDataProvider.prototype.setChatroomHisMessageTimestamp = function (chatRoomId, timestamp) { }; VCDataProvider.prototype.getChatRoomHistoryMessages = function (chatRoomId, count, order, callback) { }; VCDataProvider.prototype.getDelaTime = function () { return this.addon.getDeltaTime(); }; VCDataProvider.prototype.getUserStatus = function (userId, callback) { var me = this; this.addon.getUserStatus(userId, function (status) { var entity = RongIMLib.RongInnerTools.convertUserStatus({ status: status, userId: '' }); callback.onSuccess(entity); }, function (code) { callback.onError(code); }); }; VCDataProvider.prototype.setUserStatus = function (status, callback) { this.addon.setUserStatus(status, function () { callback.onSuccess(true); }, function (code) { callback.onError(code); }); }; VCDataProvider.prototype.subscribeUserStatus = function (userIds, callback) { this.addon.subscribeUserStatus(userIds, function () { callback && callback.onSuccess(true); }, function (code) { callback && callback.onError(code); }); }; VCDataProvider.prototype.setUserStatusListener = function (params, callback) { var me = this; this.addon.setOnReceiveStatusListener(function (userId, status) { var entity = RongIMLib.RongInnerTools.convertUserStatus({ userId: userId, status: status }); RongIMLib.RongIMClient.userStatusObserver.notify({ key: userId, entity: entity }); }); var userIds = params.userIds || []; if (userIds.length) { RongIMLib.RongIMClient._dataAccessProvider.subscribeUserStatus(userIds); } }; VCDataProvider.prototype.getUnreadMentionedMessages = function (conversationType, targetId) { var me = this; var mentions = JSON.parse(me.addon.getUnreadMentionedMessages(conversationType, targetId)).list; for (var i = 0, len = mentions.length; i < len; i++) { var temp = JSON.parse(mentions[i].obj); temp.content = JSON.parse(temp.content); mentions[i] = temp; } return mentions; }; VCDataProvider.prototype.hasRemoteUnreadMessages = function (token, callback) { callback.onSuccess(false); }; VCDataProvider.prototype.sendRecallMessage = function (content, sendMessageCallback) { var me = this; me.addon.recallMessage("RC:RcCmd", JSON.stringify(content), content.push || "", function () { content.objectName = 'RC:RcCmd'; sendMessageCallback.onSuccess(me.buildMessage(JSON.stringify(content))); }, function (errorCode) { sendMessageCallback.onError(errorCode); }); }; VCDataProvider.prototype.updateMessage = function (message, callback) { }; VCDataProvider.prototype.updateMessages = function (conversationType, targetId, key, value, callback) { }; VCDataProvider.prototype.reconnect = function (callback) { }; VCDataProvider.prototype.sendReceiptResponse = function (conversationType, targetId, sendCallback) { }; VCDataProvider.prototype.setMessageExtra = function (messageId, value, callback) { }; VCDataProvider.prototype.addMemberToDiscussion = function (discussionId, userIdList, callback) { }; VCDataProvider.prototype.createDiscussion = function (name, userIdList, callback) { }; VCDataProvider.prototype.getDiscussion = function (discussionId, callback) { }; VCDataProvider.prototype.quitDiscussion = function (discussionId, callback) { }; VCDataProvider.prototype.removeMemberFromDiscussion = function (discussionId, userId, callback) { }; VCDataProvider.prototype.setDiscussionInviteStatus = function (discussionId, status, callback) { }; VCDataProvider.prototype.setDiscussionName = function (discussionId, name, callback) { }; VCDataProvider.prototype.setEnvironment = function (isPrivate) { this.addon.setEnvironment(isPrivate); }; VCDataProvider.prototype.addConversation = function (conversation, callback) { }; VCDataProvider.prototype.updateConversation = function (conversation) { return null; }; VCDataProvider.prototype.getConversationNotificationStatus = function (params, callback) { var conversationType = params.conversationType; var targetId = params.targetId; var notification = RongIMLib.RongIMClient._memoryStore.notification; var key = conversationType + '_' + targetId; var status = notification[key]; if (typeof status == 'number') { callback.onSuccess(status); return; } this.addon.getConversationNotificationStatus(conversationType, targetId, function (status) { notification[key] = status; callback.onSuccess(status); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.setConversationNotificationStatus = function (params, callback) { var conversationType = params.conversationType; var targetId = params.targetId; var status = params.status; var notification = RongIMLib.RongIMClient._memoryStore.notification; var key = conversationType + '_' + targetId; notification[key] = status; var notify = !!status; this.addon.setConversationNotificationStatus(conversationType, targetId, notify, function () { callback.onSuccess(status); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.getCurrentConnectionStatus = function () { return this.addon.getConnectionStatus(); }; VCDataProvider.prototype.getAgoraDynamicKey = function (engineType, channelName, callback) { var extra = ""; this.addon.getVoIPKey(engineType, channelName, extra, function (token) { callback.onSuccess(token); }, function (errorCode) { callback.onError(errorCode); }); }; VCDataProvider.prototype.getPublicServiceProfile = function (publicServiceType, publicServiceId, callback) { var profile = RongIMLib.RongIMClient._memoryStore.publicServiceMap.get(publicServiceType, publicServiceId); callback.onSuccess(profile); }; VCDataProvider.prototype.setDeviceInfo = function (device) { var id = device.id || ''; this.addon.setDeviceId(id); }; VCDataProvider.prototype.getRemotePublicServiceList = function (callback, pullMessageTime) { var publicList = []; var ret = this.addon.getAccounts(); var transformProto = function (ret) { var result = { hasFollowed: false, isGlobal: false, menu: null }; if (!ret.obj) { var error = { error: ret }; throw new Error('公众账号数据格式错误: ' + JSON.stringify(error)); } var obj = JSON.parse(ret.obj); var protoMap = { aType: 'conversationType', aId: 'publicServiceId', aName: 'introduction', aUri: 'portraitUri', follow: 'hasFollowed', isGlobal: 'isGlobal' }; for (var key in obj) { var val = obj[key]; if (key == 'aExtra') { var extra = JSON.parse(val); result["hasFollowed"] = extra.follow; result["isGlobal"] = extra.isGlobal; result["menu"] = extra.menu; } var uId = protoMap[key]; if (uId) { result[uId] = val; } } return result; }; if (ret) { ret = JSON.parse(ret); var list = ret.list; for (var i = 0, len = list.length; i < len; i++) { var item = list[i]; item = transformProto(item); publicList.push(item); } } if (publicList.length > 0) { RongIMLib.RongIMClient._memoryStore.publicServiceMap.publicServiceList.length = 0; RongIMLib.RongIMClient._memoryStore.publicServiceMap.publicServiceList = publicList; } callback.onSuccess(RongIMLib.RongIMClient._memoryStore.publicServiceMap.publicServiceList); }; VCDataProvider.prototype.buildMessage = function (result) { var message = new RongIMLib.Message(), ret = JSON.parse(result); message.conversationType = ret.conversationType; message.targetId = ret.targetId; message.messageDirection = ret.direction; message.senderUserId = ret.senderUserId; if (ret.direction == RongIMLib.MessageDirection.RECEIVE) { message.receivedStatus = ret.status; } else if (ret.direction == RongIMLib.MessageDirection.SEND) { message.sentStatus = ret.status; } message.sentTime = ret.sentTime; message.objectName = ret.objectName; var content = ret.content ? JSON.parse(ret.content) : ret.content; var messageType = typeMapping[ret.objectName] || registerMessageTypeMapping[ret.objectName]; if (content) { content.messageName = messageType; } message.content = content; message.messageId = ret.messageId; message.messageUId = ret.messageUid; message.messageType = messageType; return message; }; VCDataProvider.prototype.buildConversation = function (val) { if (val === '') { return null; } var conver = new RongIMLib.Conversation(), c = JSON.parse(val), lastestMsg = c.lastestMsg ? this.buildMessage(c.lastestMsg) : {}; conver.conversationTitle = c.title; conver.conversationType = c.conversationType; conver.draft = c.draft; conver.isTop = c.isTop; conver.isHidden = c.isHidden; lastestMsg.conversationType = c.conversationType; lastestMsg.targetId = c.targetId; conver.latestMessage = lastestMsg; conver.latestMessageId = lastestMsg.messageId; conver.latestMessage.messageType = typeMapping[lastestMsg.objectName] || registerMessageTypeMapping[lastestMsg.objectName]; conver.objectName = lastestMsg.objectName; conver.receivedStatus = RongIMLib.ReceivedStatus.READ; conver.sentTime = lastestMsg.sentTime; conver.senderUserId = lastestMsg.senderUserId; conver.sentStatus = lastestMsg.status; conver.targetId = c.targetId; conver.unreadMessageCount = c.unreadCount; conver.hasUnreadMention = c.m_hasUnreadMention; var mentions = this.getUnreadMentionedMessages(c.conversationType, c.targetId); if (mentions.length > 0) { // 取最后一条 @ 消息,原因:和 web 互相兼容 var mention = mentions.pop(); conver.mentionedMsg = { uid: mention.messageUid, time: mention.sentTime, mentionedInfo: mention.content.mentionedInfo, sendUserId: mention.senderUserId }; } return conver; }; VCDataProvider.prototype.getRTCUserInfoList = function (room, callback) { this.addon.getRTCUsers(room.id, 1, function (result) { callback.onSuccess(result); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.getRTCRoomInfo = function (room, callback) { var order = 2; this.addon.getRTCResouce(room.id, order, function (result) { callback.onSuccess(JSON.parse(result)); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.joinRTCRoom = function (room, callback) { var id = room.id; var type = room.type || 0; this.addon.joinRTCRoom(id, type, function (result, token) { var res = JSON.parse(result); var users = {}; var list = res.list; RongIMLib.RongUtil.forEach(list, function (item) { var userId = item.id; var tmpData = {}; RongIMLib.RongUtil.forEach(item.data, function (data) { var key = data.key; var value = data.value; tmpData[key] = value; }); users[userId] = tmpData; }); callback.onSuccess({ users: users, token: token }); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.quitRTCRoom = function (room, callback) { this.addon.exitRTCRoom(room.id, function () { callback.onSuccess(true); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.RTCPing = function (room, callback) { this.addon.sendRTCPing(room.id, function () { callback.onSuccess(true); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.setRTCData = function (roomId, key, value, isInner, apiType, callback, message) { var context = this; var hanlders = { room_inner: function (roomId, key, value, name, content, success, error) { context.addon.setRTCInnerData(roomId, RongIMLib.RTCAPIType.ROOM, key, value, name, content, success, error); }, room_outer: function (roomId, key, value, name, content, success, error) { context.addon.setRTCOuterData(roomId, RongIMLib.RTCAPIType.ROOM, key, value, name, content, success, error); }, user_inner: function (roomId, key, value, name, content, success, error) { context.addon.setRTCInnerData(roomId, RongIMLib.RTCAPIType.PERSON, key, value, name, content, success, error); }, user_outer: function (roomId, key, value, name, content, success, error) { context.addon.setRTCOuterData(roomId, RongIMLib.RTCAPIType.PERSON, key, value, name, content, success, error); } }; var type = RongIMLib.RTCAPIType.PERSON == apiType ? 'user' : 'room'; var direction = isInner ? 'inner' : 'outer'; var tpl = '{type}_{direction}'; var name = RongIMLib.RongUtil.tplEngine(tpl, { type: type, direction: direction }); var handler = hanlders[name]; if (handler) { message = message || {}; var name = message.name; var content = message.content; handler(roomId, key, value, name, content, function () { callback.onSuccess(true); }, function (code) { callback.onError(code); }); } }; VCDataProvider.prototype.setRTCRoomData = function (roomId, key, value, isInner, callback, message) { this.setRTCData(roomId, key, value, isInner, RongIMLib.RTCAPIType.ROOM, callback, message); }; VCDataProvider.prototype.getRTCData = function (roomId, keys, isInner, apiType, callback) { var context = this; var hanlders = { room_inner: function (roomId, keys, success, error) { context.addon.getRTCInnerData(roomId, RongIMLib.RTCAPIType.ROOM, keys, success, error); }, room_outer: function (roomId, keys, success, error) { context.addon.getRTCOuterData(roomId, RongIMLib.RTCAPIType.ROOM, keys, success, error); } }; var type = RongIMLib.RTCAPIType.PERSON == apiType ? 'user' : 'room'; var direction = isInner ? 'inner' : 'outer'; var tpl = '{type}_{direction}'; var name = RongIMLib.RongUtil.tplEngine(tpl, { type: type, direction: direction }); var handler = hanlders[name]; if (handler) { handler(roomId, keys, function (result) { var res = JSON.parse(result); var props = {}; var list = res.list; RongIMLib.RongUtil.forEach(list, function (item) { props[item.key] = item.value; }); callback.onSuccess(props); }, function (code) { callback.onError(code); }); } }; VCDataProvider.prototype.getRTCRoomData = function (roomId, keys, isInner, callback, message) { this.getRTCData(roomId, keys, isInner, RongIMLib.RTCAPIType.ROOM, callback); }; VCDataProvider.prototype.removeRTCData = function (roomId, keys, isInner, apiType, callback, message) { var context = this; var hanlders = { room_inner: function (roomId, keys, name, content, success, error) { context.addon.deleteRTCInnerData(roomId, RongIMLib.RTCAPIType.ROOM, keys, name, content, success, error); }, room_outer: function (roomId, keys, name, content, success, error) { context.addon.deleteRTCOuterData(roomId, RongIMLib.RTCAPIType.ROOM, keys, name, content, success, error); }, user_inner: function (roomId, keys, name, content, success, error) { }, user_outer: function (roomId, keys, name, content, success, error) { } }; var type = RongIMLib.RTCAPIType.PERSON == apiType ? 'user' : 'room'; var direction = isInner ? 'inner' : 'outer'; var tpl = '{type}_{direction}'; var name = RongIMLib.RongUtil.tplEngine(tpl, { type: type, direction: direction }); var handler = hanlders[name]; if (handler) { message = message || {}; var name = message.name || ''; var content = message.content || ''; handler(roomId, keys, name, content, function () { callback.onSuccess(true); }, function (code) { callback.onError(code); }); } }; VCDataProvider.prototype.removeRTCRoomData = function (roomId, keys, isInner, callback, message) { this.removeRTCData(roomId, keys, isInner, RongIMLib.RTCAPIType.ROOM, callback); }; VCDataProvider.prototype.getNavi = function () { var nav = this.addon.getNav(); return nav[this.userId]; }; // 信令 SDK 新增 VCDataProvider.prototype.setRTCOutData = function (roomId, data, type, callback, message) { }; // 信令 SDK 新增 VCDataProvider.prototype.getRTCOutData = function (roomId, userId, callback) { }; VCDataProvider.prototype.setRTCUserInfo = function (room, info, callback) { }; VCDataProvider.prototype.removeRTCUserInfo = function (room, info, callback) { }; VCDataProvider.prototype.getRTCUserList = function (room, callback) { }; VCDataProvider.prototype.setRTCRoomInfo = function (room, data, callback) { }; VCDataProvider.prototype.removeRTCRoomInfo = function (room, data, callback) { }; VCDataProvider.prototype.setRTCUserData = function (roomId, key, value, isInner, callback, message) { this.setRTCData(roomId, key, value, isInner, RongIMLib.RTCAPIType.PERSON, callback, message); }; VCDataProvider.prototype.getRTCUserData = function (roomId, key, isInner, callback, message) { }; VCDataProvider.prototype.removeRTCUserData = function (roomId, key, isInner, callback, message) { }; VCDataProvider.prototype.getRTCToken = function (room, callback) { }; VCDataProvider.prototype.setRTCState = function (room, content, callback) { }; return VCDataProvider; })(); RongIMLib.VCDataProvider = VCDataProvider; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var MemeoryProvider = (function () { function MemeoryProvider() { this._memeoryStore = {}; this.prefix = "rong_"; } MemeoryProvider.prototype.setItem = function (composedKey, object) { this._memeoryStore[composedKey] = decodeURIComponent(object); }; MemeoryProvider.prototype.getItem = function (composedKey) { return this._memeoryStore[composedKey]; }; MemeoryProvider.prototype.removeItem = function (composedKey) { if (this.getItem(composedKey)) { delete this._memeoryStore[composedKey]; } }; MemeoryProvider.prototype.getItemKey = function (regStr) { var me = this, item = null, reg = new RegExp(regStr + "\\w+"); for (var key in me._memeoryStore) { var arr = key.match(reg); if (arr) { item = key; } } return item; }; MemeoryProvider.prototype.getItemKeyList = function (regStr) { var prefix = this.prefix; var me = this, itemList = [], reg = new RegExp(regStr + "\\w+"); for (var key in me._memeoryStore) { var arr = key.match(reg); if (arr) { key = key.substring(prefix.length); itemList.push(key); } } return itemList; }; MemeoryProvider.prototype.clearItem = function () { var me = this; for (var key in me._memeoryStore) { delete me._memeoryStore[key]; } }; //单位:字节 MemeoryProvider.prototype.onOutOfQuota = function () { return 4 * 1024; }; return MemeoryProvider; })(); RongIMLib.MemeoryProvider = MemeoryProvider; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var LocalStorageProvider = (function () { // static _instance: LocalStorageProvider = new LocalStorageProvider(); function LocalStorageProvider() { this.prefix = 'rong_'; this._host = ""; var d = new Date(), m = d.getMonth() + 1, date = d.getFullYear() + '/' + (m.toString().length == 1 ? '0' + m : m) + '/' + d.getDate(), nowDate = new Date(date).getTime(); for (var key in localStorage) { if (key.lastIndexOf('RECEIVED') > -1) { var recObj = JSON.parse(localStorage.getItem(key)); for (var key_1 in recObj) { nowDate - recObj[key_1].dealtime > 0 && (delete recObj[key_1]); } if (RongIMLib.RongUtil.isEmpty(recObj)) { localStorage.removeItem(key); } else { localStorage.setItem(key, JSON.stringify(recObj)); } } if (key.lastIndexOf('SENT') > -1) { var sentObj = JSON.parse(localStorage.getItem(key)); nowDate - sentObj.dealtime > 0 && (localStorage.removeItem(key)); } } } LocalStorageProvider.prototype.setItem = function (composedKey, object) { if (composedKey) { composedKey.indexOf(this.prefix) == -1 && (composedKey = this.prefix + composedKey); localStorage.setItem(composedKey, object); } }; LocalStorageProvider.prototype.getItem = function (composedKey) { if (composedKey) { composedKey.indexOf(this.prefix) == -1 && (composedKey = this.prefix + composedKey); return localStorage.getItem(composedKey ? composedKey : ""); } return ""; }; LocalStorageProvider.prototype.getItemKey = function (composedStr) { var item = ""; var _key = this.prefix + composedStr; for (var key in localStorage) { if (key.indexOf(_key) == 0) { item = key; break; } } return item; }; LocalStorageProvider.prototype.getItemKeyList = function (composedStr) { var itemList = []; var prefix = this.prefix; var _key = prefix + composedStr; for (var key in localStorage) { if (key.indexOf(_key) == 0) { key = key.substring(prefix.length); itemList.push(key); } } return itemList; }; LocalStorageProvider.prototype.removeItem = function (composedKey) { if (composedKey) { composedKey.indexOf(this.prefix) == -1 && (composedKey = this.prefix + composedKey); localStorage.removeItem(composedKey.toString()); } }; LocalStorageProvider.prototype.clearItem = function () { var me = this; for (var key in localStorage) { if (key.indexOf(me.prefix) > -1) { me.removeItem(key); } } }; //单位:字节 LocalStorageProvider.prototype.onOutOfQuota = function () { return JSON.stringify(localStorage).length; }; return LocalStorageProvider; })(); RongIMLib.LocalStorageProvider = LocalStorageProvider; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var UserDataProvider = (function () { function UserDataProvider() { this.opersistName = 'RongIMLib'; this.keyManager = 'RongUserDataKeyManager'; this._host = ""; this.prefix = "rong_"; this.oPersist = document.createElement("div"); this.oPersist.style.display = "none"; this.oPersist.style.behavior = "url('#default#userData')"; document.body.appendChild(this.oPersist); this.oPersist.load(this.opersistName); } UserDataProvider.prototype.setItem = function (key, value) { key && key.indexOf(this.prefix) == -1 && (key = this.prefix + key); this.oPersist.setAttribute(key, value); var keyNames = this.getItem(this.keyManager); keyNames ? keyNames.indexOf(key) == -1 && (keyNames += ',' + key) : (keyNames = key); this.oPersist.setAttribute(this.prefix + this.keyManager, keyNames); this.oPersist.save(this.opersistName); }; UserDataProvider.prototype.getItem = function (key) { key && key.indexOf(this.prefix) == -1 && (key = this.prefix + key); return key ? this.oPersist.getAttribute(key) : key; }; UserDataProvider.prototype.removeItem = function (key) { key && key.indexOf(this.prefix) == -1 && (key = this.prefix + key); this.oPersist.removeAttribute(key); this.oPersist.save(this.opersistName); var keyNames = this.getItem(this.keyManager), keyNameArray = keyNames && keyNames.split(',') || []; for (var i = 0, len = keyNameArray.length; i < len; i++) { if (keyNameArray[i] == key) { keyNameArray.splice(i, 1); } } this.oPersist.setAttribute(this.prefix + this.keyManager, keyNameArray.join(',')); this.oPersist.save(this.opersistName); }; UserDataProvider.prototype.getItemKey = function (composedStr) { var item = null, keyNames = this.getItem(this.keyManager), keyNameArray = keyNames && keyNames.split(',') || [], me = this; var _key = this.prefix + composedStr; if (keyNameArray.length) { for (var i = 0, len = keyNameArray.length; i < len; i++) { if (keyNameArray[i] && keyNameArray[i].indexOf(_key) == 0) { item = keyNameArray[i]; break; } } } return item; }; UserDataProvider.prototype.getItemKeyList = function (composedStr) { var itemList = [], keyNames = this.getItem(this.keyManager), keyNameArray = keyNames && keyNames.split(',') || []; var prefix = this.prefix; var _key = prefix + composedStr; if (keyNameArray.length) { for (var i = 0, len = keyNameArray.length; i < len; i++) { if (keyNameArray[i] && keyNameArray[i].indexOf(_key) == 0) { var keyName = keyNameArray[i]; keyName = keyName.substring(prefix.length); itemList.push(keyNameArray[i]); } } } return itemList; }; UserDataProvider.prototype.clearItem = function () { var keyNames = this.getItem(this.keyManager), keyNameArray = [], me = this; keyNames && (keyNameArray = keyNames.split(',')); if (keyNameArray.length) { for (var i = 0, len = keyNameArray.length; i < len; i++) { keyNameArray[i] && me.removeItem(keyNameArray[i]); } me.removeItem(me.keyManager); } }; UserDataProvider.prototype.onOutOfQuota = function () { return 10 * 1024 * 1024; }; return UserDataProvider; })(); RongIMLib.UserDataProvider = UserDataProvider; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var FeatureDectector = (function () { function FeatureDectector(callback) { this.script = document.createElement("script"); this.head = document.getElementsByTagName("head")[0]; if ("WebSocket" in window && "ArrayBuffer" in window && WebSocket.prototype.CLOSED === 3 && !RongIMLib.RongIMClient._memoryStore.depend.isPolling) { RongIMLib.Transportations._TransportType = RongIMLib.Socket.WEBSOCKET; if (!RongIMLib.RongIMClient.Protobuf) { var url = RongIMLib.RongIMClient._memoryStore.depend.protobuf; var script = this.script; script.src = url; this.head.appendChild(script); script.onload = script.onreadystatechange = function () { var isLoaded = (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete'); if (isLoaded) { // 防止 IE6、7 下偶发触发两次 loaded script.onload = script.onreadystatechange = null; if (callback) { callback(); } if (!callback) { var token = RongIMLib.RongIMClient._memoryStore.token; var connectCallback = RongIMLib.RongIMClient._memoryStore.callback; token && RongIMLib.RongIMClient.connect(token, connectCallback); } } }; script.onerror = function () { console.log('----------'); } } } else { RongIMLib.Transportations._TransportType = "xhr-polling"; RongIMLib.RongIMClient.Protobuf = Polling; } } return FeatureDectector; })(); RongIMLib.FeatureDectector = FeatureDectector; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var FeaturePatcher = (function () { function FeaturePatcher() { } FeaturePatcher.prototype.patchAll = function () { this.patchJSON(); this.patchForEach(); }; FeaturePatcher.prototype.patchForEach = function () { if (!Array.forEach) { Array.forEach = function (arr, func) { for (var i = 0; i < arr.length; i++) { func.call(arr, arr[i], i, arr); } }; } }; FeaturePatcher.prototype.patchJSON = function () { if (!window["JSON"]) { window["JSON"] = (function () { function JSON() { } JSON.parse = function (sJSON) { return eval('(' + sJSON + ')'); }; JSON.stringify = function (value) { return this.str("", { "": value }); }; JSON.str = function (key, holder) { var i, k, v, length, mind = "", partial, value = holder[key], me = this; if (value && typeof value === "object" && typeof value.toJSON === "function") { value = value.toJSON(key); } switch (typeof value) { case "string": return me.quote(value); case "number": return isFinite(value) ? String(value) : "null"; case "boolean": case "null": return String(value); case "object": if (!value) { return "null"; } partial = []; if (Object.prototype.toString.apply(value) === "[object Array]") { length = value.length; for (i = 0; i < length; i += 1) { partial[i] = me.str(i, value) || "null"; } v = partial.length === 0 ? "[]" : "[" + partial.join(",") + "]"; return v; } for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = me.str(k, value); if (v) { partial.push(me.quote(k) + ":" + v); } } } v = partial.length === 0 ? "{}" : "{" + partial.join(",") + "}"; return v; } }; JSON.quote = function (string) { var me = this; me.rx_escapable.lastIndex = 0; return me.rx_escapable.test(string) ? '"' + string.replace(me.rx_escapable, function (a) { var c = me.meta[a]; return typeof c === "string" ? c : "\\u" + ("0000" + a.charCodeAt(0).toString(16)).slice(-4); }) + '"' : '"' + string + '"'; }; JSON.rx_escapable = new RegExp('[\\\"\\\\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]', "g"); JSON.meta = { "\b": "\\b", " ": "\\t", "\n": "\\n", "\f": "\\f", "\r": "\\r", '"': '\\"', "''": "\\''", "\\": "\\\\" }; return JSON; })(); } }; return FeaturePatcher; })(); RongIMLib.FeaturePatcher = FeaturePatcher; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var ScriptLoader = (function () { function ScriptLoader() { } ScriptLoader.prototype.load = function (src, onLoad, onError) { var script = document.createElement("script"); script.async = true; if (onLoad) { if (script.addEventListener) { script.addEventListener("load", function (event) { var target = event.target || event.srcElement; onLoad(target.src); }, false); } else if (script.readyState) { script.onreadystatechange = function (event) { var target = event.srcElement; onLoad(target.src); }; } } if (onError) { script.onerror = function (event) { var target = event.target || event.srcElement; onError(target.src); }; } (document.head || document.getElementsByTagName("head")[0]).appendChild(script); script.src = src; }; return ScriptLoader; })(); })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var PublicServiceMap = (function () { function PublicServiceMap() { this.publicServiceList = []; } PublicServiceMap.prototype.get = function (publicServiceType, publicServiceId) { for (var i = 0, len = this.publicServiceList.length; i < len; i++) { if (this.publicServiceList[i].conversationType == publicServiceType && publicServiceId == this.publicServiceList[i].publicServiceId) { return this.publicServiceList[i]; } } }; PublicServiceMap.prototype.add = function (publicServiceProfile) { var isAdd = true, me = this; for (var i = 0, len = this.publicServiceList.length; i < len; i++) { if (me.publicServiceList[i].conversationType == publicServiceProfile.conversationType && publicServiceProfile.publicServiceId == me.publicServiceList[i].publicServiceId) { this.publicServiceList.unshift(this.publicServiceList.splice(i, 1)[0]); isAdd = false; break; } } if (isAdd) { this.publicServiceList.unshift(publicServiceProfile); } }; PublicServiceMap.prototype.replace = function (publicServiceProfile) { var me = this; for (var i = 0, len = this.publicServiceList.length; i < len; i++) { if (me.publicServiceList[i].conversationType == publicServiceProfile.conversationType && publicServiceProfile.publicServiceId == me.publicServiceList[i].publicServiceId) { me.publicServiceList.splice(i, 1, publicServiceProfile); break; } } }; PublicServiceMap.prototype.remove = function (conversationType, publicServiceId) { var me = this; for (var i = 0, len = this.publicServiceList.length; i < len; i++) { if (me.publicServiceList[i].conversationType == conversationType && publicServiceId == me.publicServiceList[i].publicServiceId) { this.publicServiceList.splice(i, 1); break; } } }; return PublicServiceMap; })(); RongIMLib.PublicServiceMap = PublicServiceMap; /** * 会话工具类。 */ var ConversationMap = (function () { function ConversationMap() { this.conversationList = []; } ConversationMap.prototype.get = function (conversavtionType, targetId) { for (var i = 0, len = this.conversationList.length; i < len; i++) { if (this.conversationList[i].conversationType == conversavtionType && this.conversationList[i].targetId == targetId) { return this.conversationList[i]; } } return null; }; ConversationMap.prototype.add = function (conversation) { var isAdd = true; for (var i = 0, len = this.conversationList.length; i < len; i++) { if (this.conversationList[i].conversationType === conversation.conversationType && this.conversationList[i].targetId === conversation.targetId) { this.conversationList.unshift(this.conversationList.splice(i, 1)[0]); isAdd = false; break; } } if (isAdd) { this.conversationList.unshift(conversation); } }; /** * [replace 替换会话] * 会话数组存在的情况下调用add方法会是当前会话被替换且返回到第一个位置,导致用户本地一些设置失效,所以提供replace方法 */ ConversationMap.prototype.replace = function (conversation) { for (var i = 0, len = this.conversationList.length; i < len; i++) { if (this.conversationList[i].conversationType === conversation.conversationType && this.conversationList[i].targetId === conversation.targetId) { this.conversationList.splice(i, 1, conversation); break; } } }; ConversationMap.prototype.remove = function (conversation) { for (var i = 0, len = this.conversationList.length; i < len; i++) { if (this.conversationList[i].conversationType === conversation.conversationType && this.conversationList[i].targetId === conversation.targetId) { this.conversationList.splice(i, 1); break; } } }; return ConversationMap; })(); RongIMLib.ConversationMap = ConversationMap; var CheckParam = (function () { function CheckParam() { } CheckParam.getInstance = function () { if (!CheckParam._instance) { CheckParam._instance = new CheckParam(); } return CheckParam._instance; }; CheckParam.prototype.logger = function (code, funcName, msg) { RongIMLib.RongIMClient.logger({ code: code, funcName: funcName, msg: msg }); }; CheckParam.prototype.check = function (f, position, d, c) { if (RongIMLib.RongIMClient._dataAccessProvider || d) { for (var g = 0, e = c.length; g < e; g++) { if (!new RegExp(this.getType(c[g])).test(f[g])) { // throw new Error("The index of " + g + " parameter was wrong type " + this.getType(c[g]) + " [" + f[g] + "] -> position:" + position); var msg = "第" + (g + 1) + "个参数错误, 错误类型:" + this.getType(c[g]) + " [" + f[g] + "] -> 位置:" + position; this.logger("-3", position, msg); } } } else { var msg = "该参数不正确或尚未实例化RongIMClient -> 位置:" + position; this.logger("-4", position, msg); } }; CheckParam.prototype.getType = function (str) { var temp = Object.prototype.toString.call(str).toLowerCase(); return temp.slice(8, temp.length - 1); }; CheckParam.prototype.checkCookieDisable = function () { document.cookie = "checkCookie=1"; var arr = document.cookie.match(new RegExp("(^| )checkCookie=([^;]*)(;|$)")), isDisable = false; if (!arr) { isDisable = true; } document.cookie = "checkCookie=1;expires=Thu, 01-Jan-1970 00:00:01 GMT"; return isDisable; }; return CheckParam; })(); RongIMLib.CheckParam = CheckParam; var LimitableMap = (function () { function LimitableMap(limit) { this.map = {}; this.keys = []; this.limit = limit || 10; } LimitableMap.prototype.set = function (key, value) { this.map[key] = value; }; LimitableMap.prototype.get = function (key) { return this.map[key] || 0; }; LimitableMap.prototype.remove = function (key) { delete this.map[key]; }; return LimitableMap; })(); RongIMLib.LimitableMap = LimitableMap; var MemoryCache = (function () { function MemoryCache() { this.cache = {}; } MemoryCache.prototype.set = function (key, value) { this.cache[key] = value; }; MemoryCache.prototype.get = function (key) { return this.cache[key]; }; MemoryCache.prototype.remove = function (key) { delete this.cache[key]; }; return MemoryCache; })(); RongIMLib.MemoryCache = MemoryCache; var RongAjax = (function () { function RongAjax(options) { var me = this; me.xmlhttp = null; me.options = options; var hasCORS = typeof XMLHttpRequest !== "undefined" && "withCredentials" in new XMLHttpRequest(); if ("undefined" != typeof XMLHttpRequest && hasCORS) { me.xmlhttp = new XMLHttpRequest(); } else if ("undefined" != typeof XDomainRequest) { me.xmlhttp = new XDomainRequest(); } else { me.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } } RongAjax.prototype.send = function (callback) { var me = this; me.options.url || (me.options.url = "http://upload.qiniu.com/putb64/-1"); me.xmlhttp.onreadystatechange = function () { if (me.xmlhttp.readyState == 4) { if (me.options.type) { callback(); } else { callback(JSON.parse(me.xmlhttp.responseText.replace(/'/g, '"'))); } } }; me.xmlhttp.open("POST", me.options.url, true); me.xmlhttp.withCredentials = false; if ("setRequestHeader" in me.xmlhttp) { if (me.options.type) { me.xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=utf-8"); } else { me.xmlhttp.setRequestHeader("Content-type", "application/octet-stream"); me.xmlhttp.setRequestHeader('Authorization', "UpToken " + me.options.token); } } me.xmlhttp.send(me.options.type ? "appKey=" + me.options.appKey + "&deviceId=" + me.options.deviceId + "×tamp=" + me.options.timestamp + "&deviceInfo=" + me.options.deviceInfo + "&privateInfo=" + JSON.stringify(me.options.privateInfo) : me.options.base64); }; return RongAjax; })(); RongIMLib.RongAjax = RongAjax; function Prosumer() { var data = [], isConsuming = false; this.produce = function (res) { data.push(res); }; this.consume = function (callback, finished) { if (isConsuming) { return; } isConsuming = true; var next = function () { var res = data.shift(); if (RongUtil.isUndefined(res)) { isConsuming = false; finished && finished(); return; } callback(res, next); }; next(); }; this.isExeuting = function () { return isConsuming; }; } var RongUtil = (function () { function RongUtil() { } RongUtil.noop = function () { }; RongUtil.isEmpty = function (obj) { var result = true; if (RongUtil.isObject(obj)) { RongUtil.forEach(obj, function () { result = false; }); } if (RongUtil.isString(obj) || RongUtil.isArray(obj)) { return obj.length === 0; } if (RongUtil.isNumber(obj)) { return obj === 0; } return result; }; RongUtil.isLengthLimit = function (str, maxLen, minLen) { minLen = minLen || 0; var strLen = str.length; return strLen <= maxLen && strLen >= minLen; }; RongUtil.MD5 = function (str, key, raw) { return md5(str, key, raw); }; RongUtil.isObject = function (obj) { return Object.prototype.toString.call(obj) == '[object Object]'; }; RongUtil.isArray = function (array) { return Object.prototype.toString.call(array) == '[object Array]'; }; RongUtil.isString = function (array) { return Object.prototype.toString.call(array) == '[object String]'; }; RongUtil.isFunction = function (fun) { return Object.prototype.toString.call(fun) == '[object Function]'; }; ; RongUtil.isUndefined = function (str) { return Object.prototype.toString.call(str) == '[object Undefined]'; }; ; RongUtil.isEqual = function (a, b) { return a === b; }; ; RongUtil.indexOf = function (arrs, item) { var index = -1; for (var i = 0; i < arrs.length; i++) { if (item === arrs[i]) { index = i; break; } } return index; }; RongUtil.stringFormat = function (tmpl, vals) { for (var i = 0, len = vals.length; i < len; i++) { var val = vals[i], reg = new RegExp("\\{" + (i) + "\\}", "g"); tmpl = tmpl.replace(reg, val); } return tmpl; }; RongUtil.tplEngine = function (temp, data, regexp) { if (!(Object.prototype.toString.call(data) === "[object Array]")) { data = [data]; } var ret = []; for (var i = 0, j = data.length; i < j; i++) { ret.push(replaceAction(data[i])); } return ret.join(""); function replaceAction(object) { return temp.replace(regexp || (/{([^}]+)}/g), function (match, name) { if (match.charAt(0) == '\\') { return match.slice(1); } return (object[name] != undefined) ? object[name] : '{' + name + '}'; }); } }; ; RongUtil.forEach = function (obj, callback) { callback = callback || RongUtil.noop; var loopObj = function () { for (var key in obj) { if (obj.hasOwnProperty(key)) { callback(obj[key], key, obj); } } }; var loopArr = function () { for (var i = 0, len = obj.length; i < len; i++) { callback(obj[i], i); } }; if (RongUtil.isObject(obj)) { loopObj(); } if (RongUtil.isArray(obj)) { loopArr(); } }; RongUtil.extend = function (source, target, callback, force) { RongUtil.forEach(source, function (val, key) { var hasProto = (key in target); if (force && hasProto) { target[key] = val; } if (!hasProto) { target[key] = val; } }); return target; }; RongUtil.createXHR = function () { var item = { XMLHttpRequest: function () { return new XMLHttpRequest(); }, XDomainRequest: function () { return new XDomainRequest(); }, ActiveXObject: function () { return new ActiveXObject('Microsoft.XMLHTTP'); } }; var isXHR = (typeof XMLHttpRequest == 'function'); if (window.navigator) { var browserAgent = window.navigator.userAgent.toLowerCase(); var isIPhone = browserAgent.indexOf('iphone') > -1; if (isIPhone && isXHR == false) { isXHR = (typeof XMLHttpRequest == 'object'); } } var isXDR = (typeof XDomainRequest == 'function'); var key = isXHR ? 'XMLHttpRequest' : isXDR ? 'XDomainRequest' : 'ActiveXObject'; return item[key](); }; RongUtil.request = function (opts) { var url = opts.url; var success = opts.success; var error = opts.error; var method = opts.method || 'GET'; var xhr = RongUtil.createXHR(); xhr.onreadystatechange = function () { if (xhr.readyState == 4) { var status = xhr.status; if (status == 200) { success(xhr.responseText); } else { error(status, xhr.responseText); } } }; xhr.open(method, url, true); xhr.send(null); return xhr; }; RongUtil.formatProtoclPath = function (config) { var path = config.path; var protocol = config.protocol; var tmpl = config.tmpl || '{0}{1}'; var sub = config.sub; var flag = '://'; var index = path.indexOf(flag); var hasProtocol = (index > -1); if (hasProtocol) { index += flag.length; path = path.substring(index); } if (sub) { index = path.indexOf('/'); var hasPath = (index > -1); if (hasPath) { path = path.substr(0, index); } } return RongUtil.stringFormat(tmpl, [protocol, path]); }; ; RongUtil.getUrlHost = function (url) { var index = RongUtil.indexOf(url, '/'); return url.substring(0, index); }; RongUtil.supportLocalStorage = function () { var support = false; if (typeof localStorage == 'object') { try { var key = 'RC_TMP_KEY', value = 'RC_TMP_VAL'; localStorage.setItem(key, value); var localVal = localStorage.getItem(key); if (localVal == value) { support = true; } } catch (err) { console.log('localStorage is disabled.'); } } return support; }; /* //返回新引用,不破坏原始对象 rename({n: 'martin'}, {n: 'name'}); => {name: 'martin'} rename([{n: 'martin'}, {a: 18}], {n: 'name', a: 'age'}); => [{name: 'martin'}, {age: 18}] */ RongUtil.rename = function (origin, newNames) { var isObject = RongUtil.isObject(origin); if (isObject) { origin = [origin]; } origin = JSON.parse(JSON.stringify(origin)); var updateProperty = function (val, key, obj) { delete obj[key]; key = newNames[key]; obj[key] = val; }; RongUtil.forEach(origin, function (item) { RongUtil.forEach(item, function (val, key, obj) { var isRename = (key in newNames); (isRename ? updateProperty : RongUtil.noop)(val, key, obj); }); }); return isObject ? origin[0] : origin; }; RongUtil.some = function (arrs, callback) { var has = false; for (var i = 0, len = arrs.length; i < len; i++) { if (callback(arrs[i])) { has = true; break; } } return has; }; RongUtil.keys = function (obj) { var props = []; for (var key in obj) { props.push(key); } return props; }; RongUtil.isNumber = function (num) { return Object.prototype.toString.call(num) == '[object Number]'; }; RongUtil.getTimestamp = function () { var date = new Date(); return date.getTime(); }; RongUtil.isSupportRequestHeaders = function () { var userAgent = navigator.userAgent; var isIE = window.ActiveXObject || 'ActiveXObject' in window; if (isIE) { var reIE = new RegExp('MSIE (\\d+\\.\\d+);'); reIE.test(userAgent); var fIEVersion = parseFloat(RegExp['$1']); return fIEVersion > 9; } return true; }; RongUtil.hasValidWsUrl = function (urls) { try { urls = JSON.parse(urls); } catch (e) { return false; } var validUrlList = RongUtil.getValidWsUrlList(urls); return validUrlList.length > 0; }; RongUtil.getValidWsUrlList = function (urls) { var invalidWsUrls = RongIMLib.RongIMClient.invalidWsUrls; var validUrlList = []; RongUtil.forEach(urls, function (url) { if (RongUtil.indexOf(invalidWsUrls, url) === -1) { validUrlList.push(url); } }); return validUrlList; }; RongUtil.Prosumer = Prosumer; return RongUtil; })(); RongIMLib.RongUtil = RongUtil; /* var observer = new RongObserver(); observer.watch({ key: 'key', func: function(entity){ } }); */ var RongObserver = (function () { function RongObserver() { this.watchers = {}; } RongObserver.prototype.genUId = function (key) { var time = new Date().getTime(); return [key, time].join('_'); }; RongObserver.prototype.watch = function (params) { var me = this; var key = params.key; var multiple = params.multiple; key = RongUtil.isArray(key) ? key : [key]; var func = params.func; RongUtil.forEach(key, function (k) { k = multiple ? me.genUId(k) : k; me.watchers[k] = func; }); }; RongObserver.prototype.notify = function (params) { var me = this; var key = params.key; var entity = params.entity; for (var k in me.watchers) { var isNotify = (k.indexOf(key) == 0); if (isNotify) { me.watchers[k](entity); } } }; RongObserver.prototype.remove = function () { }; return RongObserver; })(); RongIMLib.RongObserver = RongObserver; var Observer = (function () { function Observer() { this.observers = []; } Observer.prototype.add = function (observer, force) { if (force) { this.observers = [observer]; } if (RongUtil.isFunction(observer)) { this.observers.push(observer); } }; Observer.prototype.emit = function (data) { RongUtil.forEach(this.observers, function (observer) { observer(data); }); }; Observer.prototype.clear = function () { this.observers = []; }; Observer.prototype.checkIndexOutBound = function (index, bound) { var isOutBound = (index > -1 && index < bound); return isOutBound; }; Observer.prototype.removeAt = function (index) { var isOutBound = this.checkIndexOutBound(index, this.observers.length); if (isOutBound) { this.observers.splice(index, 1); } }; Observer.prototype.remove = function (observer) { var me = this; if (!observer) { me.clear(); return; } if (!RongUtil.isFunction(observer)) { return; } var observerList = me.observers; for (var i = observerList.length - 1; i >= 0; i--) { if (observer === observerList[i]) { me.removeAt(i); } } }; return Observer; })(); RongIMLib.Observer = Observer; var Timer = (function () { function Timer(config) { this.timeout = 0; this.timers = []; this.timeout = config.timeout; } Timer.prototype.resume = function (callback) { var timer = setTimeout(callback, this.timeout); this.timers.push(timer); }; Timer.prototype.pause = function () { RongUtil.forEach(this.timers, function (timer) { clearTimeout(timer); }); }; return Timer; })(); RongIMLib.Timer = Timer; var IndexTools = (function () { function IndexTools(config) { this.items = []; this.index = 0; this.onwheel = function () { }; this.items = config.items; this.onwheel = config.onwheel; } IndexTools.prototype.get = function () { var context = this; var items = context.items; var index = context.index; var isWheel = index >= items.length; if (isWheel) { context.onwheel(); } return isWheel ? 0 : index; }; IndexTools.prototype.add = function () { this.index += 1; }; return IndexTools; })(); RongIMLib.IndexTools = IndexTools; var InnerUtil = (function () { function InnerUtil() { } InnerUtil.getUId = function (token) { return md5(token).slice(8, 16); }; return InnerUtil; })(); RongIMLib.InnerUtil = InnerUtil; })(RongIMLib || (RongIMLib = {})); // {WebEnd} WebSDK 内容开始的标识, 方便小程序 SDK 定位 /* 说明: 请勿修改 header.js 和 footer.js 用途: 自动拼接暴露方式 命令: grunt release 中 concat */ return RongIMLib; }); ================================================ FILE: api-test-v2/lib/js/RongIMLib-2.5.4.js ================================================ /* 说明: 请勿修改 header.js 和 footer.js 用途: 自动拼接暴露方式 命令: grunt release 中 concat */ (function(global, factory) { if (typeof exports === 'object' && typeof module !== 'undefined') { module.exports = factory(); } else if (typeof define === 'function' && (define.amd || define.cmd)) { define(factory); } else { var tempIMLib = factory(); var tempClient = tempIMLib.RongIMClient; var isExists = (!!global.RongIMLib); if (isExists) { var currentClient = RongIMLib.RongIMClient || {}; for(var key in currentClient){ tempClient[key] = currentClient[key]; } } global.RongIMLib = tempIMLib; global.RongIMClient = tempClient; } })(window, function(){ // {WebStart} WebSDK 内容开始的标识, 方便小程序 SDK 定位 var Polling = { SetUserStatusInput: function(){ var a = {}; this.setStatus = function(b){ a.status = b; }; this.toArrayBuffer = function(){ return a; }; }, SetUserStatusOutput: function(){ var a = {}; this.setNothing = function(b){ a.nothing = b; }; this.toArrayBuffer = function(){ return a; }; }, GetUserStatusInput: function(){ var a = {}; this.setNothing = function(b){ a.nothing = b; }; this.toArrayBuffer = function(){ return a; }; }, GetUserStatusOutput: function(){ var a = {}; this.setStatus = function(b){ a.status = b; }; this.setSubUserId = function(b){ a.subUserId = b; }; this.toArrayBuffer = function(){ return a; }; }, VoipDynamicInput: function(){ var a = {}; this.setEngineType = function(b){ a.engineType = b; }; this.setChannelName = function(b){ a.channelName = b; }; this.setChannelExtra = function(b){ a.channelExtra = b; }; this.toArrayBuffer = function(){ return a; }; }, VoipDynamicOutput: function(){ var a = {}; this.setDynamicKey = function(b){ a.dynamicKey = b; }; this.toArrayBuffer = function(){ return a; }; }, SubUserStatusInput: function(){ var a = {}; this.setUserid = function(b){ a.userid = b; }; this.toArrayBuffer = function(){ return a; }; }, SubUserStatusOutput: function(){ var a = {}; this.setNothing = function(b){ a.nothing = b; }; this.toArrayBuffer = function(){ return a; }; }, CleanHisMsgInput: function(){ var a = {}; this.setTargetId = function(b){ a.targetId = b; }; this.setDataTime = function(b){ a.dataTime = b; }; this.setConversationType = function(b){ a.conversationType = b; }; this.toArrayBuffer = function(){ return a; }; }, DeleteMsgInput:function(){ var a = {}; this.setType = function(b){ a.type = b; }; this.setConversationId = function(b){ a.conversationId = b; }; this.setMsgs = function(b){ a.msgs = b; }; this.toArrayBuffer = function () { return a; } }, DeleteMsg:function(){ var a = {}; this.setMsgId = function(b){ a.msgId = b; }; this.setMsgDataTime = function(b){ a.msgDataTime = b; }; this.setDirect = function(b){ a.direct = b; }; this.toArrayBuffer = function () { return a; } }, DeleteMsgOutput:function(){ var a = {}; this.setNothing = function(b){ a.nothing = b; }; this.toArrayBuffer = function () { return a; } }, SearchMpInput:function(){ var a = {}; this.setType = function (b) { a.type = b; }; this.setId = function (b) { a.id = b; }; this.toArrayBuffer = function () { return a; } }, SearchMpOutput:function(){ var a = {}; this.setNothing = function (b) { a.nothing = b; }; this.setInfo = function (b) { a.info = b; }; this.toArrayBuffer = function () { return a; } }, MpInfo:function(){ var a = {}; this.setMpid = function(b){ a.mpid = b; }; this.setName = function(b){ a.name = b; }; this.setType = function(b){ a.type = b; }; this.setTime = function(b){ a.time = b; }; this.setPortraitUri = function(b){ a.portraitUrl = b; }; this.setExtra = function(b){ a.extra = b; }; this.toArrayBuffer = function () { return a; } }, PullMpInput:function(){ var a = {}; this.setMpid = function(b){ a.mpid = b; }; this.setTime = function(b){ a.time = b; }; this.toArrayBuffer = function () { return a; }; }, PullMpOutput:function(){ var a = {}; this.setStatus = function(b){ a.status = b; } this.setInfo = function(b){ a.info = b; }; this.toArrayBuffer = function () { return a; }; }, MPFollowInput:function(){ var a = {}; this.setId = function(b){ a.id = b; }; this.toArrayBuffer = function () { return a; }; }, MPFollowOutput:function(){ var a = {}; this.setNothing = function(b){ a.nothing = b; }; this.setInfo = function(b){ a.info = b; }; this.toArrayBuffer = function () { return a; }; }, NotifyMsg: function () { var a = {}; this.setType = function (b) { a.type = b; }; this.setTime = function (b) { a.time = b; }; this.setChrmId = function(b){ a.chrmId = b; }; this.toArrayBuffer = function () { return a; }; }, SyncRequestMsg: function () { var a = {}; this.setSyncTime = function (b) { a.syncTime = b || 0; }; this.setIspolling = function (b) { a.ispolling = !!b; }; this.setIsweb = function (b) { a.isweb = !!b; }; this.setIsPullSend = function (b) { a.isPullSend = !!b; }; this.setSendBoxSyncTime = function (b) { a.sendBoxSyncTime = b; }; this.toArrayBuffer = function () { return a; }; }, UpStreamMessage: function () { var a = {}; this.setSessionId = function (b) { a.sessionId = b }; this.setClassname = function (b) { a.classname = b }; this.setContent = function (b) { if (b) a.content = b; }; this.setPushText = function (b) { a.pushText = b }; this.setUserId = function(b){ a.userId = b; }; this.setConfigFlag = function (b) { a.configFlag = b; }; this.setAppData = function(b){ a.appData = b; }; this.toArrayBuffer = function () { return a }; }, DownStreamMessages: function () { var a = {}; this.setList = function (b) { a.list = b }; this.setSyncTime = function (b) { a.syncTime = b; }; this.setFinished = function(b){ a.finished = b; }; this.toArrayBuffer = function () { return a }; }, DownStreamMessage: function () { var a = {}; this.setFromUserId = function (b) { a.fromUserId = b }; this.setType = function (b) { a.type = b }; this.setGroupId = function (b) { a.groupId = b }; this.setClassname = function (b) { a.classname = b }; this.setContent = function (b) { if (b) a.content = b }; this.setDataTime = function (b) { a.dataTime = b; }; this.setStatus = function (b) { a.status = b; }; this.setMsgId = function (b) { a.msgId = b; }; this.toArrayBuffer = function () { return a; }; }, CreateDiscussionInput: function () { var a = {}; this.setName = function (b) { a.name = b }; this.toArrayBuffer = function () { return a } }, CreateDiscussionOutput: function () { var a = {}; this.setId = function (b) { a.id = b }; this.toArrayBuffer = function () { return a }; }, ChannelInvitationInput: function () { var a = {}; this.setUsers = function (b) { a.users = b }; this.toArrayBuffer = function () { return a }; }, LeaveChannelInput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b }; this.toArrayBuffer = function () { return a }; }, QueryChatroomInfoInput:function(){ var a = {}; this.setCount = function (b) { a.count = b; }; this.setOrder = function (b) { a.order = b; }; this.toArrayBuffer = function () { return a }; }, QueryChatroomInfoOutput:function(){ var a = {}; this.setUserTotalNums = function (b) { a.userTotalNums = b; }; this.setUserInfos = function (b) { a.userInfos = b; }; this.toArrayBuffer = function () { return a; }; }, ChannelEvictionInput: function () { var a = {}; this.setUser = function (b) { a.user = b }; this.toArrayBuffer = function () { return a }; }, RenameChannelInput: function () { var a = {}; this.setName = function (b) { a.name = b }; this.toArrayBuffer = function () { return a } }, ChannelInfoInput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b }; this.toArrayBuffer = function () { return a } }, ChannelInfoOutput: function () { var a = {}; this.setType = function (b) { a.type = b }; this.setChannelId = function (b) { a.channelId = b }; this.setChannelName = function (b) { a.channelName = b }; this.setAdminUserId = function (b) { a.adminUserId = b }; this.setFirstTenUserIds = function (b) { a.firstTenUserIds = b }; this.setOpenStatus = function (b) { a.openStatus = b }; this.toArrayBuffer = function () { return a } }, ChannelInfosInput: function () { var a = {}; this.setPage = function (b) { a.page = b }; this.setNumber = function (b) { a.number = b }; this.toArrayBuffer = function () { return a }; }, ChannelInfosOutput: function () { var a = {}; this.setChannels = function (b) { a.channels = b }; this.setTotal = function (b) { a.total = b }; this.toArrayBuffer = function () { return a }; }, MemberInfo: function () { var a = {}; this.setUserId = function (b) { a.userId = b }; this.setUserName = function (b) { a.userName = b }; this.setUserPortrait = function (b) { a.userPortrait = b }; this.setExtension = function (b) { a.extension = b }; this.toArrayBuffer = function () { return a }; }, GroupMembersInput: function () { var a = {}; this.setPage = function (b) { a.page = b }; this.setNumber = function (b) { a.number = b }; this.toArrayBuffer = function () { return a }; }, GroupMembersOutput: function () { var a = {}; this.setMembers = function (b) { a.members = b }; this.setTotal = function (b) { a.total = b }; this.toArrayBuffer = function () { return a }; }, GetUserInfoInput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b }; this.toArrayBuffer = function () { return a }; }, GetUserInfoOutput: function () { var a = {}; this.setUserId = function (b) { a.userId = b }; this.setUserName = function (b) { a.userName = b }; this.setUserPortrait = function (b) { a.userPortrait = b }; this.toArrayBuffer = function () { return a }; }, GetSessionIdInput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b }; this.toArrayBuffer = function () { return a }; }, GetSessionIdOutput: function () { var a = {}; this.setSessionId = function (b) { a.sessionId = b }; this.toArrayBuffer = function () { return a }; }, GetQNupTokenInput: function () { var a = {}; this.setType = function (b) { a.type = b; } this.toArrayBuffer = function () { return a } }, GetQNupTokenOutput: function () { var a = {}; this.setDeadline = function (b) { a.deadline = b }; this.setToken = function (b) { a.token = b; }; this.toArrayBuffer = function () { return a } }, GetQNdownloadUrlInput: function () { var a = {}; this.setType = function (b) { a.type = b; }; this.setKey = function (b) { a.key = b; }; this.setFileName = function(b){ a.fileName = b; }; this.toArrayBuffer = function () { return a } }, GetQNdownloadUrlOutput: function () { var a = {}; this.setDownloadUrl = function (b) { a.downloadUrl = b; }; this.toArrayBuffer = function () { return a } }, Add2BlackListInput: function () { var a = {}; this.setUserId = function (b) { a.userId = b; }; this.toArrayBuffer = function () { return a } }, RemoveFromBlackListInput: function () { var a = {}; this.setUserId = function (b) { a.userId = b; }; this.toArrayBuffer = function () { return a } }, QueryBlackListInput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b; }; this.toArrayBuffer = function () { return a } }, QueryBlackListOutput: function () { var a = {}; this.setUserIds = function (b) { a.userIds = b; }; this.toArrayBuffer = function () { return a } }, BlackListStatusInput: function () { var a = {}; this.setUserId = function (b) { a.userId = b; }; this.toArrayBuffer = function () { return a } }, BlockPushInput: function () { var a = {}; this.setBlockeeId = function (b) { a.blockeeId = b; }; this.toArrayBuffer = function () { return a } }, ModifyPermissionInput: function () { var a = {}; this.setOpenStatus = function (b) { a.openStatus = b; }; this.toArrayBuffer = function () { return a }; }, GroupInput: function () { var a = {}; this.setGroupInfo = function (b) { for (var i = 0, arr = []; i < b.length; i++) { arr.push({id: b[i].getContent().id, name: b[i].getContent().name}) } a.groupInfo = arr; }; this.toArrayBuffer = function () { return a }; }, GroupOutput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b; }; this.toArrayBuffer = function () { return a }; }, GroupInfo: function () { var a = {}; this.setId = function (b) { a.id = b; }; this.setName = function (b) { a.name = b; }; this.getContent = function () { return a; }; this.toArrayBuffer = function () { return a }; }, GroupHashInput: function () { var a = {}; this.setUserId = function (b) { a.userId = b; }; this.setGroupHashCode = function (b) { a.groupHashCode = b; }; this.toArrayBuffer = function () { return a }; }, GroupHashOutput: function () { var a = {}; this.setResult = function (b) { a.result = b; }; this.toArrayBuffer = function () { return a }; }, ChrmInput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b; }; this.toArrayBuffer = function () { return a }; }, ChrmOutput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b; }; this.toArrayBuffer = function () { return a }; }, ChrmPullMsg: function () { var a = {}; this.setSyncTime = function (b) { a.syncTime = b }; this.setCount = function (b) { a.count = b; }; this.toArrayBuffer = function () { return a }; }, RelationsInput: function () { var a = {}; this.setType = function (b) { a.type = b; }; this.setMsg = function(b){ a.msg = b; }; this.setCount = function(b){ a.count = b; }; this.toArrayBuffer = function () { return a }; }, RelationsOutput: function () { var a = {}; this.setInfo = function (b) { a.info = b; }; this.toArrayBuffer = function () { return a } }, RelationInfo: function () { var a = {}; this.setType = function (b) { a.type = b; }; this.setUserId = function (b) { a.userId = b; }; this.setMsg = function(b){ a.msg = b; }; this.toArrayBuffer = function () { return a } }, HistoryMessageInput: function () { var a={}; this.setTargetId=function(b){ a.targetId=b; }; this.setDataTime=function(b){ a.dataTime=b; }; this.setSize=function(b){ a.size=b; }; this.toArrayBuffer = function () { return a } }, HistoryMessagesOuput: function () { var a={}; this.setList=function(b){ a.list=b; }; this.setSyncTime=function(b){ a.syncTime=b; }; this.setHasMsg=function(b){ a.hasMsg=b; }; this.toArrayBuffer = function () { return a } }, HistoryMsgInput: function(){ var a = {}; this.setTargetId = function(b){ a.targetId = b; }; this.setTime = function(b){ a.time = b; }; this.setCount = function(b){ a.count = b; }; this.setOrder = function(b){ a.order = b; }; this.toArrayBuffer = function(){ return a; }; }, HistoryMsgOuput: function(){ var a = {}; this.setList = function(b){ a.list = b; }; this.setSyncTime = function(b){ a.syncTime = b; }; this.setHasMsg = function(b){ a.hasMsg = b; }; this.toArrayBuffer = function(){ return a; }; }, RtcQueryListInput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setOrder = function (b) { a.order = b; }; }, RtcKeyDeleteInput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setKey = function (b) { a.key = b; }; }, RtcValueInfo: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setKey = function (b) { a.key = b; }; this.setValue = function (b) { a.value = b; }; }, // RtcUserInfo: function () { // var a = {}; // }, RtcUserListOutput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setList = function (b) { a.list = b; }; this.setToken = function (b) { a.token = b; }; }, RtcRoomInfoOutput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setRoomId = function (b) { a.roomId = b; }; this.setRoomData = function (b) { a.roomData = b; }; this.setUserCount = function (b) { a.userCount = b; }; this.setList = function (b) { a.list = b; } }, RtcInput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setRoomType = function (b) { a.roomType = b; }; this.setBroadcastType = function (b) { a.broadcastType = b; } }, // RtcQryInput: function () { // var a = {}; // }, RtcQryOutput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setOutInfo = function (b) { a.outInfo = b; }; }, // RtcDelDataInput: function () { // var a = {}; // }, RtcDataInput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setInterior = function (b) { a.interior = b; }; this.setTarget = function (b) { a.target = b; }; this.setKey = function (b) { a.key = b; }; this.setObjectName = function (b) { a.objectName = b; }; this.setContent = function (b) { a.content = b; }; }, RtcSetDataInput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setInterior = function (b) { a.interior = b; }; this.setTarget = function (b) { a.target = b; }; this.setKey = function (b) { a.key = b; }; this.setValue = function (b) { a.value = b; }; this.setObjectName = function (b) { a.objectName = b; }; this.setContent = function (b) { a.content = b; }; }, RtcOutput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setNothing = function (b) { a.nothing = b; }; }, RtcTokenOutput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setRtcToken = function (b) { a.rtcToken = b; } }, /** * 聊天室 KV 存储 */ ChrmNotifyMsg: function () { var a = {}; this.toArrayBuffer = function () { return a; }; this.setType = function (b) { a.type = b; }; this.setTime = function (b) { a.time = b; }; this.setChrmId = function (b) { a.chrmId = b; }; }, ChrmKVEntity: function () { var a = {}; this.toArrayBuffer = function () { return a; }; this.setKey = function (key) { a.key = key; }; this.setValue = function (value) { a.value = value; }; this.setStatus = function (b) { a.status = b; }; this.setTimestamp = function (b) { a.timestamp = b; }; this.setUid = function (b) { a.uid = b; }; }, SetChrmKV: function () { var a = {}; this.toArrayBuffer = function () { return a; }; this.setEntry = function (b) { a.entry = b; }; this.setNotification = function (b) { a.notification = b.toArrayBuffer(); }; this.setBNotify = function (b) { a.bNotify = b; }; this.setType = function (b) { a.type = b; }; }, ChrmKVOutput: function () { var a = {}; this.toArrayBuffer = function () { return a; }; this.setEntries = function (b) { this.entries = b; }; this.setBFullUpdate = function (b) { this.bFullUpdate = b; }; this.setSyncTime = function (b) { this.syncTime = b; }; }, QueryChrmKV: function () { var a = {}; this.toArrayBuffer = function () { return a; }; this.setTimestamp = function (b) { a.timestamp = b; }; }, DeleteChrmKV: function () { var a = {}; this.toArrayBuffer = function () { return a; }; this.setEntry = function (b) { a.entry = b; }; this.setBNotify = function (b) { a.bNotify = b; }; this.setNotification = function (b) { a.notification = b; }; this.setType = function (b) { a.type = b; }; } }; for (var f in Polling) { Polling[f].decode = function (b) { var back = {}, val = JSON.parse(b) || eval("(" + b + ")"); for (var i in val) { back[i]=val[i]; back["get"+ i.charAt(0).toUpperCase()+i.slice(1)]=function(){ return val[i]; } } return back; } } /* * JavaScript MD5 * https://github.com/blueimp/JavaScript-MD5 * * Copyright 2011, Sebastian Tschan * https://blueimp.net * * Licensed under the MIT license: * http://www.opensource.org/licenses/MIT * * Based on * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message * Digest Algorithm, as defined in RFC 1321. * Version 2.2 Copyright (C) Paul Johnston 1999 - 2009 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet * Distributed under the BSD License * See http://pajhome.org.uk/crypt/md5 for more info. */ /*jslint bitwise: true */ /*global unescape, define, module */ var md5 = (function () { 'use strict'; /* * Add integers, wrapping at 2^32. This uses 16-bit operations internally * to work around bugs in some JS interpreters. */ function safe_add(x, y) { var lsw = (x & 0xFFFF) + (y & 0xFFFF), msw = (x >> 16) + (y >> 16) + (lsw >> 16); return (msw << 16) | (lsw & 0xFFFF); } /* * Bitwise rotate a 32-bit number to the left. */ function bit_rol(num, cnt) { return (num << cnt) | (num >>> (32 - cnt)); } /* * These functions implement the four basic operations the algorithm uses. */ function md5_cmn(q, a, b, x, s, t) { return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s), b); } function md5_ff(a, b, c, d, x, s, t) { return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t); } function md5_gg(a, b, c, d, x, s, t) { return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t); } function md5_hh(a, b, c, d, x, s, t) { return md5_cmn(b ^ c ^ d, a, b, x, s, t); } function md5_ii(a, b, c, d, x, s, t) { return md5_cmn(c ^ (b | (~d)), a, b, x, s, t); } /* * Calculate the MD5 of an array of little-endian words, and a bit length. */ function binl_md5(x, len) { /* append padding */ x[len >> 5] |= 0x80 << (len % 32); x[(((len + 64) >>> 9) << 4) + 14] = len; var i, olda, oldb, oldc, oldd, a = 1732584193, b = -271733879, c = -1732584194, d = 271733878; for (i = 0; i < x.length; i += 16) { olda = a; oldb = b; oldc = c; oldd = d; a = md5_ff(a, b, c, d, x[i], 7, -680876936); d = md5_ff(d, a, b, c, x[i + 1], 12, -389564586); c = md5_ff(c, d, a, b, x[i + 2], 17, 606105819); b = md5_ff(b, c, d, a, x[i + 3], 22, -1044525330); a = md5_ff(a, b, c, d, x[i + 4], 7, -176418897); d = md5_ff(d, a, b, c, x[i + 5], 12, 1200080426); c = md5_ff(c, d, a, b, x[i + 6], 17, -1473231341); b = md5_ff(b, c, d, a, x[i + 7], 22, -45705983); a = md5_ff(a, b, c, d, x[i + 8], 7, 1770035416); d = md5_ff(d, a, b, c, x[i + 9], 12, -1958414417); c = md5_ff(c, d, a, b, x[i + 10], 17, -42063); b = md5_ff(b, c, d, a, x[i + 11], 22, -1990404162); a = md5_ff(a, b, c, d, x[i + 12], 7, 1804603682); d = md5_ff(d, a, b, c, x[i + 13], 12, -40341101); c = md5_ff(c, d, a, b, x[i + 14], 17, -1502002290); b = md5_ff(b, c, d, a, x[i + 15], 22, 1236535329); a = md5_gg(a, b, c, d, x[i + 1], 5, -165796510); d = md5_gg(d, a, b, c, x[i + 6], 9, -1069501632); c = md5_gg(c, d, a, b, x[i + 11], 14, 643717713); b = md5_gg(b, c, d, a, x[i], 20, -373897302); a = md5_gg(a, b, c, d, x[i + 5], 5, -701558691); d = md5_gg(d, a, b, c, x[i + 10], 9, 38016083); c = md5_gg(c, d, a, b, x[i + 15], 14, -660478335); b = md5_gg(b, c, d, a, x[i + 4], 20, -405537848); a = md5_gg(a, b, c, d, x[i + 9], 5, 568446438); d = md5_gg(d, a, b, c, x[i + 14], 9, -1019803690); c = md5_gg(c, d, a, b, x[i + 3], 14, -187363961); b = md5_gg(b, c, d, a, x[i + 8], 20, 1163531501); a = md5_gg(a, b, c, d, x[i + 13], 5, -1444681467); d = md5_gg(d, a, b, c, x[i + 2], 9, -51403784); c = md5_gg(c, d, a, b, x[i + 7], 14, 1735328473); b = md5_gg(b, c, d, a, x[i + 12], 20, -1926607734); a = md5_hh(a, b, c, d, x[i + 5], 4, -378558); d = md5_hh(d, a, b, c, x[i + 8], 11, -2022574463); c = md5_hh(c, d, a, b, x[i + 11], 16, 1839030562); b = md5_hh(b, c, d, a, x[i + 14], 23, -35309556); a = md5_hh(a, b, c, d, x[i + 1], 4, -1530992060); d = md5_hh(d, a, b, c, x[i + 4], 11, 1272893353); c = md5_hh(c, d, a, b, x[i + 7], 16, -155497632); b = md5_hh(b, c, d, a, x[i + 10], 23, -1094730640); a = md5_hh(a, b, c, d, x[i + 13], 4, 681279174); d = md5_hh(d, a, b, c, x[i], 11, -358537222); c = md5_hh(c, d, a, b, x[i + 3], 16, -722521979); b = md5_hh(b, c, d, a, x[i + 6], 23, 76029189); a = md5_hh(a, b, c, d, x[i + 9], 4, -640364487); d = md5_hh(d, a, b, c, x[i + 12], 11, -421815835); c = md5_hh(c, d, a, b, x[i + 15], 16, 530742520); b = md5_hh(b, c, d, a, x[i + 2], 23, -995338651); a = md5_ii(a, b, c, d, x[i], 6, -198630844); d = md5_ii(d, a, b, c, x[i + 7], 10, 1126891415); c = md5_ii(c, d, a, b, x[i + 14], 15, -1416354905); b = md5_ii(b, c, d, a, x[i + 5], 21, -57434055); a = md5_ii(a, b, c, d, x[i + 12], 6, 1700485571); d = md5_ii(d, a, b, c, x[i + 3], 10, -1894986606); c = md5_ii(c, d, a, b, x[i + 10], 15, -1051523); b = md5_ii(b, c, d, a, x[i + 1], 21, -2054922799); a = md5_ii(a, b, c, d, x[i + 8], 6, 1873313359); d = md5_ii(d, a, b, c, x[i + 15], 10, -30611744); c = md5_ii(c, d, a, b, x[i + 6], 15, -1560198380); b = md5_ii(b, c, d, a, x[i + 13], 21, 1309151649); a = md5_ii(a, b, c, d, x[i + 4], 6, -145523070); d = md5_ii(d, a, b, c, x[i + 11], 10, -1120210379); c = md5_ii(c, d, a, b, x[i + 2], 15, 718787259); b = md5_ii(b, c, d, a, x[i + 9], 21, -343485551); a = safe_add(a, olda); b = safe_add(b, oldb); c = safe_add(c, oldc); d = safe_add(d, oldd); } return [a, b, c, d]; } /* * Convert an array of little-endian words to a string */ function binl2rstr(input) { var i, output = ''; for (i = 0; i < input.length * 32; i += 8) { output += String.fromCharCode((input[i >> 5] >>> (i % 32)) & 0xFF); } return output; } /* * Convert a raw string to an array of little-endian words * Characters >255 have their high-byte silently ignored. */ function rstr2binl(input) { var i, output = []; output[(input.length >> 2) - 1] = undefined; for (i = 0; i < output.length; i += 1) { output[i] = 0; } for (i = 0; i < input.length * 8; i += 8) { output[i >> 5] |= (input.charCodeAt(i / 8) & 0xFF) << (i % 32); } return output; } /* * Calculate the MD5 of a raw string */ function rstr_md5(s) { return binl2rstr(binl_md5(rstr2binl(s), s.length * 8)); } /* * Calculate the HMAC-MD5, of a key and some data (raw strings) */ function rstr_hmac_md5(key, data) { var i, bkey = rstr2binl(key), ipad = [], opad = [], hash; ipad[15] = opad[15] = undefined; if (bkey.length > 16) { bkey = binl_md5(bkey, key.length * 8); } for (i = 0; i < 16; i += 1) { ipad[i] = bkey[i] ^ 0x36363636; opad[i] = bkey[i] ^ 0x5C5C5C5C; } hash = binl_md5(ipad.concat(rstr2binl(data)), 512 + data.length * 8); return binl2rstr(binl_md5(opad.concat(hash), 512 + 128)); } /* * Convert a raw string to a hex string */ function rstr2hex(input) { var hex_tab = '0123456789abcdef', output = '', x, i; for (i = 0; i < input.length; i += 1) { x = input.charCodeAt(i); output += hex_tab.charAt((x >>> 4) & 0x0F) + hex_tab.charAt(x & 0x0F); } return output; } /* * Encode a string as utf-8 */ function str2rstr_utf8(input) { return unescape(encodeURIComponent(input)); } /* * Take string arguments and return either raw or hex encoded strings */ function raw_md5(s) { return rstr_md5(str2rstr_utf8(s)); } function hex_md5(s) { return rstr2hex(raw_md5(s)); } function raw_hmac_md5(k, d) { return rstr_hmac_md5(str2rstr_utf8(k), str2rstr_utf8(d)); } function hex_hmac_md5(k, d) { return rstr2hex(raw_hmac_md5(k, d)); } function md5(string, key, raw) { if (!key) { if (!raw) { return hex_md5(string); } return raw_md5(string); } if (!raw) { return hex_hmac_md5(key, string); } return raw_hmac_md5(key, string); } return md5; }()); var RongIMLib; (function (RongIMLib) { (function (MentionedType) { MentionedType[MentionedType["ALL"] = 1] = "ALL"; MentionedType[MentionedType["PART"] = 2] = "PART"; })(RongIMLib.MentionedType || (RongIMLib.MentionedType = {})); var MentionedType = RongIMLib.MentionedType; (function (MethodType) { MethodType[MethodType["CUSTOMER_SERVICE"] = 1] = "CUSTOMER_SERVICE"; MethodType[MethodType["RECALL"] = 2] = "RECALL"; })(RongIMLib.MethodType || (RongIMLib.MethodType = {})); var MethodType = RongIMLib.MethodType; (function (BlacklistStatus) { /** * 在黑名单中。 */ BlacklistStatus[BlacklistStatus["IN_BLACK_LIST"] = 0] = "IN_BLACK_LIST"; /** * 不在黑名单中。 */ BlacklistStatus[BlacklistStatus["NOT_IN_BLACK_LIST"] = 1] = "NOT_IN_BLACK_LIST"; })(RongIMLib.BlacklistStatus || (RongIMLib.BlacklistStatus = {})); var BlacklistStatus = RongIMLib.BlacklistStatus; (function (ConnectionChannel) { ConnectionChannel[ConnectionChannel["XHR_POLLING"] = 0] = "XHR_POLLING"; ConnectionChannel[ConnectionChannel["WEBSOCKET"] = 1] = "WEBSOCKET"; //外部调用 ConnectionChannel[ConnectionChannel["HTTP"] = 0] = "HTTP"; //外部调用 ConnectionChannel[ConnectionChannel["HTTPS"] = 1] = "HTTPS"; })(RongIMLib.ConnectionChannel || (RongIMLib.ConnectionChannel = {})); var ConnectionChannel = RongIMLib.ConnectionChannel; (function (CustomerType) { CustomerType[CustomerType["ONLY_ROBOT"] = 1] = "ONLY_ROBOT"; CustomerType[CustomerType["ONLY_HUMAN"] = 2] = "ONLY_HUMAN"; CustomerType[CustomerType["ROBOT_FIRST"] = 3] = "ROBOT_FIRST"; CustomerType[CustomerType["HUMAN_FIRST"] = 4] = "HUMAN_FIRST"; })(RongIMLib.CustomerType || (RongIMLib.CustomerType = {})); var CustomerType = RongIMLib.CustomerType; (function (GetChatRoomType) { GetChatRoomType[GetChatRoomType["NONE"] = 0] = "NONE"; GetChatRoomType[GetChatRoomType["SQQUENCE"] = 1] = "SQQUENCE"; GetChatRoomType[GetChatRoomType["REVERSE"] = 2] = "REVERSE"; })(RongIMLib.GetChatRoomType || (RongIMLib.GetChatRoomType = {})); var GetChatRoomType = RongIMLib.GetChatRoomType; (function (ConnectionStatus) { /** * 连接成功。 */ ConnectionStatus[ConnectionStatus["CONNECTED"] = 0] = "CONNECTED"; /** * 连接中。 */ ConnectionStatus[ConnectionStatus["CONNECTING"] = 1] = "CONNECTING"; /** * 断开连接。 */ ConnectionStatus[ConnectionStatus["DISCONNECTED"] = 2] = "DISCONNECTED"; /** * 用户账户在其他设备登录,本机会被踢掉线。 */ ConnectionStatus[ConnectionStatus["KICKED_OFFLINE_BY_OTHER_CLIENT"] = 6] = "KICKED_OFFLINE_BY_OTHER_CLIENT"; /** * websocket 连接失败 */ ConnectionStatus[ConnectionStatus["WEBSOCKET_UNAVAILABLE"] = 7] = "WEBSOCKET_UNAVAILABLE"; /** * websocket 报错 */ ConnectionStatus[ConnectionStatus["WEBSOCKET_ERROR"] = 8] = "WEBSOCKET_ERROR"; /** * 网络不可用。 */ ConnectionStatus[ConnectionStatus["NETWORK_UNAVAILABLE"] = 3] = "NETWORK_UNAVAILABLE"; /** * 域名错误 */ ConnectionStatus[ConnectionStatus["DOMAIN_INCORRECT"] = 12] = "DOMAIN_INCORRECT"; /** * appkey 不正确 */ ConnectionStatus[ConnectionStatus["APPKEY_IS_FAKE"] = 20] = "APPKEY_IS_FAKE"; /** * 连接关闭。 */ ConnectionStatus[ConnectionStatus["CONNECTION_CLOSED"] = 4] = "CONNECTION_CLOSED"; /* 互踢次数过多(count > 5),此时可能出现:在其它他设备登陆有 reconnect 逻辑 */ ConnectionStatus[ConnectionStatus["ULTRALIMIT"] = 1101] = "ULTRALIMIT"; /* 开始请求导航 */ ConnectionStatus[ConnectionStatus["REQUEST_NAVI"] = 201] = "REQUEST_NAVI"; /* 请求导航结束 */ ConnectionStatus[ConnectionStatus["RESPONSE_NAVI"] = 202] = "RESPONSE_NAVI"; /* 请求导航失败 */ ConnectionStatus[ConnectionStatus["RESPONSE_NAVI_ERROR"] = 203] = "RESPONSE_NAVI_ERROR"; /* 请求导航超时 */ ConnectionStatus[ConnectionStatus["RESPONSE_NAVI_TIMEOUT"] = 204] = "RESPONSE_NAVI_TIMEOUT"; })(RongIMLib.ConnectionStatus || (RongIMLib.ConnectionStatus = {})); var ConnectionStatus = RongIMLib.ConnectionStatus; (function (ConversationNotificationStatus) { /** * 免打扰状态,关闭对应会话的通知提醒。 */ ConversationNotificationStatus[ConversationNotificationStatus["DO_NOT_DISTURB"] = 0] = "DO_NOT_DISTURB"; /** * 提醒。 */ ConversationNotificationStatus[ConversationNotificationStatus["NOTIFY"] = 1] = "NOTIFY"; })(RongIMLib.ConversationNotificationStatus || (RongIMLib.ConversationNotificationStatus = {})); var ConversationNotificationStatus = RongIMLib.ConversationNotificationStatus; (function (ConversationType) { ConversationType[ConversationType["NONE"] = 0] = "NONE"; ConversationType[ConversationType["PRIVATE"] = 1] = "PRIVATE"; ConversationType[ConversationType["DISCUSSION"] = 2] = "DISCUSSION"; ConversationType[ConversationType["GROUP"] = 3] = "GROUP"; ConversationType[ConversationType["CHATROOM"] = 4] = "CHATROOM"; ConversationType[ConversationType["CUSTOMER_SERVICE"] = 5] = "CUSTOMER_SERVICE"; ConversationType[ConversationType["SYSTEM"] = 6] = "SYSTEM"; //默认关注 MC ConversationType[ConversationType["APP_PUBLIC_SERVICE"] = 7] = "APP_PUBLIC_SERVICE"; //手工关注 MP ConversationType[ConversationType["PUBLIC_SERVICE"] = 8] = "PUBLIC_SERVICE"; })(RongIMLib.ConversationType || (RongIMLib.ConversationType = {})); var ConversationType = RongIMLib.ConversationType; (function (DiscussionInviteStatus) { /** * 开放邀请。 */ DiscussionInviteStatus[DiscussionInviteStatus["OPENED"] = 0] = "OPENED"; /** * 关闭邀请。 */ DiscussionInviteStatus[DiscussionInviteStatus["CLOSED"] = 1] = "CLOSED"; })(RongIMLib.DiscussionInviteStatus || (RongIMLib.DiscussionInviteStatus = {})); var DiscussionInviteStatus = RongIMLib.DiscussionInviteStatus; (function (ErrorCode) { /* 超时 */ ErrorCode[ErrorCode["TIMEOUT"] = -1] = "TIMEOUT"; /** * 未知原因失败。 */ ErrorCode[ErrorCode["UNKNOWN"] = -2] = "UNKNOWN"; /* 参数错误 */ ErrorCode[ErrorCode["PARAMETER_ERROR"] = -3] = "PARAMETER_ERROR"; ErrorCode[ErrorCode["RECALL_MESSAGE"] = 25101] = "RECALL_MESSAGE"; /** * 发送频率过快 */ ErrorCode[ErrorCode["SEND_FREQUENCY_TOO_FAST"] = 20604] = "SEND_FREQUENCY_TOO_FAST"; ErrorCode[ErrorCode["RC_MSG_UNAUTHORIZED"] = 20406] = "RC_MSG_UNAUTHORIZED"; /** * 群组 Id 无效 */ ErrorCode[ErrorCode["RC_DISCUSSION_GROUP_ID_INVALID"] = 20407] = "RC_DISCUSSION_GROUP_ID_INVALID"; /** * 群组被禁言 */ ErrorCode[ErrorCode["FORBIDDEN_IN_GROUP"] = 22408] = "FORBIDDEN_IN_GROUP"; /** * 不在讨论组。 */ ErrorCode[ErrorCode["NOT_IN_DISCUSSION"] = 21406] = "NOT_IN_DISCUSSION"; /** * 不在群组。 */ ErrorCode[ErrorCode["NOT_IN_GROUP"] = 22406] = "NOT_IN_GROUP"; /** * 不在聊天室。 */ ErrorCode[ErrorCode["NOT_IN_CHATROOM"] = 23406] = "NOT_IN_CHATROOM"; /** *聊天室被禁言 */ ErrorCode[ErrorCode["FORBIDDEN_IN_CHATROOM"] = 23408] = "FORBIDDEN_IN_CHATROOM"; /** * 聊天室中成员被踢出 */ ErrorCode[ErrorCode["RC_CHATROOM_USER_KICKED"] = 23409] = "RC_CHATROOM_USER_KICKED"; /** * 聊天室不存在 */ ErrorCode[ErrorCode["RC_CHATROOM_NOT_EXIST"] = 23410] = "RC_CHATROOM_NOT_EXIST"; /** * 聊天室成员已满 */ ErrorCode[ErrorCode["RC_CHATROOM_IS_FULL"] = 23411] = "RC_CHATROOM_IS_FULL"; /** * 获取聊天室信息参数无效 */ ErrorCode[ErrorCode["RC_CHATROOM_PATAMETER_INVALID"] = 23412] = "RC_CHATROOM_PATAMETER_INVALID"; /** * 聊天室异常 */ ErrorCode[ErrorCode["CHATROOM_GET_HISTORYMSG_ERROR"] = 23413] = "CHATROOM_GET_HISTORYMSG_ERROR"; /** * 没有打开聊天室消息存储 */ ErrorCode[ErrorCode["CHATROOM_NOT_OPEN_HISTORYMSG_STORE"] = 23414] = "CHATROOM_NOT_OPEN_HISTORYMSG_STORE"; /** * 聊天室 KV 设置超出最大值(已满, 默认最多设置 100 个) */ ErrorCode[ErrorCode["CHATROOM_KV_EXCEED"] = 23423] = "CHATROOM_KV_EXCEED"; /** * 聊天室 KV 设置失败(kv 已存在, 需覆盖设置) */ ErrorCode[ErrorCode["CHATROOM_KV_OVERWRITE_INVALID"] = 23424] = "CHATROOM_KV_OVERWRITE_INVALID"; /** * 聊天室 KV 存储功能没有开通 */ ErrorCode[ErrorCode["CHATROOM_KV_STORE_NOT_OPEN"] = 23426] = "CHATROOM_KV_STORE_NOT_OPEN"; /** * 聊天室Key不存在 */ ErrorCode[ErrorCode["CHATROOM_KEY_NOT_EXIST"] = 23427] = "CHATROOM_KEY_NOT_EXIST"; /** * 敏感词屏蔽 */ ErrorCode[ErrorCode["SENSITIVE_SHIELD"] = 21501] = "SENSITIVE_SHIELD"; ErrorCode[ErrorCode["SENSITIVE_REPLACE"] = 21502] = "SENSITIVE_REPLACE"; /** * 加入讨论失败 */ ErrorCode[ErrorCode["JOIN_IN_DISCUSSION"] = 21407] = "JOIN_IN_DISCUSSION"; /** * 创建讨论组失败 */ ErrorCode[ErrorCode["CREATE_DISCUSSION"] = 21408] = "CREATE_DISCUSSION"; /** * 设置讨论组邀请状态失败 */ ErrorCode[ErrorCode["INVITE_DICUSSION"] = 21409] = "INVITE_DICUSSION"; /** *获取用户失败 */ ErrorCode[ErrorCode["GET_USERINFO_ERROR"] = 23407] = "GET_USERINFO_ERROR"; /** * 在黑名单中。 */ ErrorCode[ErrorCode["REJECTED_BY_BLACKLIST"] = 405] = "REJECTED_BY_BLACKLIST"; /** * 通信过程中,当前 Socket 不存在。 */ ErrorCode[ErrorCode["RC_NET_CHANNEL_INVALID"] = 30001] = "RC_NET_CHANNEL_INVALID"; /** * Socket 连接不可用。 */ ErrorCode[ErrorCode["RC_NET_UNAVAILABLE"] = 30002] = "RC_NET_UNAVAILABLE"; /** * 通信超时。 */ ErrorCode[ErrorCode["RC_MSG_RESP_TIMEOUT"] = 30003] = "RC_MSG_RESP_TIMEOUT"; /** * 导航操作时,Http 请求失败。 */ ErrorCode[ErrorCode["RC_HTTP_SEND_FAIL"] = 30004] = "RC_HTTP_SEND_FAIL"; /** * HTTP 请求失败。 */ ErrorCode[ErrorCode["RC_HTTP_REQ_TIMEOUT"] = 30005] = "RC_HTTP_REQ_TIMEOUT"; /** * HTTP 接收失败。 */ ErrorCode[ErrorCode["RC_HTTP_RECV_FAIL"] = 30006] = "RC_HTTP_RECV_FAIL"; /** * 导航操作的 HTTP 请求,返回不是200。 */ ErrorCode[ErrorCode["RC_NAVI_RESOURCE_ERROR"] = 30007] = "RC_NAVI_RESOURCE_ERROR"; /** * 导航数据解析后,其中不存在有效数据。 */ ErrorCode[ErrorCode["RC_NODE_NOT_FOUND"] = 30008] = "RC_NODE_NOT_FOUND"; /** * 导航数据解析后,其中不存在有效 IP 地址。 */ ErrorCode[ErrorCode["RC_DOMAIN_NOT_RESOLVE"] = 30009] = "RC_DOMAIN_NOT_RESOLVE"; /** * 创建 Socket 失败。 */ ErrorCode[ErrorCode["RC_SOCKET_NOT_CREATED"] = 30010] = "RC_SOCKET_NOT_CREATED"; /** * Socket 被断开。 */ ErrorCode[ErrorCode["RC_SOCKET_DISCONNECTED"] = 30011] = "RC_SOCKET_DISCONNECTED"; /** * PING 操作失败。 */ ErrorCode[ErrorCode["RC_PING_SEND_FAIL"] = 30012] = "RC_PING_SEND_FAIL"; /** * PING 超时。 */ ErrorCode[ErrorCode["RC_PONG_RECV_FAIL"] = 30013] = "RC_PONG_RECV_FAIL"; /** * 消息发送失败。 */ ErrorCode[ErrorCode["RC_MSG_SEND_FAIL"] = 30014] = "RC_MSG_SEND_FAIL"; /** * 做 connect 连接时,收到的 ACK 超时。 */ ErrorCode[ErrorCode["RC_CONN_ACK_TIMEOUT"] = 31000] = "RC_CONN_ACK_TIMEOUT"; /** * 参数错误。 */ ErrorCode[ErrorCode["RC_CONN_PROTO_VERSION_ERROR"] = 31001] = "RC_CONN_PROTO_VERSION_ERROR"; /** * 参数错误,App Id 错误。 */ ErrorCode[ErrorCode["RC_CONN_ID_REJECT"] = 31002] = "RC_CONN_ID_REJECT"; /** * 服务器不可用。 */ ErrorCode[ErrorCode["RC_CONN_SERVER_UNAVAILABLE"] = 31003] = "RC_CONN_SERVER_UNAVAILABLE"; /** * Token 错误。 */ ErrorCode[ErrorCode["RC_CONN_USER_OR_PASSWD_ERROR"] = 31004] = "RC_CONN_USER_OR_PASSWD_ERROR"; /** * App Id 与 Token 不匹配。 */ ErrorCode[ErrorCode["RC_CONN_NOT_AUTHRORIZED"] = 31005] = "RC_CONN_NOT_AUTHRORIZED"; /** * 重定向,地址错误。 */ ErrorCode[ErrorCode["RC_CONN_REDIRECTED"] = 31006] = "RC_CONN_REDIRECTED"; /** * NAME 与后台注册信息不一致。 */ ErrorCode[ErrorCode["RC_CONN_PACKAGE_NAME_INVALID"] = 31007] = "RC_CONN_PACKAGE_NAME_INVALID"; /** * APP 被屏蔽、删除或不存在。 */ ErrorCode[ErrorCode["RC_CONN_APP_BLOCKED_OR_DELETED"] = 31008] = "RC_CONN_APP_BLOCKED_OR_DELETED"; /** * 用户被屏蔽。 */ ErrorCode[ErrorCode["RC_CONN_USER_BLOCKED"] = 31009] = "RC_CONN_USER_BLOCKED"; /** * Disconnect,由服务器返回,比如用户互踢。 */ ErrorCode[ErrorCode["RC_DISCONN_KICK"] = 31010] = "RC_DISCONN_KICK"; /** * Disconnect,由服务器返回,比如用户互踢。 */ ErrorCode[ErrorCode["RC_DISCONN_EXCEPTION"] = 31011] = "RC_DISCONN_EXCEPTION"; /** * 协议层内部错误。query,上传下载过程中数据错误。 */ ErrorCode[ErrorCode["RC_QUERY_ACK_NO_DATA"] = 32001] = "RC_QUERY_ACK_NO_DATA"; /** * 协议层内部错误。 */ ErrorCode[ErrorCode["RC_MSG_DATA_INCOMPLETE"] = 32002] = "RC_MSG_DATA_INCOMPLETE"; /** * 未调用 init 初始化函数。 */ ErrorCode[ErrorCode["BIZ_ERROR_CLIENT_NOT_INIT"] = 33001] = "BIZ_ERROR_CLIENT_NOT_INIT"; /** * 数据库初始化失败。 */ ErrorCode[ErrorCode["BIZ_ERROR_DATABASE_ERROR"] = 33002] = "BIZ_ERROR_DATABASE_ERROR"; /** * 传入参数无效。 */ ErrorCode[ErrorCode["BIZ_ERROR_INVALID_PARAMETER"] = 33003] = "BIZ_ERROR_INVALID_PARAMETER"; /** * 通道无效。 */ ErrorCode[ErrorCode["BIZ_ERROR_NO_CHANNEL"] = 33004] = "BIZ_ERROR_NO_CHANNEL"; /** * 重新连接成功。 */ ErrorCode[ErrorCode["BIZ_ERROR_RECONNECT_SUCCESS"] = 33005] = "BIZ_ERROR_RECONNECT_SUCCESS"; /** * 连接中,再调用 connect 被拒绝。 */ ErrorCode[ErrorCode["BIZ_ERROR_CONNECTING"] = 33006] = "BIZ_ERROR_CONNECTING"; /** * 消息漫游服务未开通 */ ErrorCode[ErrorCode["MSG_ROAMING_SERVICE_UNAVAILABLE"] = 33007] = "MSG_ROAMING_SERVICE_UNAVAILABLE"; ErrorCode[ErrorCode["MSG_INSERT_ERROR"] = 33008] = "MSG_INSERT_ERROR"; ErrorCode[ErrorCode["MSG_DEL_ERROR"] = 33009] = "MSG_DEL_ERROR"; /** * 删除会话失败 */ ErrorCode[ErrorCode["CONVER_REMOVE_ERROR"] = 34001] = "CONVER_REMOVE_ERROR"; /** *拉取历史消息 */ ErrorCode[ErrorCode["CONVER_GETLIST_ERROR"] = 34002] = "CONVER_GETLIST_ERROR"; /** * 会话指定异常 */ ErrorCode[ErrorCode["CONVER_SETOP_ERROR"] = 34003] = "CONVER_SETOP_ERROR"; /** * 获取会话未读消息总数失败 */ ErrorCode[ErrorCode["CONVER_TOTAL_UNREAD_ERROR"] = 34004] = "CONVER_TOTAL_UNREAD_ERROR"; /** * 获取指定会话类型未读消息数异常 */ ErrorCode[ErrorCode["CONVER_TYPE_UNREAD_ERROR"] = 34005] = "CONVER_TYPE_UNREAD_ERROR"; /** * 获取指定用户ID&会话类型未读消息数异常 */ ErrorCode[ErrorCode["CONVER_ID_TYPE_UNREAD_ERROR"] = 34006] = "CONVER_ID_TYPE_UNREAD_ERROR"; ErrorCode[ErrorCode["CONVER_CLEAR_ERROR"] = 34007] = "CONVER_CLEAR_ERROR"; ErrorCode[ErrorCode["CLEAR_HIS_ERROR"] = 34010] = "CLEAR_HIS_ERROR"; ErrorCode[ErrorCode["CLEAR_HIS_TYPE_ERROR"] = 34008] = "CLEAR_HIS_TYPE_ERROR"; ErrorCode[ErrorCode["CLEAR_HIS_TIME_ERROR"] = 34011] = "CLEAR_HIS_TIME_ERROR"; /* */ ErrorCode[ErrorCode["CONVER_GET_ERROR"] = 34009] = "CONVER_GET_ERROR"; //群组异常信息 /** * */ ErrorCode[ErrorCode["GROUP_SYNC_ERROR"] = 35001] = "GROUP_SYNC_ERROR"; /** * 匹配群信息异常 */ ErrorCode[ErrorCode["GROUP_MATCH_ERROR"] = 35002] = "GROUP_MATCH_ERROR"; //聊天室异常 /** * 加入聊天室Id为空 */ ErrorCode[ErrorCode["CHATROOM_ID_ISNULL"] = 36001] = "CHATROOM_ID_ISNULL"; /** * 加入聊天室失败 */ ErrorCode[ErrorCode["CHARTOOM_JOIN_ERROR"] = 36002] = "CHARTOOM_JOIN_ERROR"; /** * 拉取聊天室历史消息失败 */ ErrorCode[ErrorCode["CHATROOM_HISMESSAGE_ERROR"] = 36003] = "CHATROOM_HISMESSAGE_ERROR"; /** * 聊天室 kv 未找到 * */ ErrorCode[ErrorCode["CHATROOM_KV_NOT_FOUND"] = 36004] = "CHATROOM_KV_NOT_FOUND"; //黑名单异常 /** * 加入黑名单异常 */ ErrorCode[ErrorCode["BLACK_ADD_ERROR"] = 37001] = "BLACK_ADD_ERROR"; /** * 获得指定人员再黑名单中的状态异常 */ ErrorCode[ErrorCode["BLACK_GETSTATUS_ERROR"] = 37002] = "BLACK_GETSTATUS_ERROR"; /** * 移除黑名单异常 */ ErrorCode[ErrorCode["BLACK_REMOVE_ERROR"] = 37003] = "BLACK_REMOVE_ERROR"; /** * 获取草稿失败 */ ErrorCode[ErrorCode["DRAF_GET_ERROR"] = 38001] = "DRAF_GET_ERROR"; /** * 保存草稿失败 */ ErrorCode[ErrorCode["DRAF_SAVE_ERROR"] = 38002] = "DRAF_SAVE_ERROR"; /** * 删除草稿失败 */ ErrorCode[ErrorCode["DRAF_REMOVE_ERROR"] = 38003] = "DRAF_REMOVE_ERROR"; /** * 关注公众号失败 */ ErrorCode[ErrorCode["SUBSCRIBE_ERROR"] = 39001] = "SUBSCRIBE_ERROR"; /** * 关注公众号失败 */ ErrorCode[ErrorCode["QNTKN_FILETYPE_ERROR"] = 41001] = "QNTKN_FILETYPE_ERROR"; /** * 获取七牛token失败 */ ErrorCode[ErrorCode["QNTKN_GET_ERROR"] = 41002] = "QNTKN_GET_ERROR"; /** * cookie被禁用 */ ErrorCode[ErrorCode["COOKIE_ENABLE"] = 51001] = "COOKIE_ENABLE"; ErrorCode[ErrorCode["GET_MESSAGE_BY_ID_ERROR"] = 61001] = "GET_MESSAGE_BY_ID_ERROR"; // 没有注册DeviveId 也就是用户没有登陆 ErrorCode[ErrorCode["HAVNODEVICEID"] = 24001] = "HAVNODEVICEID"; // 已经存在 ErrorCode[ErrorCode["DEVICEIDISHAVE"] = 24002] = "DEVICEIDISHAVE"; // 成功 ErrorCode[ErrorCode["SUCCESS"] = 0] = "SUCCESS"; // 没有对应的用户或token ErrorCode[ErrorCode["FEILD"] = 24009] = "FEILD"; // voip为空 ErrorCode[ErrorCode["VOIPISNULL"] = 24013] = "VOIPISNULL"; // 不支持的Voip引擎 ErrorCode[ErrorCode["NOENGINETYPE"] = 24010] = "NOENGINETYPE"; // channleName 是空 ErrorCode[ErrorCode["NULLCHANNELNAME"] = 24011] = "NULLCHANNELNAME"; // 生成Voipkey失败 ErrorCode[ErrorCode["VOIPDYANMICERROR"] = 24012] = "VOIPDYANMICERROR"; // 没有配置voip ErrorCode[ErrorCode["NOVOIP"] = 24014] = "NOVOIP"; // 服务器内部错误 ErrorCode[ErrorCode["INTERNALERRROR"] = 24015] = "INTERNALERRROR"; //VOIP close ErrorCode[ErrorCode["VOIPCLOSE"] = 24016] = "VOIPCLOSE"; ErrorCode[ErrorCode["CLOSE_BEFORE_OPEN"] = 51001] = "CLOSE_BEFORE_OPEN"; ErrorCode[ErrorCode["ALREADY_IN_USE"] = 51002] = "ALREADY_IN_USE"; ErrorCode[ErrorCode["INVALID_CHANNEL_NAME"] = 51003] = "INVALID_CHANNEL_NAME"; ErrorCode[ErrorCode["VIDEO_CONTAINER_IS_NULL"] = 51004] = "VIDEO_CONTAINER_IS_NULL"; /** * 删除消息数组长度为 0 . */ ErrorCode[ErrorCode["DELETE_MESSAGE_ID_IS_NULL"] = 61001] = "DELETE_MESSAGE_ID_IS_NULL"; /*! 己方取消已发出的通话请求 */ ErrorCode[ErrorCode["CANCEL"] = 1] = "CANCEL"; /*! 己方拒绝收到的通话请求 */ ErrorCode[ErrorCode["REJECT"] = 2] = "REJECT"; /*! 己方挂断 */ ErrorCode[ErrorCode["HANGUP"] = 3] = "HANGUP"; /*! 己方忙碌 */ ErrorCode[ErrorCode["BUSYLINE"] = 4] = "BUSYLINE"; /*! 己方未接听 */ ErrorCode[ErrorCode["NO_RESPONSE"] = 5] = "NO_RESPONSE"; /*! 己方不支持当前引擎 */ ErrorCode[ErrorCode["ENGINE_UN_SUPPORTED"] = 6] = "ENGINE_UN_SUPPORTED"; /*! 己方网络出错 */ ErrorCode[ErrorCode["NETWORK_ERROR"] = 7] = "NETWORK_ERROR"; /*! 对方取消已发出的通话请求 */ ErrorCode[ErrorCode["REMOTE_CANCEL"] = 11] = "REMOTE_CANCEL"; /*! 对方拒绝收到的通话请求 */ ErrorCode[ErrorCode["REMOTE_REJECT"] = 12] = "REMOTE_REJECT"; /*! 通话过程对方挂断 */ ErrorCode[ErrorCode["REMOTE_HANGUP"] = 13] = "REMOTE_HANGUP"; /*! 对方忙碌 */ ErrorCode[ErrorCode["REMOTE_BUSYLINE"] = 14] = "REMOTE_BUSYLINE"; /*! 对方未接听 */ ErrorCode[ErrorCode["REMOTE_NO_RESPONSE"] = 15] = "REMOTE_NO_RESPONSE"; /*! 对方网络错误 */ ErrorCode[ErrorCode["REMOTE_ENGINE_UN_SUPPORTED"] = 16] = "REMOTE_ENGINE_UN_SUPPORTED"; /*! 对方网络错误 */ ErrorCode[ErrorCode["REMOTE_NETWORK_ERROR"] = 17] = "REMOTE_NETWORK_ERROR"; /*! VoIP 不可用 */ ErrorCode[ErrorCode["VOIP_NOT_AVALIABLE"] = 18] = "VOIP_NOT_AVALIABLE"; })(RongIMLib.ErrorCode || (RongIMLib.ErrorCode = {})); var ErrorCode = RongIMLib.ErrorCode; (function (VoIPMediaType) { VoIPMediaType[VoIPMediaType["MEDIA_AUDIO"] = 1] = "MEDIA_AUDIO"; VoIPMediaType[VoIPMediaType["MEDIA_VEDIO"] = 2] = "MEDIA_VEDIO"; VoIPMediaType[VoIPMediaType["MEDIA_VIDEO"] = 2] = "MEDIA_VIDEO"; })(RongIMLib.VoIPMediaType || (RongIMLib.VoIPMediaType = {})); var VoIPMediaType = RongIMLib.VoIPMediaType; (function (MediaType) { /** * 图片。 */ MediaType[MediaType["IMAGE"] = 1] = "IMAGE"; /** * 声音。 */ MediaType[MediaType["AUDIO"] = 2] = "AUDIO"; /** * 视频。 */ MediaType[MediaType["VIDEO"] = 3] = "VIDEO"; /** * 通用文件。 */ MediaType[MediaType["FILE"] = 100] = "FILE"; })(RongIMLib.MediaType || (RongIMLib.MediaType = {})); var MediaType = RongIMLib.MediaType; (function (MessageDirection) { /** * 发送消息。 */ MessageDirection[MessageDirection["SEND"] = 1] = "SEND"; /** * 接收消息。 */ MessageDirection[MessageDirection["RECEIVE"] = 2] = "RECEIVE"; })(RongIMLib.MessageDirection || (RongIMLib.MessageDirection = {})); var MessageDirection = RongIMLib.MessageDirection; (function (FileType) { FileType[FileType["IMAGE"] = 1] = "IMAGE"; FileType[FileType["AUDIO"] = 2] = "AUDIO"; FileType[FileType["VIDEO"] = 3] = "VIDEO"; FileType[FileType["FILE"] = 4] = "FILE"; })(RongIMLib.FileType || (RongIMLib.FileType = {})); var FileType = RongIMLib.FileType; (function (RealTimeLocationErrorCode) { /** * 未初始化 RealTimeLocation 实例 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_NOT_INIT"] = -1] = "RC_REAL_TIME_LOCATION_NOT_INIT"; /** * 执行成功。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_SUCCESS"] = 0] = "RC_REAL_TIME_LOCATION_SUCCESS"; /** * 获取 RealTimeLocation 实例时返回 * GPS 未打开。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_GPS_DISABLED"] = 1] = "RC_REAL_TIME_LOCATION_GPS_DISABLED"; /** * 获取 RealTimeLocation 实例时返回 * 当前会话不支持位置共享。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_CONVERSATION_NOT_SUPPORT"] = 2] = "RC_REAL_TIME_LOCATION_CONVERSATION_NOT_SUPPORT"; /** * 获取 RealTimeLocation 实例时返回 * 对方已发起位置共享。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_IS_ON_GOING"] = 3] = "RC_REAL_TIME_LOCATION_IS_ON_GOING"; /** * Join 时返回 * 当前位置共享已超过最大支持人数。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_EXCEED_MAX_PARTICIPANT"] = 4] = "RC_REAL_TIME_LOCATION_EXCEED_MAX_PARTICIPANT"; /** * Join 时返回 * 加入位置共享失败。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_JOIN_FAILURE"] = 5] = "RC_REAL_TIME_LOCATION_JOIN_FAILURE"; /** * Start 时返回 * 发起位置共享失败。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_START_FAILURE"] = 6] = "RC_REAL_TIME_LOCATION_START_FAILURE"; /** * 网络不可用。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_NETWORK_UNAVAILABLE"] = 7] = "RC_REAL_TIME_LOCATION_NETWORK_UNAVAILABLE"; })(RongIMLib.RealTimeLocationErrorCode || (RongIMLib.RealTimeLocationErrorCode = {})); var RealTimeLocationErrorCode = RongIMLib.RealTimeLocationErrorCode; (function (RealTimeLocationStatus) { /** * 空闲状态 (默认状态) * 对方或者自己都未发起位置共享业务,或者位置共享业务已结束。 */ RealTimeLocationStatus[RealTimeLocationStatus["RC_REAL_TIME_LOCATION_STATUS_IDLE"] = 0] = "RC_REAL_TIME_LOCATION_STATUS_IDLE"; /** * 呼入状态 (待加入) * 1. 对方发起了位置共享业务,此状态下,自己只能选择加入。 * 2. 自己从已连接的位置共享中退出。 */ RealTimeLocationStatus[RealTimeLocationStatus["RC_REAL_TIME_LOCATION_STATUS_INCOMING"] = 1] = "RC_REAL_TIME_LOCATION_STATUS_INCOMING"; /** * 呼出状态 =(自己创建) * 1. 自己发起位置共享业务,对方只能选择加入。 * 2. 对方从已连接的位置共享业务中退出。 */ RealTimeLocationStatus[RealTimeLocationStatus["RC_REAL_TIME_LOCATION_STATUS_OUTGOING"] = 2] = "RC_REAL_TIME_LOCATION_STATUS_OUTGOING"; /** * 连接状态 (自己加入) * 对方加入了自己发起的位置共享,或者自己加入了对方发起的位置共享。 */ RealTimeLocationStatus[RealTimeLocationStatus["RC_REAL_TIME_LOCATION_STATUS_CONNECTED"] = 3] = "RC_REAL_TIME_LOCATION_STATUS_CONNECTED"; })(RongIMLib.RealTimeLocationStatus || (RongIMLib.RealTimeLocationStatus = {})); var RealTimeLocationStatus = RongIMLib.RealTimeLocationStatus; (function (ReceivedStatus) { ReceivedStatus[ReceivedStatus["READ"] = 1] = "READ"; ReceivedStatus[ReceivedStatus["LISTENED"] = 2] = "LISTENED"; ReceivedStatus[ReceivedStatus["DOWNLOADED"] = 4] = "DOWNLOADED"; ReceivedStatus[ReceivedStatus["RETRIEVED"] = 8] = "RETRIEVED"; ReceivedStatus[ReceivedStatus["UNREAD"] = 0] = "UNREAD"; })(RongIMLib.ReceivedStatus || (RongIMLib.ReceivedStatus = {})); var ReceivedStatus = RongIMLib.ReceivedStatus; (function (ReadStatus) { ReadStatus[ReadStatus["READ"] = 1] = "READ"; ReadStatus[ReadStatus["LISTENED"] = 2] = "LISTENED"; ReadStatus[ReadStatus["DOWNLOADED"] = 4] = "DOWNLOADED"; ReadStatus[ReadStatus["RETRIEVED"] = 8] = "RETRIEVED"; ReadStatus[ReadStatus["UNREAD"] = 0] = "UNREAD"; })(RongIMLib.ReadStatus || (RongIMLib.ReadStatus = {})); var ReadStatus = RongIMLib.ReadStatus; (function (SearchType) { /** * 精确。 */ SearchType[SearchType["EXACT"] = 0] = "EXACT"; /** * 模糊。 */ SearchType[SearchType["FUZZY"] = 1] = "FUZZY"; })(RongIMLib.SearchType || (RongIMLib.SearchType = {})); var SearchType = RongIMLib.SearchType; (function (SentStatus) { /** * 发送中。 */ SentStatus[SentStatus["SENDING"] = 10] = "SENDING"; /** * 发送失败。 */ SentStatus[SentStatus["FAILED"] = 20] = "FAILED"; /** * 已发送。 */ SentStatus[SentStatus["SENT"] = 30] = "SENT"; /** * 对方已接收。 */ SentStatus[SentStatus["RECEIVED"] = 40] = "RECEIVED"; /** * 对方已读。 */ SentStatus[SentStatus["READ"] = 50] = "READ"; /** * 对方已销毁。 */ SentStatus[SentStatus["DESTROYED"] = 60] = "DESTROYED"; })(RongIMLib.SentStatus || (RongIMLib.SentStatus = {})); var SentStatus = RongIMLib.SentStatus; (function (ConnectionState) { ConnectionState[ConnectionState["ACCEPTED"] = 0] = "ACCEPTED"; ConnectionState[ConnectionState["UNACCEPTABLE_PROTOCOL_VERSION"] = 1] = "UNACCEPTABLE_PROTOCOL_VERSION"; ConnectionState[ConnectionState["IDENTIFIER_REJECTED"] = 2] = "IDENTIFIER_REJECTED"; ConnectionState[ConnectionState["SERVER_UNAVAILABLE"] = 3] = "SERVER_UNAVAILABLE"; /** * token无效 */ ConnectionState[ConnectionState["TOKEN_INCORRECT"] = 4] = "TOKEN_INCORRECT"; ConnectionState[ConnectionState["NOT_AUTHORIZED"] = 5] = "NOT_AUTHORIZED"; ConnectionState[ConnectionState["REDIRECT"] = 6] = "REDIRECT"; ConnectionState[ConnectionState["PACKAGE_ERROR"] = 7] = "PACKAGE_ERROR"; ConnectionState[ConnectionState["APP_BLOCK_OR_DELETE"] = 8] = "APP_BLOCK_OR_DELETE"; ConnectionState[ConnectionState["BLOCK"] = 9] = "BLOCK"; ConnectionState[ConnectionState["TOKEN_EXPIRE"] = 10] = "TOKEN_EXPIRE"; ConnectionState[ConnectionState["DEVICE_ERROR"] = 11] = "DEVICE_ERROR"; })(RongIMLib.ConnectionState || (RongIMLib.ConnectionState = {})); var ConnectionState = RongIMLib.ConnectionState; (function (RTCAPIType) { RTCAPIType[RTCAPIType["ROOM"] = 1] = "ROOM"; RTCAPIType[RTCAPIType["PERSON"] = 2] = "PERSON"; })(RongIMLib.RTCAPIType || (RongIMLib.RTCAPIType = {})); var RTCAPIType = RongIMLib.RTCAPIType; (function (ChatroomEntityOpt) { ChatroomEntityOpt[ChatroomEntityOpt["UPDATE"] = 1] = "UPDATE"; ChatroomEntityOpt[ChatroomEntityOpt["DELETE"] = 2] = "DELETE"; })(RongIMLib.ChatroomEntityOpt || (RongIMLib.ChatroomEntityOpt = {})); var ChatroomEntityOpt = RongIMLib.ChatroomEntityOpt; (function (ChatroomEntityLimit) { ChatroomEntityLimit[ChatroomEntityLimit["KEY"] = 128] = "KEY"; ChatroomEntityLimit[ChatroomEntityLimit["VALUE"] = 4096] = "VALUE"; })(RongIMLib.ChatroomEntityLimit || (RongIMLib.ChatroomEntityLimit = {})); var ChatroomEntityLimit = RongIMLib.ChatroomEntityLimit; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var RongIMClient = (function () { function RongIMClient() { } RongIMClient.getInstance = function () { if (!RongIMClient._instance) { throw new Error("RongIMClient is not initialized. Call .init() method first."); } return RongIMClient._instance; }; RongIMClient.showError = function (errorInfo) { var hasConsole = (console && console.error); if (hasConsole) { console.error(JSON.stringify(errorInfo)); } }; RongIMClient.logger = function (params) { var code = params.code; var errorInfo = RongIMClient.LogFactory[code] || params; errorInfo.funcName = params.funcName; errorInfo.msg = params.msg || errorInfo.msg; if (RongIMClient._memoryStore.depend.showError) { RongIMClient.showError(errorInfo); } }; RongIMClient.logCallback = function (callback, funcName) { return { onSuccess: callback.onSuccess, onError: function (errorCode) { RongIMClient.logger({ code: errorCode, funcName: funcName }); callback.onError(errorCode); } }; }; ; RongIMClient.logSendCallback = function (callback, funcName) { return { onSuccess: callback.onSuccess, onError: function (errorCode, result) { RongIMClient.logger({ code: errorCode, funcName: funcName }); callback.onError(errorCode, result); }, onBefore: callback.onBefore }; }; ; /** * 初始化 SDK,在整个应用全局只需要调用一次。 * @param appKey 开发者后台申请的 AppKey,用来标识应用。 * @param dataAccessProvider 必须是DataAccessProvider的实例 */ RongIMClient.init = function (appKey, dataAccessProvider, options, callback) { RongIMClient.statusListeners = []; RongIMClient.messageListeners = []; if (RongIMClient._instance) { return RongIMClient._memoryStore.sdkInfo; } RongIMClient._instance = new RongIMClient(); options = options || {}; var protocol = "http://", wsScheme = 'ws://'; var isLocationInvalid = typeof location !== 'object'; // 未找到全局 location 变量, 则协议为 https. 比如小程序 if (isLocationInvalid || location.protocol == 'https:') { wsScheme = 'wss://'; protocol = 'https://'; } var isPolling = false; if (typeof WebSocket != 'function') { isPolling = true; } var isIntegrity = function () { //iOS 9 var hasWS = (typeof WebSocket); var integrity = (typeof WebSocket.OPEN == 'number'); return (hasWS && integrity); }; if (typeof WebSocket == 'object' && isIntegrity()) { isPolling = false; } var supportUserData = function () { var element = document.documentElement; return element.addBehavior; }; if (RongIMLib.RongUtil.supportLocalStorage()) { RongIMClient._storageProvider = new RongIMLib.LocalStorageProvider(); } else if (supportUserData()) { RongIMClient._storageProvider = new RongIMLib.UserDataProvider(); } else { RongIMClient._storageProvider = new RongIMLib.MemeoryProvider(); } var serverIndex = RongIMClient._storageProvider.getItem('serverIndex'); RongIMClient.serverStore.index = serverIndex || 0; var pathTmpl = '{0}{1}'; var _serverPath = { api: 'api.cn.ronghub.com' }; RongIMLib.RongUtil.forEach(_serverPath, function (path, key) { _serverPath[key] = RongIMLib.RongUtil.stringFormat(pathTmpl, [protocol, path]); }); RongIMLib.RongUtil.forEach(_serverPath, function (path, key) { var hasProto = (key in options); var config = { path: options[key], tmpl: pathTmpl, protocol: protocol, sub: true }; path = hasProto ? RongIMLib.RongUtil.formatProtoclPath(config) : path; options[key] = path; }); var navigaters = options.navigaters || []; if (options.navi) { navigaters = [options.navi]; } if (!options.navi && RongIMLib.RongUtil.isEqual(navigaters.length, 0)) { navigaters = ['nav.cn.ronghub.com', 'nav2-cn.ronghub.com']; } RongIMLib.RongUtil.forEach(navigaters, function (navi, index) { var config = { path: navi, tmpl: pathTmpl, protocol: protocol, sub: true }; navi = RongIMLib.RongUtil.formatProtoclPath(config); navigaters[index] = navi; }); var _sourcePath = { protobuf: 'cdn.ronghub.com/protobuf-2.3.7.min.js' }; RongIMLib.RongUtil.forEach(_sourcePath, function (path, key) { _sourcePath[key] = RongIMLib.RongUtil.stringFormat(pathTmpl, [protocol, path]); }); RongIMLib.RongUtil.extend(_sourcePath, options); var _defaultOpts = { isPolling: isPolling, wsScheme: wsScheme, protocol: protocol, showError: true, openMp: true, snifferTime: 2000, naviTimeout: 5000, navigaters: navigaters, maxNaviRetry: 10, isNaviJSONP: false, isWSPingJSONP: false, isNotifyConversationList: false, maxConversationCount: 300 }; delete options.navigaters; RongIMLib.RongUtil.extend(_defaultOpts, options); if (RongIMLib.RongUtil.isFunction(options.protobuf)) { RongIMClient.Protobuf = options.protobuf; } RongIMClient.userStatusObserver = new RongIMLib.RongObserver(); var pather = new RongIMLib.FeaturePatcher(); pather.patchAll(); var tempStore = { token: "", callback: null, lastReadTime: new RongIMLib.LimitableMap(), historyMessageLimit: new RongIMLib.MemoryCache(), conversationList: [], appKey: appKey, publicServiceMap: new RongIMLib.PublicServiceMap(), providerType: 1, deltaTime: 0, filterMessages: [], isSyncRemoteConverList: true, otherDevice: false, custStore: {}, converStore: { latestMessage: {} }, connectAckTime: 0, voipStategy: 0, isFirstPingMsg: true, depend: options, notification: {} }; RongIMClient._memoryStore = tempStore; var isCPlusSDK = dataAccessProvider && Object.prototype.toString.call(dataAccessProvider) == "[object Object]"; if (isCPlusSDK) { RongIMClient._dataAccessProvider = dataAccessProvider; } else { RongIMClient._dataAccessProvider = new RongIMLib.ServerDataProvider(); } options.appCallback = callback; var sdkInfo = RongIMClient._dataAccessProvider.init(appKey, options); RongIMClient._memoryStore.sdkInfo = sdkInfo; if (isCPlusSDK) { // 兼容 c++ 设置导航,Web 端不生效 RongIMClient._dataAccessProvider.setServerInfo({ navi: location.protocol + options.navi + '/navi.xml' }); } RongIMClient.MessageParams = { TextMessage: { objectName: "RC:TxtMsg", msgTag: new RongIMLib.MessageTag(true, true) }, ImageMessage: { objectName: "RC:ImgMsg", msgTag: new RongIMLib.MessageTag(true, true) }, DiscussionNotificationMessage: { objectName: "RC:DizNtf", msgTag: new RongIMLib.MessageTag(false, true) }, VoiceMessage: { objectName: "RC:VcMsg", msgTag: new RongIMLib.MessageTag(true, true) }, RichContentMessage: { objectName: "RC:ImgTextMsg", msgTag: new RongIMLib.MessageTag(true, true) }, FileMessage: { objectName: "RC:FileMsg", msgTag: new RongIMLib.MessageTag(true, true) }, HQVoiceMessage: { objectName: "RC:HQVCMsg", msgTag: new RongIMLib.MessageTag(true, true) }, HandshakeMessage: { objectName: "", msgTag: new RongIMLib.MessageTag(true, true) }, UnknownMessage: { objectName: "", msgTag: new RongIMLib.MessageTag(true, true) }, LocationMessage: { objectName: "RC:LBSMsg", msgTag: new RongIMLib.MessageTag(true, true) }, InformationNotificationMessage: { objectName: "RC:InfoNtf", msgTag: new RongIMLib.MessageTag(false, true) }, ContactNotificationMessage: { objectName: "RC:ContactNtf", msgTag: new RongIMLib.MessageTag(false, true) }, ProfileNotificationMessage: { objectName: "RC:ProfileNtf", msgTag: new RongIMLib.MessageTag(false, true) }, CommandNotificationMessage: { objectName: "RC:CmdNtf", msgTag: new RongIMLib.MessageTag(false, true) }, PublicServiceRichContentMessage: { objectName: "RC:PSImgTxtMsg", msgTag: new RongIMLib.MessageTag(true, true) }, PublicServiceMultiRichContentMessage: { objectName: "RC:PSMultiImgTxtMsg", msgTag: new RongIMLib.MessageTag(true, true) }, JrmfRedPacketMessage: { objectName: "RCJrmf:RpMsg", msgTag: new RongIMLib.MessageTag(true, true) }, JrmfRedPacketOpenedMessage: { objectName: "RCJrmf:RpOpendMsg", msgTag: new RongIMLib.MessageTag(true, true) }, GroupNotificationMessage: { objectName: "RC:GrpNtf", msgTag: new RongIMLib.MessageTag(false, true) }, CommandMessage: { objectName: "RC:CmdMsg", msgTag: new RongIMLib.MessageTag(false, false) }, TypingStatusMessage: { objectName: "RC:TypSts", msgTag: new RongIMLib.MessageTag(false, false) }, PublicServiceCommandMessage: { objectName: "RC:PSCmd", msgTag: new RongIMLib.MessageTag(false, false) }, RecallCommandMessage: { objectName: "RC:RcCmd", msgTag: new RongIMLib.MessageTag(false, true) }, SyncReadStatusMessage: { objectName: "RC:SRSMsg", msgTag: new RongIMLib.MessageTag(false, false) }, ReadReceiptRequestMessage: { objectName: "RC:RRReqMsg", msgTag: new RongIMLib.MessageTag(false, false) }, ReadReceiptResponseMessage: { objectName: "RC:RRRspMsg", msgTag: new RongIMLib.MessageTag(false, false) }, ChangeModeResponseMessage: { objectName: "RC:CsChaR", msgTag: new RongIMLib.MessageTag(false, false) }, ChangeModeMessage: { objectName: "RC:CSCha", msgTag: new RongIMLib.MessageTag(false, false) }, EvaluateMessage: { objectName: "RC:CsEva", msgTag: new RongIMLib.MessageTag(false, false) }, CustomerContact: { objectName: "RC:CsContact", msgTag: new RongIMLib.MessageTag(false, false) }, HandShakeMessage: { objectName: "RC:CsHs", msgTag: new RongIMLib.MessageTag(false, false) }, HandShakeResponseMessage: { objectName: "RC:CsHsR", msgTag: new RongIMLib.MessageTag(false, false) }, SuspendMessage: { objectName: "RC:CsSp", msgTag: new RongIMLib.MessageTag(false, false) }, TerminateMessage: { objectName: "RC:CsEnd", msgTag: new RongIMLib.MessageTag(false, false) }, CustomerStatusUpdateMessage: { objectName: "RC:CsUpdate", msgTag: new RongIMLib.MessageTag(false, false) }, ReadReceiptMessage: { objectName: "RC:ReadNtf", msgTag: new RongIMLib.MessageTag(false, false) }, RCCombineMessage: { objectName: "RC:CombineMsg", msgTag: new RongIMLib.MessageTag(true, true) }, ChrmKVNotificationMessage: { objectName: 'RC:chrmKVNotiMsg', msgTag: new RongIMLib.MessageTag(false, false) } }; RongIMClient.MessageParams["AcceptMessage"] = { objectName: "RC:VCAccept", msgTag: new RongIMLib.MessageTag(false, false) }; RongIMClient.MessageParams["RingingMessage"] = { objectName: "RC:VCRinging", msgTag: new RongIMLib.MessageTag(false, false) }; RongIMClient.MessageParams["SummaryMessage"] = { objectName: "RC:VCSummary", msgTag: new RongIMLib.MessageTag(false, false) }; RongIMClient.MessageParams["HungupMessage"] = { objectName: "RC:VCHangup", msgTag: new RongIMLib.MessageTag(false, false) }; RongIMClient.MessageParams["InviteMessage"] = { objectName: "RC:VCInvite", msgTag: new RongIMLib.MessageTag(false, false) }; RongIMClient.MessageParams["MediaModifyMessage"] = { objectName: "RC:VCModifyMedia", msgTag: new RongIMLib.MessageTag(false, false) }; RongIMClient.MessageParams["MemberModifyMessage"] = { objectName: "RC:VCModifyMem", msgTag: new RongIMLib.MessageTag(false, false) }; RongIMClient.MessageType = { TextMessage: "TextMessage", ImageMessage: "ImageMessage", DiscussionNotificationMessage: "DiscussionNotificationMessage", VoiceMessage: "VoiceMessage", RichContentMessage: "RichContentMessage", HandshakeMessage: "HandshakeMessage", UnknownMessage: "UnknownMessage", LocationMessage: "LocationMessage", InformationNotificationMessage: "InformationNotificationMessage", ContactNotificationMessage: "ContactNotificationMessage", ProfileNotificationMessage: "ProfileNotificationMessage", CommandNotificationMessage: "CommandNotificationMessage", CommandMessage: "CommandMessage", TypingStatusMessage: "TypingStatusMessage", ChangeModeResponseMessage: "ChangeModeResponseMessage", ChangeModeMessage: "ChangeModeMessage", EvaluateMessage: "EvaluateMessage", HandShakeMessage: "HandShakeMessage", HandShakeResponseMessage: "HandShakeResponseMessage", SuspendMessage: "SuspendMessage", TerminateMessage: "TerminateMessage", CustomerContact: "CustomerContact", CustomerStatusUpdateMessage: "CustomerStatusUpdateMessage", SyncReadStatusMessage: "SyncReadStatusMessage", ReadReceiptRequestMessage: "ReadReceiptRequestMessage", ReadReceiptResponseMessage: "ReadReceiptResponseMessage", FileMessage: 'FileMessage', HQVoiceMessage: 'HQVoiceMessage', AcceptMessage: "AcceptMessage", RingingMessage: "RingingMessage", SummaryMessage: "SummaryMessage", HungupMessage: "HungupMessage", InviteMessage: "InviteMessage", MediaModifyMessage: "MediaModifyMessage", MemberModifyMessage: "MemberModifyMessage", JrmfRedPacketMessage: "JrmfRedPacketMessage", JrmfRedPacketOpenedMessage: "JrmfRedPacketOpenedMessage", GroupNotificationMessage: "GroupNotificationMessage", PublicServiceRichContentMessage: "PublicServiceRichContentMessage", PublicServiceMultiRichContentMessage: "PublicServiceMultiRichContentMessage", PublicServiceCommandMessage: "PublicServiceCommandMessage", RecallCommandMessage: "RecallCommandMessage", ReadReceiptMessage: "ReadReceiptMessage", RCCombineMessage: "RCCombineMessage", ChrmKVNotificationMessage: 'ChrmKVNotificationMessage' }; RongIMClient.LogFactory = { /** * 个人 */ "-1": { code: "-1", msg: "服务器超时" }, "-2": { code: "-2", msg: "未知原因失败" }, "-3": { code: "-3", msg: "参数错误" }, "-4": { code: "-4", msg: "参数不正确或尚未实例化" }, "25101": { code: "25101", msg: "撤回消息参数错误", desc: "请检查撤回消息参数 https://rongcloud.github.io/websdk-demo/api-test.html" }, "25102": { code: "25101", msg: "只能撤回自发发送的消息" }, "20604": { code: "20604", msg: "发送频率过快", desc: "https://developer.rongcloud.cn/ticket/info/9Q3L6vRKd1cLS7rycA==?type=1" }, "20406": { code: "20406", msg: "被禁言" }, "23407": { code: "23407", msg: "获取用户失败" }, /** * 群组 */ "20407": { code: "20407", msg: "群组Id无效" }, "22408": { code: "22408", msg: "群组被禁言" }, "22406": { code: "22406", msg: "不在群组" }, "35001": { code: "35001", msg: "群组同步异常" }, "35002": { code: "35002", msg: "匹配群信息异常" }, /** * 讨论组 */ "21406": { code: "21406", msg: "不在讨论组" }, "21407": { code: "21407", msg: "加入讨论失败" }, "21408": { code: "21408", msg: "创建讨论组失败" }, "21409": { code: "21409", msg: "设置讨论组邀请状态失败" }, /** * 聊天室 */ "23406": { code: "23406", msg: "不在聊天室" }, "23408": { code: "23408", msg: "聊天室被禁言" }, "23409": { code: "23409", msg: "聊天室中成员被踢出" }, "23410": { code: "23410", msg: "聊天室不存在" }, "23411": { code: "23411", msg: "聊天室成员已满" }, "23412": { code: "23412", msg: "获取聊天室信息参数无效" }, "23413": { code: "23413", msg: "聊天室异常" }, "23414": { code: "23414", msg: "没有打开聊天室消息存储" }, "36001": { code: "36001", msg: "加入聊天室Id为空" }, "36002": { code: "36002", msg: "加入聊天室失败" }, "36003": { code: "36003", msg: "拉取聊天室历史消息失败" }, /** * voip */ "24001": { code: "24001", msg: "没有注册DeviveId 也就是用户没有登陆" }, "24002": { code: "24002", msg: "用户已经存在" }, "0": { code: "0", msg: "成功" }, "24009": { code: "24009", msg: "没有对应的用户或token" }, "24013": { code: "24013", msg: "voip为空" }, "24010": { code: "24010", msg: "不支持的Voip引擎" }, "24011": { code: "24011", msg: "channelName 是空" }, "24012": { code: "24012", msg: "生成Voipkey失败" }, "24014": { code: "24014", msg: "没有配置voip" }, "24015": { code: "24015", msg: "服务器内部错误" }, "24016": { code: "24016", msg: "VOIP close" }, /** * 通讯、导航 */ "30001": { code: "30001", msg: "通信过程中,当前Socket不存在" }, "30002": { code: "30002", msg: "Socket连接不可用" }, "30003": { code: "30003", msg: "通信超时" }, "30004": { code: "30004", msg: "导航操作时,Http请求失败" }, "30005": { code: "30005", msg: "HTTP请求失败" }, "30006": { code: "30006", msg: "HTTP接收失败" }, "30007": { code: "30007", msg: "导航资源错误" }, "30008": { code: "30008", msg: "没有有效数据" }, "30009": { code: "30009", msg: "不存在有效 IP 地址" }, "30010": { code: "30010", msg: "创建 Socket 失败" }, "30011": { code: "30011", msg: " Socket 被断开" }, "30012": { code: "30012", msg: "PING 操作失败" }, "30013": { code: "30013", msg: "PING 超时" }, "30014": { code: "30014", msg: "消息发送失败" }, "30016": { code: "30016", msg: "消息大小超限,最大 128 KB" }, /** * 连接 */ "31000": { code: "31000", msg: "做 connect 连接时,收到的 ACK 超时" }, "31001": { code: "31001", msg: "参数错误" }, "31002": { code: "31002", msg: "参数错误,App Id 错误" }, "31003": { code: "31003", msg: "服务器不可用" }, "31004": { code: "31004", msg: "Token 错误" }, "31005": { code: "31005", msg: "App Id 与 Token 不匹配" }, "31006": { code: "31006", msg: "重定向,地址错误" }, "31007": { code: "31007", msg: "NAME 与后台注册信息不一致" }, "31008": { code: "31008", msg: "APP 被屏蔽、删除或不存在" }, "31009": { code: "31009", msg: "用户被屏蔽" }, "31010": { code: "31010", msg: "Disconnect,由服务器返回,比如用户互踢" }, "31011": { code: "31011", msg: "Disconnect,由服务器返回,比如用户互踢" }, /** * 协议 */ "32001": { code: "32001", msg: "协议层内部错误。query,上传下载过程中数据错误" }, "32002": { code: "32002", msg: "协议层内部错误" }, /** * BIZ */ "33001": { code: "33001", msg: "未调用 init 初始化函数" }, "33002": { code: "33002", msg: "数据库初始化失败" }, "33003": { code: "33003", msg: "传入参数无效" }, "33004": { code: "33004", msg: "通道无效" }, "33005": { code: "33005", msg: "重新连接成功" }, "33006": { code: "33006", msg: "连接中,再调用 connect 被拒绝" }, "33007": { code: "33007", msg: "消息漫游服务未开通" }, "33008": { code: "33008", msg: "消息添加失败" }, "33009": { code: "33009", msg: "消息删除失败" }, /** * 会话 */ "34001": { code: "34001", msg: "删除会话失败" }, "34002": { code: "34002", msg: "拉取历史消息失败" }, "34003": { code: "34003", msg: "会话指定异常" }, "34004": { code: "34004", msg: "获取会话未读消息总数失败" }, "34005": { code: "34005", msg: "获取指定会话类型未读消息数异常" }, "34006": { code: "34006", msg: "获取指定用户ID&会话类型未读消息数异常" }, "34007": { code: "34007", msg: "清除会话消息异常" }, "34008": { code: "34008", msg: "获取会话消息异常" }, "34009": { code: "34009", msg: "清除历史消息会话类型不正确" }, "34010": { code: "34010", msg: "清除历史消息失败,请检查传入参数" }, /** * 黑名单异常 */ "37001": { code: "37001", msg: "加入黑名单异常" }, "37002": { code: "37002", msg: "获得指定人员再黑名单中的状态异常" }, "37003": { code: "37003", msg: "移除黑名单异常" }, "405": { code: "405", msg: "在黑名单中" }, /** * 草稿 */ "38001": { code: "38001", msg: "获取草稿失败" }, "38002": { code: "38002", msg: "保存草稿失败" }, "38003": { code: "38003", msg: "删除草稿失败" }, /** * 公众号 */ "39001": { code: "39001", msg: "关注公众号失败" }, /** * 文件 */ "41001": { code: "41001", msg: "文件类型错误" }, "41002": { code: "41002", msg: "获取七牛token失败" }, /** * */ "51001": { code: "51001", msg: "未安装或未启动插件" }, "51002": { code: "51002", msg: "视频已经存在" }, "51003": { code: "51003", msg: "无效的channelName" }, "51004": { code: "51004", msg: "视频内容为空" }, /** * */ "61001": { code: "61001", msg: "删除消息数组长度为 0" } }; var handler = function (message, uris, callback) { var userId = message.senderUserId; var _uris = RongIMClient.roomInfo.users[userId].uris || '[]'; if (RongIMLib.RongUtil.isString(_uris)) { _uris = JSON.parse(_uris); } var tUris = JSON.parse(JSON.stringify(_uris)); RongIMLib.RongUtil.forEach(tUris, function (_uri, index) { RongIMLib.RongUtil.forEach(uris, function (uri) { if (uri.uri == _uri.uri) { callback(_uri, uri, _uris, index); } }); }); RongIMClient.roomInfo.users[userId].uris = JSON.stringify(_uris); }; var RTCMessage = { RTCPublishResourceMessage: function (message, uris) { var userId = message.senderUserId; var user = RongIMClient.roomInfo.users[userId]; if (!user) { user = {}; RongIMClient.roomInfo.users[userId] = {}; } var _uris = user.uris || '[]'; if (RongIMLib.RongUtil.isString(_uris)) { _uris = JSON.parse(_uris); } _uris = _uris.concat(uris); RongIMClient.roomInfo.users[userId].uris = JSON.stringify(_uris); }, RTCUnpublishResourceMessage: function (message, uris) { handler(message, uris, function (_uri, uri, _uris, index) { _uris.splice(index, 1); }); }, RTCModifyResourceMessage: function (message, uris) { handler(message, uris, function (_uri, uri) { _uri.state = uri.state; }); }, RTCUserChangeMessage: function (message) { var content = message.content; var users = content.users; var UserState = { JOINED: 0, LEFT: 1, OFFLINE: 2 }; RongIMLib.RongUtil.forEach(users, function (user) { var state = user.state; var userId = user.userId; switch (+state) { case UserState.JOINED: RongIMClient.roomInfo.users[userId] = {}; break; case UserState.LEFT: case UserState.OFFLINE: delete RongIMClient.roomInfo.users[userId]; break; } }); } }; RongIMClient.RTCInnerListener = function (message) { var func = RTCMessage[message.messageType] || function () { }; var content = message.content; var uris = content.uris; func(message, uris); }; RongIMClient.Conversation = RongIMClient._dataAccessProvider.Conversation; return sdkInfo; }; ; /** var config = { appkey: appkey, token: token, dataAccessProvider:dataAccessProvider, opts: opts }; callback(_instance, userId); */ RongIMClient.initApp = function (config, callback) { RongIMClient.init(config.appkey, config.dataAccessProvider, config.opts, function () { var instance = RongIMClient._instance; //备用 var error = null; callback(error, instance); }); }; /** * 连接服务器,在整个应用全局只需要调用一次,断线后 SDK 会自动重连。 * * @param token 从服务端获取的用户身份令牌(Token)。 * @param callback 连接回调,返回连接的成功或者失败状态。 */ RongIMClient.connect = function (token, _callback, userId, serverConf) { RongIMLib.CheckParam.getInstance().check(["string", "object", "string|null|object|global|undefined", "object|null|global|undefined"], "connect", true, arguments); var connectCallback = { onSuccess: _callback.onSuccess, onTokenIncorrect: _callback.onTokenIncorrect, onError: function (errorCode) { RongIMClient.logger({ code: errorCode, funcName: "connect" }); _callback.onError(errorCode); } }; RongIMClient._dataAccessProvider.connect(token, connectCallback, userId, serverConf); }; RongIMClient.reconnect = function (callback, config) { var connectCallback = { onSuccess: callback.onSuccess, onTokenIncorrect: callback.onTokenIncorrect, onError: function (errorCode) { RongIMClient.logger({ code: errorCode, funcName: "connect" }); callback.onError(errorCode); } }; RongIMClient._dataAccessProvider.reconnect(connectCallback, config); }; /** * 注册消息类型,用于注册用户自定义的消息。 * 内建的消息类型已经注册过,不需要再次注册。 * 自定义消息声明需放在执行顺序最高的位置(在RongIMClient.init(appkey)之后即可) * @param objectName 消息内置名称 */ RongIMClient.registerMessageType = function (messageType, objectName, messageTag, messageContent, searchProps) { RongIMClient._dataAccessProvider.registerMessageType(messageType, objectName, messageTag, messageContent, searchProps); RongIMClient.RegisterMessage[messageType].messageName = messageType; RongIMClient.MessageType[messageType] = messageType; RongIMClient.MessageParams[messageType] = { objectName: objectName, msgTag: messageTag }; }; RongIMClient.prototype.registerMessageTypes = function (types) { types = types || {}; RongIMClient._dataAccessProvider.registerMessageTypes(types); }; /** * 设置连接状态变化的监听器。 * * @param listener 连接状态变化的监听器。 */ RongIMClient.setConnectionStatusListener = function (listener) { if (RongIMLib.RongUtil.isObject(listener) && RongIMLib.RongUtil.isFunction(listener.onChanged)) { RongIMClient.statusListeners.push(listener.onChanged); } }; RongIMClient.statusWatch = function (watcher) { if (RongIMLib.RongUtil.isFunction(watcher)) { RongIMClient.statusListeners.push(watcher); } }; /** * 设置接收消息的监听器。 * * @param listener 接收消息的监听器。 */ RongIMClient.setOnReceiveMessageListener = function (listener) { if (RongIMLib.RongUtil.isObject(listener) && RongIMLib.RongUtil.isFunction(listener.onReceived)) { RongIMClient.messageListeners.push(listener.onReceived); } }; /** * 清理所有连接相关的变量 */ RongIMClient.prototype.logout = function () { RongIMClient._dataAccessProvider.logout(); }; /** * 断开连接。 */ RongIMClient.prototype.disconnect = function () { RongIMClient._dataAccessProvider.disconnect(); }; RongIMClient.prototype.startCustomService = function (custId, callback, content) { if (!custId || !callback) return; var msg = new RongIMLib.HandShakeMessage(content); var me = this; RongIMLib.RongIMClient._memoryStore.custStore["isInit"] = true; RongIMClient.getInstance().sendMessage(RongIMLib.ConversationType.CUSTOMER_SERVICE, custId, msg, { onSuccess: function (data) { if (data.isBlack) { callback.onError(); me.stopCustomeService(custId, { onSuccess: function () { }, onError: function () { } }); } else { callback.onSuccess(); } }, onError: function () { callback.onError(); }, onBefore: function () { } }); }; RongIMClient.prototype.stopCustomeService = function (custId, callback) { if (!custId || !callback) return; var session = RongIMClient._memoryStore.custStore[custId]; if (!session) return; var msg = new RongIMLib.SuspendMessage({ sid: session.sid, uid: session.uid, pid: session.pid }); this.sendCustMessage(custId, msg, { onSuccess: function () { // delete RongIMClient._memoryStore.custStore[custId]; setTimeout(function () { callback.onSuccess(); }); }, onError: function () { setTimeout(function () { callback.onError(); }); } }); }; RongIMClient.prototype.switchToHumanMode = function (custId, callback) { if (!custId || !callback) return; var session = RongIMClient._memoryStore.custStore[custId]; if (!session) return; var msg = new RongIMLib.ChangeModeMessage({ sid: session.sid, uid: session.uid, pid: session.pid }); this.sendCustMessage(custId, msg, callback); }; RongIMClient.prototype.evaluateRebotCustomService = function (custId, isRobotResolved, sugest, callback) { if (!custId || !callback) return; var session = RongIMClient._memoryStore.custStore[custId]; if (!session) return; var msg = new RongIMLib.EvaluateMessage({ sid: session.sid, uid: session.uid, pid: session.pid, isRobotResolved: isRobotResolved, sugest: sugest, type: 0 }); this.sendCustMessage(custId, msg, callback); }; RongIMClient.prototype.evaluateHumanCustomService = function (custId, humanValue, sugest, callback) { if (!custId || !callback) return; var session = RongIMClient._memoryStore.custStore[custId]; if (!session) return; var msg = new RongIMLib.EvaluateMessage({ sid: session.sid, uid: session.uid, pid: session.pid, humanValue: humanValue, sugest: sugest, type: 1 }); this.sendCustMessage(custId, msg, callback); }; RongIMClient.prototype.sendCustMessage = function (custId, msg, callback) { RongIMClient.getInstance().sendMessage(RongIMLib.ConversationType.CUSTOMER_SERVICE, custId, msg, { onSuccess: function (data) { callback.onSuccess(); }, onError: function () { callback.onError(); }, onBefore: function () { } }); }; /** * 获取当前连接的状态。 */ RongIMClient.prototype.getCurrentConnectionStatus = function () { return RongIMClient._dataAccessProvider.getCurrentConnectionStatus(); }; /** * 获取当前使用的连接通道。 */ RongIMClient.prototype.getConnectionChannel = function () { if (RongIMLib.Transportations._TransportType == RongIMLib.Socket.XHR_POLLING) { return RongIMLib.ConnectionChannel.XHR_POLLING; } else if (RongIMLib.Transportations._TransportType == RongIMLib.Socket.WEBSOCKET) { return RongIMLib.ConnectionChannel.WEBSOCKET; } }; /** * 获取当前使用的本地储存提供者。 TODO */ RongIMClient.prototype.getStorageProvider = function () { if (RongIMClient._memoryStore.providerType == 1) { return "ServerDataProvider"; } else { return "OtherDataProvider"; } }; /** * 过滤聊天室消息(拉取最近聊天消息) * @param {string[]} msgFilterNames */ RongIMClient.prototype.setFilterMessages = function (msgFilterNames) { if (Object.prototype.toString.call(msgFilterNames) == "[object Array]") { RongIMClient._memoryStore.filterMessages = msgFilterNames; } }; RongIMClient.prototype.getAgoraDynamicKey = function (engineType, channelName, callback) { RongIMClient._dataAccessProvider.getAgoraDynamicKey(engineType, channelName, callback); }; /** * 获取当前连接用户的 UserId。 */ RongIMClient.prototype.getCurrentUserId = function () { return RongIMLib.Bridge._client.userId; }; /** * 获取服务器时间与本地时间的差值,单位为毫秒。 * 计算公式:差值 = 本地时间毫秒数 - 服务器时间毫秒数 * @param callback 获取的回调,返回差值。 */ RongIMClient.prototype.getDeltaTime = function () { return RongIMClient._dataAccessProvider.getDelaTime(); }; // #region Message RongIMClient.prototype.getMessage = function (messageId, callback) { RongIMClient._dataAccessProvider.getMessage(messageId, RongIMClient.logCallback(callback, "getMessage")); }; RongIMClient.prototype.deleteLocalMessages = function (conversationType, targetId, messageIds, callback) { RongIMClient._dataAccessProvider.removeLocalMessage(conversationType, targetId, messageIds, RongIMClient.logCallback(callback, "deleteLocalMessages")); }; RongIMClient.prototype.updateMessage = function (message, callback) { RongIMClient._dataAccessProvider.updateMessage(message, RongIMClient.logCallback(callback, "updateMessage")); }; RongIMClient.prototype.clearData = function () { return RongIMClient._dataAccessProvider.clearData(); }; RongIMClient.prototype.clearMessages = function (conversationType, targetId, callback) { RongIMClient._dataAccessProvider.clearMessages(conversationType, targetId, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "clearMessages" }); callback.onError(errorCode); }); } }); }; /**TODO 清楚本地存储的未读消息,目前清空内存中的未读消息 * [clearMessagesUnreadStatus 清空指定会话未读消息] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [用户id] * @param {ResultCallback} callback [返回值,参数回调] */ RongIMClient.prototype.clearMessagesUnreadStatus = function (conversationType, targetId, callback) { RongIMClient._dataAccessProvider.updateMessages(conversationType, targetId, "readStatus", null, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "clearMessagesUnreadStatus" }); callback.onError(errorCode); }); } }); }; // deleteRemoteMessages(conversationType: ConversationType, targetId: string, delMsgs: DeleteMessage[], callback: ResultCallback) { // CheckParam.getInstance().check(["number", "string|number", "array", "object"], "deleteRemoteMessages", false, arguments); // if (delMsgs.length == 0) { // var errorCode = ErrorCode.DELETE_MESSAGE_ID_IS_NULL; // RongIMClient.logger({ // code: errorCode, // funcName: "deleteRemoteMessages" // }); // callback.onError(ErrorCode.DELETE_MESSAGE_ID_IS_NULL); // return; // } else if (delMsgs.length > 100) { // delMsgs.length = 100; // } // // 后续增加,去掉注释即可 // callback.onSuccess(true); // // var modules = new RongIMClient.Protobuf.DeleteMsgInput(); // // modules.setType(conversationType); // // modules.setConversationId(targetId); // // modules.setMsgs(delMsgs); // // RongIMClient.bridge.queryMsg(33, MessageUtil.ArrayForm(modules.toArrayBuffer()), Bridge._client.userId, { // // onSuccess: function(info: any) { // // callback.onSuccess(true); // // }, // // onError: function(err: any) { // // callback.onError(err); // // } // // }, "DeleteMsgOutput"); // } /** * [deleteMessages 删除消息记录。] * @param {ConversationType} conversationType [description] * @param {string} targetId [description] * @param {number[]} messageIds [description] * @param {ResultCallback} callback [description] */ RongIMClient.prototype.deleteMessages = function (conversationType, targetId, messages, callback) { RongIMClient._dataAccessProvider.removeMessage(conversationType, targetId, messages, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "deleteMessages" }); callback.onError(errorCode); }); } }); }; RongIMClient.prototype.sendLocalMessage = function (message, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object"], "sendLocalMessage", false, arguments); RongIMClient._dataAccessProvider.updateMessage(message); this.sendMessage(message.conversationType, message.targetId, message.content, RongIMClient.logSendCallback(callback, "sendLocalMessage")); }; RongIMClient.prototype.getPullSetting = function (callback) { RongIMClient._dataAccessProvider.getPullSetting(callback); }; RongIMClient.prototype.setOfflineMessageDuration = function (duration, callback) { RongIMLib.CheckParam.getInstance().check(["number", "object"], "setOfflineMessageDuration", true, arguments); RongIMClient._dataAccessProvider.setOfflineMessageDuration(duration, callback); }; /** * [sendMessage 发送消息。] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [目标Id] * @param {MessageContent} messageContent [消息类型] * @param {SendMessageCallback} sendCallback [] * @param {ResultCallback} resultCallback [返回值,函数回调] * @param {string} pushContent [] * @param {string} pushData [] */ RongIMClient.prototype.sendMessage = function (conversationType, targetId, messageContent, sendCallback, mentiondMsg, pushText, appData, methodType, params) { RongIMLib.CheckParam.getInstance().check(["number", "string", "object", "object", "undefined|object|null|global|boolean", "undefined|object|null|global|string", "undefined|object|null|global|string", "undefined|object|null|global|number", "undefined|object|null|global"], "sendMessage", false, arguments); if (!RongIMLib.RongUtil.isString(targetId)) { return sendCallback.onError(RongIMLib.ErrorCode.PARAMETER_ERROR); } RongIMClient._dataAccessProvider.sendMessage(conversationType, targetId, messageContent, RongIMClient.logSendCallback(sendCallback, "sendMessage"), mentiondMsg, pushText, appData, methodType, params); }; RongIMClient.prototype.sendReceiptResponse = function (conversationType, targetId, sendCallback) { RongIMClient._dataAccessProvider.sendReceiptResponse(conversationType, targetId, RongIMClient.logSendCallback(sendCallback, "sendReceiptResponse")); }; RongIMClient.prototype.sendTypingStatusMessage = function (conversationType, targetId, messageName, sendCallback) { RongIMClient._dataAccessProvider.sendTypingStatusMessage(conversationType, targetId, messageName, RongIMClient.logSendCallback(sendCallback, "sendTypingStatusMessage")); }; /** * [sendStatusMessage description] * @param {MessageContent} messageContent [description] * @param {SendMessageCallback} sendCallback [description] * @param {ResultCallback} resultCallback [description] */ RongIMClient.prototype.sendStatusMessage = function (messageContent, sendCallback, resultCallback) { throw new Error("Not implemented yet"); }; /** * [sendTextMessage 发送TextMessage快捷方式] * @param {string} content [消息内容] * @param {ResultCallback} resultCallback [返回值,参数回调] */ RongIMClient.prototype.sendTextMessage = function (conversationType, targetId, content, sendMessageCallback) { RongIMClient._dataAccessProvider.sendTextMessage(conversationType, targetId, content, RongIMClient.logSendCallback(sendMessageCallback, "sendTextMessage")); }; RongIMClient.prototype.sendRecallMessage = function (content, sendMessageCallback) { var callback = RongIMClient.logSendCallback(sendMessageCallback, "sendRecallMessage"); var senderUserId = content.senderUserId; var userId = RongIMLib.Bridge._client.userId; var isOther = (senderUserId != userId); if (isOther) { var callback = RongIMClient.logSendCallback(sendMessageCallback, "sendRecallMessage"); callback.onError(RongIMLib.ErrorCode.RECALL_MESSAGE, content); return; } RongIMClient._dataAccessProvider.sendRecallMessage(content, callback); }; /** * [insertMessage 向本地插入一条消息,不发送到服务器。] * @param {ConversationType} conversationType [description] * @param {string} targetId [description] * @param {string} senderUserId [description] * @param {MessageContent} content [description] * @param {ResultCallback} callback [description] */ RongIMClient.prototype.insertMessage = function (conversationType, targetId, content, callback) { RongIMClient._dataAccessProvider.addMessage(conversationType, targetId, content, RongIMClient.logCallback(callback, "insertMessage")); }; RongIMClient.prototype.setMessageContent = function (messageId, content, objectName) { RongIMClient._dataAccessProvider.setMessageContent(messageId, content, objectName); }; ; RongIMClient.prototype.setMessageSearchField = function (messageId, content, searchFiles) { RongIMClient._dataAccessProvider.setMessageContent(messageId, content, searchFiles); }; ; /** * [getHistoryMessages 拉取历史消息记录。] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [用户Id] * @param {number|null} pullMessageTime [拉取历史消息起始位置(格式为毫秒数),可以为null] * @param {number} count [历史消息数量] * @param {ResultCallback} callback [回调函数] * @param {string} objectName [objectName] */ RongIMClient.prototype.getHistoryMessages = function (conversationType, targetId, timestamp, count, callback, objectname, order) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "number|null|global|object", "number", "object", "undefined|object|null|global|string", "number|null|global|object"], "getHistoryMessages", false, arguments); if (count > 20) { throw new Error("HistroyMessage count must be less than or equal to 20!"); } if (conversationType.valueOf() < 0) { throw new Error("ConversationType must be greater than -1"); } RongIMClient._dataAccessProvider.getHistoryMessages(conversationType, targetId, timestamp, count, RongIMClient.logCallback(callback, "getHistoryMessages"), objectname, order); }; /** * [getRemoteHistoryMessages 拉取某个时间戳之前的消息] * @param {ConversationType} conversationType [description] * @param {string} targetId [description] * @param {Date} dateTime [description] * @param {number} count [description] * @param {ResultCallback} callback [description] */ RongIMClient.prototype.getRemoteHistoryMessages = function (conversationType, targetId, timestamp, count, callback, config) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "number|null|global|object", "number", "object", "undefined|null|global|object"], "getRemoteHistoryMessages", false, arguments); var funcName = "getRemoteHistoryMessages"; var log = { errorCode: RongIMLib.ErrorCode.RC_CONN_PROTO_VERSION_ERROR, funcName: "getRemoteHistoryMessages" }; if (count > 20) { RongIMClient.logger(log); callback.onError(RongIMLib.ErrorCode.RC_CONN_PROTO_VERSION_ERROR); return; } if (conversationType.valueOf() < 0) { RongIMClient.logger(log); callback.onError(RongIMLib.ErrorCode.RC_CONN_PROTO_VERSION_ERROR); return; } RongIMClient._dataAccessProvider.getRemoteHistoryMessages(conversationType, targetId, timestamp, count, RongIMClient.logCallback(callback, funcName), config); }; RongIMClient.prototype.clearHistoryMessages = function (params, callback) { RongIMClient._dataAccessProvider.clearHistoryMessages(params, callback); }; RongIMClient.prototype.clearRemoteHistoryMessages = function (params, callback) { RongIMClient._dataAccessProvider.clearRemoteHistoryMessages(params, RongIMClient.logCallback(callback, "clearRemoteHistoryMessages")); }; RongIMClient.prototype.deleteRemoteMessages = function (conversationType, targetId, messages, callback) { RongIMClient._dataAccessProvider.deleteRemoteMessages(conversationType, targetId, messages, RongIMClient.logCallback(callback, "deleteRemoteMessages")); }; /** * [hasRemoteUnreadMessages 是否有未接收的消息,jsonp方法] * @param {string} appkey [appkey] * @param {string} token [token] * @param {ConnectCallback} callback [返回值,参数回调] */ RongIMClient.prototype.hasRemoteUnreadMessages = function (token, callback) { RongIMClient._dataAccessProvider.hasRemoteUnreadMessages(token, RongIMClient.logCallback(callback, "hasRemoteUnreadMessages")); }; RongIMClient.prototype.getTotalUnreadCount = function (callback, conversationTypes) { RongIMClient._dataAccessProvider.getTotalUnreadCount({ onSuccess: function (count) { setTimeout(function () { callback.onSuccess(count); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "getTotalUnreadCount" }); callback.onError(errorCode); }); } }, conversationTypes); }; /** * [getConversationUnreadCount 指定多种会话类型获取未读消息数] * @param {ResultCallback} callback [返回值,参数回调。] * @param {ConversationType[]} ...conversationTypes [会话类型。] */ RongIMClient.prototype.getConversationUnreadCount = function (conversationTypes, callback) { RongIMClient._dataAccessProvider.getConversationUnreadCount(conversationTypes, { onSuccess: function (count) { setTimeout(function () { callback.onSuccess(count); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "getConversationUnreadCount" }); callback.onError(errorCode); }); } }); }; /** * [getUnreadCount 指定用户、会话类型的未读消息总数。] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [用户Id] */ RongIMClient.prototype.getUnreadCount = function (conversationType, targetId, callback) { RongIMClient._dataAccessProvider.getUnreadCount(conversationType, targetId, { onSuccess: function (count) { setTimeout(function () { callback.onSuccess(count); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "getUnreadCount" }); callback.onError(errorCode); }); } }); }; RongIMClient.prototype.setUnreadCount = function (conversationType, targetId, count) { RongIMLib.CheckParam.getInstance().check(["number", "string", "number"], "setUnreadCount", false, arguments); RongIMClient._dataAccessProvider.setUnreadCount(conversationType, targetId, count); }; RongIMClient.prototype.clearUnreadCountByTimestamp = function (conversationType, targetId, timestamp, callback) { RongIMClient._dataAccessProvider.clearUnreadCountByTimestamp(conversationType, targetId, timestamp, RongIMClient.logCallback(callback, "clearUnreadCountByTimestamp")); }; /** * 清楚会话未读消息数 * @param {ConversationType} conversationType 会话类型 * @param {string} targetId 目标Id * @param {ResultCallback} callback 返回值,函数回调 */ RongIMClient.prototype.clearUnreadCount = function (conversationType, targetId, callback) { RongIMClient._dataAccessProvider.clearUnreadCount(conversationType, targetId, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "clearUnreadCount" }); callback.onError(errorCode); }); } }); }; RongIMClient.prototype.clearTotalUnreadCount = function (callback) { RongIMClient._dataAccessProvider.clearTotalUnreadCount({ onSuccess: function (bool) { callback.onSuccess(bool); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: 'clearTotalUnreadCount' }); callback.onError(errorCode); }); } }); }; RongIMClient.prototype.clearLocalStorage = function (callback) { RongIMClient._storageProvider.clearItem(); callback(); }; RongIMClient.prototype.setMessageExtra = function (messageId, value, callback) { RongIMClient._dataAccessProvider.setMessageExtra(messageId, value, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "setMessageExtra" }); callback.onError(errorCode); }); } }); }; RongIMClient.prototype.setMessageReceivedStatus = function (messageUId, receivedStatus, callback) { RongIMClient._dataAccessProvider.setMessageReceivedStatus(messageUId, receivedStatus, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "setMessageReceivedStatus" }); callback.onError(errorCode); }); } }); }; RongIMClient.prototype.setMessageStatus = function (conersationType, targetId, timestamp, status, callback) { RongIMClient._dataAccessProvider.setMessageStatus(conersationType, targetId, timestamp, status, RongIMClient.logCallback(callback, "setMessageStatus")); }; RongIMClient.prototype.setMessageSentStatus = function (messageId, sentStatus, callback) { RongIMClient._dataAccessProvider.setMessageSentStatus(messageId, sentStatus, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "setMessageSentStatus" }); callback.onError(errorCode); }); } }); }; // #endregion Message // #region TextMessage Draft /** * clearTextMessageDraft 清除指定会话和消息类型的草稿。 * @param {ConversationType} conversationType 会话类型 * @param {string} targetId 目标Id */ RongIMClient.prototype.clearTextMessageDraft = function (conversationType, targetId) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "clearTextMessageDraft", false, arguments); var key = "darf_" + conversationType + "_" + targetId; delete RongIMClient._memoryStore[key]; return true; }; /** * [getTextMessageDraft 获取指定消息和会话的草稿。] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [目标Id] */ RongIMClient.prototype.getTextMessageDraft = function (conversationType, targetId) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "getTextMessageDraft", false, arguments); if (targetId == "" || conversationType < 0) { throw new Error("params error : " + RongIMLib.ErrorCode.DRAF_GET_ERROR); } var key = "darf_" + conversationType + "_" + targetId; return RongIMClient._memoryStore[key]; }; /** * [saveTextMessageDraft description] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [目标Id] * @param {string} value [草稿值] */ RongIMClient.prototype.saveTextMessageDraft = function (conversationType, targetId, value) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "string", "object"], "saveTextMessageDraft", false, arguments); var key = "darf_" + conversationType + "_" + targetId; RongIMClient._memoryStore[key] = value; return true; }; // #endregion TextMessage Draft // #region Conversation RongIMClient.prototype.searchConversationByContent = function (keyword, callback, conversationTypes) { RongIMClient._dataAccessProvider.searchConversationByContent(keyword, RongIMClient.logCallback(callback, "searchConversationByContent"), conversationTypes); }; RongIMClient.prototype.searchMessageByContent = function (conversationType, targetId, keyword, timestamp, count, total, callback) { RongIMClient._dataAccessProvider.searchMessageByContent(conversationType, targetId, keyword, timestamp, count, total, RongIMClient.logCallback(callback, "searchMessageByContent")); }; RongIMClient.prototype.clearCache = function () { RongIMClient._dataAccessProvider.clearCache(); }; RongIMClient.prototype.clearConversations = function (callback) { var conversationTypes = []; for (var _i = 1; _i < arguments.length; _i++) { conversationTypes[_i - 1] = arguments[_i]; } if (conversationTypes.length == 0) { conversationTypes = [RongIMLib.ConversationType.CHATROOM, RongIMLib.ConversationType.CUSTOMER_SERVICE, RongIMLib.ConversationType.DISCUSSION, RongIMLib.ConversationType.GROUP, RongIMLib.ConversationType.PRIVATE, RongIMLib.ConversationType.SYSTEM, RongIMLib.ConversationType.PUBLIC_SERVICE, RongIMLib.ConversationType.APP_PUBLIC_SERVICE]; } RongIMClient._dataAccessProvider.clearConversations(conversationTypes, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "clearConversations" }); callback.onError(errorCode); }); } }); }; /** * [getConversation 获取指定会话,此方法需在getConversationList之后执行] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [目标Id] * @param {ResultCallback} callback [返回值,函数回调] */ RongIMClient.prototype.getConversation = function (conversationType, targetId, callback) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "getConversation", false, arguments); RongIMClient._dataAccessProvider.getConversation(conversationType, targetId, { onSuccess: function (conver) { setTimeout(function () { callback.onSuccess(conver); }); }, onError: function (error) { setTimeout(function () { RongIMClient.logger({ code: error, funcName: "getConversation" }); callback.onError(error); }); } }); }; /** * [pottingConversation 组装会话列表] * @param {any} tempConver [临时会话] * conver_conversationType_targetId_no. * msg_conversationType_targetId_no. */ RongIMClient.prototype.pottingConversation = function (tempConver) { var self = this, isUseReplace = false; RongIMClient._dataAccessProvider.getConversation(tempConver.type, tempConver.userId, { onSuccess: function (conver) { if (!conver) { conver = new RongIMLib.Conversation(); } else { isUseReplace = true; } conver.conversationType = tempConver.type; conver.targetId = tempConver.userId; conver.latestMessage = RongIMLib.MessageUtil.messageParser(tempConver.msg); conver.latestMessageId = conver.latestMessage.messageId; conver.objectName = conver.latestMessage.objectName; conver.receivedStatus = conver.latestMessage.receivedStatus; conver.receivedTime = conver.latestMessage.receiveTime; conver.sentStatus = conver.latestMessage.sentStatus; conver.sentTime = conver.latestMessage.sentTime; var mentioneds = RongIMClient._storageProvider.getItem("mentioneds_" + RongIMLib.Bridge._client.userId + '_' + conver.conversationType + '_' + conver.targetId); if (mentioneds) { var info = JSON.parse(mentioneds); conver.mentionedMsg = info[tempConver.type + "_" + tempConver.userId]; } if (!isUseReplace) { if (RongIMLib.RongUtil.supportLocalStorage()) { // var count = RongIMClient._storageProvider.getItem("cu" + Bridge._client.userId + tempConver.type + tempConver.userId); conver.unreadMessageCount = RongIMLib.UnreadCountHandler.get(tempConver.type, tempConver.userId); } else { conver.unreadMessageCount = 0; } } if (conver.conversationType == RongIMLib.ConversationType.DISCUSSION) { self.getDiscussion(tempConver.userId, { onSuccess: function (info) { conver.conversationTitle = info.name; }, onError: function (error) { } }); } RongIMClient._dataAccessProvider.addConversation(conver, { onSuccess: function (data) { } }); }, onError: function (error) { } }); }; RongIMClient.prototype.addConversation = function (conversation, callback) { RongIMClient._dataAccessProvider.addConversation(conversation, callback); }; RongIMClient.prototype.sortConversationList = function (conversationList) { var convers = []; for (var i = 0, len = conversationList.length; i < len; i++) { if (!conversationList[i]) { continue; } if (conversationList[i].isTop) { convers.push(conversationList[i]); conversationList.splice(i, 1); continue; } for (var j = 0; j < len - i - 1; j++) { if (conversationList[j].sentTime < conversationList[j + 1].sentTime) { var swap = conversationList[j]; conversationList[j] = conversationList[j + 1]; conversationList[j + 1] = swap; } } } return RongIMClient._memoryStore.conversationList = convers.concat(conversationList); }; RongIMClient.prototype.getConversationList = function (callback, conversationTypes, count, isGetHiddenConvers) { RongIMLib.CheckParam.getInstance().check(["object", "null|undefined|array|object|global", "number|undefined|null|object|global", "boolean|undefined|null|object|global"], "getConversationList", false, arguments); var me = this; RongIMClient._dataAccessProvider.getConversationList({ onSuccess: function (data) { if (conversationTypes || RongIMClient._dataAccessProvider) { setTimeout(function () { callback.onSuccess(data); }); } else { setTimeout(function () { callback.onSuccess(RongIMClient._memoryStore.conversationList); }); } }, onError: function (error) { setTimeout(function () { RongIMClient.logger({ code: error, funcName: "getConversationList" }); callback.onError(error); }); } }, conversationTypes, count, isGetHiddenConvers); }; RongIMClient.prototype.getRemoteConversationList = function (callback, conversationTypes, count, isGetHiddenConvers) { RongIMLib.CheckParam.getInstance().check(["object", "null|array|object|global", "number|undefined|null|object|global", "boolean|undefined|null|object|global"], "getRemoteConversationList", false, arguments); RongIMClient._dataAccessProvider.getRemoteConversationList(RongIMClient.logCallback(callback, "getRemoteConversationList"), conversationTypes, count, isGetHiddenConvers); }; RongIMClient.prototype.updateConversation = function (conversation) { return RongIMClient._dataAccessProvider.updateConversation(conversation); }; /** * [createConversation 创建会话。] * @param {number} conversationType [会话类型] * @param {string} targetId [目标Id] * @param {string} converTitle [会话标题] * @param {boolean} islocal [是否同步到服务器,ture:同步,false:不同步] */ RongIMClient.prototype.createConversation = function (conversationType, targetId, converTitle) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "string"], "createConversation", false, arguments); var conver = new RongIMLib.Conversation(); // var unreadContent: string = RongIMClient._storageProvider.getItem("cu" + Bridge._client.userId + conversationType + targetId); // var unreadCount = Number(unreadContent) || 0; conver.targetId = targetId; conver.conversationType = conversationType; conver.conversationTitle = converTitle; conver.latestMessage = {}; conver.unreadMessageCount = 0; return conver; }; //TODO 删除本地和服务器、删除本地和服务器分开 RongIMClient.prototype.removeConversation = function (conversationType, targetId, callback) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "removeConversation", false, arguments); RongIMClient._dataAccessProvider.removeConversation(conversationType, targetId, RongIMClient.logCallback(callback, "removeConversation")); }; RongIMClient.prototype.setConversationHidden = function (conversationType, targetId, isHidden) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "boolean"], "setConversationHidden", false, arguments); RongIMClient._dataAccessProvider.setConversationHidden(conversationType, targetId, isHidden); }; RongIMClient.prototype.setConversationToTop = function (conversationType, targetId, isTop, callback) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "boolean", "object"], "setConversationToTop", false, arguments); RongIMClient._dataAccessProvider.setConversationToTop(conversationType, targetId, isTop, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "setConversationToTop" }); callback.onError(errorCode); }); } }); }; // #endregion Conversation // #region Notifications /** * [getConversationNotificationStatus 获取指定用户和会话类型免提醒。] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [目标Id] * @param {ResultCallback} callback [返回值,函数回调] */ RongIMClient.prototype.getConversationNotificationStatus = function (conversationType, targetId, callback) { var params = { conversationType: conversationType, targetId: targetId }; RongIMClient._dataAccessProvider.getConversationNotificationStatus(params, RongIMClient.logCallback(callback, "getConversationNotificationStatus")); }; /** * [setConversationNotificationStatus 设置指定用户和会话类型免提醒。] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [目标Id] * @param {ResultCallback} callback [返回值,函数回调] */ RongIMClient.prototype.setConversationNotificationStatus = function (conversationType, targetId, notificationStatus, callback) { var params = { conversationType: conversationType, targetId: targetId, status: status }; RongIMClient._dataAccessProvider.setConversationNotificationStatus(params, RongIMClient.logCallback(callback, "setConversationNotificationStatus")); }; /** * [getNotificationQuietHours 获取免提醒消息时间。] * @param {GetNotificationQuietHoursCallback} callback [返回值,函数回调] */ RongIMClient.prototype.getNotificationQuietHours = function (callback) { throw new Error("Not implemented yet"); }; /** * [removeNotificationQuietHours 移除免提醒消息时间。] * @param {GetNotificationQuietHoursCallback} callback [返回值,函数回调] */ RongIMClient.prototype.removeNotificationQuietHours = function (callback) { throw new Error("Not implemented yet"); }; /** * [setNotificationQuietHours 设置免提醒消息时间。] * @param {GetNotificationQuietHoursCallback} callback [返回值,函数回调] */ RongIMClient.prototype.setNotificationQuietHours = function (startTime, spanMinutes, callback) { throw new Error("Not implemented yet"); }; // #endregion Notifications // #region Discussion /** * [addMemberToDiscussion 加入讨论组] * @param {string} discussionId [讨论组Id] * @param {string[]} userIdList [讨论中成员] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.addMemberToDiscussion = function (discussionId, userIdList, callback) { RongIMLib.CheckParam.getInstance().check(["string", "array", "object"], "addMemberToDiscussion", false, arguments); RongIMClient._dataAccessProvider.addMemberToDiscussion(discussionId, userIdList, RongIMClient.logCallback(callback, "addMemberToDiscussion")); }; /** * [createDiscussion 创建讨论组] * @param {string} name [讨论组名称] * @param {string[]} userIdList [讨论组成员] * @param {CreateDiscussionCallback} callback [返回值,函数回调] */ RongIMClient.prototype.createDiscussion = function (name, userIdList, callback) { RongIMLib.CheckParam.getInstance().check(["string", "array", "object"], "createDiscussion", false, arguments); RongIMClient._dataAccessProvider.createDiscussion(name, userIdList, callback); }; /** * [getDiscussion 获取讨论组信息] * @param {string} discussionId [讨论组Id] * @param {ResultCallback} callback [返回值,函数回调] */ RongIMClient.prototype.getDiscussion = function (discussionId, callback) { RongIMLib.CheckParam.getInstance().check(["string", "object"], "getDiscussion", false, arguments); RongIMClient._dataAccessProvider.getDiscussion(discussionId, RongIMClient.logCallback(callback, "getDiscussion")); }; /** * [quitDiscussion 退出讨论组] * @param {string} discussionId [讨论组Id] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.quitDiscussion = function (discussionId, callback) { RongIMLib.CheckParam.getInstance().check(["string", "object"], "quitDiscussion", false, arguments); RongIMClient._dataAccessProvider.quitDiscussion(discussionId, RongIMClient.logCallback(callback, "quitDiscussion")); }; /** * [removeMemberFromDiscussion 将指定成员移除讨论租] * @param {string} discussionId [讨论组Id] * @param {string} userId [被移除的用户Id] * @param {OperationCallback} callback [返回值,参数回调] */ RongIMClient.prototype.removeMemberFromDiscussion = function (discussionId, userId, callback) { RongIMLib.CheckParam.getInstance().check(["string", "string", "object"], "removeMemberFromDiscussion", false, arguments); RongIMClient._dataAccessProvider.removeMemberFromDiscussion(discussionId, userId, RongIMClient.logCallback(callback, "removeMemberFromDiscussion")); }; /** * [setDiscussionInviteStatus 设置讨论组邀请状态] * @param {string} discussionId [讨论组Id] * @param {DiscussionInviteStatus} status [邀请状态] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.setDiscussionInviteStatus = function (discussionId, status, callback) { RongIMLib.CheckParam.getInstance().check(["string", "number", "object"], "setDiscussionInviteStatus", false, arguments); RongIMClient._dataAccessProvider.setDiscussionInviteStatus(discussionId, status, RongIMClient.logCallback(callback, "setDiscussionInviteStatus")); }; /** * [setDiscussionName 设置讨论组名称] * @param {string} discussionId [讨论组Id] * @param {string} name [讨论组名称] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.setDiscussionName = function (discussionId, name, callback) { RongIMLib.CheckParam.getInstance().check(["string", "string", "object"], "setDiscussionName", false, arguments); RongIMClient._dataAccessProvider.setDiscussionName(discussionId, name, RongIMClient.logCallback(callback, "setDiscussionName")); }; // #endregion Discussion // #region ChatRoom /** * [加入聊天室。] * @param {string} chatroomId [聊天室Id] * @param {number} messageCount [拉取消息数量,-1为不拉去消息] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.joinChatRoom = function (chatroomId, messageCount, callback) { RongIMLib.CheckParam.getInstance().check(["string", "number", "object"], "joinChatRoom", false, arguments); if (chatroomId == "") { setTimeout(function () { var errorCode = RongIMLib.ErrorCode.CHATROOM_ID_ISNULL; RongIMClient.logger({ code: errorCode, funcName: "joinChatRoom" }); callback.onError(RongIMLib.ErrorCode.CHATROOM_ID_ISNULL); }); return; } RongIMClient._dataAccessProvider.joinChatRoom(chatroomId, messageCount, RongIMClient.logCallback(callback, "joinChatRoom")); }; RongIMClient.prototype.setDeviceInfo = function (device) { RongIMClient._dataAccessProvider.setDeviceInfo(device); }; RongIMClient.prototype.setChatroomHisMessageTimestamp = function (chatRoomId, timestamp) { RongIMLib.CheckParam.getInstance().check(["string", "number"], "setChatroomHisMessageTimestamp", false, arguments); RongIMClient._dataAccessProvider.setChatroomHisMessageTimestamp(chatRoomId, timestamp); }; RongIMClient.prototype.getChatRoomHistoryMessages = function (chatRoomId, count, order, callback) { RongIMLib.CheckParam.getInstance().check(["string", "number", "number", "object"], "getChatRoomHistoryMessages", false, arguments); RongIMClient._dataAccessProvider.getChatRoomHistoryMessages(chatRoomId, count, order, RongIMClient.logCallback(callback, "getChatRoomHistoryMessages")); }; RongIMClient.prototype.getChatRoomInfo = function (chatRoomId, count, order, callback) { RongIMLib.CheckParam.getInstance().check(["string", "number", "number", "object"], "getChatRoomInfo", false, arguments); RongIMClient._dataAccessProvider.getChatRoomInfo(chatRoomId, count, order, RongIMClient.logCallback(callback, "getChatRoomInfo")); }; /** * [退出聊天室] * @param {string} chatroomId [聊天室Id] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.quitChatRoom = function (chatroomId, callback) { RongIMLib.CheckParam.getInstance().check(["string", "object"], "quitChatRoom", false, arguments); RongIMClient._dataAccessProvider.quitChatRoom(chatroomId, RongIMClient.logCallback(callback, "quitChatRoom")); }; RongIMClient.prototype.setChatroomEntry = function (chatroomId, chatroomEntry, callback) { RongIMLib.CheckParam.getInstance().check(['string', 'object', 'object'], 'setChatroomEntry', false, arguments); RongIMClient._dataAccessProvider.setChatroomEntry(chatroomId, chatroomEntry, RongIMClient.logCallback(callback, "setChatroomEntry")); }; RongIMClient.prototype.forceSetChatroomEntry = function (chatroomId, chatroomEntry, callback) { RongIMLib.CheckParam.getInstance().check(['string', 'object', 'object'], 'setChatroomEntry', false, arguments); RongIMClient._dataAccessProvider.forceSetChatroomEntry(chatroomId, chatroomEntry, RongIMClient.logCallback(callback, "setChatroomEntry")); }; RongIMClient.prototype.getChatroomEntry = function (chatroomId, key, callback) { RongIMLib.CheckParam.getInstance().check(['string', 'string', 'object'], 'getChatroomEntry', false, arguments); RongIMClient._dataAccessProvider.getChatroomEntry(chatroomId, key, RongIMClient.logCallback(callback, "setChatroomEntry")); }; RongIMClient.prototype.getAllChatroomEntries = function (chatroomId, callback) { RongIMLib.CheckParam.getInstance().check(['string', 'object'], 'getAllChatroomEntries', false, arguments); RongIMClient._dataAccessProvider.getAllChatroomEntries(chatroomId, RongIMClient.logCallback(callback, "setChatroomEntry")); }; RongIMClient.prototype.removeChatroomEntry = function (chatroomId, chatroomEntry, callback) { RongIMLib.CheckParam.getInstance().check(['string', 'object', 'object'], 'removeChatroomEntry', false, arguments); RongIMClient._dataAccessProvider.removeChatroomEntry(chatroomId, chatroomEntry, RongIMClient.logCallback(callback, "setChatroomEntry")); }; RongIMClient.prototype.forceRemoveChatroomEntry = function (chatroomId, chatroomEntry, callback) { RongIMLib.CheckParam.getInstance().check(['string', 'object', 'object'], 'removeChatroomEntry', false, arguments); RongIMClient._dataAccessProvider.forceRemoveChatroomEntry(chatroomId, chatroomEntry, RongIMClient.logCallback(callback, "setChatroomEntry")); }; // #endregion ChatRoom // #region Public Service RongIMClient.prototype.getRemotePublicServiceList = function (callback, pullMessageTime) { RongIMClient._dataAccessProvider.getRemotePublicServiceList(RongIMClient.logCallback(callback, "getRemotePublicServiceList"), pullMessageTime); }; /** * [getPublicServiceList ]获取本地的公共账号列表 * @param {ResultCallback} callback [返回值,参数回调] */ RongIMClient.prototype.getPublicServiceList = function (callback) { if (RongIMClient._memoryStore.depend.openMp) { RongIMLib.CheckParam.getInstance().check(["object"], "getPublicServiceList", false, arguments); this.getRemotePublicServiceList(RongIMClient.logCallback(callback, "getPublicServiceList")); } }; /** * [getPublicServiceProfile ] 获取某公共服务信息。 * @param {PublicServiceType} publicServiceType [公众服务类型。] * @param {string} publicServiceId [公共服务 Id。] * @param {ResultCallback} callback [公共账号信息回调。] */ RongIMClient.prototype.getPublicServiceProfile = function (publicServiceType, publicServiceId, callback) { if (RongIMClient._memoryStore.depend.openMp) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "getPublicServiceProfile", false, arguments); RongIMClient._dataAccessProvider.getPublicServiceProfile(publicServiceType, publicServiceId, RongIMClient.logCallback(callback, "getPublicServiceProfile")); } }; /** * [pottingPublicSearchType ] 公众好查询类型 * @param {number} bussinessType [ 0-all 1-mp 2-mc] * @param {number} searchType [0-exact 1-fuzzy] */ RongIMClient.prototype.pottingPublicSearchType = function (bussinessType, searchType) { if (RongIMClient._memoryStore.depend.openMp) { var bits = 0; if (bussinessType == 0) { bits |= 3; if (searchType == 0) { bits |= 12; } else { bits |= 48; } } else if (bussinessType == 1) { bits |= 1; if (searchType == 0) { bits |= 8; } else { bits |= 32; } } else { bits |= 2; if (bussinessType == 0) { bits |= 4; } else { bits |= 16; } } return bits; } }; /** * [searchPublicService ]按公众服务类型搜索公众服务。 * @param {SearchType} searchType [搜索类型枚举。] * @param {string} keywords [搜索关键字。] * @param {ResultCallback} callback [搜索结果回调。] */ RongIMClient.prototype.searchPublicService = function (searchType, keywords, callback) { if (RongIMClient._memoryStore.depend.openMp) { RongIMLib.CheckParam.getInstance().check(["number", "string", "object"], "searchPublicService", false, arguments); var modules = new RongIMClient.Protobuf.SearchMpInput(); modules.setType(this.pottingPublicSearchType(0, searchType)); modules.setId(keywords); RongIMClient.bridge.queryMsg(29, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, RongIMClient.logCallback(callback, "searchPublicService"), "SearchMpOutput"); } }; /** * [searchPublicServiceByType ]按公众服务类型搜索公众服务。 * @param {PublicServiceType} publicServiceType [公众服务类型。] * @param {SearchType} searchType [搜索类型枚举。] * @param {string} keywords [搜索关键字。] * @param {ResultCallback} callback [搜索结果回调。] */ RongIMClient.prototype.searchPublicServiceByType = function (publicServiceType, searchType, keywords, callback) { if (RongIMClient._memoryStore.depend.openMp) { RongIMLib.CheckParam.getInstance().check(["number", "number", "string", "object"], "searchPublicServiceByType", false, arguments); var type = publicServiceType == RongIMLib.ConversationType.APP_PUBLIC_SERVICE ? 2 : 1; var modules = new RongIMClient.Protobuf.SearchMpInput(); modules.setType(this.pottingPublicSearchType(type, searchType)); modules.setId(keywords); RongIMClient.bridge.queryMsg(29, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, RongIMClient.logCallback(callback, "searchPublicServiceByType"), "SearchMpOutput"); } }; /** * [subscribePublicService ] 订阅公众号。 * @param {PublicServiceType} publicServiceType [公众服务类型。] * @param {string} publicServiceId [公共服务 Id。] * @param {OperationCallback} callback [订阅公众号回调。] */ RongIMClient.prototype.subscribePublicService = function (publicServiceType, publicServiceId, callback) { if (RongIMClient._memoryStore.depend.openMp) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "subscribePublicService", false, arguments); var modules = new RongIMClient.Protobuf.MPFollowInput(), me = this, follow = publicServiceType == RongIMLib.ConversationType.APP_PUBLIC_SERVICE ? "mcFollow" : "mpFollow"; modules.setId(publicServiceId); RongIMClient.bridge.queryMsg(follow, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function () { me.getRemotePublicServiceList({ onSuccess: function () { }, onError: function () { } }); callback.onSuccess(); }, onError: function (code) { var errorCode = code; RongIMClient.logger({ code: errorCode, funcName: "subscribePublicService" }); callback.onError(code); } }, "MPFollowOutput"); } }; /** * [unsubscribePublicService ] 取消订阅公众号。 * @param {PublicServiceType} publicServiceType [公众服务类型。] * @param {string} publicServiceId [公共服务 Id。] * @param {OperationCallback} callback [取消订阅公众号回调。] */ RongIMClient.prototype.unsubscribePublicService = function (publicServiceType, publicServiceId, callback) { if (RongIMClient._memoryStore.depend.openMp) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "unsubscribePublicService", false, arguments); var modules = new RongIMClient.Protobuf.MPFollowInput(), me = this, follow = publicServiceType == RongIMLib.ConversationType.APP_PUBLIC_SERVICE ? "mcUnFollow" : "mpUnFollow"; modules.setId(publicServiceId); RongIMClient.bridge.queryMsg(follow, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function () { RongIMClient._memoryStore.publicServiceMap.remove(publicServiceType, publicServiceId); callback.onSuccess(); }, onError: function (code) { var errorCode = code; RongIMClient.logger({ code: errorCode, funcName: "unsubscribePublicService" }); callback.onError(code); } }, "MPFollowOutput"); } }; // #endregion Public Service // #region Blacklist /** * [加入黑名单] * @param {string} userId [将被加入黑名单的用户Id] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.addToBlacklist = function (userId, callback) { RongIMLib.CheckParam.getInstance().check(["string|number", "object"], "addToBlacklist", false, arguments); RongIMClient._dataAccessProvider.addToBlacklist(userId, RongIMClient.logCallback(callback, "addToBlacklist")); }; /** * [获取黑名单列表] * @param {GetBlacklistCallback} callback [返回值,函数回调] */ RongIMClient.prototype.getBlacklist = function (callback) { RongIMLib.CheckParam.getInstance().check(["object"], "getBlacklist", false, arguments); RongIMClient._dataAccessProvider.getBlacklist(callback); }; /** * [得到指定人员再黑名单中的状态] * @param {string} userId [description] * @param {ResultCallback} callback [返回值,函数回调] */ //TODO 如果人员不在黑名单中,获取状态会出现异常 RongIMClient.prototype.getBlacklistStatus = function (userId, callback) { RongIMLib.CheckParam.getInstance().check(["string|number", "object"], "getBlacklistStatus", false, arguments); RongIMClient._dataAccessProvider.getBlacklistStatus(userId, RongIMClient.logCallback(callback, "getBlacklistStatus")); }; /** * [将指定用户移除黑名单] * @param {string} userId [将被移除的用户Id] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.removeFromBlacklist = function (userId, callback) { RongIMLib.CheckParam.getInstance().check(["string|number", "object"], "removeFromBlacklist", false, arguments); RongIMClient._dataAccessProvider.removeFromBlacklist(userId, RongIMClient.logCallback(callback, "removeFromBlacklist")); }; RongIMClient.prototype.getFileToken = function (fileType, callback) { RongIMLib.CheckParam.getInstance().check(["number", "object"], "getQngetFileTokenTkn", false, arguments); RongIMClient._dataAccessProvider.getFileToken(fileType, RongIMClient.logCallback(callback, "getFileToken")); }; RongIMClient.prototype.getFileUrl = function (fileType, fileName, oriName, callback) { RongIMLib.CheckParam.getInstance().check(["number", "string", "string|global|object|null", "object"], "getFileUrl", false, arguments); RongIMClient._dataAccessProvider.getFileUrl(fileType, fileName, oriName, RongIMClient.logCallback(callback, "getFileUrl")); }; ; // #endregion Blacklist // #region Real-time Location Service RongIMClient.prototype.addRealTimeLocationListener = function (conversationType, targetId, listener) { throw new Error("Not implemented yet"); }; RongIMClient.prototype.getRealTimeLocation = function (conversationType, targetId) { throw new Error("Not implemented yet"); }; RongIMClient.prototype.getRealTimeLocationCurrentState = function (conversationType, targetId) { throw new Error("Not implemented yet"); }; RongIMClient.prototype.getRealTimeLocationParticipants = function (conversationType, targetId) { throw new Error("Not implemented yet"); }; RongIMClient.prototype.joinRealTimeLocation = function (conversationType, targetId) { throw new Error("Not implemented yet"); }; RongIMClient.prototype.quitRealTimeLocation = function (conversationType, targetId) { throw new Error("Not implemented yet"); }; RongIMClient.prototype.startRealTimeLocation = function (conversationType, targetId) { throw new Error("Not implemented yet"); }; RongIMClient.prototype.updateRealTimeLocationStatus = function (conversationType, targetId, latitude, longitude) { throw new Error("Not implemented yet"); }; // #endregion Real-time Location Service // # startVoIP RongIMClient.prototype.startCall = function (converType, targetId, userIds, mediaType, extra, callback) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "array", "number", "string", "object"], "startCall", false, arguments); if (RongIMClient._memoryStore.voipStategy) { RongIMClient._voipProvider.startCall(converType, targetId, userIds, mediaType, extra, RongIMClient.logCallback(callback, "startCall")); } else { var errorCode = RongIMLib.ErrorCode.VOIP_NOT_AVALIABLE; RongIMClient.logger({ code: errorCode, funcName: "startCall" }); callback.onError(RongIMLib.ErrorCode.VOIP_NOT_AVALIABLE); } }; RongIMClient.prototype.joinCall = function (mediaType, callback) { RongIMLib.CheckParam.getInstance().check(['number', 'object'], "joinCall", false, arguments); if (RongIMClient._memoryStore.voipStategy) { RongIMClient._voipProvider.joinCall(mediaType, RongIMClient.logCallback(callback, "joinCall")); } else { var errorCode = RongIMLib.ErrorCode.VOIP_NOT_AVALIABLE; RongIMClient.logger({ code: errorCode, funcName: "joinCall" }); callback.onError(RongIMLib.ErrorCode.VOIP_NOT_AVALIABLE); } }; RongIMClient.prototype.hungupCall = function (converType, targetId, reason) { RongIMLib.CheckParam.getInstance().check(["number", "string", "number"], "hungupCall", false, arguments); if (RongIMClient._memoryStore.voipStategy) { RongIMClient._voipProvider.hungupCall(converType, targetId, reason); } }; RongIMClient.prototype.changeMediaType = function (converType, targetId, mediaType, callback) { RongIMLib.CheckParam.getInstance().check(["number", "string", "number", "object"], "changeMediaType", false, arguments); if (RongIMClient._memoryStore.voipStategy) { RongIMClient._voipProvider.changeMediaType(converType, targetId, mediaType, RongIMClient.logCallback(callback, "changeMediaType")); } else { var errorCode = RongIMLib.ErrorCode.VOIP_NOT_AVALIABLE; RongIMClient.logger({ code: errorCode, funcName: "changeMediaType" }); callback.onError(RongIMLib.ErrorCode.VOIP_NOT_AVALIABLE); } }; // # endVoIP RongIMClient.prototype.getUnreadMentionedMessages = function (conversationType, targetId) { return RongIMClient._dataAccessProvider.getUnreadMentionedMessages(conversationType, targetId); }; RongIMClient.prototype.clearListeners = function () { RongIMClient._dataAccessProvider.clearListeners(); }; // UserStatus start RongIMClient.prototype.getUserStatus = function (userId, callback) { RongIMClient._dataAccessProvider.getUserStatus(userId, RongIMClient.logCallback(callback, "getUserStatus")); }; RongIMClient.prototype.setUserStatus = function (status, callback) { RongIMClient._dataAccessProvider.setUserStatus(status, RongIMClient.logCallback(callback, "setUserStatus")); }; RongIMClient.prototype.setUserStatusListener = function (params, callback) { var userIds = params.userIds; var multiple = params.multiple; RongIMClient.userStatusObserver.watch({ key: userIds, func: callback, multiple: multiple }); RongIMClient._dataAccessProvider.setUserStatusListener(params, callback); }; // UserStaus end // RTC start RongIMClient.messageWatch = function (watcher) { RongIMClient.RTCListener = watcher; }; RongIMClient.messageSignalWatch = function (watcher) { RongIMClient.RTCSignalLisener = watcher; }; /* var data = { key1: 123, key2: 345 }; */ RongIMClient.prototype.getRTCUserInfoList = function (room, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object"], "getRTCUserInfoList", false, arguments); RongIMClient._dataAccessProvider.getRTCUserInfoList(room, callback); }; RongIMClient.prototype.getRTCUserList = function (room, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object"], "getRTCUserList", false, arguments); RongIMClient._dataAccessProvider.getRTCUserList(room, callback); }; RongIMClient.prototype.setRTCUserInfo = function (room, info, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object", "object"], "setRTCUserInfo", false, arguments); RongIMClient._dataAccessProvider.setRTCUserInfo(room, info, callback); }; RongIMClient.prototype.removeRTCUserInfo = function (room, info, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object", "object"], "removeRTCUserInfo", false, arguments); RongIMClient._dataAccessProvider.removeRTCUserInfo(room, info, callback); }; RongIMClient.prototype.getRTCRoomInfo = function (room, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object"], "getRTCRoomInfo", false, arguments); RongIMClient._dataAccessProvider.getRTCRoomInfo(room, callback); }; RongIMClient.prototype.setRTCRoomInfo = function (room, info, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object", "object"], "setRTCRoomInfo", false, arguments); RongIMClient._dataAccessProvider.setRTCRoomInfo(room, info, callback); }; RongIMClient.prototype.removeRTCRoomInfo = function (room, info, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object", "object"], "removeRTCRoomInfo", false, arguments); RongIMClient._dataAccessProvider.removeRTCRoomInfo(room, info, callback); }; RongIMClient.prototype.joinRTCRoom = function (room, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object"], "joinRTCRoom", false, arguments); if (RongIMClient.isJoinedRTCRoom) { return callback.onSuccess(RongIMClient.roomInfo); } RongIMClient._dataAccessProvider.joinRTCRoom(room, { onSuccess: function (result) { RongIMClient.roomInfo = result; RongIMClient.isJoinedRTCRoom = true; callback.onSuccess(result); }, onError: callback.onError }); }; RongIMClient.prototype.quitRTCRoom = function (room, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object"], "quitRTCRoom", false, arguments); RongIMClient.isJoinedRTCRoom = false; RongIMClient._dataAccessProvider.quitRTCRoom(room, { onSuccess: function () { RongIMClient.roomInfo = { users: {}, token: '' }; callback.onSuccess(true); }, onError: callback.onError }); }; RongIMClient.prototype.RTCPing = function (room, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object"], "RTCPing", false, arguments); RongIMClient._dataAccessProvider.RTCPing(room, callback); }; RongIMClient.prototype.setRTCUserData = function (roomId, key, value, isInner, callback, message) { RongIMLib.CheckParam.getInstance().check(["string", "string", "string", "boolean", "object", "global|object|null|undefined"], "setRTCUserData", false, arguments); RongIMClient._dataAccessProvider.setRTCUserData(roomId, key, value, isInner, callback, message); }; RongIMClient.prototype.getRTCUserData = function (roomId, keys, isInner, callback) { RongIMLib.CheckParam.getInstance().check(["string", "array", "boolean", "object", "global|object|null"], "getRTCUserData", false, arguments); RongIMClient._dataAccessProvider.getRTCUserData(roomId, keys, isInner, callback); }; RongIMClient.prototype.removeRTCUserData = function (roomId, keys, isInner, callback, message) { RongIMLib.CheckParam.getInstance().check(["string", "array", "boolean", "object", "global|object|null|undefined"], "removeRTCUserData", false, arguments); RongIMClient._dataAccessProvider.removeRTCUserData(roomId, keys, isInner, callback, message); }; RongIMClient.prototype.setRTCRoomData = function (roomId, key, value, isInner, callback, message) { RongIMLib.CheckParam.getInstance().check(["string", "string", "string", "boolean", "object", "global|object|null|undefined"], "setRTCRoomData", false, arguments); RongIMClient._dataAccessProvider.setRTCRoomData(roomId, key, value, isInner, callback, message); }; RongIMClient.prototype.getRTCRoomData = function (roomId, keys, isInner, callback) { RongIMLib.CheckParam.getInstance().check(["string", "array", "boolean", "object"], "getRTCRoomData", false, arguments); RongIMClient._dataAccessProvider.getRTCRoomData(roomId, keys, isInner, callback); }; RongIMClient.prototype.removeRTCRoomData = function (roomId, keys, isInner, callback, message) { RongIMLib.CheckParam.getInstance().check(["string", "array", "boolean", "object", "global|object|null|undefined"], "removeRTCRoomData", false, arguments); RongIMClient._dataAccessProvider.removeRTCRoomData(roomId, keys, isInner, callback, message); }; RongIMClient.prototype.setRTCOutData = function (roomId, data, type, callback, message) { RongIMClient._dataAccessProvider.setRTCOutData(roomId, data, type, callback, message); }; // 信令 SDK 新增 RongIMClient.prototype.getRTCOutData = function (roomId, userIds, callback) { RongIMClient._dataAccessProvider.getRTCOutData(roomId, userIds, callback); }; RongIMClient.prototype.getNavi = function () { return RongIMClient._dataAccessProvider.getNavi(); }; RongIMClient.prototype.getRTCToken = function (room, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object"], "getRTCToken", false, arguments); return RongIMClient._dataAccessProvider.getRTCToken(room, callback); }; RongIMClient.prototype.setRTCState = function (room, content, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object", "object"], "setRTCState", false, arguments); return RongIMClient._dataAccessProvider.setRTCState(room, content, callback); }; RongIMClient.prototype.getAppInfo = function () { var appKey = RongIMClient._memoryStore.appKey; return { appKey: appKey }; }; RongIMClient.prototype.getSDKInfo = function () { return { version: RongIMClient.sdkver }; }; RongIMClient.RTCListener = function () { }; RongIMClient.RTCInnerListener = function () { }; RongIMClient.RTCSignalLisener = function () { }; RongIMClient.currentServer = ''; RongIMClient.LogFactory = {}; RongIMClient.MessageType = {}; RongIMClient.RegisterMessage = {}; RongIMClient._memoryStore = { isPullFinished: false, syncMsgQueue: [] }; RongIMClient.isNotPullMsg = false; RongIMClient.userStatusObserver = null; RongIMClient.sdkver = '2.5.3'; RongIMClient.otherDeviceLoginCount = 0; RongIMClient.serverStore = { index: 0 }; RongIMClient.isFirstConnect = true; RongIMClient.roomInfo = { users: {}, token: '' }; RongIMClient.invalidWsUrls = []; RongIMClient.isJoinedRTCRoom = false; RongIMClient.statusListeners = []; RongIMClient.messageListeners = []; RongIMClient.userStatusListener = null; return RongIMClient; })(); RongIMLib.RongIMClient = RongIMClient; })(RongIMLib || (RongIMLib = {})); //用于连接通道 var RongIMLib; (function (RongIMLib) { (function (Qos) { Qos[Qos["AT_MOST_ONCE"] = 0] = "AT_MOST_ONCE"; Qos[Qos["AT_LEAST_ONCE"] = 1] = "AT_LEAST_ONCE"; Qos[Qos["EXACTLY_ONCE"] = 2] = "EXACTLY_ONCE"; Qos[Qos["DEFAULT"] = 3] = "DEFAULT"; })(RongIMLib.Qos || (RongIMLib.Qos = {})); var Qos = RongIMLib.Qos; (function (Type) { Type[Type["CONNECT"] = 1] = "CONNECT"; Type[Type["CONNACK"] = 2] = "CONNACK"; Type[Type["PUBLISH"] = 3] = "PUBLISH"; Type[Type["PUBACK"] = 4] = "PUBACK"; Type[Type["QUERY"] = 5] = "QUERY"; Type[Type["QUERYACK"] = 6] = "QUERYACK"; Type[Type["QUERYCON"] = 7] = "QUERYCON"; Type[Type["SUBSCRIBE"] = 8] = "SUBSCRIBE"; Type[Type["SUBACK"] = 9] = "SUBACK"; Type[Type["UNSUBSCRIBE"] = 10] = "UNSUBSCRIBE"; Type[Type["UNSUBACK"] = 11] = "UNSUBACK"; Type[Type["PINGREQ"] = 12] = "PINGREQ"; Type[Type["PINGRESP"] = 13] = "PINGRESP"; Type[Type["DISCONNECT"] = 14] = "DISCONNECT"; })(RongIMLib.Type || (RongIMLib.Type = {})); var Type = RongIMLib.Type; var _topic = [ "invtDiz", "crDiz", "qnUrl", "userInf", "dizInf", "userInf", "joinGrp", "quitDiz", "exitGrp", "evctDiz", ["", "ppMsgP", "pdMsgP", "pgMsgP", "chatMsg", "pcMsgP", "", "pmcMsgN", "pmpMsgN", "", "", "", "prMsgS", "prMsgP"], "pdOpen", "rename", "uGcmpr", "qnTkn", "destroyChrm", "createChrm", "exitChrm", "queryChrm", "joinChrm", "pGrps", "addBlack", "rmBlack", "getBlack", "blackStat", "addRelation", "qryRelation", "delRelation", "pullMp", "schMp", "qnTkn", "qnUrl", "qryVoipK", "delMsg", "qryCHMsg", "getUserStatus", "setUserStatus", "subUserStatus", "cleanHisMsg" ]; var Channel = (function () { function Channel(cb, self) { this.connectionStatus = -1; var appId = self.appId; var token = encodeURIComponent(self.token); var sdkVer = self.sdkVer; var apiVer = self.apiVer; this.self = self; this.socket = Socket.getInstance().createServer(); var that = this; var storage = RongIMLib.RongIMClient._storageProvider; var servers = storage.getItem('servers'); servers = JSON.parse(servers) || []; servers = RongIMLib.RongUtil.getValidWsUrlList(servers); var depend = RongIMLib.RongIMClient._memoryStore.depend; var startConnect = function (host) { var tpl = '{host}/websocket?appId={appId}&token={token}&sdkVer={sdkVer}&apiVer={apiVer}'; that.url = RongIMLib.RongUtil.tplEngine(tpl, { host: host, appId: appId, token: token, sdkVer: sdkVer, apiVer: apiVer }); that.socket.connect(that.url, cb); // 临时兼容 Comet 逻辑,Comet 中用到 var userId = storage.getItem('rong_current_user'); RongIMLib.Navigation.Endpoint = { host: host, userId: userId }; }; var connectMap = { get: function () { // 所有链接计算器,超过 15 秒后认为所有 CMP 地址均不可用 var totalTimer = new RongIMLib.Timer({ timeout: 1 * 1000 * 15 }); var timers = []; var xhrs = []; var isFinished = false; var clearHandler = function () { for (var i = 0; i < timers.length; i++) { var timer = timers[i]; clearTimeout(timer); } for (var i = 0; i < xhrs.length; i++) { var xhr = xhrs[i]; xhr.abort(); } timers.length = 0; xhrs.length = 0; }; var request = function (config, callback) { var url = config.url; var time = config.time; if (isFinished) { return; } var timer = setTimeout(function () { var onSuccess = function () { if (isFinished) { return; } clearHandler(); isFinished = true; totalTimer.pause(); callback(url); }; var xhr = RongIMLib.MessageUtil.detectCMP({ url: url, success: onSuccess, fail: function (code) { console.log(code); } }); xhrs.push(xhr); }, time); timers.push(timer); }; var snifferCallback = function (url) { var reg = /(http|https):\/\/([^\/]+)/i; var host = url.match(reg)[2]; RongIMLib.RongIMClient.currentServer = host; startConnect(host); }; var snifferTpl = '{protocol}{server}/ping?r={random}'; for (var i = 0; i < servers.length; i++) { var server = servers[i]; if (server) { server = RongIMLib.RongUtil.tplEngine(snifferTpl, { protocol: depend.protocol, server: server, random: RongIMLib.RongUtil.getTimestamp() }); request({ url: server, time: i * 1000 }, snifferCallback); } } totalTimer.resume(function () { RongIMLib.Navigation.clear(); clearHandler(); that.socket.fire("StatusChanged", RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE); }); }, element: function () { var totalTimer = new RongIMLib.Timer({ timeout: 1 * 1000 * 15 }); var timers = []; var elements = []; var isFinished = false; var clearHandler = function () { for (var i = 0; i < timers.length; i++) { var timer = timers[i]; clearTimeout(timer); } for (var i = 0; i < elements.length; i++) { var el = elements[i]; document.body.removeChild(el); } }; var request = function (config, callback) { var url = config.url; var time = config.time; if (isFinished) { return; } var timer = setTimeout(function () { var el = document.createElement('script'); el.src = url; document.body.appendChild(el); el.onerror = function () { if (isFinished) { return; } clearHandler(); isFinished = true; totalTimer.pause(); var url = el.src; callback(url); }; elements.push(el); }, time); timers.push(timer); }; var snifferCallback = function (url) { var reg = /(http|https):\/\/([^\/]+)/i; var host = url.match(reg)[2]; startConnect(host); }; var snifferTpl = '//{server}/{path}'; for (var i = 0; i < servers.length; i++) { var server = RongIMLib.RongUtil.tplEngine(snifferTpl, { server: servers[i], path: i }); request({ url: server, time: i * 1000 }, snifferCallback); } totalTimer.resume(function () { clearHandler(); that.socket.fire("StatusChanged", RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE); }); } }; var isWSPingJSONP = depend.isWSPingJSONP; var connectType = isWSPingJSONP ? 'element' : 'get'; connectMap[connectType](); //注册状态改变观察者 var StatusEvent = Channel._ConnectionStatusListener; var hasEvent = (typeof StatusEvent == "object"); var me = this; me.socket.on("StatusChanged", function (code) { if (RongIMLib.Bridge && RongIMLib.Bridge._client && RongIMLib.Bridge._client.channel && me !== RongIMLib.Bridge._client.channel) { return; } if (!hasEvent) { throw new Error("setConnectStatusListener:Parameter format is incorrect"); } var isNetworkUnavailable = (code == RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE); var isWebSocket = !RongIMLib.RongIMClient._memoryStore.depend.isPolling; if (RongIMLib.RongIMClient.isFirstConnect && isNetworkUnavailable && isWebSocket) { code = RongIMLib.ConnectionStatus.WEBSOCKET_UNAVAILABLE; } if (isNetworkUnavailable) { var storage = RongIMLib.RongIMClient._storageProvider; var servers = storage.getItem('servers'); servers = JSON.parse(servers); var currentServer = RongIMLib.RongIMClient.currentServer; if (currentServer) { var index = RongIMLib.RongUtil.indexOf(servers, currentServer); // 如果 currentServer 是 servers 的最后一个,不再替换位置 if (!RongIMLib.RongUtil.isEqual(index, -1)) { var server = servers.splice(index, 1)[0]; servers.push(server); storage.setItem('servers', JSON.stringify(servers)); } } } me.connectionStatus = code; setTimeout(function () { StatusEvent.onChanged(code); }); var isDisconnected = (code == RongIMLib.ConnectionStatus.DISCONNECTED); if (isDisconnected) { self.clearHeartbeat(); } var isOtherDevice = (code == RongIMLib.ConnectionStatus.KICKED_OFFLINE_BY_OTHER_CLIENT); if (isOtherDevice) { // 累计其他设备登陆次数,超过 5 次后,自动销毁内部对象 // 删除位置:ServerDataProivder.prototype.connect RongIMLib.RongIMClient.otherDeviceLoginCount++; } var isConnected = (code == RongIMLib.ConnectionStatus.CONNECTED); if (isConnected) { RongIMLib.RongIMClient.isFirstConnect = false; } var isWebsocketUnAvailable = (code == RongIMLib.ConnectionStatus.WEBSOCKET_UNAVAILABLE); if (isWebsocketUnAvailable) { me.changeConnectType(); RongIMLib.RongIMClient.isFirstConnect = false; RongIMLib.RongIMClient.connect(self.token, RongIMLib.RongIMClient._memoryStore.callback); } }); //注册message观察者 this.socket.on("message", self.handler.handleMessage); //注册断开连接观察者 this.socket.on("disconnect", function (status) { that.socket.fire("StatusChanged", status ? status : 2); }); } Channel.prototype.changeConnectType = function () { RongIMLib.RongIMClient._memoryStore.depend.isPolling = !RongIMLib.RongIMClient._memoryStore.depend.isPolling; new RongIMLib.FeatureDectector(); }; Channel.prototype.writeAndFlush = function (val) { this.socket.send(val); }; Channel.prototype.reconnect = function (callback) { RongIMLib.MessageIdHandler.clearMessageId(); this.socket = this.socket.reconnect(); if (callback) { this.self.reconnectObj = callback; } }; Channel.prototype.disconnect = function (status) { this.socket.disconnect(status); }; return Channel; })(); RongIMLib.Channel = Channel; var Socket = (function () { function Socket() { this.socket = null; this._events = {}; } Socket.getInstance = function () { return new Socket(); }; Socket.prototype.connect = function (url, cb) { if (this.socket) { if (url) { RongIMLib.RongIMClient._storageProvider.setItem("rongSDK", this.checkTransport()); this.on("connect", cb || new Function); } if (url) { this.currentURL = url; } this.socket.createTransport(url); } return this; }; Socket.prototype.createServer = function () { var transport = this.getTransport(this.checkTransport()); if (transport === null) { throw new Error("the channel was not supported"); } return transport; }; Socket.prototype.getTransport = function (transportType) { if (transportType == Socket.XHR_POLLING) { this.socket = new RongIMLib.PollingTransportation(this); } else if (transportType == Socket.WEBSOCKET) { this.socket = new RongIMLib.SocketTransportation(this); } return this; }; Socket.prototype.send = function (data) { if (this.socket) { if (this.checkTransport() == Socket.WEBSOCKET) { this.socket.send(data); } else { this.socket.send(this._encode(data)); } } }; Socket.prototype.onMessage = function (data) { this.fire("message", data); }; Socket.prototype.disconnect = function (status) { this.socket.disconnect(status); this.fire("disconnect", status); return this; }; Socket.prototype.reconnect = function () { if (this.currentURL && RongIMLib.RongIMClient._storageProvider.getItem("rongSDK")) { return this.connect(this.currentURL, null); } else { throw new Error("reconnect:no have URL"); } }; /** * [checkTransport 返回通道类型] */ Socket.prototype.checkTransport = function () { if (RongIMLib.RongIMClient._memoryStore.depend.isPolling) { RongIMLib.Transportations._TransportType = Socket.XHR_POLLING; } return RongIMLib.Transportations._TransportType; }; Socket.prototype.fire = function (x, args) { if (x in this._events) { for (var i = 0, ii = this._events[x].length; i < ii; i++) { this._events[x][i](args); } } return this; }; Socket.prototype.on = function (x, func) { if (!(typeof func == "function" && x)) { return this; } if (x in this._events) { RongIMLib.MessageUtil.indexOf(this._events, func) == -1 && this._events[x].push(func); } else { this._events[x] = [func]; } return this; }; Socket.prototype.removeEvent = function (x, fn) { if (x in this._events) { for (var a = 0, l = this._events[x].length; a < l; a++) { if (this._events[x][a] == fn) { this._events[x].splice(a, 1); } } } return this; }; Socket.prototype._encode = function (x) { var str = "?messageid=" + x.getMessageId() + "&header=" + x.getHeaderFlag() + "&sessionid=" + RongIMLib.RongIMClient._storageProvider.getItem("sId" + RongIMLib.Navigation.Endpoint.userId); if (!/(PubAckMessage|QueryConMessage)/.test(x._name)) { str += "&topic=" + x.getTopic() + "&targetid=" + (x.getTargetId() || ""); } return { url: str, data: "getData" in x ? x.getData() : "" }; }; //消息通道常量,所有和通道相关判断均用 XHR_POLLING WEBSOCKET两属性 Socket.XHR_POLLING = "xhr-polling"; Socket.WEBSOCKET = "websocket"; return Socket; })(); RongIMLib.Socket = Socket; //连接端消息累 var Client = (function () { function Client(token, appId) { this.timeoutMillis = 6000; this.timeout_ = 0; this.sdkVer = ''; this.apiVer = Math.floor(Math.random() * 1e6); this.channel = null; this.handler = null; this.userId = ""; this.reconnectObj = {}; this.heartbeat = 0; this.pullMsgHearbeat = 0; this.chatroomId = ""; this.SyncTimeQueue = []; this.cacheMessageIds = []; this.token = token; this.appId = appId; this.SyncTimeQueue.state = "complete"; this.sdkVer = RongIMLib.RongIMClient.sdkver; } Client.prototype.resumeTimer = function () { var me = this; this.timeout_ = setTimeout(function () { me.channel.disconnect(RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE); }, this.timeoutMillis); }; Client.prototype.pauseTimer = function () { if (this.timeout_) { clearTimeout(this.timeout_); this.timeout_ = 0; } }; Client.prototype.connect = function (_callback) { //实例消息处理类 this.handler = new MessageHandler(this); //设置连接回调 this.handler.setConnectCallback(_callback); //实例通道类型 var me = this; this.channel = new Channel(function () { RongIMLib.Transportations._TransportType == Socket.WEBSOCKET && me.keepLive(); }, this); //触发状态改变观察者 this.channel.socket.fire("StatusChanged", RongIMLib.ConnectionStatus.CONNECTING); //没有返回地址就手动抛出错误 //_callback.onError(ConnectionState.NOT_AUTHORIZED); }; Client.prototype.checkSocket = function (callback) { var me = this; me.channel.writeAndFlush(new RongIMLib.PingReqMessage()); var count = 0; var checkTimeout = setInterval(function () { if (!RongIMLib.RongIMClient._memoryStore.isFirstPingMsg) { clearInterval(checkTimeout); callback.onSuccess(); } else { if (count > 15) { clearInterval(checkTimeout); callback.onError(); } } count++; }, 100); }; Client.prototype.keepLive = function () { if (this.heartbeat > 0) { clearInterval(this.heartbeat); } var me = this; me.heartbeat = setInterval(function () { me.resumeTimer(); me.channel.writeAndFlush(new RongIMLib.PingReqMessage()); }, 30000); if (me.pullMsgHearbeat > 0) { clearInterval(me.pullMsgHearbeat); } me.pullMsgHearbeat = setInterval(function () { me.syncTime(true, undefined, undefined, false); }, 180000); }; Client.prototype.clearHeartbeat = function () { clearInterval(this.heartbeat); this.heartbeat = 0; this.pauseTimer(); clearInterval(this.pullMsgHearbeat); this.pullMsgHearbeat = 0; }; Client.prototype.publishMessage = function (_topic, _data, _targetId, _callback, _msg) { var msgId = RongIMLib.MessageIdHandler.messageIdPlus(this.channel.reconnect); if (!msgId) { return; } var msg = new RongIMLib.PublishMessage(_topic, _data, _targetId); msg.setMessageId(msgId); if (_callback) { msg.setQos(Qos.AT_LEAST_ONCE); this.handler.putCallback(new RongIMLib.PublishCallback(_callback.onSuccess, _callback.onError), msg.getMessageId(), _msg); } else { msg.setQos(Qos.AT_MOST_ONCE); } this.channel.writeAndFlush(msg); }; Client.prototype.queryMessage = function (_topic, _data, _targetId, _qos, _callback, pbtype) { if (_topic == "userInf") { if (Client.userInfoMapping[_targetId]) { _callback.onSuccess(Client.userInfoMapping[_targetId]); return; } } var msgId = RongIMLib.MessageIdHandler.messageIdPlus(this.channel.reconnect); if (!msgId) { return; } var msg = new RongIMLib.QueryMessage(_topic, _data, _targetId); msg.setMessageId(msgId); msg.setQos(_qos); this.handler.putCallback(new RongIMLib.QueryCallback(_callback.onSuccess, _callback.onError), msg.getMessageId(), pbtype); this.channel.writeAndFlush(msg); }; Client.prototype.invoke = function (isPullMsg, chrmId, offlineMsg) { var time, modules, str, me = this, target, temp = this.SyncTimeQueue.shift(); if (temp == undefined) { return; } this.SyncTimeQueue.state = "pending"; var localSyncTime = RongIMLib.SyncTimeUtil.get(); var sentBoxTime = localSyncTime.sent; if (temp.type != 2) { //普通消息 time = localSyncTime.received; modules = new RongIMLib.RongIMClient.Protobuf.SyncRequestMsg(); modules.setIspolling(false); str = "pullMsg"; target = this.userId; modules.setSendBoxSyncTime(sentBoxTime); } else { //聊天室消息 target = temp.chrmId || me.chatroomId; time = RongIMLib.RongIMClient._memoryStore.lastReadTime.get(target + Bridge._client.userId + "CST") || 0; modules = new RongIMLib.RongIMClient.Protobuf.ChrmPullMsg(); modules.setCount(0); str = "chrmPull"; if (!target) { throw new Error("syncTime:Received messages of chatroom but was not init"); } } //判断服务器给的时间是否消息本地存储的时间,小于的话不执行拉取操作,进行一下步队列操作 if (temp.pulltime <= time) { this.SyncTimeQueue.state = "complete"; this.invoke(isPullMsg, target, offlineMsg); return; } if (isPullMsg && 'setIsPullSend' in modules) { modules.setIsPullSend(true); } modules.setSyncTime(time); //发送queryMessage请求 this.queryMessage(str, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), target, Qos.AT_LEAST_ONCE, { onSuccess: function (collection) { var sync = RongIMLib.MessageUtil.int64ToTimestamp(collection.syncTime), symbol = target; //把返回时间戳存入本地,普通消息key为userid,聊天室消息key为userid+'CST';value都为服务器返回的时间戳 var isChrmPull = str == 'chrmPull'; if (isChrmPull) { symbol += Bridge._client.userId + "CST"; RongIMLib.RongIMClient._memoryStore.lastReadTime.set(symbol, sync); } else { var storage = RongIMLib.RongIMClient._storageProvider; if (sync > storage.getItem(symbol)) { storage.setItem(symbol, sync); } } //把拉取到的消息逐条传给消息监听器 var list = collection.list; var isPullFinished = collection.finished; // chrmPull 没有 finished 字段,自动设置为拉取完成 if (isChrmPull) { isPullFinished = true; } // 兼容长轮训 finished 为空的造成丢消息情况 if (typeof isPullFinished == 'undefined') { isPullFinished = true; } RongIMLib.RongIMClient._memoryStore.isPullFinished = isPullFinished; var connectAckTime = RongIMLib.RongIMClient._memoryStore.connectAckTime; var len = list.length; for (var i = 0, count = len; i < len; i++) { count -= 1; var message = list[i]; var sentTime = RongIMLib.MessageUtil.int64ToTimestamp(message.dataTime); var isSender = message.direction == RongIMLib.MessageDirection.SEND; var compareTime = isSender ? sentBoxTime : time; if (sentTime > compareTime) { var isSyncMessage = false; var isOffLineMessage = sentTime < connectAckTime; Bridge._client.handler.onReceived(message, undefined, isOffLineMessage, count, isSyncMessage, isPullFinished); } } if (len <= 200 && str == 'pullMsg') { var Conversation = RongIMLib.RongIMClient._dataAccessProvider.Conversation; var conversationList = RongIMLib.RongIMClient._memoryStore.conversationList; Conversation._notify(conversationList); } me.SyncTimeQueue.state = "complete"; me.invoke(isPullMsg, target, offlineMsg); }, onError: function (error) { me.SyncTimeQueue.state = "complete"; me.invoke(isPullMsg, target, offlineMsg); } }, "DownStreamMessages"); }; Client.prototype.syncTime = function (_type, pullTime, chrmId, offlineMsg) { this.SyncTimeQueue.push({ type: _type, pulltime: pullTime, chrmId: chrmId }); //如果队列中只有一个成员并且状态已经完成就执行invoke方法 if (this.SyncTimeQueue.length == 1 && this.SyncTimeQueue.state == "complete") { this.invoke(!_type, chrmId, offlineMsg); } }; Client.prototype.__init = function (f) { this.handler = new MessageHandler(this); //设置连接回调 this.handler.setConnectCallback(RongIMLib.RongIMClient._memoryStore.callback); this.channel = new Channel(f, this); }; Client.userInfoMapping = {}; return Client; })(); RongIMLib.Client = Client; //连接类,实现imclient与connect_client的连接 var Bridge = (function () { function Bridge() { } Bridge.getInstance = function () { return new Bridge(); }; //连接服务器 Bridge.prototype.connect = function (appKey, token, callback) { if (!RongIMLib.RongIMClient.Protobuf) { return; } Bridge._client = new RongIMLib.Navigation().connect(appKey, token, callback); return Bridge._client; }; Bridge.prototype.setListener = function () { Channel._ConnectionStatusListener = { onChanged: function (status) { RongIMLib.RongUtil.forEach(RongIMLib.RongIMClient.statusListeners, function (watch) { RongIMLib.RongUtil.isFunction(watch) && watch(status); }); } }; Channel._ReceiveMessageListener = { onReceived: function (msg, count, hasMore) { RongIMLib.RongUtil.forEach(RongIMLib.RongIMClient.messageListeners, function (watch) { RongIMLib.RongUtil.isFunction(watch) && watch(msg, count, hasMore); }); } }; }; Bridge.prototype.reconnect = function (callabck) { Bridge._client.channel.reconnect(callabck); }; Bridge.prototype.disconnect = function () { Bridge._client.channel.disconnect(2); }; //执行queryMessage请求 Bridge.prototype.queryMsg = function (topic, content, targetId, callback, pbname) { if (typeof topic != "string") { topic = _topic[topic]; } Bridge._client.queryMessage(topic, content, targetId, Qos.AT_MOST_ONCE, callback, pbname); }; //发送消息 执行publishMessage 请求 Bridge.prototype.pubMsg = function (topic, content, targetId, callback, msg, methodType) { if (typeof methodType == 'number') { if (methodType == RongIMLib.MethodType.CUSTOMER_SERVICE) { Bridge._client.publishMessage("pcuMsgP", content, targetId, callback, msg); } else if (methodType == RongIMLib.MethodType.RECALL) { Bridge._client.publishMessage("recallMsg", content, targetId, callback, msg); } } else { Bridge._client.publishMessage(_topic[10][topic], content, targetId, callback, msg); } }; return Bridge; })(); RongIMLib.Bridge = Bridge; var MessageHandler = (function () { function MessageHandler(client) { this.map = {}; this.connectCallback = null; if (!Channel._ReceiveMessageListener) { throw new Error("please set onReceiveMessageListener"); } this._onReceived = Channel._ReceiveMessageListener.onReceived; this._client = client; this.syncMsgMap = new Object; } //把对象推入回调对象队列中,并启动定时器 MessageHandler.prototype.putCallback = function (callbackObj, _publishMessageId, _msg) { var item = { Callback: callbackObj, Message: _msg }; item.Callback.resumeTimer(); this.map[_publishMessageId] = item; }; //设置连接回调对象,启动定时器 MessageHandler.prototype.setConnectCallback = function (_connectCallback) { if (_connectCallback) { this.connectCallback = new RongIMLib.ConnectAck(_connectCallback.onSuccess, _connectCallback.onError, this._client); } }; MessageHandler.prototype.handleChrmKVPullMsg = function (msg) { try { var pbtype = 'ChrmNotifyMsg'; var data = RongIMLib.CallbackMapping.getInstance().mapping(RongIMLib.RongIMClient.Protobuf[pbtype].decode(msg.data), pbtype); if (data.type === 2) { var timestamp = RongIMLib.MessageUtil.int64ToTimestamp(data.time); RongIMLib.ChrmKVHandler.pull(data.chrmId, timestamp); } } catch (e) { } }; MessageHandler.prototype.onReceived = function (msg, pubAckItem, offlineMsg, leftCount, isSync) { //实体对象 var entity, //解析完成的消息对象 message, //会话对象 con, // 是否为直发消息 isStraightMsg = false; if (msg._name != "PublishMessage") { entity = msg; RongIMLib.RongIMClient._storageProvider.setItem(this._client.userId, RongIMLib.MessageUtil.int64ToTimestamp(entity.dataTime)); } else { if (msg.getTopic() == "s_ntf") { entity = RongIMLib.RongIMClient.Protobuf.NotifyMsg.decode(msg.getData()); this._client.syncTime(entity.type, RongIMLib.MessageUtil.int64ToTimestamp(entity.time), entity.chrmId); return; } else if (msg.getTopic() == "s_msg") { isStraightMsg = true; entity = RongIMLib.RongIMClient.Protobuf.DownStreamMessage.decode(msg.getData()); var timestamp = RongIMLib.MessageUtil.int64ToTimestamp(entity.dataTime); RongIMLib.RongIMClient._storageProvider.setItem(this._client.userId, timestamp); RongIMLib.RongIMClient._memoryStore.lastReadTime.get(this._client.userId, timestamp); } else if (msg.getTopic() == "s_stat") { entity = RongIMLib.RongIMClient.Protobuf.GetUserStatusOutput.decode(msg.getData()); entity = RongIMLib.RongInnerTools.convertUserStatus(entity); RongIMLib.RongIMClient.userStatusObserver.notify({ key: entity.userId, entity: entity }); return; } else if (msg.getTopic() === 's_cmd') { this.handleChrmKVPullMsg(msg); return; } else { if (Bridge._client.sdkVer && Bridge._client.sdkVer == "1.0.0") { return; } entity = RongIMLib.RongIMClient.Protobuf.UpStreamMessage.decode(msg.getData()); var tmpTopic = msg.getTopic(); var tmpType = tmpTopic.substr(0, 2); if (tmpType == "pp") { entity.type = 1; } else if (tmpType == "pd") { entity.type = 2; } else if (tmpType == "pg") { entity.type = 3; } else if (tmpType == "ch") { entity.type = 4; } else if (tmpType == "pc") { entity.type = 5; } //复用字段,targetId 以此为准 entity.groupId = msg.getTargetId(); entity.fromUserId = this._client.userId; entity.dataTime = Date.parse(new Date().toString()); } if (!entity) { return; } } var isPullFinished = RongIMLib.RongIMClient._memoryStore.isPullFinished; // PullMsg 没有拉取完成,抛弃所有直发在线消息,抛弃的消息会在 PullMsg 中返回 if (!isPullFinished && !offlineMsg && isStraightMsg) { return; } //解析实体对象为消息对象。 message = RongIMLib.MessageUtil.messageParser(entity, this._onReceived, offlineMsg); var isRTCMessage = message.conversationType == 12; if (isRTCMessage) { RongIMLib.RongIMClient.RTCListener(message); RongIMLib.RongIMClient.RTCInnerListener(message); RongIMLib.RongIMClient.RTCSignalLisener(message); return; } var isRecall = (msg.getTopic && msg.getTopic() == "recallMsg"); if (isRecall) { var content = message.content; message.conversationType = content.conversationType; message.targetId = content.targetId; message.messageId = null; } if (pubAckItem) { message.messageUId = pubAckItem.getMessageUId(); message.sentTime = pubAckItem.getTimestamp(); RongIMLib.RongIMClient._storageProvider.setItem(this._client.userId, message.sentTime); } if (message === null) { return; } var isChatroomMessage = message.conversationType == RongIMLib.ConversationType.CHATROOM; if (!isChatroomMessage) { var msgTag = RongIMLib.RongIMClient.MessageParams[message.messageType].msgTag.getMessageTag(); if (msgTag >= 0) { RongIMLib.SyncTimeUtil.set(message); } var isSend = (message.messageDirection == RongIMLib.MessageDirection.SEND); if (isSend) { var storageProvider = RongIMLib.RongIMClient._storageProvider; var userId = RongIMLib.Bridge._client.userId; var lastSentTime = storageProvider.getItem('last_sentTime_' + userId) || 0; if (message.sentTime <= lastSentTime && !isSync) { return; } } } // 设置会话时间戳并且判断是否传递 message 发送消息未处理会话时间戳 // key:'converST_' + 当前用户 + conversationType + targetId // RongIMClient._storageProvider.setItem('converST_' + Bridge._client.userId + message.conversationType + message.targetId, message.sentTime); // var isPersited = (RongIMClient.MessageParams[message.messageType].msgTag.getMessageTag() > 0); var msgTag = RongIMLib.RongIMClient.MessageParams[message.messageType].msgTag.getMessageTag(); var isPersited = msgTag === 3 || msgTag === 2; if (isPersited) { con = RongIMLib.RongIMClient._dataAccessProvider.getConversation(message.conversationType, message.targetId, { onSuccess: function () { }, onError: function () { } }); if (!con) { con = RongIMLib.RongIMClient.getInstance().createConversation(message.conversationType, message.targetId, ""); } if (message.messageDirection == RongIMLib.MessageDirection.RECEIVE && (entity.status & 64) == 64) { var mentioneds = RongIMLib.RongIMClient._storageProvider.getItem("mentioneds_" + Bridge._client.userId + '_' + message.conversationType + '_' + message.targetId); var key = message.conversationType + '_' + message.targetId, info = {}; if (message.content && message.content.mentionedInfo) { info[key] = { uid: message.messageUId, time: message.sentTime, mentionedInfo: message.content.mentionedInfo }; RongIMLib.RongIMClient._storageProvider.setItem("mentioneds_" + Bridge._client.userId + '_' + message.conversationType + '_' + message.targetId, JSON.stringify(info)); mentioneds = JSON.stringify(info); } if (mentioneds) { var info = JSON.parse(mentioneds); con.mentionedMsg = info[key]; } } var isReceiver = message.messageDirection == RongIMLib.MessageDirection.RECEIVE; if (isReceiver && message.senderUserId != Bridge._client.userId) { con.unreadMessageCount = con.unreadMessageCount + 1; if (RongIMLib.RongUtil.supportLocalStorage()) { // var originUnreadCount = RongIMClient._storageProvider.getItem("cu" + Bridge._client.userId + con.conversationType + con.targetId); // 与本地存储会话合并 // var newUnreadCount = Number(originUnreadCount) + 1; // RongIMClient._storageProvider.setItem("cu" + Bridge._client.userId + con.conversationType + message.targetId, newUnreadCount); var newUnreadCount = RongIMLib.UnreadCountHandler.add(con.conversationType, message.targetId, 1, message.sentTime); con.unreadMessageCount = newUnreadCount; } } con.receivedTime = new Date().getTime(); con.receivedStatus = message.receivedStatus; con.senderUserId = message.sendUserId; con.notificationStatus = RongIMLib.ConversationNotificationStatus.DO_NOT_DISTURB; con.latestMessageId = message.messageId; con.latestMessage = message; con.sentTime = message.sentTime; RongIMLib.RongIMClient._dataAccessProvider.addConversation(con, { onSuccess: function (data) { if (!offlineMsg) { var Conversation_1 = RongIMLib.RongIMClient._dataAccessProvider.Conversation; var conversationList = RongIMLib.RongIMClient._memoryStore.conversationList; Conversation_1._notify(conversationList); } }, onError: function () { } }); } if (message.conversationType == RongIMLib.ConversationType.CUSTOMER_SERVICE && (message.messageType == "ChangeModeResponseMessage" || message.messageType == "SuspendMessage" || message.messageType == "HandShakeResponseMessage" || message.messageType == "TerminateMessage" || message.messageType == "CustomerStatusUpdateMessage" || message.messageType == "TextMessage" || message.messageType == "InformationNotificationMessage")) { if (!RongIMLib.RongIMClient._memoryStore.custStore["isInit"]) { return; } } if (message.conversationType == RongIMLib.ConversationType.CUSTOMER_SERVICE && message.messageType != "HandShakeResponseMessage") { if (!RongIMLib.RongIMClient._memoryStore.custStore[message.targetId]) { return; } if (message.messageType == "TerminateMessage") { if (RongIMLib.RongIMClient._memoryStore.custStore[message.targetId].sid != message.content.sid) { return; } } } if (message.messageType === RongIMLib.RongIMClient.MessageType["HandShakeResponseMessage"]) { var session = message.content.data; RongIMLib.RongIMClient._memoryStore.custStore[message.targetId] = session; if (session.serviceType == RongIMLib.CustomerType.ONLY_HUMAN || session.serviceType == RongIMLib.CustomerType.HUMAN_FIRST) { if (session.notAutoCha == "1") { RongIMLib.RongIMClient.getInstance().switchToHumanMode(message.targetId, { onSuccess: function () { }, onError: function () { } }); } } } var d = new Date(), m = d.getMonth() + 1, date = d.getFullYear() + '/' + (m.toString().length == 1 ? '0' + m : m) + '/' + d.getDate(); //new Date(date).getTime() - message.sentTime < 1 逻辑判断 超过 1 天未收的 ReadReceiptRequestMessage 离线消息自动忽略。 var dealtime = new Date(date).getTime() - message.sentTime < 0; if (RongIMLib.RongUtil.supportLocalStorage() && message.messageType === RongIMLib.RongIMClient.MessageType["ReadReceiptRequestMessage"] && dealtime && message.messageDirection == RongIMLib.MessageDirection.SEND) { var sentkey = Bridge._client.userId + message.content.messageUId + "SENT"; RongIMLib.RongIMClient._storageProvider.setItem(sentkey, JSON.stringify({ count: 0, dealtime: message.sentTime, userIds: {} })); } else if (RongIMLib.RongUtil.supportLocalStorage() && message.messageType === RongIMLib.RongIMClient.MessageType["ReadReceiptRequestMessage"] && dealtime) { var reckey = Bridge._client.userId + message.conversationType + message.targetId + 'RECEIVED', recData = JSON.parse(RongIMLib.RongIMClient._storageProvider.getItem(reckey)); if (recData) { if (message.senderUserId in recData) { if (recData[message.senderUserId].uIds && recData[message.senderUserId].uIds && recData[message.senderUserId].uIds.indexOf(message.content.messageUId) == -1) { recData[message.senderUserId].uIds.push(message.content.messageUId); recData[message.senderUserId].dealtime = message.sentTime; recData[message.senderUserId].isResponse = false; RongIMLib.RongIMClient._storageProvider.setItem(reckey, JSON.stringify(recData)); } else { return; } } else { var objSon = { uIds: [message.content.messageUId], dealtime: message.sentTime, isResponse: false }; recData[message.senderUserId] = objSon; RongIMLib.RongIMClient._storageProvider.setItem(reckey, JSON.stringify(recData)); } } else { var obj = {}; obj[message.senderUserId] = { uIds: [message.content.messageUId], dealtime: message.sentTime, isResponse: false }; RongIMLib.RongIMClient._storageProvider.setItem(reckey, JSON.stringify(obj)); } } if (RongIMLib.RongUtil.supportLocalStorage() && message.messageType === RongIMLib.RongIMClient.MessageType["ReadReceiptResponseMessage"] && dealtime) { var receiptResponseMsg = message.content, uIds = receiptResponseMsg.receiptMessageDic[Bridge._client.userId], sentkey = "", sentObj; message.receiptResponse || (message.receiptResponse = {}); if (uIds) { var cbuIds = []; for (var i = 0, len = uIds.length; i < len; i++) { sentkey = Bridge._client.userId + uIds[i] + "SENT"; sentObj = JSON.parse(RongIMLib.RongIMClient._storageProvider.getItem(sentkey)); if (sentObj && !(message.senderUserId in sentObj.userIds)) { cbuIds.push(uIds[i]); sentObj.count += 1; sentObj.userIds[message.senderUserId] = message.sentTime; message.receiptResponse[uIds[i]] = sentObj.count; RongIMLib.RongIMClient._storageProvider.setItem(sentkey, JSON.stringify(sentObj)); } } receiptResponseMsg.receiptMessageDic[Bridge._client.userId] = cbuIds; message.content = receiptResponseMsg; } } var that = this; if (RongIMLib.RongIMClient._voipProvider && ['AcceptMessage', 'RingingMessage', 'HungupMessage', 'InviteMessage', 'MediaModifyMessage', 'MemberModifyMessage'].indexOf(message.messageType) > -1) { setTimeout(function () { RongIMLib.RongIMClient._voipProvider.onReceived(message); }); } else { var count = leftCount || 0; var hasMore = !isPullFinished; that._onReceived(message, count, hasMore); } }; MessageHandler.prototype.handleMessage = function (msg) { if (!msg) { return; } switch (msg._name) { case "ConnAckMessage": Bridge._client.handler.connectCallback.process(msg.getStatus(), msg.getUserId(), msg.getTimestamp()); break; case "PublishMessage": if (!msg.getSyncMsg() && msg.getQos() != 0) { Bridge._client.channel.writeAndFlush(new RongIMLib.PubAckMessage(msg.getMessageId())); } // TODO && -> if (msg.getSyncMsg() && !RongIMLib.RongIMClient._memoryStore.depend.isPolling) { Bridge._client.handler.syncMsgMap[msg.getMessageId()] = msg; } else { //如果是PublishMessage就把该对象给onReceived方法执行处理 Bridge._client.handler.onReceived(msg); } break; case "QueryAckMessage": if (msg.getQos() != 0) { Bridge._client.channel.writeAndFlush(new RongIMLib.QueryConMessage(msg.getMessageId())); } var temp = Bridge._client.handler.map[msg.getMessageId()]; if (temp) { //执行回调操作 temp.Callback.process(msg.getStatus(), msg.getData(), msg.getDate(), temp.Message); delete Bridge._client.handler.map[msg.getMessageId()]; } break; case "PubAckMessage": var item = Bridge._client.handler.map[msg.getMessageId()]; if (item) { item.Callback.process(msg.getStatus() || 0, msg.getMessageUId(), msg.getTimestamp(), item.Message, msg.getMessageId()); delete Bridge._client.handler.map[msg.getMessageId()]; } else { var userId = RongIMLib.Bridge._client.userId; RongIMLib.RongIMClient._storageProvider.setItem('last_sentTime_' + userId, msg.timestamp); Bridge._client.handler.onReceived(Bridge._client.handler.syncMsgMap[msg.messageId], msg, null, null, true); delete Bridge._client.handler.syncMsgMap[msg.getMessageId()]; } break; case "PingRespMessage": if (RongIMLib.RongIMClient._memoryStore.isFirstPingMsg) { RongIMLib.RongIMClient._memoryStore.isFirstPingMsg = false; } else { Bridge._client.pauseTimer(); } break; case "DisconnectMessage": Bridge._client.channel.disconnect(msg.getStatus()); break; default: } }; return MessageHandler; })(); RongIMLib.MessageHandler = MessageHandler; })(RongIMLib || (RongIMLib = {})); var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; /// var RongIMLib; (function (RongIMLib) { var MessageCallback = (function () { function MessageCallback(error) { this.timeout = null; this.onError = null; if (error && typeof error == "number") { this.timeoutMillis = error; } else { this.timeoutMillis = 30000; this.onError = error; } } MessageCallback.prototype.resumeTimer = function () { var me = this; if (this.timeoutMillis > 0 && !this.timeout) { this.timeout = setTimeout(function () { me.readTimeOut(true); }, this.timeoutMillis); } }; MessageCallback.prototype.pauseTimer = function () { if (this.timeout) { clearTimeout(this.timeout); this.timeout = null; } }; MessageCallback.prototype.readTimeOut = function (isTimeout) { if (isTimeout && this.onError) { this.onError(RongIMLib.ErrorCode.TIMEOUT); } else { this.pauseTimer(); } }; return MessageCallback; })(); RongIMLib.MessageCallback = MessageCallback; var CallbackMapping = (function () { function CallbackMapping() { this.publicServiceList = []; } CallbackMapping.getInstance = function () { return new CallbackMapping(); }; CallbackMapping.prototype.pottingProfile = function (item) { var temp; this.profile = new RongIMLib.PublicServiceProfile(); temp = JSON.parse(item.extra); this.profile.isGlobal = temp.isGlobal; this.profile.introduction = temp.introduction; this.profile.menu = temp.menu; this.profile.hasFollowed = temp.follow; this.profile.publicServiceId = item.mpid; this.profile.name = item.name; this.profile.portraitUri = item.portraitUrl; this.profile.conversationType = item.type == "mc" ? RongIMLib.ConversationType.APP_PUBLIC_SERVICE : RongIMLib.ConversationType.PUBLIC_SERVICE; this.publicServiceList.push(this.profile); }; CallbackMapping.prototype.mapping = function (entity, tag) { switch (tag) { case "GetUserInfoOutput": var userInfo = new RongIMLib.UserInfo(entity.userId, entity.userName, entity.userPortrait); return userInfo; case "GetQNupTokenOutput": return { deadline: RongIMLib.MessageUtil.int64ToTimestamp(entity.deadline), token: entity.token }; case "GetQNdownloadUrlOutput": return { downloadUrl: entity.downloadUrl }; case "CreateDiscussionOutput": return entity.id; case "ChannelInfoOutput": var disInfo = new RongIMLib.Discussion(); disInfo.creatorId = entity.adminUserId; disInfo.id = entity.channelId; disInfo.memberIdList = entity.firstTenUserIds; disInfo.name = entity.channelName; disInfo.isOpen = entity.openStatus; return disInfo; case "GroupHashOutput": return entity.result; case "QueryBlackListOutput": return entity.userIds; case "SearchMpOutput": case "PullMpOutput": if (entity.info) { var self = this; Array.forEach(entity.info, function (item) { setTimeout(function () { self.pottingProfile(item); }, 100); }); } return this.publicServiceList; default: return entity; } }; return CallbackMapping; })(); RongIMLib.CallbackMapping = CallbackMapping; var PublishCallback = (function (_super) { __extends(PublishCallback, _super); function PublishCallback(_cb, _timeout) { _super.call(this, _timeout); this._cb = _cb; this._timeout = _timeout; } PublishCallback.prototype.process = function (_status, messageUId, timestamp, _msg, messageId) { this.readTimeOut(); if (_status == 0) { if (_msg) { _msg.setSentStatus = _status; } var isPullFinished = RongIMLib.RongIMClient._memoryStore.isPullFinished; if (isPullFinished) { var userId = RongIMLib.Bridge._client.userId; var stroageProvider = RongIMLib.RongIMClient._storageProvider; stroageProvider.setItem('last_sentTime_' + userId, timestamp); RongIMLib.SyncTimeUtil.set({ messageDirection: RongIMLib.MessageDirection.SEND, sentTime: timestamp }); } this._cb({ messageUId: messageUId, timestamp: timestamp, messageId: messageId }); } else { this._timeout(_status, { messageUId: messageUId, sentTime: timestamp }); } }; PublishCallback.prototype.readTimeOut = function (x) { MessageCallback.prototype.readTimeOut.call(this, x); }; return PublishCallback; })(MessageCallback); RongIMLib.PublishCallback = PublishCallback; var QueryCallback = (function (_super) { __extends(QueryCallback, _super); function QueryCallback(_cb, _timeout) { _super.call(this, _timeout); this._cb = _cb; this._timeout = _timeout; } QueryCallback.prototype.process = function (status, data, serverTime, pbtype) { this.readTimeOut(); if (pbtype && data && status == 0) { try { data = CallbackMapping.getInstance().mapping(RongIMLib.RongIMClient.Protobuf[pbtype].decode(data), pbtype); } catch (e) { this._timeout(RongIMLib.ErrorCode.UNKNOWN); return; } if ("GetUserInfoOutput" == pbtype) { //pb类型为GetUserInfoOutput的话就把data放入userinfo缓存队列 RongIMLib.Client.userInfoMapping[data.userId] = data; } this._cb(data); } else { status > 0 ? this._timeout(status) : this._cb(status); } }; QueryCallback.prototype.readTimeOut = function (x) { MessageCallback.prototype.readTimeOut.call(this, x); }; return QueryCallback; })(MessageCallback); RongIMLib.QueryCallback = QueryCallback; var ConnectAck = (function (_super) { __extends(ConnectAck, _super); function ConnectAck(_cb, _timeout, client) { _super.call(this, _timeout); this._client = client; this._cb = _cb; this._timeout = _timeout; } ConnectAck.prototype.process = function (status, userId, timestamp) { this.readTimeOut(); if (status == 0) { this._client.userId = userId; var self = this; if (!RongIMLib.RongIMClient._memoryStore.depend.isPolling && RongIMLib.RongIMClient._memoryStore.isFirstPingMsg) { RongIMLib.Bridge._client.checkSocket({ onSuccess: function () { if (!RongIMLib.RongIMClient.isNotPullMsg) { self._client.syncTime(undefined, undefined, undefined, true); } }, onError: function () { RongIMLib.RongIMClient._memoryStore.isFirstPingMsg = false; RongIMLib.RongIMClient.getInstance().disconnect(); RongIMLib.RongIMClient.connect(RongIMLib.RongIMClient._memoryStore.token, RongIMLib.RongIMClient._memoryStore.callback); } }); } else { if (!RongIMLib.RongIMClient.isNotPullMsg) { self._client.syncTime(undefined, undefined, undefined, true); } } RongIMLib.Bridge._client.channel.socket.fire("StatusChanged", 0); if (this._client.reconnectObj.onSuccess) { this._client.reconnectObj.onSuccess(userId); delete this._client.reconnectObj.onSuccess; } else { var me = this; me._cb(userId); // setTimeout(function() { me._cb(userId); }, 500); var depend = RongIMLib.RongIMClient._memoryStore.depend; var maxConversationCount = depend.maxConversationCount; var isNotifyConversationList = depend.isNotifyConversationList; isNotifyConversationList && RongIMLib.RongIMClient._dataAccessProvider.getRemoteConversationList({ onSuccess: function (conversationList) { var Conversation = RongIMLib.RongIMClient._dataAccessProvider.Conversation; Conversation._notify(conversationList); }, onError: function (code) { console.log('内部获取列表失败: %d', code); } }, null, maxConversationCount); } RongIMLib.RongIMClient._memoryStore.connectAckTime = timestamp; if (!(new Date().getTime() - timestamp)) { RongIMLib.RongIMClient._memoryStore.deltaTime = 0; } else { RongIMLib.RongIMClient._memoryStore.deltaTime = new Date().getTime() - timestamp; } } else if (status == 6) { RongIMLib.RongIMClient.getInstance().disconnect(); //重定向 连错 CMP var me = this; var _client = me._client; var appId = _client.appId, token = _client.token; new RongIMLib.Navigation().requestNavi(token, appId, function () { _client.clearHeartbeat(); var newClient = new RongIMLib.Client(token, appId); RongIMLib.Bridge._client = newClient; newClient.__init(function () { RongIMLib.Transportations._TransportType == "websocket" && newClient.keepLive(); }); }, me._timeout, false); } else { RongIMLib.Bridge._client.channel.socket.socket._status = status; if (this._client.reconnectObj.onError) { this._client.reconnectObj.onError(status); delete this._client.reconnectObj.onError; } else { this._timeout(status); } } }; ConnectAck.prototype.readTimeOut = function (x) { MessageCallback.prototype.readTimeOut.call(this, x); }; return ConnectAck; })(MessageCallback); RongIMLib.ConnectAck = ConnectAck; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var Navigation = (function () { function Navigation() { } Navigation.clear = function () { var storage = RongIMLib.RongIMClient._storageProvider; storage.removeItem('rc_uid'); storage.removeItem('serverIndex'); storage.removeItem('rongSDK'); }; Navigation.prototype.getNaviSuccess = function (result) { var storage = RongIMLib.RongIMClient._storageProvider; storage.setItem('fullnavi', JSON.stringify(result)); var server = result.server; if (server) { server += ','; } var backupServer = result.backupServer || ''; var tpl = '{server}{backupServer}'; var servers = RongIMLib.RongUtil.tplEngine(tpl, { server: server, backupServer: backupServer }); servers = servers.split(','); storage.setItem('servers', JSON.stringify(servers)); var token = RongIMLib.RongIMClient._memoryStore.token; var uid = RongIMLib.InnerUtil.getUId(token); storage.setItem('rc_uid', uid); var userId = result.userId; storage.setItem('current_user', userId); if (result.voipCallInfo) { var callInfo = JSON.parse(result.voipCallInfo); RongIMLib.RongIMClient._memoryStore.voipStategy = callInfo.strategy; storage.setItem("voipStrategy", callInfo.strategy); } //替换本地存储的导航信息 var openMp = result.openMp; storage.setItem('openMp' + uid, openMp); RongIMLib.RongIMClient._memoryStore.depend.openMp = openMp; }; ; Navigation.prototype.connect = function (appId, token, callback) { var oldAppId = RongIMLib.RongIMClient._storageProvider.getItem("appId"); //如果appid和本地存储的不一样,清空所有本地存储数据 if (oldAppId && oldAppId != appId) { RongIMLib.RongIMClient._storageProvider.clearItem(); RongIMLib.RongIMClient._storageProvider.setItem("appId", appId); } if (!oldAppId) { RongIMLib.RongIMClient._storageProvider.setItem("appId", appId); } var client = new RongIMLib.Client(token, appId); this.requestNavi(token, appId, function () { client.connect(callback); }, callback.onError, true); return client; }; Navigation.prototype.requestNavi = function (token, appId, _onsuccess, _onerror, unignore) { if (unignore) { //根据token生成MD5截取8-16下标的数据与本地存储的导航信息进行比对 //如果信息和上次的通道类型都一样,不执行navi请求,用本地存储的导航信息连接服务器 var uId = md5(token).slice(8, 16); var storage = RongIMLib.RongIMClient._storageProvider; var transportType = storage.getItem("rongSDK"); var isSameType = (RongIMLib.Transportations._TransportType == transportType); var _old = storage.getItem('rc_uid'); var isSameUser = (_old == uId); var servers = storage.getItem('servers'); var hasServers = (typeof servers == 'string'); if (isSameUser && isSameType && hasServers && RongIMLib.RongUtil.hasValidWsUrl(servers)) { RongIMLib.RongIMClient._memoryStore.voipStategy = storage.getItem("voipStrategy"); var openMp = storage.getItem('openMp' + uId); RongIMLib.RongIMClient._memoryStore.depend.openMp = openMp; _onsuccess(); return; } } Navigation.clear(); RongIMLib.RongIMClient.invalidWsUrls = []; var context = this; var StatusEvent = RongIMLib.Channel._ConnectionStatusListener; var depend = RongIMLib.RongIMClient._memoryStore.depend; var navigaters = depend.navigaters; var naviTimeout = depend.naviTimeout; var maxNaviRetry = depend.maxNaviRetry; var isNaviJSONP = depend.isNaviJSONP; var isSupportRequestHeaders = RongIMLib.RongUtil.isSupportRequestHeaders(); var isRequestJSONP = !isSupportRequestHeaders || isNaviJSONP; var requestFunc = isRequestJSONP ? context.requestJSONP : context.request; var timer = new RongIMLib.Timer({ timeout: naviTimeout }); var internalRetry = 1; var isRange = function () { return internalRetry >= maxNaviRetry; }; var indexTools = new RongIMLib.IndexTools({ items: navigaters, onwheel: function () { internalRetry += 1; } }); var consume = function () { if (isRange()) { _onerror(RongIMLib.ConnectionStatus.RESPONSE_NAVI_ERROR); return; } var index = indexTools.get(); var navi = navigaters[index]; indexTools.add(); var success = function (result) { timer.pause(); StatusEvent.onChanged(RongIMLib.ConnectionStatus.RESPONSE_NAVI); var code = result.code; if (RongIMLib.RongUtil.isEqual(code, 200)) { context.getNaviSuccess(result); _onsuccess(); } if (RongIMLib.RongUtil.isEqual(code, 401)) { _onerror(RongIMLib.ConnectionState.TOKEN_INCORRECT); } if (RongIMLib.RongUtil.isEqual(code, 403)) { StatusEvent.onChanged(RongIMLib.ConnectionStatus.APPKEY_IS_FAKE); } }; var error = function (status) { if (RongIMLib.RongUtil.isEqual(status, 0)) { return; } timer.pause(); StatusEvent.onChanged(RongIMLib.ConnectionStatus.RESPONSE_NAVI_ERROR); consume(); }; StatusEvent.onChanged(RongIMLib.ConnectionStatus.REQUEST_NAVI); var xhr = requestFunc.call(context, navi, appId, token, success, error); timer.resume(function () { StatusEvent.onChanged(RongIMLib.ConnectionStatus.RESPONSE_NAVI_TIMEOUT); xhr.abort(); consume(); }); }; consume(); }; Navigation.prototype.getPath = function (navi, appId, token, callbackName) { var depend = RongIMLib.RongIMClient._memoryStore.depend; var path = (depend.isPolling ? 'cometnavi' : 'navi'); token = encodeURIComponent(token); var sdkver = RongIMLib.RongIMClient.sdkver; var random = RongIMLib.RongUtil.getTimestamp(); var tpl = '{navi}/{path}.js?appId={appId}&token={token}&callBack={callback}&v={sdkver}&r={random}'; var url = RongIMLib.RongUtil.tplEngine(tpl, { navi: navi, path: path, appId: appId, token: token, sdkver: sdkver, random: random, callback: callbackName }); return url; }; Navigation.prototype.request = function (navi, appId, token, success, error) { var url = this.getPath(navi, appId, token, 'getServerEndpoint'); return RongIMLib.RongUtil.request({ url: url, success: function (result) { result = result.replace('getServerEndpoint(', '').replace(');', ''); // 兼容私有云无分号 var lastIndex = result.lastIndexOf(')'); var maxIndex = result.length - 1; if (lastIndex == maxIndex) { result = result.substr(0, lastIndex); } success(JSON.parse(result)); }, error: function (status, result) { if (status == 401 || status == 403) { success(JSON.parse(result)); } else { error(status); } } }); }; Navigation.prototype.requestJSONP = function (navi, appId, token, success, error) { var callbackName = 'getServerEndpoint'; window.getServerEndpoint = function (result) { var code = result.code; if (code !== 200) { return error(RongIMLib.ConnectionState.TOKEN_INCORRECT); } success(result); }; var url = this.getPath(navi, appId, token, callbackName); var xss = document.createElement('script'); xss.src = url; document.body.appendChild(xss); xss.onerror = function () { error(RongIMLib.ConnectionState.TOKEN_INCORRECT); }; }; Navigation.Endpoint = new Object; return Navigation; })(); RongIMLib.Navigation = Navigation; })(RongIMLib || (RongIMLib = {})); // TODO: 统一变量、方法等命名规范 var RongIMLib; (function (RongIMLib) { /** * 消息基类 */ var BaseMessage = (function () { function BaseMessage(arg) { this._name = "BaseMessage"; this.lengthSize = 0; if (arg instanceof RongIMLib.Header) { this._header = arg; } else { this._header = new RongIMLib.Header(arg, false, RongIMLib.Qos.AT_MOST_ONCE, false); } } BaseMessage.prototype.read = function (In, length) { this.readMessage(In, length); }; BaseMessage.prototype.write = function (Out) { var binaryHelper = new RongIMLib.BinaryHelper(); var out = binaryHelper.convertStream(Out); this._headerCode = this.getHeaderFlag(); out.write(this._headerCode); this.writeMessage(out); return out; }; BaseMessage.prototype.getHeaderFlag = function () { return this._header.encode(); }; BaseMessage.prototype.getLengthSize = function () { return this.lengthSize; }; BaseMessage.prototype.toBytes = function () { return this.write([]).getBytesArray(); }; BaseMessage.prototype.isRetained = function () { return this._header.retain; }; BaseMessage.prototype.setRetained = function (retain) { this._header.retain = retain; }; BaseMessage.prototype.setQos = function (qos) { this._header.qos = Object.prototype.toString.call(qos) == "[object Object]" ? qos : RongIMLib.Qos[qos]; }; BaseMessage.prototype.setDup = function (dup) { this._header.dup = dup; }; BaseMessage.prototype.isDup = function () { return this._header.dup; }; BaseMessage.prototype.getType = function () { return this._header.type; }; BaseMessage.prototype.getQos = function () { return this._header.qos; }; BaseMessage.prototype.messageLength = function () { return 0; }; BaseMessage.prototype.writeMessage = function (out) { }; BaseMessage.prototype.readMessage = function (In, length) { }; BaseMessage.prototype.init = function (args) { var valName, nana, me = this; for (nana in args) { if (!args.hasOwnProperty(nana)) { continue; } valName = nana.replace(/^\w/, function (x) { var tt = x.charCodeAt(0); return "set" + (tt >= 0x61 ? String.fromCharCode(tt & ~32) : x); }); if (valName in me) { if (nana == "status") { me[valName](disconnectStatus[args[nana]] ? disconnectStatus[args[nana]] : args[nana]); } else { me[valName](args[nana]); } } } }; return BaseMessage; })(); RongIMLib.BaseMessage = BaseMessage; /** *连接消息类型 */ var ConnectMessage = (function (_super) { __extends(ConnectMessage, _super); function ConnectMessage(header) { _super.call(this, arguments.length == 0 || arguments.length == 3 ? RongIMLib.Type.CONNECT : arguments[0]); this._name = "ConnectMessage"; this.CONNECT_HEADER_SIZE = 12; this.protocolId = "RCloud"; this.binaryHelper = new RongIMLib.BinaryHelper(); this.protocolVersion = 3; switch (arguments.length) { case 0: case 1: case 3: if (!arguments[0] || arguments[0].length > 64) { throw new Error("ConnectMessage:Client Id cannot be null and must be at most 64 characters long: " + arguments[0]); } this.clientId = arguments[0]; this.cleanSession = arguments[1]; this.keepAlive = arguments[2]; break; } } ConnectMessage.prototype.messageLength = function () { var payloadSize = this.binaryHelper.toMQttString(this.clientId).length; payloadSize += this.binaryHelper.toMQttString(this.willTopic).length; payloadSize += this.binaryHelper.toMQttString(this.will).length; payloadSize += this.binaryHelper.toMQttString(this.appId).length; payloadSize += this.binaryHelper.toMQttString(this.token).length; return payloadSize + this.CONNECT_HEADER_SIZE; }; ConnectMessage.prototype.readMessage = function (stream) { this.protocolId = stream.readUTF(); this.protocolVersion = stream.readByte(); var cFlags = stream.readByte(); this.hasAppId = (cFlags & 128) > 0; this.hasToken = (cFlags & 64) > 0; this.retainWill = (cFlags & 32) > 0; this.willQos = cFlags >> 3 & 3; this.hasWill = (cFlags & 4) > 0; this.cleanSession = (cFlags & 32) > 0; this.keepAlive = stream.read() * 256 + stream.read(); this.clientId = stream.readUTF(); if (this.hasWill) { this.willTopic = stream.readUTF(); this.will = stream.readUTF(); } if (this.hasAppId) { try { this.appId = stream.readUTF(); } catch (ex) { throw new Error(ex); } } if (this.hasToken) { try { this.token = stream.readUTF(); } catch (ex) { throw new Error(ex); } } return stream; }; ConnectMessage.prototype.writeMessage = function (out) { var stream = this.binaryHelper.convertStream(out); stream.writeUTF(this.protocolId); stream.write(this.protocolVersion); var flags = this.cleanSession ? 2 : 0; flags |= this.hasWill ? 4 : 0; flags |= this.willQos ? this.willQos >> 3 : 0; flags |= this.retainWill ? 32 : 0; flags |= this.hasToken ? 64 : 0; flags |= this.hasAppId ? 128 : 0; stream.write(flags); stream.writeChar(this.keepAlive); stream.writeUTF(this.clientId); if (this.hasWill) { stream.writeUTF(this.willTopic); stream.writeUTF(this.will); } if (this.hasAppId) { stream.writeUTF(this.appId); } if (this.hasToken) { stream.writeUTF(this.token); } return stream; }; return ConnectMessage; })(BaseMessage); RongIMLib.ConnectMessage = ConnectMessage; /** *连接应答类型 */ var ConnAckMessage = (function (_super) { __extends(ConnAckMessage, _super); function ConnAckMessage(header) { _super.call(this, arguments.length == 0 ? RongIMLib.Type.CONNACK : arguments.length == 1 ? arguments[0] instanceof RongIMLib.Header ? arguments[0] : RongIMLib.Type.CONNACK : null); this._name = "ConnAckMessage"; this.MESSAGE_LENGTH = 2; this.binaryHelper = new RongIMLib.BinaryHelper(); var me = this; switch (arguments.length) { case 0: case 1: if (!(arguments[0] instanceof RongIMLib.Header)) { if (arguments[0] in RongIMLib.ConnectionState) { if (arguments[0] == null) { throw new Error("ConnAckMessage:The status of ConnAskMessage can't be null"); } me.setStatus(arguments[0]); } } break; } } ; ConnAckMessage.prototype.messageLength = function () { var length = this.MESSAGE_LENGTH; if (this.userId) { length += this.binaryHelper.toMQttString(this.userId).length; } return length; }; ; ConnAckMessage.prototype.readMessage = function (_in, msglength) { _in.read(); var result = +_in.read(); if (result >= 0 && result <= 12) { this.setStatus(result); } else { throw new Error("Unsupported CONNACK code:" + result); } if (msglength > this.MESSAGE_LENGTH) { this.setUserId(_in.readUTF()); var sessionId = _in.readUTF(); var timestamp = _in.readLong(); this.setTimestamp(timestamp); } }; ; ConnAckMessage.prototype.writeMessage = function (out) { var stream = this.binaryHelper.convertStream(out); stream.write(128); switch (+status) { case 0: case 1: case 2: case 5: case 6: stream.write(+status); break; case 3: case 4: stream.write(3); break; default: throw new Error("Unsupported CONNACK code:" + status); } if (this.userId) { stream.writeUTF(this.userId); } return stream; }; ; ConnAckMessage.prototype.setStatus = function (x) { this.status = x; }; ; ConnAckMessage.prototype.setUserId = function (_userId) { this.userId = _userId; }; ; ConnAckMessage.prototype.getStatus = function () { return this.status; }; ; ConnAckMessage.prototype.getUserId = function () { return this.userId; }; ; ConnAckMessage.prototype.setTimestamp = function (x) { this.timestrap = x; }; ; ConnAckMessage.prototype.getTimestamp = function () { return this.timestrap; }; return ConnAckMessage; })(BaseMessage); RongIMLib.ConnAckMessage = ConnAckMessage; /** *断开消息类型 */ var DisconnectMessage = (function (_super) { __extends(DisconnectMessage, _super); function DisconnectMessage(header) { _super.call(this, header instanceof RongIMLib.Header ? header : RongIMLib.Type.DISCONNECT); this._name = "DisconnectMessage"; this.MESSAGE_LENGTH = 2; this.binaryHelper = new RongIMLib.BinaryHelper(); if (!(header instanceof RongIMLib.Header)) { if (header in RongIMLib.ConnectionStatus) { this.status = header; } } } DisconnectMessage.prototype.messageLength = function () { return this.MESSAGE_LENGTH; }; DisconnectMessage.prototype.readMessage = function (_in) { _in.read(); var result = +_in.read(); if (result >= 0 && result <= 5) { this.setStatus(disconnectStatus[result] ? disconnectStatus[result] : result); } else { throw new Error("Unsupported CONNACK code:" + result); } }; DisconnectMessage.prototype.writeMessage = function (Out) { var out = this.binaryHelper.convertStream(Out); out.write(0); if (+status >= 1 && +status <= 3) { out.write((+status) - 1); } else { throw new Error("Unsupported CONNACK code:" + status); } }; DisconnectMessage.prototype.setStatus = function (x) { this.status = x; }; ; DisconnectMessage.prototype.getStatus = function () { return this.status; }; ; return DisconnectMessage; })(BaseMessage); RongIMLib.DisconnectMessage = DisconnectMessage; /** *请求消息信令 */ var PingReqMessage = (function (_super) { __extends(PingReqMessage, _super); function PingReqMessage(header) { _super.call(this, (header && header instanceof RongIMLib.Header) ? header : RongIMLib.Type.PINGREQ); this._name = "PingReqMessage"; } return PingReqMessage; })(BaseMessage); RongIMLib.PingReqMessage = PingReqMessage; /** *响应消息信令 */ var PingRespMessage = (function (_super) { __extends(PingRespMessage, _super); function PingRespMessage(header) { _super.call(this, (header && header instanceof RongIMLib.Header) ? header : RongIMLib.Type.PINGRESP); this._name = "PingRespMessage"; } return PingRespMessage; })(BaseMessage); RongIMLib.PingRespMessage = PingRespMessage; /** *封装MesssageId */ var RetryableMessage = (function (_super) { __extends(RetryableMessage, _super); function RetryableMessage(argu) { _super.call(this, argu); this._name = "RetryableMessage"; this.binaryHelper = new RongIMLib.BinaryHelper(); } RetryableMessage.prototype.messageLength = function () { return 2; }; RetryableMessage.prototype.writeMessage = function (Out) { var out = this.binaryHelper.convertStream(Out), Id = this.getMessageId(), lsb = Id & 255, msb = (Id & 65280) >> 8; out.write(msb); out.write(lsb); return out; }; RetryableMessage.prototype.readMessage = function (_in, msgLength) { var msgId = _in.read() * 256 + _in.read(); this.setMessageId(parseInt(msgId, 10)); }; RetryableMessage.prototype.setMessageId = function (_messageId) { this.messageId = _messageId; }; RetryableMessage.prototype.getMessageId = function () { return this.messageId; }; return RetryableMessage; })(BaseMessage); RongIMLib.RetryableMessage = RetryableMessage; /** *发送消息应答(双向) *qos为1必须给出应答(所有消息类型一样) */ var PubAckMessage = (function (_super) { __extends(PubAckMessage, _super); function PubAckMessage(header) { _super.call(this, (header instanceof RongIMLib.Header) ? header : RongIMLib.Type.PUBACK); this.msgLen = 2; this.date = 0; this.millisecond = 0; this.timestamp = 0; this.binaryHelper = new RongIMLib.BinaryHelper(); this._name = "PubAckMessage"; if (!(header instanceof RongIMLib.Header)) { _super.prototype.setMessageId.call(this, header); } } PubAckMessage.prototype.messageLength = function () { return this.msgLen; }; PubAckMessage.prototype.writeMessage = function (Out) { var out = this.binaryHelper.convertStream(Out); RetryableMessage.prototype.writeMessage.call(this, out); }; PubAckMessage.prototype.readMessage = function (_in, msgLength) { RetryableMessage.prototype.readMessage.call(this, _in); this.date = _in.readInt(); this.status = _in.read() * 256 + _in.read(); this.millisecond = _in.read() * 256 + _in.read(); this.timestamp = this.date * 1000 + this.millisecond; this.messageUId = _in.readUTF(); }; PubAckMessage.prototype.setStatus = function (x) { this.status = x; }; PubAckMessage.prototype.setTimestamp = function (timestamp) { this.timestamp = timestamp; }; PubAckMessage.prototype.setMessageUId = function (messageUId) { this.messageUId = messageUId; }; PubAckMessage.prototype.getStatus = function () { return this.status; }; PubAckMessage.prototype.getDate = function () { return this.date; }; PubAckMessage.prototype.getTimestamp = function () { return this.timestamp; }; PubAckMessage.prototype.getMessageUId = function () { return this.messageUId; }; return PubAckMessage; })(RetryableMessage); RongIMLib.PubAckMessage = PubAckMessage; /** *发布消息 */ var PublishMessage = (function (_super) { __extends(PublishMessage, _super); function PublishMessage(header, two, three) { _super.call(this, (arguments.length == 1 && header instanceof RongIMLib.Header) ? header : arguments.length == 3 ? RongIMLib.Type.PUBLISH : 0); this._name = "PublishMessage"; this.binaryHelper = new RongIMLib.BinaryHelper(); this.syncMsg = false; if (arguments.length == 3) { this.topic = header; this.targetId = three; this.data = typeof two == "string" ? this.binaryHelper.toMQttString(two) : two; } } PublishMessage.prototype.messageLength = function () { var length = 10; length += this.binaryHelper.toMQttString(this.topic).length; length += this.binaryHelper.toMQttString(this.targetId).length; length += this.data.length; return length; }; PublishMessage.prototype.writeMessage = function (Out) { var out = this.binaryHelper.convertStream(Out); out.writeUTF(this.topic); out.writeUTF(this.targetId); RetryableMessage.prototype.writeMessage.apply(this, arguments); out.write(this.data); }; ; PublishMessage.prototype.readMessage = function (_in, msgLength) { var pos = 6; this.date = _in.readInt(); this.topic = _in.readUTF(); pos += this.binaryHelper.toMQttString(this.topic).length; this.targetId = _in.readUTF(); pos += this.binaryHelper.toMQttString(this.targetId).length; RetryableMessage.prototype.readMessage.apply(this, arguments); this.data = new Array(msgLength - pos); this.data = _in.read(this.data); }; ; PublishMessage.prototype.setTopic = function (x) { this.topic = x; }; PublishMessage.prototype.setData = function (x) { this.data = x; }; PublishMessage.prototype.setTargetId = function (x) { this.targetId = x; }; PublishMessage.prototype.setDate = function (x) { this.date = x; }; PublishMessage.prototype.setSyncMsg = function (x) { this.syncMsg = x; }; //是否是其他端同步过来的消息 PublishMessage.prototype.getSyncMsg = function () { return this.syncMsg; }; PublishMessage.prototype.getTopic = function () { return this.topic; }; PublishMessage.prototype.getData = function () { return this.data; }; PublishMessage.prototype.getTargetId = function () { return this.targetId; }; PublishMessage.prototype.getDate = function () { return this.date; }; return PublishMessage; })(RetryableMessage); RongIMLib.PublishMessage = PublishMessage; /** *请求查询 */ var QueryMessage = (function (_super) { __extends(QueryMessage, _super); function QueryMessage(header, two, three) { _super.call(this, header instanceof RongIMLib.Header ? header : arguments.length == 3 ? RongIMLib.Type.QUERY : null); this.binaryHelper = new RongIMLib.BinaryHelper(); this._name = "QueryMessage"; if (arguments.length == 3) { this.data = typeof two == "string" ? this.binaryHelper.toMQttString(two) : two; this.topic = header; this.targetId = three; } } QueryMessage.prototype.messageLength = function () { var length = 0; length += this.binaryHelper.toMQttString(this.topic).length; length += this.binaryHelper.toMQttString(this.targetId).length; length += 2; length += this.data.length; return length; }; QueryMessage.prototype.writeMessage = function (Out) { var out = this.binaryHelper.convertStream(Out); out.writeUTF(this.topic); out.writeUTF(this.targetId); RetryableMessage.prototype.writeMessage.call(this, out); out.write(this.data); }; QueryMessage.prototype.readMessage = function (_in, msgLength) { var pos = 0; this.topic = _in.readUTF(); this.targetId = _in.readUTF(); pos += this.binaryHelper.toMQttString(this.topic).length; pos += this.binaryHelper.toMQttString(this.targetId).length; this.readMessage.apply(this, arguments); pos += 2; this.data = new Array(msgLength - pos); _in.read(this.data); }; QueryMessage.prototype.setTopic = function (x) { this.topic = x; }; QueryMessage.prototype.setData = function (x) { this.data = x; }; QueryMessage.prototype.setTargetId = function (x) { this.targetId = x; }; QueryMessage.prototype.getTopic = function () { return this.topic; }; QueryMessage.prototype.getData = function () { return this.data; }; QueryMessage.prototype.getTargetId = function () { return this.targetId; }; return QueryMessage; })(RetryableMessage); RongIMLib.QueryMessage = QueryMessage; /** *请求查询确认 */ var QueryConMessage = (function (_super) { __extends(QueryConMessage, _super); function QueryConMessage(messageId) { _super.call(this, (messageId instanceof RongIMLib.Header) ? messageId : RongIMLib.Type.QUERYCON); this._name = "QueryConMessage"; if (!(messageId instanceof RongIMLib.Header)) { _super.prototype.setMessageId.call(this, messageId); } } return QueryConMessage; })(RetryableMessage); RongIMLib.QueryConMessage = QueryConMessage; /** *请求查询应答 */ var QueryAckMessage = (function (_super) { __extends(QueryAckMessage, _super); function QueryAckMessage(header) { _super.call(this, header); this._name = "QueryAckMessage"; this.binaryHelper = new RongIMLib.BinaryHelper(); } QueryAckMessage.prototype.readMessage = function (In, msgLength) { RetryableMessage.prototype.readMessage.call(this, In); this.date = In.readInt(); this.setStatus(In.read() * 256 + In.read()); if (msgLength > 0) { this.data = new Array(msgLength - 8); this.data = In.read(this.data); } }; QueryAckMessage.prototype.getData = function () { return this.data; }; QueryAckMessage.prototype.getStatus = function () { return this.status; }; QueryAckMessage.prototype.getDate = function () { return this.date; }; QueryAckMessage.prototype.setDate = function (x) { this.date = x; }; QueryAckMessage.prototype.setStatus = function (x) { this.status = x; }; QueryAckMessage.prototype.setData = function (x) { this.data = x; }; return QueryAckMessage; })(RetryableMessage); RongIMLib.QueryAckMessage = QueryAckMessage; })(RongIMLib || (RongIMLib = {})); /// var RongIMLib; (function (RongIMLib) { /** * 把消息对象写入流中 * 发送消息时用到 */ var MessageOutputStream = (function () { function MessageOutputStream(_out) { var binaryHelper = new RongIMLib.BinaryHelper(); this.out = binaryHelper.convertStream(_out); } MessageOutputStream.prototype.writeMessage = function (msg) { if (msg instanceof RongIMLib.BaseMessage) { msg.write(this.out); } }; return MessageOutputStream; })(); RongIMLib.MessageOutputStream = MessageOutputStream; /** * 流转换为消息对象 * 服务器返回消息时用到 */ var MessageInputStream = (function () { function MessageInputStream(In, isPolling) { if (!isPolling) { var _in = new RongIMLib.BinaryHelper().convertStream(In); this.flags = _in.readByte(); this._in = _in; } else { this.flags = In["headerCode"]; } this.header = new RongIMLib.Header(this.flags); this.isPolling = isPolling; this.In = In; } MessageInputStream.prototype.readMessage = function () { switch (this.header.getType()) { case 1: this.msg = new RongIMLib.ConnectMessage(this.header); break; case 2: this.msg = new RongIMLib.ConnAckMessage(this.header); break; case 3: this.msg = new RongIMLib.PublishMessage(this.header); this.msg.setSyncMsg(this.header.getSyncMsg()); break; case 4: this.msg = new RongIMLib.PubAckMessage(this.header); break; case 5: this.msg = new RongIMLib.QueryMessage(this.header); break; case 6: this.msg = new RongIMLib.QueryAckMessage(this.header); break; case 7: this.msg = new RongIMLib.QueryConMessage(this.header); break; case 9: case 11: case 13: this.msg = new RongIMLib.PingRespMessage(this.header); break; case 8: case 10: case 12: this.msg = new RongIMLib.PingReqMessage(this.header); break; case 14: this.msg = new RongIMLib.DisconnectMessage(this.header); break; default: throw new Error("No support for deserializing " + this.header.getType() + " messages"); } if (this.isPolling) { this.msg.init(this.In); } else { this.msg.read(this._in, this.In.length - 1); } return this.msg; }; return MessageInputStream; })(); RongIMLib.MessageInputStream = MessageInputStream; var Header = (function () { function Header(_type, _retain, _qos, _dup) { this.retain = false; this.qos = RongIMLib.Qos.AT_LEAST_ONCE; this.dup = false; this.syncMsg = false; if (_type && +_type == _type && arguments.length == 1) { this.retain = (_type & 1) > 0; this.qos = (_type & 6) >> 1; this.dup = (_type & 8) > 0; this.type = (_type >> 4) & 15; this.syncMsg = (_type & 8) == 8; } else { this.type = _type; this.retain = _retain; this.qos = _qos; this.dup = _dup; } } Header.prototype.getSyncMsg = function () { return this.syncMsg; }; Header.prototype.getType = function () { return this.type; }; Header.prototype.encode = function () { var me = this; switch (this.qos) { case RongIMLib.Qos[0]: me.qos = RongIMLib.Qos.AT_MOST_ONCE; break; case RongIMLib.Qos[1]: me.qos = RongIMLib.Qos.AT_LEAST_ONCE; break; case RongIMLib.Qos[2]: me.qos = RongIMLib.Qos.EXACTLY_ONCE; break; case RongIMLib.Qos[3]: me.qos = RongIMLib.Qos.DEFAULT; break; } var _byte = (this.type << 4); _byte |= this.retain ? 1 : 0; _byte |= this.qos << 1; _byte |= this.dup ? 8 : 0; return _byte; }; Header.prototype.toString = function () { return "Header [type=" + this.type + ",retain=" + this.retain + ",qos=" + this.qos + ",dup=" + this.dup + "]"; }; return Header; })(); RongIMLib.Header = Header; /** * 二进制帮助对象 */ var BinaryHelper = (function () { function BinaryHelper() { } BinaryHelper.prototype.writeUTF = function (str, isGetBytes) { var back = [], byteSize = 0; for (var i = 0, len = str.length; i < len; i++) { var code = str.charCodeAt(i); if (code >= 0 && code <= 127) { byteSize += 1; back.push(code); } else if (code >= 128 && code <= 2047) { byteSize += 2; back.push((192 | (31 & (code >> 6)))); back.push((128 | (63 & code))); } else if (code >= 2048 && code <= 65535) { byteSize += 3; back.push((224 | (15 & (code >> 12)))); back.push((128 | (63 & (code >> 6)))); back.push((128 | (63 & code))); } } for (var i = 0, len = back.length; i < len; i++) { if (back[i] > 255) { back[i] &= 255; } } if (isGetBytes) { return back; } if (byteSize <= 255) { return [0, byteSize].concat(back); } else { return [byteSize >> 8, byteSize & 255].concat(back); } }; BinaryHelper.prototype.readUTF = function (arr) { if (Object.prototype.toString.call(arr) == "[object String]") { return arr; } var UTF = "", _arr = arr; for (var i = 0, len = _arr.length; i < len; i++) { if (_arr[i] < 0) { _arr[i] += 256; } ; var one = _arr[i].toString(2), v = one.match(/^1+?(?=0)/); if (v && one.length == 8) { var bytesLength = v[0].length, // store = _arr[i].toString(2).slice(7 - bytesLength); store = ''; for (var st = 0; st < bytesLength; st++) { store += _arr[st + i].toString(2).slice(2); } UTF += String.fromCharCode(parseInt(store, 2)); i += bytesLength - 1; } else { UTF += String.fromCharCode(_arr[i]); } } return UTF; }; /** * [convertStream 将参数x转化为RongIMStream对象] * @param {any} x [参数] */ BinaryHelper.prototype.convertStream = function (x) { if (x instanceof RongIMStream) { return x; } else { return new RongIMStream(x); } }; BinaryHelper.prototype.toMQttString = function (str) { return this.writeUTF(str); }; return BinaryHelper; })(); RongIMLib.BinaryHelper = BinaryHelper; var RongIMStream = (function () { function RongIMStream(arr) { //当前流执行的起始位置 this.position = 0; //当前流写入的多少字节 this.writen = 0; this.poolLen = 0; this.binaryHelper = new BinaryHelper(); this.pool = arr; this.poolLen = arr.length; } RongIMStream.prototype.check = function () { return this.position >= this.pool.length; }; RongIMStream.prototype.readInt = function () { if (this.check()) { return -1; } var end = ""; for (var i = 0; i < 4; i++) { var t = this.pool[this.position++].toString(16); if (t.length == 1) { t = "0" + t; } end += t.toString(16); } return parseInt(end, 16); }; RongIMStream.prototype.readLong = function () { if (this.check()) { return -1; } var end = ""; for (var i = 0; i < 8; i++) { var t = this.pool[this.position++].toString(16); if (t.length == 1) { t = "0" + t; } end += t; } return parseInt(end, 16); }; RongIMStream.prototype.readTimestamp = function () { if (this.check()) { return -1; } var end = ""; for (var i = 0; i < 8; i++) { end += this.pool[this.position++].toString(16); } end = end.substring(2, 8); return parseInt(end, 16); }; RongIMStream.prototype.readUTF = function () { if (this.check()) { return -1; } var big = (this.readByte() << 8) | this.readByte(); return this.binaryHelper.readUTF(this.pool.subarray(this.position, this.position += big)); }; RongIMStream.prototype.readByte = function () { if (this.check()) { return -1; } var val = this.pool[this.position++]; if (val > 255) { val &= 255; } return val; }; RongIMStream.prototype.read = function (bytesArray) { if (bytesArray) { return this.pool.subarray(this.position, this.poolLen); } else { return this.readByte(); } }; RongIMStream.prototype.write = function (_byte) { var b = _byte; if (Object.prototype.toString.call(b).toLowerCase() == "[object array]") { [].push.apply(this.pool, b); } else { if (+b == b) { if (b > 255) { b &= 255; } this.pool.push(b); this.writen++; } } return b; }; RongIMStream.prototype.writeChar = function (v) { if (+v != v) { throw new Error("writeChar:arguments type is error"); } this.write(v >> 8 & 255); this.write(v & 255); this.writen += 2; }; RongIMStream.prototype.writeUTF = function (str) { var val = this.binaryHelper.writeUTF(str); [].push.apply(this.pool, val); this.writen += val.length; }; RongIMStream.prototype.toComplements = function () { var _tPool = this.pool; for (var i = 0; i < this.poolLen; i++) { if (_tPool[i] > 128) { _tPool[i] -= 256; } } return _tPool; }; RongIMStream.prototype.getBytesArray = function (isCom) { if (isCom) { return this.toComplements(); } return this.pool; }; return RongIMStream; })(); RongIMLib.RongIMStream = RongIMStream; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var SocketTransportation = (function () { /** * [constructor] * @param {string} url [连接地址:包含token、version] */ function SocketTransportation(_socket) { //连接状态 true:已连接 false:未连接 this.connected = false; //是否关闭: true:已关闭 false:未关闭 this.isClose = false; //存放消息队列的临时变量 this.queue = []; this.empty = new Function; this._socket = _socket; return this; } /** * [createTransport 创建WebScoket对象] */ SocketTransportation.prototype.createTransport = function (url, method) { if (!url) { throw new Error("URL can't be empty"); } ; this.url = url; var depend = RongIMLib.RongIMClient._memoryStore.depend; var wsScheme = depend.wsScheme; var tpl = '{wsScheme}{url}'; url = RongIMLib.RongUtil.tplEngine(tpl, { wsScheme: wsScheme, url: url }); this.socket = new WebSocket(url); this.socket.binaryType = "arraybuffer"; this.addEvent(); return this.socket; }; /** * [send 传送消息流] * @param {ArrayBuffer} data [二进制消息流] */ SocketTransportation.prototype.send = function (data) { if (!this.connected && !this.isClose) { //当通道不可用时,加入消息队列 this.queue.push(data); return; } if (this.isClose) { this._socket.fire("StatusChanged", RongIMLib.ConnectionStatus.CONNECTION_CLOSED); return; } var stream = new RongIMLib.RongIMStream([]), msg = new RongIMLib.MessageOutputStream(stream); msg.writeMessage(data); var val = stream.getBytesArray(true); var binary = new Int8Array(val); this.socket.send(binary.buffer); return this; }; /** * [onData 通道返回数据时调用的方法,用来想上层传递服务器返回的二进制消息流] * @param {ArrayBuffer} data [二进制消息流] */ SocketTransportation.prototype.onData = function (data) { if (RongIMLib.MessageUtil.isArray(data)) { this._socket.onMessage(new RongIMLib.MessageInputStream(data).readMessage()); } else { this._socket.onMessage(new RongIMLib.MessageInputStream(RongIMLib.MessageUtil.ArrayFormInput(data)).readMessage()); } return ""; }; /** * [onClose 通道关闭时触发的方法] */ SocketTransportation.prototype.onClose = function (ev) { var me = this; me.isClose = true; me.socket = this.empty; RongIMLib.Bridge._client.clearHeartbeat(); if (ev.code == 1006 && !this._status) { var currentTime = new Date().getTime(); if (currentTime - me.connectedTime <= SocketTransportation.MinConnectTime) { var host = RongIMLib.RongUtil.getUrlHost(me.url); RongIMLib.RongIMClient.invalidWsUrls.push(host); } me._socket.fire("StatusChanged", RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE); } else { me._status = 0; } }; /** * [onError 通道报错时触发的方法] * @param {any} error [抛出异常] */ SocketTransportation.prototype.onError = function (error) { this._socket.fire("StatusChanged", RongIMLib.ConnectionStatus.WEBSOCKET_ERROR); throw new Error(error); }; /** * [addEvent 为通道绑定事件] */ SocketTransportation.prototype.addEvent = function () { var self = this; self.socket.onopen = function () { self.connected = true; self.isClose = false; //通道可以用后,调用发送队列方法,把所有等得发送的消息发出 self.doQueue(); self._socket.fire("connect"); self.connectedTime = new Date().getTime(); }; self.socket.onmessage = function (ev) { //判断数据是不是字符串,如果是字符串那么就是flash传过来的。 if (typeof ev.data == "string") { self.onData(ev.data.split(",")); } else { self.onData(ev.data); } }; self.socket.onerror = function (ev) { self.onError(ev); }; self.socket.onclose = function (ev) { self.onClose(ev); }; }; /** * [doQueue 消息队列,把队列中消息发出] */ SocketTransportation.prototype.doQueue = function () { var self = this; for (var i = 0, len = self.queue.length; i < len; i++) { self.send(self.queue[i]); } }; /** * [disconnect 断开连接] */ SocketTransportation.prototype.disconnect = function (status) { var me = this; if (me.socket.readyState) { me.isClose = true; if (status) { me._status = status; } me.socket.close(); } }; /** * [reconnect 重新连接] */ SocketTransportation.prototype.reconnect = function () { this.disconnect(); this.createTransport(this.url); }; SocketTransportation.prototype.close = function () { this.socket.close(); }; // 最短链接时长(若 5000ms 内, ws 自动断开, 此 ws 地址置为不可用) SocketTransportation.MinConnectTime = 5000; return SocketTransportation; })(); RongIMLib.SocketTransportation = SocketTransportation; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var PollingTransportation = (function () { function PollingTransportation(socket) { this.empty = new Function; this.connected = false; this.pid = +new Date + Math.random() + ""; this.queue = []; this.socket = socket; return this; } PollingTransportation.prototype.createTransport = function (url, method) { if (!url) { throw new Error("Url is empty,Please check it!"); } ; this.url = url; var sid = RongIMLib.RongIMClient._storageProvider.getItem("sId" + RongIMLib.Navigation.Endpoint.userId), me = this; if (sid) { setTimeout(function () { me.onSuccess("{\"status\":0,\"userId\":\"" + RongIMLib.Navigation.Endpoint.userId + "\",\"headerCode\":32,\"messageId\":0,\"sessionid\":\"" + sid + "\"}"); me.connected = true; }, 500); return this; } this.getRequest(url, true); return this; }; PollingTransportation.prototype.requestFactory = function (url, method, multipart) { var reqest = this.XmlHttpRequest(); if (multipart) { reqest.multipart = true; } // reqest.timeout = 60000; reqest.open(method || "GET", RongIMLib.RongIMClient._memoryStore.depend.protocol + url); if (method == "POST" && "setRequestHeader" in reqest) { reqest.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=utf-8"); } return reqest; }; PollingTransportation.prototype.getRequest = function (url, isconnect) { var me = this; me.xhr = this.requestFactory(url + "&pid=" + encodeURIComponent(me.pid), "GET"); var timer = new RongIMLib.Timer({ timeout: 45000 }); if ("onload" in me.xhr) { me.xhr.onload = function () { timer.pause(); me.xhr.onload = me.empty; if (this.responseText == "lost params") { me.onError(); } else { me.onSuccess(this.responseText, isconnect); } }; me.xhr.onerror = function () { timer.pause(); me.disconnect(); }; } else { me.xhr.onreadystatechange = function () { timer.pause(); if (me.xhr.readyState == 4) { me.xhr.onreadystatechange = me.empty; if (/^(200|202)$/.test(me.xhr.status)) { me.onSuccess(me.xhr.responseText, isconnect); } else if (/^(400|403)$/.test(me.xhr.status)) { me.onError(); } else { me.disconnect(); } } }; } timer.resume(function () { me.onError(); }); me.xhr.send(); }; /** * [send 发送消息,Method:POST] * queue 为消息队列,待通道可用发送所有等待消息 * @param {string} data [需要传入comet格式数据,此处只负责通讯通道,数据转换在外层处理] */ PollingTransportation.prototype.send = function (data) { var me = this; var _send = me.sendxhr = this.requestFactory(RongIMLib.Navigation.Endpoint.host + "/websocket" + data.url + "&pid=" + encodeURIComponent(me.pid), "POST"); if ("onload" in _send) { _send.onload = function () { _send.onload = me.empty; me.onData(_send.responseText); }; _send.onerror = function () { _send.onerror = me.empty; }; } else { _send.onreadystatechange = function () { if (_send.readyState == 4) { this.onreadystatechange = this.empty; if (/^(202|200)$/.test(_send.status)) { me.onData(_send.responseText); } } }; } _send.send(JSON.stringify(data.data)); }; PollingTransportation.prototype.onData = function (data, header) { if (!data || data == "lost params") { return; } var self = this, val = JSON.parse(data); if (val.userId) { RongIMLib.Navigation.Endpoint.userId = val.userId; } if (header) { RongIMLib.RongIMClient._storageProvider.setItem("sId" + RongIMLib.Navigation.Endpoint.userId, header); } if (!RongIMLib.MessageUtil.isArray(val)) { val = [val]; } Array.forEach(val, function (m) { self.socket.fire("message", new RongIMLib.MessageInputStream(m, true).readMessage()); }); return ""; }; PollingTransportation.prototype.XmlHttpRequest = function () { var hasCORS = typeof XMLHttpRequest !== "undefined" && "withCredentials" in new XMLHttpRequest(), self = this; if ("undefined" != typeof XMLHttpRequest && hasCORS) { return new XMLHttpRequest(); } else if ("undefined" != typeof XDomainRequest) { return new XDomainRequest(); } else { return new ActiveXObject("Microsoft.XMLHTTP"); } }; PollingTransportation.prototype.onClose = function () { if (this.xhr) { if (this.xhr.onload) { this.xhr.onreadystatechange = this.xhr.onload = this.empty; } else { this.xhr.onreadystatechange = this.empty; } this.xhr.abort(); this.xhr = null; } if (this.sendxhr) { if (this.sendxhr.onload) { this.sendxhr.onreadystatechange = this.sendxhr.onload = this.empty; } else { this.sendxhr.onreadystatechange = this.empty; } this.sendxhr.abort(); this.sendxhr = null; } }; PollingTransportation.prototype.disconnect = function () { RongIMLib.RongIMClient._storageProvider.removeItem("sId" + RongIMLib.Navigation.Endpoint.userId); RongIMLib.RongIMClient._storageProvider.removeItem(RongIMLib.Navigation.Endpoint.userId + "msgId"); this.onClose(); }; PollingTransportation.prototype.reconnect = function () { this.disconnect(); this.createTransport(this.url); }; PollingTransportation.prototype.onSuccess = function (responseText, isconnect) { var txt = responseText.match(/"sessionid":"\S+?(?=")/); this.onData(responseText, txt ? txt[0].slice(13) : 0); if (/"headerCode":-32,/.test(responseText)) { RongIMLib.RongIMClient._storageProvider.removeItem("sId" + RongIMLib.Navigation.Endpoint.userId); RongIMLib.RongIMClient._storageProvider.removeItem(RongIMLib.Navigation.Endpoint.userId + "msgId"); return; } this.getRequest(RongIMLib.Navigation.Endpoint.host + "/pullmsg.js?sessionid=" + RongIMLib.RongIMClient._storageProvider.getItem("sId" + RongIMLib.Navigation.Endpoint.userId) + "×trap=" + encodeURIComponent(new Date().getTime() + Math.random() + "")); this.connected = true; isconnect && this.socket.fire("connect"); }; PollingTransportation.prototype.onError = function () { RongIMLib.RongIMClient._storageProvider.removeItem("sId" + RongIMLib.Navigation.Endpoint.userId); RongIMLib.RongIMClient._storageProvider.removeItem(RongIMLib.Navigation.Endpoint.userId + "msgId"); this.onClose(); if (this.connected) { this.connected = false; var code = RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE; this.socket.fire("disconnect", code); } }; PollingTransportation.prototype.close = function () { this.xhr.abort(); this.sendxhr = null; }; return PollingTransportation; })(); RongIMLib.PollingTransportation = PollingTransportation; })(RongIMLib || (RongIMLib = {})); //objectname映射 var typeMapping = { "RC:TxtMsg": "TextMessage", "RC:ImgMsg": "ImageMessage", "RC:VcMsg": "VoiceMessage", "RC:ImgTextMsg": "RichContentMessage", "RC:FileMsg": "FileMessage", "RC:HQVCMsg": "HQVoiceMessage", "RC:LBSMsg": "LocationMessage", "RC:InfoNtf": "InformationNotificationMessage", "RC:ContactNtf": "ContactNotificationMessage", "RC:ProfileNtf": "ProfileNotificationMessage", "RC:CmdNtf": "CommandNotificationMessage", "RC:DizNtf": "DiscussionNotificationMessage", "RC:CmdMsg": "CommandMessage", "RC:TypSts": "TypingStatusMessage", "RC:CsChaR": "ChangeModeResponseMessage", "RC:CsHsR": "HandShakeResponseMessage", "RC:CsEnd": "TerminateMessage", "RC:CsSp": "SuspendMessage", "RC:CsUpdate": "CustomerStatusUpdateMessage", "RC:ReadNtf": "ReadReceiptMessage", "RC:VCAccept": "AcceptMessage", "RC:VCRinging": "RingingMessage", "RC:VCSummary": "SummaryMessage", "RC:VCHangup": "HungupMessage", "RC:VCInvite": "InviteMessage", "RC:VCModifyMedia": "MediaModifyMessage", "RC:VCModifyMem": "MemberModifyMessage", "RC:CsContact": "CustomerContact", "RC:PSImgTxtMsg": "PublicServiceRichContentMessage", "RC:PSMultiImgTxtMsg": "PublicServiceMultiRichContentMessage", "RC:GrpNtf": "GroupNotificationMessage", "RC:PSCmd": "PublicServiceCommandMessage", "RC:RcCmd": "RecallCommandMessage", "RC:SRSMsg": "SyncReadStatusMessage", "RC:RRReqMsg": "ReadReceiptRequestMessage", "RC:RRRspMsg": "ReadReceiptResponseMessage", "RCJrmf:RpMsg": "JrmfRedPacketMessage", "RCJrmf:RpOpendMsg": "JrmfRedPacketOpenedMessage", "RC:CombineMsg": "RCCombineMessage", "RC:chrmKVNotiMsg": "ChrmKVNotificationMessage" }, //自定义消息类型 registerMessageTypeMapping = {}, HistoryMsgType = { 4: "qryCMsg", 2: "qryDMsg", 3: "qryGMsg", 1: "qryPMsg", 6: "qrySMsg", 7: "qryPMsg", 8: "qryPMsg", 5: "qryCMsg" }, disconnectStatus = { 1: 6 }; var RongIMLib; (function (RongIMLib) { /** * 通道标识类 */ var Transportations = (function () { function Transportations() { } Transportations._TransportType = RongIMLib.Socket.WEBSOCKET; return Transportations; })(); RongIMLib.Transportations = Transportations; var SyncTimeUtil = (function () { function SyncTimeUtil() { } SyncTimeUtil.$getKey = function (message) { var client = RongIMLib.Bridge._client; var userId = client.userId; var direction = (message.messageDirection == 1 ? 'send' : 'receive'); var appkey = RongIMLib.RongIMClient._memoryStore.appKey; var tpl = '{appkey}_{userId}_{direction}box'; return RongIMLib.RongUtil.tplEngine(tpl, { appkey: appkey, userId: userId, direction: direction }); }; SyncTimeUtil.set = function (message) { var key = SyncTimeUtil.$getKey(message); var sentTime = message.sentTime; var storage = RongIMLib.RongIMClient._storageProvider; storage.setItem(key, sentTime); }; SyncTimeUtil.get = function () { var sent = SyncTimeUtil.$getKey({ messageDirection: RongIMLib.MessageDirection.SEND }); var received = SyncTimeUtil.$getKey({ messageDirection: RongIMLib.MessageDirection.RECEIVE }); var storage = RongIMLib.RongIMClient._storageProvider; return { sent: Number(storage.getItem(sent) || 0), received: Number(storage.getItem(received) || 0) }; }; return SyncTimeUtil; })(); RongIMLib.SyncTimeUtil = SyncTimeUtil; var MessageUtil = (function () { function MessageUtil() { } /** *4680000 为localstorage最小容量5200000字节的90%,超过90%将删除之前过早的存储 */ MessageUtil.checkStorageSize = function () { return JSON.stringify(localStorage).length < 4680000; }; MessageUtil.getFirstKey = function (obj) { var str = ""; for (var key in obj) { str = key; break; } return str; }; MessageUtil.isEmpty = function (obj) { var empty = true; for (var key in obj) { empty = false; break; } return empty; }; MessageUtil.ArrayForm = function (typearray) { if (Object.prototype.toString.call(typearray) == "[object ArrayBuffer]") { var arr = new Int8Array(typearray); return [].slice.call(arr); } return typearray; }; MessageUtil.ArrayFormInput = function (typearray) { if (Object.prototype.toString.call(typearray) == "[object ArrayBuffer]") { var arr = new Uint8Array(typearray); return arr; } return typearray; }; MessageUtil.indexOf = function (arr, item, from) { for (var l = arr.length, i = (from < 0) ? Math.max(0, +from) : from || 0; i < l; i++) { if (arr[i] == item) { return i; } } return -1; }; MessageUtil.isArray = function (obj) { return Object.prototype.toString.call(obj) == "[object Array]"; }; //遍历,只能遍历数组 MessageUtil.forEach = function (arr, func) { if ([].forEach) { return function (arr, func) { [].forEach.call(arr, func); }; } else { return function (arr, func) { for (var i = 0; i < arr.length; i++) { func.call(arr, arr[i], i, arr); } }; } }; MessageUtil.remove = function (array, func) { for (var i = 0, len = array.length; i < len; i++) { if (func(array[i])) { return array.splice(i, 1)[0]; } } return null; }; MessageUtil.int64ToTimestamp = function (obj, isDate) { if (obj.low === undefined) { return obj; } var low = obj.low; if (low < 0) { low += 0xffffffff + 1; } low = low.toString(16); var timestamp = parseInt(obj.high.toString(16) + "00000000".replace(new RegExp("0{" + low.length + "}$"), low), 16); if (isDate) { return new Date(timestamp); } return timestamp; }; //消息转换方法 MessageUtil.messageParser = function (entity, onReceived, offlineMsg) { var message = new RongIMLib.Message(), content = entity.content, de, objectName = entity.classname, val, isUseDef = false; try { if (RongIMLib.RongIMClient._memoryStore.depend.isPolling) { val = new RongIMLib.BinaryHelper().readUTF(content.offset ? MessageUtil.ArrayForm(content.buffer).slice(content.offset, content.limit) : content); de = JSON.parse(val); } else { val = new RongIMLib.BinaryHelper().readUTF(content.offset ? MessageUtil.ArrayFormInput(content.buffer).subarray(content.offset, content.limit) : content); de = JSON.parse(val); } } catch (ex) { de = val; isUseDef = true; } var IMLib = RongIMLib; //映射为具体消息对象 if (objectName in typeMapping) { var typeName = typeMapping[objectName]; message.content = new IMLib[typeName](de); message.messageType = typeMapping[objectName]; } else if (objectName in registerMessageTypeMapping) { var typeName = registerMessageTypeMapping[objectName]; var regMsg = new IMLib.RongIMClient.RegisterMessage[typeName](de); if (isUseDef) { message.content = regMsg.decode(de); } else { message.content = regMsg; } message.messageType = registerMessageTypeMapping[objectName]; } else { message.content = new RongIMLib.UnknownMessage({ content: de, objectName: objectName }); message.messageType = "UnknownMessage"; } //根据实体对象设置message对象] var dateTime = MessageUtil.int64ToTimestamp(entity.dataTime); if (dateTime > 0) { message.sentTime = dateTime; } else { message.sentTime = +new Date; } message.senderUserId = entity.fromUserId; message.conversationType = entity.type; if (entity.fromUserId == RongIMLib.Bridge._client.userId) { message.targetId = entity.groupId; } else { message.targetId = (/^[234]$/.test(entity.type || entity.getType()) ? entity.groupId : message.senderUserId); } var selfUserId = RongIMLib.Bridge._client.userId; // 解决多端在线收自己发的消息时, messageDirection 为 2(接收), 导致未读数增加 var isSelfSend = entity.direction == 1 || message.senderUserId === selfUserId; if (isSelfSend) { message.messageDirection = RongIMLib.MessageDirection.SEND; message.senderUserId = RongIMLib.Bridge._client.userId; } else { message.messageDirection = RongIMLib.MessageDirection.RECEIVE; } // 自己给自己发的消息, messageDirection 为 2(接收) var isSelfToSelf = message.senderUserId === selfUserId && message.targetId === selfUserId; if (isSelfToSelf) { message.messageDirection = RongIMLib.MessageDirection.RECEIVE; } message.messageUId = entity.msgId; message.receivedTime = new Date().getTime(); message.messageId = (message.conversationType + "_" + ~~(Math.random() * 0xffffff)); message.objectName = objectName; message.receivedStatus = RongIMLib.ReceivedStatus.READ; if ((entity.status & 2) == 2) { message.receivedStatus = RongIMLib.ReceivedStatus.RETRIEVED; } message.offLineMessage = offlineMsg ? true : false; if (!offlineMsg) { if (RongIMLib.RongIMClient._memoryStore.connectAckTime > message.sentTime) { message.offLineMessage = true; } } return message; }; MessageUtil.detectCMP = function (options) { options.error = options.fail; return RongIMLib.RongUtil.request(options); }; //适配SSL // static schemeArrs: Array = [["http", "ws"], ["https", "wss"]]; MessageUtil.sign = { converNum: 1, msgNum: 1, isMsgStart: true, isConvStart: true }; return MessageUtil; })(); RongIMLib.MessageUtil = MessageUtil; /** * 工具类 */ var MessageIdHandler = (function () { function MessageIdHandler() { } MessageIdHandler.init = function () { this.messageId = +(RongIMLib.RongIMClient._storageProvider.getItem(RongIMLib.Navigation.Endpoint.userId + "msgId") || RongIMLib.RongIMClient._storageProvider.setItem(RongIMLib.Navigation.Endpoint.userId + "msgId", 0) || 0); }; MessageIdHandler.messageIdPlus = function (method) { RongIMLib.RongIMClient._memoryStore.depend.isPolling && this.init(); if (this.messageId >= 65535) { this.messageId = 0; } this.messageId++; RongIMLib.RongIMClient._memoryStore.depend.isPolling && RongIMLib.RongIMClient._storageProvider.setItem(RongIMLib.Navigation.Endpoint.userId + "msgId", this.messageId); return this.messageId; }; MessageIdHandler.clearMessageId = function () { this.messageId = 0; RongIMLib.RongIMClient._memoryStore.depend.isPolling && RongIMLib.RongIMClient._storageProvider.setItem(RongIMLib.Navigation.Endpoint.userId + "msgId", this.messageId); }; MessageIdHandler.getMessageId = function () { RongIMLib.RongIMClient._memoryStore.depend.isPolling && this.init(); return this.messageId; }; MessageIdHandler.messageId = 0; return MessageIdHandler; })(); RongIMLib.MessageIdHandler = MessageIdHandler; var ChrmKVCaches = (function () { function ChrmKVCaches() { this.time = 0; this.cache = {}; } ChrmKVCaches.prototype.setTime = function (time) { this.time = time; }; ChrmKVCaches.prototype.getTime = function () { return this.time; }; ChrmKVCaches.prototype.setValue = function (kvContent) { var key = kvContent.key, timestamp = kvContent.timestamp; this.cache[key] = this.cache[key] || {}; this.cache[key] = { value: kvContent.value, userId: kvContent.userId, isDeleted: false, timestamp: timestamp }; }; ChrmKVCaches.prototype.removeValue = function (kvContent) { var key = kvContent.key, timestamp = kvContent.timestamp; this.cache[key] = this.cache[key] || {}; var cache = this.cache[key]; this.cache[key] = RongIMLib.RongUtil.extend(cache, { isDeleted: true, userId: kvContent.userId, timestamp: timestamp }); }; ChrmKVCaches.prototype.getValue = function (key) { this.cache[key] = this.cache[key] || {}; var cache = this.cache[key]; return cache.isDeleted ? null : cache.value; }; ChrmKVCaches.prototype.getAllKV = function () { var kv = {}; RongIMLib.RongUtil.forEach(this.cache, function (item, key) { if (!item.isDeleted) { kv[key] = item.value; } }); return kv; }; ChrmKVCaches.prototype.getSetUserId = function (key) { this.cache[key] = this.cache[key] || {}; return this.cache[key].userId; }; ChrmKVCaches.prototype.isKeyExisted = function (key) { this.cache[key] = this.cache[key] || {}; var cache = this.cache[key]; var hasValue = !RongIMLib.RongUtil.isEmpty(cache.value); return hasValue && !cache.isDeleted; }; ChrmKVCaches.prototype.clear = function () { this.cache = {}; }; return ChrmKVCaches; })(); var chrmKVCaches = {}; var chrmKVProsumerCaches = {}; var getKVCache = function (chrmId) { var chrmKVCache = chrmKVCaches[chrmId]; if (!chrmKVCache) { chrmKVCache = chrmKVCaches[chrmId] = new ChrmKVCaches(); } return chrmKVCache; }; var getKVProsumer = function (chrmId) { var kvProsumer = chrmKVProsumerCaches[chrmId]; if (!kvProsumer) { kvProsumer = chrmKVProsumerCaches[chrmId] = new RongIMLib.RongUtil.Prosumer(); } return kvProsumer; }; var ChrmKVHandler = (function () { function ChrmKVHandler() { } ChrmKVHandler.pull = function (chrmId, time) { var prosumer = getKVProsumer(chrmId); var event = RongIMLib.RongIMClient._dataAccessProvider.pullChatroomEntry; prosumer.produce({ event: event, chrmId: chrmId, time: time }); prosumer.consume(function (params, next) { var event = params.event, chrmId = params.chrmId, time = params.time; var kvCache = getKVCache(chrmId); var currentTime = kvCache.getTime(); var isKVNeedUpdated = currentTime < time; if (isKVNeedUpdated) { event(chrmId, currentTime, { onSuccess: function (result) { ChrmKVHandler.setEntries(chrmId, result); next(); }, onError: next }); } else { next(); } }); }; ChrmKVHandler.setEntries = function (chrmId, entity) { var entries = entity.entries, isFullUpdate = entity.bFullUpdate, syncTime = entity.syncTime; var event = isFullUpdate ? ChrmKVHandler.setFullEntries : ChrmKVHandler.setIncreEntries; var kvCache = getKVCache(chrmId); syncTime = MessageUtil.int64ToTimestamp(syncTime); if (RongIMLib.RongUtil.isArray(entries)) { RongIMLib.RongUtil.forEach(entries, function (item) { var setTime = item.timestamp; if (!RongIMLib.RongUtil.isNumber(setTime)) { item.timestamp = MessageUtil.int64ToTimestamp(setTime); } }); } kvCache.setTime(syncTime); // 更新拉取时间 event(chrmId, entries); // 更新 kv 值 }; ChrmKVHandler.setEntry = function (chrmId, chatroomEntry, status, userId) { var kvCache = getKVCache(chrmId); var timestamp = chatroomEntry.timestamp || +new Date(); var isDelete = RongInnerTools.getChrmEntityByStatus(status).isDelete; var eventName = isDelete ? 'removeValue' : 'setValue'; kvCache[eventName]({ key: chatroomEntry.key, value: chatroomEntry.value, userId: userId, timestamp: timestamp }); }; ChrmKVHandler.setFullEntries = function (chrmId, entries) { var kvCache = getKVCache(chrmId); kvCache.clear(); RongIMLib.RongUtil.forEach(entries, function (entity) { entity.timestamp = MessageUtil.int64ToTimestamp(entity.timestamp); kvCache.setValue({ key: entity.key, value: entity.value, userId: entity.uid, timestamp: entity.timestamp }); }); }; ChrmKVHandler.setIncreEntries = function (chrmId, entries) { var kvCache = getKVCache(chrmId); var currentUserId = RongIMLib.RongIMClient.getInstance().getCurrentUserId(); var optEvent = function (entity, isOverwrite, eventName) { var key = entity.key, value = entity.value; var isLatestedKeySetBySelf = kvCache.getSetUserId(key) === currentUserId; var isKeyNotExist = !kvCache.isKeyExisted(key); /* 1. 需覆盖时, 不管 key 是否已存在, 都直接设置 2. 不覆盖时, 必须最后一次 key 为自己设置的或此 key 还未设置过, 才能继续 */ if (isOverwrite || isLatestedKeySetBySelf || isKeyNotExist) { kvCache[eventName]({ key: key, value: value, userId: entity.uid, timestamp: entity.timestamp }); } }; RongIMLib.RongUtil.forEach(entries, function (entity) { var entityContent = RongInnerTools.getChrmEntityByStatus(entity.status); var eventName = entityContent.isDelete ? 'removeValue' : 'setValue'; optEvent(entity, entityContent.isOverwrite, eventName); }); }; ChrmKVHandler.getEntityValue = function (chrmId, key) { var kvCache = getKVCache(chrmId); return kvCache.getValue(key); }; ChrmKVHandler.getAllEntityValue = function (chrmId) { var kvCache = getKVCache(chrmId); return kvCache.getAllKV(); }; ChrmKVHandler.isKeyValid = function (key) { return /^[A-Za-z0-9_=+-]+$/.test(key); }; return ChrmKVHandler; })(); RongIMLib.ChrmKVHandler = ChrmKVHandler; var AutoDeleteCode = 0x0001; var OverwriteCode = 0x0002; var DeleteOperationCode = 0x0004; var RongInnerTools = (function () { function RongInnerTools() { } RongInnerTools.convertUserStatus = function (entity) { entity = RongIMLib.RongUtil.rename(entity, { subUserId: 'userId' }); var status = JSON.parse(entity.status); var us = status.us; if (!us) { return entity; } entity.status = RongIMLib.RongUtil.rename(us, { o: 'online', 'p': 'platform', s: 'status' }); return entity; }; RongInnerTools.getChrmEntityStatus = function (entity, chatroomOpt) { var status = 0; // 是否自动清理 if (entity.isAutoDelete) { status = status | AutoDeleteCode; } // 是否覆盖 if (entity.isOverwrite) { status = status | OverwriteCode; } // 操作类型 switch (chatroomOpt) { case RongIMLib.ChatroomEntityOpt.DELETE: status = status | DeleteOperationCode; break; default: break; } return status; }; RongInnerTools.getChrmEntityByStatus = function (status) { var isDelete = !!(status & DeleteOperationCode); var entityOpt = isDelete ? RongIMLib.ChatroomEntityOpt.DELETE : RongIMLib.ChatroomEntityOpt.UPDATE; return { isAutoDelete: !!(status & AutoDeleteCode), isOverwrite: !!(status & OverwriteCode), entityOpt: entityOpt, isDelete: isDelete }; }; return RongInnerTools; })(); RongIMLib.RongInnerTools = RongInnerTools; var UnreadCountHandler = (function () { function UnreadCountHandler() { } UnreadCountHandler.getKey = function (type, targetId) { var selfId = RongIMLib.RongIMClient.getInstance().getCurrentUserId(); return RongIMLib.RongUtil.tplEngine(UnreadCountHandler.KeyTemp, { selfId: selfId, type: type, targetId: targetId }); }; UnreadCountHandler.getDetailByKey = function (key) { var detail = { count: 0, sentTime: 0 }; var value = RongIMLib.RongIMClient._storageProvider.getItem(key); if (!value) { return detail; } value += ''; var unreadItems = value.split('_'); var hasUnderline = unreadItems.length > 1; detail.count = Number(unreadItems[0]); if (hasUnderline) { detail.sentTime = Number(unreadItems[1]); } return detail; }; UnreadCountHandler.getDetail = function (type, targetId) { var key = UnreadCountHandler.getKey(type, targetId); var detail = UnreadCountHandler.getDetailByKey(key); return detail; }; UnreadCountHandler.set = function (type, id, count, sentTime) { var key = UnreadCountHandler.getKey(type, id); var value = sentTime ? RongIMLib.RongUtil.tplEngine(UnreadCountHandler.ValueTemp, { count: count, sentTime: sentTime }) : count; RongIMLib.RongIMClient._storageProvider.setItem(key, value); return count; }; UnreadCountHandler.add = function (type, id, plusCount, sentTime) { var detail = UnreadCountHandler.getDetail(type, id), count = detail.count, oldSentTime = detail.sentTime; if (sentTime && sentTime > oldSentTime) { count = count + plusCount; UnreadCountHandler.set(type, id, count, sentTime); } return count; }; UnreadCountHandler.get = function (type, id) { var detail = UnreadCountHandler.getDetail(type, id); return detail.count; }; UnreadCountHandler.getAll = function (types) { var total = 0; var selfId = RongIMLib.RongIMClient.getInstance().getCurrentUserId(); var setTotal = function (keyList) { RongIMLib.RongUtil.forEach(keyList, function (key) { var detail = UnreadCountHandler.getDetailByKey(key); total += detail.count; }); }; if (types) { RongIMLib.RongUtil.forEach(types, function (type) { var key = UnreadCountHandler.getKey(type, ''); var unreadKeys = RongIMLib.RongIMClient._storageProvider.getItemKeyList(key); setTotal(unreadKeys); }); } else { var key = UnreadCountHandler.getKey('', ''); var unreadKeys = RongIMLib.RongIMClient._storageProvider.getItemKeyList(key); setTotal(unreadKeys); } return total; }; UnreadCountHandler.remove = function (type, targetId) { var key = UnreadCountHandler.getKey(type, targetId); RongIMLib.RongIMClient._storageProvider.removeItem(key); }; UnreadCountHandler.clear = function () { var key = UnreadCountHandler.getKey('', ''); var keyList = RongIMLib.RongIMClient._storageProvider.getItemKeyList(key); RongIMLib.RongUtil.forEach(keyList, function (key) { RongIMLib.RongIMClient._storageProvider.removeItem(key); }); }; UnreadCountHandler.KeyTemp = 'cu{selfId}{type}{targetId}'; UnreadCountHandler.ValueTemp = '{count}_{sentTime}'; return UnreadCountHandler; })(); RongIMLib.UnreadCountHandler = UnreadCountHandler; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var MessageContent = (function () { function MessageContent(data) { throw new Error("This method is abstract, you must implement this method in inherited class."); } MessageContent.obtain = function () { throw new Error("This method is abstract, you must implement this method in inherited class."); }; return MessageContent; })(); RongIMLib.MessageContent = MessageContent; var NotificationMessage = (function (_super) { __extends(NotificationMessage, _super); function NotificationMessage() { _super.apply(this, arguments); } return NotificationMessage; })(MessageContent); RongIMLib.NotificationMessage = NotificationMessage; var StatusMessage = (function (_super) { __extends(StatusMessage, _super); function StatusMessage() { _super.apply(this, arguments); } return StatusMessage; })(MessageContent); RongIMLib.StatusMessage = StatusMessage; var ModelUtil = (function () { function ModelUtil() { } ModelUtil.modelClone = function (object) { var obj = {}; for (var item in object) { if (item != "messageName" && "encode" != item) { obj[item] = object[item]; } } return obj; }; ModelUtil.modleCreate = function (fields, msgType) { // if (fields.length < 1) { // throw new Error("Array is empty -> registerMessageType.modleCreate"); // } var Object = function (message) { var me = this; for (var index in fields) { me[fields[index]] = message[fields[index]]; } Object.prototype.messageName = msgType; Object.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; }; return Object; }; return ModelUtil; })(); RongIMLib.ModelUtil = ModelUtil; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var CustomerStatusMessage = (function () { function CustomerStatusMessage(message) { this.messageName = "CustomerStatusMessage"; this.status = message.status; } CustomerStatusMessage.obtain = function () { return null; }; CustomerStatusMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return CustomerStatusMessage; })(); RongIMLib.CustomerStatusMessage = CustomerStatusMessage; /** * 客服转换响应消息的类型名 */ var ChangeModeResponseMessage = (function () { function ChangeModeResponseMessage(message) { this.messageName = "ChangeModeResponseMessage"; this.code = message.code; this.data = message.data; this.msg = message.msg; } ChangeModeResponseMessage.obtain = function () { return null; }; ChangeModeResponseMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ChangeModeResponseMessage; })(); RongIMLib.ChangeModeResponseMessage = ChangeModeResponseMessage; /** * 客服转换消息的类型名 * 此消息不计入未读消息数 */ var ChangeModeMessage = (function () { function ChangeModeMessage(message) { this.messageName = "ChangeModeMessage"; this.uid = message.uid; this.sid = message.sid; this.pid = message.pid; } ChangeModeMessage.obtain = function () { return null; }; ChangeModeMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ChangeModeMessage; })(); RongIMLib.ChangeModeMessage = ChangeModeMessage; var CustomerStatusUpdateMessage = (function () { function CustomerStatusUpdateMessage(message) { this.messageName = "CustomerStatusUpdateMessage"; this.serviceStatus = message.serviceStatus; this.sid = message.sid; } CustomerStatusUpdateMessage.obtain = function () { return null; }; CustomerStatusUpdateMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return CustomerStatusUpdateMessage; })(); RongIMLib.CustomerStatusUpdateMessage = CustomerStatusUpdateMessage; var HandShakeMessage = (function () { function HandShakeMessage(message) { this.messageName = "HandShakeMessage"; if (message) { this.requestInfo = message.requestInfo; this.userInfo = message.userInfo; } } HandShakeMessage.obtain = function () { return null; }; HandShakeMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return HandShakeMessage; })(); RongIMLib.HandShakeMessage = HandShakeMessage; var CustomerContact = (function () { function CustomerContact(message) { this.messageName = "CustomerContact"; this.page = message.page; this.nickName = message.nickName; this.routingInfo = message.routingInfo; this.info = message.info; this.requestInfo = message.requestInfo; } CustomerContact.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return CustomerContact; })(); RongIMLib.CustomerContact = CustomerContact; var EvaluateMessage = (function () { function EvaluateMessage(message) { this.messageName = "EvaluateMessage"; this.uid = message.uid; this.sid = message.sid; this.pid = message.pid; this.source = message.source; this.suggest = message.suggest; this.isresolve = message.isresolve; this.type = message.type; } EvaluateMessage.obtain = function () { return null; }; EvaluateMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return EvaluateMessage; })(); RongIMLib.EvaluateMessage = EvaluateMessage; /** * 客服握手响应消息的类型名 */ var HandShakeResponseMessage = (function () { function HandShakeResponseMessage(message) { this.messageName = "HandShakeResponseMessage"; this.msg = message.msg; this.status = message.status; this.data = message.data; } HandShakeResponseMessage.obtain = function () { return null; }; HandShakeResponseMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return HandShakeResponseMessage; })(); RongIMLib.HandShakeResponseMessage = HandShakeResponseMessage; var SuspendMessage = (function () { function SuspendMessage(message) { this.messageName = "SuspendMessage"; this.uid = message.uid; this.sid = message.sid; this.pid = message.pid; } SuspendMessage.obtain = function () { return null; }; SuspendMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return SuspendMessage; })(); RongIMLib.SuspendMessage = SuspendMessage; var TerminateMessage = (function () { function TerminateMessage(message) { this.messageName = "TerminateMessage"; this.code = message.code; this.msg = message.msg; this.sid = message.sid; } TerminateMessage.obtain = function () { return null; }; TerminateMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return TerminateMessage; })(); RongIMLib.TerminateMessage = TerminateMessage; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var IsTypingStatusMessage = (function () { function IsTypingStatusMessage(data) { this.messageName = "IsTypingStatusMessage"; var msg = data; } IsTypingStatusMessage.prototype.encode = function () { return undefined; }; IsTypingStatusMessage.prototype.getMessage = function () { return null; }; return IsTypingStatusMessage; })(); RongIMLib.IsTypingStatusMessage = IsTypingStatusMessage; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var InformationNotificationMessage = (function () { function InformationNotificationMessage(message) { this.messageName = "InformationNotificationMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> InformationNotificationMessage."); } this.message = message.message; this.extra = message.extra; if (message.user) { this.user = message.user; } } InformationNotificationMessage.obtain = function (message) { return new InformationNotificationMessage({ message: message, extra: "" }); }; InformationNotificationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return InformationNotificationMessage; })(); RongIMLib.InformationNotificationMessage = InformationNotificationMessage; var CommandMessage = (function () { function CommandMessage(message) { this.messageName = "CommandMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> CommandMessage."); } try { if (Object.prototype.toString.call(message.data) == "[object String]") { this.data = JSON.parse(message.data); } else { this.data = message.data; } } catch (e) { this.data = message.data; } this.name = message.name; this.extra = message.extra; } CommandMessage.obtain = function (data) { return new CommandMessage({ data: data, extra: "" }); }; CommandMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return CommandMessage; })(); RongIMLib.CommandMessage = CommandMessage; var ContactNotificationMessage = (function () { function ContactNotificationMessage(message) { this.messageName = "ContactNotificationMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> ContactNotificationMessage."); } this.operation = message.operation; this.targetUserId = message.targetUserId; this.message = message.message; this.extra = message.extra; this.sourceUserId = message.sourceUserId; if (message.user) { this.user = message.user; } } ContactNotificationMessage.obtain = function (operation, sourceUserId, targetUserId, message) { return new InformationNotificationMessage({ operation: operation, sourceUserId: sourceUserId, targetUserId: targetUserId, message: message }); }; ContactNotificationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; ContactNotificationMessage.CONTACT_OPERATION_ACCEPT_RESPONSE = "ContactOperationAcceptResponse"; ContactNotificationMessage.CONTACT_OPERATION_REJECT_RESPONSE = "ContactOperationRejectResponse"; ContactNotificationMessage.CONTACT_OPERATION_REQUEST = "ContactOperationRequest"; return ContactNotificationMessage; })(); RongIMLib.ContactNotificationMessage = ContactNotificationMessage; var ProfileNotificationMessage = (function () { function ProfileNotificationMessage(message) { this.messageName = "ProfileNotificationMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> ProfileNotificationMessage."); } this.operation = message.operation; try { if (Object.prototype.toString.call(message.data) == "[object String]") { this.data = JSON.parse(message.data); } else { this.data = message.data; } } catch (e) { this.data = message.data; } this.extra = message.extra; if (message.user) { this.user = message.user; } } ProfileNotificationMessage.obtain = function (operation, data) { return new ProfileNotificationMessage({ operation: operation, data: data }); }; ProfileNotificationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ProfileNotificationMessage; })(); RongIMLib.ProfileNotificationMessage = ProfileNotificationMessage; var CommandNotificationMessage = (function () { function CommandNotificationMessage(message) { this.messageName = "CommandNotificationMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> ProfileNotificationMessage."); } try { if (Object.prototype.toString.call(message.data) == "[object String]") { this.data = JSON.parse(message.data); } else { this.data = message.data; } } catch (e) { this.data = message.data; } this.name = message.name; this.extra = message.extra; if (message.user) { this.user = message.user; } } CommandNotificationMessage.obtain = function (name, data) { return new CommandNotificationMessage({ name: name, data: data, extra: "" }); }; CommandNotificationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return CommandNotificationMessage; })(); RongIMLib.CommandNotificationMessage = CommandNotificationMessage; var DiscussionNotificationMessage = (function () { function DiscussionNotificationMessage(message) { this.messageName = "DiscussionNotificationMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> DiscussionNotificationMessage."); } this.extra = message.extra; this.extension = message.extension; this.type = message.type; this.isHasReceived = message.isHasReceived; this.operation = message.operation; this.user = message.user; if (message.user) { this.user = message.user; } } DiscussionNotificationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return DiscussionNotificationMessage; })(); RongIMLib.DiscussionNotificationMessage = DiscussionNotificationMessage; var GroupNotificationMessage = (function () { function GroupNotificationMessage(msg) { this.messageName = "GroupNotificationMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> GroupNotificationMessage."); } msg.operatorUserId && (this.operatorUserId = msg.operatorUserId); msg.operation && (this.operation = msg.operation); msg.data && (this.data = msg.data); msg.message && (this.message = msg.message); msg.extra && (this.extra = msg.extra); } GroupNotificationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return GroupNotificationMessage; })(); RongIMLib.GroupNotificationMessage = GroupNotificationMessage; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var TextMessage = (function () { function TextMessage(message) { this.messageName = "TextMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> TextMessage."); } this.content = message.content; this.extra = message.extra; if (message.user) { this.user = message.user; } if (message.mentionedInfo) { this.mentionedInfo = message.mentionedInfo; } } TextMessage.obtain = function (text) { return new TextMessage({ extra: "", content: text }); }; TextMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return TextMessage; })(); RongIMLib.TextMessage = TextMessage; var TypingStatusMessage = (function () { function TypingStatusMessage(message) { this.messageName = "TypingStatusMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> TypingStatusMessage."); } this.typingContentType = message.typingContentType; this.data = message.data; } TypingStatusMessage.obtain = function (typingContentType, data) { return new TypingStatusMessage({ typingContentType: typingContentType, data: data }); }; TypingStatusMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return TypingStatusMessage; })(); RongIMLib.TypingStatusMessage = TypingStatusMessage; var ReadReceiptMessage = (function () { function ReadReceiptMessage(message) { this.messageName = "ReadReceiptMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> ReadReceiptMessage."); } this.lastMessageSendTime = message.lastMessageSendTime; this.messageUId = message.messageUId; this.type = message.type; } ReadReceiptMessage.obtain = function (messageUId, lastMessageSendTime, type) { return new ReadReceiptMessage({ messageUId: messageUId, lastMessageSendTime: lastMessageSendTime, type: type }); }; ReadReceiptMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ReadReceiptMessage; })(); RongIMLib.ReadReceiptMessage = ReadReceiptMessage; var VoiceMessage = (function () { function VoiceMessage(message) { this.messageName = "VoiceMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> VoiceMessage."); } this.content = message.content; this.duration = message.duration; this.extra = message.extra; if (message.user) { this.user = message.user; } if (message.mentionedInfo) { this.mentionedInfo = message.mentionedInfo; } } VoiceMessage.obtain = function (base64Content, duration) { return new VoiceMessage({ content: base64Content, duration: duration, extra: "" }); }; VoiceMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return VoiceMessage; })(); RongIMLib.VoiceMessage = VoiceMessage; var RecallCommandMessage = (function () { function RecallCommandMessage(message) { this.messageName = "RecallCommandMessage"; this.messageUId = message.messageUId; this.conversationType = message.conversationType; this.targetId = message.targetId; this.sentTime = message.sentTime; message.extra && (this.extra = message.extra); message.user && (this.user = message.user); } RecallCommandMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return RecallCommandMessage; })(); RongIMLib.RecallCommandMessage = RecallCommandMessage; var ImageMessage = (function () { function ImageMessage(message) { this.messageName = "ImageMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> ImageMessage."); } this.content = message.content; this.imageUri = message.imageUri; message.extra && (this.extra = message.extra); message.user && (this.user = message.user); if (message.mentionedInfo) { this.mentionedInfo = message.mentionedInfo; } } ImageMessage.obtain = function (content, imageUri) { return new ImageMessage({ content: content, imageUri: imageUri, extra: "" }); }; ImageMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ImageMessage; })(); RongIMLib.ImageMessage = ImageMessage; var LocationMessage = (function () { function LocationMessage(message) { this.messageName = "LocationMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> LocationMessage."); } this.latitude = message.latitude; this.longitude = message.longitude; this.poi = message.poi; this.content = message.content; this.extra = message.extra; if (message.user) { this.user = message.user; } if (message.mentionedInfo) { this.mentionedInfo = message.mentionedInfo; } } LocationMessage.obtain = function (latitude, longitude, poi, content) { return new LocationMessage({ latitude: latitude, longitude: longitude, poi: poi, content: content, extra: "" }); }; LocationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return LocationMessage; })(); RongIMLib.LocationMessage = LocationMessage; var RichContentMessage = (function () { function RichContentMessage(message) { this.messageName = "RichContentMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> RichContentMessage."); } this.title = message.title; this.content = message.content; this.imageUri = message.imageUri; this.extra = message.extra; this.url = message.url; if (message.user) { this.user = message.user; } } RichContentMessage.obtain = function (title, content, imageUri, url) { return new RichContentMessage({ title: title, content: content, imageUri: imageUri, url: url, extra: "" }); }; RichContentMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return RichContentMessage; })(); RongIMLib.RichContentMessage = RichContentMessage; var JrmfRedPacketMessage = (function () { function JrmfRedPacketMessage(message) { this.messageName = 'JrmfRedPacketMessage'; message && (this.message = message); } JrmfRedPacketMessage.prototype.encode = function () { return ""; }; return JrmfRedPacketMessage; })(); RongIMLib.JrmfRedPacketMessage = JrmfRedPacketMessage; var JrmfRedPacketOpenedMessage = (function () { function JrmfRedPacketOpenedMessage(message) { this.messageName = 'JrmfRedPacketOpenedMessage'; message && (this.message = message); } JrmfRedPacketOpenedMessage.prototype.encode = function () { return ""; }; return JrmfRedPacketOpenedMessage; })(); RongIMLib.JrmfRedPacketOpenedMessage = JrmfRedPacketOpenedMessage; var UnknownMessage = (function () { function UnknownMessage(message) { this.messageName = "UnknownMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> UnknownMessage."); } this.message = message; } UnknownMessage.prototype.encode = function () { return ""; }; return UnknownMessage; })(); RongIMLib.UnknownMessage = UnknownMessage; var PublicServiceCommandMessage = (function () { function PublicServiceCommandMessage(message) { this.messageName = "PublicServiceCommandMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> PublicServiceCommandMessage."); } this.content = message.content; this.extra = message.extra; this.menuItem = message.menuItem; if (message.user) { this.user = message.user; } if (message.mentionedInfo) { this.mentionedInfo = message.mentionedInfo; } } PublicServiceCommandMessage.obtain = function (item) { return new PublicServiceCommandMessage({ content: "", command: "", menuItem: item, extra: "" }); }; PublicServiceCommandMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return PublicServiceCommandMessage; })(); RongIMLib.PublicServiceCommandMessage = PublicServiceCommandMessage; var PublicServiceMultiRichContentMessage = (function () { function PublicServiceMultiRichContentMessage(messages) { this.messageName = "PublicServiceMultiRichContentMessage"; this.richContentMessages = messages; } PublicServiceMultiRichContentMessage.prototype.encode = function () { return null; }; return PublicServiceMultiRichContentMessage; })(); RongIMLib.PublicServiceMultiRichContentMessage = PublicServiceMultiRichContentMessage; var SyncReadStatusMessage = (function () { function SyncReadStatusMessage(message) { this.messageName = "SyncReadStatusMessage"; message.lastMessageSendTime && (this.lastMessageSendTime = message.lastMessageSendTime); } SyncReadStatusMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return SyncReadStatusMessage; })(); RongIMLib.SyncReadStatusMessage = SyncReadStatusMessage; var ReadReceiptRequestMessage = (function () { function ReadReceiptRequestMessage(message) { this.messageName = "ReadReceiptRequestMessage"; message.messageUId && (this.messageUId = message.messageUId); } ReadReceiptRequestMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ReadReceiptRequestMessage; })(); RongIMLib.ReadReceiptRequestMessage = ReadReceiptRequestMessage; var ReadReceiptResponseMessage = (function () { function ReadReceiptResponseMessage(message) { this.messageName = "ReadReceiptResponseMessage"; message.receiptMessageDic && (this.receiptMessageDic = message.receiptMessageDic); } ReadReceiptResponseMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ReadReceiptResponseMessage; })(); RongIMLib.ReadReceiptResponseMessage = ReadReceiptResponseMessage; var PublicServiceRichContentMessage = (function () { function PublicServiceRichContentMessage(message) { this.messageName = "PublicServiceRichContentMessage"; this.richContentMessage = message; } PublicServiceRichContentMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return PublicServiceRichContentMessage; })(); RongIMLib.PublicServiceRichContentMessage = PublicServiceRichContentMessage; var FileMessage = (function () { function FileMessage(message) { this.messageName = "FileMessage"; message.name && (this.name = message.name); message.size && (this.size = message.size); message.type && (this.type = message.type); message.fileUrl && (this.fileUrl = message.fileUrl); message.extra && (this.extra = message.extra); message.user && (this.user = message.user); } FileMessage.obtain = function (msg) { return new FileMessage({ name: msg.name, size: msg.size, type: msg.type, fileUrl: msg.fileUrl }); }; FileMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return FileMessage; })(); RongIMLib.FileMessage = FileMessage; var HQVoiceMessage = (function () { function HQVoiceMessage(message) { this.messageName = "HQVoiceMessage"; this.type = message.type || 'aac'; message.localPath && (this.localPath = message.localPath); message.remoteUrl && (this.remoteUrl = message.remoteUrl); message.duration && (this.duration = message.duration); message.extra && (this.extra = message.extra); message.user && (this.user = message.user); } HQVoiceMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return HQVoiceMessage; })(); RongIMLib.HQVoiceMessage = HQVoiceMessage; var AcceptMessage = (function () { function AcceptMessage(message) { this.messageName = "AcceptMessage"; this.mediaId = message.mediaId; this.callId = message.callId; this.mediaType = message.mediaType; this.mode = message.mode; this.subInfo = message.subInfo; } AcceptMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return AcceptMessage; })(); RongIMLib.AcceptMessage = AcceptMessage; var RingingMessage = (function () { function RingingMessage(message) { this.messageName = "RingingMessage"; this.callId = message.callId; } RingingMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return RingingMessage; })(); RongIMLib.RingingMessage = RingingMessage; var SummaryMessage = (function () { function SummaryMessage(message) { this.messageName = "SummaryMessage"; this.caller = message.caller; this.inviter = message.inviter; this.mediaType = message.mediaType; this.memberIdList = message.memberIdList; this.startTime = message.startTime; this.connectedTime = message.connectedTime; this.duration = message.duration; this.status = message.status; } SummaryMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return SummaryMessage; })(); RongIMLib.SummaryMessage = SummaryMessage; var HungupMessage = (function () { function HungupMessage(message) { this.messageName = "HungupMessage"; this.callId = message.callId; this.reason = message.reason; this.mode = message.mode; this.subInfo = message.subInfo; } HungupMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return HungupMessage; })(); RongIMLib.HungupMessage = HungupMessage; var InviteMessage = (function () { function InviteMessage(message) { this.messageName = "InviteMessage"; this.mediaId = message.mediaId; this.callId = message.callId; this.engineType = message.engineType; this.channelInfo = message.channelInfo; this.mediaType = message.mediaType; this.extra = message.extra; this.inviteUserIds = message.inviteUserIds; this.observerUserIds = message.observerUserIds; this.mode = message.mode; this.subInfo = message.subInfo; } InviteMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return InviteMessage; })(); RongIMLib.InviteMessage = InviteMessage; var MediaModifyMessage = (function () { function MediaModifyMessage(message) { this.messageName = "MediaModifyMessage"; this.callId = message.callId; this.mediaType = message.mediaType; this.mode = message.mode; this.subInfo = message.subInfo; } MediaModifyMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return MediaModifyMessage; })(); RongIMLib.MediaModifyMessage = MediaModifyMessage; var MemberModifyMessage = (function () { function MemberModifyMessage(message) { this.messageName = "MemberModifyMessage"; this.modifyMemType = message.modifyMemType; this.callId = message.callId; this.caller = message.caller; this.engineType = message.engineType; this.channelInfo = message.channelInfo; this.mediaType = message.mediaType; this.extra = message.extra; this.inviteUserIds = message.inviteUserIds; this.existedMemberStatusList = message.existedMemberStatusList; this.existedUserPofiles = message.existedUserPofiles; this.observerUserIds = message.observerUserIds; this.mode = message.mode; this.subInfo = message.subInfo; } MemberModifyMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return MemberModifyMessage; })(); RongIMLib.MemberModifyMessage = MemberModifyMessage; var RCCombineMessage = (function () { function RCCombineMessage(message) { this.messageName = "RCCombineMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> RCCombineMessage."); } this.nameList = message.nameList; this.remoteUrl = message.remoteUrl; if (message.user) { this.user = message.user; } this.summaryList = message.summaryList; } RCCombineMessage.obtain = function (remoteUrl, nameList, summaryList) { return new RCCombineMessage({ extra: "", content: remoteUrl, nameList: nameList, summaryList: summaryList }); }; RCCombineMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return RCCombineMessage; })(); RongIMLib.RCCombineMessage = RCCombineMessage; var ChrmKVNotificationMessage = (function () { function ChrmKVNotificationMessage(message) { this.messageName = "ChrmKVNotificationMessage"; message.key && (this.key = message.key); message.value && (this.value = message.value); message.type && (this.type = message.type); message.extra && (this.extra = message.extra); message.user && (this.user = message.user); } ChrmKVNotificationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ChrmKVNotificationMessage; })(); RongIMLib.ChrmKVNotificationMessage = ChrmKVNotificationMessage; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var ChannelInfo = (function () { function ChannelInfo(Id, Key) { this.Id = Id; this.Key = Key; } return ChannelInfo; })(); RongIMLib.ChannelInfo = ChannelInfo; var UserStatus = (function () { function UserStatus(platform, online, status) { this.platform = platform; this.online = online; this.status = status; } return UserStatus; })(); RongIMLib.UserStatus = UserStatus; var MentionedInfo = (function () { function MentionedInfo(type, userIdList, mentionedContent) { } return MentionedInfo; })(); RongIMLib.MentionedInfo = MentionedInfo; var DeleteMessage = (function () { function DeleteMessage(msgId, msgDataTime, direct) { this.msgId = msgId; this.msgDataTime = msgDataTime; this.direct = direct; } return DeleteMessage; })(); RongIMLib.DeleteMessage = DeleteMessage; var CustomServiceConfig = (function () { function CustomServiceConfig(isBlack, companyName, companyUrl) { } return CustomServiceConfig; })(); RongIMLib.CustomServiceConfig = CustomServiceConfig; var CustomServiceSession = (function () { function CustomServiceSession(uid, cid, pid, isQuited, type, adminHelloWord, adminOfflineWord) { } return CustomServiceSession; })(); RongIMLib.CustomServiceSession = CustomServiceSession; var Conversation = (function () { function Conversation(conversationTitle, conversationType, draft, isTop, latestMessage, latestMessageId, notificationStatus, objectName, receivedStatus, receivedTime, senderUserId, senderUserName, sentStatus, sentTime, targetId, unreadMessageCount, senderPortraitUri, isHidden, mentionedMsg, hasUnreadMention, _readTime) { this.conversationTitle = conversationTitle; this.conversationType = conversationType; this.draft = draft; this.isTop = isTop; this.latestMessage = latestMessage; this.latestMessageId = latestMessageId; this.notificationStatus = notificationStatus; this.objectName = objectName; this.receivedStatus = receivedStatus; this.receivedTime = receivedTime; this.senderUserId = senderUserId; this.senderUserName = senderUserName; this.sentStatus = sentStatus; this.sentTime = sentTime; this.targetId = targetId; this.unreadMessageCount = unreadMessageCount; this.senderPortraitUri = senderPortraitUri; this.isHidden = isHidden; this.mentionedMsg = mentionedMsg; this.hasUnreadMention = hasUnreadMention; this._readTime = _readTime; } Conversation.prototype.setTop = function () { RongIMLib.RongIMClient._dataAccessProvider.addConversation(this, { onSuccess: function (data) { } }); }; return Conversation; })(); RongIMLib.Conversation = Conversation; var Discussion = (function () { function Discussion(creatorId, id, memberIdList, name, isOpen) { this.creatorId = creatorId; this.id = id; this.memberIdList = memberIdList; this.name = name; this.isOpen = isOpen; } return Discussion; })(); RongIMLib.Discussion = Discussion; var Group = (function () { function Group(id, name, portraitUri) { this.id = id; this.name = name; this.portraitUri = portraitUri; } return Group; })(); RongIMLib.Group = Group; var Message = (function () { function Message(content, conversationType, extra, objectName, messageDirection, messageId, receivedStatus, receivedTime, senderUserId, sentStatus, sentTime, targetId, messageType, messageUId, isLocalMessage, offLineMessage, receiptResponse) { this.content = content; this.conversationType = conversationType; this.extra = extra; this.objectName = objectName; this.messageDirection = messageDirection; this.messageId = messageId; this.receivedStatus = receivedStatus; this.receivedTime = receivedTime; this.senderUserId = senderUserId; this.sentStatus = sentStatus; this.sentTime = sentTime; this.targetId = targetId; this.messageType = messageType; this.messageUId = messageUId; this.isLocalMessage = isLocalMessage; this.offLineMessage = offLineMessage; this.receiptResponse = receiptResponse; } return Message; })(); RongIMLib.Message = Message; var MessageTag = (function () { function MessageTag(isCounted, isPersited) { this.isCounted = isCounted; this.isPersited = isPersited; } MessageTag.prototype.getMessageTag = function () { if (this.isCounted && this.isPersited) { return 3; } else if (this.isCounted) { return 2; } else if (this.isPersited) { return 1; } else if (!this.isCounted && !this.isPersited) { return 0; } }; MessageTag.getTagByStatus = function (status) { var statusMap = { 3: { isCounted: true, isPersited: true }, 2: { isCounted: true, isPersited: false }, 1: { isCounted: true, isPersited: true }, 0: { isCounted: true, isPersited: true } }; return statusMap[status] || statusMap[3]; }; return MessageTag; })(); RongIMLib.MessageTag = MessageTag; var PublicServiceMenuItem = (function () { function PublicServiceMenuItem(id, name, type, sunMenuItems, url) { this.id = id; this.name = name; this.type = type; this.sunMenuItems = sunMenuItems; this.url = url; } return PublicServiceMenuItem; })(); RongIMLib.PublicServiceMenuItem = PublicServiceMenuItem; // TODO: TBD var PublicServiceProfile = (function () { function PublicServiceProfile(conversationType, introduction, menu, name, portraitUri, publicServiceId, hasFollowed, isGlobal) { this.conversationType = conversationType; this.introduction = introduction; this.menu = menu; this.name = name; this.portraitUri = portraitUri; this.publicServiceId = publicServiceId; this.hasFollowed = hasFollowed; this.isGlobal = isGlobal; } return PublicServiceProfile; })(); RongIMLib.PublicServiceProfile = PublicServiceProfile; var UserInfo = (function () { function UserInfo(id, name, portraitUri) { this.id = id; this.name = name; this.portraitUri = portraitUri; } return UserInfo; })(); RongIMLib.UserInfo = UserInfo; var User = (function () { function User(id, token) { this.id = id; this.token = token; } return User; })(); RongIMLib.User = User; var Room = (function () { function Room(id, user, mode, broadcastType, type) { this.id = id; this.user = user; this.mode = mode; this.broadcastType = broadcastType; this.type = type; } return Room; })(); RongIMLib.Room = Room; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var ServerDataProvider = (function () { function ServerDataProvider() { this.userStatusListener = null; this.Conversation = { watcher: new RongIMLib.Observer(), watch: function (_watcher) { this.watcher.add(_watcher); var conversationList = RongIMLib.RongIMClient._memoryStore.conversationList; this.watcher.emit(conversationList); }, unwatch: function (_watcher) { this.watcher.remove(_watcher); }, _notify: function (conversationList) { this.watcher.emit(conversationList); } }; } ServerDataProvider.prototype.init = function (appKey, options) { new RongIMLib.FeatureDectector(options.appCallback); }; ServerDataProvider.prototype.connect = function (token, callback, userId, option) { RongIMLib.RongIMClient.bridge = RongIMLib.Bridge.getInstance(); RongIMLib.RongIMClient._memoryStore.token = token; RongIMLib.RongIMClient._memoryStore.callback = callback; userId = userId || ''; option = option || {}; var isConnecting = false, isConnected = false; if (RongIMLib.Bridge._client && RongIMLib.Bridge._client.channel) { isConnecting = (RongIMLib.Bridge._client.channel.connectionStatus == RongIMLib.ConnectionStatus.CONNECTING); isConnected = (RongIMLib.Bridge._client.channel.connectionStatus == RongIMLib.ConnectionStatus.CONNECTED); } if (isConnected || isConnecting) { return; } var isGreater = (RongIMLib.RongIMClient.otherDeviceLoginCount > 5); if (isGreater) { callback.onError(RongIMLib.ConnectionStatus.ULTRALIMIT); return; } // 清除本地导航缓存 if (option.force) { RongIMLib.RongIMClient._storageProvider.removeItem('servers'); } RongIMLib.RongIMClient.bridge.setListener(); RongIMLib.RongIMClient.bridge.connect(RongIMLib.RongIMClient._memoryStore.appKey, token, { onSuccess: function (data) { setTimeout(function () { callback.onSuccess(data); }); }, onError: function (e) { if (e == RongIMLib.ConnectionState.TOKEN_INCORRECT || !e) { setTimeout(function () { callback.onTokenIncorrect(); }); } else { setTimeout(function () { callback.onError(e); }); } } }); }; /* config.auto: 默认 false, true 启用自动重连,启用则为必选参数 config.rate: 重试频率 [100, 1000, 3000, 6000, 10000, 18000] 单位为毫秒,可选 config.url: 网络嗅探地址 [http(s)://]cdn.ronghub.com/RongIMLib-2.2.6.min.js 可选 */ ServerDataProvider.prototype.reconnect = function (callback, config) { var store = RongIMLib.RongIMClient._memoryStore; var token = store.token; if (!token) { throw new Error('reconnect: token is empty.'); } if (RongIMLib.Bridge._client && RongIMLib.Bridge._client.channel && RongIMLib.Bridge._client.channel.connectionStatus != RongIMLib.ConnectionStatus.CONNECTED && RongIMLib.Bridge._client.channel.connectionStatus != RongIMLib.ConnectionStatus.CONNECTING) { config = config || {}; var key = config.auto ? 'auto' : 'custom'; var handler = { auto: function () { var repeatConnect = function (options) { var step = options.step(); var done = 'done'; var url = options.url; var ping = function () { RongIMLib.RongUtil.request({ url: url, success: function () { options.done(); }, error: function () { repeat(); } }); }; var repeat = function () { var next = step(); if (next == 'done') { var error = RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE; options.done(error); return; } setTimeout(ping, next); }; repeat(); }; var protocol = RongIMLib.RongIMClient._memoryStore.depend.protocol; var url = config.url || 'cdn.ronghub.com/RongIMLib-2.2.6.min.js'; var pathConfig = { protocol: protocol, path: url }; url = RongIMLib.RongUtil.formatProtoclPath(pathConfig); var rate = config.rate || [100, 1000, 3000, 6000, 10000, 18000]; //结束标识 rate.push('done'); var opts = { url: url, step: function () { var index = 0; return function () { var time = rate[index]; index++; return time; }; }, done: function (error) { if (error) { callback.onError(error); return; } RongIMLib.RongIMClient.connect(token, callback); } }; repeatConnect(opts); }, custom: function () { RongIMLib.RongIMClient.connect(token, callback); } }; handler[key](); } }; ServerDataProvider.prototype.logout = function () { RongIMLib.RongIMClient.bridge.disconnect(); RongIMLib.RongIMClient.bridge = null; }; ServerDataProvider.prototype.disconnect = function () { RongIMLib.RongIMClient.bridge.disconnect(); }; ServerDataProvider.prototype.sendReceiptResponse = function (conversationType, targetId, sendCallback) { var rspkey = RongIMLib.Bridge._client.userId + conversationType + targetId + 'RECEIVED', me = this; if (RongIMLib.RongUtil.supportLocalStorage()) { var valObj = JSON.parse(RongIMLib.RongIMClient._storageProvider.getItem(rspkey)); if (valObj) { var vals = []; for (var key in valObj) { var tmp = {}; tmp[key] = valObj[key].uIds; valObj[key].isResponse || vals.push(tmp); } if (vals.length == 0) { sendCallback.onSuccess(); return; } var interval = setInterval(function () { if (vals.length == 1) { clearInterval(interval); } var obj = vals.splice(0, 1)[0]; var rspMsg = new RongIMLib.ReadReceiptResponseMessage({ receiptMessageDic: obj }); me.sendMessage(conversationType, targetId, rspMsg, { onSuccess: function (msg) { var senderUserId = RongIMLib.MessageUtil.getFirstKey(obj); valObj[senderUserId].isResponse = true; RongIMLib.RongIMClient._storageProvider.setItem(rspkey, JSON.stringify(valObj)); sendCallback.onSuccess(msg); }, onError: function (error, msg) { sendCallback.onError(error, msg); } }); }, 200); } else { sendCallback.onSuccess(); } } else { sendCallback.onSuccess(); } }; ServerDataProvider.prototype.sendTypingStatusMessage = function (conversationType, targetId, messageName, sendCallback) { var me = this; if (messageName in RongIMLib.RongIMClient.MessageParams) { me.sendMessage(conversationType, targetId, RongIMLib.TypingStatusMessage.obtain(RongIMLib.RongIMClient.MessageParams[messageName].objectName, ""), { onSuccess: function () { setTimeout(function () { sendCallback.onSuccess(); }); }, onError: function (errorCode) { setTimeout(function () { sendCallback.onError(errorCode, null); }); }, onBefore: function () { } }); } }; ServerDataProvider.prototype.sendRecallMessage = function (content, sendMessageCallback) { var msg = new RongIMLib.RecallCommandMessage({ conversationType: content.conversationType, targetId: content.targetId, sentTime: content.sentTime, messageUId: content.messageUId, extra: content.extra, user: content.user }); this.sendMessage(content.conversationType, content.senderUserId, msg, sendMessageCallback, false, null, null, 2); }; ServerDataProvider.prototype.sendTextMessage = function (conversationType, targetId, content, sendMessageCallback) { var msgContent = RongIMLib.TextMessage.obtain(content); this.sendMessage(conversationType, targetId, msgContent, sendMessageCallback); }; ServerDataProvider.prototype.getRemoteHistoryMessages = function (conversationType, targetId, timestamp, count, callback, config) { if (count <= 1) { throw new Error("the count must be greater than 1."); } config = config || {}; var order = config.order || 0; var getKey = function () { return [conversationType, targetId, '_', order].join(''); }; var key = getKey(); if (!RongIMLib.RongUtil.isNumber(timestamp)) { timestamp = RongIMLib.RongIMClient._memoryStore.lastReadTime.get(key); } var memoryStore = RongIMLib.RongIMClient._memoryStore; var historyMessageLimit = memoryStore.historyMessageLimit; /* limit 属性: var limit = { time: '时间戳, 最后一次拉取时间', hasMore: '是否还有历史消息, bool 值' }; */ var limit = historyMessageLimit.get(key) || {}; var hasMore = limit.hasMore; var isFecth = (hasMore || limit.time != timestamp); // 正序获取消息时不做限制,防止有新消息导致无法获取 if (!isFecth && order == 0) { return callback.onSuccess([], hasMore); } var modules = new RongIMLib.RongIMClient.Protobuf.HistoryMsgInput(), self = this; modules.setTargetId(targetId); modules.setTime(timestamp); modules.setCount(count); modules.setOrder(order); var topic = HistoryMsgType[conversationType] || HistoryMsgType[RongIMLib.ConversationType.PRIVATE]; RongIMLib.RongIMClient.bridge.queryMsg(topic, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), targetId, { onSuccess: function (data) { var fetchTime = RongIMLib.MessageUtil.int64ToTimestamp(data.syncTime); RongIMLib.RongIMClient._memoryStore.lastReadTime.set(key, fetchTime); historyMessageLimit.set(key, { hasMore: !!data.hasMsg, time: fetchTime }); var list = data.list.reverse(), tempMsg = null, tempDir; var read = RongIMLib.SentStatus.READ; if (RongIMLib.RongUtil.supportLocalStorage()) { for (var i = 0, len = list.length; i < len; i++) { tempMsg = RongIMLib.MessageUtil.messageParser(list[i]); tempDir = JSON.parse(RongIMLib.RongIMClient._storageProvider.getItem(RongIMLib.Bridge._client.userId + tempMsg.messageUId + "SENT")); if (tempDir) { tempMsg.receiptResponse || (tempMsg.receiptResponse = {}); tempMsg.receiptResponse[tempMsg.messageUId] = tempDir.count; } tempMsg.sentStatus = read; tempMsg.targetId = targetId; list[i] = tempMsg; } } else { for (var i = 0, len = list.length; i < len; i++) { var tempMsg = RongIMLib.MessageUtil.messageParser(list[i]); tempMsg.sentStatus = read; list[i] = tempMsg; } } setTimeout(function () { callback.onSuccess(list, !!data.hasMsg); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }, "HistoryMessagesOuput"); }; ServerDataProvider.prototype.hasRemoteUnreadMessages = function (token, callback) { var xss = null; window.RCCallback = function (x) { setTimeout(function () { callback.onSuccess(!!+x.status); }); xss.parentNode.removeChild(xss); }; xss = document.createElement("script"); xss.src = RongIMLib.RongIMClient._memoryStore.depend.api + "/message/exist.js?appKey=" + encodeURIComponent(RongIMLib.RongIMClient._memoryStore.appKey) + "&token=" + encodeURIComponent(token) + "&callBack=RCCallback&_=" + RongIMLib.RongUtil.getTimestamp(); document.body.appendChild(xss); xss.onerror = function () { setTimeout(function () { callback.onError(RongIMLib.ErrorCode.UNKNOWN); }); xss.parentNode.removeChild(xss); }; }; ServerDataProvider.prototype.getRemoteConversationList = function (callback, conversationTypes, count) { var modules = new RongIMLib.RongIMClient.Protobuf.RelationsInput(), self = this; modules.setType(1); if (typeof count == 'undefined') { modules.setCount(0); } else { modules.setCount(count); } RongIMLib.RongIMClient.bridge.queryMsg(26, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (list) { if (list.info) { list.info = list.info.reverse(); for (var i = 0, len = list.info.length; i < len; i++) { RongIMLib.RongIMClient.getInstance().pottingConversation(list.info[i]); } } var conversations = RongIMLib.RongIMClient._memoryStore.conversationList; setTimeout(function () { if (conversationTypes) { return callback.onSuccess(self.filterConversations(conversationTypes, conversations)); } callback.onSuccess(conversations); }); }, onError: function (error) { callback.onError(error); } }, "RelationsOutput"); }; ServerDataProvider.prototype.addMemberToDiscussion = function (discussionId, userIdList, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.ChannelInvitationInput(); modules.setUsers(userIdList); RongIMLib.RongIMClient.bridge.queryMsg(0, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), discussionId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.createDiscussion = function (name, userIdList, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.CreateDiscussionInput(), self = this; modules.setName(name); RongIMLib.RongIMClient.bridge.queryMsg(1, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (discussId) { if (userIdList.length > 0) { self.addMemberToDiscussion(discussId, userIdList, { onSuccess: function () { }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); } setTimeout(function () { callback.onSuccess(discussId); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }, "CreateDiscussionOutput"); }; ServerDataProvider.prototype.getDiscussion = function (discussionId, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.ChannelInfoInput(); modules.setNothing(1); RongIMLib.RongIMClient.bridge.queryMsg(4, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), discussionId, { onSuccess: function (data) { setTimeout(function () { callback.onSuccess(data); }); }, onError: function (errorCode) { setTimeout(function () { callback.onError(errorCode); }); } }, "ChannelInfoOutput"); }; ServerDataProvider.prototype.quitDiscussion = function (discussionId, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.LeaveChannelInput(); modules.setNothing(1); RongIMLib.RongIMClient.bridge.queryMsg(7, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), discussionId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (errorCode) { setTimeout(function () { callback.onError(errorCode); }); } }); }; ServerDataProvider.prototype.removeMemberFromDiscussion = function (discussionId, userId, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.ChannelEvictionInput(); modules.setUser(userId); RongIMLib.RongIMClient.bridge.queryMsg(9, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), discussionId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (errorCode) { setTimeout(function () { callback.onError(errorCode); }); } }); }; ServerDataProvider.prototype.setDiscussionInviteStatus = function (discussionId, status, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.ModifyPermissionInput(); modules.setOpenStatus(status.valueOf()); RongIMLib.RongIMClient.bridge.queryMsg(11, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), discussionId, { onSuccess: function (x) { setTimeout(function () { callback.onSuccess(); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.setDiscussionName = function (discussionId, name, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RenameChannelInput(); modules.setName(name); RongIMLib.RongIMClient.bridge.queryMsg(12, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), discussionId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (errcode) { callback.onError(errcode); } }); }; ServerDataProvider.prototype.joinChatRoom = function (chatroomId, messageCount, callback) { var e = new RongIMLib.RongIMClient.Protobuf.ChrmInput(); e.setNothing(1); RongIMLib.Bridge._client.chatroomId = chatroomId; RongIMLib.RongIMClient.bridge.queryMsg(19, RongIMLib.MessageUtil.ArrayForm(e.toArrayBuffer()), chatroomId, { onSuccess: function () { var navi = RongIMLib.RongIMClient.getInstance().getNavi(); var isOpenKVStorage = navi.kvStorage; if (isOpenKVStorage) { RongIMLib.RongIMClient._dataAccessProvider.pullChatroomEntry(chatroomId, 0, { onSuccess: function (result) { RongIMLib.ChrmKVHandler.setEntries(chatroomId, result); setTimeout(function () { callback.onSuccess(); }); }, onError: function (errorCode) { setTimeout(function () { callback.onError(errorCode); }); } }); } else { setTimeout(function () { callback.onSuccess(); }); } var modules = new RongIMLib.RongIMClient.Protobuf.ChrmPullMsg(); messageCount == 0 && (messageCount = -1); modules.setCount(messageCount); modules.setSyncTime(0); RongIMLib.Bridge._client.queryMessage("chrmPull", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), chatroomId, 1, { onSuccess: function (collection) { var list = collection.list; var sync = RongIMLib.MessageUtil.int64ToTimestamp(collection.syncTime); var latestMessage = list[list.length - 1]; if (latestMessage) { latestMessage = RongIMLib.MessageUtil.messageParser(latestMessage); sync = latestMessage.sentTime; } RongIMLib.RongIMClient._memoryStore.lastReadTime.set(chatroomId + RongIMLib.Bridge._client.userId + "CST", sync); var _client = RongIMLib.Bridge._client; for (var i = 0, mlen = list.length; i < mlen; i++) { var uId = 'R' + list[i].msgId; if (!(uId in _client.cacheMessageIds)) { _client.cacheMessageIds[uId] = true; var cacheUIds = RongIMLib.RongUtil.keys(_client.cacheMessageIds); if (cacheUIds.length > 10) { uId = cacheUIds[0]; delete _client.cacheMessageIds[uId]; } if (RongIMLib.RongIMClient._memoryStore.filterMessages.length > 0) { for (var j = 0, flen = RongIMLib.RongIMClient._memoryStore.filterMessages.length; j < flen; j++) { if (RongIMLib.RongIMClient.MessageParams[RongIMLib.RongIMClient._memoryStore.filterMessages[j]].objectName != list[i].classname) { _client.handler.onReceived(list[i]); } } } else { _client.handler.onReceived(list[i]); } } } }, onError: function (x) { setTimeout(function () { callback.onError(RongIMLib.ErrorCode.CHATROOM_HISMESSAGE_ERROR); }); } }, "DownStreamMessages"); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }, "ChrmOutput"); }; ServerDataProvider.prototype.getChatRoomInfo = function (chatRoomId, count, order, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.QueryChatroomInfoInput(); modules.setCount(count); modules.setOrder(order); RongIMLib.RongIMClient.bridge.queryMsg("queryChrmI", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), chatRoomId, { onSuccess: function (ret) { var userInfos = ret.userInfos; userInfos.forEach(function (item) { item.time = RongIMLib.MessageUtil.int64ToTimestamp(item.time); }); setTimeout(function () { callback.onSuccess(ret); }); }, onError: function (errcode) { setTimeout(function () { callback.onError(errcode); }); } }, "QueryChatroomInfoOutput"); }; ServerDataProvider.prototype.quitChatRoom = function (chatroomId, callback) { var e = new RongIMLib.RongIMClient.Protobuf.ChrmInput(); e.setNothing(1); RongIMLib.RongIMClient.bridge.queryMsg(17, RongIMLib.MessageUtil.ArrayForm(e.toArrayBuffer()), chatroomId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (errcode) { setTimeout(function () { callback.onError(errcode); }); } }, "ChrmOutput"); }; ServerDataProvider.prototype.setChatroomHisMessageTimestamp = function (chatRoomId, timestamp) { RongIMLib.RongIMClient._memoryStore.lastReadTime.set('chrhis_' + chatRoomId, timestamp); }; ServerDataProvider.prototype.getChatRoomHistoryMessages = function (chatRoomId, count, order, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.HistoryMsgInput(); modules.setTargetId(chatRoomId); var timestamp = RongIMLib.RongIMClient._memoryStore.lastReadTime.get('chrhis_' + chatRoomId) || 0; modules.setTime(timestamp); modules.setCount(count); modules.setOrder(order); RongIMLib.RongIMClient.bridge.queryMsg(34, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (data) { RongIMLib.RongIMClient._memoryStore.lastReadTime.set('chrhis_' + chatRoomId, RongIMLib.MessageUtil.int64ToTimestamp(data.syncTime)); var list = data.list.reverse(); for (var i = 0, len = list.length; i < len; i++) { list[i] = RongIMLib.MessageUtil.messageParser(list[i]); } setTimeout(function () { callback.onSuccess(list, !!data.hasMsg); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }, "HistoryMsgOuput"); }; ServerDataProvider.prototype.setChatroomEntry = function (chatroomId, chatroomEntry, callback) { var opt = RongIMLib.ChatroomEntityOpt.UPDATE; var key = chatroomEntry.key, value = chatroomEntry.value; var isKeyInValid = !RongIMLib.RongUtil.isLengthLimit(key, RongIMLib.ChatroomEntityLimit.KEY, 1) || !RongIMLib.ChrmKVHandler.isKeyValid(key); var isValueInValid = !RongIMLib.RongUtil.isLengthLimit(value, RongIMLib.ChatroomEntityLimit.VALUE, 1); if (isKeyInValid || isValueInValid) { setTimeout(function () { callback.onError(RongIMLib.ErrorCode.BIZ_ERROR_INVALID_PARAMETER); }); } else { this.refreshChatroomEntry(chatroomId, chatroomEntry, opt, callback); } }; ServerDataProvider.prototype.forceSetChatroomEntry = function (chatroomId, chatroomEntry, callback) { chatroomEntry.isOverwrite = true; this.setChatroomEntry(chatroomId, chatroomEntry, callback); }; ServerDataProvider.prototype.removeChatroomEntry = function (chatroomId, chatroomEntry, callback) { var opt = RongIMLib.ChatroomEntityOpt.DELETE; var key = chatroomEntry.key; var isKeyInValid = !RongIMLib.RongUtil.isLengthLimit(key, RongIMLib.ChatroomEntityLimit.KEY, 1) || !RongIMLib.ChrmKVHandler.isKeyValid(key); if (isKeyInValid) { setTimeout(function () { callback.onError(RongIMLib.ErrorCode.BIZ_ERROR_INVALID_PARAMETER); }); } else { this.refreshChatroomEntry(chatroomId, chatroomEntry, opt, callback); } }; ServerDataProvider.prototype.forceRemoveChatroomEntry = function (chatroomId, chatroomEntry, callback) { chatroomEntry.isOverwrite = true; this.removeChatroomEntry(chatroomId, chatroomEntry, callback); }; ServerDataProvider.prototype.refreshChatroomEntry = function (chatroomId, chatroomEntry, chatroomEntryOpt, callback) { var modules, topic; var key = chatroomEntry.key, value = chatroomEntry.value || '', extra = chatroomEntry.notificationExtra; if (chatroomEntryOpt === RongIMLib.ChatroomEntityOpt.DELETE) { modules = new RongIMLib.RongIMClient.Protobuf.DeleteChrmKV(); topic = 'delKV'; } else { modules = new RongIMLib.RongIMClient.Protobuf.SetChrmKV(); topic = 'setKV'; } var status = RongIMLib.RongInnerTools.getChrmEntityStatus(chatroomEntry, chatroomEntryOpt); var currentUserId = RongIMLib.RongIMClient.getInstance().getCurrentUserId(); var entry = { key: key, value: value, uid: currentUserId }; if (status) { entry.status = status; } modules.setEntry(entry); if (chatroomEntry.isSendNotification) { modules.setBNotify(true); var msgModules = new RongIMLib.RongIMClient.Protobuf.UpStreamMessage(); var msg = new RongIMLib.ChrmKVNotificationMessage({ key: key, value: value, extra: extra, type: chatroomEntryOpt }); msgModules.setSessionId(RongIMLib.RongIMClient.MessageParams[msg.messageName].msgTag.getMessageTag()); msgModules.setClassname(RongIMLib.RongIMClient.MessageParams[msg.messageName].objectName); msgModules.setContent(msg.encode()); modules.setNotification(msgModules); // 默认设置为 聊天室消息 modules.setType(RongIMLib.ConversationType.CHATROOM); } RongIMLib.RongIMClient.bridge.queryMsg(topic, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), chatroomId, { onSuccess: function (ret) { var currentUserId = RongIMLib.RongIMClient.getInstance().getCurrentUserId(); RongIMLib.ChrmKVHandler.setEntry(chatroomId, chatroomEntry, status, currentUserId); setTimeout(function () { callback.onSuccess(!!ret); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }, 'ChrmOutput'); }; ServerDataProvider.prototype.getChatroomEntry = function (chatroomId, key, callback) { var value = RongIMLib.ChrmKVHandler.getEntityValue(chatroomId, key); setTimeout(function () { if (RongIMLib.RongUtil.isEmpty(value)) { callback.onError(RongIMLib.ErrorCode.CHATROOM_KEY_NOT_EXIST); } else { callback.onSuccess(value); } }); }; ServerDataProvider.prototype.getAllChatroomEntries = function (chatroomId, callback) { setTimeout(function () { var entries = RongIMLib.ChrmKVHandler.getAllEntityValue(chatroomId); callback.onSuccess(entries); }); }; ServerDataProvider.prototype.pullChatroomEntry = function (chatroomId, time, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.QueryChrmKV(); modules.setTimestamp(time); RongIMLib.RongIMClient.bridge.queryMsg('pullKV', RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), chatroomId, { onSuccess: function (data) { setTimeout(function () { callback.onSuccess(data); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }, "ChrmKVOutput"); }; ServerDataProvider.prototype.setMessageStatus = function (conversationType, targetId, timestamp, status, callback) { setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.addToBlacklist = function (userId, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.Add2BlackListInput(); modules.setUserId(userId); RongIMLib.RongIMClient.bridge.queryMsg(21, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.getBlacklist = function (callback) { var modules = new RongIMLib.RongIMClient.Protobuf.QueryBlackListInput(); modules.setNothing(1); RongIMLib.RongIMClient.bridge.queryMsg(23, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (list) { setTimeout(function () { callback.onSuccess(list); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }, "QueryBlackListOutput"); }; ServerDataProvider.prototype.getBlacklistStatus = function (userId, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.BlackListStatusInput(); modules.setUserId(userId); RongIMLib.RongIMClient.bridge.queryMsg(24, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function (status) { setTimeout(function () { callback.onSuccess(RongIMLib.BlacklistStatus[status]); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.removeFromBlacklist = function (userId, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RemoveFromBlackListInput(); modules.setUserId(userId); RongIMLib.RongIMClient.bridge.queryMsg(22, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.getFileToken = function (fileType, callback) { if (!(/(1|2|3|4)/.test(fileType.toString()))) { setTimeout(function () { callback.onError(RongIMLib.ErrorCode.QNTKN_FILETYPE_ERROR); }); return; } var modules = new RongIMLib.RongIMClient.Protobuf.GetQNupTokenInput(); modules.setType(fileType); RongIMLib.RongIMClient.bridge.queryMsg(30, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (data) { setTimeout(function () { callback.onSuccess(data); }); }, onError: function (errcode) { setTimeout(function () { callback.onError(errcode); }); } }, "GetQNupTokenOutput"); }; ServerDataProvider.prototype.getFileUrl = function (fileType, fileName, oriName, callback) { if (!(/(1|2|3|4)/.test(fileType.toString()))) { setTimeout(function () { callback.onError(RongIMLib.ErrorCode.QNTKN_FILETYPE_ERROR); }); return; } var modules = new RongIMLib.RongIMClient.Protobuf.GetQNdownloadUrlInput(); modules.setType(fileType); modules.setKey(fileName); if (oriName) { modules.setFileName(oriName); } RongIMLib.RongIMClient.bridge.queryMsg(31, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (data) { setTimeout(function () { callback.onSuccess(data); }); }, onError: function (errcode) { setTimeout(function () { callback.onError(errcode); }); } }, "GetQNdownloadUrlOutput"); }; ServerDataProvider.prototype.getPullSetting = function (callback) { var modules = new RongIMLib.RongIMClient.Protobuf.PullUserSettingInput(); var version = parseInt(RongIMLib.RongIMClient.sdkver); modules.setVersion(version); RongIMLib.RongIMClient.bridge.queryMsg('pullUS', RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (result) { result = result || {}; result.version = RongIMLib.MessageUtil.int64ToTimestamp(result.version); setTimeout(function () { callback.onSuccess(result); }); }, onError: function (errcode) { setTimeout(function () { callback.onError(errcode); }); } }, 'PullUserSettingOutput'); }; ServerDataProvider.prototype.setOfflineMessageDuration = function (duration, callback) { this.getPullSetting({ onSuccess: function (result) { /** * GetQNupTokenOutput 第一位为 int64, 第二位为 string, 与设置离线消息一致 * 为避免修改 Protobuf 带来的更新成本. 仅复用, 不重新命名 */ var modules = new RongIMLib.RongIMClient.Protobuf.GetQNupTokenOutput(); var version = result.version; modules.setDeadline(version); modules.setToken(duration + ''); RongIMLib.RongIMClient.bridge.queryMsg('setOfflineMsgDur', RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (data) { setTimeout(function () { callback.onSuccess(data); }); }, onError: function (errcode) { setTimeout(function () { callback.onError(errcode); }); } }); }, onError: callback.onError }); }; /* methodType 1 : 多客服(客服后台使用); 2 : 消息撤回 params.userIds : 定向消息接收者 */ ServerDataProvider.prototype.sendMessage = function (conversationType, targetId, messageContent, sendCallback, mentiondMsg, pushText, appData, methodType, params) { if (!RongIMLib.Bridge._client.channel) { setTimeout(function () { sendCallback.onError(RongIMLib.ErrorCode.RC_NET_UNAVAILABLE, null); }); return; } if (!RongIMLib.Bridge._client.channel.socket.socket.connected) { setTimeout(function () { sendCallback.onError(RongIMLib.ErrorCode.TIMEOUT, null); }); throw new Error("connect is timeout! postion:sendMessage"); } var isGroup = (conversationType == RongIMLib.ConversationType.DISCUSSION || conversationType == RongIMLib.ConversationType.GROUP); var modules = new RongIMLib.RongIMClient.Protobuf.UpStreamMessage(); if (mentiondMsg && isGroup) { modules.setSessionId(7); } else { modules.setSessionId(RongIMLib.RongIMClient.MessageParams[messageContent.messageName].msgTag.getMessageTag()); } pushText && modules.setPushText(pushText); appData && modules.setAppData(appData); if (isGroup && messageContent.messageName == RongIMLib.RongIMClient.MessageType["ReadReceiptResponseMessage"]) { var rspMsg = messageContent; if (rspMsg.receiptMessageDic) { var ids = []; for (var key in rspMsg.receiptMessageDic) { ids.push(key); } modules.setUserId(ids); } } if (isGroup && messageContent.messageName == RongIMLib.RongIMClient.MessageType["SyncReadStatusMessage"]) { modules.setUserId(RongIMLib.Bridge._client.userId); } params = params || {}; var userIds = params.userIds; if (userIds) { modules.setUserId(userIds); } var flag = 0; if (params.isPush || params.isVoipPush) { flag |= 0x01; } if (params.isFilerWhiteBlacklist) { flag |= 0x02; } modules.setConfigFlag(flag); modules.setClassname(RongIMLib.RongIMClient.MessageParams[messageContent.messageName].objectName); modules.setContent(messageContent.encode()); var content = modules.toArrayBuffer(); if (Object.prototype.toString.call(content) == "[object ArrayBuffer]") { content = [].slice.call(new Int8Array(content)); } var me = this, msg = new RongIMLib.Message(); var c = this.getConversation(conversationType, targetId); if (RongIMLib.RongIMClient.MessageParams[messageContent.messageName].msgTag.getMessageTag() == 3) { if (!c) { c = RongIMLib.RongIMClient.getInstance().createConversation(conversationType, targetId, ""); } c.sentTime = new Date().getTime(); c.sentStatus = RongIMLib.SentStatus.SENDING; c.senderUserName = ""; c.senderUserId = RongIMLib.Bridge._client.userId; c.notificationStatus = RongIMLib.ConversationNotificationStatus.DO_NOT_DISTURB; c.latestMessage = msg; c.unreadMessageCount = 0; RongIMLib.RongIMClient._dataAccessProvider.addConversation(c, { onSuccess: function (data) { } }); } RongIMLib.RongIMClient._memoryStore.converStore = c; msg.content = messageContent; msg.conversationType = conversationType; msg.senderUserId = RongIMLib.Bridge._client.userId; msg.objectName = RongIMLib.RongIMClient.MessageParams[messageContent.messageName].objectName; msg.targetId = targetId; msg.sentTime = new Date().getTime(); msg.messageDirection = RongIMLib.MessageDirection.SEND; msg.sentStatus = RongIMLib.SentStatus.SENT; msg.messageType = messageContent.messageName; RongIMLib.RongIMClient.bridge.pubMsg(conversationType.valueOf(), content, targetId, { onSuccess: function (data) { if (data && data.timestamp) { RongIMLib.RongIMClient._memoryStore.lastReadTime.set('converST_' + RongIMLib.Bridge._client.userId + conversationType + targetId, data.timestamp); } if ((conversationType == RongIMLib.ConversationType.DISCUSSION || conversationType == RongIMLib.ConversationType.GROUP) && messageContent.messageName == RongIMLib.RongIMClient.MessageType["ReadReceiptRequestMessage"]) { var reqMsg = msg.content; var sentkey = RongIMLib.Bridge._client.userId + reqMsg.messageUId + "SENT"; RongIMLib.RongIMClient._storageProvider.setItem(sentkey, JSON.stringify({ count: 0, dealtime: data.timestamp, userIds: {} })); } if (RongIMLib.RongIMClient.MessageParams[msg.messageType].msgTag.getMessageTag() == 3) { var cacheConversation = RongIMLib.RongIMClient._memoryStore.converStore; cacheConversation.sentStatus = msg.sentStatus; cacheConversation.latestMessage = msg; me.updateConversation(cacheConversation); var Conversation = RongIMLib.RongIMClient._dataAccessProvider.Conversation; Conversation._notify(RongIMLib.RongIMClient._memoryStore.conversationList); RongIMLib.RongIMClient._dataAccessProvider.addMessage(conversationType, targetId, msg, { onSuccess: function (ret) { msg = ret; msg.messageUId = data.messageUId; msg.sentTime = data.timestamp; msg.sentStatus = RongIMLib.SentStatus.SENT; msg.messageId = data.messageId; RongIMLib.RongIMClient._dataAccessProvider.updateMessage(msg); }, onError: function () { } }); } setTimeout(function () { cacheConversation && me.updateConversation(cacheConversation); msg.sentTime = data.timestamp; msg.messageUId = data.messageUId; sendCallback.onSuccess(msg); }); }, onError: function (errorCode, _msg) { msg.sentStatus = RongIMLib.SentStatus.FAILED; if (_msg) { msg.messageUId = _msg.messageUId; msg.sentTime = _msg.sentTime; } if (RongIMLib.RongIMClient.MessageParams[msg.messageType].msgTag.getMessageTag() == 3) { RongIMLib.RongIMClient._memoryStore.converStore.latestMessage = msg; } RongIMLib.RongIMClient._dataAccessProvider.addMessage(conversationType, targetId, msg, { onSuccess: function (ret) { msg.messageId = ret.messageId; RongIMLib.RongIMClient._dataAccessProvider.updateMessage(msg); }, onError: function () { } }); setTimeout(function () { sendCallback.onError(errorCode, msg); }); } }, null, methodType); sendCallback.onBefore && sendCallback.onBefore(RongIMLib.MessageIdHandler.messageId); msg.messageId = RongIMLib.MessageIdHandler.messageId + ""; }; ServerDataProvider.prototype.setConnectionStatusListener = function (listener) { if (RongIMLib.RongUtil.isObject(listener) && RongIMLib.RongUtil.isFunction(listener.onChanged)) { RongIMLib.RongIMClient.statusListeners.push(listener.onChanged); } }; ServerDataProvider.prototype.setOnReceiveMessageListener = function (listener) { if (RongIMLib.RongUtil.isObject(listener) && RongIMLib.RongUtil.isFunction(listener.onReceived)) { RongIMLib.RongIMClient.messageListeners.push(listener.onReceived); } }; ServerDataProvider.prototype.registerMessageType = function (messageType, objectName, messageTag, messageContent, searchProps) { if (!messageType) { throw new Error("messageType can't be empty,postion -> registerMessageType"); } if (!objectName) { throw new Error("objectName can't be empty,postion -> registerMessageType"); } if (Object.prototype.toString.call(messageContent) == "[object Array]") { var regMsg = RongIMLib.ModelUtil.modleCreate(messageContent, messageType); RongIMLib.RongIMClient.RegisterMessage[messageType] = regMsg; } else if (Object.prototype.toString.call(messageContent) == "[object Function]" || Object.prototype.toString.call(messageContent) == "[object Object]") { if (!messageContent.encode) { throw new Error("encode method has not realized or messageName is undefined-> registerMessageType"); } if (!messageContent.decode) { throw new Error("decode method has not realized -> registerMessageType"); } } else { throw new Error("The index of 3 parameter was wrong type must be object or function or array-> registerMessageType"); } registerMessageTypeMapping[objectName] = messageType; }; ServerDataProvider.prototype.registerMessageTypes = function (messages) { var types = []; var getProtos = function (proto) { var protos = []; for (var p in proto) { protos.push(p); } return protos; }; //转换消息为自定义消息参数格式 for (var name in messages) { var message = messages[name]; var proto = message.proto; var protos = getProtos(proto); var flag = message.flag || 3; var tag = RongIMLib.MessageTag.getTagByStatus(flag); flag = new RongIMLib.MessageTag(tag.isCounted, tag.isPersited); types.push({ type: name, name: message.name, flag: flag, protos: protos }); } var register = function (message) { var type = message.type; var name = message.name; var flag = message.flag; var protos = message.protos; RongIMLib.RongIMClient.registerMessageType(type, name, flag, protos); }; for (var i = 0, len = types.length; i < len; i++) { var message = types[i]; register(message); } }; ServerDataProvider.prototype.addConversation = function (conversation, callback) { var isAdd = true; for (var i = 0, len = RongIMLib.RongIMClient._memoryStore.conversationList.length; i < len; i++) { if (RongIMLib.RongIMClient._memoryStore.conversationList[i].conversationType === conversation.conversationType && RongIMLib.RongIMClient._memoryStore.conversationList[i].targetId === conversation.targetId) { // RongIMClient._memoryStore.conversationList[i] = conversation; RongIMLib.RongIMClient._memoryStore.conversationList.unshift(RongIMLib.RongIMClient._memoryStore.conversationList.splice(i, 1)[0]); isAdd = false; break; } } if (isAdd) { RongIMLib.RongIMClient._memoryStore.conversationList.unshift(conversation); } callback && callback.onSuccess(true); }; ServerDataProvider.prototype.updateConversation = function (conversation) { var conver; for (var i = 0, len = RongIMLib.RongIMClient._memoryStore.conversationList.length; i < len; i++) { var item = RongIMLib.RongIMClient._memoryStore.conversationList[i]; if (conversation.conversationType === item.conversationType && conversation.targetId === item.targetId) { conversation.conversationTitle && (item.conversationTitle = conversation.conversationTitle); conversation.senderUserName && (item.senderUserName = conversation.senderUserName); conversation.senderPortraitUri && (item.senderPortraitUri = conversation.senderPortraitUri); conversation.latestMessage && (item.latestMessage = conversation.latestMessage); conversation.sentStatus && (item.sentStatus = conversation.sentStatus); break; } } return conver; }; ServerDataProvider.prototype.removeConversation = function (conversationType, targetId, callback) { var mod = new RongIMLib.RongIMClient.Protobuf.RelationsInput(); mod.setType(conversationType); RongIMLib.RongIMClient.bridge.queryMsg(27, RongIMLib.MessageUtil.ArrayForm(mod.toArrayBuffer()), targetId, { onSuccess: function () { var isRemoved = false; var conversations = RongIMLib.RongIMClient._memoryStore.conversationList; var len = conversations.length; for (var i = 0; i < len; i++) { if (conversations[i].conversationType == conversationType && targetId == conversations[i].targetId) { conversations.splice(i, 1); isRemoved = true; break; } } isRemoved && RongIMLib.RongIMClient._dataAccessProvider.Conversation._notify(RongIMLib.RongIMClient._memoryStore.conversationList); callback.onSuccess(true); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.getMessage = function (messageId, callback) { callback.onSuccess(new RongIMLib.Message()); }; ServerDataProvider.prototype.addMessage = function (conversationType, targetId, message, callback) { if (callback) { callback.onSuccess(message); } }; ServerDataProvider.prototype.removeMessage = function (conversationType, targetId, messages, callback) { RongIMLib.RongIMClient.getInstance().deleteRemoteMessages(conversationType, targetId, messages, callback); }; ServerDataProvider.prototype.removeLocalMessage = function (conversationType, targetId, timestamps, callback) { callback.onSuccess(true); }; ServerDataProvider.prototype.updateMessage = function (message, callback) { if (callback) { callback.onSuccess(message); } }; ServerDataProvider.prototype.deleteRemoteMessages = function (conversationType, targetId, messages, callback) { if (!RongIMLib.RongIMClient.Protobuf.DeleteMsgInput) { throw new Error('SDK Protobuf version is too low'); } var modules = new RongIMLib.RongIMClient.Protobuf.DeleteMsgInput(); var msgs = []; RongIMLib.RongUtil.forEach(messages, function (msg) { msgs.push({ msgId: msg.messageUId, msgDataTime: msg.sentTime, direct: msg.messageDirection }); }); modules.setType(conversationType); modules.setConversationId(targetId); modules.setMsgs(msgs); RongIMLib.RongIMClient.bridge.queryMsg('delMsg', RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), targetId, { onSuccess: function (result) { callback.onSuccess(result); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }, 'DeleteMsgOutput'); }; ServerDataProvider.prototype.clearRemoteHistoryMessages = function (params, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.CleanHisMsgInput(); var conversationType = params.conversationType; var _topic = { 1: 'cleanPMsg', 2: 'cleanDMsg', 3: 'cleanGMsg', 5: 'cleanCMsg', 6: 'cleanSMsg' }; var topic = _topic[conversationType]; if (!topic) { callback.onError(RongIMLib.ErrorCode.CLEAR_HIS_TYPE_ERROR); return; } var timestamp = params.timestamp; if (typeof timestamp != 'number') { callback.onError(RongIMLib.ErrorCode.CLEAR_HIS_TIME_ERROR); return; } modules.setDataTime(timestamp); var targetId = params.targetId; modules.setTargetId(targetId); RongIMLib.RongIMClient.bridge.queryMsg(topic, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), targetId, { onSuccess: function (result) { callback.onSuccess(!result); }, onError: function (error) { // error 1 历史消息云存储没有开通、传入时间大于服务器时间 清除失败,1 与其他错误码冲突,所以自定义错误码返回 if (error == 1) { error = RongIMLib.ErrorCode.CLEAR_HIS_ERROR; } setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.clearHistoryMessages = function (params, callback) { this.clearRemoteHistoryMessages(params, callback); }; // 兼容老版本 ServerDataProvider.prototype.clearMessages = function (conversationType, targetId, callback) { }; ServerDataProvider.prototype.updateMessages = function (conversationType, targetId, key, value, callback) { var me = this; if (key == "readStatus") { if (RongIMLib.RongIMClient._memoryStore.conversationList.length > 0) { me.getConversationList({ onSuccess: function (list) { Array.forEach(list, function (conver) { if (conver.conversationType == conversationType && conver.targetId == targetId) { conver.unreadMessageCount = 0; } }); }, onError: function (errorCode) { setTimeout(function () { callback.onError(errorCode); }); } }, null); } } setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.getConversation = function (conversationType, targetId, callback) { var conver = null; for (var i = 0, len = RongIMLib.RongIMClient._memoryStore.conversationList.length; i < len; i++) { if (RongIMLib.RongIMClient._memoryStore.conversationList[i].conversationType == conversationType && RongIMLib.RongIMClient._memoryStore.conversationList[i].targetId == targetId) { conver = RongIMLib.RongIMClient._memoryStore.conversationList[i]; if (RongIMLib.RongUtil.supportLocalStorage()) { // var count = RongIMClient._storageProvider.getItem("cu" + Bridge._client.userId + conversationType + targetId); var count = RongIMLib.UnreadCountHandler.get(conversationType, targetId); if (conver.unreadMessageCount == 0) { conver.unreadMessageCount = Number(count); } } } } setTimeout(function () { callback && callback.onSuccess(conver); }); return conver; }; ServerDataProvider.prototype.filterConversations = function (types, list) { var conversaions = []; RongIMLib.RongUtil.forEach(types, function (type) { RongIMLib.RongUtil.forEach(list, function (conversation) { if (conversation.conversationType == type) { conversaions.push(conversation); } }); }); return conversaions; }; ServerDataProvider.prototype.getConversationList = function (callback, conversationTypes, count, isHidden) { var that = this; var isSync = RongIMLib.RongIMClient._memoryStore.isSyncRemoteConverList; var list = RongIMLib.RongIMClient._memoryStore.conversationList; var isLocalInclude = list.length > count; if (!isSync && isLocalInclude) { setTimeout(function () { var localList = list.slice(0, count); if (conversationTypes) { localList = that.filterConversations(conversationTypes, localList); } callback.onSuccess(localList); }); return; } RongIMLib.RongIMClient.getInstance().getRemoteConversationList({ onSuccess: function (list) { if (RongIMLib.RongUtil.supportLocalStorage()) { Array.forEach(RongIMLib.RongIMClient._memoryStore.conversationList, function (item) { // var count = RongIMClient._storageProvider.getItem("cu" + Bridge._client.userId + item.conversationType + item.targetId); var count = RongIMLib.UnreadCountHandler.get(item.conversationType, item.targetId); if (item.unreadMessageCount == 0) { item.unreadMessageCount = Number(count); } }); } RongIMLib.RongIMClient._memoryStore.isSyncRemoteConverList = false; setTimeout(function () { callback.onSuccess(list); }); }, onError: function (errorcode) { setTimeout(function () { callback.onError(errorcode); }); } }, conversationTypes, count, isHidden); }; ServerDataProvider.prototype.clearCache = function () { var memoryStore = RongIMLib.RongIMClient._memoryStore || {}; memoryStore.conversationList = []; memoryStore.isSyncRemoteConverList = true; }; ServerDataProvider.prototype.clearConversations = function (conversationTypes, callback) { Array.forEach(conversationTypes, function (conversationType) { Array.forEach(RongIMLib.RongIMClient._memoryStore.conversationList, function (conver) { if (conversationType == conver.conversationType) { RongIMLib.RongIMClient.getInstance().removeConversation(conver.conversationType, conver.targetId, { onSuccess: function () { }, onError: function () { } }); } }); }); setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.setMessageContent = function (messageId, content, objectname) { }; ; ServerDataProvider.prototype.setMessageSearchField = function (messageId, content, searchFiles) { }; ; ServerDataProvider.prototype.getHistoryMessages = function (conversationType, targetId, timestamp, count, callback, objectname, order) { var config = { objectname: objectname, order: order }; RongIMLib.RongIMClient.getInstance().getRemoteHistoryMessages(conversationType, targetId, timestamp, count, callback, config); }; ServerDataProvider.prototype.getTotalUnreadCount = function (callback, conversationTypes) { var count = RongIMLib.UnreadCountHandler.getAll(conversationTypes); callback.onSuccess(count); }; ServerDataProvider.prototype.getConversationUnreadCount = function (conversationTypes, callback) { var count = 0; Array.forEach(conversationTypes, function (converType) { Array.forEach(RongIMLib.RongIMClient._memoryStore.conversationList, function (conver) { if (conver.conversationType == converType) { count += conver.unreadMessageCount; } }); }); setTimeout(function () { callback.onSuccess(count); }); }; //由于 Web 端未读消息数按会话统计,撤回消息会导致未读数不准确,提供设置未读数接口,桌面版不实现此方法 ServerDataProvider.prototype.setUnreadCount = function (conversationType, targetId, count, sentTime) { sentTime = sentTime || new Date().getTime(); RongIMLib.UnreadCountHandler.set(conversationType, targetId, count, sentTime); }; ServerDataProvider.prototype.getUnreadCount = function (conversationType, targetId, callback) { var unreadCount = RongIMLib.UnreadCountHandler.get(conversationType, targetId); setTimeout(function () { callback.onSuccess(unreadCount || 0); }); }; ServerDataProvider.prototype.cleanMentioneds = function (conver) { if (conver) { conver.mentionedMsg = null; var targetId = conver.targetId; var conversationType = conver.conversationType; var mentioneds = RongIMLib.RongIMClient._storageProvider.getItem("mentioneds_" + RongIMLib.Bridge._client.userId + '_' + conversationType + '_' + targetId); if (mentioneds) { var info = JSON.parse(mentioneds); delete info[conversationType + "_" + targetId]; if (!RongIMLib.MessageUtil.isEmpty(info)) { RongIMLib.RongIMClient._storageProvider.setItem("mentioneds_" + RongIMLib.Bridge._client.userId + '_' + conversationType + '_' + targetId, JSON.stringify(info)); } else { RongIMLib.RongIMClient._storageProvider.removeItem("mentioneds_" + RongIMLib.Bridge._client.userId + '_' + conversationType + '_' + targetId); } } } }; ServerDataProvider.prototype.clearUnreadCountByTimestamp = function (conversationType, targetId, timestamp, callback) { setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.clearUnreadCount = function (conversationType, targetId, callback) { var me = this; // RongIMClient._storageProvider.removeItem("cu" + Bridge._client.userId + conversationType + targetId); RongIMLib.UnreadCountHandler.remove(conversationType, targetId); this.getConversation(conversationType, targetId, { onSuccess: function (conver) { conver = conver || new RongIMLib.Conversation(); var isNotifyConversation = conver.unreadMessageCount; if (conver) { conver.unreadMessageCount = 0; me.cleanMentioneds(conver); } setTimeout(function () { callback.onSuccess(true); isNotifyConversation && RongIMLib.RongIMClient._dataAccessProvider.Conversation._notify(RongIMLib.RongIMClient._memoryStore.conversationList); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.clearTotalUnreadCount = function (callback) { var list = RongIMLib.RongIMClient._memoryStore.conversationList; var me = this; var isNotifyConversation = false; if (list) { // 清除 mentioneds、清除 list 中的 unreadMessageCount for (var i = 0; i < list.length; i++) { var conver = list[i]; if (conver) { isNotifyConversation = conver.unreadMessageCount ? true : isNotifyConversation; conver.unreadMessageCount = 0; me.cleanMentioneds(conver); } } } RongIMLib.UnreadCountHandler.clear(); setTimeout(function () { callback.onSuccess(true); isNotifyConversation && RongIMLib.RongIMClient._dataAccessProvider.Conversation._notify(RongIMLib.RongIMClient._memoryStore.conversationList); }); }; ServerDataProvider.prototype.setConversationToTop = function (conversationType, targetId, isTop, callback) { var me = this; this.getConversation(conversationType, targetId, { onSuccess: function (conver) { conver.isTop = isTop; me.addConversation(conver, callback); setTimeout(function () { callback.onSuccess(true); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.getConversationNotificationStatus = function (params, callback) { var targetId = params.targetId; var conversationType = params.conversationType; var notification = RongIMLib.RongIMClient._memoryStore.notification; var getKey = function () { return conversationType + '_' + targetId; }; var key = getKey(); var status = notification[key]; if (typeof status == 'number') { callback.onSuccess(status); return; } var topics = { 1: 'qryPPush', 3: 'qryDPush' }; var topic = topics[conversationType]; if (!topic) { var error = 8001; callback.onError(error); return; } var modules = new RongIMLib.RongIMClient.Protobuf.BlockPushInput(); modules.setBlockeeId(targetId); var userId = RongIMLib.Bridge._client.userId; var success = function (status) { notification[key] = status; setTimeout(function () { callback.onSuccess(status); }); }; RongIMLib.RongIMClient.bridge.queryMsg(topic, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function (status) { success(status); }, onError: function (e) { if (e == 1) { success(e); } else { setTimeout(function () { callback.onError(e); }); } } }); }; ServerDataProvider.prototype.setConversationNotificationStatus = function (params, callback) { var conversationType = params.conversationType; var targetId = params.targetId; var status = params.status; var getKey = function () { return conversationType + '_' + status; }; var topics = { '1_1': 'blkPPush', '3_1': 'blkDPush', '1_0': 'unblkPPush', '3_0': 'unblkDPush' }; var key = getKey(); var notification = RongIMLib.RongIMClient._memoryStore.notification; notification[key] = status; var topic = topics[key]; if (!topic) { var error = 8001; setTimeout(function () { callback.onError(error); }); return; } var modules = new RongIMLib.RongIMClient.Protobuf.BlockPushInput(); modules.setBlockeeId(targetId); var userId = RongIMLib.Bridge._client.userId; RongIMLib.RongIMClient.bridge.queryMsg(topic, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function (status) { setTimeout(function () { callback.onSuccess(status); }); }, onError: function (e) { setTimeout(function () { callback.onError(e); }); } }); }; ServerDataProvider.prototype.getUserStatus = function (userId, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.GetUserStatusInput(); userId = RongIMLib.Bridge._client.userId; RongIMLib.RongIMClient.bridge.queryMsg(35, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function (status) { status = RongIMLib.RongInnerTools.convertUserStatus(status); setTimeout(function () { callback.onSuccess(status); }); }, onError: function (e) { setTimeout(function () { callback.onError(e); }); } }, 'GetUserStatusOutput'); // callback.onSuccess(new UserStatus()); }; ServerDataProvider.prototype.setUserStatus = function (status, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.SetUserStatusInput(); var userId = RongIMLib.Bridge._client.userId; if (status) { modules.setStatus(status); } RongIMLib.RongIMClient.bridge.queryMsg(36, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function (status) { setTimeout(function () { callback.onSuccess(true); }); }, onError: function (e) { setTimeout(function () { callback.onError(e); }); } }, 'SetUserStatusOutput'); }; ServerDataProvider.prototype.subscribeUserStatus = function (userIds, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.SubUserStatusInput(); var userId = RongIMLib.Bridge._client.userId; modules.setUserid(userIds); RongIMLib.RongIMClient.bridge.queryMsg(37, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function (status) { setTimeout(function () { callback && callback.onSuccess(true); }); }, onError: function (e) { setTimeout(function () { callback && callback.onError(e); }); } }, 'SubUserStatusOutput'); }; ServerDataProvider.prototype.setUserStatusListener = function (params, callback) { RongIMLib.RongIMClient.userStatusListener = callback; var userIds = params.userIds || []; if (userIds.length) { RongIMLib.RongIMClient._dataAccessProvider.subscribeUserStatus(userIds); } }; ServerDataProvider.prototype.clearListeners = function () { }; ServerDataProvider.prototype.setServerInfo = function (info) { }; ServerDataProvider.prototype.getUnreadMentionedMessages = function (conversationType, targetId) { return null; }; ServerDataProvider.prototype.setConversationHidden = function (conversationType, targetId, isHidden) { }; ServerDataProvider.prototype.setMessageExtra = function (messageId, value, callback) { setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.setMessageReceivedStatus = function (messageId, receivedStatus, callback) { setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.setMessageSentStatus = function (messageId, sentStatus, callback) { setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.getAllConversations = function (callback) { setTimeout(function () { callback.onSuccess([]); }); }; ServerDataProvider.prototype.getConversationByContent = function (keywords, callback) { setTimeout(function () { callback.onSuccess([]); }); }; ServerDataProvider.prototype.getMessagesFromConversation = function (conversationType, targetId, keywords, callback) { setTimeout(function () { callback.onSuccess([]); }); }; ServerDataProvider.prototype.searchConversationByContent = function (keyword, callback, conversationTypes) { setTimeout(function () { callback.onSuccess([]); }); }; ServerDataProvider.prototype.searchMessageByContent = function (conversationType, targetId, keyword, timestamp, count, total, callback) { setTimeout(function () { callback.onSuccess([]); }); }; ServerDataProvider.prototype.getDelaTime = function () { return RongIMLib.RongIMClient._memoryStore.deltaTime; }; ServerDataProvider.prototype.getCurrentConnectionStatus = function () { var client = RongIMLib.Bridge._client || {}; var channel = client.channel || {}; var status = RongIMLib.ConnectionStatus.CONNECTION_CLOSED; if (typeof channel.connectionStatus == 'number') { status = channel.connectionStatus; } return status; }; ServerDataProvider.prototype.getAgoraDynamicKey = function (engineType, channelName, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.VoipDynamicInput(); modules.setEngineType(engineType); modules.setChannelName(channelName); RongIMLib.RongIMClient.bridge.queryMsg(32, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (result) { setTimeout(function () { callback.onSuccess(result); }); }, onError: function (errorCode) { setTimeout(function () { callback.onError(errorCode); }); } }, "VoipDynamicOutput"); }; ServerDataProvider.prototype.setDeviceInfo = function (deviceId) { }; ServerDataProvider.prototype.setEnvironment = function (isPrivate) { }; ServerDataProvider.prototype.clearData = function () { return true; }; ServerDataProvider.prototype.getPublicServiceProfile = function (publicServiceType, publicServiceId, callback) { var profile = RongIMLib.RongIMClient._memoryStore.publicServiceMap.get(publicServiceType, publicServiceId); setTimeout(function () { callback.onSuccess(profile); }); }; ServerDataProvider.prototype.getRemotePublicServiceList = function (callback, pullMessageTime) { if (RongIMLib.RongIMClient._memoryStore.depend.openMp) { var modules = new RongIMLib.RongIMClient.Protobuf.PullMpInput(), self = this; if (!pullMessageTime) { modules.setTime(0); } else { modules.setTime(pullMessageTime); } modules.setMpid(""); RongIMLib.RongIMClient.bridge.queryMsg(28, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (data) { //TODO 找出最大时间 // self.lastReadTime.set(conversationType + targetId, MessageUtil.int64ToTimestamp(data.syncTime)); RongIMLib.RongIMClient._memoryStore.publicServiceMap.publicServiceList.length = 0; RongIMLib.RongIMClient._memoryStore.publicServiceMap.publicServiceList = data; setTimeout(function () { callback && callback.onSuccess(data); }); }, onError: function (errorCode) { setTimeout(function () { callback && callback.onError(errorCode); }); } }, "PullMpOutput"); } }; ServerDataProvider.prototype.getRTCUserInfoList = function (room, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcQueryListInput(); // 1 是正序,2是倒序 modules.setOrder(2); RongIMLib.RongIMClient.bridge.queryMsg("rtcUData", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function (result) { var users = {}; var list = result.list; RongIMLib.RongUtil.forEach(list, function (item) { var userId = item.userId; var tmpData = {}; RongIMLib.RongUtil.forEach(item.userData, function (data) { var key = data.key; var value = data.value; tmpData[key] = value; }); users[userId] = tmpData; }); callback.onSuccess(users); }, onError: function (errorCode) { callback.onError(errorCode); } }, "RtcUserListOutput"); }; ServerDataProvider.prototype.getRTCUserList = function (room, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcQueryListInput(); modules.setOrder(2); RongIMLib.RongIMClient.bridge.queryMsg("rtcUList", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function (result) { callback.onSuccess({ users: result.list }); }, onError: function (errorCode) { callback.onError(errorCode); } }, "RtcUserListOutput"); }; ServerDataProvider.prototype.setRTCUserInfo = function (room, info, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcValueInfo(); modules.setKey(info.key); modules.setValue(info.value); RongIMLib.RongIMClient.bridge.queryMsg("rtcUPut", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function () { callback.onSuccess(true); }, onError: function (errorCode) { callback.onError(errorCode); } }); }; ServerDataProvider.prototype.removeRTCUserInfo = function (room, info, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcKeyDeleteInput(); var keys = info.keys || []; if (!RongIMLib.RongUtil.isArray(keys)) { keys = [keys]; } modules.setKey(keys); RongIMLib.RongIMClient.bridge.queryMsg("rtcUDel", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function () { callback.onSuccess(true); }, onError: function (errorCode) { callback.onError(errorCode); } }); }; ServerDataProvider.prototype.getRTCRoomInfo = function (room, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcQueryListInput(); modules.setOrder(2); RongIMLib.RongIMClient.bridge.queryMsg("rtcRInfo", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function (result) { var room = { id: result.roomId, total: result.userCount }; RongIMLib.RongUtil.forEach(result.roomData, function (data) { room[data.key] = data.value; }); callback.onSuccess(room); }, onError: function (errorCode) { callback.onError(errorCode); } }, "RtcRoomInfoOutput"); }; ServerDataProvider.prototype.setRTCRoomInfo = function (room, info, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcValueInfo(); modules.setKey(info.key); modules.setValue(info.value); RongIMLib.RongIMClient.bridge.queryMsg("rtcRPut", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function () { callback.onSuccess(true); }, onError: function (errorCode) { callback.onError(errorCode); } }); }; ServerDataProvider.prototype.removeRTCRoomInfo = function (room, info, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcKeyDeleteInput(); var keys = info.keys || []; if (!RongIMLib.RongUtil.isArray(keys)) { keys = [keys]; } modules.setKey(keys); RongIMLib.RongIMClient.bridge.queryMsg("rtcRDel", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function () { callback.onSuccess(true); }, onError: function (errorCode) { callback.onError(errorCode); } }); }; ServerDataProvider.prototype.joinRTCRoom = function (room, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcInput(); var mode = room.mode || 0; modules.setRoomType(mode); if (room.broadcastType) { modules.setBroadcastType(room.broadcastType); } RongIMLib.RongIMClient.bridge.queryMsg("rtcRJoin_data", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function (result) { var users = {}; var list = result.list, token = result.token, sessionId = result.sessionId; RongIMLib.RongUtil.forEach(list, function (item) { var userId = item.userId; var tmpData = {}; RongIMLib.RongUtil.forEach(item.userData, function (data) { var key = data.key; var value = data.value; tmpData[key] = value; }); users[userId] = tmpData; }); callback.onSuccess({ users: users, token: token, sessionId: sessionId }); }, onError: function (errorCode) { callback.onError(errorCode); } }, "RtcUserListOutput"); }; ServerDataProvider.prototype.quitRTCRoom = function (room, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.SetUserStatusInput(); RongIMLib.RongIMClient.bridge.queryMsg("rtcRExit", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function () { callback.onSuccess(true); }, onError: function (errorCode) { callback.onError(errorCode); } }); }; ServerDataProvider.prototype.RTCPing = function (room, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcInput(); var mode = room.mode || 0; modules.setRoomType(mode); if (room.broadcastType) { modules.setBroadcastType(room.broadcastType); } RongIMLib.RongIMClient.bridge.queryMsg("rtcPing", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, callback); }; ServerDataProvider.prototype.setRTCData = function (roomId, key, value, isInner, apiType, callback, message) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcSetDataInput(); modules.setInterior(isInner); modules.setTarget(apiType); modules.setKey(key); modules.setValue(value); message = message || {}; var name = message.name; var content = message.content; if (name) { modules.setObjectName(name); } if (content) { if (!RongIMLib.RongUtil.isString(content)) { content = JSON.stringify(content); } modules.setContent(content); } RongIMLib.RongIMClient.bridge.queryMsg("rtcSetData", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), roomId, callback, "RtcOutput"); }; ServerDataProvider.prototype.getRTCData = function (roomId, keys, isInner, apiType, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcDataInput(); modules.setInterior(isInner); modules.setTarget(apiType); modules.setKey(keys); RongIMLib.RongIMClient.bridge.queryMsg("rtcQryData", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), roomId, { onSuccess: function (result) { var props = {}; var list = result.outInfo; RongIMLib.RongUtil.forEach(list, function (item) { props[item.key] = item.value; }); callback.onSuccess(props); }, onError: callback.onError }, "RtcQryOutput"); }; ServerDataProvider.prototype.removeRTCData = function (roomId, keys, isInner, apiType, callback, message) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcDataInput(); modules.setInterior(isInner); modules.setTarget(apiType); modules.setKey(keys); message = message || {}; var name = message.name; var content = message.content; if (name) { modules.setObjectName(name); } if (content) { if (!RongIMLib.RongUtil.isString(content)) { content = JSON.stringify(content); } modules.setContent(content); } RongIMLib.RongIMClient.bridge.queryMsg("rtcDelData", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), roomId, callback, "RtcOutput"); }; ServerDataProvider.prototype.setRTCUserData = function (roomId, key, value, isInner, callback, message) { this.setRTCData(roomId, key, value, isInner, RongIMLib.RTCAPIType.PERSON, callback, message); }; ServerDataProvider.prototype.getRTCUserData = function (roomId, keys, isInner, callback, message) { this.getRTCData(roomId, keys, isInner, RongIMLib.RTCAPIType.PERSON, callback); }; ServerDataProvider.prototype.removeRTCUserData = function (roomId, keys, isInner, callback, message) { this.removeRTCData(roomId, keys, isInner, RongIMLib.RTCAPIType.PERSON, callback, message); }; ServerDataProvider.prototype.setRTCRoomData = function (roomId, key, value, isInner, callback, message) { this.setRTCData(roomId, key, value, isInner, RongIMLib.RTCAPIType.ROOM, callback, message); }; ServerDataProvider.prototype.getRTCRoomData = function (roomId, keys, isInner, callback, message) { this.getRTCData(roomId, keys, isInner, RongIMLib.RTCAPIType.ROOM, callback); }; ServerDataProvider.prototype.removeRTCRoomData = function (roomId, keys, isInner, callback, message) { this.removeRTCData(roomId, keys, isInner, RongIMLib.RTCAPIType.ROOM, callback, message); }; // 信令 SDK 新增 ServerDataProvider.prototype.setRTCOutData = function (roomId, data, type, callback, message) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcSetOutDataInput(); modules.setTarget(type); if (!RongIMLib.RongUtil.isArray(data)) { data = [data]; } for (var i = 0; i < data.length; i++) { var item = data[i]; if (item.key) { item.key = item.key.toString(); } if (item.value) { item.value = item.value.toString(); } } modules.setValueInfo(data); message = message || {}; var name = message.name; var content = message.content; if (name) { modules.setObjectName(name); } if (content) { if (!RongIMLib.RongUtil.isString(content)) { content = JSON.stringify(content); } modules.setContent(content); } RongIMLib.RongIMClient.bridge.queryMsg("rtcSetOutData", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), roomId, callback, "RtcOutput"); }; // 信令 SDK 新增 ServerDataProvider.prototype.getRTCOutData = function (roomId, userIds, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcQryUserOutDataInput(); modules.setUserId(userIds); RongIMLib.RongIMClient.bridge.queryMsg("rtcQryUserOutData", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), roomId, callback, "RtcUserOutDataOutput"); }; ServerDataProvider.prototype.getNavi = function () { var navi = RongIMLib.RongIMClient._storageProvider.getItem("fullnavi") || "{}"; return JSON.parse(navi); }; ServerDataProvider.prototype.getRTCToken = function (room, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcInput(); var mode = room.mode || 0; modules.setRoomType(mode); if (room.broadcastType) { modules.setBroadcastType(room.broadcastType); } RongIMLib.RongIMClient.bridge.queryMsg("rtcToken", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function (result) { callback.onSuccess(result); }, onError: function (errorCode) { callback.onError(errorCode); } }, "RtcTokenOutput"); }; ServerDataProvider.prototype.setRTCState = function (room, content, callback) { // MCFollowInput 为 PB 复用,字段:一个必传 string(第一位) var modules = new RongIMLib.RongIMClient.Protobuf.MCFollowInput(); var report = content.report; modules.setId(report); RongIMLib.RongIMClient.bridge.queryMsg("rtcUserState", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function (result) { callback.onSuccess(result); }, onError: function (errorCode) { callback.onError(errorCode); } }, "RtcOutput"); }; return ServerDataProvider; })(); RongIMLib.ServerDataProvider = ServerDataProvider; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var VCDataProvider = (function () { function VCDataProvider(addon) { this.Conversation = { watcher: new RongIMLib.Observer(), watch: function (_watcher) { }, unwatch: function (_watcher) { }, _notify: function (conversationList) { } }; // C++ 需要的 SDK 版本号 this.version = '2.8.27'; this.userId = ""; this.useConsole = false; this.appKey = ""; this.token = ""; this.addon = addon; } VCDataProvider.prototype.init = function (appKey, config) { this.appKey = appKey; this.useConsole && console.log("init"); config = config || {}; config.version = this.version; var sdkInfo = this.addon.initWithAppkey(appKey, config.dbPath, config); if (sdkInfo) { sdkInfo = JSON.parse(sdkInfo); } // 0 不存不计数 1 只存不计数 3 存且计数 this.addon.registerMessageType("RC:VcMsg", 3); this.addon.registerMessageType("RC:ImgTextMsg", 3); this.addon.registerMessageType("RC:FileMsg", 3); this.addon.registerMessageType("RC:LBSMsg", 3); this.addon.registerMessageType("RC:PSImgTxtMsg", 3); this.addon.registerMessageType("RC:PSMultiImgTxtMsg", 3); this.addon.registerMessageType("RCJrmf:RpMsg", 3); this.addon.registerMessageType("RCJrmf:RpOpendMsg", 1); this.addon.registerMessageType("RC:GrpNtf", 1); this.addon.registerMessageType("RC:DizNtf", 0); this.addon.registerMessageType("RC:InfoNtf", 0); this.addon.registerMessageType("RC:ContactNtf", 0); this.addon.registerMessageType("RC:ProfileNtf", 0); this.addon.registerMessageType("RC:CmdNtf", 0); this.addon.registerMessageType("RC:CmdMsg", 0); this.addon.registerMessageType("RC:TypSts", 0); this.addon.registerMessageType("RC:CsChaR", 0); this.addon.registerMessageType("RC:CsHsR", 0); this.addon.registerMessageType("RC:CsEnd", 0); this.addon.registerMessageType("RC:CsSp", 0); this.addon.registerMessageType("RC:CsUpdate", 0); this.addon.registerMessageType("RC:CsContact", 0); this.addon.registerMessageType("RC:ReadNtf", 0); this.addon.registerMessageType("RC:VCAccept", 0); this.addon.registerMessageType("RC:VCRinging", 0); this.addon.registerMessageType("RC:VCSummary", 0); this.addon.registerMessageType("RC:VCHangup", 0); this.addon.registerMessageType("RC:VCInvite", 0); this.addon.registerMessageType("RC:VCModifyMedia", 0); this.addon.registerMessageType("RC:VCModifyMem", 0); this.addon.registerMessageType("RC:PSCmd", 0); this.addon.registerMessageType("RC:RcCmd", 0); this.addon.registerMessageType("RC:SRSMsg", 0); this.addon.registerMessageType("RC:RRReqMsg", 0); this.addon.registerMessageType("RC:RRRspMsg", 0); return sdkInfo; }; VCDataProvider.prototype.connect = function (token, callback, userId, serverConf) { this.useConsole && console.log("connect"); this.userId = userId; this.connectCallback = callback; RongIMLib.Bridge._client = { userId: userId }; serverConf = serverConf || {}; var openmp = !!serverConf.openMp; var openus = !!serverConf.openUS; if (serverConf.type) { this.addon.setEnvironment(true); } this.addon.connectWithToken(token, userId, serverConf.serverList, openmp, openus); }; VCDataProvider.prototype.setServerInfo = function (info) { 'setServerInfo' in this.addon && this.addon.setServerInfo(info.navi); }; VCDataProvider.prototype.logout = function () { this.useConsole && console.log("logout"); this.disconnect(); }; VCDataProvider.prototype.disconnect = function () { this.useConsole && console.log("disconnect"); this.addon.disconnect(true); }; VCDataProvider.prototype.clearListeners = function () { this.addon.setOnReceiveStatusListener(); this.addon.setConnectionStatusListener(); this.addon.setOnReceiveMessageListener(); }; VCDataProvider.prototype.clearData = function () { this.useConsole && console.log("clearData"); return this.addon.clearData(); }; VCDataProvider.prototype.setConnectionStatusListener = function (listener) { var me = this; /** ConnectionStatus_TokenIncorrect = 31004, ConnectionStatus_Connected = 0, ConnectionStatus_KickedOff = 6, // 其他设备登录 ConnectionStatus_Connecting = 10,// 连接中 ConnectionStatus_SignUp = 12, // 未登录 ConnectionStatus_NetworkUnavailable = 1, // 连接断开 ConnectionStatus_ServerInvalid = 8, // 断开 ConnectionStatus_ValidateFailure = 9,//断开 ConnectionStatus_Unconnected = 11,//断开 ConnectionStatus_DisconnExecption = 31011 //断开 RC_NAVI_MALLOC_ERROR = 30000,//断开 RC_NAVI_NET_UNAVAILABLE= 30002,//断开 RC_NAVI_SEND_FAIL = 30004,//断开 RC_NAVI_REQ_TIMEOUT = 30005,//断开 RC_NAVI_RECV_FAIL = 30006,//断开 RC_NAVI_RESOURCE_ERROR = 30007,//断开 RC_NAVI_NODE_NOT_FOUND = 30008,//断开 RC_NAVI_DNS_ERROR = 30009,//断开 */ me.connectListener = listener; this.useConsole && console.log("setConnectionStatusListener"); me.addon && me.addon.setConnectionStatusListener(function (result) { switch (result) { case 10: setTimeout(function () { listener.onChanged(RongIMLib.ConnectionStatus.CONNECTING); }); break; case 31004: setTimeout(function () { me.connectCallback.onTokenIncorrect(); }); break; case 1: case 8: case 9: case 11: case 12: case 31011: case 30000: case 30002: setTimeout(function () { listener.onChanged(RongIMLib.ConnectionStatus.DISCONNECTED); }); break; case 0: case 33005: setTimeout(function () { me.connectCallback.onSuccess(me.userId); listener.onChanged(RongIMLib.ConnectionStatus.CONNECTED); }); break; case 6: setTimeout(function () { listener.onChanged(RongIMLib.ConnectionStatus.KICKED_OFFLINE_BY_OTHER_CLIENT); }); break; default: setTimeout(function () { listener.onChanged(result); }); break; } }); }; VCDataProvider.prototype.setOnReceiveMessageListener = function (listener) { var me = this, localCount = 0; me.messageListener = listener; this.useConsole && console.log("setOnReceiveMessageListener"); me.addon && me.addon.setOnReceiveMessageListener(function (result, leftCount, offline, hasMore) { var message = me.buildMessage(result); message.offLineMessage = offline; setTimeout(function () { var voipMsgTypes = ['AcceptMessage', 'RingingMessage', 'HungupMessage', 'InviteMessage', 'MediaModifyMessage', 'MemberModifyMessage']; var isVoIPMsg = voipMsgTypes.indexOf(message.messageType) > -1; if (isVoIPMsg) { RongIMLib.RongIMClient._voipProvider && RongIMLib.RongIMClient._voipProvider.onReceived(message); } else if (message.conversationType == 12) { RongIMLib.RongIMClient.RTCListener(message); RongIMLib.RongIMClient.RTCInnerListener(message); RongIMLib.RongIMClient.RTCSignalLisener(message); } else { listener.onReceived(message, leftCount, hasMore); } }); }); }; VCDataProvider.prototype.sendTypingStatusMessage = function (conversationType, targetId, messageName, sendCallback) { var me = this; this.useConsole && console.log("sendTypingStatusMessage"); if (messageName in RongIMLib.RongIMClient.MessageParams) { me.sendMessage(conversationType, targetId, RongIMLib.TypingStatusMessage.obtain(RongIMLib.RongIMClient.MessageParams[messageName].objectName, ""), { onSuccess: function () { setTimeout(function () { sendCallback.onSuccess(); }); }, onError: function (errorCode) { setTimeout(function () { sendCallback.onError(errorCode, null); }); }, onBefore: function () { } }); } }; VCDataProvider.prototype.setMessageStatus = function (conversationType, targetId, timestamp, status, callback) { this.addon.updateMessageReceiptStatus(conversationType, targetId, timestamp); callback.onSuccess(true); }; VCDataProvider.prototype.sendTextMessage = function (conversationType, targetId, content, sendMessageCallback) { var msgContent = RongIMLib.TextMessage.obtain(content); this.useConsole && console.log("sendTextMessage"); this.sendMessage(conversationType, targetId, msgContent, sendMessageCallback); }; VCDataProvider.prototype.getRemoteHistoryMessages = function (conversationType, targetId, timestamp, count, callback, config) { try { var me = this; me.useConsole && console.log("getRemoteHistoryMessages"); me.addon.getRemoteHistoryMessages(conversationType, targetId, timestamp ? timestamp : 0, count, function (ret, hasMore) { var list = ret ? JSON.parse(ret).list : [], msgs = []; list.reverse(); for (var i = 0, len = list.length; i < len; i++) { var message = me.buildMessage(list[i].obj); message.sentStatus = RongIMLib.SentStatus.READ; msgs[i] = message; } callback.onSuccess(msgs, hasMore ? true : false); }, function (errorCode) { callback.onError(errorCode); }); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.getRemoteConversationList = function (callback, conversationTypes, count, isGetHiddenConvers) { try { this.useConsole && console.log("getRemoteConversationList"); var converTypes = conversationTypes || [1, 2, 3, 4, 5, 6, 7, 8]; var result = this.addon.getConversationList(converTypes); var list = JSON.parse(result).list, convers = [], me = this, index = 0; list.reverse(); isGetHiddenConvers = typeof isGetHiddenConvers === 'boolean' ? isGetHiddenConvers : false; for (var i = 0, len_1 = list.length; i < len_1; i++) { var tmpObj = list[i].obj, obj = JSON.parse(tmpObj); if (obj != "") { if (obj.isHidden == 1 && isGetHiddenConvers) { continue; } convers[index] = me.buildConversation(tmpObj); index++; } } convers.reverse(); var len = convers.length; count = count || len; if (len > count) { convers.length = count; } callback.onSuccess(convers); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.removeConversation = function (conversationType, targetId, callback) { try { this.useConsole && console.log("removeConversation"); this.addon.removeConversation(conversationType, targetId); var conversations = RongIMLib.RongIMClient._memoryStore.conversationList; var len = conversations.length; for (var i = 0; i < len; i++) { if (conversations[i].conversationType == conversationType && targetId == conversations[i].targetId) { conversations.splice(i, 1); break; } } callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.joinChatRoom = function (chatRoomId, messageCount, callback) { this.useConsole && console.log("joinChatRoom"); this.addon.joinChatRoom(chatRoomId, messageCount, function () { callback.onSuccess(); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.quitChatRoom = function (chatRoomId, callback) { this.useConsole && console.log("quitChatRoom"); this.addon.quitChatRoom(chatRoomId, function () { callback.onSuccess(); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.setChatroomEntry = function (chatroomId, chatroomEntry, callback) { }; VCDataProvider.prototype.forceSetChatroomEntry = function (chatroomId, chatroomEntry, callback) { }; VCDataProvider.prototype.getChatroomEntry = function (chatroomId, key, callback) { }; VCDataProvider.prototype.getAllChatroomEntries = function (chatroomId, callback) { }; VCDataProvider.prototype.removeChatroomEntry = function (chatroomId, chatroomEntry, callback) { }; VCDataProvider.prototype.forceRemoveChatroomEntry = function (chatroomId, chatroomEntry, callback) { }; VCDataProvider.prototype.pullChatroomEntry = function (chatroomId, time, callback) { }; VCDataProvider.prototype.addToBlacklist = function (userId, callback) { this.useConsole && console.log("addToBlacklist"); this.addon.addToBlacklist(userId, function () { callback.onSuccess(); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.getBlacklist = function (callback) { this.useConsole && console.log("getBlacklist"); this.addon.getBlacklist(function (blacklistors) { callback.onSuccess(blacklistors); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.getBlacklistStatus = function (userId, callback) { this.useConsole && console.log("getBlacklistStatus"); this.addon.getBlacklistStatus(userId, function (result) { callback.onSuccess(result); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.removeFromBlacklist = function (userId, callback) { this.useConsole && console.log("removeFromBlacklist"); this.addon.removeFromBlacklist(userId, function () { callback.onSuccess(); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.sendMessage = function (conversationType, targetId, messageContent, sendCallback, mentiondMsg, pushText, appData, methodType, params) { var me = this, users = []; me.useConsole && console.log("sendMessage"); params = params || {}; var isGroup = (conversationType == RongIMLib.ConversationType.DISCUSSION || conversationType == RongIMLib.ConversationType.GROUP); if (isGroup && messageContent.messageName == RongIMLib.RongIMClient.MessageType["ReadReceiptResponseMessage"]) { users = []; var rspMsg = messageContent; if (rspMsg.receiptMessageDic) { var ids = []; for (var key in rspMsg.receiptMessageDic) { ids.push(key); } users = ids; } } if (isGroup && messageContent.messageName == RongIMLib.RongIMClient.MessageType["SyncReadStatusMessage"]) { users = []; users.push(me.userId); } var userIds = params.userIds; if (isGroup && userIds) { users = userIds; } var msg = me.addon.sendMessage(conversationType, targetId, RongIMLib.RongIMClient.MessageParams[messageContent.messageName].objectName, messageContent.encode(), pushText || "", appData || "", function (progress) { }, function (message, code) { var msg = me.buildMessage(message); var errorCode = RongIMLib.ErrorCode.SENSITIVE_REPLACE; if (code == errorCode) { return sendCallback.onError(errorCode, msg); } sendCallback.onSuccess(msg); }, function (message, code) { sendCallback.onError(code, me.buildMessage(message)); }, users, mentiondMsg); var tempMessage = JSON.parse(msg); sendCallback.onBefore && sendCallback.onBefore(tempMessage.messageId); RongIMLib.MessageIdHandler.messageId = tempMessage.messageId; }; VCDataProvider.prototype.registerMessageType = function (messageType, objectName, messageTag, messageContent, searchProps) { this.useConsole && console.log("registerMessageType"); this.addon.registerMessageType(objectName, messageTag.getMessageTag(), searchProps); var regMsg = RongIMLib.ModelUtil.modleCreate(messageContent, messageType); RongIMLib.RongIMClient.RegisterMessage[messageType] = regMsg; RongIMLib.RongIMClient.RegisterMessage[messageType].messageName = messageType; registerMessageTypeMapping[objectName] = messageType; RongIMLib.RongIMClient.MessageType[messageType] = messageType; RongIMLib.RongIMClient.MessageParams[messageType] = { objectName: objectName, msgTag: messageTag }; typeMapping[objectName] = messageType; }; VCDataProvider.prototype.registerMessageTypes = function (messages) { var types = []; var getProtos = function (proto) { var protos = []; for (var p in proto) { protos.push(p); } return protos; }; //转换消息为自定义消息参数格式 for (var name in messages) { var message = messages[name]; var proto = message.proto; var protos = getProtos(proto); var flag = message.flag || 3; var tag = RongIMLib.MessageTag.getTagByStatus(flag); flag = new RongIMLib.MessageTag(tag.isCounted, tag.isPersited); types.push({ type: name, name: message.name, flag: flag, protos: protos }); } var register = function (message) { var type = message.type; var name = message.name; var flag = message.flag; var protos = message.protos; RongIMLib.RongIMClient.registerMessageType(type, name, flag, protos); }; for (var i = 0, len = types.length; i < len; i++) { var message = types[i]; register(message); } }; VCDataProvider.prototype.addMessage = function (conversationType, targetId, message, callback) { this.useConsole && console.log("addMessage"); var direction = message.direction; var msg = this.addon.insertMessage(conversationType, targetId, message.senderUserId, message.objectName, JSON.stringify(message.content), function () { callback.onSuccess(me.buildMessage(msg)); }, function () { callback.onError(RongIMLib.ErrorCode.MSG_INSERT_ERROR); }, direction), me = this; }; VCDataProvider.prototype.removeMessage = function (conversationType, targetId, messages, callback) { }; VCDataProvider.prototype.deleteRemoteMessages = function (conversationType, targetId, messages, callback) { }; VCDataProvider.prototype.removeLocalMessage = function (conversationType, targetId, timestamps, callback) { try { this.useConsole && console.log("removeLocalMessage"); this.addon.deleteMessages(timestamps); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.getMessage = function (messageId, callback) { try { this.useConsole && console.log("getMessage"); var msg = this.buildMessage(this.addon.getMessage(messageId)); callback.onSuccess(msg); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.clearMessages = function (conversationType, targetId, callback) { try { this.useConsole && console.log("clearMessages"); this.addon.clearMessages(conversationType, targetId); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; // Web 端接口,桌面版无需实现 VCDataProvider.prototype.setUnreadCount = function (conversationType, targetId, count) { }; VCDataProvider.prototype.getConversation = function (conversationType, targetId, callback) { try { this.useConsole && console.log("getConversation"); var ret = this.addon.getConversation(conversationType, targetId); callback.onSuccess(this.buildConversation(ret)); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.getConversationList = function (callback, conversationTypes, count, isGetHiddenConvers) { this.useConsole && console.log("getConversationList"); this.getRemoteConversationList(callback, conversationTypes, count, isGetHiddenConvers); }; VCDataProvider.prototype.clearCache = function () { var memoryStore = RongIMLib.RongIMClient._memoryStore || {}; memoryStore.conversationList = []; memoryStore.isSyncRemoteConverList; }; VCDataProvider.prototype.clearConversations = function (conversationTypes, callback) { try { this.useConsole && console.log("clearConversations"); this.addon.clearConversations(); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.setMessageContent = function (messageId, content, objectName) { content = JSON.stringify(content); this.addon.setMessageContent(messageId, content, objectName); }; VCDataProvider.prototype.setMessageSearchField = function (messageId, content, searchFiles) { content = JSON.stringify(content); this.addon.setMessageContent(messageId, content, searchFiles); }; VCDataProvider.prototype.getHistoryMessages = function (conversationType, targetId, timestamp, count, callback, objectname, direction) { this.useConsole && console.log("getHistoryMessages"); if (count <= 0) { callback.onError(RongIMLib.ErrorCode.TIMEOUT); return; } objectname = objectname || ''; direction = typeof direction == 'undefined' || direction; try { var ret = this.addon.getHistoryMessages(conversationType, targetId, timestamp ? timestamp : 0, count, objectname, direction); var list = ret ? JSON.parse(ret).list : [], msgs = [], me = this; list.reverse(); for (var i = 0, len = list.length; i < len; i++) { var message = me.buildMessage(list[i].obj); msgs[i] = message; } callback.onSuccess(msgs, len == count); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.clearRemoteHistoryMessages = function (params, callback) { var conversationType = params.conversationType; var targetId = params.targetId; var timestamp = params.timestamp; var _topic = { 1: true, 2: true, 3: true, 5: true, 6: true }; var topic = _topic[conversationType]; if (!topic) { callback.onError(RongIMLib.ErrorCode.CLEAR_HIS_TYPE_ERROR); return; } if (typeof timestamp != 'number') { callback.onError(RongIMLib.ErrorCode.CLEAR_HIS_TIME_ERROR); return; } this.addon.clearRemoteHistoryMessages(+conversationType, targetId, timestamp, function () { callback.onSuccess(true); }, function (errorCode) { if (errorCode == 1) { // 没有开通历史消息云存储 errorCode = RongIMLib.ErrorCode.CLEAR_HIS_ERROR; } callback.onError(errorCode); }); }; VCDataProvider.prototype.clearHistoryMessages = function (params, callback) { var conversationType = +params.conversationType; var targetId = params.targetId; try { this.addon.clearMessages(conversationType, targetId); var isSuccess = true; callback.onSuccess(isSuccess); } catch (e) { console.log(e); callback.onError(RongIMLib.ErrorCode.CLEAR_HIS_ERROR); } }; VCDataProvider.prototype.getTotalUnreadCount = function (callback, conversationTypes) { try { var result; this.useConsole && console.log("getTotalUnreadCount"); if (conversationTypes) { result = this.addon.getTotalUnreadCount(conversationTypes); } else { result = this.addon.getTotalUnreadCount(); } callback.onSuccess(result); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.getConversationUnreadCount = function (conversationTypes, callback) { this.useConsole && console.log("getConversationUnreadCount"); this.getTotalUnreadCount(callback, conversationTypes); }; VCDataProvider.prototype.getUnreadCount = function (conversationType, targetId, callback) { try { this.useConsole && console.log("getUnreadCount"); var result = this.addon.getUnreadCount(conversationType, targetId); callback.onSuccess(result); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.clearUnreadCount = function (conversationType, targetId, callback) { try { this.useConsole && console.log("clearUnreadCount"); var result = this.addon.clearUnreadCount(conversationType, targetId); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.clearTotalUnreadCount = function (callback) { this.useConsole && console.log("clearTotalUnreadCount"); }; VCDataProvider.prototype.clearUnreadCountByTimestamp = function (conversationType, targetId, timestamp, callback) { try { this.useConsole && console.log("clearUnreadCountByTimestamp"); var result = this.addon.clearUnreadCountByTimestamp(conversationType, targetId, timestamp); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.setConversationToTop = function (conversationType, targetId, isTop, callback) { try { this.useConsole && console.log("setConversationToTop"); this.addon.setConversationToTop(conversationType, targetId, isTop); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.setConversationHidden = function (conversationType, targetId, isHidden) { this.addon.setConversationHidden(conversationType, targetId, isHidden); }; VCDataProvider.prototype.setMessageReceivedStatus = function (messageId, receivedStatus, callback) { try { this.useConsole && console.log("setMessageReceivedStatus"); this.addon.setMessageReceivedStatus(messageId, receivedStatus); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.setMessageSentStatus = function (messageId, sentStatus, callback) { try { this.useConsole && console.log("setMessageSentStatus"); this.addon.setMessageSentStatus(messageId, sentStatus); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.getFileToken = function (fileType, callback) { this.useConsole && console.log("getFileToken"); this.addon.getUploadToken(fileType, function (token) { callback.onSuccess({ token: token }); }, function (errorCode) { callback.onError(errorCode); }); }; VCDataProvider.prototype.getFileUrl = function (fileType, fileName, oriName, callback) { this.useConsole && console.log("getFileUrl"); this.addon.getDownloadUrl(fileType, fileName, oriName, function (url) { callback.onSuccess({ downloadUrl: url }); }, function (errorCode) { callback.onError(errorCode); }); }; VCDataProvider.prototype.getPullSetting = function (callback) { this.useConsole && console.log("getPullSetting"); }; VCDataProvider.prototype.setOfflineMessageDuration = function (duration, callback) { this.useConsole && console.log("setOfflineMessageDuration"); }; VCDataProvider.prototype.searchConversationByContent = function (keyword, callback, conversationTypes) { var converTypes = []; if (typeof conversationTypes == 'undefined') { converTypes = [1, 2, 3, 4, 5, 6, 7]; } else { converTypes = conversationTypes; } try { this.useConsole && console.log("searchConversationByContent"); var result = this.addon.searchConversationByContent(converTypes, keyword); var list = JSON.parse(result).list, convers = [], me = this; list.reverse(); for (var i = 0, len = list.length; i < len; i++) { convers[i] = me.buildConversation(list[i].obj); } callback.onSuccess(convers); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.searchMessageByContent = function (conversationType, targetId, keyword, timestamp, count, total, callback) { var me = this; try { this.useConsole && console.log("searchMessageByContent"); this.addon.searchMessageByContent(conversationType, targetId, keyword, timestamp, count, total, function (ret, matched) { var list = ret ? JSON.parse(ret).list : [], msgs = []; list.reverse(); for (var i = 0, len = list.length; i < len; i++) { msgs[i] = me.buildMessage(list[i].obj); } callback.onSuccess(msgs, matched); }); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.getChatRoomInfo = function (chatRoomId, count, order, callback) { this.useConsole && console.log("getChatRoomInfo"); this.addon.getChatroomInfo(chatRoomId, count, order, function (ret, count) { var list = ret ? JSON.parse(ret).list : [], chatRoomInfo = { userInfos: [], userTotalNums: count }; if (list.length > 0) { for (var i = 0, len = list.length; i < len; i++) { chatRoomInfo.userInfos.push(JSON.parse(list[i].obj)); } } callback.onSuccess(chatRoomInfo); }, function (errcode) { callback.onError(errcode); }); }; VCDataProvider.prototype.setChatroomHisMessageTimestamp = function (chatRoomId, timestamp) { }; VCDataProvider.prototype.getChatRoomHistoryMessages = function (chatRoomId, count, order, callback) { }; VCDataProvider.prototype.getDelaTime = function () { return this.addon.getDeltaTime(); }; VCDataProvider.prototype.getUserStatus = function (userId, callback) { var me = this; this.addon.getUserStatus(userId, function (status) { var entity = RongIMLib.RongInnerTools.convertUserStatus({ status: status, userId: '' }); callback.onSuccess(entity); }, function (code) { callback.onError(code); }); }; VCDataProvider.prototype.setUserStatus = function (status, callback) { this.addon.setUserStatus(status, function () { callback.onSuccess(true); }, function (code) { callback.onError(code); }); }; VCDataProvider.prototype.subscribeUserStatus = function (userIds, callback) { this.addon.subscribeUserStatus(userIds, function () { callback && callback.onSuccess(true); }, function (code) { callback && callback.onError(code); }); }; VCDataProvider.prototype.setUserStatusListener = function (params, callback) { var me = this; this.addon.setOnReceiveStatusListener(function (userId, status) { var entity = RongIMLib.RongInnerTools.convertUserStatus({ userId: userId, status: status }); RongIMLib.RongIMClient.userStatusObserver.notify({ key: userId, entity: entity }); }); var userIds = params.userIds || []; if (userIds.length) { RongIMLib.RongIMClient._dataAccessProvider.subscribeUserStatus(userIds); } }; VCDataProvider.prototype.getUnreadMentionedMessages = function (conversationType, targetId) { var me = this; var mentions = JSON.parse(me.addon.getUnreadMentionedMessages(conversationType, targetId)).list; for (var i = 0, len = mentions.length; i < len; i++) { var temp = JSON.parse(mentions[i].obj); temp.content = JSON.parse(temp.content); mentions[i] = temp; } return mentions; }; VCDataProvider.prototype.hasRemoteUnreadMessages = function (token, callback) { callback.onSuccess(false); }; VCDataProvider.prototype.sendRecallMessage = function (content, sendMessageCallback) { var me = this; me.addon.recallMessage("RC:RcCmd", JSON.stringify(content), content.push || "", function () { content.objectName = 'RC:RcCmd'; sendMessageCallback.onSuccess(me.buildMessage(JSON.stringify(content))); }, function (errorCode) { sendMessageCallback.onError(errorCode); }); }; VCDataProvider.prototype.updateMessage = function (message, callback) { }; VCDataProvider.prototype.updateMessages = function (conversationType, targetId, key, value, callback) { }; VCDataProvider.prototype.reconnect = function (callback) { }; VCDataProvider.prototype.sendReceiptResponse = function (conversationType, targetId, sendCallback) { }; VCDataProvider.prototype.setMessageExtra = function (messageId, value, callback) { }; VCDataProvider.prototype.addMemberToDiscussion = function (discussionId, userIdList, callback) { }; VCDataProvider.prototype.createDiscussion = function (name, userIdList, callback) { }; VCDataProvider.prototype.getDiscussion = function (discussionId, callback) { }; VCDataProvider.prototype.quitDiscussion = function (discussionId, callback) { }; VCDataProvider.prototype.removeMemberFromDiscussion = function (discussionId, userId, callback) { }; VCDataProvider.prototype.setDiscussionInviteStatus = function (discussionId, status, callback) { }; VCDataProvider.prototype.setDiscussionName = function (discussionId, name, callback) { }; VCDataProvider.prototype.setEnvironment = function (isPrivate) { this.addon.setEnvironment(isPrivate); }; VCDataProvider.prototype.addConversation = function (conversation, callback) { }; VCDataProvider.prototype.updateConversation = function (conversation) { return null; }; VCDataProvider.prototype.getConversationNotificationStatus = function (params, callback) { var conversationType = params.conversationType; var targetId = params.targetId; var notification = RongIMLib.RongIMClient._memoryStore.notification; var key = conversationType + '_' + targetId; var status = notification[key]; if (typeof status == 'number') { callback.onSuccess(status); return; } this.addon.getConversationNotificationStatus(conversationType, targetId, function (status) { notification[key] = status; callback.onSuccess(status); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.setConversationNotificationStatus = function (params, callback) { var conversationType = params.conversationType; var targetId = params.targetId; var status = params.status; var notification = RongIMLib.RongIMClient._memoryStore.notification; var key = conversationType + '_' + targetId; notification[key] = status; var notify = !!status; this.addon.setConversationNotificationStatus(conversationType, targetId, notify, function () { callback.onSuccess(status); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.getCurrentConnectionStatus = function () { return this.addon.getConnectionStatus(); }; VCDataProvider.prototype.getAgoraDynamicKey = function (engineType, channelName, callback) { var extra = ""; this.addon.getVoIPKey(engineType, channelName, extra, function (token) { callback.onSuccess(token); }, function (errorCode) { callback.onError(errorCode); }); }; VCDataProvider.prototype.getPublicServiceProfile = function (publicServiceType, publicServiceId, callback) { var profile = RongIMLib.RongIMClient._memoryStore.publicServiceMap.get(publicServiceType, publicServiceId); callback.onSuccess(profile); }; VCDataProvider.prototype.setDeviceInfo = function (device) { var id = device.id || ''; this.addon.setDeviceId(id); }; VCDataProvider.prototype.getRemotePublicServiceList = function (callback, pullMessageTime) { var publicList = []; var ret = this.addon.getAccounts(); var transformProto = function (ret) { var result = { hasFollowed: false, isGlobal: false, menu: null }; if (!ret.obj) { var error = { error: ret }; throw new Error('公众账号数据格式错误: ' + JSON.stringify(error)); } var obj = JSON.parse(ret.obj); var protoMap = { aType: 'conversationType', aId: 'publicServiceId', aName: 'introduction', aUri: 'portraitUri', follow: 'hasFollowed', isGlobal: 'isGlobal' }; for (var key in obj) { var val = obj[key]; if (key == 'aExtra') { var extra = JSON.parse(val); result["hasFollowed"] = extra.follow; result["isGlobal"] = extra.isGlobal; result["menu"] = extra.menu; } var uId = protoMap[key]; if (uId) { result[uId] = val; } } return result; }; if (ret) { ret = JSON.parse(ret); var list = ret.list; for (var i = 0, len = list.length; i < len; i++) { var item = list[i]; item = transformProto(item); publicList.push(item); } } if (publicList.length > 0) { RongIMLib.RongIMClient._memoryStore.publicServiceMap.publicServiceList.length = 0; RongIMLib.RongIMClient._memoryStore.publicServiceMap.publicServiceList = publicList; } callback.onSuccess(RongIMLib.RongIMClient._memoryStore.publicServiceMap.publicServiceList); }; VCDataProvider.prototype.buildMessage = function (result) { var message = new RongIMLib.Message(), ret = JSON.parse(result); message.conversationType = ret.conversationType; message.targetId = ret.targetId; message.messageDirection = ret.direction; message.senderUserId = ret.senderUserId; if (ret.direction == RongIMLib.MessageDirection.RECEIVE) { message.receivedStatus = ret.status; } else if (ret.direction == RongIMLib.MessageDirection.SEND) { message.sentStatus = ret.status; } message.sentTime = ret.sentTime; message.objectName = ret.objectName; var content = ret.content ? JSON.parse(ret.content) : ret.content; var messageType = typeMapping[ret.objectName] || registerMessageTypeMapping[ret.objectName]; if (content) { content.messageName = messageType; } message.content = content; message.messageId = ret.messageId; message.messageUId = ret.messageUid; message.messageType = messageType; return message; }; VCDataProvider.prototype.buildConversation = function (val) { if (val === '') { return null; } var conver = new RongIMLib.Conversation(), c = JSON.parse(val), lastestMsg = c.lastestMsg ? this.buildMessage(c.lastestMsg) : {}; conver.conversationTitle = c.title; conver.conversationType = c.conversationType; conver.draft = c.draft; conver.isTop = c.isTop; conver.isHidden = c.isHidden; lastestMsg.conversationType = c.conversationType; lastestMsg.targetId = c.targetId; conver.latestMessage = lastestMsg; conver.latestMessageId = lastestMsg.messageId; conver.latestMessage.messageType = typeMapping[lastestMsg.objectName] || registerMessageTypeMapping[lastestMsg.objectName]; conver.objectName = lastestMsg.objectName; conver.receivedStatus = RongIMLib.ReceivedStatus.READ; conver.sentTime = lastestMsg.sentTime; conver.senderUserId = lastestMsg.senderUserId; conver.sentStatus = lastestMsg.status; conver.targetId = c.targetId; conver.unreadMessageCount = c.unreadCount; conver.hasUnreadMention = c.m_hasUnreadMention; var mentions = this.getUnreadMentionedMessages(c.conversationType, c.targetId); if (mentions.length > 0) { // 取最后一条 @ 消息,原因:和 web 互相兼容 var mention = mentions.pop(); conver.mentionedMsg = { uid: mention.messageUid, time: mention.sentTime, mentionedInfo: mention.content.mentionedInfo, sendUserId: mention.senderUserId }; } return conver; }; VCDataProvider.prototype.getRTCUserInfoList = function (room, callback) { this.addon.getRTCUsers(room.id, 1, function (result) { callback.onSuccess(result); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.getRTCRoomInfo = function (room, callback) { var order = 2; this.addon.getRTCResouce(room.id, order, function (result) { callback.onSuccess(JSON.parse(result)); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.joinRTCRoom = function (room, callback) { var id = room.id; var type = room.type || 0; this.addon.joinRTCRoom(id, type, function (result, token) { var res = JSON.parse(result); var users = {}; var list = res.list; RongIMLib.RongUtil.forEach(list, function (item) { var userId = item.id; var tmpData = {}; RongIMLib.RongUtil.forEach(item.data, function (data) { var key = data.key; var value = data.value; tmpData[key] = value; }); users[userId] = tmpData; }); callback.onSuccess({ users: users, token: token }); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.quitRTCRoom = function (room, callback) { this.addon.exitRTCRoom(room.id, function () { callback.onSuccess(true); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.RTCPing = function (room, callback) { this.addon.sendRTCPing(room.id, function () { callback.onSuccess(true); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.setRTCData = function (roomId, key, value, isInner, apiType, callback, message) { var context = this; var hanlders = { room_inner: function (roomId, key, value, name, content, success, error) { context.addon.setRTCInnerData(roomId, RongIMLib.RTCAPIType.ROOM, key, value, name, content, success, error); }, room_outer: function (roomId, key, value, name, content, success, error) { context.addon.setRTCOuterData(roomId, RongIMLib.RTCAPIType.ROOM, key, value, name, content, success, error); }, user_inner: function (roomId, key, value, name, content, success, error) { context.addon.setRTCInnerData(roomId, RongIMLib.RTCAPIType.PERSON, key, value, name, content, success, error); }, user_outer: function (roomId, key, value, name, content, success, error) { context.addon.setRTCOuterData(roomId, RongIMLib.RTCAPIType.PERSON, key, value, name, content, success, error); } }; var type = RongIMLib.RTCAPIType.PERSON == apiType ? 'user' : 'room'; var direction = isInner ? 'inner' : 'outer'; var tpl = '{type}_{direction}'; var name = RongIMLib.RongUtil.tplEngine(tpl, { type: type, direction: direction }); var handler = hanlders[name]; if (handler) { message = message || {}; var name = message.name; var content = message.content; handler(roomId, key, value, name, content, function () { callback.onSuccess(true); }, function (code) { callback.onError(code); }); } }; VCDataProvider.prototype.setRTCRoomData = function (roomId, key, value, isInner, callback, message) { this.setRTCData(roomId, key, value, isInner, RongIMLib.RTCAPIType.ROOM, callback, message); }; VCDataProvider.prototype.getRTCData = function (roomId, keys, isInner, apiType, callback) { var context = this; var hanlders = { room_inner: function (roomId, keys, success, error) { context.addon.getRTCInnerData(roomId, RongIMLib.RTCAPIType.ROOM, keys, success, error); }, room_outer: function (roomId, keys, success, error) { context.addon.getRTCOuterData(roomId, RongIMLib.RTCAPIType.ROOM, keys, success, error); } }; var type = RongIMLib.RTCAPIType.PERSON == apiType ? 'user' : 'room'; var direction = isInner ? 'inner' : 'outer'; var tpl = '{type}_{direction}'; var name = RongIMLib.RongUtil.tplEngine(tpl, { type: type, direction: direction }); var handler = hanlders[name]; if (handler) { handler(roomId, keys, function (result) { var res = JSON.parse(result); var props = {}; var list = res.list; RongIMLib.RongUtil.forEach(list, function (item) { props[item.key] = item.value; }); callback.onSuccess(props); }, function (code) { callback.onError(code); }); } }; VCDataProvider.prototype.getRTCRoomData = function (roomId, keys, isInner, callback, message) { this.getRTCData(roomId, keys, isInner, RongIMLib.RTCAPIType.ROOM, callback); }; VCDataProvider.prototype.removeRTCData = function (roomId, keys, isInner, apiType, callback, message) { var context = this; var hanlders = { room_inner: function (roomId, keys, name, content, success, error) { context.addon.deleteRTCInnerData(roomId, RongIMLib.RTCAPIType.ROOM, keys, name, content, success, error); }, room_outer: function (roomId, keys, name, content, success, error) { context.addon.deleteRTCOuterData(roomId, RongIMLib.RTCAPIType.ROOM, keys, name, content, success, error); }, user_inner: function (roomId, keys, name, content, success, error) { }, user_outer: function (roomId, keys, name, content, success, error) { } }; var type = RongIMLib.RTCAPIType.PERSON == apiType ? 'user' : 'room'; var direction = isInner ? 'inner' : 'outer'; var tpl = '{type}_{direction}'; var name = RongIMLib.RongUtil.tplEngine(tpl, { type: type, direction: direction }); var handler = hanlders[name]; if (handler) { message = message || {}; var name = message.name || ''; var content = message.content || ''; handler(roomId, keys, name, content, function () { callback.onSuccess(true); }, function (code) { callback.onError(code); }); } }; VCDataProvider.prototype.removeRTCRoomData = function (roomId, keys, isInner, callback, message) { this.removeRTCData(roomId, keys, isInner, RongIMLib.RTCAPIType.ROOM, callback); }; VCDataProvider.prototype.getNavi = function () { var nav = this.addon.getNav(); return nav[this.userId]; }; // 信令 SDK 新增 VCDataProvider.prototype.setRTCOutData = function (roomId, data, type, callback, message) { }; // 信令 SDK 新增 VCDataProvider.prototype.getRTCOutData = function (roomId, userId, callback) { }; VCDataProvider.prototype.setRTCUserInfo = function (room, info, callback) { }; VCDataProvider.prototype.removeRTCUserInfo = function (room, info, callback) { }; VCDataProvider.prototype.getRTCUserList = function (room, callback) { }; VCDataProvider.prototype.setRTCRoomInfo = function (room, data, callback) { }; VCDataProvider.prototype.removeRTCRoomInfo = function (room, data, callback) { }; VCDataProvider.prototype.setRTCUserData = function (roomId, key, value, isInner, callback, message) { this.setRTCData(roomId, key, value, isInner, RongIMLib.RTCAPIType.PERSON, callback, message); }; VCDataProvider.prototype.getRTCUserData = function (roomId, key, isInner, callback, message) { }; VCDataProvider.prototype.removeRTCUserData = function (roomId, key, isInner, callback, message) { }; VCDataProvider.prototype.getRTCToken = function (room, callback) { }; VCDataProvider.prototype.setRTCState = function (room, content, callback) { }; return VCDataProvider; })(); RongIMLib.VCDataProvider = VCDataProvider; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var MemeoryProvider = (function () { function MemeoryProvider() { this._memeoryStore = {}; this.prefix = "rong_"; } MemeoryProvider.prototype.setItem = function (composedKey, object) { this._memeoryStore[composedKey] = decodeURIComponent(object); }; MemeoryProvider.prototype.getItem = function (composedKey) { return this._memeoryStore[composedKey]; }; MemeoryProvider.prototype.removeItem = function (composedKey) { if (this.getItem(composedKey)) { delete this._memeoryStore[composedKey]; } }; MemeoryProvider.prototype.getItemKey = function (regStr) { var me = this, item = null, reg = new RegExp(regStr + "\\w+"); for (var key in me._memeoryStore) { var arr = key.match(reg); if (arr) { item = key; } } return item; }; MemeoryProvider.prototype.getItemKeyList = function (regStr) { var prefix = this.prefix; var me = this, itemList = [], reg = new RegExp(regStr + "\\w+"); for (var key in me._memeoryStore) { var arr = key.match(reg); if (arr) { key = key.substring(prefix.length); itemList.push(key); } } return itemList; }; MemeoryProvider.prototype.clearItem = function () { var me = this; for (var key in me._memeoryStore) { delete me._memeoryStore[key]; } }; //单位:字节 MemeoryProvider.prototype.onOutOfQuota = function () { return 4 * 1024; }; return MemeoryProvider; })(); RongIMLib.MemeoryProvider = MemeoryProvider; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var LocalStorageProvider = (function () { // static _instance: LocalStorageProvider = new LocalStorageProvider(); function LocalStorageProvider() { this.prefix = 'rong_'; this._host = ""; var d = new Date(), m = d.getMonth() + 1, date = d.getFullYear() + '/' + (m.toString().length == 1 ? '0' + m : m) + '/' + d.getDate(), nowDate = new Date(date).getTime(); for (var key in localStorage) { if (key.lastIndexOf('RECEIVED') > -1) { var recObj = JSON.parse(localStorage.getItem(key)); for (var key_1 in recObj) { nowDate - recObj[key_1].dealtime > 0 && (delete recObj[key_1]); } if (RongIMLib.RongUtil.isEmpty(recObj)) { localStorage.removeItem(key); } else { localStorage.setItem(key, JSON.stringify(recObj)); } } if (key.lastIndexOf('SENT') > -1) { var sentObj = JSON.parse(localStorage.getItem(key)); nowDate - sentObj.dealtime > 0 && (localStorage.removeItem(key)); } } } LocalStorageProvider.prototype.setItem = function (composedKey, object) { if (composedKey) { composedKey.indexOf(this.prefix) == -1 && (composedKey = this.prefix + composedKey); localStorage.setItem(composedKey, object); } }; LocalStorageProvider.prototype.getItem = function (composedKey) { if (composedKey) { composedKey.indexOf(this.prefix) == -1 && (composedKey = this.prefix + composedKey); return localStorage.getItem(composedKey ? composedKey : ""); } return ""; }; LocalStorageProvider.prototype.getItemKey = function (composedStr) { var item = ""; var _key = this.prefix + composedStr; for (var key in localStorage) { if (key.indexOf(_key) == 0) { item = key; break; } } return item; }; LocalStorageProvider.prototype.getItemKeyList = function (composedStr) { var itemList = []; var prefix = this.prefix; var _key = prefix + composedStr; for (var key in localStorage) { if (key.indexOf(_key) == 0) { key = key.substring(prefix.length); itemList.push(key); } } return itemList; }; LocalStorageProvider.prototype.removeItem = function (composedKey) { if (composedKey) { composedKey.indexOf(this.prefix) == -1 && (composedKey = this.prefix + composedKey); localStorage.removeItem(composedKey.toString()); } }; LocalStorageProvider.prototype.clearItem = function () { var me = this; for (var key in localStorage) { if (key.indexOf(me.prefix) > -1) { me.removeItem(key); } } }; //单位:字节 LocalStorageProvider.prototype.onOutOfQuota = function () { return JSON.stringify(localStorage).length; }; return LocalStorageProvider; })(); RongIMLib.LocalStorageProvider = LocalStorageProvider; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var UserDataProvider = (function () { function UserDataProvider() { this.opersistName = 'RongIMLib'; this.keyManager = 'RongUserDataKeyManager'; this._host = ""; this.prefix = "rong_"; this.oPersist = document.createElement("div"); this.oPersist.style.display = "none"; this.oPersist.style.behavior = "url('#default#userData')"; document.body.appendChild(this.oPersist); this.oPersist.load(this.opersistName); } UserDataProvider.prototype.setItem = function (key, value) { key && key.indexOf(this.prefix) == -1 && (key = this.prefix + key); this.oPersist.setAttribute(key, value); var keyNames = this.getItem(this.keyManager); keyNames ? keyNames.indexOf(key) == -1 && (keyNames += ',' + key) : (keyNames = key); this.oPersist.setAttribute(this.prefix + this.keyManager, keyNames); this.oPersist.save(this.opersistName); }; UserDataProvider.prototype.getItem = function (key) { key && key.indexOf(this.prefix) == -1 && (key = this.prefix + key); return key ? this.oPersist.getAttribute(key) : key; }; UserDataProvider.prototype.removeItem = function (key) { key && key.indexOf(this.prefix) == -1 && (key = this.prefix + key); this.oPersist.removeAttribute(key); this.oPersist.save(this.opersistName); var keyNames = this.getItem(this.keyManager), keyNameArray = keyNames && keyNames.split(',') || []; for (var i = 0, len = keyNameArray.length; i < len; i++) { if (keyNameArray[i] == key) { keyNameArray.splice(i, 1); } } this.oPersist.setAttribute(this.prefix + this.keyManager, keyNameArray.join(',')); this.oPersist.save(this.opersistName); }; UserDataProvider.prototype.getItemKey = function (composedStr) { var item = null, keyNames = this.getItem(this.keyManager), keyNameArray = keyNames && keyNames.split(',') || [], me = this; var _key = this.prefix + composedStr; if (keyNameArray.length) { for (var i = 0, len = keyNameArray.length; i < len; i++) { if (keyNameArray[i] && keyNameArray[i].indexOf(_key) == 0) { item = keyNameArray[i]; break; } } } return item; }; UserDataProvider.prototype.getItemKeyList = function (composedStr) { var itemList = [], keyNames = this.getItem(this.keyManager), keyNameArray = keyNames && keyNames.split(',') || []; var prefix = this.prefix; var _key = prefix + composedStr; if (keyNameArray.length) { for (var i = 0, len = keyNameArray.length; i < len; i++) { if (keyNameArray[i] && keyNameArray[i].indexOf(_key) == 0) { var keyName = keyNameArray[i]; keyName = keyName.substring(prefix.length); itemList.push(keyNameArray[i]); } } } return itemList; }; UserDataProvider.prototype.clearItem = function () { var keyNames = this.getItem(this.keyManager), keyNameArray = [], me = this; keyNames && (keyNameArray = keyNames.split(',')); if (keyNameArray.length) { for (var i = 0, len = keyNameArray.length; i < len; i++) { keyNameArray[i] && me.removeItem(keyNameArray[i]); } me.removeItem(me.keyManager); } }; UserDataProvider.prototype.onOutOfQuota = function () { return 10 * 1024 * 1024; }; return UserDataProvider; })(); RongIMLib.UserDataProvider = UserDataProvider; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var FeatureDectector = (function () { function FeatureDectector(callback) { this.script = document.createElement("script"); this.head = document.getElementsByTagName("head")[0]; if ("WebSocket" in window && "ArrayBuffer" in window && WebSocket.prototype.CLOSED === 3 && !RongIMLib.RongIMClient._memoryStore.depend.isPolling) { RongIMLib.Transportations._TransportType = RongIMLib.Socket.WEBSOCKET; if (!RongIMLib.RongIMClient.Protobuf) { var url = RongIMLib.RongIMClient._memoryStore.depend.protobuf; var script = this.script; script.src = url; this.head.appendChild(script); script.onload = script.onreadystatechange = function () { var isLoaded = (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete'); if (isLoaded) { // 防止 IE6、7 下偶发触发两次 loaded script.onload = script.onreadystatechange = null; if (callback) { callback(); } if (!callback) { var token = RongIMLib.RongIMClient._memoryStore.token; var connectCallback = RongIMLib.RongIMClient._memoryStore.callback; token && RongIMLib.RongIMClient.connect(token, connectCallback); } } }; } } else { RongIMLib.Transportations._TransportType = "xhr-polling"; RongIMLib.RongIMClient.Protobuf = Polling; } } return FeatureDectector; })(); RongIMLib.FeatureDectector = FeatureDectector; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var FeaturePatcher = (function () { function FeaturePatcher() { } FeaturePatcher.prototype.patchAll = function () { this.patchJSON(); this.patchForEach(); }; FeaturePatcher.prototype.patchForEach = function () { if (!Array.forEach) { Array.forEach = function (arr, func) { for (var i = 0; i < arr.length; i++) { func.call(arr, arr[i], i, arr); } }; } }; FeaturePatcher.prototype.patchJSON = function () { if (!window["JSON"]) { window["JSON"] = (function () { function JSON() { } JSON.parse = function (sJSON) { return eval('(' + sJSON + ')'); }; JSON.stringify = function (value) { return this.str("", { "": value }); }; JSON.str = function (key, holder) { var i, k, v, length, mind = "", partial, value = holder[key], me = this; if (value && typeof value === "object" && typeof value.toJSON === "function") { value = value.toJSON(key); } switch (typeof value) { case "string": return me.quote(value); case "number": return isFinite(value) ? String(value) : "null"; case "boolean": case "null": return String(value); case "object": if (!value) { return "null"; } partial = []; if (Object.prototype.toString.apply(value) === "[object Array]") { length = value.length; for (i = 0; i < length; i += 1) { partial[i] = me.str(i, value) || "null"; } v = partial.length === 0 ? "[]" : "[" + partial.join(",") + "]"; return v; } for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = me.str(k, value); if (v) { partial.push(me.quote(k) + ":" + v); } } } v = partial.length === 0 ? "{}" : "{" + partial.join(",") + "}"; return v; } }; JSON.quote = function (string) { var me = this; me.rx_escapable.lastIndex = 0; return me.rx_escapable.test(string) ? '"' + string.replace(me.rx_escapable, function (a) { var c = me.meta[a]; return typeof c === "string" ? c : "\\u" + ("0000" + a.charCodeAt(0).toString(16)).slice(-4); }) + '"' : '"' + string + '"'; }; JSON.rx_escapable = new RegExp('[\\\"\\\\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]', "g"); JSON.meta = { "\b": "\\b", " ": "\\t", "\n": "\\n", "\f": "\\f", "\r": "\\r", '"': '\\"', "''": "\\''", "\\": "\\\\" }; return JSON; })(); } }; return FeaturePatcher; })(); RongIMLib.FeaturePatcher = FeaturePatcher; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var ScriptLoader = (function () { function ScriptLoader() { } ScriptLoader.prototype.load = function (src, onLoad, onError) { var script = document.createElement("script"); script.async = true; if (onLoad) { if (script.addEventListener) { script.addEventListener("load", function (event) { var target = event.target || event.srcElement; onLoad(target.src); }, false); } else if (script.readyState) { script.onreadystatechange = function (event) { var target = event.srcElement; onLoad(target.src); }; } } if (onError) { script.onerror = function (event) { var target = event.target || event.srcElement; onError(target.src); }; } (document.head || document.getElementsByTagName("head")[0]).appendChild(script); script.src = src; }; return ScriptLoader; })(); })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var PublicServiceMap = (function () { function PublicServiceMap() { this.publicServiceList = []; } PublicServiceMap.prototype.get = function (publicServiceType, publicServiceId) { for (var i = 0, len = this.publicServiceList.length; i < len; i++) { if (this.publicServiceList[i].conversationType == publicServiceType && publicServiceId == this.publicServiceList[i].publicServiceId) { return this.publicServiceList[i]; } } }; PublicServiceMap.prototype.add = function (publicServiceProfile) { var isAdd = true, me = this; for (var i = 0, len = this.publicServiceList.length; i < len; i++) { if (me.publicServiceList[i].conversationType == publicServiceProfile.conversationType && publicServiceProfile.publicServiceId == me.publicServiceList[i].publicServiceId) { this.publicServiceList.unshift(this.publicServiceList.splice(i, 1)[0]); isAdd = false; break; } } if (isAdd) { this.publicServiceList.unshift(publicServiceProfile); } }; PublicServiceMap.prototype.replace = function (publicServiceProfile) { var me = this; for (var i = 0, len = this.publicServiceList.length; i < len; i++) { if (me.publicServiceList[i].conversationType == publicServiceProfile.conversationType && publicServiceProfile.publicServiceId == me.publicServiceList[i].publicServiceId) { me.publicServiceList.splice(i, 1, publicServiceProfile); break; } } }; PublicServiceMap.prototype.remove = function (conversationType, publicServiceId) { var me = this; for (var i = 0, len = this.publicServiceList.length; i < len; i++) { if (me.publicServiceList[i].conversationType == conversationType && publicServiceId == me.publicServiceList[i].publicServiceId) { this.publicServiceList.splice(i, 1); break; } } }; return PublicServiceMap; })(); RongIMLib.PublicServiceMap = PublicServiceMap; /** * 会话工具类。 */ var ConversationMap = (function () { function ConversationMap() { this.conversationList = []; } ConversationMap.prototype.get = function (conversavtionType, targetId) { for (var i = 0, len = this.conversationList.length; i < len; i++) { if (this.conversationList[i].conversationType == conversavtionType && this.conversationList[i].targetId == targetId) { return this.conversationList[i]; } } return null; }; ConversationMap.prototype.add = function (conversation) { var isAdd = true; for (var i = 0, len = this.conversationList.length; i < len; i++) { if (this.conversationList[i].conversationType === conversation.conversationType && this.conversationList[i].targetId === conversation.targetId) { this.conversationList.unshift(this.conversationList.splice(i, 1)[0]); isAdd = false; break; } } if (isAdd) { this.conversationList.unshift(conversation); } }; /** * [replace 替换会话] * 会话数组存在的情况下调用add方法会是当前会话被替换且返回到第一个位置,导致用户本地一些设置失效,所以提供replace方法 */ ConversationMap.prototype.replace = function (conversation) { for (var i = 0, len = this.conversationList.length; i < len; i++) { if (this.conversationList[i].conversationType === conversation.conversationType && this.conversationList[i].targetId === conversation.targetId) { this.conversationList.splice(i, 1, conversation); break; } } }; ConversationMap.prototype.remove = function (conversation) { for (var i = 0, len = this.conversationList.length; i < len; i++) { if (this.conversationList[i].conversationType === conversation.conversationType && this.conversationList[i].targetId === conversation.targetId) { this.conversationList.splice(i, 1); break; } } }; return ConversationMap; })(); RongIMLib.ConversationMap = ConversationMap; var CheckParam = (function () { function CheckParam() { } CheckParam.getInstance = function () { if (!CheckParam._instance) { CheckParam._instance = new CheckParam(); } return CheckParam._instance; }; CheckParam.prototype.logger = function (code, funcName, msg) { RongIMLib.RongIMClient.logger({ code: code, funcName: funcName, msg: msg }); }; CheckParam.prototype.check = function (f, position, d, c) { if (RongIMLib.RongIMClient._dataAccessProvider || d) { for (var g = 0, e = c.length; g < e; g++) { if (!new RegExp(this.getType(c[g])).test(f[g])) { // throw new Error("The index of " + g + " parameter was wrong type " + this.getType(c[g]) + " [" + f[g] + "] -> position:" + position); var msg = "第" + (g + 1) + "个参数错误, 错误类型:" + this.getType(c[g]) + " [" + f[g] + "] -> 位置:" + position; this.logger("-3", position, msg); } } } else { var msg = "该参数不正确或尚未实例化RongIMClient -> 位置:" + position; this.logger("-4", position, msg); } }; CheckParam.prototype.getType = function (str) { var temp = Object.prototype.toString.call(str).toLowerCase(); return temp.slice(8, temp.length - 1); }; CheckParam.prototype.checkCookieDisable = function () { document.cookie = "checkCookie=1"; var arr = document.cookie.match(new RegExp("(^| )checkCookie=([^;]*)(;|$)")), isDisable = false; if (!arr) { isDisable = true; } document.cookie = "checkCookie=1;expires=Thu, 01-Jan-1970 00:00:01 GMT"; return isDisable; }; return CheckParam; })(); RongIMLib.CheckParam = CheckParam; var LimitableMap = (function () { function LimitableMap(limit) { this.map = {}; this.keys = []; this.limit = limit || 10; } LimitableMap.prototype.set = function (key, value) { this.map[key] = value; }; LimitableMap.prototype.get = function (key) { return this.map[key] || 0; }; LimitableMap.prototype.remove = function (key) { delete this.map[key]; }; return LimitableMap; })(); RongIMLib.LimitableMap = LimitableMap; var MemoryCache = (function () { function MemoryCache() { this.cache = {}; } MemoryCache.prototype.set = function (key, value) { this.cache[key] = value; }; MemoryCache.prototype.get = function (key) { return this.cache[key]; }; MemoryCache.prototype.remove = function (key) { delete this.cache[key]; }; return MemoryCache; })(); RongIMLib.MemoryCache = MemoryCache; var RongAjax = (function () { function RongAjax(options) { var me = this; me.xmlhttp = null; me.options = options; var hasCORS = typeof XMLHttpRequest !== "undefined" && "withCredentials" in new XMLHttpRequest(); if ("undefined" != typeof XMLHttpRequest && hasCORS) { me.xmlhttp = new XMLHttpRequest(); } else if ("undefined" != typeof XDomainRequest) { me.xmlhttp = new XDomainRequest(); } else { me.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } } RongAjax.prototype.send = function (callback) { var me = this; me.options.url || (me.options.url = "http://upload.qiniu.com/putb64/-1"); me.xmlhttp.onreadystatechange = function () { if (me.xmlhttp.readyState == 4) { if (me.options.type) { callback(); } else { callback(JSON.parse(me.xmlhttp.responseText.replace(/'/g, '"'))); } } }; me.xmlhttp.open("POST", me.options.url, true); me.xmlhttp.withCredentials = false; if ("setRequestHeader" in me.xmlhttp) { if (me.options.type) { me.xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=utf-8"); } else { me.xmlhttp.setRequestHeader("Content-type", "application/octet-stream"); me.xmlhttp.setRequestHeader('Authorization', "UpToken " + me.options.token); } } me.xmlhttp.send(me.options.type ? "appKey=" + me.options.appKey + "&deviceId=" + me.options.deviceId + "×tamp=" + me.options.timestamp + "&deviceInfo=" + me.options.deviceInfo + "&privateInfo=" + JSON.stringify(me.options.privateInfo) : me.options.base64); }; return RongAjax; })(); RongIMLib.RongAjax = RongAjax; function Prosumer() { var data = [], isConsuming = false; this.produce = function (res) { data.push(res); }; this.consume = function (callback, finished) { if (isConsuming) { return; } isConsuming = true; var next = function () { var res = data.shift(); if (RongUtil.isUndefined(res)) { isConsuming = false; finished && finished(); return; } callback(res, next); }; next(); }; this.isExeuting = function () { return isConsuming; }; } var RongUtil = (function () { function RongUtil() { } RongUtil.noop = function () { }; RongUtil.isEmpty = function (obj) { var result = true; if (RongUtil.isObject(obj)) { RongUtil.forEach(obj, function () { result = false; }); } if (RongUtil.isString(obj) || RongUtil.isArray(obj)) { return obj.length === 0; } if (RongUtil.isNumber(obj)) { return obj === 0; } return result; }; RongUtil.isLengthLimit = function (str, maxLen, minLen) { minLen = minLen || 0; var strLen = str.length; return strLen <= maxLen && strLen >= minLen; }; RongUtil.MD5 = function (str, key, raw) { return md5(str, key, raw); }; RongUtil.isObject = function (obj) { return Object.prototype.toString.call(obj) == '[object Object]'; }; RongUtil.isArray = function (array) { return Object.prototype.toString.call(array) == '[object Array]'; }; RongUtil.isString = function (array) { return Object.prototype.toString.call(array) == '[object String]'; }; RongUtil.isFunction = function (fun) { return Object.prototype.toString.call(fun) == '[object Function]'; }; ; RongUtil.isUndefined = function (str) { return Object.prototype.toString.call(str) == '[object Undefined]'; }; ; RongUtil.isEqual = function (a, b) { return a === b; }; ; RongUtil.indexOf = function (arrs, item) { var index = -1; for (var i = 0; i < arrs.length; i++) { if (item === arrs[i]) { index = i; break; } } return index; }; RongUtil.stringFormat = function (tmpl, vals) { for (var i = 0, len = vals.length; i < len; i++) { var val = vals[i], reg = new RegExp("\\{" + (i) + "\\}", "g"); tmpl = tmpl.replace(reg, val); } return tmpl; }; RongUtil.tplEngine = function (temp, data, regexp) { if (!(Object.prototype.toString.call(data) === "[object Array]")) { data = [data]; } var ret = []; for (var i = 0, j = data.length; i < j; i++) { ret.push(replaceAction(data[i])); } return ret.join(""); function replaceAction(object) { return temp.replace(regexp || (/{([^}]+)}/g), function (match, name) { if (match.charAt(0) == '\\') { return match.slice(1); } return (object[name] != undefined) ? object[name] : '{' + name + '}'; }); } }; ; RongUtil.forEach = function (obj, callback) { callback = callback || RongUtil.noop; var loopObj = function () { for (var key in obj) { if (obj.hasOwnProperty(key)) { callback(obj[key], key, obj); } } }; var loopArr = function () { for (var i = 0, len = obj.length; i < len; i++) { callback(obj[i], i); } }; if (RongUtil.isObject(obj)) { loopObj(); } if (RongUtil.isArray(obj)) { loopArr(); } }; RongUtil.extend = function (source, target, callback, force) { RongUtil.forEach(source, function (val, key) { var hasProto = (key in target); if (force && hasProto) { target[key] = val; } if (!hasProto) { target[key] = val; } }); return target; }; RongUtil.createXHR = function () { var item = { XMLHttpRequest: function () { return new XMLHttpRequest(); }, XDomainRequest: function () { return new XDomainRequest(); }, ActiveXObject: function () { return new ActiveXObject('Microsoft.XMLHTTP'); } }; var isXHR = typeof XMLHttpRequest !== "undefined" && "withCredentials" in new XMLHttpRequest(); var isXDR = typeof XDomainRequest == 'function'; var key = isXHR ? 'XMLHttpRequest' : isXDR ? 'XDomainRequest' : 'ActiveXObject'; return item[key](); }; RongUtil.request = function (opts) { var url = opts.url; var success = opts.success; var error = opts.error; var method = opts.method || 'GET'; var xhr = RongUtil.createXHR(); if ('onload' in xhr) { xhr.onload = function () { xhr.onload = RongUtil.noop; success(xhr.responseText); }; xhr.onerror = function () { xhr.onerror = RongUtil.noop; }; } else { xhr.onreadystatechange = function () { if (xhr.readyState == 4) { var status = xhr.status; if (status == 200) { success(xhr.responseText); } else { error(status, xhr.responseText); } } }; } xhr.open(method, url, true); xhr.send(null); return xhr; }; RongUtil.formatProtoclPath = function (config) { var path = config.path; var protocol = config.protocol; var tmpl = config.tmpl || '{0}{1}'; var sub = config.sub; var flag = '://'; var index = path.indexOf(flag); var hasProtocol = (index > -1); if (hasProtocol) { index += flag.length; path = path.substring(index); } if (sub) { index = path.indexOf('/'); var hasPath = (index > -1); if (hasPath) { path = path.substr(0, index); } } return RongUtil.stringFormat(tmpl, [protocol, path]); }; ; RongUtil.getUrlHost = function (url) { var index = RongUtil.indexOf(url, '/'); return url.substring(0, index); }; RongUtil.supportLocalStorage = function () { var support = false; if (typeof localStorage == 'object') { try { var key = 'RC_TMP_KEY', value = 'RC_TMP_VAL'; localStorage.setItem(key, value); var localVal = localStorage.getItem(key); if (localVal == value) { support = true; } } catch (err) { console.log('localStorage is disabled.'); } } return support; }; /* //返回新引用,不破坏原始对象 rename({n: 'martin'}, {n: 'name'}); => {name: 'martin'} rename([{n: 'martin'}, {a: 18}], {n: 'name', a: 'age'}); => [{name: 'martin'}, {age: 18}] */ RongUtil.rename = function (origin, newNames) { var isObject = RongUtil.isObject(origin); if (isObject) { origin = [origin]; } origin = JSON.parse(JSON.stringify(origin)); var updateProperty = function (val, key, obj) { delete obj[key]; key = newNames[key]; obj[key] = val; }; RongUtil.forEach(origin, function (item) { RongUtil.forEach(item, function (val, key, obj) { var isRename = (key in newNames); (isRename ? updateProperty : RongUtil.noop)(val, key, obj); }); }); return isObject ? origin[0] : origin; }; RongUtil.some = function (arrs, callback) { var has = false; for (var i = 0, len = arrs.length; i < len; i++) { if (callback(arrs[i])) { has = true; break; } } return has; }; RongUtil.keys = function (obj) { var props = []; for (var key in obj) { props.push(key); } return props; }; RongUtil.isNumber = function (num) { return Object.prototype.toString.call(num) == '[object Number]'; }; RongUtil.getTimestamp = function () { var date = new Date(); return date.getTime(); }; RongUtil.isSupportRequestHeaders = function () { var userAgent = navigator.userAgent; var isIE = window.ActiveXObject || 'ActiveXObject' in window; if (isIE) { var reIE = new RegExp('MSIE (\\d+\\.\\d+);'); reIE.test(userAgent); var fIEVersion = parseFloat(RegExp['$1']); return fIEVersion > 9; } return true; }; RongUtil.hasValidWsUrl = function (urls) { try { urls = JSON.parse(urls); } catch (e) { return false; } var validUrlList = RongUtil.getValidWsUrlList(urls); return validUrlList.length > 0; }; RongUtil.getValidWsUrlList = function (urls) { var invalidWsUrls = RongIMLib.RongIMClient.invalidWsUrls; var validUrlList = []; RongUtil.forEach(urls, function (url) { if (RongUtil.indexOf(invalidWsUrls, url) === -1) { validUrlList.push(url); } }); return validUrlList; }; RongUtil.Prosumer = Prosumer; return RongUtil; })(); RongIMLib.RongUtil = RongUtil; /* var observer = new RongObserver(); observer.watch({ key: 'key', func: function(entity){ } }); */ var RongObserver = (function () { function RongObserver() { this.watchers = {}; } RongObserver.prototype.genUId = function (key) { var time = new Date().getTime(); return [key, time].join('_'); }; RongObserver.prototype.watch = function (params) { var me = this; var key = params.key; var multiple = params.multiple; key = RongUtil.isArray(key) ? key : [key]; var func = params.func; RongUtil.forEach(key, function (k) { k = multiple ? me.genUId(k) : k; me.watchers[k] = func; }); }; RongObserver.prototype.notify = function (params) { var me = this; var key = params.key; var entity = params.entity; for (var k in me.watchers) { var isNotify = (k.indexOf(key) == 0); if (isNotify) { me.watchers[k](entity); } } }; RongObserver.prototype.remove = function () { }; return RongObserver; })(); RongIMLib.RongObserver = RongObserver; var Observer = (function () { function Observer() { this.observers = []; } Observer.prototype.add = function (observer, force) { if (force) { this.observers = [observer]; } if (RongUtil.isFunction(observer)) { this.observers.push(observer); } }; Observer.prototype.emit = function (data) { RongUtil.forEach(this.observers, function (observer) { observer(data); }); }; Observer.prototype.clear = function () { this.observers = []; }; Observer.prototype.checkIndexOutBound = function (index, bound) { var isOutBound = (index > -1 && index < bound); return isOutBound; }; Observer.prototype.removeAt = function (index) { var isOutBound = this.checkIndexOutBound(index, this.observers.length); if (isOutBound) { this.observers.splice(index, 1); } }; Observer.prototype.remove = function (observer) { var me = this; if (!observer) { me.clear(); return; } if (!RongUtil.isFunction(observer)) { return; } var observerList = me.observers; for (var i = observerList.length - 1; i >= 0; i--) { if (observer === observerList[i]) { me.removeAt(i); } } }; return Observer; })(); RongIMLib.Observer = Observer; var Timer = (function () { function Timer(config) { this.timeout = 0; this.timers = []; this.timeout = config.timeout; } Timer.prototype.resume = function (callback) { var timer = setTimeout(callback, this.timeout); this.timers.push(timer); }; Timer.prototype.pause = function () { RongUtil.forEach(this.timers, function (timer) { clearTimeout(timer); }); }; return Timer; })(); RongIMLib.Timer = Timer; var IndexTools = (function () { function IndexTools(config) { this.items = []; this.index = 0; this.onwheel = function () { }; this.items = config.items; this.onwheel = config.onwheel; } IndexTools.prototype.get = function () { var context = this; var items = context.items; var index = context.index; var isWheel = index >= items.length; if (isWheel) { context.onwheel(); } return isWheel ? 0 : index; }; IndexTools.prototype.add = function () { this.index += 1; }; return IndexTools; })(); RongIMLib.IndexTools = IndexTools; var InnerUtil = (function () { function InnerUtil() { } InnerUtil.getUId = function (token) { return md5(token).slice(8, 16); }; return InnerUtil; })(); RongIMLib.InnerUtil = InnerUtil; })(RongIMLib || (RongIMLib = {})); // {WebEnd} WebSDK 内容开始的标识, 方便小程序 SDK 定位 /* 说明: 请勿修改 header.js 和 footer.js 用途: 自动拼接暴露方式 命令: grunt release 中 concat */ return RongIMLib; }); ================================================ FILE: api-test-v2/lib/js/RongIMLib-2.5.5-private.js ================================================ /* 说明: 请勿修改 header.js 和 footer.js 用途: 自动拼接暴露方式 命令: grunt release 中 concat */ (function(global, factory) { if (typeof exports === 'object' && typeof module !== 'undefined') { module.exports = factory(); } else if (typeof define === 'function' && (define.amd || define.cmd)) { define(factory); } else { var tempIMLib = factory(); var tempClient = tempIMLib.RongIMClient; var isExists = (!!global.RongIMLib); if (isExists) { var currentClient = RongIMLib.RongIMClient || {}; for(var key in currentClient){ tempClient[key] = currentClient[key]; } } global.RongIMLib = tempIMLib; global.RongIMClient = tempClient; } })(window, function(){ // {WebStart} WebSDK 内容开始的标识, 方便小程序 SDK 定位 var Polling = { SetUserStatusInput: function(){ var a = {}; this.setStatus = function(b){ a.status = b; }; this.toArrayBuffer = function(){ return a; }; }, SetUserStatusOutput: function(){ var a = {}; this.setNothing = function(b){ a.nothing = b; }; this.toArrayBuffer = function(){ return a; }; }, GetUserStatusInput: function(){ var a = {}; this.setNothing = function(b){ a.nothing = b; }; this.toArrayBuffer = function(){ return a; }; }, GetUserStatusOutput: function(){ var a = {}; this.setStatus = function(b){ a.status = b; }; this.setSubUserId = function(b){ a.subUserId = b; }; this.toArrayBuffer = function(){ return a; }; }, VoipDynamicInput: function(){ var a = {}; this.setEngineType = function(b){ a.engineType = b; }; this.setChannelName = function(b){ a.channelName = b; }; this.setChannelExtra = function(b){ a.channelExtra = b; }; this.toArrayBuffer = function(){ return a; }; }, VoipDynamicOutput: function(){ var a = {}; this.setDynamicKey = function(b){ a.dynamicKey = b; }; this.toArrayBuffer = function(){ return a; }; }, SubUserStatusInput: function(){ var a = {}; this.setUserid = function(b){ a.userid = b; }; this.toArrayBuffer = function(){ return a; }; }, SubUserStatusOutput: function(){ var a = {}; this.setNothing = function(b){ a.nothing = b; }; this.toArrayBuffer = function(){ return a; }; }, CleanHisMsgInput: function(){ var a = {}; this.setTargetId = function(b){ a.targetId = b; }; this.setDataTime = function(b){ a.dataTime = b; }; this.setConversationType = function(b){ a.conversationType = b; }; this.toArrayBuffer = function(){ return a; }; }, DeleteMsgInput:function(){ var a = {}; this.setType = function(b){ a.type = b; }; this.setConversationId = function(b){ a.conversationId = b; }; this.setMsgs = function(b){ a.msgs = b; }; this.toArrayBuffer = function () { return a; } }, DeleteMsg:function(){ var a = {}; this.setMsgId = function(b){ a.msgId = b; }; this.setMsgDataTime = function(b){ a.msgDataTime = b; }; this.setDirect = function(b){ a.direct = b; }; this.toArrayBuffer = function () { return a; } }, DeleteMsgOutput:function(){ var a = {}; this.setNothing = function(b){ a.nothing = b; }; this.toArrayBuffer = function () { return a; } }, SearchMpInput:function(){ var a = {}; this.setType = function (b) { a.type = b; }; this.setId = function (b) { a.id = b; }; this.toArrayBuffer = function () { return a; } }, SearchMpOutput:function(){ var a = {}; this.setNothing = function (b) { a.nothing = b; }; this.setInfo = function (b) { a.info = b; }; this.toArrayBuffer = function () { return a; } }, MpInfo:function(){ var a = {}; this.setMpid = function(b){ a.mpid = b; }; this.setName = function(b){ a.name = b; }; this.setType = function(b){ a.type = b; }; this.setTime = function(b){ a.time = b; }; this.setPortraitUri = function(b){ a.portraitUrl = b; }; this.setExtra = function(b){ a.extra = b; }; this.toArrayBuffer = function () { return a; } }, PullMpInput:function(){ var a = {}; this.setMpid = function(b){ a.mpid = b; }; this.setTime = function(b){ a.time = b; }; this.toArrayBuffer = function () { return a; }; }, PullMpOutput:function(){ var a = {}; this.setStatus = function(b){ a.status = b; } this.setInfo = function(b){ a.info = b; }; this.toArrayBuffer = function () { return a; }; }, MPFollowInput:function(){ var a = {}; this.setId = function(b){ a.id = b; }; this.toArrayBuffer = function () { return a; }; }, MPFollowOutput:function(){ var a = {}; this.setNothing = function(b){ a.nothing = b; }; this.setInfo = function(b){ a.info = b; }; this.toArrayBuffer = function () { return a; }; }, NotifyMsg: function () { var a = {}; this.setType = function (b) { a.type = b; }; this.setTime = function (b) { a.time = b; }; this.setChrmId = function(b){ a.chrmId = b; }; this.toArrayBuffer = function () { return a; }; }, SyncRequestMsg: function () { var a = {}; this.setSyncTime = function (b) { a.syncTime = b || 0; }; this.setIspolling = function (b) { a.ispolling = !!b; }; this.setIsweb = function (b) { a.isweb = !!b; }; this.setIsPullSend = function (b) { a.isPullSend = !!b; }; this.setSendBoxSyncTime = function (b) { a.sendBoxSyncTime = b; }; this.toArrayBuffer = function () { return a; }; }, UpStreamMessage: function () { var a = {}; this.setSessionId = function (b) { a.sessionId = b }; this.setClassname = function (b) { a.classname = b }; this.setContent = function (b) { if (b) a.content = b; }; this.setPushText = function (b) { a.pushText = b }; this.setUserId = function(b){ a.userId = b; }; this.setConfigFlag = function (b) { a.configFlag = b; }; this.setAppData = function(b){ a.appData = b; }; this.toArrayBuffer = function () { return a }; }, DownStreamMessages: function () { var a = {}; this.setList = function (b) { a.list = b }; this.setSyncTime = function (b) { a.syncTime = b; }; this.setFinished = function(b){ a.finished = b; }; this.toArrayBuffer = function () { return a }; }, DownStreamMessage: function () { var a = {}; this.setFromUserId = function (b) { a.fromUserId = b }; this.setType = function (b) { a.type = b }; this.setGroupId = function (b) { a.groupId = b }; this.setClassname = function (b) { a.classname = b }; this.setContent = function (b) { if (b) a.content = b }; this.setDataTime = function (b) { a.dataTime = b; }; this.setStatus = function (b) { a.status = b; }; this.setMsgId = function (b) { a.msgId = b; }; this.toArrayBuffer = function () { return a; }; }, CreateDiscussionInput: function () { var a = {}; this.setName = function (b) { a.name = b }; this.toArrayBuffer = function () { return a } }, CreateDiscussionOutput: function () { var a = {}; this.setId = function (b) { a.id = b }; this.toArrayBuffer = function () { return a }; }, ChannelInvitationInput: function () { var a = {}; this.setUsers = function (b) { a.users = b }; this.toArrayBuffer = function () { return a }; }, LeaveChannelInput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b }; this.toArrayBuffer = function () { return a }; }, QueryChatroomInfoInput:function(){ var a = {}; this.setCount = function (b) { a.count = b; }; this.setOrder = function (b) { a.order = b; }; this.toArrayBuffer = function () { return a }; }, QueryChatroomInfoOutput:function(){ var a = {}; this.setUserTotalNums = function (b) { a.userTotalNums = b; }; this.setUserInfos = function (b) { a.userInfos = b; }; this.toArrayBuffer = function () { return a; }; }, ChannelEvictionInput: function () { var a = {}; this.setUser = function (b) { a.user = b }; this.toArrayBuffer = function () { return a }; }, RenameChannelInput: function () { var a = {}; this.setName = function (b) { a.name = b }; this.toArrayBuffer = function () { return a } }, ChannelInfoInput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b }; this.toArrayBuffer = function () { return a } }, ChannelInfoOutput: function () { var a = {}; this.setType = function (b) { a.type = b }; this.setChannelId = function (b) { a.channelId = b }; this.setChannelName = function (b) { a.channelName = b }; this.setAdminUserId = function (b) { a.adminUserId = b }; this.setFirstTenUserIds = function (b) { a.firstTenUserIds = b }; this.setOpenStatus = function (b) { a.openStatus = b }; this.toArrayBuffer = function () { return a } }, ChannelInfosInput: function () { var a = {}; this.setPage = function (b) { a.page = b }; this.setNumber = function (b) { a.number = b }; this.toArrayBuffer = function () { return a }; }, ChannelInfosOutput: function () { var a = {}; this.setChannels = function (b) { a.channels = b }; this.setTotal = function (b) { a.total = b }; this.toArrayBuffer = function () { return a }; }, MemberInfo: function () { var a = {}; this.setUserId = function (b) { a.userId = b }; this.setUserName = function (b) { a.userName = b }; this.setUserPortrait = function (b) { a.userPortrait = b }; this.setExtension = function (b) { a.extension = b }; this.toArrayBuffer = function () { return a }; }, GroupMembersInput: function () { var a = {}; this.setPage = function (b) { a.page = b }; this.setNumber = function (b) { a.number = b }; this.toArrayBuffer = function () { return a }; }, GroupMembersOutput: function () { var a = {}; this.setMembers = function (b) { a.members = b }; this.setTotal = function (b) { a.total = b }; this.toArrayBuffer = function () { return a }; }, GetUserInfoInput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b }; this.toArrayBuffer = function () { return a }; }, GetUserInfoOutput: function () { var a = {}; this.setUserId = function (b) { a.userId = b }; this.setUserName = function (b) { a.userName = b }; this.setUserPortrait = function (b) { a.userPortrait = b }; this.toArrayBuffer = function () { return a }; }, GetSessionIdInput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b }; this.toArrayBuffer = function () { return a }; }, GetSessionIdOutput: function () { var a = {}; this.setSessionId = function (b) { a.sessionId = b }; this.toArrayBuffer = function () { return a }; }, GetQNupTokenInput: function () { var a = {}; this.setType = function (b) { a.type = b; } this.toArrayBuffer = function () { return a } }, GetQNupTokenOutput: function () { var a = {}; this.setDeadline = function (b) { a.deadline = b }; this.setToken = function (b) { a.token = b; }; this.toArrayBuffer = function () { return a } }, GetQNdownloadUrlInput: function () { var a = {}; this.setType = function (b) { a.type = b; }; this.setKey = function (b) { a.key = b; }; this.setFileName = function(b){ a.fileName = b; }; this.toArrayBuffer = function () { return a } }, GetQNdownloadUrlOutput: function () { var a = {}; this.setDownloadUrl = function (b) { a.downloadUrl = b; }; this.toArrayBuffer = function () { return a } }, Add2BlackListInput: function () { var a = {}; this.setUserId = function (b) { a.userId = b; }; this.toArrayBuffer = function () { return a } }, RemoveFromBlackListInput: function () { var a = {}; this.setUserId = function (b) { a.userId = b; }; this.toArrayBuffer = function () { return a } }, QueryBlackListInput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b; }; this.toArrayBuffer = function () { return a } }, QueryBlackListOutput: function () { var a = {}; this.setUserIds = function (b) { a.userIds = b; }; this.toArrayBuffer = function () { return a } }, BlackListStatusInput: function () { var a = {}; this.setUserId = function (b) { a.userId = b; }; this.toArrayBuffer = function () { return a } }, BlockPushInput: function () { var a = {}; this.setBlockeeId = function (b) { a.blockeeId = b; }; this.toArrayBuffer = function () { return a } }, ModifyPermissionInput: function () { var a = {}; this.setOpenStatus = function (b) { a.openStatus = b; }; this.toArrayBuffer = function () { return a }; }, GroupInput: function () { var a = {}; this.setGroupInfo = function (b) { for (var i = 0, arr = []; i < b.length; i++) { arr.push({id: b[i].getContent().id, name: b[i].getContent().name}) } a.groupInfo = arr; }; this.toArrayBuffer = function () { return a }; }, GroupOutput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b; }; this.toArrayBuffer = function () { return a }; }, GroupInfo: function () { var a = {}; this.setId = function (b) { a.id = b; }; this.setName = function (b) { a.name = b; }; this.getContent = function () { return a; }; this.toArrayBuffer = function () { return a }; }, GroupHashInput: function () { var a = {}; this.setUserId = function (b) { a.userId = b; }; this.setGroupHashCode = function (b) { a.groupHashCode = b; }; this.toArrayBuffer = function () { return a }; }, GroupHashOutput: function () { var a = {}; this.setResult = function (b) { a.result = b; }; this.toArrayBuffer = function () { return a }; }, ChrmInput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b; }; this.toArrayBuffer = function () { return a }; }, ChrmOutput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b; }; this.toArrayBuffer = function () { return a }; }, ChrmPullMsg: function () { var a = {}; this.setSyncTime = function (b) { a.syncTime = b }; this.setCount = function (b) { a.count = b; }; this.toArrayBuffer = function () { return a }; }, RelationsInput: function () { var a = {}; this.setType = function (b) { a.type = b; }; this.setMsg = function(b){ a.msg = b; }; this.setCount = function(b){ a.count = b; }; this.toArrayBuffer = function () { return a }; }, RelationsOutput: function () { var a = {}; this.setInfo = function (b) { a.info = b; }; this.toArrayBuffer = function () { return a } }, RelationInfo: function () { var a = {}; this.setType = function (b) { a.type = b; }; this.setUserId = function (b) { a.userId = b; }; this.setMsg = function(b){ a.msg = b; }; this.toArrayBuffer = function () { return a } }, HistoryMessageInput: function () { var a={}; this.setTargetId=function(b){ a.targetId=b; }; this.setDataTime=function(b){ a.dataTime=b; }; this.setSize=function(b){ a.size=b; }; this.toArrayBuffer = function () { return a } }, HistoryMessagesOuput: function () { var a={}; this.setList=function(b){ a.list=b; }; this.setSyncTime=function(b){ a.syncTime=b; }; this.setHasMsg=function(b){ a.hasMsg=b; }; this.toArrayBuffer = function () { return a } }, HistoryMsgInput: function(){ var a = {}; this.setTargetId = function(b){ a.targetId = b; }; this.setTime = function(b){ a.time = b; }; this.setCount = function(b){ a.count = b; }; this.setOrder = function(b){ a.order = b; }; this.toArrayBuffer = function(){ return a; }; }, HistoryMsgOuput: function(){ var a = {}; this.setList = function(b){ a.list = b; }; this.setSyncTime = function(b){ a.syncTime = b; }; this.setHasMsg = function(b){ a.hasMsg = b; }; this.toArrayBuffer = function(){ return a; }; }, RtcQueryListInput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setOrder = function (b) { a.order = b; }; }, RtcKeyDeleteInput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setKey = function (b) { a.key = b; }; }, RtcValueInfo: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setKey = function (b) { a.key = b; }; this.setValue = function (b) { a.value = b; }; }, // RtcUserInfo: function () { // var a = {}; // }, RtcUserListOutput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setList = function (b) { a.list = b; }; this.setToken = function (b) { a.token = b; }; }, RtcRoomInfoOutput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setRoomId = function (b) { a.roomId = b; }; this.setRoomData = function (b) { a.roomData = b; }; this.setUserCount = function (b) { a.userCount = b; }; this.setList = function (b) { a.list = b; } }, RtcInput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setRoomType = function (b) { a.roomType = b; }; this.setBroadcastType = function (b) { a.broadcastType = b; } }, // RtcQryInput: function () { // var a = {}; // }, RtcQryOutput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setOutInfo = function (b) { a.outInfo = b; }; }, // RtcDelDataInput: function () { // var a = {}; // }, RtcDataInput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setInterior = function (b) { a.interior = b; }; this.setTarget = function (b) { a.target = b; }; this.setKey = function (b) { a.key = b; }; this.setObjectName = function (b) { a.objectName = b; }; this.setContent = function (b) { a.content = b; }; }, RtcSetDataInput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setInterior = function (b) { a.interior = b; }; this.setTarget = function (b) { a.target = b; }; this.setKey = function (b) { a.key = b; }; this.setValue = function (b) { a.value = b; }; this.setObjectName = function (b) { a.objectName = b; }; this.setContent = function (b) { a.content = b; }; }, RtcOutput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setNothing = function (b) { a.nothing = b; }; }, RtcTokenOutput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setRtcToken = function (b) { a.rtcToken = b; } }, /** * 聊天室 KV 存储 */ ChrmNotifyMsg: function () { var a = {}; this.toArrayBuffer = function () { return a; }; this.setType = function (b) { a.type = b; }; this.setTime = function (b) { a.time = b; }; this.setChrmId = function (b) { a.chrmId = b; }; }, ChrmKVEntity: function () { var a = {}; this.toArrayBuffer = function () { return a; }; this.setKey = function (key) { a.key = key; }; this.setValue = function (value) { a.value = value; }; this.setStatus = function (b) { a.status = b; }; this.setTimestamp = function (b) { a.timestamp = b; }; this.setUid = function (b) { a.uid = b; }; }, SetChrmKV: function () { var a = {}; this.toArrayBuffer = function () { return a; }; this.setEntry = function (b) { a.entry = b; }; this.setNotification = function (b) { a.notification = b.toArrayBuffer(); }; this.setBNotify = function (b) { a.bNotify = b; }; this.setType = function (b) { a.type = b; }; }, ChrmKVOutput: function () { var a = {}; this.toArrayBuffer = function () { return a; }; this.setEntries = function (b) { this.entries = b; }; this.setBFullUpdate = function (b) { this.bFullUpdate = b; }; this.setSyncTime = function (b) { this.syncTime = b; }; }, QueryChrmKV: function () { var a = {}; this.toArrayBuffer = function () { return a; }; this.setTimestamp = function (b) { a.timestamp = b; }; }, DeleteChrmKV: function () { var a = {}; this.toArrayBuffer = function () { return a; }; this.setEntry = function (b) { a.entry = b; }; this.setBNotify = function (b) { a.bNotify = b; }; this.setNotification = function (b) { a.notification = b.toArrayBuffer(); }; this.setType = function (b) { a.type = b; }; } }; for (var f in Polling) { Polling[f].decode = function (b) { var back = {}, val = JSON.parse(b) || eval("(" + b + ")"); for (var i in val) { back[i]=val[i]; back["get"+ i.charAt(0).toUpperCase()+i.slice(1)]=function(){ return val[i]; } } return back; } } /* * JavaScript MD5 * https://github.com/blueimp/JavaScript-MD5 * * Copyright 2011, Sebastian Tschan * https://blueimp.net * * Licensed under the MIT license: * http://www.opensource.org/licenses/MIT * * Based on * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message * Digest Algorithm, as defined in RFC 1321. * Version 2.2 Copyright (C) Paul Johnston 1999 - 2009 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet * Distributed under the BSD License * See http://pajhome.org.uk/crypt/md5 for more info. */ /*jslint bitwise: true */ /*global unescape, define, module */ var md5 = (function () { 'use strict'; /* * Add integers, wrapping at 2^32. This uses 16-bit operations internally * to work around bugs in some JS interpreters. */ function safe_add(x, y) { var lsw = (x & 0xFFFF) + (y & 0xFFFF), msw = (x >> 16) + (y >> 16) + (lsw >> 16); return (msw << 16) | (lsw & 0xFFFF); } /* * Bitwise rotate a 32-bit number to the left. */ function bit_rol(num, cnt) { return (num << cnt) | (num >>> (32 - cnt)); } /* * These functions implement the four basic operations the algorithm uses. */ function md5_cmn(q, a, b, x, s, t) { return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s), b); } function md5_ff(a, b, c, d, x, s, t) { return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t); } function md5_gg(a, b, c, d, x, s, t) { return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t); } function md5_hh(a, b, c, d, x, s, t) { return md5_cmn(b ^ c ^ d, a, b, x, s, t); } function md5_ii(a, b, c, d, x, s, t) { return md5_cmn(c ^ (b | (~d)), a, b, x, s, t); } /* * Calculate the MD5 of an array of little-endian words, and a bit length. */ function binl_md5(x, len) { /* append padding */ x[len >> 5] |= 0x80 << (len % 32); x[(((len + 64) >>> 9) << 4) + 14] = len; var i, olda, oldb, oldc, oldd, a = 1732584193, b = -271733879, c = -1732584194, d = 271733878; for (i = 0; i < x.length; i += 16) { olda = a; oldb = b; oldc = c; oldd = d; a = md5_ff(a, b, c, d, x[i], 7, -680876936); d = md5_ff(d, a, b, c, x[i + 1], 12, -389564586); c = md5_ff(c, d, a, b, x[i + 2], 17, 606105819); b = md5_ff(b, c, d, a, x[i + 3], 22, -1044525330); a = md5_ff(a, b, c, d, x[i + 4], 7, -176418897); d = md5_ff(d, a, b, c, x[i + 5], 12, 1200080426); c = md5_ff(c, d, a, b, x[i + 6], 17, -1473231341); b = md5_ff(b, c, d, a, x[i + 7], 22, -45705983); a = md5_ff(a, b, c, d, x[i + 8], 7, 1770035416); d = md5_ff(d, a, b, c, x[i + 9], 12, -1958414417); c = md5_ff(c, d, a, b, x[i + 10], 17, -42063); b = md5_ff(b, c, d, a, x[i + 11], 22, -1990404162); a = md5_ff(a, b, c, d, x[i + 12], 7, 1804603682); d = md5_ff(d, a, b, c, x[i + 13], 12, -40341101); c = md5_ff(c, d, a, b, x[i + 14], 17, -1502002290); b = md5_ff(b, c, d, a, x[i + 15], 22, 1236535329); a = md5_gg(a, b, c, d, x[i + 1], 5, -165796510); d = md5_gg(d, a, b, c, x[i + 6], 9, -1069501632); c = md5_gg(c, d, a, b, x[i + 11], 14, 643717713); b = md5_gg(b, c, d, a, x[i], 20, -373897302); a = md5_gg(a, b, c, d, x[i + 5], 5, -701558691); d = md5_gg(d, a, b, c, x[i + 10], 9, 38016083); c = md5_gg(c, d, a, b, x[i + 15], 14, -660478335); b = md5_gg(b, c, d, a, x[i + 4], 20, -405537848); a = md5_gg(a, b, c, d, x[i + 9], 5, 568446438); d = md5_gg(d, a, b, c, x[i + 14], 9, -1019803690); c = md5_gg(c, d, a, b, x[i + 3], 14, -187363961); b = md5_gg(b, c, d, a, x[i + 8], 20, 1163531501); a = md5_gg(a, b, c, d, x[i + 13], 5, -1444681467); d = md5_gg(d, a, b, c, x[i + 2], 9, -51403784); c = md5_gg(c, d, a, b, x[i + 7], 14, 1735328473); b = md5_gg(b, c, d, a, x[i + 12], 20, -1926607734); a = md5_hh(a, b, c, d, x[i + 5], 4, -378558); d = md5_hh(d, a, b, c, x[i + 8], 11, -2022574463); c = md5_hh(c, d, a, b, x[i + 11], 16, 1839030562); b = md5_hh(b, c, d, a, x[i + 14], 23, -35309556); a = md5_hh(a, b, c, d, x[i + 1], 4, -1530992060); d = md5_hh(d, a, b, c, x[i + 4], 11, 1272893353); c = md5_hh(c, d, a, b, x[i + 7], 16, -155497632); b = md5_hh(b, c, d, a, x[i + 10], 23, -1094730640); a = md5_hh(a, b, c, d, x[i + 13], 4, 681279174); d = md5_hh(d, a, b, c, x[i], 11, -358537222); c = md5_hh(c, d, a, b, x[i + 3], 16, -722521979); b = md5_hh(b, c, d, a, x[i + 6], 23, 76029189); a = md5_hh(a, b, c, d, x[i + 9], 4, -640364487); d = md5_hh(d, a, b, c, x[i + 12], 11, -421815835); c = md5_hh(c, d, a, b, x[i + 15], 16, 530742520); b = md5_hh(b, c, d, a, x[i + 2], 23, -995338651); a = md5_ii(a, b, c, d, x[i], 6, -198630844); d = md5_ii(d, a, b, c, x[i + 7], 10, 1126891415); c = md5_ii(c, d, a, b, x[i + 14], 15, -1416354905); b = md5_ii(b, c, d, a, x[i + 5], 21, -57434055); a = md5_ii(a, b, c, d, x[i + 12], 6, 1700485571); d = md5_ii(d, a, b, c, x[i + 3], 10, -1894986606); c = md5_ii(c, d, a, b, x[i + 10], 15, -1051523); b = md5_ii(b, c, d, a, x[i + 1], 21, -2054922799); a = md5_ii(a, b, c, d, x[i + 8], 6, 1873313359); d = md5_ii(d, a, b, c, x[i + 15], 10, -30611744); c = md5_ii(c, d, a, b, x[i + 6], 15, -1560198380); b = md5_ii(b, c, d, a, x[i + 13], 21, 1309151649); a = md5_ii(a, b, c, d, x[i + 4], 6, -145523070); d = md5_ii(d, a, b, c, x[i + 11], 10, -1120210379); c = md5_ii(c, d, a, b, x[i + 2], 15, 718787259); b = md5_ii(b, c, d, a, x[i + 9], 21, -343485551); a = safe_add(a, olda); b = safe_add(b, oldb); c = safe_add(c, oldc); d = safe_add(d, oldd); } return [a, b, c, d]; } /* * Convert an array of little-endian words to a string */ function binl2rstr(input) { var i, output = ''; for (i = 0; i < input.length * 32; i += 8) { output += String.fromCharCode((input[i >> 5] >>> (i % 32)) & 0xFF); } return output; } /* * Convert a raw string to an array of little-endian words * Characters >255 have their high-byte silently ignored. */ function rstr2binl(input) { var i, output = []; output[(input.length >> 2) - 1] = undefined; for (i = 0; i < output.length; i += 1) { output[i] = 0; } for (i = 0; i < input.length * 8; i += 8) { output[i >> 5] |= (input.charCodeAt(i / 8) & 0xFF) << (i % 32); } return output; } /* * Calculate the MD5 of a raw string */ function rstr_md5(s) { return binl2rstr(binl_md5(rstr2binl(s), s.length * 8)); } /* * Calculate the HMAC-MD5, of a key and some data (raw strings) */ function rstr_hmac_md5(key, data) { var i, bkey = rstr2binl(key), ipad = [], opad = [], hash; ipad[15] = opad[15] = undefined; if (bkey.length > 16) { bkey = binl_md5(bkey, key.length * 8); } for (i = 0; i < 16; i += 1) { ipad[i] = bkey[i] ^ 0x36363636; opad[i] = bkey[i] ^ 0x5C5C5C5C; } hash = binl_md5(ipad.concat(rstr2binl(data)), 512 + data.length * 8); return binl2rstr(binl_md5(opad.concat(hash), 512 + 128)); } /* * Convert a raw string to a hex string */ function rstr2hex(input) { var hex_tab = '0123456789abcdef', output = '', x, i; for (i = 0; i < input.length; i += 1) { x = input.charCodeAt(i); output += hex_tab.charAt((x >>> 4) & 0x0F) + hex_tab.charAt(x & 0x0F); } return output; } /* * Encode a string as utf-8 */ function str2rstr_utf8(input) { return unescape(encodeURIComponent(input)); } /* * Take string arguments and return either raw or hex encoded strings */ function raw_md5(s) { return rstr_md5(str2rstr_utf8(s)); } function hex_md5(s) { return rstr2hex(raw_md5(s)); } function raw_hmac_md5(k, d) { return rstr_hmac_md5(str2rstr_utf8(k), str2rstr_utf8(d)); } function hex_hmac_md5(k, d) { return rstr2hex(raw_hmac_md5(k, d)); } function md5(string, key, raw) { if (!key) { if (!raw) { return hex_md5(string); } return raw_md5(string); } if (!raw) { return hex_hmac_md5(key, string); } return raw_hmac_md5(key, string); } return md5; }()); var RongIMLib; (function (RongIMLib) { (function (MentionedType) { MentionedType[MentionedType["ALL"] = 1] = "ALL"; MentionedType[MentionedType["PART"] = 2] = "PART"; })(RongIMLib.MentionedType || (RongIMLib.MentionedType = {})); var MentionedType = RongIMLib.MentionedType; (function (MethodType) { MethodType[MethodType["CUSTOMER_SERVICE"] = 1] = "CUSTOMER_SERVICE"; MethodType[MethodType["RECALL"] = 2] = "RECALL"; })(RongIMLib.MethodType || (RongIMLib.MethodType = {})); var MethodType = RongIMLib.MethodType; (function (BlacklistStatus) { /** * 在黑名单中。 */ BlacklistStatus[BlacklistStatus["IN_BLACK_LIST"] = 0] = "IN_BLACK_LIST"; /** * 不在黑名单中。 */ BlacklistStatus[BlacklistStatus["NOT_IN_BLACK_LIST"] = 1] = "NOT_IN_BLACK_LIST"; })(RongIMLib.BlacklistStatus || (RongIMLib.BlacklistStatus = {})); var BlacklistStatus = RongIMLib.BlacklistStatus; (function (ConnectionChannel) { ConnectionChannel[ConnectionChannel["XHR_POLLING"] = 0] = "XHR_POLLING"; ConnectionChannel[ConnectionChannel["WEBSOCKET"] = 1] = "WEBSOCKET"; //外部调用 ConnectionChannel[ConnectionChannel["HTTP"] = 0] = "HTTP"; //外部调用 ConnectionChannel[ConnectionChannel["HTTPS"] = 1] = "HTTPS"; })(RongIMLib.ConnectionChannel || (RongIMLib.ConnectionChannel = {})); var ConnectionChannel = RongIMLib.ConnectionChannel; (function (CustomerType) { CustomerType[CustomerType["ONLY_ROBOT"] = 1] = "ONLY_ROBOT"; CustomerType[CustomerType["ONLY_HUMAN"] = 2] = "ONLY_HUMAN"; CustomerType[CustomerType["ROBOT_FIRST"] = 3] = "ROBOT_FIRST"; CustomerType[CustomerType["HUMAN_FIRST"] = 4] = "HUMAN_FIRST"; })(RongIMLib.CustomerType || (RongIMLib.CustomerType = {})); var CustomerType = RongIMLib.CustomerType; (function (GetChatRoomType) { GetChatRoomType[GetChatRoomType["NONE"] = 0] = "NONE"; GetChatRoomType[GetChatRoomType["SQQUENCE"] = 1] = "SQQUENCE"; GetChatRoomType[GetChatRoomType["REVERSE"] = 2] = "REVERSE"; })(RongIMLib.GetChatRoomType || (RongIMLib.GetChatRoomType = {})); var GetChatRoomType = RongIMLib.GetChatRoomType; (function (ConnectionStatus) { /** * 连接成功。 */ ConnectionStatus[ConnectionStatus["CONNECTED"] = 0] = "CONNECTED"; /** * 连接中。 */ ConnectionStatus[ConnectionStatus["CONNECTING"] = 1] = "CONNECTING"; /** * 断开连接。 */ ConnectionStatus[ConnectionStatus["DISCONNECTED"] = 2] = "DISCONNECTED"; /** * 用户账户在其他设备登录,本机会被踢掉线。 */ ConnectionStatus[ConnectionStatus["KICKED_OFFLINE_BY_OTHER_CLIENT"] = 6] = "KICKED_OFFLINE_BY_OTHER_CLIENT"; /** * websocket 连接失败 */ ConnectionStatus[ConnectionStatus["WEBSOCKET_UNAVAILABLE"] = 7] = "WEBSOCKET_UNAVAILABLE"; /** * websocket 报错 */ ConnectionStatus[ConnectionStatus["WEBSOCKET_ERROR"] = 8] = "WEBSOCKET_ERROR"; /** * 网络不可用。 */ ConnectionStatus[ConnectionStatus["NETWORK_UNAVAILABLE"] = 3] = "NETWORK_UNAVAILABLE"; /** * 域名错误 */ ConnectionStatus[ConnectionStatus["DOMAIN_INCORRECT"] = 12] = "DOMAIN_INCORRECT"; /** * appkey 不正确 */ ConnectionStatus[ConnectionStatus["APPKEY_IS_FAKE"] = 20] = "APPKEY_IS_FAKE"; /** * 连接关闭。 */ ConnectionStatus[ConnectionStatus["CONNECTION_CLOSED"] = 4] = "CONNECTION_CLOSED"; /* 互踢次数过多(count > 5),此时可能出现:在其它他设备登陆有 reconnect 逻辑 */ ConnectionStatus[ConnectionStatus["ULTRALIMIT"] = 1101] = "ULTRALIMIT"; /* 开始请求导航 */ ConnectionStatus[ConnectionStatus["REQUEST_NAVI"] = 201] = "REQUEST_NAVI"; /* 请求导航结束 */ ConnectionStatus[ConnectionStatus["RESPONSE_NAVI"] = 202] = "RESPONSE_NAVI"; /* 请求导航失败 */ ConnectionStatus[ConnectionStatus["RESPONSE_NAVI_ERROR"] = 203] = "RESPONSE_NAVI_ERROR"; /* 请求导航超时 */ ConnectionStatus[ConnectionStatus["RESPONSE_NAVI_TIMEOUT"] = 204] = "RESPONSE_NAVI_TIMEOUT"; })(RongIMLib.ConnectionStatus || (RongIMLib.ConnectionStatus = {})); var ConnectionStatus = RongIMLib.ConnectionStatus; (function (ConversationNotificationStatus) { /** * 免打扰状态,关闭对应会话的通知提醒。 */ ConversationNotificationStatus[ConversationNotificationStatus["DO_NOT_DISTURB"] = 0] = "DO_NOT_DISTURB"; /** * 提醒。 */ ConversationNotificationStatus[ConversationNotificationStatus["NOTIFY"] = 1] = "NOTIFY"; })(RongIMLib.ConversationNotificationStatus || (RongIMLib.ConversationNotificationStatus = {})); var ConversationNotificationStatus = RongIMLib.ConversationNotificationStatus; (function (ConversationType) { ConversationType[ConversationType["NONE"] = 0] = "NONE"; ConversationType[ConversationType["PRIVATE"] = 1] = "PRIVATE"; ConversationType[ConversationType["DISCUSSION"] = 2] = "DISCUSSION"; ConversationType[ConversationType["GROUP"] = 3] = "GROUP"; ConversationType[ConversationType["CHATROOM"] = 4] = "CHATROOM"; ConversationType[ConversationType["CUSTOMER_SERVICE"] = 5] = "CUSTOMER_SERVICE"; ConversationType[ConversationType["SYSTEM"] = 6] = "SYSTEM"; //默认关注 MC ConversationType[ConversationType["APP_PUBLIC_SERVICE"] = 7] = "APP_PUBLIC_SERVICE"; //手工关注 MP ConversationType[ConversationType["PUBLIC_SERVICE"] = 8] = "PUBLIC_SERVICE"; })(RongIMLib.ConversationType || (RongIMLib.ConversationType = {})); var ConversationType = RongIMLib.ConversationType; (function (DiscussionInviteStatus) { /** * 开放邀请。 */ DiscussionInviteStatus[DiscussionInviteStatus["OPENED"] = 0] = "OPENED"; /** * 关闭邀请。 */ DiscussionInviteStatus[DiscussionInviteStatus["CLOSED"] = 1] = "CLOSED"; })(RongIMLib.DiscussionInviteStatus || (RongIMLib.DiscussionInviteStatus = {})); var DiscussionInviteStatus = RongIMLib.DiscussionInviteStatus; (function (ErrorCode) { /* 超时 */ ErrorCode[ErrorCode["TIMEOUT"] = -1] = "TIMEOUT"; /** * 未知原因失败。 */ ErrorCode[ErrorCode["UNKNOWN"] = -2] = "UNKNOWN"; /* 参数错误 */ ErrorCode[ErrorCode["PARAMETER_ERROR"] = -3] = "PARAMETER_ERROR"; ErrorCode[ErrorCode["RECALL_MESSAGE"] = 25101] = "RECALL_MESSAGE"; /** * 发送频率过快 */ ErrorCode[ErrorCode["SEND_FREQUENCY_TOO_FAST"] = 20604] = "SEND_FREQUENCY_TOO_FAST"; ErrorCode[ErrorCode["RC_MSG_UNAUTHORIZED"] = 20406] = "RC_MSG_UNAUTHORIZED"; /** * 群组 Id 无效 */ ErrorCode[ErrorCode["RC_DISCUSSION_GROUP_ID_INVALID"] = 20407] = "RC_DISCUSSION_GROUP_ID_INVALID"; /** * 群组被禁言 */ ErrorCode[ErrorCode["FORBIDDEN_IN_GROUP"] = 22408] = "FORBIDDEN_IN_GROUP"; /** * 不在讨论组。 */ ErrorCode[ErrorCode["NOT_IN_DISCUSSION"] = 21406] = "NOT_IN_DISCUSSION"; /** * 不在群组。 */ ErrorCode[ErrorCode["NOT_IN_GROUP"] = 22406] = "NOT_IN_GROUP"; /** * 不在聊天室。 */ ErrorCode[ErrorCode["NOT_IN_CHATROOM"] = 23406] = "NOT_IN_CHATROOM"; /** *聊天室被禁言 */ ErrorCode[ErrorCode["FORBIDDEN_IN_CHATROOM"] = 23408] = "FORBIDDEN_IN_CHATROOM"; /** * 聊天室中成员被踢出 */ ErrorCode[ErrorCode["RC_CHATROOM_USER_KICKED"] = 23409] = "RC_CHATROOM_USER_KICKED"; /** * 聊天室不存在 */ ErrorCode[ErrorCode["RC_CHATROOM_NOT_EXIST"] = 23410] = "RC_CHATROOM_NOT_EXIST"; /** * 聊天室成员已满 */ ErrorCode[ErrorCode["RC_CHATROOM_IS_FULL"] = 23411] = "RC_CHATROOM_IS_FULL"; /** * 获取聊天室信息参数无效 */ ErrorCode[ErrorCode["RC_CHATROOM_PATAMETER_INVALID"] = 23412] = "RC_CHATROOM_PATAMETER_INVALID"; /** * 聊天室异常 */ ErrorCode[ErrorCode["CHATROOM_GET_HISTORYMSG_ERROR"] = 23413] = "CHATROOM_GET_HISTORYMSG_ERROR"; /** * 没有打开聊天室消息存储 */ ErrorCode[ErrorCode["CHATROOM_NOT_OPEN_HISTORYMSG_STORE"] = 23414] = "CHATROOM_NOT_OPEN_HISTORYMSG_STORE"; /** * 聊天室 KV 设置超出最大值(已满, 默认最多设置 100 个) */ ErrorCode[ErrorCode["CHATROOM_KV_EXCEED"] = 23423] = "CHATROOM_KV_EXCEED"; /** * 聊天室 KV 设置失败(kv 已存在, 需覆盖设置) */ ErrorCode[ErrorCode["CHATROOM_KV_OVERWRITE_INVALID"] = 23424] = "CHATROOM_KV_OVERWRITE_INVALID"; /** * 聊天室 KV 存储功能没有开通 */ ErrorCode[ErrorCode["CHATROOM_KV_STORE_NOT_OPEN"] = 23426] = "CHATROOM_KV_STORE_NOT_OPEN"; /** * 聊天室Key不存在 */ ErrorCode[ErrorCode["CHATROOM_KEY_NOT_EXIST"] = 23427] = "CHATROOM_KEY_NOT_EXIST"; /** * 敏感词屏蔽 */ ErrorCode[ErrorCode["SENSITIVE_SHIELD"] = 21501] = "SENSITIVE_SHIELD"; ErrorCode[ErrorCode["SENSITIVE_REPLACE"] = 21502] = "SENSITIVE_REPLACE"; /** * 加入讨论失败 */ ErrorCode[ErrorCode["JOIN_IN_DISCUSSION"] = 21407] = "JOIN_IN_DISCUSSION"; /** * 创建讨论组失败 */ ErrorCode[ErrorCode["CREATE_DISCUSSION"] = 21408] = "CREATE_DISCUSSION"; /** * 设置讨论组邀请状态失败 */ ErrorCode[ErrorCode["INVITE_DICUSSION"] = 21409] = "INVITE_DICUSSION"; /** *获取用户失败 */ ErrorCode[ErrorCode["GET_USERINFO_ERROR"] = 23407] = "GET_USERINFO_ERROR"; /** * 在黑名单中。 */ ErrorCode[ErrorCode["REJECTED_BY_BLACKLIST"] = 405] = "REJECTED_BY_BLACKLIST"; /** * 通信过程中,当前 Socket 不存在。 */ ErrorCode[ErrorCode["RC_NET_CHANNEL_INVALID"] = 30001] = "RC_NET_CHANNEL_INVALID"; /** * Socket 连接不可用。 */ ErrorCode[ErrorCode["RC_NET_UNAVAILABLE"] = 30002] = "RC_NET_UNAVAILABLE"; /** * 通信超时。 */ ErrorCode[ErrorCode["RC_MSG_RESP_TIMEOUT"] = 30003] = "RC_MSG_RESP_TIMEOUT"; /** * 导航操作时,Http 请求失败。 */ ErrorCode[ErrorCode["RC_HTTP_SEND_FAIL"] = 30004] = "RC_HTTP_SEND_FAIL"; /** * HTTP 请求失败。 */ ErrorCode[ErrorCode["RC_HTTP_REQ_TIMEOUT"] = 30005] = "RC_HTTP_REQ_TIMEOUT"; /** * HTTP 接收失败。 */ ErrorCode[ErrorCode["RC_HTTP_RECV_FAIL"] = 30006] = "RC_HTTP_RECV_FAIL"; /** * 导航操作的 HTTP 请求,返回不是200。 */ ErrorCode[ErrorCode["RC_NAVI_RESOURCE_ERROR"] = 30007] = "RC_NAVI_RESOURCE_ERROR"; /** * 导航数据解析后,其中不存在有效数据。 */ ErrorCode[ErrorCode["RC_NODE_NOT_FOUND"] = 30008] = "RC_NODE_NOT_FOUND"; /** * 导航数据解析后,其中不存在有效 IP 地址。 */ ErrorCode[ErrorCode["RC_DOMAIN_NOT_RESOLVE"] = 30009] = "RC_DOMAIN_NOT_RESOLVE"; /** * 创建 Socket 失败。 */ ErrorCode[ErrorCode["RC_SOCKET_NOT_CREATED"] = 30010] = "RC_SOCKET_NOT_CREATED"; /** * Socket 被断开。 */ ErrorCode[ErrorCode["RC_SOCKET_DISCONNECTED"] = 30011] = "RC_SOCKET_DISCONNECTED"; /** * PING 操作失败。 */ ErrorCode[ErrorCode["RC_PING_SEND_FAIL"] = 30012] = "RC_PING_SEND_FAIL"; /** * PING 超时。 */ ErrorCode[ErrorCode["RC_PONG_RECV_FAIL"] = 30013] = "RC_PONG_RECV_FAIL"; /** * 消息发送失败。 */ ErrorCode[ErrorCode["RC_MSG_SEND_FAIL"] = 30014] = "RC_MSG_SEND_FAIL"; /** * 做 connect 连接时,收到的 ACK 超时。 */ ErrorCode[ErrorCode["RC_CONN_ACK_TIMEOUT"] = 31000] = "RC_CONN_ACK_TIMEOUT"; /** * 参数错误。 */ ErrorCode[ErrorCode["RC_CONN_PROTO_VERSION_ERROR"] = 31001] = "RC_CONN_PROTO_VERSION_ERROR"; /** * 参数错误,App Id 错误。 */ ErrorCode[ErrorCode["RC_CONN_ID_REJECT"] = 31002] = "RC_CONN_ID_REJECT"; /** * 服务器不可用。 */ ErrorCode[ErrorCode["RC_CONN_SERVER_UNAVAILABLE"] = 31003] = "RC_CONN_SERVER_UNAVAILABLE"; /** * Token 错误。 */ ErrorCode[ErrorCode["RC_CONN_USER_OR_PASSWD_ERROR"] = 31004] = "RC_CONN_USER_OR_PASSWD_ERROR"; /** * App Id 与 Token 不匹配。 */ ErrorCode[ErrorCode["RC_CONN_NOT_AUTHRORIZED"] = 31005] = "RC_CONN_NOT_AUTHRORIZED"; /** * 重定向,地址错误。 */ ErrorCode[ErrorCode["RC_CONN_REDIRECTED"] = 31006] = "RC_CONN_REDIRECTED"; /** * NAME 与后台注册信息不一致。 */ ErrorCode[ErrorCode["RC_CONN_PACKAGE_NAME_INVALID"] = 31007] = "RC_CONN_PACKAGE_NAME_INVALID"; /** * APP 被屏蔽、删除或不存在。 */ ErrorCode[ErrorCode["RC_CONN_APP_BLOCKED_OR_DELETED"] = 31008] = "RC_CONN_APP_BLOCKED_OR_DELETED"; /** * 用户被屏蔽。 */ ErrorCode[ErrorCode["RC_CONN_USER_BLOCKED"] = 31009] = "RC_CONN_USER_BLOCKED"; /** * Disconnect,由服务器返回,比如用户互踢。 */ ErrorCode[ErrorCode["RC_DISCONN_KICK"] = 31010] = "RC_DISCONN_KICK"; /** * Disconnect,由服务器返回,比如用户互踢。 */ ErrorCode[ErrorCode["RC_DISCONN_EXCEPTION"] = 31011] = "RC_DISCONN_EXCEPTION"; /** * 协议层内部错误。query,上传下载过程中数据错误。 */ ErrorCode[ErrorCode["RC_QUERY_ACK_NO_DATA"] = 32001] = "RC_QUERY_ACK_NO_DATA"; /** * 协议层内部错误。 */ ErrorCode[ErrorCode["RC_MSG_DATA_INCOMPLETE"] = 32002] = "RC_MSG_DATA_INCOMPLETE"; /** * 未调用 init 初始化函数。 */ ErrorCode[ErrorCode["BIZ_ERROR_CLIENT_NOT_INIT"] = 33001] = "BIZ_ERROR_CLIENT_NOT_INIT"; /** * 数据库初始化失败。 */ ErrorCode[ErrorCode["BIZ_ERROR_DATABASE_ERROR"] = 33002] = "BIZ_ERROR_DATABASE_ERROR"; /** * 传入参数无效。 */ ErrorCode[ErrorCode["BIZ_ERROR_INVALID_PARAMETER"] = 33003] = "BIZ_ERROR_INVALID_PARAMETER"; /** * 通道无效。 */ ErrorCode[ErrorCode["BIZ_ERROR_NO_CHANNEL"] = 33004] = "BIZ_ERROR_NO_CHANNEL"; /** * 重新连接成功。 */ ErrorCode[ErrorCode["BIZ_ERROR_RECONNECT_SUCCESS"] = 33005] = "BIZ_ERROR_RECONNECT_SUCCESS"; /** * 连接中,再调用 connect 被拒绝。 */ ErrorCode[ErrorCode["BIZ_ERROR_CONNECTING"] = 33006] = "BIZ_ERROR_CONNECTING"; /** * 消息漫游服务未开通 */ ErrorCode[ErrorCode["MSG_ROAMING_SERVICE_UNAVAILABLE"] = 33007] = "MSG_ROAMING_SERVICE_UNAVAILABLE"; ErrorCode[ErrorCode["MSG_INSERT_ERROR"] = 33008] = "MSG_INSERT_ERROR"; ErrorCode[ErrorCode["MSG_DEL_ERROR"] = 33009] = "MSG_DEL_ERROR"; /** * 删除会话失败 */ ErrorCode[ErrorCode["CONVER_REMOVE_ERROR"] = 34001] = "CONVER_REMOVE_ERROR"; /** *拉取历史消息 */ ErrorCode[ErrorCode["CONVER_GETLIST_ERROR"] = 34002] = "CONVER_GETLIST_ERROR"; /** * 会话指定异常 */ ErrorCode[ErrorCode["CONVER_SETOP_ERROR"] = 34003] = "CONVER_SETOP_ERROR"; /** * 获取会话未读消息总数失败 */ ErrorCode[ErrorCode["CONVER_TOTAL_UNREAD_ERROR"] = 34004] = "CONVER_TOTAL_UNREAD_ERROR"; /** * 获取指定会话类型未读消息数异常 */ ErrorCode[ErrorCode["CONVER_TYPE_UNREAD_ERROR"] = 34005] = "CONVER_TYPE_UNREAD_ERROR"; /** * 获取指定用户ID&会话类型未读消息数异常 */ ErrorCode[ErrorCode["CONVER_ID_TYPE_UNREAD_ERROR"] = 34006] = "CONVER_ID_TYPE_UNREAD_ERROR"; ErrorCode[ErrorCode["CONVER_CLEAR_ERROR"] = 34007] = "CONVER_CLEAR_ERROR"; ErrorCode[ErrorCode["CLEAR_HIS_ERROR"] = 34010] = "CLEAR_HIS_ERROR"; ErrorCode[ErrorCode["CLEAR_HIS_TYPE_ERROR"] = 34008] = "CLEAR_HIS_TYPE_ERROR"; ErrorCode[ErrorCode["CLEAR_HIS_TIME_ERROR"] = 34011] = "CLEAR_HIS_TIME_ERROR"; /* */ ErrorCode[ErrorCode["CONVER_GET_ERROR"] = 34009] = "CONVER_GET_ERROR"; //群组异常信息 /** * */ ErrorCode[ErrorCode["GROUP_SYNC_ERROR"] = 35001] = "GROUP_SYNC_ERROR"; /** * 匹配群信息异常 */ ErrorCode[ErrorCode["GROUP_MATCH_ERROR"] = 35002] = "GROUP_MATCH_ERROR"; //聊天室异常 /** * 加入聊天室Id为空 */ ErrorCode[ErrorCode["CHATROOM_ID_ISNULL"] = 36001] = "CHATROOM_ID_ISNULL"; /** * 加入聊天室失败 */ ErrorCode[ErrorCode["CHARTOOM_JOIN_ERROR"] = 36002] = "CHARTOOM_JOIN_ERROR"; /** * 拉取聊天室历史消息失败 */ ErrorCode[ErrorCode["CHATROOM_HISMESSAGE_ERROR"] = 36003] = "CHATROOM_HISMESSAGE_ERROR"; /** * 聊天室 kv 未找到 * */ ErrorCode[ErrorCode["CHATROOM_KV_NOT_FOUND"] = 36004] = "CHATROOM_KV_NOT_FOUND"; //黑名单异常 /** * 加入黑名单异常 */ ErrorCode[ErrorCode["BLACK_ADD_ERROR"] = 37001] = "BLACK_ADD_ERROR"; /** * 获得指定人员再黑名单中的状态异常 */ ErrorCode[ErrorCode["BLACK_GETSTATUS_ERROR"] = 37002] = "BLACK_GETSTATUS_ERROR"; /** * 移除黑名单异常 */ ErrorCode[ErrorCode["BLACK_REMOVE_ERROR"] = 37003] = "BLACK_REMOVE_ERROR"; /** * 获取草稿失败 */ ErrorCode[ErrorCode["DRAF_GET_ERROR"] = 38001] = "DRAF_GET_ERROR"; /** * 保存草稿失败 */ ErrorCode[ErrorCode["DRAF_SAVE_ERROR"] = 38002] = "DRAF_SAVE_ERROR"; /** * 删除草稿失败 */ ErrorCode[ErrorCode["DRAF_REMOVE_ERROR"] = 38003] = "DRAF_REMOVE_ERROR"; /** * 关注公众号失败 */ ErrorCode[ErrorCode["SUBSCRIBE_ERROR"] = 39001] = "SUBSCRIBE_ERROR"; /** * 关注公众号失败 */ ErrorCode[ErrorCode["QNTKN_FILETYPE_ERROR"] = 41001] = "QNTKN_FILETYPE_ERROR"; /** * 获取七牛token失败 */ ErrorCode[ErrorCode["QNTKN_GET_ERROR"] = 41002] = "QNTKN_GET_ERROR"; /** * cookie被禁用 */ ErrorCode[ErrorCode["COOKIE_ENABLE"] = 51001] = "COOKIE_ENABLE"; ErrorCode[ErrorCode["GET_MESSAGE_BY_ID_ERROR"] = 61001] = "GET_MESSAGE_BY_ID_ERROR"; // 没有注册DeviveId 也就是用户没有登陆 ErrorCode[ErrorCode["HAVNODEVICEID"] = 24001] = "HAVNODEVICEID"; // 已经存在 ErrorCode[ErrorCode["DEVICEIDISHAVE"] = 24002] = "DEVICEIDISHAVE"; // 成功 ErrorCode[ErrorCode["SUCCESS"] = 0] = "SUCCESS"; // 没有对应的用户或token ErrorCode[ErrorCode["FEILD"] = 24009] = "FEILD"; // voip为空 ErrorCode[ErrorCode["VOIPISNULL"] = 24013] = "VOIPISNULL"; // 不支持的Voip引擎 ErrorCode[ErrorCode["NOENGINETYPE"] = 24010] = "NOENGINETYPE"; // channleName 是空 ErrorCode[ErrorCode["NULLCHANNELNAME"] = 24011] = "NULLCHANNELNAME"; // 生成Voipkey失败 ErrorCode[ErrorCode["VOIPDYANMICERROR"] = 24012] = "VOIPDYANMICERROR"; // 没有配置voip ErrorCode[ErrorCode["NOVOIP"] = 24014] = "NOVOIP"; // 服务器内部错误 ErrorCode[ErrorCode["INTERNALERRROR"] = 24015] = "INTERNALERRROR"; //VOIP close ErrorCode[ErrorCode["VOIPCLOSE"] = 24016] = "VOIPCLOSE"; ErrorCode[ErrorCode["CLOSE_BEFORE_OPEN"] = 51001] = "CLOSE_BEFORE_OPEN"; ErrorCode[ErrorCode["ALREADY_IN_USE"] = 51002] = "ALREADY_IN_USE"; ErrorCode[ErrorCode["INVALID_CHANNEL_NAME"] = 51003] = "INVALID_CHANNEL_NAME"; ErrorCode[ErrorCode["VIDEO_CONTAINER_IS_NULL"] = 51004] = "VIDEO_CONTAINER_IS_NULL"; /** * 删除消息数组长度为 0 . */ ErrorCode[ErrorCode["DELETE_MESSAGE_ID_IS_NULL"] = 61001] = "DELETE_MESSAGE_ID_IS_NULL"; /*! 己方取消已发出的通话请求 */ ErrorCode[ErrorCode["CANCEL"] = 1] = "CANCEL"; /*! 己方拒绝收到的通话请求 */ ErrorCode[ErrorCode["REJECT"] = 2] = "REJECT"; /*! 己方挂断 */ ErrorCode[ErrorCode["HANGUP"] = 3] = "HANGUP"; /*! 己方忙碌 */ ErrorCode[ErrorCode["BUSYLINE"] = 4] = "BUSYLINE"; /*! 己方未接听 */ ErrorCode[ErrorCode["NO_RESPONSE"] = 5] = "NO_RESPONSE"; /*! 己方不支持当前引擎 */ ErrorCode[ErrorCode["ENGINE_UN_SUPPORTED"] = 6] = "ENGINE_UN_SUPPORTED"; /*! 己方网络出错 */ ErrorCode[ErrorCode["NETWORK_ERROR"] = 7] = "NETWORK_ERROR"; /*! 对方取消已发出的通话请求 */ ErrorCode[ErrorCode["REMOTE_CANCEL"] = 11] = "REMOTE_CANCEL"; /*! 对方拒绝收到的通话请求 */ ErrorCode[ErrorCode["REMOTE_REJECT"] = 12] = "REMOTE_REJECT"; /*! 通话过程对方挂断 */ ErrorCode[ErrorCode["REMOTE_HANGUP"] = 13] = "REMOTE_HANGUP"; /*! 对方忙碌 */ ErrorCode[ErrorCode["REMOTE_BUSYLINE"] = 14] = "REMOTE_BUSYLINE"; /*! 对方未接听 */ ErrorCode[ErrorCode["REMOTE_NO_RESPONSE"] = 15] = "REMOTE_NO_RESPONSE"; /*! 对方网络错误 */ ErrorCode[ErrorCode["REMOTE_ENGINE_UN_SUPPORTED"] = 16] = "REMOTE_ENGINE_UN_SUPPORTED"; /*! 对方网络错误 */ ErrorCode[ErrorCode["REMOTE_NETWORK_ERROR"] = 17] = "REMOTE_NETWORK_ERROR"; /*! VoIP 不可用 */ ErrorCode[ErrorCode["VOIP_NOT_AVALIABLE"] = 18] = "VOIP_NOT_AVALIABLE"; })(RongIMLib.ErrorCode || (RongIMLib.ErrorCode = {})); var ErrorCode = RongIMLib.ErrorCode; (function (VoIPMediaType) { VoIPMediaType[VoIPMediaType["MEDIA_AUDIO"] = 1] = "MEDIA_AUDIO"; VoIPMediaType[VoIPMediaType["MEDIA_VEDIO"] = 2] = "MEDIA_VEDIO"; VoIPMediaType[VoIPMediaType["MEDIA_VIDEO"] = 2] = "MEDIA_VIDEO"; })(RongIMLib.VoIPMediaType || (RongIMLib.VoIPMediaType = {})); var VoIPMediaType = RongIMLib.VoIPMediaType; (function (MediaType) { /** * 图片。 */ MediaType[MediaType["IMAGE"] = 1] = "IMAGE"; /** * 声音。 */ MediaType[MediaType["AUDIO"] = 2] = "AUDIO"; /** * 视频。 */ MediaType[MediaType["VIDEO"] = 3] = "VIDEO"; /** * 通用文件。 */ MediaType[MediaType["FILE"] = 100] = "FILE"; })(RongIMLib.MediaType || (RongIMLib.MediaType = {})); var MediaType = RongIMLib.MediaType; (function (MessageDirection) { /** * 发送消息。 */ MessageDirection[MessageDirection["SEND"] = 1] = "SEND"; /** * 接收消息。 */ MessageDirection[MessageDirection["RECEIVE"] = 2] = "RECEIVE"; })(RongIMLib.MessageDirection || (RongIMLib.MessageDirection = {})); var MessageDirection = RongIMLib.MessageDirection; (function (FileType) { FileType[FileType["IMAGE"] = 1] = "IMAGE"; FileType[FileType["AUDIO"] = 2] = "AUDIO"; FileType[FileType["VIDEO"] = 3] = "VIDEO"; FileType[FileType["FILE"] = 4] = "FILE"; })(RongIMLib.FileType || (RongIMLib.FileType = {})); var FileType = RongIMLib.FileType; (function (RealTimeLocationErrorCode) { /** * 未初始化 RealTimeLocation 实例 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_NOT_INIT"] = -1] = "RC_REAL_TIME_LOCATION_NOT_INIT"; /** * 执行成功。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_SUCCESS"] = 0] = "RC_REAL_TIME_LOCATION_SUCCESS"; /** * 获取 RealTimeLocation 实例时返回 * GPS 未打开。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_GPS_DISABLED"] = 1] = "RC_REAL_TIME_LOCATION_GPS_DISABLED"; /** * 获取 RealTimeLocation 实例时返回 * 当前会话不支持位置共享。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_CONVERSATION_NOT_SUPPORT"] = 2] = "RC_REAL_TIME_LOCATION_CONVERSATION_NOT_SUPPORT"; /** * 获取 RealTimeLocation 实例时返回 * 对方已发起位置共享。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_IS_ON_GOING"] = 3] = "RC_REAL_TIME_LOCATION_IS_ON_GOING"; /** * Join 时返回 * 当前位置共享已超过最大支持人数。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_EXCEED_MAX_PARTICIPANT"] = 4] = "RC_REAL_TIME_LOCATION_EXCEED_MAX_PARTICIPANT"; /** * Join 时返回 * 加入位置共享失败。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_JOIN_FAILURE"] = 5] = "RC_REAL_TIME_LOCATION_JOIN_FAILURE"; /** * Start 时返回 * 发起位置共享失败。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_START_FAILURE"] = 6] = "RC_REAL_TIME_LOCATION_START_FAILURE"; /** * 网络不可用。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_NETWORK_UNAVAILABLE"] = 7] = "RC_REAL_TIME_LOCATION_NETWORK_UNAVAILABLE"; })(RongIMLib.RealTimeLocationErrorCode || (RongIMLib.RealTimeLocationErrorCode = {})); var RealTimeLocationErrorCode = RongIMLib.RealTimeLocationErrorCode; (function (RealTimeLocationStatus) { /** * 空闲状态 (默认状态) * 对方或者自己都未发起位置共享业务,或者位置共享业务已结束。 */ RealTimeLocationStatus[RealTimeLocationStatus["RC_REAL_TIME_LOCATION_STATUS_IDLE"] = 0] = "RC_REAL_TIME_LOCATION_STATUS_IDLE"; /** * 呼入状态 (待加入) * 1. 对方发起了位置共享业务,此状态下,自己只能选择加入。 * 2. 自己从已连接的位置共享中退出。 */ RealTimeLocationStatus[RealTimeLocationStatus["RC_REAL_TIME_LOCATION_STATUS_INCOMING"] = 1] = "RC_REAL_TIME_LOCATION_STATUS_INCOMING"; /** * 呼出状态 =(自己创建) * 1. 自己发起位置共享业务,对方只能选择加入。 * 2. 对方从已连接的位置共享业务中退出。 */ RealTimeLocationStatus[RealTimeLocationStatus["RC_REAL_TIME_LOCATION_STATUS_OUTGOING"] = 2] = "RC_REAL_TIME_LOCATION_STATUS_OUTGOING"; /** * 连接状态 (自己加入) * 对方加入了自己发起的位置共享,或者自己加入了对方发起的位置共享。 */ RealTimeLocationStatus[RealTimeLocationStatus["RC_REAL_TIME_LOCATION_STATUS_CONNECTED"] = 3] = "RC_REAL_TIME_LOCATION_STATUS_CONNECTED"; })(RongIMLib.RealTimeLocationStatus || (RongIMLib.RealTimeLocationStatus = {})); var RealTimeLocationStatus = RongIMLib.RealTimeLocationStatus; (function (ReceivedStatus) { ReceivedStatus[ReceivedStatus["READ"] = 1] = "READ"; ReceivedStatus[ReceivedStatus["LISTENED"] = 2] = "LISTENED"; ReceivedStatus[ReceivedStatus["DOWNLOADED"] = 4] = "DOWNLOADED"; ReceivedStatus[ReceivedStatus["RETRIEVED"] = 8] = "RETRIEVED"; ReceivedStatus[ReceivedStatus["UNREAD"] = 0] = "UNREAD"; })(RongIMLib.ReceivedStatus || (RongIMLib.ReceivedStatus = {})); var ReceivedStatus = RongIMLib.ReceivedStatus; (function (ReadStatus) { ReadStatus[ReadStatus["READ"] = 1] = "READ"; ReadStatus[ReadStatus["LISTENED"] = 2] = "LISTENED"; ReadStatus[ReadStatus["DOWNLOADED"] = 4] = "DOWNLOADED"; ReadStatus[ReadStatus["RETRIEVED"] = 8] = "RETRIEVED"; ReadStatus[ReadStatus["UNREAD"] = 0] = "UNREAD"; })(RongIMLib.ReadStatus || (RongIMLib.ReadStatus = {})); var ReadStatus = RongIMLib.ReadStatus; (function (SearchType) { /** * 精确。 */ SearchType[SearchType["EXACT"] = 0] = "EXACT"; /** * 模糊。 */ SearchType[SearchType["FUZZY"] = 1] = "FUZZY"; })(RongIMLib.SearchType || (RongIMLib.SearchType = {})); var SearchType = RongIMLib.SearchType; (function (SentStatus) { /** * 发送中。 */ SentStatus[SentStatus["SENDING"] = 10] = "SENDING"; /** * 发送失败。 */ SentStatus[SentStatus["FAILED"] = 20] = "FAILED"; /** * 已发送。 */ SentStatus[SentStatus["SENT"] = 30] = "SENT"; /** * 对方已接收。 */ SentStatus[SentStatus["RECEIVED"] = 40] = "RECEIVED"; /** * 对方已读。 */ SentStatus[SentStatus["READ"] = 50] = "READ"; /** * 对方已销毁。 */ SentStatus[SentStatus["DESTROYED"] = 60] = "DESTROYED"; })(RongIMLib.SentStatus || (RongIMLib.SentStatus = {})); var SentStatus = RongIMLib.SentStatus; (function (ConnectionState) { ConnectionState[ConnectionState["ACCEPTED"] = 0] = "ACCEPTED"; ConnectionState[ConnectionState["UNACCEPTABLE_PROTOCOL_VERSION"] = 1] = "UNACCEPTABLE_PROTOCOL_VERSION"; ConnectionState[ConnectionState["IDENTIFIER_REJECTED"] = 2] = "IDENTIFIER_REJECTED"; ConnectionState[ConnectionState["SERVER_UNAVAILABLE"] = 3] = "SERVER_UNAVAILABLE"; /** * token无效 */ ConnectionState[ConnectionState["TOKEN_INCORRECT"] = 4] = "TOKEN_INCORRECT"; ConnectionState[ConnectionState["NOT_AUTHORIZED"] = 5] = "NOT_AUTHORIZED"; ConnectionState[ConnectionState["REDIRECT"] = 6] = "REDIRECT"; ConnectionState[ConnectionState["PACKAGE_ERROR"] = 7] = "PACKAGE_ERROR"; ConnectionState[ConnectionState["APP_BLOCK_OR_DELETE"] = 8] = "APP_BLOCK_OR_DELETE"; ConnectionState[ConnectionState["BLOCK"] = 9] = "BLOCK"; ConnectionState[ConnectionState["TOKEN_EXPIRE"] = 10] = "TOKEN_EXPIRE"; ConnectionState[ConnectionState["DEVICE_ERROR"] = 11] = "DEVICE_ERROR"; })(RongIMLib.ConnectionState || (RongIMLib.ConnectionState = {})); var ConnectionState = RongIMLib.ConnectionState; (function (RTCAPIType) { RTCAPIType[RTCAPIType["ROOM"] = 1] = "ROOM"; RTCAPIType[RTCAPIType["PERSON"] = 2] = "PERSON"; })(RongIMLib.RTCAPIType || (RongIMLib.RTCAPIType = {})); var RTCAPIType = RongIMLib.RTCAPIType; (function (ChatroomEntityOpt) { ChatroomEntityOpt[ChatroomEntityOpt["UPDATE"] = 1] = "UPDATE"; ChatroomEntityOpt[ChatroomEntityOpt["DELETE"] = 2] = "DELETE"; })(RongIMLib.ChatroomEntityOpt || (RongIMLib.ChatroomEntityOpt = {})); var ChatroomEntityOpt = RongIMLib.ChatroomEntityOpt; (function (ChatroomEntityLimit) { ChatroomEntityLimit[ChatroomEntityLimit["KEY"] = 128] = "KEY"; ChatroomEntityLimit[ChatroomEntityLimit["VALUE"] = 4096] = "VALUE"; })(RongIMLib.ChatroomEntityLimit || (RongIMLib.ChatroomEntityLimit = {})); var ChatroomEntityLimit = RongIMLib.ChatroomEntityLimit; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var RongIMClient = (function () { function RongIMClient() { } RongIMClient.getInstance = function () { if (!RongIMClient._instance) { throw new Error("RongIMClient is not initialized. Call .init() method first."); } return RongIMClient._instance; }; RongIMClient.showError = function (errorInfo) { var hasConsole = (console && console.error); if (hasConsole) { console.error(JSON.stringify(errorInfo)); } }; RongIMClient.logger = function (params) { var code = params.code; var errorInfo = RongIMClient.LogFactory[code] || params; errorInfo.funcName = params.funcName; errorInfo.msg = params.msg || errorInfo.msg; if (RongIMClient._memoryStore.depend.showError) { RongIMClient.showError(errorInfo); } }; RongIMClient.logCallback = function (callback, funcName) { return { onSuccess: callback.onSuccess, onError: function (errorCode) { RongIMClient.logger({ code: errorCode, funcName: funcName }); callback.onError(errorCode); } }; }; ; RongIMClient.logSendCallback = function (callback, funcName) { return { onSuccess: callback.onSuccess, onError: function (errorCode, result) { RongIMClient.logger({ code: errorCode, funcName: funcName }); callback.onError(errorCode, result); }, onBefore: callback.onBefore }; }; ; /** * 初始化 SDK,在整个应用全局只需要调用一次。 * @param appKey 开发者后台申请的 AppKey,用来标识应用。 * @param dataAccessProvider 必须是DataAccessProvider的实例 */ RongIMClient.init = function (appKey, dataAccessProvider, options, callback) { RongIMClient.statusListeners = []; RongIMClient.messageListeners = []; if (RongIMClient._instance) { return RongIMClient._memoryStore.sdkInfo; } RongIMClient._instance = new RongIMClient(); options = options || {}; var protocol = "http://", wsScheme = 'ws://'; var isLocationInvalid = typeof location !== 'object'; // 未找到全局 location 变量, 则协议为 https. 比如小程序 if (isLocationInvalid || location.protocol == 'https:') { wsScheme = 'wss://'; protocol = 'https://'; } var isPolling = false; if (typeof WebSocket != 'function') { isPolling = true; } var isIntegrity = function () { //iOS 9 var hasWS = (typeof WebSocket); var integrity = (typeof WebSocket.OPEN == 'number'); return (hasWS && integrity); }; if (typeof WebSocket == 'object' && isIntegrity()) { isPolling = false; } var supportUserData = function () { var element = document.documentElement; return element.addBehavior; }; if (RongIMLib.RongUtil.supportLocalStorage()) { RongIMClient._storageProvider = new RongIMLib.LocalStorageProvider(); } else if (supportUserData()) { RongIMClient._storageProvider = new RongIMLib.UserDataProvider(); } else { RongIMClient._storageProvider = new RongIMLib.MemeoryProvider(); } var serverIndex = RongIMClient._storageProvider.getItem('serverIndex'); RongIMClient.serverStore.index = serverIndex || 0; var pathTmpl = '{0}{1}'; var _serverPath = { api: 'api.cn.ronghub.com' }; RongIMLib.RongUtil.forEach(_serverPath, function (path, key) { _serverPath[key] = RongIMLib.RongUtil.stringFormat(pathTmpl, [protocol, path]); }); RongIMLib.RongUtil.forEach(_serverPath, function (path, key) { var hasProto = (key in options); var config = { path: options[key], tmpl: pathTmpl, protocol: protocol, sub: true }; path = hasProto ? RongIMLib.RongUtil.formatProtoclPath(config) : path; options[key] = path; }); var navigaters = options.navigaters || []; if (options.navi) { navigaters = [options.navi]; } if (!options.navi && RongIMLib.RongUtil.isEqual(navigaters.length, 0)) { navigaters = ['nav.cn.ronghub.com', 'nav2-cn.ronghub.com']; } RongIMLib.RongUtil.forEach(navigaters, function (navi, index) { var config = { path: navi, tmpl: pathTmpl, protocol: protocol, sub: true }; navi = RongIMLib.RongUtil.formatProtoclPath(config); navigaters[index] = navi; }); var _sourcePath = { protobuf: 'cdn.ronghub.com/protobuf-2.3.7.min.js' }; RongIMLib.RongUtil.forEach(_sourcePath, function (path, key) { _sourcePath[key] = RongIMLib.RongUtil.stringFormat(pathTmpl, [protocol, path]); }); RongIMLib.RongUtil.extend(_sourcePath, options); var _defaultOpts = { isPolling: isPolling, wsScheme: wsScheme, protocol: protocol, showError: true, openMp: true, snifferTime: 2000, naviTimeout: 5000, navigaters: navigaters, maxNaviRetry: 10, isNaviJSONP: true, isWSPingJSONP: true, isNotifyConversationList: false, maxConversationCount: 300, cmpUrl: '' // 若传入 cmpUrl, 则优先链接此地址 }; delete options.navigaters; RongIMLib.RongUtil.extend(_defaultOpts, options); if (RongIMLib.RongUtil.isFunction(options.protobuf)) { RongIMClient.Protobuf = options.protobuf; } RongIMClient.userStatusObserver = new RongIMLib.RongObserver(); var pather = new RongIMLib.FeaturePatcher(); pather.patchAll(); var tempStore = { token: "", callback: null, lastReadTime: new RongIMLib.LimitableMap(), historyMessageLimit: new RongIMLib.MemoryCache(), conversationList: [], appKey: appKey, publicServiceMap: new RongIMLib.PublicServiceMap(), providerType: 1, deltaTime: 0, filterMessages: [], isSyncRemoteConverList: true, otherDevice: false, custStore: {}, converStore: { latestMessage: {} }, connectAckTime: 0, voipStategy: 0, isFirstPingMsg: true, depend: options, notification: {} }; RongIMClient._memoryStore = tempStore; var isCPlusSDK = dataAccessProvider && Object.prototype.toString.call(dataAccessProvider) == "[object Object]"; if (isCPlusSDK) { RongIMClient._dataAccessProvider = dataAccessProvider; } else { RongIMClient._dataAccessProvider = new RongIMLib.ServerDataProvider(); } options.appCallback = callback; var sdkInfo = RongIMClient._dataAccessProvider.init(appKey, options); RongIMClient._memoryStore.sdkInfo = sdkInfo; if (isCPlusSDK) { // 兼容 c++ 设置导航,Web 端不生效 RongIMClient._dataAccessProvider.setServerInfo({ navi: location.protocol + options.navi + '/navi.xml' }); } RongIMClient.MessageParams = { TextMessage: { objectName: "RC:TxtMsg", msgTag: new RongIMLib.MessageTag(true, true) }, ImageMessage: { objectName: "RC:ImgMsg", msgTag: new RongIMLib.MessageTag(true, true) }, DiscussionNotificationMessage: { objectName: "RC:DizNtf", msgTag: new RongIMLib.MessageTag(false, true) }, VoiceMessage: { objectName: "RC:VcMsg", msgTag: new RongIMLib.MessageTag(true, true) }, RichContentMessage: { objectName: "RC:ImgTextMsg", msgTag: new RongIMLib.MessageTag(true, true) }, FileMessage: { objectName: "RC:FileMsg", msgTag: new RongIMLib.MessageTag(true, true) }, HQVoiceMessage: { objectName: "RC:HQVCMsg", msgTag: new RongIMLib.MessageTag(true, true) }, HandshakeMessage: { objectName: "", msgTag: new RongIMLib.MessageTag(true, true) }, UnknownMessage: { objectName: "", msgTag: new RongIMLib.MessageTag(true, true) }, LocationMessage: { objectName: "RC:LBSMsg", msgTag: new RongIMLib.MessageTag(true, true) }, InformationNotificationMessage: { objectName: "RC:InfoNtf", msgTag: new RongIMLib.MessageTag(false, true) }, ContactNotificationMessage: { objectName: "RC:ContactNtf", msgTag: new RongIMLib.MessageTag(false, true) }, ProfileNotificationMessage: { objectName: "RC:ProfileNtf", msgTag: new RongIMLib.MessageTag(false, true) }, CommandNotificationMessage: { objectName: "RC:CmdNtf", msgTag: new RongIMLib.MessageTag(false, true) }, PublicServiceRichContentMessage: { objectName: "RC:PSImgTxtMsg", msgTag: new RongIMLib.MessageTag(true, true) }, PublicServiceMultiRichContentMessage: { objectName: "RC:PSMultiImgTxtMsg", msgTag: new RongIMLib.MessageTag(true, true) }, JrmfRedPacketMessage: { objectName: "RCJrmf:RpMsg", msgTag: new RongIMLib.MessageTag(true, true) }, JrmfRedPacketOpenedMessage: { objectName: "RCJrmf:RpOpendMsg", msgTag: new RongIMLib.MessageTag(true, true) }, GroupNotificationMessage: { objectName: "RC:GrpNtf", msgTag: new RongIMLib.MessageTag(false, true) }, CommandMessage: { objectName: "RC:CmdMsg", msgTag: new RongIMLib.MessageTag(false, false) }, TypingStatusMessage: { objectName: "RC:TypSts", msgTag: new RongIMLib.MessageTag(false, false) }, PublicServiceCommandMessage: { objectName: "RC:PSCmd", msgTag: new RongIMLib.MessageTag(false, false) }, RecallCommandMessage: { objectName: "RC:RcCmd", msgTag: new RongIMLib.MessageTag(false, true) }, SyncReadStatusMessage: { objectName: "RC:SRSMsg", msgTag: new RongIMLib.MessageTag(false, false) }, ReadReceiptRequestMessage: { objectName: "RC:RRReqMsg", msgTag: new RongIMLib.MessageTag(false, false) }, ReadReceiptResponseMessage: { objectName: "RC:RRRspMsg", msgTag: new RongIMLib.MessageTag(false, false) }, ChangeModeResponseMessage: { objectName: "RC:CsChaR", msgTag: new RongIMLib.MessageTag(false, false) }, ChangeModeMessage: { objectName: "RC:CSCha", msgTag: new RongIMLib.MessageTag(false, false) }, EvaluateMessage: { objectName: "RC:CsEva", msgTag: new RongIMLib.MessageTag(false, false) }, CustomerContact: { objectName: "RC:CsContact", msgTag: new RongIMLib.MessageTag(false, false) }, HandShakeMessage: { objectName: "RC:CsHs", msgTag: new RongIMLib.MessageTag(false, false) }, HandShakeResponseMessage: { objectName: "RC:CsHsR", msgTag: new RongIMLib.MessageTag(false, false) }, SuspendMessage: { objectName: "RC:CsSp", msgTag: new RongIMLib.MessageTag(false, false) }, TerminateMessage: { objectName: "RC:CsEnd", msgTag: new RongIMLib.MessageTag(false, false) }, CustomerStatusUpdateMessage: { objectName: "RC:CsUpdate", msgTag: new RongIMLib.MessageTag(false, false) }, ReadReceiptMessage: { objectName: "RC:ReadNtf", msgTag: new RongIMLib.MessageTag(false, false) }, RCCombineMessage: { objectName: "RC:CombineMsg", msgTag: new RongIMLib.MessageTag(true, true) }, ChrmKVNotificationMessage: { objectName: 'RC:chrmKVNotiMsg', msgTag: new RongIMLib.MessageTag(false, false) } }; RongIMClient.MessageParams["AcceptMessage"] = { objectName: "RC:VCAccept", msgTag: new RongIMLib.MessageTag(false, false) }; RongIMClient.MessageParams["RingingMessage"] = { objectName: "RC:VCRinging", msgTag: new RongIMLib.MessageTag(false, false) }; RongIMClient.MessageParams["SummaryMessage"] = { objectName: "RC:VCSummary", msgTag: new RongIMLib.MessageTag(false, false) }; RongIMClient.MessageParams["HungupMessage"] = { objectName: "RC:VCHangup", msgTag: new RongIMLib.MessageTag(false, false) }; RongIMClient.MessageParams["InviteMessage"] = { objectName: "RC:VCInvite", msgTag: new RongIMLib.MessageTag(false, false) }; RongIMClient.MessageParams["MediaModifyMessage"] = { objectName: "RC:VCModifyMedia", msgTag: new RongIMLib.MessageTag(false, false) }; RongIMClient.MessageParams["MemberModifyMessage"] = { objectName: "RC:VCModifyMem", msgTag: new RongIMLib.MessageTag(false, false) }; RongIMClient.MessageType = { TextMessage: "TextMessage", ImageMessage: "ImageMessage", DiscussionNotificationMessage: "DiscussionNotificationMessage", VoiceMessage: "VoiceMessage", RichContentMessage: "RichContentMessage", HandshakeMessage: "HandshakeMessage", UnknownMessage: "UnknownMessage", LocationMessage: "LocationMessage", InformationNotificationMessage: "InformationNotificationMessage", ContactNotificationMessage: "ContactNotificationMessage", ProfileNotificationMessage: "ProfileNotificationMessage", CommandNotificationMessage: "CommandNotificationMessage", CommandMessage: "CommandMessage", TypingStatusMessage: "TypingStatusMessage", ChangeModeResponseMessage: "ChangeModeResponseMessage", ChangeModeMessage: "ChangeModeMessage", EvaluateMessage: "EvaluateMessage", HandShakeMessage: "HandShakeMessage", HandShakeResponseMessage: "HandShakeResponseMessage", SuspendMessage: "SuspendMessage", TerminateMessage: "TerminateMessage", CustomerContact: "CustomerContact", CustomerStatusUpdateMessage: "CustomerStatusUpdateMessage", SyncReadStatusMessage: "SyncReadStatusMessage", ReadReceiptRequestMessage: "ReadReceiptRequestMessage", ReadReceiptResponseMessage: "ReadReceiptResponseMessage", FileMessage: 'FileMessage', HQVoiceMessage: 'HQVoiceMessage', AcceptMessage: "AcceptMessage", RingingMessage: "RingingMessage", SummaryMessage: "SummaryMessage", HungupMessage: "HungupMessage", InviteMessage: "InviteMessage", MediaModifyMessage: "MediaModifyMessage", MemberModifyMessage: "MemberModifyMessage", JrmfRedPacketMessage: "JrmfRedPacketMessage", JrmfRedPacketOpenedMessage: "JrmfRedPacketOpenedMessage", GroupNotificationMessage: "GroupNotificationMessage", PublicServiceRichContentMessage: "PublicServiceRichContentMessage", PublicServiceMultiRichContentMessage: "PublicServiceMultiRichContentMessage", PublicServiceCommandMessage: "PublicServiceCommandMessage", RecallCommandMessage: "RecallCommandMessage", ReadReceiptMessage: "ReadReceiptMessage", RCCombineMessage: "RCCombineMessage", ChrmKVNotificationMessage: 'ChrmKVNotificationMessage' }; RongIMClient.LogFactory = { /** * 个人 */ "-1": { code: "-1", msg: "服务器超时" }, "-2": { code: "-2", msg: "未知原因失败" }, "-3": { code: "-3", msg: "参数错误" }, "-4": { code: "-4", msg: "参数不正确或尚未实例化" }, "25101": { code: "25101", msg: "撤回消息参数错误", desc: "请检查撤回消息参数 https://rongcloud.github.io/websdk-demo/api-test.html" }, "25102": { code: "25101", msg: "只能撤回自发发送的消息" }, "20604": { code: "20604", msg: "发送频率过快", desc: "https://developer.rongcloud.cn/ticket/info/9Q3L6vRKd1cLS7rycA==?type=1" }, "20406": { code: "20406", msg: "被禁言" }, "23407": { code: "23407", msg: "获取用户失败" }, /** * 群组 */ "20407": { code: "20407", msg: "群组Id无效" }, "22408": { code: "22408", msg: "群组被禁言" }, "22406": { code: "22406", msg: "不在群组" }, "35001": { code: "35001", msg: "群组同步异常" }, "35002": { code: "35002", msg: "匹配群信息异常" }, /** * 讨论组 */ "21406": { code: "21406", msg: "不在讨论组" }, "21407": { code: "21407", msg: "加入讨论失败" }, "21408": { code: "21408", msg: "创建讨论组失败" }, "21409": { code: "21409", msg: "设置讨论组邀请状态失败" }, /** * 聊天室 */ "23406": { code: "23406", msg: "不在聊天室" }, "23408": { code: "23408", msg: "聊天室被禁言" }, "23409": { code: "23409", msg: "聊天室中成员被踢出" }, "23410": { code: "23410", msg: "聊天室不存在" }, "23411": { code: "23411", msg: "聊天室成员已满" }, "23412": { code: "23412", msg: "获取聊天室信息参数无效" }, "23413": { code: "23413", msg: "聊天室异常" }, "23414": { code: "23414", msg: "没有打开聊天室消息存储" }, "36001": { code: "36001", msg: "加入聊天室Id为空" }, "36002": { code: "36002", msg: "加入聊天室失败" }, "36003": { code: "36003", msg: "拉取聊天室历史消息失败" }, /** * voip */ "24001": { code: "24001", msg: "没有注册DeviveId 也就是用户没有登陆" }, "24002": { code: "24002", msg: "用户已经存在" }, "0": { code: "0", msg: "成功" }, "24009": { code: "24009", msg: "没有对应的用户或token" }, "24013": { code: "24013", msg: "voip为空" }, "24010": { code: "24010", msg: "不支持的Voip引擎" }, "24011": { code: "24011", msg: "channelName 是空" }, "24012": { code: "24012", msg: "生成Voipkey失败" }, "24014": { code: "24014", msg: "没有配置voip" }, "24015": { code: "24015", msg: "服务器内部错误" }, "24016": { code: "24016", msg: "VOIP close" }, /** * 通讯、导航 */ "30001": { code: "30001", msg: "通信过程中,当前Socket不存在" }, "30002": { code: "30002", msg: "Socket连接不可用" }, "30003": { code: "30003", msg: "通信超时" }, "30004": { code: "30004", msg: "导航操作时,Http请求失败" }, "30005": { code: "30005", msg: "HTTP请求失败" }, "30006": { code: "30006", msg: "HTTP接收失败" }, "30007": { code: "30007", msg: "导航资源错误" }, "30008": { code: "30008", msg: "没有有效数据" }, "30009": { code: "30009", msg: "不存在有效 IP 地址" }, "30010": { code: "30010", msg: "创建 Socket 失败" }, "30011": { code: "30011", msg: " Socket 被断开" }, "30012": { code: "30012", msg: "PING 操作失败" }, "30013": { code: "30013", msg: "PING 超时" }, "30014": { code: "30014", msg: "消息发送失败" }, "30016": { code: "30016", msg: "消息大小超限,最大 128 KB" }, /** * 连接 */ "31000": { code: "31000", msg: "做 connect 连接时,收到的 ACK 超时" }, "31001": { code: "31001", msg: "参数错误" }, "31002": { code: "31002", msg: "参数错误,App Id 错误" }, "31003": { code: "31003", msg: "服务器不可用" }, "31004": { code: "31004", msg: "Token 错误" }, "31005": { code: "31005", msg: "App Id 与 Token 不匹配" }, "31006": { code: "31006", msg: "重定向,地址错误" }, "31007": { code: "31007", msg: "NAME 与后台注册信息不一致" }, "31008": { code: "31008", msg: "APP 被屏蔽、删除或不存在" }, "31009": { code: "31009", msg: "用户被屏蔽" }, "31010": { code: "31010", msg: "Disconnect,由服务器返回,比如用户互踢" }, "31011": { code: "31011", msg: "Disconnect,由服务器返回,比如用户互踢" }, /** * 协议 */ "32001": { code: "32001", msg: "协议层内部错误。query,上传下载过程中数据错误" }, "32002": { code: "32002", msg: "协议层内部错误" }, /** * BIZ */ "33001": { code: "33001", msg: "未调用 init 初始化函数" }, "33002": { code: "33002", msg: "数据库初始化失败" }, "33003": { code: "33003", msg: "传入参数无效" }, "33004": { code: "33004", msg: "通道无效" }, "33005": { code: "33005", msg: "重新连接成功" }, "33006": { code: "33006", msg: "连接中,再调用 connect 被拒绝" }, "33007": { code: "33007", msg: "消息漫游服务未开通" }, "33008": { code: "33008", msg: "消息添加失败" }, "33009": { code: "33009", msg: "消息删除失败" }, /** * 会话 */ "34001": { code: "34001", msg: "删除会话失败" }, "34002": { code: "34002", msg: "拉取历史消息失败" }, "34003": { code: "34003", msg: "会话指定异常" }, "34004": { code: "34004", msg: "获取会话未读消息总数失败" }, "34005": { code: "34005", msg: "获取指定会话类型未读消息数异常" }, "34006": { code: "34006", msg: "获取指定用户ID&会话类型未读消息数异常" }, "34007": { code: "34007", msg: "清除会话消息异常" }, "34008": { code: "34008", msg: "获取会话消息异常" }, "34009": { code: "34009", msg: "清除历史消息会话类型不正确" }, "34010": { code: "34010", msg: "清除历史消息失败,请检查传入参数" }, /** * 黑名单异常 */ "37001": { code: "37001", msg: "加入黑名单异常" }, "37002": { code: "37002", msg: "获得指定人员再黑名单中的状态异常" }, "37003": { code: "37003", msg: "移除黑名单异常" }, "405": { code: "405", msg: "在黑名单中" }, /** * 草稿 */ "38001": { code: "38001", msg: "获取草稿失败" }, "38002": { code: "38002", msg: "保存草稿失败" }, "38003": { code: "38003", msg: "删除草稿失败" }, /** * 公众号 */ "39001": { code: "39001", msg: "关注公众号失败" }, /** * 文件 */ "41001": { code: "41001", msg: "文件类型错误" }, "41002": { code: "41002", msg: "获取七牛token失败" }, /** * */ "51001": { code: "51001", msg: "未安装或未启动插件" }, "51002": { code: "51002", msg: "视频已经存在" }, "51003": { code: "51003", msg: "无效的channelName" }, "51004": { code: "51004", msg: "视频内容为空" }, /** * */ "61001": { code: "61001", msg: "删除消息数组长度为 0" } }; var handler = function (message, uris, callback) { var userId = message.senderUserId; var _uris = RongIMClient.roomInfo.users[userId].uris || '[]'; if (RongIMLib.RongUtil.isString(_uris)) { _uris = JSON.parse(_uris); } var tUris = JSON.parse(JSON.stringify(_uris)); RongIMLib.RongUtil.forEach(tUris, function (_uri, index) { RongIMLib.RongUtil.forEach(uris, function (uri) { if (uri.uri == _uri.uri) { callback(_uri, uri, _uris, index); } }); }); RongIMClient.roomInfo.users[userId].uris = JSON.stringify(_uris); }; var RTCMessage = { RTCPublishResourceMessage: function (message, uris) { var userId = message.senderUserId; var user = RongIMClient.roomInfo.users[userId]; if (!user) { user = {}; RongIMClient.roomInfo.users[userId] = {}; } var _uris = user.uris || '[]'; if (RongIMLib.RongUtil.isString(_uris)) { _uris = JSON.parse(_uris); } _uris = _uris.concat(uris); RongIMClient.roomInfo.users[userId].uris = JSON.stringify(_uris); }, RTCUnpublishResourceMessage: function (message, uris) { handler(message, uris, function (_uri, uri, _uris, index) { _uris.splice(index, 1); }); }, RTCModifyResourceMessage: function (message, uris) { handler(message, uris, function (_uri, uri) { _uri.state = uri.state; }); }, RTCUserChangeMessage: function (message) { var content = message.content; var users = content.users; var UserState = { JOINED: 0, LEFT: 1, OFFLINE: 2 }; RongIMLib.RongUtil.forEach(users, function (user) { var state = user.state; var userId = user.userId; switch (+state) { case UserState.JOINED: RongIMClient.roomInfo.users[userId] = {}; break; case UserState.LEFT: case UserState.OFFLINE: delete RongIMClient.roomInfo.users[userId]; break; } }); } }; RongIMClient.RTCInnerListener = function (message) { var func = RTCMessage[message.messageType] || function () { }; var content = message.content; var uris = content.uris; func(message, uris); }; RongIMClient.Conversation = RongIMClient._dataAccessProvider.Conversation; return sdkInfo; }; ; /** var config = { appkey: appkey, token: token, dataAccessProvider:dataAccessProvider, opts: opts }; callback(_instance, userId); */ RongIMClient.initApp = function (config, callback) { RongIMClient.init(config.appkey, config.dataAccessProvider, config.opts, function () { var instance = RongIMClient._instance; //备用 var error = null; callback(error, instance); }); }; /** * 连接服务器,在整个应用全局只需要调用一次,断线后 SDK 会自动重连。 * * @param token 从服务端获取的用户身份令牌(Token)。 * @param callback 连接回调,返回连接的成功或者失败状态。 */ RongIMClient.connect = function (token, _callback, userId, serverConf) { RongIMLib.CheckParam.getInstance().check(["string", "object", "string|null|object|global|undefined", "object|null|global|undefined"], "connect", true, arguments); var connectCallback = { onSuccess: _callback.onSuccess, onTokenIncorrect: _callback.onTokenIncorrect, onError: function (errorCode) { RongIMClient.logger({ code: errorCode, funcName: "connect" }); _callback.onError(errorCode); } }; RongIMClient._dataAccessProvider.connect(token, connectCallback, userId, serverConf); }; RongIMClient.reconnect = function (callback, config) { var connectCallback = { onSuccess: callback.onSuccess, onTokenIncorrect: callback.onTokenIncorrect, onError: function (errorCode) { RongIMClient.logger({ code: errorCode, funcName: "connect" }); callback.onError(errorCode); } }; RongIMClient._dataAccessProvider.reconnect(connectCallback, config); }; /** * 注册消息类型,用于注册用户自定义的消息。 * 内建的消息类型已经注册过,不需要再次注册。 * 自定义消息声明需放在执行顺序最高的位置(在RongIMClient.init(appkey)之后即可) * @param objectName 消息内置名称 */ RongIMClient.registerMessageType = function (messageType, objectName, messageTag, messageContent, searchProps) { RongIMClient._dataAccessProvider.registerMessageType(messageType, objectName, messageTag, messageContent, searchProps); RongIMClient.RegisterMessage[messageType].messageName = messageType; RongIMClient.MessageType[messageType] = messageType; RongIMClient.MessageParams[messageType] = { objectName: objectName, msgTag: messageTag }; }; RongIMClient.prototype.registerMessageTypes = function (types) { types = types || {}; RongIMClient._dataAccessProvider.registerMessageTypes(types); }; /** * 设置连接状态变化的监听器。 * * @param listener 连接状态变化的监听器。 */ RongIMClient.setConnectionStatusListener = function (listener) { if (RongIMClient._dataAccessProvider) { RongIMClient._dataAccessProvider.setConnectionStatusListener(listener); } else { if (RongIMLib.RongUtil.isObject(listener) && RongIMLib.RongUtil.isFunction(listener.onChanged)) { RongIMClient.statusListeners.push(listener.onChanged); } } }; RongIMClient.statusWatch = function (watcher) { if (RongIMLib.RongUtil.isFunction(watcher)) { RongIMClient.statusListeners.push(watcher); } }; /** * 设置接收消息的监听器。 * * @param listener 接收消息的监听器。 */ RongIMClient.setOnReceiveMessageListener = function (listener) { if (RongIMClient._dataAccessProvider) { RongIMClient._dataAccessProvider.setOnReceiveMessageListener(listener); } else { if (RongIMLib.RongUtil.isObject(listener) && RongIMLib.RongUtil.isFunction(listener.onReceived)) { RongIMClient.messageListeners.push(listener.onReceived); } } }; /** * 清理所有连接相关的变量 */ RongIMClient.prototype.logout = function () { RongIMClient._dataAccessProvider.logout(); }; /** * 断开连接。 */ RongIMClient.prototype.disconnect = function () { RongIMClient._dataAccessProvider.disconnect(); }; RongIMClient.prototype.startCustomService = function (custId, callback, content) { if (!custId || !callback) return; var msg = new RongIMLib.HandShakeMessage(content); var me = this; RongIMLib.RongIMClient._memoryStore.custStore["isInit"] = true; RongIMClient.getInstance().sendMessage(RongIMLib.ConversationType.CUSTOMER_SERVICE, custId, msg, { onSuccess: function (data) { if (data.isBlack) { callback.onError(); me.stopCustomeService(custId, { onSuccess: function () { }, onError: function () { } }); } else { callback.onSuccess(); } }, onError: function () { callback.onError(); }, onBefore: function () { } }); }; RongIMClient.prototype.stopCustomeService = function (custId, callback) { if (!custId || !callback) return; var session = RongIMClient._memoryStore.custStore[custId]; if (!session) return; var msg = new RongIMLib.SuspendMessage({ sid: session.sid, uid: session.uid, pid: session.pid }); this.sendCustMessage(custId, msg, { onSuccess: function () { // delete RongIMClient._memoryStore.custStore[custId]; setTimeout(function () { callback.onSuccess(); }); }, onError: function () { setTimeout(function () { callback.onError(); }); } }); }; RongIMClient.prototype.switchToHumanMode = function (custId, callback) { if (!custId || !callback) return; var session = RongIMClient._memoryStore.custStore[custId]; if (!session) return; var msg = new RongIMLib.ChangeModeMessage({ sid: session.sid, uid: session.uid, pid: session.pid }); this.sendCustMessage(custId, msg, callback); }; RongIMClient.prototype.evaluateRebotCustomService = function (custId, isRobotResolved, sugest, callback) { if (!custId || !callback) return; var session = RongIMClient._memoryStore.custStore[custId]; if (!session) return; var msg = new RongIMLib.EvaluateMessage({ sid: session.sid, uid: session.uid, pid: session.pid, isRobotResolved: isRobotResolved, sugest: sugest, type: 0 }); this.sendCustMessage(custId, msg, callback); }; RongIMClient.prototype.evaluateHumanCustomService = function (custId, humanValue, sugest, callback) { if (!custId || !callback) return; var session = RongIMClient._memoryStore.custStore[custId]; if (!session) return; var msg = new RongIMLib.EvaluateMessage({ sid: session.sid, uid: session.uid, pid: session.pid, humanValue: humanValue, sugest: sugest, type: 1 }); this.sendCustMessage(custId, msg, callback); }; RongIMClient.prototype.sendCustMessage = function (custId, msg, callback) { RongIMClient.getInstance().sendMessage(RongIMLib.ConversationType.CUSTOMER_SERVICE, custId, msg, { onSuccess: function (data) { callback.onSuccess(); }, onError: function () { callback.onError(); }, onBefore: function () { } }); }; /** * 获取当前连接的状态。 */ RongIMClient.prototype.getCurrentConnectionStatus = function () { return RongIMClient._dataAccessProvider.getCurrentConnectionStatus(); }; /** * 获取当前使用的连接通道。 */ RongIMClient.prototype.getConnectionChannel = function () { if (RongIMLib.Transportations._TransportType == RongIMLib.Socket.XHR_POLLING) { return RongIMLib.ConnectionChannel.XHR_POLLING; } else if (RongIMLib.Transportations._TransportType == RongIMLib.Socket.WEBSOCKET) { return RongIMLib.ConnectionChannel.WEBSOCKET; } }; /** * 获取当前使用的本地储存提供者。 TODO */ RongIMClient.prototype.getStorageProvider = function () { if (RongIMClient._memoryStore.providerType == 1) { return "ServerDataProvider"; } else { return "OtherDataProvider"; } }; /** * 过滤聊天室消息(拉取最近聊天消息) * @param {string[]} msgFilterNames */ RongIMClient.prototype.setFilterMessages = function (msgFilterNames) { if (Object.prototype.toString.call(msgFilterNames) == "[object Array]") { RongIMClient._memoryStore.filterMessages = msgFilterNames; } }; RongIMClient.prototype.getAgoraDynamicKey = function (engineType, channelName, callback) { RongIMClient._dataAccessProvider.getAgoraDynamicKey(engineType, channelName, callback); }; /** * 获取当前连接用户的 UserId。 */ RongIMClient.prototype.getCurrentUserId = function () { return RongIMLib.Bridge._client.userId; }; /** * 获取服务器时间与本地时间的差值,单位为毫秒。 * 计算公式:差值 = 本地时间毫秒数 - 服务器时间毫秒数 * @param callback 获取的回调,返回差值。 */ RongIMClient.prototype.getDeltaTime = function () { return RongIMClient._dataAccessProvider.getDelaTime(); }; // #region Message RongIMClient.prototype.getMessage = function (messageId, callback) { RongIMClient._dataAccessProvider.getMessage(messageId, RongIMClient.logCallback(callback, "getMessage")); }; RongIMClient.prototype.deleteLocalMessages = function (conversationType, targetId, messageIds, callback) { RongIMClient._dataAccessProvider.removeLocalMessage(conversationType, targetId, messageIds, RongIMClient.logCallback(callback, "deleteLocalMessages")); }; RongIMClient.prototype.updateMessage = function (message, callback) { RongIMClient._dataAccessProvider.updateMessage(message, RongIMClient.logCallback(callback, "updateMessage")); }; RongIMClient.prototype.clearData = function () { return RongIMClient._dataAccessProvider.clearData(); }; RongIMClient.prototype.clearMessages = function (conversationType, targetId, callback) { RongIMClient._dataAccessProvider.clearMessages(conversationType, targetId, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "clearMessages" }); callback.onError(errorCode); }); } }); }; /**TODO 清楚本地存储的未读消息,目前清空内存中的未读消息 * [clearMessagesUnreadStatus 清空指定会话未读消息] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [用户id] * @param {ResultCallback} callback [返回值,参数回调] */ RongIMClient.prototype.clearMessagesUnreadStatus = function (conversationType, targetId, callback) { RongIMClient._dataAccessProvider.updateMessages(conversationType, targetId, "readStatus", null, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "clearMessagesUnreadStatus" }); callback.onError(errorCode); }); } }); }; // deleteRemoteMessages(conversationType: ConversationType, targetId: string, delMsgs: DeleteMessage[], callback: ResultCallback) { // CheckParam.getInstance().check(["number", "string|number", "array", "object"], "deleteRemoteMessages", false, arguments); // if (delMsgs.length == 0) { // var errorCode = ErrorCode.DELETE_MESSAGE_ID_IS_NULL; // RongIMClient.logger({ // code: errorCode, // funcName: "deleteRemoteMessages" // }); // callback.onError(ErrorCode.DELETE_MESSAGE_ID_IS_NULL); // return; // } else if (delMsgs.length > 100) { // delMsgs.length = 100; // } // // 后续增加,去掉注释即可 // callback.onSuccess(true); // // var modules = new RongIMClient.Protobuf.DeleteMsgInput(); // // modules.setType(conversationType); // // modules.setConversationId(targetId); // // modules.setMsgs(delMsgs); // // RongIMClient.bridge.queryMsg(33, MessageUtil.ArrayForm(modules.toArrayBuffer()), Bridge._client.userId, { // // onSuccess: function(info: any) { // // callback.onSuccess(true); // // }, // // onError: function(err: any) { // // callback.onError(err); // // } // // }, "DeleteMsgOutput"); // } /** * [deleteMessages 删除消息记录。] * @param {ConversationType} conversationType [description] * @param {string} targetId [description] * @param {number[]} messageIds [description] * @param {ResultCallback} callback [description] */ RongIMClient.prototype.deleteMessages = function (conversationType, targetId, messages, callback) { RongIMClient._dataAccessProvider.removeMessage(conversationType, targetId, messages, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "deleteMessages" }); callback.onError(errorCode); }); } }); }; RongIMClient.prototype.sendLocalMessage = function (message, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object"], "sendLocalMessage", false, arguments); RongIMClient._dataAccessProvider.updateMessage(message); this.sendMessage(message.conversationType, message.targetId, message.content, RongIMClient.logSendCallback(callback, "sendLocalMessage")); }; RongIMClient.prototype.getPullSetting = function (callback) { RongIMClient._dataAccessProvider.getPullSetting(callback); }; RongIMClient.prototype.setOfflineMessageDuration = function (duration, callback) { RongIMLib.CheckParam.getInstance().check(["number", "object"], "setOfflineMessageDuration", true, arguments); RongIMClient._dataAccessProvider.setOfflineMessageDuration(duration, callback); }; /** * [sendMessage 发送消息。] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [目标Id] * @param {MessageContent} messageContent [消息类型] * @param {SendMessageCallback} sendCallback [] * @param {ResultCallback} resultCallback [返回值,函数回调] * @param {string} pushContent [] * @param {string} pushData [] */ RongIMClient.prototype.sendMessage = function (conversationType, targetId, messageContent, sendCallback, mentiondMsg, pushText, appData, methodType, params) { RongIMLib.CheckParam.getInstance().check(["number", "string", "object", "object", "undefined|object|null|global|boolean", "undefined|object|null|global|string", "undefined|object|null|global|string", "undefined|object|null|global|number", "undefined|object|null|global"], "sendMessage", false, arguments); if (!RongIMLib.RongUtil.isString(targetId)) { return sendCallback.onError(RongIMLib.ErrorCode.PARAMETER_ERROR); } RongIMClient._dataAccessProvider.sendMessage(conversationType, targetId, messageContent, RongIMClient.logSendCallback(sendCallback, "sendMessage"), mentiondMsg, pushText, appData, methodType, params); }; RongIMClient.prototype.sendReceiptResponse = function (conversationType, targetId, sendCallback) { RongIMClient._dataAccessProvider.sendReceiptResponse(conversationType, targetId, RongIMClient.logSendCallback(sendCallback, "sendReceiptResponse")); }; RongIMClient.prototype.sendTypingStatusMessage = function (conversationType, targetId, messageName, sendCallback) { RongIMClient._dataAccessProvider.sendTypingStatusMessage(conversationType, targetId, messageName, RongIMClient.logSendCallback(sendCallback, "sendTypingStatusMessage")); }; /** * [sendStatusMessage description] * @param {MessageContent} messageContent [description] * @param {SendMessageCallback} sendCallback [description] * @param {ResultCallback} resultCallback [description] */ RongIMClient.prototype.sendStatusMessage = function (messageContent, sendCallback, resultCallback) { throw new Error("Not implemented yet"); }; /** * [sendTextMessage 发送TextMessage快捷方式] * @param {string} content [消息内容] * @param {ResultCallback} resultCallback [返回值,参数回调] */ RongIMClient.prototype.sendTextMessage = function (conversationType, targetId, content, sendMessageCallback) { RongIMClient._dataAccessProvider.sendTextMessage(conversationType, targetId, content, RongIMClient.logSendCallback(sendMessageCallback, "sendTextMessage")); }; RongIMClient.prototype.sendRecallMessage = function (content, sendMessageCallback) { var callback = RongIMClient.logSendCallback(sendMessageCallback, "sendRecallMessage"); var senderUserId = content.senderUserId; var userId = RongIMLib.Bridge._client.userId; var isOther = (senderUserId != userId); if (isOther) { var callback = RongIMClient.logSendCallback(sendMessageCallback, "sendRecallMessage"); callback.onError(RongIMLib.ErrorCode.RECALL_MESSAGE, content); return; } RongIMClient._dataAccessProvider.sendRecallMessage(content, callback); }; /** * [insertMessage 向本地插入一条消息,不发送到服务器。] * @param {ConversationType} conversationType [description] * @param {string} targetId [description] * @param {string} senderUserId [description] * @param {MessageContent} content [description] * @param {ResultCallback} callback [description] */ RongIMClient.prototype.insertMessage = function (conversationType, targetId, content, callback) { RongIMClient._dataAccessProvider.addMessage(conversationType, targetId, content, RongIMClient.logCallback(callback, "insertMessage")); }; RongIMClient.prototype.setMessageContent = function (messageId, content, objectName) { RongIMClient._dataAccessProvider.setMessageContent(messageId, content, objectName); }; ; RongIMClient.prototype.setMessageSearchField = function (messageId, content, searchFiles) { RongIMClient._dataAccessProvider.setMessageContent(messageId, content, searchFiles); }; ; /** * [getHistoryMessages 拉取历史消息记录。] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [用户Id] * @param {number|null} pullMessageTime [拉取历史消息起始位置(格式为毫秒数),可以为null] * @param {number} count [历史消息数量] * @param {ResultCallback} callback [回调函数] * @param {string} objectName [objectName] */ RongIMClient.prototype.getHistoryMessages = function (conversationType, targetId, timestamp, count, callback, objectname, order) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "number|null|global|object", "number", "object", "undefined|object|null|global|string", "number|null|global|object"], "getHistoryMessages", false, arguments); if (count > 20) { throw new Error("HistroyMessage count must be less than or equal to 20!"); } if (conversationType.valueOf() < 0) { throw new Error("ConversationType must be greater than -1"); } RongIMClient._dataAccessProvider.getHistoryMessages(conversationType, targetId, timestamp, count, RongIMClient.logCallback(callback, "getHistoryMessages"), objectname, order); }; /** * [getRemoteHistoryMessages 拉取某个时间戳之前的消息] * @param {ConversationType} conversationType [description] * @param {string} targetId [description] * @param {Date} dateTime [description] * @param {number} count [description] * @param {ResultCallback} callback [description] */ RongIMClient.prototype.getRemoteHistoryMessages = function (conversationType, targetId, timestamp, count, callback, config) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "number|null|global|object", "number", "object", "undefined|null|global|object"], "getRemoteHistoryMessages", false, arguments); var funcName = "getRemoteHistoryMessages"; var log = { errorCode: RongIMLib.ErrorCode.RC_CONN_PROTO_VERSION_ERROR, funcName: "getRemoteHistoryMessages" }; if (count > 20) { RongIMClient.logger(log); callback.onError(RongIMLib.ErrorCode.RC_CONN_PROTO_VERSION_ERROR); return; } if (conversationType.valueOf() < 0) { RongIMClient.logger(log); callback.onError(RongIMLib.ErrorCode.RC_CONN_PROTO_VERSION_ERROR); return; } RongIMClient._dataAccessProvider.getRemoteHistoryMessages(conversationType, targetId, timestamp, count, RongIMClient.logCallback(callback, funcName), config); }; RongIMClient.prototype.clearHistoryMessages = function (params, callback) { RongIMClient._dataAccessProvider.clearHistoryMessages(params, callback); }; RongIMClient.prototype.clearRemoteHistoryMessages = function (params, callback) { RongIMClient._dataAccessProvider.clearRemoteHistoryMessages(params, RongIMClient.logCallback(callback, "clearRemoteHistoryMessages")); }; RongIMClient.prototype.deleteRemoteMessages = function (conversationType, targetId, messages, callback) { RongIMClient._dataAccessProvider.deleteRemoteMessages(conversationType, targetId, messages, RongIMClient.logCallback(callback, "deleteRemoteMessages")); }; /** * [hasRemoteUnreadMessages 是否有未接收的消息,jsonp方法] * @param {string} appkey [appkey] * @param {string} token [token] * @param {ConnectCallback} callback [返回值,参数回调] */ RongIMClient.prototype.hasRemoteUnreadMessages = function (token, callback) { RongIMClient._dataAccessProvider.hasRemoteUnreadMessages(token, RongIMClient.logCallback(callback, "hasRemoteUnreadMessages")); }; RongIMClient.prototype.getTotalUnreadCount = function (callback, conversationTypes) { RongIMClient._dataAccessProvider.getTotalUnreadCount({ onSuccess: function (count) { setTimeout(function () { callback.onSuccess(count); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "getTotalUnreadCount" }); callback.onError(errorCode); }); } }, conversationTypes); }; /** * [getConversationUnreadCount 指定多种会话类型获取未读消息数] * @param {ResultCallback} callback [返回值,参数回调。] * @param {ConversationType[]} ...conversationTypes [会话类型。] */ RongIMClient.prototype.getConversationUnreadCount = function (conversationTypes, callback) { RongIMClient._dataAccessProvider.getConversationUnreadCount(conversationTypes, { onSuccess: function (count) { setTimeout(function () { callback.onSuccess(count); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "getConversationUnreadCount" }); callback.onError(errorCode); }); } }); }; /** * [getUnreadCount 指定用户、会话类型的未读消息总数。] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [用户Id] */ RongIMClient.prototype.getUnreadCount = function (conversationType, targetId, callback) { RongIMClient._dataAccessProvider.getUnreadCount(conversationType, targetId, { onSuccess: function (count) { setTimeout(function () { callback.onSuccess(count); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "getUnreadCount" }); callback.onError(errorCode); }); } }); }; RongIMClient.prototype.setUnreadCount = function (conversationType, targetId, count) { RongIMLib.CheckParam.getInstance().check(["number", "string", "number"], "setUnreadCount", false, arguments); RongIMClient._dataAccessProvider.setUnreadCount(conversationType, targetId, count); }; RongIMClient.prototype.clearUnreadCountByTimestamp = function (conversationType, targetId, timestamp, callback) { RongIMClient._dataAccessProvider.clearUnreadCountByTimestamp(conversationType, targetId, timestamp, RongIMClient.logCallback(callback, "clearUnreadCountByTimestamp")); }; /** * 清楚会话未读消息数 * @param {ConversationType} conversationType 会话类型 * @param {string} targetId 目标Id * @param {ResultCallback} callback 返回值,函数回调 */ RongIMClient.prototype.clearUnreadCount = function (conversationType, targetId, callback) { RongIMClient._dataAccessProvider.clearUnreadCount(conversationType, targetId, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "clearUnreadCount" }); callback.onError(errorCode); }); } }); }; RongIMClient.prototype.clearTotalUnreadCount = function (callback) { RongIMClient._dataAccessProvider.clearTotalUnreadCount({ onSuccess: function (bool) { callback.onSuccess(bool); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: 'clearTotalUnreadCount' }); callback.onError(errorCode); }); } }); }; RongIMClient.prototype.clearLocalStorage = function (callback) { RongIMClient._storageProvider.clearItem(); callback(); }; RongIMClient.prototype.setMessageExtra = function (messageId, value, callback) { RongIMClient._dataAccessProvider.setMessageExtra(messageId, value, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "setMessageExtra" }); callback.onError(errorCode); }); } }); }; RongIMClient.prototype.setMessageReceivedStatus = function (messageUId, receivedStatus, callback) { RongIMClient._dataAccessProvider.setMessageReceivedStatus(messageUId, receivedStatus, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "setMessageReceivedStatus" }); callback.onError(errorCode); }); } }); }; RongIMClient.prototype.setMessageStatus = function (conersationType, targetId, timestamp, status, callback) { RongIMClient._dataAccessProvider.setMessageStatus(conersationType, targetId, timestamp, status, RongIMClient.logCallback(callback, "setMessageStatus")); }; RongIMClient.prototype.setMessageSentStatus = function (messageId, sentStatus, callback) { RongIMClient._dataAccessProvider.setMessageSentStatus(messageId, sentStatus, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "setMessageSentStatus" }); callback.onError(errorCode); }); } }); }; // #endregion Message // #region TextMessage Draft /** * clearTextMessageDraft 清除指定会话和消息类型的草稿。 * @param {ConversationType} conversationType 会话类型 * @param {string} targetId 目标Id */ RongIMClient.prototype.clearTextMessageDraft = function (conversationType, targetId) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "clearTextMessageDraft", false, arguments); var key = "darf_" + conversationType + "_" + targetId; delete RongIMClient._memoryStore[key]; return true; }; /** * [getTextMessageDraft 获取指定消息和会话的草稿。] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [目标Id] */ RongIMClient.prototype.getTextMessageDraft = function (conversationType, targetId) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "getTextMessageDraft", false, arguments); if (targetId == "" || conversationType < 0) { throw new Error("params error : " + RongIMLib.ErrorCode.DRAF_GET_ERROR); } var key = "darf_" + conversationType + "_" + targetId; return RongIMClient._memoryStore[key]; }; /** * [saveTextMessageDraft description] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [目标Id] * @param {string} value [草稿值] */ RongIMClient.prototype.saveTextMessageDraft = function (conversationType, targetId, value) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "string", "object"], "saveTextMessageDraft", false, arguments); var key = "darf_" + conversationType + "_" + targetId; RongIMClient._memoryStore[key] = value; return true; }; // #endregion TextMessage Draft // #region Conversation RongIMClient.prototype.searchConversationByContent = function (keyword, callback, conversationTypes) { RongIMClient._dataAccessProvider.searchConversationByContent(keyword, RongIMClient.logCallback(callback, "searchConversationByContent"), conversationTypes); }; RongIMClient.prototype.searchMessageByContent = function (conversationType, targetId, keyword, timestamp, count, total, callback) { RongIMClient._dataAccessProvider.searchMessageByContent(conversationType, targetId, keyword, timestamp, count, total, RongIMClient.logCallback(callback, "searchMessageByContent")); }; RongIMClient.prototype.clearCache = function () { RongIMClient._dataAccessProvider.clearCache(); }; RongIMClient.prototype.clearConversations = function (callback) { var conversationTypes = []; for (var _i = 1; _i < arguments.length; _i++) { conversationTypes[_i - 1] = arguments[_i]; } if (conversationTypes.length == 0) { conversationTypes = [RongIMLib.ConversationType.CHATROOM, RongIMLib.ConversationType.CUSTOMER_SERVICE, RongIMLib.ConversationType.DISCUSSION, RongIMLib.ConversationType.GROUP, RongIMLib.ConversationType.PRIVATE, RongIMLib.ConversationType.SYSTEM, RongIMLib.ConversationType.PUBLIC_SERVICE, RongIMLib.ConversationType.APP_PUBLIC_SERVICE]; } RongIMClient._dataAccessProvider.clearConversations(conversationTypes, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "clearConversations" }); callback.onError(errorCode); }); } }); }; /** * [getConversation 获取指定会话,此方法需在getConversationList之后执行] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [目标Id] * @param {ResultCallback} callback [返回值,函数回调] */ RongIMClient.prototype.getConversation = function (conversationType, targetId, callback) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "getConversation", false, arguments); RongIMClient._dataAccessProvider.getConversation(conversationType, targetId, { onSuccess: function (conver) { setTimeout(function () { callback.onSuccess(conver); }); }, onError: function (error) { setTimeout(function () { RongIMClient.logger({ code: error, funcName: "getConversation" }); callback.onError(error); }); } }); }; /** * [pottingConversation 组装会话列表] * @param {any} tempConver [临时会话] * conver_conversationType_targetId_no. * msg_conversationType_targetId_no. */ RongIMClient.prototype.pottingConversation = function (tempConver) { var self = this, isUseReplace = false; RongIMClient._dataAccessProvider.getConversation(tempConver.type, tempConver.userId, { onSuccess: function (conver) { if (!conver) { conver = new RongIMLib.Conversation(); } else { isUseReplace = true; } conver.conversationType = tempConver.type; conver.targetId = tempConver.userId; conver.latestMessage = RongIMLib.MessageUtil.messageParser(tempConver.msg); conver.latestMessageId = conver.latestMessage.messageId; conver.objectName = conver.latestMessage.objectName; conver.receivedStatus = conver.latestMessage.receivedStatus; conver.receivedTime = conver.latestMessage.receiveTime; conver.sentStatus = conver.latestMessage.sentStatus; conver.sentTime = conver.latestMessage.sentTime; var mentioneds = RongIMClient._storageProvider.getItem("mentioneds_" + RongIMLib.Bridge._client.userId + '_' + conver.conversationType + '_' + conver.targetId); if (mentioneds) { var info = JSON.parse(mentioneds); conver.mentionedMsg = info[tempConver.type + "_" + tempConver.userId]; } if (!isUseReplace) { if (RongIMLib.RongUtil.supportLocalStorage()) { // var count = RongIMClient._storageProvider.getItem("cu" + Bridge._client.userId + tempConver.type + tempConver.userId); conver.unreadMessageCount = RongIMLib.UnreadCountHandler.get(tempConver.type, tempConver.userId); } else { conver.unreadMessageCount = 0; } } if (conver.conversationType == RongIMLib.ConversationType.DISCUSSION) { self.getDiscussion(tempConver.userId, { onSuccess: function (info) { conver.conversationTitle = info.name; }, onError: function (error) { } }); } RongIMClient._dataAccessProvider.addConversation(conver, { onSuccess: function (data) { } }); }, onError: function (error) { } }); }; RongIMClient.prototype.addConversation = function (conversation, callback) { RongIMClient._dataAccessProvider.addConversation(conversation, callback); }; RongIMClient.prototype.sortConversationList = function (conversationList) { var convers = []; for (var i = 0, len = conversationList.length; i < len; i++) { if (!conversationList[i]) { continue; } if (conversationList[i].isTop) { convers.push(conversationList[i]); conversationList.splice(i, 1); continue; } for (var j = 0; j < len - i - 1; j++) { if (conversationList[j].sentTime < conversationList[j + 1].sentTime) { var swap = conversationList[j]; conversationList[j] = conversationList[j + 1]; conversationList[j + 1] = swap; } } } return RongIMClient._memoryStore.conversationList = convers.concat(conversationList); }; RongIMClient.prototype.getConversationList = function (callback, conversationTypes, count, isGetHiddenConvers) { RongIMLib.CheckParam.getInstance().check(["object", "null|undefined|array|object|global", "number|undefined|null|object|global", "boolean|undefined|null|object|global"], "getConversationList", false, arguments); var me = this; RongIMClient._dataAccessProvider.getConversationList({ onSuccess: function (data) { if (conversationTypes || RongIMClient._dataAccessProvider) { setTimeout(function () { callback.onSuccess(data); }); } else { setTimeout(function () { callback.onSuccess(RongIMClient._memoryStore.conversationList); }); } }, onError: function (error) { setTimeout(function () { RongIMClient.logger({ code: error, funcName: "getConversationList" }); callback.onError(error); }); } }, conversationTypes, count, isGetHiddenConvers); }; RongIMClient.prototype.getRemoteConversationList = function (callback, conversationTypes, count, isGetHiddenConvers) { RongIMLib.CheckParam.getInstance().check(["object", "null|array|object|global", "number|undefined|null|object|global", "boolean|undefined|null|object|global"], "getRemoteConversationList", false, arguments); RongIMClient._dataAccessProvider.getRemoteConversationList(RongIMClient.logCallback(callback, "getRemoteConversationList"), conversationTypes, count, isGetHiddenConvers); }; RongIMClient.prototype.updateConversation = function (conversation) { return RongIMClient._dataAccessProvider.updateConversation(conversation); }; /** * [createConversation 创建会话。] * @param {number} conversationType [会话类型] * @param {string} targetId [目标Id] * @param {string} converTitle [会话标题] * @param {boolean} islocal [是否同步到服务器,ture:同步,false:不同步] */ RongIMClient.prototype.createConversation = function (conversationType, targetId, converTitle) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "string"], "createConversation", false, arguments); var conver = new RongIMLib.Conversation(); // var unreadContent: string = RongIMClient._storageProvider.getItem("cu" + Bridge._client.userId + conversationType + targetId); // var unreadCount = Number(unreadContent) || 0; conver.targetId = targetId; conver.conversationType = conversationType; conver.conversationTitle = converTitle; conver.latestMessage = {}; conver.unreadMessageCount = 0; return conver; }; //TODO 删除本地和服务器、删除本地和服务器分开 RongIMClient.prototype.removeConversation = function (conversationType, targetId, callback) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "removeConversation", false, arguments); RongIMClient._dataAccessProvider.removeConversation(conversationType, targetId, RongIMClient.logCallback(callback, "removeConversation")); }; RongIMClient.prototype.setConversationHidden = function (conversationType, targetId, isHidden) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "boolean"], "setConversationHidden", false, arguments); RongIMClient._dataAccessProvider.setConversationHidden(conversationType, targetId, isHidden); }; RongIMClient.prototype.setConversationToTop = function (conversationType, targetId, isTop, callback) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "boolean", "object"], "setConversationToTop", false, arguments); RongIMClient._dataAccessProvider.setConversationToTop(conversationType, targetId, isTop, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "setConversationToTop" }); callback.onError(errorCode); }); } }); }; // #endregion Conversation // #region Notifications /** * [getConversationNotificationStatus 获取指定用户和会话类型免提醒。] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [目标Id] * @param {ResultCallback} callback [返回值,函数回调] */ RongIMClient.prototype.getConversationNotificationStatus = function (conversationType, targetId, callback) { var params = { conversationType: conversationType, targetId: targetId }; RongIMClient._dataAccessProvider.getConversationNotificationStatus(params, RongIMClient.logCallback(callback, "getConversationNotificationStatus")); }; /** * [setConversationNotificationStatus 设置指定用户和会话类型免提醒。] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [目标Id] * @param {ResultCallback} callback [返回值,函数回调] */ RongIMClient.prototype.setConversationNotificationStatus = function (conversationType, targetId, notificationStatus, callback) { var params = { conversationType: conversationType, targetId: targetId, status: status }; RongIMClient._dataAccessProvider.setConversationNotificationStatus(params, RongIMClient.logCallback(callback, "setConversationNotificationStatus")); }; /** * [getNotificationQuietHours 获取免提醒消息时间。] * @param {GetNotificationQuietHoursCallback} callback [返回值,函数回调] */ RongIMClient.prototype.getNotificationQuietHours = function (callback) { throw new Error("Not implemented yet"); }; /** * [removeNotificationQuietHours 移除免提醒消息时间。] * @param {GetNotificationQuietHoursCallback} callback [返回值,函数回调] */ RongIMClient.prototype.removeNotificationQuietHours = function (callback) { throw new Error("Not implemented yet"); }; /** * [setNotificationQuietHours 设置免提醒消息时间。] * @param {GetNotificationQuietHoursCallback} callback [返回值,函数回调] */ RongIMClient.prototype.setNotificationQuietHours = function (startTime, spanMinutes, callback) { throw new Error("Not implemented yet"); }; // #endregion Notifications // #region Discussion /** * [addMemberToDiscussion 加入讨论组] * @param {string} discussionId [讨论组Id] * @param {string[]} userIdList [讨论中成员] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.addMemberToDiscussion = function (discussionId, userIdList, callback) { RongIMLib.CheckParam.getInstance().check(["string", "array", "object"], "addMemberToDiscussion", false, arguments); RongIMClient._dataAccessProvider.addMemberToDiscussion(discussionId, userIdList, RongIMClient.logCallback(callback, "addMemberToDiscussion")); }; /** * [createDiscussion 创建讨论组] * @param {string} name [讨论组名称] * @param {string[]} userIdList [讨论组成员] * @param {CreateDiscussionCallback} callback [返回值,函数回调] */ RongIMClient.prototype.createDiscussion = function (name, userIdList, callback) { RongIMLib.CheckParam.getInstance().check(["string", "array", "object"], "createDiscussion", false, arguments); RongIMClient._dataAccessProvider.createDiscussion(name, userIdList, callback); }; /** * [getDiscussion 获取讨论组信息] * @param {string} discussionId [讨论组Id] * @param {ResultCallback} callback [返回值,函数回调] */ RongIMClient.prototype.getDiscussion = function (discussionId, callback) { RongIMLib.CheckParam.getInstance().check(["string", "object"], "getDiscussion", false, arguments); RongIMClient._dataAccessProvider.getDiscussion(discussionId, RongIMClient.logCallback(callback, "getDiscussion")); }; /** * [quitDiscussion 退出讨论组] * @param {string} discussionId [讨论组Id] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.quitDiscussion = function (discussionId, callback) { RongIMLib.CheckParam.getInstance().check(["string", "object"], "quitDiscussion", false, arguments); RongIMClient._dataAccessProvider.quitDiscussion(discussionId, RongIMClient.logCallback(callback, "quitDiscussion")); }; /** * [removeMemberFromDiscussion 将指定成员移除讨论租] * @param {string} discussionId [讨论组Id] * @param {string} userId [被移除的用户Id] * @param {OperationCallback} callback [返回值,参数回调] */ RongIMClient.prototype.removeMemberFromDiscussion = function (discussionId, userId, callback) { RongIMLib.CheckParam.getInstance().check(["string", "string", "object"], "removeMemberFromDiscussion", false, arguments); RongIMClient._dataAccessProvider.removeMemberFromDiscussion(discussionId, userId, RongIMClient.logCallback(callback, "removeMemberFromDiscussion")); }; /** * [setDiscussionInviteStatus 设置讨论组邀请状态] * @param {string} discussionId [讨论组Id] * @param {DiscussionInviteStatus} status [邀请状态] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.setDiscussionInviteStatus = function (discussionId, status, callback) { RongIMLib.CheckParam.getInstance().check(["string", "number", "object"], "setDiscussionInviteStatus", false, arguments); RongIMClient._dataAccessProvider.setDiscussionInviteStatus(discussionId, status, RongIMClient.logCallback(callback, "setDiscussionInviteStatus")); }; /** * [setDiscussionName 设置讨论组名称] * @param {string} discussionId [讨论组Id] * @param {string} name [讨论组名称] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.setDiscussionName = function (discussionId, name, callback) { RongIMLib.CheckParam.getInstance().check(["string", "string", "object"], "setDiscussionName", false, arguments); RongIMClient._dataAccessProvider.setDiscussionName(discussionId, name, RongIMClient.logCallback(callback, "setDiscussionName")); }; // #endregion Discussion // #region ChatRoom /** * [加入聊天室。] * @param {string} chatroomId [聊天室Id] * @param {number} messageCount [拉取消息数量,-1为不拉去消息] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.joinChatRoom = function (chatroomId, messageCount, callback) { RongIMLib.CheckParam.getInstance().check(["string", "number", "object"], "joinChatRoom", false, arguments); if (chatroomId == "") { setTimeout(function () { var errorCode = RongIMLib.ErrorCode.CHATROOM_ID_ISNULL; RongIMClient.logger({ code: errorCode, funcName: "joinChatRoom" }); callback.onError(RongIMLib.ErrorCode.CHATROOM_ID_ISNULL); }); return; } RongIMClient._dataAccessProvider.joinChatRoom(chatroomId, messageCount, RongIMClient.logCallback(callback, "joinChatRoom")); }; RongIMClient.prototype.setDeviceInfo = function (device) { RongIMClient._dataAccessProvider.setDeviceInfo(device); }; RongIMClient.prototype.setChatroomHisMessageTimestamp = function (chatRoomId, timestamp) { RongIMLib.CheckParam.getInstance().check(["string", "number"], "setChatroomHisMessageTimestamp", false, arguments); RongIMClient._dataAccessProvider.setChatroomHisMessageTimestamp(chatRoomId, timestamp); }; RongIMClient.prototype.getChatRoomHistoryMessages = function (chatRoomId, count, order, callback) { RongIMLib.CheckParam.getInstance().check(["string", "number", "number", "object"], "getChatRoomHistoryMessages", false, arguments); RongIMClient._dataAccessProvider.getChatRoomHistoryMessages(chatRoomId, count, order, RongIMClient.logCallback(callback, "getChatRoomHistoryMessages")); }; RongIMClient.prototype.getChatRoomInfo = function (chatRoomId, count, order, callback) { RongIMLib.CheckParam.getInstance().check(["string", "number", "number", "object"], "getChatRoomInfo", false, arguments); RongIMClient._dataAccessProvider.getChatRoomInfo(chatRoomId, count, order, RongIMClient.logCallback(callback, "getChatRoomInfo")); }; /** * [退出聊天室] * @param {string} chatroomId [聊天室Id] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.quitChatRoom = function (chatroomId, callback) { RongIMLib.CheckParam.getInstance().check(["string", "object"], "quitChatRoom", false, arguments); RongIMClient._dataAccessProvider.quitChatRoom(chatroomId, RongIMClient.logCallback(callback, "quitChatRoom")); }; RongIMClient.prototype.setChatroomEntry = function (chatroomId, chatroomEntry, callback) { RongIMLib.CheckParam.getInstance().check(['string', 'object', 'object'], 'setChatroomEntry', false, arguments); RongIMClient._dataAccessProvider.setChatroomEntry(chatroomId, chatroomEntry, RongIMClient.logCallback(callback, "setChatroomEntry")); }; RongIMClient.prototype.forceSetChatroomEntry = function (chatroomId, chatroomEntry, callback) { RongIMLib.CheckParam.getInstance().check(['string', 'object', 'object'], 'setChatroomEntry', false, arguments); RongIMClient._dataAccessProvider.forceSetChatroomEntry(chatroomId, chatroomEntry, RongIMClient.logCallback(callback, "setChatroomEntry")); }; RongIMClient.prototype.getChatroomEntry = function (chatroomId, key, callback) { RongIMLib.CheckParam.getInstance().check(['string', 'string', 'object'], 'getChatroomEntry', false, arguments); RongIMClient._dataAccessProvider.getChatroomEntry(chatroomId, key, RongIMClient.logCallback(callback, "setChatroomEntry")); }; RongIMClient.prototype.getAllChatroomEntries = function (chatroomId, callback) { RongIMLib.CheckParam.getInstance().check(['string', 'object'], 'getAllChatroomEntries', false, arguments); RongIMClient._dataAccessProvider.getAllChatroomEntries(chatroomId, RongIMClient.logCallback(callback, "setChatroomEntry")); }; RongIMClient.prototype.removeChatroomEntry = function (chatroomId, chatroomEntry, callback) { RongIMLib.CheckParam.getInstance().check(['string', 'object', 'object'], 'removeChatroomEntry', false, arguments); RongIMClient._dataAccessProvider.removeChatroomEntry(chatroomId, chatroomEntry, RongIMClient.logCallback(callback, "setChatroomEntry")); }; RongIMClient.prototype.forceRemoveChatroomEntry = function (chatroomId, chatroomEntry, callback) { RongIMLib.CheckParam.getInstance().check(['string', 'object', 'object'], 'removeChatroomEntry', false, arguments); RongIMClient._dataAccessProvider.forceRemoveChatroomEntry(chatroomId, chatroomEntry, RongIMClient.logCallback(callback, "setChatroomEntry")); }; // #endregion ChatRoom // #region Public Service RongIMClient.prototype.getRemotePublicServiceList = function (callback, pullMessageTime) { RongIMClient._dataAccessProvider.getRemotePublicServiceList(RongIMClient.logCallback(callback, "getRemotePublicServiceList"), pullMessageTime); }; /** * [getPublicServiceList ]获取本地的公共账号列表 * @param {ResultCallback} callback [返回值,参数回调] */ RongIMClient.prototype.getPublicServiceList = function (callback) { if (RongIMClient._memoryStore.depend.openMp) { RongIMLib.CheckParam.getInstance().check(["object"], "getPublicServiceList", false, arguments); this.getRemotePublicServiceList(RongIMClient.logCallback(callback, "getPublicServiceList")); } }; /** * [getPublicServiceProfile ] 获取某公共服务信息。 * @param {PublicServiceType} publicServiceType [公众服务类型。] * @param {string} publicServiceId [公共服务 Id。] * @param {ResultCallback} callback [公共账号信息回调。] */ RongIMClient.prototype.getPublicServiceProfile = function (publicServiceType, publicServiceId, callback) { if (RongIMClient._memoryStore.depend.openMp) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "getPublicServiceProfile", false, arguments); RongIMClient._dataAccessProvider.getPublicServiceProfile(publicServiceType, publicServiceId, RongIMClient.logCallback(callback, "getPublicServiceProfile")); } }; /** * [pottingPublicSearchType ] 公众好查询类型 * @param {number} bussinessType [ 0-all 1-mp 2-mc] * @param {number} searchType [0-exact 1-fuzzy] */ RongIMClient.prototype.pottingPublicSearchType = function (bussinessType, searchType) { if (RongIMClient._memoryStore.depend.openMp) { var bits = 0; if (bussinessType == 0) { bits |= 3; if (searchType == 0) { bits |= 12; } else { bits |= 48; } } else if (bussinessType == 1) { bits |= 1; if (searchType == 0) { bits |= 8; } else { bits |= 32; } } else { bits |= 2; if (bussinessType == 0) { bits |= 4; } else { bits |= 16; } } return bits; } }; /** * [searchPublicService ]按公众服务类型搜索公众服务。 * @param {SearchType} searchType [搜索类型枚举。] * @param {string} keywords [搜索关键字。] * @param {ResultCallback} callback [搜索结果回调。] */ RongIMClient.prototype.searchPublicService = function (searchType, keywords, callback) { if (RongIMClient._memoryStore.depend.openMp) { RongIMLib.CheckParam.getInstance().check(["number", "string", "object"], "searchPublicService", false, arguments); var modules = new RongIMClient.Protobuf.SearchMpInput(); modules.setType(this.pottingPublicSearchType(0, searchType)); modules.setId(keywords); RongIMClient.bridge.queryMsg(29, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, RongIMClient.logCallback(callback, "searchPublicService"), "SearchMpOutput"); } }; /** * [searchPublicServiceByType ]按公众服务类型搜索公众服务。 * @param {PublicServiceType} publicServiceType [公众服务类型。] * @param {SearchType} searchType [搜索类型枚举。] * @param {string} keywords [搜索关键字。] * @param {ResultCallback} callback [搜索结果回调。] */ RongIMClient.prototype.searchPublicServiceByType = function (publicServiceType, searchType, keywords, callback) { if (RongIMClient._memoryStore.depend.openMp) { RongIMLib.CheckParam.getInstance().check(["number", "number", "string", "object"], "searchPublicServiceByType", false, arguments); var type = publicServiceType == RongIMLib.ConversationType.APP_PUBLIC_SERVICE ? 2 : 1; var modules = new RongIMClient.Protobuf.SearchMpInput(); modules.setType(this.pottingPublicSearchType(type, searchType)); modules.setId(keywords); RongIMClient.bridge.queryMsg(29, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, RongIMClient.logCallback(callback, "searchPublicServiceByType"), "SearchMpOutput"); } }; /** * [subscribePublicService ] 订阅公众号。 * @param {PublicServiceType} publicServiceType [公众服务类型。] * @param {string} publicServiceId [公共服务 Id。] * @param {OperationCallback} callback [订阅公众号回调。] */ RongIMClient.prototype.subscribePublicService = function (publicServiceType, publicServiceId, callback) { if (RongIMClient._memoryStore.depend.openMp) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "subscribePublicService", false, arguments); var modules = new RongIMClient.Protobuf.MPFollowInput(), me = this, follow = publicServiceType == RongIMLib.ConversationType.APP_PUBLIC_SERVICE ? "mcFollow" : "mpFollow"; modules.setId(publicServiceId); RongIMClient.bridge.queryMsg(follow, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function () { me.getRemotePublicServiceList({ onSuccess: function () { }, onError: function () { } }); callback.onSuccess(); }, onError: function (code) { var errorCode = code; RongIMClient.logger({ code: errorCode, funcName: "subscribePublicService" }); callback.onError(code); } }, "MPFollowOutput"); } }; /** * [unsubscribePublicService ] 取消订阅公众号。 * @param {PublicServiceType} publicServiceType [公众服务类型。] * @param {string} publicServiceId [公共服务 Id。] * @param {OperationCallback} callback [取消订阅公众号回调。] */ RongIMClient.prototype.unsubscribePublicService = function (publicServiceType, publicServiceId, callback) { if (RongIMClient._memoryStore.depend.openMp) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "unsubscribePublicService", false, arguments); var modules = new RongIMClient.Protobuf.MPFollowInput(), me = this, follow = publicServiceType == RongIMLib.ConversationType.APP_PUBLIC_SERVICE ? "mcUnFollow" : "mpUnFollow"; modules.setId(publicServiceId); RongIMClient.bridge.queryMsg(follow, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function () { RongIMClient._memoryStore.publicServiceMap.remove(publicServiceType, publicServiceId); callback.onSuccess(); }, onError: function (code) { var errorCode = code; RongIMClient.logger({ code: errorCode, funcName: "unsubscribePublicService" }); callback.onError(code); } }, "MPFollowOutput"); } }; // #endregion Public Service // #region Blacklist /** * [加入黑名单] * @param {string} userId [将被加入黑名单的用户Id] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.addToBlacklist = function (userId, callback) { RongIMLib.CheckParam.getInstance().check(["string|number", "object"], "addToBlacklist", false, arguments); RongIMClient._dataAccessProvider.addToBlacklist(userId, RongIMClient.logCallback(callback, "addToBlacklist")); }; /** * [获取黑名单列表] * @param {GetBlacklistCallback} callback [返回值,函数回调] */ RongIMClient.prototype.getBlacklist = function (callback) { RongIMLib.CheckParam.getInstance().check(["object"], "getBlacklist", false, arguments); RongIMClient._dataAccessProvider.getBlacklist(callback); }; /** * [得到指定人员再黑名单中的状态] * @param {string} userId [description] * @param {ResultCallback} callback [返回值,函数回调] */ //TODO 如果人员不在黑名单中,获取状态会出现异常 RongIMClient.prototype.getBlacklistStatus = function (userId, callback) { RongIMLib.CheckParam.getInstance().check(["string|number", "object"], "getBlacklistStatus", false, arguments); RongIMClient._dataAccessProvider.getBlacklistStatus(userId, RongIMClient.logCallback(callback, "getBlacklistStatus")); }; /** * [将指定用户移除黑名单] * @param {string} userId [将被移除的用户Id] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.removeFromBlacklist = function (userId, callback) { RongIMLib.CheckParam.getInstance().check(["string|number", "object"], "removeFromBlacklist", false, arguments); RongIMClient._dataAccessProvider.removeFromBlacklist(userId, RongIMClient.logCallback(callback, "removeFromBlacklist")); }; RongIMClient.prototype.getFileToken = function (fileType, callback) { RongIMLib.CheckParam.getInstance().check(["number", "object"], "getQngetFileTokenTkn", false, arguments); RongIMClient._dataAccessProvider.getFileToken(fileType, RongIMClient.logCallback(callback, "getFileToken")); }; RongIMClient.prototype.getFileUrl = function (fileType, fileName, oriName, callback) { RongIMLib.CheckParam.getInstance().check(["number", "string", "string|global|object|null", "object"], "getFileUrl", false, arguments); RongIMClient._dataAccessProvider.getFileUrl(fileType, fileName, oriName, RongIMClient.logCallback(callback, "getFileUrl")); }; ; // #endregion Blacklist // #region Real-time Location Service RongIMClient.prototype.addRealTimeLocationListener = function (conversationType, targetId, listener) { throw new Error("Not implemented yet"); }; RongIMClient.prototype.getRealTimeLocation = function (conversationType, targetId) { throw new Error("Not implemented yet"); }; RongIMClient.prototype.getRealTimeLocationCurrentState = function (conversationType, targetId) { throw new Error("Not implemented yet"); }; RongIMClient.prototype.getRealTimeLocationParticipants = function (conversationType, targetId) { throw new Error("Not implemented yet"); }; RongIMClient.prototype.joinRealTimeLocation = function (conversationType, targetId) { throw new Error("Not implemented yet"); }; RongIMClient.prototype.quitRealTimeLocation = function (conversationType, targetId) { throw new Error("Not implemented yet"); }; RongIMClient.prototype.startRealTimeLocation = function (conversationType, targetId) { throw new Error("Not implemented yet"); }; RongIMClient.prototype.updateRealTimeLocationStatus = function (conversationType, targetId, latitude, longitude) { throw new Error("Not implemented yet"); }; // #endregion Real-time Location Service // # startVoIP RongIMClient.prototype.startCall = function (converType, targetId, userIds, mediaType, extra, callback) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "array", "number", "string", "object"], "startCall", false, arguments); if (RongIMClient._memoryStore.voipStategy) { RongIMClient._voipProvider.startCall(converType, targetId, userIds, mediaType, extra, RongIMClient.logCallback(callback, "startCall")); } else { var errorCode = RongIMLib.ErrorCode.VOIP_NOT_AVALIABLE; RongIMClient.logger({ code: errorCode, funcName: "startCall" }); callback.onError(RongIMLib.ErrorCode.VOIP_NOT_AVALIABLE); } }; RongIMClient.prototype.joinCall = function (mediaType, callback) { RongIMLib.CheckParam.getInstance().check(['number', 'object'], "joinCall", false, arguments); if (RongIMClient._memoryStore.voipStategy) { RongIMClient._voipProvider.joinCall(mediaType, RongIMClient.logCallback(callback, "joinCall")); } else { var errorCode = RongIMLib.ErrorCode.VOIP_NOT_AVALIABLE; RongIMClient.logger({ code: errorCode, funcName: "joinCall" }); callback.onError(RongIMLib.ErrorCode.VOIP_NOT_AVALIABLE); } }; RongIMClient.prototype.hungupCall = function (converType, targetId, reason) { RongIMLib.CheckParam.getInstance().check(["number", "string", "number"], "hungupCall", false, arguments); if (RongIMClient._memoryStore.voipStategy) { RongIMClient._voipProvider.hungupCall(converType, targetId, reason); } }; RongIMClient.prototype.changeMediaType = function (converType, targetId, mediaType, callback) { RongIMLib.CheckParam.getInstance().check(["number", "string", "number", "object"], "changeMediaType", false, arguments); if (RongIMClient._memoryStore.voipStategy) { RongIMClient._voipProvider.changeMediaType(converType, targetId, mediaType, RongIMClient.logCallback(callback, "changeMediaType")); } else { var errorCode = RongIMLib.ErrorCode.VOIP_NOT_AVALIABLE; RongIMClient.logger({ code: errorCode, funcName: "changeMediaType" }); callback.onError(RongIMLib.ErrorCode.VOIP_NOT_AVALIABLE); } }; // # endVoIP RongIMClient.prototype.getUnreadMentionedMessages = function (conversationType, targetId) { return RongIMClient._dataAccessProvider.getUnreadMentionedMessages(conversationType, targetId); }; RongIMClient.prototype.clearListeners = function () { RongIMClient._dataAccessProvider.clearListeners(); }; // UserStatus start RongIMClient.prototype.getUserStatus = function (userId, callback) { RongIMClient._dataAccessProvider.getUserStatus(userId, RongIMClient.logCallback(callback, "getUserStatus")); }; RongIMClient.prototype.setUserStatus = function (status, callback) { RongIMClient._dataAccessProvider.setUserStatus(status, RongIMClient.logCallback(callback, "setUserStatus")); }; RongIMClient.prototype.setUserStatusListener = function (params, callback) { var userIds = params.userIds; var multiple = params.multiple; RongIMClient.userStatusObserver.watch({ key: userIds, func: callback, multiple: multiple }); RongIMClient._dataAccessProvider.setUserStatusListener(params, callback); }; // UserStaus end // RTC start RongIMClient.messageWatch = function (watcher) { RongIMClient.RTCListener = watcher; }; RongIMClient.messageSignalWatch = function (watcher) { RongIMClient.RTCSignalLisener = watcher; }; /* var data = { key1: 123, key2: 345 }; */ RongIMClient.prototype.getRTCUserInfoList = function (room, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object"], "getRTCUserInfoList", false, arguments); RongIMClient._dataAccessProvider.getRTCUserInfoList(room, callback); }; RongIMClient.prototype.getRTCUserList = function (room, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object"], "getRTCUserList", false, arguments); RongIMClient._dataAccessProvider.getRTCUserList(room, callback); }; RongIMClient.prototype.setRTCUserInfo = function (room, info, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object", "object"], "setRTCUserInfo", false, arguments); RongIMClient._dataAccessProvider.setRTCUserInfo(room, info, callback); }; RongIMClient.prototype.removeRTCUserInfo = function (room, info, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object", "object"], "removeRTCUserInfo", false, arguments); RongIMClient._dataAccessProvider.removeRTCUserInfo(room, info, callback); }; RongIMClient.prototype.getRTCRoomInfo = function (room, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object"], "getRTCRoomInfo", false, arguments); RongIMClient._dataAccessProvider.getRTCRoomInfo(room, callback); }; RongIMClient.prototype.setRTCRoomInfo = function (room, info, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object", "object"], "setRTCRoomInfo", false, arguments); RongIMClient._dataAccessProvider.setRTCRoomInfo(room, info, callback); }; RongIMClient.prototype.removeRTCRoomInfo = function (room, info, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object", "object"], "removeRTCRoomInfo", false, arguments); RongIMClient._dataAccessProvider.removeRTCRoomInfo(room, info, callback); }; RongIMClient.prototype.joinRTCRoom = function (room, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object"], "joinRTCRoom", false, arguments); if (RongIMClient.isJoinedRTCRoom) { return callback.onSuccess(RongIMClient.roomInfo); } RongIMClient._dataAccessProvider.joinRTCRoom(room, { onSuccess: function (result) { RongIMClient.roomInfo = result; RongIMClient.isJoinedRTCRoom = true; callback.onSuccess(result); }, onError: callback.onError }); }; RongIMClient.prototype.quitRTCRoom = function (room, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object"], "quitRTCRoom", false, arguments); RongIMClient.isJoinedRTCRoom = false; RongIMClient._dataAccessProvider.quitRTCRoom(room, { onSuccess: function () { RongIMClient.roomInfo = { users: {}, token: '' }; callback.onSuccess(true); }, onError: callback.onError }); }; RongIMClient.prototype.RTCPing = function (room, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object"], "RTCPing", false, arguments); RongIMClient._dataAccessProvider.RTCPing(room, callback); }; RongIMClient.prototype.setRTCUserData = function (roomId, key, value, isInner, callback, message) { RongIMLib.CheckParam.getInstance().check(["string", "string", "string", "boolean", "object", "global|object|null|undefined"], "setRTCUserData", false, arguments); RongIMClient._dataAccessProvider.setRTCUserData(roomId, key, value, isInner, callback, message); }; RongIMClient.prototype.getRTCUserData = function (roomId, keys, isInner, callback) { RongIMLib.CheckParam.getInstance().check(["string", "array", "boolean", "object", "global|object|null"], "getRTCUserData", false, arguments); RongIMClient._dataAccessProvider.getRTCUserData(roomId, keys, isInner, callback); }; RongIMClient.prototype.removeRTCUserData = function (roomId, keys, isInner, callback, message) { RongIMLib.CheckParam.getInstance().check(["string", "array", "boolean", "object", "global|object|null|undefined"], "removeRTCUserData", false, arguments); RongIMClient._dataAccessProvider.removeRTCUserData(roomId, keys, isInner, callback, message); }; RongIMClient.prototype.setRTCRoomData = function (roomId, key, value, isInner, callback, message) { RongIMLib.CheckParam.getInstance().check(["string", "string", "string", "boolean", "object", "global|object|null|undefined"], "setRTCRoomData", false, arguments); RongIMClient._dataAccessProvider.setRTCRoomData(roomId, key, value, isInner, callback, message); }; RongIMClient.prototype.getRTCRoomData = function (roomId, keys, isInner, callback) { RongIMLib.CheckParam.getInstance().check(["string", "array", "boolean", "object"], "getRTCRoomData", false, arguments); RongIMClient._dataAccessProvider.getRTCRoomData(roomId, keys, isInner, callback); }; RongIMClient.prototype.removeRTCRoomData = function (roomId, keys, isInner, callback, message) { RongIMLib.CheckParam.getInstance().check(["string", "array", "boolean", "object", "global|object|null|undefined"], "removeRTCRoomData", false, arguments); RongIMClient._dataAccessProvider.removeRTCRoomData(roomId, keys, isInner, callback, message); }; RongIMClient.prototype.setRTCOutData = function (roomId, data, type, callback, message) { RongIMClient._dataAccessProvider.setRTCOutData(roomId, data, type, callback, message); }; // 信令 SDK 新增 RongIMClient.prototype.getRTCOutData = function (roomId, userIds, callback) { RongIMClient._dataAccessProvider.getRTCOutData(roomId, userIds, callback); }; RongIMClient.prototype.getNavi = function () { return RongIMClient._dataAccessProvider.getNavi(); }; RongIMClient.prototype.getRTCToken = function (room, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object"], "getRTCToken", false, arguments); return RongIMClient._dataAccessProvider.getRTCToken(room, callback); }; RongIMClient.prototype.setRTCState = function (room, content, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object", "object"], "setRTCState", false, arguments); return RongIMClient._dataAccessProvider.setRTCState(room, content, callback); }; RongIMClient.prototype.getAppInfo = function () { var appKey = RongIMClient._memoryStore.appKey; return { appKey: appKey }; }; RongIMClient.prototype.getSDKInfo = function () { return { version: RongIMClient.sdkver }; }; RongIMClient.RTCListener = function () { }; RongIMClient.RTCInnerListener = function () { }; RongIMClient.RTCSignalLisener = function () { }; RongIMClient.currentServer = ''; RongIMClient.LogFactory = {}; RongIMClient.MessageType = {}; RongIMClient.RegisterMessage = {}; RongIMClient._memoryStore = { isPullFinished: false, syncMsgQueue: [] }; RongIMClient.isNotPullMsg = false; RongIMClient.userStatusObserver = null; RongIMClient.sdkver = '2.5.5'; RongIMClient.otherDeviceLoginCount = 0; RongIMClient.serverStore = { index: 0 }; RongIMClient.isFirstConnect = true; RongIMClient.roomInfo = { users: {}, token: '' }; RongIMClient.invalidWsUrls = []; RongIMClient.isJoinedRTCRoom = false; RongIMClient.statusListeners = []; RongIMClient.messageListeners = []; RongIMClient.userStatusListener = null; return RongIMClient; })(); RongIMLib.RongIMClient = RongIMClient; })(RongIMLib || (RongIMLib = {})); //用于连接通道 var RongIMLib; (function (RongIMLib) { (function (Qos) { Qos[Qos["AT_MOST_ONCE"] = 0] = "AT_MOST_ONCE"; Qos[Qos["AT_LEAST_ONCE"] = 1] = "AT_LEAST_ONCE"; Qos[Qos["EXACTLY_ONCE"] = 2] = "EXACTLY_ONCE"; Qos[Qos["DEFAULT"] = 3] = "DEFAULT"; })(RongIMLib.Qos || (RongIMLib.Qos = {})); var Qos = RongIMLib.Qos; (function (Type) { Type[Type["CONNECT"] = 1] = "CONNECT"; Type[Type["CONNACK"] = 2] = "CONNACK"; Type[Type["PUBLISH"] = 3] = "PUBLISH"; Type[Type["PUBACK"] = 4] = "PUBACK"; Type[Type["QUERY"] = 5] = "QUERY"; Type[Type["QUERYACK"] = 6] = "QUERYACK"; Type[Type["QUERYCON"] = 7] = "QUERYCON"; Type[Type["SUBSCRIBE"] = 8] = "SUBSCRIBE"; Type[Type["SUBACK"] = 9] = "SUBACK"; Type[Type["UNSUBSCRIBE"] = 10] = "UNSUBSCRIBE"; Type[Type["UNSUBACK"] = 11] = "UNSUBACK"; Type[Type["PINGREQ"] = 12] = "PINGREQ"; Type[Type["PINGRESP"] = 13] = "PINGRESP"; Type[Type["DISCONNECT"] = 14] = "DISCONNECT"; })(RongIMLib.Type || (RongIMLib.Type = {})); var Type = RongIMLib.Type; var _topic = [ "invtDiz", "crDiz", "qnUrl", "userInf", "dizInf", "userInf", "joinGrp", "quitDiz", "exitGrp", "evctDiz", ["", "ppMsgP", "pdMsgP", "pgMsgP", "chatMsg", "pcMsgP", "", "pmcMsgN", "pmpMsgN", "", "", "", "prMsgS", "prMsgP"], "pdOpen", "rename", "uGcmpr", "qnTkn", "destroyChrm", "createChrm", "exitChrm", "queryChrm", "joinChrm", "pGrps", "addBlack", "rmBlack", "getBlack", "blackStat", "addRelation", "qryRelation", "delRelation", "pullMp", "schMp", "qnTkn", "qnUrl", "qryVoipK", "delMsg", "qryCHMsg", "getUserStatus", "setUserStatus", "subUserStatus", "cleanHisMsg" ]; var Channel = (function () { function Channel(cb, self) { this.connectionStatus = -1; var appId = self.appId; var token = encodeURIComponent(self.token); var sdkVer = self.sdkVer; var apiVer = self.apiVer; this.self = self; this.socket = Socket.getInstance().createServer(); var that = this; var storage = RongIMLib.RongIMClient._storageProvider; var servers = storage.getItem('servers'); servers = JSON.parse(servers) || []; servers = RongIMLib.RongUtil.getValidWsUrlList(servers); var depend = RongIMLib.RongIMClient._memoryStore.depend; if (depend.cmpUrl) { servers = [depend.cmpUrl].concat(servers); } var startConnect = function (host) { var tpl = '{host}/websocket?appId={appId}&token={token}&sdkVer={sdkVer}&apiVer={apiVer}'; that.url = RongIMLib.RongUtil.tplEngine(tpl, { host: host, appId: appId, token: token, sdkVer: sdkVer, apiVer: apiVer }); that.socket.connect(that.url, cb); // 临时兼容 Comet 逻辑,Comet 中用到 var userId = storage.getItem('rong_current_user'); RongIMLib.Navigation.Endpoint = { host: host, userId: userId }; }; var connectMap = { get: function () { // 所有链接计算器,超过 15 秒后认为所有 CMP 地址均不可用 var totalTimer = new RongIMLib.Timer({ timeout: 1 * 1000 * 15 }); var timers = []; var xhrs = []; var isFinished = false; var clearHandler = function () { for (var i = 0; i < timers.length; i++) { var timer = timers[i]; clearTimeout(timer); } for (var i = 0; i < xhrs.length; i++) { var xhr = xhrs[i]; xhr.abort(); } timers.length = 0; xhrs.length = 0; }; var request = function (config, callback) { var url = config.url; var time = config.time; if (isFinished) { return; } var timer = setTimeout(function () { var onSuccess = function () { if (isFinished) { return; } clearHandler(); isFinished = true; totalTimer.pause(); callback(url); }; var xhr = RongIMLib.MessageUtil.detectCMP({ url: url, success: onSuccess, fail: function (code) { console.log(code); } }); xhrs.push(xhr); }, time); timers.push(timer); }; var snifferCallback = function (url) { var reg = /(http|https):\/\/([^\/]+)/i; var host = url.match(reg)[2]; RongIMLib.RongIMClient.currentServer = host; startConnect(host); }; var snifferTpl = '{protocol}{server}/ping?r={random}'; for (var i = 0; i < servers.length; i++) { var server = servers[i]; if (server) { server = RongIMLib.RongUtil.tplEngine(snifferTpl, { protocol: depend.protocol, server: server, random: RongIMLib.RongUtil.getTimestamp() }); request({ url: server, time: i * 1000 }, snifferCallback); } } totalTimer.resume(function () { RongIMLib.Navigation.clear(); clearHandler(); that.socket.fire("StatusChanged", RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE); }); }, element: function () { var totalTimer = new RongIMLib.Timer({ timeout: 1 * 1000 * 15 }); var timers = []; var elements = []; var isFinished = false; var clearHandler = function () { for (var i = 0; i < timers.length; i++) { var timer = timers[i]; clearTimeout(timer); } for (var i = 0; i < elements.length; i++) { var el = elements[i]; document.body.removeChild(el); } }; var request = function (config, callback) { var url = config.url; var time = config.time; if (isFinished) { return; } var timer = setTimeout(function () { var el = document.createElement('script'); el.src = url; document.body.appendChild(el); el.onerror = function () { if (isFinished) { return; } clearHandler(); isFinished = true; totalTimer.pause(); var url = el.src; callback(url); }; elements.push(el); }, time); timers.push(timer); }; var snifferCallback = function (url) { var reg = /(http|https):\/\/([^\/]+)/i; var host = url.match(reg)[2]; startConnect(host); }; var snifferTpl = '//{server}/{path}'; for (var i = 0; i < servers.length; i++) { var server = RongIMLib.RongUtil.tplEngine(snifferTpl, { server: servers[i], path: i }); request({ url: server, time: i * 1000 }, snifferCallback); } totalTimer.resume(function () { clearHandler(); that.socket.fire("StatusChanged", RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE); }); } }; var isWSPingJSONP = depend.isWSPingJSONP; var connectType = isWSPingJSONP ? 'element' : 'get'; connectMap[connectType](); //注册状态改变观察者 var StatusEvent = Channel._ConnectionStatusListener; var hasEvent = (typeof StatusEvent == "object"); var me = this; me.socket.on("StatusChanged", function (code) { if (RongIMLib.Bridge && RongIMLib.Bridge._client && RongIMLib.Bridge._client.channel && me !== RongIMLib.Bridge._client.channel) { return; } if (!hasEvent) { throw new Error("setConnectStatusListener:Parameter format is incorrect"); } var isNetworkUnavailable = (code == RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE); var isWebSocket = !RongIMLib.RongIMClient._memoryStore.depend.isPolling; if (RongIMLib.RongIMClient.isFirstConnect && isNetworkUnavailable && isWebSocket) { code = RongIMLib.ConnectionStatus.WEBSOCKET_UNAVAILABLE; } if (isNetworkUnavailable) { var storage = RongIMLib.RongIMClient._storageProvider; var servers = storage.getItem('servers'); servers = JSON.parse(servers); var currentServer = RongIMLib.RongIMClient.currentServer; if (currentServer) { var index = RongIMLib.RongUtil.indexOf(servers, currentServer); // 如果 currentServer 是 servers 的最后一个,不再替换位置 if (!RongIMLib.RongUtil.isEqual(index, -1)) { var server = servers.splice(index, 1)[0]; servers.push(server); storage.setItem('servers', JSON.stringify(servers)); } } } me.connectionStatus = code; setTimeout(function () { StatusEvent.onChanged(code); }); var isDisconnected = (code == RongIMLib.ConnectionStatus.DISCONNECTED); if (isDisconnected) { self.clearHeartbeat(); } var isOtherDevice = (code == RongIMLib.ConnectionStatus.KICKED_OFFLINE_BY_OTHER_CLIENT); if (isOtherDevice) { // 累计其他设备登陆次数,超过 5 次后,自动销毁内部对象 // 删除位置:ServerDataProivder.prototype.connect RongIMLib.RongIMClient.otherDeviceLoginCount++; } var isConnected = (code == RongIMLib.ConnectionStatus.CONNECTED); if (isConnected) { RongIMLib.RongIMClient.isFirstConnect = false; } var isWebsocketUnAvailable = (code == RongIMLib.ConnectionStatus.WEBSOCKET_UNAVAILABLE); if (isWebsocketUnAvailable) { me.changeConnectType(); RongIMLib.RongIMClient.isFirstConnect = false; RongIMLib.RongIMClient.connect(self.token, RongIMLib.RongIMClient._memoryStore.callback); } }); //注册message观察者 this.socket.on("message", self.handler.handleMessage); //注册断开连接观察者 this.socket.on("disconnect", function (status) { that.socket.fire("StatusChanged", status ? status : 2); }); } Channel.prototype.changeConnectType = function () { RongIMLib.RongIMClient._memoryStore.depend.isPolling = !RongIMLib.RongIMClient._memoryStore.depend.isPolling; new RongIMLib.FeatureDectector(); }; Channel.prototype.writeAndFlush = function (val) { this.socket.send(val); }; Channel.prototype.reconnect = function (callback) { RongIMLib.MessageIdHandler.clearMessageId(); this.socket = this.socket.reconnect(); if (callback) { this.self.reconnectObj = callback; } }; Channel.prototype.disconnect = function (status) { this.socket.disconnect(status); }; return Channel; })(); RongIMLib.Channel = Channel; var Socket = (function () { function Socket() { this.socket = null; this._events = {}; } Socket.getInstance = function () { return new Socket(); }; Socket.prototype.connect = function (url, cb) { if (this.socket) { if (url) { RongIMLib.RongIMClient._storageProvider.setItem("rongSDK", this.checkTransport()); this.on("connect", cb || new Function); } if (url) { this.currentURL = url; } this.socket.createTransport(url); } return this; }; Socket.prototype.createServer = function () { var transport = this.getTransport(this.checkTransport()); if (transport === null) { throw new Error("the channel was not supported"); } return transport; }; Socket.prototype.getTransport = function (transportType) { if (transportType == Socket.XHR_POLLING) { this.socket = new RongIMLib.PollingTransportation(this); } else if (transportType == Socket.WEBSOCKET) { this.socket = new RongIMLib.SocketTransportation(this); } return this; }; Socket.prototype.send = function (data) { if (this.socket) { if (this.checkTransport() == Socket.WEBSOCKET) { this.socket.send(data); } else { this.socket.send(this._encode(data)); } } }; Socket.prototype.onMessage = function (data) { this.fire("message", data); }; Socket.prototype.disconnect = function (status) { this.socket.disconnect(status); this.fire("disconnect", status); return this; }; Socket.prototype.reconnect = function () { if (this.currentURL && RongIMLib.RongIMClient._storageProvider.getItem("rongSDK")) { return this.connect(this.currentURL, null); } else { throw new Error("reconnect:no have URL"); } }; /** * [checkTransport 返回通道类型] */ Socket.prototype.checkTransport = function () { if (RongIMLib.RongIMClient._memoryStore.depend.isPolling) { RongIMLib.Transportations._TransportType = Socket.XHR_POLLING; } return RongIMLib.Transportations._TransportType; }; Socket.prototype.fire = function (x, args) { if (x in this._events) { for (var i = 0, ii = this._events[x].length; i < ii; i++) { this._events[x][i](args); } } return this; }; Socket.prototype.on = function (x, func) { if (!(typeof func == "function" && x)) { return this; } if (x in this._events) { RongIMLib.MessageUtil.indexOf(this._events, func) == -1 && this._events[x].push(func); } else { this._events[x] = [func]; } return this; }; Socket.prototype.removeEvent = function (x, fn) { if (x in this._events) { for (var a = 0, l = this._events[x].length; a < l; a++) { if (this._events[x][a] == fn) { this._events[x].splice(a, 1); } } } return this; }; Socket.prototype._encode = function (x) { var str = "?messageid=" + x.getMessageId() + "&header=" + x.getHeaderFlag() + "&sessionid=" + RongIMLib.RongIMClient._storageProvider.getItem("sId" + RongIMLib.Navigation.Endpoint.userId); if (!/(PubAckMessage|QueryConMessage)/.test(x._name)) { str += "&topic=" + x.getTopic() + "&targetid=" + (x.getTargetId() || ""); } return { url: str, data: "getData" in x ? x.getData() : "" }; }; //消息通道常量,所有和通道相关判断均用 XHR_POLLING WEBSOCKET两属性 Socket.XHR_POLLING = "xhr-polling"; Socket.WEBSOCKET = "websocket"; return Socket; })(); RongIMLib.Socket = Socket; //连接端消息累 var Client = (function () { function Client(token, appId) { this.timeoutMillis = 6000; this.timeout_ = 0; this.sdkVer = ''; this.apiVer = Math.floor(Math.random() * 1e6); this.channel = null; this.handler = null; this.userId = ""; this.reconnectObj = {}; this.heartbeat = 0; this.pullMsgHearbeat = 0; this.chatroomId = ""; this.SyncTimeQueue = []; this.cacheMessageIds = []; this.token = token; this.appId = appId; this.SyncTimeQueue.state = "complete"; this.sdkVer = RongIMLib.RongIMClient.sdkver; } Client.prototype.resumeTimer = function () { var me = this; this.timeout_ = setTimeout(function () { me.channel.disconnect(RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE); }, this.timeoutMillis); }; Client.prototype.pauseTimer = function () { if (this.timeout_) { clearTimeout(this.timeout_); this.timeout_ = 0; } }; Client.prototype.connect = function (_callback) { //实例消息处理类 this.handler = new MessageHandler(this); //设置连接回调 this.handler.setConnectCallback(_callback); //实例通道类型 var me = this; this.channel = new Channel(function () { RongIMLib.Transportations._TransportType == Socket.WEBSOCKET && me.keepLive(); }, this); //触发状态改变观察者 this.channel.socket.fire("StatusChanged", RongIMLib.ConnectionStatus.CONNECTING); //没有返回地址就手动抛出错误 //_callback.onError(ConnectionState.NOT_AUTHORIZED); }; Client.prototype.checkSocket = function (callback) { var me = this; me.channel.writeAndFlush(new RongIMLib.PingReqMessage()); var count = 0; var checkTimeout = setInterval(function () { if (!RongIMLib.RongIMClient._memoryStore.isFirstPingMsg) { clearInterval(checkTimeout); callback.onSuccess(); } else { if (count > 15) { clearInterval(checkTimeout); callback.onError(); } } count++; }, 100); }; Client.prototype.keepLive = function () { if (this.heartbeat > 0) { clearInterval(this.heartbeat); } var me = this; me.heartbeat = setInterval(function () { me.resumeTimer(); me.channel.writeAndFlush(new RongIMLib.PingReqMessage()); }, 30000); if (me.pullMsgHearbeat > 0) { clearInterval(me.pullMsgHearbeat); } me.pullMsgHearbeat = setInterval(function () { me.syncTime(true, undefined, undefined, false); }, 180000); }; Client.prototype.clearHeartbeat = function () { clearInterval(this.heartbeat); this.heartbeat = 0; this.pauseTimer(); clearInterval(this.pullMsgHearbeat); this.pullMsgHearbeat = 0; }; Client.prototype.publishMessage = function (_topic, _data, _targetId, _callback, _msg) { var msgId = RongIMLib.MessageIdHandler.messageIdPlus(this.channel.reconnect); if (!msgId) { return; } var msg = new RongIMLib.PublishMessage(_topic, _data, _targetId); msg.setMessageId(msgId); if (_callback) { msg.setQos(Qos.AT_LEAST_ONCE); this.handler.putCallback(new RongIMLib.PublishCallback(_callback.onSuccess, _callback.onError), msg.getMessageId(), _msg); } else { msg.setQos(Qos.AT_MOST_ONCE); } this.channel.writeAndFlush(msg); }; Client.prototype.queryMessage = function (_topic, _data, _targetId, _qos, _callback, pbtype) { if (_topic == "userInf") { if (Client.userInfoMapping[_targetId]) { _callback.onSuccess(Client.userInfoMapping[_targetId]); return; } } var msgId = RongIMLib.MessageIdHandler.messageIdPlus(this.channel.reconnect); if (!msgId) { return; } var msg = new RongIMLib.QueryMessage(_topic, _data, _targetId); msg.setMessageId(msgId); msg.setQos(_qos); this.handler.putCallback(new RongIMLib.QueryCallback(_callback.onSuccess, _callback.onError), msg.getMessageId(), pbtype); this.channel.writeAndFlush(msg); }; Client.prototype.invoke = function (isPullMsg, chrmId, offlineMsg) { var time, modules, str, me = this, target, temp = this.SyncTimeQueue.shift(); if (temp == undefined) { return; } this.SyncTimeQueue.state = "pending"; var localSyncTime = RongIMLib.SyncTimeUtil.get(); var sentBoxTime = localSyncTime.sent; var isPullChatroom = temp.type === 2; if (temp.type != 2) { //普通消息 time = localSyncTime.received; modules = new RongIMLib.RongIMClient.Protobuf.SyncRequestMsg(); modules.setIspolling(false); str = "pullMsg"; target = this.userId; modules.setSendBoxSyncTime(sentBoxTime); } else { //聊天室消息 target = temp.chrmId || me.chatroomId; time = RongIMLib.RongIMClient._memoryStore.lastReadTime.get(target + Bridge._client.userId + "CST") || 0; modules = new RongIMLib.RongIMClient.Protobuf.ChrmPullMsg(); modules.setCount(0); str = "chrmPull"; if (!target) { throw new Error("syncTime:Received messages of chatroom but was not init"); } } //判断服务器给的时间是否消息本地存储的时间,小于的话不执行拉取操作,进行一下步队列操作 if (temp.pulltime <= time) { this.SyncTimeQueue.state = "complete"; this.invoke(isPullMsg, target, offlineMsg); return; } if (isPullMsg && 'setIsPullSend' in modules) { modules.setIsPullSend(true); } modules.setSyncTime(time); //发送queryMessage请求 this.queryMessage(str, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), target, Qos.AT_LEAST_ONCE, { onSuccess: function (collection) { var sync = RongIMLib.MessageUtil.int64ToTimestamp(collection.syncTime), symbol = target; //把返回时间戳存入本地,普通消息key为userid,聊天室消息key为userid+'CST';value都为服务器返回的时间戳 var isChrmPull = str == 'chrmPull'; if (isChrmPull) { symbol += Bridge._client.userId + "CST"; RongIMLib.RongIMClient._memoryStore.lastReadTime.set(symbol, sync); } else { var storage = RongIMLib.RongIMClient._storageProvider; if (sync > storage.getItem(symbol)) { storage.setItem(symbol, sync); } } //把拉取到的消息逐条传给消息监听器 var list = collection.list; var isPullFinished = collection.finished; // chrmPull 没有 finished 字段,自动设置为拉取完成 if (isChrmPull) { isPullFinished = true; } // 兼容长轮训 finished 为空的造成丢消息情况 if (typeof isPullFinished == 'undefined') { isPullFinished = true; } RongIMLib.RongIMClient._memoryStore.isPullFinished = isPullFinished; var connectAckTime = RongIMLib.RongIMClient._memoryStore.connectAckTime; var len = list.length; for (var i = 0, count = len; i < len; i++) { count -= 1; var message = list[i]; var sentTime = RongIMLib.MessageUtil.int64ToTimestamp(message.dataTime); var isSender = message.direction == RongIMLib.MessageDirection.SEND; var compareTime = isSender ? sentBoxTime : time; if (sentTime > compareTime || isPullChatroom) { var isSyncMessage = false; var isOffLineMessage = sentTime < connectAckTime; Bridge._client.handler.onReceived(message, undefined, isOffLineMessage, count, isSyncMessage, isPullFinished); } } if (len <= 200 && str == 'pullMsg') { var Conversation = RongIMLib.RongIMClient._dataAccessProvider.Conversation; var conversationList = RongIMLib.RongIMClient._memoryStore.conversationList; Conversation._notify(conversationList); } me.SyncTimeQueue.state = "complete"; me.invoke(isPullMsg, target, offlineMsg); }, onError: function (error) { me.SyncTimeQueue.state = "complete"; me.invoke(isPullMsg, target, offlineMsg); } }, "DownStreamMessages"); }; Client.prototype.syncTime = function (_type, pullTime, chrmId, offlineMsg) { this.SyncTimeQueue.push({ type: _type, pulltime: pullTime, chrmId: chrmId }); //如果队列中只有一个成员并且状态已经完成就执行invoke方法 if (this.SyncTimeQueue.length == 1 && this.SyncTimeQueue.state == "complete") { this.invoke(!_type, chrmId, offlineMsg); } }; Client.prototype.__init = function (f) { this.handler = new MessageHandler(this); //设置连接回调 this.handler.setConnectCallback(RongIMLib.RongIMClient._memoryStore.callback); this.channel = new Channel(f, this); }; Client.userInfoMapping = {}; return Client; })(); RongIMLib.Client = Client; //连接类,实现imclient与connect_client的连接 var Bridge = (function () { function Bridge() { } Bridge.getInstance = function () { return new Bridge(); }; //连接服务器 Bridge.prototype.connect = function (appKey, token, callback) { if (!RongIMLib.RongIMClient.Protobuf) { return; } Bridge._client = new RongIMLib.Navigation().connect(appKey, token, callback); return Bridge._client; }; Bridge.prototype.setListener = function () { Channel._ConnectionStatusListener = { onChanged: function (status) { RongIMLib.RongUtil.forEach(RongIMLib.RongIMClient.statusListeners, function (watch) { RongIMLib.RongUtil.isFunction(watch) && watch(status); }); } }; Channel._ReceiveMessageListener = { onReceived: function (msg, count, hasMore) { RongIMLib.RongUtil.forEach(RongIMLib.RongIMClient.messageListeners, function (watch) { RongIMLib.RongUtil.isFunction(watch) && watch(msg, count, hasMore); }); } }; }; Bridge.prototype.reconnect = function (callabck) { Bridge._client.channel.reconnect(callabck); }; Bridge.prototype.disconnect = function () { Bridge._client.channel.disconnect(2); }; //执行queryMessage请求 Bridge.prototype.queryMsg = function (topic, content, targetId, callback, pbname) { if (typeof topic != "string") { topic = _topic[topic]; } Bridge._client.queryMessage(topic, content, targetId, Qos.AT_MOST_ONCE, callback, pbname); }; //发送消息 执行publishMessage 请求 Bridge.prototype.pubMsg = function (topic, content, targetId, callback, msg, methodType) { if (typeof methodType == 'number') { if (methodType == RongIMLib.MethodType.CUSTOMER_SERVICE) { Bridge._client.publishMessage("pcuMsgP", content, targetId, callback, msg); } else if (methodType == RongIMLib.MethodType.RECALL) { Bridge._client.publishMessage("recallMsg", content, targetId, callback, msg); } } else { Bridge._client.publishMessage(_topic[10][topic], content, targetId, callback, msg); } }; return Bridge; })(); RongIMLib.Bridge = Bridge; var MessageHandler = (function () { function MessageHandler(client) { this.map = {}; this.connectCallback = null; if (!Channel._ReceiveMessageListener) { throw new Error("please set onReceiveMessageListener"); } this._onReceived = Channel._ReceiveMessageListener.onReceived; this._client = client; this.syncMsgMap = new Object; } //把对象推入回调对象队列中,并启动定时器 MessageHandler.prototype.putCallback = function (callbackObj, _publishMessageId, _msg) { var item = { Callback: callbackObj, Message: _msg }; item.Callback.resumeTimer(); this.map[_publishMessageId] = item; }; //设置连接回调对象,启动定时器 MessageHandler.prototype.setConnectCallback = function (_connectCallback) { if (_connectCallback) { this.connectCallback = new RongIMLib.ConnectAck(_connectCallback.onSuccess, _connectCallback.onError, this._client); } }; MessageHandler.prototype.handleChrmKVPullMsg = function (msg) { try { var pbtype = 'ChrmNotifyMsg'; var data = RongIMLib.CallbackMapping.getInstance().mapping(RongIMLib.RongIMClient.Protobuf[pbtype].decode(msg.data), pbtype); if (data.type === 2) { var timestamp = RongIMLib.MessageUtil.int64ToTimestamp(data.time); RongIMLib.ChrmKVHandler.pull(data.chrmId, timestamp); } } catch (e) { } }; MessageHandler.prototype.onReceived = function (msg, pubAckItem, offlineMsg, leftCount, isSync) { //实体对象 var entity, //解析完成的消息对象 message, //会话对象 con, // 是否为直发消息 isStraightMsg = false; if (msg._name != "PublishMessage") { entity = msg; RongIMLib.RongIMClient._storageProvider.setItem(this._client.userId, RongIMLib.MessageUtil.int64ToTimestamp(entity.dataTime)); } else { if (msg.getTopic() == "s_ntf") { entity = RongIMLib.RongIMClient.Protobuf.NotifyMsg.decode(msg.getData()); this._client.syncTime(entity.type, RongIMLib.MessageUtil.int64ToTimestamp(entity.time), entity.chrmId); return; } else if (msg.getTopic() == "s_msg") { isStraightMsg = true; entity = RongIMLib.RongIMClient.Protobuf.DownStreamMessage.decode(msg.getData()); var timestamp = RongIMLib.MessageUtil.int64ToTimestamp(entity.dataTime); RongIMLib.RongIMClient._storageProvider.setItem(this._client.userId, timestamp); RongIMLib.RongIMClient._memoryStore.lastReadTime.get(this._client.userId, timestamp); } else if (msg.getTopic() == "s_stat") { entity = RongIMLib.RongIMClient.Protobuf.GetUserStatusOutput.decode(msg.getData()); entity = RongIMLib.RongInnerTools.convertUserStatus(entity); RongIMLib.RongIMClient.userStatusObserver.notify({ key: entity.userId, entity: entity }); return; } else if (msg.getTopic() === 's_cmd') { this.handleChrmKVPullMsg(msg); return; } else { if (Bridge._client.sdkVer && Bridge._client.sdkVer == "1.0.0") { return; } entity = RongIMLib.RongIMClient.Protobuf.UpStreamMessage.decode(msg.getData()); var tmpTopic = msg.getTopic(); var tmpType = tmpTopic.substr(0, 2); if (tmpType == "pp") { entity.type = 1; } else if (tmpType == "pd") { entity.type = 2; } else if (tmpType == "pg") { entity.type = 3; } else if (tmpType == "ch") { entity.type = 4; } else if (tmpType == "pc") { entity.type = 5; } //复用字段,targetId 以此为准 entity.groupId = msg.getTargetId(); entity.fromUserId = this._client.userId; entity.dataTime = Date.parse(new Date().toString()); } if (!entity) { return; } } var isPullFinished = RongIMLib.RongIMClient._memoryStore.isPullFinished; // PullMsg 没有拉取完成,抛弃所有直发在线消息,抛弃的消息会在 PullMsg 中返回 if (!isPullFinished && !offlineMsg && isStraightMsg) { return; } //解析实体对象为消息对象。 message = RongIMLib.MessageUtil.messageParser(entity, this._onReceived, offlineMsg); var isRTCMessage = message.conversationType == 12; if (isRTCMessage) { RongIMLib.RongIMClient.RTCListener(message); RongIMLib.RongIMClient.RTCInnerListener(message); RongIMLib.RongIMClient.RTCSignalLisener(message); return; } var isRecall = (msg.getTopic && msg.getTopic() == "recallMsg"); if (isRecall) { var content = message.content; message.conversationType = content.conversationType; message.targetId = content.targetId; message.messageId = null; } if (pubAckItem) { message.messageUId = pubAckItem.getMessageUId(); message.sentTime = pubAckItem.getTimestamp(); RongIMLib.RongIMClient._storageProvider.setItem(this._client.userId, message.sentTime); } if (message === null) { return; } var isChatroomMessage = message.conversationType == RongIMLib.ConversationType.CHATROOM; if (!isChatroomMessage) { var msgTag = RongIMLib.RongIMClient.MessageParams[message.messageType].msgTag.getMessageTag(); if (msgTag >= 0) { RongIMLib.SyncTimeUtil.set(message); } var isSend = (message.messageDirection == RongIMLib.MessageDirection.SEND); if (isSend) { var storageProvider = RongIMLib.RongIMClient._storageProvider; var userId = RongIMLib.Bridge._client.userId; var lastSentTime = storageProvider.getItem('last_sentTime_' + userId) || 0; if (message.sentTime <= lastSentTime && !isSync) { return; } } } // 设置会话时间戳并且判断是否传递 message 发送消息未处理会话时间戳 // key:'converST_' + 当前用户 + conversationType + targetId // RongIMClient._storageProvider.setItem('converST_' + Bridge._client.userId + message.conversationType + message.targetId, message.sentTime); // var isPersited = (RongIMClient.MessageParams[message.messageType].msgTag.getMessageTag() > 0); var msgTag = RongIMLib.RongIMClient.MessageParams[message.messageType].msgTag.getMessageTag(); var isPersited = msgTag === 3 || msgTag === 2; if (isPersited) { con = RongIMLib.RongIMClient._dataAccessProvider.getConversation(message.conversationType, message.targetId, { onSuccess: function () { }, onError: function () { } }); if (!con) { con = RongIMLib.RongIMClient.getInstance().createConversation(message.conversationType, message.targetId, ""); } if (message.messageDirection == RongIMLib.MessageDirection.RECEIVE && (entity.status & 64) == 64) { var mentioneds = RongIMLib.RongIMClient._storageProvider.getItem("mentioneds_" + Bridge._client.userId + '_' + message.conversationType + '_' + message.targetId); var key = message.conversationType + '_' + message.targetId, info = {}; if (message.content && message.content.mentionedInfo) { info[key] = { uid: message.messageUId, time: message.sentTime, mentionedInfo: message.content.mentionedInfo }; RongIMLib.RongIMClient._storageProvider.setItem("mentioneds_" + Bridge._client.userId + '_' + message.conversationType + '_' + message.targetId, JSON.stringify(info)); mentioneds = JSON.stringify(info); } if (mentioneds) { var info = JSON.parse(mentioneds); con.mentionedMsg = info[key]; } } var isReceiver = message.messageDirection == RongIMLib.MessageDirection.RECEIVE; if (isReceiver && message.senderUserId != Bridge._client.userId) { con.unreadMessageCount = con.unreadMessageCount + 1; if (RongIMLib.RongUtil.supportLocalStorage()) { // var originUnreadCount = RongIMClient._storageProvider.getItem("cu" + Bridge._client.userId + con.conversationType + con.targetId); // 与本地存储会话合并 // var newUnreadCount = Number(originUnreadCount) + 1; // RongIMClient._storageProvider.setItem("cu" + Bridge._client.userId + con.conversationType + message.targetId, newUnreadCount); var newUnreadCount = RongIMLib.UnreadCountHandler.add(con.conversationType, message.targetId, 1, message.sentTime); con.unreadMessageCount = newUnreadCount; } } con.receivedTime = new Date().getTime(); con.receivedStatus = message.receivedStatus; con.senderUserId = message.sendUserId; con.notificationStatus = RongIMLib.ConversationNotificationStatus.DO_NOT_DISTURB; con.latestMessageId = message.messageId; con.latestMessage = message; con.sentTime = message.sentTime; RongIMLib.RongIMClient._dataAccessProvider.addConversation(con, { onSuccess: function (data) { if (!offlineMsg) { var Conversation_1 = RongIMLib.RongIMClient._dataAccessProvider.Conversation; var conversationList = RongIMLib.RongIMClient._memoryStore.conversationList; Conversation_1._notify(conversationList); } }, onError: function () { } }); } if (message.conversationType == RongIMLib.ConversationType.CUSTOMER_SERVICE && (message.messageType == "ChangeModeResponseMessage" || message.messageType == "SuspendMessage" || message.messageType == "HandShakeResponseMessage" || message.messageType == "TerminateMessage" || message.messageType == "CustomerStatusUpdateMessage" || message.messageType == "TextMessage" || message.messageType == "InformationNotificationMessage")) { if (!RongIMLib.RongIMClient._memoryStore.custStore["isInit"]) { return; } } if (message.conversationType == RongIMLib.ConversationType.CUSTOMER_SERVICE && message.messageType != "HandShakeResponseMessage") { if (!RongIMLib.RongIMClient._memoryStore.custStore[message.targetId]) { return; } if (message.messageType == "TerminateMessage") { if (RongIMLib.RongIMClient._memoryStore.custStore[message.targetId].sid != message.content.sid) { return; } } } if (message.messageType === RongIMLib.RongIMClient.MessageType["HandShakeResponseMessage"]) { var session = message.content.data; RongIMLib.RongIMClient._memoryStore.custStore[message.targetId] = session; if (session.serviceType == RongIMLib.CustomerType.ONLY_HUMAN || session.serviceType == RongIMLib.CustomerType.HUMAN_FIRST) { if (session.notAutoCha == "1") { RongIMLib.RongIMClient.getInstance().switchToHumanMode(message.targetId, { onSuccess: function () { }, onError: function () { } }); } } } var d = new Date(), m = d.getMonth() + 1, date = d.getFullYear() + '/' + (m.toString().length == 1 ? '0' + m : m) + '/' + d.getDate(); //new Date(date).getTime() - message.sentTime < 1 逻辑判断 超过 1 天未收的 ReadReceiptRequestMessage 离线消息自动忽略。 var dealtime = new Date(date).getTime() - message.sentTime < 0; if (RongIMLib.RongUtil.supportLocalStorage() && message.messageType === RongIMLib.RongIMClient.MessageType["ReadReceiptRequestMessage"] && dealtime && message.messageDirection == RongIMLib.MessageDirection.SEND) { var sentkey = Bridge._client.userId + message.content.messageUId + "SENT"; RongIMLib.RongIMClient._storageProvider.setItem(sentkey, JSON.stringify({ count: 0, dealtime: message.sentTime, userIds: {} })); } else if (RongIMLib.RongUtil.supportLocalStorage() && message.messageType === RongIMLib.RongIMClient.MessageType["ReadReceiptRequestMessage"] && dealtime) { var reckey = Bridge._client.userId + message.conversationType + message.targetId + 'RECEIVED', recData = JSON.parse(RongIMLib.RongIMClient._storageProvider.getItem(reckey)); if (recData) { if (message.senderUserId in recData) { if (recData[message.senderUserId].uIds && recData[message.senderUserId].uIds && recData[message.senderUserId].uIds.indexOf(message.content.messageUId) == -1) { recData[message.senderUserId].uIds.push(message.content.messageUId); recData[message.senderUserId].dealtime = message.sentTime; recData[message.senderUserId].isResponse = false; RongIMLib.RongIMClient._storageProvider.setItem(reckey, JSON.stringify(recData)); } else { return; } } else { var objSon = { uIds: [message.content.messageUId], dealtime: message.sentTime, isResponse: false }; recData[message.senderUserId] = objSon; RongIMLib.RongIMClient._storageProvider.setItem(reckey, JSON.stringify(recData)); } } else { var obj = {}; obj[message.senderUserId] = { uIds: [message.content.messageUId], dealtime: message.sentTime, isResponse: false }; RongIMLib.RongIMClient._storageProvider.setItem(reckey, JSON.stringify(obj)); } } if (RongIMLib.RongUtil.supportLocalStorage() && message.messageType === RongIMLib.RongIMClient.MessageType["ReadReceiptResponseMessage"] && dealtime) { var receiptResponseMsg = message.content, uIds = receiptResponseMsg.receiptMessageDic[Bridge._client.userId], sentkey = "", sentObj; message.receiptResponse || (message.receiptResponse = {}); if (uIds) { var cbuIds = []; for (var i = 0, len = uIds.length; i < len; i++) { sentkey = Bridge._client.userId + uIds[i] + "SENT"; sentObj = JSON.parse(RongIMLib.RongIMClient._storageProvider.getItem(sentkey)); if (sentObj && !(message.senderUserId in sentObj.userIds)) { cbuIds.push(uIds[i]); sentObj.count += 1; sentObj.userIds[message.senderUserId] = message.sentTime; message.receiptResponse[uIds[i]] = sentObj.count; RongIMLib.RongIMClient._storageProvider.setItem(sentkey, JSON.stringify(sentObj)); } } receiptResponseMsg.receiptMessageDic[Bridge._client.userId] = cbuIds; message.content = receiptResponseMsg; } } var that = this; if (RongIMLib.RongIMClient._voipProvider && ['AcceptMessage', 'RingingMessage', 'HungupMessage', 'InviteMessage', 'MediaModifyMessage', 'MemberModifyMessage'].indexOf(message.messageType) > -1) { setTimeout(function () { RongIMLib.RongIMClient._voipProvider.onReceived(message); }); } else { var count = leftCount || 0; var hasMore = !isPullFinished; that._onReceived(message, count, hasMore); } }; MessageHandler.prototype.handleMessage = function (msg) { if (!msg) { return; } switch (msg._name) { case "ConnAckMessage": Bridge._client.handler.connectCallback.process(msg.getStatus(), msg.getUserId(), msg.getTimestamp()); break; case "PublishMessage": if (!msg.getSyncMsg() && msg.getQos() != 0) { Bridge._client.channel.writeAndFlush(new RongIMLib.PubAckMessage(msg.getMessageId())); } // TODO && -> if (msg.getSyncMsg() && !RongIMLib.RongIMClient._memoryStore.depend.isPolling) { Bridge._client.handler.syncMsgMap[msg.getMessageId()] = msg; } else { //如果是PublishMessage就把该对象给onReceived方法执行处理 Bridge._client.handler.onReceived(msg); } break; case "QueryAckMessage": if (msg.getQos() != 0) { Bridge._client.channel.writeAndFlush(new RongIMLib.QueryConMessage(msg.getMessageId())); } var temp = Bridge._client.handler.map[msg.getMessageId()]; if (temp) { //执行回调操作 temp.Callback.process(msg.getStatus(), msg.getData(), msg.getDate(), temp.Message); delete Bridge._client.handler.map[msg.getMessageId()]; } break; case "PubAckMessage": var item = Bridge._client.handler.map[msg.getMessageId()]; if (item) { item.Callback.process(msg.getStatus() || 0, msg.getMessageUId(), msg.getTimestamp(), item.Message, msg.getMessageId()); delete Bridge._client.handler.map[msg.getMessageId()]; } else { var userId = RongIMLib.Bridge._client.userId; RongIMLib.RongIMClient._storageProvider.setItem('last_sentTime_' + userId, msg.timestamp); Bridge._client.handler.onReceived(Bridge._client.handler.syncMsgMap[msg.messageId], msg, null, null, true); delete Bridge._client.handler.syncMsgMap[msg.getMessageId()]; } break; case "PingRespMessage": if (RongIMLib.RongIMClient._memoryStore.isFirstPingMsg) { RongIMLib.RongIMClient._memoryStore.isFirstPingMsg = false; } else { Bridge._client.pauseTimer(); } break; case "DisconnectMessage": Bridge._client.channel.disconnect(msg.getStatus()); break; default: } }; return MessageHandler; })(); RongIMLib.MessageHandler = MessageHandler; })(RongIMLib || (RongIMLib = {})); var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; /// var RongIMLib; (function (RongIMLib) { var MessageCallback = (function () { function MessageCallback(error) { this.timeout = null; this.onError = null; if (error && typeof error == "number") { this.timeoutMillis = error; } else { this.timeoutMillis = 30000; this.onError = error; } } MessageCallback.prototype.resumeTimer = function () { var me = this; if (this.timeoutMillis > 0 && !this.timeout) { this.timeout = setTimeout(function () { me.readTimeOut(true); }, this.timeoutMillis); } }; MessageCallback.prototype.pauseTimer = function () { if (this.timeout) { clearTimeout(this.timeout); this.timeout = null; } }; MessageCallback.prototype.readTimeOut = function (isTimeout) { if (isTimeout && this.onError) { this.onError(RongIMLib.ErrorCode.TIMEOUT); } else { this.pauseTimer(); } }; return MessageCallback; })(); RongIMLib.MessageCallback = MessageCallback; var CallbackMapping = (function () { function CallbackMapping() { this.publicServiceList = []; } CallbackMapping.getInstance = function () { return new CallbackMapping(); }; CallbackMapping.prototype.pottingProfile = function (item) { var temp; this.profile = new RongIMLib.PublicServiceProfile(); temp = JSON.parse(item.extra); this.profile.isGlobal = temp.isGlobal; this.profile.introduction = temp.introduction; this.profile.menu = temp.menu; this.profile.hasFollowed = temp.follow; this.profile.publicServiceId = item.mpid; this.profile.name = item.name; this.profile.portraitUri = item.portraitUrl; this.profile.conversationType = item.type == "mc" ? RongIMLib.ConversationType.APP_PUBLIC_SERVICE : RongIMLib.ConversationType.PUBLIC_SERVICE; this.publicServiceList.push(this.profile); }; CallbackMapping.prototype.mapping = function (entity, tag) { switch (tag) { case "GetUserInfoOutput": var userInfo = new RongIMLib.UserInfo(entity.userId, entity.userName, entity.userPortrait); return userInfo; case "GetQNupTokenOutput": return { deadline: RongIMLib.MessageUtil.int64ToTimestamp(entity.deadline), token: entity.token }; case "GetQNdownloadUrlOutput": return { downloadUrl: entity.downloadUrl }; case "CreateDiscussionOutput": return entity.id; case "ChannelInfoOutput": var disInfo = new RongIMLib.Discussion(); disInfo.creatorId = entity.adminUserId; disInfo.id = entity.channelId; disInfo.memberIdList = entity.firstTenUserIds; disInfo.name = entity.channelName; disInfo.isOpen = entity.openStatus; return disInfo; case "GroupHashOutput": return entity.result; case "QueryBlackListOutput": return entity.userIds; case "SearchMpOutput": case "PullMpOutput": if (entity.info) { var self = this; Array.forEach(entity.info, function (item) { setTimeout(function () { self.pottingProfile(item); }, 100); }); } return this.publicServiceList; default: return entity; } }; return CallbackMapping; })(); RongIMLib.CallbackMapping = CallbackMapping; var PublishCallback = (function (_super) { __extends(PublishCallback, _super); function PublishCallback(_cb, _timeout) { _super.call(this, _timeout); this._cb = _cb; this._timeout = _timeout; } PublishCallback.prototype.process = function (_status, messageUId, timestamp, _msg, messageId) { this.readTimeOut(); if (_status == 0) { if (_msg) { _msg.setSentStatus = _status; } var isPullFinished = RongIMLib.RongIMClient._memoryStore.isPullFinished; if (isPullFinished) { var userId = RongIMLib.Bridge._client.userId; var stroageProvider = RongIMLib.RongIMClient._storageProvider; stroageProvider.setItem('last_sentTime_' + userId, timestamp); RongIMLib.SyncTimeUtil.set({ messageDirection: RongIMLib.MessageDirection.SEND, sentTime: timestamp }); } this._cb({ messageUId: messageUId, timestamp: timestamp, messageId: messageId }); } else { this._timeout(_status, { messageUId: messageUId, sentTime: timestamp }); } }; PublishCallback.prototype.readTimeOut = function (x) { MessageCallback.prototype.readTimeOut.call(this, x); }; return PublishCallback; })(MessageCallback); RongIMLib.PublishCallback = PublishCallback; var QueryCallback = (function (_super) { __extends(QueryCallback, _super); function QueryCallback(_cb, _timeout) { _super.call(this, _timeout); this._cb = _cb; this._timeout = _timeout; } QueryCallback.prototype.process = function (status, data, serverTime, pbtype) { this.readTimeOut(); if (pbtype && data && status == 0) { try { data = CallbackMapping.getInstance().mapping(RongIMLib.RongIMClient.Protobuf[pbtype].decode(data), pbtype); } catch (e) { this._timeout(RongIMLib.ErrorCode.UNKNOWN); return; } if ("GetUserInfoOutput" == pbtype) { //pb类型为GetUserInfoOutput的话就把data放入userinfo缓存队列 RongIMLib.Client.userInfoMapping[data.userId] = data; } this._cb(data); } else { status > 0 ? this._timeout(status) : this._cb(status); } }; QueryCallback.prototype.readTimeOut = function (x) { MessageCallback.prototype.readTimeOut.call(this, x); }; return QueryCallback; })(MessageCallback); RongIMLib.QueryCallback = QueryCallback; var ConnectAck = (function (_super) { __extends(ConnectAck, _super); function ConnectAck(_cb, _timeout, client) { _super.call(this, _timeout); this._client = client; this._cb = _cb; this._timeout = _timeout; } ConnectAck.prototype.process = function (status, userId, timestamp) { this.readTimeOut(); if (status == 0) { this._client.userId = userId; var self = this; if (!RongIMLib.RongIMClient._memoryStore.depend.isPolling && RongIMLib.RongIMClient._memoryStore.isFirstPingMsg) { RongIMLib.Bridge._client.checkSocket({ onSuccess: function () { if (!RongIMLib.RongIMClient.isNotPullMsg) { self._client.syncTime(undefined, undefined, undefined, true); } }, onError: function () { RongIMLib.RongIMClient._memoryStore.isFirstPingMsg = false; RongIMLib.RongIMClient.getInstance().disconnect(); RongIMLib.RongIMClient.connect(RongIMLib.RongIMClient._memoryStore.token, RongIMLib.RongIMClient._memoryStore.callback); } }); } else { if (!RongIMLib.RongIMClient.isNotPullMsg) { self._client.syncTime(undefined, undefined, undefined, true); } } RongIMLib.Bridge._client.channel.socket.fire("StatusChanged", 0); if (this._client.reconnectObj.onSuccess) { this._client.reconnectObj.onSuccess(userId); delete this._client.reconnectObj.onSuccess; } else { var me = this; me._cb(userId); // setTimeout(function() { me._cb(userId); }, 500); var depend = RongIMLib.RongIMClient._memoryStore.depend; var maxConversationCount = depend.maxConversationCount; var isNotifyConversationList = depend.isNotifyConversationList; isNotifyConversationList && RongIMLib.RongIMClient._dataAccessProvider.getRemoteConversationList({ onSuccess: function (conversationList) { var Conversation = RongIMLib.RongIMClient._dataAccessProvider.Conversation; Conversation._notify(conversationList); }, onError: function (code) { console.log('内部获取列表失败: %d', code); } }, null, maxConversationCount); } RongIMLib.RongIMClient._memoryStore.connectAckTime = timestamp; if (!(new Date().getTime() - timestamp)) { RongIMLib.RongIMClient._memoryStore.deltaTime = 0; } else { RongIMLib.RongIMClient._memoryStore.deltaTime = new Date().getTime() - timestamp; } } else if (status == 6) { RongIMLib.RongIMClient.getInstance().disconnect(); //重定向 连错 CMP var me = this; var _client = me._client; var appId = _client.appId, token = _client.token; new RongIMLib.Navigation().requestNavi(token, appId, function () { _client.clearHeartbeat(); var newClient = new RongIMLib.Client(token, appId); RongIMLib.Bridge._client = newClient; newClient.__init(function () { RongIMLib.Transportations._TransportType == "websocket" && newClient.keepLive(); }); }, me._timeout, false); } else { RongIMLib.Bridge._client.channel.socket.socket._status = status; if (this._client.reconnectObj.onError) { this._client.reconnectObj.onError(status); delete this._client.reconnectObj.onError; } else { this._timeout(status); } } }; ConnectAck.prototype.readTimeOut = function (x) { MessageCallback.prototype.readTimeOut.call(this, x); }; return ConnectAck; })(MessageCallback); RongIMLib.ConnectAck = ConnectAck; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var Navigation = (function () { function Navigation() { } Navigation.clear = function () { var storage = RongIMLib.RongIMClient._storageProvider; storage.removeItem('rc_uid'); storage.removeItem('serverIndex'); storage.removeItem('rongSDK'); }; Navigation.prototype.getNaviSuccess = function (result) { var storage = RongIMLib.RongIMClient._storageProvider; storage.setItem('fullnavi', JSON.stringify(result)); var server = result.server; if (server) { server += ','; } var backupServer = result.backupServer || ''; var tpl = '{server}{backupServer}'; var servers = RongIMLib.RongUtil.tplEngine(tpl, { server: server, backupServer: backupServer }); servers = servers.split(','); storage.setItem('servers', JSON.stringify(servers)); var token = RongIMLib.RongIMClient._memoryStore.token; var uid = RongIMLib.InnerUtil.getUId(token); storage.setItem('rc_uid', uid); var userId = result.userId; storage.setItem('current_user', userId); if (result.voipCallInfo) { var callInfo = JSON.parse(result.voipCallInfo); RongIMLib.RongIMClient._memoryStore.voipStategy = callInfo.strategy; storage.setItem("voipStrategy", callInfo.strategy); } //替换本地存储的导航信息 var openMp = result.openMp; storage.setItem('openMp' + uid, openMp); RongIMLib.RongIMClient._memoryStore.depend.openMp = openMp; }; ; Navigation.prototype.connect = function (appId, token, callback) { var oldAppId = RongIMLib.RongIMClient._storageProvider.getItem("appId"); //如果appid和本地存储的不一样,清空所有本地存储数据 if (oldAppId && oldAppId != appId) { RongIMLib.RongIMClient._storageProvider.clearItem(); RongIMLib.RongIMClient._storageProvider.setItem("appId", appId); } if (!oldAppId) { RongIMLib.RongIMClient._storageProvider.setItem("appId", appId); } var client = new RongIMLib.Client(token, appId); this.requestNavi(token, appId, function () { client.connect(callback); }, callback.onError, true); return client; }; Navigation.prototype.requestNavi = function (token, appId, _onsuccess, _onerror, unignore) { if (unignore) { //根据token生成MD5截取8-16下标的数据与本地存储的导航信息进行比对 //如果信息和上次的通道类型都一样,不执行navi请求,用本地存储的导航信息连接服务器 var uId = md5(token).slice(8, 16); var storage = RongIMLib.RongIMClient._storageProvider; var transportType = storage.getItem("rongSDK"); var isSameType = (RongIMLib.Transportations._TransportType == transportType); var _old = storage.getItem('rc_uid'); var isSameUser = (_old == uId); var servers = storage.getItem('servers'); var hasServers = (typeof servers == 'string'); if (isSameUser && isSameType && hasServers && RongIMLib.RongUtil.hasValidWsUrl(servers)) { RongIMLib.RongIMClient._memoryStore.voipStategy = storage.getItem("voipStrategy"); var openMp = storage.getItem('openMp' + uId); RongIMLib.RongIMClient._memoryStore.depend.openMp = openMp; _onsuccess(); return; } } Navigation.clear(); RongIMLib.RongIMClient.invalidWsUrls = []; var context = this; var StatusEvent = RongIMLib.Channel._ConnectionStatusListener; var depend = RongIMLib.RongIMClient._memoryStore.depend; var navigaters = depend.navigaters; var naviTimeout = depend.naviTimeout; var maxNaviRetry = depend.maxNaviRetry; var isNaviJSONP = depend.isNaviJSONP; var isSupportRequestHeaders = RongIMLib.RongUtil.isSupportRequestHeaders(); var isRequestJSONP = !isSupportRequestHeaders || isNaviJSONP; var requestFunc = isRequestJSONP ? context.requestJSONP : context.request; var timer = new RongIMLib.Timer({ timeout: naviTimeout }); var internalRetry = 1; var isRange = function () { return internalRetry >= maxNaviRetry; }; var indexTools = new RongIMLib.IndexTools({ items: navigaters, onwheel: function () { internalRetry += 1; } }); var consume = function () { if (isRange()) { _onerror(RongIMLib.ConnectionStatus.RESPONSE_NAVI_ERROR); return; } var index = indexTools.get(); var navi = navigaters[index]; indexTools.add(); var success = function (result) { timer.pause(); StatusEvent.onChanged(RongIMLib.ConnectionStatus.RESPONSE_NAVI); var code = result.code; if (RongIMLib.RongUtil.isEqual(code, 200)) { context.getNaviSuccess(result); _onsuccess(); } if (RongIMLib.RongUtil.isEqual(code, 401)) { _onerror(RongIMLib.ConnectionState.TOKEN_INCORRECT); } if (RongIMLib.RongUtil.isEqual(code, 403)) { StatusEvent.onChanged(RongIMLib.ConnectionStatus.APPKEY_IS_FAKE); } }; var error = function (status) { if (RongIMLib.RongUtil.isEqual(status, 0)) { return; } timer.pause(); StatusEvent.onChanged(RongIMLib.ConnectionStatus.RESPONSE_NAVI_ERROR); consume(); }; StatusEvent.onChanged(RongIMLib.ConnectionStatus.REQUEST_NAVI); var xhr = requestFunc.call(context, navi, appId, token, success, error); timer.resume(function () { StatusEvent.onChanged(RongIMLib.ConnectionStatus.RESPONSE_NAVI_TIMEOUT); xhr.abort(); consume(); }); }; consume(); }; Navigation.prototype.getPath = function (navi, appId, token, callbackName) { var depend = RongIMLib.RongIMClient._memoryStore.depend; var path = (depend.isPolling ? 'cometnavi' : 'navi'); token = encodeURIComponent(token); var sdkver = RongIMLib.RongIMClient.sdkver; var random = RongIMLib.RongUtil.getTimestamp(); var tpl = '{navi}/{path}.js?appId={appId}&token={token}&callBack={callback}&v={sdkver}&r={random}'; var url = RongIMLib.RongUtil.tplEngine(tpl, { navi: navi, path: path, appId: appId, token: token, sdkver: sdkver, random: random, callback: callbackName }); return url; }; Navigation.prototype.request = function (navi, appId, token, success, error) { var url = this.getPath(navi, appId, token, 'getServerEndpoint'); return RongIMLib.RongUtil.request({ url: url, success: function (result) { result = result.replace('getServerEndpoint(', '').replace(');', ''); // 兼容私有云无分号 var lastIndex = result.lastIndexOf(')'); var maxIndex = result.length - 1; if (lastIndex == maxIndex) { result = result.substr(0, lastIndex); } success(JSON.parse(result)); }, error: function (status, result) { if (status == 401 || status == 403) { success(JSON.parse(result)); } else { error(status); } } }); }; Navigation.prototype.requestJSONP = function (navi, appId, token, success, error) { var callbackName = 'getServerEndpoint'; window.getServerEndpoint = function (result) { var code = result.code; if (code !== 200) { return error(RongIMLib.ConnectionState.TOKEN_INCORRECT); } success(result); }; var url = this.getPath(navi, appId, token, callbackName); var xss = document.createElement('script'); xss.src = url; document.body.appendChild(xss); xss.onerror = function () { error(RongIMLib.ConnectionState.TOKEN_INCORRECT); }; }; Navigation.Endpoint = new Object; return Navigation; })(); RongIMLib.Navigation = Navigation; })(RongIMLib || (RongIMLib = {})); // TODO: 统一变量、方法等命名规范 var RongIMLib; (function (RongIMLib) { /** * 消息基类 */ var BaseMessage = (function () { function BaseMessage(arg) { this._name = "BaseMessage"; this.lengthSize = 0; if (arg instanceof RongIMLib.Header) { this._header = arg; } else { this._header = new RongIMLib.Header(arg, false, RongIMLib.Qos.AT_MOST_ONCE, false); } } BaseMessage.prototype.read = function (In, length) { this.readMessage(In, length); }; BaseMessage.prototype.write = function (Out) { var binaryHelper = new RongIMLib.BinaryHelper(); var out = binaryHelper.convertStream(Out); this._headerCode = this.getHeaderFlag(); out.write(this._headerCode); this.writeMessage(out); return out; }; BaseMessage.prototype.getHeaderFlag = function () { return this._header.encode(); }; BaseMessage.prototype.getLengthSize = function () { return this.lengthSize; }; BaseMessage.prototype.toBytes = function () { return this.write([]).getBytesArray(); }; BaseMessage.prototype.isRetained = function () { return this._header.retain; }; BaseMessage.prototype.setRetained = function (retain) { this._header.retain = retain; }; BaseMessage.prototype.setQos = function (qos) { this._header.qos = Object.prototype.toString.call(qos) == "[object Object]" ? qos : RongIMLib.Qos[qos]; }; BaseMessage.prototype.setDup = function (dup) { this._header.dup = dup; }; BaseMessage.prototype.isDup = function () { return this._header.dup; }; BaseMessage.prototype.getType = function () { return this._header.type; }; BaseMessage.prototype.getQos = function () { return this._header.qos; }; BaseMessage.prototype.messageLength = function () { return 0; }; BaseMessage.prototype.writeMessage = function (out) { }; BaseMessage.prototype.readMessage = function (In, length) { }; BaseMessage.prototype.init = function (args) { var valName, nana, me = this; for (nana in args) { if (!args.hasOwnProperty(nana)) { continue; } valName = nana.replace(/^\w/, function (x) { var tt = x.charCodeAt(0); return "set" + (tt >= 0x61 ? String.fromCharCode(tt & ~32) : x); }); if (valName in me) { if (nana == "status") { me[valName](disconnectStatus[args[nana]] ? disconnectStatus[args[nana]] : args[nana]); } else { me[valName](args[nana]); } } } }; return BaseMessage; })(); RongIMLib.BaseMessage = BaseMessage; /** *连接消息类型 */ var ConnectMessage = (function (_super) { __extends(ConnectMessage, _super); function ConnectMessage(header) { _super.call(this, arguments.length == 0 || arguments.length == 3 ? RongIMLib.Type.CONNECT : arguments[0]); this._name = "ConnectMessage"; this.CONNECT_HEADER_SIZE = 12; this.protocolId = "RCloud"; this.binaryHelper = new RongIMLib.BinaryHelper(); this.protocolVersion = 3; switch (arguments.length) { case 0: case 1: case 3: if (!arguments[0] || arguments[0].length > 64) { throw new Error("ConnectMessage:Client Id cannot be null and must be at most 64 characters long: " + arguments[0]); } this.clientId = arguments[0]; this.cleanSession = arguments[1]; this.keepAlive = arguments[2]; break; } } ConnectMessage.prototype.messageLength = function () { var payloadSize = this.binaryHelper.toMQttString(this.clientId).length; payloadSize += this.binaryHelper.toMQttString(this.willTopic).length; payloadSize += this.binaryHelper.toMQttString(this.will).length; payloadSize += this.binaryHelper.toMQttString(this.appId).length; payloadSize += this.binaryHelper.toMQttString(this.token).length; return payloadSize + this.CONNECT_HEADER_SIZE; }; ConnectMessage.prototype.readMessage = function (stream) { this.protocolId = stream.readUTF(); this.protocolVersion = stream.readByte(); var cFlags = stream.readByte(); this.hasAppId = (cFlags & 128) > 0; this.hasToken = (cFlags & 64) > 0; this.retainWill = (cFlags & 32) > 0; this.willQos = cFlags >> 3 & 3; this.hasWill = (cFlags & 4) > 0; this.cleanSession = (cFlags & 32) > 0; this.keepAlive = stream.read() * 256 + stream.read(); this.clientId = stream.readUTF(); if (this.hasWill) { this.willTopic = stream.readUTF(); this.will = stream.readUTF(); } if (this.hasAppId) { try { this.appId = stream.readUTF(); } catch (ex) { throw new Error(ex); } } if (this.hasToken) { try { this.token = stream.readUTF(); } catch (ex) { throw new Error(ex); } } return stream; }; ConnectMessage.prototype.writeMessage = function (out) { var stream = this.binaryHelper.convertStream(out); stream.writeUTF(this.protocolId); stream.write(this.protocolVersion); var flags = this.cleanSession ? 2 : 0; flags |= this.hasWill ? 4 : 0; flags |= this.willQos ? this.willQos >> 3 : 0; flags |= this.retainWill ? 32 : 0; flags |= this.hasToken ? 64 : 0; flags |= this.hasAppId ? 128 : 0; stream.write(flags); stream.writeChar(this.keepAlive); stream.writeUTF(this.clientId); if (this.hasWill) { stream.writeUTF(this.willTopic); stream.writeUTF(this.will); } if (this.hasAppId) { stream.writeUTF(this.appId); } if (this.hasToken) { stream.writeUTF(this.token); } return stream; }; return ConnectMessage; })(BaseMessage); RongIMLib.ConnectMessage = ConnectMessage; /** *连接应答类型 */ var ConnAckMessage = (function (_super) { __extends(ConnAckMessage, _super); function ConnAckMessage(header) { _super.call(this, arguments.length == 0 ? RongIMLib.Type.CONNACK : arguments.length == 1 ? arguments[0] instanceof RongIMLib.Header ? arguments[0] : RongIMLib.Type.CONNACK : null); this._name = "ConnAckMessage"; this.MESSAGE_LENGTH = 2; this.binaryHelper = new RongIMLib.BinaryHelper(); var me = this; switch (arguments.length) { case 0: case 1: if (!(arguments[0] instanceof RongIMLib.Header)) { if (arguments[0] in RongIMLib.ConnectionState) { if (arguments[0] == null) { throw new Error("ConnAckMessage:The status of ConnAskMessage can't be null"); } me.setStatus(arguments[0]); } } break; } } ; ConnAckMessage.prototype.messageLength = function () { var length = this.MESSAGE_LENGTH; if (this.userId) { length += this.binaryHelper.toMQttString(this.userId).length; } return length; }; ; ConnAckMessage.prototype.readMessage = function (_in, msglength) { _in.read(); var result = +_in.read(); if (result >= 0 && result <= 12) { this.setStatus(result); } else { throw new Error("Unsupported CONNACK code:" + result); } if (msglength > this.MESSAGE_LENGTH) { this.setUserId(_in.readUTF()); var sessionId = _in.readUTF(); var timestamp = _in.readLong(); this.setTimestamp(timestamp); } }; ; ConnAckMessage.prototype.writeMessage = function (out) { var stream = this.binaryHelper.convertStream(out); stream.write(128); switch (+status) { case 0: case 1: case 2: case 5: case 6: stream.write(+status); break; case 3: case 4: stream.write(3); break; default: throw new Error("Unsupported CONNACK code:" + status); } if (this.userId) { stream.writeUTF(this.userId); } return stream; }; ; ConnAckMessage.prototype.setStatus = function (x) { this.status = x; }; ; ConnAckMessage.prototype.setUserId = function (_userId) { this.userId = _userId; }; ; ConnAckMessage.prototype.getStatus = function () { return this.status; }; ; ConnAckMessage.prototype.getUserId = function () { return this.userId; }; ; ConnAckMessage.prototype.setTimestamp = function (x) { this.timestrap = x; }; ; ConnAckMessage.prototype.getTimestamp = function () { return this.timestrap; }; return ConnAckMessage; })(BaseMessage); RongIMLib.ConnAckMessage = ConnAckMessage; /** *断开消息类型 */ var DisconnectMessage = (function (_super) { __extends(DisconnectMessage, _super); function DisconnectMessage(header) { _super.call(this, header instanceof RongIMLib.Header ? header : RongIMLib.Type.DISCONNECT); this._name = "DisconnectMessage"; this.MESSAGE_LENGTH = 2; this.binaryHelper = new RongIMLib.BinaryHelper(); if (!(header instanceof RongIMLib.Header)) { if (header in RongIMLib.ConnectionStatus) { this.status = header; } } } DisconnectMessage.prototype.messageLength = function () { return this.MESSAGE_LENGTH; }; DisconnectMessage.prototype.readMessage = function (_in) { _in.read(); var result = +_in.read(); if (result >= 0 && result <= 5) { this.setStatus(disconnectStatus[result] ? disconnectStatus[result] : result); } else { throw new Error("Unsupported CONNACK code:" + result); } }; DisconnectMessage.prototype.writeMessage = function (Out) { var out = this.binaryHelper.convertStream(Out); out.write(0); if (+status >= 1 && +status <= 3) { out.write((+status) - 1); } else { throw new Error("Unsupported CONNACK code:" + status); } }; DisconnectMessage.prototype.setStatus = function (x) { this.status = x; }; ; DisconnectMessage.prototype.getStatus = function () { return this.status; }; ; return DisconnectMessage; })(BaseMessage); RongIMLib.DisconnectMessage = DisconnectMessage; /** *请求消息信令 */ var PingReqMessage = (function (_super) { __extends(PingReqMessage, _super); function PingReqMessage(header) { _super.call(this, (header && header instanceof RongIMLib.Header) ? header : RongIMLib.Type.PINGREQ); this._name = "PingReqMessage"; } return PingReqMessage; })(BaseMessage); RongIMLib.PingReqMessage = PingReqMessage; /** *响应消息信令 */ var PingRespMessage = (function (_super) { __extends(PingRespMessage, _super); function PingRespMessage(header) { _super.call(this, (header && header instanceof RongIMLib.Header) ? header : RongIMLib.Type.PINGRESP); this._name = "PingRespMessage"; } return PingRespMessage; })(BaseMessage); RongIMLib.PingRespMessage = PingRespMessage; /** *封装MesssageId */ var RetryableMessage = (function (_super) { __extends(RetryableMessage, _super); function RetryableMessage(argu) { _super.call(this, argu); this._name = "RetryableMessage"; this.binaryHelper = new RongIMLib.BinaryHelper(); } RetryableMessage.prototype.messageLength = function () { return 2; }; RetryableMessage.prototype.writeMessage = function (Out) { var out = this.binaryHelper.convertStream(Out), Id = this.getMessageId(), lsb = Id & 255, msb = (Id & 65280) >> 8; out.write(msb); out.write(lsb); return out; }; RetryableMessage.prototype.readMessage = function (_in, msgLength) { var msgId = _in.read() * 256 + _in.read(); this.setMessageId(parseInt(msgId, 10)); }; RetryableMessage.prototype.setMessageId = function (_messageId) { this.messageId = _messageId; }; RetryableMessage.prototype.getMessageId = function () { return this.messageId; }; return RetryableMessage; })(BaseMessage); RongIMLib.RetryableMessage = RetryableMessage; /** *发送消息应答(双向) *qos为1必须给出应答(所有消息类型一样) */ var PubAckMessage = (function (_super) { __extends(PubAckMessage, _super); function PubAckMessage(header) { _super.call(this, (header instanceof RongIMLib.Header) ? header : RongIMLib.Type.PUBACK); this.msgLen = 2; this.date = 0; this.millisecond = 0; this.timestamp = 0; this.binaryHelper = new RongIMLib.BinaryHelper(); this._name = "PubAckMessage"; if (!(header instanceof RongIMLib.Header)) { _super.prototype.setMessageId.call(this, header); } } PubAckMessage.prototype.messageLength = function () { return this.msgLen; }; PubAckMessage.prototype.writeMessage = function (Out) { var out = this.binaryHelper.convertStream(Out); RetryableMessage.prototype.writeMessage.call(this, out); }; PubAckMessage.prototype.readMessage = function (_in, msgLength) { RetryableMessage.prototype.readMessage.call(this, _in); this.date = _in.readInt(); this.status = _in.read() * 256 + _in.read(); this.millisecond = _in.read() * 256 + _in.read(); this.timestamp = this.date * 1000 + this.millisecond; this.messageUId = _in.readUTF(); }; PubAckMessage.prototype.setStatus = function (x) { this.status = x; }; PubAckMessage.prototype.setTimestamp = function (timestamp) { this.timestamp = timestamp; }; PubAckMessage.prototype.setMessageUId = function (messageUId) { this.messageUId = messageUId; }; PubAckMessage.prototype.getStatus = function () { return this.status; }; PubAckMessage.prototype.getDate = function () { return this.date; }; PubAckMessage.prototype.getTimestamp = function () { return this.timestamp; }; PubAckMessage.prototype.getMessageUId = function () { return this.messageUId; }; return PubAckMessage; })(RetryableMessage); RongIMLib.PubAckMessage = PubAckMessage; /** *发布消息 */ var PublishMessage = (function (_super) { __extends(PublishMessage, _super); function PublishMessage(header, two, three) { _super.call(this, (arguments.length == 1 && header instanceof RongIMLib.Header) ? header : arguments.length == 3 ? RongIMLib.Type.PUBLISH : 0); this._name = "PublishMessage"; this.binaryHelper = new RongIMLib.BinaryHelper(); this.syncMsg = false; if (arguments.length == 3) { this.topic = header; this.targetId = three; this.data = typeof two == "string" ? this.binaryHelper.toMQttString(two) : two; } } PublishMessage.prototype.messageLength = function () { var length = 10; length += this.binaryHelper.toMQttString(this.topic).length; length += this.binaryHelper.toMQttString(this.targetId).length; length += this.data.length; return length; }; PublishMessage.prototype.writeMessage = function (Out) { var out = this.binaryHelper.convertStream(Out); out.writeUTF(this.topic); out.writeUTF(this.targetId); RetryableMessage.prototype.writeMessage.apply(this, arguments); out.write(this.data); }; ; PublishMessage.prototype.readMessage = function (_in, msgLength) { var pos = 6; this.date = _in.readInt(); this.topic = _in.readUTF(); pos += this.binaryHelper.toMQttString(this.topic).length; this.targetId = _in.readUTF(); pos += this.binaryHelper.toMQttString(this.targetId).length; RetryableMessage.prototype.readMessage.apply(this, arguments); this.data = new Array(msgLength - pos); this.data = _in.read(this.data); }; ; PublishMessage.prototype.setTopic = function (x) { this.topic = x; }; PublishMessage.prototype.setData = function (x) { this.data = x; }; PublishMessage.prototype.setTargetId = function (x) { this.targetId = x; }; PublishMessage.prototype.setDate = function (x) { this.date = x; }; PublishMessage.prototype.setSyncMsg = function (x) { this.syncMsg = x; }; //是否是其他端同步过来的消息 PublishMessage.prototype.getSyncMsg = function () { return this.syncMsg; }; PublishMessage.prototype.getTopic = function () { return this.topic; }; PublishMessage.prototype.getData = function () { return this.data; }; PublishMessage.prototype.getTargetId = function () { return this.targetId; }; PublishMessage.prototype.getDate = function () { return this.date; }; return PublishMessage; })(RetryableMessage); RongIMLib.PublishMessage = PublishMessage; /** *请求查询 */ var QueryMessage = (function (_super) { __extends(QueryMessage, _super); function QueryMessage(header, two, three) { _super.call(this, header instanceof RongIMLib.Header ? header : arguments.length == 3 ? RongIMLib.Type.QUERY : null); this.binaryHelper = new RongIMLib.BinaryHelper(); this._name = "QueryMessage"; if (arguments.length == 3) { this.data = typeof two == "string" ? this.binaryHelper.toMQttString(two) : two; this.topic = header; this.targetId = three; } } QueryMessage.prototype.messageLength = function () { var length = 0; length += this.binaryHelper.toMQttString(this.topic).length; length += this.binaryHelper.toMQttString(this.targetId).length; length += 2; length += this.data.length; return length; }; QueryMessage.prototype.writeMessage = function (Out) { var out = this.binaryHelper.convertStream(Out); out.writeUTF(this.topic); out.writeUTF(this.targetId); RetryableMessage.prototype.writeMessage.call(this, out); out.write(this.data); }; QueryMessage.prototype.readMessage = function (_in, msgLength) { var pos = 0; this.topic = _in.readUTF(); this.targetId = _in.readUTF(); pos += this.binaryHelper.toMQttString(this.topic).length; pos += this.binaryHelper.toMQttString(this.targetId).length; this.readMessage.apply(this, arguments); pos += 2; this.data = new Array(msgLength - pos); _in.read(this.data); }; QueryMessage.prototype.setTopic = function (x) { this.topic = x; }; QueryMessage.prototype.setData = function (x) { this.data = x; }; QueryMessage.prototype.setTargetId = function (x) { this.targetId = x; }; QueryMessage.prototype.getTopic = function () { return this.topic; }; QueryMessage.prototype.getData = function () { return this.data; }; QueryMessage.prototype.getTargetId = function () { return this.targetId; }; return QueryMessage; })(RetryableMessage); RongIMLib.QueryMessage = QueryMessage; /** *请求查询确认 */ var QueryConMessage = (function (_super) { __extends(QueryConMessage, _super); function QueryConMessage(messageId) { _super.call(this, (messageId instanceof RongIMLib.Header) ? messageId : RongIMLib.Type.QUERYCON); this._name = "QueryConMessage"; if (!(messageId instanceof RongIMLib.Header)) { _super.prototype.setMessageId.call(this, messageId); } } return QueryConMessage; })(RetryableMessage); RongIMLib.QueryConMessage = QueryConMessage; /** *请求查询应答 */ var QueryAckMessage = (function (_super) { __extends(QueryAckMessage, _super); function QueryAckMessage(header) { _super.call(this, header); this._name = "QueryAckMessage"; this.binaryHelper = new RongIMLib.BinaryHelper(); } QueryAckMessage.prototype.readMessage = function (In, msgLength) { RetryableMessage.prototype.readMessage.call(this, In); this.date = In.readInt(); this.setStatus(In.read() * 256 + In.read()); if (msgLength > 0) { this.data = new Array(msgLength - 8); this.data = In.read(this.data); } }; QueryAckMessage.prototype.getData = function () { return this.data; }; QueryAckMessage.prototype.getStatus = function () { return this.status; }; QueryAckMessage.prototype.getDate = function () { return this.date; }; QueryAckMessage.prototype.setDate = function (x) { this.date = x; }; QueryAckMessage.prototype.setStatus = function (x) { this.status = x; }; QueryAckMessage.prototype.setData = function (x) { this.data = x; }; return QueryAckMessage; })(RetryableMessage); RongIMLib.QueryAckMessage = QueryAckMessage; })(RongIMLib || (RongIMLib = {})); /// var RongIMLib; (function (RongIMLib) { /** * 把消息对象写入流中 * 发送消息时用到 */ var MessageOutputStream = (function () { function MessageOutputStream(_out) { var binaryHelper = new RongIMLib.BinaryHelper(); this.out = binaryHelper.convertStream(_out); } MessageOutputStream.prototype.writeMessage = function (msg) { if (msg instanceof RongIMLib.BaseMessage) { msg.write(this.out); } }; return MessageOutputStream; })(); RongIMLib.MessageOutputStream = MessageOutputStream; /** * 流转换为消息对象 * 服务器返回消息时用到 */ var MessageInputStream = (function () { function MessageInputStream(In, isPolling) { if (!isPolling) { var _in = new RongIMLib.BinaryHelper().convertStream(In); this.flags = _in.readByte(); this._in = _in; } else { this.flags = In["headerCode"]; } this.header = new RongIMLib.Header(this.flags); this.isPolling = isPolling; this.In = In; } MessageInputStream.prototype.readMessage = function () { switch (this.header.getType()) { case 1: this.msg = new RongIMLib.ConnectMessage(this.header); break; case 2: this.msg = new RongIMLib.ConnAckMessage(this.header); break; case 3: this.msg = new RongIMLib.PublishMessage(this.header); this.msg.setSyncMsg(this.header.getSyncMsg()); break; case 4: this.msg = new RongIMLib.PubAckMessage(this.header); break; case 5: this.msg = new RongIMLib.QueryMessage(this.header); break; case 6: this.msg = new RongIMLib.QueryAckMessage(this.header); break; case 7: this.msg = new RongIMLib.QueryConMessage(this.header); break; case 9: case 11: case 13: this.msg = new RongIMLib.PingRespMessage(this.header); break; case 8: case 10: case 12: this.msg = new RongIMLib.PingReqMessage(this.header); break; case 14: this.msg = new RongIMLib.DisconnectMessage(this.header); break; default: throw new Error("No support for deserializing " + this.header.getType() + " messages"); } if (this.isPolling) { this.msg.init(this.In); } else { this.msg.read(this._in, this.In.length - 1); } return this.msg; }; return MessageInputStream; })(); RongIMLib.MessageInputStream = MessageInputStream; var Header = (function () { function Header(_type, _retain, _qos, _dup) { this.retain = false; this.qos = RongIMLib.Qos.AT_LEAST_ONCE; this.dup = false; this.syncMsg = false; if (_type && +_type == _type && arguments.length == 1) { this.retain = (_type & 1) > 0; this.qos = (_type & 6) >> 1; this.dup = (_type & 8) > 0; this.type = (_type >> 4) & 15; this.syncMsg = (_type & 8) == 8; } else { this.type = _type; this.retain = _retain; this.qos = _qos; this.dup = _dup; } } Header.prototype.getSyncMsg = function () { return this.syncMsg; }; Header.prototype.getType = function () { return this.type; }; Header.prototype.encode = function () { var me = this; switch (this.qos) { case RongIMLib.Qos[0]: me.qos = RongIMLib.Qos.AT_MOST_ONCE; break; case RongIMLib.Qos[1]: me.qos = RongIMLib.Qos.AT_LEAST_ONCE; break; case RongIMLib.Qos[2]: me.qos = RongIMLib.Qos.EXACTLY_ONCE; break; case RongIMLib.Qos[3]: me.qos = RongIMLib.Qos.DEFAULT; break; } var _byte = (this.type << 4); _byte |= this.retain ? 1 : 0; _byte |= this.qos << 1; _byte |= this.dup ? 8 : 0; return _byte; }; Header.prototype.toString = function () { return "Header [type=" + this.type + ",retain=" + this.retain + ",qos=" + this.qos + ",dup=" + this.dup + "]"; }; return Header; })(); RongIMLib.Header = Header; /** * 二进制帮助对象 */ var BinaryHelper = (function () { function BinaryHelper() { } BinaryHelper.prototype.writeUTF = function (str, isGetBytes) { var back = [], byteSize = 0; for (var i = 0, len = str.length; i < len; i++) { var code = str.charCodeAt(i); if (code >= 0 && code <= 127) { byteSize += 1; back.push(code); } else if (code >= 128 && code <= 2047) { byteSize += 2; back.push((192 | (31 & (code >> 6)))); back.push((128 | (63 & code))); } else if (code >= 2048 && code <= 65535) { byteSize += 3; back.push((224 | (15 & (code >> 12)))); back.push((128 | (63 & (code >> 6)))); back.push((128 | (63 & code))); } } for (var i = 0, len = back.length; i < len; i++) { if (back[i] > 255) { back[i] &= 255; } } if (isGetBytes) { return back; } if (byteSize <= 255) { return [0, byteSize].concat(back); } else { return [byteSize >> 8, byteSize & 255].concat(back); } }; BinaryHelper.prototype.readUTF = function (arr) { if (Object.prototype.toString.call(arr) == "[object String]") { return arr; } var UTF = "", _arr = arr; for (var i = 0, len = _arr.length; i < len; i++) { if (_arr[i] < 0) { _arr[i] += 256; } ; var one = _arr[i].toString(2), v = one.match(/^1+?(?=0)/); if (v && one.length == 8) { var bytesLength = v[0].length, // store = _arr[i].toString(2).slice(7 - bytesLength); store = ''; for (var st = 0; st < bytesLength; st++) { store += _arr[st + i].toString(2).slice(2); } UTF += String.fromCharCode(parseInt(store, 2)); i += bytesLength - 1; } else { UTF += String.fromCharCode(_arr[i]); } } return UTF; }; /** * [convertStream 将参数x转化为RongIMStream对象] * @param {any} x [参数] */ BinaryHelper.prototype.convertStream = function (x) { if (x instanceof RongIMStream) { return x; } else { return new RongIMStream(x); } }; BinaryHelper.prototype.toMQttString = function (str) { return this.writeUTF(str); }; return BinaryHelper; })(); RongIMLib.BinaryHelper = BinaryHelper; var RongIMStream = (function () { function RongIMStream(arr) { //当前流执行的起始位置 this.position = 0; //当前流写入的多少字节 this.writen = 0; this.poolLen = 0; this.binaryHelper = new BinaryHelper(); this.pool = arr; this.poolLen = arr.length; } RongIMStream.prototype.check = function () { return this.position >= this.pool.length; }; RongIMStream.prototype.readInt = function () { if (this.check()) { return -1; } var end = ""; for (var i = 0; i < 4; i++) { var t = this.pool[this.position++].toString(16); if (t.length == 1) { t = "0" + t; } end += t.toString(16); } return parseInt(end, 16); }; RongIMStream.prototype.readLong = function () { if (this.check()) { return -1; } var end = ""; for (var i = 0; i < 8; i++) { var t = this.pool[this.position++].toString(16); if (t.length == 1) { t = "0" + t; } end += t; } return parseInt(end, 16); }; RongIMStream.prototype.readTimestamp = function () { if (this.check()) { return -1; } var end = ""; for (var i = 0; i < 8; i++) { end += this.pool[this.position++].toString(16); } end = end.substring(2, 8); return parseInt(end, 16); }; RongIMStream.prototype.readUTF = function () { if (this.check()) { return -1; } var big = (this.readByte() << 8) | this.readByte(); return this.binaryHelper.readUTF(this.pool.subarray(this.position, this.position += big)); }; RongIMStream.prototype.readByte = function () { if (this.check()) { return -1; } var val = this.pool[this.position++]; if (val > 255) { val &= 255; } return val; }; RongIMStream.prototype.read = function (bytesArray) { if (bytesArray) { return this.pool.subarray(this.position, this.poolLen); } else { return this.readByte(); } }; RongIMStream.prototype.write = function (_byte) { var b = _byte; if (Object.prototype.toString.call(b).toLowerCase() == "[object array]") { [].push.apply(this.pool, b); } else { if (+b == b) { if (b > 255) { b &= 255; } this.pool.push(b); this.writen++; } } return b; }; RongIMStream.prototype.writeChar = function (v) { if (+v != v) { throw new Error("writeChar:arguments type is error"); } this.write(v >> 8 & 255); this.write(v & 255); this.writen += 2; }; RongIMStream.prototype.writeUTF = function (str) { var val = this.binaryHelper.writeUTF(str); [].push.apply(this.pool, val); this.writen += val.length; }; RongIMStream.prototype.toComplements = function () { var _tPool = this.pool; for (var i = 0; i < this.poolLen; i++) { if (_tPool[i] > 128) { _tPool[i] -= 256; } } return _tPool; }; RongIMStream.prototype.getBytesArray = function (isCom) { if (isCom) { return this.toComplements(); } return this.pool; }; return RongIMStream; })(); RongIMLib.RongIMStream = RongIMStream; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var SocketTransportation = (function () { /** * [constructor] * @param {string} url [连接地址:包含token、version] */ function SocketTransportation(_socket) { //连接状态 true:已连接 false:未连接 this.connected = false; //是否关闭: true:已关闭 false:未关闭 this.isClose = false; //存放消息队列的临时变量 this.queue = []; this.empty = new Function; this._socket = _socket; return this; } /** * [createTransport 创建WebScoket对象] */ SocketTransportation.prototype.createTransport = function (url, method) { if (!url) { throw new Error("URL can't be empty"); } ; this.url = url; var depend = RongIMLib.RongIMClient._memoryStore.depend; var wsScheme = depend.wsScheme; var tpl = '{wsScheme}{url}'; url = RongIMLib.RongUtil.tplEngine(tpl, { wsScheme: wsScheme, url: url }); this.socket = new WebSocket(url); this.socket.binaryType = "arraybuffer"; this.addEvent(); return this.socket; }; /** * [send 传送消息流] * @param {ArrayBuffer} data [二进制消息流] */ SocketTransportation.prototype.send = function (data) { if (!this.connected && !this.isClose) { //当通道不可用时,加入消息队列 this.queue.push(data); return; } if (this.isClose) { this._socket.fire("StatusChanged", RongIMLib.ConnectionStatus.CONNECTION_CLOSED); return; } var stream = new RongIMLib.RongIMStream([]), msg = new RongIMLib.MessageOutputStream(stream); msg.writeMessage(data); var val = stream.getBytesArray(true); var binary = new Int8Array(val); this.socket.send(binary.buffer); return this; }; /** * [onData 通道返回数据时调用的方法,用来想上层传递服务器返回的二进制消息流] * @param {ArrayBuffer} data [二进制消息流] */ SocketTransportation.prototype.onData = function (data) { if (RongIMLib.MessageUtil.isArray(data)) { this._socket.onMessage(new RongIMLib.MessageInputStream(data).readMessage()); } else { this._socket.onMessage(new RongIMLib.MessageInputStream(RongIMLib.MessageUtil.ArrayFormInput(data)).readMessage()); } return ""; }; /** * [onClose 通道关闭时触发的方法] */ SocketTransportation.prototype.onClose = function (ev) { var me = this; me.isClose = true; me.socket = this.empty; RongIMLib.Bridge._client.clearHeartbeat(); if (ev.code == 1006 && !this._status) { var currentTime = new Date().getTime(); if (currentTime - me.connectedTime <= SocketTransportation.MinConnectTime) { var host = RongIMLib.RongUtil.getUrlHost(me.url); RongIMLib.RongIMClient.invalidWsUrls.push(host); } me._socket.fire("StatusChanged", RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE); } else { me._status = 0; } }; /** * [onError 通道报错时触发的方法] * @param {any} error [抛出异常] */ SocketTransportation.prototype.onError = function (error) { this._socket.fire("StatusChanged", RongIMLib.ConnectionStatus.WEBSOCKET_ERROR); throw new Error(error); }; /** * [addEvent 为通道绑定事件] */ SocketTransportation.prototype.addEvent = function () { var self = this; self.socket.onopen = function () { self.connected = true; self.isClose = false; //通道可以用后,调用发送队列方法,把所有等得发送的消息发出 self.doQueue(); self._socket.fire("connect"); self.connectedTime = new Date().getTime(); }; self.socket.onmessage = function (ev) { //判断数据是不是字符串,如果是字符串那么就是flash传过来的。 if (typeof ev.data == "string") { self.onData(ev.data.split(",")); } else { self.onData(ev.data); } }; self.socket.onerror = function (ev) { self.onError(ev); }; self.socket.onclose = function (ev) { self.onClose(ev); }; }; /** * [doQueue 消息队列,把队列中消息发出] */ SocketTransportation.prototype.doQueue = function () { var self = this; for (var i = 0, len = self.queue.length; i < len; i++) { self.send(self.queue[i]); } }; /** * [disconnect 断开连接] */ SocketTransportation.prototype.disconnect = function (status) { var me = this; if (me.socket.readyState) { me.isClose = true; if (status) { me._status = status; } me.socket.close(); } }; /** * [reconnect 重新连接] */ SocketTransportation.prototype.reconnect = function () { this.disconnect(); this.createTransport(this.url); }; SocketTransportation.prototype.close = function () { this.socket.close(); }; // 最短链接时长(若 5000ms 内, ws 自动断开, 此 ws 地址置为不可用) SocketTransportation.MinConnectTime = 5000; return SocketTransportation; })(); RongIMLib.SocketTransportation = SocketTransportation; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var PollingTransportation = (function () { function PollingTransportation(socket) { this.empty = new Function; this.connected = false; this.pid = +new Date + Math.random() + ""; this.queue = []; this.socket = socket; return this; } PollingTransportation.prototype.createTransport = function (url, method) { if (!url) { throw new Error("Url is empty,Please check it!"); } ; this.url = url; var sid = RongIMLib.RongIMClient._storageProvider.getItem("sId" + RongIMLib.Navigation.Endpoint.userId), me = this; if (sid) { setTimeout(function () { me.onSuccess("{\"status\":0,\"userId\":\"" + RongIMLib.Navigation.Endpoint.userId + "\",\"headerCode\":32,\"messageId\":0,\"sessionid\":\"" + sid + "\"}"); me.connected = true; }, 500); return this; } this.getRequest(url, true); return this; }; PollingTransportation.prototype.requestFactory = function (url, method, multipart) { var reqest = this.XmlHttpRequest(); if (multipart) { reqest.multipart = true; } // reqest.timeout = 60000; reqest.open(method || "GET", RongIMLib.RongIMClient._memoryStore.depend.protocol + url); if (method == "POST" && "setRequestHeader" in reqest) { reqest.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=utf-8"); } return reqest; }; PollingTransportation.prototype.getRequest = function (url, isconnect) { var me = this; me.xhr = this.requestFactory(url + "&pid=" + encodeURIComponent(me.pid), "GET"); var timer = new RongIMLib.Timer({ timeout: 45000 }); if ("onload" in me.xhr) { me.xhr.onload = function () { timer.pause(); me.xhr.onload = me.empty; if (this.responseText == "lost params") { me.onError(); } else { me.onSuccess(this.responseText, isconnect); } }; me.xhr.onerror = function () { timer.pause(); me.disconnect(); }; } else { me.xhr.onreadystatechange = function () { timer.pause(); if (me.xhr.readyState == 4) { me.xhr.onreadystatechange = me.empty; if (/^(200|202)$/.test(me.xhr.status)) { me.onSuccess(me.xhr.responseText, isconnect); } else if (/^(400|403)$/.test(me.xhr.status)) { me.onError(); } else { me.disconnect(); } } }; } timer.resume(function () { me.onError(); }); me.xhr.send(); }; /** * [send 发送消息,Method:POST] * queue 为消息队列,待通道可用发送所有等待消息 * @param {string} data [需要传入comet格式数据,此处只负责通讯通道,数据转换在外层处理] */ PollingTransportation.prototype.send = function (data) { var me = this; var _send = me.sendxhr = this.requestFactory(RongIMLib.Navigation.Endpoint.host + "/websocket" + data.url + "&pid=" + encodeURIComponent(me.pid), "POST"); if ("onload" in _send) { _send.onload = function () { _send.onload = me.empty; me.onData(_send.responseText); }; _send.onerror = function () { _send.onerror = me.empty; }; } else { _send.onreadystatechange = function () { if (_send.readyState == 4) { this.onreadystatechange = this.empty; if (/^(202|200)$/.test(_send.status)) { me.onData(_send.responseText); } } }; } _send.send(JSON.stringify(data.data)); }; PollingTransportation.prototype.onData = function (data, header) { if (!data || data == "lost params") { return; } var self = this, val = JSON.parse(data); if (val.userId) { RongIMLib.Navigation.Endpoint.userId = val.userId; } if (header) { RongIMLib.RongIMClient._storageProvider.setItem("sId" + RongIMLib.Navigation.Endpoint.userId, header); } if (!RongIMLib.MessageUtil.isArray(val)) { val = [val]; } Array.forEach(val, function (m) { self.socket.fire("message", new RongIMLib.MessageInputStream(m, true).readMessage()); }); return ""; }; PollingTransportation.prototype.XmlHttpRequest = function () { var hasCORS = typeof XMLHttpRequest !== "undefined" && "withCredentials" in new XMLHttpRequest(), self = this; if ("undefined" != typeof XMLHttpRequest && hasCORS) { return new XMLHttpRequest(); } else if ("undefined" != typeof XDomainRequest) { return new XDomainRequest(); } else { return new ActiveXObject("Microsoft.XMLHTTP"); } }; PollingTransportation.prototype.onClose = function () { if (this.xhr) { if (this.xhr.onload) { this.xhr.onreadystatechange = this.xhr.onload = this.empty; } else { this.xhr.onreadystatechange = this.empty; } this.xhr.abort(); this.xhr = null; } if (this.sendxhr) { if (this.sendxhr.onload) { this.sendxhr.onreadystatechange = this.sendxhr.onload = this.empty; } else { this.sendxhr.onreadystatechange = this.empty; } this.sendxhr.abort(); this.sendxhr = null; } }; PollingTransportation.prototype.disconnect = function () { RongIMLib.RongIMClient._storageProvider.removeItem("sId" + RongIMLib.Navigation.Endpoint.userId); RongIMLib.RongIMClient._storageProvider.removeItem(RongIMLib.Navigation.Endpoint.userId + "msgId"); this.onClose(); }; PollingTransportation.prototype.reconnect = function () { this.disconnect(); this.createTransport(this.url); }; PollingTransportation.prototype.onSuccess = function (responseText, isconnect) { var txt = responseText.match(/"sessionid":"\S+?(?=")/); this.onData(responseText, txt ? txt[0].slice(13) : 0); if (/"headerCode":-32,/.test(responseText)) { RongIMLib.RongIMClient._storageProvider.removeItem("sId" + RongIMLib.Navigation.Endpoint.userId); RongIMLib.RongIMClient._storageProvider.removeItem(RongIMLib.Navigation.Endpoint.userId + "msgId"); return; } this.getRequest(RongIMLib.Navigation.Endpoint.host + "/pullmsg.js?sessionid=" + RongIMLib.RongIMClient._storageProvider.getItem("sId" + RongIMLib.Navigation.Endpoint.userId) + "×trap=" + encodeURIComponent(new Date().getTime() + Math.random() + "")); this.connected = true; isconnect && this.socket.fire("connect"); }; PollingTransportation.prototype.onError = function () { RongIMLib.RongIMClient._storageProvider.removeItem("sId" + RongIMLib.Navigation.Endpoint.userId); RongIMLib.RongIMClient._storageProvider.removeItem(RongIMLib.Navigation.Endpoint.userId + "msgId"); this.onClose(); if (this.connected) { this.connected = false; var code = RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE; this.socket.fire("disconnect", code); } }; PollingTransportation.prototype.close = function () { this.xhr.abort(); this.sendxhr = null; }; return PollingTransportation; })(); RongIMLib.PollingTransportation = PollingTransportation; })(RongIMLib || (RongIMLib = {})); //objectname映射 var typeMapping = { "RC:TxtMsg": "TextMessage", "RC:ImgMsg": "ImageMessage", "RC:VcMsg": "VoiceMessage", "RC:ImgTextMsg": "RichContentMessage", "RC:FileMsg": "FileMessage", "RC:HQVCMsg": "HQVoiceMessage", "RC:LBSMsg": "LocationMessage", "RC:InfoNtf": "InformationNotificationMessage", "RC:ContactNtf": "ContactNotificationMessage", "RC:ProfileNtf": "ProfileNotificationMessage", "RC:CmdNtf": "CommandNotificationMessage", "RC:DizNtf": "DiscussionNotificationMessage", "RC:CmdMsg": "CommandMessage", "RC:TypSts": "TypingStatusMessage", "RC:CsChaR": "ChangeModeResponseMessage", "RC:CsHsR": "HandShakeResponseMessage", "RC:CsEnd": "TerminateMessage", "RC:CsSp": "SuspendMessage", "RC:CsUpdate": "CustomerStatusUpdateMessage", "RC:ReadNtf": "ReadReceiptMessage", "RC:VCAccept": "AcceptMessage", "RC:VCRinging": "RingingMessage", "RC:VCSummary": "SummaryMessage", "RC:VCHangup": "HungupMessage", "RC:VCInvite": "InviteMessage", "RC:VCModifyMedia": "MediaModifyMessage", "RC:VCModifyMem": "MemberModifyMessage", "RC:CsContact": "CustomerContact", "RC:PSImgTxtMsg": "PublicServiceRichContentMessage", "RC:PSMultiImgTxtMsg": "PublicServiceMultiRichContentMessage", "RC:GrpNtf": "GroupNotificationMessage", "RC:PSCmd": "PublicServiceCommandMessage", "RC:RcCmd": "RecallCommandMessage", "RC:SRSMsg": "SyncReadStatusMessage", "RC:RRReqMsg": "ReadReceiptRequestMessage", "RC:RRRspMsg": "ReadReceiptResponseMessage", "RCJrmf:RpMsg": "JrmfRedPacketMessage", "RCJrmf:RpOpendMsg": "JrmfRedPacketOpenedMessage", "RC:CombineMsg": "RCCombineMessage", "RC:chrmKVNotiMsg": "ChrmKVNotificationMessage" }, //自定义消息类型 registerMessageTypeMapping = {}, HistoryMsgType = { 4: "qryCMsg", 2: "qryDMsg", 3: "qryGMsg", 1: "qryPMsg", 6: "qrySMsg", 7: "qryPMsg", 8: "qryPMsg", 5: "qryCMsg" }, disconnectStatus = { 1: 6 }; var RongIMLib; (function (RongIMLib) { /** * 通道标识类 */ var Transportations = (function () { function Transportations() { } Transportations._TransportType = RongIMLib.Socket.WEBSOCKET; return Transportations; })(); RongIMLib.Transportations = Transportations; var SyncTimeUtil = (function () { function SyncTimeUtil() { } SyncTimeUtil.$getKey = function (message) { var client = RongIMLib.Bridge._client; var userId = client.userId; var direction = (message.messageDirection == 1 ? 'send' : 'receive'); var appkey = RongIMLib.RongIMClient._memoryStore.appKey; var tpl = '{appkey}_{userId}_{direction}box'; return RongIMLib.RongUtil.tplEngine(tpl, { appkey: appkey, userId: userId, direction: direction }); }; SyncTimeUtil.set = function (message) { var key = SyncTimeUtil.$getKey(message); var sentTime = message.sentTime; var storage = RongIMLib.RongIMClient._storageProvider; storage.setItem(key, sentTime); }; SyncTimeUtil.get = function () { var sent = SyncTimeUtil.$getKey({ messageDirection: RongIMLib.MessageDirection.SEND }); var received = SyncTimeUtil.$getKey({ messageDirection: RongIMLib.MessageDirection.RECEIVE }); var storage = RongIMLib.RongIMClient._storageProvider; return { sent: Number(storage.getItem(sent) || 0), received: Number(storage.getItem(received) || 0) }; }; return SyncTimeUtil; })(); RongIMLib.SyncTimeUtil = SyncTimeUtil; var MessageUtil = (function () { function MessageUtil() { } /** *4680000 为localstorage最小容量5200000字节的90%,超过90%将删除之前过早的存储 */ MessageUtil.checkStorageSize = function () { return JSON.stringify(localStorage).length < 4680000; }; MessageUtil.getFirstKey = function (obj) { var str = ""; for (var key in obj) { str = key; break; } return str; }; MessageUtil.isEmpty = function (obj) { var empty = true; for (var key in obj) { empty = false; break; } return empty; }; MessageUtil.ArrayForm = function (typearray) { if (Object.prototype.toString.call(typearray) == "[object ArrayBuffer]") { var arr = new Int8Array(typearray); return [].slice.call(arr); } return typearray; }; MessageUtil.ArrayFormInput = function (typearray) { if (Object.prototype.toString.call(typearray) == "[object ArrayBuffer]") { var arr = new Uint8Array(typearray); return arr; } return typearray; }; MessageUtil.indexOf = function (arr, item, from) { for (var l = arr.length, i = (from < 0) ? Math.max(0, +from) : from || 0; i < l; i++) { if (arr[i] == item) { return i; } } return -1; }; MessageUtil.isArray = function (obj) { return Object.prototype.toString.call(obj) == "[object Array]"; }; //遍历,只能遍历数组 MessageUtil.forEach = function (arr, func) { if ([].forEach) { return function (arr, func) { [].forEach.call(arr, func); }; } else { return function (arr, func) { for (var i = 0; i < arr.length; i++) { func.call(arr, arr[i], i, arr); } }; } }; MessageUtil.remove = function (array, func) { for (var i = 0, len = array.length; i < len; i++) { if (func(array[i])) { return array.splice(i, 1)[0]; } } return null; }; MessageUtil.int64ToTimestamp = function (obj, isDate) { if (obj.low === undefined) { return obj; } var low = obj.low; if (low < 0) { low += 0xffffffff + 1; } low = low.toString(16); var timestamp = parseInt(obj.high.toString(16) + "00000000".replace(new RegExp("0{" + low.length + "}$"), low), 16); if (isDate) { return new Date(timestamp); } return timestamp; }; //消息转换方法 MessageUtil.messageParser = function (entity, onReceived, offlineMsg) { var message = new RongIMLib.Message(), content = entity.content, de, objectName = entity.classname, val, isUseDef = false; try { if (RongIMLib.RongIMClient._memoryStore.depend.isPolling) { val = new RongIMLib.BinaryHelper().readUTF(content.offset ? MessageUtil.ArrayForm(content.buffer).slice(content.offset, content.limit) : content); de = JSON.parse(val); } else { val = new RongIMLib.BinaryHelper().readUTF(content.offset ? MessageUtil.ArrayFormInput(content.buffer).subarray(content.offset, content.limit) : content); de = JSON.parse(val); } } catch (ex) { de = val; isUseDef = true; } var IMLib = RongIMLib; //映射为具体消息对象 if (objectName in typeMapping) { var typeName = typeMapping[objectName]; message.content = new IMLib[typeName](de); message.messageType = typeMapping[objectName]; } else if (objectName in registerMessageTypeMapping) { var typeName = registerMessageTypeMapping[objectName]; var regMsg = new IMLib.RongIMClient.RegisterMessage[typeName](de); if (isUseDef) { message.content = regMsg.decode(de); } else { message.content = regMsg; } message.messageType = registerMessageTypeMapping[objectName]; } else { message.content = new RongIMLib.UnknownMessage({ content: de, objectName: objectName }); message.messageType = "UnknownMessage"; } //根据实体对象设置message对象] var dateTime = MessageUtil.int64ToTimestamp(entity.dataTime); if (dateTime > 0) { message.sentTime = dateTime; } else { message.sentTime = +new Date; } message.senderUserId = entity.fromUserId; message.conversationType = entity.type; if (entity.fromUserId == RongIMLib.Bridge._client.userId) { message.targetId = entity.groupId; } else { message.targetId = (/^[234]$/.test(entity.type || entity.getType()) ? entity.groupId : message.senderUserId); } var selfUserId = RongIMLib.Bridge._client.userId; // 解决多端在线收自己发的消息时, messageDirection 为 2(接收), 导致未读数增加 var isSelfSend = entity.direction == 1 || message.senderUserId === selfUserId; if (isSelfSend) { message.messageDirection = RongIMLib.MessageDirection.SEND; message.senderUserId = RongIMLib.Bridge._client.userId; } else { message.messageDirection = RongIMLib.MessageDirection.RECEIVE; } // 自己给自己发的消息, messageDirection 为 2(接收) var isSelfToSelf = message.senderUserId === selfUserId && message.targetId === selfUserId; if (isSelfToSelf) { message.messageDirection = RongIMLib.MessageDirection.RECEIVE; } message.messageUId = entity.msgId; message.receivedTime = new Date().getTime(); message.messageId = (message.conversationType + "_" + ~~(Math.random() * 0xffffff)); message.objectName = objectName; message.receivedStatus = RongIMLib.ReceivedStatus.READ; if ((entity.status & 2) == 2) { message.receivedStatus = RongIMLib.ReceivedStatus.RETRIEVED; } message.offLineMessage = offlineMsg ? true : false; if (!offlineMsg) { if (RongIMLib.RongIMClient._memoryStore.connectAckTime > message.sentTime) { message.offLineMessage = true; } } return message; }; MessageUtil.detectCMP = function (options) { options.error = options.fail; return RongIMLib.RongUtil.request(options); }; //适配SSL // static schemeArrs: Array = [["http", "ws"], ["https", "wss"]]; MessageUtil.sign = { converNum: 1, msgNum: 1, isMsgStart: true, isConvStart: true }; return MessageUtil; })(); RongIMLib.MessageUtil = MessageUtil; /** * 工具类 */ var MessageIdHandler = (function () { function MessageIdHandler() { } MessageIdHandler.init = function () { this.messageId = +(RongIMLib.RongIMClient._storageProvider.getItem(RongIMLib.Navigation.Endpoint.userId + "msgId") || RongIMLib.RongIMClient._storageProvider.setItem(RongIMLib.Navigation.Endpoint.userId + "msgId", 0) || 0); }; MessageIdHandler.messageIdPlus = function (method) { RongIMLib.RongIMClient._memoryStore.depend.isPolling && this.init(); if (this.messageId >= 65535) { this.messageId = 0; } this.messageId++; RongIMLib.RongIMClient._memoryStore.depend.isPolling && RongIMLib.RongIMClient._storageProvider.setItem(RongIMLib.Navigation.Endpoint.userId + "msgId", this.messageId); return this.messageId; }; MessageIdHandler.clearMessageId = function () { this.messageId = 0; RongIMLib.RongIMClient._memoryStore.depend.isPolling && RongIMLib.RongIMClient._storageProvider.setItem(RongIMLib.Navigation.Endpoint.userId + "msgId", this.messageId); }; MessageIdHandler.getMessageId = function () { RongIMLib.RongIMClient._memoryStore.depend.isPolling && this.init(); return this.messageId; }; MessageIdHandler.messageId = 0; return MessageIdHandler; })(); RongIMLib.MessageIdHandler = MessageIdHandler; var ChrmKVCaches = (function () { function ChrmKVCaches() { this.time = 0; this.cache = {}; } ChrmKVCaches.prototype.setTime = function (time) { this.time = time; }; ChrmKVCaches.prototype.getTime = function () { return this.time; }; ChrmKVCaches.prototype.setValue = function (kvContent) { var key = kvContent.key, timestamp = kvContent.timestamp; this.cache[key] = this.cache[key] || {}; this.cache[key] = { value: kvContent.value, userId: kvContent.userId, isDeleted: false, timestamp: timestamp }; }; ChrmKVCaches.prototype.removeValue = function (kvContent) { var key = kvContent.key, timestamp = kvContent.timestamp; this.cache[key] = this.cache[key] || {}; var cache = this.cache[key]; this.cache[key] = RongIMLib.RongUtil.extend(cache, { isDeleted: true, userId: kvContent.userId, timestamp: timestamp }); }; ChrmKVCaches.prototype.getValue = function (key) { this.cache[key] = this.cache[key] || {}; var cache = this.cache[key]; return cache.isDeleted ? null : cache.value; }; ChrmKVCaches.prototype.getAllKV = function () { var kv = {}; RongIMLib.RongUtil.forEach(this.cache, function (item, key) { if (!item.isDeleted) { kv[key] = item.value; } }); return kv; }; ChrmKVCaches.prototype.getSetUserId = function (key) { this.cache[key] = this.cache[key] || {}; return this.cache[key].userId; }; ChrmKVCaches.prototype.isKeyExisted = function (key) { this.cache[key] = this.cache[key] || {}; var cache = this.cache[key]; var hasValue = !RongIMLib.RongUtil.isEmpty(cache.value); return hasValue && !cache.isDeleted; }; ChrmKVCaches.prototype.clear = function () { this.cache = {}; }; return ChrmKVCaches; })(); var chrmKVCaches = {}; var chrmKVProsumerCaches = {}; var getKVCache = function (chrmId) { var chrmKVCache = chrmKVCaches[chrmId]; if (!chrmKVCache) { chrmKVCache = chrmKVCaches[chrmId] = new ChrmKVCaches(); } return chrmKVCache; }; var getKVProsumer = function (chrmId) { var kvProsumer = chrmKVProsumerCaches[chrmId]; if (!kvProsumer) { kvProsumer = chrmKVProsumerCaches[chrmId] = new RongIMLib.RongUtil.Prosumer(); } return kvProsumer; }; var ChrmKVHandler = (function () { function ChrmKVHandler() { } ChrmKVHandler.pull = function (chrmId, time) { var prosumer = getKVProsumer(chrmId); var event = RongIMLib.RongIMClient._dataAccessProvider.pullChatroomEntry; prosumer.produce({ event: event, chrmId: chrmId, time: time }); prosumer.consume(function (params, next) { var event = params.event, chrmId = params.chrmId, time = params.time; var kvCache = getKVCache(chrmId); var currentTime = kvCache.getTime(); var isKVNeedUpdated = currentTime < time; if (isKVNeedUpdated) { event(chrmId, currentTime, { onSuccess: function (result) { ChrmKVHandler.setEntries(chrmId, result); next(); }, onError: next }); } else { next(); } }); }; ChrmKVHandler.setEntries = function (chrmId, entity) { var entries = entity.entries, isFullUpdate = entity.bFullUpdate, syncTime = entity.syncTime; var event = isFullUpdate ? ChrmKVHandler.setFullEntries : ChrmKVHandler.setIncreEntries; var kvCache = getKVCache(chrmId); syncTime = MessageUtil.int64ToTimestamp(syncTime); if (RongIMLib.RongUtil.isArray(entries)) { RongIMLib.RongUtil.forEach(entries, function (item) { var setTime = item.timestamp; if (!RongIMLib.RongUtil.isNumber(setTime)) { item.timestamp = MessageUtil.int64ToTimestamp(setTime); } }); } kvCache.setTime(syncTime); // 更新拉取时间 event(chrmId, entries); // 更新 kv 值 }; ChrmKVHandler.setEntry = function (chrmId, chatroomEntry, status, userId) { var kvCache = getKVCache(chrmId); var timestamp = chatroomEntry.timestamp || +new Date(); var isDelete = RongInnerTools.getChrmEntityByStatus(status).isDelete; var eventName = isDelete ? 'removeValue' : 'setValue'; kvCache[eventName]({ key: chatroomEntry.key, value: chatroomEntry.value, userId: userId, timestamp: timestamp }); }; ChrmKVHandler.setFullEntries = function (chrmId, entries) { var kvCache = getKVCache(chrmId); kvCache.clear(); RongIMLib.RongUtil.forEach(entries, function (entity) { entity.timestamp = MessageUtil.int64ToTimestamp(entity.timestamp); kvCache.setValue({ key: entity.key, value: entity.value, userId: entity.uid, timestamp: entity.timestamp }); }); }; ChrmKVHandler.setIncreEntries = function (chrmId, entries) { var kvCache = getKVCache(chrmId); var currentUserId = RongIMLib.RongIMClient.getInstance().getCurrentUserId(); var optEvent = function (entity, isOverwrite, eventName) { var key = entity.key, value = entity.value; var isLatestedKeySetBySelf = kvCache.getSetUserId(key) === currentUserId; var isKeyNotExist = !kvCache.isKeyExisted(key); /* 1. 需覆盖时, 不管 key 是否已存在, 都直接设置 2. 不覆盖时, 必须最后一次 key 为自己设置的或此 key 还未设置过, 才能继续 */ if (isOverwrite || isLatestedKeySetBySelf || isKeyNotExist) { kvCache[eventName]({ key: key, value: value, userId: entity.uid, timestamp: entity.timestamp }); } }; RongIMLib.RongUtil.forEach(entries, function (entity) { var entityContent = RongInnerTools.getChrmEntityByStatus(entity.status); var eventName = entityContent.isDelete ? 'removeValue' : 'setValue'; optEvent(entity, entityContent.isOverwrite, eventName); }); }; ChrmKVHandler.getEntityValue = function (chrmId, key) { var kvCache = getKVCache(chrmId); return kvCache.getValue(key); }; ChrmKVHandler.getAllEntityValue = function (chrmId) { var kvCache = getKVCache(chrmId); return kvCache.getAllKV(); }; ChrmKVHandler.isKeyValid = function (key) { return /^[A-Za-z0-9_=+-]+$/.test(key); }; return ChrmKVHandler; })(); RongIMLib.ChrmKVHandler = ChrmKVHandler; var AutoDeleteCode = 0x0001; var OverwriteCode = 0x0002; var DeleteOperationCode = 0x0004; var RongInnerTools = (function () { function RongInnerTools() { } RongInnerTools.convertUserStatus = function (entity) { entity = RongIMLib.RongUtil.rename(entity, { subUserId: 'userId' }); var status = JSON.parse(entity.status); var us = status.us; if (!us) { return entity; } entity.status = RongIMLib.RongUtil.rename(us, { o: 'online', 'p': 'platform', s: 'status' }); return entity; }; RongInnerTools.getChrmEntityStatus = function (entity, chatroomOpt) { var status = 0; // 是否自动清理 if (entity.isAutoDelete) { status = status | AutoDeleteCode; } // 是否覆盖 if (entity.isOverwrite) { status = status | OverwriteCode; } // 操作类型 switch (chatroomOpt) { case RongIMLib.ChatroomEntityOpt.DELETE: status = status | DeleteOperationCode; break; default: break; } return status; }; RongInnerTools.getChrmEntityByStatus = function (status) { var isDelete = !!(status & DeleteOperationCode); var entityOpt = isDelete ? RongIMLib.ChatroomEntityOpt.DELETE : RongIMLib.ChatroomEntityOpt.UPDATE; return { isAutoDelete: !!(status & AutoDeleteCode), isOverwrite: !!(status & OverwriteCode), entityOpt: entityOpt, isDelete: isDelete }; }; return RongInnerTools; })(); RongIMLib.RongInnerTools = RongInnerTools; var UnreadCountHandler = (function () { function UnreadCountHandler() { } UnreadCountHandler.getKey = function (type, targetId) { var selfId = RongIMLib.RongIMClient.getInstance().getCurrentUserId(); return RongIMLib.RongUtil.tplEngine(UnreadCountHandler.KeyTemp, { selfId: selfId, type: type, targetId: targetId }); }; UnreadCountHandler.getDetailByKey = function (key) { var detail = { count: 0, sentTime: 0 }; var value = RongIMLib.RongIMClient._storageProvider.getItem(key); if (!value) { return detail; } value += ''; var unreadItems = value.split('_'); var hasUnderline = unreadItems.length > 1; detail.count = Number(unreadItems[0]); if (hasUnderline) { detail.sentTime = Number(unreadItems[1]); } return detail; }; UnreadCountHandler.getDetail = function (type, targetId) { var key = UnreadCountHandler.getKey(type, targetId); var detail = UnreadCountHandler.getDetailByKey(key); return detail; }; UnreadCountHandler.set = function (type, id, count, sentTime) { var key = UnreadCountHandler.getKey(type, id); var value = sentTime ? RongIMLib.RongUtil.tplEngine(UnreadCountHandler.ValueTemp, { count: count, sentTime: sentTime }) : count; RongIMLib.RongIMClient._storageProvider.setItem(key, value); return count; }; UnreadCountHandler.add = function (type, id, plusCount, sentTime) { var detail = UnreadCountHandler.getDetail(type, id), count = detail.count, oldSentTime = detail.sentTime; if (sentTime && sentTime > oldSentTime) { count = count + plusCount; UnreadCountHandler.set(type, id, count, sentTime); } return count; }; UnreadCountHandler.get = function (type, id) { var detail = UnreadCountHandler.getDetail(type, id); return detail.count; }; UnreadCountHandler.getAll = function (types) { var total = 0; var selfId = RongIMLib.RongIMClient.getInstance().getCurrentUserId(); var setTotal = function (keyList) { RongIMLib.RongUtil.forEach(keyList, function (key) { var detail = UnreadCountHandler.getDetailByKey(key); total += detail.count; }); }; if (types) { RongIMLib.RongUtil.forEach(types, function (type) { var key = UnreadCountHandler.getKey(type, ''); var unreadKeys = RongIMLib.RongIMClient._storageProvider.getItemKeyList(key); setTotal(unreadKeys); }); } else { var key = UnreadCountHandler.getKey('', ''); var unreadKeys = RongIMLib.RongIMClient._storageProvider.getItemKeyList(key); setTotal(unreadKeys); } return total; }; UnreadCountHandler.remove = function (type, targetId) { var key = UnreadCountHandler.getKey(type, targetId); RongIMLib.RongIMClient._storageProvider.removeItem(key); }; UnreadCountHandler.clear = function () { var key = UnreadCountHandler.getKey('', ''); var keyList = RongIMLib.RongIMClient._storageProvider.getItemKeyList(key); RongIMLib.RongUtil.forEach(keyList, function (key) { RongIMLib.RongIMClient._storageProvider.removeItem(key); }); }; UnreadCountHandler.KeyTemp = 'cu{selfId}{type}{targetId}'; UnreadCountHandler.ValueTemp = '{count}_{sentTime}'; return UnreadCountHandler; })(); RongIMLib.UnreadCountHandler = UnreadCountHandler; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var MessageContent = (function () { function MessageContent(data) { throw new Error("This method is abstract, you must implement this method in inherited class."); } MessageContent.obtain = function () { throw new Error("This method is abstract, you must implement this method in inherited class."); }; return MessageContent; })(); RongIMLib.MessageContent = MessageContent; var NotificationMessage = (function (_super) { __extends(NotificationMessage, _super); function NotificationMessage() { _super.apply(this, arguments); } return NotificationMessage; })(MessageContent); RongIMLib.NotificationMessage = NotificationMessage; var StatusMessage = (function (_super) { __extends(StatusMessage, _super); function StatusMessage() { _super.apply(this, arguments); } return StatusMessage; })(MessageContent); RongIMLib.StatusMessage = StatusMessage; var ModelUtil = (function () { function ModelUtil() { } ModelUtil.modelClone = function (object) { var obj = {}; for (var item in object) { if (item != "messageName" && "encode" != item) { obj[item] = object[item]; } } return obj; }; ModelUtil.modleCreate = function (fields, msgType) { // if (fields.length < 1) { // throw new Error("Array is empty -> registerMessageType.modleCreate"); // } var Object = function (message) { var me = this; for (var index in fields) { me[fields[index]] = message[fields[index]]; } Object.prototype.messageName = msgType; Object.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; }; return Object; }; return ModelUtil; })(); RongIMLib.ModelUtil = ModelUtil; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var CustomerStatusMessage = (function () { function CustomerStatusMessage(message) { this.messageName = "CustomerStatusMessage"; this.status = message.status; } CustomerStatusMessage.obtain = function () { return null; }; CustomerStatusMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return CustomerStatusMessage; })(); RongIMLib.CustomerStatusMessage = CustomerStatusMessage; /** * 客服转换响应消息的类型名 */ var ChangeModeResponseMessage = (function () { function ChangeModeResponseMessage(message) { this.messageName = "ChangeModeResponseMessage"; this.code = message.code; this.data = message.data; this.msg = message.msg; } ChangeModeResponseMessage.obtain = function () { return null; }; ChangeModeResponseMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ChangeModeResponseMessage; })(); RongIMLib.ChangeModeResponseMessage = ChangeModeResponseMessage; /** * 客服转换消息的类型名 * 此消息不计入未读消息数 */ var ChangeModeMessage = (function () { function ChangeModeMessage(message) { this.messageName = "ChangeModeMessage"; this.uid = message.uid; this.sid = message.sid; this.pid = message.pid; } ChangeModeMessage.obtain = function () { return null; }; ChangeModeMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ChangeModeMessage; })(); RongIMLib.ChangeModeMessage = ChangeModeMessage; var CustomerStatusUpdateMessage = (function () { function CustomerStatusUpdateMessage(message) { this.messageName = "CustomerStatusUpdateMessage"; this.serviceStatus = message.serviceStatus; this.sid = message.sid; } CustomerStatusUpdateMessage.obtain = function () { return null; }; CustomerStatusUpdateMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return CustomerStatusUpdateMessage; })(); RongIMLib.CustomerStatusUpdateMessage = CustomerStatusUpdateMessage; var HandShakeMessage = (function () { function HandShakeMessage(message) { this.messageName = "HandShakeMessage"; if (message) { this.requestInfo = message.requestInfo; this.userInfo = message.userInfo; } } HandShakeMessage.obtain = function () { return null; }; HandShakeMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return HandShakeMessage; })(); RongIMLib.HandShakeMessage = HandShakeMessage; var CustomerContact = (function () { function CustomerContact(message) { this.messageName = "CustomerContact"; this.page = message.page; this.nickName = message.nickName; this.routingInfo = message.routingInfo; this.info = message.info; this.requestInfo = message.requestInfo; } CustomerContact.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return CustomerContact; })(); RongIMLib.CustomerContact = CustomerContact; var EvaluateMessage = (function () { function EvaluateMessage(message) { this.messageName = "EvaluateMessage"; this.uid = message.uid; this.sid = message.sid; this.pid = message.pid; this.source = message.source; this.suggest = message.suggest; this.isresolve = message.isresolve; this.type = message.type; } EvaluateMessage.obtain = function () { return null; }; EvaluateMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return EvaluateMessage; })(); RongIMLib.EvaluateMessage = EvaluateMessage; /** * 客服握手响应消息的类型名 */ var HandShakeResponseMessage = (function () { function HandShakeResponseMessage(message) { this.messageName = "HandShakeResponseMessage"; this.msg = message.msg; this.status = message.status; this.data = message.data; } HandShakeResponseMessage.obtain = function () { return null; }; HandShakeResponseMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return HandShakeResponseMessage; })(); RongIMLib.HandShakeResponseMessage = HandShakeResponseMessage; var SuspendMessage = (function () { function SuspendMessage(message) { this.messageName = "SuspendMessage"; this.uid = message.uid; this.sid = message.sid; this.pid = message.pid; } SuspendMessage.obtain = function () { return null; }; SuspendMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return SuspendMessage; })(); RongIMLib.SuspendMessage = SuspendMessage; var TerminateMessage = (function () { function TerminateMessage(message) { this.messageName = "TerminateMessage"; this.code = message.code; this.msg = message.msg; this.sid = message.sid; } TerminateMessage.obtain = function () { return null; }; TerminateMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return TerminateMessage; })(); RongIMLib.TerminateMessage = TerminateMessage; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var IsTypingStatusMessage = (function () { function IsTypingStatusMessage(data) { this.messageName = "IsTypingStatusMessage"; var msg = data; } IsTypingStatusMessage.prototype.encode = function () { return undefined; }; IsTypingStatusMessage.prototype.getMessage = function () { return null; }; return IsTypingStatusMessage; })(); RongIMLib.IsTypingStatusMessage = IsTypingStatusMessage; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var InformationNotificationMessage = (function () { function InformationNotificationMessage(message) { this.messageName = "InformationNotificationMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> InformationNotificationMessage."); } this.message = message.message; this.extra = message.extra; if (message.user) { this.user = message.user; } } InformationNotificationMessage.obtain = function (message) { return new InformationNotificationMessage({ message: message, extra: "" }); }; InformationNotificationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return InformationNotificationMessage; })(); RongIMLib.InformationNotificationMessage = InformationNotificationMessage; var CommandMessage = (function () { function CommandMessage(message) { this.messageName = "CommandMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> CommandMessage."); } try { if (Object.prototype.toString.call(message.data) == "[object String]") { this.data = JSON.parse(message.data); } else { this.data = message.data; } } catch (e) { this.data = message.data; } this.name = message.name; this.extra = message.extra; } CommandMessage.obtain = function (data) { return new CommandMessage({ data: data, extra: "" }); }; CommandMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return CommandMessage; })(); RongIMLib.CommandMessage = CommandMessage; var ContactNotificationMessage = (function () { function ContactNotificationMessage(message) { this.messageName = "ContactNotificationMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> ContactNotificationMessage."); } this.operation = message.operation; this.targetUserId = message.targetUserId; this.message = message.message; this.extra = message.extra; this.sourceUserId = message.sourceUserId; if (message.user) { this.user = message.user; } } ContactNotificationMessage.obtain = function (operation, sourceUserId, targetUserId, message) { return new InformationNotificationMessage({ operation: operation, sourceUserId: sourceUserId, targetUserId: targetUserId, message: message }); }; ContactNotificationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; ContactNotificationMessage.CONTACT_OPERATION_ACCEPT_RESPONSE = "ContactOperationAcceptResponse"; ContactNotificationMessage.CONTACT_OPERATION_REJECT_RESPONSE = "ContactOperationRejectResponse"; ContactNotificationMessage.CONTACT_OPERATION_REQUEST = "ContactOperationRequest"; return ContactNotificationMessage; })(); RongIMLib.ContactNotificationMessage = ContactNotificationMessage; var ProfileNotificationMessage = (function () { function ProfileNotificationMessage(message) { this.messageName = "ProfileNotificationMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> ProfileNotificationMessage."); } this.operation = message.operation; try { if (Object.prototype.toString.call(message.data) == "[object String]") { this.data = JSON.parse(message.data); } else { this.data = message.data; } } catch (e) { this.data = message.data; } this.extra = message.extra; if (message.user) { this.user = message.user; } } ProfileNotificationMessage.obtain = function (operation, data) { return new ProfileNotificationMessage({ operation: operation, data: data }); }; ProfileNotificationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ProfileNotificationMessage; })(); RongIMLib.ProfileNotificationMessage = ProfileNotificationMessage; var CommandNotificationMessage = (function () { function CommandNotificationMessage(message) { this.messageName = "CommandNotificationMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> ProfileNotificationMessage."); } try { if (Object.prototype.toString.call(message.data) == "[object String]") { this.data = JSON.parse(message.data); } else { this.data = message.data; } } catch (e) { this.data = message.data; } this.name = message.name; this.extra = message.extra; if (message.user) { this.user = message.user; } } CommandNotificationMessage.obtain = function (name, data) { return new CommandNotificationMessage({ name: name, data: data, extra: "" }); }; CommandNotificationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return CommandNotificationMessage; })(); RongIMLib.CommandNotificationMessage = CommandNotificationMessage; var DiscussionNotificationMessage = (function () { function DiscussionNotificationMessage(message) { this.messageName = "DiscussionNotificationMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> DiscussionNotificationMessage."); } this.extra = message.extra; this.extension = message.extension; this.type = message.type; this.isHasReceived = message.isHasReceived; this.operation = message.operation; this.user = message.user; if (message.user) { this.user = message.user; } } DiscussionNotificationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return DiscussionNotificationMessage; })(); RongIMLib.DiscussionNotificationMessage = DiscussionNotificationMessage; var GroupNotificationMessage = (function () { function GroupNotificationMessage(msg) { this.messageName = "GroupNotificationMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> GroupNotificationMessage."); } msg.operatorUserId && (this.operatorUserId = msg.operatorUserId); msg.operation && (this.operation = msg.operation); msg.data && (this.data = msg.data); msg.message && (this.message = msg.message); msg.extra && (this.extra = msg.extra); } GroupNotificationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return GroupNotificationMessage; })(); RongIMLib.GroupNotificationMessage = GroupNotificationMessage; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var TextMessage = (function () { function TextMessage(message) { this.messageName = "TextMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> TextMessage."); } this.content = message.content; this.extra = message.extra; if (message.user) { this.user = message.user; } if (message.mentionedInfo) { this.mentionedInfo = message.mentionedInfo; } } TextMessage.obtain = function (text) { return new TextMessage({ extra: "", content: text }); }; TextMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return TextMessage; })(); RongIMLib.TextMessage = TextMessage; var TypingStatusMessage = (function () { function TypingStatusMessage(message) { this.messageName = "TypingStatusMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> TypingStatusMessage."); } this.typingContentType = message.typingContentType; this.data = message.data; } TypingStatusMessage.obtain = function (typingContentType, data) { return new TypingStatusMessage({ typingContentType: typingContentType, data: data }); }; TypingStatusMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return TypingStatusMessage; })(); RongIMLib.TypingStatusMessage = TypingStatusMessage; var ReadReceiptMessage = (function () { function ReadReceiptMessage(message) { this.messageName = "ReadReceiptMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> ReadReceiptMessage."); } this.lastMessageSendTime = message.lastMessageSendTime; this.messageUId = message.messageUId; this.type = message.type; } ReadReceiptMessage.obtain = function (messageUId, lastMessageSendTime, type) { return new ReadReceiptMessage({ messageUId: messageUId, lastMessageSendTime: lastMessageSendTime, type: type }); }; ReadReceiptMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ReadReceiptMessage; })(); RongIMLib.ReadReceiptMessage = ReadReceiptMessage; var VoiceMessage = (function () { function VoiceMessage(message) { this.messageName = "VoiceMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> VoiceMessage."); } this.content = message.content; this.duration = message.duration; this.extra = message.extra; if (message.user) { this.user = message.user; } if (message.mentionedInfo) { this.mentionedInfo = message.mentionedInfo; } } VoiceMessage.obtain = function (base64Content, duration) { return new VoiceMessage({ content: base64Content, duration: duration, extra: "" }); }; VoiceMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return VoiceMessage; })(); RongIMLib.VoiceMessage = VoiceMessage; var RecallCommandMessage = (function () { function RecallCommandMessage(message) { this.messageName = "RecallCommandMessage"; this.messageUId = message.messageUId; this.conversationType = message.conversationType; this.targetId = message.targetId; this.sentTime = message.sentTime; message.extra && (this.extra = message.extra); message.user && (this.user = message.user); } RecallCommandMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return RecallCommandMessage; })(); RongIMLib.RecallCommandMessage = RecallCommandMessage; var ImageMessage = (function () { function ImageMessage(message) { this.messageName = "ImageMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> ImageMessage."); } this.content = message.content; this.imageUri = message.imageUri; message.extra && (this.extra = message.extra); message.user && (this.user = message.user); if (message.mentionedInfo) { this.mentionedInfo = message.mentionedInfo; } } ImageMessage.obtain = function (content, imageUri) { return new ImageMessage({ content: content, imageUri: imageUri, extra: "" }); }; ImageMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ImageMessage; })(); RongIMLib.ImageMessage = ImageMessage; var LocationMessage = (function () { function LocationMessage(message) { this.messageName = "LocationMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> LocationMessage."); } this.latitude = message.latitude; this.longitude = message.longitude; this.poi = message.poi; this.content = message.content; this.extra = message.extra; if (message.user) { this.user = message.user; } if (message.mentionedInfo) { this.mentionedInfo = message.mentionedInfo; } } LocationMessage.obtain = function (latitude, longitude, poi, content) { return new LocationMessage({ latitude: latitude, longitude: longitude, poi: poi, content: content, extra: "" }); }; LocationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return LocationMessage; })(); RongIMLib.LocationMessage = LocationMessage; var RichContentMessage = (function () { function RichContentMessage(message) { this.messageName = "RichContentMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> RichContentMessage."); } this.title = message.title; this.content = message.content; this.imageUri = message.imageUri; this.extra = message.extra; this.url = message.url; if (message.user) { this.user = message.user; } } RichContentMessage.obtain = function (title, content, imageUri, url) { return new RichContentMessage({ title: title, content: content, imageUri: imageUri, url: url, extra: "" }); }; RichContentMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return RichContentMessage; })(); RongIMLib.RichContentMessage = RichContentMessage; var JrmfRedPacketMessage = (function () { function JrmfRedPacketMessage(message) { this.messageName = 'JrmfRedPacketMessage'; message && (this.message = message); } JrmfRedPacketMessage.prototype.encode = function () { return ""; }; return JrmfRedPacketMessage; })(); RongIMLib.JrmfRedPacketMessage = JrmfRedPacketMessage; var JrmfRedPacketOpenedMessage = (function () { function JrmfRedPacketOpenedMessage(message) { this.messageName = 'JrmfRedPacketOpenedMessage'; message && (this.message = message); } JrmfRedPacketOpenedMessage.prototype.encode = function () { return ""; }; return JrmfRedPacketOpenedMessage; })(); RongIMLib.JrmfRedPacketOpenedMessage = JrmfRedPacketOpenedMessage; var UnknownMessage = (function () { function UnknownMessage(message) { this.messageName = "UnknownMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> UnknownMessage."); } this.message = message; } UnknownMessage.prototype.encode = function () { return ""; }; return UnknownMessage; })(); RongIMLib.UnknownMessage = UnknownMessage; var PublicServiceCommandMessage = (function () { function PublicServiceCommandMessage(message) { this.messageName = "PublicServiceCommandMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> PublicServiceCommandMessage."); } this.content = message.content; this.extra = message.extra; this.menuItem = message.menuItem; if (message.user) { this.user = message.user; } if (message.mentionedInfo) { this.mentionedInfo = message.mentionedInfo; } } PublicServiceCommandMessage.obtain = function (item) { return new PublicServiceCommandMessage({ content: "", command: "", menuItem: item, extra: "" }); }; PublicServiceCommandMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return PublicServiceCommandMessage; })(); RongIMLib.PublicServiceCommandMessage = PublicServiceCommandMessage; var PublicServiceMultiRichContentMessage = (function () { function PublicServiceMultiRichContentMessage(messages) { this.messageName = "PublicServiceMultiRichContentMessage"; this.richContentMessages = messages; } PublicServiceMultiRichContentMessage.prototype.encode = function () { return null; }; return PublicServiceMultiRichContentMessage; })(); RongIMLib.PublicServiceMultiRichContentMessage = PublicServiceMultiRichContentMessage; var SyncReadStatusMessage = (function () { function SyncReadStatusMessage(message) { this.messageName = "SyncReadStatusMessage"; message.lastMessageSendTime && (this.lastMessageSendTime = message.lastMessageSendTime); } SyncReadStatusMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return SyncReadStatusMessage; })(); RongIMLib.SyncReadStatusMessage = SyncReadStatusMessage; var ReadReceiptRequestMessage = (function () { function ReadReceiptRequestMessage(message) { this.messageName = "ReadReceiptRequestMessage"; message.messageUId && (this.messageUId = message.messageUId); } ReadReceiptRequestMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ReadReceiptRequestMessage; })(); RongIMLib.ReadReceiptRequestMessage = ReadReceiptRequestMessage; var ReadReceiptResponseMessage = (function () { function ReadReceiptResponseMessage(message) { this.messageName = "ReadReceiptResponseMessage"; message.receiptMessageDic && (this.receiptMessageDic = message.receiptMessageDic); } ReadReceiptResponseMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ReadReceiptResponseMessage; })(); RongIMLib.ReadReceiptResponseMessage = ReadReceiptResponseMessage; var PublicServiceRichContentMessage = (function () { function PublicServiceRichContentMessage(message) { this.messageName = "PublicServiceRichContentMessage"; this.richContentMessage = message; } PublicServiceRichContentMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return PublicServiceRichContentMessage; })(); RongIMLib.PublicServiceRichContentMessage = PublicServiceRichContentMessage; var FileMessage = (function () { function FileMessage(message) { this.messageName = "FileMessage"; message.name && (this.name = message.name); message.size && (this.size = message.size); message.type && (this.type = message.type); message.fileUrl && (this.fileUrl = message.fileUrl); message.extra && (this.extra = message.extra); message.user && (this.user = message.user); } FileMessage.obtain = function (msg) { return new FileMessage({ name: msg.name, size: msg.size, type: msg.type, fileUrl: msg.fileUrl }); }; FileMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return FileMessage; })(); RongIMLib.FileMessage = FileMessage; var HQVoiceMessage = (function () { function HQVoiceMessage(message) { this.messageName = "HQVoiceMessage"; this.type = message.type || 'aac'; message.localPath && (this.localPath = message.localPath); message.remoteUrl && (this.remoteUrl = message.remoteUrl); message.duration && (this.duration = message.duration); message.extra && (this.extra = message.extra); message.user && (this.user = message.user); } HQVoiceMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return HQVoiceMessage; })(); RongIMLib.HQVoiceMessage = HQVoiceMessage; var AcceptMessage = (function () { function AcceptMessage(message) { this.messageName = "AcceptMessage"; this.mediaId = message.mediaId; this.callId = message.callId; this.mediaType = message.mediaType; this.mode = message.mode; this.subInfo = message.subInfo; } AcceptMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return AcceptMessage; })(); RongIMLib.AcceptMessage = AcceptMessage; var RingingMessage = (function () { function RingingMessage(message) { this.messageName = "RingingMessage"; this.callId = message.callId; } RingingMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return RingingMessage; })(); RongIMLib.RingingMessage = RingingMessage; var SummaryMessage = (function () { function SummaryMessage(message) { this.messageName = "SummaryMessage"; this.caller = message.caller; this.inviter = message.inviter; this.mediaType = message.mediaType; this.memberIdList = message.memberIdList; this.startTime = message.startTime; this.connectedTime = message.connectedTime; this.duration = message.duration; this.status = message.status; } SummaryMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return SummaryMessage; })(); RongIMLib.SummaryMessage = SummaryMessage; var HungupMessage = (function () { function HungupMessage(message) { this.messageName = "HungupMessage"; this.callId = message.callId; this.reason = message.reason; this.mode = message.mode; this.subInfo = message.subInfo; } HungupMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return HungupMessage; })(); RongIMLib.HungupMessage = HungupMessage; var InviteMessage = (function () { function InviteMessage(message) { this.messageName = "InviteMessage"; this.mediaId = message.mediaId; this.callId = message.callId; this.engineType = message.engineType; this.channelInfo = message.channelInfo; this.mediaType = message.mediaType; this.extra = message.extra; this.inviteUserIds = message.inviteUserIds; this.observerUserIds = message.observerUserIds; this.mode = message.mode; this.subInfo = message.subInfo; } InviteMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return InviteMessage; })(); RongIMLib.InviteMessage = InviteMessage; var MediaModifyMessage = (function () { function MediaModifyMessage(message) { this.messageName = "MediaModifyMessage"; this.callId = message.callId; this.mediaType = message.mediaType; this.mode = message.mode; this.subInfo = message.subInfo; } MediaModifyMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return MediaModifyMessage; })(); RongIMLib.MediaModifyMessage = MediaModifyMessage; var MemberModifyMessage = (function () { function MemberModifyMessage(message) { this.messageName = "MemberModifyMessage"; this.modifyMemType = message.modifyMemType; this.callId = message.callId; this.caller = message.caller; this.engineType = message.engineType; this.channelInfo = message.channelInfo; this.mediaType = message.mediaType; this.extra = message.extra; this.inviteUserIds = message.inviteUserIds; this.existedMemberStatusList = message.existedMemberStatusList; this.existedUserPofiles = message.existedUserPofiles; this.observerUserIds = message.observerUserIds; this.mode = message.mode; this.subInfo = message.subInfo; } MemberModifyMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return MemberModifyMessage; })(); RongIMLib.MemberModifyMessage = MemberModifyMessage; var RCCombineMessage = (function () { function RCCombineMessage(message) { this.messageName = "RCCombineMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> RCCombineMessage."); } this.nameList = message.nameList; this.remoteUrl = message.remoteUrl; if (message.user) { this.user = message.user; } this.summaryList = message.summaryList; } RCCombineMessage.obtain = function (remoteUrl, nameList, summaryList) { return new RCCombineMessage({ extra: "", content: remoteUrl, nameList: nameList, summaryList: summaryList }); }; RCCombineMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return RCCombineMessage; })(); RongIMLib.RCCombineMessage = RCCombineMessage; var ChrmKVNotificationMessage = (function () { function ChrmKVNotificationMessage(message) { this.messageName = "ChrmKVNotificationMessage"; message.key && (this.key = message.key); message.value && (this.value = message.value); message.type && (this.type = message.type); message.extra && (this.extra = message.extra); message.user && (this.user = message.user); } ChrmKVNotificationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ChrmKVNotificationMessage; })(); RongIMLib.ChrmKVNotificationMessage = ChrmKVNotificationMessage; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var ChannelInfo = (function () { function ChannelInfo(Id, Key) { this.Id = Id; this.Key = Key; } return ChannelInfo; })(); RongIMLib.ChannelInfo = ChannelInfo; var UserStatus = (function () { function UserStatus(platform, online, status) { this.platform = platform; this.online = online; this.status = status; } return UserStatus; })(); RongIMLib.UserStatus = UserStatus; var MentionedInfo = (function () { function MentionedInfo(type, userIdList, mentionedContent) { } return MentionedInfo; })(); RongIMLib.MentionedInfo = MentionedInfo; var DeleteMessage = (function () { function DeleteMessage(msgId, msgDataTime, direct) { this.msgId = msgId; this.msgDataTime = msgDataTime; this.direct = direct; } return DeleteMessage; })(); RongIMLib.DeleteMessage = DeleteMessage; var CustomServiceConfig = (function () { function CustomServiceConfig(isBlack, companyName, companyUrl) { } return CustomServiceConfig; })(); RongIMLib.CustomServiceConfig = CustomServiceConfig; var CustomServiceSession = (function () { function CustomServiceSession(uid, cid, pid, isQuited, type, adminHelloWord, adminOfflineWord) { } return CustomServiceSession; })(); RongIMLib.CustomServiceSession = CustomServiceSession; var Conversation = (function () { function Conversation(conversationTitle, conversationType, draft, isTop, latestMessage, latestMessageId, notificationStatus, objectName, receivedStatus, receivedTime, senderUserId, senderUserName, sentStatus, sentTime, targetId, unreadMessageCount, senderPortraitUri, isHidden, mentionedMsg, hasUnreadMention, _readTime) { this.conversationTitle = conversationTitle; this.conversationType = conversationType; this.draft = draft; this.isTop = isTop; this.latestMessage = latestMessage; this.latestMessageId = latestMessageId; this.notificationStatus = notificationStatus; this.objectName = objectName; this.receivedStatus = receivedStatus; this.receivedTime = receivedTime; this.senderUserId = senderUserId; this.senderUserName = senderUserName; this.sentStatus = sentStatus; this.sentTime = sentTime; this.targetId = targetId; this.unreadMessageCount = unreadMessageCount; this.senderPortraitUri = senderPortraitUri; this.isHidden = isHidden; this.mentionedMsg = mentionedMsg; this.hasUnreadMention = hasUnreadMention; this._readTime = _readTime; } Conversation.prototype.setTop = function () { RongIMLib.RongIMClient._dataAccessProvider.addConversation(this, { onSuccess: function (data) { } }); }; return Conversation; })(); RongIMLib.Conversation = Conversation; var Discussion = (function () { function Discussion(creatorId, id, memberIdList, name, isOpen) { this.creatorId = creatorId; this.id = id; this.memberIdList = memberIdList; this.name = name; this.isOpen = isOpen; } return Discussion; })(); RongIMLib.Discussion = Discussion; var Group = (function () { function Group(id, name, portraitUri) { this.id = id; this.name = name; this.portraitUri = portraitUri; } return Group; })(); RongIMLib.Group = Group; var Message = (function () { function Message(content, conversationType, extra, objectName, messageDirection, messageId, receivedStatus, receivedTime, senderUserId, sentStatus, sentTime, targetId, messageType, messageUId, isLocalMessage, offLineMessage, receiptResponse) { this.content = content; this.conversationType = conversationType; this.extra = extra; this.objectName = objectName; this.messageDirection = messageDirection; this.messageId = messageId; this.receivedStatus = receivedStatus; this.receivedTime = receivedTime; this.senderUserId = senderUserId; this.sentStatus = sentStatus; this.sentTime = sentTime; this.targetId = targetId; this.messageType = messageType; this.messageUId = messageUId; this.isLocalMessage = isLocalMessage; this.offLineMessage = offLineMessage; this.receiptResponse = receiptResponse; } return Message; })(); RongIMLib.Message = Message; var MessageTag = (function () { function MessageTag(isCounted, isPersited) { this.isCounted = isCounted; this.isPersited = isPersited; } MessageTag.prototype.getMessageTag = function () { if (this.isCounted && this.isPersited) { return 3; } else if (this.isCounted) { return 2; } else if (this.isPersited) { return 1; } else if (!this.isCounted && !this.isPersited) { return 0; } }; MessageTag.getTagByStatus = function (status) { var statusMap = { 3: { isCounted: true, isPersited: true }, 2: { isCounted: true, isPersited: false }, 1: { isCounted: true, isPersited: true }, 0: { isCounted: true, isPersited: true } }; return statusMap[status] || statusMap[3]; }; return MessageTag; })(); RongIMLib.MessageTag = MessageTag; var PublicServiceMenuItem = (function () { function PublicServiceMenuItem(id, name, type, sunMenuItems, url) { this.id = id; this.name = name; this.type = type; this.sunMenuItems = sunMenuItems; this.url = url; } return PublicServiceMenuItem; })(); RongIMLib.PublicServiceMenuItem = PublicServiceMenuItem; // TODO: TBD var PublicServiceProfile = (function () { function PublicServiceProfile(conversationType, introduction, menu, name, portraitUri, publicServiceId, hasFollowed, isGlobal) { this.conversationType = conversationType; this.introduction = introduction; this.menu = menu; this.name = name; this.portraitUri = portraitUri; this.publicServiceId = publicServiceId; this.hasFollowed = hasFollowed; this.isGlobal = isGlobal; } return PublicServiceProfile; })(); RongIMLib.PublicServiceProfile = PublicServiceProfile; var UserInfo = (function () { function UserInfo(id, name, portraitUri) { this.id = id; this.name = name; this.portraitUri = portraitUri; } return UserInfo; })(); RongIMLib.UserInfo = UserInfo; var User = (function () { function User(id, token) { this.id = id; this.token = token; } return User; })(); RongIMLib.User = User; var Room = (function () { function Room(id, user, mode, broadcastType, type) { this.id = id; this.user = user; this.mode = mode; this.broadcastType = broadcastType; this.type = type; } return Room; })(); RongIMLib.Room = Room; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var ServerDataProvider = (function () { function ServerDataProvider() { this.userStatusListener = null; this.Conversation = { watcher: new RongIMLib.Observer(), watch: function (_watcher) { this.watcher.add(_watcher); var conversationList = RongIMLib.RongIMClient._memoryStore.conversationList; this.watcher.emit(conversationList); }, unwatch: function (_watcher) { this.watcher.remove(_watcher); }, _notify: function (conversationList) { this.watcher.emit(conversationList); } }; } ServerDataProvider.prototype.init = function (appKey, options) { new RongIMLib.FeatureDectector(options.appCallback); }; ServerDataProvider.prototype.connect = function (token, callback, userId, option) { RongIMLib.RongIMClient.bridge = RongIMLib.Bridge.getInstance(); RongIMLib.RongIMClient._memoryStore.token = token; RongIMLib.RongIMClient._memoryStore.callback = callback; userId = userId || ''; option = option || {}; var isConnecting = false, isConnected = false; if (RongIMLib.Bridge._client && RongIMLib.Bridge._client.channel) { isConnecting = (RongIMLib.Bridge._client.channel.connectionStatus == RongIMLib.ConnectionStatus.CONNECTING); isConnected = (RongIMLib.Bridge._client.channel.connectionStatus == RongIMLib.ConnectionStatus.CONNECTED); } if (isConnected || isConnecting) { return; } var isGreater = (RongIMLib.RongIMClient.otherDeviceLoginCount > 5); if (isGreater) { callback.onError(RongIMLib.ConnectionStatus.ULTRALIMIT); return; } // 清除本地导航缓存 if (option.force) { RongIMLib.RongIMClient._storageProvider.removeItem('servers'); } RongIMLib.RongIMClient.bridge.setListener(); RongIMLib.RongIMClient.bridge.connect(RongIMLib.RongIMClient._memoryStore.appKey, token, { onSuccess: function (data) { setTimeout(function () { callback.onSuccess(data); }); }, onError: function (e) { if (e == RongIMLib.ConnectionState.TOKEN_INCORRECT || !e) { setTimeout(function () { callback.onTokenIncorrect(); }); } else { setTimeout(function () { callback.onError(e); }); } } }); }; /* config.auto: 默认 false, true 启用自动重连,启用则为必选参数 config.rate: 重试频率 [100, 1000, 3000, 6000, 10000, 18000] 单位为毫秒,可选 config.url: 网络嗅探地址 [http(s)://]cdn.ronghub.com/RongIMLib-2.2.6.min.js 可选 */ ServerDataProvider.prototype.reconnect = function (callback, config) { var store = RongIMLib.RongIMClient._memoryStore; var token = store.token; if (!token) { throw new Error('reconnect: token is empty.'); } if (RongIMLib.Bridge._client && RongIMLib.Bridge._client.channel && RongIMLib.Bridge._client.channel.connectionStatus != RongIMLib.ConnectionStatus.CONNECTED && RongIMLib.Bridge._client.channel.connectionStatus != RongIMLib.ConnectionStatus.CONNECTING) { config = config || {}; var key = config.auto ? 'auto' : 'custom'; var handler = { auto: function () { var repeatConnect = function (options) { var step = options.step(); var done = 'done'; var url = options.url; var ping = function () { RongIMLib.RongUtil.request({ url: url, success: function () { options.done(); }, error: function () { repeat(); } }); }; var repeat = function () { var next = step(); if (next == 'done') { var error = RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE; options.done(error); return; } setTimeout(ping, next); }; repeat(); }; var protocol = RongIMLib.RongIMClient._memoryStore.depend.protocol; var url = config.url || 'cdn.ronghub.com/RongIMLib-2.2.6.min.js'; var pathConfig = { protocol: protocol, path: url }; url = RongIMLib.RongUtil.formatProtoclPath(pathConfig); var rate = config.rate || [100, 1000, 3000, 6000, 10000, 18000]; //结束标识 rate.push('done'); var opts = { url: url, step: function () { var index = 0; return function () { var time = rate[index]; index++; return time; }; }, done: function (error) { if (error) { callback.onError(error); return; } RongIMLib.RongIMClient.connect(token, callback); } }; repeatConnect(opts); }, custom: function () { RongIMLib.RongIMClient.connect(token, callback); } }; handler[key](); } }; ServerDataProvider.prototype.logout = function () { RongIMLib.RongIMClient.bridge.disconnect(); RongIMLib.RongIMClient.bridge = null; }; ServerDataProvider.prototype.disconnect = function () { RongIMLib.RongIMClient.bridge.disconnect(); }; ServerDataProvider.prototype.sendReceiptResponse = function (conversationType, targetId, sendCallback) { var rspkey = RongIMLib.Bridge._client.userId + conversationType + targetId + 'RECEIVED', me = this; if (RongIMLib.RongUtil.supportLocalStorage()) { var valObj = JSON.parse(RongIMLib.RongIMClient._storageProvider.getItem(rspkey)); if (valObj) { var vals = []; for (var key in valObj) { var tmp = {}; tmp[key] = valObj[key].uIds; valObj[key].isResponse || vals.push(tmp); } if (vals.length == 0) { sendCallback.onSuccess(); return; } var interval = setInterval(function () { if (vals.length == 1) { clearInterval(interval); } var obj = vals.splice(0, 1)[0]; var rspMsg = new RongIMLib.ReadReceiptResponseMessage({ receiptMessageDic: obj }); me.sendMessage(conversationType, targetId, rspMsg, { onSuccess: function (msg) { var senderUserId = RongIMLib.MessageUtil.getFirstKey(obj); valObj[senderUserId].isResponse = true; RongIMLib.RongIMClient._storageProvider.setItem(rspkey, JSON.stringify(valObj)); sendCallback.onSuccess(msg); }, onError: function (error, msg) { sendCallback.onError(error, msg); } }); }, 200); } else { sendCallback.onSuccess(); } } else { sendCallback.onSuccess(); } }; ServerDataProvider.prototype.sendTypingStatusMessage = function (conversationType, targetId, messageName, sendCallback) { var me = this; if (messageName in RongIMLib.RongIMClient.MessageParams) { me.sendMessage(conversationType, targetId, RongIMLib.TypingStatusMessage.obtain(RongIMLib.RongIMClient.MessageParams[messageName].objectName, ""), { onSuccess: function () { setTimeout(function () { sendCallback.onSuccess(); }); }, onError: function (errorCode) { setTimeout(function () { sendCallback.onError(errorCode, null); }); }, onBefore: function () { } }); } }; ServerDataProvider.prototype.sendRecallMessage = function (content, sendMessageCallback) { var msg = new RongIMLib.RecallCommandMessage({ conversationType: content.conversationType, targetId: content.targetId, sentTime: content.sentTime, messageUId: content.messageUId, extra: content.extra, user: content.user }); this.sendMessage(content.conversationType, content.senderUserId, msg, sendMessageCallback, false, null, null, 2); }; ServerDataProvider.prototype.sendTextMessage = function (conversationType, targetId, content, sendMessageCallback) { var msgContent = RongIMLib.TextMessage.obtain(content); this.sendMessage(conversationType, targetId, msgContent, sendMessageCallback); }; ServerDataProvider.prototype.getRemoteHistoryMessages = function (conversationType, targetId, timestamp, count, callback, config) { if (count <= 1) { throw new Error("the count must be greater than 1."); } config = config || {}; var order = config.order || 0; var getKey = function () { return [conversationType, targetId, '_', order].join(''); }; var key = getKey(); if (!RongIMLib.RongUtil.isNumber(timestamp)) { timestamp = RongIMLib.RongIMClient._memoryStore.lastReadTime.get(key); } var memoryStore = RongIMLib.RongIMClient._memoryStore; var historyMessageLimit = memoryStore.historyMessageLimit; /* limit 属性: var limit = { time: '时间戳, 最后一次拉取时间', hasMore: '是否还有历史消息, bool 值' }; */ var limit = historyMessageLimit.get(key) || {}; var hasMore = limit.hasMore; var isFecth = (hasMore || limit.time != timestamp); // 正序获取消息时不做限制,防止有新消息导致无法获取 if (!isFecth && order == 0) { return callback.onSuccess([], hasMore); } var modules = new RongIMLib.RongIMClient.Protobuf.HistoryMsgInput(), self = this; modules.setTargetId(targetId); modules.setTime(timestamp); modules.setCount(count); modules.setOrder(order); var topic = HistoryMsgType[conversationType] || HistoryMsgType[RongIMLib.ConversationType.PRIVATE]; RongIMLib.RongIMClient.bridge.queryMsg(topic, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), targetId, { onSuccess: function (data) { var fetchTime = RongIMLib.MessageUtil.int64ToTimestamp(data.syncTime); RongIMLib.RongIMClient._memoryStore.lastReadTime.set(key, fetchTime); historyMessageLimit.set(key, { hasMore: !!data.hasMsg, time: fetchTime }); var list = data.list.reverse(), tempMsg = null, tempDir; var read = RongIMLib.SentStatus.READ; if (RongIMLib.RongUtil.supportLocalStorage()) { for (var i = 0, len = list.length; i < len; i++) { tempMsg = RongIMLib.MessageUtil.messageParser(list[i]); tempDir = JSON.parse(RongIMLib.RongIMClient._storageProvider.getItem(RongIMLib.Bridge._client.userId + tempMsg.messageUId + "SENT")); if (tempDir) { tempMsg.receiptResponse || (tempMsg.receiptResponse = {}); tempMsg.receiptResponse[tempMsg.messageUId] = tempDir.count; } tempMsg.sentStatus = read; tempMsg.targetId = targetId; list[i] = tempMsg; } } else { for (var i = 0, len = list.length; i < len; i++) { var tempMsg = RongIMLib.MessageUtil.messageParser(list[i]); tempMsg.sentStatus = read; list[i] = tempMsg; } } setTimeout(function () { callback.onSuccess(list, !!data.hasMsg); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }, "HistoryMessagesOuput"); }; ServerDataProvider.prototype.hasRemoteUnreadMessages = function (token, callback) { var xss = null; window.RCCallback = function (x) { setTimeout(function () { callback.onSuccess(!!+x.status); }); xss.parentNode.removeChild(xss); }; xss = document.createElement("script"); xss.src = RongIMLib.RongIMClient._memoryStore.depend.api + "/message/exist.js?appKey=" + encodeURIComponent(RongIMLib.RongIMClient._memoryStore.appKey) + "&token=" + encodeURIComponent(token) + "&callBack=RCCallback&_=" + RongIMLib.RongUtil.getTimestamp(); document.body.appendChild(xss); xss.onerror = function () { setTimeout(function () { callback.onError(RongIMLib.ErrorCode.UNKNOWN); }); xss.parentNode.removeChild(xss); }; }; ServerDataProvider.prototype.getRemoteConversationList = function (callback, conversationTypes, count) { var modules = new RongIMLib.RongIMClient.Protobuf.RelationsInput(), self = this; modules.setType(1); if (typeof count == 'undefined') { modules.setCount(0); } else { modules.setCount(count); } RongIMLib.RongIMClient.bridge.queryMsg(26, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (list) { if (list.info) { list.info = list.info.reverse(); for (var i = 0, len = list.info.length; i < len; i++) { RongIMLib.RongIMClient.getInstance().pottingConversation(list.info[i]); } } var conversations = RongIMLib.RongIMClient._memoryStore.conversationList; setTimeout(function () { if (conversationTypes) { return callback.onSuccess(self.filterConversations(conversationTypes, conversations)); } callback.onSuccess(conversations); }); }, onError: function (error) { callback.onError(error); } }, "RelationsOutput"); }; ServerDataProvider.prototype.addMemberToDiscussion = function (discussionId, userIdList, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.ChannelInvitationInput(); modules.setUsers(userIdList); RongIMLib.RongIMClient.bridge.queryMsg(0, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), discussionId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.createDiscussion = function (name, userIdList, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.CreateDiscussionInput(), self = this; modules.setName(name); RongIMLib.RongIMClient.bridge.queryMsg(1, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (discussId) { if (userIdList.length > 0) { self.addMemberToDiscussion(discussId, userIdList, { onSuccess: function () { }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); } setTimeout(function () { callback.onSuccess(discussId); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }, "CreateDiscussionOutput"); }; ServerDataProvider.prototype.getDiscussion = function (discussionId, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.ChannelInfoInput(); modules.setNothing(1); RongIMLib.RongIMClient.bridge.queryMsg(4, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), discussionId, { onSuccess: function (data) { setTimeout(function () { callback.onSuccess(data); }); }, onError: function (errorCode) { setTimeout(function () { callback.onError(errorCode); }); } }, "ChannelInfoOutput"); }; ServerDataProvider.prototype.quitDiscussion = function (discussionId, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.LeaveChannelInput(); modules.setNothing(1); RongIMLib.RongIMClient.bridge.queryMsg(7, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), discussionId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (errorCode) { setTimeout(function () { callback.onError(errorCode); }); } }); }; ServerDataProvider.prototype.removeMemberFromDiscussion = function (discussionId, userId, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.ChannelEvictionInput(); modules.setUser(userId); RongIMLib.RongIMClient.bridge.queryMsg(9, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), discussionId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (errorCode) { setTimeout(function () { callback.onError(errorCode); }); } }); }; ServerDataProvider.prototype.setDiscussionInviteStatus = function (discussionId, status, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.ModifyPermissionInput(); modules.setOpenStatus(status.valueOf()); RongIMLib.RongIMClient.bridge.queryMsg(11, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), discussionId, { onSuccess: function (x) { setTimeout(function () { callback.onSuccess(); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.setDiscussionName = function (discussionId, name, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RenameChannelInput(); modules.setName(name); RongIMLib.RongIMClient.bridge.queryMsg(12, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), discussionId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (errcode) { callback.onError(errcode); } }); }; ServerDataProvider.prototype.joinChatRoom = function (chatroomId, messageCount, callback) { var e = new RongIMLib.RongIMClient.Protobuf.ChrmInput(); e.setNothing(1); RongIMLib.Bridge._client.chatroomId = chatroomId; RongIMLib.RongIMClient.bridge.queryMsg(19, RongIMLib.MessageUtil.ArrayForm(e.toArrayBuffer()), chatroomId, { onSuccess: function () { var navi = RongIMLib.RongIMClient.getInstance().getNavi(); var isOpenKVStorage = navi.kvStorage; if (isOpenKVStorage) { RongIMLib.RongIMClient._dataAccessProvider.pullChatroomEntry(chatroomId, 0, { onSuccess: function (result) { RongIMLib.ChrmKVHandler.setEntries(chatroomId, result); setTimeout(function () { callback.onSuccess(); }); }, onError: function (errorCode) { setTimeout(function () { callback.onError(errorCode); }); } }); } else { setTimeout(function () { callback.onSuccess(); }); } var modules = new RongIMLib.RongIMClient.Protobuf.ChrmPullMsg(); messageCount == 0 && (messageCount = -1); modules.setCount(messageCount); modules.setSyncTime(0); RongIMLib.Bridge._client.queryMessage("chrmPull", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), chatroomId, 1, { onSuccess: function (collection) { var list = collection.list; var sync = RongIMLib.MessageUtil.int64ToTimestamp(collection.syncTime); var latestMessage = list[list.length - 1]; if (latestMessage) { latestMessage = RongIMLib.MessageUtil.messageParser(latestMessage); sync = latestMessage.sentTime; } RongIMLib.RongIMClient._memoryStore.lastReadTime.set(chatroomId + RongIMLib.Bridge._client.userId + "CST", sync); var _client = RongIMLib.Bridge._client; for (var i = 0, mlen = list.length; i < mlen; i++) { var uId = 'R' + list[i].msgId; if (!(uId in _client.cacheMessageIds)) { _client.cacheMessageIds[uId] = true; var cacheUIds = RongIMLib.RongUtil.keys(_client.cacheMessageIds); if (cacheUIds.length > 10) { uId = cacheUIds[0]; delete _client.cacheMessageIds[uId]; } if (RongIMLib.RongIMClient._memoryStore.filterMessages.length > 0) { for (var j = 0, flen = RongIMLib.RongIMClient._memoryStore.filterMessages.length; j < flen; j++) { if (RongIMLib.RongIMClient.MessageParams[RongIMLib.RongIMClient._memoryStore.filterMessages[j]].objectName != list[i].classname) { _client.handler.onReceived(list[i]); } } } else { _client.handler.onReceived(list[i]); } } } }, onError: function (x) { setTimeout(function () { callback.onError(RongIMLib.ErrorCode.CHATROOM_HISMESSAGE_ERROR); }); } }, "DownStreamMessages"); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }, "ChrmOutput"); }; ServerDataProvider.prototype.getChatRoomInfo = function (chatRoomId, count, order, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.QueryChatroomInfoInput(); modules.setCount(count); modules.setOrder(order); RongIMLib.RongIMClient.bridge.queryMsg("queryChrmI", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), chatRoomId, { onSuccess: function (ret) { var userInfos = ret.userInfos; userInfos.forEach(function (item) { item.time = RongIMLib.MessageUtil.int64ToTimestamp(item.time); }); setTimeout(function () { callback.onSuccess(ret); }); }, onError: function (errcode) { setTimeout(function () { callback.onError(errcode); }); } }, "QueryChatroomInfoOutput"); }; ServerDataProvider.prototype.quitChatRoom = function (chatroomId, callback) { var e = new RongIMLib.RongIMClient.Protobuf.ChrmInput(); e.setNothing(1); RongIMLib.RongIMClient.bridge.queryMsg(17, RongIMLib.MessageUtil.ArrayForm(e.toArrayBuffer()), chatroomId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (errcode) { setTimeout(function () { callback.onError(errcode); }); } }, "ChrmOutput"); }; ServerDataProvider.prototype.setChatroomHisMessageTimestamp = function (chatRoomId, timestamp) { RongIMLib.RongIMClient._memoryStore.lastReadTime.set('chrhis_' + chatRoomId, timestamp); }; ServerDataProvider.prototype.getChatRoomHistoryMessages = function (chatRoomId, count, order, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.HistoryMsgInput(); modules.setTargetId(chatRoomId); var timestamp = RongIMLib.RongIMClient._memoryStore.lastReadTime.get('chrhis_' + chatRoomId) || 0; modules.setTime(timestamp); modules.setCount(count); modules.setOrder(order); RongIMLib.RongIMClient.bridge.queryMsg(34, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (data) { RongIMLib.RongIMClient._memoryStore.lastReadTime.set('chrhis_' + chatRoomId, RongIMLib.MessageUtil.int64ToTimestamp(data.syncTime)); var list = data.list.reverse(); for (var i = 0, len = list.length; i < len; i++) { list[i] = RongIMLib.MessageUtil.messageParser(list[i]); } setTimeout(function () { callback.onSuccess(list, !!data.hasMsg); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }, "HistoryMsgOuput"); }; ServerDataProvider.prototype.setChatroomEntry = function (chatroomId, chatroomEntry, callback) { var opt = RongIMLib.ChatroomEntityOpt.UPDATE; var key = chatroomEntry.key, value = chatroomEntry.value; var isKeyInValid = !RongIMLib.RongUtil.isLengthLimit(key, RongIMLib.ChatroomEntityLimit.KEY, 1) || !RongIMLib.ChrmKVHandler.isKeyValid(key); var isValueInValid = !RongIMLib.RongUtil.isLengthLimit(value, RongIMLib.ChatroomEntityLimit.VALUE, 1); if (isKeyInValid || isValueInValid) { setTimeout(function () { callback.onError(RongIMLib.ErrorCode.BIZ_ERROR_INVALID_PARAMETER); }); } else { this.refreshChatroomEntry(chatroomId, chatroomEntry, opt, callback); } }; ServerDataProvider.prototype.forceSetChatroomEntry = function (chatroomId, chatroomEntry, callback) { chatroomEntry.isOverwrite = true; this.setChatroomEntry(chatroomId, chatroomEntry, callback); }; ServerDataProvider.prototype.removeChatroomEntry = function (chatroomId, chatroomEntry, callback) { var opt = RongIMLib.ChatroomEntityOpt.DELETE; var key = chatroomEntry.key; var isKeyInValid = !RongIMLib.RongUtil.isLengthLimit(key, RongIMLib.ChatroomEntityLimit.KEY, 1) || !RongIMLib.ChrmKVHandler.isKeyValid(key); if (isKeyInValid) { setTimeout(function () { callback.onError(RongIMLib.ErrorCode.BIZ_ERROR_INVALID_PARAMETER); }); } else { this.refreshChatroomEntry(chatroomId, chatroomEntry, opt, callback); } }; ServerDataProvider.prototype.forceRemoveChatroomEntry = function (chatroomId, chatroomEntry, callback) { chatroomEntry.isOverwrite = true; this.removeChatroomEntry(chatroomId, chatroomEntry, callback); }; ServerDataProvider.prototype.refreshChatroomEntry = function (chatroomId, chatroomEntry, chatroomEntryOpt, callback) { var modules, topic; var key = chatroomEntry.key, value = chatroomEntry.value || '', extra = chatroomEntry.notificationExtra; if (chatroomEntryOpt === RongIMLib.ChatroomEntityOpt.DELETE) { modules = new RongIMLib.RongIMClient.Protobuf.DeleteChrmKV(); topic = 'delKV'; } else { modules = new RongIMLib.RongIMClient.Protobuf.SetChrmKV(); topic = 'setKV'; } var status = RongIMLib.RongInnerTools.getChrmEntityStatus(chatroomEntry, chatroomEntryOpt); var currentUserId = RongIMLib.RongIMClient.getInstance().getCurrentUserId(); var entry = { key: key, value: value, uid: currentUserId }; if (status) { entry.status = status; } modules.setEntry(entry); if (chatroomEntry.isSendNotification) { modules.setBNotify(true); var msgModules = new RongIMLib.RongIMClient.Protobuf.UpStreamMessage(); var msg = new RongIMLib.ChrmKVNotificationMessage({ key: key, value: value, extra: extra, type: chatroomEntryOpt }); msgModules.setSessionId(RongIMLib.RongIMClient.MessageParams[msg.messageName].msgTag.getMessageTag()); msgModules.setClassname(RongIMLib.RongIMClient.MessageParams[msg.messageName].objectName); msgModules.setContent(msg.encode()); modules.setNotification(msgModules); // 默认设置为 聊天室消息 modules.setType(RongIMLib.ConversationType.CHATROOM); } RongIMLib.RongIMClient.bridge.queryMsg(topic, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), chatroomId, { onSuccess: function (ret) { var currentUserId = RongIMLib.RongIMClient.getInstance().getCurrentUserId(); RongIMLib.ChrmKVHandler.setEntry(chatroomId, chatroomEntry, status, currentUserId); setTimeout(function () { callback.onSuccess(!!ret); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }, 'ChrmOutput'); }; ServerDataProvider.prototype.getChatroomEntry = function (chatroomId, key, callback) { var value = RongIMLib.ChrmKVHandler.getEntityValue(chatroomId, key); setTimeout(function () { if (RongIMLib.RongUtil.isEmpty(value)) { callback.onError(RongIMLib.ErrorCode.CHATROOM_KEY_NOT_EXIST); } else { callback.onSuccess(value); } }); }; ServerDataProvider.prototype.getAllChatroomEntries = function (chatroomId, callback) { setTimeout(function () { var entries = RongIMLib.ChrmKVHandler.getAllEntityValue(chatroomId); callback.onSuccess(entries); }); }; ServerDataProvider.prototype.pullChatroomEntry = function (chatroomId, time, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.QueryChrmKV(); modules.setTimestamp(time); RongIMLib.RongIMClient.bridge.queryMsg('pullKV', RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), chatroomId, { onSuccess: function (data) { setTimeout(function () { callback.onSuccess(data); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }, "ChrmKVOutput"); }; ServerDataProvider.prototype.setMessageStatus = function (conversationType, targetId, timestamp, status, callback) { setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.addToBlacklist = function (userId, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.Add2BlackListInput(); modules.setUserId(userId); RongIMLib.RongIMClient.bridge.queryMsg(21, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.getBlacklist = function (callback) { var modules = new RongIMLib.RongIMClient.Protobuf.QueryBlackListInput(); modules.setNothing(1); RongIMLib.RongIMClient.bridge.queryMsg(23, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (list) { setTimeout(function () { callback.onSuccess(list); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }, "QueryBlackListOutput"); }; ServerDataProvider.prototype.getBlacklistStatus = function (userId, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.BlackListStatusInput(); modules.setUserId(userId); RongIMLib.RongIMClient.bridge.queryMsg(24, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function (status) { setTimeout(function () { callback.onSuccess(RongIMLib.BlacklistStatus[status]); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.removeFromBlacklist = function (userId, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RemoveFromBlackListInput(); modules.setUserId(userId); RongIMLib.RongIMClient.bridge.queryMsg(22, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.getFileToken = function (fileType, callback) { if (!(/(1|2|3|4)/.test(fileType.toString()))) { setTimeout(function () { callback.onError(RongIMLib.ErrorCode.QNTKN_FILETYPE_ERROR); }); return; } var modules = new RongIMLib.RongIMClient.Protobuf.GetQNupTokenInput(); modules.setType(fileType); RongIMLib.RongIMClient.bridge.queryMsg(30, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (data) { setTimeout(function () { callback.onSuccess(data); }); }, onError: function (errcode) { setTimeout(function () { callback.onError(errcode); }); } }, "GetQNupTokenOutput"); }; ServerDataProvider.prototype.getFileUrl = function (fileType, fileName, oriName, callback) { if (!(/(1|2|3|4)/.test(fileType.toString()))) { setTimeout(function () { callback.onError(RongIMLib.ErrorCode.QNTKN_FILETYPE_ERROR); }); return; } var modules = new RongIMLib.RongIMClient.Protobuf.GetQNdownloadUrlInput(); modules.setType(fileType); modules.setKey(fileName); if (oriName) { modules.setFileName(oriName); } RongIMLib.RongIMClient.bridge.queryMsg(31, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (data) { setTimeout(function () { callback.onSuccess(data); }); }, onError: function (errcode) { setTimeout(function () { callback.onError(errcode); }); } }, "GetQNdownloadUrlOutput"); }; ServerDataProvider.prototype.getPullSetting = function (callback) { var modules = new RongIMLib.RongIMClient.Protobuf.PullUserSettingInput(); var version = parseInt(RongIMLib.RongIMClient.sdkver); modules.setVersion(version); RongIMLib.RongIMClient.bridge.queryMsg('pullUS', RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (result) { result = result || {}; result.version = RongIMLib.MessageUtil.int64ToTimestamp(result.version); setTimeout(function () { callback.onSuccess(result); }); }, onError: function (errcode) { setTimeout(function () { callback.onError(errcode); }); } }, 'PullUserSettingOutput'); }; ServerDataProvider.prototype.setOfflineMessageDuration = function (duration, callback) { this.getPullSetting({ onSuccess: function (result) { /** * GetQNupTokenOutput 第一位为 int64, 第二位为 string, 与设置离线消息一致 * 为避免修改 Protobuf 带来的更新成本. 仅复用, 不重新命名 */ var modules = new RongIMLib.RongIMClient.Protobuf.GetQNupTokenOutput(); var version = result.version; modules.setDeadline(version); modules.setToken(duration + ''); RongIMLib.RongIMClient.bridge.queryMsg('setOfflineMsgDur', RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (data) { setTimeout(function () { callback.onSuccess(data); }); }, onError: function (errcode) { setTimeout(function () { callback.onError(errcode); }); } }); }, onError: callback.onError }); }; /* methodType 1 : 多客服(客服后台使用); 2 : 消息撤回 params.userIds : 定向消息接收者 */ ServerDataProvider.prototype.sendMessage = function (conversationType, targetId, messageContent, sendCallback, mentiondMsg, pushText, appData, methodType, params) { if (!RongIMLib.Bridge._client.channel) { setTimeout(function () { sendCallback.onError(RongIMLib.ErrorCode.RC_NET_UNAVAILABLE, null); }); return; } if (!RongIMLib.Bridge._client.channel.socket.socket.connected) { setTimeout(function () { sendCallback.onError(RongIMLib.ErrorCode.TIMEOUT, null); }); throw new Error("connect is timeout! postion:sendMessage"); } var isGroup = (conversationType == RongIMLib.ConversationType.DISCUSSION || conversationType == RongIMLib.ConversationType.GROUP); var modules = new RongIMLib.RongIMClient.Protobuf.UpStreamMessage(); if (mentiondMsg && isGroup) { modules.setSessionId(7); } else { modules.setSessionId(RongIMLib.RongIMClient.MessageParams[messageContent.messageName].msgTag.getMessageTag()); } pushText && modules.setPushText(pushText); appData && modules.setAppData(appData); if (isGroup && messageContent.messageName == RongIMLib.RongIMClient.MessageType["ReadReceiptResponseMessage"]) { var rspMsg = messageContent; if (rspMsg.receiptMessageDic) { var ids = []; for (var key in rspMsg.receiptMessageDic) { ids.push(key); } modules.setUserId(ids); } } if (isGroup && messageContent.messageName == RongIMLib.RongIMClient.MessageType["SyncReadStatusMessage"]) { modules.setUserId(RongIMLib.Bridge._client.userId); } params = params || {}; var userIds = params.userIds; if (userIds) { modules.setUserId(userIds); } var flag = 0; if (params.isPush || params.isVoipPush) { flag |= 0x01; } if (params.isFilerWhiteBlacklist) { flag |= 0x02; } modules.setConfigFlag(flag); modules.setClassname(RongIMLib.RongIMClient.MessageParams[messageContent.messageName].objectName); modules.setContent(messageContent.encode()); var content = modules.toArrayBuffer(); if (Object.prototype.toString.call(content) == "[object ArrayBuffer]") { content = [].slice.call(new Int8Array(content)); } var me = this, msg = new RongIMLib.Message(); var c = this.getConversation(conversationType, targetId); if (RongIMLib.RongIMClient.MessageParams[messageContent.messageName].msgTag.getMessageTag() == 3) { if (!c) { c = RongIMLib.RongIMClient.getInstance().createConversation(conversationType, targetId, ""); } c.sentTime = new Date().getTime(); c.sentStatus = RongIMLib.SentStatus.SENDING; c.senderUserName = ""; c.senderUserId = RongIMLib.Bridge._client.userId; c.notificationStatus = RongIMLib.ConversationNotificationStatus.DO_NOT_DISTURB; c.latestMessage = msg; c.unreadMessageCount = 0; RongIMLib.RongIMClient._dataAccessProvider.addConversation(c, { onSuccess: function (data) { } }); } RongIMLib.RongIMClient._memoryStore.converStore = c; msg.content = messageContent; msg.conversationType = conversationType; msg.senderUserId = RongIMLib.Bridge._client.userId; msg.objectName = RongIMLib.RongIMClient.MessageParams[messageContent.messageName].objectName; msg.targetId = targetId; msg.sentTime = new Date().getTime(); msg.messageDirection = RongIMLib.MessageDirection.SEND; msg.sentStatus = RongIMLib.SentStatus.SENT; msg.messageType = messageContent.messageName; RongIMLib.RongIMClient.bridge.pubMsg(conversationType.valueOf(), content, targetId, { onSuccess: function (data) { if (data && data.timestamp) { RongIMLib.RongIMClient._memoryStore.lastReadTime.set('converST_' + RongIMLib.Bridge._client.userId + conversationType + targetId, data.timestamp); } if ((conversationType == RongIMLib.ConversationType.DISCUSSION || conversationType == RongIMLib.ConversationType.GROUP) && messageContent.messageName == RongIMLib.RongIMClient.MessageType["ReadReceiptRequestMessage"]) { var reqMsg = msg.content; var sentkey = RongIMLib.Bridge._client.userId + reqMsg.messageUId + "SENT"; RongIMLib.RongIMClient._storageProvider.setItem(sentkey, JSON.stringify({ count: 0, dealtime: data.timestamp, userIds: {} })); } if (RongIMLib.RongIMClient.MessageParams[msg.messageType].msgTag.getMessageTag() == 3) { var cacheConversation = RongIMLib.RongIMClient._memoryStore.converStore; cacheConversation.sentStatus = msg.sentStatus; cacheConversation.latestMessage = msg; me.updateConversation(cacheConversation); var Conversation = RongIMLib.RongIMClient._dataAccessProvider.Conversation; Conversation._notify(RongIMLib.RongIMClient._memoryStore.conversationList); RongIMLib.RongIMClient._dataAccessProvider.addMessage(conversationType, targetId, msg, { onSuccess: function (ret) { msg = ret; msg.messageUId = data.messageUId; msg.sentTime = data.timestamp; msg.sentStatus = RongIMLib.SentStatus.SENT; msg.messageId = data.messageId; RongIMLib.RongIMClient._dataAccessProvider.updateMessage(msg); }, onError: function () { } }); } setTimeout(function () { cacheConversation && me.updateConversation(cacheConversation); msg.sentTime = data.timestamp; msg.messageUId = data.messageUId; sendCallback.onSuccess(msg); }); }, onError: function (errorCode, _msg) { msg.sentStatus = RongIMLib.SentStatus.FAILED; if (_msg) { msg.messageUId = _msg.messageUId; msg.sentTime = _msg.sentTime; } if (RongIMLib.RongIMClient.MessageParams[msg.messageType].msgTag.getMessageTag() == 3) { RongIMLib.RongIMClient._memoryStore.converStore.latestMessage = msg; } RongIMLib.RongIMClient._dataAccessProvider.addMessage(conversationType, targetId, msg, { onSuccess: function (ret) { msg.messageId = ret.messageId; RongIMLib.RongIMClient._dataAccessProvider.updateMessage(msg); }, onError: function () { } }); setTimeout(function () { sendCallback.onError(errorCode, msg); }); } }, null, methodType); sendCallback.onBefore && sendCallback.onBefore(RongIMLib.MessageIdHandler.messageId); msg.messageId = RongIMLib.MessageIdHandler.messageId + ""; }; ServerDataProvider.prototype.setConnectionStatusListener = function (listener) { if (RongIMLib.RongUtil.isObject(listener) && RongIMLib.RongUtil.isFunction(listener.onChanged)) { RongIMLib.RongIMClient.statusListeners.push(listener.onChanged); } }; ServerDataProvider.prototype.setOnReceiveMessageListener = function (listener) { if (RongIMLib.RongUtil.isObject(listener) && RongIMLib.RongUtil.isFunction(listener.onReceived)) { RongIMLib.RongIMClient.messageListeners.push(listener.onReceived); } }; ServerDataProvider.prototype.registerMessageType = function (messageType, objectName, messageTag, messageContent, searchProps) { if (!messageType) { throw new Error("messageType can't be empty,postion -> registerMessageType"); } if (!objectName) { throw new Error("objectName can't be empty,postion -> registerMessageType"); } if (Object.prototype.toString.call(messageContent) == "[object Array]") { var regMsg = RongIMLib.ModelUtil.modleCreate(messageContent, messageType); RongIMLib.RongIMClient.RegisterMessage[messageType] = regMsg; } else if (Object.prototype.toString.call(messageContent) == "[object Function]" || Object.prototype.toString.call(messageContent) == "[object Object]") { if (!messageContent.encode) { throw new Error("encode method has not realized or messageName is undefined-> registerMessageType"); } if (!messageContent.decode) { throw new Error("decode method has not realized -> registerMessageType"); } } else { throw new Error("The index of 3 parameter was wrong type must be object or function or array-> registerMessageType"); } registerMessageTypeMapping[objectName] = messageType; }; ServerDataProvider.prototype.registerMessageTypes = function (messages) { var types = []; var getProtos = function (proto) { var protos = []; for (var p in proto) { protos.push(p); } return protos; }; //转换消息为自定义消息参数格式 for (var name in messages) { var message = messages[name]; var proto = message.proto; var protos = getProtos(proto); var flag = message.flag || 3; var tag = RongIMLib.MessageTag.getTagByStatus(flag); flag = new RongIMLib.MessageTag(tag.isCounted, tag.isPersited); types.push({ type: name, name: message.name, flag: flag, protos: protos }); } var register = function (message) { var type = message.type; var name = message.name; var flag = message.flag; var protos = message.protos; RongIMLib.RongIMClient.registerMessageType(type, name, flag, protos); }; for (var i = 0, len = types.length; i < len; i++) { var message = types[i]; register(message); } }; ServerDataProvider.prototype.addConversation = function (conversation, callback) { var isAdd = true; for (var i = 0, len = RongIMLib.RongIMClient._memoryStore.conversationList.length; i < len; i++) { if (RongIMLib.RongIMClient._memoryStore.conversationList[i].conversationType === conversation.conversationType && RongIMLib.RongIMClient._memoryStore.conversationList[i].targetId === conversation.targetId) { // RongIMClient._memoryStore.conversationList[i] = conversation; RongIMLib.RongIMClient._memoryStore.conversationList.unshift(RongIMLib.RongIMClient._memoryStore.conversationList.splice(i, 1)[0]); isAdd = false; break; } } if (isAdd) { RongIMLib.RongIMClient._memoryStore.conversationList.unshift(conversation); } callback && callback.onSuccess(true); }; ServerDataProvider.prototype.updateConversation = function (conversation) { var conver; for (var i = 0, len = RongIMLib.RongIMClient._memoryStore.conversationList.length; i < len; i++) { var item = RongIMLib.RongIMClient._memoryStore.conversationList[i]; if (conversation.conversationType === item.conversationType && conversation.targetId === item.targetId) { conversation.conversationTitle && (item.conversationTitle = conversation.conversationTitle); conversation.senderUserName && (item.senderUserName = conversation.senderUserName); conversation.senderPortraitUri && (item.senderPortraitUri = conversation.senderPortraitUri); conversation.latestMessage && (item.latestMessage = conversation.latestMessage); conversation.sentStatus && (item.sentStatus = conversation.sentStatus); break; } } return conver; }; ServerDataProvider.prototype.removeConversation = function (conversationType, targetId, callback) { var mod = new RongIMLib.RongIMClient.Protobuf.RelationsInput(); mod.setType(conversationType); RongIMLib.RongIMClient.bridge.queryMsg(27, RongIMLib.MessageUtil.ArrayForm(mod.toArrayBuffer()), targetId, { onSuccess: function () { var isRemoved = false; var conversations = RongIMLib.RongIMClient._memoryStore.conversationList; var len = conversations.length; for (var i = 0; i < len; i++) { if (conversations[i].conversationType == conversationType && targetId == conversations[i].targetId) { conversations.splice(i, 1); isRemoved = true; break; } } isRemoved && RongIMLib.RongIMClient._dataAccessProvider.Conversation._notify(RongIMLib.RongIMClient._memoryStore.conversationList); callback.onSuccess(true); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.getMessage = function (messageId, callback) { callback.onSuccess(new RongIMLib.Message()); }; ServerDataProvider.prototype.addMessage = function (conversationType, targetId, message, callback) { if (callback) { callback.onSuccess(message); } }; ServerDataProvider.prototype.removeMessage = function (conversationType, targetId, messages, callback) { RongIMLib.RongIMClient.getInstance().deleteRemoteMessages(conversationType, targetId, messages, callback); }; ServerDataProvider.prototype.removeLocalMessage = function (conversationType, targetId, timestamps, callback) { callback.onSuccess(true); }; ServerDataProvider.prototype.updateMessage = function (message, callback) { if (callback) { callback.onSuccess(message); } }; ServerDataProvider.prototype.deleteRemoteMessages = function (conversationType, targetId, messages, callback) { if (!RongIMLib.RongIMClient.Protobuf.DeleteMsgInput) { throw new Error('SDK Protobuf version is too low'); } var modules = new RongIMLib.RongIMClient.Protobuf.DeleteMsgInput(); var msgs = []; RongIMLib.RongUtil.forEach(messages, function (msg) { msgs.push({ msgId: msg.messageUId, msgDataTime: msg.sentTime, direct: msg.messageDirection }); }); modules.setType(conversationType); modules.setConversationId(targetId); modules.setMsgs(msgs); RongIMLib.RongIMClient.bridge.queryMsg('delMsg', RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), targetId, { onSuccess: function (result) { callback.onSuccess(result); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }, 'DeleteMsgOutput'); }; ServerDataProvider.prototype.clearRemoteHistoryMessages = function (params, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.CleanHisMsgInput(); var conversationType = params.conversationType; var _topic = { 1: 'cleanPMsg', 2: 'cleanDMsg', 3: 'cleanGMsg', 5: 'cleanCMsg', 6: 'cleanSMsg' }; var topic = _topic[conversationType]; if (!topic) { callback.onError(RongIMLib.ErrorCode.CLEAR_HIS_TYPE_ERROR); return; } var timestamp = params.timestamp; if (typeof timestamp != 'number') { callback.onError(RongIMLib.ErrorCode.CLEAR_HIS_TIME_ERROR); return; } modules.setDataTime(timestamp); var targetId = params.targetId; modules.setTargetId(targetId); RongIMLib.RongIMClient.bridge.queryMsg(topic, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), targetId, { onSuccess: function (result) { callback.onSuccess(!result); }, onError: function (error) { // error 1 历史消息云存储没有开通、传入时间大于服务器时间 清除失败,1 与其他错误码冲突,所以自定义错误码返回 if (error == 1) { error = RongIMLib.ErrorCode.CLEAR_HIS_ERROR; } setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.clearHistoryMessages = function (params, callback) { this.clearRemoteHistoryMessages(params, callback); }; // 兼容老版本 ServerDataProvider.prototype.clearMessages = function (conversationType, targetId, callback) { }; ServerDataProvider.prototype.updateMessages = function (conversationType, targetId, key, value, callback) { var me = this; if (key == "readStatus") { if (RongIMLib.RongIMClient._memoryStore.conversationList.length > 0) { me.getConversationList({ onSuccess: function (list) { Array.forEach(list, function (conver) { if (conver.conversationType == conversationType && conver.targetId == targetId) { conver.unreadMessageCount = 0; } }); }, onError: function (errorCode) { setTimeout(function () { callback.onError(errorCode); }); } }, null); } } setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.getConversation = function (conversationType, targetId, callback) { var conver = null; for (var i = 0, len = RongIMLib.RongIMClient._memoryStore.conversationList.length; i < len; i++) { if (RongIMLib.RongIMClient._memoryStore.conversationList[i].conversationType == conversationType && RongIMLib.RongIMClient._memoryStore.conversationList[i].targetId == targetId) { conver = RongIMLib.RongIMClient._memoryStore.conversationList[i]; if (RongIMLib.RongUtil.supportLocalStorage()) { // var count = RongIMClient._storageProvider.getItem("cu" + Bridge._client.userId + conversationType + targetId); var count = RongIMLib.UnreadCountHandler.get(conversationType, targetId); if (conver.unreadMessageCount == 0) { conver.unreadMessageCount = Number(count); } } } } setTimeout(function () { callback && callback.onSuccess(conver); }); return conver; }; ServerDataProvider.prototype.filterConversations = function (types, list) { var conversaions = []; RongIMLib.RongUtil.forEach(types, function (type) { RongIMLib.RongUtil.forEach(list, function (conversation) { if (conversation.conversationType == type) { conversaions.push(conversation); } }); }); return conversaions; }; ServerDataProvider.prototype.getConversationList = function (callback, conversationTypes, count, isHidden) { var that = this; var isSync = RongIMLib.RongIMClient._memoryStore.isSyncRemoteConverList; var list = RongIMLib.RongIMClient._memoryStore.conversationList; var isLocalInclude = list.length > count; if (!isSync && isLocalInclude) { setTimeout(function () { var localList = list.slice(0, count); if (conversationTypes) { localList = that.filterConversations(conversationTypes, localList); } callback.onSuccess(localList); }); return; } RongIMLib.RongIMClient.getInstance().getRemoteConversationList({ onSuccess: function (list) { if (RongIMLib.RongUtil.supportLocalStorage()) { Array.forEach(RongIMLib.RongIMClient._memoryStore.conversationList, function (item) { // var count = RongIMClient._storageProvider.getItem("cu" + Bridge._client.userId + item.conversationType + item.targetId); var count = RongIMLib.UnreadCountHandler.get(item.conversationType, item.targetId); if (item.unreadMessageCount == 0) { item.unreadMessageCount = Number(count); } }); } RongIMLib.RongIMClient._memoryStore.isSyncRemoteConverList = false; setTimeout(function () { callback.onSuccess(list); }); }, onError: function (errorcode) { setTimeout(function () { callback.onError(errorcode); }); } }, conversationTypes, count, isHidden); }; ServerDataProvider.prototype.clearCache = function () { var memoryStore = RongIMLib.RongIMClient._memoryStore || {}; memoryStore.conversationList = []; memoryStore.isSyncRemoteConverList = true; }; ServerDataProvider.prototype.clearConversations = function (conversationTypes, callback) { Array.forEach(conversationTypes, function (conversationType) { Array.forEach(RongIMLib.RongIMClient._memoryStore.conversationList, function (conver) { if (conversationType == conver.conversationType) { RongIMLib.RongIMClient.getInstance().removeConversation(conver.conversationType, conver.targetId, { onSuccess: function () { }, onError: function () { } }); } }); }); setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.setMessageContent = function (messageId, content, objectname) { }; ; ServerDataProvider.prototype.setMessageSearchField = function (messageId, content, searchFiles) { }; ; ServerDataProvider.prototype.getHistoryMessages = function (conversationType, targetId, timestamp, count, callback, objectname, order) { var config = { objectname: objectname, order: order }; RongIMLib.RongIMClient.getInstance().getRemoteHistoryMessages(conversationType, targetId, timestamp, count, callback, config); }; ServerDataProvider.prototype.getTotalUnreadCount = function (callback, conversationTypes) { var count = RongIMLib.UnreadCountHandler.getAll(conversationTypes); callback.onSuccess(count); }; ServerDataProvider.prototype.getConversationUnreadCount = function (conversationTypes, callback) { var count = 0; Array.forEach(conversationTypes, function (converType) { Array.forEach(RongIMLib.RongIMClient._memoryStore.conversationList, function (conver) { if (conver.conversationType == converType) { count += conver.unreadMessageCount; } }); }); setTimeout(function () { callback.onSuccess(count); }); }; //由于 Web 端未读消息数按会话统计,撤回消息会导致未读数不准确,提供设置未读数接口,桌面版不实现此方法 ServerDataProvider.prototype.setUnreadCount = function (conversationType, targetId, count, sentTime) { sentTime = sentTime || new Date().getTime(); RongIMLib.UnreadCountHandler.set(conversationType, targetId, count, sentTime); }; ServerDataProvider.prototype.getUnreadCount = function (conversationType, targetId, callback) { var unreadCount = RongIMLib.UnreadCountHandler.get(conversationType, targetId); setTimeout(function () { callback.onSuccess(unreadCount || 0); }); }; ServerDataProvider.prototype.cleanMentioneds = function (conver) { if (conver) { conver.mentionedMsg = null; var targetId = conver.targetId; var conversationType = conver.conversationType; var mentioneds = RongIMLib.RongIMClient._storageProvider.getItem("mentioneds_" + RongIMLib.Bridge._client.userId + '_' + conversationType + '_' + targetId); if (mentioneds) { var info = JSON.parse(mentioneds); delete info[conversationType + "_" + targetId]; if (!RongIMLib.MessageUtil.isEmpty(info)) { RongIMLib.RongIMClient._storageProvider.setItem("mentioneds_" + RongIMLib.Bridge._client.userId + '_' + conversationType + '_' + targetId, JSON.stringify(info)); } else { RongIMLib.RongIMClient._storageProvider.removeItem("mentioneds_" + RongIMLib.Bridge._client.userId + '_' + conversationType + '_' + targetId); } } } }; ServerDataProvider.prototype.clearUnreadCountByTimestamp = function (conversationType, targetId, timestamp, callback) { setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.clearUnreadCount = function (conversationType, targetId, callback) { var me = this; // RongIMClient._storageProvider.removeItem("cu" + Bridge._client.userId + conversationType + targetId); RongIMLib.UnreadCountHandler.remove(conversationType, targetId); this.getConversation(conversationType, targetId, { onSuccess: function (conver) { conver = conver || new RongIMLib.Conversation(); var isNotifyConversation = conver.unreadMessageCount; if (conver) { conver.unreadMessageCount = 0; me.cleanMentioneds(conver); } setTimeout(function () { callback.onSuccess(true); isNotifyConversation && RongIMLib.RongIMClient._dataAccessProvider.Conversation._notify(RongIMLib.RongIMClient._memoryStore.conversationList); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.clearTotalUnreadCount = function (callback) { var list = RongIMLib.RongIMClient._memoryStore.conversationList; var me = this; var isNotifyConversation = false; if (list) { // 清除 mentioneds、清除 list 中的 unreadMessageCount for (var i = 0; i < list.length; i++) { var conver = list[i]; if (conver) { isNotifyConversation = conver.unreadMessageCount ? true : isNotifyConversation; conver.unreadMessageCount = 0; me.cleanMentioneds(conver); } } } RongIMLib.UnreadCountHandler.clear(); setTimeout(function () { callback.onSuccess(true); isNotifyConversation && RongIMLib.RongIMClient._dataAccessProvider.Conversation._notify(RongIMLib.RongIMClient._memoryStore.conversationList); }); }; ServerDataProvider.prototype.setConversationToTop = function (conversationType, targetId, isTop, callback) { var me = this; this.getConversation(conversationType, targetId, { onSuccess: function (conver) { conver.isTop = isTop; me.addConversation(conver, callback); setTimeout(function () { callback.onSuccess(true); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.getConversationNotificationStatus = function (params, callback) { var targetId = params.targetId; var conversationType = params.conversationType; var notification = RongIMLib.RongIMClient._memoryStore.notification; var getKey = function () { return conversationType + '_' + targetId; }; var key = getKey(); var status = notification[key]; if (typeof status == 'number') { callback.onSuccess(status); return; } var topics = { 1: 'qryPPush', 3: 'qryDPush' }; var topic = topics[conversationType]; if (!topic) { var error = 8001; callback.onError(error); return; } var modules = new RongIMLib.RongIMClient.Protobuf.BlockPushInput(); modules.setBlockeeId(targetId); var userId = RongIMLib.Bridge._client.userId; var success = function (status) { notification[key] = status; setTimeout(function () { callback.onSuccess(status); }); }; RongIMLib.RongIMClient.bridge.queryMsg(topic, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function (status) { success(status); }, onError: function (e) { if (e == 1) { success(e); } else { setTimeout(function () { callback.onError(e); }); } } }); }; ServerDataProvider.prototype.setConversationNotificationStatus = function (params, callback) { var conversationType = params.conversationType; var targetId = params.targetId; var status = params.status; var getKey = function () { return conversationType + '_' + status; }; var topics = { '1_1': 'blkPPush', '3_1': 'blkDPush', '1_0': 'unblkPPush', '3_0': 'unblkDPush' }; var key = getKey(); var notification = RongIMLib.RongIMClient._memoryStore.notification; notification[key] = status; var topic = topics[key]; if (!topic) { var error = 8001; setTimeout(function () { callback.onError(error); }); return; } var modules = new RongIMLib.RongIMClient.Protobuf.BlockPushInput(); modules.setBlockeeId(targetId); var userId = RongIMLib.Bridge._client.userId; RongIMLib.RongIMClient.bridge.queryMsg(topic, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function (status) { setTimeout(function () { callback.onSuccess(status); }); }, onError: function (e) { setTimeout(function () { callback.onError(e); }); } }); }; ServerDataProvider.prototype.getUserStatus = function (userId, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.GetUserStatusInput(); userId = RongIMLib.Bridge._client.userId; RongIMLib.RongIMClient.bridge.queryMsg(35, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function (status) { status = RongIMLib.RongInnerTools.convertUserStatus(status); setTimeout(function () { callback.onSuccess(status); }); }, onError: function (e) { setTimeout(function () { callback.onError(e); }); } }, 'GetUserStatusOutput'); // callback.onSuccess(new UserStatus()); }; ServerDataProvider.prototype.setUserStatus = function (status, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.SetUserStatusInput(); var userId = RongIMLib.Bridge._client.userId; if (status) { modules.setStatus(status); } RongIMLib.RongIMClient.bridge.queryMsg(36, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function (status) { setTimeout(function () { callback.onSuccess(true); }); }, onError: function (e) { setTimeout(function () { callback.onError(e); }); } }, 'SetUserStatusOutput'); }; ServerDataProvider.prototype.subscribeUserStatus = function (userIds, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.SubUserStatusInput(); var userId = RongIMLib.Bridge._client.userId; modules.setUserid(userIds); RongIMLib.RongIMClient.bridge.queryMsg(37, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function (status) { setTimeout(function () { callback && callback.onSuccess(true); }); }, onError: function (e) { setTimeout(function () { callback && callback.onError(e); }); } }, 'SubUserStatusOutput'); }; ServerDataProvider.prototype.setUserStatusListener = function (params, callback) { RongIMLib.RongIMClient.userStatusListener = callback; var userIds = params.userIds || []; if (userIds.length) { RongIMLib.RongIMClient._dataAccessProvider.subscribeUserStatus(userIds); } }; ServerDataProvider.prototype.clearListeners = function () { }; ServerDataProvider.prototype.setServerInfo = function (info) { }; ServerDataProvider.prototype.getUnreadMentionedMessages = function (conversationType, targetId) { return null; }; ServerDataProvider.prototype.setConversationHidden = function (conversationType, targetId, isHidden) { }; ServerDataProvider.prototype.setMessageExtra = function (messageId, value, callback) { setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.setMessageReceivedStatus = function (messageId, receivedStatus, callback) { setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.setMessageSentStatus = function (messageId, sentStatus, callback) { setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.getAllConversations = function (callback) { setTimeout(function () { callback.onSuccess([]); }); }; ServerDataProvider.prototype.getConversationByContent = function (keywords, callback) { setTimeout(function () { callback.onSuccess([]); }); }; ServerDataProvider.prototype.getMessagesFromConversation = function (conversationType, targetId, keywords, callback) { setTimeout(function () { callback.onSuccess([]); }); }; ServerDataProvider.prototype.searchConversationByContent = function (keyword, callback, conversationTypes) { setTimeout(function () { callback.onSuccess([]); }); }; ServerDataProvider.prototype.searchMessageByContent = function (conversationType, targetId, keyword, timestamp, count, total, callback) { setTimeout(function () { callback.onSuccess([]); }); }; ServerDataProvider.prototype.getDelaTime = function () { return RongIMLib.RongIMClient._memoryStore.deltaTime; }; ServerDataProvider.prototype.getCurrentConnectionStatus = function () { var client = RongIMLib.Bridge._client || {}; var channel = client.channel || {}; var status = RongIMLib.ConnectionStatus.CONNECTION_CLOSED; if (typeof channel.connectionStatus == 'number') { status = channel.connectionStatus; } return status; }; ServerDataProvider.prototype.getAgoraDynamicKey = function (engineType, channelName, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.VoipDynamicInput(); modules.setEngineType(engineType); modules.setChannelName(channelName); RongIMLib.RongIMClient.bridge.queryMsg(32, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (result) { setTimeout(function () { callback.onSuccess(result); }); }, onError: function (errorCode) { setTimeout(function () { callback.onError(errorCode); }); } }, "VoipDynamicOutput"); }; ServerDataProvider.prototype.setDeviceInfo = function (deviceId) { }; ServerDataProvider.prototype.setEnvironment = function (isPrivate) { }; ServerDataProvider.prototype.clearData = function () { return true; }; ServerDataProvider.prototype.getPublicServiceProfile = function (publicServiceType, publicServiceId, callback) { var profile = RongIMLib.RongIMClient._memoryStore.publicServiceMap.get(publicServiceType, publicServiceId); setTimeout(function () { callback.onSuccess(profile); }); }; ServerDataProvider.prototype.getRemotePublicServiceList = function (callback, pullMessageTime) { if (RongIMLib.RongIMClient._memoryStore.depend.openMp) { var modules = new RongIMLib.RongIMClient.Protobuf.PullMpInput(), self = this; if (!pullMessageTime) { modules.setTime(0); } else { modules.setTime(pullMessageTime); } modules.setMpid(""); RongIMLib.RongIMClient.bridge.queryMsg(28, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (data) { //TODO 找出最大时间 // self.lastReadTime.set(conversationType + targetId, MessageUtil.int64ToTimestamp(data.syncTime)); RongIMLib.RongIMClient._memoryStore.publicServiceMap.publicServiceList.length = 0; RongIMLib.RongIMClient._memoryStore.publicServiceMap.publicServiceList = data; setTimeout(function () { callback && callback.onSuccess(data); }); }, onError: function (errorCode) { setTimeout(function () { callback && callback.onError(errorCode); }); } }, "PullMpOutput"); } }; ServerDataProvider.prototype.getRTCUserInfoList = function (room, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcQueryListInput(); // 1 是正序,2是倒序 modules.setOrder(2); RongIMLib.RongIMClient.bridge.queryMsg("rtcUData", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function (result) { var users = {}; var list = result.list; RongIMLib.RongUtil.forEach(list, function (item) { var userId = item.userId; var tmpData = {}; RongIMLib.RongUtil.forEach(item.userData, function (data) { var key = data.key; var value = data.value; tmpData[key] = value; }); users[userId] = tmpData; }); callback.onSuccess(users); }, onError: function (errorCode) { callback.onError(errorCode); } }, "RtcUserListOutput"); }; ServerDataProvider.prototype.getRTCUserList = function (room, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcQueryListInput(); modules.setOrder(2); RongIMLib.RongIMClient.bridge.queryMsg("rtcUList", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function (result) { callback.onSuccess({ users: result.list }); }, onError: function (errorCode) { callback.onError(errorCode); } }, "RtcUserListOutput"); }; ServerDataProvider.prototype.setRTCUserInfo = function (room, info, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcValueInfo(); modules.setKey(info.key); modules.setValue(info.value); RongIMLib.RongIMClient.bridge.queryMsg("rtcUPut", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function () { callback.onSuccess(true); }, onError: function (errorCode) { callback.onError(errorCode); } }); }; ServerDataProvider.prototype.removeRTCUserInfo = function (room, info, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcKeyDeleteInput(); var keys = info.keys || []; if (!RongIMLib.RongUtil.isArray(keys)) { keys = [keys]; } modules.setKey(keys); RongIMLib.RongIMClient.bridge.queryMsg("rtcUDel", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function () { callback.onSuccess(true); }, onError: function (errorCode) { callback.onError(errorCode); } }); }; ServerDataProvider.prototype.getRTCRoomInfo = function (room, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcQueryListInput(); modules.setOrder(2); RongIMLib.RongIMClient.bridge.queryMsg("rtcRInfo", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function (result) { var room = { id: result.roomId, total: result.userCount }; RongIMLib.RongUtil.forEach(result.roomData, function (data) { room[data.key] = data.value; }); callback.onSuccess(room); }, onError: function (errorCode) { callback.onError(errorCode); } }, "RtcRoomInfoOutput"); }; ServerDataProvider.prototype.setRTCRoomInfo = function (room, info, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcValueInfo(); modules.setKey(info.key); modules.setValue(info.value); RongIMLib.RongIMClient.bridge.queryMsg("rtcRPut", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function () { callback.onSuccess(true); }, onError: function (errorCode) { callback.onError(errorCode); } }); }; ServerDataProvider.prototype.removeRTCRoomInfo = function (room, info, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcKeyDeleteInput(); var keys = info.keys || []; if (!RongIMLib.RongUtil.isArray(keys)) { keys = [keys]; } modules.setKey(keys); RongIMLib.RongIMClient.bridge.queryMsg("rtcRDel", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function () { callback.onSuccess(true); }, onError: function (errorCode) { callback.onError(errorCode); } }); }; ServerDataProvider.prototype.joinRTCRoom = function (room, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcInput(); var mode = room.mode || 0; modules.setRoomType(mode); if (room.broadcastType) { modules.setBroadcastType(room.broadcastType); } RongIMLib.RongIMClient.bridge.queryMsg("rtcRJoin_data", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function (result) { var users = {}; var list = result.list, token = result.token, sessionId = result.sessionId; RongIMLib.RongUtil.forEach(list, function (item) { var userId = item.userId; var tmpData = {}; RongIMLib.RongUtil.forEach(item.userData, function (data) { var key = data.key; var value = data.value; tmpData[key] = value; }); users[userId] = tmpData; }); callback.onSuccess({ users: users, token: token, sessionId: sessionId }); }, onError: function (errorCode) { callback.onError(errorCode); } }, "RtcUserListOutput"); }; ServerDataProvider.prototype.quitRTCRoom = function (room, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.SetUserStatusInput(); RongIMLib.RongIMClient.bridge.queryMsg("rtcRExit", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function () { callback.onSuccess(true); }, onError: function (errorCode) { callback.onError(errorCode); } }); }; ServerDataProvider.prototype.RTCPing = function (room, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcInput(); var mode = room.mode || 0; modules.setRoomType(mode); if (room.broadcastType) { modules.setBroadcastType(room.broadcastType); } RongIMLib.RongIMClient.bridge.queryMsg("rtcPing", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, callback); }; ServerDataProvider.prototype.setRTCData = function (roomId, key, value, isInner, apiType, callback, message) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcSetDataInput(); modules.setInterior(isInner); modules.setTarget(apiType); modules.setKey(key); modules.setValue(value); message = message || {}; var name = message.name; var content = message.content; if (name) { modules.setObjectName(name); } if (content) { if (!RongIMLib.RongUtil.isString(content)) { content = JSON.stringify(content); } modules.setContent(content); } RongIMLib.RongIMClient.bridge.queryMsg("rtcSetData", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), roomId, callback, "RtcOutput"); }; ServerDataProvider.prototype.getRTCData = function (roomId, keys, isInner, apiType, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcDataInput(); modules.setInterior(isInner); modules.setTarget(apiType); modules.setKey(keys); RongIMLib.RongIMClient.bridge.queryMsg("rtcQryData", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), roomId, { onSuccess: function (result) { var props = {}; var list = result.outInfo; RongIMLib.RongUtil.forEach(list, function (item) { props[item.key] = item.value; }); callback.onSuccess(props); }, onError: callback.onError }, "RtcQryOutput"); }; ServerDataProvider.prototype.removeRTCData = function (roomId, keys, isInner, apiType, callback, message) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcDataInput(); modules.setInterior(isInner); modules.setTarget(apiType); modules.setKey(keys); message = message || {}; var name = message.name; var content = message.content; if (name) { modules.setObjectName(name); } if (content) { if (!RongIMLib.RongUtil.isString(content)) { content = JSON.stringify(content); } modules.setContent(content); } RongIMLib.RongIMClient.bridge.queryMsg("rtcDelData", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), roomId, callback, "RtcOutput"); }; ServerDataProvider.prototype.setRTCUserData = function (roomId, key, value, isInner, callback, message) { this.setRTCData(roomId, key, value, isInner, RongIMLib.RTCAPIType.PERSON, callback, message); }; ServerDataProvider.prototype.getRTCUserData = function (roomId, keys, isInner, callback, message) { this.getRTCData(roomId, keys, isInner, RongIMLib.RTCAPIType.PERSON, callback); }; ServerDataProvider.prototype.removeRTCUserData = function (roomId, keys, isInner, callback, message) { this.removeRTCData(roomId, keys, isInner, RongIMLib.RTCAPIType.PERSON, callback, message); }; ServerDataProvider.prototype.setRTCRoomData = function (roomId, key, value, isInner, callback, message) { this.setRTCData(roomId, key, value, isInner, RongIMLib.RTCAPIType.ROOM, callback, message); }; ServerDataProvider.prototype.getRTCRoomData = function (roomId, keys, isInner, callback, message) { this.getRTCData(roomId, keys, isInner, RongIMLib.RTCAPIType.ROOM, callback); }; ServerDataProvider.prototype.removeRTCRoomData = function (roomId, keys, isInner, callback, message) { this.removeRTCData(roomId, keys, isInner, RongIMLib.RTCAPIType.ROOM, callback, message); }; // 信令 SDK 新增 ServerDataProvider.prototype.setRTCOutData = function (roomId, data, type, callback, message) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcSetOutDataInput(); modules.setTarget(type); if (!RongIMLib.RongUtil.isArray(data)) { data = [data]; } for (var i = 0; i < data.length; i++) { var item = data[i]; if (item.key) { item.key = item.key.toString(); } if (item.value) { item.value = item.value.toString(); } } modules.setValueInfo(data); message = message || {}; var name = message.name; var content = message.content; if (name) { modules.setObjectName(name); } if (content) { if (!RongIMLib.RongUtil.isString(content)) { content = JSON.stringify(content); } modules.setContent(content); } RongIMLib.RongIMClient.bridge.queryMsg("rtcSetOutData", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), roomId, callback, "RtcOutput"); }; // 信令 SDK 新增 ServerDataProvider.prototype.getRTCOutData = function (roomId, userIds, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcQryUserOutDataInput(); modules.setUserId(userIds); RongIMLib.RongIMClient.bridge.queryMsg("rtcQryUserOutData", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), roomId, callback, "RtcUserOutDataOutput"); }; ServerDataProvider.prototype.getNavi = function () { var navi = RongIMLib.RongIMClient._storageProvider.getItem("fullnavi") || "{}"; return JSON.parse(navi); }; ServerDataProvider.prototype.getRTCToken = function (room, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcInput(); var mode = room.mode || 0; modules.setRoomType(mode); if (room.broadcastType) { modules.setBroadcastType(room.broadcastType); } RongIMLib.RongIMClient.bridge.queryMsg("rtcToken", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function (result) { callback.onSuccess(result); }, onError: function (errorCode) { callback.onError(errorCode); } }, "RtcTokenOutput"); }; ServerDataProvider.prototype.setRTCState = function (room, content, callback) { // MCFollowInput 为 PB 复用,字段:一个必传 string(第一位) var modules = new RongIMLib.RongIMClient.Protobuf.MCFollowInput(); var report = content.report; modules.setId(report); RongIMLib.RongIMClient.bridge.queryMsg("rtcUserState", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function (result) { callback.onSuccess(result); }, onError: function (errorCode) { callback.onError(errorCode); } }, "RtcOutput"); }; return ServerDataProvider; })(); RongIMLib.ServerDataProvider = ServerDataProvider; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var VCDataProvider = (function () { function VCDataProvider(addon) { this.Conversation = { watcher: new RongIMLib.Observer(), watch: function (_watcher) { }, unwatch: function (_watcher) { }, _notify: function (conversationList) { } }; // C++ 需要的 SDK 版本号 this.version = '2.8.27'; this.userId = ""; this.useConsole = false; this.appKey = ""; this.token = ""; this.connectionStatus = RongIMLib.ConnectionStatus.DISCONNECTED; this.addon = addon; } VCDataProvider.prototype.init = function (appKey, config) { this.appKey = appKey; this.useConsole && console.log("init"); config = config || {}; config.version = this.version; var sdkInfo = this.addon.initWithAppkey(appKey, config.dbPath, config); if (sdkInfo) { sdkInfo = JSON.parse(sdkInfo); } // 0 不存不计数 1 只存不计数 3 存且计数 this.addon.registerMessageType("RC:VcMsg", 3); this.addon.registerMessageType("RC:ImgTextMsg", 3); this.addon.registerMessageType("RC:FileMsg", 3); this.addon.registerMessageType("RC:LBSMsg", 3); this.addon.registerMessageType("RC:PSImgTxtMsg", 3); this.addon.registerMessageType("RC:PSMultiImgTxtMsg", 3); this.addon.registerMessageType("RCJrmf:RpMsg", 3); this.addon.registerMessageType("RCJrmf:RpOpendMsg", 1); this.addon.registerMessageType("RC:GrpNtf", 1); this.addon.registerMessageType("RC:DizNtf", 0); this.addon.registerMessageType("RC:InfoNtf", 0); this.addon.registerMessageType("RC:ContactNtf", 0); this.addon.registerMessageType("RC:ProfileNtf", 0); this.addon.registerMessageType("RC:CmdNtf", 0); this.addon.registerMessageType("RC:CmdMsg", 0); this.addon.registerMessageType("RC:TypSts", 0); this.addon.registerMessageType("RC:CsChaR", 0); this.addon.registerMessageType("RC:CsHsR", 0); this.addon.registerMessageType("RC:CsEnd", 0); this.addon.registerMessageType("RC:CsSp", 0); this.addon.registerMessageType("RC:CsUpdate", 0); this.addon.registerMessageType("RC:CsContact", 0); this.addon.registerMessageType("RC:ReadNtf", 0); this.addon.registerMessageType("RC:VCAccept", 0); this.addon.registerMessageType("RC:VCRinging", 0); this.addon.registerMessageType("RC:VCSummary", 0); this.addon.registerMessageType("RC:VCHangup", 0); this.addon.registerMessageType("RC:VCInvite", 0); this.addon.registerMessageType("RC:VCModifyMedia", 0); this.addon.registerMessageType("RC:VCModifyMem", 0); this.addon.registerMessageType("RC:PSCmd", 0); this.addon.registerMessageType("RC:RcCmd", 0); this.addon.registerMessageType("RC:SRSMsg", 0); this.addon.registerMessageType("RC:RRReqMsg", 0); this.addon.registerMessageType("RC:RRRspMsg", 0); return sdkInfo; }; VCDataProvider.prototype.connect = function (token, callback, userId, serverConf) { this.useConsole && console.log("connect"); this.userId = userId; this.connectCallback = callback; RongIMLib.Bridge._client = { userId: userId, token: token }; serverConf = serverConf || {}; var openmp = !!serverConf.openMp; var openus = !!serverConf.openUS; if (serverConf.type) { this.addon.setEnvironment(true); } var me = this; // this.addon.connectWithToken(token, userId, serverConf.serverList, openmp, openus); this.addon.connectWithToken(token, userId, function (userId) { me.userId = userId; RongIMLib.Bridge._client.userId = userId; }); }; VCDataProvider.prototype.setServerInfo = function (info) { 'setServerInfo' in this.addon && this.addon.setServerInfo(info.navi); }; VCDataProvider.prototype.logout = function () { this.useConsole && console.log("logout"); this.disconnect(); }; VCDataProvider.prototype.disconnect = function () { this.useConsole && console.log("disconnect"); this.connectionStatus = RongIMLib.ConnectionStatus.DISCONNECTED; this.addon.disconnect(true); }; VCDataProvider.prototype.clearListeners = function () { this.addon.setOnReceiveStatusListener(); this.addon.setConnectionStatusListener(); this.addon.setOnReceiveMessageListener(); }; VCDataProvider.prototype.clearData = function () { this.useConsole && console.log("clearData"); return this.addon.clearData(); }; VCDataProvider.prototype.setConnectionStatusListener = function (listener) { var me = this; /** ConnectionStatus_TokenIncorrect = 31004, ConnectionStatus_Connected = 0, ConnectionStatus_KickedOff = 6, // 其他设备登录 ConnectionStatus_Connecting = 10,// 连接中 ConnectionStatus_SignUp = 12, // 未登录 ConnectionStatus_NetworkUnavailable = 1, // 连接断开 ConnectionStatus_ServerInvalid = 8, // 断开 ConnectionStatus_ValidateFailure = 9,//断开 ConnectionStatus_Unconnected = 11,//断开 ConnectionStatus_DisconnExecption = 31011 //断开 RC_NAVI_MALLOC_ERROR = 30000,//断开 RC_NAVI_NET_UNAVAILABLE= 30002,//断开 RC_NAVI_SEND_FAIL = 30004,//断开 RC_NAVI_REQ_TIMEOUT = 30005,//断开 RC_NAVI_RECV_FAIL = 30006,//断开 RC_NAVI_RESOURCE_ERROR = 30007,//断开 RC_NAVI_NODE_NOT_FOUND = 30008,//断开 RC_NAVI_DNS_ERROR = 30009,//断开 */ me.connectListener = listener; this.useConsole && console.log("setConnectionStatusListener"); me.addon && me.addon.setConnectionStatusListener(function (result) { var isCurrentConnected = me.connectionStatus === RongIMLib.ConnectionStatus.CONNECTED; var code = result; switch (result) { case 10: code = RongIMLib.ConnectionStatus.CONNECTING; break; case 31004: setTimeout(function () { me.connectCallback.onTokenIncorrect(); }); return; case 1: case 8: case 9: case 11: case 12: case 31011: case 30000: case 30002: case 30010: if (!isCurrentConnected) { return; } code = RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE; break; case 0: case 33005: code = RongIMLib.ConnectionStatus.CONNECTED; setTimeout(function () { me.connectCallback.onSuccess(me.userId); }); break; case 6: code = RongIMLib.ConnectionStatus.KICKED_OFFLINE_BY_OTHER_CLIENT; break; default: code = result; break; } me.connectionStatus = code; setTimeout(function () { listener.onChanged(code); }); }); }; VCDataProvider.prototype.setOnReceiveMessageListener = function (listener) { var me = this, localCount = 0; me.messageListener = listener; this.useConsole && console.log("setOnReceiveMessageListener"); me.addon && me.addon.setOnReceiveMessageListener(function (result, leftCount, offline, hasMore) { var message = me.buildMessage(result); message.offLineMessage = offline; setTimeout(function () { var voipMsgTypes = ['AcceptMessage', 'RingingMessage', 'HungupMessage', 'InviteMessage', 'MediaModifyMessage', 'MemberModifyMessage']; var isVoIPMsg = voipMsgTypes.indexOf(message.messageType) > -1; if (isVoIPMsg) { RongIMLib.RongIMClient._voipProvider && RongIMLib.RongIMClient._voipProvider.onReceived(message); } else if (message.conversationType == 12) { RongIMLib.RongIMClient.RTCListener(message); RongIMLib.RongIMClient.RTCInnerListener(message); RongIMLib.RongIMClient.RTCSignalLisener(message); } else { listener.onReceived(message, leftCount, hasMore); } }); }); }; VCDataProvider.prototype.sendTypingStatusMessage = function (conversationType, targetId, messageName, sendCallback) { var me = this; this.useConsole && console.log("sendTypingStatusMessage"); if (messageName in RongIMLib.RongIMClient.MessageParams) { me.sendMessage(conversationType, targetId, RongIMLib.TypingStatusMessage.obtain(RongIMLib.RongIMClient.MessageParams[messageName].objectName, ""), { onSuccess: function () { setTimeout(function () { sendCallback.onSuccess(); }); }, onError: function (errorCode) { setTimeout(function () { sendCallback.onError(errorCode, null); }); }, onBefore: function () { } }); } }; VCDataProvider.prototype.setMessageStatus = function (conversationType, targetId, timestamp, status, callback) { this.addon.updateMessageReceiptStatus(conversationType, targetId, timestamp); callback.onSuccess(true); }; VCDataProvider.prototype.sendTextMessage = function (conversationType, targetId, content, sendMessageCallback) { var msgContent = RongIMLib.TextMessage.obtain(content); this.useConsole && console.log("sendTextMessage"); this.sendMessage(conversationType, targetId, msgContent, sendMessageCallback); }; VCDataProvider.prototype.getRemoteHistoryMessages = function (conversationType, targetId, timestamp, count, callback, config) { try { var me = this; me.useConsole && console.log("getRemoteHistoryMessages"); me.addon.getRemoteHistoryMessages(conversationType, targetId, timestamp ? timestamp : 0, count, function (ret, hasMore) { var list = ret ? JSON.parse(ret).list : [], msgs = []; list.reverse(); for (var i = 0, len = list.length; i < len; i++) { var message = me.buildMessage(list[i].obj); message.sentStatus = RongIMLib.SentStatus.READ; msgs[i] = message; } callback.onSuccess(msgs, hasMore ? true : false); }, function (errorCode) { callback.onError(errorCode); }); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.getRemoteConversationList = function (callback, conversationTypes, count, isGetHiddenConvers) { try { this.useConsole && console.log("getRemoteConversationList"); var converTypes = conversationTypes || [1, 2, 3, 4, 5, 6, 7, 8]; var result = this.addon.getConversationList(converTypes); var list = JSON.parse(result).list, convers = [], me = this, index = 0; list.reverse(); isGetHiddenConvers = typeof isGetHiddenConvers === 'boolean' ? isGetHiddenConvers : false; for (var i = 0, len_1 = list.length; i < len_1; i++) { var tmpObj = list[i].obj, obj = JSON.parse(tmpObj); if (obj != "") { if (obj.isHidden == 1 && isGetHiddenConvers) { continue; } convers[index] = me.buildConversation(tmpObj); index++; } } convers.reverse(); var len = convers.length; count = count || len; if (len > count) { convers.length = count; } callback.onSuccess(convers); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.removeConversation = function (conversationType, targetId, callback) { try { this.useConsole && console.log("removeConversation"); this.addon.removeConversation(conversationType, targetId); var conversations = RongIMLib.RongIMClient._memoryStore.conversationList; var len = conversations.length; for (var i = 0; i < len; i++) { if (conversations[i].conversationType == conversationType && targetId == conversations[i].targetId) { conversations.splice(i, 1); break; } } callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.joinChatRoom = function (chatRoomId, messageCount, callback) { this.useConsole && console.log("joinChatRoom"); this.addon.joinChatRoom(chatRoomId, messageCount, function () { callback.onSuccess(); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.quitChatRoom = function (chatRoomId, callback) { this.useConsole && console.log("quitChatRoom"); this.addon.quitChatRoom(chatRoomId, function () { callback.onSuccess(); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.setChatroomEntry = function (chatroomId, chatroomEntry, callback) { }; VCDataProvider.prototype.forceSetChatroomEntry = function (chatroomId, chatroomEntry, callback) { }; VCDataProvider.prototype.getChatroomEntry = function (chatroomId, key, callback) { }; VCDataProvider.prototype.getAllChatroomEntries = function (chatroomId, callback) { }; VCDataProvider.prototype.removeChatroomEntry = function (chatroomId, chatroomEntry, callback) { }; VCDataProvider.prototype.forceRemoveChatroomEntry = function (chatroomId, chatroomEntry, callback) { }; VCDataProvider.prototype.pullChatroomEntry = function (chatroomId, time, callback) { }; VCDataProvider.prototype.addToBlacklist = function (userId, callback) { this.useConsole && console.log("addToBlacklist"); this.addon.addToBlacklist(userId, function () { callback.onSuccess(); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.getBlacklist = function (callback) { this.useConsole && console.log("getBlacklist"); this.addon.getBlacklist(function (blacklistors) { callback.onSuccess(blacklistors); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.getBlacklistStatus = function (userId, callback) { this.useConsole && console.log("getBlacklistStatus"); this.addon.getBlacklistStatus(userId, function (result) { callback.onSuccess(result); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.removeFromBlacklist = function (userId, callback) { this.useConsole && console.log("removeFromBlacklist"); this.addon.removeFromBlacklist(userId, function () { callback.onSuccess(); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.sendMessage = function (conversationType, targetId, messageContent, sendCallback, mentiondMsg, pushText, appData, methodType, params) { var me = this, users = []; me.useConsole && console.log("sendMessage"); params = params || {}; var isGroup = (conversationType == RongIMLib.ConversationType.DISCUSSION || conversationType == RongIMLib.ConversationType.GROUP); if (isGroup && messageContent.messageName == RongIMLib.RongIMClient.MessageType["ReadReceiptResponseMessage"]) { users = []; var rspMsg = messageContent; if (rspMsg.receiptMessageDic) { var ids = []; for (var key in rspMsg.receiptMessageDic) { ids.push(key); } users = ids; } } if (isGroup && messageContent.messageName == RongIMLib.RongIMClient.MessageType["SyncReadStatusMessage"]) { users = []; users.push(me.userId); } var userIds = params.userIds; if (isGroup && userIds) { users = userIds; } var msg = me.addon.sendMessage(conversationType, targetId, RongIMLib.RongIMClient.MessageParams[messageContent.messageName].objectName, messageContent.encode(), pushText || "", appData || "", function (progress) { }, function (message, code) { var msg = me.buildMessage(message); var errorCode = RongIMLib.ErrorCode.SENSITIVE_REPLACE; if (code == errorCode) { return sendCallback.onError(errorCode, msg); } sendCallback.onSuccess(msg); }, function (message, code) { sendCallback.onError(code, me.buildMessage(message)); }, users, mentiondMsg); var tempMessage = JSON.parse(msg); sendCallback.onBefore && sendCallback.onBefore(tempMessage.messageId); RongIMLib.MessageIdHandler.messageId = tempMessage.messageId; }; VCDataProvider.prototype.registerMessageType = function (messageType, objectName, messageTag, messageContent, searchProps) { this.useConsole && console.log("registerMessageType"); this.addon.registerMessageType(objectName, messageTag.getMessageTag(), searchProps); var regMsg = RongIMLib.ModelUtil.modleCreate(messageContent, messageType); RongIMLib.RongIMClient.RegisterMessage[messageType] = regMsg; RongIMLib.RongIMClient.RegisterMessage[messageType].messageName = messageType; registerMessageTypeMapping[objectName] = messageType; RongIMLib.RongIMClient.MessageType[messageType] = messageType; RongIMLib.RongIMClient.MessageParams[messageType] = { objectName: objectName, msgTag: messageTag }; typeMapping[objectName] = messageType; }; VCDataProvider.prototype.registerMessageTypes = function (messages) { var types = []; var getProtos = function (proto) { var protos = []; for (var p in proto) { protos.push(p); } return protos; }; //转换消息为自定义消息参数格式 for (var name in messages) { var message = messages[name]; var proto = message.proto; var protos = getProtos(proto); var flag = message.flag || 3; var tag = RongIMLib.MessageTag.getTagByStatus(flag); flag = new RongIMLib.MessageTag(tag.isCounted, tag.isPersited); types.push({ type: name, name: message.name, flag: flag, protos: protos }); } var register = function (message) { var type = message.type; var name = message.name; var flag = message.flag; var protos = message.protos; RongIMLib.RongIMClient.registerMessageType(type, name, flag, protos); }; for (var i = 0, len = types.length; i < len; i++) { var message = types[i]; register(message); } }; VCDataProvider.prototype.addMessage = function (conversationType, targetId, message, callback) { this.useConsole && console.log("addMessage"); var direction = message.direction; var msg = this.addon.insertMessage(conversationType, targetId, message.senderUserId, message.objectName, JSON.stringify(message.content), function () { callback.onSuccess(me.buildMessage(msg)); }, function () { callback.onError(RongIMLib.ErrorCode.MSG_INSERT_ERROR); }, direction), me = this; }; VCDataProvider.prototype.removeMessage = function (conversationType, targetId, messages, callback) { }; VCDataProvider.prototype.deleteRemoteMessages = function (conversationType, targetId, messages, callback) { }; VCDataProvider.prototype.removeLocalMessage = function (conversationType, targetId, timestamps, callback) { try { this.useConsole && console.log("removeLocalMessage"); this.addon.deleteMessages(timestamps); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.getMessage = function (messageId, callback) { try { this.useConsole && console.log("getMessage"); var msg = this.buildMessage(this.addon.getMessage(messageId)); callback.onSuccess(msg); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.clearMessages = function (conversationType, targetId, callback) { try { this.useConsole && console.log("clearMessages"); this.addon.clearMessages(conversationType, targetId); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; // Web 端接口,桌面版无需实现 VCDataProvider.prototype.setUnreadCount = function (conversationType, targetId, count) { }; VCDataProvider.prototype.getConversation = function (conversationType, targetId, callback) { try { this.useConsole && console.log("getConversation"); var ret = this.addon.getConversation(conversationType, targetId); callback.onSuccess(this.buildConversation(ret)); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.getConversationList = function (callback, conversationTypes, count, isGetHiddenConvers) { this.useConsole && console.log("getConversationList"); this.getRemoteConversationList(callback, conversationTypes, count, isGetHiddenConvers); }; VCDataProvider.prototype.clearCache = function () { var memoryStore = RongIMLib.RongIMClient._memoryStore || {}; memoryStore.conversationList = []; memoryStore.isSyncRemoteConverList; }; VCDataProvider.prototype.clearConversations = function (conversationTypes, callback) { try { this.useConsole && console.log("clearConversations"); this.addon.clearConversations(); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.setMessageContent = function (messageId, content, objectName) { content = JSON.stringify(content); this.addon.setMessageContent(messageId, content, objectName); }; VCDataProvider.prototype.setMessageSearchField = function (messageId, content, searchFiles) { content = JSON.stringify(content); this.addon.setMessageContent(messageId, content, searchFiles); }; VCDataProvider.prototype.getHistoryMessages = function (conversationType, targetId, timestamp, count, callback, objectname, direction) { this.useConsole && console.log("getHistoryMessages"); if (count <= 0) { callback.onError(RongIMLib.ErrorCode.TIMEOUT); return; } objectname = objectname || ''; direction = typeof direction == 'undefined' || direction; try { var ret = this.addon.getHistoryMessages(conversationType, targetId, timestamp ? timestamp : 0, count, objectname, direction); var list = ret ? JSON.parse(ret).list : [], msgs = [], me = this; list.reverse(); for (var i = 0, len = list.length; i < len; i++) { var message = me.buildMessage(list[i].obj); msgs[i] = message; } callback.onSuccess(msgs, len == count); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.clearRemoteHistoryMessages = function (params, callback) { var conversationType = params.conversationType; var targetId = params.targetId; var timestamp = params.timestamp; var _topic = { 1: true, 2: true, 3: true, 5: true, 6: true }; var topic = _topic[conversationType]; if (!topic) { callback.onError(RongIMLib.ErrorCode.CLEAR_HIS_TYPE_ERROR); return; } if (typeof timestamp != 'number') { callback.onError(RongIMLib.ErrorCode.CLEAR_HIS_TIME_ERROR); return; } this.addon.clearRemoteHistoryMessages(+conversationType, targetId, timestamp, function () { callback.onSuccess(true); }, function (errorCode) { if (errorCode == 1) { // 没有开通历史消息云存储 errorCode = RongIMLib.ErrorCode.CLEAR_HIS_ERROR; } callback.onError(errorCode); }); }; VCDataProvider.prototype.clearHistoryMessages = function (params, callback) { var conversationType = +params.conversationType; var targetId = params.targetId; try { this.addon.clearMessages(conversationType, targetId); var isSuccess = true; callback.onSuccess(isSuccess); } catch (e) { console.log(e); callback.onError(RongIMLib.ErrorCode.CLEAR_HIS_ERROR); } }; VCDataProvider.prototype.getTotalUnreadCount = function (callback, conversationTypes) { try { var result; this.useConsole && console.log("getTotalUnreadCount"); if (conversationTypes) { result = this.addon.getTotalUnreadCount(conversationTypes); } else { result = this.addon.getTotalUnreadCount(); } callback.onSuccess(result); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.getConversationUnreadCount = function (conversationTypes, callback) { this.useConsole && console.log("getConversationUnreadCount"); this.getTotalUnreadCount(callback, conversationTypes); }; VCDataProvider.prototype.getUnreadCount = function (conversationType, targetId, callback) { try { this.useConsole && console.log("getUnreadCount"); var result = this.addon.getUnreadCount(conversationType, targetId); callback.onSuccess(result); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.clearUnreadCount = function (conversationType, targetId, callback) { try { this.useConsole && console.log("clearUnreadCount"); var result = this.addon.clearUnreadCount(conversationType, targetId); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.clearTotalUnreadCount = function (callback) { this.useConsole && console.log("clearTotalUnreadCount"); }; VCDataProvider.prototype.clearUnreadCountByTimestamp = function (conversationType, targetId, timestamp, callback) { try { this.useConsole && console.log("clearUnreadCountByTimestamp"); var result = this.addon.clearUnreadCountByTimestamp(conversationType, targetId, timestamp); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.setConversationToTop = function (conversationType, targetId, isTop, callback) { try { this.useConsole && console.log("setConversationToTop"); this.addon.setConversationToTop(conversationType, targetId, isTop); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.setConversationHidden = function (conversationType, targetId, isHidden) { this.addon.setConversationHidden(conversationType, targetId, isHidden); }; VCDataProvider.prototype.setMessageReceivedStatus = function (messageId, receivedStatus, callback) { try { this.useConsole && console.log("setMessageReceivedStatus"); this.addon.setMessageReceivedStatus(messageId, receivedStatus); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.setMessageSentStatus = function (messageId, sentStatus, callback) { try { this.useConsole && console.log("setMessageSentStatus"); this.addon.setMessageSentStatus(messageId, sentStatus); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.getFileToken = function (fileType, callback) { this.useConsole && console.log("getFileToken"); this.addon.getUploadToken(fileType, function (token) { callback.onSuccess({ token: token }); }, function (errorCode) { callback.onError(errorCode); }); }; VCDataProvider.prototype.getFileUrl = function (fileType, fileName, oriName, callback) { this.useConsole && console.log("getFileUrl"); this.addon.getDownloadUrl(fileType, fileName, oriName, function (url) { callback.onSuccess({ downloadUrl: url }); }, function (errorCode) { callback.onError(errorCode); }); }; VCDataProvider.prototype.getPullSetting = function (callback) { this.useConsole && console.log("getPullSetting"); }; VCDataProvider.prototype.setOfflineMessageDuration = function (duration, callback) { this.useConsole && console.log("setOfflineMessageDuration"); }; VCDataProvider.prototype.searchConversationByContent = function (keyword, callback, conversationTypes) { var converTypes = []; if (typeof conversationTypes == 'undefined') { converTypes = [1, 2, 3, 4, 5, 6, 7]; } else { converTypes = conversationTypes; } try { this.useConsole && console.log("searchConversationByContent"); var result = this.addon.searchConversationByContent(converTypes, keyword); var list = JSON.parse(result).list, convers = [], me = this; list.reverse(); for (var i = 0, len = list.length; i < len; i++) { convers[i] = me.buildConversation(list[i].obj); } callback.onSuccess(convers); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.searchMessageByContent = function (conversationType, targetId, keyword, timestamp, count, total, callback) { var me = this; try { this.useConsole && console.log("searchMessageByContent"); this.addon.searchMessageByContent(conversationType, targetId, keyword, timestamp, count, total, function (ret, matched) { var list = ret ? JSON.parse(ret).list : [], msgs = []; list.reverse(); for (var i = 0, len = list.length; i < len; i++) { msgs[i] = me.buildMessage(list[i].obj); } callback.onSuccess(msgs, matched); }); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.getChatRoomInfo = function (chatRoomId, count, order, callback) { this.useConsole && console.log("getChatRoomInfo"); this.addon.getChatroomInfo(chatRoomId, count, order, function (ret, count) { var list = ret ? JSON.parse(ret).list : [], chatRoomInfo = { userInfos: [], userTotalNums: count }; if (list.length > 0) { for (var i = 0, len = list.length; i < len; i++) { chatRoomInfo.userInfos.push(JSON.parse(list[i].obj)); } } callback.onSuccess(chatRoomInfo); }, function (errcode) { callback.onError(errcode); }); }; VCDataProvider.prototype.setChatroomHisMessageTimestamp = function (chatRoomId, timestamp) { }; VCDataProvider.prototype.getChatRoomHistoryMessages = function (chatRoomId, count, order, callback) { }; VCDataProvider.prototype.getDelaTime = function () { return this.addon.getDeltaTime(); }; VCDataProvider.prototype.getUserStatus = function (userId, callback) { var me = this; this.addon.getUserStatus(userId, function (status) { var entity = RongIMLib.RongInnerTools.convertUserStatus({ status: status, userId: '' }); callback.onSuccess(entity); }, function (code) { callback.onError(code); }); }; VCDataProvider.prototype.setUserStatus = function (status, callback) { this.addon.setUserStatus(status, function () { callback.onSuccess(true); }, function (code) { callback.onError(code); }); }; VCDataProvider.prototype.subscribeUserStatus = function (userIds, callback) { this.addon.subscribeUserStatus(userIds, function () { callback && callback.onSuccess(true); }, function (code) { callback && callback.onError(code); }); }; VCDataProvider.prototype.setUserStatusListener = function (params, callback) { var me = this; this.addon.setOnReceiveStatusListener(function (userId, status) { var entity = RongIMLib.RongInnerTools.convertUserStatus({ userId: userId, status: status }); RongIMLib.RongIMClient.userStatusObserver.notify({ key: userId, entity: entity }); }); var userIds = params.userIds || []; if (userIds.length) { RongIMLib.RongIMClient._dataAccessProvider.subscribeUserStatus(userIds); } }; VCDataProvider.prototype.getUnreadMentionedMessages = function (conversationType, targetId) { var me = this; var mentions = JSON.parse(me.addon.getUnreadMentionedMessages(conversationType, targetId)).list; for (var i = 0, len = mentions.length; i < len; i++) { var temp = JSON.parse(mentions[i].obj); temp.content = JSON.parse(temp.content); mentions[i] = temp; } return mentions; }; VCDataProvider.prototype.hasRemoteUnreadMessages = function (token, callback) { callback.onSuccess(false); }; VCDataProvider.prototype.sendRecallMessage = function (content, sendMessageCallback) { var me = this; me.addon.recallMessage("RC:RcCmd", JSON.stringify(content), content.push || "", function () { content.objectName = 'RC:RcCmd'; sendMessageCallback.onSuccess(me.buildMessage(JSON.stringify(content))); }, function (errorCode) { sendMessageCallback.onError(errorCode); }); }; VCDataProvider.prototype.updateMessage = function (message, callback) { }; VCDataProvider.prototype.updateMessages = function (conversationType, targetId, key, value, callback) { }; VCDataProvider.prototype.reconnect = function (callback) { var token = RongIMLib.Bridge._client.token; this.disconnect(); this.connect(token, callback); }; VCDataProvider.prototype.sendReceiptResponse = function (conversationType, targetId, sendCallback) { }; VCDataProvider.prototype.setMessageExtra = function (messageId, value, callback) { }; VCDataProvider.prototype.addMemberToDiscussion = function (discussionId, userIdList, callback) { }; VCDataProvider.prototype.createDiscussion = function (name, userIdList, callback) { }; VCDataProvider.prototype.getDiscussion = function (discussionId, callback) { }; VCDataProvider.prototype.quitDiscussion = function (discussionId, callback) { }; VCDataProvider.prototype.removeMemberFromDiscussion = function (discussionId, userId, callback) { }; VCDataProvider.prototype.setDiscussionInviteStatus = function (discussionId, status, callback) { }; VCDataProvider.prototype.setDiscussionName = function (discussionId, name, callback) { }; VCDataProvider.prototype.setEnvironment = function (isPrivate) { this.addon.setEnvironment(isPrivate); }; VCDataProvider.prototype.addConversation = function (conversation, callback) { }; VCDataProvider.prototype.updateConversation = function (conversation) { return null; }; VCDataProvider.prototype.getConversationNotificationStatus = function (params, callback) { var conversationType = params.conversationType; var targetId = params.targetId; var notification = RongIMLib.RongIMClient._memoryStore.notification; var key = conversationType + '_' + targetId; var status = notification[key]; if (typeof status == 'number') { callback.onSuccess(status); return; } this.addon.getConversationNotificationStatus(conversationType, targetId, function (status) { notification[key] = status; callback.onSuccess(status); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.setConversationNotificationStatus = function (params, callback) { var conversationType = params.conversationType; var targetId = params.targetId; var status = params.status; var notification = RongIMLib.RongIMClient._memoryStore.notification; var key = conversationType + '_' + targetId; notification[key] = status; var notify = !!status; this.addon.setConversationNotificationStatus(conversationType, targetId, notify, function () { callback.onSuccess(status); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.getCurrentConnectionStatus = function () { return this.addon.getConnectionStatus(); }; VCDataProvider.prototype.getAgoraDynamicKey = function (engineType, channelName, callback) { var extra = ""; this.addon.getVoIPKey(engineType, channelName, extra, function (token) { callback.onSuccess(token); }, function (errorCode) { callback.onError(errorCode); }); }; VCDataProvider.prototype.getPublicServiceProfile = function (publicServiceType, publicServiceId, callback) { var profile = RongIMLib.RongIMClient._memoryStore.publicServiceMap.get(publicServiceType, publicServiceId); callback.onSuccess(profile); }; VCDataProvider.prototype.setDeviceInfo = function (device) { var id = device.id || ''; this.addon.setDeviceId(id); }; VCDataProvider.prototype.getRemotePublicServiceList = function (callback, pullMessageTime) { var publicList = []; var ret = this.addon.getAccounts(); var transformProto = function (ret) { var result = { hasFollowed: false, isGlobal: false, menu: null }; if (!ret.obj) { var error = { error: ret }; throw new Error('公众账号数据格式错误: ' + JSON.stringify(error)); } var obj = JSON.parse(ret.obj); var protoMap = { aType: 'conversationType', aId: 'publicServiceId', aName: 'introduction', aUri: 'portraitUri', follow: 'hasFollowed', isGlobal: 'isGlobal' }; for (var key in obj) { var val = obj[key]; if (key == 'aExtra') { var extra = JSON.parse(val); result["hasFollowed"] = extra.follow; result["isGlobal"] = extra.isGlobal; result["menu"] = extra.menu; } var uId = protoMap[key]; if (uId) { result[uId] = val; } } return result; }; if (ret) { ret = JSON.parse(ret); var list = ret.list; for (var i = 0, len = list.length; i < len; i++) { var item = list[i]; item = transformProto(item); publicList.push(item); } } if (publicList.length > 0) { RongIMLib.RongIMClient._memoryStore.publicServiceMap.publicServiceList.length = 0; RongIMLib.RongIMClient._memoryStore.publicServiceMap.publicServiceList = publicList; } callback.onSuccess(RongIMLib.RongIMClient._memoryStore.publicServiceMap.publicServiceList); }; VCDataProvider.prototype.buildMessage = function (result) { var message = new RongIMLib.Message(), ret = JSON.parse(result); message.conversationType = ret.conversationType; message.targetId = ret.targetId; message.messageDirection = ret.direction; message.senderUserId = ret.senderUserId; if (ret.direction == RongIMLib.MessageDirection.RECEIVE) { message.receivedStatus = ret.status; } else if (ret.direction == RongIMLib.MessageDirection.SEND) { message.sentStatus = ret.status; } message.sentTime = ret.sentTime; message.objectName = ret.objectName; var content = ret.content ? JSON.parse(ret.content) : ret.content; var messageType = typeMapping[ret.objectName] || registerMessageTypeMapping[ret.objectName]; if (content) { content.messageName = messageType; } message.content = content; message.messageId = ret.messageId; message.messageUId = ret.messageUid; message.messageType = messageType; return message; }; VCDataProvider.prototype.buildConversation = function (val) { if (val === '') { return null; } var conver = new RongIMLib.Conversation(), c = JSON.parse(val), lastestMsg = c.lastestMsg ? this.buildMessage(c.lastestMsg) : {}; conver.conversationTitle = c.title; conver.conversationType = c.conversationType; conver.draft = c.draft; conver.isTop = c.isTop; conver.isHidden = c.isHidden; lastestMsg.conversationType = c.conversationType; lastestMsg.targetId = c.targetId; conver.latestMessage = lastestMsg; conver.latestMessageId = lastestMsg.messageId; conver.latestMessage.messageType = typeMapping[lastestMsg.objectName] || registerMessageTypeMapping[lastestMsg.objectName]; conver.objectName = lastestMsg.objectName; conver.receivedStatus = RongIMLib.ReceivedStatus.READ; conver.sentTime = lastestMsg.sentTime; conver.senderUserId = lastestMsg.senderUserId; conver.sentStatus = lastestMsg.status; conver.targetId = c.targetId; conver.unreadMessageCount = c.unreadCount; conver.hasUnreadMention = c.m_hasUnreadMention; var mentions = this.getUnreadMentionedMessages(c.conversationType, c.targetId); if (mentions.length > 0) { // 取最后一条 @ 消息,原因:和 web 互相兼容 var mention = mentions.pop(); conver.mentionedMsg = { uid: mention.messageUid, time: mention.sentTime, mentionedInfo: mention.content.mentionedInfo, sendUserId: mention.senderUserId }; } return conver; }; VCDataProvider.prototype.getRTCUserInfoList = function (room, callback) { this.addon.getRTCUsers(room.id, 1, function (result) { callback.onSuccess(result); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.getRTCRoomInfo = function (room, callback) { var order = 2; this.addon.getRTCResouce(room.id, order, function (result) { callback.onSuccess(JSON.parse(result)); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.joinRTCRoom = function (room, callback) { var id = room.id; var type = room.type || 0; this.addon.joinRTCRoom(id, type, function (result, token) { var res = JSON.parse(result); var users = {}; var list = res.list; RongIMLib.RongUtil.forEach(list, function (item) { var userId = item.id; var tmpData = {}; RongIMLib.RongUtil.forEach(item.data, function (data) { var key = data.key; var value = data.value; tmpData[key] = value; }); users[userId] = tmpData; }); callback.onSuccess({ users: users, token: token }); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.quitRTCRoom = function (room, callback) { this.addon.exitRTCRoom(room.id, function () { callback.onSuccess(true); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.RTCPing = function (room, callback) { this.addon.sendRTCPing(room.id, function () { callback.onSuccess(true); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.setRTCData = function (roomId, key, value, isInner, apiType, callback, message) { var context = this; var hanlders = { room_inner: function (roomId, key, value, name, content, success, error) { context.addon.setRTCInnerData(roomId, RongIMLib.RTCAPIType.ROOM, key, value, name, content, success, error); }, room_outer: function (roomId, key, value, name, content, success, error) { context.addon.setRTCOuterData(roomId, RongIMLib.RTCAPIType.ROOM, key, value, name, content, success, error); }, user_inner: function (roomId, key, value, name, content, success, error) { context.addon.setRTCInnerData(roomId, RongIMLib.RTCAPIType.PERSON, key, value, name, content, success, error); }, user_outer: function (roomId, key, value, name, content, success, error) { context.addon.setRTCOuterData(roomId, RongIMLib.RTCAPIType.PERSON, key, value, name, content, success, error); } }; var type = RongIMLib.RTCAPIType.PERSON == apiType ? 'user' : 'room'; var direction = isInner ? 'inner' : 'outer'; var tpl = '{type}_{direction}'; var name = RongIMLib.RongUtil.tplEngine(tpl, { type: type, direction: direction }); var handler = hanlders[name]; if (handler) { message = message || {}; var name = message.name; var content = message.content; handler(roomId, key, value, name, content, function () { callback.onSuccess(true); }, function (code) { callback.onError(code); }); } }; VCDataProvider.prototype.setRTCRoomData = function (roomId, key, value, isInner, callback, message) { this.setRTCData(roomId, key, value, isInner, RongIMLib.RTCAPIType.ROOM, callback, message); }; VCDataProvider.prototype.getRTCData = function (roomId, keys, isInner, apiType, callback) { var context = this; var hanlders = { room_inner: function (roomId, keys, success, error) { context.addon.getRTCInnerData(roomId, RongIMLib.RTCAPIType.ROOM, keys, success, error); }, room_outer: function (roomId, keys, success, error) { context.addon.getRTCOuterData(roomId, RongIMLib.RTCAPIType.ROOM, keys, success, error); } }; var type = RongIMLib.RTCAPIType.PERSON == apiType ? 'user' : 'room'; var direction = isInner ? 'inner' : 'outer'; var tpl = '{type}_{direction}'; var name = RongIMLib.RongUtil.tplEngine(tpl, { type: type, direction: direction }); var handler = hanlders[name]; if (handler) { handler(roomId, keys, function (result) { var res = JSON.parse(result); var props = {}; var list = res.list; RongIMLib.RongUtil.forEach(list, function (item) { props[item.key] = item.value; }); callback.onSuccess(props); }, function (code) { callback.onError(code); }); } }; VCDataProvider.prototype.getRTCRoomData = function (roomId, keys, isInner, callback, message) { this.getRTCData(roomId, keys, isInner, RongIMLib.RTCAPIType.ROOM, callback); }; VCDataProvider.prototype.removeRTCData = function (roomId, keys, isInner, apiType, callback, message) { var context = this; var hanlders = { room_inner: function (roomId, keys, name, content, success, error) { context.addon.deleteRTCInnerData(roomId, RongIMLib.RTCAPIType.ROOM, keys, name, content, success, error); }, room_outer: function (roomId, keys, name, content, success, error) { context.addon.deleteRTCOuterData(roomId, RongIMLib.RTCAPIType.ROOM, keys, name, content, success, error); }, user_inner: function (roomId, keys, name, content, success, error) { }, user_outer: function (roomId, keys, name, content, success, error) { } }; var type = RongIMLib.RTCAPIType.PERSON == apiType ? 'user' : 'room'; var direction = isInner ? 'inner' : 'outer'; var tpl = '{type}_{direction}'; var name = RongIMLib.RongUtil.tplEngine(tpl, { type: type, direction: direction }); var handler = hanlders[name]; if (handler) { message = message || {}; var name = message.name || ''; var content = message.content || ''; handler(roomId, keys, name, content, function () { callback.onSuccess(true); }, function (code) { callback.onError(code); }); } }; VCDataProvider.prototype.removeRTCRoomData = function (roomId, keys, isInner, callback, message) { this.removeRTCData(roomId, keys, isInner, RongIMLib.RTCAPIType.ROOM, callback); }; VCDataProvider.prototype.getNavi = function () { var nav = this.addon.getNav(); return nav[this.userId]; }; // 信令 SDK 新增 VCDataProvider.prototype.setRTCOutData = function (roomId, data, type, callback, message) { }; // 信令 SDK 新增 VCDataProvider.prototype.getRTCOutData = function (roomId, userId, callback) { }; VCDataProvider.prototype.setRTCUserInfo = function (room, info, callback) { }; VCDataProvider.prototype.removeRTCUserInfo = function (room, info, callback) { }; VCDataProvider.prototype.getRTCUserList = function (room, callback) { }; VCDataProvider.prototype.setRTCRoomInfo = function (room, data, callback) { }; VCDataProvider.prototype.removeRTCRoomInfo = function (room, data, callback) { }; VCDataProvider.prototype.setRTCUserData = function (roomId, key, value, isInner, callback, message) { this.setRTCData(roomId, key, value, isInner, RongIMLib.RTCAPIType.PERSON, callback, message); }; VCDataProvider.prototype.getRTCUserData = function (roomId, key, isInner, callback, message) { }; VCDataProvider.prototype.removeRTCUserData = function (roomId, key, isInner, callback, message) { }; VCDataProvider.prototype.getRTCToken = function (room, callback) { }; VCDataProvider.prototype.setRTCState = function (room, content, callback) { }; return VCDataProvider; })(); RongIMLib.VCDataProvider = VCDataProvider; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var MemeoryProvider = (function () { function MemeoryProvider() { this._memeoryStore = {}; this.prefix = "rong_"; } MemeoryProvider.prototype.setItem = function (composedKey, object) { this._memeoryStore[composedKey] = decodeURIComponent(object); }; MemeoryProvider.prototype.getItem = function (composedKey) { return this._memeoryStore[composedKey]; }; MemeoryProvider.prototype.removeItem = function (composedKey) { if (this.getItem(composedKey)) { delete this._memeoryStore[composedKey]; } }; MemeoryProvider.prototype.getItemKey = function (regStr) { var me = this, item = null, reg = new RegExp(regStr + "\\w+"); for (var key in me._memeoryStore) { var arr = key.match(reg); if (arr) { item = key; } } return item; }; MemeoryProvider.prototype.getItemKeyList = function (regStr) { var prefix = this.prefix; var me = this, itemList = [], reg = new RegExp(regStr + "\\w+"); for (var key in me._memeoryStore) { var arr = key.match(reg); if (arr) { key = key.substring(prefix.length); itemList.push(key); } } return itemList; }; MemeoryProvider.prototype.clearItem = function () { var me = this; for (var key in me._memeoryStore) { delete me._memeoryStore[key]; } }; //单位:字节 MemeoryProvider.prototype.onOutOfQuota = function () { return 4 * 1024; }; return MemeoryProvider; })(); RongIMLib.MemeoryProvider = MemeoryProvider; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var LocalStorageProvider = (function () { // static _instance: LocalStorageProvider = new LocalStorageProvider(); function LocalStorageProvider() { this.prefix = 'rong_'; this._host = ""; var d = new Date(), m = d.getMonth() + 1, date = d.getFullYear() + '/' + (m.toString().length == 1 ? '0' + m : m) + '/' + d.getDate(), nowDate = new Date(date).getTime(); for (var key in localStorage) { if (key.lastIndexOf('RECEIVED') > -1) { var recObj = JSON.parse(localStorage.getItem(key)); for (var key_1 in recObj) { nowDate - recObj[key_1].dealtime > 0 && (delete recObj[key_1]); } if (RongIMLib.RongUtil.isEmpty(recObj)) { localStorage.removeItem(key); } else { localStorage.setItem(key, JSON.stringify(recObj)); } } if (key.lastIndexOf('SENT') > -1) { var sentObj = JSON.parse(localStorage.getItem(key)); nowDate - sentObj.dealtime > 0 && (localStorage.removeItem(key)); } } } LocalStorageProvider.prototype.setItem = function (composedKey, object) { if (composedKey) { composedKey.indexOf(this.prefix) == -1 && (composedKey = this.prefix + composedKey); localStorage.setItem(composedKey, object); } }; LocalStorageProvider.prototype.getItem = function (composedKey) { if (composedKey) { composedKey.indexOf(this.prefix) == -1 && (composedKey = this.prefix + composedKey); return localStorage.getItem(composedKey ? composedKey : ""); } return ""; }; LocalStorageProvider.prototype.getItemKey = function (composedStr) { var item = ""; var _key = this.prefix + composedStr; for (var key in localStorage) { if (key.indexOf(_key) == 0) { item = key; break; } } return item; }; LocalStorageProvider.prototype.getItemKeyList = function (composedStr) { var itemList = []; var prefix = this.prefix; var _key = prefix + composedStr; for (var key in localStorage) { if (key.indexOf(_key) == 0) { key = key.substring(prefix.length); itemList.push(key); } } return itemList; }; LocalStorageProvider.prototype.removeItem = function (composedKey) { if (composedKey) { composedKey.indexOf(this.prefix) == -1 && (composedKey = this.prefix + composedKey); localStorage.removeItem(composedKey.toString()); } }; LocalStorageProvider.prototype.clearItem = function () { var me = this; for (var key in localStorage) { if (key.indexOf(me.prefix) > -1) { me.removeItem(key); } } }; //单位:字节 LocalStorageProvider.prototype.onOutOfQuota = function () { return JSON.stringify(localStorage).length; }; return LocalStorageProvider; })(); RongIMLib.LocalStorageProvider = LocalStorageProvider; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var UserDataProvider = (function () { function UserDataProvider() { this.opersistName = 'RongIMLib'; this.keyManager = 'RongUserDataKeyManager'; this._host = ""; this.prefix = "rong_"; this.oPersist = document.createElement("div"); this.oPersist.style.display = "none"; this.oPersist.style.behavior = "url('#default#userData')"; document.body.appendChild(this.oPersist); this.oPersist.load(this.opersistName); } UserDataProvider.prototype.setItem = function (key, value) { key && key.indexOf(this.prefix) == -1 && (key = this.prefix + key); this.oPersist.setAttribute(key, value); var keyNames = this.getItem(this.keyManager); keyNames ? keyNames.indexOf(key) == -1 && (keyNames += ',' + key) : (keyNames = key); this.oPersist.setAttribute(this.prefix + this.keyManager, keyNames); this.oPersist.save(this.opersistName); }; UserDataProvider.prototype.getItem = function (key) { key && key.indexOf(this.prefix) == -1 && (key = this.prefix + key); return key ? this.oPersist.getAttribute(key) : key; }; UserDataProvider.prototype.removeItem = function (key) { key && key.indexOf(this.prefix) == -1 && (key = this.prefix + key); this.oPersist.removeAttribute(key); this.oPersist.save(this.opersistName); var keyNames = this.getItem(this.keyManager), keyNameArray = keyNames && keyNames.split(',') || []; for (var i = 0, len = keyNameArray.length; i < len; i++) { if (keyNameArray[i] == key) { keyNameArray.splice(i, 1); } } this.oPersist.setAttribute(this.prefix + this.keyManager, keyNameArray.join(',')); this.oPersist.save(this.opersistName); }; UserDataProvider.prototype.getItemKey = function (composedStr) { var item = null, keyNames = this.getItem(this.keyManager), keyNameArray = keyNames && keyNames.split(',') || [], me = this; var _key = this.prefix + composedStr; if (keyNameArray.length) { for (var i = 0, len = keyNameArray.length; i < len; i++) { if (keyNameArray[i] && keyNameArray[i].indexOf(_key) == 0) { item = keyNameArray[i]; break; } } } return item; }; UserDataProvider.prototype.getItemKeyList = function (composedStr) { var itemList = [], keyNames = this.getItem(this.keyManager), keyNameArray = keyNames && keyNames.split(',') || []; var prefix = this.prefix; var _key = prefix + composedStr; if (keyNameArray.length) { for (var i = 0, len = keyNameArray.length; i < len; i++) { if (keyNameArray[i] && keyNameArray[i].indexOf(_key) == 0) { var keyName = keyNameArray[i]; keyName = keyName.substring(prefix.length); itemList.push(keyNameArray[i]); } } } return itemList; }; UserDataProvider.prototype.clearItem = function () { var keyNames = this.getItem(this.keyManager), keyNameArray = [], me = this; keyNames && (keyNameArray = keyNames.split(',')); if (keyNameArray.length) { for (var i = 0, len = keyNameArray.length; i < len; i++) { keyNameArray[i] && me.removeItem(keyNameArray[i]); } me.removeItem(me.keyManager); } }; UserDataProvider.prototype.onOutOfQuota = function () { return 10 * 1024 * 1024; }; return UserDataProvider; })(); RongIMLib.UserDataProvider = UserDataProvider; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var FeatureDectector = (function () { function FeatureDectector(callback) { this.script = document.createElement("script"); this.head = document.getElementsByTagName("head")[0]; if ("WebSocket" in window && "ArrayBuffer" in window && WebSocket.prototype.CLOSED === 3 && !RongIMLib.RongIMClient._memoryStore.depend.isPolling) { RongIMLib.Transportations._TransportType = RongIMLib.Socket.WEBSOCKET; if (!RongIMLib.RongIMClient.Protobuf) { var url = RongIMLib.RongIMClient._memoryStore.depend.protobuf; var script = this.script; script.src = url; this.head.appendChild(script); script.onload = script.onreadystatechange = function () { var isLoaded = (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete'); if (isLoaded) { // 防止 IE6、7 下偶发触发两次 loaded script.onload = script.onreadystatechange = null; if (callback) { callback(); } if (!callback) { var token = RongIMLib.RongIMClient._memoryStore.token; var connectCallback = RongIMLib.RongIMClient._memoryStore.callback; token && RongIMLib.RongIMClient.connect(token, connectCallback); } } }; } } else { RongIMLib.Transportations._TransportType = "xhr-polling"; RongIMLib.RongIMClient.Protobuf = Polling; } } return FeatureDectector; })(); RongIMLib.FeatureDectector = FeatureDectector; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var FeaturePatcher = (function () { function FeaturePatcher() { } FeaturePatcher.prototype.patchAll = function () { this.patchJSON(); this.patchForEach(); }; FeaturePatcher.prototype.patchForEach = function () { if (!Array.forEach) { Array.forEach = function (arr, func) { for (var i = 0; i < arr.length; i++) { func.call(arr, arr[i], i, arr); } }; } }; FeaturePatcher.prototype.patchJSON = function () { if (!window["JSON"]) { window["JSON"] = (function () { function JSON() { } JSON.parse = function (sJSON) { return eval('(' + sJSON + ')'); }; JSON.stringify = function (value) { return this.str("", { "": value }); }; JSON.str = function (key, holder) { var i, k, v, length, mind = "", partial, value = holder[key], me = this; if (value && typeof value === "object" && typeof value.toJSON === "function") { value = value.toJSON(key); } switch (typeof value) { case "string": return me.quote(value); case "number": return isFinite(value) ? String(value) : "null"; case "boolean": case "null": return String(value); case "object": if (!value) { return "null"; } partial = []; if (Object.prototype.toString.apply(value) === "[object Array]") { length = value.length; for (i = 0; i < length; i += 1) { partial[i] = me.str(i, value) || "null"; } v = partial.length === 0 ? "[]" : "[" + partial.join(",") + "]"; return v; } for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = me.str(k, value); if (v) { partial.push(me.quote(k) + ":" + v); } } } v = partial.length === 0 ? "{}" : "{" + partial.join(",") + "}"; return v; } }; JSON.quote = function (string) { var me = this; me.rx_escapable.lastIndex = 0; return me.rx_escapable.test(string) ? '"' + string.replace(me.rx_escapable, function (a) { var c = me.meta[a]; return typeof c === "string" ? c : "\\u" + ("0000" + a.charCodeAt(0).toString(16)).slice(-4); }) + '"' : '"' + string + '"'; }; JSON.rx_escapable = new RegExp('[\\\"\\\\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]', "g"); JSON.meta = { "\b": "\\b", " ": "\\t", "\n": "\\n", "\f": "\\f", "\r": "\\r", '"': '\\"', "''": "\\''", "\\": "\\\\" }; return JSON; })(); } }; return FeaturePatcher; })(); RongIMLib.FeaturePatcher = FeaturePatcher; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var ScriptLoader = (function () { function ScriptLoader() { } ScriptLoader.prototype.load = function (src, onLoad, onError) { var script = document.createElement("script"); script.async = true; if (onLoad) { if (script.addEventListener) { script.addEventListener("load", function (event) { var target = event.target || event.srcElement; onLoad(target.src); }, false); } else if (script.readyState) { script.onreadystatechange = function (event) { var target = event.srcElement; onLoad(target.src); }; } } if (onError) { script.onerror = function (event) { var target = event.target || event.srcElement; onError(target.src); }; } (document.head || document.getElementsByTagName("head")[0]).appendChild(script); script.src = src; }; return ScriptLoader; })(); })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var PublicServiceMap = (function () { function PublicServiceMap() { this.publicServiceList = []; } PublicServiceMap.prototype.get = function (publicServiceType, publicServiceId) { for (var i = 0, len = this.publicServiceList.length; i < len; i++) { if (this.publicServiceList[i].conversationType == publicServiceType && publicServiceId == this.publicServiceList[i].publicServiceId) { return this.publicServiceList[i]; } } }; PublicServiceMap.prototype.add = function (publicServiceProfile) { var isAdd = true, me = this; for (var i = 0, len = this.publicServiceList.length; i < len; i++) { if (me.publicServiceList[i].conversationType == publicServiceProfile.conversationType && publicServiceProfile.publicServiceId == me.publicServiceList[i].publicServiceId) { this.publicServiceList.unshift(this.publicServiceList.splice(i, 1)[0]); isAdd = false; break; } } if (isAdd) { this.publicServiceList.unshift(publicServiceProfile); } }; PublicServiceMap.prototype.replace = function (publicServiceProfile) { var me = this; for (var i = 0, len = this.publicServiceList.length; i < len; i++) { if (me.publicServiceList[i].conversationType == publicServiceProfile.conversationType && publicServiceProfile.publicServiceId == me.publicServiceList[i].publicServiceId) { me.publicServiceList.splice(i, 1, publicServiceProfile); break; } } }; PublicServiceMap.prototype.remove = function (conversationType, publicServiceId) { var me = this; for (var i = 0, len = this.publicServiceList.length; i < len; i++) { if (me.publicServiceList[i].conversationType == conversationType && publicServiceId == me.publicServiceList[i].publicServiceId) { this.publicServiceList.splice(i, 1); break; } } }; return PublicServiceMap; })(); RongIMLib.PublicServiceMap = PublicServiceMap; /** * 会话工具类。 */ var ConversationMap = (function () { function ConversationMap() { this.conversationList = []; } ConversationMap.prototype.get = function (conversavtionType, targetId) { for (var i = 0, len = this.conversationList.length; i < len; i++) { if (this.conversationList[i].conversationType == conversavtionType && this.conversationList[i].targetId == targetId) { return this.conversationList[i]; } } return null; }; ConversationMap.prototype.add = function (conversation) { var isAdd = true; for (var i = 0, len = this.conversationList.length; i < len; i++) { if (this.conversationList[i].conversationType === conversation.conversationType && this.conversationList[i].targetId === conversation.targetId) { this.conversationList.unshift(this.conversationList.splice(i, 1)[0]); isAdd = false; break; } } if (isAdd) { this.conversationList.unshift(conversation); } }; /** * [replace 替换会话] * 会话数组存在的情况下调用add方法会是当前会话被替换且返回到第一个位置,导致用户本地一些设置失效,所以提供replace方法 */ ConversationMap.prototype.replace = function (conversation) { for (var i = 0, len = this.conversationList.length; i < len; i++) { if (this.conversationList[i].conversationType === conversation.conversationType && this.conversationList[i].targetId === conversation.targetId) { this.conversationList.splice(i, 1, conversation); break; } } }; ConversationMap.prototype.remove = function (conversation) { for (var i = 0, len = this.conversationList.length; i < len; i++) { if (this.conversationList[i].conversationType === conversation.conversationType && this.conversationList[i].targetId === conversation.targetId) { this.conversationList.splice(i, 1); break; } } }; return ConversationMap; })(); RongIMLib.ConversationMap = ConversationMap; var CheckParam = (function () { function CheckParam() { } CheckParam.getInstance = function () { if (!CheckParam._instance) { CheckParam._instance = new CheckParam(); } return CheckParam._instance; }; CheckParam.prototype.logger = function (code, funcName, msg) { RongIMLib.RongIMClient.logger({ code: code, funcName: funcName, msg: msg }); }; CheckParam.prototype.check = function (f, position, d, c) { if (RongIMLib.RongIMClient._dataAccessProvider || d) { for (var g = 0, e = c.length; g < e; g++) { if (!new RegExp(this.getType(c[g])).test(f[g])) { // throw new Error("The index of " + g + " parameter was wrong type " + this.getType(c[g]) + " [" + f[g] + "] -> position:" + position); var msg = "第" + (g + 1) + "个参数错误, 错误类型:" + this.getType(c[g]) + " [" + f[g] + "] -> 位置:" + position; this.logger("-3", position, msg); } } } else { var msg = "该参数不正确或尚未实例化RongIMClient -> 位置:" + position; this.logger("-4", position, msg); } }; CheckParam.prototype.getType = function (str) { var temp = Object.prototype.toString.call(str).toLowerCase(); return temp.slice(8, temp.length - 1); }; CheckParam.prototype.checkCookieDisable = function () { document.cookie = "checkCookie=1"; var arr = document.cookie.match(new RegExp("(^| )checkCookie=([^;]*)(;|$)")), isDisable = false; if (!arr) { isDisable = true; } document.cookie = "checkCookie=1;expires=Thu, 01-Jan-1970 00:00:01 GMT"; return isDisable; }; return CheckParam; })(); RongIMLib.CheckParam = CheckParam; var LimitableMap = (function () { function LimitableMap(limit) { this.map = {}; this.keys = []; this.limit = limit || 10; } LimitableMap.prototype.set = function (key, value) { this.map[key] = value; }; LimitableMap.prototype.get = function (key) { return this.map[key] || 0; }; LimitableMap.prototype.remove = function (key) { delete this.map[key]; }; return LimitableMap; })(); RongIMLib.LimitableMap = LimitableMap; var MemoryCache = (function () { function MemoryCache() { this.cache = {}; } MemoryCache.prototype.set = function (key, value) { this.cache[key] = value; }; MemoryCache.prototype.get = function (key) { return this.cache[key]; }; MemoryCache.prototype.remove = function (key) { delete this.cache[key]; }; return MemoryCache; })(); RongIMLib.MemoryCache = MemoryCache; var RongAjax = (function () { function RongAjax(options) { var me = this; me.xmlhttp = null; me.options = options; var hasCORS = typeof XMLHttpRequest !== "undefined" && "withCredentials" in new XMLHttpRequest(); if ("undefined" != typeof XMLHttpRequest && hasCORS) { me.xmlhttp = new XMLHttpRequest(); } else if ("undefined" != typeof XDomainRequest) { me.xmlhttp = new XDomainRequest(); } else { me.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } } RongAjax.prototype.send = function (callback) { var me = this; me.options.url || (me.options.url = "http://upload.qiniu.com/putb64/-1"); me.xmlhttp.onreadystatechange = function () { if (me.xmlhttp.readyState == 4) { if (me.options.type) { callback(); } else { callback(JSON.parse(me.xmlhttp.responseText.replace(/'/g, '"'))); } } }; me.xmlhttp.open("POST", me.options.url, true); me.xmlhttp.withCredentials = false; if ("setRequestHeader" in me.xmlhttp) { if (me.options.type) { me.xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=utf-8"); } else { me.xmlhttp.setRequestHeader("Content-type", "application/octet-stream"); me.xmlhttp.setRequestHeader('Authorization', "UpToken " + me.options.token); } } me.xmlhttp.send(me.options.type ? "appKey=" + me.options.appKey + "&deviceId=" + me.options.deviceId + "×tamp=" + me.options.timestamp + "&deviceInfo=" + me.options.deviceInfo + "&privateInfo=" + JSON.stringify(me.options.privateInfo) : me.options.base64); }; return RongAjax; })(); RongIMLib.RongAjax = RongAjax; function Prosumer() { var data = [], isConsuming = false; this.produce = function (res) { data.push(res); }; this.consume = function (callback, finished) { if (isConsuming) { return; } isConsuming = true; var next = function () { var res = data.shift(); if (RongUtil.isUndefined(res)) { isConsuming = false; finished && finished(); return; } callback(res, next); }; next(); }; this.isExeuting = function () { return isConsuming; }; } var RongUtil = (function () { function RongUtil() { } RongUtil.noop = function () { }; RongUtil.isEmpty = function (obj) { var result = true; if (RongUtil.isObject(obj)) { RongUtil.forEach(obj, function () { result = false; }); } if (RongUtil.isString(obj) || RongUtil.isArray(obj)) { return obj.length === 0; } if (RongUtil.isNumber(obj)) { return obj === 0; } return result; }; RongUtil.isLengthLimit = function (str, maxLen, minLen) { minLen = minLen || 0; var strLen = str.length; return strLen <= maxLen && strLen >= minLen; }; RongUtil.MD5 = function (str, key, raw) { return md5(str, key, raw); }; RongUtil.isObject = function (obj) { return Object.prototype.toString.call(obj) == '[object Object]'; }; RongUtil.isArray = function (array) { return Object.prototype.toString.call(array) == '[object Array]'; }; RongUtil.isString = function (array) { return Object.prototype.toString.call(array) == '[object String]'; }; RongUtil.isFunction = function (fun) { return Object.prototype.toString.call(fun) == '[object Function]'; }; ; RongUtil.isUndefined = function (str) { return Object.prototype.toString.call(str) == '[object Undefined]'; }; ; RongUtil.isEqual = function (a, b) { return a === b; }; ; RongUtil.indexOf = function (arrs, item) { var index = -1; for (var i = 0; i < arrs.length; i++) { if (item === arrs[i]) { index = i; break; } } return index; }; RongUtil.stringFormat = function (tmpl, vals) { for (var i = 0, len = vals.length; i < len; i++) { var val = vals[i], reg = new RegExp("\\{" + (i) + "\\}", "g"); tmpl = tmpl.replace(reg, val); } return tmpl; }; RongUtil.tplEngine = function (temp, data, regexp) { if (!(Object.prototype.toString.call(data) === "[object Array]")) { data = [data]; } var ret = []; for (var i = 0, j = data.length; i < j; i++) { ret.push(replaceAction(data[i])); } return ret.join(""); function replaceAction(object) { return temp.replace(regexp || (/{([^}]+)}/g), function (match, name) { if (match.charAt(0) == '\\') { return match.slice(1); } return (object[name] != undefined) ? object[name] : '{' + name + '}'; }); } }; ; RongUtil.forEach = function (obj, callback) { callback = callback || RongUtil.noop; var loopObj = function () { for (var key in obj) { if (obj.hasOwnProperty(key)) { callback(obj[key], key, obj); } } }; var loopArr = function () { for (var i = 0, len = obj.length; i < len; i++) { callback(obj[i], i); } }; if (RongUtil.isObject(obj)) { loopObj(); } if (RongUtil.isArray(obj)) { loopArr(); } }; RongUtil.extend = function (source, target, callback, force) { RongUtil.forEach(source, function (val, key) { var hasProto = (key in target); if (force && hasProto) { target[key] = val; } if (!hasProto) { target[key] = val; } }); return target; }; RongUtil.createXHR = function () { var item = { XMLHttpRequest: function () { return new XMLHttpRequest(); }, XDomainRequest: function () { return new XDomainRequest(); }, ActiveXObject: function () { return new ActiveXObject('Microsoft.XMLHTTP'); } }; var isXHR = typeof XMLHttpRequest !== "undefined" && "withCredentials" in new XMLHttpRequest(); var isXDR = typeof XDomainRequest == 'function'; var key = isXHR ? 'XMLHttpRequest' : isXDR ? 'XDomainRequest' : 'ActiveXObject'; return item[key](); }; RongUtil.request = function (opts) { var url = opts.url; var success = opts.success; var error = opts.error || RongUtil.noop; var method = opts.method || 'GET'; var xhr = RongUtil.createXHR(); if ('onload' in xhr) { xhr.onload = function () { xhr.onload = RongUtil.noop; success(xhr.responseText); }; xhr.onerror = function () { error(xhr.status, xhr.responseText); xhr.onerror = RongUtil.noop; }; } else { xhr.onreadystatechange = function () { if (xhr.readyState == 4) { var status = xhr.status; if (status == 200) { success(xhr.responseText); } else { error(status, xhr.responseText); } } }; } xhr.open(method, url, true); xhr.send(null); return xhr; }; RongUtil.formatProtoclPath = function (config) { var path = config.path; var protocol = config.protocol; var tmpl = config.tmpl || '{0}{1}'; var sub = config.sub; var flag = '://'; var index = path.indexOf(flag); var hasProtocol = (index > -1); if (hasProtocol) { index += flag.length; path = path.substring(index); } if (sub) { index = path.indexOf('/'); var hasPath = (index > -1); if (hasPath) { path = path.substr(0, index); } } return RongUtil.stringFormat(tmpl, [protocol, path]); }; ; RongUtil.getUrlHost = function (url) { var index = RongUtil.indexOf(url, '/'); return url.substring(0, index); }; RongUtil.supportLocalStorage = function () { var support = false; if (typeof localStorage == 'object') { try { var key = 'RC_TMP_KEY', value = 'RC_TMP_VAL'; localStorage.setItem(key, value); var localVal = localStorage.getItem(key); if (localVal == value) { support = true; } } catch (err) { console.log('localStorage is disabled.'); } } return support; }; /* //返回新引用,不破坏原始对象 rename({n: 'martin'}, {n: 'name'}); => {name: 'martin'} rename([{n: 'martin'}, {a: 18}], {n: 'name', a: 'age'}); => [{name: 'martin'}, {age: 18}] */ RongUtil.rename = function (origin, newNames) { var isObject = RongUtil.isObject(origin); if (isObject) { origin = [origin]; } origin = JSON.parse(JSON.stringify(origin)); var updateProperty = function (val, key, obj) { delete obj[key]; key = newNames[key]; obj[key] = val; }; RongUtil.forEach(origin, function (item) { RongUtil.forEach(item, function (val, key, obj) { var isRename = (key in newNames); (isRename ? updateProperty : RongUtil.noop)(val, key, obj); }); }); return isObject ? origin[0] : origin; }; RongUtil.some = function (arrs, callback) { var has = false; for (var i = 0, len = arrs.length; i < len; i++) { if (callback(arrs[i])) { has = true; break; } } return has; }; RongUtil.keys = function (obj) { var props = []; for (var key in obj) { props.push(key); } return props; }; RongUtil.isNumber = function (num) { return Object.prototype.toString.call(num) == '[object Number]'; }; RongUtil.getTimestamp = function () { var date = new Date(); return date.getTime(); }; RongUtil.isSupportRequestHeaders = function () { var userAgent = navigator.userAgent; var isIE = window.ActiveXObject || 'ActiveXObject' in window; if (isIE) { var reIE = new RegExp('MSIE (\\d+\\.\\d+);'); reIE.test(userAgent); var fIEVersion = parseFloat(RegExp['$1']); return fIEVersion > 9; } return true; }; RongUtil.hasValidWsUrl = function (urls) { try { urls = JSON.parse(urls); } catch (e) { return false; } var validUrlList = RongUtil.getValidWsUrlList(urls); return validUrlList.length > 0; }; RongUtil.getValidWsUrlList = function (urls) { var invalidWsUrls = RongIMLib.RongIMClient.invalidWsUrls; var validUrlList = []; RongUtil.forEach(urls, function (url) { if (RongUtil.indexOf(invalidWsUrls, url) === -1) { validUrlList.push(url); } }); return validUrlList; }; RongUtil.Prosumer = Prosumer; return RongUtil; })(); RongIMLib.RongUtil = RongUtil; /* var observer = new RongObserver(); observer.watch({ key: 'key', func: function(entity){ } }); */ var RongObserver = (function () { function RongObserver() { this.watchers = {}; } RongObserver.prototype.genUId = function (key) { var time = new Date().getTime(); return [key, time].join('_'); }; RongObserver.prototype.watch = function (params) { var me = this; var key = params.key; var multiple = params.multiple; key = RongUtil.isArray(key) ? key : [key]; var func = params.func; RongUtil.forEach(key, function (k) { k = multiple ? me.genUId(k) : k; me.watchers[k] = func; }); }; RongObserver.prototype.notify = function (params) { var me = this; var key = params.key; var entity = params.entity; for (var k in me.watchers) { var isNotify = (k.indexOf(key) == 0); if (isNotify) { me.watchers[k](entity); } } }; RongObserver.prototype.remove = function () { }; return RongObserver; })(); RongIMLib.RongObserver = RongObserver; var Observer = (function () { function Observer() { this.observers = []; } Observer.prototype.add = function (observer, force) { if (force) { this.observers = [observer]; } if (RongUtil.isFunction(observer)) { this.observers.push(observer); } }; Observer.prototype.emit = function (data) { RongUtil.forEach(this.observers, function (observer) { observer(data); }); }; Observer.prototype.clear = function () { this.observers = []; }; Observer.prototype.checkIndexOutBound = function (index, bound) { var isOutBound = (index > -1 && index < bound); return isOutBound; }; Observer.prototype.removeAt = function (index) { var isOutBound = this.checkIndexOutBound(index, this.observers.length); if (isOutBound) { this.observers.splice(index, 1); } }; Observer.prototype.remove = function (observer) { var me = this; if (!observer) { me.clear(); return; } if (!RongUtil.isFunction(observer)) { return; } var observerList = me.observers; for (var i = observerList.length - 1; i >= 0; i--) { if (observer === observerList[i]) { me.removeAt(i); } } }; return Observer; })(); RongIMLib.Observer = Observer; var Timer = (function () { function Timer(config) { this.timeout = 0; this.timers = []; this.timeout = config.timeout; } Timer.prototype.resume = function (callback) { var timer = setTimeout(callback, this.timeout); this.timers.push(timer); }; Timer.prototype.pause = function () { RongUtil.forEach(this.timers, function (timer) { clearTimeout(timer); }); }; return Timer; })(); RongIMLib.Timer = Timer; var IndexTools = (function () { function IndexTools(config) { this.items = []; this.index = 0; this.onwheel = function () { }; this.items = config.items; this.onwheel = config.onwheel; } IndexTools.prototype.get = function () { var context = this; var items = context.items; var index = context.index; var isWheel = index >= items.length; if (isWheel) { context.onwheel(); } return isWheel ? 0 : index; }; IndexTools.prototype.add = function () { this.index += 1; }; return IndexTools; })(); RongIMLib.IndexTools = IndexTools; var InnerUtil = (function () { function InnerUtil() { } InnerUtil.getUId = function (token) { return md5(token).slice(8, 16); }; return InnerUtil; })(); RongIMLib.InnerUtil = InnerUtil; })(RongIMLib || (RongIMLib = {})); // {WebEnd} WebSDK 内容开始的标识, 方便小程序 SDK 定位 /* 说明: 请勿修改 header.js 和 footer.js 用途: 自动拼接暴露方式 命令: grunt release 中 concat */ return RongIMLib; }); ================================================ FILE: api-test-v2/lib/js/RongIMLib-2.5.5.js ================================================ /* 说明: 请勿修改 header.js 和 footer.js 用途: 自动拼接暴露方式 命令: grunt release 中 concat */ (function(global, factory) { if (typeof exports === 'object' && typeof module !== 'undefined') { module.exports = factory(); } else if (typeof define === 'function' && (define.amd || define.cmd)) { define(factory); } else { var tempIMLib = factory(); var tempClient = tempIMLib.RongIMClient; var isExists = (!!global.RongIMLib); if (isExists) { var currentClient = RongIMLib.RongIMClient || {}; for(var key in currentClient){ tempClient[key] = currentClient[key]; } } global.RongIMLib = tempIMLib; global.RongIMClient = tempClient; } })(window, function(){ // {WebStart} WebSDK 内容开始的标识, 方便小程序 SDK 定位 var Polling = { SetUserStatusInput: function(){ var a = {}; this.setStatus = function(b){ a.status = b; }; this.toArrayBuffer = function(){ return a; }; }, SetUserStatusOutput: function(){ var a = {}; this.setNothing = function(b){ a.nothing = b; }; this.toArrayBuffer = function(){ return a; }; }, GetUserStatusInput: function(){ var a = {}; this.setNothing = function(b){ a.nothing = b; }; this.toArrayBuffer = function(){ return a; }; }, GetUserStatusOutput: function(){ var a = {}; this.setStatus = function(b){ a.status = b; }; this.setSubUserId = function(b){ a.subUserId = b; }; this.toArrayBuffer = function(){ return a; }; }, VoipDynamicInput: function(){ var a = {}; this.setEngineType = function(b){ a.engineType = b; }; this.setChannelName = function(b){ a.channelName = b; }; this.setChannelExtra = function(b){ a.channelExtra = b; }; this.toArrayBuffer = function(){ return a; }; }, VoipDynamicOutput: function(){ var a = {}; this.setDynamicKey = function(b){ a.dynamicKey = b; }; this.toArrayBuffer = function(){ return a; }; }, SubUserStatusInput: function(){ var a = {}; this.setUserid = function(b){ a.userid = b; }; this.toArrayBuffer = function(){ return a; }; }, SubUserStatusOutput: function(){ var a = {}; this.setNothing = function(b){ a.nothing = b; }; this.toArrayBuffer = function(){ return a; }; }, CleanHisMsgInput: function(){ var a = {}; this.setTargetId = function(b){ a.targetId = b; }; this.setDataTime = function(b){ a.dataTime = b; }; this.setConversationType = function(b){ a.conversationType = b; }; this.toArrayBuffer = function(){ return a; }; }, DeleteMsgInput:function(){ var a = {}; this.setType = function(b){ a.type = b; }; this.setConversationId = function(b){ a.conversationId = b; }; this.setMsgs = function(b){ a.msgs = b; }; this.toArrayBuffer = function () { return a; } }, DeleteMsg:function(){ var a = {}; this.setMsgId = function(b){ a.msgId = b; }; this.setMsgDataTime = function(b){ a.msgDataTime = b; }; this.setDirect = function(b){ a.direct = b; }; this.toArrayBuffer = function () { return a; } }, DeleteMsgOutput:function(){ var a = {}; this.setNothing = function(b){ a.nothing = b; }; this.toArrayBuffer = function () { return a; } }, SearchMpInput:function(){ var a = {}; this.setType = function (b) { a.type = b; }; this.setId = function (b) { a.id = b; }; this.toArrayBuffer = function () { return a; } }, SearchMpOutput:function(){ var a = {}; this.setNothing = function (b) { a.nothing = b; }; this.setInfo = function (b) { a.info = b; }; this.toArrayBuffer = function () { return a; } }, MpInfo:function(){ var a = {}; this.setMpid = function(b){ a.mpid = b; }; this.setName = function(b){ a.name = b; }; this.setType = function(b){ a.type = b; }; this.setTime = function(b){ a.time = b; }; this.setPortraitUri = function(b){ a.portraitUrl = b; }; this.setExtra = function(b){ a.extra = b; }; this.toArrayBuffer = function () { return a; } }, PullMpInput:function(){ var a = {}; this.setMpid = function(b){ a.mpid = b; }; this.setTime = function(b){ a.time = b; }; this.toArrayBuffer = function () { return a; }; }, PullMpOutput:function(){ var a = {}; this.setStatus = function(b){ a.status = b; } this.setInfo = function(b){ a.info = b; }; this.toArrayBuffer = function () { return a; }; }, MPFollowInput:function(){ var a = {}; this.setId = function(b){ a.id = b; }; this.toArrayBuffer = function () { return a; }; }, MPFollowOutput:function(){ var a = {}; this.setNothing = function(b){ a.nothing = b; }; this.setInfo = function(b){ a.info = b; }; this.toArrayBuffer = function () { return a; }; }, NotifyMsg: function () { var a = {}; this.setType = function (b) { a.type = b; }; this.setTime = function (b) { a.time = b; }; this.setChrmId = function(b){ a.chrmId = b; }; this.toArrayBuffer = function () { return a; }; }, SyncRequestMsg: function () { var a = {}; this.setSyncTime = function (b) { a.syncTime = b || 0; }; this.setIspolling = function (b) { a.ispolling = !!b; }; this.setIsweb = function (b) { a.isweb = !!b; }; this.setIsPullSend = function (b) { a.isPullSend = !!b; }; this.setSendBoxSyncTime = function (b) { a.sendBoxSyncTime = b; }; this.toArrayBuffer = function () { return a; }; }, UpStreamMessage: function () { var a = {}; this.setSessionId = function (b) { a.sessionId = b }; this.setClassname = function (b) { a.classname = b }; this.setContent = function (b) { if (b) a.content = b; }; this.setPushText = function (b) { a.pushText = b }; this.setUserId = function(b){ a.userId = b; }; this.setConfigFlag = function (b) { a.configFlag = b; }; this.setAppData = function(b){ a.appData = b; }; this.toArrayBuffer = function () { return a }; }, DownStreamMessages: function () { var a = {}; this.setList = function (b) { a.list = b }; this.setSyncTime = function (b) { a.syncTime = b; }; this.setFinished = function(b){ a.finished = b; }; this.toArrayBuffer = function () { return a }; }, DownStreamMessage: function () { var a = {}; this.setFromUserId = function (b) { a.fromUserId = b }; this.setType = function (b) { a.type = b }; this.setGroupId = function (b) { a.groupId = b }; this.setClassname = function (b) { a.classname = b }; this.setContent = function (b) { if (b) a.content = b }; this.setDataTime = function (b) { a.dataTime = b; }; this.setStatus = function (b) { a.status = b; }; this.setMsgId = function (b) { a.msgId = b; }; this.toArrayBuffer = function () { return a; }; }, CreateDiscussionInput: function () { var a = {}; this.setName = function (b) { a.name = b }; this.toArrayBuffer = function () { return a } }, CreateDiscussionOutput: function () { var a = {}; this.setId = function (b) { a.id = b }; this.toArrayBuffer = function () { return a }; }, ChannelInvitationInput: function () { var a = {}; this.setUsers = function (b) { a.users = b }; this.toArrayBuffer = function () { return a }; }, LeaveChannelInput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b }; this.toArrayBuffer = function () { return a }; }, QueryChatroomInfoInput:function(){ var a = {}; this.setCount = function (b) { a.count = b; }; this.setOrder = function (b) { a.order = b; }; this.toArrayBuffer = function () { return a }; }, QueryChatroomInfoOutput:function(){ var a = {}; this.setUserTotalNums = function (b) { a.userTotalNums = b; }; this.setUserInfos = function (b) { a.userInfos = b; }; this.toArrayBuffer = function () { return a; }; }, ChannelEvictionInput: function () { var a = {}; this.setUser = function (b) { a.user = b }; this.toArrayBuffer = function () { return a }; }, RenameChannelInput: function () { var a = {}; this.setName = function (b) { a.name = b }; this.toArrayBuffer = function () { return a } }, ChannelInfoInput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b }; this.toArrayBuffer = function () { return a } }, ChannelInfoOutput: function () { var a = {}; this.setType = function (b) { a.type = b }; this.setChannelId = function (b) { a.channelId = b }; this.setChannelName = function (b) { a.channelName = b }; this.setAdminUserId = function (b) { a.adminUserId = b }; this.setFirstTenUserIds = function (b) { a.firstTenUserIds = b }; this.setOpenStatus = function (b) { a.openStatus = b }; this.toArrayBuffer = function () { return a } }, ChannelInfosInput: function () { var a = {}; this.setPage = function (b) { a.page = b }; this.setNumber = function (b) { a.number = b }; this.toArrayBuffer = function () { return a }; }, ChannelInfosOutput: function () { var a = {}; this.setChannels = function (b) { a.channels = b }; this.setTotal = function (b) { a.total = b }; this.toArrayBuffer = function () { return a }; }, MemberInfo: function () { var a = {}; this.setUserId = function (b) { a.userId = b }; this.setUserName = function (b) { a.userName = b }; this.setUserPortrait = function (b) { a.userPortrait = b }; this.setExtension = function (b) { a.extension = b }; this.toArrayBuffer = function () { return a }; }, GroupMembersInput: function () { var a = {}; this.setPage = function (b) { a.page = b }; this.setNumber = function (b) { a.number = b }; this.toArrayBuffer = function () { return a }; }, GroupMembersOutput: function () { var a = {}; this.setMembers = function (b) { a.members = b }; this.setTotal = function (b) { a.total = b }; this.toArrayBuffer = function () { return a }; }, GetUserInfoInput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b }; this.toArrayBuffer = function () { return a }; }, GetUserInfoOutput: function () { var a = {}; this.setUserId = function (b) { a.userId = b }; this.setUserName = function (b) { a.userName = b }; this.setUserPortrait = function (b) { a.userPortrait = b }; this.toArrayBuffer = function () { return a }; }, GetSessionIdInput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b }; this.toArrayBuffer = function () { return a }; }, GetSessionIdOutput: function () { var a = {}; this.setSessionId = function (b) { a.sessionId = b }; this.toArrayBuffer = function () { return a }; }, GetQNupTokenInput: function () { var a = {}; this.setType = function (b) { a.type = b; } this.toArrayBuffer = function () { return a } }, GetQNupTokenOutput: function () { var a = {}; this.setDeadline = function (b) { a.deadline = b }; this.setToken = function (b) { a.token = b; }; this.toArrayBuffer = function () { return a } }, GetQNdownloadUrlInput: function () { var a = {}; this.setType = function (b) { a.type = b; }; this.setKey = function (b) { a.key = b; }; this.setFileName = function(b){ a.fileName = b; }; this.toArrayBuffer = function () { return a } }, GetQNdownloadUrlOutput: function () { var a = {}; this.setDownloadUrl = function (b) { a.downloadUrl = b; }; this.toArrayBuffer = function () { return a } }, Add2BlackListInput: function () { var a = {}; this.setUserId = function (b) { a.userId = b; }; this.toArrayBuffer = function () { return a } }, RemoveFromBlackListInput: function () { var a = {}; this.setUserId = function (b) { a.userId = b; }; this.toArrayBuffer = function () { return a } }, QueryBlackListInput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b; }; this.toArrayBuffer = function () { return a } }, QueryBlackListOutput: function () { var a = {}; this.setUserIds = function (b) { a.userIds = b; }; this.toArrayBuffer = function () { return a } }, BlackListStatusInput: function () { var a = {}; this.setUserId = function (b) { a.userId = b; }; this.toArrayBuffer = function () { return a } }, BlockPushInput: function () { var a = {}; this.setBlockeeId = function (b) { a.blockeeId = b; }; this.toArrayBuffer = function () { return a } }, ModifyPermissionInput: function () { var a = {}; this.setOpenStatus = function (b) { a.openStatus = b; }; this.toArrayBuffer = function () { return a }; }, GroupInput: function () { var a = {}; this.setGroupInfo = function (b) { for (var i = 0, arr = []; i < b.length; i++) { arr.push({id: b[i].getContent().id, name: b[i].getContent().name}) } a.groupInfo = arr; }; this.toArrayBuffer = function () { return a }; }, GroupOutput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b; }; this.toArrayBuffer = function () { return a }; }, GroupInfo: function () { var a = {}; this.setId = function (b) { a.id = b; }; this.setName = function (b) { a.name = b; }; this.getContent = function () { return a; }; this.toArrayBuffer = function () { return a }; }, GroupHashInput: function () { var a = {}; this.setUserId = function (b) { a.userId = b; }; this.setGroupHashCode = function (b) { a.groupHashCode = b; }; this.toArrayBuffer = function () { return a }; }, GroupHashOutput: function () { var a = {}; this.setResult = function (b) { a.result = b; }; this.toArrayBuffer = function () { return a }; }, ChrmInput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b; }; this.toArrayBuffer = function () { return a }; }, ChrmOutput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b; }; this.toArrayBuffer = function () { return a }; }, ChrmPullMsg: function () { var a = {}; this.setSyncTime = function (b) { a.syncTime = b }; this.setCount = function (b) { a.count = b; }; this.toArrayBuffer = function () { return a }; }, RelationsInput: function () { var a = {}; this.setType = function (b) { a.type = b; }; this.setMsg = function(b){ a.msg = b; }; this.setCount = function(b){ a.count = b; }; this.toArrayBuffer = function () { return a }; }, RelationsOutput: function () { var a = {}; this.setInfo = function (b) { a.info = b; }; this.toArrayBuffer = function () { return a } }, RelationInfo: function () { var a = {}; this.setType = function (b) { a.type = b; }; this.setUserId = function (b) { a.userId = b; }; this.setMsg = function(b){ a.msg = b; }; this.toArrayBuffer = function () { return a } }, HistoryMessageInput: function () { var a={}; this.setTargetId=function(b){ a.targetId=b; }; this.setDataTime=function(b){ a.dataTime=b; }; this.setSize=function(b){ a.size=b; }; this.toArrayBuffer = function () { return a } }, HistoryMessagesOuput: function () { var a={}; this.setList=function(b){ a.list=b; }; this.setSyncTime=function(b){ a.syncTime=b; }; this.setHasMsg=function(b){ a.hasMsg=b; }; this.toArrayBuffer = function () { return a } }, HistoryMsgInput: function(){ var a = {}; this.setTargetId = function(b){ a.targetId = b; }; this.setTime = function(b){ a.time = b; }; this.setCount = function(b){ a.count = b; }; this.setOrder = function(b){ a.order = b; }; this.toArrayBuffer = function(){ return a; }; }, HistoryMsgOuput: function(){ var a = {}; this.setList = function(b){ a.list = b; }; this.setSyncTime = function(b){ a.syncTime = b; }; this.setHasMsg = function(b){ a.hasMsg = b; }; this.toArrayBuffer = function(){ return a; }; }, RtcQueryListInput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setOrder = function (b) { a.order = b; }; }, RtcKeyDeleteInput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setKey = function (b) { a.key = b; }; }, RtcValueInfo: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setKey = function (b) { a.key = b; }; this.setValue = function (b) { a.value = b; }; }, // RtcUserInfo: function () { // var a = {}; // }, RtcUserListOutput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setList = function (b) { a.list = b; }; this.setToken = function (b) { a.token = b; }; }, RtcRoomInfoOutput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setRoomId = function (b) { a.roomId = b; }; this.setRoomData = function (b) { a.roomData = b; }; this.setUserCount = function (b) { a.userCount = b; }; this.setList = function (b) { a.list = b; } }, RtcInput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setRoomType = function (b) { a.roomType = b; }; this.setBroadcastType = function (b) { a.broadcastType = b; } }, // RtcQryInput: function () { // var a = {}; // }, RtcQryOutput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setOutInfo = function (b) { a.outInfo = b; }; }, // RtcDelDataInput: function () { // var a = {}; // }, RtcDataInput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setInterior = function (b) { a.interior = b; }; this.setTarget = function (b) { a.target = b; }; this.setKey = function (b) { a.key = b; }; this.setObjectName = function (b) { a.objectName = b; }; this.setContent = function (b) { a.content = b; }; }, RtcSetDataInput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setInterior = function (b) { a.interior = b; }; this.setTarget = function (b) { a.target = b; }; this.setKey = function (b) { a.key = b; }; this.setValue = function (b) { a.value = b; }; this.setObjectName = function (b) { a.objectName = b; }; this.setContent = function (b) { a.content = b; }; }, RtcOutput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setNothing = function (b) { a.nothing = b; }; }, RtcTokenOutput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setRtcToken = function (b) { a.rtcToken = b; } }, /** * 聊天室 KV 存储 */ ChrmNotifyMsg: function () { var a = {}; this.toArrayBuffer = function () { return a; }; this.setType = function (b) { a.type = b; }; this.setTime = function (b) { a.time = b; }; this.setChrmId = function (b) { a.chrmId = b; }; }, ChrmKVEntity: function () { var a = {}; this.toArrayBuffer = function () { return a; }; this.setKey = function (key) { a.key = key; }; this.setValue = function (value) { a.value = value; }; this.setStatus = function (b) { a.status = b; }; this.setTimestamp = function (b) { a.timestamp = b; }; this.setUid = function (b) { a.uid = b; }; }, SetChrmKV: function () { var a = {}; this.toArrayBuffer = function () { return a; }; this.setEntry = function (b) { a.entry = b; }; this.setNotification = function (b) { a.notification = b.toArrayBuffer(); }; this.setBNotify = function (b) { a.bNotify = b; }; this.setType = function (b) { a.type = b; }; }, ChrmKVOutput: function () { var a = {}; this.toArrayBuffer = function () { return a; }; this.setEntries = function (b) { this.entries = b; }; this.setBFullUpdate = function (b) { this.bFullUpdate = b; }; this.setSyncTime = function (b) { this.syncTime = b; }; }, QueryChrmKV: function () { var a = {}; this.toArrayBuffer = function () { return a; }; this.setTimestamp = function (b) { a.timestamp = b; }; }, DeleteChrmKV: function () { var a = {}; this.toArrayBuffer = function () { return a; }; this.setEntry = function (b) { a.entry = b; }; this.setBNotify = function (b) { a.bNotify = b; }; this.setNotification = function (b) { a.notification = b.toArrayBuffer(); }; this.setType = function (b) { a.type = b; }; } }; for (var f in Polling) { Polling[f].decode = function (b) { var back = {}, val = JSON.parse(b) || eval("(" + b + ")"); for (var i in val) { back[i]=val[i]; back["get"+ i.charAt(0).toUpperCase()+i.slice(1)]=function(){ return val[i]; } } return back; } } /* * JavaScript MD5 * https://github.com/blueimp/JavaScript-MD5 * * Copyright 2011, Sebastian Tschan * https://blueimp.net * * Licensed under the MIT license: * http://www.opensource.org/licenses/MIT * * Based on * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message * Digest Algorithm, as defined in RFC 1321. * Version 2.2 Copyright (C) Paul Johnston 1999 - 2009 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet * Distributed under the BSD License * See http://pajhome.org.uk/crypt/md5 for more info. */ /*jslint bitwise: true */ /*global unescape, define, module */ var md5 = (function () { 'use strict'; /* * Add integers, wrapping at 2^32. This uses 16-bit operations internally * to work around bugs in some JS interpreters. */ function safe_add(x, y) { var lsw = (x & 0xFFFF) + (y & 0xFFFF), msw = (x >> 16) + (y >> 16) + (lsw >> 16); return (msw << 16) | (lsw & 0xFFFF); } /* * Bitwise rotate a 32-bit number to the left. */ function bit_rol(num, cnt) { return (num << cnt) | (num >>> (32 - cnt)); } /* * These functions implement the four basic operations the algorithm uses. */ function md5_cmn(q, a, b, x, s, t) { return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s), b); } function md5_ff(a, b, c, d, x, s, t) { return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t); } function md5_gg(a, b, c, d, x, s, t) { return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t); } function md5_hh(a, b, c, d, x, s, t) { return md5_cmn(b ^ c ^ d, a, b, x, s, t); } function md5_ii(a, b, c, d, x, s, t) { return md5_cmn(c ^ (b | (~d)), a, b, x, s, t); } /* * Calculate the MD5 of an array of little-endian words, and a bit length. */ function binl_md5(x, len) { /* append padding */ x[len >> 5] |= 0x80 << (len % 32); x[(((len + 64) >>> 9) << 4) + 14] = len; var i, olda, oldb, oldc, oldd, a = 1732584193, b = -271733879, c = -1732584194, d = 271733878; for (i = 0; i < x.length; i += 16) { olda = a; oldb = b; oldc = c; oldd = d; a = md5_ff(a, b, c, d, x[i], 7, -680876936); d = md5_ff(d, a, b, c, x[i + 1], 12, -389564586); c = md5_ff(c, d, a, b, x[i + 2], 17, 606105819); b = md5_ff(b, c, d, a, x[i + 3], 22, -1044525330); a = md5_ff(a, b, c, d, x[i + 4], 7, -176418897); d = md5_ff(d, a, b, c, x[i + 5], 12, 1200080426); c = md5_ff(c, d, a, b, x[i + 6], 17, -1473231341); b = md5_ff(b, c, d, a, x[i + 7], 22, -45705983); a = md5_ff(a, b, c, d, x[i + 8], 7, 1770035416); d = md5_ff(d, a, b, c, x[i + 9], 12, -1958414417); c = md5_ff(c, d, a, b, x[i + 10], 17, -42063); b = md5_ff(b, c, d, a, x[i + 11], 22, -1990404162); a = md5_ff(a, b, c, d, x[i + 12], 7, 1804603682); d = md5_ff(d, a, b, c, x[i + 13], 12, -40341101); c = md5_ff(c, d, a, b, x[i + 14], 17, -1502002290); b = md5_ff(b, c, d, a, x[i + 15], 22, 1236535329); a = md5_gg(a, b, c, d, x[i + 1], 5, -165796510); d = md5_gg(d, a, b, c, x[i + 6], 9, -1069501632); c = md5_gg(c, d, a, b, x[i + 11], 14, 643717713); b = md5_gg(b, c, d, a, x[i], 20, -373897302); a = md5_gg(a, b, c, d, x[i + 5], 5, -701558691); d = md5_gg(d, a, b, c, x[i + 10], 9, 38016083); c = md5_gg(c, d, a, b, x[i + 15], 14, -660478335); b = md5_gg(b, c, d, a, x[i + 4], 20, -405537848); a = md5_gg(a, b, c, d, x[i + 9], 5, 568446438); d = md5_gg(d, a, b, c, x[i + 14], 9, -1019803690); c = md5_gg(c, d, a, b, x[i + 3], 14, -187363961); b = md5_gg(b, c, d, a, x[i + 8], 20, 1163531501); a = md5_gg(a, b, c, d, x[i + 13], 5, -1444681467); d = md5_gg(d, a, b, c, x[i + 2], 9, -51403784); c = md5_gg(c, d, a, b, x[i + 7], 14, 1735328473); b = md5_gg(b, c, d, a, x[i + 12], 20, -1926607734); a = md5_hh(a, b, c, d, x[i + 5], 4, -378558); d = md5_hh(d, a, b, c, x[i + 8], 11, -2022574463); c = md5_hh(c, d, a, b, x[i + 11], 16, 1839030562); b = md5_hh(b, c, d, a, x[i + 14], 23, -35309556); a = md5_hh(a, b, c, d, x[i + 1], 4, -1530992060); d = md5_hh(d, a, b, c, x[i + 4], 11, 1272893353); c = md5_hh(c, d, a, b, x[i + 7], 16, -155497632); b = md5_hh(b, c, d, a, x[i + 10], 23, -1094730640); a = md5_hh(a, b, c, d, x[i + 13], 4, 681279174); d = md5_hh(d, a, b, c, x[i], 11, -358537222); c = md5_hh(c, d, a, b, x[i + 3], 16, -722521979); b = md5_hh(b, c, d, a, x[i + 6], 23, 76029189); a = md5_hh(a, b, c, d, x[i + 9], 4, -640364487); d = md5_hh(d, a, b, c, x[i + 12], 11, -421815835); c = md5_hh(c, d, a, b, x[i + 15], 16, 530742520); b = md5_hh(b, c, d, a, x[i + 2], 23, -995338651); a = md5_ii(a, b, c, d, x[i], 6, -198630844); d = md5_ii(d, a, b, c, x[i + 7], 10, 1126891415); c = md5_ii(c, d, a, b, x[i + 14], 15, -1416354905); b = md5_ii(b, c, d, a, x[i + 5], 21, -57434055); a = md5_ii(a, b, c, d, x[i + 12], 6, 1700485571); d = md5_ii(d, a, b, c, x[i + 3], 10, -1894986606); c = md5_ii(c, d, a, b, x[i + 10], 15, -1051523); b = md5_ii(b, c, d, a, x[i + 1], 21, -2054922799); a = md5_ii(a, b, c, d, x[i + 8], 6, 1873313359); d = md5_ii(d, a, b, c, x[i + 15], 10, -30611744); c = md5_ii(c, d, a, b, x[i + 6], 15, -1560198380); b = md5_ii(b, c, d, a, x[i + 13], 21, 1309151649); a = md5_ii(a, b, c, d, x[i + 4], 6, -145523070); d = md5_ii(d, a, b, c, x[i + 11], 10, -1120210379); c = md5_ii(c, d, a, b, x[i + 2], 15, 718787259); b = md5_ii(b, c, d, a, x[i + 9], 21, -343485551); a = safe_add(a, olda); b = safe_add(b, oldb); c = safe_add(c, oldc); d = safe_add(d, oldd); } return [a, b, c, d]; } /* * Convert an array of little-endian words to a string */ function binl2rstr(input) { var i, output = ''; for (i = 0; i < input.length * 32; i += 8) { output += String.fromCharCode((input[i >> 5] >>> (i % 32)) & 0xFF); } return output; } /* * Convert a raw string to an array of little-endian words * Characters >255 have their high-byte silently ignored. */ function rstr2binl(input) { var i, output = []; output[(input.length >> 2) - 1] = undefined; for (i = 0; i < output.length; i += 1) { output[i] = 0; } for (i = 0; i < input.length * 8; i += 8) { output[i >> 5] |= (input.charCodeAt(i / 8) & 0xFF) << (i % 32); } return output; } /* * Calculate the MD5 of a raw string */ function rstr_md5(s) { return binl2rstr(binl_md5(rstr2binl(s), s.length * 8)); } /* * Calculate the HMAC-MD5, of a key and some data (raw strings) */ function rstr_hmac_md5(key, data) { var i, bkey = rstr2binl(key), ipad = [], opad = [], hash; ipad[15] = opad[15] = undefined; if (bkey.length > 16) { bkey = binl_md5(bkey, key.length * 8); } for (i = 0; i < 16; i += 1) { ipad[i] = bkey[i] ^ 0x36363636; opad[i] = bkey[i] ^ 0x5C5C5C5C; } hash = binl_md5(ipad.concat(rstr2binl(data)), 512 + data.length * 8); return binl2rstr(binl_md5(opad.concat(hash), 512 + 128)); } /* * Convert a raw string to a hex string */ function rstr2hex(input) { var hex_tab = '0123456789abcdef', output = '', x, i; for (i = 0; i < input.length; i += 1) { x = input.charCodeAt(i); output += hex_tab.charAt((x >>> 4) & 0x0F) + hex_tab.charAt(x & 0x0F); } return output; } /* * Encode a string as utf-8 */ function str2rstr_utf8(input) { return unescape(encodeURIComponent(input)); } /* * Take string arguments and return either raw or hex encoded strings */ function raw_md5(s) { return rstr_md5(str2rstr_utf8(s)); } function hex_md5(s) { return rstr2hex(raw_md5(s)); } function raw_hmac_md5(k, d) { return rstr_hmac_md5(str2rstr_utf8(k), str2rstr_utf8(d)); } function hex_hmac_md5(k, d) { return rstr2hex(raw_hmac_md5(k, d)); } function md5(string, key, raw) { if (!key) { if (!raw) { return hex_md5(string); } return raw_md5(string); } if (!raw) { return hex_hmac_md5(key, string); } return raw_hmac_md5(key, string); } return md5; }()); var RongIMLib; (function (RongIMLib) { (function (MentionedType) { MentionedType[MentionedType["ALL"] = 1] = "ALL"; MentionedType[MentionedType["PART"] = 2] = "PART"; })(RongIMLib.MentionedType || (RongIMLib.MentionedType = {})); var MentionedType = RongIMLib.MentionedType; (function (MethodType) { MethodType[MethodType["CUSTOMER_SERVICE"] = 1] = "CUSTOMER_SERVICE"; MethodType[MethodType["RECALL"] = 2] = "RECALL"; })(RongIMLib.MethodType || (RongIMLib.MethodType = {})); var MethodType = RongIMLib.MethodType; (function (BlacklistStatus) { /** * 在黑名单中。 */ BlacklistStatus[BlacklistStatus["IN_BLACK_LIST"] = 0] = "IN_BLACK_LIST"; /** * 不在黑名单中。 */ BlacklistStatus[BlacklistStatus["NOT_IN_BLACK_LIST"] = 1] = "NOT_IN_BLACK_LIST"; })(RongIMLib.BlacklistStatus || (RongIMLib.BlacklistStatus = {})); var BlacklistStatus = RongIMLib.BlacklistStatus; (function (ConnectionChannel) { ConnectionChannel[ConnectionChannel["XHR_POLLING"] = 0] = "XHR_POLLING"; ConnectionChannel[ConnectionChannel["WEBSOCKET"] = 1] = "WEBSOCKET"; //外部调用 ConnectionChannel[ConnectionChannel["HTTP"] = 0] = "HTTP"; //外部调用 ConnectionChannel[ConnectionChannel["HTTPS"] = 1] = "HTTPS"; })(RongIMLib.ConnectionChannel || (RongIMLib.ConnectionChannel = {})); var ConnectionChannel = RongIMLib.ConnectionChannel; (function (CustomerType) { CustomerType[CustomerType["ONLY_ROBOT"] = 1] = "ONLY_ROBOT"; CustomerType[CustomerType["ONLY_HUMAN"] = 2] = "ONLY_HUMAN"; CustomerType[CustomerType["ROBOT_FIRST"] = 3] = "ROBOT_FIRST"; CustomerType[CustomerType["HUMAN_FIRST"] = 4] = "HUMAN_FIRST"; })(RongIMLib.CustomerType || (RongIMLib.CustomerType = {})); var CustomerType = RongIMLib.CustomerType; (function (GetChatRoomType) { GetChatRoomType[GetChatRoomType["NONE"] = 0] = "NONE"; GetChatRoomType[GetChatRoomType["SQQUENCE"] = 1] = "SQQUENCE"; GetChatRoomType[GetChatRoomType["REVERSE"] = 2] = "REVERSE"; })(RongIMLib.GetChatRoomType || (RongIMLib.GetChatRoomType = {})); var GetChatRoomType = RongIMLib.GetChatRoomType; (function (ConnectionStatus) { /** * 连接成功。 */ ConnectionStatus[ConnectionStatus["CONNECTED"] = 0] = "CONNECTED"; /** * 连接中。 */ ConnectionStatus[ConnectionStatus["CONNECTING"] = 1] = "CONNECTING"; /** * 断开连接。 */ ConnectionStatus[ConnectionStatus["DISCONNECTED"] = 2] = "DISCONNECTED"; /** * 用户账户在其他设备登录,本机会被踢掉线。 */ ConnectionStatus[ConnectionStatus["KICKED_OFFLINE_BY_OTHER_CLIENT"] = 6] = "KICKED_OFFLINE_BY_OTHER_CLIENT"; /** * websocket 连接失败 */ ConnectionStatus[ConnectionStatus["WEBSOCKET_UNAVAILABLE"] = 7] = "WEBSOCKET_UNAVAILABLE"; /** * websocket 报错 */ ConnectionStatus[ConnectionStatus["WEBSOCKET_ERROR"] = 8] = "WEBSOCKET_ERROR"; /** * 网络不可用。 */ ConnectionStatus[ConnectionStatus["NETWORK_UNAVAILABLE"] = 3] = "NETWORK_UNAVAILABLE"; /** * 域名错误 */ ConnectionStatus[ConnectionStatus["DOMAIN_INCORRECT"] = 12] = "DOMAIN_INCORRECT"; /** * appkey 不正确 */ ConnectionStatus[ConnectionStatus["APPKEY_IS_FAKE"] = 20] = "APPKEY_IS_FAKE"; /** * 连接关闭。 */ ConnectionStatus[ConnectionStatus["CONNECTION_CLOSED"] = 4] = "CONNECTION_CLOSED"; /* 互踢次数过多(count > 5),此时可能出现:在其它他设备登陆有 reconnect 逻辑 */ ConnectionStatus[ConnectionStatus["ULTRALIMIT"] = 1101] = "ULTRALIMIT"; /* 开始请求导航 */ ConnectionStatus[ConnectionStatus["REQUEST_NAVI"] = 201] = "REQUEST_NAVI"; /* 请求导航结束 */ ConnectionStatus[ConnectionStatus["RESPONSE_NAVI"] = 202] = "RESPONSE_NAVI"; /* 请求导航失败 */ ConnectionStatus[ConnectionStatus["RESPONSE_NAVI_ERROR"] = 203] = "RESPONSE_NAVI_ERROR"; /* 请求导航超时 */ ConnectionStatus[ConnectionStatus["RESPONSE_NAVI_TIMEOUT"] = 204] = "RESPONSE_NAVI_TIMEOUT"; })(RongIMLib.ConnectionStatus || (RongIMLib.ConnectionStatus = {})); var ConnectionStatus = RongIMLib.ConnectionStatus; (function (ConversationNotificationStatus) { /** * 免打扰状态,关闭对应会话的通知提醒。 */ ConversationNotificationStatus[ConversationNotificationStatus["DO_NOT_DISTURB"] = 0] = "DO_NOT_DISTURB"; /** * 提醒。 */ ConversationNotificationStatus[ConversationNotificationStatus["NOTIFY"] = 1] = "NOTIFY"; })(RongIMLib.ConversationNotificationStatus || (RongIMLib.ConversationNotificationStatus = {})); var ConversationNotificationStatus = RongIMLib.ConversationNotificationStatus; (function (ConversationType) { ConversationType[ConversationType["NONE"] = 0] = "NONE"; ConversationType[ConversationType["PRIVATE"] = 1] = "PRIVATE"; ConversationType[ConversationType["DISCUSSION"] = 2] = "DISCUSSION"; ConversationType[ConversationType["GROUP"] = 3] = "GROUP"; ConversationType[ConversationType["CHATROOM"] = 4] = "CHATROOM"; ConversationType[ConversationType["CUSTOMER_SERVICE"] = 5] = "CUSTOMER_SERVICE"; ConversationType[ConversationType["SYSTEM"] = 6] = "SYSTEM"; //默认关注 MC ConversationType[ConversationType["APP_PUBLIC_SERVICE"] = 7] = "APP_PUBLIC_SERVICE"; //手工关注 MP ConversationType[ConversationType["PUBLIC_SERVICE"] = 8] = "PUBLIC_SERVICE"; })(RongIMLib.ConversationType || (RongIMLib.ConversationType = {})); var ConversationType = RongIMLib.ConversationType; (function (DiscussionInviteStatus) { /** * 开放邀请。 */ DiscussionInviteStatus[DiscussionInviteStatus["OPENED"] = 0] = "OPENED"; /** * 关闭邀请。 */ DiscussionInviteStatus[DiscussionInviteStatus["CLOSED"] = 1] = "CLOSED"; })(RongIMLib.DiscussionInviteStatus || (RongIMLib.DiscussionInviteStatus = {})); var DiscussionInviteStatus = RongIMLib.DiscussionInviteStatus; (function (ErrorCode) { /* 超时 */ ErrorCode[ErrorCode["TIMEOUT"] = -1] = "TIMEOUT"; /** * 未知原因失败。 */ ErrorCode[ErrorCode["UNKNOWN"] = -2] = "UNKNOWN"; /* 参数错误 */ ErrorCode[ErrorCode["PARAMETER_ERROR"] = -3] = "PARAMETER_ERROR"; ErrorCode[ErrorCode["RECALL_MESSAGE"] = 25101] = "RECALL_MESSAGE"; /** * 发送频率过快 */ ErrorCode[ErrorCode["SEND_FREQUENCY_TOO_FAST"] = 20604] = "SEND_FREQUENCY_TOO_FAST"; ErrorCode[ErrorCode["RC_MSG_UNAUTHORIZED"] = 20406] = "RC_MSG_UNAUTHORIZED"; /** * 群组 Id 无效 */ ErrorCode[ErrorCode["RC_DISCUSSION_GROUP_ID_INVALID"] = 20407] = "RC_DISCUSSION_GROUP_ID_INVALID"; /** * 群组被禁言 */ ErrorCode[ErrorCode["FORBIDDEN_IN_GROUP"] = 22408] = "FORBIDDEN_IN_GROUP"; /** * 不在讨论组。 */ ErrorCode[ErrorCode["NOT_IN_DISCUSSION"] = 21406] = "NOT_IN_DISCUSSION"; /** * 不在群组。 */ ErrorCode[ErrorCode["NOT_IN_GROUP"] = 22406] = "NOT_IN_GROUP"; /** * 不在聊天室。 */ ErrorCode[ErrorCode["NOT_IN_CHATROOM"] = 23406] = "NOT_IN_CHATROOM"; /** *聊天室被禁言 */ ErrorCode[ErrorCode["FORBIDDEN_IN_CHATROOM"] = 23408] = "FORBIDDEN_IN_CHATROOM"; /** * 聊天室中成员被踢出 */ ErrorCode[ErrorCode["RC_CHATROOM_USER_KICKED"] = 23409] = "RC_CHATROOM_USER_KICKED"; /** * 聊天室不存在 */ ErrorCode[ErrorCode["RC_CHATROOM_NOT_EXIST"] = 23410] = "RC_CHATROOM_NOT_EXIST"; /** * 聊天室成员已满 */ ErrorCode[ErrorCode["RC_CHATROOM_IS_FULL"] = 23411] = "RC_CHATROOM_IS_FULL"; /** * 获取聊天室信息参数无效 */ ErrorCode[ErrorCode["RC_CHATROOM_PATAMETER_INVALID"] = 23412] = "RC_CHATROOM_PATAMETER_INVALID"; /** * 聊天室异常 */ ErrorCode[ErrorCode["CHATROOM_GET_HISTORYMSG_ERROR"] = 23413] = "CHATROOM_GET_HISTORYMSG_ERROR"; /** * 没有打开聊天室消息存储 */ ErrorCode[ErrorCode["CHATROOM_NOT_OPEN_HISTORYMSG_STORE"] = 23414] = "CHATROOM_NOT_OPEN_HISTORYMSG_STORE"; /** * 聊天室 KV 设置超出最大值(已满, 默认最多设置 100 个) */ ErrorCode[ErrorCode["CHATROOM_KV_EXCEED"] = 23423] = "CHATROOM_KV_EXCEED"; /** * 聊天室 KV 设置失败(kv 已存在, 需覆盖设置) */ ErrorCode[ErrorCode["CHATROOM_KV_OVERWRITE_INVALID"] = 23424] = "CHATROOM_KV_OVERWRITE_INVALID"; /** * 聊天室 KV 存储功能没有开通 */ ErrorCode[ErrorCode["CHATROOM_KV_STORE_NOT_OPEN"] = 23426] = "CHATROOM_KV_STORE_NOT_OPEN"; /** * 聊天室Key不存在 */ ErrorCode[ErrorCode["CHATROOM_KEY_NOT_EXIST"] = 23427] = "CHATROOM_KEY_NOT_EXIST"; /** * 敏感词屏蔽 */ ErrorCode[ErrorCode["SENSITIVE_SHIELD"] = 21501] = "SENSITIVE_SHIELD"; ErrorCode[ErrorCode["SENSITIVE_REPLACE"] = 21502] = "SENSITIVE_REPLACE"; /** * 加入讨论失败 */ ErrorCode[ErrorCode["JOIN_IN_DISCUSSION"] = 21407] = "JOIN_IN_DISCUSSION"; /** * 创建讨论组失败 */ ErrorCode[ErrorCode["CREATE_DISCUSSION"] = 21408] = "CREATE_DISCUSSION"; /** * 设置讨论组邀请状态失败 */ ErrorCode[ErrorCode["INVITE_DICUSSION"] = 21409] = "INVITE_DICUSSION"; /** *获取用户失败 */ ErrorCode[ErrorCode["GET_USERINFO_ERROR"] = 23407] = "GET_USERINFO_ERROR"; /** * 在黑名单中。 */ ErrorCode[ErrorCode["REJECTED_BY_BLACKLIST"] = 405] = "REJECTED_BY_BLACKLIST"; /** * 通信过程中,当前 Socket 不存在。 */ ErrorCode[ErrorCode["RC_NET_CHANNEL_INVALID"] = 30001] = "RC_NET_CHANNEL_INVALID"; /** * Socket 连接不可用。 */ ErrorCode[ErrorCode["RC_NET_UNAVAILABLE"] = 30002] = "RC_NET_UNAVAILABLE"; /** * 通信超时。 */ ErrorCode[ErrorCode["RC_MSG_RESP_TIMEOUT"] = 30003] = "RC_MSG_RESP_TIMEOUT"; /** * 导航操作时,Http 请求失败。 */ ErrorCode[ErrorCode["RC_HTTP_SEND_FAIL"] = 30004] = "RC_HTTP_SEND_FAIL"; /** * HTTP 请求失败。 */ ErrorCode[ErrorCode["RC_HTTP_REQ_TIMEOUT"] = 30005] = "RC_HTTP_REQ_TIMEOUT"; /** * HTTP 接收失败。 */ ErrorCode[ErrorCode["RC_HTTP_RECV_FAIL"] = 30006] = "RC_HTTP_RECV_FAIL"; /** * 导航操作的 HTTP 请求,返回不是200。 */ ErrorCode[ErrorCode["RC_NAVI_RESOURCE_ERROR"] = 30007] = "RC_NAVI_RESOURCE_ERROR"; /** * 导航数据解析后,其中不存在有效数据。 */ ErrorCode[ErrorCode["RC_NODE_NOT_FOUND"] = 30008] = "RC_NODE_NOT_FOUND"; /** * 导航数据解析后,其中不存在有效 IP 地址。 */ ErrorCode[ErrorCode["RC_DOMAIN_NOT_RESOLVE"] = 30009] = "RC_DOMAIN_NOT_RESOLVE"; /** * 创建 Socket 失败。 */ ErrorCode[ErrorCode["RC_SOCKET_NOT_CREATED"] = 30010] = "RC_SOCKET_NOT_CREATED"; /** * Socket 被断开。 */ ErrorCode[ErrorCode["RC_SOCKET_DISCONNECTED"] = 30011] = "RC_SOCKET_DISCONNECTED"; /** * PING 操作失败。 */ ErrorCode[ErrorCode["RC_PING_SEND_FAIL"] = 30012] = "RC_PING_SEND_FAIL"; /** * PING 超时。 */ ErrorCode[ErrorCode["RC_PONG_RECV_FAIL"] = 30013] = "RC_PONG_RECV_FAIL"; /** * 消息发送失败。 */ ErrorCode[ErrorCode["RC_MSG_SEND_FAIL"] = 30014] = "RC_MSG_SEND_FAIL"; /** * 做 connect 连接时,收到的 ACK 超时。 */ ErrorCode[ErrorCode["RC_CONN_ACK_TIMEOUT"] = 31000] = "RC_CONN_ACK_TIMEOUT"; /** * 参数错误。 */ ErrorCode[ErrorCode["RC_CONN_PROTO_VERSION_ERROR"] = 31001] = "RC_CONN_PROTO_VERSION_ERROR"; /** * 参数错误,App Id 错误。 */ ErrorCode[ErrorCode["RC_CONN_ID_REJECT"] = 31002] = "RC_CONN_ID_REJECT"; /** * 服务器不可用。 */ ErrorCode[ErrorCode["RC_CONN_SERVER_UNAVAILABLE"] = 31003] = "RC_CONN_SERVER_UNAVAILABLE"; /** * Token 错误。 */ ErrorCode[ErrorCode["RC_CONN_USER_OR_PASSWD_ERROR"] = 31004] = "RC_CONN_USER_OR_PASSWD_ERROR"; /** * App Id 与 Token 不匹配。 */ ErrorCode[ErrorCode["RC_CONN_NOT_AUTHRORIZED"] = 31005] = "RC_CONN_NOT_AUTHRORIZED"; /** * 重定向,地址错误。 */ ErrorCode[ErrorCode["RC_CONN_REDIRECTED"] = 31006] = "RC_CONN_REDIRECTED"; /** * NAME 与后台注册信息不一致。 */ ErrorCode[ErrorCode["RC_CONN_PACKAGE_NAME_INVALID"] = 31007] = "RC_CONN_PACKAGE_NAME_INVALID"; /** * APP 被屏蔽、删除或不存在。 */ ErrorCode[ErrorCode["RC_CONN_APP_BLOCKED_OR_DELETED"] = 31008] = "RC_CONN_APP_BLOCKED_OR_DELETED"; /** * 用户被屏蔽。 */ ErrorCode[ErrorCode["RC_CONN_USER_BLOCKED"] = 31009] = "RC_CONN_USER_BLOCKED"; /** * Disconnect,由服务器返回,比如用户互踢。 */ ErrorCode[ErrorCode["RC_DISCONN_KICK"] = 31010] = "RC_DISCONN_KICK"; /** * Disconnect,由服务器返回,比如用户互踢。 */ ErrorCode[ErrorCode["RC_DISCONN_EXCEPTION"] = 31011] = "RC_DISCONN_EXCEPTION"; /** * 协议层内部错误。query,上传下载过程中数据错误。 */ ErrorCode[ErrorCode["RC_QUERY_ACK_NO_DATA"] = 32001] = "RC_QUERY_ACK_NO_DATA"; /** * 协议层内部错误。 */ ErrorCode[ErrorCode["RC_MSG_DATA_INCOMPLETE"] = 32002] = "RC_MSG_DATA_INCOMPLETE"; /** * 未调用 init 初始化函数。 */ ErrorCode[ErrorCode["BIZ_ERROR_CLIENT_NOT_INIT"] = 33001] = "BIZ_ERROR_CLIENT_NOT_INIT"; /** * 数据库初始化失败。 */ ErrorCode[ErrorCode["BIZ_ERROR_DATABASE_ERROR"] = 33002] = "BIZ_ERROR_DATABASE_ERROR"; /** * 传入参数无效。 */ ErrorCode[ErrorCode["BIZ_ERROR_INVALID_PARAMETER"] = 33003] = "BIZ_ERROR_INVALID_PARAMETER"; /** * 通道无效。 */ ErrorCode[ErrorCode["BIZ_ERROR_NO_CHANNEL"] = 33004] = "BIZ_ERROR_NO_CHANNEL"; /** * 重新连接成功。 */ ErrorCode[ErrorCode["BIZ_ERROR_RECONNECT_SUCCESS"] = 33005] = "BIZ_ERROR_RECONNECT_SUCCESS"; /** * 连接中,再调用 connect 被拒绝。 */ ErrorCode[ErrorCode["BIZ_ERROR_CONNECTING"] = 33006] = "BIZ_ERROR_CONNECTING"; /** * 消息漫游服务未开通 */ ErrorCode[ErrorCode["MSG_ROAMING_SERVICE_UNAVAILABLE"] = 33007] = "MSG_ROAMING_SERVICE_UNAVAILABLE"; ErrorCode[ErrorCode["MSG_INSERT_ERROR"] = 33008] = "MSG_INSERT_ERROR"; ErrorCode[ErrorCode["MSG_DEL_ERROR"] = 33009] = "MSG_DEL_ERROR"; /** * 删除会话失败 */ ErrorCode[ErrorCode["CONVER_REMOVE_ERROR"] = 34001] = "CONVER_REMOVE_ERROR"; /** *拉取历史消息 */ ErrorCode[ErrorCode["CONVER_GETLIST_ERROR"] = 34002] = "CONVER_GETLIST_ERROR"; /** * 会话指定异常 */ ErrorCode[ErrorCode["CONVER_SETOP_ERROR"] = 34003] = "CONVER_SETOP_ERROR"; /** * 获取会话未读消息总数失败 */ ErrorCode[ErrorCode["CONVER_TOTAL_UNREAD_ERROR"] = 34004] = "CONVER_TOTAL_UNREAD_ERROR"; /** * 获取指定会话类型未读消息数异常 */ ErrorCode[ErrorCode["CONVER_TYPE_UNREAD_ERROR"] = 34005] = "CONVER_TYPE_UNREAD_ERROR"; /** * 获取指定用户ID&会话类型未读消息数异常 */ ErrorCode[ErrorCode["CONVER_ID_TYPE_UNREAD_ERROR"] = 34006] = "CONVER_ID_TYPE_UNREAD_ERROR"; ErrorCode[ErrorCode["CONVER_CLEAR_ERROR"] = 34007] = "CONVER_CLEAR_ERROR"; ErrorCode[ErrorCode["CLEAR_HIS_ERROR"] = 34010] = "CLEAR_HIS_ERROR"; ErrorCode[ErrorCode["CLEAR_HIS_TYPE_ERROR"] = 34008] = "CLEAR_HIS_TYPE_ERROR"; ErrorCode[ErrorCode["CLEAR_HIS_TIME_ERROR"] = 34011] = "CLEAR_HIS_TIME_ERROR"; /* */ ErrorCode[ErrorCode["CONVER_GET_ERROR"] = 34009] = "CONVER_GET_ERROR"; //群组异常信息 /** * */ ErrorCode[ErrorCode["GROUP_SYNC_ERROR"] = 35001] = "GROUP_SYNC_ERROR"; /** * 匹配群信息异常 */ ErrorCode[ErrorCode["GROUP_MATCH_ERROR"] = 35002] = "GROUP_MATCH_ERROR"; //聊天室异常 /** * 加入聊天室Id为空 */ ErrorCode[ErrorCode["CHATROOM_ID_ISNULL"] = 36001] = "CHATROOM_ID_ISNULL"; /** * 加入聊天室失败 */ ErrorCode[ErrorCode["CHARTOOM_JOIN_ERROR"] = 36002] = "CHARTOOM_JOIN_ERROR"; /** * 拉取聊天室历史消息失败 */ ErrorCode[ErrorCode["CHATROOM_HISMESSAGE_ERROR"] = 36003] = "CHATROOM_HISMESSAGE_ERROR"; /** * 聊天室 kv 未找到 * */ ErrorCode[ErrorCode["CHATROOM_KV_NOT_FOUND"] = 36004] = "CHATROOM_KV_NOT_FOUND"; //黑名单异常 /** * 加入黑名单异常 */ ErrorCode[ErrorCode["BLACK_ADD_ERROR"] = 37001] = "BLACK_ADD_ERROR"; /** * 获得指定人员再黑名单中的状态异常 */ ErrorCode[ErrorCode["BLACK_GETSTATUS_ERROR"] = 37002] = "BLACK_GETSTATUS_ERROR"; /** * 移除黑名单异常 */ ErrorCode[ErrorCode["BLACK_REMOVE_ERROR"] = 37003] = "BLACK_REMOVE_ERROR"; /** * 获取草稿失败 */ ErrorCode[ErrorCode["DRAF_GET_ERROR"] = 38001] = "DRAF_GET_ERROR"; /** * 保存草稿失败 */ ErrorCode[ErrorCode["DRAF_SAVE_ERROR"] = 38002] = "DRAF_SAVE_ERROR"; /** * 删除草稿失败 */ ErrorCode[ErrorCode["DRAF_REMOVE_ERROR"] = 38003] = "DRAF_REMOVE_ERROR"; /** * 关注公众号失败 */ ErrorCode[ErrorCode["SUBSCRIBE_ERROR"] = 39001] = "SUBSCRIBE_ERROR"; /** * 关注公众号失败 */ ErrorCode[ErrorCode["QNTKN_FILETYPE_ERROR"] = 41001] = "QNTKN_FILETYPE_ERROR"; /** * 获取七牛token失败 */ ErrorCode[ErrorCode["QNTKN_GET_ERROR"] = 41002] = "QNTKN_GET_ERROR"; /** * cookie被禁用 */ ErrorCode[ErrorCode["COOKIE_ENABLE"] = 51001] = "COOKIE_ENABLE"; ErrorCode[ErrorCode["GET_MESSAGE_BY_ID_ERROR"] = 61001] = "GET_MESSAGE_BY_ID_ERROR"; // 没有注册DeviveId 也就是用户没有登陆 ErrorCode[ErrorCode["HAVNODEVICEID"] = 24001] = "HAVNODEVICEID"; // 已经存在 ErrorCode[ErrorCode["DEVICEIDISHAVE"] = 24002] = "DEVICEIDISHAVE"; // 成功 ErrorCode[ErrorCode["SUCCESS"] = 0] = "SUCCESS"; // 没有对应的用户或token ErrorCode[ErrorCode["FEILD"] = 24009] = "FEILD"; // voip为空 ErrorCode[ErrorCode["VOIPISNULL"] = 24013] = "VOIPISNULL"; // 不支持的Voip引擎 ErrorCode[ErrorCode["NOENGINETYPE"] = 24010] = "NOENGINETYPE"; // channleName 是空 ErrorCode[ErrorCode["NULLCHANNELNAME"] = 24011] = "NULLCHANNELNAME"; // 生成Voipkey失败 ErrorCode[ErrorCode["VOIPDYANMICERROR"] = 24012] = "VOIPDYANMICERROR"; // 没有配置voip ErrorCode[ErrorCode["NOVOIP"] = 24014] = "NOVOIP"; // 服务器内部错误 ErrorCode[ErrorCode["INTERNALERRROR"] = 24015] = "INTERNALERRROR"; //VOIP close ErrorCode[ErrorCode["VOIPCLOSE"] = 24016] = "VOIPCLOSE"; ErrorCode[ErrorCode["CLOSE_BEFORE_OPEN"] = 51001] = "CLOSE_BEFORE_OPEN"; ErrorCode[ErrorCode["ALREADY_IN_USE"] = 51002] = "ALREADY_IN_USE"; ErrorCode[ErrorCode["INVALID_CHANNEL_NAME"] = 51003] = "INVALID_CHANNEL_NAME"; ErrorCode[ErrorCode["VIDEO_CONTAINER_IS_NULL"] = 51004] = "VIDEO_CONTAINER_IS_NULL"; /** * 删除消息数组长度为 0 . */ ErrorCode[ErrorCode["DELETE_MESSAGE_ID_IS_NULL"] = 61001] = "DELETE_MESSAGE_ID_IS_NULL"; /*! 己方取消已发出的通话请求 */ ErrorCode[ErrorCode["CANCEL"] = 1] = "CANCEL"; /*! 己方拒绝收到的通话请求 */ ErrorCode[ErrorCode["REJECT"] = 2] = "REJECT"; /*! 己方挂断 */ ErrorCode[ErrorCode["HANGUP"] = 3] = "HANGUP"; /*! 己方忙碌 */ ErrorCode[ErrorCode["BUSYLINE"] = 4] = "BUSYLINE"; /*! 己方未接听 */ ErrorCode[ErrorCode["NO_RESPONSE"] = 5] = "NO_RESPONSE"; /*! 己方不支持当前引擎 */ ErrorCode[ErrorCode["ENGINE_UN_SUPPORTED"] = 6] = "ENGINE_UN_SUPPORTED"; /*! 己方网络出错 */ ErrorCode[ErrorCode["NETWORK_ERROR"] = 7] = "NETWORK_ERROR"; /*! 对方取消已发出的通话请求 */ ErrorCode[ErrorCode["REMOTE_CANCEL"] = 11] = "REMOTE_CANCEL"; /*! 对方拒绝收到的通话请求 */ ErrorCode[ErrorCode["REMOTE_REJECT"] = 12] = "REMOTE_REJECT"; /*! 通话过程对方挂断 */ ErrorCode[ErrorCode["REMOTE_HANGUP"] = 13] = "REMOTE_HANGUP"; /*! 对方忙碌 */ ErrorCode[ErrorCode["REMOTE_BUSYLINE"] = 14] = "REMOTE_BUSYLINE"; /*! 对方未接听 */ ErrorCode[ErrorCode["REMOTE_NO_RESPONSE"] = 15] = "REMOTE_NO_RESPONSE"; /*! 对方网络错误 */ ErrorCode[ErrorCode["REMOTE_ENGINE_UN_SUPPORTED"] = 16] = "REMOTE_ENGINE_UN_SUPPORTED"; /*! 对方网络错误 */ ErrorCode[ErrorCode["REMOTE_NETWORK_ERROR"] = 17] = "REMOTE_NETWORK_ERROR"; /*! VoIP 不可用 */ ErrorCode[ErrorCode["VOIP_NOT_AVALIABLE"] = 18] = "VOIP_NOT_AVALIABLE"; })(RongIMLib.ErrorCode || (RongIMLib.ErrorCode = {})); var ErrorCode = RongIMLib.ErrorCode; (function (VoIPMediaType) { VoIPMediaType[VoIPMediaType["MEDIA_AUDIO"] = 1] = "MEDIA_AUDIO"; VoIPMediaType[VoIPMediaType["MEDIA_VEDIO"] = 2] = "MEDIA_VEDIO"; VoIPMediaType[VoIPMediaType["MEDIA_VIDEO"] = 2] = "MEDIA_VIDEO"; })(RongIMLib.VoIPMediaType || (RongIMLib.VoIPMediaType = {})); var VoIPMediaType = RongIMLib.VoIPMediaType; (function (MediaType) { /** * 图片。 */ MediaType[MediaType["IMAGE"] = 1] = "IMAGE"; /** * 声音。 */ MediaType[MediaType["AUDIO"] = 2] = "AUDIO"; /** * 视频。 */ MediaType[MediaType["VIDEO"] = 3] = "VIDEO"; /** * 通用文件。 */ MediaType[MediaType["FILE"] = 100] = "FILE"; })(RongIMLib.MediaType || (RongIMLib.MediaType = {})); var MediaType = RongIMLib.MediaType; (function (MessageDirection) { /** * 发送消息。 */ MessageDirection[MessageDirection["SEND"] = 1] = "SEND"; /** * 接收消息。 */ MessageDirection[MessageDirection["RECEIVE"] = 2] = "RECEIVE"; })(RongIMLib.MessageDirection || (RongIMLib.MessageDirection = {})); var MessageDirection = RongIMLib.MessageDirection; (function (FileType) { FileType[FileType["IMAGE"] = 1] = "IMAGE"; FileType[FileType["AUDIO"] = 2] = "AUDIO"; FileType[FileType["VIDEO"] = 3] = "VIDEO"; FileType[FileType["FILE"] = 4] = "FILE"; })(RongIMLib.FileType || (RongIMLib.FileType = {})); var FileType = RongIMLib.FileType; (function (RealTimeLocationErrorCode) { /** * 未初始化 RealTimeLocation 实例 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_NOT_INIT"] = -1] = "RC_REAL_TIME_LOCATION_NOT_INIT"; /** * 执行成功。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_SUCCESS"] = 0] = "RC_REAL_TIME_LOCATION_SUCCESS"; /** * 获取 RealTimeLocation 实例时返回 * GPS 未打开。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_GPS_DISABLED"] = 1] = "RC_REAL_TIME_LOCATION_GPS_DISABLED"; /** * 获取 RealTimeLocation 实例时返回 * 当前会话不支持位置共享。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_CONVERSATION_NOT_SUPPORT"] = 2] = "RC_REAL_TIME_LOCATION_CONVERSATION_NOT_SUPPORT"; /** * 获取 RealTimeLocation 实例时返回 * 对方已发起位置共享。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_IS_ON_GOING"] = 3] = "RC_REAL_TIME_LOCATION_IS_ON_GOING"; /** * Join 时返回 * 当前位置共享已超过最大支持人数。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_EXCEED_MAX_PARTICIPANT"] = 4] = "RC_REAL_TIME_LOCATION_EXCEED_MAX_PARTICIPANT"; /** * Join 时返回 * 加入位置共享失败。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_JOIN_FAILURE"] = 5] = "RC_REAL_TIME_LOCATION_JOIN_FAILURE"; /** * Start 时返回 * 发起位置共享失败。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_START_FAILURE"] = 6] = "RC_REAL_TIME_LOCATION_START_FAILURE"; /** * 网络不可用。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_NETWORK_UNAVAILABLE"] = 7] = "RC_REAL_TIME_LOCATION_NETWORK_UNAVAILABLE"; })(RongIMLib.RealTimeLocationErrorCode || (RongIMLib.RealTimeLocationErrorCode = {})); var RealTimeLocationErrorCode = RongIMLib.RealTimeLocationErrorCode; (function (RealTimeLocationStatus) { /** * 空闲状态 (默认状态) * 对方或者自己都未发起位置共享业务,或者位置共享业务已结束。 */ RealTimeLocationStatus[RealTimeLocationStatus["RC_REAL_TIME_LOCATION_STATUS_IDLE"] = 0] = "RC_REAL_TIME_LOCATION_STATUS_IDLE"; /** * 呼入状态 (待加入) * 1. 对方发起了位置共享业务,此状态下,自己只能选择加入。 * 2. 自己从已连接的位置共享中退出。 */ RealTimeLocationStatus[RealTimeLocationStatus["RC_REAL_TIME_LOCATION_STATUS_INCOMING"] = 1] = "RC_REAL_TIME_LOCATION_STATUS_INCOMING"; /** * 呼出状态 =(自己创建) * 1. 自己发起位置共享业务,对方只能选择加入。 * 2. 对方从已连接的位置共享业务中退出。 */ RealTimeLocationStatus[RealTimeLocationStatus["RC_REAL_TIME_LOCATION_STATUS_OUTGOING"] = 2] = "RC_REAL_TIME_LOCATION_STATUS_OUTGOING"; /** * 连接状态 (自己加入) * 对方加入了自己发起的位置共享,或者自己加入了对方发起的位置共享。 */ RealTimeLocationStatus[RealTimeLocationStatus["RC_REAL_TIME_LOCATION_STATUS_CONNECTED"] = 3] = "RC_REAL_TIME_LOCATION_STATUS_CONNECTED"; })(RongIMLib.RealTimeLocationStatus || (RongIMLib.RealTimeLocationStatus = {})); var RealTimeLocationStatus = RongIMLib.RealTimeLocationStatus; (function (ReceivedStatus) { ReceivedStatus[ReceivedStatus["READ"] = 1] = "READ"; ReceivedStatus[ReceivedStatus["LISTENED"] = 2] = "LISTENED"; ReceivedStatus[ReceivedStatus["DOWNLOADED"] = 4] = "DOWNLOADED"; ReceivedStatus[ReceivedStatus["RETRIEVED"] = 8] = "RETRIEVED"; ReceivedStatus[ReceivedStatus["UNREAD"] = 0] = "UNREAD"; })(RongIMLib.ReceivedStatus || (RongIMLib.ReceivedStatus = {})); var ReceivedStatus = RongIMLib.ReceivedStatus; (function (ReadStatus) { ReadStatus[ReadStatus["READ"] = 1] = "READ"; ReadStatus[ReadStatus["LISTENED"] = 2] = "LISTENED"; ReadStatus[ReadStatus["DOWNLOADED"] = 4] = "DOWNLOADED"; ReadStatus[ReadStatus["RETRIEVED"] = 8] = "RETRIEVED"; ReadStatus[ReadStatus["UNREAD"] = 0] = "UNREAD"; })(RongIMLib.ReadStatus || (RongIMLib.ReadStatus = {})); var ReadStatus = RongIMLib.ReadStatus; (function (SearchType) { /** * 精确。 */ SearchType[SearchType["EXACT"] = 0] = "EXACT"; /** * 模糊。 */ SearchType[SearchType["FUZZY"] = 1] = "FUZZY"; })(RongIMLib.SearchType || (RongIMLib.SearchType = {})); var SearchType = RongIMLib.SearchType; (function (SentStatus) { /** * 发送中。 */ SentStatus[SentStatus["SENDING"] = 10] = "SENDING"; /** * 发送失败。 */ SentStatus[SentStatus["FAILED"] = 20] = "FAILED"; /** * 已发送。 */ SentStatus[SentStatus["SENT"] = 30] = "SENT"; /** * 对方已接收。 */ SentStatus[SentStatus["RECEIVED"] = 40] = "RECEIVED"; /** * 对方已读。 */ SentStatus[SentStatus["READ"] = 50] = "READ"; /** * 对方已销毁。 */ SentStatus[SentStatus["DESTROYED"] = 60] = "DESTROYED"; })(RongIMLib.SentStatus || (RongIMLib.SentStatus = {})); var SentStatus = RongIMLib.SentStatus; (function (ConnectionState) { ConnectionState[ConnectionState["ACCEPTED"] = 0] = "ACCEPTED"; ConnectionState[ConnectionState["UNACCEPTABLE_PROTOCOL_VERSION"] = 1] = "UNACCEPTABLE_PROTOCOL_VERSION"; ConnectionState[ConnectionState["IDENTIFIER_REJECTED"] = 2] = "IDENTIFIER_REJECTED"; ConnectionState[ConnectionState["SERVER_UNAVAILABLE"] = 3] = "SERVER_UNAVAILABLE"; /** * token无效 */ ConnectionState[ConnectionState["TOKEN_INCORRECT"] = 4] = "TOKEN_INCORRECT"; ConnectionState[ConnectionState["NOT_AUTHORIZED"] = 5] = "NOT_AUTHORIZED"; ConnectionState[ConnectionState["REDIRECT"] = 6] = "REDIRECT"; ConnectionState[ConnectionState["PACKAGE_ERROR"] = 7] = "PACKAGE_ERROR"; ConnectionState[ConnectionState["APP_BLOCK_OR_DELETE"] = 8] = "APP_BLOCK_OR_DELETE"; ConnectionState[ConnectionState["BLOCK"] = 9] = "BLOCK"; ConnectionState[ConnectionState["TOKEN_EXPIRE"] = 10] = "TOKEN_EXPIRE"; ConnectionState[ConnectionState["DEVICE_ERROR"] = 11] = "DEVICE_ERROR"; })(RongIMLib.ConnectionState || (RongIMLib.ConnectionState = {})); var ConnectionState = RongIMLib.ConnectionState; (function (RTCAPIType) { RTCAPIType[RTCAPIType["ROOM"] = 1] = "ROOM"; RTCAPIType[RTCAPIType["PERSON"] = 2] = "PERSON"; })(RongIMLib.RTCAPIType || (RongIMLib.RTCAPIType = {})); var RTCAPIType = RongIMLib.RTCAPIType; (function (ChatroomEntityOpt) { ChatroomEntityOpt[ChatroomEntityOpt["UPDATE"] = 1] = "UPDATE"; ChatroomEntityOpt[ChatroomEntityOpt["DELETE"] = 2] = "DELETE"; })(RongIMLib.ChatroomEntityOpt || (RongIMLib.ChatroomEntityOpt = {})); var ChatroomEntityOpt = RongIMLib.ChatroomEntityOpt; (function (ChatroomEntityLimit) { ChatroomEntityLimit[ChatroomEntityLimit["KEY"] = 128] = "KEY"; ChatroomEntityLimit[ChatroomEntityLimit["VALUE"] = 4096] = "VALUE"; })(RongIMLib.ChatroomEntityLimit || (RongIMLib.ChatroomEntityLimit = {})); var ChatroomEntityLimit = RongIMLib.ChatroomEntityLimit; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var RongIMClient = (function () { function RongIMClient() { } RongIMClient.getInstance = function () { if (!RongIMClient._instance) { throw new Error("RongIMClient is not initialized. Call .init() method first."); } return RongIMClient._instance; }; RongIMClient.showError = function (errorInfo) { var hasConsole = (console && console.error); if (hasConsole) { console.error(JSON.stringify(errorInfo)); } }; RongIMClient.logger = function (params) { var code = params.code; var errorInfo = RongIMClient.LogFactory[code] || params; errorInfo.funcName = params.funcName; errorInfo.msg = params.msg || errorInfo.msg; if (RongIMClient._memoryStore.depend.showError) { RongIMClient.showError(errorInfo); } }; RongIMClient.logCallback = function (callback, funcName) { return { onSuccess: callback.onSuccess, onError: function (errorCode) { RongIMClient.logger({ code: errorCode, funcName: funcName }); callback.onError(errorCode); } }; }; ; RongIMClient.logSendCallback = function (callback, funcName) { return { onSuccess: callback.onSuccess, onError: function (errorCode, result) { RongIMClient.logger({ code: errorCode, funcName: funcName }); callback.onError(errorCode, result); }, onBefore: callback.onBefore }; }; ; /** * 初始化 SDK,在整个应用全局只需要调用一次。 * @param appKey 开发者后台申请的 AppKey,用来标识应用。 * @param dataAccessProvider 必须是DataAccessProvider的实例 */ RongIMClient.init = function (appKey, dataAccessProvider, options, callback) { RongIMClient.statusListeners = []; RongIMClient.messageListeners = []; if (RongIMClient._instance) { return RongIMClient._memoryStore.sdkInfo; } RongIMClient._instance = new RongIMClient(); options = options || {}; var protocol = "http://", wsScheme = 'ws://'; var isLocationInvalid = typeof location !== 'object'; // 未找到全局 location 变量, 则协议为 https. 比如小程序 if (isLocationInvalid || location.protocol == 'https:') { wsScheme = 'wss://'; protocol = 'https://'; } var isPolling = false; if (typeof WebSocket != 'function') { isPolling = true; } var isIntegrity = function () { //iOS 9 var hasWS = (typeof WebSocket); var integrity = (typeof WebSocket.OPEN == 'number'); return (hasWS && integrity); }; if (typeof WebSocket == 'object' && isIntegrity()) { isPolling = false; } var supportUserData = function () { var element = document.documentElement; return element.addBehavior; }; if (RongIMLib.RongUtil.supportLocalStorage()) { RongIMClient._storageProvider = new RongIMLib.LocalStorageProvider(); } else if (supportUserData()) { RongIMClient._storageProvider = new RongIMLib.UserDataProvider(); } else { RongIMClient._storageProvider = new RongIMLib.MemeoryProvider(); } var serverIndex = RongIMClient._storageProvider.getItem('serverIndex'); RongIMClient.serverStore.index = serverIndex || 0; var pathTmpl = '{0}{1}'; var _serverPath = { api: 'api.cn.ronghub.com' }; RongIMLib.RongUtil.forEach(_serverPath, function (path, key) { _serverPath[key] = RongIMLib.RongUtil.stringFormat(pathTmpl, [protocol, path]); }); RongIMLib.RongUtil.forEach(_serverPath, function (path, key) { var hasProto = (key in options); var config = { path: options[key], tmpl: pathTmpl, protocol: protocol, sub: true }; path = hasProto ? RongIMLib.RongUtil.formatProtoclPath(config) : path; options[key] = path; }); var navigaters = options.navigaters || []; if (options.navi) { navigaters = [options.navi]; } if (!options.navi && RongIMLib.RongUtil.isEqual(navigaters.length, 0)) { navigaters = ['nav.cn.ronghub.com', 'nav2-cn.ronghub.com']; } RongIMLib.RongUtil.forEach(navigaters, function (navi, index) { var config = { path: navi, tmpl: pathTmpl, protocol: protocol, sub: true }; navi = RongIMLib.RongUtil.formatProtoclPath(config); navigaters[index] = navi; }); var _sourcePath = { protobuf: 'cdn.ronghub.com/protobuf-2.3.7.min.js' }; RongIMLib.RongUtil.forEach(_sourcePath, function (path, key) { _sourcePath[key] = RongIMLib.RongUtil.stringFormat(pathTmpl, [protocol, path]); }); RongIMLib.RongUtil.extend(_sourcePath, options); var _defaultOpts = { isPolling: isPolling, wsScheme: wsScheme, protocol: protocol, showError: true, openMp: true, snifferTime: 2000, naviTimeout: 5000, navigaters: navigaters, maxNaviRetry: 10, isNaviJSONP: false, isWSPingJSONP: false, isNotifyConversationList: false, maxConversationCount: 300, cmpUrl: '' // 若传入 cmpUrl, 则优先链接此地址 }; delete options.navigaters; RongIMLib.RongUtil.extend(_defaultOpts, options); if (RongIMLib.RongUtil.isFunction(options.protobuf)) { RongIMClient.Protobuf = options.protobuf; } RongIMClient.userStatusObserver = new RongIMLib.RongObserver(); var pather = new RongIMLib.FeaturePatcher(); pather.patchAll(); var tempStore = { token: "", callback: null, lastReadTime: new RongIMLib.LimitableMap(), historyMessageLimit: new RongIMLib.MemoryCache(), conversationList: [], appKey: appKey, publicServiceMap: new RongIMLib.PublicServiceMap(), providerType: 1, deltaTime: 0, filterMessages: [], isSyncRemoteConverList: true, otherDevice: false, custStore: {}, converStore: { latestMessage: {} }, connectAckTime: 0, voipStategy: 0, isFirstPingMsg: true, depend: options, notification: {} }; RongIMClient._memoryStore = tempStore; var isCPlusSDK = dataAccessProvider && Object.prototype.toString.call(dataAccessProvider) == "[object Object]"; if (isCPlusSDK) { RongIMClient._dataAccessProvider = dataAccessProvider; } else { RongIMClient._dataAccessProvider = new RongIMLib.ServerDataProvider(); } options.appCallback = callback; var sdkInfo = RongIMClient._dataAccessProvider.init(appKey, options); RongIMClient._memoryStore.sdkInfo = sdkInfo; if (isCPlusSDK) { // 兼容 c++ 设置导航,Web 端不生效 RongIMClient._dataAccessProvider.setServerInfo({ navi: location.protocol + options.navi + '/navi.xml' }); } RongIMClient.MessageParams = { TextMessage: { objectName: "RC:TxtMsg", msgTag: new RongIMLib.MessageTag(true, true) }, ImageMessage: { objectName: "RC:ImgMsg", msgTag: new RongIMLib.MessageTag(true, true) }, DiscussionNotificationMessage: { objectName: "RC:DizNtf", msgTag: new RongIMLib.MessageTag(false, true) }, VoiceMessage: { objectName: "RC:VcMsg", msgTag: new RongIMLib.MessageTag(true, true) }, RichContentMessage: { objectName: "RC:ImgTextMsg", msgTag: new RongIMLib.MessageTag(true, true) }, FileMessage: { objectName: "RC:FileMsg", msgTag: new RongIMLib.MessageTag(true, true) }, HQVoiceMessage: { objectName: "RC:HQVCMsg", msgTag: new RongIMLib.MessageTag(true, true) }, HandshakeMessage: { objectName: "", msgTag: new RongIMLib.MessageTag(true, true) }, UnknownMessage: { objectName: "", msgTag: new RongIMLib.MessageTag(true, true) }, LocationMessage: { objectName: "RC:LBSMsg", msgTag: new RongIMLib.MessageTag(true, true) }, InformationNotificationMessage: { objectName: "RC:InfoNtf", msgTag: new RongIMLib.MessageTag(false, true) }, ContactNotificationMessage: { objectName: "RC:ContactNtf", msgTag: new RongIMLib.MessageTag(false, true) }, ProfileNotificationMessage: { objectName: "RC:ProfileNtf", msgTag: new RongIMLib.MessageTag(false, true) }, CommandNotificationMessage: { objectName: "RC:CmdNtf", msgTag: new RongIMLib.MessageTag(false, true) }, PublicServiceRichContentMessage: { objectName: "RC:PSImgTxtMsg", msgTag: new RongIMLib.MessageTag(true, true) }, PublicServiceMultiRichContentMessage: { objectName: "RC:PSMultiImgTxtMsg", msgTag: new RongIMLib.MessageTag(true, true) }, JrmfRedPacketMessage: { objectName: "RCJrmf:RpMsg", msgTag: new RongIMLib.MessageTag(true, true) }, JrmfRedPacketOpenedMessage: { objectName: "RCJrmf:RpOpendMsg", msgTag: new RongIMLib.MessageTag(true, true) }, GroupNotificationMessage: { objectName: "RC:GrpNtf", msgTag: new RongIMLib.MessageTag(false, true) }, CommandMessage: { objectName: "RC:CmdMsg", msgTag: new RongIMLib.MessageTag(false, false) }, TypingStatusMessage: { objectName: "RC:TypSts", msgTag: new RongIMLib.MessageTag(false, false) }, PublicServiceCommandMessage: { objectName: "RC:PSCmd", msgTag: new RongIMLib.MessageTag(false, false) }, RecallCommandMessage: { objectName: "RC:RcCmd", msgTag: new RongIMLib.MessageTag(false, true) }, SyncReadStatusMessage: { objectName: "RC:SRSMsg", msgTag: new RongIMLib.MessageTag(false, false) }, ReadReceiptRequestMessage: { objectName: "RC:RRReqMsg", msgTag: new RongIMLib.MessageTag(false, false) }, ReadReceiptResponseMessage: { objectName: "RC:RRRspMsg", msgTag: new RongIMLib.MessageTag(false, false) }, ChangeModeResponseMessage: { objectName: "RC:CsChaR", msgTag: new RongIMLib.MessageTag(false, false) }, ChangeModeMessage: { objectName: "RC:CSCha", msgTag: new RongIMLib.MessageTag(false, false) }, EvaluateMessage: { objectName: "RC:CsEva", msgTag: new RongIMLib.MessageTag(false, false) }, CustomerContact: { objectName: "RC:CsContact", msgTag: new RongIMLib.MessageTag(false, false) }, HandShakeMessage: { objectName: "RC:CsHs", msgTag: new RongIMLib.MessageTag(false, false) }, HandShakeResponseMessage: { objectName: "RC:CsHsR", msgTag: new RongIMLib.MessageTag(false, false) }, SuspendMessage: { objectName: "RC:CsSp", msgTag: new RongIMLib.MessageTag(false, false) }, TerminateMessage: { objectName: "RC:CsEnd", msgTag: new RongIMLib.MessageTag(false, false) }, CustomerStatusUpdateMessage: { objectName: "RC:CsUpdate", msgTag: new RongIMLib.MessageTag(false, false) }, ReadReceiptMessage: { objectName: "RC:ReadNtf", msgTag: new RongIMLib.MessageTag(false, false) }, RCCombineMessage: { objectName: "RC:CombineMsg", msgTag: new RongIMLib.MessageTag(true, true) }, ChrmKVNotificationMessage: { objectName: 'RC:chrmKVNotiMsg', msgTag: new RongIMLib.MessageTag(false, false) } }; RongIMClient.MessageParams["AcceptMessage"] = { objectName: "RC:VCAccept", msgTag: new RongIMLib.MessageTag(false, false) }; RongIMClient.MessageParams["RingingMessage"] = { objectName: "RC:VCRinging", msgTag: new RongIMLib.MessageTag(false, false) }; RongIMClient.MessageParams["SummaryMessage"] = { objectName: "RC:VCSummary", msgTag: new RongIMLib.MessageTag(false, false) }; RongIMClient.MessageParams["HungupMessage"] = { objectName: "RC:VCHangup", msgTag: new RongIMLib.MessageTag(false, false) }; RongIMClient.MessageParams["InviteMessage"] = { objectName: "RC:VCInvite", msgTag: new RongIMLib.MessageTag(false, false) }; RongIMClient.MessageParams["MediaModifyMessage"] = { objectName: "RC:VCModifyMedia", msgTag: new RongIMLib.MessageTag(false, false) }; RongIMClient.MessageParams["MemberModifyMessage"] = { objectName: "RC:VCModifyMem", msgTag: new RongIMLib.MessageTag(false, false) }; RongIMClient.MessageType = { TextMessage: "TextMessage", ImageMessage: "ImageMessage", DiscussionNotificationMessage: "DiscussionNotificationMessage", VoiceMessage: "VoiceMessage", RichContentMessage: "RichContentMessage", HandshakeMessage: "HandshakeMessage", UnknownMessage: "UnknownMessage", LocationMessage: "LocationMessage", InformationNotificationMessage: "InformationNotificationMessage", ContactNotificationMessage: "ContactNotificationMessage", ProfileNotificationMessage: "ProfileNotificationMessage", CommandNotificationMessage: "CommandNotificationMessage", CommandMessage: "CommandMessage", TypingStatusMessage: "TypingStatusMessage", ChangeModeResponseMessage: "ChangeModeResponseMessage", ChangeModeMessage: "ChangeModeMessage", EvaluateMessage: "EvaluateMessage", HandShakeMessage: "HandShakeMessage", HandShakeResponseMessage: "HandShakeResponseMessage", SuspendMessage: "SuspendMessage", TerminateMessage: "TerminateMessage", CustomerContact: "CustomerContact", CustomerStatusUpdateMessage: "CustomerStatusUpdateMessage", SyncReadStatusMessage: "SyncReadStatusMessage", ReadReceiptRequestMessage: "ReadReceiptRequestMessage", ReadReceiptResponseMessage: "ReadReceiptResponseMessage", FileMessage: 'FileMessage', HQVoiceMessage: 'HQVoiceMessage', AcceptMessage: "AcceptMessage", RingingMessage: "RingingMessage", SummaryMessage: "SummaryMessage", HungupMessage: "HungupMessage", InviteMessage: "InviteMessage", MediaModifyMessage: "MediaModifyMessage", MemberModifyMessage: "MemberModifyMessage", JrmfRedPacketMessage: "JrmfRedPacketMessage", JrmfRedPacketOpenedMessage: "JrmfRedPacketOpenedMessage", GroupNotificationMessage: "GroupNotificationMessage", PublicServiceRichContentMessage: "PublicServiceRichContentMessage", PublicServiceMultiRichContentMessage: "PublicServiceMultiRichContentMessage", PublicServiceCommandMessage: "PublicServiceCommandMessage", RecallCommandMessage: "RecallCommandMessage", ReadReceiptMessage: "ReadReceiptMessage", RCCombineMessage: "RCCombineMessage", ChrmKVNotificationMessage: 'ChrmKVNotificationMessage' }; RongIMClient.LogFactory = { /** * 个人 */ "-1": { code: "-1", msg: "服务器超时" }, "-2": { code: "-2", msg: "未知原因失败" }, "-3": { code: "-3", msg: "参数错误" }, "-4": { code: "-4", msg: "参数不正确或尚未实例化" }, "25101": { code: "25101", msg: "撤回消息参数错误", desc: "请检查撤回消息参数 https://rongcloud.github.io/websdk-demo/api-test.html" }, "25102": { code: "25101", msg: "只能撤回自发发送的消息" }, "20604": { code: "20604", msg: "发送频率过快", desc: "https://developer.rongcloud.cn/ticket/info/9Q3L6vRKd1cLS7rycA==?type=1" }, "20406": { code: "20406", msg: "被禁言" }, "23407": { code: "23407", msg: "获取用户失败" }, /** * 群组 */ "20407": { code: "20407", msg: "群组Id无效" }, "22408": { code: "22408", msg: "群组被禁言" }, "22406": { code: "22406", msg: "不在群组" }, "35001": { code: "35001", msg: "群组同步异常" }, "35002": { code: "35002", msg: "匹配群信息异常" }, /** * 讨论组 */ "21406": { code: "21406", msg: "不在讨论组" }, "21407": { code: "21407", msg: "加入讨论失败" }, "21408": { code: "21408", msg: "创建讨论组失败" }, "21409": { code: "21409", msg: "设置讨论组邀请状态失败" }, /** * 聊天室 */ "23406": { code: "23406", msg: "不在聊天室" }, "23408": { code: "23408", msg: "聊天室被禁言" }, "23409": { code: "23409", msg: "聊天室中成员被踢出" }, "23410": { code: "23410", msg: "聊天室不存在" }, "23411": { code: "23411", msg: "聊天室成员已满" }, "23412": { code: "23412", msg: "获取聊天室信息参数无效" }, "23413": { code: "23413", msg: "聊天室异常" }, "23414": { code: "23414", msg: "没有打开聊天室消息存储" }, "36001": { code: "36001", msg: "加入聊天室Id为空" }, "36002": { code: "36002", msg: "加入聊天室失败" }, "36003": { code: "36003", msg: "拉取聊天室历史消息失败" }, /** * voip */ "24001": { code: "24001", msg: "没有注册DeviveId 也就是用户没有登陆" }, "24002": { code: "24002", msg: "用户已经存在" }, "0": { code: "0", msg: "成功" }, "24009": { code: "24009", msg: "没有对应的用户或token" }, "24013": { code: "24013", msg: "voip为空" }, "24010": { code: "24010", msg: "不支持的Voip引擎" }, "24011": { code: "24011", msg: "channelName 是空" }, "24012": { code: "24012", msg: "生成Voipkey失败" }, "24014": { code: "24014", msg: "没有配置voip" }, "24015": { code: "24015", msg: "服务器内部错误" }, "24016": { code: "24016", msg: "VOIP close" }, /** * 通讯、导航 */ "30001": { code: "30001", msg: "通信过程中,当前Socket不存在" }, "30002": { code: "30002", msg: "Socket连接不可用" }, "30003": { code: "30003", msg: "通信超时" }, "30004": { code: "30004", msg: "导航操作时,Http请求失败" }, "30005": { code: "30005", msg: "HTTP请求失败" }, "30006": { code: "30006", msg: "HTTP接收失败" }, "30007": { code: "30007", msg: "导航资源错误" }, "30008": { code: "30008", msg: "没有有效数据" }, "30009": { code: "30009", msg: "不存在有效 IP 地址" }, "30010": { code: "30010", msg: "创建 Socket 失败" }, "30011": { code: "30011", msg: " Socket 被断开" }, "30012": { code: "30012", msg: "PING 操作失败" }, "30013": { code: "30013", msg: "PING 超时" }, "30014": { code: "30014", msg: "消息发送失败" }, "30016": { code: "30016", msg: "消息大小超限,最大 128 KB" }, /** * 连接 */ "31000": { code: "31000", msg: "做 connect 连接时,收到的 ACK 超时" }, "31001": { code: "31001", msg: "参数错误" }, "31002": { code: "31002", msg: "参数错误,App Id 错误" }, "31003": { code: "31003", msg: "服务器不可用" }, "31004": { code: "31004", msg: "Token 错误" }, "31005": { code: "31005", msg: "App Id 与 Token 不匹配" }, "31006": { code: "31006", msg: "重定向,地址错误" }, "31007": { code: "31007", msg: "NAME 与后台注册信息不一致" }, "31008": { code: "31008", msg: "APP 被屏蔽、删除或不存在" }, "31009": { code: "31009", msg: "用户被屏蔽" }, "31010": { code: "31010", msg: "Disconnect,由服务器返回,比如用户互踢" }, "31011": { code: "31011", msg: "Disconnect,由服务器返回,比如用户互踢" }, /** * 协议 */ "32001": { code: "32001", msg: "协议层内部错误。query,上传下载过程中数据错误" }, "32002": { code: "32002", msg: "协议层内部错误" }, /** * BIZ */ "33001": { code: "33001", msg: "未调用 init 初始化函数" }, "33002": { code: "33002", msg: "数据库初始化失败" }, "33003": { code: "33003", msg: "传入参数无效" }, "33004": { code: "33004", msg: "通道无效" }, "33005": { code: "33005", msg: "重新连接成功" }, "33006": { code: "33006", msg: "连接中,再调用 connect 被拒绝" }, "33007": { code: "33007", msg: "消息漫游服务未开通" }, "33008": { code: "33008", msg: "消息添加失败" }, "33009": { code: "33009", msg: "消息删除失败" }, /** * 会话 */ "34001": { code: "34001", msg: "删除会话失败" }, "34002": { code: "34002", msg: "拉取历史消息失败" }, "34003": { code: "34003", msg: "会话指定异常" }, "34004": { code: "34004", msg: "获取会话未读消息总数失败" }, "34005": { code: "34005", msg: "获取指定会话类型未读消息数异常" }, "34006": { code: "34006", msg: "获取指定用户ID&会话类型未读消息数异常" }, "34007": { code: "34007", msg: "清除会话消息异常" }, "34008": { code: "34008", msg: "获取会话消息异常" }, "34009": { code: "34009", msg: "清除历史消息会话类型不正确" }, "34010": { code: "34010", msg: "清除历史消息失败,请检查传入参数" }, /** * 黑名单异常 */ "37001": { code: "37001", msg: "加入黑名单异常" }, "37002": { code: "37002", msg: "获得指定人员再黑名单中的状态异常" }, "37003": { code: "37003", msg: "移除黑名单异常" }, "405": { code: "405", msg: "在黑名单中" }, /** * 草稿 */ "38001": { code: "38001", msg: "获取草稿失败" }, "38002": { code: "38002", msg: "保存草稿失败" }, "38003": { code: "38003", msg: "删除草稿失败" }, /** * 公众号 */ "39001": { code: "39001", msg: "关注公众号失败" }, /** * 文件 */ "41001": { code: "41001", msg: "文件类型错误" }, "41002": { code: "41002", msg: "获取七牛token失败" }, /** * */ "51001": { code: "51001", msg: "未安装或未启动插件" }, "51002": { code: "51002", msg: "视频已经存在" }, "51003": { code: "51003", msg: "无效的channelName" }, "51004": { code: "51004", msg: "视频内容为空" }, /** * */ "61001": { code: "61001", msg: "删除消息数组长度为 0" } }; var handler = function (message, uris, callback) { var userId = message.senderUserId; var _uris = RongIMClient.roomInfo.users[userId].uris || '[]'; if (RongIMLib.RongUtil.isString(_uris)) { _uris = JSON.parse(_uris); } var tUris = JSON.parse(JSON.stringify(_uris)); RongIMLib.RongUtil.forEach(tUris, function (_uri, index) { RongIMLib.RongUtil.forEach(uris, function (uri) { if (uri.uri == _uri.uri) { callback(_uri, uri, _uris, index); } }); }); RongIMClient.roomInfo.users[userId].uris = JSON.stringify(_uris); }; var RTCMessage = { RTCPublishResourceMessage: function (message, uris) { var userId = message.senderUserId; var user = RongIMClient.roomInfo.users[userId]; if (!user) { user = {}; RongIMClient.roomInfo.users[userId] = {}; } var _uris = user.uris || '[]'; if (RongIMLib.RongUtil.isString(_uris)) { _uris = JSON.parse(_uris); } _uris = _uris.concat(uris); RongIMClient.roomInfo.users[userId].uris = JSON.stringify(_uris); }, RTCUnpublishResourceMessage: function (message, uris) { handler(message, uris, function (_uri, uri, _uris, index) { _uris.splice(index, 1); }); }, RTCModifyResourceMessage: function (message, uris) { handler(message, uris, function (_uri, uri) { _uri.state = uri.state; }); }, RTCUserChangeMessage: function (message) { var content = message.content; var users = content.users; var UserState = { JOINED: 0, LEFT: 1, OFFLINE: 2 }; RongIMLib.RongUtil.forEach(users, function (user) { var state = user.state; var userId = user.userId; switch (+state) { case UserState.JOINED: RongIMClient.roomInfo.users[userId] = {}; break; case UserState.LEFT: case UserState.OFFLINE: delete RongIMClient.roomInfo.users[userId]; break; } }); } }; RongIMClient.RTCInnerListener = function (message) { var func = RTCMessage[message.messageType] || function () { }; var content = message.content; var uris = content.uris; func(message, uris); }; RongIMClient.Conversation = RongIMClient._dataAccessProvider.Conversation; return sdkInfo; }; ; /** var config = { appkey: appkey, token: token, dataAccessProvider:dataAccessProvider, opts: opts }; callback(_instance, userId); */ RongIMClient.initApp = function (config, callback) { RongIMClient.init(config.appkey, config.dataAccessProvider, config.opts, function () { var instance = RongIMClient._instance; //备用 var error = null; callback(error, instance); }); }; /** * 连接服务器,在整个应用全局只需要调用一次,断线后 SDK 会自动重连。 * * @param token 从服务端获取的用户身份令牌(Token)。 * @param callback 连接回调,返回连接的成功或者失败状态。 */ RongIMClient.connect = function (token, _callback, userId, serverConf) { RongIMLib.CheckParam.getInstance().check(["string", "object", "string|null|object|global|undefined", "object|null|global|undefined"], "connect", true, arguments); var connectCallback = { onSuccess: _callback.onSuccess, onTokenIncorrect: _callback.onTokenIncorrect, onError: function (errorCode) { RongIMClient.logger({ code: errorCode, funcName: "connect" }); _callback.onError(errorCode); } }; RongIMClient._dataAccessProvider.connect(token, connectCallback, userId, serverConf); }; RongIMClient.reconnect = function (callback, config) { var connectCallback = { onSuccess: callback.onSuccess, onTokenIncorrect: callback.onTokenIncorrect, onError: function (errorCode) { RongIMClient.logger({ code: errorCode, funcName: "connect" }); callback.onError(errorCode); } }; RongIMClient._dataAccessProvider.reconnect(connectCallback, config); }; /** * 注册消息类型,用于注册用户自定义的消息。 * 内建的消息类型已经注册过,不需要再次注册。 * 自定义消息声明需放在执行顺序最高的位置(在RongIMClient.init(appkey)之后即可) * @param objectName 消息内置名称 */ RongIMClient.registerMessageType = function (messageType, objectName, messageTag, messageContent, searchProps) { RongIMClient._dataAccessProvider.registerMessageType(messageType, objectName, messageTag, messageContent, searchProps); RongIMClient.RegisterMessage[messageType].messageName = messageType; RongIMClient.MessageType[messageType] = messageType; RongIMClient.MessageParams[messageType] = { objectName: objectName, msgTag: messageTag }; }; RongIMClient.prototype.registerMessageTypes = function (types) { types = types || {}; RongIMClient._dataAccessProvider.registerMessageTypes(types); }; /** * 设置连接状态变化的监听器。 * * @param listener 连接状态变化的监听器。 */ RongIMClient.setConnectionStatusListener = function (listener) { if (RongIMClient._dataAccessProvider) { RongIMClient._dataAccessProvider.setConnectionStatusListener(listener); } else { if (RongIMLib.RongUtil.isObject(listener) && RongIMLib.RongUtil.isFunction(listener.onChanged)) { RongIMClient.statusListeners.push(listener.onChanged); } } }; RongIMClient.statusWatch = function (watcher) { if (RongIMLib.RongUtil.isFunction(watcher)) { RongIMClient.statusListeners.push(watcher); } }; /** * 设置接收消息的监听器。 * * @param listener 接收消息的监听器。 */ RongIMClient.setOnReceiveMessageListener = function (listener) { if (RongIMClient._dataAccessProvider) { RongIMClient._dataAccessProvider.setOnReceiveMessageListener(listener); } else { if (RongIMLib.RongUtil.isObject(listener) && RongIMLib.RongUtil.isFunction(listener.onReceived)) { RongIMClient.messageListeners.push(listener.onReceived); } } }; /** * 清理所有连接相关的变量 */ RongIMClient.prototype.logout = function () { RongIMClient._dataAccessProvider.logout(); }; /** * 断开连接。 */ RongIMClient.prototype.disconnect = function () { RongIMClient._dataAccessProvider.disconnect(); }; RongIMClient.prototype.startCustomService = function (custId, callback, content) { if (!custId || !callback) return; var msg = new RongIMLib.HandShakeMessage(content); var me = this; RongIMLib.RongIMClient._memoryStore.custStore["isInit"] = true; RongIMClient.getInstance().sendMessage(RongIMLib.ConversationType.CUSTOMER_SERVICE, custId, msg, { onSuccess: function (data) { if (data.isBlack) { callback.onError(); me.stopCustomeService(custId, { onSuccess: function () { }, onError: function () { } }); } else { callback.onSuccess(); } }, onError: function () { callback.onError(); }, onBefore: function () { } }); }; RongIMClient.prototype.stopCustomeService = function (custId, callback) { if (!custId || !callback) return; var session = RongIMClient._memoryStore.custStore[custId]; if (!session) return; var msg = new RongIMLib.SuspendMessage({ sid: session.sid, uid: session.uid, pid: session.pid }); this.sendCustMessage(custId, msg, { onSuccess: function () { // delete RongIMClient._memoryStore.custStore[custId]; setTimeout(function () { callback.onSuccess(); }); }, onError: function () { setTimeout(function () { callback.onError(); }); } }); }; RongIMClient.prototype.switchToHumanMode = function (custId, callback) { if (!custId || !callback) return; var session = RongIMClient._memoryStore.custStore[custId]; if (!session) return; var msg = new RongIMLib.ChangeModeMessage({ sid: session.sid, uid: session.uid, pid: session.pid }); this.sendCustMessage(custId, msg, callback); }; RongIMClient.prototype.evaluateRebotCustomService = function (custId, isRobotResolved, sugest, callback) { if (!custId || !callback) return; var session = RongIMClient._memoryStore.custStore[custId]; if (!session) return; var msg = new RongIMLib.EvaluateMessage({ sid: session.sid, uid: session.uid, pid: session.pid, isRobotResolved: isRobotResolved, sugest: sugest, type: 0 }); this.sendCustMessage(custId, msg, callback); }; RongIMClient.prototype.evaluateHumanCustomService = function (custId, humanValue, sugest, callback) { if (!custId || !callback) return; var session = RongIMClient._memoryStore.custStore[custId]; if (!session) return; var msg = new RongIMLib.EvaluateMessage({ sid: session.sid, uid: session.uid, pid: session.pid, humanValue: humanValue, sugest: sugest, type: 1 }); this.sendCustMessage(custId, msg, callback); }; RongIMClient.prototype.sendCustMessage = function (custId, msg, callback) { RongIMClient.getInstance().sendMessage(RongIMLib.ConversationType.CUSTOMER_SERVICE, custId, msg, { onSuccess: function (data) { callback.onSuccess(); }, onError: function () { callback.onError(); }, onBefore: function () { } }); }; /** * 获取当前连接的状态。 */ RongIMClient.prototype.getCurrentConnectionStatus = function () { return RongIMClient._dataAccessProvider.getCurrentConnectionStatus(); }; /** * 获取当前使用的连接通道。 */ RongIMClient.prototype.getConnectionChannel = function () { if (RongIMLib.Transportations._TransportType == RongIMLib.Socket.XHR_POLLING) { return RongIMLib.ConnectionChannel.XHR_POLLING; } else if (RongIMLib.Transportations._TransportType == RongIMLib.Socket.WEBSOCKET) { return RongIMLib.ConnectionChannel.WEBSOCKET; } }; /** * 获取当前使用的本地储存提供者。 TODO */ RongIMClient.prototype.getStorageProvider = function () { if (RongIMClient._memoryStore.providerType == 1) { return "ServerDataProvider"; } else { return "OtherDataProvider"; } }; /** * 过滤聊天室消息(拉取最近聊天消息) * @param {string[]} msgFilterNames */ RongIMClient.prototype.setFilterMessages = function (msgFilterNames) { if (Object.prototype.toString.call(msgFilterNames) == "[object Array]") { RongIMClient._memoryStore.filterMessages = msgFilterNames; } }; RongIMClient.prototype.getAgoraDynamicKey = function (engineType, channelName, callback) { RongIMClient._dataAccessProvider.getAgoraDynamicKey(engineType, channelName, callback); }; /** * 获取当前连接用户的 UserId。 */ RongIMClient.prototype.getCurrentUserId = function () { return RongIMLib.Bridge._client.userId; }; /** * 获取服务器时间与本地时间的差值,单位为毫秒。 * 计算公式:差值 = 本地时间毫秒数 - 服务器时间毫秒数 * @param callback 获取的回调,返回差值。 */ RongIMClient.prototype.getDeltaTime = function () { return RongIMClient._dataAccessProvider.getDelaTime(); }; // #region Message RongIMClient.prototype.getMessage = function (messageId, callback) { RongIMClient._dataAccessProvider.getMessage(messageId, RongIMClient.logCallback(callback, "getMessage")); }; RongIMClient.prototype.deleteLocalMessages = function (conversationType, targetId, messageIds, callback) { RongIMClient._dataAccessProvider.removeLocalMessage(conversationType, targetId, messageIds, RongIMClient.logCallback(callback, "deleteLocalMessages")); }; RongIMClient.prototype.updateMessage = function (message, callback) { RongIMClient._dataAccessProvider.updateMessage(message, RongIMClient.logCallback(callback, "updateMessage")); }; RongIMClient.prototype.clearData = function () { return RongIMClient._dataAccessProvider.clearData(); }; RongIMClient.prototype.clearMessages = function (conversationType, targetId, callback) { RongIMClient._dataAccessProvider.clearMessages(conversationType, targetId, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "clearMessages" }); callback.onError(errorCode); }); } }); }; /**TODO 清楚本地存储的未读消息,目前清空内存中的未读消息 * [clearMessagesUnreadStatus 清空指定会话未读消息] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [用户id] * @param {ResultCallback} callback [返回值,参数回调] */ RongIMClient.prototype.clearMessagesUnreadStatus = function (conversationType, targetId, callback) { RongIMClient._dataAccessProvider.updateMessages(conversationType, targetId, "readStatus", null, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "clearMessagesUnreadStatus" }); callback.onError(errorCode); }); } }); }; // deleteRemoteMessages(conversationType: ConversationType, targetId: string, delMsgs: DeleteMessage[], callback: ResultCallback) { // CheckParam.getInstance().check(["number", "string|number", "array", "object"], "deleteRemoteMessages", false, arguments); // if (delMsgs.length == 0) { // var errorCode = ErrorCode.DELETE_MESSAGE_ID_IS_NULL; // RongIMClient.logger({ // code: errorCode, // funcName: "deleteRemoteMessages" // }); // callback.onError(ErrorCode.DELETE_MESSAGE_ID_IS_NULL); // return; // } else if (delMsgs.length > 100) { // delMsgs.length = 100; // } // // 后续增加,去掉注释即可 // callback.onSuccess(true); // // var modules = new RongIMClient.Protobuf.DeleteMsgInput(); // // modules.setType(conversationType); // // modules.setConversationId(targetId); // // modules.setMsgs(delMsgs); // // RongIMClient.bridge.queryMsg(33, MessageUtil.ArrayForm(modules.toArrayBuffer()), Bridge._client.userId, { // // onSuccess: function(info: any) { // // callback.onSuccess(true); // // }, // // onError: function(err: any) { // // callback.onError(err); // // } // // }, "DeleteMsgOutput"); // } /** * [deleteMessages 删除消息记录。] * @param {ConversationType} conversationType [description] * @param {string} targetId [description] * @param {number[]} messageIds [description] * @param {ResultCallback} callback [description] */ RongIMClient.prototype.deleteMessages = function (conversationType, targetId, messages, callback) { RongIMClient._dataAccessProvider.removeMessage(conversationType, targetId, messages, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "deleteMessages" }); callback.onError(errorCode); }); } }); }; RongIMClient.prototype.sendLocalMessage = function (message, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object"], "sendLocalMessage", false, arguments); RongIMClient._dataAccessProvider.updateMessage(message); this.sendMessage(message.conversationType, message.targetId, message.content, RongIMClient.logSendCallback(callback, "sendLocalMessage")); }; RongIMClient.prototype.getPullSetting = function (callback) { RongIMClient._dataAccessProvider.getPullSetting(callback); }; RongIMClient.prototype.setOfflineMessageDuration = function (duration, callback) { RongIMLib.CheckParam.getInstance().check(["number", "object"], "setOfflineMessageDuration", true, arguments); RongIMClient._dataAccessProvider.setOfflineMessageDuration(duration, callback); }; /** * [sendMessage 发送消息。] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [目标Id] * @param {MessageContent} messageContent [消息类型] * @param {SendMessageCallback} sendCallback [] * @param {ResultCallback} resultCallback [返回值,函数回调] * @param {string} pushContent [] * @param {string} pushData [] */ RongIMClient.prototype.sendMessage = function (conversationType, targetId, messageContent, sendCallback, mentiondMsg, pushText, appData, methodType, params) { RongIMLib.CheckParam.getInstance().check(["number", "string", "object", "object", "undefined|object|null|global|boolean", "undefined|object|null|global|string", "undefined|object|null|global|string", "undefined|object|null|global|number", "undefined|object|null|global"], "sendMessage", false, arguments); if (!RongIMLib.RongUtil.isString(targetId)) { return sendCallback.onError(RongIMLib.ErrorCode.PARAMETER_ERROR); } RongIMClient._dataAccessProvider.sendMessage(conversationType, targetId, messageContent, RongIMClient.logSendCallback(sendCallback, "sendMessage"), mentiondMsg, pushText, appData, methodType, params); }; RongIMClient.prototype.sendReceiptResponse = function (conversationType, targetId, sendCallback) { RongIMClient._dataAccessProvider.sendReceiptResponse(conversationType, targetId, RongIMClient.logSendCallback(sendCallback, "sendReceiptResponse")); }; RongIMClient.prototype.sendTypingStatusMessage = function (conversationType, targetId, messageName, sendCallback) { RongIMClient._dataAccessProvider.sendTypingStatusMessage(conversationType, targetId, messageName, RongIMClient.logSendCallback(sendCallback, "sendTypingStatusMessage")); }; /** * [sendStatusMessage description] * @param {MessageContent} messageContent [description] * @param {SendMessageCallback} sendCallback [description] * @param {ResultCallback} resultCallback [description] */ RongIMClient.prototype.sendStatusMessage = function (messageContent, sendCallback, resultCallback) { throw new Error("Not implemented yet"); }; /** * [sendTextMessage 发送TextMessage快捷方式] * @param {string} content [消息内容] * @param {ResultCallback} resultCallback [返回值,参数回调] */ RongIMClient.prototype.sendTextMessage = function (conversationType, targetId, content, sendMessageCallback) { RongIMClient._dataAccessProvider.sendTextMessage(conversationType, targetId, content, RongIMClient.logSendCallback(sendMessageCallback, "sendTextMessage")); }; RongIMClient.prototype.sendRecallMessage = function (content, sendMessageCallback) { var callback = RongIMClient.logSendCallback(sendMessageCallback, "sendRecallMessage"); var senderUserId = content.senderUserId; var userId = RongIMLib.Bridge._client.userId; var isOther = (senderUserId != userId); if (isOther) { var callback = RongIMClient.logSendCallback(sendMessageCallback, "sendRecallMessage"); callback.onError(RongIMLib.ErrorCode.RECALL_MESSAGE, content); return; } RongIMClient._dataAccessProvider.sendRecallMessage(content, callback); }; /** * [insertMessage 向本地插入一条消息,不发送到服务器。] * @param {ConversationType} conversationType [description] * @param {string} targetId [description] * @param {string} senderUserId [description] * @param {MessageContent} content [description] * @param {ResultCallback} callback [description] */ RongIMClient.prototype.insertMessage = function (conversationType, targetId, content, callback) { RongIMClient._dataAccessProvider.addMessage(conversationType, targetId, content, RongIMClient.logCallback(callback, "insertMessage")); }; RongIMClient.prototype.setMessageContent = function (messageId, content, objectName) { RongIMClient._dataAccessProvider.setMessageContent(messageId, content, objectName); }; ; RongIMClient.prototype.setMessageSearchField = function (messageId, content, searchFiles) { RongIMClient._dataAccessProvider.setMessageContent(messageId, content, searchFiles); }; ; /** * [getHistoryMessages 拉取历史消息记录。] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [用户Id] * @param {number|null} pullMessageTime [拉取历史消息起始位置(格式为毫秒数),可以为null] * @param {number} count [历史消息数量] * @param {ResultCallback} callback [回调函数] * @param {string} objectName [objectName] */ RongIMClient.prototype.getHistoryMessages = function (conversationType, targetId, timestamp, count, callback, objectname, order) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "number|null|global|object", "number", "object", "undefined|object|null|global|string", "number|null|global|object"], "getHistoryMessages", false, arguments); if (count > 20) { throw new Error("HistroyMessage count must be less than or equal to 20!"); } if (conversationType.valueOf() < 0) { throw new Error("ConversationType must be greater than -1"); } RongIMClient._dataAccessProvider.getHistoryMessages(conversationType, targetId, timestamp, count, RongIMClient.logCallback(callback, "getHistoryMessages"), objectname, order); }; /** * [getRemoteHistoryMessages 拉取某个时间戳之前的消息] * @param {ConversationType} conversationType [description] * @param {string} targetId [description] * @param {Date} dateTime [description] * @param {number} count [description] * @param {ResultCallback} callback [description] */ RongIMClient.prototype.getRemoteHistoryMessages = function (conversationType, targetId, timestamp, count, callback, config) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "number|null|global|object", "number", "object", "undefined|null|global|object"], "getRemoteHistoryMessages", false, arguments); var funcName = "getRemoteHistoryMessages"; var log = { errorCode: RongIMLib.ErrorCode.RC_CONN_PROTO_VERSION_ERROR, funcName: "getRemoteHistoryMessages" }; if (count > 20) { RongIMClient.logger(log); callback.onError(RongIMLib.ErrorCode.RC_CONN_PROTO_VERSION_ERROR); return; } if (conversationType.valueOf() < 0) { RongIMClient.logger(log); callback.onError(RongIMLib.ErrorCode.RC_CONN_PROTO_VERSION_ERROR); return; } RongIMClient._dataAccessProvider.getRemoteHistoryMessages(conversationType, targetId, timestamp, count, RongIMClient.logCallback(callback, funcName), config); }; RongIMClient.prototype.clearHistoryMessages = function (params, callback) { RongIMClient._dataAccessProvider.clearHistoryMessages(params, callback); }; RongIMClient.prototype.clearRemoteHistoryMessages = function (params, callback) { RongIMClient._dataAccessProvider.clearRemoteHistoryMessages(params, RongIMClient.logCallback(callback, "clearRemoteHistoryMessages")); }; RongIMClient.prototype.deleteRemoteMessages = function (conversationType, targetId, messages, callback) { RongIMClient._dataAccessProvider.deleteRemoteMessages(conversationType, targetId, messages, RongIMClient.logCallback(callback, "deleteRemoteMessages")); }; /** * [hasRemoteUnreadMessages 是否有未接收的消息,jsonp方法] * @param {string} appkey [appkey] * @param {string} token [token] * @param {ConnectCallback} callback [返回值,参数回调] */ RongIMClient.prototype.hasRemoteUnreadMessages = function (token, callback) { RongIMClient._dataAccessProvider.hasRemoteUnreadMessages(token, RongIMClient.logCallback(callback, "hasRemoteUnreadMessages")); }; RongIMClient.prototype.getTotalUnreadCount = function (callback, conversationTypes) { RongIMClient._dataAccessProvider.getTotalUnreadCount({ onSuccess: function (count) { setTimeout(function () { callback.onSuccess(count); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "getTotalUnreadCount" }); callback.onError(errorCode); }); } }, conversationTypes); }; /** * [getConversationUnreadCount 指定多种会话类型获取未读消息数] * @param {ResultCallback} callback [返回值,参数回调。] * @param {ConversationType[]} ...conversationTypes [会话类型。] */ RongIMClient.prototype.getConversationUnreadCount = function (conversationTypes, callback) { RongIMClient._dataAccessProvider.getConversationUnreadCount(conversationTypes, { onSuccess: function (count) { setTimeout(function () { callback.onSuccess(count); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "getConversationUnreadCount" }); callback.onError(errorCode); }); } }); }; /** * [getUnreadCount 指定用户、会话类型的未读消息总数。] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [用户Id] */ RongIMClient.prototype.getUnreadCount = function (conversationType, targetId, callback) { RongIMClient._dataAccessProvider.getUnreadCount(conversationType, targetId, { onSuccess: function (count) { setTimeout(function () { callback.onSuccess(count); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "getUnreadCount" }); callback.onError(errorCode); }); } }); }; RongIMClient.prototype.setUnreadCount = function (conversationType, targetId, count) { RongIMLib.CheckParam.getInstance().check(["number", "string", "number"], "setUnreadCount", false, arguments); RongIMClient._dataAccessProvider.setUnreadCount(conversationType, targetId, count); }; RongIMClient.prototype.clearUnreadCountByTimestamp = function (conversationType, targetId, timestamp, callback) { RongIMClient._dataAccessProvider.clearUnreadCountByTimestamp(conversationType, targetId, timestamp, RongIMClient.logCallback(callback, "clearUnreadCountByTimestamp")); }; /** * 清楚会话未读消息数 * @param {ConversationType} conversationType 会话类型 * @param {string} targetId 目标Id * @param {ResultCallback} callback 返回值,函数回调 */ RongIMClient.prototype.clearUnreadCount = function (conversationType, targetId, callback) { RongIMClient._dataAccessProvider.clearUnreadCount(conversationType, targetId, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "clearUnreadCount" }); callback.onError(errorCode); }); } }); }; RongIMClient.prototype.clearTotalUnreadCount = function (callback) { RongIMClient._dataAccessProvider.clearTotalUnreadCount({ onSuccess: function (bool) { callback.onSuccess(bool); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: 'clearTotalUnreadCount' }); callback.onError(errorCode); }); } }); }; RongIMClient.prototype.clearLocalStorage = function (callback) { RongIMClient._storageProvider.clearItem(); callback(); }; RongIMClient.prototype.setMessageExtra = function (messageId, value, callback) { RongIMClient._dataAccessProvider.setMessageExtra(messageId, value, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "setMessageExtra" }); callback.onError(errorCode); }); } }); }; RongIMClient.prototype.setMessageReceivedStatus = function (messageUId, receivedStatus, callback) { RongIMClient._dataAccessProvider.setMessageReceivedStatus(messageUId, receivedStatus, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "setMessageReceivedStatus" }); callback.onError(errorCode); }); } }); }; RongIMClient.prototype.setMessageStatus = function (conersationType, targetId, timestamp, status, callback) { RongIMClient._dataAccessProvider.setMessageStatus(conersationType, targetId, timestamp, status, RongIMClient.logCallback(callback, "setMessageStatus")); }; RongIMClient.prototype.setMessageSentStatus = function (messageId, sentStatus, callback) { RongIMClient._dataAccessProvider.setMessageSentStatus(messageId, sentStatus, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "setMessageSentStatus" }); callback.onError(errorCode); }); } }); }; // #endregion Message // #region TextMessage Draft /** * clearTextMessageDraft 清除指定会话和消息类型的草稿。 * @param {ConversationType} conversationType 会话类型 * @param {string} targetId 目标Id */ RongIMClient.prototype.clearTextMessageDraft = function (conversationType, targetId) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "clearTextMessageDraft", false, arguments); var key = "darf_" + conversationType + "_" + targetId; delete RongIMClient._memoryStore[key]; return true; }; /** * [getTextMessageDraft 获取指定消息和会话的草稿。] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [目标Id] */ RongIMClient.prototype.getTextMessageDraft = function (conversationType, targetId) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "getTextMessageDraft", false, arguments); if (targetId == "" || conversationType < 0) { throw new Error("params error : " + RongIMLib.ErrorCode.DRAF_GET_ERROR); } var key = "darf_" + conversationType + "_" + targetId; return RongIMClient._memoryStore[key]; }; /** * [saveTextMessageDraft description] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [目标Id] * @param {string} value [草稿值] */ RongIMClient.prototype.saveTextMessageDraft = function (conversationType, targetId, value) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "string", "object"], "saveTextMessageDraft", false, arguments); var key = "darf_" + conversationType + "_" + targetId; RongIMClient._memoryStore[key] = value; return true; }; // #endregion TextMessage Draft // #region Conversation RongIMClient.prototype.searchConversationByContent = function (keyword, callback, conversationTypes) { RongIMClient._dataAccessProvider.searchConversationByContent(keyword, RongIMClient.logCallback(callback, "searchConversationByContent"), conversationTypes); }; RongIMClient.prototype.searchMessageByContent = function (conversationType, targetId, keyword, timestamp, count, total, callback) { RongIMClient._dataAccessProvider.searchMessageByContent(conversationType, targetId, keyword, timestamp, count, total, RongIMClient.logCallback(callback, "searchMessageByContent")); }; RongIMClient.prototype.clearCache = function () { RongIMClient._dataAccessProvider.clearCache(); }; RongIMClient.prototype.clearConversations = function (callback) { var conversationTypes = []; for (var _i = 1; _i < arguments.length; _i++) { conversationTypes[_i - 1] = arguments[_i]; } if (conversationTypes.length == 0) { conversationTypes = [RongIMLib.ConversationType.CHATROOM, RongIMLib.ConversationType.CUSTOMER_SERVICE, RongIMLib.ConversationType.DISCUSSION, RongIMLib.ConversationType.GROUP, RongIMLib.ConversationType.PRIVATE, RongIMLib.ConversationType.SYSTEM, RongIMLib.ConversationType.PUBLIC_SERVICE, RongIMLib.ConversationType.APP_PUBLIC_SERVICE]; } RongIMClient._dataAccessProvider.clearConversations(conversationTypes, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "clearConversations" }); callback.onError(errorCode); }); } }); }; /** * [getConversation 获取指定会话,此方法需在getConversationList之后执行] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [目标Id] * @param {ResultCallback} callback [返回值,函数回调] */ RongIMClient.prototype.getConversation = function (conversationType, targetId, callback) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "getConversation", false, arguments); RongIMClient._dataAccessProvider.getConversation(conversationType, targetId, { onSuccess: function (conver) { setTimeout(function () { callback.onSuccess(conver); }); }, onError: function (error) { setTimeout(function () { RongIMClient.logger({ code: error, funcName: "getConversation" }); callback.onError(error); }); } }); }; /** * [pottingConversation 组装会话列表] * @param {any} tempConver [临时会话] * conver_conversationType_targetId_no. * msg_conversationType_targetId_no. */ RongIMClient.prototype.pottingConversation = function (tempConver) { var self = this, isUseReplace = false; RongIMClient._dataAccessProvider.getConversation(tempConver.type, tempConver.userId, { onSuccess: function (conver) { if (!conver) { conver = new RongIMLib.Conversation(); } else { isUseReplace = true; } conver.conversationType = tempConver.type; conver.targetId = tempConver.userId; conver.latestMessage = RongIMLib.MessageUtil.messageParser(tempConver.msg); conver.latestMessageId = conver.latestMessage.messageId; conver.objectName = conver.latestMessage.objectName; conver.receivedStatus = conver.latestMessage.receivedStatus; conver.receivedTime = conver.latestMessage.receiveTime; conver.sentStatus = conver.latestMessage.sentStatus; conver.sentTime = conver.latestMessage.sentTime; var mentioneds = RongIMClient._storageProvider.getItem("mentioneds_" + RongIMLib.Bridge._client.userId + '_' + conver.conversationType + '_' + conver.targetId); if (mentioneds) { var info = JSON.parse(mentioneds); conver.mentionedMsg = info[tempConver.type + "_" + tempConver.userId]; } if (!isUseReplace) { if (RongIMLib.RongUtil.supportLocalStorage()) { // var count = RongIMClient._storageProvider.getItem("cu" + Bridge._client.userId + tempConver.type + tempConver.userId); conver.unreadMessageCount = RongIMLib.UnreadCountHandler.get(tempConver.type, tempConver.userId); } else { conver.unreadMessageCount = 0; } } if (conver.conversationType == RongIMLib.ConversationType.DISCUSSION) { self.getDiscussion(tempConver.userId, { onSuccess: function (info) { conver.conversationTitle = info.name; }, onError: function (error) { } }); } RongIMClient._dataAccessProvider.addConversation(conver, { onSuccess: function (data) { } }); }, onError: function (error) { } }); }; RongIMClient.prototype.addConversation = function (conversation, callback) { RongIMClient._dataAccessProvider.addConversation(conversation, callback); }; RongIMClient.prototype.sortConversationList = function (conversationList) { var convers = []; for (var i = 0, len = conversationList.length; i < len; i++) { if (!conversationList[i]) { continue; } if (conversationList[i].isTop) { convers.push(conversationList[i]); conversationList.splice(i, 1); continue; } for (var j = 0; j < len - i - 1; j++) { if (conversationList[j].sentTime < conversationList[j + 1].sentTime) { var swap = conversationList[j]; conversationList[j] = conversationList[j + 1]; conversationList[j + 1] = swap; } } } return RongIMClient._memoryStore.conversationList = convers.concat(conversationList); }; RongIMClient.prototype.getConversationList = function (callback, conversationTypes, count, isGetHiddenConvers) { RongIMLib.CheckParam.getInstance().check(["object", "null|undefined|array|object|global", "number|undefined|null|object|global", "boolean|undefined|null|object|global"], "getConversationList", false, arguments); var me = this; RongIMClient._dataAccessProvider.getConversationList({ onSuccess: function (data) { if (conversationTypes || RongIMClient._dataAccessProvider) { setTimeout(function () { callback.onSuccess(data); }); } else { setTimeout(function () { callback.onSuccess(RongIMClient._memoryStore.conversationList); }); } }, onError: function (error) { setTimeout(function () { RongIMClient.logger({ code: error, funcName: "getConversationList" }); callback.onError(error); }); } }, conversationTypes, count, isGetHiddenConvers); }; RongIMClient.prototype.getRemoteConversationList = function (callback, conversationTypes, count, isGetHiddenConvers) { RongIMLib.CheckParam.getInstance().check(["object", "null|array|object|global", "number|undefined|null|object|global", "boolean|undefined|null|object|global"], "getRemoteConversationList", false, arguments); RongIMClient._dataAccessProvider.getRemoteConversationList(RongIMClient.logCallback(callback, "getRemoteConversationList"), conversationTypes, count, isGetHiddenConvers); }; RongIMClient.prototype.updateConversation = function (conversation) { return RongIMClient._dataAccessProvider.updateConversation(conversation); }; /** * [createConversation 创建会话。] * @param {number} conversationType [会话类型] * @param {string} targetId [目标Id] * @param {string} converTitle [会话标题] * @param {boolean} islocal [是否同步到服务器,ture:同步,false:不同步] */ RongIMClient.prototype.createConversation = function (conversationType, targetId, converTitle) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "string"], "createConversation", false, arguments); var conver = new RongIMLib.Conversation(); // var unreadContent: string = RongIMClient._storageProvider.getItem("cu" + Bridge._client.userId + conversationType + targetId); // var unreadCount = Number(unreadContent) || 0; conver.targetId = targetId; conver.conversationType = conversationType; conver.conversationTitle = converTitle; conver.latestMessage = {}; conver.unreadMessageCount = 0; return conver; }; //TODO 删除本地和服务器、删除本地和服务器分开 RongIMClient.prototype.removeConversation = function (conversationType, targetId, callback) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "removeConversation", false, arguments); RongIMClient._dataAccessProvider.removeConversation(conversationType, targetId, RongIMClient.logCallback(callback, "removeConversation")); }; RongIMClient.prototype.setConversationHidden = function (conversationType, targetId, isHidden) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "boolean"], "setConversationHidden", false, arguments); RongIMClient._dataAccessProvider.setConversationHidden(conversationType, targetId, isHidden); }; RongIMClient.prototype.setConversationToTop = function (conversationType, targetId, isTop, callback) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "boolean", "object"], "setConversationToTop", false, arguments); RongIMClient._dataAccessProvider.setConversationToTop(conversationType, targetId, isTop, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "setConversationToTop" }); callback.onError(errorCode); }); } }); }; // #endregion Conversation // #region Notifications /** * [getConversationNotificationStatus 获取指定用户和会话类型免提醒。] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [目标Id] * @param {ResultCallback} callback [返回值,函数回调] */ RongIMClient.prototype.getConversationNotificationStatus = function (conversationType, targetId, callback) { var params = { conversationType: conversationType, targetId: targetId }; RongIMClient._dataAccessProvider.getConversationNotificationStatus(params, RongIMClient.logCallback(callback, "getConversationNotificationStatus")); }; /** * [setConversationNotificationStatus 设置指定用户和会话类型免提醒。] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [目标Id] * @param {ResultCallback} callback [返回值,函数回调] */ RongIMClient.prototype.setConversationNotificationStatus = function (conversationType, targetId, notificationStatus, callback) { var params = { conversationType: conversationType, targetId: targetId, status: status }; RongIMClient._dataAccessProvider.setConversationNotificationStatus(params, RongIMClient.logCallback(callback, "setConversationNotificationStatus")); }; /** * [getNotificationQuietHours 获取免提醒消息时间。] * @param {GetNotificationQuietHoursCallback} callback [返回值,函数回调] */ RongIMClient.prototype.getNotificationQuietHours = function (callback) { throw new Error("Not implemented yet"); }; /** * [removeNotificationQuietHours 移除免提醒消息时间。] * @param {GetNotificationQuietHoursCallback} callback [返回值,函数回调] */ RongIMClient.prototype.removeNotificationQuietHours = function (callback) { throw new Error("Not implemented yet"); }; /** * [setNotificationQuietHours 设置免提醒消息时间。] * @param {GetNotificationQuietHoursCallback} callback [返回值,函数回调] */ RongIMClient.prototype.setNotificationQuietHours = function (startTime, spanMinutes, callback) { throw new Error("Not implemented yet"); }; // #endregion Notifications // #region Discussion /** * [addMemberToDiscussion 加入讨论组] * @param {string} discussionId [讨论组Id] * @param {string[]} userIdList [讨论中成员] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.addMemberToDiscussion = function (discussionId, userIdList, callback) { RongIMLib.CheckParam.getInstance().check(["string", "array", "object"], "addMemberToDiscussion", false, arguments); RongIMClient._dataAccessProvider.addMemberToDiscussion(discussionId, userIdList, RongIMClient.logCallback(callback, "addMemberToDiscussion")); }; /** * [createDiscussion 创建讨论组] * @param {string} name [讨论组名称] * @param {string[]} userIdList [讨论组成员] * @param {CreateDiscussionCallback} callback [返回值,函数回调] */ RongIMClient.prototype.createDiscussion = function (name, userIdList, callback) { RongIMLib.CheckParam.getInstance().check(["string", "array", "object"], "createDiscussion", false, arguments); RongIMClient._dataAccessProvider.createDiscussion(name, userIdList, callback); }; /** * [getDiscussion 获取讨论组信息] * @param {string} discussionId [讨论组Id] * @param {ResultCallback} callback [返回值,函数回调] */ RongIMClient.prototype.getDiscussion = function (discussionId, callback) { RongIMLib.CheckParam.getInstance().check(["string", "object"], "getDiscussion", false, arguments); RongIMClient._dataAccessProvider.getDiscussion(discussionId, RongIMClient.logCallback(callback, "getDiscussion")); }; /** * [quitDiscussion 退出讨论组] * @param {string} discussionId [讨论组Id] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.quitDiscussion = function (discussionId, callback) { RongIMLib.CheckParam.getInstance().check(["string", "object"], "quitDiscussion", false, arguments); RongIMClient._dataAccessProvider.quitDiscussion(discussionId, RongIMClient.logCallback(callback, "quitDiscussion")); }; /** * [removeMemberFromDiscussion 将指定成员移除讨论租] * @param {string} discussionId [讨论组Id] * @param {string} userId [被移除的用户Id] * @param {OperationCallback} callback [返回值,参数回调] */ RongIMClient.prototype.removeMemberFromDiscussion = function (discussionId, userId, callback) { RongIMLib.CheckParam.getInstance().check(["string", "string", "object"], "removeMemberFromDiscussion", false, arguments); RongIMClient._dataAccessProvider.removeMemberFromDiscussion(discussionId, userId, RongIMClient.logCallback(callback, "removeMemberFromDiscussion")); }; /** * [setDiscussionInviteStatus 设置讨论组邀请状态] * @param {string} discussionId [讨论组Id] * @param {DiscussionInviteStatus} status [邀请状态] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.setDiscussionInviteStatus = function (discussionId, status, callback) { RongIMLib.CheckParam.getInstance().check(["string", "number", "object"], "setDiscussionInviteStatus", false, arguments); RongIMClient._dataAccessProvider.setDiscussionInviteStatus(discussionId, status, RongIMClient.logCallback(callback, "setDiscussionInviteStatus")); }; /** * [setDiscussionName 设置讨论组名称] * @param {string} discussionId [讨论组Id] * @param {string} name [讨论组名称] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.setDiscussionName = function (discussionId, name, callback) { RongIMLib.CheckParam.getInstance().check(["string", "string", "object"], "setDiscussionName", false, arguments); RongIMClient._dataAccessProvider.setDiscussionName(discussionId, name, RongIMClient.logCallback(callback, "setDiscussionName")); }; // #endregion Discussion // #region ChatRoom /** * [加入聊天室。] * @param {string} chatroomId [聊天室Id] * @param {number} messageCount [拉取消息数量,-1为不拉去消息] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.joinChatRoom = function (chatroomId, messageCount, callback) { RongIMLib.CheckParam.getInstance().check(["string", "number", "object"], "joinChatRoom", false, arguments); if (chatroomId == "") { setTimeout(function () { var errorCode = RongIMLib.ErrorCode.CHATROOM_ID_ISNULL; RongIMClient.logger({ code: errorCode, funcName: "joinChatRoom" }); callback.onError(RongIMLib.ErrorCode.CHATROOM_ID_ISNULL); }); return; } RongIMClient._dataAccessProvider.joinChatRoom(chatroomId, messageCount, RongIMClient.logCallback(callback, "joinChatRoom")); }; RongIMClient.prototype.setDeviceInfo = function (device) { RongIMClient._dataAccessProvider.setDeviceInfo(device); }; RongIMClient.prototype.setChatroomHisMessageTimestamp = function (chatRoomId, timestamp) { RongIMLib.CheckParam.getInstance().check(["string", "number"], "setChatroomHisMessageTimestamp", false, arguments); RongIMClient._dataAccessProvider.setChatroomHisMessageTimestamp(chatRoomId, timestamp); }; RongIMClient.prototype.getChatRoomHistoryMessages = function (chatRoomId, count, order, callback) { RongIMLib.CheckParam.getInstance().check(["string", "number", "number", "object"], "getChatRoomHistoryMessages", false, arguments); RongIMClient._dataAccessProvider.getChatRoomHistoryMessages(chatRoomId, count, order, RongIMClient.logCallback(callback, "getChatRoomHistoryMessages")); }; RongIMClient.prototype.getChatRoomInfo = function (chatRoomId, count, order, callback) { RongIMLib.CheckParam.getInstance().check(["string", "number", "number", "object"], "getChatRoomInfo", false, arguments); RongIMClient._dataAccessProvider.getChatRoomInfo(chatRoomId, count, order, RongIMClient.logCallback(callback, "getChatRoomInfo")); }; /** * [退出聊天室] * @param {string} chatroomId [聊天室Id] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.quitChatRoom = function (chatroomId, callback) { RongIMLib.CheckParam.getInstance().check(["string", "object"], "quitChatRoom", false, arguments); RongIMClient._dataAccessProvider.quitChatRoom(chatroomId, RongIMClient.logCallback(callback, "quitChatRoom")); }; RongIMClient.prototype.setChatroomEntry = function (chatroomId, chatroomEntry, callback) { RongIMLib.CheckParam.getInstance().check(['string', 'object', 'object'], 'setChatroomEntry', false, arguments); RongIMClient._dataAccessProvider.setChatroomEntry(chatroomId, chatroomEntry, RongIMClient.logCallback(callback, "setChatroomEntry")); }; RongIMClient.prototype.forceSetChatroomEntry = function (chatroomId, chatroomEntry, callback) { RongIMLib.CheckParam.getInstance().check(['string', 'object', 'object'], 'setChatroomEntry', false, arguments); RongIMClient._dataAccessProvider.forceSetChatroomEntry(chatroomId, chatroomEntry, RongIMClient.logCallback(callback, "setChatroomEntry")); }; RongIMClient.prototype.getChatroomEntry = function (chatroomId, key, callback) { RongIMLib.CheckParam.getInstance().check(['string', 'string', 'object'], 'getChatroomEntry', false, arguments); RongIMClient._dataAccessProvider.getChatroomEntry(chatroomId, key, RongIMClient.logCallback(callback, "setChatroomEntry")); }; RongIMClient.prototype.getAllChatroomEntries = function (chatroomId, callback) { RongIMLib.CheckParam.getInstance().check(['string', 'object'], 'getAllChatroomEntries', false, arguments); RongIMClient._dataAccessProvider.getAllChatroomEntries(chatroomId, RongIMClient.logCallback(callback, "setChatroomEntry")); }; RongIMClient.prototype.removeChatroomEntry = function (chatroomId, chatroomEntry, callback) { RongIMLib.CheckParam.getInstance().check(['string', 'object', 'object'], 'removeChatroomEntry', false, arguments); RongIMClient._dataAccessProvider.removeChatroomEntry(chatroomId, chatroomEntry, RongIMClient.logCallback(callback, "setChatroomEntry")); }; RongIMClient.prototype.forceRemoveChatroomEntry = function (chatroomId, chatroomEntry, callback) { RongIMLib.CheckParam.getInstance().check(['string', 'object', 'object'], 'removeChatroomEntry', false, arguments); RongIMClient._dataAccessProvider.forceRemoveChatroomEntry(chatroomId, chatroomEntry, RongIMClient.logCallback(callback, "setChatroomEntry")); }; // #endregion ChatRoom // #region Public Service RongIMClient.prototype.getRemotePublicServiceList = function (callback, pullMessageTime) { RongIMClient._dataAccessProvider.getRemotePublicServiceList(RongIMClient.logCallback(callback, "getRemotePublicServiceList"), pullMessageTime); }; /** * [getPublicServiceList ]获取本地的公共账号列表 * @param {ResultCallback} callback [返回值,参数回调] */ RongIMClient.prototype.getPublicServiceList = function (callback) { if (RongIMClient._memoryStore.depend.openMp) { RongIMLib.CheckParam.getInstance().check(["object"], "getPublicServiceList", false, arguments); this.getRemotePublicServiceList(RongIMClient.logCallback(callback, "getPublicServiceList")); } }; /** * [getPublicServiceProfile ] 获取某公共服务信息。 * @param {PublicServiceType} publicServiceType [公众服务类型。] * @param {string} publicServiceId [公共服务 Id。] * @param {ResultCallback} callback [公共账号信息回调。] */ RongIMClient.prototype.getPublicServiceProfile = function (publicServiceType, publicServiceId, callback) { if (RongIMClient._memoryStore.depend.openMp) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "getPublicServiceProfile", false, arguments); RongIMClient._dataAccessProvider.getPublicServiceProfile(publicServiceType, publicServiceId, RongIMClient.logCallback(callback, "getPublicServiceProfile")); } }; /** * [pottingPublicSearchType ] 公众好查询类型 * @param {number} bussinessType [ 0-all 1-mp 2-mc] * @param {number} searchType [0-exact 1-fuzzy] */ RongIMClient.prototype.pottingPublicSearchType = function (bussinessType, searchType) { if (RongIMClient._memoryStore.depend.openMp) { var bits = 0; if (bussinessType == 0) { bits |= 3; if (searchType == 0) { bits |= 12; } else { bits |= 48; } } else if (bussinessType == 1) { bits |= 1; if (searchType == 0) { bits |= 8; } else { bits |= 32; } } else { bits |= 2; if (bussinessType == 0) { bits |= 4; } else { bits |= 16; } } return bits; } }; /** * [searchPublicService ]按公众服务类型搜索公众服务。 * @param {SearchType} searchType [搜索类型枚举。] * @param {string} keywords [搜索关键字。] * @param {ResultCallback} callback [搜索结果回调。] */ RongIMClient.prototype.searchPublicService = function (searchType, keywords, callback) { if (RongIMClient._memoryStore.depend.openMp) { RongIMLib.CheckParam.getInstance().check(["number", "string", "object"], "searchPublicService", false, arguments); var modules = new RongIMClient.Protobuf.SearchMpInput(); modules.setType(this.pottingPublicSearchType(0, searchType)); modules.setId(keywords); RongIMClient.bridge.queryMsg(29, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, RongIMClient.logCallback(callback, "searchPublicService"), "SearchMpOutput"); } }; /** * [searchPublicServiceByType ]按公众服务类型搜索公众服务。 * @param {PublicServiceType} publicServiceType [公众服务类型。] * @param {SearchType} searchType [搜索类型枚举。] * @param {string} keywords [搜索关键字。] * @param {ResultCallback} callback [搜索结果回调。] */ RongIMClient.prototype.searchPublicServiceByType = function (publicServiceType, searchType, keywords, callback) { if (RongIMClient._memoryStore.depend.openMp) { RongIMLib.CheckParam.getInstance().check(["number", "number", "string", "object"], "searchPublicServiceByType", false, arguments); var type = publicServiceType == RongIMLib.ConversationType.APP_PUBLIC_SERVICE ? 2 : 1; var modules = new RongIMClient.Protobuf.SearchMpInput(); modules.setType(this.pottingPublicSearchType(type, searchType)); modules.setId(keywords); RongIMClient.bridge.queryMsg(29, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, RongIMClient.logCallback(callback, "searchPublicServiceByType"), "SearchMpOutput"); } }; /** * [subscribePublicService ] 订阅公众号。 * @param {PublicServiceType} publicServiceType [公众服务类型。] * @param {string} publicServiceId [公共服务 Id。] * @param {OperationCallback} callback [订阅公众号回调。] */ RongIMClient.prototype.subscribePublicService = function (publicServiceType, publicServiceId, callback) { if (RongIMClient._memoryStore.depend.openMp) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "subscribePublicService", false, arguments); var modules = new RongIMClient.Protobuf.MPFollowInput(), me = this, follow = publicServiceType == RongIMLib.ConversationType.APP_PUBLIC_SERVICE ? "mcFollow" : "mpFollow"; modules.setId(publicServiceId); RongIMClient.bridge.queryMsg(follow, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function () { me.getRemotePublicServiceList({ onSuccess: function () { }, onError: function () { } }); callback.onSuccess(); }, onError: function (code) { var errorCode = code; RongIMClient.logger({ code: errorCode, funcName: "subscribePublicService" }); callback.onError(code); } }, "MPFollowOutput"); } }; /** * [unsubscribePublicService ] 取消订阅公众号。 * @param {PublicServiceType} publicServiceType [公众服务类型。] * @param {string} publicServiceId [公共服务 Id。] * @param {OperationCallback} callback [取消订阅公众号回调。] */ RongIMClient.prototype.unsubscribePublicService = function (publicServiceType, publicServiceId, callback) { if (RongIMClient._memoryStore.depend.openMp) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "unsubscribePublicService", false, arguments); var modules = new RongIMClient.Protobuf.MPFollowInput(), me = this, follow = publicServiceType == RongIMLib.ConversationType.APP_PUBLIC_SERVICE ? "mcUnFollow" : "mpUnFollow"; modules.setId(publicServiceId); RongIMClient.bridge.queryMsg(follow, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function () { RongIMClient._memoryStore.publicServiceMap.remove(publicServiceType, publicServiceId); callback.onSuccess(); }, onError: function (code) { var errorCode = code; RongIMClient.logger({ code: errorCode, funcName: "unsubscribePublicService" }); callback.onError(code); } }, "MPFollowOutput"); } }; // #endregion Public Service // #region Blacklist /** * [加入黑名单] * @param {string} userId [将被加入黑名单的用户Id] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.addToBlacklist = function (userId, callback) { RongIMLib.CheckParam.getInstance().check(["string|number", "object"], "addToBlacklist", false, arguments); RongIMClient._dataAccessProvider.addToBlacklist(userId, RongIMClient.logCallback(callback, "addToBlacklist")); }; /** * [获取黑名单列表] * @param {GetBlacklistCallback} callback [返回值,函数回调] */ RongIMClient.prototype.getBlacklist = function (callback) { RongIMLib.CheckParam.getInstance().check(["object"], "getBlacklist", false, arguments); RongIMClient._dataAccessProvider.getBlacklist(callback); }; /** * [得到指定人员再黑名单中的状态] * @param {string} userId [description] * @param {ResultCallback} callback [返回值,函数回调] */ //TODO 如果人员不在黑名单中,获取状态会出现异常 RongIMClient.prototype.getBlacklistStatus = function (userId, callback) { RongIMLib.CheckParam.getInstance().check(["string|number", "object"], "getBlacklistStatus", false, arguments); RongIMClient._dataAccessProvider.getBlacklistStatus(userId, RongIMClient.logCallback(callback, "getBlacklistStatus")); }; /** * [将指定用户移除黑名单] * @param {string} userId [将被移除的用户Id] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.removeFromBlacklist = function (userId, callback) { RongIMLib.CheckParam.getInstance().check(["string|number", "object"], "removeFromBlacklist", false, arguments); RongIMClient._dataAccessProvider.removeFromBlacklist(userId, RongIMClient.logCallback(callback, "removeFromBlacklist")); }; RongIMClient.prototype.getFileToken = function (fileType, callback) { RongIMLib.CheckParam.getInstance().check(["number", "object"], "getQngetFileTokenTkn", false, arguments); RongIMClient._dataAccessProvider.getFileToken(fileType, RongIMClient.logCallback(callback, "getFileToken")); }; RongIMClient.prototype.getFileUrl = function (fileType, fileName, oriName, callback) { RongIMLib.CheckParam.getInstance().check(["number", "string", "string|global|object|null", "object"], "getFileUrl", false, arguments); RongIMClient._dataAccessProvider.getFileUrl(fileType, fileName, oriName, RongIMClient.logCallback(callback, "getFileUrl")); }; ; // #endregion Blacklist // #region Real-time Location Service RongIMClient.prototype.addRealTimeLocationListener = function (conversationType, targetId, listener) { throw new Error("Not implemented yet"); }; RongIMClient.prototype.getRealTimeLocation = function (conversationType, targetId) { throw new Error("Not implemented yet"); }; RongIMClient.prototype.getRealTimeLocationCurrentState = function (conversationType, targetId) { throw new Error("Not implemented yet"); }; RongIMClient.prototype.getRealTimeLocationParticipants = function (conversationType, targetId) { throw new Error("Not implemented yet"); }; RongIMClient.prototype.joinRealTimeLocation = function (conversationType, targetId) { throw new Error("Not implemented yet"); }; RongIMClient.prototype.quitRealTimeLocation = function (conversationType, targetId) { throw new Error("Not implemented yet"); }; RongIMClient.prototype.startRealTimeLocation = function (conversationType, targetId) { throw new Error("Not implemented yet"); }; RongIMClient.prototype.updateRealTimeLocationStatus = function (conversationType, targetId, latitude, longitude) { throw new Error("Not implemented yet"); }; // #endregion Real-time Location Service // # startVoIP RongIMClient.prototype.startCall = function (converType, targetId, userIds, mediaType, extra, callback) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "array", "number", "string", "object"], "startCall", false, arguments); if (RongIMClient._memoryStore.voipStategy) { RongIMClient._voipProvider.startCall(converType, targetId, userIds, mediaType, extra, RongIMClient.logCallback(callback, "startCall")); } else { var errorCode = RongIMLib.ErrorCode.VOIP_NOT_AVALIABLE; RongIMClient.logger({ code: errorCode, funcName: "startCall" }); callback.onError(RongIMLib.ErrorCode.VOIP_NOT_AVALIABLE); } }; RongIMClient.prototype.joinCall = function (mediaType, callback) { RongIMLib.CheckParam.getInstance().check(['number', 'object'], "joinCall", false, arguments); if (RongIMClient._memoryStore.voipStategy) { RongIMClient._voipProvider.joinCall(mediaType, RongIMClient.logCallback(callback, "joinCall")); } else { var errorCode = RongIMLib.ErrorCode.VOIP_NOT_AVALIABLE; RongIMClient.logger({ code: errorCode, funcName: "joinCall" }); callback.onError(RongIMLib.ErrorCode.VOIP_NOT_AVALIABLE); } }; RongIMClient.prototype.hungupCall = function (converType, targetId, reason) { RongIMLib.CheckParam.getInstance().check(["number", "string", "number"], "hungupCall", false, arguments); if (RongIMClient._memoryStore.voipStategy) { RongIMClient._voipProvider.hungupCall(converType, targetId, reason); } }; RongIMClient.prototype.changeMediaType = function (converType, targetId, mediaType, callback) { RongIMLib.CheckParam.getInstance().check(["number", "string", "number", "object"], "changeMediaType", false, arguments); if (RongIMClient._memoryStore.voipStategy) { RongIMClient._voipProvider.changeMediaType(converType, targetId, mediaType, RongIMClient.logCallback(callback, "changeMediaType")); } else { var errorCode = RongIMLib.ErrorCode.VOIP_NOT_AVALIABLE; RongIMClient.logger({ code: errorCode, funcName: "changeMediaType" }); callback.onError(RongIMLib.ErrorCode.VOIP_NOT_AVALIABLE); } }; // # endVoIP RongIMClient.prototype.getUnreadMentionedMessages = function (conversationType, targetId) { return RongIMClient._dataAccessProvider.getUnreadMentionedMessages(conversationType, targetId); }; RongIMClient.prototype.clearListeners = function () { RongIMClient._dataAccessProvider.clearListeners(); }; // UserStatus start RongIMClient.prototype.getUserStatus = function (userId, callback) { RongIMClient._dataAccessProvider.getUserStatus(userId, RongIMClient.logCallback(callback, "getUserStatus")); }; RongIMClient.prototype.setUserStatus = function (status, callback) { RongIMClient._dataAccessProvider.setUserStatus(status, RongIMClient.logCallback(callback, "setUserStatus")); }; RongIMClient.prototype.setUserStatusListener = function (params, callback) { var userIds = params.userIds; var multiple = params.multiple; RongIMClient.userStatusObserver.watch({ key: userIds, func: callback, multiple: multiple }); RongIMClient._dataAccessProvider.setUserStatusListener(params, callback); }; // UserStaus end // RTC start RongIMClient.messageWatch = function (watcher) { RongIMClient.RTCListener = watcher; }; RongIMClient.messageSignalWatch = function (watcher) { RongIMClient.RTCSignalLisener = watcher; }; /* var data = { key1: 123, key2: 345 }; */ RongIMClient.prototype.getRTCUserInfoList = function (room, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object"], "getRTCUserInfoList", false, arguments); RongIMClient._dataAccessProvider.getRTCUserInfoList(room, callback); }; RongIMClient.prototype.getRTCUserList = function (room, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object"], "getRTCUserList", false, arguments); RongIMClient._dataAccessProvider.getRTCUserList(room, callback); }; RongIMClient.prototype.setRTCUserInfo = function (room, info, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object", "object"], "setRTCUserInfo", false, arguments); RongIMClient._dataAccessProvider.setRTCUserInfo(room, info, callback); }; RongIMClient.prototype.removeRTCUserInfo = function (room, info, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object", "object"], "removeRTCUserInfo", false, arguments); RongIMClient._dataAccessProvider.removeRTCUserInfo(room, info, callback); }; RongIMClient.prototype.getRTCRoomInfo = function (room, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object"], "getRTCRoomInfo", false, arguments); RongIMClient._dataAccessProvider.getRTCRoomInfo(room, callback); }; RongIMClient.prototype.setRTCRoomInfo = function (room, info, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object", "object"], "setRTCRoomInfo", false, arguments); RongIMClient._dataAccessProvider.setRTCRoomInfo(room, info, callback); }; RongIMClient.prototype.removeRTCRoomInfo = function (room, info, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object", "object"], "removeRTCRoomInfo", false, arguments); RongIMClient._dataAccessProvider.removeRTCRoomInfo(room, info, callback); }; RongIMClient.prototype.joinRTCRoom = function (room, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object"], "joinRTCRoom", false, arguments); if (RongIMClient.isJoinedRTCRoom) { return callback.onSuccess(RongIMClient.roomInfo); } RongIMClient._dataAccessProvider.joinRTCRoom(room, { onSuccess: function (result) { RongIMClient.roomInfo = result; RongIMClient.isJoinedRTCRoom = true; callback.onSuccess(result); }, onError: callback.onError }); }; RongIMClient.prototype.quitRTCRoom = function (room, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object"], "quitRTCRoom", false, arguments); RongIMClient.isJoinedRTCRoom = false; RongIMClient._dataAccessProvider.quitRTCRoom(room, { onSuccess: function () { RongIMClient.roomInfo = { users: {}, token: '' }; callback.onSuccess(true); }, onError: callback.onError }); }; RongIMClient.prototype.RTCPing = function (room, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object"], "RTCPing", false, arguments); RongIMClient._dataAccessProvider.RTCPing(room, callback); }; RongIMClient.prototype.setRTCUserData = function (roomId, key, value, isInner, callback, message) { RongIMLib.CheckParam.getInstance().check(["string", "string", "string", "boolean", "object", "global|object|null|undefined"], "setRTCUserData", false, arguments); RongIMClient._dataAccessProvider.setRTCUserData(roomId, key, value, isInner, callback, message); }; RongIMClient.prototype.getRTCUserData = function (roomId, keys, isInner, callback) { RongIMLib.CheckParam.getInstance().check(["string", "array", "boolean", "object", "global|object|null"], "getRTCUserData", false, arguments); RongIMClient._dataAccessProvider.getRTCUserData(roomId, keys, isInner, callback); }; RongIMClient.prototype.removeRTCUserData = function (roomId, keys, isInner, callback, message) { RongIMLib.CheckParam.getInstance().check(["string", "array", "boolean", "object", "global|object|null|undefined"], "removeRTCUserData", false, arguments); RongIMClient._dataAccessProvider.removeRTCUserData(roomId, keys, isInner, callback, message); }; RongIMClient.prototype.setRTCRoomData = function (roomId, key, value, isInner, callback, message) { RongIMLib.CheckParam.getInstance().check(["string", "string", "string", "boolean", "object", "global|object|null|undefined"], "setRTCRoomData", false, arguments); RongIMClient._dataAccessProvider.setRTCRoomData(roomId, key, value, isInner, callback, message); }; RongIMClient.prototype.getRTCRoomData = function (roomId, keys, isInner, callback) { RongIMLib.CheckParam.getInstance().check(["string", "array", "boolean", "object"], "getRTCRoomData", false, arguments); RongIMClient._dataAccessProvider.getRTCRoomData(roomId, keys, isInner, callback); }; RongIMClient.prototype.removeRTCRoomData = function (roomId, keys, isInner, callback, message) { RongIMLib.CheckParam.getInstance().check(["string", "array", "boolean", "object", "global|object|null|undefined"], "removeRTCRoomData", false, arguments); RongIMClient._dataAccessProvider.removeRTCRoomData(roomId, keys, isInner, callback, message); }; RongIMClient.prototype.setRTCOutData = function (roomId, data, type, callback, message) { RongIMClient._dataAccessProvider.setRTCOutData(roomId, data, type, callback, message); }; // 信令 SDK 新增 RongIMClient.prototype.getRTCOutData = function (roomId, userIds, callback) { RongIMClient._dataAccessProvider.getRTCOutData(roomId, userIds, callback); }; RongIMClient.prototype.getNavi = function () { return RongIMClient._dataAccessProvider.getNavi(); }; RongIMClient.prototype.getRTCToken = function (room, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object"], "getRTCToken", false, arguments); return RongIMClient._dataAccessProvider.getRTCToken(room, callback); }; RongIMClient.prototype.setRTCState = function (room, content, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object", "object"], "setRTCState", false, arguments); return RongIMClient._dataAccessProvider.setRTCState(room, content, callback); }; RongIMClient.prototype.getAppInfo = function () { var appKey = RongIMClient._memoryStore.appKey; return { appKey: appKey }; }; RongIMClient.prototype.getSDKInfo = function () { return { version: RongIMClient.sdkver }; }; RongIMClient.RTCListener = function () { }; RongIMClient.RTCInnerListener = function () { }; RongIMClient.RTCSignalLisener = function () { }; RongIMClient.currentServer = ''; RongIMClient.LogFactory = {}; RongIMClient.MessageType = {}; RongIMClient.RegisterMessage = {}; RongIMClient._memoryStore = { isPullFinished: false, syncMsgQueue: [] }; RongIMClient.isNotPullMsg = false; RongIMClient.userStatusObserver = null; RongIMClient.sdkver = '2.5.4'; RongIMClient.otherDeviceLoginCount = 0; RongIMClient.serverStore = { index: 0 }; RongIMClient.isFirstConnect = true; RongIMClient.roomInfo = { users: {}, token: '' }; RongIMClient.invalidWsUrls = []; RongIMClient.isJoinedRTCRoom = false; RongIMClient.statusListeners = []; RongIMClient.messageListeners = []; RongIMClient.userStatusListener = null; return RongIMClient; })(); RongIMLib.RongIMClient = RongIMClient; })(RongIMLib || (RongIMLib = {})); //用于连接通道 var RongIMLib; (function (RongIMLib) { (function (Qos) { Qos[Qos["AT_MOST_ONCE"] = 0] = "AT_MOST_ONCE"; Qos[Qos["AT_LEAST_ONCE"] = 1] = "AT_LEAST_ONCE"; Qos[Qos["EXACTLY_ONCE"] = 2] = "EXACTLY_ONCE"; Qos[Qos["DEFAULT"] = 3] = "DEFAULT"; })(RongIMLib.Qos || (RongIMLib.Qos = {})); var Qos = RongIMLib.Qos; (function (Type) { Type[Type["CONNECT"] = 1] = "CONNECT"; Type[Type["CONNACK"] = 2] = "CONNACK"; Type[Type["PUBLISH"] = 3] = "PUBLISH"; Type[Type["PUBACK"] = 4] = "PUBACK"; Type[Type["QUERY"] = 5] = "QUERY"; Type[Type["QUERYACK"] = 6] = "QUERYACK"; Type[Type["QUERYCON"] = 7] = "QUERYCON"; Type[Type["SUBSCRIBE"] = 8] = "SUBSCRIBE"; Type[Type["SUBACK"] = 9] = "SUBACK"; Type[Type["UNSUBSCRIBE"] = 10] = "UNSUBSCRIBE"; Type[Type["UNSUBACK"] = 11] = "UNSUBACK"; Type[Type["PINGREQ"] = 12] = "PINGREQ"; Type[Type["PINGRESP"] = 13] = "PINGRESP"; Type[Type["DISCONNECT"] = 14] = "DISCONNECT"; })(RongIMLib.Type || (RongIMLib.Type = {})); var Type = RongIMLib.Type; var _topic = [ "invtDiz", "crDiz", "qnUrl", "userInf", "dizInf", "userInf", "joinGrp", "quitDiz", "exitGrp", "evctDiz", ["", "ppMsgP", "pdMsgP", "pgMsgP", "chatMsg", "pcMsgP", "", "pmcMsgN", "pmpMsgN", "", "", "", "prMsgS", "prMsgP"], "pdOpen", "rename", "uGcmpr", "qnTkn", "destroyChrm", "createChrm", "exitChrm", "queryChrm", "joinChrm", "pGrps", "addBlack", "rmBlack", "getBlack", "blackStat", "addRelation", "qryRelation", "delRelation", "pullMp", "schMp", "qnTkn", "qnUrl", "qryVoipK", "delMsg", "qryCHMsg", "getUserStatus", "setUserStatus", "subUserStatus", "cleanHisMsg" ]; var Channel = (function () { function Channel(cb, self) { this.connectionStatus = -1; var appId = self.appId; var token = encodeURIComponent(self.token); var sdkVer = self.sdkVer; var apiVer = self.apiVer; this.self = self; this.socket = Socket.getInstance().createServer(); var that = this; var storage = RongIMLib.RongIMClient._storageProvider; var servers = storage.getItem('servers'); servers = JSON.parse(servers) || []; servers = RongIMLib.RongUtil.getValidWsUrlList(servers); var depend = RongIMLib.RongIMClient._memoryStore.depend; if (depend.cmpUrl) { servers = [depend.cmpUrl].concat(servers); } var startConnect = function (host) { var tpl = '{host}/websocket?appId={appId}&token={token}&sdkVer={sdkVer}&apiVer={apiVer}'; that.url = RongIMLib.RongUtil.tplEngine(tpl, { host: host, appId: appId, token: token, sdkVer: sdkVer, apiVer: apiVer }); that.socket.connect(that.url, cb); // 临时兼容 Comet 逻辑,Comet 中用到 var userId = storage.getItem('rong_current_user'); RongIMLib.Navigation.Endpoint = { host: host, userId: userId }; }; var connectMap = { get: function () { // 所有链接计算器,超过 15 秒后认为所有 CMP 地址均不可用 var totalTimer = new RongIMLib.Timer({ timeout: 1 * 1000 * 15 }); var timers = []; var xhrs = []; var isFinished = false; var clearHandler = function () { for (var i = 0; i < timers.length; i++) { var timer = timers[i]; clearTimeout(timer); } for (var i = 0; i < xhrs.length; i++) { var xhr = xhrs[i]; xhr.abort(); } timers.length = 0; xhrs.length = 0; }; var request = function (config, callback) { var url = config.url; var time = config.time; if (isFinished) { return; } var timer = setTimeout(function () { var onSuccess = function () { if (isFinished) { return; } clearHandler(); isFinished = true; totalTimer.pause(); callback(url); }; var xhr = RongIMLib.MessageUtil.detectCMP({ url: url, success: onSuccess, fail: function (code) { console.log(code); } }); xhrs.push(xhr); }, time); timers.push(timer); }; var snifferCallback = function (url) { var reg = /(http|https):\/\/([^\/]+)/i; var host = url.match(reg)[2]; RongIMLib.RongIMClient.currentServer = host; startConnect(host); }; var snifferTpl = '{protocol}{server}/ping?r={random}'; for (var i = 0; i < servers.length; i++) { var server = servers[i]; if (server) { server = RongIMLib.RongUtil.tplEngine(snifferTpl, { protocol: depend.protocol, server: server, random: RongIMLib.RongUtil.getTimestamp() }); request({ url: server, time: i * 1000 }, snifferCallback); } } totalTimer.resume(function () { RongIMLib.Navigation.clear(); clearHandler(); that.socket.fire("StatusChanged", RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE); }); }, element: function () { var totalTimer = new RongIMLib.Timer({ timeout: 1 * 1000 * 15 }); var timers = []; var elements = []; var isFinished = false; var clearHandler = function () { for (var i = 0; i < timers.length; i++) { var timer = timers[i]; clearTimeout(timer); } for (var i = 0; i < elements.length; i++) { var el = elements[i]; document.body.removeChild(el); } }; var request = function (config, callback) { var url = config.url; var time = config.time; if (isFinished) { return; } var timer = setTimeout(function () { var el = document.createElement('script'); el.src = url; document.body.appendChild(el); el.onerror = function () { if (isFinished) { return; } clearHandler(); isFinished = true; totalTimer.pause(); var url = el.src; callback(url); }; elements.push(el); }, time); timers.push(timer); }; var snifferCallback = function (url) { var reg = /(http|https):\/\/([^\/]+)/i; var host = url.match(reg)[2]; startConnect(host); }; var snifferTpl = '//{server}/{path}'; for (var i = 0; i < servers.length; i++) { var server = RongIMLib.RongUtil.tplEngine(snifferTpl, { server: servers[i], path: i }); request({ url: server, time: i * 1000 }, snifferCallback); } totalTimer.resume(function () { clearHandler(); that.socket.fire("StatusChanged", RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE); }); } }; var isWSPingJSONP = depend.isWSPingJSONP; var connectType = isWSPingJSONP ? 'element' : 'get'; if (depend.cmpUrl) { startConnect(depend.cmpUrl); } else { connectMap[connectType](); } //注册状态改变观察者 var StatusEvent = Channel._ConnectionStatusListener; var hasEvent = (typeof StatusEvent == "object"); var me = this; me.socket.on("StatusChanged", function (code) { if (RongIMLib.Bridge && RongIMLib.Bridge._client && RongIMLib.Bridge._client.channel && me !== RongIMLib.Bridge._client.channel) { return; } if (!hasEvent) { throw new Error("setConnectStatusListener:Parameter format is incorrect"); } var isNetworkUnavailable = (code == RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE); var isWebSocket = !RongIMLib.RongIMClient._memoryStore.depend.isPolling; if (RongIMLib.RongIMClient.isFirstConnect && isNetworkUnavailable && isWebSocket) { code = RongIMLib.ConnectionStatus.WEBSOCKET_UNAVAILABLE; } if (isNetworkUnavailable) { var storage = RongIMLib.RongIMClient._storageProvider; var servers = storage.getItem('servers'); servers = JSON.parse(servers); var currentServer = RongIMLib.RongIMClient.currentServer; if (currentServer) { var index = RongIMLib.RongUtil.indexOf(servers, currentServer); // 如果 currentServer 是 servers 的最后一个,不再替换位置 if (!RongIMLib.RongUtil.isEqual(index, -1)) { var server = servers.splice(index, 1)[0]; servers.push(server); storage.setItem('servers', JSON.stringify(servers)); } } } me.connectionStatus = code; setTimeout(function () { StatusEvent.onChanged(code); }); var isDisconnected = (code == RongIMLib.ConnectionStatus.DISCONNECTED); if (isDisconnected) { self.clearHeartbeat(); } var isOtherDevice = (code == RongIMLib.ConnectionStatus.KICKED_OFFLINE_BY_OTHER_CLIENT); if (isOtherDevice) { // 累计其他设备登陆次数,超过 5 次后,自动销毁内部对象 // 删除位置:ServerDataProivder.prototype.connect RongIMLib.RongIMClient.otherDeviceLoginCount++; } var isConnected = (code == RongIMLib.ConnectionStatus.CONNECTED); if (isConnected) { RongIMLib.RongIMClient.isFirstConnect = false; } var isWebsocketUnAvailable = (code == RongIMLib.ConnectionStatus.WEBSOCKET_UNAVAILABLE); if (isWebsocketUnAvailable) { me.changeConnectType(); RongIMLib.RongIMClient.isFirstConnect = false; RongIMLib.RongIMClient.connect(self.token, RongIMLib.RongIMClient._memoryStore.callback); } }); //注册message观察者 this.socket.on("message", self.handler.handleMessage); //注册断开连接观察者 this.socket.on("disconnect", function (status) { that.socket.fire("StatusChanged", status ? status : 2); }); } Channel.prototype.changeConnectType = function () { RongIMLib.RongIMClient._memoryStore.depend.isPolling = !RongIMLib.RongIMClient._memoryStore.depend.isPolling; new RongIMLib.FeatureDectector(); }; Channel.prototype.writeAndFlush = function (val) { this.socket.send(val); }; Channel.prototype.reconnect = function (callback) { RongIMLib.MessageIdHandler.clearMessageId(); this.socket = this.socket.reconnect(); if (callback) { this.self.reconnectObj = callback; } }; Channel.prototype.disconnect = function (status) { this.socket.disconnect(status); }; return Channel; })(); RongIMLib.Channel = Channel; var Socket = (function () { function Socket() { this.socket = null; this._events = {}; } Socket.getInstance = function () { return new Socket(); }; Socket.prototype.connect = function (url, cb) { if (this.socket) { if (url) { RongIMLib.RongIMClient._storageProvider.setItem("rongSDK", this.checkTransport()); this.on("connect", cb || new Function); } if (url) { this.currentURL = url; } this.socket.createTransport(url); } return this; }; Socket.prototype.createServer = function () { var transport = this.getTransport(this.checkTransport()); if (transport === null) { throw new Error("the channel was not supported"); } return transport; }; Socket.prototype.getTransport = function (transportType) { if (transportType == Socket.XHR_POLLING) { this.socket = new RongIMLib.PollingTransportation(this); } else if (transportType == Socket.WEBSOCKET) { this.socket = new RongIMLib.SocketTransportation(this); } return this; }; Socket.prototype.send = function (data) { if (this.socket) { if (this.checkTransport() == Socket.WEBSOCKET) { this.socket.send(data); } else { this.socket.send(this._encode(data)); } } }; Socket.prototype.onMessage = function (data) { this.fire("message", data); }; Socket.prototype.disconnect = function (status) { this.socket.disconnect(status); this.fire("disconnect", status); return this; }; Socket.prototype.reconnect = function () { if (this.currentURL && RongIMLib.RongIMClient._storageProvider.getItem("rongSDK")) { return this.connect(this.currentURL, null); } else { throw new Error("reconnect:no have URL"); } }; /** * [checkTransport 返回通道类型] */ Socket.prototype.checkTransport = function () { if (RongIMLib.RongIMClient._memoryStore.depend.isPolling) { RongIMLib.Transportations._TransportType = Socket.XHR_POLLING; } return RongIMLib.Transportations._TransportType; }; Socket.prototype.fire = function (x, args) { if (x in this._events) { for (var i = 0, ii = this._events[x].length; i < ii; i++) { this._events[x][i](args); } } return this; }; Socket.prototype.on = function (x, func) { if (!(typeof func == "function" && x)) { return this; } if (x in this._events) { RongIMLib.MessageUtil.indexOf(this._events, func) == -1 && this._events[x].push(func); } else { this._events[x] = [func]; } return this; }; Socket.prototype.removeEvent = function (x, fn) { if (x in this._events) { for (var a = 0, l = this._events[x].length; a < l; a++) { if (this._events[x][a] == fn) { this._events[x].splice(a, 1); } } } return this; }; Socket.prototype._encode = function (x) { var str = "?messageid=" + x.getMessageId() + "&header=" + x.getHeaderFlag() + "&sessionid=" + RongIMLib.RongIMClient._storageProvider.getItem("sId" + RongIMLib.Navigation.Endpoint.userId); if (!RongIMLib.RongIMClient._storageProvider.getItem("sId" + RongIMLib.Navigation.Endpoint.userId)) { // debugger; } if (!/(PubAckMessage|QueryConMessage)/.test(x._name)) { str += "&topic=" + x.getTopic() + "&targetid=" + (x.getTargetId() || ""); } return { url: str, data: "getData" in x ? x.getData() : "" }; }; //消息通道常量,所有和通道相关判断均用 XHR_POLLING WEBSOCKET两属性 Socket.XHR_POLLING = "xhr-polling"; Socket.WEBSOCKET = "websocket"; return Socket; })(); RongIMLib.Socket = Socket; //连接端消息累 var Client = (function () { function Client(token, appId) { this.timeoutMillis = 6000; this.timeout_ = 0; this.sdkVer = ''; this.apiVer = Math.floor(Math.random() * 1e6); this.channel = null; this.handler = null; this.userId = ""; this.reconnectObj = {}; this.heartbeat = 0; this.pullMsgHearbeat = 0; this.chatroomId = ""; this.SyncTimeQueue = []; this.cacheMessageIds = []; this.token = token; this.appId = appId; this.SyncTimeQueue.state = "complete"; this.sdkVer = RongIMLib.RongIMClient.sdkver; } Client.prototype.resumeTimer = function () { var me = this; this.timeout_ = setTimeout(function () { me.channel.disconnect(RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE); }, this.timeoutMillis); }; Client.prototype.pauseTimer = function () { if (this.timeout_) { clearTimeout(this.timeout_); this.timeout_ = 0; } }; Client.prototype.connect = function (_callback) { //实例消息处理类 this.handler = new MessageHandler(this); //设置连接回调 this.handler.setConnectCallback(_callback); //实例通道类型 var me = this; this.channel = new Channel(function () { RongIMLib.Transportations._TransportType == Socket.WEBSOCKET && me.keepLive(); }, this); //触发状态改变观察者 this.channel.socket.fire("StatusChanged", RongIMLib.ConnectionStatus.CONNECTING); //没有返回地址就手动抛出错误 //_callback.onError(ConnectionState.NOT_AUTHORIZED); }; Client.prototype.checkSocket = function (callback) { var me = this; me.channel.writeAndFlush(new RongIMLib.PingReqMessage()); var count = 0; var checkTimeout = setInterval(function () { if (!RongIMLib.RongIMClient._memoryStore.isFirstPingMsg) { clearInterval(checkTimeout); callback.onSuccess(); } else { if (count > 15) { clearInterval(checkTimeout); callback.onError(); } } count++; }, 100); }; Client.prototype.keepLive = function () { if (this.heartbeat > 0) { clearInterval(this.heartbeat); } var me = this; me.heartbeat = setInterval(function () { me.resumeTimer(); me.channel.writeAndFlush(new RongIMLib.PingReqMessage()); }, 30000); if (me.pullMsgHearbeat > 0) { clearInterval(me.pullMsgHearbeat); } me.pullMsgHearbeat = setInterval(function () { me.syncTime(true, undefined, undefined, false); }, 180000); }; Client.prototype.clearHeartbeat = function () { clearInterval(this.heartbeat); this.heartbeat = 0; this.pauseTimer(); clearInterval(this.pullMsgHearbeat); this.pullMsgHearbeat = 0; }; Client.prototype.publishMessage = function (_topic, _data, _targetId, _callback, _msg) { var msgId = RongIMLib.MessageIdHandler.messageIdPlus(this.channel.reconnect); if (!msgId) { return; } var msg = new RongIMLib.PublishMessage(_topic, _data, _targetId); msg.setMessageId(msgId); if (_callback) { msg.setQos(Qos.AT_LEAST_ONCE); this.handler.putCallback(new RongIMLib.PublishCallback(_callback.onSuccess, _callback.onError), msg.getMessageId(), _msg); } else { msg.setQos(Qos.AT_MOST_ONCE); } this.channel.writeAndFlush(msg); }; Client.prototype.queryMessage = function (_topic, _data, _targetId, _qos, _callback, pbtype) { if (_topic == "userInf") { if (Client.userInfoMapping[_targetId]) { _callback.onSuccess(Client.userInfoMapping[_targetId]); return; } } var msgId = RongIMLib.MessageIdHandler.messageIdPlus(this.channel.reconnect); if (!msgId) { return; } var msg = new RongIMLib.QueryMessage(_topic, _data, _targetId); msg.setMessageId(msgId); msg.setQos(_qos); this.handler.putCallback(new RongIMLib.QueryCallback(_callback.onSuccess, _callback.onError), msg.getMessageId(), pbtype); this.channel.writeAndFlush(msg); }; Client.prototype.invoke = function (isPullMsg, chrmId, offlineMsg) { var time, modules, str, me = this, target, temp = this.SyncTimeQueue.shift(); if (temp == undefined) { return; } this.SyncTimeQueue.state = "pending"; var localSyncTime = RongIMLib.SyncTimeUtil.get(); var sentBoxTime = localSyncTime.sent; if (temp.type != 2) { //普通消息 time = localSyncTime.received; modules = new RongIMLib.RongIMClient.Protobuf.SyncRequestMsg(); modules.setIspolling(false); str = "pullMsg"; target = this.userId; modules.setSendBoxSyncTime(sentBoxTime); } else { //聊天室消息 target = temp.chrmId || me.chatroomId; time = RongIMLib.RongIMClient._memoryStore.lastReadTime.get(target + Bridge._client.userId + "CST") || 0; modules = new RongIMLib.RongIMClient.Protobuf.ChrmPullMsg(); modules.setCount(0); str = "chrmPull"; if (!target) { throw new Error("syncTime:Received messages of chatroom but was not init"); } } //判断服务器给的时间是否消息本地存储的时间,小于的话不执行拉取操作,进行一下步队列操作 if (temp.pulltime <= time) { this.SyncTimeQueue.state = "complete"; this.invoke(isPullMsg, target, offlineMsg); return; } if (isPullMsg && 'setIsPullSend' in modules) { modules.setIsPullSend(true); } modules.setSyncTime(time); //发送queryMessage请求 this.queryMessage(str, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), target, Qos.AT_LEAST_ONCE, { onSuccess: function (collection) { var sync = RongIMLib.MessageUtil.int64ToTimestamp(collection.syncTime), symbol = target; //把返回时间戳存入本地,普通消息key为userid,聊天室消息key为userid+'CST';value都为服务器返回的时间戳 var isChrmPull = str == 'chrmPull'; if (isChrmPull) { symbol += Bridge._client.userId + "CST"; RongIMLib.RongIMClient._memoryStore.lastReadTime.set(symbol, sync); } else { var storage = RongIMLib.RongIMClient._storageProvider; if (sync > storage.getItem(symbol)) { storage.setItem(symbol, sync); } } //把拉取到的消息逐条传给消息监听器 var list = collection.list; var isPullFinished = collection.finished; // chrmPull 没有 finished 字段,自动设置为拉取完成 if (isChrmPull) { isPullFinished = true; } // 兼容长轮训 finished 为空的造成丢消息情况 if (typeof isPullFinished == 'undefined') { isPullFinished = true; } RongIMLib.RongIMClient._memoryStore.isPullFinished = isPullFinished; var connectAckTime = RongIMLib.RongIMClient._memoryStore.connectAckTime; var len = list.length; for (var i = 0, count = len; i < len; i++) { count -= 1; var message = list[i]; var sentTime = RongIMLib.MessageUtil.int64ToTimestamp(message.dataTime); var isSender = message.direction == RongIMLib.MessageDirection.SEND; var compareTime = isSender ? sentBoxTime : time; if (sentTime > compareTime) { var isSyncMessage = false; var isOffLineMessage = sentTime < connectAckTime; Bridge._client.handler.onReceived(message, undefined, isOffLineMessage, count, isSyncMessage, isPullFinished); } } if (len <= 200 && str == 'pullMsg') { var Conversation = RongIMLib.RongIMClient._dataAccessProvider.Conversation; var conversationList = RongIMLib.RongIMClient._memoryStore.conversationList; Conversation._notify(conversationList); } me.SyncTimeQueue.state = "complete"; me.invoke(isPullMsg, target, offlineMsg); }, onError: function (error) { me.SyncTimeQueue.state = "complete"; me.invoke(isPullMsg, target, offlineMsg); } }, "DownStreamMessages"); }; Client.prototype.syncTime = function (_type, pullTime, chrmId, offlineMsg) { this.SyncTimeQueue.push({ type: _type, pulltime: pullTime, chrmId: chrmId }); //如果队列中只有一个成员并且状态已经完成就执行invoke方法 if (this.SyncTimeQueue.length == 1 && this.SyncTimeQueue.state == "complete") { this.invoke(!_type, chrmId, offlineMsg); } }; Client.prototype.__init = function (f) { this.handler = new MessageHandler(this); //设置连接回调 this.handler.setConnectCallback(RongIMLib.RongIMClient._memoryStore.callback); this.channel = new Channel(f, this); }; Client.userInfoMapping = {}; return Client; })(); RongIMLib.Client = Client; //连接类,实现imclient与connect_client的连接 var Bridge = (function () { function Bridge() { } Bridge.getInstance = function () { return new Bridge(); }; //连接服务器 Bridge.prototype.connect = function (appKey, token, callback) { if (!RongIMLib.RongIMClient.Protobuf) { return; } Bridge._client = new RongIMLib.Navigation().connect(appKey, token, callback); return Bridge._client; }; Bridge.prototype.setListener = function () { Channel._ConnectionStatusListener = { onChanged: function (status) { RongIMLib.RongUtil.forEach(RongIMLib.RongIMClient.statusListeners, function (watch) { RongIMLib.RongUtil.isFunction(watch) && watch(status); }); } }; Channel._ReceiveMessageListener = { onReceived: function (msg, count, hasMore) { RongIMLib.RongUtil.forEach(RongIMLib.RongIMClient.messageListeners, function (watch) { RongIMLib.RongUtil.isFunction(watch) && watch(msg, count, hasMore); }); } }; }; Bridge.prototype.reconnect = function (callabck) { Bridge._client.channel.reconnect(callabck); }; Bridge.prototype.disconnect = function () { Bridge._client.channel.disconnect(2); }; //执行queryMessage请求 Bridge.prototype.queryMsg = function (topic, content, targetId, callback, pbname) { if (typeof topic != "string") { topic = _topic[topic]; } Bridge._client.queryMessage(topic, content, targetId, Qos.AT_MOST_ONCE, callback, pbname); }; //发送消息 执行publishMessage 请求 Bridge.prototype.pubMsg = function (topic, content, targetId, callback, msg, methodType) { if (typeof methodType == 'number') { if (methodType == RongIMLib.MethodType.CUSTOMER_SERVICE) { Bridge._client.publishMessage("pcuMsgP", content, targetId, callback, msg); } else if (methodType == RongIMLib.MethodType.RECALL) { Bridge._client.publishMessage("recallMsg", content, targetId, callback, msg); } } else { Bridge._client.publishMessage(_topic[10][topic], content, targetId, callback, msg); } }; return Bridge; })(); RongIMLib.Bridge = Bridge; var MessageHandler = (function () { function MessageHandler(client) { this.map = {}; this.connectCallback = null; if (!Channel._ReceiveMessageListener) { throw new Error("please set onReceiveMessageListener"); } this._onReceived = Channel._ReceiveMessageListener.onReceived; this._client = client; this.syncMsgMap = new Object; } //把对象推入回调对象队列中,并启动定时器 MessageHandler.prototype.putCallback = function (callbackObj, _publishMessageId, _msg) { var item = { Callback: callbackObj, Message: _msg }; item.Callback.resumeTimer(); this.map[_publishMessageId] = item; }; //设置连接回调对象,启动定时器 MessageHandler.prototype.setConnectCallback = function (_connectCallback) { if (_connectCallback) { this.connectCallback = new RongIMLib.ConnectAck(_connectCallback.onSuccess, _connectCallback.onError, this._client); } }; MessageHandler.prototype.handleChrmKVPullMsg = function (msg) { try { var pbtype = 'ChrmNotifyMsg'; var data = RongIMLib.CallbackMapping.getInstance().mapping(RongIMLib.RongIMClient.Protobuf[pbtype].decode(msg.data), pbtype); if (data.type === 2) { var timestamp = RongIMLib.MessageUtil.int64ToTimestamp(data.time); RongIMLib.ChrmKVHandler.pull(data.chrmId, timestamp); } } catch (e) { } }; MessageHandler.prototype.onReceived = function (msg, pubAckItem, offlineMsg, leftCount, isSync) { //实体对象 var entity, //解析完成的消息对象 message, //会话对象 con, // 是否为直发消息 isStraightMsg = false; if (msg._name != "PublishMessage") { entity = msg; RongIMLib.RongIMClient._storageProvider.setItem(this._client.userId, RongIMLib.MessageUtil.int64ToTimestamp(entity.dataTime)); } else { if (msg.getTopic() == "s_ntf") { entity = RongIMLib.RongIMClient.Protobuf.NotifyMsg.decode(msg.getData()); this._client.syncTime(entity.type, RongIMLib.MessageUtil.int64ToTimestamp(entity.time), entity.chrmId); return; } else if (msg.getTopic() == "s_msg") { isStraightMsg = true; entity = RongIMLib.RongIMClient.Protobuf.DownStreamMessage.decode(msg.getData()); var timestamp = RongIMLib.MessageUtil.int64ToTimestamp(entity.dataTime); RongIMLib.RongIMClient._storageProvider.setItem(this._client.userId, timestamp); RongIMLib.RongIMClient._memoryStore.lastReadTime.get(this._client.userId, timestamp); } else if (msg.getTopic() == "s_stat") { entity = RongIMLib.RongIMClient.Protobuf.GetUserStatusOutput.decode(msg.getData()); entity = RongIMLib.RongInnerTools.convertUserStatus(entity); RongIMLib.RongIMClient.userStatusObserver.notify({ key: entity.userId, entity: entity }); return; } else if (msg.getTopic() === 's_cmd') { this.handleChrmKVPullMsg(msg); return; } else { if (Bridge._client.sdkVer && Bridge._client.sdkVer == "1.0.0") { return; } entity = RongIMLib.RongIMClient.Protobuf.UpStreamMessage.decode(msg.getData()); var tmpTopic = msg.getTopic(); var tmpType = tmpTopic.substr(0, 2); if (tmpType == "pp") { entity.type = 1; } else if (tmpType == "pd") { entity.type = 2; } else if (tmpType == "pg") { entity.type = 3; } else if (tmpType == "ch") { entity.type = 4; } else if (tmpType == "pc") { entity.type = 5; } //复用字段,targetId 以此为准 entity.groupId = msg.getTargetId(); entity.fromUserId = this._client.userId; entity.dataTime = Date.parse(new Date().toString()); } if (!entity) { return; } } var isPullFinished = RongIMLib.RongIMClient._memoryStore.isPullFinished; // PullMsg 没有拉取完成,抛弃所有直发在线消息,抛弃的消息会在 PullMsg 中返回 if (!isPullFinished && !offlineMsg && isStraightMsg) { return; } //解析实体对象为消息对象。 message = RongIMLib.MessageUtil.messageParser(entity, this._onReceived, offlineMsg); var isRTCMessage = message.conversationType == 12; if (isRTCMessage) { RongIMLib.RongIMClient.RTCListener(message); RongIMLib.RongIMClient.RTCInnerListener(message); RongIMLib.RongIMClient.RTCSignalLisener(message); return; } var isRecall = (msg.getTopic && msg.getTopic() == "recallMsg"); if (isRecall) { var content = message.content; message.conversationType = content.conversationType; message.targetId = content.targetId; message.messageId = null; } if (pubAckItem) { message.messageUId = pubAckItem.getMessageUId(); message.sentTime = pubAckItem.getTimestamp(); RongIMLib.RongIMClient._storageProvider.setItem(this._client.userId, message.sentTime); } if (message === null) { return; } var isChatroomMessage = message.conversationType == RongIMLib.ConversationType.CHATROOM; if (!isChatroomMessage) { var msgTag = RongIMLib.RongIMClient.MessageParams[message.messageType].msgTag.getMessageTag(); if (msgTag >= 0) { RongIMLib.SyncTimeUtil.set(message); } var isSend = (message.messageDirection == RongIMLib.MessageDirection.SEND); if (isSend) { var storageProvider = RongIMLib.RongIMClient._storageProvider; var userId = RongIMLib.Bridge._client.userId; var lastSentTime = storageProvider.getItem('last_sentTime_' + userId) || 0; if (message.sentTime <= lastSentTime && !isSync) { return; } } } // 设置会话时间戳并且判断是否传递 message 发送消息未处理会话时间戳 // key:'converST_' + 当前用户 + conversationType + targetId // RongIMClient._storageProvider.setItem('converST_' + Bridge._client.userId + message.conversationType + message.targetId, message.sentTime); // var isPersited = (RongIMClient.MessageParams[message.messageType].msgTag.getMessageTag() > 0); var msgTag = RongIMLib.RongIMClient.MessageParams[message.messageType].msgTag.getMessageTag(); var isPersited = msgTag === 3 || msgTag === 2; if (isPersited) { con = RongIMLib.RongIMClient._dataAccessProvider.getConversation(message.conversationType, message.targetId, { onSuccess: function () { }, onError: function () { } }); if (!con) { con = RongIMLib.RongIMClient.getInstance().createConversation(message.conversationType, message.targetId, ""); } if (message.messageDirection == RongIMLib.MessageDirection.RECEIVE && (entity.status & 64) == 64) { var mentioneds = RongIMLib.RongIMClient._storageProvider.getItem("mentioneds_" + Bridge._client.userId + '_' + message.conversationType + '_' + message.targetId); var key = message.conversationType + '_' + message.targetId, info = {}; if (message.content && message.content.mentionedInfo) { info[key] = { uid: message.messageUId, time: message.sentTime, mentionedInfo: message.content.mentionedInfo }; RongIMLib.RongIMClient._storageProvider.setItem("mentioneds_" + Bridge._client.userId + '_' + message.conversationType + '_' + message.targetId, JSON.stringify(info)); mentioneds = JSON.stringify(info); } if (mentioneds) { var info = JSON.parse(mentioneds); con.mentionedMsg = info[key]; } } var isReceiver = message.messageDirection == RongIMLib.MessageDirection.RECEIVE; if (isReceiver && message.senderUserId != Bridge._client.userId) { con.unreadMessageCount = con.unreadMessageCount + 1; if (RongIMLib.RongUtil.supportLocalStorage()) { // var originUnreadCount = RongIMClient._storageProvider.getItem("cu" + Bridge._client.userId + con.conversationType + con.targetId); // 与本地存储会话合并 // var newUnreadCount = Number(originUnreadCount) + 1; // RongIMClient._storageProvider.setItem("cu" + Bridge._client.userId + con.conversationType + message.targetId, newUnreadCount); var newUnreadCount = RongIMLib.UnreadCountHandler.add(con.conversationType, message.targetId, 1, message.sentTime); con.unreadMessageCount = newUnreadCount; } } con.receivedTime = new Date().getTime(); con.receivedStatus = message.receivedStatus; con.senderUserId = message.sendUserId; con.notificationStatus = RongIMLib.ConversationNotificationStatus.DO_NOT_DISTURB; con.latestMessageId = message.messageId; con.latestMessage = message; con.sentTime = message.sentTime; RongIMLib.RongIMClient._dataAccessProvider.addConversation(con, { onSuccess: function (data) { if (!offlineMsg) { var Conversation_1 = RongIMLib.RongIMClient._dataAccessProvider.Conversation; var conversationList = RongIMLib.RongIMClient._memoryStore.conversationList; Conversation_1._notify(conversationList); } }, onError: function () { } }); } if (message.conversationType == RongIMLib.ConversationType.CUSTOMER_SERVICE && (message.messageType == "ChangeModeResponseMessage" || message.messageType == "SuspendMessage" || message.messageType == "HandShakeResponseMessage" || message.messageType == "TerminateMessage" || message.messageType == "CustomerStatusUpdateMessage" || message.messageType == "TextMessage" || message.messageType == "InformationNotificationMessage")) { if (!RongIMLib.RongIMClient._memoryStore.custStore["isInit"]) { return; } } if (message.conversationType == RongIMLib.ConversationType.CUSTOMER_SERVICE && message.messageType != "HandShakeResponseMessage") { if (!RongIMLib.RongIMClient._memoryStore.custStore[message.targetId]) { return; } if (message.messageType == "TerminateMessage") { if (RongIMLib.RongIMClient._memoryStore.custStore[message.targetId].sid != message.content.sid) { return; } } } if (message.messageType === RongIMLib.RongIMClient.MessageType["HandShakeResponseMessage"]) { var session = message.content.data; RongIMLib.RongIMClient._memoryStore.custStore[message.targetId] = session; if (session.serviceType == RongIMLib.CustomerType.ONLY_HUMAN || session.serviceType == RongIMLib.CustomerType.HUMAN_FIRST) { if (session.notAutoCha == "1") { RongIMLib.RongIMClient.getInstance().switchToHumanMode(message.targetId, { onSuccess: function () { }, onError: function () { } }); } } } var d = new Date(), m = d.getMonth() + 1, date = d.getFullYear() + '/' + (m.toString().length == 1 ? '0' + m : m) + '/' + d.getDate(); //new Date(date).getTime() - message.sentTime < 1 逻辑判断 超过 1 天未收的 ReadReceiptRequestMessage 离线消息自动忽略。 var dealtime = new Date(date).getTime() - message.sentTime < 0; if (RongIMLib.RongUtil.supportLocalStorage() && message.messageType === RongIMLib.RongIMClient.MessageType["ReadReceiptRequestMessage"] && dealtime && message.messageDirection == RongIMLib.MessageDirection.SEND) { var sentkey = Bridge._client.userId + message.content.messageUId + "SENT"; RongIMLib.RongIMClient._storageProvider.setItem(sentkey, JSON.stringify({ count: 0, dealtime: message.sentTime, userIds: {} })); } else if (RongIMLib.RongUtil.supportLocalStorage() && message.messageType === RongIMLib.RongIMClient.MessageType["ReadReceiptRequestMessage"] && dealtime) { var reckey = Bridge._client.userId + message.conversationType + message.targetId + 'RECEIVED', recData = JSON.parse(RongIMLib.RongIMClient._storageProvider.getItem(reckey)); if (recData) { if (message.senderUserId in recData) { if (recData[message.senderUserId].uIds && recData[message.senderUserId].uIds && recData[message.senderUserId].uIds.indexOf(message.content.messageUId) == -1) { recData[message.senderUserId].uIds.push(message.content.messageUId); recData[message.senderUserId].dealtime = message.sentTime; recData[message.senderUserId].isResponse = false; RongIMLib.RongIMClient._storageProvider.setItem(reckey, JSON.stringify(recData)); } else { return; } } else { var objSon = { uIds: [message.content.messageUId], dealtime: message.sentTime, isResponse: false }; recData[message.senderUserId] = objSon; RongIMLib.RongIMClient._storageProvider.setItem(reckey, JSON.stringify(recData)); } } else { var obj = {}; obj[message.senderUserId] = { uIds: [message.content.messageUId], dealtime: message.sentTime, isResponse: false }; RongIMLib.RongIMClient._storageProvider.setItem(reckey, JSON.stringify(obj)); } } if (RongIMLib.RongUtil.supportLocalStorage() && message.messageType === RongIMLib.RongIMClient.MessageType["ReadReceiptResponseMessage"] && dealtime) { var receiptResponseMsg = message.content, uIds = receiptResponseMsg.receiptMessageDic[Bridge._client.userId], sentkey = "", sentObj; message.receiptResponse || (message.receiptResponse = {}); if (uIds) { var cbuIds = []; for (var i = 0, len = uIds.length; i < len; i++) { sentkey = Bridge._client.userId + uIds[i] + "SENT"; sentObj = JSON.parse(RongIMLib.RongIMClient._storageProvider.getItem(sentkey)); if (sentObj && !(message.senderUserId in sentObj.userIds)) { cbuIds.push(uIds[i]); sentObj.count += 1; sentObj.userIds[message.senderUserId] = message.sentTime; message.receiptResponse[uIds[i]] = sentObj.count; RongIMLib.RongIMClient._storageProvider.setItem(sentkey, JSON.stringify(sentObj)); } } receiptResponseMsg.receiptMessageDic[Bridge._client.userId] = cbuIds; message.content = receiptResponseMsg; } } var that = this; if (RongIMLib.RongIMClient._voipProvider && ['AcceptMessage', 'RingingMessage', 'HungupMessage', 'InviteMessage', 'MediaModifyMessage', 'MemberModifyMessage'].indexOf(message.messageType) > -1) { setTimeout(function () { RongIMLib.RongIMClient._voipProvider.onReceived(message); }); } else { var count = leftCount || 0; var hasMore = !isPullFinished; that._onReceived(message, count, hasMore); } }; MessageHandler.prototype.handleMessage = function (msg) { if (!msg) { return; } switch (msg._name) { case "ConnAckMessage": Bridge._client.handler.connectCallback.process(msg.getStatus(), msg.getUserId(), msg.getTimestamp()); break; case "PublishMessage": if (!msg.getSyncMsg() && msg.getQos() != 0) { Bridge._client.channel.writeAndFlush(new RongIMLib.PubAckMessage(msg.getMessageId())); } // TODO && -> if (msg.getSyncMsg() && !RongIMLib.RongIMClient._memoryStore.depend.isPolling) { Bridge._client.handler.syncMsgMap[msg.getMessageId()] = msg; } else { //如果是PublishMessage就把该对象给onReceived方法执行处理 Bridge._client.handler.onReceived(msg); } break; case "QueryAckMessage": if (msg.getQos() != 0) { Bridge._client.channel.writeAndFlush(new RongIMLib.QueryConMessage(msg.getMessageId())); } var temp = Bridge._client.handler.map[msg.getMessageId()]; if (temp) { //执行回调操作 temp.Callback.process(msg.getStatus(), msg.getData(), msg.getDate(), temp.Message); delete Bridge._client.handler.map[msg.getMessageId()]; } break; case "PubAckMessage": var item = Bridge._client.handler.map[msg.getMessageId()]; if (item) { item.Callback.process(msg.getStatus() || 0, msg.getMessageUId(), msg.getTimestamp(), item.Message, msg.getMessageId()); delete Bridge._client.handler.map[msg.getMessageId()]; } else { var userId = RongIMLib.Bridge._client.userId; RongIMLib.RongIMClient._storageProvider.setItem('last_sentTime_' + userId, msg.timestamp); Bridge._client.handler.onReceived(Bridge._client.handler.syncMsgMap[msg.messageId], msg, null, null, true); delete Bridge._client.handler.syncMsgMap[msg.getMessageId()]; } break; case "PingRespMessage": if (RongIMLib.RongIMClient._memoryStore.isFirstPingMsg) { RongIMLib.RongIMClient._memoryStore.isFirstPingMsg = false; } else { Bridge._client.pauseTimer(); } break; case "DisconnectMessage": Bridge._client.channel.disconnect(msg.getStatus()); break; default: } }; return MessageHandler; })(); RongIMLib.MessageHandler = MessageHandler; })(RongIMLib || (RongIMLib = {})); var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; /// var RongIMLib; (function (RongIMLib) { var MessageCallback = (function () { function MessageCallback(error) { this.timeout = null; this.onError = null; if (error && typeof error == "number") { this.timeoutMillis = error; } else { this.timeoutMillis = 30000; this.onError = error; } } MessageCallback.prototype.resumeTimer = function () { var me = this; if (this.timeoutMillis > 0 && !this.timeout) { this.timeout = setTimeout(function () { me.readTimeOut(true); }, this.timeoutMillis); } }; MessageCallback.prototype.pauseTimer = function () { if (this.timeout) { clearTimeout(this.timeout); this.timeout = null; } }; MessageCallback.prototype.readTimeOut = function (isTimeout) { if (isTimeout && this.onError) { this.onError(RongIMLib.ErrorCode.TIMEOUT); } else { this.pauseTimer(); } }; return MessageCallback; })(); RongIMLib.MessageCallback = MessageCallback; var CallbackMapping = (function () { function CallbackMapping() { this.publicServiceList = []; } CallbackMapping.getInstance = function () { return new CallbackMapping(); }; CallbackMapping.prototype.pottingProfile = function (item) { var temp; this.profile = new RongIMLib.PublicServiceProfile(); temp = JSON.parse(item.extra); this.profile.isGlobal = temp.isGlobal; this.profile.introduction = temp.introduction; this.profile.menu = temp.menu; this.profile.hasFollowed = temp.follow; this.profile.publicServiceId = item.mpid; this.profile.name = item.name; this.profile.portraitUri = item.portraitUrl; this.profile.conversationType = item.type == "mc" ? RongIMLib.ConversationType.APP_PUBLIC_SERVICE : RongIMLib.ConversationType.PUBLIC_SERVICE; this.publicServiceList.push(this.profile); }; CallbackMapping.prototype.mapping = function (entity, tag) { switch (tag) { case "GetUserInfoOutput": var userInfo = new RongIMLib.UserInfo(entity.userId, entity.userName, entity.userPortrait); return userInfo; case "GetQNupTokenOutput": return { deadline: RongIMLib.MessageUtil.int64ToTimestamp(entity.deadline), token: entity.token }; case "GetQNdownloadUrlOutput": return { downloadUrl: entity.downloadUrl }; case "CreateDiscussionOutput": return entity.id; case "ChannelInfoOutput": var disInfo = new RongIMLib.Discussion(); disInfo.creatorId = entity.adminUserId; disInfo.id = entity.channelId; disInfo.memberIdList = entity.firstTenUserIds; disInfo.name = entity.channelName; disInfo.isOpen = entity.openStatus; return disInfo; case "GroupHashOutput": return entity.result; case "QueryBlackListOutput": return entity.userIds; case "SearchMpOutput": case "PullMpOutput": if (entity.info) { var self = this; Array.forEach(entity.info, function (item) { setTimeout(function () { self.pottingProfile(item); }, 100); }); } return this.publicServiceList; default: return entity; } }; return CallbackMapping; })(); RongIMLib.CallbackMapping = CallbackMapping; var PublishCallback = (function (_super) { __extends(PublishCallback, _super); function PublishCallback(_cb, _timeout) { _super.call(this, _timeout); this._cb = _cb; this._timeout = _timeout; } PublishCallback.prototype.process = function (_status, messageUId, timestamp, _msg, messageId) { this.readTimeOut(); if (_status == 0) { if (_msg) { _msg.setSentStatus = _status; } var isPullFinished = RongIMLib.RongIMClient._memoryStore.isPullFinished; if (isPullFinished) { var userId = RongIMLib.Bridge._client.userId; var stroageProvider = RongIMLib.RongIMClient._storageProvider; stroageProvider.setItem('last_sentTime_' + userId, timestamp); RongIMLib.SyncTimeUtil.set({ messageDirection: RongIMLib.MessageDirection.SEND, sentTime: timestamp }); } this._cb({ messageUId: messageUId, timestamp: timestamp, messageId: messageId }); } else { this._timeout(_status, { messageUId: messageUId, sentTime: timestamp }); } }; PublishCallback.prototype.readTimeOut = function (x) { MessageCallback.prototype.readTimeOut.call(this, x); }; return PublishCallback; })(MessageCallback); RongIMLib.PublishCallback = PublishCallback; var QueryCallback = (function (_super) { __extends(QueryCallback, _super); function QueryCallback(_cb, _timeout) { _super.call(this, _timeout); this._cb = _cb; this._timeout = _timeout; } QueryCallback.prototype.process = function (status, data, serverTime, pbtype) { this.readTimeOut(); if (pbtype && data && status == 0) { try { data = CallbackMapping.getInstance().mapping(RongIMLib.RongIMClient.Protobuf[pbtype].decode(data), pbtype); } catch (e) { this._timeout(RongIMLib.ErrorCode.UNKNOWN); return; } if ("GetUserInfoOutput" == pbtype) { //pb类型为GetUserInfoOutput的话就把data放入userinfo缓存队列 RongIMLib.Client.userInfoMapping[data.userId] = data; } this._cb(data); } else { status > 0 ? this._timeout(status) : this._cb(status); } }; QueryCallback.prototype.readTimeOut = function (x) { MessageCallback.prototype.readTimeOut.call(this, x); }; return QueryCallback; })(MessageCallback); RongIMLib.QueryCallback = QueryCallback; var ConnectAck = (function (_super) { __extends(ConnectAck, _super); function ConnectAck(_cb, _timeout, client) { _super.call(this, _timeout); this._client = client; this._cb = _cb; this._timeout = _timeout; } ConnectAck.prototype.process = function (status, userId, timestamp) { this.readTimeOut(); if (status == 0) { this._client.userId = userId; var self = this; if (!RongIMLib.RongIMClient._memoryStore.depend.isPolling && RongIMLib.RongIMClient._memoryStore.isFirstPingMsg) { RongIMLib.Bridge._client.checkSocket({ onSuccess: function () { if (!RongIMLib.RongIMClient.isNotPullMsg) { self._client.syncTime(undefined, undefined, undefined, true); } }, onError: function () { RongIMLib.RongIMClient._memoryStore.isFirstPingMsg = false; RongIMLib.RongIMClient.getInstance().disconnect(); RongIMLib.RongIMClient.connect(RongIMLib.RongIMClient._memoryStore.token, RongIMLib.RongIMClient._memoryStore.callback); } }); } else { if (!RongIMLib.RongIMClient.isNotPullMsg) { self._client.syncTime(undefined, undefined, undefined, true); } } RongIMLib.Bridge._client.channel.socket.fire("StatusChanged", 0); if (this._client.reconnectObj.onSuccess) { this._client.reconnectObj.onSuccess(userId); delete this._client.reconnectObj.onSuccess; } else { var me = this; me._cb(userId); // setTimeout(function() { me._cb(userId); }, 500); var depend = RongIMLib.RongIMClient._memoryStore.depend; var maxConversationCount = depend.maxConversationCount; var isNotifyConversationList = depend.isNotifyConversationList; isNotifyConversationList && RongIMLib.RongIMClient._dataAccessProvider.getRemoteConversationList({ onSuccess: function (conversationList) { var Conversation = RongIMLib.RongIMClient._dataAccessProvider.Conversation; Conversation._notify(conversationList); }, onError: function (code) { console.log('内部获取列表失败: %d', code); } }, null, maxConversationCount); } RongIMLib.RongIMClient._memoryStore.connectAckTime = timestamp; if (!(new Date().getTime() - timestamp)) { RongIMLib.RongIMClient._memoryStore.deltaTime = 0; } else { RongIMLib.RongIMClient._memoryStore.deltaTime = new Date().getTime() - timestamp; } } else if (status == 6) { RongIMLib.RongIMClient.getInstance().disconnect(); //重定向 连错 CMP var me = this; var _client = me._client; var appId = _client.appId, token = _client.token; new RongIMLib.Navigation().requestNavi(token, appId, function () { _client.clearHeartbeat(); var newClient = new RongIMLib.Client(token, appId); RongIMLib.Bridge._client = newClient; newClient.__init(function () { RongIMLib.Transportations._TransportType == "websocket" && newClient.keepLive(); }); }, me._timeout, false); } else { RongIMLib.Bridge._client.channel.socket.socket._status = status; if (this._client.reconnectObj.onError) { this._client.reconnectObj.onError(status); delete this._client.reconnectObj.onError; } else { this._timeout(status); } } }; ConnectAck.prototype.readTimeOut = function (x) { MessageCallback.prototype.readTimeOut.call(this, x); }; return ConnectAck; })(MessageCallback); RongIMLib.ConnectAck = ConnectAck; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var Navigation = (function () { function Navigation() { } Navigation.clear = function () { var storage = RongIMLib.RongIMClient._storageProvider; storage.removeItem('rc_uid'); storage.removeItem('serverIndex'); storage.removeItem('rongSDK'); }; Navigation.prototype.getNaviSuccess = function (result) { var storage = RongIMLib.RongIMClient._storageProvider; storage.setItem('fullnavi', JSON.stringify(result)); var server = result.server; if (server) { server += ','; } var backupServer = result.backupServer || ''; var tpl = '{server}{backupServer}'; var servers = RongIMLib.RongUtil.tplEngine(tpl, { server: server, backupServer: backupServer }); servers = servers.split(','); storage.setItem('servers', JSON.stringify(servers)); var token = RongIMLib.RongIMClient._memoryStore.token; var uid = RongIMLib.InnerUtil.getUId(token); storage.setItem('rc_uid', uid); var userId = result.userId; storage.setItem('current_user', userId); if (result.voipCallInfo) { var callInfo = JSON.parse(result.voipCallInfo); RongIMLib.RongIMClient._memoryStore.voipStategy = callInfo.strategy; storage.setItem("voipStrategy", callInfo.strategy); } //替换本地存储的导航信息 var openMp = result.openMp; storage.setItem('openMp' + uid, openMp); RongIMLib.RongIMClient._memoryStore.depend.openMp = openMp; }; ; Navigation.prototype.connect = function (appId, token, callback) { var oldAppId = RongIMLib.RongIMClient._storageProvider.getItem("appId"); //如果appid和本地存储的不一样,清空所有本地存储数据 if (oldAppId && oldAppId != appId) { RongIMLib.RongIMClient._storageProvider.clearItem(); RongIMLib.RongIMClient._storageProvider.setItem("appId", appId); } if (!oldAppId) { RongIMLib.RongIMClient._storageProvider.setItem("appId", appId); } var client = new RongIMLib.Client(token, appId); this.requestNavi(token, appId, function () { client.connect(callback); }, callback.onError, true); return client; }; Navigation.prototype.requestNavi = function (token, appId, _onsuccess, _onerror, unignore) { if (unignore) { //根据token生成MD5截取8-16下标的数据与本地存储的导航信息进行比对 //如果信息和上次的通道类型都一样,不执行navi请求,用本地存储的导航信息连接服务器 var uId = md5(token).slice(8, 16); var storage = RongIMLib.RongIMClient._storageProvider; var transportType = storage.getItem("rongSDK"); var isSameType = (RongIMLib.Transportations._TransportType == transportType); var _old = storage.getItem('rc_uid'); var isSameUser = (_old == uId); var servers = storage.getItem('servers'); var hasServers = (typeof servers == 'string'); if (isSameUser && isSameType && hasServers && RongIMLib.RongUtil.hasValidWsUrl(servers)) { RongIMLib.RongIMClient._memoryStore.voipStategy = storage.getItem("voipStrategy"); var openMp = storage.getItem('openMp' + uId); RongIMLib.RongIMClient._memoryStore.depend.openMp = openMp; _onsuccess(); return; } } Navigation.clear(); RongIMLib.RongIMClient.invalidWsUrls = []; var context = this; var StatusEvent = RongIMLib.Channel._ConnectionStatusListener; var depend = RongIMLib.RongIMClient._memoryStore.depend; var navigaters = depend.navigaters; var naviTimeout = depend.naviTimeout; var maxNaviRetry = depend.maxNaviRetry; var isNaviJSONP = depend.isNaviJSONP; var isSupportRequestHeaders = RongIMLib.RongUtil.isSupportRequestHeaders(); var isRequestJSONP = !isSupportRequestHeaders || isNaviJSONP; var requestFunc = isRequestJSONP ? context.requestJSONP : context.request; var timer = new RongIMLib.Timer({ timeout: naviTimeout }); var internalRetry = 1; var isRange = function () { return internalRetry >= maxNaviRetry; }; var indexTools = new RongIMLib.IndexTools({ items: navigaters, onwheel: function () { internalRetry += 1; } }); var consume = function () { if (isRange()) { _onerror(RongIMLib.ConnectionStatus.RESPONSE_NAVI_ERROR); return; } var index = indexTools.get(); var navi = navigaters[index]; indexTools.add(); var success = function (result) { timer.pause(); StatusEvent.onChanged(RongIMLib.ConnectionStatus.RESPONSE_NAVI); var code = result.code; if (RongIMLib.RongUtil.isEqual(code, 200)) { context.getNaviSuccess(result); _onsuccess(); } if (RongIMLib.RongUtil.isEqual(code, 401)) { _onerror(RongIMLib.ConnectionState.TOKEN_INCORRECT); } if (RongIMLib.RongUtil.isEqual(code, 403)) { StatusEvent.onChanged(RongIMLib.ConnectionStatus.APPKEY_IS_FAKE); } }; var error = function (status) { if (RongIMLib.RongUtil.isEqual(status, 0)) { return; } timer.pause(); StatusEvent.onChanged(RongIMLib.ConnectionStatus.RESPONSE_NAVI_ERROR); consume(); }; StatusEvent.onChanged(RongIMLib.ConnectionStatus.REQUEST_NAVI); var xhr = requestFunc.call(context, navi, appId, token, success, error); timer.resume(function () { StatusEvent.onChanged(RongIMLib.ConnectionStatus.RESPONSE_NAVI_TIMEOUT); xhr.abort(); consume(); }); }; consume(); }; Navigation.prototype.getPath = function (navi, appId, token, callbackName) { var depend = RongIMLib.RongIMClient._memoryStore.depend; var path = (depend.isPolling ? 'cometnavi' : 'navi'); token = encodeURIComponent(token); var sdkver = RongIMLib.RongIMClient.sdkver; var random = RongIMLib.RongUtil.getTimestamp(); var tpl = '{navi}/{path}.js?appId={appId}&token={token}&callBack={callback}&v={sdkver}&r={random}'; var url = RongIMLib.RongUtil.tplEngine(tpl, { navi: navi, path: path, appId: appId, token: token, sdkver: sdkver, random: random, callback: callbackName }); return url; }; Navigation.prototype.request = function (navi, appId, token, success, error) { var url = this.getPath(navi, appId, token, 'getServerEndpoint'); return RongIMLib.RongUtil.request({ url: url, success: function (result) { result = result.replace('getServerEndpoint(', '').replace(');', ''); // 兼容私有云无分号 var lastIndex = result.lastIndexOf(')'); var maxIndex = result.length - 1; if (lastIndex == maxIndex) { result = result.substr(0, lastIndex); } success(JSON.parse(result)); }, error: function (status, result) { if (status == 401 || status == 403) { success(JSON.parse(result)); } else { error(status); } } }); }; Navigation.prototype.requestJSONP = function (navi, appId, token, success, error) { var callbackName = 'getServerEndpoint'; window.getServerEndpoint = function (result) { var code = result.code; if (code !== 200) { return error(RongIMLib.ConnectionState.TOKEN_INCORRECT); } success(result); }; var url = this.getPath(navi, appId, token, callbackName); var xss = document.createElement('script'); xss.src = url; document.body.appendChild(xss); xss.onerror = function () { error(RongIMLib.ConnectionState.TOKEN_INCORRECT); }; }; Navigation.Endpoint = new Object; return Navigation; })(); RongIMLib.Navigation = Navigation; })(RongIMLib || (RongIMLib = {})); // TODO: 统一变量、方法等命名规范 var RongIMLib; (function (RongIMLib) { /** * 消息基类 */ var BaseMessage = (function () { function BaseMessage(arg) { this._name = "BaseMessage"; this.lengthSize = 0; if (arg instanceof RongIMLib.Header) { this._header = arg; } else { this._header = new RongIMLib.Header(arg, false, RongIMLib.Qos.AT_MOST_ONCE, false); } } BaseMessage.prototype.read = function (In, length) { this.readMessage(In, length); }; BaseMessage.prototype.write = function (Out) { var binaryHelper = new RongIMLib.BinaryHelper(); var out = binaryHelper.convertStream(Out); this._headerCode = this.getHeaderFlag(); out.write(this._headerCode); this.writeMessage(out); return out; }; BaseMessage.prototype.getHeaderFlag = function () { return this._header.encode(); }; BaseMessage.prototype.getLengthSize = function () { return this.lengthSize; }; BaseMessage.prototype.toBytes = function () { return this.write([]).getBytesArray(); }; BaseMessage.prototype.isRetained = function () { return this._header.retain; }; BaseMessage.prototype.setRetained = function (retain) { this._header.retain = retain; }; BaseMessage.prototype.setQos = function (qos) { this._header.qos = Object.prototype.toString.call(qos) == "[object Object]" ? qos : RongIMLib.Qos[qos]; }; BaseMessage.prototype.setDup = function (dup) { this._header.dup = dup; }; BaseMessage.prototype.isDup = function () { return this._header.dup; }; BaseMessage.prototype.getType = function () { return this._header.type; }; BaseMessage.prototype.getQos = function () { return this._header.qos; }; BaseMessage.prototype.messageLength = function () { return 0; }; BaseMessage.prototype.writeMessage = function (out) { }; BaseMessage.prototype.readMessage = function (In, length) { }; BaseMessage.prototype.init = function (args) { var valName, nana, me = this; for (nana in args) { if (!args.hasOwnProperty(nana)) { continue; } valName = nana.replace(/^\w/, function (x) { var tt = x.charCodeAt(0); return "set" + (tt >= 0x61 ? String.fromCharCode(tt & ~32) : x); }); if (valName in me) { if (nana == "status") { me[valName](disconnectStatus[args[nana]] ? disconnectStatus[args[nana]] : args[nana]); } else { me[valName](args[nana]); } } } }; return BaseMessage; })(); RongIMLib.BaseMessage = BaseMessage; /** *连接消息类型 */ var ConnectMessage = (function (_super) { __extends(ConnectMessage, _super); function ConnectMessage(header) { _super.call(this, arguments.length == 0 || arguments.length == 3 ? RongIMLib.Type.CONNECT : arguments[0]); this._name = "ConnectMessage"; this.CONNECT_HEADER_SIZE = 12; this.protocolId = "RCloud"; this.binaryHelper = new RongIMLib.BinaryHelper(); this.protocolVersion = 3; switch (arguments.length) { case 0: case 1: case 3: if (!arguments[0] || arguments[0].length > 64) { throw new Error("ConnectMessage:Client Id cannot be null and must be at most 64 characters long: " + arguments[0]); } this.clientId = arguments[0]; this.cleanSession = arguments[1]; this.keepAlive = arguments[2]; break; } } ConnectMessage.prototype.messageLength = function () { var payloadSize = this.binaryHelper.toMQttString(this.clientId).length; payloadSize += this.binaryHelper.toMQttString(this.willTopic).length; payloadSize += this.binaryHelper.toMQttString(this.will).length; payloadSize += this.binaryHelper.toMQttString(this.appId).length; payloadSize += this.binaryHelper.toMQttString(this.token).length; return payloadSize + this.CONNECT_HEADER_SIZE; }; ConnectMessage.prototype.readMessage = function (stream) { this.protocolId = stream.readUTF(); this.protocolVersion = stream.readByte(); var cFlags = stream.readByte(); this.hasAppId = (cFlags & 128) > 0; this.hasToken = (cFlags & 64) > 0; this.retainWill = (cFlags & 32) > 0; this.willQos = cFlags >> 3 & 3; this.hasWill = (cFlags & 4) > 0; this.cleanSession = (cFlags & 32) > 0; this.keepAlive = stream.read() * 256 + stream.read(); this.clientId = stream.readUTF(); if (this.hasWill) { this.willTopic = stream.readUTF(); this.will = stream.readUTF(); } if (this.hasAppId) { try { this.appId = stream.readUTF(); } catch (ex) { throw new Error(ex); } } if (this.hasToken) { try { this.token = stream.readUTF(); } catch (ex) { throw new Error(ex); } } return stream; }; ConnectMessage.prototype.writeMessage = function (out) { var stream = this.binaryHelper.convertStream(out); stream.writeUTF(this.protocolId); stream.write(this.protocolVersion); var flags = this.cleanSession ? 2 : 0; flags |= this.hasWill ? 4 : 0; flags |= this.willQos ? this.willQos >> 3 : 0; flags |= this.retainWill ? 32 : 0; flags |= this.hasToken ? 64 : 0; flags |= this.hasAppId ? 128 : 0; stream.write(flags); stream.writeChar(this.keepAlive); stream.writeUTF(this.clientId); if (this.hasWill) { stream.writeUTF(this.willTopic); stream.writeUTF(this.will); } if (this.hasAppId) { stream.writeUTF(this.appId); } if (this.hasToken) { stream.writeUTF(this.token); } return stream; }; return ConnectMessage; })(BaseMessage); RongIMLib.ConnectMessage = ConnectMessage; /** *连接应答类型 */ var ConnAckMessage = (function (_super) { __extends(ConnAckMessage, _super); function ConnAckMessage(header) { _super.call(this, arguments.length == 0 ? RongIMLib.Type.CONNACK : arguments.length == 1 ? arguments[0] instanceof RongIMLib.Header ? arguments[0] : RongIMLib.Type.CONNACK : null); this._name = "ConnAckMessage"; this.MESSAGE_LENGTH = 2; this.binaryHelper = new RongIMLib.BinaryHelper(); var me = this; switch (arguments.length) { case 0: case 1: if (!(arguments[0] instanceof RongIMLib.Header)) { if (arguments[0] in RongIMLib.ConnectionState) { if (arguments[0] == null) { throw new Error("ConnAckMessage:The status of ConnAskMessage can't be null"); } me.setStatus(arguments[0]); } } break; } } ; ConnAckMessage.prototype.messageLength = function () { var length = this.MESSAGE_LENGTH; if (this.userId) { length += this.binaryHelper.toMQttString(this.userId).length; } return length; }; ; ConnAckMessage.prototype.readMessage = function (_in, msglength) { _in.read(); var result = +_in.read(); if (result >= 0 && result <= 12) { this.setStatus(result); } else { throw new Error("Unsupported CONNACK code:" + result); } if (msglength > this.MESSAGE_LENGTH) { this.setUserId(_in.readUTF()); var sessionId = _in.readUTF(); var timestamp = _in.readLong(); this.setTimestamp(timestamp); } }; ; ConnAckMessage.prototype.writeMessage = function (out) { var stream = this.binaryHelper.convertStream(out); stream.write(128); switch (+status) { case 0: case 1: case 2: case 5: case 6: stream.write(+status); break; case 3: case 4: stream.write(3); break; default: throw new Error("Unsupported CONNACK code:" + status); } if (this.userId) { stream.writeUTF(this.userId); } return stream; }; ; ConnAckMessage.prototype.setStatus = function (x) { this.status = x; }; ; ConnAckMessage.prototype.setUserId = function (_userId) { this.userId = _userId; }; ; ConnAckMessage.prototype.getStatus = function () { return this.status; }; ; ConnAckMessage.prototype.getUserId = function () { return this.userId; }; ; ConnAckMessage.prototype.setTimestamp = function (x) { this.timestrap = x; }; ; ConnAckMessage.prototype.getTimestamp = function () { return this.timestrap; }; return ConnAckMessage; })(BaseMessage); RongIMLib.ConnAckMessage = ConnAckMessage; /** *断开消息类型 */ var DisconnectMessage = (function (_super) { __extends(DisconnectMessage, _super); function DisconnectMessage(header) { _super.call(this, header instanceof RongIMLib.Header ? header : RongIMLib.Type.DISCONNECT); this._name = "DisconnectMessage"; this.MESSAGE_LENGTH = 2; this.binaryHelper = new RongIMLib.BinaryHelper(); if (!(header instanceof RongIMLib.Header)) { if (header in RongIMLib.ConnectionStatus) { this.status = header; } } } DisconnectMessage.prototype.messageLength = function () { return this.MESSAGE_LENGTH; }; DisconnectMessage.prototype.readMessage = function (_in) { _in.read(); var result = +_in.read(); if (result >= 0 && result <= 5) { this.setStatus(disconnectStatus[result] ? disconnectStatus[result] : result); } else { throw new Error("Unsupported CONNACK code:" + result); } }; DisconnectMessage.prototype.writeMessage = function (Out) { var out = this.binaryHelper.convertStream(Out); out.write(0); if (+status >= 1 && +status <= 3) { out.write((+status) - 1); } else { throw new Error("Unsupported CONNACK code:" + status); } }; DisconnectMessage.prototype.setStatus = function (x) { this.status = x; }; ; DisconnectMessage.prototype.getStatus = function () { return this.status; }; ; return DisconnectMessage; })(BaseMessage); RongIMLib.DisconnectMessage = DisconnectMessage; /** *请求消息信令 */ var PingReqMessage = (function (_super) { __extends(PingReqMessage, _super); function PingReqMessage(header) { _super.call(this, (header && header instanceof RongIMLib.Header) ? header : RongIMLib.Type.PINGREQ); this._name = "PingReqMessage"; } return PingReqMessage; })(BaseMessage); RongIMLib.PingReqMessage = PingReqMessage; /** *响应消息信令 */ var PingRespMessage = (function (_super) { __extends(PingRespMessage, _super); function PingRespMessage(header) { _super.call(this, (header && header instanceof RongIMLib.Header) ? header : RongIMLib.Type.PINGRESP); this._name = "PingRespMessage"; } return PingRespMessage; })(BaseMessage); RongIMLib.PingRespMessage = PingRespMessage; /** *封装MesssageId */ var RetryableMessage = (function (_super) { __extends(RetryableMessage, _super); function RetryableMessage(argu) { _super.call(this, argu); this._name = "RetryableMessage"; this.binaryHelper = new RongIMLib.BinaryHelper(); } RetryableMessage.prototype.messageLength = function () { return 2; }; RetryableMessage.prototype.writeMessage = function (Out) { var out = this.binaryHelper.convertStream(Out), Id = this.getMessageId(), lsb = Id & 255, msb = (Id & 65280) >> 8; out.write(msb); out.write(lsb); return out; }; RetryableMessage.prototype.readMessage = function (_in, msgLength) { var msgId = _in.read() * 256 + _in.read(); this.setMessageId(parseInt(msgId, 10)); }; RetryableMessage.prototype.setMessageId = function (_messageId) { this.messageId = _messageId; }; RetryableMessage.prototype.getMessageId = function () { return this.messageId; }; return RetryableMessage; })(BaseMessage); RongIMLib.RetryableMessage = RetryableMessage; /** *发送消息应答(双向) *qos为1必须给出应答(所有消息类型一样) */ var PubAckMessage = (function (_super) { __extends(PubAckMessage, _super); function PubAckMessage(header) { _super.call(this, (header instanceof RongIMLib.Header) ? header : RongIMLib.Type.PUBACK); this.msgLen = 2; this.date = 0; this.millisecond = 0; this.timestamp = 0; this.binaryHelper = new RongIMLib.BinaryHelper(); this._name = "PubAckMessage"; if (!(header instanceof RongIMLib.Header)) { _super.prototype.setMessageId.call(this, header); } } PubAckMessage.prototype.messageLength = function () { return this.msgLen; }; PubAckMessage.prototype.writeMessage = function (Out) { var out = this.binaryHelper.convertStream(Out); RetryableMessage.prototype.writeMessage.call(this, out); }; PubAckMessage.prototype.readMessage = function (_in, msgLength) { RetryableMessage.prototype.readMessage.call(this, _in); this.date = _in.readInt(); this.status = _in.read() * 256 + _in.read(); this.millisecond = _in.read() * 256 + _in.read(); this.timestamp = this.date * 1000 + this.millisecond; this.messageUId = _in.readUTF(); }; PubAckMessage.prototype.setStatus = function (x) { this.status = x; }; PubAckMessage.prototype.setTimestamp = function (timestamp) { this.timestamp = timestamp; }; PubAckMessage.prototype.setMessageUId = function (messageUId) { this.messageUId = messageUId; }; PubAckMessage.prototype.getStatus = function () { return this.status; }; PubAckMessage.prototype.getDate = function () { return this.date; }; PubAckMessage.prototype.getTimestamp = function () { return this.timestamp; }; PubAckMessage.prototype.getMessageUId = function () { return this.messageUId; }; return PubAckMessage; })(RetryableMessage); RongIMLib.PubAckMessage = PubAckMessage; /** *发布消息 */ var PublishMessage = (function (_super) { __extends(PublishMessage, _super); function PublishMessage(header, two, three) { _super.call(this, (arguments.length == 1 && header instanceof RongIMLib.Header) ? header : arguments.length == 3 ? RongIMLib.Type.PUBLISH : 0); this._name = "PublishMessage"; this.binaryHelper = new RongIMLib.BinaryHelper(); this.syncMsg = false; if (arguments.length == 3) { this.topic = header; this.targetId = three; this.data = typeof two == "string" ? this.binaryHelper.toMQttString(two) : two; } } PublishMessage.prototype.messageLength = function () { var length = 10; length += this.binaryHelper.toMQttString(this.topic).length; length += this.binaryHelper.toMQttString(this.targetId).length; length += this.data.length; return length; }; PublishMessage.prototype.writeMessage = function (Out) { var out = this.binaryHelper.convertStream(Out); out.writeUTF(this.topic); out.writeUTF(this.targetId); RetryableMessage.prototype.writeMessage.apply(this, arguments); out.write(this.data); }; ; PublishMessage.prototype.readMessage = function (_in, msgLength) { var pos = 6; this.date = _in.readInt(); this.topic = _in.readUTF(); pos += this.binaryHelper.toMQttString(this.topic).length; this.targetId = _in.readUTF(); pos += this.binaryHelper.toMQttString(this.targetId).length; RetryableMessage.prototype.readMessage.apply(this, arguments); this.data = new Array(msgLength - pos); this.data = _in.read(this.data); }; ; PublishMessage.prototype.setTopic = function (x) { this.topic = x; }; PublishMessage.prototype.setData = function (x) { this.data = x; }; PublishMessage.prototype.setTargetId = function (x) { this.targetId = x; }; PublishMessage.prototype.setDate = function (x) { this.date = x; }; PublishMessage.prototype.setSyncMsg = function (x) { this.syncMsg = x; }; //是否是其他端同步过来的消息 PublishMessage.prototype.getSyncMsg = function () { return this.syncMsg; }; PublishMessage.prototype.getTopic = function () { return this.topic; }; PublishMessage.prototype.getData = function () { return this.data; }; PublishMessage.prototype.getTargetId = function () { return this.targetId; }; PublishMessage.prototype.getDate = function () { return this.date; }; return PublishMessage; })(RetryableMessage); RongIMLib.PublishMessage = PublishMessage; /** *请求查询 */ var QueryMessage = (function (_super) { __extends(QueryMessage, _super); function QueryMessage(header, two, three) { _super.call(this, header instanceof RongIMLib.Header ? header : arguments.length == 3 ? RongIMLib.Type.QUERY : null); this.binaryHelper = new RongIMLib.BinaryHelper(); this._name = "QueryMessage"; if (arguments.length == 3) { this.data = typeof two == "string" ? this.binaryHelper.toMQttString(two) : two; this.topic = header; this.targetId = three; } } QueryMessage.prototype.messageLength = function () { var length = 0; length += this.binaryHelper.toMQttString(this.topic).length; length += this.binaryHelper.toMQttString(this.targetId).length; length += 2; length += this.data.length; return length; }; QueryMessage.prototype.writeMessage = function (Out) { var out = this.binaryHelper.convertStream(Out); out.writeUTF(this.topic); out.writeUTF(this.targetId); RetryableMessage.prototype.writeMessage.call(this, out); out.write(this.data); }; QueryMessage.prototype.readMessage = function (_in, msgLength) { var pos = 0; this.topic = _in.readUTF(); this.targetId = _in.readUTF(); pos += this.binaryHelper.toMQttString(this.topic).length; pos += this.binaryHelper.toMQttString(this.targetId).length; this.readMessage.apply(this, arguments); pos += 2; this.data = new Array(msgLength - pos); _in.read(this.data); }; QueryMessage.prototype.setTopic = function (x) { this.topic = x; }; QueryMessage.prototype.setData = function (x) { this.data = x; }; QueryMessage.prototype.setTargetId = function (x) { this.targetId = x; }; QueryMessage.prototype.getTopic = function () { return this.topic; }; QueryMessage.prototype.getData = function () { return this.data; }; QueryMessage.prototype.getTargetId = function () { return this.targetId; }; return QueryMessage; })(RetryableMessage); RongIMLib.QueryMessage = QueryMessage; /** *请求查询确认 */ var QueryConMessage = (function (_super) { __extends(QueryConMessage, _super); function QueryConMessage(messageId) { _super.call(this, (messageId instanceof RongIMLib.Header) ? messageId : RongIMLib.Type.QUERYCON); this._name = "QueryConMessage"; if (!(messageId instanceof RongIMLib.Header)) { _super.prototype.setMessageId.call(this, messageId); } } return QueryConMessage; })(RetryableMessage); RongIMLib.QueryConMessage = QueryConMessage; /** *请求查询应答 */ var QueryAckMessage = (function (_super) { __extends(QueryAckMessage, _super); function QueryAckMessage(header) { _super.call(this, header); this._name = "QueryAckMessage"; this.binaryHelper = new RongIMLib.BinaryHelper(); } QueryAckMessage.prototype.readMessage = function (In, msgLength) { RetryableMessage.prototype.readMessage.call(this, In); this.date = In.readInt(); this.setStatus(In.read() * 256 + In.read()); if (msgLength > 0) { this.data = new Array(msgLength - 8); this.data = In.read(this.data); } }; QueryAckMessage.prototype.getData = function () { return this.data; }; QueryAckMessage.prototype.getStatus = function () { return this.status; }; QueryAckMessage.prototype.getDate = function () { return this.date; }; QueryAckMessage.prototype.setDate = function (x) { this.date = x; }; QueryAckMessage.prototype.setStatus = function (x) { this.status = x; }; QueryAckMessage.prototype.setData = function (x) { this.data = x; }; return QueryAckMessage; })(RetryableMessage); RongIMLib.QueryAckMessage = QueryAckMessage; })(RongIMLib || (RongIMLib = {})); /// var RongIMLib; (function (RongIMLib) { /** * 把消息对象写入流中 * 发送消息时用到 */ var MessageOutputStream = (function () { function MessageOutputStream(_out) { var binaryHelper = new RongIMLib.BinaryHelper(); this.out = binaryHelper.convertStream(_out); } MessageOutputStream.prototype.writeMessage = function (msg) { if (msg instanceof RongIMLib.BaseMessage) { msg.write(this.out); } }; return MessageOutputStream; })(); RongIMLib.MessageOutputStream = MessageOutputStream; /** * 流转换为消息对象 * 服务器返回消息时用到 */ var MessageInputStream = (function () { function MessageInputStream(In, isPolling) { if (!isPolling) { var _in = new RongIMLib.BinaryHelper().convertStream(In); this.flags = _in.readByte(); this._in = _in; } else { this.flags = In["headerCode"]; } this.header = new RongIMLib.Header(this.flags); this.isPolling = isPolling; this.In = In; } MessageInputStream.prototype.readMessage = function () { switch (this.header.getType()) { case 1: this.msg = new RongIMLib.ConnectMessage(this.header); break; case 2: this.msg = new RongIMLib.ConnAckMessage(this.header); break; case 3: this.msg = new RongIMLib.PublishMessage(this.header); this.msg.setSyncMsg(this.header.getSyncMsg()); break; case 4: this.msg = new RongIMLib.PubAckMessage(this.header); break; case 5: this.msg = new RongIMLib.QueryMessage(this.header); break; case 6: this.msg = new RongIMLib.QueryAckMessage(this.header); break; case 7: this.msg = new RongIMLib.QueryConMessage(this.header); break; case 9: case 11: case 13: this.msg = new RongIMLib.PingRespMessage(this.header); break; case 8: case 10: case 12: this.msg = new RongIMLib.PingReqMessage(this.header); break; case 14: this.msg = new RongIMLib.DisconnectMessage(this.header); break; default: throw new Error("No support for deserializing " + this.header.getType() + " messages"); } if (this.isPolling) { this.msg.init(this.In); } else { this.msg.read(this._in, this.In.length - 1); } return this.msg; }; return MessageInputStream; })(); RongIMLib.MessageInputStream = MessageInputStream; var Header = (function () { function Header(_type, _retain, _qos, _dup) { this.retain = false; this.qos = RongIMLib.Qos.AT_LEAST_ONCE; this.dup = false; this.syncMsg = false; if (_type && +_type == _type && arguments.length == 1) { this.retain = (_type & 1) > 0; this.qos = (_type & 6) >> 1; this.dup = (_type & 8) > 0; this.type = (_type >> 4) & 15; this.syncMsg = (_type & 8) == 8; } else { this.type = _type; this.retain = _retain; this.qos = _qos; this.dup = _dup; } } Header.prototype.getSyncMsg = function () { return this.syncMsg; }; Header.prototype.getType = function () { return this.type; }; Header.prototype.encode = function () { var me = this; switch (this.qos) { case RongIMLib.Qos[0]: me.qos = RongIMLib.Qos.AT_MOST_ONCE; break; case RongIMLib.Qos[1]: me.qos = RongIMLib.Qos.AT_LEAST_ONCE; break; case RongIMLib.Qos[2]: me.qos = RongIMLib.Qos.EXACTLY_ONCE; break; case RongIMLib.Qos[3]: me.qos = RongIMLib.Qos.DEFAULT; break; } var _byte = (this.type << 4); _byte |= this.retain ? 1 : 0; _byte |= this.qos << 1; _byte |= this.dup ? 8 : 0; return _byte; }; Header.prototype.toString = function () { return "Header [type=" + this.type + ",retain=" + this.retain + ",qos=" + this.qos + ",dup=" + this.dup + "]"; }; return Header; })(); RongIMLib.Header = Header; /** * 二进制帮助对象 */ var BinaryHelper = (function () { function BinaryHelper() { } BinaryHelper.prototype.writeUTF = function (str, isGetBytes) { var back = [], byteSize = 0; for (var i = 0, len = str.length; i < len; i++) { var code = str.charCodeAt(i); if (code >= 0 && code <= 127) { byteSize += 1; back.push(code); } else if (code >= 128 && code <= 2047) { byteSize += 2; back.push((192 | (31 & (code >> 6)))); back.push((128 | (63 & code))); } else if (code >= 2048 && code <= 65535) { byteSize += 3; back.push((224 | (15 & (code >> 12)))); back.push((128 | (63 & (code >> 6)))); back.push((128 | (63 & code))); } } for (var i = 0, len = back.length; i < len; i++) { if (back[i] > 255) { back[i] &= 255; } } if (isGetBytes) { return back; } if (byteSize <= 255) { return [0, byteSize].concat(back); } else { return [byteSize >> 8, byteSize & 255].concat(back); } }; BinaryHelper.prototype.readUTF = function (arr) { if (Object.prototype.toString.call(arr) == "[object String]") { return arr; } var UTF = "", _arr = arr; for (var i = 0, len = _arr.length; i < len; i++) { if (_arr[i] < 0) { _arr[i] += 256; } ; var one = _arr[i].toString(2), v = one.match(/^1+?(?=0)/); if (v && one.length == 8) { var bytesLength = v[0].length, // store = _arr[i].toString(2).slice(7 - bytesLength); store = ''; for (var st = 0; st < bytesLength; st++) { store += _arr[st + i].toString(2).slice(2); } UTF += String.fromCharCode(parseInt(store, 2)); i += bytesLength - 1; } else { UTF += String.fromCharCode(_arr[i]); } } return UTF; }; /** * [convertStream 将参数x转化为RongIMStream对象] * @param {any} x [参数] */ BinaryHelper.prototype.convertStream = function (x) { if (x instanceof RongIMStream) { return x; } else { return new RongIMStream(x); } }; BinaryHelper.prototype.toMQttString = function (str) { return this.writeUTF(str); }; return BinaryHelper; })(); RongIMLib.BinaryHelper = BinaryHelper; var RongIMStream = (function () { function RongIMStream(arr) { //当前流执行的起始位置 this.position = 0; //当前流写入的多少字节 this.writen = 0; this.poolLen = 0; this.binaryHelper = new BinaryHelper(); this.pool = arr; this.poolLen = arr.length; } RongIMStream.prototype.check = function () { return this.position >= this.pool.length; }; RongIMStream.prototype.readInt = function () { if (this.check()) { return -1; } var end = ""; for (var i = 0; i < 4; i++) { var t = this.pool[this.position++].toString(16); if (t.length == 1) { t = "0" + t; } end += t.toString(16); } return parseInt(end, 16); }; RongIMStream.prototype.readLong = function () { if (this.check()) { return -1; } var end = ""; for (var i = 0; i < 8; i++) { var t = this.pool[this.position++].toString(16); if (t.length == 1) { t = "0" + t; } end += t; } return parseInt(end, 16); }; RongIMStream.prototype.readTimestamp = function () { if (this.check()) { return -1; } var end = ""; for (var i = 0; i < 8; i++) { end += this.pool[this.position++].toString(16); } end = end.substring(2, 8); return parseInt(end, 16); }; RongIMStream.prototype.readUTF = function () { if (this.check()) { return -1; } var big = (this.readByte() << 8) | this.readByte(); return this.binaryHelper.readUTF(this.pool.subarray(this.position, this.position += big)); }; RongIMStream.prototype.readByte = function () { if (this.check()) { return -1; } var val = this.pool[this.position++]; if (val > 255) { val &= 255; } return val; }; RongIMStream.prototype.read = function (bytesArray) { if (bytesArray) { return this.pool.subarray(this.position, this.poolLen); } else { return this.readByte(); } }; RongIMStream.prototype.write = function (_byte) { var b = _byte; if (Object.prototype.toString.call(b).toLowerCase() == "[object array]") { [].push.apply(this.pool, b); } else { if (+b == b) { if (b > 255) { b &= 255; } this.pool.push(b); this.writen++; } } return b; }; RongIMStream.prototype.writeChar = function (v) { if (+v != v) { throw new Error("writeChar:arguments type is error"); } this.write(v >> 8 & 255); this.write(v & 255); this.writen += 2; }; RongIMStream.prototype.writeUTF = function (str) { var val = this.binaryHelper.writeUTF(str); [].push.apply(this.pool, val); this.writen += val.length; }; RongIMStream.prototype.toComplements = function () { var _tPool = this.pool; for (var i = 0; i < this.poolLen; i++) { if (_tPool[i] > 128) { _tPool[i] -= 256; } } return _tPool; }; RongIMStream.prototype.getBytesArray = function (isCom) { if (isCom) { return this.toComplements(); } return this.pool; }; return RongIMStream; })(); RongIMLib.RongIMStream = RongIMStream; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var SocketTransportation = (function () { /** * [constructor] * @param {string} url [连接地址:包含token、version] */ function SocketTransportation(_socket) { //连接状态 true:已连接 false:未连接 this.connected = false; //是否关闭: true:已关闭 false:未关闭 this.isClose = false; //存放消息队列的临时变量 this.queue = []; this.empty = new Function; this._socket = _socket; return this; } /** * [createTransport 创建WebScoket对象] */ SocketTransportation.prototype.createTransport = function (url, method) { if (!url) { throw new Error("URL can't be empty"); } ; this.url = url; var depend = RongIMLib.RongIMClient._memoryStore.depend; var wsScheme = depend.wsScheme; var tpl = '{wsScheme}{url}'; url = RongIMLib.RongUtil.tplEngine(tpl, { wsScheme: wsScheme, url: url }); this.socket = new WebSocket(url); this.socket.binaryType = "arraybuffer"; this.addEvent(); return this.socket; }; /** * [send 传送消息流] * @param {ArrayBuffer} data [二进制消息流] */ SocketTransportation.prototype.send = function (data) { if (!this.connected && !this.isClose) { //当通道不可用时,加入消息队列 this.queue.push(data); return; } if (this.isClose) { this._socket.fire("StatusChanged", RongIMLib.ConnectionStatus.CONNECTION_CLOSED); return; } var stream = new RongIMLib.RongIMStream([]), msg = new RongIMLib.MessageOutputStream(stream); msg.writeMessage(data); var val = stream.getBytesArray(true); var binary = new Int8Array(val); this.socket.send(binary.buffer); return this; }; /** * [onData 通道返回数据时调用的方法,用来想上层传递服务器返回的二进制消息流] * @param {ArrayBuffer} data [二进制消息流] */ SocketTransportation.prototype.onData = function (data) { if (RongIMLib.MessageUtil.isArray(data)) { this._socket.onMessage(new RongIMLib.MessageInputStream(data).readMessage()); } else { this._socket.onMessage(new RongIMLib.MessageInputStream(RongIMLib.MessageUtil.ArrayFormInput(data)).readMessage()); } return ""; }; /** * [onClose 通道关闭时触发的方法] */ SocketTransportation.prototype.onClose = function (ev) { var me = this; me.isClose = true; me.socket = this.empty; RongIMLib.Bridge._client.clearHeartbeat(); if (ev.code == 1006 && !this._status) { var currentTime = new Date().getTime(); if (currentTime - me.connectedTime <= SocketTransportation.MinConnectTime) { var host = RongIMLib.RongUtil.getUrlHost(me.url); RongIMLib.RongIMClient.invalidWsUrls.push(host); } me._socket.fire("StatusChanged", RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE); } else { me._status = 0; } }; /** * [onError 通道报错时触发的方法] * @param {any} error [抛出异常] */ SocketTransportation.prototype.onError = function (error) { this._socket.fire("StatusChanged", RongIMLib.ConnectionStatus.WEBSOCKET_ERROR); throw new Error(error); }; /** * [addEvent 为通道绑定事件] */ SocketTransportation.prototype.addEvent = function () { var self = this; self.socket.onopen = function () { self.connected = true; self.isClose = false; //通道可以用后,调用发送队列方法,把所有等得发送的消息发出 self.doQueue(); self._socket.fire("connect"); self.connectedTime = new Date().getTime(); }; self.socket.onmessage = function (ev) { //判断数据是不是字符串,如果是字符串那么就是flash传过来的。 if (typeof ev.data == "string") { self.onData(ev.data.split(",")); } else { self.onData(ev.data); } }; self.socket.onerror = function (ev) { self.onError(ev); }; self.socket.onclose = function (ev) { self.onClose(ev); }; }; /** * [doQueue 消息队列,把队列中消息发出] */ SocketTransportation.prototype.doQueue = function () { var self = this; for (var i = 0, len = self.queue.length; i < len; i++) { self.send(self.queue[i]); } }; /** * [disconnect 断开连接] */ SocketTransportation.prototype.disconnect = function (status) { var me = this; if (me.socket.readyState) { me.isClose = true; if (status) { me._status = status; } me.socket.close(); } }; /** * [reconnect 重新连接] */ SocketTransportation.prototype.reconnect = function () { this.disconnect(); this.createTransport(this.url); }; SocketTransportation.prototype.close = function () { this.socket.close(); }; // 最短链接时长(若 5000ms 内, ws 自动断开, 此 ws 地址置为不可用) SocketTransportation.MinConnectTime = 5000; return SocketTransportation; })(); RongIMLib.SocketTransportation = SocketTransportation; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var PollingTransportation = (function () { function PollingTransportation(socket) { this.empty = new Function; this.connected = false; this.pid = +new Date + Math.random() + ""; this.queue = []; this.socket = socket; return this; } PollingTransportation.prototype.createTransport = function (url, method) { if (!url) { throw new Error("Url is empty,Please check it!"); } ; this.url = url; var sid = RongIMLib.RongIMClient._storageProvider.getItem("sId" + RongIMLib.Navigation.Endpoint.userId), me = this; if (sid) { setTimeout(function () { me.onSuccess("{\"status\":0,\"userId\":\"" + RongIMLib.Navigation.Endpoint.userId + "\",\"headerCode\":32,\"messageId\":0,\"sessionid\":\"" + sid + "\"}"); me.connected = true; }, 500); return this; } this.getRequest(url, true); return this; }; PollingTransportation.prototype.requestFactory = function (url, method, multipart) { var reqest = this.XmlHttpRequest(); if (multipart) { reqest.multipart = true; } // reqest.timeout = 60000; reqest.open(method || "GET", RongIMLib.RongIMClient._memoryStore.depend.protocol + url); if (method == "POST" && "setRequestHeader" in reqest) { reqest.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=utf-8"); } return reqest; }; PollingTransportation.prototype.getRequest = function (url, isconnect) { var me = this; me.xhr = this.requestFactory(url + "&pid=" + encodeURIComponent(me.pid), "GET"); var timer = new RongIMLib.Timer({ timeout: 45000 }); if ("onload" in me.xhr) { me.xhr.onload = function () { timer.pause(); me.xhr.onload = me.empty; if (this.responseText == "lost params") { me.onError(); } else { me.onSuccess(this.responseText, isconnect); } }; me.xhr.onerror = function () { timer.pause(); me.disconnect(); }; } else { me.xhr.onreadystatechange = function () { timer.pause(); if (me.xhr.readyState == 4) { me.xhr.onreadystatechange = me.empty; if (/^(200|202)$/.test(me.xhr.status)) { me.onSuccess(me.xhr.responseText, isconnect); } else if (/^(400|403)$/.test(me.xhr.status)) { me.onError(); } else { me.disconnect(); } } }; } timer.resume(function () { me.onError(); }); me.xhr.send(); }; /** * [send 发送消息,Method:POST] * queue 为消息队列,待通道可用发送所有等待消息 * @param {string} data [需要传入comet格式数据,此处只负责通讯通道,数据转换在外层处理] */ PollingTransportation.prototype.send = function (data) { var me = this; var _send = me.sendxhr = this.requestFactory(RongIMLib.Navigation.Endpoint.host + "/websocket" + data.url + "&pid=" + encodeURIComponent(me.pid), "POST"); if ("onload" in _send) { _send.onload = function () { _send.onload = me.empty; me.onData(_send.responseText); }; _send.onerror = function () { _send.onerror = me.empty; }; } else { _send.onreadystatechange = function () { if (_send.readyState == 4) { this.onreadystatechange = this.empty; if (/^(202|200)$/.test(_send.status)) { me.onData(_send.responseText); } } }; } _send.send(JSON.stringify(data.data)); }; PollingTransportation.prototype.onData = function (data, header) { if (!data || data == "lost params") { return; } var self = this, val = JSON.parse(data); if (val.userId) { RongIMLib.Navigation.Endpoint.userId = val.userId; } if (header) { RongIMLib.RongIMClient._storageProvider.setItem("sId" + RongIMLib.Navigation.Endpoint.userId, header); } if (!RongIMLib.MessageUtil.isArray(val)) { val = [val]; } Array.forEach(val, function (m) { self.socket.fire("message", new RongIMLib.MessageInputStream(m, true).readMessage()); }); return ""; }; PollingTransportation.prototype.XmlHttpRequest = function () { var hasCORS = typeof XMLHttpRequest !== "undefined" && "withCredentials" in new XMLHttpRequest(), self = this; if ("undefined" != typeof XMLHttpRequest && hasCORS) { return new XMLHttpRequest(); } else if ("undefined" != typeof XDomainRequest) { return new XDomainRequest(); } else { return new ActiveXObject("Microsoft.XMLHTTP"); } }; PollingTransportation.prototype.onClose = function () { if (this.xhr) { if (this.xhr.onload) { this.xhr.onreadystatechange = this.xhr.onload = this.empty; } else { this.xhr.onreadystatechange = this.empty; } this.xhr.abort(); this.xhr = null; } if (this.sendxhr) { if (this.sendxhr.onload) { this.sendxhr.onreadystatechange = this.sendxhr.onload = this.empty; } else { this.sendxhr.onreadystatechange = this.empty; } this.sendxhr.abort(); this.sendxhr = null; } }; PollingTransportation.prototype.disconnect = function () { // RongIMLib.RongIMClient._storageProvider.removeItem("sId" + RongIMLib.Navigation.Endpoint.userId); RongIMLib.RongIMClient._storageProvider.removeItem(RongIMLib.Navigation.Endpoint.userId + "msgId"); this.onClose(); }; PollingTransportation.prototype.reconnect = function () { this.disconnect(); this.createTransport(this.url); }; PollingTransportation.prototype.onSuccess = function (responseText, isconnect) { var txt = responseText.match(/"sessionid":"\S+?(?=")/); this.onData(responseText, txt ? txt[0].slice(13) : 0); if (/"headerCode":-32,/.test(responseText)) { // RongIMLib.RongIMClient._storageProvider.removeItem("sId" + RongIMLib.Navigation.Endpoint.userId); RongIMLib.RongIMClient._storageProvider.removeItem(RongIMLib.Navigation.Endpoint.userId + "msgId"); return; } this.getRequest(RongIMLib.Navigation.Endpoint.host + "/pullmsg.js?sessionid=" + RongIMLib.RongIMClient._storageProvider.getItem("sId" + RongIMLib.Navigation.Endpoint.userId) + "×trap=" + encodeURIComponent(new Date().getTime() + Math.random() + "")); this.connected = true; isconnect && this.socket.fire("connect"); }; PollingTransportation.prototype.onError = function () { // RongIMLib.RongIMClient._storageProvider.removeItem("sId" + RongIMLib.Navigation.Endpoint.userId); RongIMLib.RongIMClient._storageProvider.removeItem(RongIMLib.Navigation.Endpoint.userId + "msgId"); this.onClose(); if (this.connected) { this.connected = false; var code = RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE; this.socket.fire("disconnect", code); } }; PollingTransportation.prototype.close = function () { this.xhr.abort(); this.sendxhr = null; }; return PollingTransportation; })(); RongIMLib.PollingTransportation = PollingTransportation; })(RongIMLib || (RongIMLib = {})); //objectname映射 var typeMapping = { "RC:TxtMsg": "TextMessage", "RC:ImgMsg": "ImageMessage", "RC:VcMsg": "VoiceMessage", "RC:ImgTextMsg": "RichContentMessage", "RC:FileMsg": "FileMessage", "RC:HQVCMsg": "HQVoiceMessage", "RC:LBSMsg": "LocationMessage", "RC:InfoNtf": "InformationNotificationMessage", "RC:ContactNtf": "ContactNotificationMessage", "RC:ProfileNtf": "ProfileNotificationMessage", "RC:CmdNtf": "CommandNotificationMessage", "RC:DizNtf": "DiscussionNotificationMessage", "RC:CmdMsg": "CommandMessage", "RC:TypSts": "TypingStatusMessage", "RC:CsChaR": "ChangeModeResponseMessage", "RC:CsHsR": "HandShakeResponseMessage", "RC:CsEnd": "TerminateMessage", "RC:CsSp": "SuspendMessage", "RC:CsUpdate": "CustomerStatusUpdateMessage", "RC:ReadNtf": "ReadReceiptMessage", "RC:VCAccept": "AcceptMessage", "RC:VCRinging": "RingingMessage", "RC:VCSummary": "SummaryMessage", "RC:VCHangup": "HungupMessage", "RC:VCInvite": "InviteMessage", "RC:VCModifyMedia": "MediaModifyMessage", "RC:VCModifyMem": "MemberModifyMessage", "RC:CsContact": "CustomerContact", "RC:PSImgTxtMsg": "PublicServiceRichContentMessage", "RC:PSMultiImgTxtMsg": "PublicServiceMultiRichContentMessage", "RC:GrpNtf": "GroupNotificationMessage", "RC:PSCmd": "PublicServiceCommandMessage", "RC:RcCmd": "RecallCommandMessage", "RC:SRSMsg": "SyncReadStatusMessage", "RC:RRReqMsg": "ReadReceiptRequestMessage", "RC:RRRspMsg": "ReadReceiptResponseMessage", "RCJrmf:RpMsg": "JrmfRedPacketMessage", "RCJrmf:RpOpendMsg": "JrmfRedPacketOpenedMessage", "RC:CombineMsg": "RCCombineMessage", "RC:chrmKVNotiMsg": "ChrmKVNotificationMessage" }, //自定义消息类型 registerMessageTypeMapping = {}, HistoryMsgType = { 4: "qryCMsg", 2: "qryDMsg", 3: "qryGMsg", 1: "qryPMsg", 6: "qrySMsg", 7: "qryPMsg", 8: "qryPMsg", 5: "qryCMsg" }, disconnectStatus = { 1: 6 }; var RongIMLib; (function (RongIMLib) { /** * 通道标识类 */ var Transportations = (function () { function Transportations() { } Transportations._TransportType = RongIMLib.Socket.WEBSOCKET; return Transportations; })(); RongIMLib.Transportations = Transportations; var SyncTimeUtil = (function () { function SyncTimeUtil() { } SyncTimeUtil.$getKey = function (message) { var client = RongIMLib.Bridge._client; var userId = client.userId; var direction = (message.messageDirection == 1 ? 'send' : 'receive'); var appkey = RongIMLib.RongIMClient._memoryStore.appKey; var tpl = '{appkey}_{userId}_{direction}box'; return RongIMLib.RongUtil.tplEngine(tpl, { appkey: appkey, userId: userId, direction: direction }); }; SyncTimeUtil.set = function (message) { var key = SyncTimeUtil.$getKey(message); var sentTime = message.sentTime; var storage = RongIMLib.RongIMClient._storageProvider; storage.setItem(key, sentTime); }; SyncTimeUtil.get = function () { var sent = SyncTimeUtil.$getKey({ messageDirection: RongIMLib.MessageDirection.SEND }); var received = SyncTimeUtil.$getKey({ messageDirection: RongIMLib.MessageDirection.RECEIVE }); var storage = RongIMLib.RongIMClient._storageProvider; return { sent: Number(storage.getItem(sent) || 0), received: Number(storage.getItem(received) || 0) }; }; return SyncTimeUtil; })(); RongIMLib.SyncTimeUtil = SyncTimeUtil; var MessageUtil = (function () { function MessageUtil() { } /** *4680000 为localstorage最小容量5200000字节的90%,超过90%将删除之前过早的存储 */ MessageUtil.checkStorageSize = function () { return JSON.stringify(localStorage).length < 4680000; }; MessageUtil.getFirstKey = function (obj) { var str = ""; for (var key in obj) { str = key; break; } return str; }; MessageUtil.isEmpty = function (obj) { var empty = true; for (var key in obj) { empty = false; break; } return empty; }; MessageUtil.ArrayForm = function (typearray) { if (Object.prototype.toString.call(typearray) == "[object ArrayBuffer]") { var arr = new Int8Array(typearray); return [].slice.call(arr); } return typearray; }; MessageUtil.ArrayFormInput = function (typearray) { if (Object.prototype.toString.call(typearray) == "[object ArrayBuffer]") { var arr = new Uint8Array(typearray); return arr; } return typearray; }; MessageUtil.indexOf = function (arr, item, from) { for (var l = arr.length, i = (from < 0) ? Math.max(0, +from) : from || 0; i < l; i++) { if (arr[i] == item) { return i; } } return -1; }; MessageUtil.isArray = function (obj) { return Object.prototype.toString.call(obj) == "[object Array]"; }; //遍历,只能遍历数组 MessageUtil.forEach = function (arr, func) { if ([].forEach) { return function (arr, func) { [].forEach.call(arr, func); }; } else { return function (arr, func) { for (var i = 0; i < arr.length; i++) { func.call(arr, arr[i], i, arr); } }; } }; MessageUtil.remove = function (array, func) { for (var i = 0, len = array.length; i < len; i++) { if (func(array[i])) { return array.splice(i, 1)[0]; } } return null; }; MessageUtil.int64ToTimestamp = function (obj, isDate) { if (obj.low === undefined) { return obj; } var low = obj.low; if (low < 0) { low += 0xffffffff + 1; } low = low.toString(16); var timestamp = parseInt(obj.high.toString(16) + "00000000".replace(new RegExp("0{" + low.length + "}$"), low), 16); if (isDate) { return new Date(timestamp); } return timestamp; }; //消息转换方法 MessageUtil.messageParser = function (entity, onReceived, offlineMsg) { var message = new RongIMLib.Message(), content = entity.content, de, objectName = entity.classname, val, isUseDef = false; try { if (RongIMLib.RongIMClient._memoryStore.depend.isPolling) { val = new RongIMLib.BinaryHelper().readUTF(content.offset ? MessageUtil.ArrayForm(content.buffer).slice(content.offset, content.limit) : content); de = JSON.parse(val); } else { val = new RongIMLib.BinaryHelper().readUTF(content.offset ? MessageUtil.ArrayFormInput(content.buffer).subarray(content.offset, content.limit) : content); de = JSON.parse(val); } } catch (ex) { de = val; isUseDef = true; } var IMLib = RongIMLib; //映射为具体消息对象 if (objectName in typeMapping) { var typeName = typeMapping[objectName]; message.content = new IMLib[typeName](de); message.messageType = typeMapping[objectName]; } else if (objectName in registerMessageTypeMapping) { var typeName = registerMessageTypeMapping[objectName]; var regMsg = new IMLib.RongIMClient.RegisterMessage[typeName](de); if (isUseDef) { message.content = regMsg.decode(de); } else { message.content = regMsg; } message.messageType = registerMessageTypeMapping[objectName]; } else { message.content = new RongIMLib.UnknownMessage({ content: de, objectName: objectName }); message.messageType = "UnknownMessage"; } //根据实体对象设置message对象] var dateTime = MessageUtil.int64ToTimestamp(entity.dataTime); if (dateTime > 0) { message.sentTime = dateTime; } else { message.sentTime = +new Date; } message.senderUserId = entity.fromUserId; message.conversationType = entity.type; if (entity.fromUserId == RongIMLib.Bridge._client.userId) { message.targetId = entity.groupId; } else { message.targetId = (/^[234]$/.test(entity.type || entity.getType()) ? entity.groupId : message.senderUserId); } var selfUserId = RongIMLib.Bridge._client.userId; // 解决多端在线收自己发的消息时, messageDirection 为 2(接收), 导致未读数增加 var isSelfSend = entity.direction == 1 || message.senderUserId === selfUserId; if (isSelfSend) { message.messageDirection = RongIMLib.MessageDirection.SEND; message.senderUserId = RongIMLib.Bridge._client.userId; } else { message.messageDirection = RongIMLib.MessageDirection.RECEIVE; } // 自己给自己发的消息, messageDirection 为 2(接收) var isSelfToSelf = message.senderUserId === selfUserId && message.targetId === selfUserId; if (isSelfToSelf) { message.messageDirection = RongIMLib.MessageDirection.RECEIVE; } message.messageUId = entity.msgId; message.receivedTime = new Date().getTime(); message.messageId = (message.conversationType + "_" + ~~(Math.random() * 0xffffff)); message.objectName = objectName; message.receivedStatus = RongIMLib.ReceivedStatus.READ; if ((entity.status & 2) == 2) { message.receivedStatus = RongIMLib.ReceivedStatus.RETRIEVED; } message.offLineMessage = offlineMsg ? true : false; if (!offlineMsg) { if (RongIMLib.RongIMClient._memoryStore.connectAckTime > message.sentTime) { message.offLineMessage = true; } } return message; }; MessageUtil.detectCMP = function (options) { options.error = options.fail; return RongIMLib.RongUtil.request(options); }; //适配SSL // static schemeArrs: Array = [["http", "ws"], ["https", "wss"]]; MessageUtil.sign = { converNum: 1, msgNum: 1, isMsgStart: true, isConvStart: true }; return MessageUtil; })(); RongIMLib.MessageUtil = MessageUtil; /** * 工具类 */ var MessageIdHandler = (function () { function MessageIdHandler() { } MessageIdHandler.init = function () { this.messageId = +(RongIMLib.RongIMClient._storageProvider.getItem(RongIMLib.Navigation.Endpoint.userId + "msgId") || RongIMLib.RongIMClient._storageProvider.setItem(RongIMLib.Navigation.Endpoint.userId + "msgId", 0) || 0); }; MessageIdHandler.messageIdPlus = function (method) { RongIMLib.RongIMClient._memoryStore.depend.isPolling && this.init(); if (this.messageId >= 65535) { this.messageId = 0; } this.messageId++; RongIMLib.RongIMClient._memoryStore.depend.isPolling && RongIMLib.RongIMClient._storageProvider.setItem(RongIMLib.Navigation.Endpoint.userId + "msgId", this.messageId); return this.messageId; }; MessageIdHandler.clearMessageId = function () { this.messageId = 0; RongIMLib.RongIMClient._memoryStore.depend.isPolling && RongIMLib.RongIMClient._storageProvider.setItem(RongIMLib.Navigation.Endpoint.userId + "msgId", this.messageId); }; MessageIdHandler.getMessageId = function () { RongIMLib.RongIMClient._memoryStore.depend.isPolling && this.init(); return this.messageId; }; MessageIdHandler.messageId = 0; return MessageIdHandler; })(); RongIMLib.MessageIdHandler = MessageIdHandler; var ChrmKVCaches = (function () { function ChrmKVCaches() { this.time = 0; this.cache = {}; } ChrmKVCaches.prototype.setTime = function (time) { this.time = time; }; ChrmKVCaches.prototype.getTime = function () { return this.time; }; ChrmKVCaches.prototype.setValue = function (kvContent) { var key = kvContent.key, timestamp = kvContent.timestamp; this.cache[key] = this.cache[key] || {}; this.cache[key] = { value: kvContent.value, userId: kvContent.userId, isDeleted: false, timestamp: timestamp }; }; ChrmKVCaches.prototype.removeValue = function (kvContent) { var key = kvContent.key, timestamp = kvContent.timestamp; this.cache[key] = this.cache[key] || {}; var cache = this.cache[key]; this.cache[key] = RongIMLib.RongUtil.extend(cache, { isDeleted: true, userId: kvContent.userId, timestamp: timestamp }); }; ChrmKVCaches.prototype.getValue = function (key) { this.cache[key] = this.cache[key] || {}; var cache = this.cache[key]; return cache.isDeleted ? null : cache.value; }; ChrmKVCaches.prototype.getAllKV = function () { var kv = {}; RongIMLib.RongUtil.forEach(this.cache, function (item, key) { if (!item.isDeleted) { kv[key] = item.value; } }); return kv; }; ChrmKVCaches.prototype.getSetUserId = function (key) { this.cache[key] = this.cache[key] || {}; return this.cache[key].userId; }; ChrmKVCaches.prototype.isKeyExisted = function (key) { this.cache[key] = this.cache[key] || {}; var cache = this.cache[key]; var hasValue = !RongIMLib.RongUtil.isEmpty(cache.value); return hasValue && !cache.isDeleted; }; ChrmKVCaches.prototype.clear = function () { this.cache = {}; }; return ChrmKVCaches; })(); var chrmKVCaches = {}; var chrmKVProsumerCaches = {}; var getKVCache = function (chrmId) { var chrmKVCache = chrmKVCaches[chrmId]; if (!chrmKVCache) { chrmKVCache = chrmKVCaches[chrmId] = new ChrmKVCaches(); } return chrmKVCache; }; var getKVProsumer = function (chrmId) { var kvProsumer = chrmKVProsumerCaches[chrmId]; if (!kvProsumer) { kvProsumer = chrmKVProsumerCaches[chrmId] = new RongIMLib.RongUtil.Prosumer(); } return kvProsumer; }; var ChrmKVHandler = (function () { function ChrmKVHandler() { } ChrmKVHandler.pull = function (chrmId, time) { var prosumer = getKVProsumer(chrmId); var event = RongIMLib.RongIMClient._dataAccessProvider.pullChatroomEntry; prosumer.produce({ event: event, chrmId: chrmId, time: time }); prosumer.consume(function (params, next) { var event = params.event, chrmId = params.chrmId, time = params.time; var kvCache = getKVCache(chrmId); var currentTime = kvCache.getTime(); var isKVNeedUpdated = currentTime < time; if (isKVNeedUpdated) { event(chrmId, currentTime, { onSuccess: function (result) { ChrmKVHandler.setEntries(chrmId, result); next(); }, onError: next }); } else { next(); } }); }; ChrmKVHandler.setEntries = function (chrmId, entity) { var entries = entity.entries, isFullUpdate = entity.bFullUpdate, syncTime = entity.syncTime; var event = isFullUpdate ? ChrmKVHandler.setFullEntries : ChrmKVHandler.setIncreEntries; var kvCache = getKVCache(chrmId); syncTime = MessageUtil.int64ToTimestamp(syncTime); if (RongIMLib.RongUtil.isArray(entries)) { RongIMLib.RongUtil.forEach(entries, function (item) { var setTime = item.timestamp; if (!RongIMLib.RongUtil.isNumber(setTime)) { item.timestamp = MessageUtil.int64ToTimestamp(setTime); } }); } kvCache.setTime(syncTime); // 更新拉取时间 event(chrmId, entries); // 更新 kv 值 }; ChrmKVHandler.setEntry = function (chrmId, chatroomEntry, status, userId) { var kvCache = getKVCache(chrmId); var timestamp = chatroomEntry.timestamp || +new Date(); var isDelete = RongInnerTools.getChrmEntityByStatus(status).isDelete; var eventName = isDelete ? 'removeValue' : 'setValue'; kvCache[eventName]({ key: chatroomEntry.key, value: chatroomEntry.value, userId: userId, timestamp: timestamp }); }; ChrmKVHandler.setFullEntries = function (chrmId, entries) { var kvCache = getKVCache(chrmId); kvCache.clear(); RongIMLib.RongUtil.forEach(entries, function (entity) { entity.timestamp = MessageUtil.int64ToTimestamp(entity.timestamp); kvCache.setValue({ key: entity.key, value: entity.value, userId: entity.uid, timestamp: entity.timestamp }); }); }; ChrmKVHandler.setIncreEntries = function (chrmId, entries) { var kvCache = getKVCache(chrmId); var currentUserId = RongIMLib.RongIMClient.getInstance().getCurrentUserId(); var optEvent = function (entity, isOverwrite, eventName) { var key = entity.key, value = entity.value; var isLatestedKeySetBySelf = kvCache.getSetUserId(key) === currentUserId; var isKeyNotExist = !kvCache.isKeyExisted(key); /* 1. 需覆盖时, 不管 key 是否已存在, 都直接设置 2. 不覆盖时, 必须最后一次 key 为自己设置的或此 key 还未设置过, 才能继续 */ if (isOverwrite || isLatestedKeySetBySelf || isKeyNotExist) { kvCache[eventName]({ key: key, value: value, userId: entity.uid, timestamp: entity.timestamp }); } }; RongIMLib.RongUtil.forEach(entries, function (entity) { var entityContent = RongInnerTools.getChrmEntityByStatus(entity.status); var eventName = entityContent.isDelete ? 'removeValue' : 'setValue'; optEvent(entity, entityContent.isOverwrite, eventName); }); }; ChrmKVHandler.getEntityValue = function (chrmId, key) { var kvCache = getKVCache(chrmId); return kvCache.getValue(key); }; ChrmKVHandler.getAllEntityValue = function (chrmId) { var kvCache = getKVCache(chrmId); return kvCache.getAllKV(); }; ChrmKVHandler.isKeyValid = function (key) { return /^[A-Za-z0-9_=+-]+$/.test(key); }; return ChrmKVHandler; })(); RongIMLib.ChrmKVHandler = ChrmKVHandler; var AutoDeleteCode = 0x0001; var OverwriteCode = 0x0002; var DeleteOperationCode = 0x0004; var RongInnerTools = (function () { function RongInnerTools() { } RongInnerTools.convertUserStatus = function (entity) { entity = RongIMLib.RongUtil.rename(entity, { subUserId: 'userId' }); var status = JSON.parse(entity.status); var us = status.us; if (!us) { return entity; } entity.status = RongIMLib.RongUtil.rename(us, { o: 'online', 'p': 'platform', s: 'status' }); return entity; }; RongInnerTools.getChrmEntityStatus = function (entity, chatroomOpt) { var status = 0; // 是否自动清理 if (entity.isAutoDelete) { status = status | AutoDeleteCode; } // 是否覆盖 if (entity.isOverwrite) { status = status | OverwriteCode; } // 操作类型 switch (chatroomOpt) { case RongIMLib.ChatroomEntityOpt.DELETE: status = status | DeleteOperationCode; break; default: break; } return status; }; RongInnerTools.getChrmEntityByStatus = function (status) { var isDelete = !!(status & DeleteOperationCode); var entityOpt = isDelete ? RongIMLib.ChatroomEntityOpt.DELETE : RongIMLib.ChatroomEntityOpt.UPDATE; return { isAutoDelete: !!(status & AutoDeleteCode), isOverwrite: !!(status & OverwriteCode), entityOpt: entityOpt, isDelete: isDelete }; }; return RongInnerTools; })(); RongIMLib.RongInnerTools = RongInnerTools; var UnreadCountHandler = (function () { function UnreadCountHandler() { } UnreadCountHandler.getKey = function (type, targetId) { var selfId = RongIMLib.RongIMClient.getInstance().getCurrentUserId(); return RongIMLib.RongUtil.tplEngine(UnreadCountHandler.KeyTemp, { selfId: selfId, type: type, targetId: targetId }); }; UnreadCountHandler.getDetailByKey = function (key) { var detail = { count: 0, sentTime: 0 }; var value = RongIMLib.RongIMClient._storageProvider.getItem(key); if (!value) { return detail; } value += ''; var unreadItems = value.split('_'); var hasUnderline = unreadItems.length > 1; detail.count = Number(unreadItems[0]); if (hasUnderline) { detail.sentTime = Number(unreadItems[1]); } return detail; }; UnreadCountHandler.getDetail = function (type, targetId) { var key = UnreadCountHandler.getKey(type, targetId); var detail = UnreadCountHandler.getDetailByKey(key); return detail; }; UnreadCountHandler.set = function (type, id, count, sentTime) { var key = UnreadCountHandler.getKey(type, id); var value = sentTime ? RongIMLib.RongUtil.tplEngine(UnreadCountHandler.ValueTemp, { count: count, sentTime: sentTime }) : count; RongIMLib.RongIMClient._storageProvider.setItem(key, value); return count; }; UnreadCountHandler.add = function (type, id, plusCount, sentTime) { var detail = UnreadCountHandler.getDetail(type, id), count = detail.count, oldSentTime = detail.sentTime; if (sentTime && sentTime > oldSentTime) { count = count + plusCount; UnreadCountHandler.set(type, id, count, sentTime); } return count; }; UnreadCountHandler.get = function (type, id) { var detail = UnreadCountHandler.getDetail(type, id); return detail.count; }; UnreadCountHandler.getAll = function (types) { var total = 0; var selfId = RongIMLib.RongIMClient.getInstance().getCurrentUserId(); var setTotal = function (keyList) { RongIMLib.RongUtil.forEach(keyList, function (key) { var detail = UnreadCountHandler.getDetailByKey(key); total += detail.count; }); }; if (types) { RongIMLib.RongUtil.forEach(types, function (type) { var key = UnreadCountHandler.getKey(type, ''); var unreadKeys = RongIMLib.RongIMClient._storageProvider.getItemKeyList(key); setTotal(unreadKeys); }); } else { var key = UnreadCountHandler.getKey('', ''); var unreadKeys = RongIMLib.RongIMClient._storageProvider.getItemKeyList(key); setTotal(unreadKeys); } return total; }; UnreadCountHandler.remove = function (type, targetId) { var key = UnreadCountHandler.getKey(type, targetId); RongIMLib.RongIMClient._storageProvider.removeItem(key); }; UnreadCountHandler.clear = function () { var key = UnreadCountHandler.getKey('', ''); var keyList = RongIMLib.RongIMClient._storageProvider.getItemKeyList(key); RongIMLib.RongUtil.forEach(keyList, function (key) { RongIMLib.RongIMClient._storageProvider.removeItem(key); }); }; UnreadCountHandler.KeyTemp = 'cu{selfId}{type}{targetId}'; UnreadCountHandler.ValueTemp = '{count}_{sentTime}'; return UnreadCountHandler; })(); RongIMLib.UnreadCountHandler = UnreadCountHandler; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var MessageContent = (function () { function MessageContent(data) { throw new Error("This method is abstract, you must implement this method in inherited class."); } MessageContent.obtain = function () { throw new Error("This method is abstract, you must implement this method in inherited class."); }; return MessageContent; })(); RongIMLib.MessageContent = MessageContent; var NotificationMessage = (function (_super) { __extends(NotificationMessage, _super); function NotificationMessage() { _super.apply(this, arguments); } return NotificationMessage; })(MessageContent); RongIMLib.NotificationMessage = NotificationMessage; var StatusMessage = (function (_super) { __extends(StatusMessage, _super); function StatusMessage() { _super.apply(this, arguments); } return StatusMessage; })(MessageContent); RongIMLib.StatusMessage = StatusMessage; var ModelUtil = (function () { function ModelUtil() { } ModelUtil.modelClone = function (object) { var obj = {}; for (var item in object) { if (item != "messageName" && "encode" != item) { obj[item] = object[item]; } } return obj; }; ModelUtil.modleCreate = function (fields, msgType) { // if (fields.length < 1) { // throw new Error("Array is empty -> registerMessageType.modleCreate"); // } var Object = function (message) { var me = this; for (var index in fields) { me[fields[index]] = message[fields[index]]; } Object.prototype.messageName = msgType; Object.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; }; return Object; }; return ModelUtil; })(); RongIMLib.ModelUtil = ModelUtil; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var CustomerStatusMessage = (function () { function CustomerStatusMessage(message) { this.messageName = "CustomerStatusMessage"; this.status = message.status; } CustomerStatusMessage.obtain = function () { return null; }; CustomerStatusMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return CustomerStatusMessage; })(); RongIMLib.CustomerStatusMessage = CustomerStatusMessage; /** * 客服转换响应消息的类型名 */ var ChangeModeResponseMessage = (function () { function ChangeModeResponseMessage(message) { this.messageName = "ChangeModeResponseMessage"; this.code = message.code; this.data = message.data; this.msg = message.msg; } ChangeModeResponseMessage.obtain = function () { return null; }; ChangeModeResponseMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ChangeModeResponseMessage; })(); RongIMLib.ChangeModeResponseMessage = ChangeModeResponseMessage; /** * 客服转换消息的类型名 * 此消息不计入未读消息数 */ var ChangeModeMessage = (function () { function ChangeModeMessage(message) { this.messageName = "ChangeModeMessage"; this.uid = message.uid; this.sid = message.sid; this.pid = message.pid; } ChangeModeMessage.obtain = function () { return null; }; ChangeModeMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ChangeModeMessage; })(); RongIMLib.ChangeModeMessage = ChangeModeMessage; var CustomerStatusUpdateMessage = (function () { function CustomerStatusUpdateMessage(message) { this.messageName = "CustomerStatusUpdateMessage"; this.serviceStatus = message.serviceStatus; this.sid = message.sid; } CustomerStatusUpdateMessage.obtain = function () { return null; }; CustomerStatusUpdateMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return CustomerStatusUpdateMessage; })(); RongIMLib.CustomerStatusUpdateMessage = CustomerStatusUpdateMessage; var HandShakeMessage = (function () { function HandShakeMessage(message) { this.messageName = "HandShakeMessage"; if (message) { this.requestInfo = message.requestInfo; this.userInfo = message.userInfo; } } HandShakeMessage.obtain = function () { return null; }; HandShakeMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return HandShakeMessage; })(); RongIMLib.HandShakeMessage = HandShakeMessage; var CustomerContact = (function () { function CustomerContact(message) { this.messageName = "CustomerContact"; this.page = message.page; this.nickName = message.nickName; this.routingInfo = message.routingInfo; this.info = message.info; this.requestInfo = message.requestInfo; } CustomerContact.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return CustomerContact; })(); RongIMLib.CustomerContact = CustomerContact; var EvaluateMessage = (function () { function EvaluateMessage(message) { this.messageName = "EvaluateMessage"; this.uid = message.uid; this.sid = message.sid; this.pid = message.pid; this.source = message.source; this.suggest = message.suggest; this.isresolve = message.isresolve; this.type = message.type; } EvaluateMessage.obtain = function () { return null; }; EvaluateMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return EvaluateMessage; })(); RongIMLib.EvaluateMessage = EvaluateMessage; /** * 客服握手响应消息的类型名 */ var HandShakeResponseMessage = (function () { function HandShakeResponseMessage(message) { this.messageName = "HandShakeResponseMessage"; this.msg = message.msg; this.status = message.status; this.data = message.data; } HandShakeResponseMessage.obtain = function () { return null; }; HandShakeResponseMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return HandShakeResponseMessage; })(); RongIMLib.HandShakeResponseMessage = HandShakeResponseMessage; var SuspendMessage = (function () { function SuspendMessage(message) { this.messageName = "SuspendMessage"; this.uid = message.uid; this.sid = message.sid; this.pid = message.pid; } SuspendMessage.obtain = function () { return null; }; SuspendMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return SuspendMessage; })(); RongIMLib.SuspendMessage = SuspendMessage; var TerminateMessage = (function () { function TerminateMessage(message) { this.messageName = "TerminateMessage"; this.code = message.code; this.msg = message.msg; this.sid = message.sid; } TerminateMessage.obtain = function () { return null; }; TerminateMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return TerminateMessage; })(); RongIMLib.TerminateMessage = TerminateMessage; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var IsTypingStatusMessage = (function () { function IsTypingStatusMessage(data) { this.messageName = "IsTypingStatusMessage"; var msg = data; } IsTypingStatusMessage.prototype.encode = function () { return undefined; }; IsTypingStatusMessage.prototype.getMessage = function () { return null; }; return IsTypingStatusMessage; })(); RongIMLib.IsTypingStatusMessage = IsTypingStatusMessage; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var InformationNotificationMessage = (function () { function InformationNotificationMessage(message) { this.messageName = "InformationNotificationMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> InformationNotificationMessage."); } this.message = message.message; this.extra = message.extra; if (message.user) { this.user = message.user; } } InformationNotificationMessage.obtain = function (message) { return new InformationNotificationMessage({ message: message, extra: "" }); }; InformationNotificationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return InformationNotificationMessage; })(); RongIMLib.InformationNotificationMessage = InformationNotificationMessage; var CommandMessage = (function () { function CommandMessage(message) { this.messageName = "CommandMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> CommandMessage."); } try { if (Object.prototype.toString.call(message.data) == "[object String]") { this.data = JSON.parse(message.data); } else { this.data = message.data; } } catch (e) { this.data = message.data; } this.name = message.name; this.extra = message.extra; } CommandMessage.obtain = function (data) { return new CommandMessage({ data: data, extra: "" }); }; CommandMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return CommandMessage; })(); RongIMLib.CommandMessage = CommandMessage; var ContactNotificationMessage = (function () { function ContactNotificationMessage(message) { this.messageName = "ContactNotificationMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> ContactNotificationMessage."); } this.operation = message.operation; this.targetUserId = message.targetUserId; this.message = message.message; this.extra = message.extra; this.sourceUserId = message.sourceUserId; if (message.user) { this.user = message.user; } } ContactNotificationMessage.obtain = function (operation, sourceUserId, targetUserId, message) { return new InformationNotificationMessage({ operation: operation, sourceUserId: sourceUserId, targetUserId: targetUserId, message: message }); }; ContactNotificationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; ContactNotificationMessage.CONTACT_OPERATION_ACCEPT_RESPONSE = "ContactOperationAcceptResponse"; ContactNotificationMessage.CONTACT_OPERATION_REJECT_RESPONSE = "ContactOperationRejectResponse"; ContactNotificationMessage.CONTACT_OPERATION_REQUEST = "ContactOperationRequest"; return ContactNotificationMessage; })(); RongIMLib.ContactNotificationMessage = ContactNotificationMessage; var ProfileNotificationMessage = (function () { function ProfileNotificationMessage(message) { this.messageName = "ProfileNotificationMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> ProfileNotificationMessage."); } this.operation = message.operation; try { if (Object.prototype.toString.call(message.data) == "[object String]") { this.data = JSON.parse(message.data); } else { this.data = message.data; } } catch (e) { this.data = message.data; } this.extra = message.extra; if (message.user) { this.user = message.user; } } ProfileNotificationMessage.obtain = function (operation, data) { return new ProfileNotificationMessage({ operation: operation, data: data }); }; ProfileNotificationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ProfileNotificationMessage; })(); RongIMLib.ProfileNotificationMessage = ProfileNotificationMessage; var CommandNotificationMessage = (function () { function CommandNotificationMessage(message) { this.messageName = "CommandNotificationMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> ProfileNotificationMessage."); } try { if (Object.prototype.toString.call(message.data) == "[object String]") { this.data = JSON.parse(message.data); } else { this.data = message.data; } } catch (e) { this.data = message.data; } this.name = message.name; this.extra = message.extra; if (message.user) { this.user = message.user; } } CommandNotificationMessage.obtain = function (name, data) { return new CommandNotificationMessage({ name: name, data: data, extra: "" }); }; CommandNotificationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return CommandNotificationMessage; })(); RongIMLib.CommandNotificationMessage = CommandNotificationMessage; var DiscussionNotificationMessage = (function () { function DiscussionNotificationMessage(message) { this.messageName = "DiscussionNotificationMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> DiscussionNotificationMessage."); } this.extra = message.extra; this.extension = message.extension; this.type = message.type; this.isHasReceived = message.isHasReceived; this.operation = message.operation; this.user = message.user; if (message.user) { this.user = message.user; } } DiscussionNotificationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return DiscussionNotificationMessage; })(); RongIMLib.DiscussionNotificationMessage = DiscussionNotificationMessage; var GroupNotificationMessage = (function () { function GroupNotificationMessage(msg) { this.messageName = "GroupNotificationMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> GroupNotificationMessage."); } msg.operatorUserId && (this.operatorUserId = msg.operatorUserId); msg.operation && (this.operation = msg.operation); msg.data && (this.data = msg.data); msg.message && (this.message = msg.message); msg.extra && (this.extra = msg.extra); } GroupNotificationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return GroupNotificationMessage; })(); RongIMLib.GroupNotificationMessage = GroupNotificationMessage; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var TextMessage = (function () { function TextMessage(message) { this.messageName = "TextMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> TextMessage."); } this.content = message.content; this.extra = message.extra; if (message.user) { this.user = message.user; } if (message.mentionedInfo) { this.mentionedInfo = message.mentionedInfo; } } TextMessage.obtain = function (text) { return new TextMessage({ extra: "", content: text }); }; TextMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return TextMessage; })(); RongIMLib.TextMessage = TextMessage; var TypingStatusMessage = (function () { function TypingStatusMessage(message) { this.messageName = "TypingStatusMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> TypingStatusMessage."); } this.typingContentType = message.typingContentType; this.data = message.data; } TypingStatusMessage.obtain = function (typingContentType, data) { return new TypingStatusMessage({ typingContentType: typingContentType, data: data }); }; TypingStatusMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return TypingStatusMessage; })(); RongIMLib.TypingStatusMessage = TypingStatusMessage; var ReadReceiptMessage = (function () { function ReadReceiptMessage(message) { this.messageName = "ReadReceiptMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> ReadReceiptMessage."); } this.lastMessageSendTime = message.lastMessageSendTime; this.messageUId = message.messageUId; this.type = message.type; } ReadReceiptMessage.obtain = function (messageUId, lastMessageSendTime, type) { return new ReadReceiptMessage({ messageUId: messageUId, lastMessageSendTime: lastMessageSendTime, type: type }); }; ReadReceiptMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ReadReceiptMessage; })(); RongIMLib.ReadReceiptMessage = ReadReceiptMessage; var VoiceMessage = (function () { function VoiceMessage(message) { this.messageName = "VoiceMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> VoiceMessage."); } this.content = message.content; this.duration = message.duration; this.extra = message.extra; if (message.user) { this.user = message.user; } if (message.mentionedInfo) { this.mentionedInfo = message.mentionedInfo; } } VoiceMessage.obtain = function (base64Content, duration) { return new VoiceMessage({ content: base64Content, duration: duration, extra: "" }); }; VoiceMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return VoiceMessage; })(); RongIMLib.VoiceMessage = VoiceMessage; var RecallCommandMessage = (function () { function RecallCommandMessage(message) { this.messageName = "RecallCommandMessage"; this.messageUId = message.messageUId; this.conversationType = message.conversationType; this.targetId = message.targetId; this.sentTime = message.sentTime; message.extra && (this.extra = message.extra); message.user && (this.user = message.user); } RecallCommandMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return RecallCommandMessage; })(); RongIMLib.RecallCommandMessage = RecallCommandMessage; var ImageMessage = (function () { function ImageMessage(message) { this.messageName = "ImageMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> ImageMessage."); } this.content = message.content; this.imageUri = message.imageUri; message.extra && (this.extra = message.extra); message.user && (this.user = message.user); if (message.mentionedInfo) { this.mentionedInfo = message.mentionedInfo; } } ImageMessage.obtain = function (content, imageUri) { return new ImageMessage({ content: content, imageUri: imageUri, extra: "" }); }; ImageMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ImageMessage; })(); RongIMLib.ImageMessage = ImageMessage; var LocationMessage = (function () { function LocationMessage(message) { this.messageName = "LocationMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> LocationMessage."); } this.latitude = message.latitude; this.longitude = message.longitude; this.poi = message.poi; this.content = message.content; this.extra = message.extra; if (message.user) { this.user = message.user; } if (message.mentionedInfo) { this.mentionedInfo = message.mentionedInfo; } } LocationMessage.obtain = function (latitude, longitude, poi, content) { return new LocationMessage({ latitude: latitude, longitude: longitude, poi: poi, content: content, extra: "" }); }; LocationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return LocationMessage; })(); RongIMLib.LocationMessage = LocationMessage; var RichContentMessage = (function () { function RichContentMessage(message) { this.messageName = "RichContentMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> RichContentMessage."); } this.title = message.title; this.content = message.content; this.imageUri = message.imageUri; this.extra = message.extra; this.url = message.url; if (message.user) { this.user = message.user; } } RichContentMessage.obtain = function (title, content, imageUri, url) { return new RichContentMessage({ title: title, content: content, imageUri: imageUri, url: url, extra: "" }); }; RichContentMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return RichContentMessage; })(); RongIMLib.RichContentMessage = RichContentMessage; var JrmfRedPacketMessage = (function () { function JrmfRedPacketMessage(message) { this.messageName = 'JrmfRedPacketMessage'; message && (this.message = message); } JrmfRedPacketMessage.prototype.encode = function () { return ""; }; return JrmfRedPacketMessage; })(); RongIMLib.JrmfRedPacketMessage = JrmfRedPacketMessage; var JrmfRedPacketOpenedMessage = (function () { function JrmfRedPacketOpenedMessage(message) { this.messageName = 'JrmfRedPacketOpenedMessage'; message && (this.message = message); } JrmfRedPacketOpenedMessage.prototype.encode = function () { return ""; }; return JrmfRedPacketOpenedMessage; })(); RongIMLib.JrmfRedPacketOpenedMessage = JrmfRedPacketOpenedMessage; var UnknownMessage = (function () { function UnknownMessage(message) { this.messageName = "UnknownMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> UnknownMessage."); } this.message = message; } UnknownMessage.prototype.encode = function () { return ""; }; return UnknownMessage; })(); RongIMLib.UnknownMessage = UnknownMessage; var PublicServiceCommandMessage = (function () { function PublicServiceCommandMessage(message) { this.messageName = "PublicServiceCommandMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> PublicServiceCommandMessage."); } this.content = message.content; this.extra = message.extra; this.menuItem = message.menuItem; if (message.user) { this.user = message.user; } if (message.mentionedInfo) { this.mentionedInfo = message.mentionedInfo; } } PublicServiceCommandMessage.obtain = function (item) { return new PublicServiceCommandMessage({ content: "", command: "", menuItem: item, extra: "" }); }; PublicServiceCommandMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return PublicServiceCommandMessage; })(); RongIMLib.PublicServiceCommandMessage = PublicServiceCommandMessage; var PublicServiceMultiRichContentMessage = (function () { function PublicServiceMultiRichContentMessage(messages) { this.messageName = "PublicServiceMultiRichContentMessage"; this.richContentMessages = messages; } PublicServiceMultiRichContentMessage.prototype.encode = function () { return null; }; return PublicServiceMultiRichContentMessage; })(); RongIMLib.PublicServiceMultiRichContentMessage = PublicServiceMultiRichContentMessage; var SyncReadStatusMessage = (function () { function SyncReadStatusMessage(message) { this.messageName = "SyncReadStatusMessage"; message.lastMessageSendTime && (this.lastMessageSendTime = message.lastMessageSendTime); } SyncReadStatusMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return SyncReadStatusMessage; })(); RongIMLib.SyncReadStatusMessage = SyncReadStatusMessage; var ReadReceiptRequestMessage = (function () { function ReadReceiptRequestMessage(message) { this.messageName = "ReadReceiptRequestMessage"; message.messageUId && (this.messageUId = message.messageUId); } ReadReceiptRequestMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ReadReceiptRequestMessage; })(); RongIMLib.ReadReceiptRequestMessage = ReadReceiptRequestMessage; var ReadReceiptResponseMessage = (function () { function ReadReceiptResponseMessage(message) { this.messageName = "ReadReceiptResponseMessage"; message.receiptMessageDic && (this.receiptMessageDic = message.receiptMessageDic); } ReadReceiptResponseMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ReadReceiptResponseMessage; })(); RongIMLib.ReadReceiptResponseMessage = ReadReceiptResponseMessage; var PublicServiceRichContentMessage = (function () { function PublicServiceRichContentMessage(message) { this.messageName = "PublicServiceRichContentMessage"; this.richContentMessage = message; } PublicServiceRichContentMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return PublicServiceRichContentMessage; })(); RongIMLib.PublicServiceRichContentMessage = PublicServiceRichContentMessage; var FileMessage = (function () { function FileMessage(message) { this.messageName = "FileMessage"; message.name && (this.name = message.name); message.size && (this.size = message.size); message.type && (this.type = message.type); message.fileUrl && (this.fileUrl = message.fileUrl); message.extra && (this.extra = message.extra); message.user && (this.user = message.user); } FileMessage.obtain = function (msg) { return new FileMessage({ name: msg.name, size: msg.size, type: msg.type, fileUrl: msg.fileUrl }); }; FileMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return FileMessage; })(); RongIMLib.FileMessage = FileMessage; var HQVoiceMessage = (function () { function HQVoiceMessage(message) { this.messageName = "HQVoiceMessage"; this.type = message.type || 'aac'; message.localPath && (this.localPath = message.localPath); message.remoteUrl && (this.remoteUrl = message.remoteUrl); message.duration && (this.duration = message.duration); message.extra && (this.extra = message.extra); message.user && (this.user = message.user); } HQVoiceMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return HQVoiceMessage; })(); RongIMLib.HQVoiceMessage = HQVoiceMessage; var AcceptMessage = (function () { function AcceptMessage(message) { this.messageName = "AcceptMessage"; this.mediaId = message.mediaId; this.callId = message.callId; this.mediaType = message.mediaType; this.mode = message.mode; this.subInfo = message.subInfo; } AcceptMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return AcceptMessage; })(); RongIMLib.AcceptMessage = AcceptMessage; var RingingMessage = (function () { function RingingMessage(message) { this.messageName = "RingingMessage"; this.callId = message.callId; } RingingMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return RingingMessage; })(); RongIMLib.RingingMessage = RingingMessage; var SummaryMessage = (function () { function SummaryMessage(message) { this.messageName = "SummaryMessage"; this.caller = message.caller; this.inviter = message.inviter; this.mediaType = message.mediaType; this.memberIdList = message.memberIdList; this.startTime = message.startTime; this.connectedTime = message.connectedTime; this.duration = message.duration; this.status = message.status; } SummaryMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return SummaryMessage; })(); RongIMLib.SummaryMessage = SummaryMessage; var HungupMessage = (function () { function HungupMessage(message) { this.messageName = "HungupMessage"; this.callId = message.callId; this.reason = message.reason; this.mode = message.mode; this.subInfo = message.subInfo; } HungupMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return HungupMessage; })(); RongIMLib.HungupMessage = HungupMessage; var InviteMessage = (function () { function InviteMessage(message) { this.messageName = "InviteMessage"; this.mediaId = message.mediaId; this.callId = message.callId; this.engineType = message.engineType; this.channelInfo = message.channelInfo; this.mediaType = message.mediaType; this.extra = message.extra; this.inviteUserIds = message.inviteUserIds; this.observerUserIds = message.observerUserIds; this.mode = message.mode; this.subInfo = message.subInfo; } InviteMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return InviteMessage; })(); RongIMLib.InviteMessage = InviteMessage; var MediaModifyMessage = (function () { function MediaModifyMessage(message) { this.messageName = "MediaModifyMessage"; this.callId = message.callId; this.mediaType = message.mediaType; this.mode = message.mode; this.subInfo = message.subInfo; } MediaModifyMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return MediaModifyMessage; })(); RongIMLib.MediaModifyMessage = MediaModifyMessage; var MemberModifyMessage = (function () { function MemberModifyMessage(message) { this.messageName = "MemberModifyMessage"; this.modifyMemType = message.modifyMemType; this.callId = message.callId; this.caller = message.caller; this.engineType = message.engineType; this.channelInfo = message.channelInfo; this.mediaType = message.mediaType; this.extra = message.extra; this.inviteUserIds = message.inviteUserIds; this.existedMemberStatusList = message.existedMemberStatusList; this.existedUserPofiles = message.existedUserPofiles; this.observerUserIds = message.observerUserIds; this.mode = message.mode; this.subInfo = message.subInfo; } MemberModifyMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return MemberModifyMessage; })(); RongIMLib.MemberModifyMessage = MemberModifyMessage; var RCCombineMessage = (function () { function RCCombineMessage(message) { this.messageName = "RCCombineMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> RCCombineMessage."); } this.nameList = message.nameList; this.remoteUrl = message.remoteUrl; if (message.user) { this.user = message.user; } this.summaryList = message.summaryList; } RCCombineMessage.obtain = function (remoteUrl, nameList, summaryList) { return new RCCombineMessage({ extra: "", content: remoteUrl, nameList: nameList, summaryList: summaryList }); }; RCCombineMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return RCCombineMessage; })(); RongIMLib.RCCombineMessage = RCCombineMessage; var ChrmKVNotificationMessage = (function () { function ChrmKVNotificationMessage(message) { this.messageName = "ChrmKVNotificationMessage"; message.key && (this.key = message.key); message.value && (this.value = message.value); message.type && (this.type = message.type); message.extra && (this.extra = message.extra); message.user && (this.user = message.user); } ChrmKVNotificationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ChrmKVNotificationMessage; })(); RongIMLib.ChrmKVNotificationMessage = ChrmKVNotificationMessage; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var ChannelInfo = (function () { function ChannelInfo(Id, Key) { this.Id = Id; this.Key = Key; } return ChannelInfo; })(); RongIMLib.ChannelInfo = ChannelInfo; var UserStatus = (function () { function UserStatus(platform, online, status) { this.platform = platform; this.online = online; this.status = status; } return UserStatus; })(); RongIMLib.UserStatus = UserStatus; var MentionedInfo = (function () { function MentionedInfo(type, userIdList, mentionedContent) { } return MentionedInfo; })(); RongIMLib.MentionedInfo = MentionedInfo; var DeleteMessage = (function () { function DeleteMessage(msgId, msgDataTime, direct) { this.msgId = msgId; this.msgDataTime = msgDataTime; this.direct = direct; } return DeleteMessage; })(); RongIMLib.DeleteMessage = DeleteMessage; var CustomServiceConfig = (function () { function CustomServiceConfig(isBlack, companyName, companyUrl) { } return CustomServiceConfig; })(); RongIMLib.CustomServiceConfig = CustomServiceConfig; var CustomServiceSession = (function () { function CustomServiceSession(uid, cid, pid, isQuited, type, adminHelloWord, adminOfflineWord) { } return CustomServiceSession; })(); RongIMLib.CustomServiceSession = CustomServiceSession; var Conversation = (function () { function Conversation(conversationTitle, conversationType, draft, isTop, latestMessage, latestMessageId, notificationStatus, objectName, receivedStatus, receivedTime, senderUserId, senderUserName, sentStatus, sentTime, targetId, unreadMessageCount, senderPortraitUri, isHidden, mentionedMsg, hasUnreadMention, _readTime) { this.conversationTitle = conversationTitle; this.conversationType = conversationType; this.draft = draft; this.isTop = isTop; this.latestMessage = latestMessage; this.latestMessageId = latestMessageId; this.notificationStatus = notificationStatus; this.objectName = objectName; this.receivedStatus = receivedStatus; this.receivedTime = receivedTime; this.senderUserId = senderUserId; this.senderUserName = senderUserName; this.sentStatus = sentStatus; this.sentTime = sentTime; this.targetId = targetId; this.unreadMessageCount = unreadMessageCount; this.senderPortraitUri = senderPortraitUri; this.isHidden = isHidden; this.mentionedMsg = mentionedMsg; this.hasUnreadMention = hasUnreadMention; this._readTime = _readTime; } Conversation.prototype.setTop = function () { RongIMLib.RongIMClient._dataAccessProvider.addConversation(this, { onSuccess: function (data) { } }); }; return Conversation; })(); RongIMLib.Conversation = Conversation; var Discussion = (function () { function Discussion(creatorId, id, memberIdList, name, isOpen) { this.creatorId = creatorId; this.id = id; this.memberIdList = memberIdList; this.name = name; this.isOpen = isOpen; } return Discussion; })(); RongIMLib.Discussion = Discussion; var Group = (function () { function Group(id, name, portraitUri) { this.id = id; this.name = name; this.portraitUri = portraitUri; } return Group; })(); RongIMLib.Group = Group; var Message = (function () { function Message(content, conversationType, extra, objectName, messageDirection, messageId, receivedStatus, receivedTime, senderUserId, sentStatus, sentTime, targetId, messageType, messageUId, isLocalMessage, offLineMessage, receiptResponse) { this.content = content; this.conversationType = conversationType; this.extra = extra; this.objectName = objectName; this.messageDirection = messageDirection; this.messageId = messageId; this.receivedStatus = receivedStatus; this.receivedTime = receivedTime; this.senderUserId = senderUserId; this.sentStatus = sentStatus; this.sentTime = sentTime; this.targetId = targetId; this.messageType = messageType; this.messageUId = messageUId; this.isLocalMessage = isLocalMessage; this.offLineMessage = offLineMessage; this.receiptResponse = receiptResponse; } return Message; })(); RongIMLib.Message = Message; var MessageTag = (function () { function MessageTag(isCounted, isPersited) { this.isCounted = isCounted; this.isPersited = isPersited; } MessageTag.prototype.getMessageTag = function () { if (this.isCounted && this.isPersited) { return 3; } else if (this.isCounted) { return 2; } else if (this.isPersited) { return 1; } else if (!this.isCounted && !this.isPersited) { return 0; } }; MessageTag.getTagByStatus = function (status) { var statusMap = { 3: { isCounted: true, isPersited: true }, 2: { isCounted: true, isPersited: false }, 1: { isCounted: true, isPersited: true }, 0: { isCounted: true, isPersited: true } }; return statusMap[status] || statusMap[3]; }; return MessageTag; })(); RongIMLib.MessageTag = MessageTag; var PublicServiceMenuItem = (function () { function PublicServiceMenuItem(id, name, type, sunMenuItems, url) { this.id = id; this.name = name; this.type = type; this.sunMenuItems = sunMenuItems; this.url = url; } return PublicServiceMenuItem; })(); RongIMLib.PublicServiceMenuItem = PublicServiceMenuItem; // TODO: TBD var PublicServiceProfile = (function () { function PublicServiceProfile(conversationType, introduction, menu, name, portraitUri, publicServiceId, hasFollowed, isGlobal) { this.conversationType = conversationType; this.introduction = introduction; this.menu = menu; this.name = name; this.portraitUri = portraitUri; this.publicServiceId = publicServiceId; this.hasFollowed = hasFollowed; this.isGlobal = isGlobal; } return PublicServiceProfile; })(); RongIMLib.PublicServiceProfile = PublicServiceProfile; var UserInfo = (function () { function UserInfo(id, name, portraitUri) { this.id = id; this.name = name; this.portraitUri = portraitUri; } return UserInfo; })(); RongIMLib.UserInfo = UserInfo; var User = (function () { function User(id, token) { this.id = id; this.token = token; } return User; })(); RongIMLib.User = User; var Room = (function () { function Room(id, user, mode, broadcastType, type) { this.id = id; this.user = user; this.mode = mode; this.broadcastType = broadcastType; this.type = type; } return Room; })(); RongIMLib.Room = Room; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var ServerDataProvider = (function () { function ServerDataProvider() { this.userStatusListener = null; this.Conversation = { watcher: new RongIMLib.Observer(), watch: function (_watcher) { this.watcher.add(_watcher); var conversationList = RongIMLib.RongIMClient._memoryStore.conversationList; this.watcher.emit(conversationList); }, unwatch: function (_watcher) { this.watcher.remove(_watcher); }, _notify: function (conversationList) { this.watcher.emit(conversationList); } }; } ServerDataProvider.prototype.init = function (appKey, options) { new RongIMLib.FeatureDectector(options.appCallback); }; ServerDataProvider.prototype.connect = function (token, callback, userId, option) { RongIMLib.RongIMClient.bridge = RongIMLib.Bridge.getInstance(); RongIMLib.RongIMClient._memoryStore.token = token; RongIMLib.RongIMClient._memoryStore.callback = callback; userId = userId || ''; option = option || {}; var isConnecting = false, isConnected = false; if (RongIMLib.Bridge._client && RongIMLib.Bridge._client.channel) { isConnecting = (RongIMLib.Bridge._client.channel.connectionStatus == RongIMLib.ConnectionStatus.CONNECTING); isConnected = (RongIMLib.Bridge._client.channel.connectionStatus == RongIMLib.ConnectionStatus.CONNECTED); } if (isConnected || isConnecting) { return; } var isGreater = (RongIMLib.RongIMClient.otherDeviceLoginCount > 5); if (isGreater) { callback.onError(RongIMLib.ConnectionStatus.ULTRALIMIT); return; } // 清除本地导航缓存 if (option.force) { RongIMLib.RongIMClient._storageProvider.removeItem('servers'); } RongIMLib.RongIMClient.bridge.setListener(); RongIMLib.RongIMClient.bridge.connect(RongIMLib.RongIMClient._memoryStore.appKey, token, { onSuccess: function (data) { setTimeout(function () { callback.onSuccess(data); }); }, onError: function (e) { if (e == RongIMLib.ConnectionState.TOKEN_INCORRECT || !e) { setTimeout(function () { callback.onTokenIncorrect(); }); } else { setTimeout(function () { callback.onError(e); }); } } }); }; /* config.auto: 默认 false, true 启用自动重连,启用则为必选参数 config.rate: 重试频率 [100, 1000, 3000, 6000, 10000, 18000] 单位为毫秒,可选 config.url: 网络嗅探地址 [http(s)://]cdn.ronghub.com/RongIMLib-2.2.6.min.js 可选 */ ServerDataProvider.prototype.reconnect = function (callback, config) { var store = RongIMLib.RongIMClient._memoryStore; var token = store.token; if (!token) { throw new Error('reconnect: token is empty.'); } if (RongIMLib.Bridge._client && RongIMLib.Bridge._client.channel && RongIMLib.Bridge._client.channel.connectionStatus != RongIMLib.ConnectionStatus.CONNECTED && RongIMLib.Bridge._client.channel.connectionStatus != RongIMLib.ConnectionStatus.CONNECTING) { config = config || {}; var key = config.auto ? 'auto' : 'custom'; var handler = { auto: function () { var repeatConnect = function (options) { var step = options.step(); var done = 'done'; var url = options.url; var ping = function () { RongIMLib.RongUtil.request({ url: url, success: function () { options.done(); }, error: function () { repeat(); } }); }; var repeat = function () { var next = step(); if (next == 'done') { var error = RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE; options.done(error); return; } setTimeout(ping, next); }; repeat(); }; var protocol = RongIMLib.RongIMClient._memoryStore.depend.protocol; var url = config.url || 'cdn.ronghub.com/RongIMLib-2.2.6.min.js'; var pathConfig = { protocol: protocol, path: url }; url = RongIMLib.RongUtil.formatProtoclPath(pathConfig); var rate = config.rate || [100, 1000, 3000, 6000, 10000, 18000]; //结束标识 rate.push('done'); var opts = { url: url, step: function () { var index = 0; return function () { var time = rate[index]; index++; return time; }; }, done: function (error) { if (error) { callback.onError(error); return; } RongIMLib.RongIMClient.connect(token, callback); } }; repeatConnect(opts); }, custom: function () { RongIMLib.RongIMClient.connect(token, callback); } }; handler[key](); } }; ServerDataProvider.prototype.logout = function () { RongIMLib.RongIMClient.bridge.disconnect(); RongIMLib.RongIMClient.bridge = null; }; ServerDataProvider.prototype.disconnect = function () { RongIMLib.RongIMClient.bridge.disconnect(); }; ServerDataProvider.prototype.sendReceiptResponse = function (conversationType, targetId, sendCallback) { var rspkey = RongIMLib.Bridge._client.userId + conversationType + targetId + 'RECEIVED', me = this; if (RongIMLib.RongUtil.supportLocalStorage()) { var valObj = JSON.parse(RongIMLib.RongIMClient._storageProvider.getItem(rspkey)); if (valObj) { var vals = []; for (var key in valObj) { var tmp = {}; tmp[key] = valObj[key].uIds; valObj[key].isResponse || vals.push(tmp); } if (vals.length == 0) { sendCallback.onSuccess(); return; } var interval = setInterval(function () { if (vals.length == 1) { clearInterval(interval); } var obj = vals.splice(0, 1)[0]; var rspMsg = new RongIMLib.ReadReceiptResponseMessage({ receiptMessageDic: obj }); me.sendMessage(conversationType, targetId, rspMsg, { onSuccess: function (msg) { var senderUserId = RongIMLib.MessageUtil.getFirstKey(obj); valObj[senderUserId].isResponse = true; RongIMLib.RongIMClient._storageProvider.setItem(rspkey, JSON.stringify(valObj)); sendCallback.onSuccess(msg); }, onError: function (error, msg) { sendCallback.onError(error, msg); } }); }, 200); } else { sendCallback.onSuccess(); } } else { sendCallback.onSuccess(); } }; ServerDataProvider.prototype.sendTypingStatusMessage = function (conversationType, targetId, messageName, sendCallback) { var me = this; if (messageName in RongIMLib.RongIMClient.MessageParams) { me.sendMessage(conversationType, targetId, RongIMLib.TypingStatusMessage.obtain(RongIMLib.RongIMClient.MessageParams[messageName].objectName, ""), { onSuccess: function () { setTimeout(function () { sendCallback.onSuccess(); }); }, onError: function (errorCode) { setTimeout(function () { sendCallback.onError(errorCode, null); }); }, onBefore: function () { } }); } }; ServerDataProvider.prototype.sendRecallMessage = function (content, sendMessageCallback) { var msg = new RongIMLib.RecallCommandMessage({ conversationType: content.conversationType, targetId: content.targetId, sentTime: content.sentTime, messageUId: content.messageUId, extra: content.extra, user: content.user }); this.sendMessage(content.conversationType, content.senderUserId, msg, sendMessageCallback, false, null, null, 2); }; ServerDataProvider.prototype.sendTextMessage = function (conversationType, targetId, content, sendMessageCallback) { var msgContent = RongIMLib.TextMessage.obtain(content); this.sendMessage(conversationType, targetId, msgContent, sendMessageCallback); }; ServerDataProvider.prototype.getRemoteHistoryMessages = function (conversationType, targetId, timestamp, count, callback, config) { if (count <= 1) { throw new Error("the count must be greater than 1."); } config = config || {}; var order = config.order || 0; var getKey = function () { return [conversationType, targetId, '_', order].join(''); }; var key = getKey(); if (!RongIMLib.RongUtil.isNumber(timestamp)) { timestamp = RongIMLib.RongIMClient._memoryStore.lastReadTime.get(key); } var memoryStore = RongIMLib.RongIMClient._memoryStore; var historyMessageLimit = memoryStore.historyMessageLimit; /* limit 属性: var limit = { time: '时间戳, 最后一次拉取时间', hasMore: '是否还有历史消息, bool 值' }; */ var limit = historyMessageLimit.get(key) || {}; var hasMore = limit.hasMore; var isFecth = (hasMore || limit.time != timestamp); // 正序获取消息时不做限制,防止有新消息导致无法获取 if (!isFecth && order == 0) { return callback.onSuccess([], hasMore); } var modules = new RongIMLib.RongIMClient.Protobuf.HistoryMsgInput(), self = this; modules.setTargetId(targetId); modules.setTime(timestamp); modules.setCount(count); modules.setOrder(order); var topic = HistoryMsgType[conversationType] || HistoryMsgType[RongIMLib.ConversationType.PRIVATE]; RongIMLib.RongIMClient.bridge.queryMsg(topic, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), targetId, { onSuccess: function (data) { var fetchTime = RongIMLib.MessageUtil.int64ToTimestamp(data.syncTime); RongIMLib.RongIMClient._memoryStore.lastReadTime.set(key, fetchTime); historyMessageLimit.set(key, { hasMore: !!data.hasMsg, time: fetchTime }); var list = data.list.reverse(), tempMsg = null, tempDir; var read = RongIMLib.SentStatus.READ; if (RongIMLib.RongUtil.supportLocalStorage()) { for (var i = 0, len = list.length; i < len; i++) { tempMsg = RongIMLib.MessageUtil.messageParser(list[i]); tempDir = JSON.parse(RongIMLib.RongIMClient._storageProvider.getItem(RongIMLib.Bridge._client.userId + tempMsg.messageUId + "SENT")); if (tempDir) { tempMsg.receiptResponse || (tempMsg.receiptResponse = {}); tempMsg.receiptResponse[tempMsg.messageUId] = tempDir.count; } tempMsg.sentStatus = read; tempMsg.targetId = targetId; list[i] = tempMsg; } } else { for (var i = 0, len = list.length; i < len; i++) { var tempMsg = RongIMLib.MessageUtil.messageParser(list[i]); tempMsg.sentStatus = read; list[i] = tempMsg; } } setTimeout(function () { callback.onSuccess(list, !!data.hasMsg); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }, "HistoryMessagesOuput"); }; ServerDataProvider.prototype.hasRemoteUnreadMessages = function (token, callback) { var xss = null; window.RCCallback = function (x) { setTimeout(function () { callback.onSuccess(!!+x.status); }); xss.parentNode.removeChild(xss); }; xss = document.createElement("script"); xss.src = RongIMLib.RongIMClient._memoryStore.depend.api + "/message/exist.js?appKey=" + encodeURIComponent(RongIMLib.RongIMClient._memoryStore.appKey) + "&token=" + encodeURIComponent(token) + "&callBack=RCCallback&_=" + RongIMLib.RongUtil.getTimestamp(); document.body.appendChild(xss); xss.onerror = function () { setTimeout(function () { callback.onError(RongIMLib.ErrorCode.UNKNOWN); }); xss.parentNode.removeChild(xss); }; }; ServerDataProvider.prototype.getRemoteConversationList = function (callback, conversationTypes, count) { var modules = new RongIMLib.RongIMClient.Protobuf.RelationsInput(), self = this; modules.setType(1); if (typeof count == 'undefined') { modules.setCount(0); } else { modules.setCount(count); } RongIMLib.RongIMClient.bridge.queryMsg(26, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (list) { if (list.info) { list.info = list.info.reverse(); for (var i = 0, len = list.info.length; i < len; i++) { RongIMLib.RongIMClient.getInstance().pottingConversation(list.info[i]); } } var conversations = RongIMLib.RongIMClient._memoryStore.conversationList; setTimeout(function () { if (conversationTypes) { return callback.onSuccess(self.filterConversations(conversationTypes, conversations)); } callback.onSuccess(conversations); }); }, onError: function (error) { callback.onError(error); } }, "RelationsOutput"); }; ServerDataProvider.prototype.addMemberToDiscussion = function (discussionId, userIdList, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.ChannelInvitationInput(); modules.setUsers(userIdList); RongIMLib.RongIMClient.bridge.queryMsg(0, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), discussionId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.createDiscussion = function (name, userIdList, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.CreateDiscussionInput(), self = this; modules.setName(name); RongIMLib.RongIMClient.bridge.queryMsg(1, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (discussId) { if (userIdList.length > 0) { self.addMemberToDiscussion(discussId, userIdList, { onSuccess: function () { }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); } setTimeout(function () { callback.onSuccess(discussId); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }, "CreateDiscussionOutput"); }; ServerDataProvider.prototype.getDiscussion = function (discussionId, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.ChannelInfoInput(); modules.setNothing(1); RongIMLib.RongIMClient.bridge.queryMsg(4, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), discussionId, { onSuccess: function (data) { setTimeout(function () { callback.onSuccess(data); }); }, onError: function (errorCode) { setTimeout(function () { callback.onError(errorCode); }); } }, "ChannelInfoOutput"); }; ServerDataProvider.prototype.quitDiscussion = function (discussionId, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.LeaveChannelInput(); modules.setNothing(1); RongIMLib.RongIMClient.bridge.queryMsg(7, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), discussionId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (errorCode) { setTimeout(function () { callback.onError(errorCode); }); } }); }; ServerDataProvider.prototype.removeMemberFromDiscussion = function (discussionId, userId, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.ChannelEvictionInput(); modules.setUser(userId); RongIMLib.RongIMClient.bridge.queryMsg(9, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), discussionId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (errorCode) { setTimeout(function () { callback.onError(errorCode); }); } }); }; ServerDataProvider.prototype.setDiscussionInviteStatus = function (discussionId, status, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.ModifyPermissionInput(); modules.setOpenStatus(status.valueOf()); RongIMLib.RongIMClient.bridge.queryMsg(11, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), discussionId, { onSuccess: function (x) { setTimeout(function () { callback.onSuccess(); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.setDiscussionName = function (discussionId, name, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RenameChannelInput(); modules.setName(name); RongIMLib.RongIMClient.bridge.queryMsg(12, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), discussionId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (errcode) { callback.onError(errcode); } }); }; ServerDataProvider.prototype.joinChatRoom = function (chatroomId, messageCount, callback) { var e = new RongIMLib.RongIMClient.Protobuf.ChrmInput(); e.setNothing(1); RongIMLib.Bridge._client.chatroomId = chatroomId; RongIMLib.RongIMClient.bridge.queryMsg(19, RongIMLib.MessageUtil.ArrayForm(e.toArrayBuffer()), chatroomId, { onSuccess: function () { var navi = RongIMLib.RongIMClient.getInstance().getNavi(); var isOpenKVStorage = navi.kvStorage; if (isOpenKVStorage) { RongIMLib.RongIMClient._dataAccessProvider.pullChatroomEntry(chatroomId, 0, { onSuccess: function (result) { RongIMLib.ChrmKVHandler.setEntries(chatroomId, result); setTimeout(function () { callback.onSuccess(); }); }, onError: function (errorCode) { setTimeout(function () { callback.onError(errorCode); }); } }); } else { setTimeout(function () { callback.onSuccess(); }); } var modules = new RongIMLib.RongIMClient.Protobuf.ChrmPullMsg(); messageCount == 0 && (messageCount = -1); modules.setCount(messageCount); modules.setSyncTime(0); RongIMLib.Bridge._client.queryMessage("chrmPull", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), chatroomId, 1, { onSuccess: function (collection) { var list = collection.list; var sync = RongIMLib.MessageUtil.int64ToTimestamp(collection.syncTime); var latestMessage = list[list.length - 1]; if (latestMessage) { latestMessage = RongIMLib.MessageUtil.messageParser(latestMessage); sync = latestMessage.sentTime; } RongIMLib.RongIMClient._memoryStore.lastReadTime.set(chatroomId + RongIMLib.Bridge._client.userId + "CST", sync); var _client = RongIMLib.Bridge._client; for (var i = 0, mlen = list.length; i < mlen; i++) { var uId = 'R' + list[i].msgId; if (!(uId in _client.cacheMessageIds)) { _client.cacheMessageIds[uId] = true; var cacheUIds = RongIMLib.RongUtil.keys(_client.cacheMessageIds); if (cacheUIds.length > 10) { uId = cacheUIds[0]; delete _client.cacheMessageIds[uId]; } if (RongIMLib.RongIMClient._memoryStore.filterMessages.length > 0) { for (var j = 0, flen = RongIMLib.RongIMClient._memoryStore.filterMessages.length; j < flen; j++) { if (RongIMLib.RongIMClient.MessageParams[RongIMLib.RongIMClient._memoryStore.filterMessages[j]].objectName != list[i].classname) { _client.handler.onReceived(list[i]); } } } else { _client.handler.onReceived(list[i]); } } } }, onError: function (x) { setTimeout(function () { callback.onError(RongIMLib.ErrorCode.CHATROOM_HISMESSAGE_ERROR); }); } }, "DownStreamMessages"); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }, "ChrmOutput"); }; ServerDataProvider.prototype.getChatRoomInfo = function (chatRoomId, count, order, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.QueryChatroomInfoInput(); modules.setCount(count); modules.setOrder(order); RongIMLib.RongIMClient.bridge.queryMsg("queryChrmI", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), chatRoomId, { onSuccess: function (ret) { var userInfos = ret.userInfos; userInfos.forEach(function (item) { item.time = RongIMLib.MessageUtil.int64ToTimestamp(item.time); }); setTimeout(function () { callback.onSuccess(ret); }); }, onError: function (errcode) { setTimeout(function () { callback.onError(errcode); }); } }, "QueryChatroomInfoOutput"); }; ServerDataProvider.prototype.quitChatRoom = function (chatroomId, callback) { var e = new RongIMLib.RongIMClient.Protobuf.ChrmInput(); e.setNothing(1); RongIMLib.RongIMClient.bridge.queryMsg(17, RongIMLib.MessageUtil.ArrayForm(e.toArrayBuffer()), chatroomId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (errcode) { setTimeout(function () { callback.onError(errcode); }); } }, "ChrmOutput"); }; ServerDataProvider.prototype.setChatroomHisMessageTimestamp = function (chatRoomId, timestamp) { RongIMLib.RongIMClient._memoryStore.lastReadTime.set('chrhis_' + chatRoomId, timestamp); }; ServerDataProvider.prototype.getChatRoomHistoryMessages = function (chatRoomId, count, order, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.HistoryMsgInput(); modules.setTargetId(chatRoomId); var timestamp = RongIMLib.RongIMClient._memoryStore.lastReadTime.get('chrhis_' + chatRoomId) || 0; modules.setTime(timestamp); modules.setCount(count); modules.setOrder(order); RongIMLib.RongIMClient.bridge.queryMsg(34, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (data) { RongIMLib.RongIMClient._memoryStore.lastReadTime.set('chrhis_' + chatRoomId, RongIMLib.MessageUtil.int64ToTimestamp(data.syncTime)); var list = data.list.reverse(); for (var i = 0, len = list.length; i < len; i++) { list[i] = RongIMLib.MessageUtil.messageParser(list[i]); } setTimeout(function () { callback.onSuccess(list, !!data.hasMsg); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }, "HistoryMsgOuput"); }; ServerDataProvider.prototype.setChatroomEntry = function (chatroomId, chatroomEntry, callback) { var opt = RongIMLib.ChatroomEntityOpt.UPDATE; var key = chatroomEntry.key, value = chatroomEntry.value; var isKeyInValid = !RongIMLib.RongUtil.isLengthLimit(key, RongIMLib.ChatroomEntityLimit.KEY, 1) || !RongIMLib.ChrmKVHandler.isKeyValid(key); var isValueInValid = !RongIMLib.RongUtil.isLengthLimit(value, RongIMLib.ChatroomEntityLimit.VALUE, 1); if (isKeyInValid || isValueInValid) { setTimeout(function () { callback.onError(RongIMLib.ErrorCode.BIZ_ERROR_INVALID_PARAMETER); }); } else { this.refreshChatroomEntry(chatroomId, chatroomEntry, opt, callback); } }; ServerDataProvider.prototype.forceSetChatroomEntry = function (chatroomId, chatroomEntry, callback) { chatroomEntry.isOverwrite = true; this.setChatroomEntry(chatroomId, chatroomEntry, callback); }; ServerDataProvider.prototype.removeChatroomEntry = function (chatroomId, chatroomEntry, callback) { var opt = RongIMLib.ChatroomEntityOpt.DELETE; var key = chatroomEntry.key; var isKeyInValid = !RongIMLib.RongUtil.isLengthLimit(key, RongIMLib.ChatroomEntityLimit.KEY, 1) || !RongIMLib.ChrmKVHandler.isKeyValid(key); if (isKeyInValid) { setTimeout(function () { callback.onError(RongIMLib.ErrorCode.BIZ_ERROR_INVALID_PARAMETER); }); } else { this.refreshChatroomEntry(chatroomId, chatroomEntry, opt, callback); } }; ServerDataProvider.prototype.forceRemoveChatroomEntry = function (chatroomId, chatroomEntry, callback) { chatroomEntry.isOverwrite = true; this.removeChatroomEntry(chatroomId, chatroomEntry, callback); }; ServerDataProvider.prototype.refreshChatroomEntry = function (chatroomId, chatroomEntry, chatroomEntryOpt, callback) { var modules, topic; var key = chatroomEntry.key, value = chatroomEntry.value || '', extra = chatroomEntry.notificationExtra; if (chatroomEntryOpt === RongIMLib.ChatroomEntityOpt.DELETE) { modules = new RongIMLib.RongIMClient.Protobuf.DeleteChrmKV(); topic = 'delKV'; } else { modules = new RongIMLib.RongIMClient.Protobuf.SetChrmKV(); topic = 'setKV'; } var status = RongIMLib.RongInnerTools.getChrmEntityStatus(chatroomEntry, chatroomEntryOpt); var currentUserId = RongIMLib.RongIMClient.getInstance().getCurrentUserId(); var entry = { key: key, value: value, uid: currentUserId }; if (status) { entry.status = status; } modules.setEntry(entry); if (chatroomEntry.isSendNotification) { modules.setBNotify(true); var msgModules = new RongIMLib.RongIMClient.Protobuf.UpStreamMessage(); var msg = new RongIMLib.ChrmKVNotificationMessage({ key: key, value: value, extra: extra, type: chatroomEntryOpt }); msgModules.setSessionId(RongIMLib.RongIMClient.MessageParams[msg.messageName].msgTag.getMessageTag()); msgModules.setClassname(RongIMLib.RongIMClient.MessageParams[msg.messageName].objectName); msgModules.setContent(msg.encode()); modules.setNotification(msgModules); // 默认设置为 聊天室消息 modules.setType(RongIMLib.ConversationType.CHATROOM); } RongIMLib.RongIMClient.bridge.queryMsg(topic, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), chatroomId, { onSuccess: function (ret) { var currentUserId = RongIMLib.RongIMClient.getInstance().getCurrentUserId(); RongIMLib.ChrmKVHandler.setEntry(chatroomId, chatroomEntry, status, currentUserId); setTimeout(function () { callback.onSuccess(!!ret); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }, 'ChrmOutput'); }; ServerDataProvider.prototype.getChatroomEntry = function (chatroomId, key, callback) { var value = RongIMLib.ChrmKVHandler.getEntityValue(chatroomId, key); setTimeout(function () { if (RongIMLib.RongUtil.isEmpty(value)) { callback.onError(RongIMLib.ErrorCode.CHATROOM_KEY_NOT_EXIST); } else { callback.onSuccess(value); } }); }; ServerDataProvider.prototype.getAllChatroomEntries = function (chatroomId, callback) { setTimeout(function () { var entries = RongIMLib.ChrmKVHandler.getAllEntityValue(chatroomId); callback.onSuccess(entries); }); }; ServerDataProvider.prototype.pullChatroomEntry = function (chatroomId, time, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.QueryChrmKV(); modules.setTimestamp(time); RongIMLib.RongIMClient.bridge.queryMsg('pullKV', RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), chatroomId, { onSuccess: function (data) { setTimeout(function () { callback.onSuccess(data); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }, "ChrmKVOutput"); }; ServerDataProvider.prototype.setMessageStatus = function (conversationType, targetId, timestamp, status, callback) { setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.addToBlacklist = function (userId, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.Add2BlackListInput(); modules.setUserId(userId); RongIMLib.RongIMClient.bridge.queryMsg(21, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.getBlacklist = function (callback) { var modules = new RongIMLib.RongIMClient.Protobuf.QueryBlackListInput(); modules.setNothing(1); RongIMLib.RongIMClient.bridge.queryMsg(23, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (list) { setTimeout(function () { callback.onSuccess(list); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }, "QueryBlackListOutput"); }; ServerDataProvider.prototype.getBlacklistStatus = function (userId, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.BlackListStatusInput(); modules.setUserId(userId); RongIMLib.RongIMClient.bridge.queryMsg(24, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function (status) { setTimeout(function () { callback.onSuccess(RongIMLib.BlacklistStatus[status]); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.removeFromBlacklist = function (userId, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RemoveFromBlackListInput(); modules.setUserId(userId); RongIMLib.RongIMClient.bridge.queryMsg(22, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.getFileToken = function (fileType, callback) { if (!(/(1|2|3|4)/.test(fileType.toString()))) { setTimeout(function () { callback.onError(RongIMLib.ErrorCode.QNTKN_FILETYPE_ERROR); }); return; } var modules = new RongIMLib.RongIMClient.Protobuf.GetQNupTokenInput(); modules.setType(fileType); RongIMLib.RongIMClient.bridge.queryMsg(30, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (data) { setTimeout(function () { callback.onSuccess(data); }); }, onError: function (errcode) { setTimeout(function () { callback.onError(errcode); }); } }, "GetQNupTokenOutput"); }; ServerDataProvider.prototype.getFileUrl = function (fileType, fileName, oriName, callback) { if (!(/(1|2|3|4)/.test(fileType.toString()))) { setTimeout(function () { callback.onError(RongIMLib.ErrorCode.QNTKN_FILETYPE_ERROR); }); return; } var modules = new RongIMLib.RongIMClient.Protobuf.GetQNdownloadUrlInput(); modules.setType(fileType); modules.setKey(fileName); if (oriName) { modules.setFileName(oriName); } RongIMLib.RongIMClient.bridge.queryMsg(31, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (data) { setTimeout(function () { callback.onSuccess(data); }); }, onError: function (errcode) { setTimeout(function () { callback.onError(errcode); }); } }, "GetQNdownloadUrlOutput"); }; ServerDataProvider.prototype.getPullSetting = function (callback) { var modules = new RongIMLib.RongIMClient.Protobuf.PullUserSettingInput(); var version = parseInt(RongIMLib.RongIMClient.sdkver); modules.setVersion(version); RongIMLib.RongIMClient.bridge.queryMsg('pullUS', RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (result) { result = result || {}; result.version = RongIMLib.MessageUtil.int64ToTimestamp(result.version); setTimeout(function () { callback.onSuccess(result); }); }, onError: function (errcode) { setTimeout(function () { callback.onError(errcode); }); } }, 'PullUserSettingOutput'); }; ServerDataProvider.prototype.setOfflineMessageDuration = function (duration, callback) { this.getPullSetting({ onSuccess: function (result) { /** * GetQNupTokenOutput 第一位为 int64, 第二位为 string, 与设置离线消息一致 * 为避免修改 Protobuf 带来的更新成本. 仅复用, 不重新命名 */ var modules = new RongIMLib.RongIMClient.Protobuf.GetQNupTokenOutput(); var version = result.version; modules.setDeadline(version); modules.setToken(duration + ''); RongIMLib.RongIMClient.bridge.queryMsg('setOfflineMsgDur', RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (data) { setTimeout(function () { callback.onSuccess(data); }); }, onError: function (errcode) { setTimeout(function () { callback.onError(errcode); }); } }); }, onError: callback.onError }); }; /* methodType 1 : 多客服(客服后台使用); 2 : 消息撤回 params.userIds : 定向消息接收者 */ ServerDataProvider.prototype.sendMessage = function (conversationType, targetId, messageContent, sendCallback, mentiondMsg, pushText, appData, methodType, params) { if (!RongIMLib.Bridge._client.channel) { setTimeout(function () { sendCallback.onError(RongIMLib.ErrorCode.RC_NET_UNAVAILABLE, null); }); return; } if (!RongIMLib.Bridge._client.channel.socket.socket.connected) { setTimeout(function () { sendCallback.onError(RongIMLib.ErrorCode.TIMEOUT, null); }); throw new Error("connect is timeout! postion:sendMessage"); } var isGroup = (conversationType == RongIMLib.ConversationType.DISCUSSION || conversationType == RongIMLib.ConversationType.GROUP); var modules = new RongIMLib.RongIMClient.Protobuf.UpStreamMessage(); if (mentiondMsg && isGroup) { modules.setSessionId(7); } else { modules.setSessionId(RongIMLib.RongIMClient.MessageParams[messageContent.messageName].msgTag.getMessageTag()); } pushText && modules.setPushText(pushText); appData && modules.setAppData(appData); if (isGroup && messageContent.messageName == RongIMLib.RongIMClient.MessageType["ReadReceiptResponseMessage"]) { var rspMsg = messageContent; if (rspMsg.receiptMessageDic) { var ids = []; for (var key in rspMsg.receiptMessageDic) { ids.push(key); } modules.setUserId(ids); } } if (isGroup && messageContent.messageName == RongIMLib.RongIMClient.MessageType["SyncReadStatusMessage"]) { modules.setUserId(RongIMLib.Bridge._client.userId); } params = params || {}; var userIds = params.userIds; if (userIds) { modules.setUserId(userIds); } var flag = 0; if (params.isPush || params.isVoipPush) { flag |= 0x01; } if (params.isFilerWhiteBlacklist) { flag |= 0x02; } modules.setConfigFlag(flag); modules.setClassname(RongIMLib.RongIMClient.MessageParams[messageContent.messageName].objectName); modules.setContent(messageContent.encode()); var content = modules.toArrayBuffer(); if (Object.prototype.toString.call(content) == "[object ArrayBuffer]") { content = [].slice.call(new Int8Array(content)); } var me = this, msg = new RongIMLib.Message(); var c = this.getConversation(conversationType, targetId); if (RongIMLib.RongIMClient.MessageParams[messageContent.messageName].msgTag.getMessageTag() == 3) { if (!c) { c = RongIMLib.RongIMClient.getInstance().createConversation(conversationType, targetId, ""); } c.sentTime = new Date().getTime(); c.sentStatus = RongIMLib.SentStatus.SENDING; c.senderUserName = ""; c.senderUserId = RongIMLib.Bridge._client.userId; c.notificationStatus = RongIMLib.ConversationNotificationStatus.DO_NOT_DISTURB; c.latestMessage = msg; c.unreadMessageCount = 0; RongIMLib.RongIMClient._dataAccessProvider.addConversation(c, { onSuccess: function (data) { } }); } RongIMLib.RongIMClient._memoryStore.converStore = c; msg.content = messageContent; msg.conversationType = conversationType; msg.senderUserId = RongIMLib.Bridge._client.userId; msg.objectName = RongIMLib.RongIMClient.MessageParams[messageContent.messageName].objectName; msg.targetId = targetId; msg.sentTime = new Date().getTime(); msg.messageDirection = RongIMLib.MessageDirection.SEND; msg.sentStatus = RongIMLib.SentStatus.SENT; msg.messageType = messageContent.messageName; RongIMLib.RongIMClient.bridge.pubMsg(conversationType.valueOf(), content, targetId, { onSuccess: function (data) { if (data && data.timestamp) { RongIMLib.RongIMClient._memoryStore.lastReadTime.set('converST_' + RongIMLib.Bridge._client.userId + conversationType + targetId, data.timestamp); } if ((conversationType == RongIMLib.ConversationType.DISCUSSION || conversationType == RongIMLib.ConversationType.GROUP) && messageContent.messageName == RongIMLib.RongIMClient.MessageType["ReadReceiptRequestMessage"]) { var reqMsg = msg.content; var sentkey = RongIMLib.Bridge._client.userId + reqMsg.messageUId + "SENT"; RongIMLib.RongIMClient._storageProvider.setItem(sentkey, JSON.stringify({ count: 0, dealtime: data.timestamp, userIds: {} })); } if (RongIMLib.RongIMClient.MessageParams[msg.messageType].msgTag.getMessageTag() == 3) { var cacheConversation = RongIMLib.RongIMClient._memoryStore.converStore; cacheConversation.sentStatus = msg.sentStatus; cacheConversation.latestMessage = msg; me.updateConversation(cacheConversation); var Conversation = RongIMLib.RongIMClient._dataAccessProvider.Conversation; Conversation._notify(RongIMLib.RongIMClient._memoryStore.conversationList); RongIMLib.RongIMClient._dataAccessProvider.addMessage(conversationType, targetId, msg, { onSuccess: function (ret) { msg = ret; msg.messageUId = data.messageUId; msg.sentTime = data.timestamp; msg.sentStatus = RongIMLib.SentStatus.SENT; msg.messageId = data.messageId; RongIMLib.RongIMClient._dataAccessProvider.updateMessage(msg); }, onError: function () { } }); } setTimeout(function () { cacheConversation && me.updateConversation(cacheConversation); msg.sentTime = data.timestamp; msg.messageUId = data.messageUId; sendCallback.onSuccess(msg); }); }, onError: function (errorCode, _msg) { msg.sentStatus = RongIMLib.SentStatus.FAILED; if (_msg) { msg.messageUId = _msg.messageUId; msg.sentTime = _msg.sentTime; } if (RongIMLib.RongIMClient.MessageParams[msg.messageType].msgTag.getMessageTag() == 3) { RongIMLib.RongIMClient._memoryStore.converStore.latestMessage = msg; } RongIMLib.RongIMClient._dataAccessProvider.addMessage(conversationType, targetId, msg, { onSuccess: function (ret) { msg.messageId = ret.messageId; RongIMLib.RongIMClient._dataAccessProvider.updateMessage(msg); }, onError: function () { } }); setTimeout(function () { sendCallback.onError(errorCode, msg); }); } }, null, methodType); sendCallback.onBefore && sendCallback.onBefore(RongIMLib.MessageIdHandler.messageId); msg.messageId = RongIMLib.MessageIdHandler.messageId + ""; }; ServerDataProvider.prototype.setConnectionStatusListener = function (listener) { if (RongIMLib.RongUtil.isObject(listener) && RongIMLib.RongUtil.isFunction(listener.onChanged)) { RongIMLib.RongIMClient.statusListeners.push(listener.onChanged); } }; ServerDataProvider.prototype.setOnReceiveMessageListener = function (listener) { if (RongIMLib.RongUtil.isObject(listener) && RongIMLib.RongUtil.isFunction(listener.onReceived)) { RongIMLib.RongIMClient.messageListeners.push(listener.onReceived); } }; ServerDataProvider.prototype.registerMessageType = function (messageType, objectName, messageTag, messageContent, searchProps) { if (!messageType) { throw new Error("messageType can't be empty,postion -> registerMessageType"); } if (!objectName) { throw new Error("objectName can't be empty,postion -> registerMessageType"); } if (Object.prototype.toString.call(messageContent) == "[object Array]") { var regMsg = RongIMLib.ModelUtil.modleCreate(messageContent, messageType); RongIMLib.RongIMClient.RegisterMessage[messageType] = regMsg; } else if (Object.prototype.toString.call(messageContent) == "[object Function]" || Object.prototype.toString.call(messageContent) == "[object Object]") { if (!messageContent.encode) { throw new Error("encode method has not realized or messageName is undefined-> registerMessageType"); } if (!messageContent.decode) { throw new Error("decode method has not realized -> registerMessageType"); } } else { throw new Error("The index of 3 parameter was wrong type must be object or function or array-> registerMessageType"); } registerMessageTypeMapping[objectName] = messageType; }; ServerDataProvider.prototype.registerMessageTypes = function (messages) { var types = []; var getProtos = function (proto) { var protos = []; for (var p in proto) { protos.push(p); } return protos; }; //转换消息为自定义消息参数格式 for (var name in messages) { var message = messages[name]; var proto = message.proto; var protos = getProtos(proto); var flag = message.flag || 3; var tag = RongIMLib.MessageTag.getTagByStatus(flag); flag = new RongIMLib.MessageTag(tag.isCounted, tag.isPersited); types.push({ type: name, name: message.name, flag: flag, protos: protos }); } var register = function (message) { var type = message.type; var name = message.name; var flag = message.flag; var protos = message.protos; RongIMLib.RongIMClient.registerMessageType(type, name, flag, protos); }; for (var i = 0, len = types.length; i < len; i++) { var message = types[i]; register(message); } }; ServerDataProvider.prototype.addConversation = function (conversation, callback) { var isAdd = true; for (var i = 0, len = RongIMLib.RongIMClient._memoryStore.conversationList.length; i < len; i++) { if (RongIMLib.RongIMClient._memoryStore.conversationList[i].conversationType === conversation.conversationType && RongIMLib.RongIMClient._memoryStore.conversationList[i].targetId === conversation.targetId) { // RongIMClient._memoryStore.conversationList[i] = conversation; RongIMLib.RongIMClient._memoryStore.conversationList.unshift(RongIMLib.RongIMClient._memoryStore.conversationList.splice(i, 1)[0]); isAdd = false; break; } } if (isAdd) { RongIMLib.RongIMClient._memoryStore.conversationList.unshift(conversation); } callback && callback.onSuccess(true); }; ServerDataProvider.prototype.updateConversation = function (conversation) { var conver; for (var i = 0, len = RongIMLib.RongIMClient._memoryStore.conversationList.length; i < len; i++) { var item = RongIMLib.RongIMClient._memoryStore.conversationList[i]; if (conversation.conversationType === item.conversationType && conversation.targetId === item.targetId) { conversation.conversationTitle && (item.conversationTitle = conversation.conversationTitle); conversation.senderUserName && (item.senderUserName = conversation.senderUserName); conversation.senderPortraitUri && (item.senderPortraitUri = conversation.senderPortraitUri); conversation.latestMessage && (item.latestMessage = conversation.latestMessage); conversation.sentStatus && (item.sentStatus = conversation.sentStatus); break; } } return conver; }; ServerDataProvider.prototype.removeConversation = function (conversationType, targetId, callback) { var mod = new RongIMLib.RongIMClient.Protobuf.RelationsInput(); mod.setType(conversationType); RongIMLib.RongIMClient.bridge.queryMsg(27, RongIMLib.MessageUtil.ArrayForm(mod.toArrayBuffer()), targetId, { onSuccess: function () { var isRemoved = false; var conversations = RongIMLib.RongIMClient._memoryStore.conversationList; var len = conversations.length; for (var i = 0; i < len; i++) { if (conversations[i].conversationType == conversationType && targetId == conversations[i].targetId) { conversations.splice(i, 1); isRemoved = true; break; } } isRemoved && RongIMLib.RongIMClient._dataAccessProvider.Conversation._notify(RongIMLib.RongIMClient._memoryStore.conversationList); callback.onSuccess(true); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.getMessage = function (messageId, callback) { callback.onSuccess(new RongIMLib.Message()); }; ServerDataProvider.prototype.addMessage = function (conversationType, targetId, message, callback) { if (callback) { callback.onSuccess(message); } }; ServerDataProvider.prototype.removeMessage = function (conversationType, targetId, messages, callback) { RongIMLib.RongIMClient.getInstance().deleteRemoteMessages(conversationType, targetId, messages, callback); }; ServerDataProvider.prototype.removeLocalMessage = function (conversationType, targetId, timestamps, callback) { callback.onSuccess(true); }; ServerDataProvider.prototype.updateMessage = function (message, callback) { if (callback) { callback.onSuccess(message); } }; ServerDataProvider.prototype.deleteRemoteMessages = function (conversationType, targetId, messages, callback) { if (!RongIMLib.RongIMClient.Protobuf.DeleteMsgInput) { throw new Error('SDK Protobuf version is too low'); } var modules = new RongIMLib.RongIMClient.Protobuf.DeleteMsgInput(); var msgs = []; RongIMLib.RongUtil.forEach(messages, function (msg) { msgs.push({ msgId: msg.messageUId, msgDataTime: msg.sentTime, direct: msg.messageDirection }); }); modules.setType(conversationType); modules.setConversationId(targetId); modules.setMsgs(msgs); RongIMLib.RongIMClient.bridge.queryMsg('delMsg', RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), targetId, { onSuccess: function (result) { callback.onSuccess(result); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }, 'DeleteMsgOutput'); }; ServerDataProvider.prototype.clearRemoteHistoryMessages = function (params, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.CleanHisMsgInput(); var conversationType = params.conversationType; var _topic = { 1: 'cleanPMsg', 2: 'cleanDMsg', 3: 'cleanGMsg', 5: 'cleanCMsg', 6: 'cleanSMsg' }; var topic = _topic[conversationType]; if (!topic) { callback.onError(RongIMLib.ErrorCode.CLEAR_HIS_TYPE_ERROR); return; } var timestamp = params.timestamp; if (typeof timestamp != 'number') { callback.onError(RongIMLib.ErrorCode.CLEAR_HIS_TIME_ERROR); return; } modules.setDataTime(timestamp); var targetId = params.targetId; modules.setTargetId(targetId); RongIMLib.RongIMClient.bridge.queryMsg(topic, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), targetId, { onSuccess: function (result) { callback.onSuccess(!result); }, onError: function (error) { // error 1 历史消息云存储没有开通、传入时间大于服务器时间 清除失败,1 与其他错误码冲突,所以自定义错误码返回 if (error == 1) { error = RongIMLib.ErrorCode.CLEAR_HIS_ERROR; } setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.clearHistoryMessages = function (params, callback) { this.clearRemoteHistoryMessages(params, callback); }; // 兼容老版本 ServerDataProvider.prototype.clearMessages = function (conversationType, targetId, callback) { }; ServerDataProvider.prototype.updateMessages = function (conversationType, targetId, key, value, callback) { var me = this; if (key == "readStatus") { if (RongIMLib.RongIMClient._memoryStore.conversationList.length > 0) { me.getConversationList({ onSuccess: function (list) { Array.forEach(list, function (conver) { if (conver.conversationType == conversationType && conver.targetId == targetId) { conver.unreadMessageCount = 0; } }); }, onError: function (errorCode) { setTimeout(function () { callback.onError(errorCode); }); } }, null); } } setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.getConversation = function (conversationType, targetId, callback) { var conver = null; for (var i = 0, len = RongIMLib.RongIMClient._memoryStore.conversationList.length; i < len; i++) { if (RongIMLib.RongIMClient._memoryStore.conversationList[i].conversationType == conversationType && RongIMLib.RongIMClient._memoryStore.conversationList[i].targetId == targetId) { conver = RongIMLib.RongIMClient._memoryStore.conversationList[i]; if (RongIMLib.RongUtil.supportLocalStorage()) { // var count = RongIMClient._storageProvider.getItem("cu" + Bridge._client.userId + conversationType + targetId); var count = RongIMLib.UnreadCountHandler.get(conversationType, targetId); if (conver.unreadMessageCount == 0) { conver.unreadMessageCount = Number(count); } } } } setTimeout(function () { callback && callback.onSuccess(conver); }); return conver; }; ServerDataProvider.prototype.filterConversations = function (types, list) { var conversaions = []; RongIMLib.RongUtil.forEach(types, function (type) { RongIMLib.RongUtil.forEach(list, function (conversation) { if (conversation.conversationType == type) { conversaions.push(conversation); } }); }); return conversaions; }; ServerDataProvider.prototype.getConversationList = function (callback, conversationTypes, count, isHidden) { var that = this; var isSync = RongIMLib.RongIMClient._memoryStore.isSyncRemoteConverList; var list = RongIMLib.RongIMClient._memoryStore.conversationList; var isLocalInclude = list.length > count; if (!isSync && isLocalInclude) { setTimeout(function () { var localList = list.slice(0, count); if (conversationTypes) { localList = that.filterConversations(conversationTypes, localList); } callback.onSuccess(localList); }); return; } RongIMLib.RongIMClient.getInstance().getRemoteConversationList({ onSuccess: function (list) { if (RongIMLib.RongUtil.supportLocalStorage()) { Array.forEach(RongIMLib.RongIMClient._memoryStore.conversationList, function (item) { // var count = RongIMClient._storageProvider.getItem("cu" + Bridge._client.userId + item.conversationType + item.targetId); var count = RongIMLib.UnreadCountHandler.get(item.conversationType, item.targetId); if (item.unreadMessageCount == 0) { item.unreadMessageCount = Number(count); } }); } RongIMLib.RongIMClient._memoryStore.isSyncRemoteConverList = false; setTimeout(function () { callback.onSuccess(list); }); }, onError: function (errorcode) { setTimeout(function () { callback.onError(errorcode); }); } }, conversationTypes, count, isHidden); }; ServerDataProvider.prototype.clearCache = function () { var memoryStore = RongIMLib.RongIMClient._memoryStore || {}; memoryStore.conversationList = []; memoryStore.isSyncRemoteConverList = true; }; ServerDataProvider.prototype.clearConversations = function (conversationTypes, callback) { Array.forEach(conversationTypes, function (conversationType) { Array.forEach(RongIMLib.RongIMClient._memoryStore.conversationList, function (conver) { if (conversationType == conver.conversationType) { RongIMLib.RongIMClient.getInstance().removeConversation(conver.conversationType, conver.targetId, { onSuccess: function () { }, onError: function () { } }); } }); }); setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.setMessageContent = function (messageId, content, objectname) { }; ; ServerDataProvider.prototype.setMessageSearchField = function (messageId, content, searchFiles) { }; ; ServerDataProvider.prototype.getHistoryMessages = function (conversationType, targetId, timestamp, count, callback, objectname, order) { var config = { objectname: objectname, order: order }; RongIMLib.RongIMClient.getInstance().getRemoteHistoryMessages(conversationType, targetId, timestamp, count, callback, config); }; ServerDataProvider.prototype.getTotalUnreadCount = function (callback, conversationTypes) { var count = RongIMLib.UnreadCountHandler.getAll(conversationTypes); callback.onSuccess(count); }; ServerDataProvider.prototype.getConversationUnreadCount = function (conversationTypes, callback) { var count = 0; Array.forEach(conversationTypes, function (converType) { Array.forEach(RongIMLib.RongIMClient._memoryStore.conversationList, function (conver) { if (conver.conversationType == converType) { count += conver.unreadMessageCount; } }); }); setTimeout(function () { callback.onSuccess(count); }); }; //由于 Web 端未读消息数按会话统计,撤回消息会导致未读数不准确,提供设置未读数接口,桌面版不实现此方法 ServerDataProvider.prototype.setUnreadCount = function (conversationType, targetId, count, sentTime) { sentTime = sentTime || new Date().getTime(); RongIMLib.UnreadCountHandler.set(conversationType, targetId, count, sentTime); }; ServerDataProvider.prototype.getUnreadCount = function (conversationType, targetId, callback) { var unreadCount = RongIMLib.UnreadCountHandler.get(conversationType, targetId); setTimeout(function () { callback.onSuccess(unreadCount || 0); }); }; ServerDataProvider.prototype.cleanMentioneds = function (conver) { if (conver) { conver.mentionedMsg = null; var targetId = conver.targetId; var conversationType = conver.conversationType; var mentioneds = RongIMLib.RongIMClient._storageProvider.getItem("mentioneds_" + RongIMLib.Bridge._client.userId + '_' + conversationType + '_' + targetId); if (mentioneds) { var info = JSON.parse(mentioneds); delete info[conversationType + "_" + targetId]; if (!RongIMLib.MessageUtil.isEmpty(info)) { RongIMLib.RongIMClient._storageProvider.setItem("mentioneds_" + RongIMLib.Bridge._client.userId + '_' + conversationType + '_' + targetId, JSON.stringify(info)); } else { RongIMLib.RongIMClient._storageProvider.removeItem("mentioneds_" + RongIMLib.Bridge._client.userId + '_' + conversationType + '_' + targetId); } } } }; ServerDataProvider.prototype.clearUnreadCountByTimestamp = function (conversationType, targetId, timestamp, callback) { setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.clearUnreadCount = function (conversationType, targetId, callback) { var me = this; // RongIMClient._storageProvider.removeItem("cu" + Bridge._client.userId + conversationType + targetId); RongIMLib.UnreadCountHandler.remove(conversationType, targetId); this.getConversation(conversationType, targetId, { onSuccess: function (conver) { conver = conver || new RongIMLib.Conversation(); var isNotifyConversation = conver.unreadMessageCount; if (conver) { conver.unreadMessageCount = 0; me.cleanMentioneds(conver); } setTimeout(function () { callback.onSuccess(true); isNotifyConversation && RongIMLib.RongIMClient._dataAccessProvider.Conversation._notify(RongIMLib.RongIMClient._memoryStore.conversationList); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.clearTotalUnreadCount = function (callback) { var list = RongIMLib.RongIMClient._memoryStore.conversationList; var me = this; var isNotifyConversation = false; if (list) { // 清除 mentioneds、清除 list 中的 unreadMessageCount for (var i = 0; i < list.length; i++) { var conver = list[i]; if (conver) { isNotifyConversation = conver.unreadMessageCount ? true : isNotifyConversation; conver.unreadMessageCount = 0; me.cleanMentioneds(conver); } } } RongIMLib.UnreadCountHandler.clear(); setTimeout(function () { callback.onSuccess(true); isNotifyConversation && RongIMLib.RongIMClient._dataAccessProvider.Conversation._notify(RongIMLib.RongIMClient._memoryStore.conversationList); }); }; ServerDataProvider.prototype.setConversationToTop = function (conversationType, targetId, isTop, callback) { var me = this; this.getConversation(conversationType, targetId, { onSuccess: function (conver) { conver.isTop = isTop; me.addConversation(conver, callback); setTimeout(function () { callback.onSuccess(true); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.getConversationNotificationStatus = function (params, callback) { var targetId = params.targetId; var conversationType = params.conversationType; var notification = RongIMLib.RongIMClient._memoryStore.notification; var getKey = function () { return conversationType + '_' + targetId; }; var key = getKey(); var status = notification[key]; if (typeof status == 'number') { callback.onSuccess(status); return; } var topics = { 1: 'qryPPush', 3: 'qryDPush' }; var topic = topics[conversationType]; if (!topic) { var error = 8001; callback.onError(error); return; } var modules = new RongIMLib.RongIMClient.Protobuf.BlockPushInput(); modules.setBlockeeId(targetId); var userId = RongIMLib.Bridge._client.userId; var success = function (status) { notification[key] = status; setTimeout(function () { callback.onSuccess(status); }); }; RongIMLib.RongIMClient.bridge.queryMsg(topic, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function (status) { success(status); }, onError: function (e) { if (e == 1) { success(e); } else { setTimeout(function () { callback.onError(e); }); } } }); }; ServerDataProvider.prototype.setConversationNotificationStatus = function (params, callback) { var conversationType = params.conversationType; var targetId = params.targetId; var status = params.status; var getKey = function () { return conversationType + '_' + status; }; var topics = { '1_1': 'blkPPush', '3_1': 'blkDPush', '1_0': 'unblkPPush', '3_0': 'unblkDPush' }; var key = getKey(); var notification = RongIMLib.RongIMClient._memoryStore.notification; notification[key] = status; var topic = topics[key]; if (!topic) { var error = 8001; setTimeout(function () { callback.onError(error); }); return; } var modules = new RongIMLib.RongIMClient.Protobuf.BlockPushInput(); modules.setBlockeeId(targetId); var userId = RongIMLib.Bridge._client.userId; RongIMLib.RongIMClient.bridge.queryMsg(topic, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function (status) { setTimeout(function () { callback.onSuccess(status); }); }, onError: function (e) { setTimeout(function () { callback.onError(e); }); } }); }; ServerDataProvider.prototype.getUserStatus = function (userId, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.GetUserStatusInput(); userId = RongIMLib.Bridge._client.userId; RongIMLib.RongIMClient.bridge.queryMsg(35, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function (status) { status = RongIMLib.RongInnerTools.convertUserStatus(status); setTimeout(function () { callback.onSuccess(status); }); }, onError: function (e) { setTimeout(function () { callback.onError(e); }); } }, 'GetUserStatusOutput'); // callback.onSuccess(new UserStatus()); }; ServerDataProvider.prototype.setUserStatus = function (status, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.SetUserStatusInput(); var userId = RongIMLib.Bridge._client.userId; if (status) { modules.setStatus(status); } RongIMLib.RongIMClient.bridge.queryMsg(36, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function (status) { setTimeout(function () { callback.onSuccess(true); }); }, onError: function (e) { setTimeout(function () { callback.onError(e); }); } }, 'SetUserStatusOutput'); }; ServerDataProvider.prototype.subscribeUserStatus = function (userIds, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.SubUserStatusInput(); var userId = RongIMLib.Bridge._client.userId; modules.setUserid(userIds); RongIMLib.RongIMClient.bridge.queryMsg(37, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function (status) { setTimeout(function () { callback && callback.onSuccess(true); }); }, onError: function (e) { setTimeout(function () { callback && callback.onError(e); }); } }, 'SubUserStatusOutput'); }; ServerDataProvider.prototype.setUserStatusListener = function (params, callback) { RongIMLib.RongIMClient.userStatusListener = callback; var userIds = params.userIds || []; if (userIds.length) { RongIMLib.RongIMClient._dataAccessProvider.subscribeUserStatus(userIds); } }; ServerDataProvider.prototype.clearListeners = function () { }; ServerDataProvider.prototype.setServerInfo = function (info) { }; ServerDataProvider.prototype.getUnreadMentionedMessages = function (conversationType, targetId) { return null; }; ServerDataProvider.prototype.setConversationHidden = function (conversationType, targetId, isHidden) { }; ServerDataProvider.prototype.setMessageExtra = function (messageId, value, callback) { setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.setMessageReceivedStatus = function (messageId, receivedStatus, callback) { setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.setMessageSentStatus = function (messageId, sentStatus, callback) { setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.getAllConversations = function (callback) { setTimeout(function () { callback.onSuccess([]); }); }; ServerDataProvider.prototype.getConversationByContent = function (keywords, callback) { setTimeout(function () { callback.onSuccess([]); }); }; ServerDataProvider.prototype.getMessagesFromConversation = function (conversationType, targetId, keywords, callback) { setTimeout(function () { callback.onSuccess([]); }); }; ServerDataProvider.prototype.searchConversationByContent = function (keyword, callback, conversationTypes) { setTimeout(function () { callback.onSuccess([]); }); }; ServerDataProvider.prototype.searchMessageByContent = function (conversationType, targetId, keyword, timestamp, count, total, callback) { setTimeout(function () { callback.onSuccess([]); }); }; ServerDataProvider.prototype.getDelaTime = function () { return RongIMLib.RongIMClient._memoryStore.deltaTime; }; ServerDataProvider.prototype.getCurrentConnectionStatus = function () { var client = RongIMLib.Bridge._client || {}; var channel = client.channel || {}; var status = RongIMLib.ConnectionStatus.CONNECTION_CLOSED; if (typeof channel.connectionStatus == 'number') { status = channel.connectionStatus; } return status; }; ServerDataProvider.prototype.getAgoraDynamicKey = function (engineType, channelName, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.VoipDynamicInput(); modules.setEngineType(engineType); modules.setChannelName(channelName); RongIMLib.RongIMClient.bridge.queryMsg(32, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (result) { setTimeout(function () { callback.onSuccess(result); }); }, onError: function (errorCode) { setTimeout(function () { callback.onError(errorCode); }); } }, "VoipDynamicOutput"); }; ServerDataProvider.prototype.setDeviceInfo = function (deviceId) { }; ServerDataProvider.prototype.setEnvironment = function (isPrivate) { }; ServerDataProvider.prototype.clearData = function () { return true; }; ServerDataProvider.prototype.getPublicServiceProfile = function (publicServiceType, publicServiceId, callback) { var profile = RongIMLib.RongIMClient._memoryStore.publicServiceMap.get(publicServiceType, publicServiceId); setTimeout(function () { callback.onSuccess(profile); }); }; ServerDataProvider.prototype.getRemotePublicServiceList = function (callback, pullMessageTime) { if (RongIMLib.RongIMClient._memoryStore.depend.openMp) { var modules = new RongIMLib.RongIMClient.Protobuf.PullMpInput(), self = this; if (!pullMessageTime) { modules.setTime(0); } else { modules.setTime(pullMessageTime); } modules.setMpid(""); RongIMLib.RongIMClient.bridge.queryMsg(28, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (data) { //TODO 找出最大时间 // self.lastReadTime.set(conversationType + targetId, MessageUtil.int64ToTimestamp(data.syncTime)); RongIMLib.RongIMClient._memoryStore.publicServiceMap.publicServiceList.length = 0; RongIMLib.RongIMClient._memoryStore.publicServiceMap.publicServiceList = data; setTimeout(function () { callback && callback.onSuccess(data); }); }, onError: function (errorCode) { setTimeout(function () { callback && callback.onError(errorCode); }); } }, "PullMpOutput"); } }; ServerDataProvider.prototype.getRTCUserInfoList = function (room, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcQueryListInput(); // 1 是正序,2是倒序 modules.setOrder(2); RongIMLib.RongIMClient.bridge.queryMsg("rtcUData", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function (result) { var users = {}; var list = result.list; RongIMLib.RongUtil.forEach(list, function (item) { var userId = item.userId; var tmpData = {}; RongIMLib.RongUtil.forEach(item.userData, function (data) { var key = data.key; var value = data.value; tmpData[key] = value; }); users[userId] = tmpData; }); callback.onSuccess(users); }, onError: function (errorCode) { callback.onError(errorCode); } }, "RtcUserListOutput"); }; ServerDataProvider.prototype.getRTCUserList = function (room, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcQueryListInput(); modules.setOrder(2); RongIMLib.RongIMClient.bridge.queryMsg("rtcUList", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function (result) { callback.onSuccess({ users: result.list }); }, onError: function (errorCode) { callback.onError(errorCode); } }, "RtcUserListOutput"); }; ServerDataProvider.prototype.setRTCUserInfo = function (room, info, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcValueInfo(); modules.setKey(info.key); modules.setValue(info.value); RongIMLib.RongIMClient.bridge.queryMsg("rtcUPut", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function () { callback.onSuccess(true); }, onError: function (errorCode) { callback.onError(errorCode); } }); }; ServerDataProvider.prototype.removeRTCUserInfo = function (room, info, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcKeyDeleteInput(); var keys = info.keys || []; if (!RongIMLib.RongUtil.isArray(keys)) { keys = [keys]; } modules.setKey(keys); RongIMLib.RongIMClient.bridge.queryMsg("rtcUDel", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function () { callback.onSuccess(true); }, onError: function (errorCode) { callback.onError(errorCode); } }); }; ServerDataProvider.prototype.getRTCRoomInfo = function (room, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcQueryListInput(); modules.setOrder(2); RongIMLib.RongIMClient.bridge.queryMsg("rtcRInfo", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function (result) { var room = { id: result.roomId, total: result.userCount }; RongIMLib.RongUtil.forEach(result.roomData, function (data) { room[data.key] = data.value; }); callback.onSuccess(room); }, onError: function (errorCode) { callback.onError(errorCode); } }, "RtcRoomInfoOutput"); }; ServerDataProvider.prototype.setRTCRoomInfo = function (room, info, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcValueInfo(); modules.setKey(info.key); modules.setValue(info.value); RongIMLib.RongIMClient.bridge.queryMsg("rtcRPut", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function () { callback.onSuccess(true); }, onError: function (errorCode) { callback.onError(errorCode); } }); }; ServerDataProvider.prototype.removeRTCRoomInfo = function (room, info, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcKeyDeleteInput(); var keys = info.keys || []; if (!RongIMLib.RongUtil.isArray(keys)) { keys = [keys]; } modules.setKey(keys); RongIMLib.RongIMClient.bridge.queryMsg("rtcRDel", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function () { callback.onSuccess(true); }, onError: function (errorCode) { callback.onError(errorCode); } }); }; ServerDataProvider.prototype.joinRTCRoom = function (room, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcInput(); var mode = room.mode || 0; modules.setRoomType(mode); if (room.broadcastType) { modules.setBroadcastType(room.broadcastType); } RongIMLib.RongIMClient.bridge.queryMsg("rtcRJoin_data", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function (result) { var users = {}; var list = result.list, token = result.token, sessionId = result.sessionId; RongIMLib.RongUtil.forEach(list, function (item) { var userId = item.userId; var tmpData = {}; RongIMLib.RongUtil.forEach(item.userData, function (data) { var key = data.key; var value = data.value; tmpData[key] = value; }); users[userId] = tmpData; }); callback.onSuccess({ users: users, token: token, sessionId: sessionId }); }, onError: function (errorCode) { callback.onError(errorCode); } }, "RtcUserListOutput"); }; ServerDataProvider.prototype.quitRTCRoom = function (room, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.SetUserStatusInput(); RongIMLib.RongIMClient.bridge.queryMsg("rtcRExit", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function () { callback.onSuccess(true); }, onError: function (errorCode) { callback.onError(errorCode); } }); }; ServerDataProvider.prototype.RTCPing = function (room, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcInput(); var mode = room.mode || 0; modules.setRoomType(mode); if (room.broadcastType) { modules.setBroadcastType(room.broadcastType); } RongIMLib.RongIMClient.bridge.queryMsg("rtcPing", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, callback); }; ServerDataProvider.prototype.setRTCData = function (roomId, key, value, isInner, apiType, callback, message) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcSetDataInput(); modules.setInterior(isInner); modules.setTarget(apiType); modules.setKey(key); modules.setValue(value); message = message || {}; var name = message.name; var content = message.content; if (name) { modules.setObjectName(name); } if (content) { if (!RongIMLib.RongUtil.isString(content)) { content = JSON.stringify(content); } modules.setContent(content); } RongIMLib.RongIMClient.bridge.queryMsg("rtcSetData", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), roomId, callback, "RtcOutput"); }; ServerDataProvider.prototype.getRTCData = function (roomId, keys, isInner, apiType, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcDataInput(); modules.setInterior(isInner); modules.setTarget(apiType); modules.setKey(keys); RongIMLib.RongIMClient.bridge.queryMsg("rtcQryData", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), roomId, { onSuccess: function (result) { var props = {}; var list = result.outInfo; RongIMLib.RongUtil.forEach(list, function (item) { props[item.key] = item.value; }); callback.onSuccess(props); }, onError: callback.onError }, "RtcQryOutput"); }; ServerDataProvider.prototype.removeRTCData = function (roomId, keys, isInner, apiType, callback, message) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcDataInput(); modules.setInterior(isInner); modules.setTarget(apiType); modules.setKey(keys); message = message || {}; var name = message.name; var content = message.content; if (name) { modules.setObjectName(name); } if (content) { if (!RongIMLib.RongUtil.isString(content)) { content = JSON.stringify(content); } modules.setContent(content); } RongIMLib.RongIMClient.bridge.queryMsg("rtcDelData", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), roomId, callback, "RtcOutput"); }; ServerDataProvider.prototype.setRTCUserData = function (roomId, key, value, isInner, callback, message) { this.setRTCData(roomId, key, value, isInner, RongIMLib.RTCAPIType.PERSON, callback, message); }; ServerDataProvider.prototype.getRTCUserData = function (roomId, keys, isInner, callback, message) { this.getRTCData(roomId, keys, isInner, RongIMLib.RTCAPIType.PERSON, callback); }; ServerDataProvider.prototype.removeRTCUserData = function (roomId, keys, isInner, callback, message) { this.removeRTCData(roomId, keys, isInner, RongIMLib.RTCAPIType.PERSON, callback, message); }; ServerDataProvider.prototype.setRTCRoomData = function (roomId, key, value, isInner, callback, message) { this.setRTCData(roomId, key, value, isInner, RongIMLib.RTCAPIType.ROOM, callback, message); }; ServerDataProvider.prototype.getRTCRoomData = function (roomId, keys, isInner, callback, message) { this.getRTCData(roomId, keys, isInner, RongIMLib.RTCAPIType.ROOM, callback); }; ServerDataProvider.prototype.removeRTCRoomData = function (roomId, keys, isInner, callback, message) { this.removeRTCData(roomId, keys, isInner, RongIMLib.RTCAPIType.ROOM, callback, message); }; // 信令 SDK 新增 ServerDataProvider.prototype.setRTCOutData = function (roomId, data, type, callback, message) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcSetOutDataInput(); modules.setTarget(type); if (!RongIMLib.RongUtil.isArray(data)) { data = [data]; } for (var i = 0; i < data.length; i++) { var item = data[i]; if (item.key) { item.key = item.key.toString(); } if (item.value) { item.value = item.value.toString(); } } modules.setValueInfo(data); message = message || {}; var name = message.name; var content = message.content; if (name) { modules.setObjectName(name); } if (content) { if (!RongIMLib.RongUtil.isString(content)) { content = JSON.stringify(content); } modules.setContent(content); } RongIMLib.RongIMClient.bridge.queryMsg("rtcSetOutData", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), roomId, callback, "RtcOutput"); }; // 信令 SDK 新增 ServerDataProvider.prototype.getRTCOutData = function (roomId, userIds, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcQryUserOutDataInput(); modules.setUserId(userIds); RongIMLib.RongIMClient.bridge.queryMsg("rtcQryUserOutData", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), roomId, callback, "RtcUserOutDataOutput"); }; ServerDataProvider.prototype.getNavi = function () { var navi = RongIMLib.RongIMClient._storageProvider.getItem("fullnavi") || "{}"; return JSON.parse(navi); }; ServerDataProvider.prototype.getRTCToken = function (room, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcInput(); var mode = room.mode || 0; modules.setRoomType(mode); if (room.broadcastType) { modules.setBroadcastType(room.broadcastType); } RongIMLib.RongIMClient.bridge.queryMsg("rtcToken", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function (result) { callback.onSuccess(result); }, onError: function (errorCode) { callback.onError(errorCode); } }, "RtcTokenOutput"); }; ServerDataProvider.prototype.setRTCState = function (room, content, callback) { // MCFollowInput 为 PB 复用,字段:一个必传 string(第一位) var modules = new RongIMLib.RongIMClient.Protobuf.MCFollowInput(); var report = content.report; modules.setId(report); RongIMLib.RongIMClient.bridge.queryMsg("rtcUserState", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function (result) { callback.onSuccess(result); }, onError: function (errorCode) { callback.onError(errorCode); } }, "RtcOutput"); }; return ServerDataProvider; })(); RongIMLib.ServerDataProvider = ServerDataProvider; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var VCDataProvider = (function () { function VCDataProvider(addon) { this.Conversation = { watcher: new RongIMLib.Observer(), watch: function (_watcher) { }, unwatch: function (_watcher) { }, _notify: function (conversationList) { } }; // C++ 需要的 SDK 版本号 this.version = '2.8.27'; this.userId = ""; this.useConsole = false; this.appKey = ""; this.token = ""; this.connectionStatus = RongIMLib.ConnectionStatus.DISCONNECTED; this.addon = addon; } VCDataProvider.prototype.init = function (appKey, config) { this.appKey = appKey; this.useConsole && console.log("init"); config = config || {}; config.version = this.version; var sdkInfo = this.addon.initWithAppkey(appKey, config.dbPath, config); if (sdkInfo) { sdkInfo = JSON.parse(sdkInfo); } // 0 不存不计数 1 只存不计数 3 存且计数 this.addon.registerMessageType("RC:VcMsg", 3); this.addon.registerMessageType("RC:ImgTextMsg", 3); this.addon.registerMessageType("RC:FileMsg", 3); this.addon.registerMessageType("RC:LBSMsg", 3); this.addon.registerMessageType("RC:PSImgTxtMsg", 3); this.addon.registerMessageType("RC:PSMultiImgTxtMsg", 3); this.addon.registerMessageType("RCJrmf:RpMsg", 3); this.addon.registerMessageType("RCJrmf:RpOpendMsg", 1); this.addon.registerMessageType("RC:GrpNtf", 1); this.addon.registerMessageType("RC:DizNtf", 0); this.addon.registerMessageType("RC:InfoNtf", 0); this.addon.registerMessageType("RC:ContactNtf", 0); this.addon.registerMessageType("RC:ProfileNtf", 0); this.addon.registerMessageType("RC:CmdNtf", 0); this.addon.registerMessageType("RC:CmdMsg", 0); this.addon.registerMessageType("RC:TypSts", 0); this.addon.registerMessageType("RC:CsChaR", 0); this.addon.registerMessageType("RC:CsHsR", 0); this.addon.registerMessageType("RC:CsEnd", 0); this.addon.registerMessageType("RC:CsSp", 0); this.addon.registerMessageType("RC:CsUpdate", 0); this.addon.registerMessageType("RC:CsContact", 0); this.addon.registerMessageType("RC:ReadNtf", 0); this.addon.registerMessageType("RC:VCAccept", 0); this.addon.registerMessageType("RC:VCRinging", 0); this.addon.registerMessageType("RC:VCSummary", 0); this.addon.registerMessageType("RC:VCHangup", 0); this.addon.registerMessageType("RC:VCInvite", 0); this.addon.registerMessageType("RC:VCModifyMedia", 0); this.addon.registerMessageType("RC:VCModifyMem", 0); this.addon.registerMessageType("RC:PSCmd", 0); this.addon.registerMessageType("RC:RcCmd", 0); this.addon.registerMessageType("RC:SRSMsg", 0); this.addon.registerMessageType("RC:RRReqMsg", 0); this.addon.registerMessageType("RC:RRRspMsg", 0); return sdkInfo; }; VCDataProvider.prototype.connect = function (token, callback, userId, serverConf) { this.useConsole && console.log("connect"); this.userId = userId; this.connectCallback = callback; RongIMLib.Bridge._client = { userId: userId, token: token }; serverConf = serverConf || {}; var openmp = !!serverConf.openMp; var openus = !!serverConf.openUS; if (serverConf.type) { this.addon.setEnvironment(true); } var me = this; // this.addon.connectWithToken(token, userId, serverConf.serverList, openmp, openus); this.addon.connectWithToken(token, userId, function (userId) { me.userId = userId; RongIMLib.Bridge._client.userId = userId; }); }; VCDataProvider.prototype.setServerInfo = function (info) { 'setServerInfo' in this.addon && this.addon.setServerInfo(info.navi); }; VCDataProvider.prototype.logout = function () { this.useConsole && console.log("logout"); this.disconnect(); }; VCDataProvider.prototype.disconnect = function () { this.useConsole && console.log("disconnect"); this.connectionStatus = RongIMLib.ConnectionStatus.DISCONNECTED; this.addon.disconnect(true); }; VCDataProvider.prototype.clearListeners = function () { this.addon.setOnReceiveStatusListener(); this.addon.setConnectionStatusListener(); this.addon.setOnReceiveMessageListener(); }; VCDataProvider.prototype.clearData = function () { this.useConsole && console.log("clearData"); return this.addon.clearData(); }; VCDataProvider.prototype.setConnectionStatusListener = function (listener) { var me = this; /** ConnectionStatus_TokenIncorrect = 31004, ConnectionStatus_Connected = 0, ConnectionStatus_KickedOff = 6, // 其他设备登录 ConnectionStatus_Connecting = 10,// 连接中 ConnectionStatus_SignUp = 12, // 未登录 ConnectionStatus_NetworkUnavailable = 1, // 连接断开 ConnectionStatus_ServerInvalid = 8, // 断开 ConnectionStatus_ValidateFailure = 9,//断开 ConnectionStatus_Unconnected = 11,//断开 ConnectionStatus_DisconnExecption = 31011 //断开 RC_NAVI_MALLOC_ERROR = 30000,//断开 RC_NAVI_NET_UNAVAILABLE= 30002,//断开 RC_NAVI_SEND_FAIL = 30004,//断开 RC_NAVI_REQ_TIMEOUT = 30005,//断开 RC_NAVI_RECV_FAIL = 30006,//断开 RC_NAVI_RESOURCE_ERROR = 30007,//断开 RC_NAVI_NODE_NOT_FOUND = 30008,//断开 RC_NAVI_DNS_ERROR = 30009,//断开 */ me.connectListener = listener; this.useConsole && console.log("setConnectionStatusListener"); me.addon && me.addon.setConnectionStatusListener(function (result) { var isCurrentConnected = me.connectionStatus === RongIMLib.ConnectionStatus.CONNECTED; var code = result; switch (result) { case 10: code = RongIMLib.ConnectionStatus.CONNECTING; break; case 31004: setTimeout(function () { me.connectCallback.onTokenIncorrect(); }); return; case 1: case 8: case 9: case 11: case 12: case 31011: case 30000: case 30002: case 30010: if (!isCurrentConnected) { return; } code = RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE; break; case 0: case 33005: code = RongIMLib.ConnectionStatus.CONNECTED; setTimeout(function () { me.connectCallback.onSuccess(me.userId); }); break; case 6: code = RongIMLib.ConnectionStatus.KICKED_OFFLINE_BY_OTHER_CLIENT; break; default: code = result; break; } me.connectionStatus = code; setTimeout(function () { listener.onChanged(code); }); }); }; VCDataProvider.prototype.setOnReceiveMessageListener = function (listener) { var me = this, localCount = 0; me.messageListener = listener; this.useConsole && console.log("setOnReceiveMessageListener"); me.addon && me.addon.setOnReceiveMessageListener(function (result, leftCount, offline, hasMore) { var message = me.buildMessage(result); message.offLineMessage = offline; setTimeout(function () { var voipMsgTypes = ['AcceptMessage', 'RingingMessage', 'HungupMessage', 'InviteMessage', 'MediaModifyMessage', 'MemberModifyMessage']; var isVoIPMsg = voipMsgTypes.indexOf(message.messageType) > -1; if (isVoIPMsg) { RongIMLib.RongIMClient._voipProvider && RongIMLib.RongIMClient._voipProvider.onReceived(message); } else if (message.conversationType == 12) { RongIMLib.RongIMClient.RTCListener(message); RongIMLib.RongIMClient.RTCInnerListener(message); RongIMLib.RongIMClient.RTCSignalLisener(message); } else { listener.onReceived(message, leftCount, hasMore); } }); }); }; VCDataProvider.prototype.sendTypingStatusMessage = function (conversationType, targetId, messageName, sendCallback) { var me = this; this.useConsole && console.log("sendTypingStatusMessage"); if (messageName in RongIMLib.RongIMClient.MessageParams) { me.sendMessage(conversationType, targetId, RongIMLib.TypingStatusMessage.obtain(RongIMLib.RongIMClient.MessageParams[messageName].objectName, ""), { onSuccess: function () { setTimeout(function () { sendCallback.onSuccess(); }); }, onError: function (errorCode) { setTimeout(function () { sendCallback.onError(errorCode, null); }); }, onBefore: function () { } }); } }; VCDataProvider.prototype.setMessageStatus = function (conversationType, targetId, timestamp, status, callback) { this.addon.updateMessageReceiptStatus(conversationType, targetId, timestamp); callback.onSuccess(true); }; VCDataProvider.prototype.sendTextMessage = function (conversationType, targetId, content, sendMessageCallback) { var msgContent = RongIMLib.TextMessage.obtain(content); this.useConsole && console.log("sendTextMessage"); this.sendMessage(conversationType, targetId, msgContent, sendMessageCallback); }; VCDataProvider.prototype.getRemoteHistoryMessages = function (conversationType, targetId, timestamp, count, callback, config) { try { var me = this; me.useConsole && console.log("getRemoteHistoryMessages"); me.addon.getRemoteHistoryMessages(conversationType, targetId, timestamp ? timestamp : 0, count, function (ret, hasMore) { var list = ret ? JSON.parse(ret).list : [], msgs = []; list.reverse(); for (var i = 0, len = list.length; i < len; i++) { var message = me.buildMessage(list[i].obj); message.sentStatus = RongIMLib.SentStatus.READ; msgs[i] = message; } callback.onSuccess(msgs, hasMore ? true : false); }, function (errorCode) { callback.onError(errorCode); }); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.getRemoteConversationList = function (callback, conversationTypes, count, isGetHiddenConvers) { try { this.useConsole && console.log("getRemoteConversationList"); var converTypes = conversationTypes || [1, 2, 3, 4, 5, 6, 7, 8]; var result = this.addon.getConversationList(converTypes); var list = JSON.parse(result).list, convers = [], me = this, index = 0; list.reverse(); isGetHiddenConvers = typeof isGetHiddenConvers === 'boolean' ? isGetHiddenConvers : false; for (var i = 0, len_1 = list.length; i < len_1; i++) { var tmpObj = list[i].obj, obj = JSON.parse(tmpObj); if (obj != "") { if (obj.isHidden == 1 && isGetHiddenConvers) { continue; } convers[index] = me.buildConversation(tmpObj); index++; } } convers.reverse(); var len = convers.length; count = count || len; if (len > count) { convers.length = count; } callback.onSuccess(convers); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.removeConversation = function (conversationType, targetId, callback) { try { this.useConsole && console.log("removeConversation"); this.addon.removeConversation(conversationType, targetId); var conversations = RongIMLib.RongIMClient._memoryStore.conversationList; var len = conversations.length; for (var i = 0; i < len; i++) { if (conversations[i].conversationType == conversationType && targetId == conversations[i].targetId) { conversations.splice(i, 1); break; } } callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.joinChatRoom = function (chatRoomId, messageCount, callback) { this.useConsole && console.log("joinChatRoom"); this.addon.joinChatRoom(chatRoomId, messageCount, function () { callback.onSuccess(); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.quitChatRoom = function (chatRoomId, callback) { this.useConsole && console.log("quitChatRoom"); this.addon.quitChatRoom(chatRoomId, function () { callback.onSuccess(); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.setChatroomEntry = function (chatroomId, chatroomEntry, callback) { }; VCDataProvider.prototype.forceSetChatroomEntry = function (chatroomId, chatroomEntry, callback) { }; VCDataProvider.prototype.getChatroomEntry = function (chatroomId, key, callback) { }; VCDataProvider.prototype.getAllChatroomEntries = function (chatroomId, callback) { }; VCDataProvider.prototype.removeChatroomEntry = function (chatroomId, chatroomEntry, callback) { }; VCDataProvider.prototype.forceRemoveChatroomEntry = function (chatroomId, chatroomEntry, callback) { }; VCDataProvider.prototype.pullChatroomEntry = function (chatroomId, time, callback) { }; VCDataProvider.prototype.addToBlacklist = function (userId, callback) { this.useConsole && console.log("addToBlacklist"); this.addon.addToBlacklist(userId, function () { callback.onSuccess(); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.getBlacklist = function (callback) { this.useConsole && console.log("getBlacklist"); this.addon.getBlacklist(function (blacklistors) { callback.onSuccess(blacklistors); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.getBlacklistStatus = function (userId, callback) { this.useConsole && console.log("getBlacklistStatus"); this.addon.getBlacklistStatus(userId, function (result) { callback.onSuccess(result); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.removeFromBlacklist = function (userId, callback) { this.useConsole && console.log("removeFromBlacklist"); this.addon.removeFromBlacklist(userId, function () { callback.onSuccess(); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.sendMessage = function (conversationType, targetId, messageContent, sendCallback, mentiondMsg, pushText, appData, methodType, params) { var me = this, users = []; me.useConsole && console.log("sendMessage"); params = params || {}; var isGroup = (conversationType == RongIMLib.ConversationType.DISCUSSION || conversationType == RongIMLib.ConversationType.GROUP); if (isGroup && messageContent.messageName == RongIMLib.RongIMClient.MessageType["ReadReceiptResponseMessage"]) { users = []; var rspMsg = messageContent; if (rspMsg.receiptMessageDic) { var ids = []; for (var key in rspMsg.receiptMessageDic) { ids.push(key); } users = ids; } } if (isGroup && messageContent.messageName == RongIMLib.RongIMClient.MessageType["SyncReadStatusMessage"]) { users = []; users.push(me.userId); } var userIds = params.userIds; if (isGroup && userIds) { users = userIds; } var msg = me.addon.sendMessage(conversationType, targetId, RongIMLib.RongIMClient.MessageParams[messageContent.messageName].objectName, messageContent.encode(), pushText || "", appData || "", function (progress) { }, function (message, code) { var msg = me.buildMessage(message); var errorCode = RongIMLib.ErrorCode.SENSITIVE_REPLACE; if (code == errorCode) { return sendCallback.onError(errorCode, msg); } sendCallback.onSuccess(msg); }, function (message, code) { sendCallback.onError(code, me.buildMessage(message)); }, users, mentiondMsg); var tempMessage = JSON.parse(msg); sendCallback.onBefore && sendCallback.onBefore(tempMessage.messageId); RongIMLib.MessageIdHandler.messageId = tempMessage.messageId; }; VCDataProvider.prototype.registerMessageType = function (messageType, objectName, messageTag, messageContent, searchProps) { this.useConsole && console.log("registerMessageType"); this.addon.registerMessageType(objectName, messageTag.getMessageTag(), searchProps); var regMsg = RongIMLib.ModelUtil.modleCreate(messageContent, messageType); RongIMLib.RongIMClient.RegisterMessage[messageType] = regMsg; RongIMLib.RongIMClient.RegisterMessage[messageType].messageName = messageType; registerMessageTypeMapping[objectName] = messageType; RongIMLib.RongIMClient.MessageType[messageType] = messageType; RongIMLib.RongIMClient.MessageParams[messageType] = { objectName: objectName, msgTag: messageTag }; typeMapping[objectName] = messageType; }; VCDataProvider.prototype.registerMessageTypes = function (messages) { var types = []; var getProtos = function (proto) { var protos = []; for (var p in proto) { protos.push(p); } return protos; }; //转换消息为自定义消息参数格式 for (var name in messages) { var message = messages[name]; var proto = message.proto; var protos = getProtos(proto); var flag = message.flag || 3; var tag = RongIMLib.MessageTag.getTagByStatus(flag); flag = new RongIMLib.MessageTag(tag.isCounted, tag.isPersited); types.push({ type: name, name: message.name, flag: flag, protos: protos }); } var register = function (message) { var type = message.type; var name = message.name; var flag = message.flag; var protos = message.protos; RongIMLib.RongIMClient.registerMessageType(type, name, flag, protos); }; for (var i = 0, len = types.length; i < len; i++) { var message = types[i]; register(message); } }; VCDataProvider.prototype.addMessage = function (conversationType, targetId, message, callback) { this.useConsole && console.log("addMessage"); var direction = message.direction; var msg = this.addon.insertMessage(conversationType, targetId, message.senderUserId, message.objectName, JSON.stringify(message.content), function () { callback.onSuccess(me.buildMessage(msg)); }, function () { callback.onError(RongIMLib.ErrorCode.MSG_INSERT_ERROR); }, direction), me = this; }; VCDataProvider.prototype.removeMessage = function (conversationType, targetId, messages, callback) { }; VCDataProvider.prototype.deleteRemoteMessages = function (conversationType, targetId, messages, callback) { }; VCDataProvider.prototype.removeLocalMessage = function (conversationType, targetId, timestamps, callback) { try { this.useConsole && console.log("removeLocalMessage"); this.addon.deleteMessages(timestamps); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.getMessage = function (messageId, callback) { try { this.useConsole && console.log("getMessage"); var msg = this.buildMessage(this.addon.getMessage(messageId)); callback.onSuccess(msg); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.clearMessages = function (conversationType, targetId, callback) { try { this.useConsole && console.log("clearMessages"); this.addon.clearMessages(conversationType, targetId); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; // Web 端接口,桌面版无需实现 VCDataProvider.prototype.setUnreadCount = function (conversationType, targetId, count) { }; VCDataProvider.prototype.getConversation = function (conversationType, targetId, callback) { try { this.useConsole && console.log("getConversation"); var ret = this.addon.getConversation(conversationType, targetId); callback.onSuccess(this.buildConversation(ret)); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.getConversationList = function (callback, conversationTypes, count, isGetHiddenConvers) { this.useConsole && console.log("getConversationList"); this.getRemoteConversationList(callback, conversationTypes, count, isGetHiddenConvers); }; VCDataProvider.prototype.clearCache = function () { var memoryStore = RongIMLib.RongIMClient._memoryStore || {}; memoryStore.conversationList = []; memoryStore.isSyncRemoteConverList; }; VCDataProvider.prototype.clearConversations = function (conversationTypes, callback) { try { this.useConsole && console.log("clearConversations"); this.addon.clearConversations(); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.setMessageContent = function (messageId, content, objectName) { content = JSON.stringify(content); this.addon.setMessageContent(messageId, content, objectName); }; VCDataProvider.prototype.setMessageSearchField = function (messageId, content, searchFiles) { content = JSON.stringify(content); this.addon.setMessageContent(messageId, content, searchFiles); }; VCDataProvider.prototype.getHistoryMessages = function (conversationType, targetId, timestamp, count, callback, objectname, direction) { this.useConsole && console.log("getHistoryMessages"); if (count <= 0) { callback.onError(RongIMLib.ErrorCode.TIMEOUT); return; } objectname = objectname || ''; direction = typeof direction == 'undefined' || direction; try { var ret = this.addon.getHistoryMessages(conversationType, targetId, timestamp ? timestamp : 0, count, objectname, direction); var list = ret ? JSON.parse(ret).list : [], msgs = [], me = this; list.reverse(); for (var i = 0, len = list.length; i < len; i++) { var message = me.buildMessage(list[i].obj); msgs[i] = message; } callback.onSuccess(msgs, len == count); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.clearRemoteHistoryMessages = function (params, callback) { var conversationType = params.conversationType; var targetId = params.targetId; var timestamp = params.timestamp; var _topic = { 1: true, 2: true, 3: true, 5: true, 6: true }; var topic = _topic[conversationType]; if (!topic) { callback.onError(RongIMLib.ErrorCode.CLEAR_HIS_TYPE_ERROR); return; } if (typeof timestamp != 'number') { callback.onError(RongIMLib.ErrorCode.CLEAR_HIS_TIME_ERROR); return; } this.addon.clearRemoteHistoryMessages(+conversationType, targetId, timestamp, function () { callback.onSuccess(true); }, function (errorCode) { if (errorCode == 1) { // 没有开通历史消息云存储 errorCode = RongIMLib.ErrorCode.CLEAR_HIS_ERROR; } callback.onError(errorCode); }); }; VCDataProvider.prototype.clearHistoryMessages = function (params, callback) { var conversationType = +params.conversationType; var targetId = params.targetId; try { this.addon.clearMessages(conversationType, targetId); var isSuccess = true; callback.onSuccess(isSuccess); } catch (e) { console.log(e); callback.onError(RongIMLib.ErrorCode.CLEAR_HIS_ERROR); } }; VCDataProvider.prototype.getTotalUnreadCount = function (callback, conversationTypes) { try { var result; this.useConsole && console.log("getTotalUnreadCount"); if (conversationTypes) { result = this.addon.getTotalUnreadCount(conversationTypes); } else { result = this.addon.getTotalUnreadCount(); } callback.onSuccess(result); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.getConversationUnreadCount = function (conversationTypes, callback) { this.useConsole && console.log("getConversationUnreadCount"); this.getTotalUnreadCount(callback, conversationTypes); }; VCDataProvider.prototype.getUnreadCount = function (conversationType, targetId, callback) { try { this.useConsole && console.log("getUnreadCount"); var result = this.addon.getUnreadCount(conversationType, targetId); callback.onSuccess(result); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.clearUnreadCount = function (conversationType, targetId, callback) { try { this.useConsole && console.log("clearUnreadCount"); var result = this.addon.clearUnreadCount(conversationType, targetId); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.clearTotalUnreadCount = function (callback) { this.useConsole && console.log("clearTotalUnreadCount"); }; VCDataProvider.prototype.clearUnreadCountByTimestamp = function (conversationType, targetId, timestamp, callback) { try { this.useConsole && console.log("clearUnreadCountByTimestamp"); var result = this.addon.clearUnreadCountByTimestamp(conversationType, targetId, timestamp); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.setConversationToTop = function (conversationType, targetId, isTop, callback) { try { this.useConsole && console.log("setConversationToTop"); this.addon.setConversationToTop(conversationType, targetId, isTop); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.setConversationHidden = function (conversationType, targetId, isHidden) { this.addon.setConversationHidden(conversationType, targetId, isHidden); }; VCDataProvider.prototype.setMessageReceivedStatus = function (messageId, receivedStatus, callback) { try { this.useConsole && console.log("setMessageReceivedStatus"); this.addon.setMessageReceivedStatus(messageId, receivedStatus); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.setMessageSentStatus = function (messageId, sentStatus, callback) { try { this.useConsole && console.log("setMessageSentStatus"); this.addon.setMessageSentStatus(messageId, sentStatus); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.getFileToken = function (fileType, callback) { this.useConsole && console.log("getFileToken"); this.addon.getUploadToken(fileType, function (token) { callback.onSuccess({ token: token }); }, function (errorCode) { callback.onError(errorCode); }); }; VCDataProvider.prototype.getFileUrl = function (fileType, fileName, oriName, callback) { this.useConsole && console.log("getFileUrl"); this.addon.getDownloadUrl(fileType, fileName, oriName, function (url) { callback.onSuccess({ downloadUrl: url }); }, function (errorCode) { callback.onError(errorCode); }); }; VCDataProvider.prototype.getPullSetting = function (callback) { this.useConsole && console.log("getPullSetting"); }; VCDataProvider.prototype.setOfflineMessageDuration = function (duration, callback) { this.useConsole && console.log("setOfflineMessageDuration"); }; VCDataProvider.prototype.searchConversationByContent = function (keyword, callback, conversationTypes) { var converTypes = []; if (typeof conversationTypes == 'undefined') { converTypes = [1, 2, 3, 4, 5, 6, 7]; } else { converTypes = conversationTypes; } try { this.useConsole && console.log("searchConversationByContent"); var result = this.addon.searchConversationByContent(converTypes, keyword); var list = JSON.parse(result).list, convers = [], me = this; list.reverse(); for (var i = 0, len = list.length; i < len; i++) { convers[i] = me.buildConversation(list[i].obj); } callback.onSuccess(convers); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.searchMessageByContent = function (conversationType, targetId, keyword, timestamp, count, total, callback) { var me = this; try { this.useConsole && console.log("searchMessageByContent"); this.addon.searchMessageByContent(conversationType, targetId, keyword, timestamp, count, total, function (ret, matched) { var list = ret ? JSON.parse(ret).list : [], msgs = []; list.reverse(); for (var i = 0, len = list.length; i < len; i++) { msgs[i] = me.buildMessage(list[i].obj); } callback.onSuccess(msgs, matched); }); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.getChatRoomInfo = function (chatRoomId, count, order, callback) { this.useConsole && console.log("getChatRoomInfo"); this.addon.getChatroomInfo(chatRoomId, count, order, function (ret, count) { var list = ret ? JSON.parse(ret).list : [], chatRoomInfo = { userInfos: [], userTotalNums: count }; if (list.length > 0) { for (var i = 0, len = list.length; i < len; i++) { chatRoomInfo.userInfos.push(JSON.parse(list[i].obj)); } } callback.onSuccess(chatRoomInfo); }, function (errcode) { callback.onError(errcode); }); }; VCDataProvider.prototype.setChatroomHisMessageTimestamp = function (chatRoomId, timestamp) { }; VCDataProvider.prototype.getChatRoomHistoryMessages = function (chatRoomId, count, order, callback) { }; VCDataProvider.prototype.getDelaTime = function () { return this.addon.getDeltaTime(); }; VCDataProvider.prototype.getUserStatus = function (userId, callback) { var me = this; this.addon.getUserStatus(userId, function (status) { var entity = RongIMLib.RongInnerTools.convertUserStatus({ status: status, userId: '' }); callback.onSuccess(entity); }, function (code) { callback.onError(code); }); }; VCDataProvider.prototype.setUserStatus = function (status, callback) { this.addon.setUserStatus(status, function () { callback.onSuccess(true); }, function (code) { callback.onError(code); }); }; VCDataProvider.prototype.subscribeUserStatus = function (userIds, callback) { this.addon.subscribeUserStatus(userIds, function () { callback && callback.onSuccess(true); }, function (code) { callback && callback.onError(code); }); }; VCDataProvider.prototype.setUserStatusListener = function (params, callback) { var me = this; this.addon.setOnReceiveStatusListener(function (userId, status) { var entity = RongIMLib.RongInnerTools.convertUserStatus({ userId: userId, status: status }); RongIMLib.RongIMClient.userStatusObserver.notify({ key: userId, entity: entity }); }); var userIds = params.userIds || []; if (userIds.length) { RongIMLib.RongIMClient._dataAccessProvider.subscribeUserStatus(userIds); } }; VCDataProvider.prototype.getUnreadMentionedMessages = function (conversationType, targetId) { var me = this; var mentions = JSON.parse(me.addon.getUnreadMentionedMessages(conversationType, targetId)).list; for (var i = 0, len = mentions.length; i < len; i++) { var temp = JSON.parse(mentions[i].obj); temp.content = JSON.parse(temp.content); mentions[i] = temp; } return mentions; }; VCDataProvider.prototype.hasRemoteUnreadMessages = function (token, callback) { callback.onSuccess(false); }; VCDataProvider.prototype.sendRecallMessage = function (content, sendMessageCallback) { var me = this; me.addon.recallMessage("RC:RcCmd", JSON.stringify(content), content.push || "", function () { content.objectName = 'RC:RcCmd'; sendMessageCallback.onSuccess(me.buildMessage(JSON.stringify(content))); }, function (errorCode) { sendMessageCallback.onError(errorCode); }); }; VCDataProvider.prototype.updateMessage = function (message, callback) { }; VCDataProvider.prototype.updateMessages = function (conversationType, targetId, key, value, callback) { }; VCDataProvider.prototype.reconnect = function (callback) { var token = RongIMLib.Bridge._client.token; this.disconnect(); this.connect(token, callback); }; VCDataProvider.prototype.sendReceiptResponse = function (conversationType, targetId, sendCallback) { }; VCDataProvider.prototype.setMessageExtra = function (messageId, value, callback) { }; VCDataProvider.prototype.addMemberToDiscussion = function (discussionId, userIdList, callback) { }; VCDataProvider.prototype.createDiscussion = function (name, userIdList, callback) { }; VCDataProvider.prototype.getDiscussion = function (discussionId, callback) { }; VCDataProvider.prototype.quitDiscussion = function (discussionId, callback) { }; VCDataProvider.prototype.removeMemberFromDiscussion = function (discussionId, userId, callback) { }; VCDataProvider.prototype.setDiscussionInviteStatus = function (discussionId, status, callback) { }; VCDataProvider.prototype.setDiscussionName = function (discussionId, name, callback) { }; VCDataProvider.prototype.setEnvironment = function (isPrivate) { this.addon.setEnvironment(isPrivate); }; VCDataProvider.prototype.addConversation = function (conversation, callback) { }; VCDataProvider.prototype.updateConversation = function (conversation) { return null; }; VCDataProvider.prototype.getConversationNotificationStatus = function (params, callback) { var conversationType = params.conversationType; var targetId = params.targetId; var notification = RongIMLib.RongIMClient._memoryStore.notification; var key = conversationType + '_' + targetId; var status = notification[key]; if (typeof status == 'number') { callback.onSuccess(status); return; } this.addon.getConversationNotificationStatus(conversationType, targetId, function (status) { notification[key] = status; callback.onSuccess(status); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.setConversationNotificationStatus = function (params, callback) { var conversationType = params.conversationType; var targetId = params.targetId; var status = params.status; var notification = RongIMLib.RongIMClient._memoryStore.notification; var key = conversationType + '_' + targetId; notification[key] = status; var notify = !!status; this.addon.setConversationNotificationStatus(conversationType, targetId, notify, function () { callback.onSuccess(status); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.getCurrentConnectionStatus = function () { return this.addon.getConnectionStatus(); }; VCDataProvider.prototype.getAgoraDynamicKey = function (engineType, channelName, callback) { var extra = ""; this.addon.getVoIPKey(engineType, channelName, extra, function (token) { callback.onSuccess(token); }, function (errorCode) { callback.onError(errorCode); }); }; VCDataProvider.prototype.getPublicServiceProfile = function (publicServiceType, publicServiceId, callback) { var profile = RongIMLib.RongIMClient._memoryStore.publicServiceMap.get(publicServiceType, publicServiceId); callback.onSuccess(profile); }; VCDataProvider.prototype.setDeviceInfo = function (device) { var id = device.id || ''; this.addon.setDeviceId(id); }; VCDataProvider.prototype.getRemotePublicServiceList = function (callback, pullMessageTime) { var publicList = []; var ret = this.addon.getAccounts(); var transformProto = function (ret) { var result = { hasFollowed: false, isGlobal: false, menu: null }; if (!ret.obj) { var error = { error: ret }; throw new Error('公众账号数据格式错误: ' + JSON.stringify(error)); } var obj = JSON.parse(ret.obj); var protoMap = { aType: 'conversationType', aId: 'publicServiceId', aName: 'introduction', aUri: 'portraitUri', follow: 'hasFollowed', isGlobal: 'isGlobal' }; for (var key in obj) { var val = obj[key]; if (key == 'aExtra') { var extra = JSON.parse(val); result["hasFollowed"] = extra.follow; result["isGlobal"] = extra.isGlobal; result["menu"] = extra.menu; } var uId = protoMap[key]; if (uId) { result[uId] = val; } } return result; }; if (ret) { ret = JSON.parse(ret); var list = ret.list; for (var i = 0, len = list.length; i < len; i++) { var item = list[i]; item = transformProto(item); publicList.push(item); } } if (publicList.length > 0) { RongIMLib.RongIMClient._memoryStore.publicServiceMap.publicServiceList.length = 0; RongIMLib.RongIMClient._memoryStore.publicServiceMap.publicServiceList = publicList; } callback.onSuccess(RongIMLib.RongIMClient._memoryStore.publicServiceMap.publicServiceList); }; VCDataProvider.prototype.buildMessage = function (result) { var message = new RongIMLib.Message(), ret = JSON.parse(result); message.conversationType = ret.conversationType; message.targetId = ret.targetId; message.messageDirection = ret.direction; message.senderUserId = ret.senderUserId; if (ret.direction == RongIMLib.MessageDirection.RECEIVE) { message.receivedStatus = ret.status; } else if (ret.direction == RongIMLib.MessageDirection.SEND) { message.sentStatus = ret.status; } message.sentTime = ret.sentTime; message.objectName = ret.objectName; var content = ret.content ? JSON.parse(ret.content) : ret.content; var messageType = typeMapping[ret.objectName] || registerMessageTypeMapping[ret.objectName]; if (content) { content.messageName = messageType; } message.content = content; message.messageId = ret.messageId; message.messageUId = ret.messageUid; message.messageType = messageType; return message; }; VCDataProvider.prototype.buildConversation = function (val) { if (val === '') { return null; } var conver = new RongIMLib.Conversation(), c = JSON.parse(val), lastestMsg = c.lastestMsg ? this.buildMessage(c.lastestMsg) : {}; conver.conversationTitle = c.title; conver.conversationType = c.conversationType; conver.draft = c.draft; conver.isTop = c.isTop; conver.isHidden = c.isHidden; lastestMsg.conversationType = c.conversationType; lastestMsg.targetId = c.targetId; conver.latestMessage = lastestMsg; conver.latestMessageId = lastestMsg.messageId; conver.latestMessage.messageType = typeMapping[lastestMsg.objectName] || registerMessageTypeMapping[lastestMsg.objectName]; conver.objectName = lastestMsg.objectName; conver.receivedStatus = RongIMLib.ReceivedStatus.READ; conver.sentTime = lastestMsg.sentTime; conver.senderUserId = lastestMsg.senderUserId; conver.sentStatus = lastestMsg.status; conver.targetId = c.targetId; conver.unreadMessageCount = c.unreadCount; conver.hasUnreadMention = c.m_hasUnreadMention; var mentions = this.getUnreadMentionedMessages(c.conversationType, c.targetId); if (mentions.length > 0) { // 取最后一条 @ 消息,原因:和 web 互相兼容 var mention = mentions.pop(); conver.mentionedMsg = { uid: mention.messageUid, time: mention.sentTime, mentionedInfo: mention.content.mentionedInfo, sendUserId: mention.senderUserId }; } return conver; }; VCDataProvider.prototype.getRTCUserInfoList = function (room, callback) { this.addon.getRTCUsers(room.id, 1, function (result) { callback.onSuccess(result); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.getRTCRoomInfo = function (room, callback) { var order = 2; this.addon.getRTCResouce(room.id, order, function (result) { callback.onSuccess(JSON.parse(result)); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.joinRTCRoom = function (room, callback) { var id = room.id; var type = room.type || 0; this.addon.joinRTCRoom(id, type, function (result, token) { var res = JSON.parse(result); var users = {}; var list = res.list; RongIMLib.RongUtil.forEach(list, function (item) { var userId = item.id; var tmpData = {}; RongIMLib.RongUtil.forEach(item.data, function (data) { var key = data.key; var value = data.value; tmpData[key] = value; }); users[userId] = tmpData; }); callback.onSuccess({ users: users, token: token }); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.quitRTCRoom = function (room, callback) { this.addon.exitRTCRoom(room.id, function () { callback.onSuccess(true); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.RTCPing = function (room, callback) { this.addon.sendRTCPing(room.id, function () { callback.onSuccess(true); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.setRTCData = function (roomId, key, value, isInner, apiType, callback, message) { var context = this; var hanlders = { room_inner: function (roomId, key, value, name, content, success, error) { context.addon.setRTCInnerData(roomId, RongIMLib.RTCAPIType.ROOM, key, value, name, content, success, error); }, room_outer: function (roomId, key, value, name, content, success, error) { context.addon.setRTCOuterData(roomId, RongIMLib.RTCAPIType.ROOM, key, value, name, content, success, error); }, user_inner: function (roomId, key, value, name, content, success, error) { context.addon.setRTCInnerData(roomId, RongIMLib.RTCAPIType.PERSON, key, value, name, content, success, error); }, user_outer: function (roomId, key, value, name, content, success, error) { context.addon.setRTCOuterData(roomId, RongIMLib.RTCAPIType.PERSON, key, value, name, content, success, error); } }; var type = RongIMLib.RTCAPIType.PERSON == apiType ? 'user' : 'room'; var direction = isInner ? 'inner' : 'outer'; var tpl = '{type}_{direction}'; var name = RongIMLib.RongUtil.tplEngine(tpl, { type: type, direction: direction }); var handler = hanlders[name]; if (handler) { message = message || {}; var name = message.name; var content = message.content; handler(roomId, key, value, name, content, function () { callback.onSuccess(true); }, function (code) { callback.onError(code); }); } }; VCDataProvider.prototype.setRTCRoomData = function (roomId, key, value, isInner, callback, message) { this.setRTCData(roomId, key, value, isInner, RongIMLib.RTCAPIType.ROOM, callback, message); }; VCDataProvider.prototype.getRTCData = function (roomId, keys, isInner, apiType, callback) { var context = this; var hanlders = { room_inner: function (roomId, keys, success, error) { context.addon.getRTCInnerData(roomId, RongIMLib.RTCAPIType.ROOM, keys, success, error); }, room_outer: function (roomId, keys, success, error) { context.addon.getRTCOuterData(roomId, RongIMLib.RTCAPIType.ROOM, keys, success, error); } }; var type = RongIMLib.RTCAPIType.PERSON == apiType ? 'user' : 'room'; var direction = isInner ? 'inner' : 'outer'; var tpl = '{type}_{direction}'; var name = RongIMLib.RongUtil.tplEngine(tpl, { type: type, direction: direction }); var handler = hanlders[name]; if (handler) { handler(roomId, keys, function (result) { var res = JSON.parse(result); var props = {}; var list = res.list; RongIMLib.RongUtil.forEach(list, function (item) { props[item.key] = item.value; }); callback.onSuccess(props); }, function (code) { callback.onError(code); }); } }; VCDataProvider.prototype.getRTCRoomData = function (roomId, keys, isInner, callback, message) { this.getRTCData(roomId, keys, isInner, RongIMLib.RTCAPIType.ROOM, callback); }; VCDataProvider.prototype.removeRTCData = function (roomId, keys, isInner, apiType, callback, message) { var context = this; var hanlders = { room_inner: function (roomId, keys, name, content, success, error) { context.addon.deleteRTCInnerData(roomId, RongIMLib.RTCAPIType.ROOM, keys, name, content, success, error); }, room_outer: function (roomId, keys, name, content, success, error) { context.addon.deleteRTCOuterData(roomId, RongIMLib.RTCAPIType.ROOM, keys, name, content, success, error); }, user_inner: function (roomId, keys, name, content, success, error) { }, user_outer: function (roomId, keys, name, content, success, error) { } }; var type = RongIMLib.RTCAPIType.PERSON == apiType ? 'user' : 'room'; var direction = isInner ? 'inner' : 'outer'; var tpl = '{type}_{direction}'; var name = RongIMLib.RongUtil.tplEngine(tpl, { type: type, direction: direction }); var handler = hanlders[name]; if (handler) { message = message || {}; var name = message.name || ''; var content = message.content || ''; handler(roomId, keys, name, content, function () { callback.onSuccess(true); }, function (code) { callback.onError(code); }); } }; VCDataProvider.prototype.removeRTCRoomData = function (roomId, keys, isInner, callback, message) { this.removeRTCData(roomId, keys, isInner, RongIMLib.RTCAPIType.ROOM, callback); }; VCDataProvider.prototype.getNavi = function () { var nav = this.addon.getNav(); return nav[this.userId]; }; // 信令 SDK 新增 VCDataProvider.prototype.setRTCOutData = function (roomId, data, type, callback, message) { }; // 信令 SDK 新增 VCDataProvider.prototype.getRTCOutData = function (roomId, userId, callback) { }; VCDataProvider.prototype.setRTCUserInfo = function (room, info, callback) { }; VCDataProvider.prototype.removeRTCUserInfo = function (room, info, callback) { }; VCDataProvider.prototype.getRTCUserList = function (room, callback) { }; VCDataProvider.prototype.setRTCRoomInfo = function (room, data, callback) { }; VCDataProvider.prototype.removeRTCRoomInfo = function (room, data, callback) { }; VCDataProvider.prototype.setRTCUserData = function (roomId, key, value, isInner, callback, message) { this.setRTCData(roomId, key, value, isInner, RongIMLib.RTCAPIType.PERSON, callback, message); }; VCDataProvider.prototype.getRTCUserData = function (roomId, key, isInner, callback, message) { }; VCDataProvider.prototype.removeRTCUserData = function (roomId, key, isInner, callback, message) { }; VCDataProvider.prototype.getRTCToken = function (room, callback) { }; VCDataProvider.prototype.setRTCState = function (room, content, callback) { }; return VCDataProvider; })(); RongIMLib.VCDataProvider = VCDataProvider; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var MemeoryProvider = (function () { function MemeoryProvider() { this._memeoryStore = {}; this.prefix = "rong_"; } MemeoryProvider.prototype.setItem = function (composedKey, object) { this._memeoryStore[composedKey] = decodeURIComponent(object); }; MemeoryProvider.prototype.getItem = function (composedKey) { return this._memeoryStore[composedKey]; }; MemeoryProvider.prototype.removeItem = function (composedKey) { if (this.getItem(composedKey)) { delete this._memeoryStore[composedKey]; } }; MemeoryProvider.prototype.getItemKey = function (regStr) { var me = this, item = null, reg = new RegExp(regStr + "\\w+"); for (var key in me._memeoryStore) { var arr = key.match(reg); if (arr) { item = key; } } return item; }; MemeoryProvider.prototype.getItemKeyList = function (regStr) { var prefix = this.prefix; var me = this, itemList = [], reg = new RegExp(regStr + "\\w+"); for (var key in me._memeoryStore) { var arr = key.match(reg); if (arr) { key = key.substring(prefix.length); itemList.push(key); } } return itemList; }; MemeoryProvider.prototype.clearItem = function () { var me = this; for (var key in me._memeoryStore) { delete me._memeoryStore[key]; } }; //单位:字节 MemeoryProvider.prototype.onOutOfQuota = function () { return 4 * 1024; }; return MemeoryProvider; })(); RongIMLib.MemeoryProvider = MemeoryProvider; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var LocalStorageProvider = (function () { // static _instance: LocalStorageProvider = new LocalStorageProvider(); function LocalStorageProvider() { this.prefix = 'rong_'; this._host = ""; var d = new Date(), m = d.getMonth() + 1, date = d.getFullYear() + '/' + (m.toString().length == 1 ? '0' + m : m) + '/' + d.getDate(), nowDate = new Date(date).getTime(); for (var key in localStorage) { if (key.lastIndexOf('RECEIVED') > -1) { var recObj = JSON.parse(localStorage.getItem(key)); for (var key_1 in recObj) { nowDate - recObj[key_1].dealtime > 0 && (delete recObj[key_1]); } if (RongIMLib.RongUtil.isEmpty(recObj)) { localStorage.removeItem(key); } else { localStorage.setItem(key, JSON.stringify(recObj)); } } if (key.lastIndexOf('SENT') > -1) { var sentObj = JSON.parse(localStorage.getItem(key)); nowDate - sentObj.dealtime > 0 && (localStorage.removeItem(key)); } } } LocalStorageProvider.prototype.setItem = function (composedKey, object) { if (composedKey) { composedKey.indexOf(this.prefix) == -1 && (composedKey = this.prefix + composedKey); localStorage.setItem(composedKey, object); } }; LocalStorageProvider.prototype.getItem = function (composedKey) { if (composedKey) { composedKey.indexOf(this.prefix) == -1 && (composedKey = this.prefix + composedKey); return localStorage.getItem(composedKey ? composedKey : ""); } return ""; }; LocalStorageProvider.prototype.getItemKey = function (composedStr) { var item = ""; var _key = this.prefix + composedStr; for (var key in localStorage) { if (key.indexOf(_key) == 0) { item = key; break; } } return item; }; LocalStorageProvider.prototype.getItemKeyList = function (composedStr) { var itemList = []; var prefix = this.prefix; var _key = prefix + composedStr; for (var key in localStorage) { if (key.indexOf(_key) == 0) { key = key.substring(prefix.length); itemList.push(key); } } return itemList; }; LocalStorageProvider.prototype.removeItem = function (composedKey) { if (composedKey) { composedKey.indexOf(this.prefix) == -1 && (composedKey = this.prefix + composedKey); localStorage.removeItem(composedKey.toString()); } }; LocalStorageProvider.prototype.clearItem = function () { var me = this; for (var key in localStorage) { if (key.indexOf(me.prefix) > -1) { me.removeItem(key); } } }; //单位:字节 LocalStorageProvider.prototype.onOutOfQuota = function () { return JSON.stringify(localStorage).length; }; return LocalStorageProvider; })(); RongIMLib.LocalStorageProvider = LocalStorageProvider; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var UserDataProvider = (function () { function UserDataProvider() { this.opersistName = 'RongIMLib'; this.keyManager = 'RongUserDataKeyManager'; this._host = ""; this.prefix = "rong_"; this.oPersist = document.createElement("div"); this.oPersist.style.display = "none"; this.oPersist.style.behavior = "url('#default#userData')"; document.body.appendChild(this.oPersist); this.oPersist.load(this.opersistName); } UserDataProvider.prototype.setItem = function (key, value) { key && key.indexOf(this.prefix) == -1 && (key = this.prefix + key); this.oPersist.setAttribute(key, value); var keyNames = this.getItem(this.keyManager); keyNames ? keyNames.indexOf(key) == -1 && (keyNames += ',' + key) : (keyNames = key); this.oPersist.setAttribute(this.prefix + this.keyManager, keyNames); this.oPersist.save(this.opersistName); }; UserDataProvider.prototype.getItem = function (key) { key && key.indexOf(this.prefix) == -1 && (key = this.prefix + key); return key ? this.oPersist.getAttribute(key) : key; }; UserDataProvider.prototype.removeItem = function (key) { key && key.indexOf(this.prefix) == -1 && (key = this.prefix + key); this.oPersist.removeAttribute(key); this.oPersist.save(this.opersistName); var keyNames = this.getItem(this.keyManager), keyNameArray = keyNames && keyNames.split(',') || []; for (var i = 0, len = keyNameArray.length; i < len; i++) { if (keyNameArray[i] == key) { keyNameArray.splice(i, 1); } } this.oPersist.setAttribute(this.prefix + this.keyManager, keyNameArray.join(',')); this.oPersist.save(this.opersistName); }; UserDataProvider.prototype.getItemKey = function (composedStr) { var item = null, keyNames = this.getItem(this.keyManager), keyNameArray = keyNames && keyNames.split(',') || [], me = this; var _key = this.prefix + composedStr; if (keyNameArray.length) { for (var i = 0, len = keyNameArray.length; i < len; i++) { if (keyNameArray[i] && keyNameArray[i].indexOf(_key) == 0) { item = keyNameArray[i]; break; } } } return item; }; UserDataProvider.prototype.getItemKeyList = function (composedStr) { var itemList = [], keyNames = this.getItem(this.keyManager), keyNameArray = keyNames && keyNames.split(',') || []; var prefix = this.prefix; var _key = prefix + composedStr; if (keyNameArray.length) { for (var i = 0, len = keyNameArray.length; i < len; i++) { if (keyNameArray[i] && keyNameArray[i].indexOf(_key) == 0) { var keyName = keyNameArray[i]; keyName = keyName.substring(prefix.length); itemList.push(keyNameArray[i]); } } } return itemList; }; UserDataProvider.prototype.clearItem = function () { var keyNames = this.getItem(this.keyManager), keyNameArray = [], me = this; keyNames && (keyNameArray = keyNames.split(',')); if (keyNameArray.length) { for (var i = 0, len = keyNameArray.length; i < len; i++) { keyNameArray[i] && me.removeItem(keyNameArray[i]); } me.removeItem(me.keyManager); } }; UserDataProvider.prototype.onOutOfQuota = function () { return 10 * 1024 * 1024; }; return UserDataProvider; })(); RongIMLib.UserDataProvider = UserDataProvider; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var FeatureDectector = (function () { function FeatureDectector(callback) { this.script = document.createElement("script"); this.head = document.getElementsByTagName("head")[0]; if ("WebSocket" in window && "ArrayBuffer" in window && WebSocket.prototype.CLOSED === 3 && !RongIMLib.RongIMClient._memoryStore.depend.isPolling) { RongIMLib.Transportations._TransportType = RongIMLib.Socket.WEBSOCKET; if (!RongIMLib.RongIMClient.Protobuf) { var url = RongIMLib.RongIMClient._memoryStore.depend.protobuf; var script = this.script; script.src = url; this.head.appendChild(script); script.onload = script.onreadystatechange = function () { var isLoaded = (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete'); if (isLoaded) { // 防止 IE6、7 下偶发触发两次 loaded script.onload = script.onreadystatechange = null; if (callback) { callback(); } if (!callback) { var token = RongIMLib.RongIMClient._memoryStore.token; var connectCallback = RongIMLib.RongIMClient._memoryStore.callback; token && RongIMLib.RongIMClient.connect(token, connectCallback); } } }; } } else { RongIMLib.Transportations._TransportType = "xhr-polling"; RongIMLib.RongIMClient.Protobuf = Polling; } } return FeatureDectector; })(); RongIMLib.FeatureDectector = FeatureDectector; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var FeaturePatcher = (function () { function FeaturePatcher() { } FeaturePatcher.prototype.patchAll = function () { this.patchJSON(); this.patchForEach(); }; FeaturePatcher.prototype.patchForEach = function () { if (!Array.forEach) { Array.forEach = function (arr, func) { for (var i = 0; i < arr.length; i++) { func.call(arr, arr[i], i, arr); } }; } }; FeaturePatcher.prototype.patchJSON = function () { if (!window["JSON"]) { window["JSON"] = (function () { function JSON() { } JSON.parse = function (sJSON) { return eval('(' + sJSON + ')'); }; JSON.stringify = function (value) { return this.str("", { "": value }); }; JSON.str = function (key, holder) { var i, k, v, length, mind = "", partial, value = holder[key], me = this; if (value && typeof value === "object" && typeof value.toJSON === "function") { value = value.toJSON(key); } switch (typeof value) { case "string": return me.quote(value); case "number": return isFinite(value) ? String(value) : "null"; case "boolean": case "null": return String(value); case "object": if (!value) { return "null"; } partial = []; if (Object.prototype.toString.apply(value) === "[object Array]") { length = value.length; for (i = 0; i < length; i += 1) { partial[i] = me.str(i, value) || "null"; } v = partial.length === 0 ? "[]" : "[" + partial.join(",") + "]"; return v; } for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = me.str(k, value); if (v) { partial.push(me.quote(k) + ":" + v); } } } v = partial.length === 0 ? "{}" : "{" + partial.join(",") + "}"; return v; } }; JSON.quote = function (string) { var me = this; me.rx_escapable.lastIndex = 0; return me.rx_escapable.test(string) ? '"' + string.replace(me.rx_escapable, function (a) { var c = me.meta[a]; return typeof c === "string" ? c : "\\u" + ("0000" + a.charCodeAt(0).toString(16)).slice(-4); }) + '"' : '"' + string + '"'; }; JSON.rx_escapable = new RegExp('[\\\"\\\\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]', "g"); JSON.meta = { "\b": "\\b", " ": "\\t", "\n": "\\n", "\f": "\\f", "\r": "\\r", '"': '\\"', "''": "\\''", "\\": "\\\\" }; return JSON; })(); } }; return FeaturePatcher; })(); RongIMLib.FeaturePatcher = FeaturePatcher; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var ScriptLoader = (function () { function ScriptLoader() { } ScriptLoader.prototype.load = function (src, onLoad, onError) { var script = document.createElement("script"); script.async = true; if (onLoad) { if (script.addEventListener) { script.addEventListener("load", function (event) { var target = event.target || event.srcElement; onLoad(target.src); }, false); } else if (script.readyState) { script.onreadystatechange = function (event) { var target = event.srcElement; onLoad(target.src); }; } } if (onError) { script.onerror = function (event) { var target = event.target || event.srcElement; onError(target.src); }; } (document.head || document.getElementsByTagName("head")[0]).appendChild(script); script.src = src; }; return ScriptLoader; })(); })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var PublicServiceMap = (function () { function PublicServiceMap() { this.publicServiceList = []; } PublicServiceMap.prototype.get = function (publicServiceType, publicServiceId) { for (var i = 0, len = this.publicServiceList.length; i < len; i++) { if (this.publicServiceList[i].conversationType == publicServiceType && publicServiceId == this.publicServiceList[i].publicServiceId) { return this.publicServiceList[i]; } } }; PublicServiceMap.prototype.add = function (publicServiceProfile) { var isAdd = true, me = this; for (var i = 0, len = this.publicServiceList.length; i < len; i++) { if (me.publicServiceList[i].conversationType == publicServiceProfile.conversationType && publicServiceProfile.publicServiceId == me.publicServiceList[i].publicServiceId) { this.publicServiceList.unshift(this.publicServiceList.splice(i, 1)[0]); isAdd = false; break; } } if (isAdd) { this.publicServiceList.unshift(publicServiceProfile); } }; PublicServiceMap.prototype.replace = function (publicServiceProfile) { var me = this; for (var i = 0, len = this.publicServiceList.length; i < len; i++) { if (me.publicServiceList[i].conversationType == publicServiceProfile.conversationType && publicServiceProfile.publicServiceId == me.publicServiceList[i].publicServiceId) { me.publicServiceList.splice(i, 1, publicServiceProfile); break; } } }; PublicServiceMap.prototype.remove = function (conversationType, publicServiceId) { var me = this; for (var i = 0, len = this.publicServiceList.length; i < len; i++) { if (me.publicServiceList[i].conversationType == conversationType && publicServiceId == me.publicServiceList[i].publicServiceId) { this.publicServiceList.splice(i, 1); break; } } }; return PublicServiceMap; })(); RongIMLib.PublicServiceMap = PublicServiceMap; /** * 会话工具类。 */ var ConversationMap = (function () { function ConversationMap() { this.conversationList = []; } ConversationMap.prototype.get = function (conversavtionType, targetId) { for (var i = 0, len = this.conversationList.length; i < len; i++) { if (this.conversationList[i].conversationType == conversavtionType && this.conversationList[i].targetId == targetId) { return this.conversationList[i]; } } return null; }; ConversationMap.prototype.add = function (conversation) { var isAdd = true; for (var i = 0, len = this.conversationList.length; i < len; i++) { if (this.conversationList[i].conversationType === conversation.conversationType && this.conversationList[i].targetId === conversation.targetId) { this.conversationList.unshift(this.conversationList.splice(i, 1)[0]); isAdd = false; break; } } if (isAdd) { this.conversationList.unshift(conversation); } }; /** * [replace 替换会话] * 会话数组存在的情况下调用add方法会是当前会话被替换且返回到第一个位置,导致用户本地一些设置失效,所以提供replace方法 */ ConversationMap.prototype.replace = function (conversation) { for (var i = 0, len = this.conversationList.length; i < len; i++) { if (this.conversationList[i].conversationType === conversation.conversationType && this.conversationList[i].targetId === conversation.targetId) { this.conversationList.splice(i, 1, conversation); break; } } }; ConversationMap.prototype.remove = function (conversation) { for (var i = 0, len = this.conversationList.length; i < len; i++) { if (this.conversationList[i].conversationType === conversation.conversationType && this.conversationList[i].targetId === conversation.targetId) { this.conversationList.splice(i, 1); break; } } }; return ConversationMap; })(); RongIMLib.ConversationMap = ConversationMap; var CheckParam = (function () { function CheckParam() { } CheckParam.getInstance = function () { if (!CheckParam._instance) { CheckParam._instance = new CheckParam(); } return CheckParam._instance; }; CheckParam.prototype.logger = function (code, funcName, msg) { RongIMLib.RongIMClient.logger({ code: code, funcName: funcName, msg: msg }); }; CheckParam.prototype.check = function (f, position, d, c) { if (RongIMLib.RongIMClient._dataAccessProvider || d) { for (var g = 0, e = c.length; g < e; g++) { if (!new RegExp(this.getType(c[g])).test(f[g])) { // throw new Error("The index of " + g + " parameter was wrong type " + this.getType(c[g]) + " [" + f[g] + "] -> position:" + position); var msg = "第" + (g + 1) + "个参数错误, 错误类型:" + this.getType(c[g]) + " [" + f[g] + "] -> 位置:" + position; this.logger("-3", position, msg); } } } else { var msg = "该参数不正确或尚未实例化RongIMClient -> 位置:" + position; this.logger("-4", position, msg); } }; CheckParam.prototype.getType = function (str) { var temp = Object.prototype.toString.call(str).toLowerCase(); return temp.slice(8, temp.length - 1); }; CheckParam.prototype.checkCookieDisable = function () { document.cookie = "checkCookie=1"; var arr = document.cookie.match(new RegExp("(^| )checkCookie=([^;]*)(;|$)")), isDisable = false; if (!arr) { isDisable = true; } document.cookie = "checkCookie=1;expires=Thu, 01-Jan-1970 00:00:01 GMT"; return isDisable; }; return CheckParam; })(); RongIMLib.CheckParam = CheckParam; var LimitableMap = (function () { function LimitableMap(limit) { this.map = {}; this.keys = []; this.limit = limit || 10; } LimitableMap.prototype.set = function (key, value) { this.map[key] = value; }; LimitableMap.prototype.get = function (key) { return this.map[key] || 0; }; LimitableMap.prototype.remove = function (key) { delete this.map[key]; }; return LimitableMap; })(); RongIMLib.LimitableMap = LimitableMap; var MemoryCache = (function () { function MemoryCache() { this.cache = {}; } MemoryCache.prototype.set = function (key, value) { this.cache[key] = value; }; MemoryCache.prototype.get = function (key) { return this.cache[key]; }; MemoryCache.prototype.remove = function (key) { delete this.cache[key]; }; return MemoryCache; })(); RongIMLib.MemoryCache = MemoryCache; var RongAjax = (function () { function RongAjax(options) { var me = this; me.xmlhttp = null; me.options = options; var hasCORS = typeof XMLHttpRequest !== "undefined" && "withCredentials" in new XMLHttpRequest(); if ("undefined" != typeof XMLHttpRequest && hasCORS) { me.xmlhttp = new XMLHttpRequest(); } else if ("undefined" != typeof XDomainRequest) { me.xmlhttp = new XDomainRequest(); } else { me.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } } RongAjax.prototype.send = function (callback) { var me = this; me.options.url || (me.options.url = "http://upload.qiniu.com/putb64/-1"); me.xmlhttp.onreadystatechange = function () { if (me.xmlhttp.readyState == 4) { if (me.options.type) { callback(); } else { callback(JSON.parse(me.xmlhttp.responseText.replace(/'/g, '"'))); } } }; me.xmlhttp.open("POST", me.options.url, true); me.xmlhttp.withCredentials = false; if ("setRequestHeader" in me.xmlhttp) { if (me.options.type) { me.xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=utf-8"); } else { me.xmlhttp.setRequestHeader("Content-type", "application/octet-stream"); me.xmlhttp.setRequestHeader('Authorization', "UpToken " + me.options.token); } } me.xmlhttp.send(me.options.type ? "appKey=" + me.options.appKey + "&deviceId=" + me.options.deviceId + "×tamp=" + me.options.timestamp + "&deviceInfo=" + me.options.deviceInfo + "&privateInfo=" + JSON.stringify(me.options.privateInfo) : me.options.base64); }; return RongAjax; })(); RongIMLib.RongAjax = RongAjax; function Prosumer() { var data = [], isConsuming = false; this.produce = function (res) { data.push(res); }; this.consume = function (callback, finished) { if (isConsuming) { return; } isConsuming = true; var next = function () { var res = data.shift(); if (RongUtil.isUndefined(res)) { isConsuming = false; finished && finished(); return; } callback(res, next); }; next(); }; this.isExeuting = function () { return isConsuming; }; } var RongUtil = (function () { function RongUtil() { } RongUtil.noop = function () { }; RongUtil.isEmpty = function (obj) { var result = true; if (RongUtil.isObject(obj)) { RongUtil.forEach(obj, function () { result = false; }); } if (RongUtil.isString(obj) || RongUtil.isArray(obj)) { return obj.length === 0; } if (RongUtil.isNumber(obj)) { return obj === 0; } return result; }; RongUtil.isLengthLimit = function (str, maxLen, minLen) { minLen = minLen || 0; var strLen = str.length; return strLen <= maxLen && strLen >= minLen; }; RongUtil.MD5 = function (str, key, raw) { return md5(str, key, raw); }; RongUtil.isObject = function (obj) { return Object.prototype.toString.call(obj) == '[object Object]'; }; RongUtil.isArray = function (array) { return Object.prototype.toString.call(array) == '[object Array]'; }; RongUtil.isString = function (array) { return Object.prototype.toString.call(array) == '[object String]'; }; RongUtil.isFunction = function (fun) { return Object.prototype.toString.call(fun) == '[object Function]'; }; ; RongUtil.isUndefined = function (str) { return Object.prototype.toString.call(str) == '[object Undefined]'; }; ; RongUtil.isEqual = function (a, b) { return a === b; }; ; RongUtil.indexOf = function (arrs, item) { var index = -1; for (var i = 0; i < arrs.length; i++) { if (item === arrs[i]) { index = i; break; } } return index; }; RongUtil.stringFormat = function (tmpl, vals) { for (var i = 0, len = vals.length; i < len; i++) { var val = vals[i], reg = new RegExp("\\{" + (i) + "\\}", "g"); tmpl = tmpl.replace(reg, val); } return tmpl; }; RongUtil.tplEngine = function (temp, data, regexp) { if (!(Object.prototype.toString.call(data) === "[object Array]")) { data = [data]; } var ret = []; for (var i = 0, j = data.length; i < j; i++) { ret.push(replaceAction(data[i])); } return ret.join(""); function replaceAction(object) { return temp.replace(regexp || (/{([^}]+)}/g), function (match, name) { if (match.charAt(0) == '\\') { return match.slice(1); } return (object[name] != undefined) ? object[name] : '{' + name + '}'; }); } }; ; RongUtil.forEach = function (obj, callback) { callback = callback || RongUtil.noop; var loopObj = function () { for (var key in obj) { if (obj.hasOwnProperty(key)) { callback(obj[key], key, obj); } } }; var loopArr = function () { for (var i = 0, len = obj.length; i < len; i++) { callback(obj[i], i); } }; if (RongUtil.isObject(obj)) { loopObj(); } if (RongUtil.isArray(obj)) { loopArr(); } }; RongUtil.extend = function (source, target, callback, force) { RongUtil.forEach(source, function (val, key) { var hasProto = (key in target); if (force && hasProto) { target[key] = val; } if (!hasProto) { target[key] = val; } }); return target; }; RongUtil.createXHR = function () { var item = { XMLHttpRequest: function () { return new XMLHttpRequest(); }, XDomainRequest: function () { return new XDomainRequest(); }, ActiveXObject: function () { return new ActiveXObject('Microsoft.XMLHTTP'); } }; var isXHR = typeof XMLHttpRequest !== "undefined" && "withCredentials" in new XMLHttpRequest(); var isXDR = typeof XDomainRequest == 'function'; var key = isXHR ? 'XMLHttpRequest' : isXDR ? 'XDomainRequest' : 'ActiveXObject'; return item[key](); }; RongUtil.request = function (opts) { var url = opts.url; var success = opts.success; var error = opts.error; var method = opts.method || 'GET'; var xhr = RongUtil.createXHR(); if ('onload' in xhr) { xhr.onload = function () { xhr.onload = RongUtil.noop; success(xhr.responseText); }; xhr.onerror = function () { xhr.onerror = RongUtil.noop; }; } else { xhr.onreadystatechange = function () { if (xhr.readyState == 4) { var status = xhr.status; if (status == 200) { success(xhr.responseText); } else { error(status, xhr.responseText); } } }; } xhr.open(method, url, true); xhr.send(null); return xhr; }; RongUtil.formatProtoclPath = function (config) { var path = config.path; var protocol = config.protocol; var tmpl = config.tmpl || '{0}{1}'; var sub = config.sub; var flag = '://'; var index = path.indexOf(flag); var hasProtocol = (index > -1); if (hasProtocol) { index += flag.length; path = path.substring(index); } if (sub) { index = path.indexOf('/'); var hasPath = (index > -1); if (hasPath) { path = path.substr(0, index); } } return RongUtil.stringFormat(tmpl, [protocol, path]); }; ; RongUtil.getUrlHost = function (url) { var index = RongUtil.indexOf(url, '/'); return url.substring(0, index); }; RongUtil.supportLocalStorage = function () { var support = false; if (typeof localStorage == 'object') { try { var key = 'RC_TMP_KEY', value = 'RC_TMP_VAL'; localStorage.setItem(key, value); var localVal = localStorage.getItem(key); if (localVal == value) { support = true; } } catch (err) { console.log('localStorage is disabled.'); } } return support; }; /* //返回新引用,不破坏原始对象 rename({n: 'martin'}, {n: 'name'}); => {name: 'martin'} rename([{n: 'martin'}, {a: 18}], {n: 'name', a: 'age'}); => [{name: 'martin'}, {age: 18}] */ RongUtil.rename = function (origin, newNames) { var isObject = RongUtil.isObject(origin); if (isObject) { origin = [origin]; } origin = JSON.parse(JSON.stringify(origin)); var updateProperty = function (val, key, obj) { delete obj[key]; key = newNames[key]; obj[key] = val; }; RongUtil.forEach(origin, function (item) { RongUtil.forEach(item, function (val, key, obj) { var isRename = (key in newNames); (isRename ? updateProperty : RongUtil.noop)(val, key, obj); }); }); return isObject ? origin[0] : origin; }; RongUtil.some = function (arrs, callback) { var has = false; for (var i = 0, len = arrs.length; i < len; i++) { if (callback(arrs[i])) { has = true; break; } } return has; }; RongUtil.keys = function (obj) { var props = []; for (var key in obj) { props.push(key); } return props; }; RongUtil.isNumber = function (num) { return Object.prototype.toString.call(num) == '[object Number]'; }; RongUtil.getTimestamp = function () { var date = new Date(); return date.getTime(); }; RongUtil.isSupportRequestHeaders = function () { var userAgent = navigator.userAgent; var isIE = window.ActiveXObject || 'ActiveXObject' in window; if (isIE) { var reIE = new RegExp('MSIE (\\d+\\.\\d+);'); reIE.test(userAgent); var fIEVersion = parseFloat(RegExp['$1']); return fIEVersion > 9; } return true; }; RongUtil.hasValidWsUrl = function (urls) { try { urls = JSON.parse(urls); } catch (e) { return false; } var validUrlList = RongUtil.getValidWsUrlList(urls); return validUrlList.length > 0; }; RongUtil.getValidWsUrlList = function (urls) { var invalidWsUrls = RongIMLib.RongIMClient.invalidWsUrls; var validUrlList = []; RongUtil.forEach(urls, function (url) { if (RongUtil.indexOf(invalidWsUrls, url) === -1) { validUrlList.push(url); } }); return validUrlList; }; RongUtil.Prosumer = Prosumer; return RongUtil; })(); RongIMLib.RongUtil = RongUtil; /* var observer = new RongObserver(); observer.watch({ key: 'key', func: function(entity){ } }); */ var RongObserver = (function () { function RongObserver() { this.watchers = {}; } RongObserver.prototype.genUId = function (key) { var time = new Date().getTime(); return [key, time].join('_'); }; RongObserver.prototype.watch = function (params) { var me = this; var key = params.key; var multiple = params.multiple; key = RongUtil.isArray(key) ? key : [key]; var func = params.func; RongUtil.forEach(key, function (k) { k = multiple ? me.genUId(k) : k; me.watchers[k] = func; }); }; RongObserver.prototype.notify = function (params) { var me = this; var key = params.key; var entity = params.entity; for (var k in me.watchers) { var isNotify = (k.indexOf(key) == 0); if (isNotify) { me.watchers[k](entity); } } }; RongObserver.prototype.remove = function () { }; return RongObserver; })(); RongIMLib.RongObserver = RongObserver; var Observer = (function () { function Observer() { this.observers = []; } Observer.prototype.add = function (observer, force) { if (force) { this.observers = [observer]; } if (RongUtil.isFunction(observer)) { this.observers.push(observer); } }; Observer.prototype.emit = function (data) { RongUtil.forEach(this.observers, function (observer) { observer(data); }); }; Observer.prototype.clear = function () { this.observers = []; }; Observer.prototype.checkIndexOutBound = function (index, bound) { var isOutBound = (index > -1 && index < bound); return isOutBound; }; Observer.prototype.removeAt = function (index) { var isOutBound = this.checkIndexOutBound(index, this.observers.length); if (isOutBound) { this.observers.splice(index, 1); } }; Observer.prototype.remove = function (observer) { var me = this; if (!observer) { me.clear(); return; } if (!RongUtil.isFunction(observer)) { return; } var observerList = me.observers; for (var i = observerList.length - 1; i >= 0; i--) { if (observer === observerList[i]) { me.removeAt(i); } } }; return Observer; })(); RongIMLib.Observer = Observer; var Timer = (function () { function Timer(config) { this.timeout = 0; this.timers = []; this.timeout = config.timeout; } Timer.prototype.resume = function (callback) { var timer = setTimeout(callback, this.timeout); this.timers.push(timer); }; Timer.prototype.pause = function () { RongUtil.forEach(this.timers, function (timer) { clearTimeout(timer); }); }; return Timer; })(); RongIMLib.Timer = Timer; var IndexTools = (function () { function IndexTools(config) { this.items = []; this.index = 0; this.onwheel = function () { }; this.items = config.items; this.onwheel = config.onwheel; } IndexTools.prototype.get = function () { var context = this; var items = context.items; var index = context.index; var isWheel = index >= items.length; if (isWheel) { context.onwheel(); } return isWheel ? 0 : index; }; IndexTools.prototype.add = function () { this.index += 1; }; return IndexTools; })(); RongIMLib.IndexTools = IndexTools; var InnerUtil = (function () { function InnerUtil() { } InnerUtil.getUId = function (token) { return md5(token).slice(8, 16); }; return InnerUtil; })(); RongIMLib.InnerUtil = InnerUtil; })(RongIMLib || (RongIMLib = {})); // {WebEnd} WebSDK 内容开始的标识, 方便小程序 SDK 定位 /* 说明: 请勿修改 header.js 和 footer.js 用途: 自动拼接暴露方式 命令: grunt release 中 concat */ return RongIMLib; }); ================================================ FILE: api-test-v2/lib/js/RongIMLib-2.5.6.js ================================================ /* 说明: 请勿修改 header.js 和 footer.js 用途: 自动拼接暴露方式 命令: grunt release 中 concat */ (function(global, factory) { if (typeof exports === 'object' && typeof module !== 'undefined') { module.exports = factory(); } else if (typeof define === 'function' && (define.amd || define.cmd)) { define(factory); } else { var tempIMLib = factory(); var tempClient = tempIMLib.RongIMClient; var isExists = (!!global.RongIMLib); if (isExists) { var currentClient = RongIMLib.RongIMClient || {}; for(var key in currentClient){ tempClient[key] = currentClient[key]; } } global.RongIMLib = tempIMLib; global.RongIMClient = tempClient; } })(window, function(){ // {WebStart} WebSDK 内容开始的标识, 方便小程序 SDK 定位 var Polling = { SetUserStatusInput: function(){ var a = {}; this.setStatus = function(b){ a.status = b; }; this.toArrayBuffer = function(){ return a; }; }, SetUserStatusOutput: function(){ var a = {}; this.setNothing = function(b){ a.nothing = b; }; this.toArrayBuffer = function(){ return a; }; }, GetUserStatusInput: function(){ var a = {}; this.setNothing = function(b){ a.nothing = b; }; this.toArrayBuffer = function(){ return a; }; }, GetUserStatusOutput: function(){ var a = {}; this.setStatus = function(b){ a.status = b; }; this.setSubUserId = function(b){ a.subUserId = b; }; this.toArrayBuffer = function(){ return a; }; }, VoipDynamicInput: function(){ var a = {}; this.setEngineType = function(b){ a.engineType = b; }; this.setChannelName = function(b){ a.channelName = b; }; this.setChannelExtra = function(b){ a.channelExtra = b; }; this.toArrayBuffer = function(){ return a; }; }, VoipDynamicOutput: function(){ var a = {}; this.setDynamicKey = function(b){ a.dynamicKey = b; }; this.toArrayBuffer = function(){ return a; }; }, SubUserStatusInput: function(){ var a = {}; this.setUserid = function(b){ a.userid = b; }; this.toArrayBuffer = function(){ return a; }; }, SubUserStatusOutput: function(){ var a = {}; this.setNothing = function(b){ a.nothing = b; }; this.toArrayBuffer = function(){ return a; }; }, CleanHisMsgInput: function(){ var a = {}; this.setTargetId = function(b){ a.targetId = b; }; this.setDataTime = function(b){ a.dataTime = b; }; this.setConversationType = function(b){ a.conversationType = b; }; this.toArrayBuffer = function(){ return a; }; }, DeleteMsgInput:function(){ var a = {}; this.setType = function(b){ a.type = b; }; this.setConversationId = function(b){ a.conversationId = b; }; this.setMsgs = function(b){ a.msgs = b; }; this.toArrayBuffer = function () { return a; } }, DeleteMsg:function(){ var a = {}; this.setMsgId = function(b){ a.msgId = b; }; this.setMsgDataTime = function(b){ a.msgDataTime = b; }; this.setDirect = function(b){ a.direct = b; }; this.toArrayBuffer = function () { return a; } }, DeleteMsgOutput:function(){ var a = {}; this.setNothing = function(b){ a.nothing = b; }; this.toArrayBuffer = function () { return a; } }, SearchMpInput:function(){ var a = {}; this.setType = function (b) { a.type = b; }; this.setId = function (b) { a.id = b; }; this.toArrayBuffer = function () { return a; } }, SearchMpOutput:function(){ var a = {}; this.setNothing = function (b) { a.nothing = b; }; this.setInfo = function (b) { a.info = b; }; this.toArrayBuffer = function () { return a; } }, MpInfo:function(){ var a = {}; this.setMpid = function(b){ a.mpid = b; }; this.setName = function(b){ a.name = b; }; this.setType = function(b){ a.type = b; }; this.setTime = function(b){ a.time = b; }; this.setPortraitUri = function(b){ a.portraitUrl = b; }; this.setExtra = function(b){ a.extra = b; }; this.toArrayBuffer = function () { return a; } }, PullMpInput:function(){ var a = {}; this.setMpid = function(b){ a.mpid = b; }; this.setTime = function(b){ a.time = b; }; this.toArrayBuffer = function () { return a; }; }, PullMpOutput:function(){ var a = {}; this.setStatus = function(b){ a.status = b; } this.setInfo = function(b){ a.info = b; }; this.toArrayBuffer = function () { return a; }; }, MPFollowInput:function(){ var a = {}; this.setId = function(b){ a.id = b; }; this.toArrayBuffer = function () { return a; }; }, MPFollowOutput:function(){ var a = {}; this.setNothing = function(b){ a.nothing = b; }; this.setInfo = function(b){ a.info = b; }; this.toArrayBuffer = function () { return a; }; }, NotifyMsg: function () { var a = {}; this.setType = function (b) { a.type = b; }; this.setTime = function (b) { a.time = b; }; this.setChrmId = function(b){ a.chrmId = b; }; this.toArrayBuffer = function () { return a; }; }, SyncRequestMsg: function () { var a = {}; this.setSyncTime = function (b) { a.syncTime = b || 0; }; this.setIspolling = function (b) { a.ispolling = !!b; }; this.setIsweb = function (b) { a.isweb = !!b; }; this.setIsPullSend = function (b) { a.isPullSend = !!b; }; this.setSendBoxSyncTime = function (b) { a.sendBoxSyncTime = b; }; this.toArrayBuffer = function () { return a; }; }, UpStreamMessage: function () { var a = {}; this.setSessionId = function (b) { a.sessionId = b }; this.setClassname = function (b) { a.classname = b }; this.setContent = function (b) { if (b) a.content = b; }; this.setPushText = function (b) { a.pushText = b }; this.setUserId = function(b){ a.userId = b; }; this.setConfigFlag = function (b) { a.configFlag = b; }; this.setAppData = function(b){ a.appData = b; }; this.toArrayBuffer = function () { return a }; }, DownStreamMessages: function () { var a = {}; this.setList = function (b) { a.list = b }; this.setSyncTime = function (b) { a.syncTime = b; }; this.setFinished = function(b){ a.finished = b; }; this.toArrayBuffer = function () { return a }; }, DownStreamMessage: function () { var a = {}; this.setFromUserId = function (b) { a.fromUserId = b }; this.setType = function (b) { a.type = b }; this.setGroupId = function (b) { a.groupId = b }; this.setClassname = function (b) { a.classname = b }; this.setContent = function (b) { if (b) a.content = b }; this.setDataTime = function (b) { a.dataTime = b; }; this.setStatus = function (b) { a.status = b; }; this.setMsgId = function (b) { a.msgId = b; }; this.toArrayBuffer = function () { return a; }; }, CreateDiscussionInput: function () { var a = {}; this.setName = function (b) { a.name = b }; this.toArrayBuffer = function () { return a } }, CreateDiscussionOutput: function () { var a = {}; this.setId = function (b) { a.id = b }; this.toArrayBuffer = function () { return a }; }, ChannelInvitationInput: function () { var a = {}; this.setUsers = function (b) { a.users = b }; this.toArrayBuffer = function () { return a }; }, LeaveChannelInput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b }; this.toArrayBuffer = function () { return a }; }, QueryChatroomInfoInput:function(){ var a = {}; this.setCount = function (b) { a.count = b; }; this.setOrder = function (b) { a.order = b; }; this.toArrayBuffer = function () { return a }; }, QueryChatroomInfoOutput:function(){ var a = {}; this.setUserTotalNums = function (b) { a.userTotalNums = b; }; this.setUserInfos = function (b) { a.userInfos = b; }; this.toArrayBuffer = function () { return a; }; }, ChannelEvictionInput: function () { var a = {}; this.setUser = function (b) { a.user = b }; this.toArrayBuffer = function () { return a }; }, RenameChannelInput: function () { var a = {}; this.setName = function (b) { a.name = b }; this.toArrayBuffer = function () { return a } }, ChannelInfoInput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b }; this.toArrayBuffer = function () { return a } }, ChannelInfoOutput: function () { var a = {}; this.setType = function (b) { a.type = b }; this.setChannelId = function (b) { a.channelId = b }; this.setChannelName = function (b) { a.channelName = b }; this.setAdminUserId = function (b) { a.adminUserId = b }; this.setFirstTenUserIds = function (b) { a.firstTenUserIds = b }; this.setOpenStatus = function (b) { a.openStatus = b }; this.toArrayBuffer = function () { return a } }, ChannelInfosInput: function () { var a = {}; this.setPage = function (b) { a.page = b }; this.setNumber = function (b) { a.number = b }; this.toArrayBuffer = function () { return a }; }, ChannelInfosOutput: function () { var a = {}; this.setChannels = function (b) { a.channels = b }; this.setTotal = function (b) { a.total = b }; this.toArrayBuffer = function () { return a }; }, MemberInfo: function () { var a = {}; this.setUserId = function (b) { a.userId = b }; this.setUserName = function (b) { a.userName = b }; this.setUserPortrait = function (b) { a.userPortrait = b }; this.setExtension = function (b) { a.extension = b }; this.toArrayBuffer = function () { return a }; }, GroupMembersInput: function () { var a = {}; this.setPage = function (b) { a.page = b }; this.setNumber = function (b) { a.number = b }; this.toArrayBuffer = function () { return a }; }, GroupMembersOutput: function () { var a = {}; this.setMembers = function (b) { a.members = b }; this.setTotal = function (b) { a.total = b }; this.toArrayBuffer = function () { return a }; }, GetUserInfoInput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b }; this.toArrayBuffer = function () { return a }; }, GetUserInfoOutput: function () { var a = {}; this.setUserId = function (b) { a.userId = b }; this.setUserName = function (b) { a.userName = b }; this.setUserPortrait = function (b) { a.userPortrait = b }; this.toArrayBuffer = function () { return a }; }, GetSessionIdInput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b }; this.toArrayBuffer = function () { return a }; }, GetSessionIdOutput: function () { var a = {}; this.setSessionId = function (b) { a.sessionId = b }; this.toArrayBuffer = function () { return a }; }, GetQNupTokenInput: function () { var a = {}; this.setType = function (b) { a.type = b; } this.toArrayBuffer = function () { return a } }, GetQNupTokenOutput: function () { var a = {}; this.setDeadline = function (b) { a.deadline = b }; this.setToken = function (b) { a.token = b; }; this.toArrayBuffer = function () { return a } }, GetQNdownloadUrlInput: function () { var a = {}; this.setType = function (b) { a.type = b; }; this.setKey = function (b) { a.key = b; }; this.setFileName = function(b){ a.fileName = b; }; this.toArrayBuffer = function () { return a } }, GetQNdownloadUrlOutput: function () { var a = {}; this.setDownloadUrl = function (b) { a.downloadUrl = b; }; this.toArrayBuffer = function () { return a } }, Add2BlackListInput: function () { var a = {}; this.setUserId = function (b) { a.userId = b; }; this.toArrayBuffer = function () { return a } }, RemoveFromBlackListInput: function () { var a = {}; this.setUserId = function (b) { a.userId = b; }; this.toArrayBuffer = function () { return a } }, QueryBlackListInput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b; }; this.toArrayBuffer = function () { return a } }, QueryBlackListOutput: function () { var a = {}; this.setUserIds = function (b) { a.userIds = b; }; this.toArrayBuffer = function () { return a } }, BlackListStatusInput: function () { var a = {}; this.setUserId = function (b) { a.userId = b; }; this.toArrayBuffer = function () { return a } }, BlockPushInput: function () { var a = {}; this.setBlockeeId = function (b) { a.blockeeId = b; }; this.toArrayBuffer = function () { return a } }, ModifyPermissionInput: function () { var a = {}; this.setOpenStatus = function (b) { a.openStatus = b; }; this.toArrayBuffer = function () { return a }; }, GroupInput: function () { var a = {}; this.setGroupInfo = function (b) { for (var i = 0, arr = []; i < b.length; i++) { arr.push({id: b[i].getContent().id, name: b[i].getContent().name}) } a.groupInfo = arr; }; this.toArrayBuffer = function () { return a }; }, GroupOutput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b; }; this.toArrayBuffer = function () { return a }; }, GroupInfo: function () { var a = {}; this.setId = function (b) { a.id = b; }; this.setName = function (b) { a.name = b; }; this.getContent = function () { return a; }; this.toArrayBuffer = function () { return a }; }, GroupHashInput: function () { var a = {}; this.setUserId = function (b) { a.userId = b; }; this.setGroupHashCode = function (b) { a.groupHashCode = b; }; this.toArrayBuffer = function () { return a }; }, GroupHashOutput: function () { var a = {}; this.setResult = function (b) { a.result = b; }; this.toArrayBuffer = function () { return a }; }, ChrmInput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b; }; this.toArrayBuffer = function () { return a }; }, ChrmOutput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b; }; this.toArrayBuffer = function () { return a }; }, ChrmPullMsg: function () { var a = {}; this.setSyncTime = function (b) { a.syncTime = b }; this.setCount = function (b) { a.count = b; }; this.toArrayBuffer = function () { return a }; }, RelationsInput: function () { var a = {}; this.setType = function (b) { a.type = b; }; this.setMsg = function(b){ a.msg = b; }; this.setCount = function(b){ a.count = b; }; this.toArrayBuffer = function () { return a }; }, RelationsOutput: function () { var a = {}; this.setInfo = function (b) { a.info = b; }; this.toArrayBuffer = function () { return a } }, RelationInfo: function () { var a = {}; this.setType = function (b) { a.type = b; }; this.setUserId = function (b) { a.userId = b; }; this.setMsg = function(b){ a.msg = b; }; this.toArrayBuffer = function () { return a } }, HistoryMessageInput: function () { var a={}; this.setTargetId=function(b){ a.targetId=b; }; this.setDataTime=function(b){ a.dataTime=b; }; this.setSize=function(b){ a.size=b; }; this.toArrayBuffer = function () { return a } }, HistoryMessagesOuput: function () { var a={}; this.setList=function(b){ a.list=b; }; this.setSyncTime=function(b){ a.syncTime=b; }; this.setHasMsg=function(b){ a.hasMsg=b; }; this.toArrayBuffer = function () { return a } }, HistoryMsgInput: function(){ var a = {}; this.setTargetId = function(b){ a.targetId = b; }; this.setTime = function(b){ a.time = b; }; this.setCount = function(b){ a.count = b; }; this.setOrder = function(b){ a.order = b; }; this.toArrayBuffer = function(){ return a; }; }, HistoryMsgOuput: function(){ var a = {}; this.setList = function(b){ a.list = b; }; this.setSyncTime = function(b){ a.syncTime = b; }; this.setHasMsg = function(b){ a.hasMsg = b; }; this.toArrayBuffer = function(){ return a; }; }, RtcQueryListInput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setOrder = function (b) { a.order = b; }; }, RtcKeyDeleteInput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setKey = function (b) { a.key = b; }; }, RtcValueInfo: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setKey = function (b) { a.key = b; }; this.setValue = function (b) { a.value = b; }; }, // RtcUserInfo: function () { // var a = {}; // }, RtcUserListOutput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setList = function (b) { a.list = b; }; this.setToken = function (b) { a.token = b; }; }, RtcRoomInfoOutput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setRoomId = function (b) { a.roomId = b; }; this.setRoomData = function (b) { a.roomData = b; }; this.setUserCount = function (b) { a.userCount = b; }; this.setList = function (b) { a.list = b; } }, RtcInput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setRoomType = function (b) { a.roomType = b; }; this.setBroadcastType = function (b) { a.broadcastType = b; } }, // RtcQryInput: function () { // var a = {}; // }, RtcQryOutput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setOutInfo = function (b) { a.outInfo = b; }; }, // RtcDelDataInput: function () { // var a = {}; // }, RtcDataInput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setInterior = function (b) { a.interior = b; }; this.setTarget = function (b) { a.target = b; }; this.setKey = function (b) { a.key = b; }; this.setObjectName = function (b) { a.objectName = b; }; this.setContent = function (b) { a.content = b; }; }, RtcSetDataInput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setInterior = function (b) { a.interior = b; }; this.setTarget = function (b) { a.target = b; }; this.setKey = function (b) { a.key = b; }; this.setValue = function (b) { a.value = b; }; this.setObjectName = function (b) { a.objectName = b; }; this.setContent = function (b) { a.content = b; }; }, RtcOutput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setNothing = function (b) { a.nothing = b; }; }, RtcTokenOutput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setRtcToken = function (b) { a.rtcToken = b; } }, /** * 聊天室 KV 存储 */ ChrmNotifyMsg: function () { var a = {}; this.toArrayBuffer = function () { return a; }; this.setType = function (b) { a.type = b; }; this.setTime = function (b) { a.time = b; }; this.setChrmId = function (b) { a.chrmId = b; }; }, ChrmKVEntity: function () { var a = {}; this.toArrayBuffer = function () { return a; }; this.setKey = function (key) { a.key = key; }; this.setValue = function (value) { a.value = value; }; this.setStatus = function (b) { a.status = b; }; this.setTimestamp = function (b) { a.timestamp = b; }; this.setUid = function (b) { a.uid = b; }; }, SetChrmKV: function () { var a = {}; this.toArrayBuffer = function () { return a; }; this.setEntry = function (b) { a.entry = b; }; this.setNotification = function (b) { a.notification = b.toArrayBuffer(); }; this.setBNotify = function (b) { a.bNotify = b; }; this.setType = function (b) { a.type = b; }; }, ChrmKVOutput: function () { var a = {}; this.toArrayBuffer = function () { return a; }; this.setEntries = function (b) { this.entries = b; }; this.setBFullUpdate = function (b) { this.bFullUpdate = b; }; this.setSyncTime = function (b) { this.syncTime = b; }; }, QueryChrmKV: function () { var a = {}; this.toArrayBuffer = function () { return a; }; this.setTimestamp = function (b) { a.timestamp = b; }; }, DeleteChrmKV: function () { var a = {}; this.toArrayBuffer = function () { return a; }; this.setEntry = function (b) { a.entry = b; }; this.setBNotify = function (b) { a.bNotify = b; }; this.setNotification = function (b) { a.notification = b.toArrayBuffer(); }; this.setType = function (b) { a.type = b; }; } }; for (var f in Polling) { Polling[f].decode = function (b) { var back = {}, val = JSON.parse(b) || eval("(" + b + ")"); for (var i in val) { back[i]=val[i]; back["get"+ i.charAt(0).toUpperCase()+i.slice(1)]=function(){ return val[i]; } } return back; } } /* * JavaScript MD5 * https://github.com/blueimp/JavaScript-MD5 * * Copyright 2011, Sebastian Tschan * https://blueimp.net * * Licensed under the MIT license: * http://www.opensource.org/licenses/MIT * * Based on * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message * Digest Algorithm, as defined in RFC 1321. * Version 2.2 Copyright (C) Paul Johnston 1999 - 2009 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet * Distributed under the BSD License * See http://pajhome.org.uk/crypt/md5 for more info. */ /*jslint bitwise: true */ /*global unescape, define, module */ var md5 = (function () { 'use strict'; /* * Add integers, wrapping at 2^32. This uses 16-bit operations internally * to work around bugs in some JS interpreters. */ function safe_add(x, y) { var lsw = (x & 0xFFFF) + (y & 0xFFFF), msw = (x >> 16) + (y >> 16) + (lsw >> 16); return (msw << 16) | (lsw & 0xFFFF); } /* * Bitwise rotate a 32-bit number to the left. */ function bit_rol(num, cnt) { return (num << cnt) | (num >>> (32 - cnt)); } /* * These functions implement the four basic operations the algorithm uses. */ function md5_cmn(q, a, b, x, s, t) { return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s), b); } function md5_ff(a, b, c, d, x, s, t) { return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t); } function md5_gg(a, b, c, d, x, s, t) { return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t); } function md5_hh(a, b, c, d, x, s, t) { return md5_cmn(b ^ c ^ d, a, b, x, s, t); } function md5_ii(a, b, c, d, x, s, t) { return md5_cmn(c ^ (b | (~d)), a, b, x, s, t); } /* * Calculate the MD5 of an array of little-endian words, and a bit length. */ function binl_md5(x, len) { /* append padding */ x[len >> 5] |= 0x80 << (len % 32); x[(((len + 64) >>> 9) << 4) + 14] = len; var i, olda, oldb, oldc, oldd, a = 1732584193, b = -271733879, c = -1732584194, d = 271733878; for (i = 0; i < x.length; i += 16) { olda = a; oldb = b; oldc = c; oldd = d; a = md5_ff(a, b, c, d, x[i], 7, -680876936); d = md5_ff(d, a, b, c, x[i + 1], 12, -389564586); c = md5_ff(c, d, a, b, x[i + 2], 17, 606105819); b = md5_ff(b, c, d, a, x[i + 3], 22, -1044525330); a = md5_ff(a, b, c, d, x[i + 4], 7, -176418897); d = md5_ff(d, a, b, c, x[i + 5], 12, 1200080426); c = md5_ff(c, d, a, b, x[i + 6], 17, -1473231341); b = md5_ff(b, c, d, a, x[i + 7], 22, -45705983); a = md5_ff(a, b, c, d, x[i + 8], 7, 1770035416); d = md5_ff(d, a, b, c, x[i + 9], 12, -1958414417); c = md5_ff(c, d, a, b, x[i + 10], 17, -42063); b = md5_ff(b, c, d, a, x[i + 11], 22, -1990404162); a = md5_ff(a, b, c, d, x[i + 12], 7, 1804603682); d = md5_ff(d, a, b, c, x[i + 13], 12, -40341101); c = md5_ff(c, d, a, b, x[i + 14], 17, -1502002290); b = md5_ff(b, c, d, a, x[i + 15], 22, 1236535329); a = md5_gg(a, b, c, d, x[i + 1], 5, -165796510); d = md5_gg(d, a, b, c, x[i + 6], 9, -1069501632); c = md5_gg(c, d, a, b, x[i + 11], 14, 643717713); b = md5_gg(b, c, d, a, x[i], 20, -373897302); a = md5_gg(a, b, c, d, x[i + 5], 5, -701558691); d = md5_gg(d, a, b, c, x[i + 10], 9, 38016083); c = md5_gg(c, d, a, b, x[i + 15], 14, -660478335); b = md5_gg(b, c, d, a, x[i + 4], 20, -405537848); a = md5_gg(a, b, c, d, x[i + 9], 5, 568446438); d = md5_gg(d, a, b, c, x[i + 14], 9, -1019803690); c = md5_gg(c, d, a, b, x[i + 3], 14, -187363961); b = md5_gg(b, c, d, a, x[i + 8], 20, 1163531501); a = md5_gg(a, b, c, d, x[i + 13], 5, -1444681467); d = md5_gg(d, a, b, c, x[i + 2], 9, -51403784); c = md5_gg(c, d, a, b, x[i + 7], 14, 1735328473); b = md5_gg(b, c, d, a, x[i + 12], 20, -1926607734); a = md5_hh(a, b, c, d, x[i + 5], 4, -378558); d = md5_hh(d, a, b, c, x[i + 8], 11, -2022574463); c = md5_hh(c, d, a, b, x[i + 11], 16, 1839030562); b = md5_hh(b, c, d, a, x[i + 14], 23, -35309556); a = md5_hh(a, b, c, d, x[i + 1], 4, -1530992060); d = md5_hh(d, a, b, c, x[i + 4], 11, 1272893353); c = md5_hh(c, d, a, b, x[i + 7], 16, -155497632); b = md5_hh(b, c, d, a, x[i + 10], 23, -1094730640); a = md5_hh(a, b, c, d, x[i + 13], 4, 681279174); d = md5_hh(d, a, b, c, x[i], 11, -358537222); c = md5_hh(c, d, a, b, x[i + 3], 16, -722521979); b = md5_hh(b, c, d, a, x[i + 6], 23, 76029189); a = md5_hh(a, b, c, d, x[i + 9], 4, -640364487); d = md5_hh(d, a, b, c, x[i + 12], 11, -421815835); c = md5_hh(c, d, a, b, x[i + 15], 16, 530742520); b = md5_hh(b, c, d, a, x[i + 2], 23, -995338651); a = md5_ii(a, b, c, d, x[i], 6, -198630844); d = md5_ii(d, a, b, c, x[i + 7], 10, 1126891415); c = md5_ii(c, d, a, b, x[i + 14], 15, -1416354905); b = md5_ii(b, c, d, a, x[i + 5], 21, -57434055); a = md5_ii(a, b, c, d, x[i + 12], 6, 1700485571); d = md5_ii(d, a, b, c, x[i + 3], 10, -1894986606); c = md5_ii(c, d, a, b, x[i + 10], 15, -1051523); b = md5_ii(b, c, d, a, x[i + 1], 21, -2054922799); a = md5_ii(a, b, c, d, x[i + 8], 6, 1873313359); d = md5_ii(d, a, b, c, x[i + 15], 10, -30611744); c = md5_ii(c, d, a, b, x[i + 6], 15, -1560198380); b = md5_ii(b, c, d, a, x[i + 13], 21, 1309151649); a = md5_ii(a, b, c, d, x[i + 4], 6, -145523070); d = md5_ii(d, a, b, c, x[i + 11], 10, -1120210379); c = md5_ii(c, d, a, b, x[i + 2], 15, 718787259); b = md5_ii(b, c, d, a, x[i + 9], 21, -343485551); a = safe_add(a, olda); b = safe_add(b, oldb); c = safe_add(c, oldc); d = safe_add(d, oldd); } return [a, b, c, d]; } /* * Convert an array of little-endian words to a string */ function binl2rstr(input) { var i, output = ''; for (i = 0; i < input.length * 32; i += 8) { output += String.fromCharCode((input[i >> 5] >>> (i % 32)) & 0xFF); } return output; } /* * Convert a raw string to an array of little-endian words * Characters >255 have their high-byte silently ignored. */ function rstr2binl(input) { var i, output = []; output[(input.length >> 2) - 1] = undefined; for (i = 0; i < output.length; i += 1) { output[i] = 0; } for (i = 0; i < input.length * 8; i += 8) { output[i >> 5] |= (input.charCodeAt(i / 8) & 0xFF) << (i % 32); } return output; } /* * Calculate the MD5 of a raw string */ function rstr_md5(s) { return binl2rstr(binl_md5(rstr2binl(s), s.length * 8)); } /* * Calculate the HMAC-MD5, of a key and some data (raw strings) */ function rstr_hmac_md5(key, data) { var i, bkey = rstr2binl(key), ipad = [], opad = [], hash; ipad[15] = opad[15] = undefined; if (bkey.length > 16) { bkey = binl_md5(bkey, key.length * 8); } for (i = 0; i < 16; i += 1) { ipad[i] = bkey[i] ^ 0x36363636; opad[i] = bkey[i] ^ 0x5C5C5C5C; } hash = binl_md5(ipad.concat(rstr2binl(data)), 512 + data.length * 8); return binl2rstr(binl_md5(opad.concat(hash), 512 + 128)); } /* * Convert a raw string to a hex string */ function rstr2hex(input) { var hex_tab = '0123456789abcdef', output = '', x, i; for (i = 0; i < input.length; i += 1) { x = input.charCodeAt(i); output += hex_tab.charAt((x >>> 4) & 0x0F) + hex_tab.charAt(x & 0x0F); } return output; } /* * Encode a string as utf-8 */ function str2rstr_utf8(input) { return unescape(encodeURIComponent(input)); } /* * Take string arguments and return either raw or hex encoded strings */ function raw_md5(s) { return rstr_md5(str2rstr_utf8(s)); } function hex_md5(s) { return rstr2hex(raw_md5(s)); } function raw_hmac_md5(k, d) { return rstr_hmac_md5(str2rstr_utf8(k), str2rstr_utf8(d)); } function hex_hmac_md5(k, d) { return rstr2hex(raw_hmac_md5(k, d)); } function md5(string, key, raw) { if (!key) { if (!raw) { return hex_md5(string); } return raw_md5(string); } if (!raw) { return hex_hmac_md5(key, string); } return raw_hmac_md5(key, string); } return md5; }()); var RongIMLib; (function (RongIMLib) { (function (MentionedType) { MentionedType[MentionedType["ALL"] = 1] = "ALL"; MentionedType[MentionedType["PART"] = 2] = "PART"; })(RongIMLib.MentionedType || (RongIMLib.MentionedType = {})); var MentionedType = RongIMLib.MentionedType; (function (MethodType) { MethodType[MethodType["CUSTOMER_SERVICE"] = 1] = "CUSTOMER_SERVICE"; MethodType[MethodType["RECALL"] = 2] = "RECALL"; })(RongIMLib.MethodType || (RongIMLib.MethodType = {})); var MethodType = RongIMLib.MethodType; (function (BlacklistStatus) { /** * 在黑名单中。 */ BlacklistStatus[BlacklistStatus["IN_BLACK_LIST"] = 0] = "IN_BLACK_LIST"; /** * 不在黑名单中。 */ BlacklistStatus[BlacklistStatus["NOT_IN_BLACK_LIST"] = 1] = "NOT_IN_BLACK_LIST"; })(RongIMLib.BlacklistStatus || (RongIMLib.BlacklistStatus = {})); var BlacklistStatus = RongIMLib.BlacklistStatus; (function (ConnectionChannel) { ConnectionChannel[ConnectionChannel["XHR_POLLING"] = 0] = "XHR_POLLING"; ConnectionChannel[ConnectionChannel["WEBSOCKET"] = 1] = "WEBSOCKET"; //外部调用 ConnectionChannel[ConnectionChannel["HTTP"] = 0] = "HTTP"; //外部调用 ConnectionChannel[ConnectionChannel["HTTPS"] = 1] = "HTTPS"; })(RongIMLib.ConnectionChannel || (RongIMLib.ConnectionChannel = {})); var ConnectionChannel = RongIMLib.ConnectionChannel; (function (CustomerType) { CustomerType[CustomerType["ONLY_ROBOT"] = 1] = "ONLY_ROBOT"; CustomerType[CustomerType["ONLY_HUMAN"] = 2] = "ONLY_HUMAN"; CustomerType[CustomerType["ROBOT_FIRST"] = 3] = "ROBOT_FIRST"; CustomerType[CustomerType["HUMAN_FIRST"] = 4] = "HUMAN_FIRST"; })(RongIMLib.CustomerType || (RongIMLib.CustomerType = {})); var CustomerType = RongIMLib.CustomerType; (function (GetChatRoomType) { GetChatRoomType[GetChatRoomType["NONE"] = 0] = "NONE"; GetChatRoomType[GetChatRoomType["SQQUENCE"] = 1] = "SQQUENCE"; GetChatRoomType[GetChatRoomType["REVERSE"] = 2] = "REVERSE"; })(RongIMLib.GetChatRoomType || (RongIMLib.GetChatRoomType = {})); var GetChatRoomType = RongIMLib.GetChatRoomType; (function (ConnectionStatus) { /** * 连接成功。 */ ConnectionStatus[ConnectionStatus["CONNECTED"] = 0] = "CONNECTED"; /** * 连接中。 */ ConnectionStatus[ConnectionStatus["CONNECTING"] = 1] = "CONNECTING"; /** * 断开连接。 */ ConnectionStatus[ConnectionStatus["DISCONNECTED"] = 2] = "DISCONNECTED"; /** * 用户账户在其他设备登录,本机会被踢掉线。 */ ConnectionStatus[ConnectionStatus["KICKED_OFFLINE_BY_OTHER_CLIENT"] = 6] = "KICKED_OFFLINE_BY_OTHER_CLIENT"; /** * websocket 连接失败 */ ConnectionStatus[ConnectionStatus["WEBSOCKET_UNAVAILABLE"] = 7] = "WEBSOCKET_UNAVAILABLE"; /** * websocket 报错 */ ConnectionStatus[ConnectionStatus["WEBSOCKET_ERROR"] = 8] = "WEBSOCKET_ERROR"; /** * 网络不可用。 */ ConnectionStatus[ConnectionStatus["NETWORK_UNAVAILABLE"] = 3] = "NETWORK_UNAVAILABLE"; /** * 域名错误 */ ConnectionStatus[ConnectionStatus["DOMAIN_INCORRECT"] = 12] = "DOMAIN_INCORRECT"; /** * appkey 不正确 */ ConnectionStatus[ConnectionStatus["APPKEY_IS_FAKE"] = 20] = "APPKEY_IS_FAKE"; /** * 连接关闭。 */ ConnectionStatus[ConnectionStatus["CONNECTION_CLOSED"] = 4] = "CONNECTION_CLOSED"; /* 互踢次数过多(count > 5),此时可能出现:在其它他设备登陆有 reconnect 逻辑 */ ConnectionStatus[ConnectionStatus["ULTRALIMIT"] = 1101] = "ULTRALIMIT"; /* 开始请求导航 */ ConnectionStatus[ConnectionStatus["REQUEST_NAVI"] = 201] = "REQUEST_NAVI"; /* 请求导航结束 */ ConnectionStatus[ConnectionStatus["RESPONSE_NAVI"] = 202] = "RESPONSE_NAVI"; /* 请求导航失败 */ ConnectionStatus[ConnectionStatus["RESPONSE_NAVI_ERROR"] = 203] = "RESPONSE_NAVI_ERROR"; /* 请求导航超时 */ ConnectionStatus[ConnectionStatus["RESPONSE_NAVI_TIMEOUT"] = 204] = "RESPONSE_NAVI_TIMEOUT"; })(RongIMLib.ConnectionStatus || (RongIMLib.ConnectionStatus = {})); var ConnectionStatus = RongIMLib.ConnectionStatus; (function (ConversationNotificationStatus) { /** * 免打扰状态,关闭对应会话的通知提醒。 */ ConversationNotificationStatus[ConversationNotificationStatus["DO_NOT_DISTURB"] = 0] = "DO_NOT_DISTURB"; /** * 提醒。 */ ConversationNotificationStatus[ConversationNotificationStatus["NOTIFY"] = 1] = "NOTIFY"; })(RongIMLib.ConversationNotificationStatus || (RongIMLib.ConversationNotificationStatus = {})); var ConversationNotificationStatus = RongIMLib.ConversationNotificationStatus; (function (ConversationType) { ConversationType[ConversationType["NONE"] = 0] = "NONE"; ConversationType[ConversationType["PRIVATE"] = 1] = "PRIVATE"; ConversationType[ConversationType["DISCUSSION"] = 2] = "DISCUSSION"; ConversationType[ConversationType["GROUP"] = 3] = "GROUP"; ConversationType[ConversationType["CHATROOM"] = 4] = "CHATROOM"; ConversationType[ConversationType["CUSTOMER_SERVICE"] = 5] = "CUSTOMER_SERVICE"; ConversationType[ConversationType["SYSTEM"] = 6] = "SYSTEM"; //默认关注 MC ConversationType[ConversationType["APP_PUBLIC_SERVICE"] = 7] = "APP_PUBLIC_SERVICE"; //手工关注 MP ConversationType[ConversationType["PUBLIC_SERVICE"] = 8] = "PUBLIC_SERVICE"; })(RongIMLib.ConversationType || (RongIMLib.ConversationType = {})); var ConversationType = RongIMLib.ConversationType; (function (DiscussionInviteStatus) { /** * 开放邀请。 */ DiscussionInviteStatus[DiscussionInviteStatus["OPENED"] = 0] = "OPENED"; /** * 关闭邀请。 */ DiscussionInviteStatus[DiscussionInviteStatus["CLOSED"] = 1] = "CLOSED"; })(RongIMLib.DiscussionInviteStatus || (RongIMLib.DiscussionInviteStatus = {})); var DiscussionInviteStatus = RongIMLib.DiscussionInviteStatus; (function (ErrorCode) { /* 超时 */ ErrorCode[ErrorCode["TIMEOUT"] = -1] = "TIMEOUT"; /** * 未知原因失败。 */ ErrorCode[ErrorCode["UNKNOWN"] = -2] = "UNKNOWN"; /* 参数错误 */ ErrorCode[ErrorCode["PARAMETER_ERROR"] = -3] = "PARAMETER_ERROR"; ErrorCode[ErrorCode["RECALL_MESSAGE"] = 25101] = "RECALL_MESSAGE"; /** * 发送频率过快 */ ErrorCode[ErrorCode["SEND_FREQUENCY_TOO_FAST"] = 20604] = "SEND_FREQUENCY_TOO_FAST"; ErrorCode[ErrorCode["RC_MSG_UNAUTHORIZED"] = 20406] = "RC_MSG_UNAUTHORIZED"; /** * 群组 Id 无效 */ ErrorCode[ErrorCode["RC_DISCUSSION_GROUP_ID_INVALID"] = 20407] = "RC_DISCUSSION_GROUP_ID_INVALID"; /** * 群组被禁言 */ ErrorCode[ErrorCode["FORBIDDEN_IN_GROUP"] = 22408] = "FORBIDDEN_IN_GROUP"; /** * 不在讨论组。 */ ErrorCode[ErrorCode["NOT_IN_DISCUSSION"] = 21406] = "NOT_IN_DISCUSSION"; /** * 不在群组。 */ ErrorCode[ErrorCode["NOT_IN_GROUP"] = 22406] = "NOT_IN_GROUP"; /** * 不在聊天室。 */ ErrorCode[ErrorCode["NOT_IN_CHATROOM"] = 23406] = "NOT_IN_CHATROOM"; /** *聊天室被禁言 */ ErrorCode[ErrorCode["FORBIDDEN_IN_CHATROOM"] = 23408] = "FORBIDDEN_IN_CHATROOM"; /** * 聊天室中成员被踢出 */ ErrorCode[ErrorCode["RC_CHATROOM_USER_KICKED"] = 23409] = "RC_CHATROOM_USER_KICKED"; /** * 聊天室不存在 */ ErrorCode[ErrorCode["RC_CHATROOM_NOT_EXIST"] = 23410] = "RC_CHATROOM_NOT_EXIST"; /** * 聊天室成员已满 */ ErrorCode[ErrorCode["RC_CHATROOM_IS_FULL"] = 23411] = "RC_CHATROOM_IS_FULL"; /** * 获取聊天室信息参数无效 */ ErrorCode[ErrorCode["RC_CHATROOM_PATAMETER_INVALID"] = 23412] = "RC_CHATROOM_PATAMETER_INVALID"; /** * 聊天室异常 */ ErrorCode[ErrorCode["CHATROOM_GET_HISTORYMSG_ERROR"] = 23413] = "CHATROOM_GET_HISTORYMSG_ERROR"; /** * 没有打开聊天室消息存储 */ ErrorCode[ErrorCode["CHATROOM_NOT_OPEN_HISTORYMSG_STORE"] = 23414] = "CHATROOM_NOT_OPEN_HISTORYMSG_STORE"; /** * 聊天室 KV 设置超出最大值(已满, 默认最多设置 100 个) */ ErrorCode[ErrorCode["CHATROOM_KV_EXCEED"] = 23423] = "CHATROOM_KV_EXCEED"; /** * 聊天室 KV 设置失败(kv 已存在, 需覆盖设置) */ ErrorCode[ErrorCode["CHATROOM_KV_OVERWRITE_INVALID"] = 23424] = "CHATROOM_KV_OVERWRITE_INVALID"; /** * 聊天室 KV 存储功能没有开通 */ ErrorCode[ErrorCode["CHATROOM_KV_STORE_NOT_OPEN"] = 23426] = "CHATROOM_KV_STORE_NOT_OPEN"; /** * 聊天室Key不存在 */ ErrorCode[ErrorCode["CHATROOM_KEY_NOT_EXIST"] = 23427] = "CHATROOM_KEY_NOT_EXIST"; /** * 敏感词屏蔽 */ ErrorCode[ErrorCode["SENSITIVE_SHIELD"] = 21501] = "SENSITIVE_SHIELD"; ErrorCode[ErrorCode["SENSITIVE_REPLACE"] = 21502] = "SENSITIVE_REPLACE"; /** * 加入讨论失败 */ ErrorCode[ErrorCode["JOIN_IN_DISCUSSION"] = 21407] = "JOIN_IN_DISCUSSION"; /** * 创建讨论组失败 */ ErrorCode[ErrorCode["CREATE_DISCUSSION"] = 21408] = "CREATE_DISCUSSION"; /** * 设置讨论组邀请状态失败 */ ErrorCode[ErrorCode["INVITE_DICUSSION"] = 21409] = "INVITE_DICUSSION"; /** *获取用户失败 */ ErrorCode[ErrorCode["GET_USERINFO_ERROR"] = 23407] = "GET_USERINFO_ERROR"; /** * 在黑名单中。 */ ErrorCode[ErrorCode["REJECTED_BY_BLACKLIST"] = 405] = "REJECTED_BY_BLACKLIST"; /** * 通信过程中,当前 Socket 不存在。 */ ErrorCode[ErrorCode["RC_NET_CHANNEL_INVALID"] = 30001] = "RC_NET_CHANNEL_INVALID"; /** * Socket 连接不可用。 */ ErrorCode[ErrorCode["RC_NET_UNAVAILABLE"] = 30002] = "RC_NET_UNAVAILABLE"; /** * 通信超时。 */ ErrorCode[ErrorCode["RC_MSG_RESP_TIMEOUT"] = 30003] = "RC_MSG_RESP_TIMEOUT"; /** * 导航操作时,Http 请求失败。 */ ErrorCode[ErrorCode["RC_HTTP_SEND_FAIL"] = 30004] = "RC_HTTP_SEND_FAIL"; /** * HTTP 请求失败。 */ ErrorCode[ErrorCode["RC_HTTP_REQ_TIMEOUT"] = 30005] = "RC_HTTP_REQ_TIMEOUT"; /** * HTTP 接收失败。 */ ErrorCode[ErrorCode["RC_HTTP_RECV_FAIL"] = 30006] = "RC_HTTP_RECV_FAIL"; /** * 导航操作的 HTTP 请求,返回不是200。 */ ErrorCode[ErrorCode["RC_NAVI_RESOURCE_ERROR"] = 30007] = "RC_NAVI_RESOURCE_ERROR"; /** * 导航数据解析后,其中不存在有效数据。 */ ErrorCode[ErrorCode["RC_NODE_NOT_FOUND"] = 30008] = "RC_NODE_NOT_FOUND"; /** * 导航数据解析后,其中不存在有效 IP 地址。 */ ErrorCode[ErrorCode["RC_DOMAIN_NOT_RESOLVE"] = 30009] = "RC_DOMAIN_NOT_RESOLVE"; /** * 创建 Socket 失败。 */ ErrorCode[ErrorCode["RC_SOCKET_NOT_CREATED"] = 30010] = "RC_SOCKET_NOT_CREATED"; /** * Socket 被断开。 */ ErrorCode[ErrorCode["RC_SOCKET_DISCONNECTED"] = 30011] = "RC_SOCKET_DISCONNECTED"; /** * PING 操作失败。 */ ErrorCode[ErrorCode["RC_PING_SEND_FAIL"] = 30012] = "RC_PING_SEND_FAIL"; /** * PING 超时。 */ ErrorCode[ErrorCode["RC_PONG_RECV_FAIL"] = 30013] = "RC_PONG_RECV_FAIL"; /** * 消息发送失败。 */ ErrorCode[ErrorCode["RC_MSG_SEND_FAIL"] = 30014] = "RC_MSG_SEND_FAIL"; /** * JSON 后的消息体超限, 目前最大 128kb * */ ErrorCode[ErrorCode["RC_MSG_CONTENT_EXCEED_LIMIT"] = 30016] = "RC_MSG_CONTENT_EXCEED_LIMIT"; /** * 做 connect 连接时,收到的 ACK 超时。 */ ErrorCode[ErrorCode["RC_CONN_ACK_TIMEOUT"] = 31000] = "RC_CONN_ACK_TIMEOUT"; /** * 参数错误。 */ ErrorCode[ErrorCode["RC_CONN_PROTO_VERSION_ERROR"] = 31001] = "RC_CONN_PROTO_VERSION_ERROR"; /** * 参数错误,App Id 错误。 */ ErrorCode[ErrorCode["RC_CONN_ID_REJECT"] = 31002] = "RC_CONN_ID_REJECT"; /** * 服务器不可用。 */ ErrorCode[ErrorCode["RC_CONN_SERVER_UNAVAILABLE"] = 31003] = "RC_CONN_SERVER_UNAVAILABLE"; /** * Token 错误。 */ ErrorCode[ErrorCode["RC_CONN_USER_OR_PASSWD_ERROR"] = 31004] = "RC_CONN_USER_OR_PASSWD_ERROR"; /** * App Id 与 Token 不匹配。 */ ErrorCode[ErrorCode["RC_CONN_NOT_AUTHRORIZED"] = 31005] = "RC_CONN_NOT_AUTHRORIZED"; /** * 重定向,地址错误。 */ ErrorCode[ErrorCode["RC_CONN_REDIRECTED"] = 31006] = "RC_CONN_REDIRECTED"; /** * NAME 与后台注册信息不一致。 */ ErrorCode[ErrorCode["RC_CONN_PACKAGE_NAME_INVALID"] = 31007] = "RC_CONN_PACKAGE_NAME_INVALID"; /** * APP 被屏蔽、删除或不存在。 */ ErrorCode[ErrorCode["RC_CONN_APP_BLOCKED_OR_DELETED"] = 31008] = "RC_CONN_APP_BLOCKED_OR_DELETED"; /** * 用户被屏蔽。 */ ErrorCode[ErrorCode["RC_CONN_USER_BLOCKED"] = 31009] = "RC_CONN_USER_BLOCKED"; /** * Disconnect,由服务器返回,比如用户互踢。 */ ErrorCode[ErrorCode["RC_DISCONN_KICK"] = 31010] = "RC_DISCONN_KICK"; /** * Disconnect,由服务器返回,比如用户互踢。 */ ErrorCode[ErrorCode["RC_DISCONN_EXCEPTION"] = 31011] = "RC_DISCONN_EXCEPTION"; /** * 协议层内部错误。query,上传下载过程中数据错误。 */ ErrorCode[ErrorCode["RC_QUERY_ACK_NO_DATA"] = 32001] = "RC_QUERY_ACK_NO_DATA"; /** * 协议层内部错误。 */ ErrorCode[ErrorCode["RC_MSG_DATA_INCOMPLETE"] = 32002] = "RC_MSG_DATA_INCOMPLETE"; /** * 未调用 init 初始化函数。 */ ErrorCode[ErrorCode["BIZ_ERROR_CLIENT_NOT_INIT"] = 33001] = "BIZ_ERROR_CLIENT_NOT_INIT"; /** * 数据库初始化失败。 */ ErrorCode[ErrorCode["BIZ_ERROR_DATABASE_ERROR"] = 33002] = "BIZ_ERROR_DATABASE_ERROR"; /** * 传入参数无效。 */ ErrorCode[ErrorCode["BIZ_ERROR_INVALID_PARAMETER"] = 33003] = "BIZ_ERROR_INVALID_PARAMETER"; /** * 通道无效。 */ ErrorCode[ErrorCode["BIZ_ERROR_NO_CHANNEL"] = 33004] = "BIZ_ERROR_NO_CHANNEL"; /** * 重新连接成功。 */ ErrorCode[ErrorCode["BIZ_ERROR_RECONNECT_SUCCESS"] = 33005] = "BIZ_ERROR_RECONNECT_SUCCESS"; /** * 连接中,再调用 connect 被拒绝。 */ ErrorCode[ErrorCode["BIZ_ERROR_CONNECTING"] = 33006] = "BIZ_ERROR_CONNECTING"; /** * 消息漫游服务未开通 */ ErrorCode[ErrorCode["MSG_ROAMING_SERVICE_UNAVAILABLE"] = 33007] = "MSG_ROAMING_SERVICE_UNAVAILABLE"; ErrorCode[ErrorCode["MSG_INSERT_ERROR"] = 33008] = "MSG_INSERT_ERROR"; ErrorCode[ErrorCode["MSG_DEL_ERROR"] = 33009] = "MSG_DEL_ERROR"; /** * 删除会话失败 */ ErrorCode[ErrorCode["CONVER_REMOVE_ERROR"] = 34001] = "CONVER_REMOVE_ERROR"; /** *拉取历史消息 */ ErrorCode[ErrorCode["CONVER_GETLIST_ERROR"] = 34002] = "CONVER_GETLIST_ERROR"; /** * 会话指定异常 */ ErrorCode[ErrorCode["CONVER_SETOP_ERROR"] = 34003] = "CONVER_SETOP_ERROR"; /** * 获取会话未读消息总数失败 */ ErrorCode[ErrorCode["CONVER_TOTAL_UNREAD_ERROR"] = 34004] = "CONVER_TOTAL_UNREAD_ERROR"; /** * 获取指定会话类型未读消息数异常 */ ErrorCode[ErrorCode["CONVER_TYPE_UNREAD_ERROR"] = 34005] = "CONVER_TYPE_UNREAD_ERROR"; /** * 获取指定用户ID&会话类型未读消息数异常 */ ErrorCode[ErrorCode["CONVER_ID_TYPE_UNREAD_ERROR"] = 34006] = "CONVER_ID_TYPE_UNREAD_ERROR"; ErrorCode[ErrorCode["CONVER_CLEAR_ERROR"] = 34007] = "CONVER_CLEAR_ERROR"; ErrorCode[ErrorCode["CLEAR_HIS_ERROR"] = 34010] = "CLEAR_HIS_ERROR"; ErrorCode[ErrorCode["CLEAR_HIS_TYPE_ERROR"] = 34008] = "CLEAR_HIS_TYPE_ERROR"; ErrorCode[ErrorCode["CLEAR_HIS_TIME_ERROR"] = 34011] = "CLEAR_HIS_TIME_ERROR"; /* */ ErrorCode[ErrorCode["CONVER_GET_ERROR"] = 34009] = "CONVER_GET_ERROR"; //群组异常信息 /** * */ ErrorCode[ErrorCode["GROUP_SYNC_ERROR"] = 35001] = "GROUP_SYNC_ERROR"; /** * 匹配群信息异常 */ ErrorCode[ErrorCode["GROUP_MATCH_ERROR"] = 35002] = "GROUP_MATCH_ERROR"; //聊天室异常 /** * 加入聊天室Id为空 */ ErrorCode[ErrorCode["CHATROOM_ID_ISNULL"] = 36001] = "CHATROOM_ID_ISNULL"; /** * 加入聊天室失败 */ ErrorCode[ErrorCode["CHARTOOM_JOIN_ERROR"] = 36002] = "CHARTOOM_JOIN_ERROR"; /** * 拉取聊天室历史消息失败 */ ErrorCode[ErrorCode["CHATROOM_HISMESSAGE_ERROR"] = 36003] = "CHATROOM_HISMESSAGE_ERROR"; /** * 聊天室 kv 未找到 * */ ErrorCode[ErrorCode["CHATROOM_KV_NOT_FOUND"] = 36004] = "CHATROOM_KV_NOT_FOUND"; //黑名单异常 /** * 加入黑名单异常 */ ErrorCode[ErrorCode["BLACK_ADD_ERROR"] = 37001] = "BLACK_ADD_ERROR"; /** * 获得指定人员再黑名单中的状态异常 */ ErrorCode[ErrorCode["BLACK_GETSTATUS_ERROR"] = 37002] = "BLACK_GETSTATUS_ERROR"; /** * 移除黑名单异常 */ ErrorCode[ErrorCode["BLACK_REMOVE_ERROR"] = 37003] = "BLACK_REMOVE_ERROR"; /** * 获取草稿失败 */ ErrorCode[ErrorCode["DRAF_GET_ERROR"] = 38001] = "DRAF_GET_ERROR"; /** * 保存草稿失败 */ ErrorCode[ErrorCode["DRAF_SAVE_ERROR"] = 38002] = "DRAF_SAVE_ERROR"; /** * 删除草稿失败 */ ErrorCode[ErrorCode["DRAF_REMOVE_ERROR"] = 38003] = "DRAF_REMOVE_ERROR"; /** * 关注公众号失败 */ ErrorCode[ErrorCode["SUBSCRIBE_ERROR"] = 39001] = "SUBSCRIBE_ERROR"; /** * 关注公众号失败 */ ErrorCode[ErrorCode["QNTKN_FILETYPE_ERROR"] = 41001] = "QNTKN_FILETYPE_ERROR"; /** * 获取七牛token失败 */ ErrorCode[ErrorCode["QNTKN_GET_ERROR"] = 41002] = "QNTKN_GET_ERROR"; /** * cookie被禁用 */ ErrorCode[ErrorCode["COOKIE_ENABLE"] = 51001] = "COOKIE_ENABLE"; ErrorCode[ErrorCode["GET_MESSAGE_BY_ID_ERROR"] = 61001] = "GET_MESSAGE_BY_ID_ERROR"; // 没有注册DeviveId 也就是用户没有登陆 ErrorCode[ErrorCode["HAVNODEVICEID"] = 24001] = "HAVNODEVICEID"; // 已经存在 ErrorCode[ErrorCode["DEVICEIDISHAVE"] = 24002] = "DEVICEIDISHAVE"; // 成功 ErrorCode[ErrorCode["SUCCESS"] = 0] = "SUCCESS"; // 没有对应的用户或token ErrorCode[ErrorCode["FEILD"] = 24009] = "FEILD"; // voip为空 ErrorCode[ErrorCode["VOIPISNULL"] = 24013] = "VOIPISNULL"; // 不支持的Voip引擎 ErrorCode[ErrorCode["NOENGINETYPE"] = 24010] = "NOENGINETYPE"; // channleName 是空 ErrorCode[ErrorCode["NULLCHANNELNAME"] = 24011] = "NULLCHANNELNAME"; // 生成Voipkey失败 ErrorCode[ErrorCode["VOIPDYANMICERROR"] = 24012] = "VOIPDYANMICERROR"; // 没有配置voip ErrorCode[ErrorCode["NOVOIP"] = 24014] = "NOVOIP"; // 服务器内部错误 ErrorCode[ErrorCode["INTERNALERRROR"] = 24015] = "INTERNALERRROR"; //VOIP close ErrorCode[ErrorCode["VOIPCLOSE"] = 24016] = "VOIPCLOSE"; ErrorCode[ErrorCode["CLOSE_BEFORE_OPEN"] = 51001] = "CLOSE_BEFORE_OPEN"; ErrorCode[ErrorCode["ALREADY_IN_USE"] = 51002] = "ALREADY_IN_USE"; ErrorCode[ErrorCode["INVALID_CHANNEL_NAME"] = 51003] = "INVALID_CHANNEL_NAME"; ErrorCode[ErrorCode["VIDEO_CONTAINER_IS_NULL"] = 51004] = "VIDEO_CONTAINER_IS_NULL"; /** * 删除消息数组长度为 0 . */ ErrorCode[ErrorCode["DELETE_MESSAGE_ID_IS_NULL"] = 61001] = "DELETE_MESSAGE_ID_IS_NULL"; /*! 己方取消已发出的通话请求 */ ErrorCode[ErrorCode["CANCEL"] = 1] = "CANCEL"; /*! 己方拒绝收到的通话请求 */ ErrorCode[ErrorCode["REJECT"] = 2] = "REJECT"; /*! 己方挂断 */ ErrorCode[ErrorCode["HANGUP"] = 3] = "HANGUP"; /*! 己方忙碌 */ ErrorCode[ErrorCode["BUSYLINE"] = 4] = "BUSYLINE"; /*! 己方未接听 */ ErrorCode[ErrorCode["NO_RESPONSE"] = 5] = "NO_RESPONSE"; /*! 己方不支持当前引擎 */ ErrorCode[ErrorCode["ENGINE_UN_SUPPORTED"] = 6] = "ENGINE_UN_SUPPORTED"; /*! 己方网络出错 */ ErrorCode[ErrorCode["NETWORK_ERROR"] = 7] = "NETWORK_ERROR"; /*! 对方取消已发出的通话请求 */ ErrorCode[ErrorCode["REMOTE_CANCEL"] = 11] = "REMOTE_CANCEL"; /*! 对方拒绝收到的通话请求 */ ErrorCode[ErrorCode["REMOTE_REJECT"] = 12] = "REMOTE_REJECT"; /*! 通话过程对方挂断 */ ErrorCode[ErrorCode["REMOTE_HANGUP"] = 13] = "REMOTE_HANGUP"; /*! 对方忙碌 */ ErrorCode[ErrorCode["REMOTE_BUSYLINE"] = 14] = "REMOTE_BUSYLINE"; /*! 对方未接听 */ ErrorCode[ErrorCode["REMOTE_NO_RESPONSE"] = 15] = "REMOTE_NO_RESPONSE"; /*! 对方网络错误 */ ErrorCode[ErrorCode["REMOTE_ENGINE_UN_SUPPORTED"] = 16] = "REMOTE_ENGINE_UN_SUPPORTED"; /*! 对方网络错误 */ ErrorCode[ErrorCode["REMOTE_NETWORK_ERROR"] = 17] = "REMOTE_NETWORK_ERROR"; /*! VoIP 不可用 */ ErrorCode[ErrorCode["VOIP_NOT_AVALIABLE"] = 18] = "VOIP_NOT_AVALIABLE"; })(RongIMLib.ErrorCode || (RongIMLib.ErrorCode = {})); var ErrorCode = RongIMLib.ErrorCode; (function (VoIPMediaType) { VoIPMediaType[VoIPMediaType["MEDIA_AUDIO"] = 1] = "MEDIA_AUDIO"; VoIPMediaType[VoIPMediaType["MEDIA_VEDIO"] = 2] = "MEDIA_VEDIO"; VoIPMediaType[VoIPMediaType["MEDIA_VIDEO"] = 2] = "MEDIA_VIDEO"; })(RongIMLib.VoIPMediaType || (RongIMLib.VoIPMediaType = {})); var VoIPMediaType = RongIMLib.VoIPMediaType; (function (MediaType) { /** * 图片。 */ MediaType[MediaType["IMAGE"] = 1] = "IMAGE"; /** * 声音。 */ MediaType[MediaType["AUDIO"] = 2] = "AUDIO"; /** * 视频。 */ MediaType[MediaType["VIDEO"] = 3] = "VIDEO"; /** * 通用文件。 */ MediaType[MediaType["FILE"] = 100] = "FILE"; })(RongIMLib.MediaType || (RongIMLib.MediaType = {})); var MediaType = RongIMLib.MediaType; (function (MessageDirection) { /** * 发送消息。 */ MessageDirection[MessageDirection["SEND"] = 1] = "SEND"; /** * 接收消息。 */ MessageDirection[MessageDirection["RECEIVE"] = 2] = "RECEIVE"; })(RongIMLib.MessageDirection || (RongIMLib.MessageDirection = {})); var MessageDirection = RongIMLib.MessageDirection; (function (FileType) { FileType[FileType["IMAGE"] = 1] = "IMAGE"; FileType[FileType["AUDIO"] = 2] = "AUDIO"; FileType[FileType["VIDEO"] = 3] = "VIDEO"; FileType[FileType["FILE"] = 4] = "FILE"; })(RongIMLib.FileType || (RongIMLib.FileType = {})); var FileType = RongIMLib.FileType; (function (RealTimeLocationErrorCode) { /** * 未初始化 RealTimeLocation 实例 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_NOT_INIT"] = -1] = "RC_REAL_TIME_LOCATION_NOT_INIT"; /** * 执行成功。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_SUCCESS"] = 0] = "RC_REAL_TIME_LOCATION_SUCCESS"; /** * 获取 RealTimeLocation 实例时返回 * GPS 未打开。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_GPS_DISABLED"] = 1] = "RC_REAL_TIME_LOCATION_GPS_DISABLED"; /** * 获取 RealTimeLocation 实例时返回 * 当前会话不支持位置共享。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_CONVERSATION_NOT_SUPPORT"] = 2] = "RC_REAL_TIME_LOCATION_CONVERSATION_NOT_SUPPORT"; /** * 获取 RealTimeLocation 实例时返回 * 对方已发起位置共享。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_IS_ON_GOING"] = 3] = "RC_REAL_TIME_LOCATION_IS_ON_GOING"; /** * Join 时返回 * 当前位置共享已超过最大支持人数。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_EXCEED_MAX_PARTICIPANT"] = 4] = "RC_REAL_TIME_LOCATION_EXCEED_MAX_PARTICIPANT"; /** * Join 时返回 * 加入位置共享失败。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_JOIN_FAILURE"] = 5] = "RC_REAL_TIME_LOCATION_JOIN_FAILURE"; /** * Start 时返回 * 发起位置共享失败。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_START_FAILURE"] = 6] = "RC_REAL_TIME_LOCATION_START_FAILURE"; /** * 网络不可用。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_NETWORK_UNAVAILABLE"] = 7] = "RC_REAL_TIME_LOCATION_NETWORK_UNAVAILABLE"; })(RongIMLib.RealTimeLocationErrorCode || (RongIMLib.RealTimeLocationErrorCode = {})); var RealTimeLocationErrorCode = RongIMLib.RealTimeLocationErrorCode; (function (RealTimeLocationStatus) { /** * 空闲状态 (默认状态) * 对方或者自己都未发起位置共享业务,或者位置共享业务已结束。 */ RealTimeLocationStatus[RealTimeLocationStatus["RC_REAL_TIME_LOCATION_STATUS_IDLE"] = 0] = "RC_REAL_TIME_LOCATION_STATUS_IDLE"; /** * 呼入状态 (待加入) * 1. 对方发起了位置共享业务,此状态下,自己只能选择加入。 * 2. 自己从已连接的位置共享中退出。 */ RealTimeLocationStatus[RealTimeLocationStatus["RC_REAL_TIME_LOCATION_STATUS_INCOMING"] = 1] = "RC_REAL_TIME_LOCATION_STATUS_INCOMING"; /** * 呼出状态 =(自己创建) * 1. 自己发起位置共享业务,对方只能选择加入。 * 2. 对方从已连接的位置共享业务中退出。 */ RealTimeLocationStatus[RealTimeLocationStatus["RC_REAL_TIME_LOCATION_STATUS_OUTGOING"] = 2] = "RC_REAL_TIME_LOCATION_STATUS_OUTGOING"; /** * 连接状态 (自己加入) * 对方加入了自己发起的位置共享,或者自己加入了对方发起的位置共享。 */ RealTimeLocationStatus[RealTimeLocationStatus["RC_REAL_TIME_LOCATION_STATUS_CONNECTED"] = 3] = "RC_REAL_TIME_LOCATION_STATUS_CONNECTED"; })(RongIMLib.RealTimeLocationStatus || (RongIMLib.RealTimeLocationStatus = {})); var RealTimeLocationStatus = RongIMLib.RealTimeLocationStatus; (function (ReceivedStatus) { ReceivedStatus[ReceivedStatus["READ"] = 1] = "READ"; ReceivedStatus[ReceivedStatus["LISTENED"] = 2] = "LISTENED"; ReceivedStatus[ReceivedStatus["DOWNLOADED"] = 4] = "DOWNLOADED"; ReceivedStatus[ReceivedStatus["RETRIEVED"] = 8] = "RETRIEVED"; ReceivedStatus[ReceivedStatus["UNREAD"] = 0] = "UNREAD"; })(RongIMLib.ReceivedStatus || (RongIMLib.ReceivedStatus = {})); var ReceivedStatus = RongIMLib.ReceivedStatus; (function (ReadStatus) { ReadStatus[ReadStatus["READ"] = 1] = "READ"; ReadStatus[ReadStatus["LISTENED"] = 2] = "LISTENED"; ReadStatus[ReadStatus["DOWNLOADED"] = 4] = "DOWNLOADED"; ReadStatus[ReadStatus["RETRIEVED"] = 8] = "RETRIEVED"; ReadStatus[ReadStatus["UNREAD"] = 0] = "UNREAD"; })(RongIMLib.ReadStatus || (RongIMLib.ReadStatus = {})); var ReadStatus = RongIMLib.ReadStatus; (function (SearchType) { /** * 精确。 */ SearchType[SearchType["EXACT"] = 0] = "EXACT"; /** * 模糊。 */ SearchType[SearchType["FUZZY"] = 1] = "FUZZY"; })(RongIMLib.SearchType || (RongIMLib.SearchType = {})); var SearchType = RongIMLib.SearchType; (function (SentStatus) { /** * 发送中。 */ SentStatus[SentStatus["SENDING"] = 10] = "SENDING"; /** * 发送失败。 */ SentStatus[SentStatus["FAILED"] = 20] = "FAILED"; /** * 已发送。 */ SentStatus[SentStatus["SENT"] = 30] = "SENT"; /** * 对方已接收。 */ SentStatus[SentStatus["RECEIVED"] = 40] = "RECEIVED"; /** * 对方已读。 */ SentStatus[SentStatus["READ"] = 50] = "READ"; /** * 对方已销毁。 */ SentStatus[SentStatus["DESTROYED"] = 60] = "DESTROYED"; })(RongIMLib.SentStatus || (RongIMLib.SentStatus = {})); var SentStatus = RongIMLib.SentStatus; (function (ConnectionState) { ConnectionState[ConnectionState["ACCEPTED"] = 0] = "ACCEPTED"; ConnectionState[ConnectionState["UNACCEPTABLE_PROTOCOL_VERSION"] = 1] = "UNACCEPTABLE_PROTOCOL_VERSION"; ConnectionState[ConnectionState["IDENTIFIER_REJECTED"] = 2] = "IDENTIFIER_REJECTED"; ConnectionState[ConnectionState["SERVER_UNAVAILABLE"] = 3] = "SERVER_UNAVAILABLE"; /** * token无效 */ ConnectionState[ConnectionState["TOKEN_INCORRECT"] = 4] = "TOKEN_INCORRECT"; ConnectionState[ConnectionState["NOT_AUTHORIZED"] = 5] = "NOT_AUTHORIZED"; ConnectionState[ConnectionState["REDIRECT"] = 6] = "REDIRECT"; ConnectionState[ConnectionState["PACKAGE_ERROR"] = 7] = "PACKAGE_ERROR"; ConnectionState[ConnectionState["APP_BLOCK_OR_DELETE"] = 8] = "APP_BLOCK_OR_DELETE"; ConnectionState[ConnectionState["BLOCK"] = 9] = "BLOCK"; ConnectionState[ConnectionState["TOKEN_EXPIRE"] = 10] = "TOKEN_EXPIRE"; ConnectionState[ConnectionState["DEVICE_ERROR"] = 11] = "DEVICE_ERROR"; })(RongIMLib.ConnectionState || (RongIMLib.ConnectionState = {})); var ConnectionState = RongIMLib.ConnectionState; (function (RTCAPIType) { RTCAPIType[RTCAPIType["ROOM"] = 1] = "ROOM"; RTCAPIType[RTCAPIType["PERSON"] = 2] = "PERSON"; })(RongIMLib.RTCAPIType || (RongIMLib.RTCAPIType = {})); var RTCAPIType = RongIMLib.RTCAPIType; (function (ChatroomEntityOpt) { ChatroomEntityOpt[ChatroomEntityOpt["UPDATE"] = 1] = "UPDATE"; ChatroomEntityOpt[ChatroomEntityOpt["DELETE"] = 2] = "DELETE"; })(RongIMLib.ChatroomEntityOpt || (RongIMLib.ChatroomEntityOpt = {})); var ChatroomEntityOpt = RongIMLib.ChatroomEntityOpt; (function (ChatroomEntityLimit) { ChatroomEntityLimit[ChatroomEntityLimit["KEY"] = 128] = "KEY"; ChatroomEntityLimit[ChatroomEntityLimit["VALUE"] = 4096] = "VALUE"; })(RongIMLib.ChatroomEntityLimit || (RongIMLib.ChatroomEntityLimit = {})); var ChatroomEntityLimit = RongIMLib.ChatroomEntityLimit; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var RongIMClient = (function () { function RongIMClient() { } RongIMClient.getInstance = function () { if (!RongIMClient._instance) { throw new Error("RongIMClient is not initialized. Call .init() method first."); } return RongIMClient._instance; }; RongIMClient.showError = function (errorInfo) { var hasConsole = (console && console.error); if (hasConsole) { console.error(JSON.stringify(errorInfo)); } }; RongIMClient.logger = function (params) { var code = params.code; var errorInfo = RongIMClient.LogFactory[code] || params; errorInfo.funcName = params.funcName; errorInfo.msg = params.msg || errorInfo.msg; if (RongIMClient._memoryStore.depend.showError) { RongIMClient.showError(errorInfo); } }; RongIMClient.logCallback = function (callback, funcName) { return { onSuccess: callback.onSuccess, onError: function (errorCode) { RongIMClient.logger({ code: errorCode, funcName: funcName }); callback.onError(errorCode); } }; }; ; RongIMClient.logSendCallback = function (callback, funcName) { return { onSuccess: callback.onSuccess, onError: function (errorCode, result) { RongIMClient.logger({ code: errorCode, funcName: funcName }); callback.onError(errorCode, result); }, onBefore: callback.onBefore }; }; ; /** * 初始化 SDK,在整个应用全局只需要调用一次。 * @param appKey 开发者后台申请的 AppKey,用来标识应用。 * @param dataAccessProvider 必须是DataAccessProvider的实例 */ RongIMClient.init = function (appKey, dataAccessProvider, options, callback) { RongIMClient.statusListeners = []; RongIMClient.messageListeners = []; if (RongIMClient._instance) { return RongIMClient._memoryStore.sdkInfo; } RongIMClient._instance = new RongIMClient(); options = options || {}; var protocol = "http://", wsScheme = 'ws://'; var isLocationInvalid = typeof location !== 'object'; // 未找到全局 location 变量, 则协议为 https. 比如小程序 if (isLocationInvalid || location.protocol == 'https:') { wsScheme = 'wss://'; protocol = 'https://'; } var isPolling = false; if (typeof WebSocket != 'function') { isPolling = true; } var isIntegrity = function () { //iOS 9 var hasWS = (typeof WebSocket); var integrity = (typeof WebSocket.OPEN == 'number'); return (hasWS && integrity); }; if (typeof WebSocket == 'object' && isIntegrity()) { isPolling = false; } var supportUserData = function () { var element = document.documentElement; return element.addBehavior; }; if (RongIMLib.RongUtil.supportLocalStorage()) { RongIMClient._storageProvider = new RongIMLib.LocalStorageProvider(); } else if (supportUserData()) { RongIMClient._storageProvider = new RongIMLib.UserDataProvider(); } else { RongIMClient._storageProvider = new RongIMLib.MemeoryProvider(); } var serverIndex = RongIMClient._storageProvider.getItem('serverIndex'); RongIMClient.serverStore.index = serverIndex || 0; var pathTmpl = '{0}{1}'; var _serverPath = { api: 'api.cn.ronghub.com' }; RongIMLib.RongUtil.forEach(_serverPath, function (path, key) { _serverPath[key] = RongIMLib.RongUtil.stringFormat(pathTmpl, [protocol, path]); }); RongIMLib.RongUtil.forEach(_serverPath, function (path, key) { var hasProto = (key in options); var config = { path: options[key], tmpl: pathTmpl, protocol: protocol, sub: true }; path = hasProto ? RongIMLib.RongUtil.formatProtoclPath(config) : path; options[key] = path; }); var navigaters = options.navigaters || []; if (options.navi) { navigaters = [options.navi]; } if (!options.navi && RongIMLib.RongUtil.isEqual(navigaters.length, 0)) { navigaters = ['nav.cn.ronghub.com', 'nav2-cn.ronghub.com']; } RongIMLib.RongUtil.forEach(navigaters, function (navi, index) { var config = { path: navi, tmpl: pathTmpl, protocol: protocol, sub: true }; navi = RongIMLib.RongUtil.formatProtoclPath(config); navigaters[index] = navi; }); var _sourcePath = { protobuf: 'cdn.ronghub.com/protobuf-2.3.7.min.js' }; RongIMLib.RongUtil.forEach(_sourcePath, function (path, key) { _sourcePath[key] = RongIMLib.RongUtil.stringFormat(pathTmpl, [protocol, path]); }); RongIMLib.RongUtil.extend(_sourcePath, options); var _defaultOpts = { isPolling: isPolling, wsScheme: wsScheme, protocol: protocol, showError: true, openMp: true, snifferTime: 2000, naviTimeout: 5000, navigaters: navigaters, maxNaviRetry: 10, isNaviJSONP: false, isWSPingJSONP: false, isNotifyConversationList: false, maxConversationCount: 300, cmpUrl: '' // 若传入 cmpUrl, 则优先链接此地址 }; delete options.navigaters; RongIMLib.RongUtil.extend(_defaultOpts, options); if (RongIMLib.RongUtil.isFunction(options.protobuf)) { RongIMClient.Protobuf = options.protobuf; } RongIMClient.userStatusObserver = new RongIMLib.RongObserver(); var pather = new RongIMLib.FeaturePatcher(); pather.patchAll(); var tempStore = { token: "", callback: null, lastReadTime: new RongIMLib.LimitableMap(), historyMessageLimit: new RongIMLib.MemoryCache(), conversationList: [], appKey: appKey, publicServiceMap: new RongIMLib.PublicServiceMap(), providerType: 1, deltaTime: 0, filterMessages: [], isSyncRemoteConverList: true, otherDevice: false, custStore: {}, converStore: { latestMessage: {} }, connectAckTime: 0, voipStategy: 0, isFirstPingMsg: true, depend: options, notification: {} }; RongIMClient._memoryStore = tempStore; var isCPlusSDK = dataAccessProvider && Object.prototype.toString.call(dataAccessProvider) == "[object Object]"; if (isCPlusSDK) { RongIMClient._dataAccessProvider = dataAccessProvider; } else { RongIMClient._dataAccessProvider = new RongIMLib.ServerDataProvider(); } options.appCallback = callback; var sdkInfo = RongIMClient._dataAccessProvider.init(appKey, options); RongIMClient._memoryStore.sdkInfo = sdkInfo; if (isCPlusSDK) { // 兼容 c++ 设置导航,Web 端不生效 RongIMClient._dataAccessProvider.setServerInfo({ navi: location.protocol + options.navi + '/navi.xml' }); } RongIMClient.MessageParams = { TextMessage: { objectName: "RC:TxtMsg", msgTag: new RongIMLib.MessageTag(true, true) }, ImageMessage: { objectName: "RC:ImgMsg", msgTag: new RongIMLib.MessageTag(true, true) }, DiscussionNotificationMessage: { objectName: "RC:DizNtf", msgTag: new RongIMLib.MessageTag(false, true) }, VoiceMessage: { objectName: "RC:VcMsg", msgTag: new RongIMLib.MessageTag(true, true) }, ReferenceMessage: { objectName: "RC:ReferenceMsg", msgTag: new RongIMLib.MessageTag(true, true) }, RichContentMessage: { objectName: "RC:ImgTextMsg", msgTag: new RongIMLib.MessageTag(true, true) }, FileMessage: { objectName: "RC:FileMsg", msgTag: new RongIMLib.MessageTag(true, true) }, HQVoiceMessage: { objectName: "RC:HQVCMsg", msgTag: new RongIMLib.MessageTag(true, true) }, HandshakeMessage: { objectName: "", msgTag: new RongIMLib.MessageTag(true, true) }, UnknownMessage: { objectName: "", msgTag: new RongIMLib.MessageTag(true, true) }, LocationMessage: { objectName: "RC:LBSMsg", msgTag: new RongIMLib.MessageTag(true, true) }, InformationNotificationMessage: { objectName: "RC:InfoNtf", msgTag: new RongIMLib.MessageTag(false, true) }, ContactNotificationMessage: { objectName: "RC:ContactNtf", msgTag: new RongIMLib.MessageTag(false, true) }, ProfileNotificationMessage: { objectName: "RC:ProfileNtf", msgTag: new RongIMLib.MessageTag(false, true) }, CommandNotificationMessage: { objectName: "RC:CmdNtf", msgTag: new RongIMLib.MessageTag(false, true) }, PublicServiceRichContentMessage: { objectName: "RC:PSImgTxtMsg", msgTag: new RongIMLib.MessageTag(true, true) }, PublicServiceMultiRichContentMessage: { objectName: "RC:PSMultiImgTxtMsg", msgTag: new RongIMLib.MessageTag(true, true) }, JrmfRedPacketMessage: { objectName: "RCJrmf:RpMsg", msgTag: new RongIMLib.MessageTag(true, true) }, JrmfRedPacketOpenedMessage: { objectName: "RCJrmf:RpOpendMsg", msgTag: new RongIMLib.MessageTag(true, true) }, GroupNotificationMessage: { objectName: "RC:GrpNtf", msgTag: new RongIMLib.MessageTag(false, true) }, CommandMessage: { objectName: "RC:CmdMsg", msgTag: new RongIMLib.MessageTag(false, false) }, TypingStatusMessage: { objectName: "RC:TypSts", msgTag: new RongIMLib.MessageTag(false, false) }, PublicServiceCommandMessage: { objectName: "RC:PSCmd", msgTag: new RongIMLib.MessageTag(false, false) }, RecallCommandMessage: { objectName: "RC:RcCmd", msgTag: new RongIMLib.MessageTag(false, true) }, SyncReadStatusMessage: { objectName: "RC:SRSMsg", msgTag: new RongIMLib.MessageTag(false, false) }, ReadReceiptRequestMessage: { objectName: "RC:RRReqMsg", msgTag: new RongIMLib.MessageTag(false, false) }, ReadReceiptResponseMessage: { objectName: "RC:RRRspMsg", msgTag: new RongIMLib.MessageTag(false, false) }, ChangeModeResponseMessage: { objectName: "RC:CsChaR", msgTag: new RongIMLib.MessageTag(false, false) }, ChangeModeMessage: { objectName: "RC:CSCha", msgTag: new RongIMLib.MessageTag(false, false) }, EvaluateMessage: { objectName: "RC:CsEva", msgTag: new RongIMLib.MessageTag(false, false) }, CustomerContact: { objectName: "RC:CsContact", msgTag: new RongIMLib.MessageTag(false, false) }, HandShakeMessage: { objectName: "RC:CsHs", msgTag: new RongIMLib.MessageTag(false, false) }, HandShakeResponseMessage: { objectName: "RC:CsHsR", msgTag: new RongIMLib.MessageTag(false, false) }, SuspendMessage: { objectName: "RC:CsSp", msgTag: new RongIMLib.MessageTag(false, false) }, TerminateMessage: { objectName: "RC:CsEnd", msgTag: new RongIMLib.MessageTag(false, false) }, CustomerStatusUpdateMessage: { objectName: "RC:CsUpdate", msgTag: new RongIMLib.MessageTag(false, false) }, ReadReceiptMessage: { objectName: "RC:ReadNtf", msgTag: new RongIMLib.MessageTag(false, false) }, RCCombineMessage: { objectName: "RC:CombineMsg", msgTag: new RongIMLib.MessageTag(true, true) }, ChrmKVNotificationMessage: { objectName: 'RC:chrmKVNotiMsg', msgTag: new RongIMLib.MessageTag(false, false) } }; RongIMClient.MessageParams["AcceptMessage"] = { objectName: "RC:VCAccept", msgTag: new RongIMLib.MessageTag(false, false) }; RongIMClient.MessageParams["RingingMessage"] = { objectName: "RC:VCRinging", msgTag: new RongIMLib.MessageTag(false, false) }; RongIMClient.MessageParams["SummaryMessage"] = { objectName: "RC:VCSummary", msgTag: new RongIMLib.MessageTag(false, false) }; RongIMClient.MessageParams["HungupMessage"] = { objectName: "RC:VCHangup", msgTag: new RongIMLib.MessageTag(false, false) }; RongIMClient.MessageParams["InviteMessage"] = { objectName: "RC:VCInvite", msgTag: new RongIMLib.MessageTag(false, false) }; RongIMClient.MessageParams["MediaModifyMessage"] = { objectName: "RC:VCModifyMedia", msgTag: new RongIMLib.MessageTag(false, false) }; RongIMClient.MessageParams["MemberModifyMessage"] = { objectName: "RC:VCModifyMem", msgTag: new RongIMLib.MessageTag(false, false) }; RongIMClient.MessageType = { TextMessage: "TextMessage", ImageMessage: "ImageMessage", ReferenceMessage: "ReferenceMessage", DiscussionNotificationMessage: "DiscussionNotificationMessage", VoiceMessage: "VoiceMessage", RichContentMessage: "RichContentMessage", HandshakeMessage: "HandshakeMessage", UnknownMessage: "UnknownMessage", LocationMessage: "LocationMessage", InformationNotificationMessage: "InformationNotificationMessage", ContactNotificationMessage: "ContactNotificationMessage", ProfileNotificationMessage: "ProfileNotificationMessage", CommandNotificationMessage: "CommandNotificationMessage", CommandMessage: "CommandMessage", TypingStatusMessage: "TypingStatusMessage", ChangeModeResponseMessage: "ChangeModeResponseMessage", ChangeModeMessage: "ChangeModeMessage", EvaluateMessage: "EvaluateMessage", HandShakeMessage: "HandShakeMessage", HandShakeResponseMessage: "HandShakeResponseMessage", SuspendMessage: "SuspendMessage", TerminateMessage: "TerminateMessage", CustomerContact: "CustomerContact", CustomerStatusUpdateMessage: "CustomerStatusUpdateMessage", SyncReadStatusMessage: "SyncReadStatusMessage", ReadReceiptRequestMessage: "ReadReceiptRequestMessage", ReadReceiptResponseMessage: "ReadReceiptResponseMessage", FileMessage: 'FileMessage', HQVoiceMessage: 'HQVoiceMessage', AcceptMessage: "AcceptMessage", RingingMessage: "RingingMessage", SummaryMessage: "SummaryMessage", HungupMessage: "HungupMessage", InviteMessage: "InviteMessage", MediaModifyMessage: "MediaModifyMessage", MemberModifyMessage: "MemberModifyMessage", JrmfRedPacketMessage: "JrmfRedPacketMessage", JrmfRedPacketOpenedMessage: "JrmfRedPacketOpenedMessage", GroupNotificationMessage: "GroupNotificationMessage", PublicServiceRichContentMessage: "PublicServiceRichContentMessage", PublicServiceMultiRichContentMessage: "PublicServiceMultiRichContentMessage", PublicServiceCommandMessage: "PublicServiceCommandMessage", RecallCommandMessage: "RecallCommandMessage", ReadReceiptMessage: "ReadReceiptMessage", RCCombineMessage: "RCCombineMessage", ChrmKVNotificationMessage: 'ChrmKVNotificationMessage' }; RongIMClient.LogFactory = { /** * 个人 */ "-1": { code: "-1", msg: "服务器超时" }, "-2": { code: "-2", msg: "未知原因失败" }, "-3": { code: "-3", msg: "参数错误" }, "-4": { code: "-4", msg: "参数不正确或尚未实例化" }, "25101": { code: "25101", msg: "撤回消息参数错误", desc: "请检查撤回消息参数 https://rongcloud.github.io/websdk-demo/api-test.html" }, "25102": { code: "25101", msg: "只能撤回自发发送的消息" }, "20604": { code: "20604", msg: "发送频率过快", desc: "https://developer.rongcloud.cn/ticket/info/9Q3L6vRKd1cLS7rycA==?type=1" }, "20406": { code: "20406", msg: "被禁言" }, "23407": { code: "23407", msg: "获取用户失败" }, /** * 群组 */ "20407": { code: "20407", msg: "群组Id无效" }, "22408": { code: "22408", msg: "群组被禁言" }, "22406": { code: "22406", msg: "不在群组" }, "35001": { code: "35001", msg: "群组同步异常" }, "35002": { code: "35002", msg: "匹配群信息异常" }, /** * 讨论组 */ "21406": { code: "21406", msg: "不在讨论组" }, "21407": { code: "21407", msg: "加入讨论失败" }, "21408": { code: "21408", msg: "创建讨论组失败" }, "21409": { code: "21409", msg: "设置讨论组邀请状态失败" }, /** * 聊天室 */ "23406": { code: "23406", msg: "不在聊天室" }, "23408": { code: "23408", msg: "聊天室被禁言" }, "23409": { code: "23409", msg: "聊天室中成员被踢出" }, "23410": { code: "23410", msg: "聊天室不存在" }, "23411": { code: "23411", msg: "聊天室成员已满" }, "23412": { code: "23412", msg: "获取聊天室信息参数无效" }, "23413": { code: "23413", msg: "聊天室异常" }, "23414": { code: "23414", msg: "没有打开聊天室消息存储" }, "36001": { code: "36001", msg: "加入聊天室Id为空" }, "36002": { code: "36002", msg: "加入聊天室失败" }, "36003": { code: "36003", msg: "拉取聊天室历史消息失败" }, /** * voip */ "24001": { code: "24001", msg: "没有注册DeviveId 也就是用户没有登陆" }, "24002": { code: "24002", msg: "用户已经存在" }, "0": { code: "0", msg: "成功" }, "24009": { code: "24009", msg: "没有对应的用户或token" }, "24013": { code: "24013", msg: "voip为空" }, "24010": { code: "24010", msg: "不支持的Voip引擎" }, "24011": { code: "24011", msg: "channelName 是空" }, "24012": { code: "24012", msg: "生成Voipkey失败" }, "24014": { code: "24014", msg: "没有配置voip" }, "24015": { code: "24015", msg: "服务器内部错误" }, "24016": { code: "24016", msg: "VOIP close" }, /** * 通讯、导航 */ "30001": { code: "30001", msg: "通信过程中,当前Socket不存在" }, "30002": { code: "30002", msg: "Socket连接不可用" }, "30003": { code: "30003", msg: "通信超时" }, "30004": { code: "30004", msg: "导航操作时,Http请求失败" }, "30005": { code: "30005", msg: "HTTP请求失败" }, "30006": { code: "30006", msg: "HTTP接收失败" }, "30007": { code: "30007", msg: "导航资源错误" }, "30008": { code: "30008", msg: "没有有效数据" }, "30009": { code: "30009", msg: "不存在有效 IP 地址" }, "30010": { code: "30010", msg: "创建 Socket 失败" }, "30011": { code: "30011", msg: " Socket 被断开" }, "30012": { code: "30012", msg: "PING 操作失败" }, "30013": { code: "30013", msg: "PING 超时" }, "30014": { code: "30014", msg: "消息发送失败" }, "30016": { code: "30016", msg: "消息大小超限,最大 128 KB" }, /** * 连接 */ "31000": { code: "31000", msg: "做 connect 连接时,收到的 ACK 超时" }, "31001": { code: "31001", msg: "参数错误" }, "31002": { code: "31002", msg: "参数错误,App Id 错误" }, "31003": { code: "31003", msg: "服务器不可用" }, "31004": { code: "31004", msg: "Token 错误" }, "31005": { code: "31005", msg: "App Id 与 Token 不匹配" }, "31006": { code: "31006", msg: "重定向,地址错误" }, "31007": { code: "31007", msg: "NAME 与后台注册信息不一致" }, "31008": { code: "31008", msg: "APP 被屏蔽、删除或不存在" }, "31009": { code: "31009", msg: "用户被屏蔽" }, "31010": { code: "31010", msg: "Disconnect,由服务器返回,比如用户互踢" }, "31011": { code: "31011", msg: "Disconnect,由服务器返回,比如用户互踢" }, /** * 协议 */ "32001": { code: "32001", msg: "协议层内部错误。query,上传下载过程中数据错误" }, "32002": { code: "32002", msg: "协议层内部错误" }, /** * BIZ */ "33001": { code: "33001", msg: "未调用 init 初始化函数" }, "33002": { code: "33002", msg: "数据库初始化失败" }, "33003": { code: "33003", msg: "传入参数无效" }, "33004": { code: "33004", msg: "通道无效" }, "33005": { code: "33005", msg: "重新连接成功" }, "33006": { code: "33006", msg: "连接中,再调用 connect 被拒绝" }, "33007": { code: "33007", msg: "消息漫游服务未开通" }, "33008": { code: "33008", msg: "消息添加失败" }, "33009": { code: "33009", msg: "消息删除失败" }, /** * 会话 */ "34001": { code: "34001", msg: "删除会话失败" }, "34002": { code: "34002", msg: "拉取历史消息失败" }, "34003": { code: "34003", msg: "会话指定异常" }, "34004": { code: "34004", msg: "获取会话未读消息总数失败" }, "34005": { code: "34005", msg: "获取指定会话类型未读消息数异常" }, "34006": { code: "34006", msg: "获取指定用户ID&会话类型未读消息数异常" }, "34007": { code: "34007", msg: "清除会话消息异常" }, "34008": { code: "34008", msg: "获取会话消息异常" }, "34009": { code: "34009", msg: "清除历史消息会话类型不正确" }, "34010": { code: "34010", msg: "清除历史消息失败,请检查传入参数" }, /** * 黑名单异常 */ "37001": { code: "37001", msg: "加入黑名单异常" }, "37002": { code: "37002", msg: "获得指定人员再黑名单中的状态异常" }, "37003": { code: "37003", msg: "移除黑名单异常" }, "405": { code: "405", msg: "在黑名单中" }, /** * 草稿 */ "38001": { code: "38001", msg: "获取草稿失败" }, "38002": { code: "38002", msg: "保存草稿失败" }, "38003": { code: "38003", msg: "删除草稿失败" }, /** * 公众号 */ "39001": { code: "39001", msg: "关注公众号失败" }, /** * 文件 */ "41001": { code: "41001", msg: "文件类型错误" }, "41002": { code: "41002", msg: "获取七牛token失败" }, /** * */ "51001": { code: "51001", msg: "未安装或未启动插件" }, "51002": { code: "51002", msg: "视频已经存在" }, "51003": { code: "51003", msg: "无效的channelName" }, "51004": { code: "51004", msg: "视频内容为空" }, /** * */ "61001": { code: "61001", msg: "删除消息数组长度为 0" } }; var handler = function (message, uris, callback) { var userId = message.senderUserId; var _uris = RongIMClient.roomInfo.users[userId].uris || '[]'; if (RongIMLib.RongUtil.isString(_uris)) { _uris = JSON.parse(_uris); } var tUris = JSON.parse(JSON.stringify(_uris)); RongIMLib.RongUtil.forEach(tUris, function (_uri, index) { RongIMLib.RongUtil.forEach(uris, function (uri) { if (uri.uri == _uri.uri) { callback(_uri, uri, _uris, index); } }); }); RongIMClient.roomInfo.users[userId].uris = JSON.stringify(_uris); }; var RTCMessage = { RTCPublishResourceMessage: function (message, uris) { var userId = message.senderUserId; var user = RongIMClient.roomInfo.users[userId]; if (!user) { user = {}; RongIMClient.roomInfo.users[userId] = {}; } var _uris = user.uris || '[]'; if (RongIMLib.RongUtil.isString(_uris)) { _uris = JSON.parse(_uris); } _uris = _uris.concat(uris); RongIMClient.roomInfo.users[userId].uris = JSON.stringify(_uris); }, RTCUnpublishResourceMessage: function (message, uris) { handler(message, uris, function (_uri, uri, _uris, index) { _uris.splice(index, 1); }); }, RTCModifyResourceMessage: function (message, uris) { handler(message, uris, function (_uri, uri) { _uri.state = uri.state; }); }, RTCUserChangeMessage: function (message) { var content = message.content; var users = content.users; var UserState = { JOINED: 0, LEFT: 1, OFFLINE: 2 }; RongIMLib.RongUtil.forEach(users, function (user) { var state = user.state; var userId = user.userId; switch (+state) { case UserState.JOINED: RongIMClient.roomInfo.users[userId] = {}; break; case UserState.LEFT: case UserState.OFFLINE: delete RongIMClient.roomInfo.users[userId]; break; } }); } }; RongIMClient.RTCInnerListener = function (message) { var func = RTCMessage[message.messageType] || function () { }; var content = message.content; var uris = content.uris; func(message, uris); }; RongIMClient.Conversation = RongIMClient._dataAccessProvider.Conversation; return sdkInfo; }; ; /** var config = { appkey: appkey, token: token, dataAccessProvider:dataAccessProvider, opts: opts }; callback(_instance, userId); */ RongIMClient.initApp = function (config, callback) { RongIMClient.init(config.appkey, config.dataAccessProvider, config.opts, function () { var instance = RongIMClient._instance; //备用 var error = null; callback(error, instance); }); }; /** * 连接服务器,在整个应用全局只需要调用一次,断线后 SDK 会自动重连。 * * @param token 从服务端获取的用户身份令牌(Token)。 * @param callback 连接回调,返回连接的成功或者失败状态。 */ RongIMClient.connect = function (token, _callback, userId, serverConf) { RongIMLib.CheckParam.getInstance().check(["string", "object", "string|null|object|global|undefined", "object|null|global|undefined"], "connect", true, arguments); var connectCallback = { onSuccess: _callback.onSuccess, onTokenIncorrect: _callback.onTokenIncorrect, onError: function (errorCode) { RongIMClient.logger({ code: errorCode, funcName: "connect" }); _callback.onError(errorCode); } }; RongIMClient._dataAccessProvider.connect(token, connectCallback, userId, serverConf); }; RongIMClient.reconnect = function (callback, config) { var connectCallback = { onSuccess: callback.onSuccess, onTokenIncorrect: callback.onTokenIncorrect, onError: function (errorCode) { RongIMClient.logger({ code: errorCode, funcName: "connect" }); callback.onError(errorCode); } }; RongIMClient._dataAccessProvider.reconnect(connectCallback, config); }; /** * 注册消息类型,用于注册用户自定义的消息。 * 内建的消息类型已经注册过,不需要再次注册。 * 自定义消息声明需放在执行顺序最高的位置(在RongIMClient.init(appkey)之后即可) * @param objectName 消息内置名称 */ RongIMClient.registerMessageType = function (messageType, objectName, messageTag, messageContent, searchProps) { RongIMClient._dataAccessProvider.registerMessageType(messageType, objectName, messageTag, messageContent, searchProps); RongIMClient.RegisterMessage[messageType].messageName = messageType; RongIMClient.MessageType[messageType] = messageType; RongIMClient.MessageParams[messageType] = { objectName: objectName, msgTag: messageTag }; }; RongIMClient.prototype.registerMessageTypes = function (types) { types = types || {}; RongIMClient._dataAccessProvider.registerMessageTypes(types); }; /** * 设置连接状态变化的监听器。 * * @param listener 连接状态变化的监听器。 */ RongIMClient.setConnectionStatusListener = function (listener) { if (RongIMClient._dataAccessProvider) { RongIMClient._dataAccessProvider.setConnectionStatusListener(listener); } else { if (RongIMLib.RongUtil.isObject(listener) && RongIMLib.RongUtil.isFunction(listener.onChanged)) { RongIMClient.statusListeners.push(listener.onChanged); } } }; RongIMClient.statusWatch = function (watcher) { if (RongIMLib.RongUtil.isFunction(watcher)) { RongIMClient.statusListeners.push(watcher); } }; /** * 设置接收消息的监听器。 * * @param listener 接收消息的监听器。 */ RongIMClient.setOnReceiveMessageListener = function (listener) { if (RongIMClient._dataAccessProvider) { RongIMClient._dataAccessProvider.setOnReceiveMessageListener(listener); } else { if (RongIMLib.RongUtil.isObject(listener) && RongIMLib.RongUtil.isFunction(listener.onReceived)) { RongIMClient.messageListeners.push(listener.onReceived); } } }; /** * 清理所有连接相关的变量 */ RongIMClient.prototype.logout = function () { RongIMClient._dataAccessProvider.logout(); }; /** * 断开连接。 */ RongIMClient.prototype.disconnect = function () { RongIMClient._dataAccessProvider.disconnect(); }; RongIMClient.prototype.startCustomService = function (custId, callback, content) { if (!custId || !callback) return; var msg = new RongIMLib.HandShakeMessage(content); var me = this; RongIMLib.RongIMClient._memoryStore.custStore["isInit"] = true; RongIMClient.getInstance().sendMessage(RongIMLib.ConversationType.CUSTOMER_SERVICE, custId, msg, { onSuccess: function (data) { if (data.isBlack) { callback.onError(); me.stopCustomeService(custId, { onSuccess: function () { }, onError: function () { } }); } else { callback.onSuccess(); } }, onError: function () { callback.onError(); }, onBefore: function () { } }); }; RongIMClient.prototype.stopCustomeService = function (custId, callback) { if (!custId || !callback) return; var session = RongIMClient._memoryStore.custStore[custId]; if (!session) return; var msg = new RongIMLib.SuspendMessage({ sid: session.sid, uid: session.uid, pid: session.pid }); this.sendCustMessage(custId, msg, { onSuccess: function () { // delete RongIMClient._memoryStore.custStore[custId]; setTimeout(function () { callback.onSuccess(); }); }, onError: function () { setTimeout(function () { callback.onError(); }); } }); }; RongIMClient.prototype.switchToHumanMode = function (custId, callback) { if (!custId || !callback) return; var session = RongIMClient._memoryStore.custStore[custId]; if (!session) return; var msg = new RongIMLib.ChangeModeMessage({ sid: session.sid, uid: session.uid, pid: session.pid }); this.sendCustMessage(custId, msg, callback); }; RongIMClient.prototype.evaluateRebotCustomService = function (custId, isRobotResolved, sugest, callback) { if (!custId || !callback) return; var session = RongIMClient._memoryStore.custStore[custId]; if (!session) return; var msg = new RongIMLib.EvaluateMessage({ sid: session.sid, uid: session.uid, pid: session.pid, isRobotResolved: isRobotResolved, sugest: sugest, type: 0 }); this.sendCustMessage(custId, msg, callback); }; RongIMClient.prototype.evaluateHumanCustomService = function (custId, humanValue, sugest, callback) { if (!custId || !callback) return; var session = RongIMClient._memoryStore.custStore[custId]; if (!session) return; var msg = new RongIMLib.EvaluateMessage({ sid: session.sid, uid: session.uid, pid: session.pid, humanValue: humanValue, sugest: sugest, type: 1 }); this.sendCustMessage(custId, msg, callback); }; RongIMClient.prototype.sendCustMessage = function (custId, msg, callback) { RongIMClient.getInstance().sendMessage(RongIMLib.ConversationType.CUSTOMER_SERVICE, custId, msg, { onSuccess: function (data) { callback.onSuccess(); }, onError: function () { callback.onError(); }, onBefore: function () { } }); }; /** * 获取当前连接的状态。 */ RongIMClient.prototype.getCurrentConnectionStatus = function () { return RongIMClient._dataAccessProvider.getCurrentConnectionStatus(); }; /** * 获取当前使用的连接通道。 */ RongIMClient.prototype.getConnectionChannel = function () { if (RongIMLib.Transportations._TransportType == RongIMLib.Socket.XHR_POLLING) { return RongIMLib.ConnectionChannel.XHR_POLLING; } else if (RongIMLib.Transportations._TransportType == RongIMLib.Socket.WEBSOCKET) { return RongIMLib.ConnectionChannel.WEBSOCKET; } }; /** * 获取当前使用的本地储存提供者。 TODO */ RongIMClient.prototype.getStorageProvider = function () { if (RongIMClient._memoryStore.providerType == 1) { return "ServerDataProvider"; } else { return "OtherDataProvider"; } }; /** * 过滤聊天室消息(拉取最近聊天消息) * @param {string[]} msgFilterNames */ RongIMClient.prototype.setFilterMessages = function (msgFilterNames) { if (Object.prototype.toString.call(msgFilterNames) == "[object Array]") { RongIMClient._memoryStore.filterMessages = msgFilterNames; } }; RongIMClient.prototype.getAgoraDynamicKey = function (engineType, channelName, callback) { RongIMClient._dataAccessProvider.getAgoraDynamicKey(engineType, channelName, callback); }; /** * 获取当前连接用户的 UserId。 */ RongIMClient.prototype.getCurrentUserId = function () { return RongIMLib.Bridge._client.userId; }; /** * 获取服务器时间与本地时间的差值,单位为毫秒。 * 计算公式:差值 = 本地时间毫秒数 - 服务器时间毫秒数 * @param callback 获取的回调,返回差值。 */ RongIMClient.prototype.getDeltaTime = function () { return RongIMClient._dataAccessProvider.getDelaTime(); }; // #region Message RongIMClient.prototype.getMessage = function (messageId, callback) { RongIMClient._dataAccessProvider.getMessage(messageId, RongIMClient.logCallback(callback, "getMessage")); }; RongIMClient.prototype.deleteLocalMessages = function (conversationType, targetId, messageIds, callback) { RongIMClient._dataAccessProvider.removeLocalMessage(conversationType, targetId, messageIds, RongIMClient.logCallback(callback, "deleteLocalMessages")); }; RongIMClient.prototype.updateMessage = function (message, callback) { RongIMClient._dataAccessProvider.updateMessage(message, RongIMClient.logCallback(callback, "updateMessage")); }; RongIMClient.prototype.clearData = function () { return RongIMClient._dataAccessProvider.clearData(); }; RongIMClient.prototype.clearMessages = function (conversationType, targetId, callback) { RongIMClient._dataAccessProvider.clearMessages(conversationType, targetId, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "clearMessages" }); callback.onError(errorCode); }); } }); }; /**TODO 清楚本地存储的未读消息,目前清空内存中的未读消息 * [clearMessagesUnreadStatus 清空指定会话未读消息] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [用户id] * @param {ResultCallback} callback [返回值,参数回调] */ RongIMClient.prototype.clearMessagesUnreadStatus = function (conversationType, targetId, callback) { RongIMClient._dataAccessProvider.updateMessages(conversationType, targetId, "readStatus", null, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "clearMessagesUnreadStatus" }); callback.onError(errorCode); }); } }); }; // deleteRemoteMessages(conversationType: ConversationType, targetId: string, delMsgs: DeleteMessage[], callback: ResultCallback) { // CheckParam.getInstance().check(["number", "string|number", "array", "object"], "deleteRemoteMessages", false, arguments); // if (delMsgs.length == 0) { // var errorCode = ErrorCode.DELETE_MESSAGE_ID_IS_NULL; // RongIMClient.logger({ // code: errorCode, // funcName: "deleteRemoteMessages" // }); // callback.onError(ErrorCode.DELETE_MESSAGE_ID_IS_NULL); // return; // } else if (delMsgs.length > 100) { // delMsgs.length = 100; // } // // 后续增加,去掉注释即可 // callback.onSuccess(true); // // var modules = new RongIMClient.Protobuf.DeleteMsgInput(); // // modules.setType(conversationType); // // modules.setConversationId(targetId); // // modules.setMsgs(delMsgs); // // RongIMClient.bridge.queryMsg(33, MessageUtil.ArrayForm(modules.toArrayBuffer()), Bridge._client.userId, { // // onSuccess: function(info: any) { // // callback.onSuccess(true); // // }, // // onError: function(err: any) { // // callback.onError(err); // // } // // }, "DeleteMsgOutput"); // } /** * [deleteMessages 删除消息记录。] * @param {ConversationType} conversationType [description] * @param {string} targetId [description] * @param {number[]} messageIds [description] * @param {ResultCallback} callback [description] */ RongIMClient.prototype.deleteMessages = function (conversationType, targetId, messages, callback) { RongIMClient._dataAccessProvider.removeMessage(conversationType, targetId, messages, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "deleteMessages" }); callback.onError(errorCode); }); } }); }; RongIMClient.prototype.sendLocalMessage = function (message, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object"], "sendLocalMessage", false, arguments); RongIMClient._dataAccessProvider.updateMessage(message); this.sendMessage(message.conversationType, message.targetId, message.content, RongIMClient.logSendCallback(callback, "sendLocalMessage")); }; RongIMClient.prototype.getPullSetting = function (callback) { RongIMClient._dataAccessProvider.getPullSetting(callback); }; RongIMClient.prototype.setOfflineMessageDuration = function (duration, callback) { RongIMLib.CheckParam.getInstance().check(["number", "object"], "setOfflineMessageDuration", true, arguments); RongIMClient._dataAccessProvider.setOfflineMessageDuration(duration, callback); }; /** * [sendMessage 发送消息。] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [目标Id] * @param {MessageContent} messageContent [消息类型] * @param {SendMessageCallback} sendCallback [] * @param {ResultCallback} resultCallback [返回值,函数回调] * @param {string} pushContent [] * @param {string} pushData [] */ RongIMClient.prototype.sendMessage = function (conversationType, targetId, messageContent, sendCallback, mentiondMsg, pushText, appData, methodType, params) { RongIMLib.CheckParam.getInstance().check(["number", "string", "object", "object", "undefined|object|null|global|boolean", "undefined|object|null|global|string", "undefined|object|null|global|string", "undefined|object|null|global|number", "undefined|object|null|global"], "sendMessage", false, arguments); if (!RongIMLib.RongUtil.isString(targetId)) { return sendCallback.onError(RongIMLib.ErrorCode.PARAMETER_ERROR); } RongIMClient._dataAccessProvider.sendMessage(conversationType, targetId, messageContent, RongIMClient.logSendCallback(sendCallback, "sendMessage"), mentiondMsg, pushText, appData, methodType, params); }; RongIMClient.prototype.sendReceiptResponse = function (conversationType, targetId, sendCallback) { RongIMClient._dataAccessProvider.sendReceiptResponse(conversationType, targetId, RongIMClient.logSendCallback(sendCallback, "sendReceiptResponse")); }; RongIMClient.prototype.sendTypingStatusMessage = function (conversationType, targetId, messageName, sendCallback) { RongIMClient._dataAccessProvider.sendTypingStatusMessage(conversationType, targetId, messageName, RongIMClient.logSendCallback(sendCallback, "sendTypingStatusMessage")); }; /** * [sendStatusMessage description] * @param {MessageContent} messageContent [description] * @param {SendMessageCallback} sendCallback [description] * @param {ResultCallback} resultCallback [description] */ RongIMClient.prototype.sendStatusMessage = function (messageContent, sendCallback, resultCallback) { throw new Error("Not implemented yet"); }; /** * [sendTextMessage 发送TextMessage快捷方式] * @param {string} content [消息内容] * @param {ResultCallback} resultCallback [返回值,参数回调] */ RongIMClient.prototype.sendTextMessage = function (conversationType, targetId, content, sendMessageCallback) { RongIMClient._dataAccessProvider.sendTextMessage(conversationType, targetId, content, RongIMClient.logSendCallback(sendMessageCallback, "sendTextMessage")); }; RongIMClient.prototype.sendRecallMessage = function (content, sendMessageCallback) { var callback = RongIMClient.logSendCallback(sendMessageCallback, "sendRecallMessage"); var senderUserId = content.senderUserId; var userId = RongIMLib.Bridge._client.userId; var isOther = (senderUserId != userId); if (isOther) { var callback = RongIMClient.logSendCallback(sendMessageCallback, "sendRecallMessage"); callback.onError(RongIMLib.ErrorCode.RECALL_MESSAGE, content); return; } RongIMClient._dataAccessProvider.sendRecallMessage(content, callback); }; /** * [insertMessage 向本地插入一条消息,不发送到服务器。] * @param {ConversationType} conversationType [description] * @param {string} targetId [description] * @param {string} senderUserId [description] * @param {MessageContent} content [description] * @param {ResultCallback} callback [description] */ RongIMClient.prototype.insertMessage = function (conversationType, targetId, content, callback) { RongIMClient._dataAccessProvider.addMessage(conversationType, targetId, content, RongIMClient.logCallback(callback, "insertMessage")); }; RongIMClient.prototype.setMessageContent = function (messageId, content, objectName) { RongIMClient._dataAccessProvider.setMessageContent(messageId, content, objectName); }; ; RongIMClient.prototype.setMessageSearchField = function (messageId, content, searchFiles) { RongIMClient._dataAccessProvider.setMessageSearchField(messageId, content, searchFiles); }; ; /** * [getHistoryMessages 拉取历史消息记录。] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [用户Id] * @param {number|null} pullMessageTime [拉取历史消息起始位置(格式为毫秒数),可以为null] * @param {number} count [历史消息数量] * @param {ResultCallback} callback [回调函数] * @param {string} objectName [objectName] */ RongIMClient.prototype.getHistoryMessages = function (conversationType, targetId, timestamp, count, callback, objectname, order) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "number|null|global|object", "number", "object", "undefined|object|null|global|string", "number|null|global|object"], "getHistoryMessages", false, arguments); if (count > 20) { throw new Error("HistroyMessage count must be less than or equal to 20!"); } if (conversationType.valueOf() < 0) { throw new Error("ConversationType must be greater than -1"); } RongIMClient._dataAccessProvider.getHistoryMessages(conversationType, targetId, timestamp, count, RongIMClient.logCallback(callback, "getHistoryMessages"), objectname, order); }; /** * [getRemoteHistoryMessages 拉取某个时间戳之前的消息] * @param {ConversationType} conversationType [description] * @param {string} targetId [description] * @param {Date} dateTime [description] * @param {number} count [description] * @param {ResultCallback} callback [description] */ RongIMClient.prototype.getRemoteHistoryMessages = function (conversationType, targetId, timestamp, count, callback, config) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "number|null|global|object", "number", "object", "undefined|null|global|object"], "getRemoteHistoryMessages", false, arguments); var funcName = "getRemoteHistoryMessages"; var log = { errorCode: RongIMLib.ErrorCode.RC_CONN_PROTO_VERSION_ERROR, funcName: "getRemoteHistoryMessages" }; if (count > 20) { RongIMClient.logger(log); callback.onError(RongIMLib.ErrorCode.RC_CONN_PROTO_VERSION_ERROR); return; } if (conversationType.valueOf() < 0) { RongIMClient.logger(log); callback.onError(RongIMLib.ErrorCode.RC_CONN_PROTO_VERSION_ERROR); return; } RongIMClient._dataAccessProvider.getRemoteHistoryMessages(conversationType, targetId, timestamp, count, RongIMClient.logCallback(callback, funcName), config); }; RongIMClient.prototype.clearHistoryMessages = function (params, callback) { RongIMClient._dataAccessProvider.clearHistoryMessages(params, callback); }; RongIMClient.prototype.clearRemoteHistoryMessages = function (params, callback) { RongIMClient._dataAccessProvider.clearRemoteHistoryMessages(params, RongIMClient.logCallback(callback, "clearRemoteHistoryMessages")); }; RongIMClient.prototype.deleteRemoteMessages = function (conversationType, targetId, messages, callback) { RongIMClient._dataAccessProvider.deleteRemoteMessages(conversationType, targetId, messages, RongIMClient.logCallback(callback, "deleteRemoteMessages")); }; /** * [hasRemoteUnreadMessages 是否有未接收的消息,jsonp方法] * @param {string} appkey [appkey] * @param {string} token [token] * @param {ConnectCallback} callback [返回值,参数回调] */ RongIMClient.prototype.hasRemoteUnreadMessages = function (token, callback) { RongIMClient._dataAccessProvider.hasRemoteUnreadMessages(token, RongIMClient.logCallback(callback, "hasRemoteUnreadMessages")); }; RongIMClient.prototype.getTotalUnreadCount = function (callback, conversationTypes) { RongIMClient._dataAccessProvider.getTotalUnreadCount({ onSuccess: function (count) { setTimeout(function () { callback.onSuccess(count); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "getTotalUnreadCount" }); callback.onError(errorCode); }); } }, conversationTypes); }; /** * [getConversationUnreadCount 指定多种会话类型获取未读消息数] * @param {ResultCallback} callback [返回值,参数回调。] * @param {ConversationType[]} ...conversationTypes [会话类型。] */ RongIMClient.prototype.getConversationUnreadCount = function (conversationTypes, callback) { RongIMClient._dataAccessProvider.getConversationUnreadCount(conversationTypes, { onSuccess: function (count) { setTimeout(function () { callback.onSuccess(count); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "getConversationUnreadCount" }); callback.onError(errorCode); }); } }); }; /** * [getUnreadCount 指定用户、会话类型的未读消息总数。] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [用户Id] */ RongIMClient.prototype.getUnreadCount = function (conversationType, targetId, callback) { RongIMClient._dataAccessProvider.getUnreadCount(conversationType, targetId, { onSuccess: function (count) { setTimeout(function () { callback.onSuccess(count); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "getUnreadCount" }); callback.onError(errorCode); }); } }); }; RongIMClient.prototype.setUnreadCount = function (conversationType, targetId, count) { RongIMLib.CheckParam.getInstance().check(["number", "string", "number"], "setUnreadCount", false, arguments); RongIMClient._dataAccessProvider.setUnreadCount(conversationType, targetId, count); }; RongIMClient.prototype.clearUnreadCountByTimestamp = function (conversationType, targetId, timestamp, callback) { RongIMClient._dataAccessProvider.clearUnreadCountByTimestamp(conversationType, targetId, timestamp, RongIMClient.logCallback(callback, "clearUnreadCountByTimestamp")); }; /** * 清楚会话未读消息数 * @param {ConversationType} conversationType 会话类型 * @param {string} targetId 目标Id * @param {ResultCallback} callback 返回值,函数回调 */ RongIMClient.prototype.clearUnreadCount = function (conversationType, targetId, callback) { RongIMClient._dataAccessProvider.clearUnreadCount(conversationType, targetId, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "clearUnreadCount" }); callback.onError(errorCode); }); } }); }; RongIMClient.prototype.clearTotalUnreadCount = function (callback) { RongIMClient._dataAccessProvider.clearTotalUnreadCount({ onSuccess: function (bool) { callback.onSuccess(bool); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: 'clearTotalUnreadCount' }); callback.onError(errorCode); }); } }); }; RongIMClient.prototype.clearLocalStorage = function (callback) { RongIMClient._storageProvider.clearItem(); callback(); }; RongIMClient.prototype.setMessageExtra = function (messageId, value, callback) { RongIMClient._dataAccessProvider.setMessageExtra(messageId, value, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "setMessageExtra" }); callback.onError(errorCode); }); } }); }; RongIMClient.prototype.setMessageReceivedStatus = function (messageUId, receivedStatus, callback) { RongIMClient._dataAccessProvider.setMessageReceivedStatus(messageUId, receivedStatus, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "setMessageReceivedStatus" }); callback.onError(errorCode); }); } }); }; RongIMClient.prototype.setMessageStatus = function (conersationType, targetId, timestamp, status, callback) { RongIMClient._dataAccessProvider.setMessageStatus(conersationType, targetId, timestamp, status, RongIMClient.logCallback(callback, "setMessageStatus")); }; RongIMClient.prototype.setMessageSentStatus = function (messageId, sentStatus, callback) { RongIMClient._dataAccessProvider.setMessageSentStatus(messageId, sentStatus, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "setMessageSentStatus" }); callback.onError(errorCode); }); } }); }; // #endregion Message // #region TextMessage Draft /** * clearTextMessageDraft 清除指定会话和消息类型的草稿。 * @param {ConversationType} conversationType 会话类型 * @param {string} targetId 目标Id */ RongIMClient.prototype.clearTextMessageDraft = function (conversationType, targetId) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "clearTextMessageDraft", false, arguments); var key = "darf_" + conversationType + "_" + targetId; delete RongIMClient._memoryStore[key]; return true; }; /** * [getTextMessageDraft 获取指定消息和会话的草稿。] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [目标Id] */ RongIMClient.prototype.getTextMessageDraft = function (conversationType, targetId) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "getTextMessageDraft", false, arguments); if (targetId == "" || conversationType < 0) { throw new Error("params error : " + RongIMLib.ErrorCode.DRAF_GET_ERROR); } var key = "darf_" + conversationType + "_" + targetId; return RongIMClient._memoryStore[key]; }; /** * [saveTextMessageDraft description] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [目标Id] * @param {string} value [草稿值] */ RongIMClient.prototype.saveTextMessageDraft = function (conversationType, targetId, value) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "string", "object"], "saveTextMessageDraft", false, arguments); var key = "darf_" + conversationType + "_" + targetId; RongIMClient._memoryStore[key] = value; return true; }; // #endregion TextMessage Draft // #region Conversation RongIMClient.prototype.searchConversationByContent = function (keyword, callback, conversationTypes) { RongIMClient._dataAccessProvider.searchConversationByContent(keyword, RongIMClient.logCallback(callback, "searchConversationByContent"), conversationTypes); }; RongIMClient.prototype.searchMessageByContent = function (conversationType, targetId, keyword, timestamp, count, total, callback) { RongIMClient._dataAccessProvider.searchMessageByContent(conversationType, targetId, keyword, timestamp, count, total, RongIMClient.logCallback(callback, "searchMessageByContent")); }; RongIMClient.prototype.clearCache = function () { RongIMClient._dataAccessProvider.clearCache(); }; RongIMClient.prototype.clearConversations = function (callback) { var conversationTypes = []; for (var _i = 1; _i < arguments.length; _i++) { conversationTypes[_i - 1] = arguments[_i]; } if (conversationTypes.length == 0) { conversationTypes = [RongIMLib.ConversationType.CHATROOM, RongIMLib.ConversationType.CUSTOMER_SERVICE, RongIMLib.ConversationType.DISCUSSION, RongIMLib.ConversationType.GROUP, RongIMLib.ConversationType.PRIVATE, RongIMLib.ConversationType.SYSTEM, RongIMLib.ConversationType.PUBLIC_SERVICE, RongIMLib.ConversationType.APP_PUBLIC_SERVICE]; } RongIMClient._dataAccessProvider.clearConversations(conversationTypes, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "clearConversations" }); callback.onError(errorCode); }); } }); }; /** * [getConversation 获取指定会话,此方法需在getConversationList之后执行] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [目标Id] * @param {ResultCallback} callback [返回值,函数回调] */ RongIMClient.prototype.getConversation = function (conversationType, targetId, callback) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "getConversation", false, arguments); RongIMClient._dataAccessProvider.getConversation(conversationType, targetId, { onSuccess: function (conver) { setTimeout(function () { callback.onSuccess(conver); }); }, onError: function (error) { setTimeout(function () { RongIMClient.logger({ code: error, funcName: "getConversation" }); callback.onError(error); }); } }); }; /** * [pottingConversation 组装会话列表] * @param {any} tempConver [临时会话] * conver_conversationType_targetId_no. * msg_conversationType_targetId_no. */ RongIMClient.prototype.pottingConversation = function (tempConver) { var self = this, isUseReplace = false; RongIMClient._dataAccessProvider.getConversation(tempConver.type, tempConver.userId, { onSuccess: function (conver) { if (!conver) { conver = new RongIMLib.Conversation(); } else { isUseReplace = true; } conver.conversationType = tempConver.type; conver.targetId = tempConver.userId; conver.latestMessage = RongIMLib.MessageUtil.messageParser(tempConver.msg); conver.latestMessageId = conver.latestMessage.messageId; conver.objectName = conver.latestMessage.objectName; conver.receivedStatus = conver.latestMessage.receivedStatus; conver.receivedTime = conver.latestMessage.receiveTime; conver.sentStatus = conver.latestMessage.sentStatus; conver.sentTime = conver.latestMessage.sentTime; var mentioneds = RongIMClient._storageProvider.getItem("mentioneds_" + RongIMLib.Bridge._client.userId + '_' + conver.conversationType + '_' + conver.targetId); if (mentioneds) { var info = JSON.parse(mentioneds); conver.mentionedMsg = info[tempConver.type + "_" + tempConver.userId]; } if (!isUseReplace) { if (RongIMLib.RongUtil.supportLocalStorage()) { // var count = RongIMClient._storageProvider.getItem("cu" + Bridge._client.userId + tempConver.type + tempConver.userId); conver.unreadMessageCount = RongIMLib.UnreadCountHandler.get(tempConver.type, tempConver.userId); } else { conver.unreadMessageCount = 0; } } if (conver.conversationType == RongIMLib.ConversationType.DISCUSSION) { self.getDiscussion(tempConver.userId, { onSuccess: function (info) { conver.conversationTitle = info.name; }, onError: function (error) { } }); } RongIMClient._dataAccessProvider.addConversation(conver, { onSuccess: function (data) { } }); }, onError: function (error) { } }); }; RongIMClient.prototype.addConversation = function (conversation, callback) { RongIMClient._dataAccessProvider.addConversation(conversation, callback); }; RongIMClient.prototype.sortConversationList = function (conversationList) { var convers = []; for (var i = 0, len = conversationList.length; i < len; i++) { if (!conversationList[i]) { continue; } if (conversationList[i].isTop) { convers.push(conversationList[i]); conversationList.splice(i, 1); continue; } for (var j = 0; j < len - i - 1; j++) { if (conversationList[j].sentTime < conversationList[j + 1].sentTime) { var swap = conversationList[j]; conversationList[j] = conversationList[j + 1]; conversationList[j + 1] = swap; } } } return RongIMClient._memoryStore.conversationList = convers.concat(conversationList); }; RongIMClient.prototype.getConversationList = function (callback, conversationTypes, count, isGetHiddenConvers) { RongIMLib.CheckParam.getInstance().check(["object", "null|undefined|array|object|global", "number|undefined|null|object|global", "boolean|undefined|null|object|global"], "getConversationList", false, arguments); var me = this; RongIMClient._dataAccessProvider.getConversationList({ onSuccess: function (data) { if (conversationTypes || RongIMClient._dataAccessProvider) { setTimeout(function () { callback.onSuccess(data); }); } else { setTimeout(function () { callback.onSuccess(RongIMClient._memoryStore.conversationList); }); } }, onError: function (error) { setTimeout(function () { RongIMClient.logger({ code: error, funcName: "getConversationList" }); callback.onError(error); }); } }, conversationTypes, count, isGetHiddenConvers); }; RongIMClient.prototype.getRemoteConversationList = function (callback, conversationTypes, count, isGetHiddenConvers) { RongIMLib.CheckParam.getInstance().check(["object", "null|array|object|global", "number|undefined|null|object|global", "boolean|undefined|null|object|global"], "getRemoteConversationList", false, arguments); RongIMClient._dataAccessProvider.getRemoteConversationList(RongIMClient.logCallback(callback, "getRemoteConversationList"), conversationTypes, count, isGetHiddenConvers); }; RongIMClient.prototype.updateConversation = function (conversation) { return RongIMClient._dataAccessProvider.updateConversation(conversation); }; /** * [createConversation 创建会话。] * @param {number} conversationType [会话类型] * @param {string} targetId [目标Id] * @param {string} converTitle [会话标题] * @param {boolean} islocal [是否同步到服务器,ture:同步,false:不同步] */ RongIMClient.prototype.createConversation = function (conversationType, targetId, converTitle) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "string"], "createConversation", false, arguments); var conver = new RongIMLib.Conversation(); // var unreadContent: string = RongIMClient._storageProvider.getItem("cu" + Bridge._client.userId + conversationType + targetId); // var unreadCount = Number(unreadContent) || 0; conver.targetId = targetId; conver.conversationType = conversationType; conver.conversationTitle = converTitle; conver.latestMessage = {}; conver.unreadMessageCount = 0; return conver; }; //TODO 删除本地和服务器、删除本地和服务器分开 RongIMClient.prototype.removeConversation = function (conversationType, targetId, callback) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "removeConversation", false, arguments); RongIMClient._dataAccessProvider.removeConversation(conversationType, targetId, RongIMClient.logCallback(callback, "removeConversation")); }; RongIMClient.prototype.setConversationHidden = function (conversationType, targetId, isHidden) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "boolean"], "setConversationHidden", false, arguments); RongIMClient._dataAccessProvider.setConversationHidden(conversationType, targetId, isHidden); }; RongIMClient.prototype.setConversationToTop = function (conversationType, targetId, isTop, callback) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "boolean", "object"], "setConversationToTop", false, arguments); RongIMClient._dataAccessProvider.setConversationToTop(conversationType, targetId, isTop, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "setConversationToTop" }); callback.onError(errorCode); }); } }); }; // #endregion Conversation // #region Notifications /** * [getConversationNotificationStatus 获取指定用户和会话类型免提醒。] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [目标Id] * @param {ResultCallback} callback [返回值,函数回调] */ RongIMClient.prototype.getConversationNotificationStatus = function (conversationType, targetId, callback) { var params = { conversationType: conversationType, targetId: targetId }; RongIMClient._dataAccessProvider.getConversationNotificationStatus(params, RongIMClient.logCallback(callback, "getConversationNotificationStatus")); }; /** * [setConversationNotificationStatus 设置指定用户和会话类型免提醒。] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [目标Id] * @param {ResultCallback} callback [返回值,函数回调] */ RongIMClient.prototype.setConversationNotificationStatus = function (conversationType, targetId, notificationStatus, callback) { var params = { conversationType: conversationType, targetId: targetId, status: status }; RongIMClient._dataAccessProvider.setConversationNotificationStatus(params, RongIMClient.logCallback(callback, "setConversationNotificationStatus")); }; /** * [getNotificationQuietHours 获取免提醒消息时间。] * @param {GetNotificationQuietHoursCallback} callback [返回值,函数回调] */ RongIMClient.prototype.getNotificationQuietHours = function (callback) { throw new Error("Not implemented yet"); }; /** * [removeNotificationQuietHours 移除免提醒消息时间。] * @param {GetNotificationQuietHoursCallback} callback [返回值,函数回调] */ RongIMClient.prototype.removeNotificationQuietHours = function (callback) { throw new Error("Not implemented yet"); }; /** * [setNotificationQuietHours 设置免提醒消息时间。] * @param {GetNotificationQuietHoursCallback} callback [返回值,函数回调] */ RongIMClient.prototype.setNotificationQuietHours = function (startTime, spanMinutes, callback) { throw new Error("Not implemented yet"); }; // #endregion Notifications // #region Discussion /** * [addMemberToDiscussion 加入讨论组] * @param {string} discussionId [讨论组Id] * @param {string[]} userIdList [讨论中成员] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.addMemberToDiscussion = function (discussionId, userIdList, callback) { RongIMLib.CheckParam.getInstance().check(["string", "array", "object"], "addMemberToDiscussion", false, arguments); RongIMClient._dataAccessProvider.addMemberToDiscussion(discussionId, userIdList, RongIMClient.logCallback(callback, "addMemberToDiscussion")); }; /** * [createDiscussion 创建讨论组] * @param {string} name [讨论组名称] * @param {string[]} userIdList [讨论组成员] * @param {CreateDiscussionCallback} callback [返回值,函数回调] */ RongIMClient.prototype.createDiscussion = function (name, userIdList, callback) { RongIMLib.CheckParam.getInstance().check(["string", "array", "object"], "createDiscussion", false, arguments); RongIMClient._dataAccessProvider.createDiscussion(name, userIdList, callback); }; /** * [getDiscussion 获取讨论组信息] * @param {string} discussionId [讨论组Id] * @param {ResultCallback} callback [返回值,函数回调] */ RongIMClient.prototype.getDiscussion = function (discussionId, callback) { RongIMLib.CheckParam.getInstance().check(["string", "object"], "getDiscussion", false, arguments); RongIMClient._dataAccessProvider.getDiscussion(discussionId, RongIMClient.logCallback(callback, "getDiscussion")); }; /** * [quitDiscussion 退出讨论组] * @param {string} discussionId [讨论组Id] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.quitDiscussion = function (discussionId, callback) { RongIMLib.CheckParam.getInstance().check(["string", "object"], "quitDiscussion", false, arguments); RongIMClient._dataAccessProvider.quitDiscussion(discussionId, RongIMClient.logCallback(callback, "quitDiscussion")); }; /** * [removeMemberFromDiscussion 将指定成员移除讨论租] * @param {string} discussionId [讨论组Id] * @param {string} userId [被移除的用户Id] * @param {OperationCallback} callback [返回值,参数回调] */ RongIMClient.prototype.removeMemberFromDiscussion = function (discussionId, userId, callback) { RongIMLib.CheckParam.getInstance().check(["string", "string", "object"], "removeMemberFromDiscussion", false, arguments); RongIMClient._dataAccessProvider.removeMemberFromDiscussion(discussionId, userId, RongIMClient.logCallback(callback, "removeMemberFromDiscussion")); }; /** * [setDiscussionInviteStatus 设置讨论组邀请状态] * @param {string} discussionId [讨论组Id] * @param {DiscussionInviteStatus} status [邀请状态] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.setDiscussionInviteStatus = function (discussionId, status, callback) { RongIMLib.CheckParam.getInstance().check(["string", "number", "object"], "setDiscussionInviteStatus", false, arguments); RongIMClient._dataAccessProvider.setDiscussionInviteStatus(discussionId, status, RongIMClient.logCallback(callback, "setDiscussionInviteStatus")); }; /** * [setDiscussionName 设置讨论组名称] * @param {string} discussionId [讨论组Id] * @param {string} name [讨论组名称] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.setDiscussionName = function (discussionId, name, callback) { RongIMLib.CheckParam.getInstance().check(["string", "string", "object"], "setDiscussionName", false, arguments); RongIMClient._dataAccessProvider.setDiscussionName(discussionId, name, RongIMClient.logCallback(callback, "setDiscussionName")); }; // #endregion Discussion // #region ChatRoom /** * [加入聊天室。] * @param {string} chatroomId [聊天室Id] * @param {number} messageCount [拉取消息数量,-1为不拉去消息] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.joinChatRoom = function (chatroomId, messageCount, callback) { RongIMLib.CheckParam.getInstance().check(["string", "number", "object"], "joinChatRoom", false, arguments); if (chatroomId == "") { setTimeout(function () { var errorCode = RongIMLib.ErrorCode.CHATROOM_ID_ISNULL; RongIMClient.logger({ code: errorCode, funcName: "joinChatRoom" }); callback.onError(RongIMLib.ErrorCode.CHATROOM_ID_ISNULL); }); return; } RongIMClient._dataAccessProvider.joinChatRoom(chatroomId, messageCount, RongIMClient.logCallback(callback, "joinChatRoom")); }; RongIMClient.prototype.setDeviceInfo = function (device) { RongIMClient._dataAccessProvider.setDeviceInfo(device); }; RongIMClient.prototype.setChatroomHisMessageTimestamp = function (chatRoomId, timestamp) { RongIMLib.CheckParam.getInstance().check(["string", "number"], "setChatroomHisMessageTimestamp", false, arguments); RongIMClient._dataAccessProvider.setChatroomHisMessageTimestamp(chatRoomId, timestamp); }; RongIMClient.prototype.getChatRoomHistoryMessages = function (chatRoomId, count, order, callback) { RongIMLib.CheckParam.getInstance().check(["string", "number", "number", "object"], "getChatRoomHistoryMessages", false, arguments); RongIMClient._dataAccessProvider.getChatRoomHistoryMessages(chatRoomId, count, order, RongIMClient.logCallback(callback, "getChatRoomHistoryMessages")); }; RongIMClient.prototype.getChatRoomInfo = function (chatRoomId, count, order, callback) { RongIMLib.CheckParam.getInstance().check(["string", "number", "number", "object"], "getChatRoomInfo", false, arguments); RongIMClient._dataAccessProvider.getChatRoomInfo(chatRoomId, count, order, RongIMClient.logCallback(callback, "getChatRoomInfo")); }; /** * [退出聊天室] * @param {string} chatroomId [聊天室Id] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.quitChatRoom = function (chatroomId, callback) { RongIMLib.CheckParam.getInstance().check(["string", "object"], "quitChatRoom", false, arguments); RongIMClient._dataAccessProvider.quitChatRoom(chatroomId, RongIMClient.logCallback(callback, "quitChatRoom")); }; RongIMClient.prototype.setChatroomEntry = function (chatroomId, chatroomEntry, callback) { RongIMLib.CheckParam.getInstance().check(['string', 'object', 'object'], 'setChatroomEntry', false, arguments); RongIMClient._dataAccessProvider.setChatroomEntry(chatroomId, chatroomEntry, RongIMClient.logCallback(callback, "setChatroomEntry")); }; RongIMClient.prototype.forceSetChatroomEntry = function (chatroomId, chatroomEntry, callback) { RongIMLib.CheckParam.getInstance().check(['string', 'object', 'object'], 'setChatroomEntry', false, arguments); RongIMClient._dataAccessProvider.forceSetChatroomEntry(chatroomId, chatroomEntry, RongIMClient.logCallback(callback, "setChatroomEntry")); }; RongIMClient.prototype.getChatroomEntry = function (chatroomId, key, callback) { RongIMLib.CheckParam.getInstance().check(['string', 'string', 'object'], 'getChatroomEntry', false, arguments); RongIMClient._dataAccessProvider.getChatroomEntry(chatroomId, key, RongIMClient.logCallback(callback, "setChatroomEntry")); }; RongIMClient.prototype.getAllChatroomEntries = function (chatroomId, callback) { RongIMLib.CheckParam.getInstance().check(['string', 'object'], 'getAllChatroomEntries', false, arguments); RongIMClient._dataAccessProvider.getAllChatroomEntries(chatroomId, RongIMClient.logCallback(callback, "setChatroomEntry")); }; RongIMClient.prototype.removeChatroomEntry = function (chatroomId, chatroomEntry, callback) { RongIMLib.CheckParam.getInstance().check(['string', 'object', 'object'], 'removeChatroomEntry', false, arguments); RongIMClient._dataAccessProvider.removeChatroomEntry(chatroomId, chatroomEntry, RongIMClient.logCallback(callback, "setChatroomEntry")); }; RongIMClient.prototype.forceRemoveChatroomEntry = function (chatroomId, chatroomEntry, callback) { RongIMLib.CheckParam.getInstance().check(['string', 'object', 'object'], 'removeChatroomEntry', false, arguments); RongIMClient._dataAccessProvider.forceRemoveChatroomEntry(chatroomId, chatroomEntry, RongIMClient.logCallback(callback, "setChatroomEntry")); }; // #endregion ChatRoom // #region Public Service RongIMClient.prototype.getRemotePublicServiceList = function (callback, pullMessageTime) { RongIMClient._dataAccessProvider.getRemotePublicServiceList(RongIMClient.logCallback(callback, "getRemotePublicServiceList"), pullMessageTime); }; /** * [getPublicServiceList ]获取本地的公共账号列表 * @param {ResultCallback} callback [返回值,参数回调] */ RongIMClient.prototype.getPublicServiceList = function (callback) { if (RongIMClient._memoryStore.depend.openMp) { RongIMLib.CheckParam.getInstance().check(["object"], "getPublicServiceList", false, arguments); this.getRemotePublicServiceList(RongIMClient.logCallback(callback, "getPublicServiceList")); } }; /** * [getPublicServiceProfile ] 获取某公共服务信息。 * @param {PublicServiceType} publicServiceType [公众服务类型。] * @param {string} publicServiceId [公共服务 Id。] * @param {ResultCallback} callback [公共账号信息回调。] */ RongIMClient.prototype.getPublicServiceProfile = function (publicServiceType, publicServiceId, callback) { if (RongIMClient._memoryStore.depend.openMp) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "getPublicServiceProfile", false, arguments); RongIMClient._dataAccessProvider.getPublicServiceProfile(publicServiceType, publicServiceId, RongIMClient.logCallback(callback, "getPublicServiceProfile")); } }; /** * [pottingPublicSearchType ] 公众好查询类型 * @param {number} bussinessType [ 0-all 1-mp 2-mc] * @param {number} searchType [0-exact 1-fuzzy] */ RongIMClient.prototype.pottingPublicSearchType = function (bussinessType, searchType) { if (RongIMClient._memoryStore.depend.openMp) { var bits = 0; if (bussinessType == 0) { bits |= 3; if (searchType == 0) { bits |= 12; } else { bits |= 48; } } else if (bussinessType == 1) { bits |= 1; if (searchType == 0) { bits |= 8; } else { bits |= 32; } } else { bits |= 2; if (bussinessType == 0) { bits |= 4; } else { bits |= 16; } } return bits; } }; /** * [searchPublicService ]按公众服务类型搜索公众服务。 * @param {SearchType} searchType [搜索类型枚举。] * @param {string} keywords [搜索关键字。] * @param {ResultCallback} callback [搜索结果回调。] */ RongIMClient.prototype.searchPublicService = function (searchType, keywords, callback) { if (RongIMClient._memoryStore.depend.openMp) { RongIMLib.CheckParam.getInstance().check(["number", "string", "object"], "searchPublicService", false, arguments); var modules = new RongIMClient.Protobuf.SearchMpInput(); modules.setType(this.pottingPublicSearchType(0, searchType)); modules.setId(keywords); RongIMClient.bridge.queryMsg(29, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, RongIMClient.logCallback(callback, "searchPublicService"), "SearchMpOutput"); } }; /** * [searchPublicServiceByType ]按公众服务类型搜索公众服务。 * @param {PublicServiceType} publicServiceType [公众服务类型。] * @param {SearchType} searchType [搜索类型枚举。] * @param {string} keywords [搜索关键字。] * @param {ResultCallback} callback [搜索结果回调。] */ RongIMClient.prototype.searchPublicServiceByType = function (publicServiceType, searchType, keywords, callback) { if (RongIMClient._memoryStore.depend.openMp) { RongIMLib.CheckParam.getInstance().check(["number", "number", "string", "object"], "searchPublicServiceByType", false, arguments); var type = publicServiceType == RongIMLib.ConversationType.APP_PUBLIC_SERVICE ? 2 : 1; var modules = new RongIMClient.Protobuf.SearchMpInput(); modules.setType(this.pottingPublicSearchType(type, searchType)); modules.setId(keywords); RongIMClient.bridge.queryMsg(29, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, RongIMClient.logCallback(callback, "searchPublicServiceByType"), "SearchMpOutput"); } }; /** * [subscribePublicService ] 订阅公众号。 * @param {PublicServiceType} publicServiceType [公众服务类型。] * @param {string} publicServiceId [公共服务 Id。] * @param {OperationCallback} callback [订阅公众号回调。] */ RongIMClient.prototype.subscribePublicService = function (publicServiceType, publicServiceId, callback) { if (RongIMClient._memoryStore.depend.openMp) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "subscribePublicService", false, arguments); var modules = new RongIMClient.Protobuf.MPFollowInput(), me = this, follow = publicServiceType == RongIMLib.ConversationType.APP_PUBLIC_SERVICE ? "mcFollow" : "mpFollow"; modules.setId(publicServiceId); RongIMClient.bridge.queryMsg(follow, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function () { me.getRemotePublicServiceList({ onSuccess: function () { }, onError: function () { } }); callback.onSuccess(); }, onError: function (code) { var errorCode = code; RongIMClient.logger({ code: errorCode, funcName: "subscribePublicService" }); callback.onError(code); } }, "MPFollowOutput"); } }; /** * [unsubscribePublicService ] 取消订阅公众号。 * @param {PublicServiceType} publicServiceType [公众服务类型。] * @param {string} publicServiceId [公共服务 Id。] * @param {OperationCallback} callback [取消订阅公众号回调。] */ RongIMClient.prototype.unsubscribePublicService = function (publicServiceType, publicServiceId, callback) { if (RongIMClient._memoryStore.depend.openMp) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "unsubscribePublicService", false, arguments); var modules = new RongIMClient.Protobuf.MPFollowInput(), me = this, follow = publicServiceType == RongIMLib.ConversationType.APP_PUBLIC_SERVICE ? "mcUnFollow" : "mpUnFollow"; modules.setId(publicServiceId); RongIMClient.bridge.queryMsg(follow, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function () { RongIMClient._memoryStore.publicServiceMap.remove(publicServiceType, publicServiceId); callback.onSuccess(); }, onError: function (code) { var errorCode = code; RongIMClient.logger({ code: errorCode, funcName: "unsubscribePublicService" }); callback.onError(code); } }, "MPFollowOutput"); } }; // #endregion Public Service // #region Blacklist /** * [加入黑名单] * @param {string} userId [将被加入黑名单的用户Id] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.addToBlacklist = function (userId, callback) { RongIMLib.CheckParam.getInstance().check(["string|number", "object"], "addToBlacklist", false, arguments); RongIMClient._dataAccessProvider.addToBlacklist(userId, RongIMClient.logCallback(callback, "addToBlacklist")); }; /** * [获取黑名单列表] * @param {GetBlacklistCallback} callback [返回值,函数回调] */ RongIMClient.prototype.getBlacklist = function (callback) { RongIMLib.CheckParam.getInstance().check(["object"], "getBlacklist", false, arguments); RongIMClient._dataAccessProvider.getBlacklist(callback); }; /** * [得到指定人员再黑名单中的状态] * @param {string} userId [description] * @param {ResultCallback} callback [返回值,函数回调] */ //TODO 如果人员不在黑名单中,获取状态会出现异常 RongIMClient.prototype.getBlacklistStatus = function (userId, callback) { RongIMLib.CheckParam.getInstance().check(["string|number", "object"], "getBlacklistStatus", false, arguments); RongIMClient._dataAccessProvider.getBlacklistStatus(userId, RongIMClient.logCallback(callback, "getBlacklistStatus")); }; /** * [将指定用户移除黑名单] * @param {string} userId [将被移除的用户Id] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.removeFromBlacklist = function (userId, callback) { RongIMLib.CheckParam.getInstance().check(["string|number", "object"], "removeFromBlacklist", false, arguments); RongIMClient._dataAccessProvider.removeFromBlacklist(userId, RongIMClient.logCallback(callback, "removeFromBlacklist")); }; RongIMClient.prototype.getFileToken = function (fileType, callback) { RongIMLib.CheckParam.getInstance().check(["number", "object"], "getQngetFileTokenTkn", false, arguments); RongIMClient._dataAccessProvider.getFileToken(fileType, RongIMClient.logCallback(callback, "getFileToken")); }; RongIMClient.prototype.getFileUrl = function (fileType, fileName, oriName, callback) { RongIMLib.CheckParam.getInstance().check(["number", "string", "string|global|object|null", "object"], "getFileUrl", false, arguments); RongIMClient._dataAccessProvider.getFileUrl(fileType, fileName, oriName, RongIMClient.logCallback(callback, "getFileUrl")); }; ; // #endregion Blacklist // #region Real-time Location Service RongIMClient.prototype.addRealTimeLocationListener = function (conversationType, targetId, listener) { throw new Error("Not implemented yet"); }; RongIMClient.prototype.getRealTimeLocation = function (conversationType, targetId) { throw new Error("Not implemented yet"); }; RongIMClient.prototype.getRealTimeLocationCurrentState = function (conversationType, targetId) { throw new Error("Not implemented yet"); }; RongIMClient.prototype.getRealTimeLocationParticipants = function (conversationType, targetId) { throw new Error("Not implemented yet"); }; RongIMClient.prototype.joinRealTimeLocation = function (conversationType, targetId) { throw new Error("Not implemented yet"); }; RongIMClient.prototype.quitRealTimeLocation = function (conversationType, targetId) { throw new Error("Not implemented yet"); }; RongIMClient.prototype.startRealTimeLocation = function (conversationType, targetId) { throw new Error("Not implemented yet"); }; RongIMClient.prototype.updateRealTimeLocationStatus = function (conversationType, targetId, latitude, longitude) { throw new Error("Not implemented yet"); }; // #endregion Real-time Location Service // # startVoIP RongIMClient.prototype.startCall = function (converType, targetId, userIds, mediaType, extra, callback) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "array", "number", "string", "object"], "startCall", false, arguments); if (RongIMClient._memoryStore.voipStategy) { RongIMClient._voipProvider.startCall(converType, targetId, userIds, mediaType, extra, RongIMClient.logCallback(callback, "startCall")); } else { var errorCode = RongIMLib.ErrorCode.VOIP_NOT_AVALIABLE; RongIMClient.logger({ code: errorCode, funcName: "startCall" }); callback.onError(RongIMLib.ErrorCode.VOIP_NOT_AVALIABLE); } }; RongIMClient.prototype.joinCall = function (mediaType, callback) { RongIMLib.CheckParam.getInstance().check(['number', 'object'], "joinCall", false, arguments); if (RongIMClient._memoryStore.voipStategy) { RongIMClient._voipProvider.joinCall(mediaType, RongIMClient.logCallback(callback, "joinCall")); } else { var errorCode = RongIMLib.ErrorCode.VOIP_NOT_AVALIABLE; RongIMClient.logger({ code: errorCode, funcName: "joinCall" }); callback.onError(RongIMLib.ErrorCode.VOIP_NOT_AVALIABLE); } }; RongIMClient.prototype.hungupCall = function (converType, targetId, reason) { RongIMLib.CheckParam.getInstance().check(["number", "string", "number"], "hungupCall", false, arguments); if (RongIMClient._memoryStore.voipStategy) { RongIMClient._voipProvider.hungupCall(converType, targetId, reason); } }; RongIMClient.prototype.changeMediaType = function (converType, targetId, mediaType, callback) { RongIMLib.CheckParam.getInstance().check(["number", "string", "number", "object"], "changeMediaType", false, arguments); if (RongIMClient._memoryStore.voipStategy) { RongIMClient._voipProvider.changeMediaType(converType, targetId, mediaType, RongIMClient.logCallback(callback, "changeMediaType")); } else { var errorCode = RongIMLib.ErrorCode.VOIP_NOT_AVALIABLE; RongIMClient.logger({ code: errorCode, funcName: "changeMediaType" }); callback.onError(RongIMLib.ErrorCode.VOIP_NOT_AVALIABLE); } }; // # endVoIP RongIMClient.prototype.getUnreadMentionedMessages = function (conversationType, targetId) { return RongIMClient._dataAccessProvider.getUnreadMentionedMessages(conversationType, targetId); }; RongIMClient.prototype.clearListeners = function () { RongIMClient._dataAccessProvider.clearListeners(); }; // UserStatus start RongIMClient.prototype.getUserStatus = function (userId, callback) { RongIMClient._dataAccessProvider.getUserStatus(userId, RongIMClient.logCallback(callback, "getUserStatus")); }; RongIMClient.prototype.setUserStatus = function (status, callback) { RongIMClient._dataAccessProvider.setUserStatus(status, RongIMClient.logCallback(callback, "setUserStatus")); }; RongIMClient.prototype.setUserStatusListener = function (params, callback) { var userIds = params.userIds; var multiple = params.multiple; RongIMClient.userStatusObserver.watch({ key: userIds, func: callback, multiple: multiple }); RongIMClient._dataAccessProvider.setUserStatusListener(params, callback); }; // UserStaus end // RTC start RongIMClient.messageWatch = function (watcher) { RongIMClient.RTCListener = watcher; }; RongIMClient.messageSignalWatch = function (watcher) { RongIMClient.RTCSignalLisener = watcher; }; /* var data = { key1: 123, key2: 345 }; */ RongIMClient.prototype.getRTCUserInfoList = function (room, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object"], "getRTCUserInfoList", false, arguments); RongIMClient._dataAccessProvider.getRTCUserInfoList(room, callback); }; RongIMClient.prototype.getRTCUserList = function (room, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object"], "getRTCUserList", false, arguments); RongIMClient._dataAccessProvider.getRTCUserList(room, callback); }; RongIMClient.prototype.setRTCUserInfo = function (room, info, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object", "object"], "setRTCUserInfo", false, arguments); RongIMClient._dataAccessProvider.setRTCUserInfo(room, info, callback); }; RongIMClient.prototype.removeRTCUserInfo = function (room, info, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object", "object"], "removeRTCUserInfo", false, arguments); RongIMClient._dataAccessProvider.removeRTCUserInfo(room, info, callback); }; RongIMClient.prototype.getRTCRoomInfo = function (room, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object"], "getRTCRoomInfo", false, arguments); RongIMClient._dataAccessProvider.getRTCRoomInfo(room, callback); }; RongIMClient.prototype.setRTCRoomInfo = function (room, info, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object", "object"], "setRTCRoomInfo", false, arguments); RongIMClient._dataAccessProvider.setRTCRoomInfo(room, info, callback); }; RongIMClient.prototype.removeRTCRoomInfo = function (room, info, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object", "object"], "removeRTCRoomInfo", false, arguments); RongIMClient._dataAccessProvider.removeRTCRoomInfo(room, info, callback); }; RongIMClient.prototype.joinRTCRoom = function (room, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object"], "joinRTCRoom", false, arguments); if (RongIMClient.isJoinedRTCRoom) { return callback.onSuccess(RongIMClient.roomInfo); } RongIMClient._dataAccessProvider.joinRTCRoom(room, { onSuccess: function (result) { RongIMClient.roomInfo = result; RongIMClient.isJoinedRTCRoom = true; callback.onSuccess(result); }, onError: callback.onError }); }; RongIMClient.prototype.quitRTCRoom = function (room, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object"], "quitRTCRoom", false, arguments); RongIMClient.isJoinedRTCRoom = false; RongIMClient._dataAccessProvider.quitRTCRoom(room, { onSuccess: function () { RongIMClient.roomInfo = { users: {}, token: '' }; callback.onSuccess(true); }, onError: callback.onError }); }; RongIMClient.prototype.RTCPing = function (room, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object"], "RTCPing", false, arguments); RongIMClient._dataAccessProvider.RTCPing(room, callback); }; RongIMClient.prototype.setRTCUserData = function (roomId, key, value, isInner, callback, message) { RongIMLib.CheckParam.getInstance().check(["string", "string", "string", "boolean", "object", "global|object|null|undefined"], "setRTCUserData", false, arguments); RongIMClient._dataAccessProvider.setRTCUserData(roomId, key, value, isInner, callback, message); }; RongIMClient.prototype.getRTCUserData = function (roomId, keys, isInner, callback) { RongIMLib.CheckParam.getInstance().check(["string", "array", "boolean", "object", "global|object|null"], "getRTCUserData", false, arguments); RongIMClient._dataAccessProvider.getRTCUserData(roomId, keys, isInner, callback); }; RongIMClient.prototype.removeRTCUserData = function (roomId, keys, isInner, callback, message) { RongIMLib.CheckParam.getInstance().check(["string", "array", "boolean", "object", "global|object|null|undefined"], "removeRTCUserData", false, arguments); RongIMClient._dataAccessProvider.removeRTCUserData(roomId, keys, isInner, callback, message); }; RongIMClient.prototype.setRTCRoomData = function (roomId, key, value, isInner, callback, message) { RongIMLib.CheckParam.getInstance().check(["string", "string", "string", "boolean", "object", "global|object|null|undefined"], "setRTCRoomData", false, arguments); RongIMClient._dataAccessProvider.setRTCRoomData(roomId, key, value, isInner, callback, message); }; RongIMClient.prototype.getRTCRoomData = function (roomId, keys, isInner, callback) { RongIMLib.CheckParam.getInstance().check(["string", "array", "boolean", "object"], "getRTCRoomData", false, arguments); RongIMClient._dataAccessProvider.getRTCRoomData(roomId, keys, isInner, callback); }; RongIMClient.prototype.removeRTCRoomData = function (roomId, keys, isInner, callback, message) { RongIMLib.CheckParam.getInstance().check(["string", "array", "boolean", "object", "global|object|null|undefined"], "removeRTCRoomData", false, arguments); RongIMClient._dataAccessProvider.removeRTCRoomData(roomId, keys, isInner, callback, message); }; RongIMClient.prototype.setRTCOutData = function (roomId, data, type, callback, message) { RongIMClient._dataAccessProvider.setRTCOutData(roomId, data, type, callback, message); }; // 信令 SDK 新增 RongIMClient.prototype.getRTCOutData = function (roomId, userIds, callback) { RongIMClient._dataAccessProvider.getRTCOutData(roomId, userIds, callback); }; RongIMClient.prototype.getNavi = function () { return RongIMClient._dataAccessProvider.getNavi(); }; RongIMClient.prototype.getRTCToken = function (room, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object"], "getRTCToken", false, arguments); return RongIMClient._dataAccessProvider.getRTCToken(room, callback); }; RongIMClient.prototype.setRTCState = function (room, content, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object", "object"], "setRTCState", false, arguments); return RongIMClient._dataAccessProvider.setRTCState(room, content, callback); }; RongIMClient.prototype.getAppInfo = function () { var appKey = RongIMClient._memoryStore.appKey; return { appKey: appKey }; }; RongIMClient.prototype.getSDKInfo = function () { return { version: RongIMClient.sdkver }; }; RongIMClient.RTCListener = function () { }; RongIMClient.RTCInnerListener = function () { }; RongIMClient.RTCSignalLisener = function () { }; RongIMClient.MaxMessageContentBytes = 131072; // 128kb RongIMClient.currentServer = ''; RongIMClient.LogFactory = {}; RongIMClient.MessageType = {}; RongIMClient.RegisterMessage = {}; RongIMClient._memoryStore = { isPullFinished: false, syncMsgQueue: [] }; RongIMClient.isNotPullMsg = false; RongIMClient.userStatusObserver = null; RongIMClient.sdkver = '2.5.5'; RongIMClient.otherDeviceLoginCount = 0; RongIMClient.serverStore = { index: 0 }; RongIMClient.isFirstConnect = true; RongIMClient.roomInfo = { users: {}, token: '' }; RongIMClient.invalidWsUrls = []; RongIMClient.isJoinedRTCRoom = false; RongIMClient.statusListeners = []; RongIMClient.messageListeners = []; RongIMClient.userStatusListener = null; return RongIMClient; })(); RongIMLib.RongIMClient = RongIMClient; })(RongIMLib || (RongIMLib = {})); //用于连接通道 var RongIMLib; (function (RongIMLib) { (function (Qos) { Qos[Qos["AT_MOST_ONCE"] = 0] = "AT_MOST_ONCE"; Qos[Qos["AT_LEAST_ONCE"] = 1] = "AT_LEAST_ONCE"; Qos[Qos["EXACTLY_ONCE"] = 2] = "EXACTLY_ONCE"; Qos[Qos["DEFAULT"] = 3] = "DEFAULT"; })(RongIMLib.Qos || (RongIMLib.Qos = {})); var Qos = RongIMLib.Qos; (function (Type) { Type[Type["CONNECT"] = 1] = "CONNECT"; Type[Type["CONNACK"] = 2] = "CONNACK"; Type[Type["PUBLISH"] = 3] = "PUBLISH"; Type[Type["PUBACK"] = 4] = "PUBACK"; Type[Type["QUERY"] = 5] = "QUERY"; Type[Type["QUERYACK"] = 6] = "QUERYACK"; Type[Type["QUERYCON"] = 7] = "QUERYCON"; Type[Type["SUBSCRIBE"] = 8] = "SUBSCRIBE"; Type[Type["SUBACK"] = 9] = "SUBACK"; Type[Type["UNSUBSCRIBE"] = 10] = "UNSUBSCRIBE"; Type[Type["UNSUBACK"] = 11] = "UNSUBACK"; Type[Type["PINGREQ"] = 12] = "PINGREQ"; Type[Type["PINGRESP"] = 13] = "PINGRESP"; Type[Type["DISCONNECT"] = 14] = "DISCONNECT"; })(RongIMLib.Type || (RongIMLib.Type = {})); var Type = RongIMLib.Type; var _topic = [ "invtDiz", "crDiz", "qnUrl", "userInf", "dizInf", "userInf", "joinGrp", "quitDiz", "exitGrp", "evctDiz", ["", "ppMsgP", "pdMsgP", "pgMsgP", "chatMsg", "pcMsgP", "", "pmcMsgN", "pmpMsgN", "", "", "", "prMsgS", "prMsgP"], "pdOpen", "rename", "uGcmpr", "qnTkn", "destroyChrm", "createChrm", "exitChrm", "queryChrm", "joinChrm", "pGrps", "addBlack", "rmBlack", "getBlack", "blackStat", "addRelation", "qryRelation", "delRelation", "pullMp", "schMp", "qnTkn", "qnUrl", "qryVoipK", "delMsg", "qryCHMsg", "getUserStatus", "setUserStatus", "subUserStatus", "cleanHisMsg" ]; var Channel = (function () { function Channel(cb, self) { this.connectionStatus = -1; var appId = self.appId; var token = encodeURIComponent(self.token); var sdkVer = self.sdkVer; var apiVer = self.apiVer; this.self = self; this.socket = Socket.getInstance().createServer(); var that = this; var storage = RongIMLib.RongIMClient._storageProvider; var servers = storage.getItem('servers'); servers = JSON.parse(servers) || []; servers = RongIMLib.RongUtil.getValidWsUrlList(servers); var depend = RongIMLib.RongIMClient._memoryStore.depend; if (depend.cmpUrl) { servers = [depend.cmpUrl].concat(servers); } var startConnect = function (host) { var tpl = '{host}/websocket?appId={appId}&token={token}&sdkVer={sdkVer}&apiVer={apiVer}'; that.url = RongIMLib.RongUtil.tplEngine(tpl, { host: host, appId: appId, token: token, sdkVer: sdkVer, apiVer: apiVer }); that.socket.connect(that.url, cb); // 临时兼容 Comet 逻辑,Comet 中用到 var userId = storage.getItem('rong_current_user'); RongIMLib.Navigation.Endpoint = { host: host, userId: userId }; }; var connectMap = { get: function () { // 所有链接计算器,超过 15 秒后认为所有 CMP 地址均不可用 var totalTimer = new RongIMLib.Timer({ timeout: 1 * 1000 * 15 }); var timers = []; var xhrs = []; var isFinished = false; var clearHandler = function () { for (var i = 0; i < timers.length; i++) { var timer = timers[i]; clearTimeout(timer); } for (var i = 0; i < xhrs.length; i++) { var xhr = xhrs[i]; xhr.abort(); } timers.length = 0; xhrs.length = 0; }; var request = function (config, callback) { var url = config.url; var time = config.time; if (isFinished) { return; } var timer = setTimeout(function () { var onSuccess = function () { if (isFinished) { return; } clearHandler(); isFinished = true; totalTimer.pause(); callback(url); }; var xhr = RongIMLib.MessageUtil.detectCMP({ url: url, success: onSuccess, fail: function (code) { console.log(code); } }); xhrs.push(xhr); }, time); timers.push(timer); }; var snifferCallback = function (url) { var reg = /(http|https):\/\/([^\/]+)/i; var host = url.match(reg)[2]; RongIMLib.RongIMClient.currentServer = host; startConnect(host); }; var snifferTpl = '{protocol}{server}/ping?r={random}'; for (var i = 0; i < servers.length; i++) { var server = servers[i]; if (server) { server = RongIMLib.RongUtil.tplEngine(snifferTpl, { protocol: depend.protocol, server: server, random: RongIMLib.RongUtil.getTimestamp() }); request({ url: server, time: i * 1000 }, snifferCallback); } } totalTimer.resume(function () { RongIMLib.Navigation.clear(); clearHandler(); that.socket.fire("StatusChanged", RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE); }); }, element: function () { var totalTimer = new RongIMLib.Timer({ timeout: 1 * 1000 * 15 }); var timers = []; var elements = []; var isFinished = false; var clearHandler = function () { for (var i = 0; i < timers.length; i++) { var timer = timers[i]; clearTimeout(timer); } for (var i = 0; i < elements.length; i++) { var el = elements[i]; document.body.removeChild(el); } }; var request = function (config, callback) { var url = config.url; var time = config.time; if (isFinished) { return; } var timer = setTimeout(function () { var el = document.createElement('script'); el.src = url; document.body.appendChild(el); el.onerror = function () { if (isFinished) { return; } clearHandler(); isFinished = true; totalTimer.pause(); var url = el.src; callback(url); }; elements.push(el); }, time); timers.push(timer); }; var snifferCallback = function (url) { var reg = /(http|https):\/\/([^\/]+)/i; var host = url.match(reg)[2]; startConnect(host); }; var snifferTpl = '//{server}/{path}'; for (var i = 0; i < servers.length; i++) { var server = RongIMLib.RongUtil.tplEngine(snifferTpl, { server: servers[i], path: i }); request({ url: server, time: i * 1000 }, snifferCallback); } totalTimer.resume(function () { clearHandler(); that.socket.fire("StatusChanged", RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE); }); } }; var isWSPingJSONP = depend.isWSPingJSONP; var connectType = isWSPingJSONP ? 'element' : 'get'; connectMap[connectType](); //注册状态改变观察者 var StatusEvent = Channel._ConnectionStatusListener; var hasEvent = (typeof StatusEvent == "object"); var me = this; me.socket.on("StatusChanged", function (code) { if (RongIMLib.Bridge && RongIMLib.Bridge._client && RongIMLib.Bridge._client.channel && me !== RongIMLib.Bridge._client.channel) { return; } if (!hasEvent) { throw new Error("setConnectStatusListener:Parameter format is incorrect"); } var isNetworkUnavailable = (code == RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE); var isWebSocket = !RongIMLib.RongIMClient._memoryStore.depend.isPolling; if (RongIMLib.RongIMClient.isFirstConnect && isNetworkUnavailable && isWebSocket) { code = RongIMLib.ConnectionStatus.WEBSOCKET_UNAVAILABLE; } if (isNetworkUnavailable) { var storage = RongIMLib.RongIMClient._storageProvider; var servers = storage.getItem('servers'); servers = JSON.parse(servers); var currentServer = RongIMLib.RongIMClient.currentServer; if (currentServer) { var index = RongIMLib.RongUtil.indexOf(servers, currentServer); // 如果 currentServer 是 servers 的最后一个,不再替换位置 if (!RongIMLib.RongUtil.isEqual(index, -1)) { var server = servers.splice(index, 1)[0]; servers.push(server); storage.setItem('servers', JSON.stringify(servers)); } } } me.connectionStatus = code; setTimeout(function () { StatusEvent.onChanged(code); }); var isDisconnected = (code == RongIMLib.ConnectionStatus.DISCONNECTED); if (isDisconnected) { self.clearHeartbeat(); } var isOtherDevice = (code == RongIMLib.ConnectionStatus.KICKED_OFFLINE_BY_OTHER_CLIENT); if (isOtherDevice) { // 累计其他设备登陆次数,超过 5 次后,自动销毁内部对象 // 删除位置:ServerDataProivder.prototype.connect RongIMLib.RongIMClient.otherDeviceLoginCount++; } var isConnected = (code == RongIMLib.ConnectionStatus.CONNECTED); if (isConnected) { RongIMLib.RongIMClient.isFirstConnect = false; } var isWebsocketUnAvailable = (code == RongIMLib.ConnectionStatus.WEBSOCKET_UNAVAILABLE); if (isWebsocketUnAvailable) { me.changeConnectType(); RongIMLib.RongIMClient.isFirstConnect = false; RongIMLib.RongIMClient.connect(self.token, RongIMLib.RongIMClient._memoryStore.callback); } }); //注册message观察者 this.socket.on("message", self.handler.handleMessage); //注册断开连接观察者 this.socket.on("disconnect", function (status) { that.socket.fire("StatusChanged", status ? status : 2); }); } Channel.prototype.changeConnectType = function () { RongIMLib.RongIMClient._memoryStore.depend.isPolling = !RongIMLib.RongIMClient._memoryStore.depend.isPolling; new RongIMLib.FeatureDectector(); }; Channel.prototype.writeAndFlush = function (val) { this.socket.send(val); }; Channel.prototype.reconnect = function (callback) { RongIMLib.MessageIdHandler.clearMessageId(); this.socket = this.socket.reconnect(); if (callback) { this.self.reconnectObj = callback; } }; Channel.prototype.disconnect = function (status) { this.socket.disconnect(status); }; return Channel; })(); RongIMLib.Channel = Channel; var Socket = (function () { function Socket() { this.socket = null; this._events = {}; } Socket.getInstance = function () { return new Socket(); }; Socket.prototype.connect = function (url, cb) { if (this.socket) { if (url) { RongIMLib.RongIMClient._storageProvider.setItem("rongSDK", this.checkTransport()); this.on("connect", cb || new Function); } if (url) { this.currentURL = url; } this.socket.createTransport(url); } return this; }; Socket.prototype.createServer = function () { var transport = this.getTransport(this.checkTransport()); if (transport === null) { throw new Error("the channel was not supported"); } return transport; }; Socket.prototype.getTransport = function (transportType) { if (transportType == Socket.XHR_POLLING) { this.socket = new RongIMLib.PollingTransportation(this); } else if (transportType == Socket.WEBSOCKET) { this.socket = new RongIMLib.SocketTransportation(this); } return this; }; Socket.prototype.send = function (data) { if (this.socket) { if (this.checkTransport() == Socket.WEBSOCKET) { this.socket.send(data); } else { this.socket.send(this._encode(data)); } } }; Socket.prototype.onMessage = function (data) { this.fire("message", data); }; Socket.prototype.disconnect = function (status) { this.socket.disconnect(status); this.fire("disconnect", status); return this; }; Socket.prototype.reconnect = function () { if (this.currentURL && RongIMLib.RongIMClient._storageProvider.getItem("rongSDK")) { return this.connect(this.currentURL, null); } else { throw new Error("reconnect:no have URL"); } }; /** * [checkTransport 返回通道类型] */ Socket.prototype.checkTransport = function () { if (RongIMLib.RongIMClient._memoryStore.depend.isPolling) { RongIMLib.Transportations._TransportType = Socket.XHR_POLLING; } return RongIMLib.Transportations._TransportType; }; Socket.prototype.fire = function (x, args) { if (x in this._events) { for (var i = 0, ii = this._events[x].length; i < ii; i++) { this._events[x][i](args); } } return this; }; Socket.prototype.on = function (x, func) { if (!(typeof func == "function" && x)) { return this; } if (x in this._events) { RongIMLib.MessageUtil.indexOf(this._events, func) == -1 && this._events[x].push(func); } else { this._events[x] = [func]; } return this; }; Socket.prototype.removeEvent = function (x, fn) { if (x in this._events) { for (var a = 0, l = this._events[x].length; a < l; a++) { if (this._events[x][a] == fn) { this._events[x].splice(a, 1); } } } return this; }; Socket.prototype._encode = function (x) { var str = "?messageid=" + x.getMessageId() + "&header=" + x.getHeaderFlag() + "&sessionid=" + RongIMLib.RongIMClient._storageProvider.getItem("sId" + RongIMLib.Navigation.Endpoint.userId); if (!/(PubAckMessage|QueryConMessage)/.test(x._name)) { str += "&topic=" + x.getTopic() + "&targetid=" + (x.getTargetId() || ""); } return { url: str, data: "getData" in x ? x.getData() : "" }; }; //消息通道常量,所有和通道相关判断均用 XHR_POLLING WEBSOCKET两属性 Socket.XHR_POLLING = "xhr-polling"; Socket.WEBSOCKET = "websocket"; return Socket; })(); RongIMLib.Socket = Socket; //连接端消息累 var Client = (function () { function Client(token, appId) { this.timeoutMillis = 6000; this.timeout_ = 0; this.sdkVer = ''; this.apiVer = Math.floor(Math.random() * 1e6); this.channel = null; this.handler = null; this.userId = ""; this.reconnectObj = {}; this.heartbeat = 0; this.pullMsgHearbeat = 0; this.chatroomId = ""; this.SyncTimeQueue = []; this.cacheMessageIds = []; this.token = token; this.appId = appId; this.SyncTimeQueue.state = "complete"; this.sdkVer = RongIMLib.RongIMClient.sdkver; } Client.prototype.resumeTimer = function () { var me = this; this.timeout_ = setTimeout(function () { me.channel.disconnect(RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE); }, this.timeoutMillis); }; Client.prototype.pauseTimer = function () { if (this.timeout_) { clearTimeout(this.timeout_); this.timeout_ = 0; } }; Client.prototype.connect = function (_callback) { //实例消息处理类 this.handler = new MessageHandler(this); //设置连接回调 this.handler.setConnectCallback(_callback); //实例通道类型 var me = this; this.channel = new Channel(function () { RongIMLib.Transportations._TransportType == Socket.WEBSOCKET && me.keepLive(); }, this); //触发状态改变观察者 this.channel.socket.fire("StatusChanged", RongIMLib.ConnectionStatus.CONNECTING); //没有返回地址就手动抛出错误 //_callback.onError(ConnectionState.NOT_AUTHORIZED); }; Client.prototype.checkSocket = function (callback) { var me = this; me.channel.writeAndFlush(new RongIMLib.PingReqMessage()); var count = 0; var checkTimeout = setInterval(function () { if (!RongIMLib.RongIMClient._memoryStore.isFirstPingMsg) { clearInterval(checkTimeout); callback.onSuccess(); } else { if (count > 15) { clearInterval(checkTimeout); callback.onError(); } } count++; }, 100); }; Client.prototype.keepLive = function () { if (this.heartbeat > 0) { clearInterval(this.heartbeat); } var me = this; me.heartbeat = setInterval(function () { me.resumeTimer(); me.channel.writeAndFlush(new RongIMLib.PingReqMessage()); }, 30000); if (me.pullMsgHearbeat > 0) { clearInterval(me.pullMsgHearbeat); } me.pullMsgHearbeat = setInterval(function () { me.syncTime(true, undefined, undefined, false); }, 180000); }; Client.prototype.clearHeartbeat = function () { clearInterval(this.heartbeat); this.heartbeat = 0; this.pauseTimer(); clearInterval(this.pullMsgHearbeat); this.pullMsgHearbeat = 0; }; Client.prototype.publishMessage = function (_topic, _data, _targetId, _callback, _msg) { var msgId = RongIMLib.MessageIdHandler.messageIdPlus(this.channel.reconnect); if (!msgId) { return; } var msg = new RongIMLib.PublishMessage(_topic, _data, _targetId); msg.setMessageId(msgId); if (_callback) { msg.setQos(Qos.AT_LEAST_ONCE); this.handler.putCallback(new RongIMLib.PublishCallback(_callback.onSuccess, _callback.onError), msg.getMessageId(), _msg); } else { msg.setQos(Qos.AT_MOST_ONCE); } this.channel.writeAndFlush(msg); }; Client.prototype.queryMessage = function (_topic, _data, _targetId, _qos, _callback, pbtype) { if (_topic == "userInf") { if (Client.userInfoMapping[_targetId]) { _callback.onSuccess(Client.userInfoMapping[_targetId]); return; } } var msgId = RongIMLib.MessageIdHandler.messageIdPlus(this.channel.reconnect); if (!msgId) { return; } var msg = new RongIMLib.QueryMessage(_topic, _data, _targetId); msg.setMessageId(msgId); msg.setQos(_qos); this.handler.putCallback(new RongIMLib.QueryCallback(_callback.onSuccess, _callback.onError), msg.getMessageId(), pbtype); this.channel.writeAndFlush(msg); }; Client.prototype.invoke = function (isPullMsg, chrmId, offlineMsg) { var time, modules, str, me = this, target, temp = this.SyncTimeQueue.shift(); if (temp == undefined) { return; } this.SyncTimeQueue.state = "pending"; var localSyncTime = RongIMLib.SyncTimeUtil.get(); var sentBoxTime = localSyncTime.sent; var isPullChatroom = temp.type === 2; if (temp.type != 2) { //普通消息 time = localSyncTime.received; modules = new RongIMLib.RongIMClient.Protobuf.SyncRequestMsg(); modules.setIspolling(false); str = "pullMsg"; target = this.userId; modules.setSendBoxSyncTime(sentBoxTime); } else { //聊天室消息 target = temp.chrmId || me.chatroomId; time = RongIMLib.RongIMClient._memoryStore.lastReadTime.get(target + Bridge._client.userId + "CST") || 0; modules = new RongIMLib.RongIMClient.Protobuf.ChrmPullMsg(); modules.setCount(0); str = "chrmPull"; if (!target) { throw new Error("syncTime:Received messages of chatroom but was not init"); } } //判断服务器给的时间是否消息本地存储的时间,小于的话不执行拉取操作,进行一下步队列操作 if (temp.pulltime <= time) { this.SyncTimeQueue.state = "complete"; this.invoke(isPullMsg, target, offlineMsg); return; } if (isPullMsg && 'setIsPullSend' in modules) { modules.setIsPullSend(true); } modules.setSyncTime(time); //发送queryMessage请求 this.queryMessage(str, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), target, Qos.AT_LEAST_ONCE, { onSuccess: function (collection) { var sync = RongIMLib.MessageUtil.int64ToTimestamp(collection.syncTime), symbol = target; //把返回时间戳存入本地,普通消息key为userid,聊天室消息key为userid+'CST';value都为服务器返回的时间戳 var isChrmPull = str == 'chrmPull'; if (isChrmPull) { symbol += Bridge._client.userId + "CST"; RongIMLib.RongIMClient._memoryStore.lastReadTime.set(symbol, sync); } else { var storage = RongIMLib.RongIMClient._storageProvider; if (sync > storage.getItem(symbol)) { storage.setItem(symbol, sync); } } //把拉取到的消息逐条传给消息监听器 var list = collection.list; var isPullFinished = collection.finished; // chrmPull 没有 finished 字段,自动设置为拉取完成 if (isChrmPull) { isPullFinished = true; } // 兼容长轮训 finished 为空的造成丢消息情况 if (typeof isPullFinished == 'undefined') { isPullFinished = true; } RongIMLib.RongIMClient._memoryStore.isPullFinished = isPullFinished; var connectAckTime = RongIMLib.RongIMClient._memoryStore.connectAckTime; var len = list.length; for (var i = 0, count = len; i < len; i++) { count -= 1; var message = list[i]; var sentTime = RongIMLib.MessageUtil.int64ToTimestamp(message.dataTime); var isSender = message.direction == RongIMLib.MessageDirection.SEND; var compareTime = isSender ? sentBoxTime : time; if (sentTime > compareTime || isPullChatroom) { var isSyncMessage = false; var isOffLineMessage = sentTime < connectAckTime; Bridge._client.handler.onReceived(message, undefined, isOffLineMessage, count, isSyncMessage, isPullFinished); } } if (len <= 200 && str == 'pullMsg') { var Conversation = RongIMLib.RongIMClient._dataAccessProvider.Conversation; var conversationList = RongIMLib.RongIMClient._memoryStore.conversationList; Conversation._notify(conversationList); } me.SyncTimeQueue.state = "complete"; me.invoke(isPullMsg, target, offlineMsg); }, onError: function (error) { me.SyncTimeQueue.state = "complete"; me.invoke(isPullMsg, target, offlineMsg); } }, "DownStreamMessages"); }; Client.prototype.syncTime = function (_type, pullTime, chrmId, offlineMsg) { this.SyncTimeQueue.push({ type: _type, pulltime: pullTime, chrmId: chrmId }); //如果队列中只有一个成员并且状态已经完成就执行invoke方法 if (this.SyncTimeQueue.length == 1 && this.SyncTimeQueue.state == "complete") { this.invoke(!_type, chrmId, offlineMsg); } }; Client.prototype.__init = function (f) { this.handler = new MessageHandler(this); //设置连接回调 this.handler.setConnectCallback(RongIMLib.RongIMClient._memoryStore.callback); this.channel = new Channel(f, this); }; Client.userInfoMapping = {}; return Client; })(); RongIMLib.Client = Client; //连接类,实现imclient与connect_client的连接 var Bridge = (function () { function Bridge() { } Bridge.getInstance = function () { return new Bridge(); }; //连接服务器 Bridge.prototype.connect = function (appKey, token, callback) { if (!RongIMLib.RongIMClient.Protobuf) { return; } Bridge._client = new RongIMLib.Navigation().connect(appKey, token, callback); return Bridge._client; }; Bridge.prototype.setListener = function () { Channel._ConnectionStatusListener = { onChanged: function (status) { RongIMLib.RongUtil.forEach(RongIMLib.RongIMClient.statusListeners, function (watch) { RongIMLib.RongUtil.isFunction(watch) && watch(status); }); } }; Channel._ReceiveMessageListener = { onReceived: function (msg, count, hasMore) { RongIMLib.RongUtil.forEach(RongIMLib.RongIMClient.messageListeners, function (watch) { RongIMLib.RongUtil.isFunction(watch) && watch(msg, count, hasMore); }); } }; }; Bridge.prototype.reconnect = function (callabck) { Bridge._client.channel.reconnect(callabck); }; Bridge.prototype.disconnect = function () { Bridge._client.channel.disconnect(2); }; //执行queryMessage请求 Bridge.prototype.queryMsg = function (topic, content, targetId, callback, pbname) { if (typeof topic != "string") { topic = _topic[topic]; } Bridge._client.queryMessage(topic, content, targetId, Qos.AT_MOST_ONCE, callback, pbname); }; //发送消息 执行publishMessage 请求 Bridge.prototype.pubMsg = function (topic, content, targetId, callback, msg, methodType) { if (typeof methodType == 'number') { if (methodType == RongIMLib.MethodType.CUSTOMER_SERVICE) { Bridge._client.publishMessage("pcuMsgP", content, targetId, callback, msg); } else if (methodType == RongIMLib.MethodType.RECALL) { Bridge._client.publishMessage("recallMsg", content, targetId, callback, msg); } } else { Bridge._client.publishMessage(_topic[10][topic], content, targetId, callback, msg); } }; return Bridge; })(); RongIMLib.Bridge = Bridge; var MessageHandler = (function () { function MessageHandler(client) { this.map = {}; this.connectCallback = null; if (!Channel._ReceiveMessageListener) { throw new Error("please set onReceiveMessageListener"); } this._onReceived = Channel._ReceiveMessageListener.onReceived; this._client = client; this.syncMsgMap = new Object; } //把对象推入回调对象队列中,并启动定时器 MessageHandler.prototype.putCallback = function (callbackObj, _publishMessageId, _msg) { var item = { Callback: callbackObj, Message: _msg }; item.Callback.resumeTimer(); this.map[_publishMessageId] = item; }; //设置连接回调对象,启动定时器 MessageHandler.prototype.setConnectCallback = function (_connectCallback) { if (_connectCallback) { this.connectCallback = new RongIMLib.ConnectAck(_connectCallback.onSuccess, _connectCallback.onError, this._client); } }; MessageHandler.prototype.handleChrmKVPullMsg = function (msg) { try { var pbtype = 'ChrmNotifyMsg'; var data = RongIMLib.CallbackMapping.getInstance().mapping(RongIMLib.RongIMClient.Protobuf[pbtype].decode(msg.data), pbtype); if (data.type === 2) { var timestamp = RongIMLib.MessageUtil.int64ToTimestamp(data.time); RongIMLib.ChrmKVHandler.pull(data.chrmId, timestamp); } } catch (e) { } }; MessageHandler.prototype.onReceived = function (msg, pubAckItem, offlineMsg, leftCount, isSync) { //实体对象 var entity, //解析完成的消息对象 message, //会话对象 con, // 是否为直发消息 isStraightMsg = false; if (msg._name != "PublishMessage") { entity = msg; RongIMLib.RongIMClient._storageProvider.setItem(this._client.userId, RongIMLib.MessageUtil.int64ToTimestamp(entity.dataTime)); } else { if (msg.getTopic() == "s_ntf") { entity = RongIMLib.RongIMClient.Protobuf.NotifyMsg.decode(msg.getData()); this._client.syncTime(entity.type, RongIMLib.MessageUtil.int64ToTimestamp(entity.time), entity.chrmId); return; } else if (msg.getTopic() == "s_msg") { isStraightMsg = true; entity = RongIMLib.RongIMClient.Protobuf.DownStreamMessage.decode(msg.getData()); var timestamp = RongIMLib.MessageUtil.int64ToTimestamp(entity.dataTime); RongIMLib.RongIMClient._storageProvider.setItem(this._client.userId, timestamp); RongIMLib.RongIMClient._memoryStore.lastReadTime.get(this._client.userId, timestamp); } else if (msg.getTopic() == "s_stat") { entity = RongIMLib.RongIMClient.Protobuf.GetUserStatusOutput.decode(msg.getData()); entity = RongIMLib.RongInnerTools.convertUserStatus(entity); RongIMLib.RongIMClient.userStatusObserver.notify({ key: entity.userId, entity: entity }); return; } else if (msg.getTopic() === 's_cmd') { this.handleChrmKVPullMsg(msg); return; } else { if (Bridge._client.sdkVer && Bridge._client.sdkVer == "1.0.0") { return; } entity = RongIMLib.RongIMClient.Protobuf.UpStreamMessage.decode(msg.getData()); var tmpTopic = msg.getTopic(); var tmpType = tmpTopic.substr(0, 2); if (tmpType == "pp") { entity.type = 1; } else if (tmpType == "pd") { entity.type = 2; } else if (tmpType == "pg") { entity.type = 3; } else if (tmpType == "ch") { entity.type = 4; } else if (tmpType == "pc") { entity.type = 5; } //复用字段,targetId 以此为准 entity.groupId = msg.getTargetId(); entity.fromUserId = this._client.userId; entity.dataTime = Date.parse(new Date().toString()); } if (!entity) { return; } } var isPullFinished = RongIMLib.RongIMClient._memoryStore.isPullFinished; // PullMsg 没有拉取完成,抛弃所有直发在线消息,抛弃的消息会在 PullMsg 中返回 if (!isPullFinished && !offlineMsg && isStraightMsg) { return; } //解析实体对象为消息对象。 message = RongIMLib.MessageUtil.messageParser(entity, this._onReceived, offlineMsg); var isRTCMessage = message.conversationType == 12; if (isRTCMessage) { RongIMLib.RongIMClient.RTCListener(message); RongIMLib.RongIMClient.RTCInnerListener(message); RongIMLib.RongIMClient.RTCSignalLisener(message); return; } var isRecall = (msg.getTopic && msg.getTopic() == "recallMsg"); if (isRecall) { var content = message.content; message.conversationType = content.conversationType; message.targetId = content.targetId; message.messageId = null; } if (pubAckItem) { message.messageUId = pubAckItem.getMessageUId(); message.sentTime = pubAckItem.getTimestamp(); RongIMLib.RongIMClient._storageProvider.setItem(this._client.userId, message.sentTime); } if (message === null) { return; } var isChatroomMessage = message.conversationType == RongIMLib.ConversationType.CHATROOM; if (!isChatroomMessage) { var msgTag = RongIMLib.RongIMClient.MessageParams[message.messageType].msgTag.getMessageTag(); if (msgTag >= 0) { RongIMLib.SyncTimeUtil.set(message); } var isSend = (message.messageDirection == RongIMLib.MessageDirection.SEND); if (isSend) { var storageProvider = RongIMLib.RongIMClient._storageProvider; var userId = RongIMLib.Bridge._client.userId; var lastSentTime = storageProvider.getItem('last_sentTime_' + userId) || 0; if (message.sentTime <= lastSentTime && !isSync) { return; } } } // 设置会话时间戳并且判断是否传递 message 发送消息未处理会话时间戳 // key:'converST_' + 当前用户 + conversationType + targetId // RongIMClient._storageProvider.setItem('converST_' + Bridge._client.userId + message.conversationType + message.targetId, message.sentTime); // var isPersited = (RongIMClient.MessageParams[message.messageType].msgTag.getMessageTag() > 0); var msgTag = RongIMLib.RongIMClient.MessageParams[message.messageType].msgTag.getMessageTag(); var isPersited = msgTag === 3 || msgTag === 2; if (isPersited) { con = RongIMLib.RongIMClient._dataAccessProvider.getConversation(message.conversationType, message.targetId, { onSuccess: function () { }, onError: function () { } }); if (!con) { con = RongIMLib.RongIMClient.getInstance().createConversation(message.conversationType, message.targetId, ""); } if (message.messageDirection == RongIMLib.MessageDirection.RECEIVE && (entity.status & 64) == 64) { var mentioneds = RongIMLib.RongIMClient._storageProvider.getItem("mentioneds_" + Bridge._client.userId + '_' + message.conversationType + '_' + message.targetId); var key = message.conversationType + '_' + message.targetId, info = {}; if (message.content && message.content.mentionedInfo) { info[key] = { uid: message.messageUId, time: message.sentTime, mentionedInfo: message.content.mentionedInfo }; RongIMLib.RongIMClient._storageProvider.setItem("mentioneds_" + Bridge._client.userId + '_' + message.conversationType + '_' + message.targetId, JSON.stringify(info)); mentioneds = JSON.stringify(info); } if (mentioneds) { var info = JSON.parse(mentioneds); con.mentionedMsg = info[key]; } } var isReceiver = message.messageDirection == RongIMLib.MessageDirection.RECEIVE; if (isReceiver && message.senderUserId != Bridge._client.userId) { con.unreadMessageCount = con.unreadMessageCount + 1; if (RongIMLib.RongUtil.supportLocalStorage()) { // var originUnreadCount = RongIMClient._storageProvider.getItem("cu" + Bridge._client.userId + con.conversationType + con.targetId); // 与本地存储会话合并 // var newUnreadCount = Number(originUnreadCount) + 1; // RongIMClient._storageProvider.setItem("cu" + Bridge._client.userId + con.conversationType + message.targetId, newUnreadCount); var newUnreadCount = RongIMLib.UnreadCountHandler.add(con.conversationType, message.targetId, 1, message.sentTime); con.unreadMessageCount = newUnreadCount; } } var receivedTime = new Date().getTime(); con.receivedTime = RongIMLib.MessageUtil.getCheckedTime(receivedTime); con.receivedStatus = message.receivedStatus; con.senderUserId = message.sendUserId; con.notificationStatus = RongIMLib.ConversationNotificationStatus.DO_NOT_DISTURB; con.latestMessageId = message.messageId; con.latestMessage = message; con.sentTime = message.sentTime; RongIMLib.RongIMClient._dataAccessProvider.addConversation(con, { onSuccess: function (data) { if (!offlineMsg) { var Conversation_1 = RongIMLib.RongIMClient._dataAccessProvider.Conversation; var conversationList = RongIMLib.RongIMClient._memoryStore.conversationList; Conversation_1._notify(conversationList); } }, onError: function () { } }); } if (message.conversationType == RongIMLib.ConversationType.CUSTOMER_SERVICE && (message.messageType == "ChangeModeResponseMessage" || message.messageType == "SuspendMessage" || message.messageType == "HandShakeResponseMessage" || message.messageType == "TerminateMessage" || message.messageType == "CustomerStatusUpdateMessage" || message.messageType == "TextMessage" || message.messageType == "InformationNotificationMessage")) { if (!RongIMLib.RongIMClient._memoryStore.custStore["isInit"]) { return; } } if (message.conversationType == RongIMLib.ConversationType.CUSTOMER_SERVICE && message.messageType != "HandShakeResponseMessage") { if (!RongIMLib.RongIMClient._memoryStore.custStore[message.targetId]) { return; } if (message.messageType == "TerminateMessage") { if (RongIMLib.RongIMClient._memoryStore.custStore[message.targetId].sid != message.content.sid) { return; } } } if (message.messageType === RongIMLib.RongIMClient.MessageType["HandShakeResponseMessage"]) { var session = message.content.data; RongIMLib.RongIMClient._memoryStore.custStore[message.targetId] = session; if (session.serviceType == RongIMLib.CustomerType.ONLY_HUMAN || session.serviceType == RongIMLib.CustomerType.HUMAN_FIRST) { if (session.notAutoCha == "1") { RongIMLib.RongIMClient.getInstance().switchToHumanMode(message.targetId, { onSuccess: function () { }, onError: function () { } }); } } } var d = new Date(), m = d.getMonth() + 1, date = d.getFullYear() + '/' + (m.toString().length == 1 ? '0' + m : m) + '/' + d.getDate(); //new Date(date).getTime() - message.sentTime < 1 逻辑判断 超过 1 天未收的 ReadReceiptRequestMessage 离线消息自动忽略。 var dealtime = new Date(date).getTime() - message.sentTime < 0; if (RongIMLib.RongUtil.supportLocalStorage() && message.messageType === RongIMLib.RongIMClient.MessageType["ReadReceiptRequestMessage"] && dealtime && message.messageDirection == RongIMLib.MessageDirection.SEND) { var sentkey = Bridge._client.userId + message.content.messageUId + "SENT"; RongIMLib.RongIMClient._storageProvider.setItem(sentkey, JSON.stringify({ count: 0, dealtime: message.sentTime, userIds: {} })); } else if (RongIMLib.RongUtil.supportLocalStorage() && message.messageType === RongIMLib.RongIMClient.MessageType["ReadReceiptRequestMessage"] && dealtime) { var reckey = Bridge._client.userId + message.conversationType + message.targetId + 'RECEIVED', recData = JSON.parse(RongIMLib.RongIMClient._storageProvider.getItem(reckey)); if (recData) { if (message.senderUserId in recData) { if (recData[message.senderUserId].uIds && recData[message.senderUserId].uIds && recData[message.senderUserId].uIds.indexOf(message.content.messageUId) == -1) { recData[message.senderUserId].uIds.push(message.content.messageUId); recData[message.senderUserId].dealtime = message.sentTime; recData[message.senderUserId].isResponse = false; RongIMLib.RongIMClient._storageProvider.setItem(reckey, JSON.stringify(recData)); } else { return; } } else { var objSon = { uIds: [message.content.messageUId], dealtime: message.sentTime, isResponse: false }; recData[message.senderUserId] = objSon; RongIMLib.RongIMClient._storageProvider.setItem(reckey, JSON.stringify(recData)); } } else { var obj = {}; obj[message.senderUserId] = { uIds: [message.content.messageUId], dealtime: message.sentTime, isResponse: false }; RongIMLib.RongIMClient._storageProvider.setItem(reckey, JSON.stringify(obj)); } } if (RongIMLib.RongUtil.supportLocalStorage() && message.messageType === RongIMLib.RongIMClient.MessageType["ReadReceiptResponseMessage"] && dealtime) { var receiptResponseMsg = message.content, uIds = receiptResponseMsg.receiptMessageDic[Bridge._client.userId], sentkey = "", sentObj; message.receiptResponse || (message.receiptResponse = {}); if (uIds) { var cbuIds = []; for (var i = 0, len = uIds.length; i < len; i++) { sentkey = Bridge._client.userId + uIds[i] + "SENT"; sentObj = JSON.parse(RongIMLib.RongIMClient._storageProvider.getItem(sentkey)); if (sentObj && !(message.senderUserId in sentObj.userIds)) { cbuIds.push(uIds[i]); sentObj.count += 1; sentObj.userIds[message.senderUserId] = message.sentTime; message.receiptResponse[uIds[i]] = sentObj.count; RongIMLib.RongIMClient._storageProvider.setItem(sentkey, JSON.stringify(sentObj)); } } receiptResponseMsg.receiptMessageDic[Bridge._client.userId] = cbuIds; message.content = receiptResponseMsg; } } var that = this; if (RongIMLib.RongIMClient._voipProvider && ['AcceptMessage', 'RingingMessage', 'HungupMessage', 'InviteMessage', 'MediaModifyMessage', 'MemberModifyMessage'].indexOf(message.messageType) > -1) { setTimeout(function () { RongIMLib.RongIMClient._voipProvider.onReceived(message); }); } else { var count = leftCount || 0; var hasMore = !isPullFinished; that._onReceived(message, count, hasMore); } }; MessageHandler.prototype.handleMessage = function (msg) { if (!msg) { return; } if (msg && RongIMLib.RongUtil.isObject(msg) && msg.timestamp) { RongIMLib.MessageUtil.setDeltaTime(msg.timestamp); } switch (msg._name) { case "ConnAckMessage": Bridge._client.handler.connectCallback.process(msg.getStatus(), msg.getUserId(), msg.getTimestamp()); break; case "PublishMessage": if (!msg.getSyncMsg() && msg.getQos() != 0) { Bridge._client.channel.writeAndFlush(new RongIMLib.PubAckMessage(msg.getMessageId())); } // TODO && -> if (msg.getSyncMsg() && !RongIMLib.RongIMClient._memoryStore.depend.isPolling) { Bridge._client.handler.syncMsgMap[msg.getMessageId()] = msg; } else { //如果是PublishMessage就把该对象给onReceived方法执行处理 Bridge._client.handler.onReceived(msg); } break; case "QueryAckMessage": if (msg.getQos() != 0) { Bridge._client.channel.writeAndFlush(new RongIMLib.QueryConMessage(msg.getMessageId())); } var temp = Bridge._client.handler.map[msg.getMessageId()]; if (temp) { //执行回调操作 temp.Callback.process(msg.getStatus(), msg.getData(), msg.getDate(), temp.Message); delete Bridge._client.handler.map[msg.getMessageId()]; } break; case "PubAckMessage": var item = Bridge._client.handler.map[msg.getMessageId()]; if (item) { item.Callback.process(msg.getStatus() || 0, msg.getMessageUId(), msg.getTimestamp(), item.Message, msg.getMessageId()); delete Bridge._client.handler.map[msg.getMessageId()]; } else { var userId = RongIMLib.Bridge._client.userId; RongIMLib.RongIMClient._storageProvider.setItem('last_sentTime_' + userId, msg.timestamp); Bridge._client.handler.onReceived(Bridge._client.handler.syncMsgMap[msg.messageId], msg, null, null, true); delete Bridge._client.handler.syncMsgMap[msg.getMessageId()]; } break; case "PingRespMessage": if (RongIMLib.RongIMClient._memoryStore.isFirstPingMsg) { RongIMLib.RongIMClient._memoryStore.isFirstPingMsg = false; } else { Bridge._client.pauseTimer(); } break; case "DisconnectMessage": Bridge._client.channel.disconnect(msg.getStatus()); break; default: } }; return MessageHandler; })(); RongIMLib.MessageHandler = MessageHandler; })(RongIMLib || (RongIMLib = {})); var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; /// var RongIMLib; (function (RongIMLib) { var MessageCallback = (function () { function MessageCallback(error) { this.timeout = null; this.onError = null; if (error && typeof error == "number") { this.timeoutMillis = error; } else { this.timeoutMillis = 30000; this.onError = error; } } MessageCallback.prototype.resumeTimer = function () { var me = this; if (this.timeoutMillis > 0 && !this.timeout) { this.timeout = setTimeout(function () { me.readTimeOut(true); }, this.timeoutMillis); } }; MessageCallback.prototype.pauseTimer = function () { if (this.timeout) { clearTimeout(this.timeout); this.timeout = null; } }; MessageCallback.prototype.readTimeOut = function (isTimeout) { if (isTimeout && this.onError) { this.onError(RongIMLib.ErrorCode.TIMEOUT); } else { this.pauseTimer(); } }; return MessageCallback; })(); RongIMLib.MessageCallback = MessageCallback; var CallbackMapping = (function () { function CallbackMapping() { this.publicServiceList = []; } CallbackMapping.getInstance = function () { return new CallbackMapping(); }; CallbackMapping.prototype.pottingProfile = function (item) { var temp; this.profile = new RongIMLib.PublicServiceProfile(); temp = JSON.parse(item.extra); this.profile.isGlobal = temp.isGlobal; this.profile.introduction = temp.introduction; this.profile.menu = temp.menu; this.profile.hasFollowed = temp.follow; this.profile.publicServiceId = item.mpid; this.profile.name = item.name; this.profile.portraitUri = item.portraitUrl; this.profile.conversationType = item.type == "mc" ? RongIMLib.ConversationType.APP_PUBLIC_SERVICE : RongIMLib.ConversationType.PUBLIC_SERVICE; this.publicServiceList.push(this.profile); }; CallbackMapping.prototype.mapping = function (entity, tag) { switch (tag) { case "GetUserInfoOutput": var userInfo = new RongIMLib.UserInfo(entity.userId, entity.userName, entity.userPortrait); return userInfo; case "GetQNupTokenOutput": return { deadline: RongIMLib.MessageUtil.int64ToTimestamp(entity.deadline), token: entity.token }; case "GetQNdownloadUrlOutput": return { downloadUrl: entity.downloadUrl }; case "CreateDiscussionOutput": return entity.id; case "ChannelInfoOutput": var disInfo = new RongIMLib.Discussion(); disInfo.creatorId = entity.adminUserId; disInfo.id = entity.channelId; disInfo.memberIdList = entity.firstTenUserIds; disInfo.name = entity.channelName; disInfo.isOpen = entity.openStatus; return disInfo; case "GroupHashOutput": return entity.result; case "QueryBlackListOutput": return entity.userIds; case "SearchMpOutput": case "PullMpOutput": if (entity.info) { var self = this; Array.forEach(entity.info, function (item) { setTimeout(function () { self.pottingProfile(item); }, 100); }); } return this.publicServiceList; default: return entity; } }; return CallbackMapping; })(); RongIMLib.CallbackMapping = CallbackMapping; var PublishCallback = (function (_super) { __extends(PublishCallback, _super); function PublishCallback(_cb, _timeout) { _super.call(this, _timeout); this._cb = _cb; this._timeout = _timeout; } PublishCallback.prototype.process = function (_status, messageUId, timestamp, _msg, messageId) { this.readTimeOut(); if (_status == 0) { if (_msg) { _msg.setSentStatus = _status; } var isPullFinished = RongIMLib.RongIMClient._memoryStore.isPullFinished; if (isPullFinished) { var userId = RongIMLib.Bridge._client.userId; var stroageProvider = RongIMLib.RongIMClient._storageProvider; stroageProvider.setItem('last_sentTime_' + userId, timestamp); RongIMLib.SyncTimeUtil.set({ messageDirection: RongIMLib.MessageDirection.SEND, sentTime: timestamp }); } this._cb({ messageUId: messageUId, timestamp: timestamp, messageId: messageId }); } else { this._timeout(_status, { messageUId: messageUId, sentTime: timestamp }); } }; PublishCallback.prototype.readTimeOut = function (x) { MessageCallback.prototype.readTimeOut.call(this, x); }; return PublishCallback; })(MessageCallback); RongIMLib.PublishCallback = PublishCallback; var QueryCallback = (function (_super) { __extends(QueryCallback, _super); function QueryCallback(_cb, _timeout) { _super.call(this, _timeout); this._cb = _cb; this._timeout = _timeout; } QueryCallback.prototype.process = function (status, data, serverTime, pbtype) { this.readTimeOut(); if (pbtype && data && status == 0) { try { data = CallbackMapping.getInstance().mapping(RongIMLib.RongIMClient.Protobuf[pbtype].decode(data), pbtype); } catch (e) { this._timeout(RongIMLib.ErrorCode.UNKNOWN); return; } if ("GetUserInfoOutput" == pbtype) { //pb类型为GetUserInfoOutput的话就把data放入userinfo缓存队列 RongIMLib.Client.userInfoMapping[data.userId] = data; } this._cb(data); } else { status > 0 ? this._timeout(status) : this._cb(status); } }; QueryCallback.prototype.readTimeOut = function (x) { MessageCallback.prototype.readTimeOut.call(this, x); }; return QueryCallback; })(MessageCallback); RongIMLib.QueryCallback = QueryCallback; var ConnectAck = (function (_super) { __extends(ConnectAck, _super); function ConnectAck(_cb, _timeout, client) { _super.call(this, _timeout); this._client = client; this._cb = _cb; this._timeout = _timeout; } ConnectAck.prototype.process = function (status, userId, timestamp) { this.readTimeOut(); if (status == 0) { this._client.userId = userId; var self = this; if (!RongIMLib.RongIMClient._memoryStore.depend.isPolling && RongIMLib.RongIMClient._memoryStore.isFirstPingMsg) { RongIMLib.Bridge._client.checkSocket({ onSuccess: function () { if (!RongIMLib.RongIMClient.isNotPullMsg) { self._client.syncTime(undefined, undefined, undefined, true); } }, onError: function () { RongIMLib.RongIMClient._memoryStore.isFirstPingMsg = false; RongIMLib.RongIMClient.getInstance().disconnect(); RongIMLib.RongIMClient.connect(RongIMLib.RongIMClient._memoryStore.token, RongIMLib.RongIMClient._memoryStore.callback); } }); } else { if (!RongIMLib.RongIMClient.isNotPullMsg) { self._client.syncTime(undefined, undefined, undefined, true); } } RongIMLib.Bridge._client.channel.socket.fire("StatusChanged", 0); if (this._client.reconnectObj.onSuccess) { this._client.reconnectObj.onSuccess(userId); delete this._client.reconnectObj.onSuccess; } else { var me = this; me._cb(userId); // setTimeout(function() { me._cb(userId); }, 500); var depend = RongIMLib.RongIMClient._memoryStore.depend; var maxConversationCount = depend.maxConversationCount; var isNotifyConversationList = depend.isNotifyConversationList; isNotifyConversationList && RongIMLib.RongIMClient._dataAccessProvider.getRemoteConversationList({ onSuccess: function (conversationList) { var Conversation = RongIMLib.RongIMClient._dataAccessProvider.Conversation; Conversation._notify(conversationList); }, onError: function (code) { console.log('内部获取列表失败: %d', code); } }, null, maxConversationCount); } RongIMLib.RongIMClient._memoryStore.connectAckTime = timestamp; RongIMLib.MessageUtil.setDeltaTime(timestamp); } else if (status == 6) { RongIMLib.RongIMClient.getInstance().disconnect(); //重定向 连错 CMP var me = this; var _client = me._client; var appId = _client.appId, token = _client.token; new RongIMLib.Navigation().requestNavi(token, appId, function () { _client.clearHeartbeat(); var newClient = new RongIMLib.Client(token, appId); RongIMLib.Bridge._client = newClient; newClient.__init(function () { RongIMLib.Transportations._TransportType == "websocket" && newClient.keepLive(); }); }, me._timeout, false); } else { RongIMLib.Bridge._client.channel.socket.socket._status = status; if (this._client.reconnectObj.onError) { this._client.reconnectObj.onError(status); delete this._client.reconnectObj.onError; } else { this._timeout(status); } } }; ConnectAck.prototype.readTimeOut = function (x) { MessageCallback.prototype.readTimeOut.call(this, x); }; return ConnectAck; })(MessageCallback); RongIMLib.ConnectAck = ConnectAck; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var Navigation = (function () { function Navigation() { } Navigation.clear = function () { var storage = RongIMLib.RongIMClient._storageProvider; storage.removeItem('rc_uid'); storage.removeItem('serverIndex'); storage.removeItem('rongSDK'); }; Navigation.prototype.getNaviSuccess = function (result) { var storage = RongIMLib.RongIMClient._storageProvider; storage.setItem('fullnavi', JSON.stringify(result)); var server = result.server; if (server) { server += ','; } var backupServer = result.backupServer || ''; var tpl = '{server}{backupServer}'; var servers = RongIMLib.RongUtil.tplEngine(tpl, { server: server, backupServer: backupServer }); servers = servers.split(','); storage.setItem('servers', JSON.stringify(servers)); var token = RongIMLib.RongIMClient._memoryStore.token; var uid = RongIMLib.InnerUtil.getUId(token); storage.setItem('rc_uid', uid); var userId = result.userId; storage.setItem('current_user', userId); if (result.voipCallInfo) { var callInfo = JSON.parse(result.voipCallInfo); RongIMLib.RongIMClient._memoryStore.voipStategy = callInfo.strategy; storage.setItem("voipStrategy", callInfo.strategy); } //替换本地存储的导航信息 var openMp = result.openMp; storage.setItem('openMp' + uid, openMp); RongIMLib.RongIMClient._memoryStore.depend.openMp = openMp; }; ; Navigation.prototype.connect = function (appId, token, callback) { var oldAppId = RongIMLib.RongIMClient._storageProvider.getItem("appId"); //如果appid和本地存储的不一样,清空所有本地存储数据 if (oldAppId && oldAppId != appId) { RongIMLib.RongIMClient._storageProvider.clearItem(); RongIMLib.RongIMClient._storageProvider.setItem("appId", appId); } if (!oldAppId) { RongIMLib.RongIMClient._storageProvider.setItem("appId", appId); } var client = new RongIMLib.Client(token, appId); this.requestNavi(token, appId, function () { client.connect(callback); }, callback.onError, true); return client; }; Navigation.prototype.requestNavi = function (token, appId, _onsuccess, _onerror, unignore) { if (unignore) { //根据token生成MD5截取8-16下标的数据与本地存储的导航信息进行比对 //如果信息和上次的通道类型都一样,不执行navi请求,用本地存储的导航信息连接服务器 var uId = md5(token).slice(8, 16); var storage = RongIMLib.RongIMClient._storageProvider; var transportType = storage.getItem("rongSDK"); var isSameType = (RongIMLib.Transportations._TransportType == transportType); var _old = storage.getItem('rc_uid'); var isSameUser = (_old == uId); var servers = storage.getItem('servers'); var hasServers = (typeof servers == 'string'); if (isSameUser && isSameType && hasServers && RongIMLib.RongUtil.hasValidWsUrl(servers)) { RongIMLib.RongIMClient._memoryStore.voipStategy = storage.getItem("voipStrategy"); var openMp = storage.getItem('openMp' + uId); RongIMLib.RongIMClient._memoryStore.depend.openMp = openMp; _onsuccess(); return; } } Navigation.clear(); RongIMLib.RongIMClient.invalidWsUrls = []; var context = this; var StatusEvent = RongIMLib.Channel._ConnectionStatusListener; var depend = RongIMLib.RongIMClient._memoryStore.depend; var navigaters = depend.navigaters; var naviTimeout = depend.naviTimeout; var maxNaviRetry = depend.maxNaviRetry; var isNaviJSONP = depend.isNaviJSONP; var isSupportRequestHeaders = RongIMLib.RongUtil.isSupportRequestHeaders(); var isRequestJSONP = !isSupportRequestHeaders || isNaviJSONP; var requestFunc = isRequestJSONP ? context.requestJSONP : context.request; var timer = new RongIMLib.Timer({ timeout: naviTimeout }); var internalRetry = 1; var isRange = function () { return internalRetry >= maxNaviRetry; }; var indexTools = new RongIMLib.IndexTools({ items: navigaters, onwheel: function () { internalRetry += 1; } }); var consume = function () { if (isRange()) { _onerror(RongIMLib.ConnectionStatus.RESPONSE_NAVI_ERROR); return; } var index = indexTools.get(); var navi = navigaters[index]; indexTools.add(); var success = function (result) { timer.pause(); StatusEvent.onChanged(RongIMLib.ConnectionStatus.RESPONSE_NAVI); var code = result.code; if (RongIMLib.RongUtil.isEqual(code, 200)) { context.getNaviSuccess(result); _onsuccess(); } if (RongIMLib.RongUtil.isEqual(code, 401)) { _onerror(RongIMLib.ConnectionState.TOKEN_INCORRECT); } if (RongIMLib.RongUtil.isEqual(code, 403)) { StatusEvent.onChanged(RongIMLib.ConnectionStatus.APPKEY_IS_FAKE); } }; var error = function (status) { if (RongIMLib.RongUtil.isEqual(status, 0)) { return; } timer.pause(); StatusEvent.onChanged(RongIMLib.ConnectionStatus.RESPONSE_NAVI_ERROR); consume(); }; StatusEvent.onChanged(RongIMLib.ConnectionStatus.REQUEST_NAVI); var xhr = requestFunc.call(context, navi, appId, token, success, error); timer.resume(function () { StatusEvent.onChanged(RongIMLib.ConnectionStatus.RESPONSE_NAVI_TIMEOUT); xhr.abort(); consume(); }); }; consume(); }; Navigation.prototype.getPath = function (navi, appId, token, callbackName) { var depend = RongIMLib.RongIMClient._memoryStore.depend; var path = (depend.isPolling ? 'cometnavi' : 'navi'); token = encodeURIComponent(token); var sdkver = RongIMLib.RongIMClient.sdkver; var random = RongIMLib.RongUtil.getTimestamp(); var tpl = '{navi}/{path}.js?appId={appId}&token={token}&callBack={callback}&v={sdkver}&r={random}'; var url = RongIMLib.RongUtil.tplEngine(tpl, { navi: navi, path: path, appId: appId, token: token, sdkver: sdkver, random: random, callback: callbackName }); return url; }; Navigation.prototype.request = function (navi, appId, token, success, error) { var url = this.getPath(navi, appId, token, 'getServerEndpoint'); return RongIMLib.RongUtil.request({ url: url, success: function (result) { result = result.replace('getServerEndpoint(', '').replace(');', ''); // 兼容私有云无分号 var lastIndex = result.lastIndexOf(')'); var maxIndex = result.length - 1; if (lastIndex == maxIndex) { result = result.substr(0, lastIndex); } success(JSON.parse(result)); }, error: function (status, result) { if (status == 401 || status == 403) { success(JSON.parse(result)); } else { error(status); } } }); }; Navigation.prototype.requestJSONP = function (navi, appId, token, success, error) { var callbackName = 'getServerEndpoint'; window.getServerEndpoint = function (result) { var code = result.code; if (code !== 200) { return error(RongIMLib.ConnectionState.TOKEN_INCORRECT); } success(result); }; var url = this.getPath(navi, appId, token, callbackName); var xss = document.createElement('script'); xss.src = url; document.body.appendChild(xss); xss.onerror = function () { error(RongIMLib.ConnectionState.TOKEN_INCORRECT); }; }; Navigation.Endpoint = new Object; return Navigation; })(); RongIMLib.Navigation = Navigation; })(RongIMLib || (RongIMLib = {})); // TODO: 统一变量、方法等命名规范 var RongIMLib; (function (RongIMLib) { /** * 消息基类 */ var BaseMessage = (function () { function BaseMessage(arg) { this._name = "BaseMessage"; this.lengthSize = 0; if (arg instanceof RongIMLib.Header) { this._header = arg; } else { this._header = new RongIMLib.Header(arg, false, RongIMLib.Qos.AT_MOST_ONCE, false); } } BaseMessage.prototype.read = function (In, length) { this.readMessage(In, length); }; BaseMessage.prototype.write = function (Out) { var binaryHelper = new RongIMLib.BinaryHelper(); var out = binaryHelper.convertStream(Out); this._headerCode = this.getHeaderFlag(); out.write(this._headerCode); this.writeMessage(out); return out; }; BaseMessage.prototype.getHeaderFlag = function () { return this._header.encode(); }; BaseMessage.prototype.getLengthSize = function () { return this.lengthSize; }; BaseMessage.prototype.toBytes = function () { return this.write([]).getBytesArray(); }; BaseMessage.prototype.isRetained = function () { return this._header.retain; }; BaseMessage.prototype.setRetained = function (retain) { this._header.retain = retain; }; BaseMessage.prototype.setQos = function (qos) { this._header.qos = Object.prototype.toString.call(qos) == "[object Object]" ? qos : RongIMLib.Qos[qos]; }; BaseMessage.prototype.setDup = function (dup) { this._header.dup = dup; }; BaseMessage.prototype.isDup = function () { return this._header.dup; }; BaseMessage.prototype.getType = function () { return this._header.type; }; BaseMessage.prototype.getQos = function () { return this._header.qos; }; BaseMessage.prototype.messageLength = function () { return 0; }; BaseMessage.prototype.writeMessage = function (out) { }; BaseMessage.prototype.readMessage = function (In, length) { }; BaseMessage.prototype.init = function (args) { var valName, nana, me = this; for (nana in args) { if (!args.hasOwnProperty(nana)) { continue; } valName = nana.replace(/^\w/, function (x) { var tt = x.charCodeAt(0); return "set" + (tt >= 0x61 ? String.fromCharCode(tt & ~32) : x); }); if (valName in me) { if (nana == "status") { me[valName](disconnectStatus[args[nana]] ? disconnectStatus[args[nana]] : args[nana]); } else { me[valName](args[nana]); } } } }; return BaseMessage; })(); RongIMLib.BaseMessage = BaseMessage; /** *连接消息类型 */ var ConnectMessage = (function (_super) { __extends(ConnectMessage, _super); function ConnectMessage(header) { _super.call(this, arguments.length == 0 || arguments.length == 3 ? RongIMLib.Type.CONNECT : arguments[0]); this._name = "ConnectMessage"; this.CONNECT_HEADER_SIZE = 12; this.protocolId = "RCloud"; this.binaryHelper = new RongIMLib.BinaryHelper(); this.protocolVersion = 3; switch (arguments.length) { case 0: case 1: case 3: if (!arguments[0] || arguments[0].length > 64) { throw new Error("ConnectMessage:Client Id cannot be null and must be at most 64 characters long: " + arguments[0]); } this.clientId = arguments[0]; this.cleanSession = arguments[1]; this.keepAlive = arguments[2]; break; } } ConnectMessage.prototype.messageLength = function () { var payloadSize = this.binaryHelper.toMQttString(this.clientId).length; payloadSize += this.binaryHelper.toMQttString(this.willTopic).length; payloadSize += this.binaryHelper.toMQttString(this.will).length; payloadSize += this.binaryHelper.toMQttString(this.appId).length; payloadSize += this.binaryHelper.toMQttString(this.token).length; return payloadSize + this.CONNECT_HEADER_SIZE; }; ConnectMessage.prototype.readMessage = function (stream) { this.protocolId = stream.readUTF(); this.protocolVersion = stream.readByte(); var cFlags = stream.readByte(); this.hasAppId = (cFlags & 128) > 0; this.hasToken = (cFlags & 64) > 0; this.retainWill = (cFlags & 32) > 0; this.willQos = cFlags >> 3 & 3; this.hasWill = (cFlags & 4) > 0; this.cleanSession = (cFlags & 32) > 0; this.keepAlive = stream.read() * 256 + stream.read(); this.clientId = stream.readUTF(); if (this.hasWill) { this.willTopic = stream.readUTF(); this.will = stream.readUTF(); } if (this.hasAppId) { try { this.appId = stream.readUTF(); } catch (ex) { throw new Error(ex); } } if (this.hasToken) { try { this.token = stream.readUTF(); } catch (ex) { throw new Error(ex); } } return stream; }; ConnectMessage.prototype.writeMessage = function (out) { var stream = this.binaryHelper.convertStream(out); stream.writeUTF(this.protocolId); stream.write(this.protocolVersion); var flags = this.cleanSession ? 2 : 0; flags |= this.hasWill ? 4 : 0; flags |= this.willQos ? this.willQos >> 3 : 0; flags |= this.retainWill ? 32 : 0; flags |= this.hasToken ? 64 : 0; flags |= this.hasAppId ? 128 : 0; stream.write(flags); stream.writeChar(this.keepAlive); stream.writeUTF(this.clientId); if (this.hasWill) { stream.writeUTF(this.willTopic); stream.writeUTF(this.will); } if (this.hasAppId) { stream.writeUTF(this.appId); } if (this.hasToken) { stream.writeUTF(this.token); } return stream; }; return ConnectMessage; })(BaseMessage); RongIMLib.ConnectMessage = ConnectMessage; /** *连接应答类型 */ var ConnAckMessage = (function (_super) { __extends(ConnAckMessage, _super); function ConnAckMessage(header) { _super.call(this, arguments.length == 0 ? RongIMLib.Type.CONNACK : arguments.length == 1 ? arguments[0] instanceof RongIMLib.Header ? arguments[0] : RongIMLib.Type.CONNACK : null); this._name = "ConnAckMessage"; this.MESSAGE_LENGTH = 2; this.binaryHelper = new RongIMLib.BinaryHelper(); var me = this; switch (arguments.length) { case 0: case 1: if (!(arguments[0] instanceof RongIMLib.Header)) { if (arguments[0] in RongIMLib.ConnectionState) { if (arguments[0] == null) { throw new Error("ConnAckMessage:The status of ConnAskMessage can't be null"); } me.setStatus(arguments[0]); } } break; } } ; ConnAckMessage.prototype.messageLength = function () { var length = this.MESSAGE_LENGTH; if (this.userId) { length += this.binaryHelper.toMQttString(this.userId).length; } return length; }; ; ConnAckMessage.prototype.readMessage = function (_in, msglength) { _in.read(); var result = +_in.read(); if (result >= 0 && result <= 12) { this.setStatus(result); } else { throw new Error("Unsupported CONNACK code:" + result); } if (msglength > this.MESSAGE_LENGTH) { this.setUserId(_in.readUTF()); var sessionId = _in.readUTF(); var timestamp = _in.readLong(); this.setTimestamp(timestamp); } }; ; ConnAckMessage.prototype.writeMessage = function (out) { var stream = this.binaryHelper.convertStream(out); stream.write(128); switch (+status) { case 0: case 1: case 2: case 5: case 6: stream.write(+status); break; case 3: case 4: stream.write(3); break; default: throw new Error("Unsupported CONNACK code:" + status); } if (this.userId) { stream.writeUTF(this.userId); } return stream; }; ; ConnAckMessage.prototype.setStatus = function (x) { this.status = x; }; ; ConnAckMessage.prototype.setUserId = function (_userId) { this.userId = _userId; }; ; ConnAckMessage.prototype.getStatus = function () { return this.status; }; ; ConnAckMessage.prototype.getUserId = function () { return this.userId; }; ; ConnAckMessage.prototype.setTimestamp = function (x) { this.timestrap = x; }; ; ConnAckMessage.prototype.getTimestamp = function () { return this.timestrap; }; return ConnAckMessage; })(BaseMessage); RongIMLib.ConnAckMessage = ConnAckMessage; /** *断开消息类型 */ var DisconnectMessage = (function (_super) { __extends(DisconnectMessage, _super); function DisconnectMessage(header) { _super.call(this, header instanceof RongIMLib.Header ? header : RongIMLib.Type.DISCONNECT); this._name = "DisconnectMessage"; this.MESSAGE_LENGTH = 2; this.binaryHelper = new RongIMLib.BinaryHelper(); if (!(header instanceof RongIMLib.Header)) { if (header in RongIMLib.ConnectionStatus) { this.status = header; } } } DisconnectMessage.prototype.messageLength = function () { return this.MESSAGE_LENGTH; }; DisconnectMessage.prototype.readMessage = function (_in) { _in.read(); var result = +_in.read(); if (result >= 0 && result <= 5) { this.setStatus(disconnectStatus[result] ? disconnectStatus[result] : result); } else { throw new Error("Unsupported CONNACK code:" + result); } }; DisconnectMessage.prototype.writeMessage = function (Out) { var out = this.binaryHelper.convertStream(Out); out.write(0); if (+status >= 1 && +status <= 3) { out.write((+status) - 1); } else { throw new Error("Unsupported CONNACK code:" + status); } }; DisconnectMessage.prototype.setStatus = function (x) { this.status = x; }; ; DisconnectMessage.prototype.getStatus = function () { return this.status; }; ; return DisconnectMessage; })(BaseMessage); RongIMLib.DisconnectMessage = DisconnectMessage; /** *请求消息信令 */ var PingReqMessage = (function (_super) { __extends(PingReqMessage, _super); function PingReqMessage(header) { _super.call(this, (header && header instanceof RongIMLib.Header) ? header : RongIMLib.Type.PINGREQ); this._name = "PingReqMessage"; } return PingReqMessage; })(BaseMessage); RongIMLib.PingReqMessage = PingReqMessage; /** *响应消息信令 */ var PingRespMessage = (function (_super) { __extends(PingRespMessage, _super); function PingRespMessage(header) { _super.call(this, (header && header instanceof RongIMLib.Header) ? header : RongIMLib.Type.PINGRESP); this._name = "PingRespMessage"; } return PingRespMessage; })(BaseMessage); RongIMLib.PingRespMessage = PingRespMessage; /** *封装MesssageId */ var RetryableMessage = (function (_super) { __extends(RetryableMessage, _super); function RetryableMessage(argu) { _super.call(this, argu); this._name = "RetryableMessage"; this.binaryHelper = new RongIMLib.BinaryHelper(); } RetryableMessage.prototype.messageLength = function () { return 2; }; RetryableMessage.prototype.writeMessage = function (Out) { var out = this.binaryHelper.convertStream(Out), Id = this.getMessageId(), lsb = Id & 255, msb = (Id & 65280) >> 8; out.write(msb); out.write(lsb); return out; }; RetryableMessage.prototype.readMessage = function (_in, msgLength) { var msgId = _in.read() * 256 + _in.read(); this.setMessageId(parseInt(msgId, 10)); }; RetryableMessage.prototype.setMessageId = function (_messageId) { this.messageId = _messageId; }; RetryableMessage.prototype.getMessageId = function () { return this.messageId; }; return RetryableMessage; })(BaseMessage); RongIMLib.RetryableMessage = RetryableMessage; /** *发送消息应答(双向) *qos为1必须给出应答(所有消息类型一样) */ var PubAckMessage = (function (_super) { __extends(PubAckMessage, _super); function PubAckMessage(header) { _super.call(this, (header instanceof RongIMLib.Header) ? header : RongIMLib.Type.PUBACK); this.msgLen = 2; this.date = 0; this.millisecond = 0; this.timestamp = 0; this.binaryHelper = new RongIMLib.BinaryHelper(); this._name = "PubAckMessage"; if (!(header instanceof RongIMLib.Header)) { _super.prototype.setMessageId.call(this, header); } } PubAckMessage.prototype.messageLength = function () { return this.msgLen; }; PubAckMessage.prototype.writeMessage = function (Out) { var out = this.binaryHelper.convertStream(Out); RetryableMessage.prototype.writeMessage.call(this, out); }; PubAckMessage.prototype.readMessage = function (_in, msgLength) { RetryableMessage.prototype.readMessage.call(this, _in); this.date = _in.readInt(); this.status = _in.read() * 256 + _in.read(); this.millisecond = _in.read() * 256 + _in.read(); this.timestamp = this.date * 1000 + this.millisecond; this.messageUId = _in.readUTF(); }; PubAckMessage.prototype.setStatus = function (x) { this.status = x; }; PubAckMessage.prototype.setTimestamp = function (timestamp) { this.timestamp = timestamp; }; PubAckMessage.prototype.setMessageUId = function (messageUId) { this.messageUId = messageUId; }; PubAckMessage.prototype.getStatus = function () { return this.status; }; PubAckMessage.prototype.getDate = function () { return this.date; }; PubAckMessage.prototype.getTimestamp = function () { return this.timestamp; }; PubAckMessage.prototype.getMessageUId = function () { return this.messageUId; }; return PubAckMessage; })(RetryableMessage); RongIMLib.PubAckMessage = PubAckMessage; /** *发布消息 */ var PublishMessage = (function (_super) { __extends(PublishMessage, _super); function PublishMessage(header, two, three) { _super.call(this, (arguments.length == 1 && header instanceof RongIMLib.Header) ? header : arguments.length == 3 ? RongIMLib.Type.PUBLISH : 0); this._name = "PublishMessage"; this.binaryHelper = new RongIMLib.BinaryHelper(); this.syncMsg = false; if (arguments.length == 3) { this.topic = header; this.targetId = three; this.data = typeof two == "string" ? this.binaryHelper.toMQttString(two) : two; } } PublishMessage.prototype.messageLength = function () { var length = 10; length += this.binaryHelper.toMQttString(this.topic).length; length += this.binaryHelper.toMQttString(this.targetId).length; length += this.data.length; return length; }; PublishMessage.prototype.writeMessage = function (Out) { var out = this.binaryHelper.convertStream(Out); out.writeUTF(this.topic); out.writeUTF(this.targetId); RetryableMessage.prototype.writeMessage.apply(this, arguments); out.write(this.data); }; ; PublishMessage.prototype.readMessage = function (_in, msgLength) { var pos = 6; this.date = _in.readInt(); this.topic = _in.readUTF(); pos += this.binaryHelper.toMQttString(this.topic).length; this.targetId = _in.readUTF(); pos += this.binaryHelper.toMQttString(this.targetId).length; RetryableMessage.prototype.readMessage.apply(this, arguments); this.data = new Array(msgLength - pos); this.data = _in.read(this.data); }; ; PublishMessage.prototype.setTopic = function (x) { this.topic = x; }; PublishMessage.prototype.setData = function (x) { this.data = x; }; PublishMessage.prototype.setTargetId = function (x) { this.targetId = x; }; PublishMessage.prototype.setDate = function (x) { this.date = x; }; PublishMessage.prototype.setSyncMsg = function (x) { this.syncMsg = x; }; //是否是其他端同步过来的消息 PublishMessage.prototype.getSyncMsg = function () { return this.syncMsg; }; PublishMessage.prototype.getTopic = function () { return this.topic; }; PublishMessage.prototype.getData = function () { return this.data; }; PublishMessage.prototype.getTargetId = function () { return this.targetId; }; PublishMessage.prototype.getDate = function () { return this.date; }; return PublishMessage; })(RetryableMessage); RongIMLib.PublishMessage = PublishMessage; /** *请求查询 */ var QueryMessage = (function (_super) { __extends(QueryMessage, _super); function QueryMessage(header, two, three) { _super.call(this, header instanceof RongIMLib.Header ? header : arguments.length == 3 ? RongIMLib.Type.QUERY : null); this.binaryHelper = new RongIMLib.BinaryHelper(); this._name = "QueryMessage"; if (arguments.length == 3) { this.data = typeof two == "string" ? this.binaryHelper.toMQttString(two) : two; this.topic = header; this.targetId = three; } } QueryMessage.prototype.messageLength = function () { var length = 0; length += this.binaryHelper.toMQttString(this.topic).length; length += this.binaryHelper.toMQttString(this.targetId).length; length += 2; length += this.data.length; return length; }; QueryMessage.prototype.writeMessage = function (Out) { var out = this.binaryHelper.convertStream(Out); out.writeUTF(this.topic); out.writeUTF(this.targetId); RetryableMessage.prototype.writeMessage.call(this, out); out.write(this.data); }; QueryMessage.prototype.readMessage = function (_in, msgLength) { var pos = 0; this.topic = _in.readUTF(); this.targetId = _in.readUTF(); pos += this.binaryHelper.toMQttString(this.topic).length; pos += this.binaryHelper.toMQttString(this.targetId).length; this.readMessage.apply(this, arguments); pos += 2; this.data = new Array(msgLength - pos); _in.read(this.data); }; QueryMessage.prototype.setTopic = function (x) { this.topic = x; }; QueryMessage.prototype.setData = function (x) { this.data = x; }; QueryMessage.prototype.setTargetId = function (x) { this.targetId = x; }; QueryMessage.prototype.getTopic = function () { return this.topic; }; QueryMessage.prototype.getData = function () { return this.data; }; QueryMessage.prototype.getTargetId = function () { return this.targetId; }; return QueryMessage; })(RetryableMessage); RongIMLib.QueryMessage = QueryMessage; /** *请求查询确认 */ var QueryConMessage = (function (_super) { __extends(QueryConMessage, _super); function QueryConMessage(messageId) { _super.call(this, (messageId instanceof RongIMLib.Header) ? messageId : RongIMLib.Type.QUERYCON); this._name = "QueryConMessage"; if (!(messageId instanceof RongIMLib.Header)) { _super.prototype.setMessageId.call(this, messageId); } } return QueryConMessage; })(RetryableMessage); RongIMLib.QueryConMessage = QueryConMessage; /** *请求查询应答 */ var QueryAckMessage = (function (_super) { __extends(QueryAckMessage, _super); function QueryAckMessage(header) { _super.call(this, header); this._name = "QueryAckMessage"; this.binaryHelper = new RongIMLib.BinaryHelper(); } QueryAckMessage.prototype.readMessage = function (In, msgLength) { RetryableMessage.prototype.readMessage.call(this, In); this.date = In.readInt(); this.setStatus(In.read() * 256 + In.read()); if (msgLength > 0) { this.data = new Array(msgLength - 8); this.data = In.read(this.data); } }; QueryAckMessage.prototype.getData = function () { return this.data; }; QueryAckMessage.prototype.getStatus = function () { return this.status; }; QueryAckMessage.prototype.getDate = function () { return this.date; }; QueryAckMessage.prototype.setDate = function (x) { this.date = x; }; QueryAckMessage.prototype.setStatus = function (x) { this.status = x; }; QueryAckMessage.prototype.setData = function (x) { this.data = x; }; return QueryAckMessage; })(RetryableMessage); RongIMLib.QueryAckMessage = QueryAckMessage; })(RongIMLib || (RongIMLib = {})); /// var RongIMLib; (function (RongIMLib) { /** * 把消息对象写入流中 * 发送消息时用到 */ var MessageOutputStream = (function () { function MessageOutputStream(_out) { var binaryHelper = new RongIMLib.BinaryHelper(); this.out = binaryHelper.convertStream(_out); } MessageOutputStream.prototype.writeMessage = function (msg) { if (msg instanceof RongIMLib.BaseMessage) { msg.write(this.out); } }; return MessageOutputStream; })(); RongIMLib.MessageOutputStream = MessageOutputStream; /** * 流转换为消息对象 * 服务器返回消息时用到 */ var MessageInputStream = (function () { function MessageInputStream(In, isPolling) { if (!isPolling) { var _in = new RongIMLib.BinaryHelper().convertStream(In); this.flags = _in.readByte(); this._in = _in; } else { this.flags = In["headerCode"]; } this.header = new RongIMLib.Header(this.flags); this.isPolling = isPolling; this.In = In; } MessageInputStream.prototype.readMessage = function () { switch (this.header.getType()) { case 1: this.msg = new RongIMLib.ConnectMessage(this.header); break; case 2: this.msg = new RongIMLib.ConnAckMessage(this.header); break; case 3: this.msg = new RongIMLib.PublishMessage(this.header); this.msg.setSyncMsg(this.header.getSyncMsg()); break; case 4: this.msg = new RongIMLib.PubAckMessage(this.header); break; case 5: this.msg = new RongIMLib.QueryMessage(this.header); break; case 6: this.msg = new RongIMLib.QueryAckMessage(this.header); break; case 7: this.msg = new RongIMLib.QueryConMessage(this.header); break; case 9: case 11: case 13: this.msg = new RongIMLib.PingRespMessage(this.header); break; case 8: case 10: case 12: this.msg = new RongIMLib.PingReqMessage(this.header); break; case 14: this.msg = new RongIMLib.DisconnectMessage(this.header); break; default: throw new Error("No support for deserializing " + this.header.getType() + " messages"); } if (this.isPolling) { this.msg.init(this.In); } else { this.msg.read(this._in, this.In.length - 1); } return this.msg; }; return MessageInputStream; })(); RongIMLib.MessageInputStream = MessageInputStream; var Header = (function () { function Header(_type, _retain, _qos, _dup) { this.retain = false; this.qos = RongIMLib.Qos.AT_LEAST_ONCE; this.dup = false; this.syncMsg = false; if (_type && +_type == _type && arguments.length == 1) { this.retain = (_type & 1) > 0; this.qos = (_type & 6) >> 1; this.dup = (_type & 8) > 0; this.type = (_type >> 4) & 15; this.syncMsg = (_type & 8) == 8; } else { this.type = _type; this.retain = _retain; this.qos = _qos; this.dup = _dup; } } Header.prototype.getSyncMsg = function () { return this.syncMsg; }; Header.prototype.getType = function () { return this.type; }; Header.prototype.encode = function () { var me = this; switch (this.qos) { case RongIMLib.Qos[0]: me.qos = RongIMLib.Qos.AT_MOST_ONCE; break; case RongIMLib.Qos[1]: me.qos = RongIMLib.Qos.AT_LEAST_ONCE; break; case RongIMLib.Qos[2]: me.qos = RongIMLib.Qos.EXACTLY_ONCE; break; case RongIMLib.Qos[3]: me.qos = RongIMLib.Qos.DEFAULT; break; } var _byte = (this.type << 4); _byte |= this.retain ? 1 : 0; _byte |= this.qos << 1; _byte |= this.dup ? 8 : 0; return _byte; }; Header.prototype.toString = function () { return "Header [type=" + this.type + ",retain=" + this.retain + ",qos=" + this.qos + ",dup=" + this.dup + "]"; }; return Header; })(); RongIMLib.Header = Header; /** * 二进制帮助对象 */ var BinaryHelper = (function () { function BinaryHelper() { } BinaryHelper.prototype.writeUTF = function (str, isGetBytes) { var back = [], byteSize = 0; for (var i = 0, len = str.length; i < len; i++) { var code = str.charCodeAt(i); if (code >= 0 && code <= 127) { byteSize += 1; back.push(code); } else if (code >= 128 && code <= 2047) { byteSize += 2; back.push((192 | (31 & (code >> 6)))); back.push((128 | (63 & code))); } else if (code >= 2048 && code <= 65535) { byteSize += 3; back.push((224 | (15 & (code >> 12)))); back.push((128 | (63 & (code >> 6)))); back.push((128 | (63 & code))); } } for (var i = 0, len = back.length; i < len; i++) { if (back[i] > 255) { back[i] &= 255; } } if (isGetBytes) { return back; } if (byteSize <= 255) { return [0, byteSize].concat(back); } else { return [byteSize >> 8, byteSize & 255].concat(back); } }; BinaryHelper.prototype.readUTF = function (arr) { if (Object.prototype.toString.call(arr) == "[object String]") { return arr; } var UTF = "", _arr = arr; for (var i = 0, len = _arr.length; i < len; i++) { if (_arr[i] < 0) { _arr[i] += 256; } ; var one = _arr[i].toString(2), v = one.match(/^1+?(?=0)/); if (v && one.length == 8) { var bytesLength = v[0].length, // store = _arr[i].toString(2).slice(7 - bytesLength); store = ''; for (var st = 0; st < bytesLength; st++) { store += _arr[st + i].toString(2).slice(2); } UTF += String.fromCharCode(parseInt(store, 2)); i += bytesLength - 1; } else { UTF += String.fromCharCode(_arr[i]); } } return UTF; }; /** * [convertStream 将参数x转化为RongIMStream对象] * @param {any} x [参数] */ BinaryHelper.prototype.convertStream = function (x) { if (x instanceof RongIMStream) { return x; } else { return new RongIMStream(x); } }; BinaryHelper.prototype.toMQttString = function (str) { return this.writeUTF(str); }; return BinaryHelper; })(); RongIMLib.BinaryHelper = BinaryHelper; var RongIMStream = (function () { function RongIMStream(arr) { //当前流执行的起始位置 this.position = 0; //当前流写入的多少字节 this.writen = 0; this.poolLen = 0; this.binaryHelper = new BinaryHelper(); this.pool = arr; this.poolLen = arr.length; } RongIMStream.prototype.check = function () { return this.position >= this.pool.length; }; RongIMStream.prototype.readInt = function () { if (this.check()) { return -1; } var end = ""; for (var i = 0; i < 4; i++) { var t = this.pool[this.position++].toString(16); if (t.length == 1) { t = "0" + t; } end += t.toString(16); } return parseInt(end, 16); }; RongIMStream.prototype.readLong = function () { if (this.check()) { return -1; } var end = ""; for (var i = 0; i < 8; i++) { var t = this.pool[this.position++].toString(16); if (t.length == 1) { t = "0" + t; } end += t; } return parseInt(end, 16); }; RongIMStream.prototype.readTimestamp = function () { if (this.check()) { return -1; } var end = ""; for (var i = 0; i < 8; i++) { end += this.pool[this.position++].toString(16); } end = end.substring(2, 8); return parseInt(end, 16); }; RongIMStream.prototype.readUTF = function () { if (this.check()) { return -1; } var big = (this.readByte() << 8) | this.readByte(); return this.binaryHelper.readUTF(this.pool.subarray(this.position, this.position += big)); }; RongIMStream.prototype.readByte = function () { if (this.check()) { return -1; } var val = this.pool[this.position++]; if (val > 255) { val &= 255; } return val; }; RongIMStream.prototype.read = function (bytesArray) { if (bytesArray) { return this.pool.subarray(this.position, this.poolLen); } else { return this.readByte(); } }; RongIMStream.prototype.write = function (_byte) { var b = _byte; if (Object.prototype.toString.call(b).toLowerCase() == "[object array]") { try { this.pool = this.pool.concat(b); } catch (e) { [].push.apply(this.pool, b); } } else { if (+b == b) { if (b > 255) { b &= 255; } this.pool.push(b); this.writen++; } } return b; }; RongIMStream.prototype.writeChar = function (v) { if (+v != v) { throw new Error("writeChar:arguments type is error"); } this.write(v >> 8 & 255); this.write(v & 255); this.writen += 2; }; RongIMStream.prototype.writeUTF = function (str) { var val = this.binaryHelper.writeUTF(str); [].push.apply(this.pool, val); this.writen += val.length; }; RongIMStream.prototype.toComplements = function () { var _tPool = this.pool; for (var i = 0; i < this.poolLen; i++) { if (_tPool[i] > 128) { _tPool[i] -= 256; } } return _tPool; }; RongIMStream.prototype.getBytesArray = function (isCom) { if (isCom) { return this.toComplements(); } return this.pool; }; return RongIMStream; })(); RongIMLib.RongIMStream = RongIMStream; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var SocketTransportation = (function () { /** * [constructor] * @param {string} url [连接地址:包含token、version] */ function SocketTransportation(_socket) { //连接状态 true:已连接 false:未连接 this.connected = false; //是否关闭: true:已关闭 false:未关闭 this.isClose = false; //存放消息队列的临时变量 this.queue = []; this.empty = new Function; this._socket = _socket; return this; } /** * [createTransport 创建WebScoket对象] */ SocketTransportation.prototype.createTransport = function (url, method) { if (!url) { throw new Error("URL can't be empty"); } ; this.url = url; var depend = RongIMLib.RongIMClient._memoryStore.depend; var wsScheme = depend.wsScheme; var tpl = '{wsScheme}{url}'; url = RongIMLib.RongUtil.tplEngine(tpl, { wsScheme: wsScheme, url: url }); this.socket = new WebSocket(url); this.socket.binaryType = "arraybuffer"; this.addEvent(); return this.socket; }; /** * [send 传送消息流] * @param {ArrayBuffer} data [二进制消息流] */ SocketTransportation.prototype.send = function (data) { if (!this.connected && !this.isClose) { //当通道不可用时,加入消息队列 this.queue.push(data); return; } if (this.isClose) { this._socket.fire("StatusChanged", RongIMLib.ConnectionStatus.CONNECTION_CLOSED); return; } var stream = new RongIMLib.RongIMStream([]), msg = new RongIMLib.MessageOutputStream(stream); msg.writeMessage(data); var val = stream.getBytesArray(true); var binary = new Int8Array(val); this.socket.send(binary.buffer); return this; }; /** * [onData 通道返回数据时调用的方法,用来想上层传递服务器返回的二进制消息流] * @param {ArrayBuffer} data [二进制消息流] */ SocketTransportation.prototype.onData = function (data) { if (RongIMLib.MessageUtil.isArray(data)) { this._socket.onMessage(new RongIMLib.MessageInputStream(data).readMessage()); } else { this._socket.onMessage(new RongIMLib.MessageInputStream(RongIMLib.MessageUtil.ArrayFormInput(data)).readMessage()); } return ""; }; /** * [onClose 通道关闭时触发的方法] */ SocketTransportation.prototype.onClose = function (ev) { var me = this; me.isClose = true; me.socket = this.empty; RongIMLib.Bridge._client.clearHeartbeat(); if (ev.code == 1006 && !this._status) { var currentTime = new Date().getTime(); if (currentTime - me.connectedTime <= SocketTransportation.MinConnectTime) { var host = RongIMLib.RongUtil.getUrlHost(me.url); RongIMLib.RongIMClient.invalidWsUrls.push(host); } me._socket.fire("StatusChanged", RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE); } else { me._status = 0; } }; /** * [onError 通道报错时触发的方法] * @param {any} error [抛出异常] */ SocketTransportation.prototype.onError = function (error) { this._socket.fire("StatusChanged", RongIMLib.ConnectionStatus.WEBSOCKET_ERROR); throw new Error(error); }; /** * [addEvent 为通道绑定事件] */ SocketTransportation.prototype.addEvent = function () { var self = this; self.socket.onopen = function () { self.connected = true; self.isClose = false; //通道可以用后,调用发送队列方法,把所有等得发送的消息发出 self.doQueue(); self._socket.fire("connect"); self.connectedTime = new Date().getTime(); }; self.socket.onmessage = function (ev) { //判断数据是不是字符串,如果是字符串那么就是flash传过来的。 if (typeof ev.data == "string") { self.onData(ev.data.split(",")); } else { self.onData(ev.data); } }; self.socket.onerror = function (ev) { self.onError(ev); }; self.socket.onclose = function (ev) { self.onClose(ev); }; }; /** * [doQueue 消息队列,把队列中消息发出] */ SocketTransportation.prototype.doQueue = function () { var self = this; for (var i = 0, len = self.queue.length; i < len; i++) { self.send(self.queue[i]); } }; /** * [disconnect 断开连接] */ SocketTransportation.prototype.disconnect = function (status) { var me = this; if (me.socket.readyState) { me.isClose = true; if (status) { me._status = status; } me.socket.close(); } }; /** * [reconnect 重新连接] */ SocketTransportation.prototype.reconnect = function () { this.disconnect(); this.createTransport(this.url); }; SocketTransportation.prototype.close = function () { this.socket.close(); }; // 最短链接时长(若 5000ms 内, ws 自动断开, 此 ws 地址置为不可用) SocketTransportation.MinConnectTime = 5000; return SocketTransportation; })(); RongIMLib.SocketTransportation = SocketTransportation; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var PollingTransportation = (function () { function PollingTransportation(socket) { this.empty = new Function; this.connected = false; this.pid = +new Date + Math.random() + ""; this.queue = []; this.socket = socket; return this; } PollingTransportation.prototype.createTransport = function (url, method) { if (!url) { throw new Error("Url is empty,Please check it!"); } ; this.url = url; var sid = RongIMLib.RongIMClient._storageProvider.getItem("sId" + RongIMLib.Navigation.Endpoint.userId), me = this; if (sid) { setTimeout(function () { me.onSuccess("{\"status\":0,\"userId\":\"" + RongIMLib.Navigation.Endpoint.userId + "\",\"headerCode\":32,\"messageId\":0,\"sessionid\":\"" + sid + "\"}"); me.connected = true; }, 500); return this; } this.getRequest(url, true); return this; }; PollingTransportation.prototype.requestFactory = function (url, method, multipart) { var reqest = this.XmlHttpRequest(); if (multipart) { reqest.multipart = true; } // reqest.timeout = 60000; reqest.open(method || "GET", RongIMLib.RongIMClient._memoryStore.depend.protocol + url); if (method == "POST" && "setRequestHeader" in reqest) { reqest.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=utf-8"); } return reqest; }; PollingTransportation.prototype.getRequest = function (url, isconnect) { var me = this; me.xhr = this.requestFactory(url + "&pid=" + encodeURIComponent(me.pid), "GET"); var timer = new RongIMLib.Timer({ timeout: 45000 }); if ("onload" in me.xhr) { me.xhr.onload = function () { timer.pause(); me.xhr.onload = me.empty; if (this.responseText == "lost params") { me.onError(); } else { me.onSuccess(this.responseText, isconnect); } }; me.xhr.onerror = function () { timer.pause(); me.disconnect(); }; } else { me.xhr.onreadystatechange = function () { timer.pause(); if (me.xhr.readyState == 4) { me.xhr.onreadystatechange = me.empty; if (/^(200|202)$/.test(me.xhr.status)) { me.onSuccess(me.xhr.responseText, isconnect); } else if (/^(400|403)$/.test(me.xhr.status)) { me.onError(); } else { me.disconnect(); } } }; } timer.resume(function () { me.onError(); }); me.xhr.send(); }; /** * [send 发送消息,Method:POST] * queue 为消息队列,待通道可用发送所有等待消息 * @param {string} data [需要传入comet格式数据,此处只负责通讯通道,数据转换在外层处理] */ PollingTransportation.prototype.send = function (data) { var me = this; var _send = me.sendxhr = this.requestFactory(RongIMLib.Navigation.Endpoint.host + "/websocket" + data.url + "&pid=" + encodeURIComponent(me.pid), "POST"); if ("onload" in _send) { _send.onload = function () { _send.onload = me.empty; me.onData(_send.responseText); }; _send.onerror = function () { _send.onerror = me.empty; }; } else { _send.onreadystatechange = function () { if (_send.readyState == 4) { this.onreadystatechange = this.empty; if (/^(202|200)$/.test(_send.status)) { me.onData(_send.responseText); } } }; } _send.send(JSON.stringify(data.data)); }; PollingTransportation.prototype.onData = function (data, header) { if (!data || data == "lost params") { return; } var self = this, val = JSON.parse(data); if (val.userId) { RongIMLib.Navigation.Endpoint.userId = val.userId; } if (header) { RongIMLib.RongIMClient._storageProvider.setItem("sId" + RongIMLib.Navigation.Endpoint.userId, header); } if (!RongIMLib.MessageUtil.isArray(val)) { val = [val]; } Array.forEach(val, function (m) { self.socket.fire("message", new RongIMLib.MessageInputStream(m, true).readMessage()); }); return ""; }; PollingTransportation.prototype.XmlHttpRequest = function () { var hasCORS = typeof XMLHttpRequest !== "undefined" && "withCredentials" in new XMLHttpRequest(), self = this; if ("undefined" != typeof XMLHttpRequest && hasCORS) { return new XMLHttpRequest(); } else if ("undefined" != typeof XDomainRequest) { return new XDomainRequest(); } else { return new ActiveXObject("Microsoft.XMLHTTP"); } }; PollingTransportation.prototype.onClose = function () { if (this.xhr) { if (this.xhr.onload) { this.xhr.onreadystatechange = this.xhr.onload = this.empty; } else { this.xhr.onreadystatechange = this.empty; } this.xhr.abort(); this.xhr = null; } if (this.sendxhr) { if (this.sendxhr.onload) { this.sendxhr.onreadystatechange = this.sendxhr.onload = this.empty; } else { this.sendxhr.onreadystatechange = this.empty; } this.sendxhr.abort(); this.sendxhr = null; } }; PollingTransportation.prototype.disconnect = function () { RongIMLib.RongIMClient._storageProvider.removeItem("sId" + RongIMLib.Navigation.Endpoint.userId); RongIMLib.RongIMClient._storageProvider.removeItem(RongIMLib.Navigation.Endpoint.userId + "msgId"); this.onClose(); }; PollingTransportation.prototype.reconnect = function () { this.disconnect(); this.createTransport(this.url); }; PollingTransportation.prototype.onSuccess = function (responseText, isconnect) { var txt = responseText.match(/"sessionid":"\S+?(?=")/); this.onData(responseText, txt ? txt[0].slice(13) : 0); if (/"headerCode":-32,/.test(responseText)) { RongIMLib.RongIMClient._storageProvider.removeItem("sId" + RongIMLib.Navigation.Endpoint.userId); RongIMLib.RongIMClient._storageProvider.removeItem(RongIMLib.Navigation.Endpoint.userId + "msgId"); return; } this.getRequest(RongIMLib.Navigation.Endpoint.host + "/pullmsg.js?sessionid=" + RongIMLib.RongIMClient._storageProvider.getItem("sId" + RongIMLib.Navigation.Endpoint.userId) + "×trap=" + encodeURIComponent(new Date().getTime() + Math.random() + "")); this.connected = true; isconnect && this.socket.fire("connect"); }; PollingTransportation.prototype.onError = function () { RongIMLib.RongIMClient._storageProvider.removeItem("sId" + RongIMLib.Navigation.Endpoint.userId); RongIMLib.RongIMClient._storageProvider.removeItem(RongIMLib.Navigation.Endpoint.userId + "msgId"); this.onClose(); if (this.connected) { this.connected = false; var code = RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE; this.socket.fire("disconnect", code); } }; PollingTransportation.prototype.close = function () { this.xhr.abort(); this.sendxhr = null; }; return PollingTransportation; })(); RongIMLib.PollingTransportation = PollingTransportation; })(RongIMLib || (RongIMLib = {})); //objectname映射 var typeMapping = { "RC:TxtMsg": "TextMessage", "RC:ImgMsg": "ImageMessage", "RC:VcMsg": "VoiceMessage", "RC:ImgTextMsg": "RichContentMessage", "RC:ReferenceMsg": "ReferenceMessage", "RC:FileMsg": "FileMessage", "RC:HQVCMsg": "HQVoiceMessage", "RC:LBSMsg": "LocationMessage", "RC:InfoNtf": "InformationNotificationMessage", "RC:ContactNtf": "ContactNotificationMessage", "RC:ProfileNtf": "ProfileNotificationMessage", "RC:CmdNtf": "CommandNotificationMessage", "RC:DizNtf": "DiscussionNotificationMessage", "RC:CmdMsg": "CommandMessage", "RC:TypSts": "TypingStatusMessage", "RC:CsChaR": "ChangeModeResponseMessage", "RC:CsHsR": "HandShakeResponseMessage", "RC:CsEnd": "TerminateMessage", "RC:CsSp": "SuspendMessage", "RC:CsUpdate": "CustomerStatusUpdateMessage", "RC:ReadNtf": "ReadReceiptMessage", "RC:VCAccept": "AcceptMessage", "RC:VCRinging": "RingingMessage", "RC:VCSummary": "SummaryMessage", "RC:VCHangup": "HungupMessage", "RC:VCInvite": "InviteMessage", "RC:VCModifyMedia": "MediaModifyMessage", "RC:VCModifyMem": "MemberModifyMessage", "RC:CsContact": "CustomerContact", "RC:PSImgTxtMsg": "PublicServiceRichContentMessage", "RC:PSMultiImgTxtMsg": "PublicServiceMultiRichContentMessage", "RC:GrpNtf": "GroupNotificationMessage", "RC:PSCmd": "PublicServiceCommandMessage", "RC:RcCmd": "RecallCommandMessage", "RC:SRSMsg": "SyncReadStatusMessage", "RC:RRReqMsg": "ReadReceiptRequestMessage", "RC:RRRspMsg": "ReadReceiptResponseMessage", "RCJrmf:RpMsg": "JrmfRedPacketMessage", "RCJrmf:RpOpendMsg": "JrmfRedPacketOpenedMessage", "RC:CombineMsg": "RCCombineMessage", "RC:chrmKVNotiMsg": "ChrmKVNotificationMessage" }, //自定义消息类型 registerMessageTypeMapping = {}, HistoryMsgType = { 4: "qryCMsg", 2: "qryDMsg", 3: "qryGMsg", 1: "qryPMsg", 6: "qrySMsg", 7: "qryPMsg", 8: "qryPMsg", 5: "qryCMsg" }, disconnectStatus = { 1: 6 }; var RongIMLib; (function (RongIMLib) { /** * 通道标识类 */ var Transportations = (function () { function Transportations() { } Transportations._TransportType = RongIMLib.Socket.WEBSOCKET; return Transportations; })(); RongIMLib.Transportations = Transportations; var SyncTimeUtil = (function () { function SyncTimeUtil() { } SyncTimeUtil.$getKey = function (message) { var client = RongIMLib.Bridge._client; var userId = client.userId; var direction = (message.messageDirection == 1 ? 'send' : 'receive'); var appkey = RongIMLib.RongIMClient._memoryStore.appKey; var tpl = '{appkey}_{userId}_{direction}box'; return RongIMLib.RongUtil.tplEngine(tpl, { appkey: appkey, userId: userId, direction: direction }); }; SyncTimeUtil.set = function (message) { var key = SyncTimeUtil.$getKey(message); var sentTime = message.sentTime; var storage = RongIMLib.RongIMClient._storageProvider; storage.setItem(key, sentTime); }; SyncTimeUtil.get = function () { var sent = SyncTimeUtil.$getKey({ messageDirection: RongIMLib.MessageDirection.SEND }); var received = SyncTimeUtil.$getKey({ messageDirection: RongIMLib.MessageDirection.RECEIVE }); var storage = RongIMLib.RongIMClient._storageProvider; return { sent: Number(storage.getItem(sent) || 0), received: Number(storage.getItem(received) || 0) }; }; return SyncTimeUtil; })(); RongIMLib.SyncTimeUtil = SyncTimeUtil; var MessageUtil = (function () { function MessageUtil() { } /** *4680000 为localstorage最小容量5200000字节的90%,超过90%将删除之前过早的存储 */ MessageUtil.checkStorageSize = function () { return JSON.stringify(localStorage).length < 4680000; }; MessageUtil.getFirstKey = function (obj) { var str = ""; for (var key in obj) { str = key; break; } return str; }; MessageUtil.isEmpty = function (obj) { var empty = true; for (var key in obj) { empty = false; break; } return empty; }; MessageUtil.ArrayForm = function (typearray) { if (Object.prototype.toString.call(typearray) == "[object ArrayBuffer]") { var arr = new Int8Array(typearray); return [].slice.call(arr); } return typearray; }; MessageUtil.ArrayFormInput = function (typearray) { if (Object.prototype.toString.call(typearray) == "[object ArrayBuffer]") { var arr = new Uint8Array(typearray); return arr; } return typearray; }; MessageUtil.indexOf = function (arr, item, from) { for (var l = arr.length, i = (from < 0) ? Math.max(0, +from) : from || 0; i < l; i++) { if (arr[i] == item) { return i; } } return -1; }; MessageUtil.isArray = function (obj) { return Object.prototype.toString.call(obj) == "[object Array]"; }; //遍历,只能遍历数组 MessageUtil.forEach = function (arr, func) { if ([].forEach) { return function (arr, func) { [].forEach.call(arr, func); }; } else { return function (arr, func) { for (var i = 0; i < arr.length; i++) { func.call(arr, arr[i], i, arr); } }; } }; MessageUtil.remove = function (array, func) { for (var i = 0, len = array.length; i < len; i++) { if (func(array[i])) { return array.splice(i, 1)[0]; } } return null; }; MessageUtil.int64ToTimestamp = function (obj, isDate) { if (obj.low === undefined) { return obj; } var low = obj.low; if (low < 0) { low += 0xffffffff + 1; } low = low.toString(16); var timestamp = parseInt(obj.high.toString(16) + "00000000".replace(new RegExp("0{" + low.length + "}$"), low), 16); if (isDate) { return new Date(timestamp); } return timestamp; }; //消息转换方法 MessageUtil.messageParser = function (entity, onReceived, offlineMsg) { var message = new RongIMLib.Message(), content = entity.content, de, objectName = entity.classname, val, isUseDef = false; try { if (RongIMLib.RongIMClient._memoryStore.depend.isPolling) { val = new RongIMLib.BinaryHelper().readUTF(content.offset ? MessageUtil.ArrayForm(content.buffer).slice(content.offset, content.limit) : content); de = JSON.parse(val); } else { val = new RongIMLib.BinaryHelper().readUTF(content.offset ? MessageUtil.ArrayFormInput(content.buffer).subarray(content.offset, content.limit) : content); de = JSON.parse(val); } } catch (ex) { de = val; isUseDef = true; } var IMLib = RongIMLib; //映射为具体消息对象 if (objectName in typeMapping) { var typeName = typeMapping[objectName]; message.content = new IMLib[typeName](de); message.messageType = typeMapping[objectName]; } else if (objectName in registerMessageTypeMapping) { var typeName = registerMessageTypeMapping[objectName]; var regMsg = new IMLib.RongIMClient.RegisterMessage[typeName](de); if (isUseDef) { message.content = regMsg.decode(de); } else { message.content = regMsg; } message.messageType = registerMessageTypeMapping[objectName]; } else { message.content = new RongIMLib.UnknownMessage({ content: de, objectName: objectName }); message.messageType = "UnknownMessage"; } //根据实体对象设置message对象] var dateTime = MessageUtil.int64ToTimestamp(entity.dataTime); if (dateTime > 0) { message.sentTime = dateTime; } else { message.sentTime = +new Date; } message.senderUserId = entity.fromUserId; message.conversationType = entity.type; if (entity.fromUserId == RongIMLib.Bridge._client.userId) { message.targetId = entity.groupId; } else { message.targetId = (/^[234]$/.test(entity.type || entity.getType()) ? entity.groupId : message.senderUserId); } var selfUserId = RongIMLib.Bridge._client.userId; // 解决多端在线收自己发的消息时, messageDirection 为 2(接收), 导致未读数增加 var isSelfSend = entity.direction == 1 || message.senderUserId === selfUserId; if (isSelfSend) { message.messageDirection = RongIMLib.MessageDirection.SEND; message.senderUserId = RongIMLib.Bridge._client.userId; } else { message.messageDirection = RongIMLib.MessageDirection.RECEIVE; } // 自己给自己发的消息, messageDirection 为 2(接收) var isSelfToSelf = message.senderUserId === selfUserId && message.targetId === selfUserId; if (isSelfToSelf) { message.messageDirection = RongIMLib.MessageDirection.RECEIVE; } var receivedTime = new Date().getTime(); message.messageUId = entity.msgId; message.receivedTime = RongIMLib.MessageUtil.getCheckedTime(receivedTime); message.messageId = (message.conversationType + "_" + ~~(Math.random() * 0xffffff)); message.objectName = objectName; message.receivedStatus = RongIMLib.ReceivedStatus.READ; if ((entity.status & 2) == 2) { message.receivedStatus = RongIMLib.ReceivedStatus.RETRIEVED; } message.offLineMessage = offlineMsg ? true : false; if (!offlineMsg) { if (RongIMLib.RongIMClient._memoryStore.connectAckTime > message.sentTime) { message.offLineMessage = true; } } return message; }; MessageUtil.detectCMP = function (options) { options.error = options.fail; return RongIMLib.RongUtil.request(options); }; MessageUtil.setDeltaTime = function (serverTime) { try { RongIMLib.RongIMClient._memoryStore.deltaTime = new Date().getTime() - serverTime; } catch (e) { } }; MessageUtil.getDeltaTime = function () { var _memoryStore = RongIMLib.RongIMClient._memoryStore || {}; return _memoryStore.deltaTime || 0; }; MessageUtil.getCheckedTime = function (time) { var deltaTime = MessageUtil.getDeltaTime(); return time - deltaTime; }; //适配SSL // static schemeArrs: Array = [["http", "ws"], ["https", "wss"]]; MessageUtil.sign = { converNum: 1, msgNum: 1, isMsgStart: true, isConvStart: true }; return MessageUtil; })(); RongIMLib.MessageUtil = MessageUtil; /** * 工具类 */ var MessageIdHandler = (function () { function MessageIdHandler() { } MessageIdHandler.init = function () { this.messageId = +(RongIMLib.RongIMClient._storageProvider.getItem(RongIMLib.Navigation.Endpoint.userId + "msgId") || RongIMLib.RongIMClient._storageProvider.setItem(RongIMLib.Navigation.Endpoint.userId + "msgId", 0) || 0); }; MessageIdHandler.messageIdPlus = function (method) { RongIMLib.RongIMClient._memoryStore.depend.isPolling && this.init(); if (this.messageId >= 65535) { this.messageId = 0; } this.messageId++; RongIMLib.RongIMClient._memoryStore.depend.isPolling && RongIMLib.RongIMClient._storageProvider.setItem(RongIMLib.Navigation.Endpoint.userId + "msgId", this.messageId); return this.messageId; }; MessageIdHandler.clearMessageId = function () { this.messageId = 0; RongIMLib.RongIMClient._memoryStore.depend.isPolling && RongIMLib.RongIMClient._storageProvider.setItem(RongIMLib.Navigation.Endpoint.userId + "msgId", this.messageId); }; MessageIdHandler.getMessageId = function () { RongIMLib.RongIMClient._memoryStore.depend.isPolling && this.init(); return this.messageId; }; MessageIdHandler.messageId = 0; return MessageIdHandler; })(); RongIMLib.MessageIdHandler = MessageIdHandler; var ChrmKVCaches = (function () { function ChrmKVCaches() { this.time = 0; this.cache = {}; } ChrmKVCaches.prototype.setTime = function (time) { this.time = time; }; ChrmKVCaches.prototype.getTime = function () { return this.time; }; ChrmKVCaches.prototype.setValue = function (kvContent) { var key = kvContent.key, timestamp = kvContent.timestamp; this.cache[key] = this.cache[key] || {}; this.cache[key] = { value: kvContent.value, userId: kvContent.userId, isDeleted: false, timestamp: timestamp }; }; ChrmKVCaches.prototype.removeValue = function (kvContent) { var key = kvContent.key, timestamp = kvContent.timestamp; this.cache[key] = this.cache[key] || {}; var cache = this.cache[key]; this.cache[key] = RongIMLib.RongUtil.extend(cache, { isDeleted: true, userId: kvContent.userId, timestamp: timestamp }); }; ChrmKVCaches.prototype.getValue = function (key) { this.cache[key] = this.cache[key] || {}; var cache = this.cache[key]; return cache.isDeleted ? null : cache.value; }; ChrmKVCaches.prototype.getAllKV = function () { var kv = {}; RongIMLib.RongUtil.forEach(this.cache, function (item, key) { if (!item.isDeleted) { kv[key] = item.value; } }); return kv; }; ChrmKVCaches.prototype.getSetUserId = function (key) { this.cache[key] = this.cache[key] || {}; return this.cache[key].userId; }; ChrmKVCaches.prototype.isKeyExisted = function (key) { this.cache[key] = this.cache[key] || {}; var cache = this.cache[key]; var hasValue = !RongIMLib.RongUtil.isEmpty(cache.value); return hasValue && !cache.isDeleted; }; ChrmKVCaches.prototype.clear = function () { this.cache = {}; }; return ChrmKVCaches; })(); var chrmKVCaches = {}; var chrmKVProsumerCaches = {}; var getKVCache = function (chrmId) { var chrmKVCache = chrmKVCaches[chrmId]; if (!chrmKVCache) { chrmKVCache = chrmKVCaches[chrmId] = new ChrmKVCaches(); } return chrmKVCache; }; var getKVProsumer = function (chrmId) { var kvProsumer = chrmKVProsumerCaches[chrmId]; if (!kvProsumer) { kvProsumer = chrmKVProsumerCaches[chrmId] = new RongIMLib.RongUtil.Prosumer(); } return kvProsumer; }; var ChrmKVHandler = (function () { function ChrmKVHandler() { } ChrmKVHandler.pull = function (chrmId, time) { var prosumer = getKVProsumer(chrmId); var event = RongIMLib.RongIMClient._dataAccessProvider.pullChatroomEntry; prosumer.produce({ event: event, chrmId: chrmId, time: time }); prosumer.consume(function (params, next) { var event = params.event, chrmId = params.chrmId, time = params.time; var kvCache = getKVCache(chrmId); var currentTime = kvCache.getTime(); var isKVNeedUpdated = currentTime < time; if (isKVNeedUpdated) { event(chrmId, currentTime, { onSuccess: function (result) { ChrmKVHandler.setEntries(chrmId, result); next(); }, onError: next }); } else { next(); } }); }; ChrmKVHandler.setEntries = function (chrmId, entity) { var entries = entity.entries, isFullUpdate = entity.bFullUpdate, syncTime = entity.syncTime; var event = isFullUpdate ? ChrmKVHandler.setFullEntries : ChrmKVHandler.setIncreEntries; var kvCache = getKVCache(chrmId); syncTime = MessageUtil.int64ToTimestamp(syncTime); if (RongIMLib.RongUtil.isArray(entries)) { RongIMLib.RongUtil.forEach(entries, function (item) { var setTime = item.timestamp; if (!RongIMLib.RongUtil.isNumber(setTime)) { item.timestamp = MessageUtil.int64ToTimestamp(setTime); } }); } kvCache.setTime(syncTime); // 更新拉取时间 event(chrmId, entries); // 更新 kv 值 }; ChrmKVHandler.setEntry = function (chrmId, chatroomEntry, status, userId) { var kvCache = getKVCache(chrmId); var timestamp = chatroomEntry.timestamp || +new Date(); var isDelete = RongInnerTools.getChrmEntityByStatus(status).isDelete; var eventName = isDelete ? 'removeValue' : 'setValue'; kvCache[eventName]({ key: chatroomEntry.key, value: chatroomEntry.value, userId: userId, timestamp: timestamp }); }; ChrmKVHandler.setFullEntries = function (chrmId, entries) { var kvCache = getKVCache(chrmId); kvCache.clear(); RongIMLib.RongUtil.forEach(entries, function (entity) { entity.timestamp = MessageUtil.int64ToTimestamp(entity.timestamp); kvCache.setValue({ key: entity.key, value: entity.value, userId: entity.uid, timestamp: entity.timestamp }); }); }; ChrmKVHandler.setIncreEntries = function (chrmId, entries) { var kvCache = getKVCache(chrmId); var currentUserId = RongIMLib.RongIMClient.getInstance().getCurrentUserId(); var optEvent = function (entity, isOverwrite, eventName) { var key = entity.key, value = entity.value; var isLatestedKeySetBySelf = kvCache.getSetUserId(key) === currentUserId; var isKeyNotExist = !kvCache.isKeyExisted(key); /* 1. 需覆盖时, 不管 key 是否已存在, 都直接设置 2. 不覆盖时, 必须最后一次 key 为自己设置的或此 key 还未设置过, 才能继续 */ if (isOverwrite || isLatestedKeySetBySelf || isKeyNotExist) { kvCache[eventName]({ key: key, value: value, userId: entity.uid, timestamp: entity.timestamp }); } }; RongIMLib.RongUtil.forEach(entries, function (entity) { var entityContent = RongInnerTools.getChrmEntityByStatus(entity.status); var eventName = entityContent.isDelete ? 'removeValue' : 'setValue'; optEvent(entity, entityContent.isOverwrite, eventName); }); }; ChrmKVHandler.getEntityValue = function (chrmId, key) { var kvCache = getKVCache(chrmId); return kvCache.getValue(key); }; ChrmKVHandler.getAllEntityValue = function (chrmId) { var kvCache = getKVCache(chrmId); return kvCache.getAllKV(); }; ChrmKVHandler.isKeyValid = function (key) { return /^[A-Za-z0-9_=+-]+$/.test(key); }; return ChrmKVHandler; })(); RongIMLib.ChrmKVHandler = ChrmKVHandler; var AutoDeleteCode = 0x0001; var OverwriteCode = 0x0002; var DeleteOperationCode = 0x0004; var RongInnerTools = (function () { function RongInnerTools() { } RongInnerTools.convertUserStatus = function (entity) { entity = RongIMLib.RongUtil.rename(entity, { subUserId: 'userId' }); var status = JSON.parse(entity.status); var us = status.us; if (!us) { return entity; } entity.status = RongIMLib.RongUtil.rename(us, { o: 'online', 'p': 'platform', s: 'status' }); return entity; }; RongInnerTools.getChrmEntityStatus = function (entity, chatroomOpt) { var status = 0; // 是否自动清理 if (entity.isAutoDelete) { status = status | AutoDeleteCode; } // 是否覆盖 if (entity.isOverwrite) { status = status | OverwriteCode; } // 操作类型 switch (chatroomOpt) { case RongIMLib.ChatroomEntityOpt.DELETE: status = status | DeleteOperationCode; break; default: break; } return status; }; RongInnerTools.getChrmEntityByStatus = function (status) { var isDelete = !!(status & DeleteOperationCode); var entityOpt = isDelete ? RongIMLib.ChatroomEntityOpt.DELETE : RongIMLib.ChatroomEntityOpt.UPDATE; return { isAutoDelete: !!(status & AutoDeleteCode), isOverwrite: !!(status & OverwriteCode), entityOpt: entityOpt, isDelete: isDelete }; }; return RongInnerTools; })(); RongIMLib.RongInnerTools = RongInnerTools; var UnreadCountHandler = (function () { function UnreadCountHandler() { } UnreadCountHandler.getKey = function (type, targetId) { var selfId = RongIMLib.RongIMClient.getInstance().getCurrentUserId(); return RongIMLib.RongUtil.tplEngine(UnreadCountHandler.KeyTemp, { selfId: selfId, type: type, targetId: targetId }); }; UnreadCountHandler.getDetailByKey = function (key) { var detail = { count: 0, sentTime: 0 }; var value = RongIMLib.RongIMClient._storageProvider.getItem(key); if (!value) { return detail; } value += ''; var unreadItems = value.split('_'); var hasUnderline = unreadItems.length > 1; detail.count = Number(unreadItems[0]); if (hasUnderline) { detail.sentTime = Number(unreadItems[1]); } return detail; }; UnreadCountHandler.getDetail = function (type, targetId) { var key = UnreadCountHandler.getKey(type, targetId); var detail = UnreadCountHandler.getDetailByKey(key); return detail; }; UnreadCountHandler.set = function (type, id, count, sentTime) { var key = UnreadCountHandler.getKey(type, id); var value = sentTime ? RongIMLib.RongUtil.tplEngine(UnreadCountHandler.ValueTemp, { count: count, sentTime: sentTime }) : count; RongIMLib.RongIMClient._storageProvider.setItem(key, value); return count; }; UnreadCountHandler.add = function (type, id, plusCount, sentTime) { var detail = UnreadCountHandler.getDetail(type, id), count = detail.count, oldSentTime = detail.sentTime; if (sentTime && sentTime > oldSentTime) { count = count + plusCount; UnreadCountHandler.set(type, id, count, sentTime); } return count; }; UnreadCountHandler.get = function (type, id) { var detail = UnreadCountHandler.getDetail(type, id); return detail.count; }; UnreadCountHandler.getAll = function (types) { var total = 0; var selfId = RongIMLib.RongIMClient.getInstance().getCurrentUserId(); var setTotal = function (keyList) { RongIMLib.RongUtil.forEach(keyList, function (key) { var detail = UnreadCountHandler.getDetailByKey(key); total += detail.count; }); }; if (types) { RongIMLib.RongUtil.forEach(types, function (type) { var key = UnreadCountHandler.getKey(type, ''); var unreadKeys = RongIMLib.RongIMClient._storageProvider.getItemKeyList(key); setTotal(unreadKeys); }); } else { var key = UnreadCountHandler.getKey('', ''); var unreadKeys = RongIMLib.RongIMClient._storageProvider.getItemKeyList(key); setTotal(unreadKeys); } return total; }; UnreadCountHandler.remove = function (type, targetId) { var key = UnreadCountHandler.getKey(type, targetId); RongIMLib.RongIMClient._storageProvider.removeItem(key); }; UnreadCountHandler.clear = function () { var key = UnreadCountHandler.getKey('', ''); var keyList = RongIMLib.RongIMClient._storageProvider.getItemKeyList(key); RongIMLib.RongUtil.forEach(keyList, function (key) { RongIMLib.RongIMClient._storageProvider.removeItem(key); }); }; UnreadCountHandler.KeyTemp = 'cu{selfId}{type}{targetId}'; UnreadCountHandler.ValueTemp = '{count}_{sentTime}'; return UnreadCountHandler; })(); RongIMLib.UnreadCountHandler = UnreadCountHandler; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var MessageContent = (function () { function MessageContent(data) { throw new Error("This method is abstract, you must implement this method in inherited class."); } MessageContent.obtain = function () { throw new Error("This method is abstract, you must implement this method in inherited class."); }; return MessageContent; })(); RongIMLib.MessageContent = MessageContent; var NotificationMessage = (function (_super) { __extends(NotificationMessage, _super); function NotificationMessage() { _super.apply(this, arguments); } return NotificationMessage; })(MessageContent); RongIMLib.NotificationMessage = NotificationMessage; var StatusMessage = (function (_super) { __extends(StatusMessage, _super); function StatusMessage() { _super.apply(this, arguments); } return StatusMessage; })(MessageContent); RongIMLib.StatusMessage = StatusMessage; var ModelUtil = (function () { function ModelUtil() { } ModelUtil.modelClone = function (object) { var obj = {}; for (var item in object) { if (item != "messageName" && "encode" != item) { obj[item] = object[item]; } } return obj; }; ModelUtil.modleCreate = function (fields, msgType) { // if (fields.length < 1) { // throw new Error("Array is empty -> registerMessageType.modleCreate"); // } var Object = function (message) { var me = this; for (var index in fields) { me[fields[index]] = message[fields[index]]; } Object.prototype.messageName = msgType; Object.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; }; return Object; }; return ModelUtil; })(); RongIMLib.ModelUtil = ModelUtil; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var CustomerStatusMessage = (function () { function CustomerStatusMessage(message) { this.messageName = "CustomerStatusMessage"; this.status = message.status; } CustomerStatusMessage.obtain = function () { return null; }; CustomerStatusMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return CustomerStatusMessage; })(); RongIMLib.CustomerStatusMessage = CustomerStatusMessage; /** * 客服转换响应消息的类型名 */ var ChangeModeResponseMessage = (function () { function ChangeModeResponseMessage(message) { this.messageName = "ChangeModeResponseMessage"; this.code = message.code; this.data = message.data; this.msg = message.msg; } ChangeModeResponseMessage.obtain = function () { return null; }; ChangeModeResponseMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ChangeModeResponseMessage; })(); RongIMLib.ChangeModeResponseMessage = ChangeModeResponseMessage; /** * 客服转换消息的类型名 * 此消息不计入未读消息数 */ var ChangeModeMessage = (function () { function ChangeModeMessage(message) { this.messageName = "ChangeModeMessage"; this.uid = message.uid; this.sid = message.sid; this.pid = message.pid; } ChangeModeMessage.obtain = function () { return null; }; ChangeModeMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ChangeModeMessage; })(); RongIMLib.ChangeModeMessage = ChangeModeMessage; var CustomerStatusUpdateMessage = (function () { function CustomerStatusUpdateMessage(message) { this.messageName = "CustomerStatusUpdateMessage"; this.serviceStatus = message.serviceStatus; this.sid = message.sid; } CustomerStatusUpdateMessage.obtain = function () { return null; }; CustomerStatusUpdateMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return CustomerStatusUpdateMessage; })(); RongIMLib.CustomerStatusUpdateMessage = CustomerStatusUpdateMessage; var HandShakeMessage = (function () { function HandShakeMessage(message) { this.messageName = "HandShakeMessage"; if (message) { this.requestInfo = message.requestInfo; this.userInfo = message.userInfo; } } HandShakeMessage.obtain = function () { return null; }; HandShakeMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return HandShakeMessage; })(); RongIMLib.HandShakeMessage = HandShakeMessage; var CustomerContact = (function () { function CustomerContact(message) { this.messageName = "CustomerContact"; this.page = message.page; this.nickName = message.nickName; this.routingInfo = message.routingInfo; this.info = message.info; this.requestInfo = message.requestInfo; } CustomerContact.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return CustomerContact; })(); RongIMLib.CustomerContact = CustomerContact; var EvaluateMessage = (function () { function EvaluateMessage(message) { this.messageName = "EvaluateMessage"; this.uid = message.uid; this.sid = message.sid; this.pid = message.pid; this.source = message.source; this.suggest = message.suggest; this.isresolve = message.isresolve; this.type = message.type; } EvaluateMessage.obtain = function () { return null; }; EvaluateMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return EvaluateMessage; })(); RongIMLib.EvaluateMessage = EvaluateMessage; /** * 客服握手响应消息的类型名 */ var HandShakeResponseMessage = (function () { function HandShakeResponseMessage(message) { this.messageName = "HandShakeResponseMessage"; this.msg = message.msg; this.status = message.status; this.data = message.data; } HandShakeResponseMessage.obtain = function () { return null; }; HandShakeResponseMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return HandShakeResponseMessage; })(); RongIMLib.HandShakeResponseMessage = HandShakeResponseMessage; var SuspendMessage = (function () { function SuspendMessage(message) { this.messageName = "SuspendMessage"; this.uid = message.uid; this.sid = message.sid; this.pid = message.pid; } SuspendMessage.obtain = function () { return null; }; SuspendMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return SuspendMessage; })(); RongIMLib.SuspendMessage = SuspendMessage; var TerminateMessage = (function () { function TerminateMessage(message) { this.messageName = "TerminateMessage"; this.code = message.code; this.msg = message.msg; this.sid = message.sid; } TerminateMessage.obtain = function () { return null; }; TerminateMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return TerminateMessage; })(); RongIMLib.TerminateMessage = TerminateMessage; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var IsTypingStatusMessage = (function () { function IsTypingStatusMessage(data) { this.messageName = "IsTypingStatusMessage"; var msg = data; } IsTypingStatusMessage.prototype.encode = function () { return undefined; }; IsTypingStatusMessage.prototype.getMessage = function () { return null; }; return IsTypingStatusMessage; })(); RongIMLib.IsTypingStatusMessage = IsTypingStatusMessage; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var InformationNotificationMessage = (function () { function InformationNotificationMessage(message) { this.messageName = "InformationNotificationMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> InformationNotificationMessage."); } this.message = message.message; this.extra = message.extra; if (message.user) { this.user = message.user; } } InformationNotificationMessage.obtain = function (message) { return new InformationNotificationMessage({ message: message, extra: "" }); }; InformationNotificationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return InformationNotificationMessage; })(); RongIMLib.InformationNotificationMessage = InformationNotificationMessage; var CommandMessage = (function () { function CommandMessage(message) { this.messageName = "CommandMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> CommandMessage."); } try { if (Object.prototype.toString.call(message.data) == "[object String]") { this.data = JSON.parse(message.data); } else { this.data = message.data; } } catch (e) { this.data = message.data; } this.name = message.name; this.extra = message.extra; } CommandMessage.obtain = function (data) { return new CommandMessage({ data: data, extra: "" }); }; CommandMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return CommandMessage; })(); RongIMLib.CommandMessage = CommandMessage; var ContactNotificationMessage = (function () { function ContactNotificationMessage(message) { this.messageName = "ContactNotificationMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> ContactNotificationMessage."); } this.operation = message.operation; this.targetUserId = message.targetUserId; this.message = message.message; this.extra = message.extra; this.sourceUserId = message.sourceUserId; if (message.user) { this.user = message.user; } } ContactNotificationMessage.obtain = function (operation, sourceUserId, targetUserId, message) { return new InformationNotificationMessage({ operation: operation, sourceUserId: sourceUserId, targetUserId: targetUserId, message: message }); }; ContactNotificationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; ContactNotificationMessage.CONTACT_OPERATION_ACCEPT_RESPONSE = "ContactOperationAcceptResponse"; ContactNotificationMessage.CONTACT_OPERATION_REJECT_RESPONSE = "ContactOperationRejectResponse"; ContactNotificationMessage.CONTACT_OPERATION_REQUEST = "ContactOperationRequest"; return ContactNotificationMessage; })(); RongIMLib.ContactNotificationMessage = ContactNotificationMessage; var ProfileNotificationMessage = (function () { function ProfileNotificationMessage(message) { this.messageName = "ProfileNotificationMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> ProfileNotificationMessage."); } this.operation = message.operation; try { if (Object.prototype.toString.call(message.data) == "[object String]") { this.data = JSON.parse(message.data); } else { this.data = message.data; } } catch (e) { this.data = message.data; } this.extra = message.extra; if (message.user) { this.user = message.user; } } ProfileNotificationMessage.obtain = function (operation, data) { return new ProfileNotificationMessage({ operation: operation, data: data }); }; ProfileNotificationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ProfileNotificationMessage; })(); RongIMLib.ProfileNotificationMessage = ProfileNotificationMessage; var CommandNotificationMessage = (function () { function CommandNotificationMessage(message) { this.messageName = "CommandNotificationMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> ProfileNotificationMessage."); } try { if (Object.prototype.toString.call(message.data) == "[object String]") { this.data = JSON.parse(message.data); } else { this.data = message.data; } } catch (e) { this.data = message.data; } this.name = message.name; this.extra = message.extra; if (message.user) { this.user = message.user; } } CommandNotificationMessage.obtain = function (name, data) { return new CommandNotificationMessage({ name: name, data: data, extra: "" }); }; CommandNotificationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return CommandNotificationMessage; })(); RongIMLib.CommandNotificationMessage = CommandNotificationMessage; var DiscussionNotificationMessage = (function () { function DiscussionNotificationMessage(message) { this.messageName = "DiscussionNotificationMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> DiscussionNotificationMessage."); } this.extra = message.extra; this.extension = message.extension; this.type = message.type; this.isHasReceived = message.isHasReceived; this.operation = message.operation; this.user = message.user; if (message.user) { this.user = message.user; } } DiscussionNotificationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return DiscussionNotificationMessage; })(); RongIMLib.DiscussionNotificationMessage = DiscussionNotificationMessage; var GroupNotificationMessage = (function () { function GroupNotificationMessage(msg) { this.messageName = "GroupNotificationMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> GroupNotificationMessage."); } msg.operatorUserId && (this.operatorUserId = msg.operatorUserId); msg.operation && (this.operation = msg.operation); msg.data && (this.data = msg.data); msg.message && (this.message = msg.message); msg.extra && (this.extra = msg.extra); } GroupNotificationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return GroupNotificationMessage; })(); RongIMLib.GroupNotificationMessage = GroupNotificationMessage; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var TextMessage = (function () { function TextMessage(message) { this.messageName = "TextMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> TextMessage."); } this.content = message.content; this.extra = message.extra; if (message.user) { this.user = message.user; } if (message.mentionedInfo) { this.mentionedInfo = message.mentionedInfo; } } TextMessage.obtain = function (text) { return new TextMessage({ extra: "", content: text }); }; TextMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return TextMessage; })(); RongIMLib.TextMessage = TextMessage; var TypingStatusMessage = (function () { function TypingStatusMessage(message) { this.messageName = "TypingStatusMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> TypingStatusMessage."); } this.typingContentType = message.typingContentType; this.data = message.data; } TypingStatusMessage.obtain = function (typingContentType, data) { return new TypingStatusMessage({ typingContentType: typingContentType, data: data }); }; TypingStatusMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return TypingStatusMessage; })(); RongIMLib.TypingStatusMessage = TypingStatusMessage; var ReadReceiptMessage = (function () { function ReadReceiptMessage(message) { this.messageName = "ReadReceiptMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> ReadReceiptMessage."); } this.lastMessageSendTime = message.lastMessageSendTime; this.messageUId = message.messageUId; this.type = message.type; } ReadReceiptMessage.obtain = function (messageUId, lastMessageSendTime, type) { return new ReadReceiptMessage({ messageUId: messageUId, lastMessageSendTime: lastMessageSendTime, type: type }); }; ReadReceiptMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ReadReceiptMessage; })(); RongIMLib.ReadReceiptMessage = ReadReceiptMessage; var VoiceMessage = (function () { function VoiceMessage(message) { this.messageName = "VoiceMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> VoiceMessage."); } this.content = message.content; this.duration = message.duration; this.extra = message.extra; if (message.user) { this.user = message.user; } if (message.mentionedInfo) { this.mentionedInfo = message.mentionedInfo; } } VoiceMessage.obtain = function (base64Content, duration) { return new VoiceMessage({ content: base64Content, duration: duration, extra: "" }); }; VoiceMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return VoiceMessage; })(); RongIMLib.VoiceMessage = VoiceMessage; var RecallCommandMessage = (function () { function RecallCommandMessage(message) { this.messageName = "RecallCommandMessage"; this.messageUId = message.messageUId; this.conversationType = message.conversationType; this.targetId = message.targetId; this.sentTime = message.sentTime; message.extra && (this.extra = message.extra); message.user && (this.user = message.user); } RecallCommandMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return RecallCommandMessage; })(); RongIMLib.RecallCommandMessage = RecallCommandMessage; var ImageMessage = (function () { function ImageMessage(message) { this.messageName = "ImageMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> ImageMessage."); } this.content = message.content; this.imageUri = message.imageUri; message.extra && (this.extra = message.extra); message.user && (this.user = message.user); if (message.mentionedInfo) { this.mentionedInfo = message.mentionedInfo; } } ImageMessage.obtain = function (content, imageUri) { return new ImageMessage({ content: content, imageUri: imageUri, extra: "" }); }; ImageMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ImageMessage; })(); RongIMLib.ImageMessage = ImageMessage; var LocationMessage = (function () { function LocationMessage(message) { this.messageName = "LocationMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> LocationMessage."); } this.latitude = message.latitude; this.longitude = message.longitude; this.poi = message.poi; this.content = message.content; this.extra = message.extra; if (message.user) { this.user = message.user; } if (message.mentionedInfo) { this.mentionedInfo = message.mentionedInfo; } } LocationMessage.obtain = function (latitude, longitude, poi, content) { return new LocationMessage({ latitude: latitude, longitude: longitude, poi: poi, content: content, extra: "" }); }; LocationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return LocationMessage; })(); RongIMLib.LocationMessage = LocationMessage; var RichContentMessage = (function () { function RichContentMessage(message) { this.messageName = "RichContentMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> RichContentMessage."); } this.title = message.title; this.content = message.content; this.imageUri = message.imageUri; this.extra = message.extra; this.url = message.url; if (message.user) { this.user = message.user; } } RichContentMessage.obtain = function (title, content, imageUri, url) { return new RichContentMessage({ title: title, content: content, imageUri: imageUri, url: url, extra: "" }); }; RichContentMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return RichContentMessage; })(); RongIMLib.RichContentMessage = RichContentMessage; var JrmfRedPacketMessage = (function () { function JrmfRedPacketMessage(message) { this.messageName = 'JrmfRedPacketMessage'; message && (this.message = message); } JrmfRedPacketMessage.prototype.encode = function () { return ""; }; return JrmfRedPacketMessage; })(); RongIMLib.JrmfRedPacketMessage = JrmfRedPacketMessage; var JrmfRedPacketOpenedMessage = (function () { function JrmfRedPacketOpenedMessage(message) { this.messageName = 'JrmfRedPacketOpenedMessage'; message && (this.message = message); } JrmfRedPacketOpenedMessage.prototype.encode = function () { return ""; }; return JrmfRedPacketOpenedMessage; })(); RongIMLib.JrmfRedPacketOpenedMessage = JrmfRedPacketOpenedMessage; var UnknownMessage = (function () { function UnknownMessage(message) { this.messageName = "UnknownMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> UnknownMessage."); } this.message = message; } UnknownMessage.prototype.encode = function () { return ""; }; return UnknownMessage; })(); RongIMLib.UnknownMessage = UnknownMessage; var PublicServiceCommandMessage = (function () { function PublicServiceCommandMessage(message) { this.messageName = "PublicServiceCommandMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> PublicServiceCommandMessage."); } this.content = message.content; this.extra = message.extra; this.menuItem = message.menuItem; if (message.user) { this.user = message.user; } if (message.mentionedInfo) { this.mentionedInfo = message.mentionedInfo; } } PublicServiceCommandMessage.obtain = function (item) { return new PublicServiceCommandMessage({ content: "", command: "", menuItem: item, extra: "" }); }; PublicServiceCommandMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return PublicServiceCommandMessage; })(); RongIMLib.PublicServiceCommandMessage = PublicServiceCommandMessage; var PublicServiceMultiRichContentMessage = (function () { function PublicServiceMultiRichContentMessage(messages) { this.messageName = "PublicServiceMultiRichContentMessage"; this.richContentMessages = messages; } PublicServiceMultiRichContentMessage.prototype.encode = function () { return null; }; return PublicServiceMultiRichContentMessage; })(); RongIMLib.PublicServiceMultiRichContentMessage = PublicServiceMultiRichContentMessage; var SyncReadStatusMessage = (function () { function SyncReadStatusMessage(message) { this.messageName = "SyncReadStatusMessage"; message.lastMessageSendTime && (this.lastMessageSendTime = message.lastMessageSendTime); } SyncReadStatusMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return SyncReadStatusMessage; })(); RongIMLib.SyncReadStatusMessage = SyncReadStatusMessage; var ReadReceiptRequestMessage = (function () { function ReadReceiptRequestMessage(message) { this.messageName = "ReadReceiptRequestMessage"; message.messageUId && (this.messageUId = message.messageUId); } ReadReceiptRequestMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ReadReceiptRequestMessage; })(); RongIMLib.ReadReceiptRequestMessage = ReadReceiptRequestMessage; var ReadReceiptResponseMessage = (function () { function ReadReceiptResponseMessage(message) { this.messageName = "ReadReceiptResponseMessage"; message.receiptMessageDic && (this.receiptMessageDic = message.receiptMessageDic); } ReadReceiptResponseMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ReadReceiptResponseMessage; })(); RongIMLib.ReadReceiptResponseMessage = ReadReceiptResponseMessage; var PublicServiceRichContentMessage = (function () { function PublicServiceRichContentMessage(message) { this.messageName = "PublicServiceRichContentMessage"; this.richContentMessage = message; } PublicServiceRichContentMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return PublicServiceRichContentMessage; })(); RongIMLib.PublicServiceRichContentMessage = PublicServiceRichContentMessage; var FileMessage = (function () { function FileMessage(message) { this.messageName = "FileMessage"; message.name && (this.name = message.name); message.size && (this.size = message.size); message.type && (this.type = message.type); message.fileUrl && (this.fileUrl = message.fileUrl); message.extra && (this.extra = message.extra); message.user && (this.user = message.user); } FileMessage.obtain = function (msg) { return new FileMessage({ name: msg.name, size: msg.size, type: msg.type, fileUrl: msg.fileUrl }); }; FileMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return FileMessage; })(); RongIMLib.FileMessage = FileMessage; var HQVoiceMessage = (function () { function HQVoiceMessage(message) { this.messageName = "HQVoiceMessage"; this.type = message.type || 'aac'; message.localPath && (this.localPath = message.localPath); message.remoteUrl && (this.remoteUrl = message.remoteUrl); message.duration && (this.duration = message.duration); message.extra && (this.extra = message.extra); message.user && (this.user = message.user); } HQVoiceMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return HQVoiceMessage; })(); RongIMLib.HQVoiceMessage = HQVoiceMessage; var AcceptMessage = (function () { function AcceptMessage(message) { this.messageName = "AcceptMessage"; this.mediaId = message.mediaId; this.callId = message.callId; this.mediaType = message.mediaType; this.mode = message.mode; this.subInfo = message.subInfo; } AcceptMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return AcceptMessage; })(); RongIMLib.AcceptMessage = AcceptMessage; var RingingMessage = (function () { function RingingMessage(message) { this.messageName = "RingingMessage"; this.callId = message.callId; } RingingMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return RingingMessage; })(); RongIMLib.RingingMessage = RingingMessage; var SummaryMessage = (function () { function SummaryMessage(message) { this.messageName = "SummaryMessage"; this.caller = message.caller; this.inviter = message.inviter; this.mediaType = message.mediaType; this.memberIdList = message.memberIdList; this.startTime = message.startTime; this.connectedTime = message.connectedTime; this.duration = message.duration; this.status = message.status; } SummaryMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return SummaryMessage; })(); RongIMLib.SummaryMessage = SummaryMessage; var HungupMessage = (function () { function HungupMessage(message) { this.messageName = "HungupMessage"; this.callId = message.callId; this.reason = message.reason; this.mode = message.mode; this.subInfo = message.subInfo; } HungupMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return HungupMessage; })(); RongIMLib.HungupMessage = HungupMessage; var InviteMessage = (function () { function InviteMessage(message) { this.messageName = "InviteMessage"; this.mediaId = message.mediaId; this.callId = message.callId; this.engineType = message.engineType; this.channelInfo = message.channelInfo; this.mediaType = message.mediaType; this.extra = message.extra; this.inviteUserIds = message.inviteUserIds; this.observerUserIds = message.observerUserIds; this.mode = message.mode; this.subInfo = message.subInfo; } InviteMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return InviteMessage; })(); RongIMLib.InviteMessage = InviteMessage; var MediaModifyMessage = (function () { function MediaModifyMessage(message) { this.messageName = "MediaModifyMessage"; this.callId = message.callId; this.mediaType = message.mediaType; this.mode = message.mode; this.subInfo = message.subInfo; } MediaModifyMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return MediaModifyMessage; })(); RongIMLib.MediaModifyMessage = MediaModifyMessage; var MemberModifyMessage = (function () { function MemberModifyMessage(message) { this.messageName = "MemberModifyMessage"; this.modifyMemType = message.modifyMemType; this.callId = message.callId; this.caller = message.caller; this.engineType = message.engineType; this.channelInfo = message.channelInfo; this.mediaType = message.mediaType; this.extra = message.extra; this.inviteUserIds = message.inviteUserIds; this.existedMemberStatusList = message.existedMemberStatusList; this.existedUserPofiles = message.existedUserPofiles; this.observerUserIds = message.observerUserIds; this.mode = message.mode; this.subInfo = message.subInfo; } MemberModifyMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return MemberModifyMessage; })(); RongIMLib.MemberModifyMessage = MemberModifyMessage; var RCCombineMessage = (function () { function RCCombineMessage(message) { this.messageName = "RCCombineMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> RCCombineMessage."); } this.nameList = message.nameList; this.remoteUrl = message.remoteUrl; if (message.user) { this.user = message.user; } this.summaryList = message.summaryList; } RCCombineMessage.obtain = function (remoteUrl, nameList, summaryList) { return new RCCombineMessage({ extra: "", content: remoteUrl, nameList: nameList, summaryList: summaryList }); }; RCCombineMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return RCCombineMessage; })(); RongIMLib.RCCombineMessage = RCCombineMessage; var ChrmKVNotificationMessage = (function () { function ChrmKVNotificationMessage(message) { this.messageName = "ChrmKVNotificationMessage"; message.key && (this.key = message.key); message.value && (this.value = message.value); message.type && (this.type = message.type); message.extra && (this.extra = message.extra); message.user && (this.user = message.user); } ChrmKVNotificationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ChrmKVNotificationMessage; })(); RongIMLib.ChrmKVNotificationMessage = ChrmKVNotificationMessage; var ReferenceMessage = (function () { function ReferenceMessage(message) { this.messageName = "ReferenceMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> ReferenceMessage."); } this.content = message.content; this.referMsgUserId = message.referMsgUserId; this.referMsgOjb = message.referMsgOjb; if (message.user) { this.user = message.user; } if (message.mentionedInfo) { this.mentionedInfo = message.mentionedInfo; } } ReferenceMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ReferenceMessage; })(); RongIMLib.ReferenceMessage = ReferenceMessage; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var ChannelInfo = (function () { function ChannelInfo(Id, Key) { this.Id = Id; this.Key = Key; } return ChannelInfo; })(); RongIMLib.ChannelInfo = ChannelInfo; var UserStatus = (function () { function UserStatus(platform, online, status) { this.platform = platform; this.online = online; this.status = status; } return UserStatus; })(); RongIMLib.UserStatus = UserStatus; var MentionedInfo = (function () { function MentionedInfo(type, userIdList, mentionedContent) { } return MentionedInfo; })(); RongIMLib.MentionedInfo = MentionedInfo; var DeleteMessage = (function () { function DeleteMessage(msgId, msgDataTime, direct) { this.msgId = msgId; this.msgDataTime = msgDataTime; this.direct = direct; } return DeleteMessage; })(); RongIMLib.DeleteMessage = DeleteMessage; var CustomServiceConfig = (function () { function CustomServiceConfig(isBlack, companyName, companyUrl) { } return CustomServiceConfig; })(); RongIMLib.CustomServiceConfig = CustomServiceConfig; var CustomServiceSession = (function () { function CustomServiceSession(uid, cid, pid, isQuited, type, adminHelloWord, adminOfflineWord) { } return CustomServiceSession; })(); RongIMLib.CustomServiceSession = CustomServiceSession; var Conversation = (function () { function Conversation(conversationTitle, conversationType, draft, isTop, latestMessage, latestMessageId, notificationStatus, objectName, receivedStatus, receivedTime, senderUserId, senderUserName, sentStatus, sentTime, targetId, unreadMessageCount, senderPortraitUri, isHidden, mentionedMsg, hasUnreadMention, _readTime) { this.conversationTitle = conversationTitle; this.conversationType = conversationType; this.draft = draft; this.isTop = isTop; this.latestMessage = latestMessage; this.latestMessageId = latestMessageId; this.notificationStatus = notificationStatus; this.objectName = objectName; this.receivedStatus = receivedStatus; this.receivedTime = receivedTime; this.senderUserId = senderUserId; this.senderUserName = senderUserName; this.sentStatus = sentStatus; this.sentTime = sentTime; this.targetId = targetId; this.unreadMessageCount = unreadMessageCount; this.senderPortraitUri = senderPortraitUri; this.isHidden = isHidden; this.mentionedMsg = mentionedMsg; this.hasUnreadMention = hasUnreadMention; this._readTime = _readTime; } Conversation.prototype.setTop = function () { RongIMLib.RongIMClient._dataAccessProvider.addConversation(this, { onSuccess: function (data) { } }); }; return Conversation; })(); RongIMLib.Conversation = Conversation; var Discussion = (function () { function Discussion(creatorId, id, memberIdList, name, isOpen) { this.creatorId = creatorId; this.id = id; this.memberIdList = memberIdList; this.name = name; this.isOpen = isOpen; } return Discussion; })(); RongIMLib.Discussion = Discussion; var Group = (function () { function Group(id, name, portraitUri) { this.id = id; this.name = name; this.portraitUri = portraitUri; } return Group; })(); RongIMLib.Group = Group; var Message = (function () { function Message(content, conversationType, extra, objectName, messageDirection, messageId, receivedStatus, receivedTime, senderUserId, sentStatus, sentTime, targetId, messageType, messageUId, isLocalMessage, offLineMessage, receiptResponse) { this.content = content; this.conversationType = conversationType; this.extra = extra; this.objectName = objectName; this.messageDirection = messageDirection; this.messageId = messageId; this.receivedStatus = receivedStatus; this.receivedTime = receivedTime; this.senderUserId = senderUserId; this.sentStatus = sentStatus; this.sentTime = sentTime; this.targetId = targetId; this.messageType = messageType; this.messageUId = messageUId; this.isLocalMessage = isLocalMessage; this.offLineMessage = offLineMessage; this.receiptResponse = receiptResponse; } return Message; })(); RongIMLib.Message = Message; var MessageTag = (function () { function MessageTag(isCounted, isPersited) { this.isCounted = isCounted; this.isPersited = isPersited; } MessageTag.prototype.getMessageTag = function () { if (this.isCounted && this.isPersited) { return 3; } else if (this.isCounted) { return 2; } else if (this.isPersited) { return 1; } else if (!this.isCounted && !this.isPersited) { return 0; } }; MessageTag.getTagByStatus = function (status) { var statusMap = { 3: { isCounted: true, isPersited: true }, 2: { isCounted: true, isPersited: false }, 1: { isCounted: true, isPersited: true }, 0: { isCounted: true, isPersited: true } }; return statusMap[status] || statusMap[3]; }; return MessageTag; })(); RongIMLib.MessageTag = MessageTag; var PublicServiceMenuItem = (function () { function PublicServiceMenuItem(id, name, type, sunMenuItems, url) { this.id = id; this.name = name; this.type = type; this.sunMenuItems = sunMenuItems; this.url = url; } return PublicServiceMenuItem; })(); RongIMLib.PublicServiceMenuItem = PublicServiceMenuItem; // TODO: TBD var PublicServiceProfile = (function () { function PublicServiceProfile(conversationType, introduction, menu, name, portraitUri, publicServiceId, hasFollowed, isGlobal) { this.conversationType = conversationType; this.introduction = introduction; this.menu = menu; this.name = name; this.portraitUri = portraitUri; this.publicServiceId = publicServiceId; this.hasFollowed = hasFollowed; this.isGlobal = isGlobal; } return PublicServiceProfile; })(); RongIMLib.PublicServiceProfile = PublicServiceProfile; var UserInfo = (function () { function UserInfo(id, name, portraitUri) { this.id = id; this.name = name; this.portraitUri = portraitUri; } return UserInfo; })(); RongIMLib.UserInfo = UserInfo; var User = (function () { function User(id, token) { this.id = id; this.token = token; } return User; })(); RongIMLib.User = User; var Room = (function () { function Room(id, user, mode, broadcastType, type) { this.id = id; this.user = user; this.mode = mode; this.broadcastType = broadcastType; this.type = type; } return Room; })(); RongIMLib.Room = Room; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var ServerDataProvider = (function () { function ServerDataProvider() { this.userStatusListener = null; this.Conversation = { watcher: new RongIMLib.Observer(), watch: function (_watcher) { this.watcher.add(_watcher); var conversationList = RongIMLib.RongIMClient._memoryStore.conversationList; this.watcher.emit(conversationList); }, unwatch: function (_watcher) { this.watcher.remove(_watcher); }, _notify: function (conversationList) { this.watcher.emit(conversationList); } }; } ServerDataProvider.prototype.init = function (appKey, options) { new RongIMLib.FeatureDectector(options.appCallback); }; ServerDataProvider.prototype.connect = function (token, callback, userId, option) { RongIMLib.RongIMClient.bridge = RongIMLib.Bridge.getInstance(); RongIMLib.RongIMClient._memoryStore.token = token; RongIMLib.RongIMClient._memoryStore.callback = callback; userId = userId || ''; option = option || {}; var isConnecting = false, isConnected = false; if (RongIMLib.Bridge._client && RongIMLib.Bridge._client.channel) { isConnecting = (RongIMLib.Bridge._client.channel.connectionStatus == RongIMLib.ConnectionStatus.CONNECTING); isConnected = (RongIMLib.Bridge._client.channel.connectionStatus == RongIMLib.ConnectionStatus.CONNECTED); } if (isConnected || isConnecting) { return; } var isGreater = (RongIMLib.RongIMClient.otherDeviceLoginCount > 5); if (isGreater) { callback.onError(RongIMLib.ConnectionStatus.ULTRALIMIT); return; } // 清除本地导航缓存 if (option.force) { RongIMLib.RongIMClient._storageProvider.removeItem('servers'); } RongIMLib.RongIMClient.bridge.setListener(); RongIMLib.RongIMClient.bridge.connect(RongIMLib.RongIMClient._memoryStore.appKey, token, { onSuccess: function (data) { setTimeout(function () { callback.onSuccess(data); }); }, onError: function (e) { if (e == RongIMLib.ConnectionState.TOKEN_INCORRECT || !e) { setTimeout(function () { callback.onTokenIncorrect(); }); } else { setTimeout(function () { callback.onError(e); }); } } }); }; /* config.auto: 默认 false, true 启用自动重连,启用则为必选参数 config.rate: 重试频率 [100, 1000, 3000, 6000, 10000, 18000] 单位为毫秒,可选 config.url: 网络嗅探地址 [http(s)://]cdn.ronghub.com/RongIMLib-2.2.6.min.js 可选 */ ServerDataProvider.prototype.reconnect = function (callback, config) { var store = RongIMLib.RongIMClient._memoryStore; var token = store.token; if (!token) { throw new Error('reconnect: token is empty.'); } if (RongIMLib.Bridge._client && RongIMLib.Bridge._client.channel && RongIMLib.Bridge._client.channel.connectionStatus != RongIMLib.ConnectionStatus.CONNECTED && RongIMLib.Bridge._client.channel.connectionStatus != RongIMLib.ConnectionStatus.CONNECTING) { config = config || {}; var key = config.auto ? 'auto' : 'custom'; var handler = { auto: function () { var repeatConnect = function (options) { var step = options.step(); var done = 'done'; var url = options.url; var ping = function () { RongIMLib.RongUtil.request({ url: url, success: function () { options.done(); }, error: function () { repeat(); } }); }; var repeat = function () { var next = step(); if (next == 'done') { var error = RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE; options.done(error); return; } setTimeout(ping, next); }; repeat(); }; var protocol = RongIMLib.RongIMClient._memoryStore.depend.protocol; var url = config.url || 'cdn.ronghub.com/RongIMLib-2.2.6.min.js'; var pathConfig = { protocol: protocol, path: url }; url = RongIMLib.RongUtil.formatProtoclPath(pathConfig); var rate = config.rate || [100, 1000, 3000, 6000, 10000, 18000]; //结束标识 rate.push('done'); var opts = { url: url, step: function () { var index = 0; return function () { var time = rate[index]; index++; return time; }; }, done: function (error) { if (error) { callback.onError(error); return; } RongIMLib.RongIMClient.connect(token, callback); } }; repeatConnect(opts); }, custom: function () { RongIMLib.RongIMClient.connect(token, callback); } }; handler[key](); } }; ServerDataProvider.prototype.logout = function () { RongIMLib.RongIMClient.bridge.disconnect(); RongIMLib.RongIMClient.bridge = null; }; ServerDataProvider.prototype.disconnect = function () { RongIMLib.RongIMClient.bridge.disconnect(); }; ServerDataProvider.prototype.sendReceiptResponse = function (conversationType, targetId, sendCallback) { var rspkey = RongIMLib.Bridge._client.userId + conversationType + targetId + 'RECEIVED', me = this; if (RongIMLib.RongUtil.supportLocalStorage()) { var valObj = JSON.parse(RongIMLib.RongIMClient._storageProvider.getItem(rspkey)); if (valObj) { var vals = []; for (var key in valObj) { var tmp = {}; tmp[key] = valObj[key].uIds; valObj[key].isResponse || vals.push(tmp); } if (vals.length == 0) { sendCallback.onSuccess(); return; } var interval = setInterval(function () { if (vals.length == 1) { clearInterval(interval); } var obj = vals.splice(0, 1)[0]; var rspMsg = new RongIMLib.ReadReceiptResponseMessage({ receiptMessageDic: obj }); me.sendMessage(conversationType, targetId, rspMsg, { onSuccess: function (msg) { var senderUserId = RongIMLib.MessageUtil.getFirstKey(obj); valObj[senderUserId].isResponse = true; RongIMLib.RongIMClient._storageProvider.setItem(rspkey, JSON.stringify(valObj)); sendCallback.onSuccess(msg); }, onError: function (error, msg) { sendCallback.onError(error, msg); } }); }, 200); } else { sendCallback.onSuccess(); } } else { sendCallback.onSuccess(); } }; ServerDataProvider.prototype.sendTypingStatusMessage = function (conversationType, targetId, messageName, sendCallback) { var me = this; if (messageName in RongIMLib.RongIMClient.MessageParams) { me.sendMessage(conversationType, targetId, RongIMLib.TypingStatusMessage.obtain(RongIMLib.RongIMClient.MessageParams[messageName].objectName, ""), { onSuccess: function () { setTimeout(function () { sendCallback.onSuccess(); }); }, onError: function (errorCode) { setTimeout(function () { sendCallback.onError(errorCode, null); }); }, onBefore: function () { } }); } }; ServerDataProvider.prototype.sendRecallMessage = function (content, sendMessageCallback) { var msg = new RongIMLib.RecallCommandMessage({ conversationType: content.conversationType, targetId: content.targetId, sentTime: content.sentTime, messageUId: content.messageUId, extra: content.extra, user: content.user }); this.sendMessage(content.conversationType, content.senderUserId, msg, sendMessageCallback, false, null, null, 2); }; ServerDataProvider.prototype.sendTextMessage = function (conversationType, targetId, content, sendMessageCallback) { var msgContent = RongIMLib.TextMessage.obtain(content); this.sendMessage(conversationType, targetId, msgContent, sendMessageCallback); }; ServerDataProvider.prototype.getRemoteHistoryMessages = function (conversationType, targetId, timestamp, count, callback, config) { if (count <= 1) { throw new Error("the count must be greater than 1."); } config = config || {}; var order = config.order || 0; var getKey = function () { return [conversationType, targetId, '_', order].join(''); }; var key = getKey(); if (!RongIMLib.RongUtil.isNumber(timestamp)) { timestamp = RongIMLib.RongIMClient._memoryStore.lastReadTime.get(key); } var memoryStore = RongIMLib.RongIMClient._memoryStore; var historyMessageLimit = memoryStore.historyMessageLimit; /* limit 属性: var limit = { time: '时间戳, 最后一次拉取时间', hasMore: '是否还有历史消息, bool 值' }; */ var limit = historyMessageLimit.get(key) || {}; var hasMore = limit.hasMore; var isFecth = (hasMore || limit.time != timestamp); // 正序获取消息时不做限制,防止有新消息导致无法获取 if (!isFecth && order == 0) { return callback.onSuccess([], hasMore); } var modules = new RongIMLib.RongIMClient.Protobuf.HistoryMsgInput(), self = this; modules.setTargetId(targetId); modules.setTime(timestamp); modules.setCount(count); modules.setOrder(order); var topic = HistoryMsgType[conversationType] || HistoryMsgType[RongIMLib.ConversationType.PRIVATE]; RongIMLib.RongIMClient.bridge.queryMsg(topic, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), targetId, { onSuccess: function (data) { var fetchTime = RongIMLib.MessageUtil.int64ToTimestamp(data.syncTime); RongIMLib.RongIMClient._memoryStore.lastReadTime.set(key, fetchTime); historyMessageLimit.set(key, { hasMore: !!data.hasMsg, time: fetchTime }); var list = data.list.reverse(), tempMsg = null, tempDir; var read = RongIMLib.SentStatus.READ; if (RongIMLib.RongUtil.supportLocalStorage()) { for (var i = 0, len = list.length; i < len; i++) { tempMsg = RongIMLib.MessageUtil.messageParser(list[i]); tempDir = JSON.parse(RongIMLib.RongIMClient._storageProvider.getItem(RongIMLib.Bridge._client.userId + tempMsg.messageUId + "SENT")); if (tempDir) { tempMsg.receiptResponse || (tempMsg.receiptResponse = {}); tempMsg.receiptResponse[tempMsg.messageUId] = tempDir.count; } tempMsg.sentStatus = read; tempMsg.targetId = targetId; list[i] = tempMsg; } } else { for (var i = 0, len = list.length; i < len; i++) { var tempMsg = RongIMLib.MessageUtil.messageParser(list[i]); tempMsg.sentStatus = read; list[i] = tempMsg; } } setTimeout(function () { callback.onSuccess(list, !!data.hasMsg); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }, "HistoryMessagesOuput"); }; ServerDataProvider.prototype.hasRemoteUnreadMessages = function (token, callback) { var xss = null; window.RCCallback = function (x) { setTimeout(function () { callback.onSuccess(!!+x.status); }); xss.parentNode.removeChild(xss); }; xss = document.createElement("script"); xss.src = RongIMLib.RongIMClient._memoryStore.depend.api + "/message/exist.js?appKey=" + encodeURIComponent(RongIMLib.RongIMClient._memoryStore.appKey) + "&token=" + encodeURIComponent(token) + "&callBack=RCCallback&_=" + RongIMLib.RongUtil.getTimestamp(); document.body.appendChild(xss); xss.onerror = function () { setTimeout(function () { callback.onError(RongIMLib.ErrorCode.UNKNOWN); }); xss.parentNode.removeChild(xss); }; }; ServerDataProvider.prototype.getRemoteConversationList = function (callback, conversationTypes, count) { var modules = new RongIMLib.RongIMClient.Protobuf.RelationsInput(), self = this; modules.setType(1); if (typeof count == 'undefined') { modules.setCount(0); } else { modules.setCount(count); } RongIMLib.RongIMClient.bridge.queryMsg(26, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (list) { if (list.info) { list.info = list.info.reverse(); for (var i = 0, len = list.info.length; i < len; i++) { RongIMLib.RongIMClient.getInstance().pottingConversation(list.info[i]); } } var conversations = RongIMLib.RongIMClient._memoryStore.conversationList; setTimeout(function () { if (conversationTypes) { return callback.onSuccess(self.filterConversations(conversationTypes, conversations)); } callback.onSuccess(conversations); }); }, onError: function (error) { callback.onError(error); } }, "RelationsOutput"); }; ServerDataProvider.prototype.addMemberToDiscussion = function (discussionId, userIdList, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.ChannelInvitationInput(); modules.setUsers(userIdList); RongIMLib.RongIMClient.bridge.queryMsg(0, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), discussionId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.createDiscussion = function (name, userIdList, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.CreateDiscussionInput(), self = this; modules.setName(name); RongIMLib.RongIMClient.bridge.queryMsg(1, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (discussId) { if (userIdList.length > 0) { self.addMemberToDiscussion(discussId, userIdList, { onSuccess: function () { }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); } setTimeout(function () { callback.onSuccess(discussId); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }, "CreateDiscussionOutput"); }; ServerDataProvider.prototype.getDiscussion = function (discussionId, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.ChannelInfoInput(); modules.setNothing(1); RongIMLib.RongIMClient.bridge.queryMsg(4, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), discussionId, { onSuccess: function (data) { setTimeout(function () { callback.onSuccess(data); }); }, onError: function (errorCode) { setTimeout(function () { callback.onError(errorCode); }); } }, "ChannelInfoOutput"); }; ServerDataProvider.prototype.quitDiscussion = function (discussionId, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.LeaveChannelInput(); modules.setNothing(1); RongIMLib.RongIMClient.bridge.queryMsg(7, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), discussionId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (errorCode) { setTimeout(function () { callback.onError(errorCode); }); } }); }; ServerDataProvider.prototype.removeMemberFromDiscussion = function (discussionId, userId, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.ChannelEvictionInput(); modules.setUser(userId); RongIMLib.RongIMClient.bridge.queryMsg(9, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), discussionId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (errorCode) { setTimeout(function () { callback.onError(errorCode); }); } }); }; ServerDataProvider.prototype.setDiscussionInviteStatus = function (discussionId, status, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.ModifyPermissionInput(); modules.setOpenStatus(status.valueOf()); RongIMLib.RongIMClient.bridge.queryMsg(11, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), discussionId, { onSuccess: function (x) { setTimeout(function () { callback.onSuccess(); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.setDiscussionName = function (discussionId, name, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RenameChannelInput(); modules.setName(name); RongIMLib.RongIMClient.bridge.queryMsg(12, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), discussionId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (errcode) { callback.onError(errcode); } }); }; ServerDataProvider.prototype.joinChatRoom = function (chatroomId, messageCount, callback) { var e = new RongIMLib.RongIMClient.Protobuf.ChrmInput(); e.setNothing(1); RongIMLib.Bridge._client.chatroomId = chatroomId; RongIMLib.RongIMClient.bridge.queryMsg(19, RongIMLib.MessageUtil.ArrayForm(e.toArrayBuffer()), chatroomId, { onSuccess: function () { var navi = RongIMLib.RongIMClient.getInstance().getNavi(); var isOpenKVStorage = navi.kvStorage; if (isOpenKVStorage) { RongIMLib.RongIMClient._dataAccessProvider.pullChatroomEntry(chatroomId, 0, { onSuccess: function (result) { RongIMLib.ChrmKVHandler.setEntries(chatroomId, result); setTimeout(function () { callback.onSuccess(); }); }, onError: function (errorCode) { setTimeout(function () { callback.onError(errorCode); }); } }); } else { setTimeout(function () { callback.onSuccess(); }); } var modules = new RongIMLib.RongIMClient.Protobuf.ChrmPullMsg(); messageCount == 0 && (messageCount = -1); modules.setCount(messageCount); modules.setSyncTime(0); RongIMLib.Bridge._client.queryMessage("chrmPull", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), chatroomId, 1, { onSuccess: function (collection) { var list = collection.list; var sync = RongIMLib.MessageUtil.int64ToTimestamp(collection.syncTime); var latestMessage = list[list.length - 1]; if (latestMessage) { latestMessage = RongIMLib.MessageUtil.messageParser(latestMessage); sync = latestMessage.sentTime; } RongIMLib.RongIMClient._memoryStore.lastReadTime.set(chatroomId + RongIMLib.Bridge._client.userId + "CST", sync); var _client = RongIMLib.Bridge._client; for (var i = 0, mlen = list.length; i < mlen; i++) { var uId = 'R' + list[i].msgId; if (!(uId in _client.cacheMessageIds)) { _client.cacheMessageIds[uId] = true; var cacheUIds = RongIMLib.RongUtil.keys(_client.cacheMessageIds); if (cacheUIds.length > 10) { uId = cacheUIds[0]; delete _client.cacheMessageIds[uId]; } if (RongIMLib.RongIMClient._memoryStore.filterMessages.length > 0) { for (var j = 0, flen = RongIMLib.RongIMClient._memoryStore.filterMessages.length; j < flen; j++) { if (RongIMLib.RongIMClient.MessageParams[RongIMLib.RongIMClient._memoryStore.filterMessages[j]].objectName != list[i].classname) { _client.handler.onReceived(list[i]); } } } else { _client.handler.onReceived(list[i]); } } } }, onError: function (x) { setTimeout(function () { callback.onError(RongIMLib.ErrorCode.CHATROOM_HISMESSAGE_ERROR); }); } }, "DownStreamMessages"); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }, "ChrmOutput"); }; ServerDataProvider.prototype.getChatRoomInfo = function (chatRoomId, count, order, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.QueryChatroomInfoInput(); modules.setCount(count); modules.setOrder(order); RongIMLib.RongIMClient.bridge.queryMsg("queryChrmI", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), chatRoomId, { onSuccess: function (ret) { var userInfos = ret.userInfos; userInfos.forEach(function (item) { item.time = RongIMLib.MessageUtil.int64ToTimestamp(item.time); }); setTimeout(function () { callback.onSuccess(ret); }); }, onError: function (errcode) { setTimeout(function () { callback.onError(errcode); }); } }, "QueryChatroomInfoOutput"); }; ServerDataProvider.prototype.quitChatRoom = function (chatroomId, callback) { var e = new RongIMLib.RongIMClient.Protobuf.ChrmInput(); e.setNothing(1); RongIMLib.RongIMClient.bridge.queryMsg(17, RongIMLib.MessageUtil.ArrayForm(e.toArrayBuffer()), chatroomId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (errcode) { setTimeout(function () { callback.onError(errcode); }); } }, "ChrmOutput"); }; ServerDataProvider.prototype.setChatroomHisMessageTimestamp = function (chatRoomId, timestamp) { RongIMLib.RongIMClient._memoryStore.lastReadTime.set('chrhis_' + chatRoomId, timestamp); }; ServerDataProvider.prototype.getChatRoomHistoryMessages = function (chatRoomId, count, order, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.HistoryMsgInput(); modules.setTargetId(chatRoomId); var timestamp = RongIMLib.RongIMClient._memoryStore.lastReadTime.get('chrhis_' + chatRoomId) || 0; modules.setTime(timestamp); modules.setCount(count); modules.setOrder(order); RongIMLib.RongIMClient.bridge.queryMsg(34, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (data) { RongIMLib.RongIMClient._memoryStore.lastReadTime.set('chrhis_' + chatRoomId, RongIMLib.MessageUtil.int64ToTimestamp(data.syncTime)); var list = data.list.reverse(); for (var i = 0, len = list.length; i < len; i++) { list[i] = RongIMLib.MessageUtil.messageParser(list[i]); } setTimeout(function () { callback.onSuccess(list, !!data.hasMsg); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }, "HistoryMsgOuput"); }; ServerDataProvider.prototype.setChatroomEntry = function (chatroomId, chatroomEntry, callback) { var opt = RongIMLib.ChatroomEntityOpt.UPDATE; var key = chatroomEntry.key, value = chatroomEntry.value; var isKeyInValid = !RongIMLib.RongUtil.isLengthLimit(key, RongIMLib.ChatroomEntityLimit.KEY, 1) || !RongIMLib.ChrmKVHandler.isKeyValid(key); var isValueInValid = !RongIMLib.RongUtil.isLengthLimit(value, RongIMLib.ChatroomEntityLimit.VALUE, 1); if (isKeyInValid || isValueInValid) { setTimeout(function () { callback.onError(RongIMLib.ErrorCode.BIZ_ERROR_INVALID_PARAMETER); }); } else { this.refreshChatroomEntry(chatroomId, chatroomEntry, opt, callback); } }; ServerDataProvider.prototype.forceSetChatroomEntry = function (chatroomId, chatroomEntry, callback) { chatroomEntry.isOverwrite = true; this.setChatroomEntry(chatroomId, chatroomEntry, callback); }; ServerDataProvider.prototype.removeChatroomEntry = function (chatroomId, chatroomEntry, callback) { var opt = RongIMLib.ChatroomEntityOpt.DELETE; var key = chatroomEntry.key; var isKeyInValid = !RongIMLib.RongUtil.isLengthLimit(key, RongIMLib.ChatroomEntityLimit.KEY, 1) || !RongIMLib.ChrmKVHandler.isKeyValid(key); if (isKeyInValid) { setTimeout(function () { callback.onError(RongIMLib.ErrorCode.BIZ_ERROR_INVALID_PARAMETER); }); } else { this.refreshChatroomEntry(chatroomId, chatroomEntry, opt, callback); } }; ServerDataProvider.prototype.forceRemoveChatroomEntry = function (chatroomId, chatroomEntry, callback) { chatroomEntry.isOverwrite = true; this.removeChatroomEntry(chatroomId, chatroomEntry, callback); }; ServerDataProvider.prototype.refreshChatroomEntry = function (chatroomId, chatroomEntry, chatroomEntryOpt, callback) { var modules, topic; var key = chatroomEntry.key, value = chatroomEntry.value || '', extra = chatroomEntry.notificationExtra; if (chatroomEntryOpt === RongIMLib.ChatroomEntityOpt.DELETE) { modules = new RongIMLib.RongIMClient.Protobuf.DeleteChrmKV(); topic = 'delKV'; } else { modules = new RongIMLib.RongIMClient.Protobuf.SetChrmKV(); topic = 'setKV'; } var status = RongIMLib.RongInnerTools.getChrmEntityStatus(chatroomEntry, chatroomEntryOpt); var currentUserId = RongIMLib.RongIMClient.getInstance().getCurrentUserId(); var entry = { key: key, value: value, uid: currentUserId }; if (status) { entry.status = status; } modules.setEntry(entry); if (chatroomEntry.isSendNotification) { modules.setBNotify(true); var msgModules = new RongIMLib.RongIMClient.Protobuf.UpStreamMessage(); var msg = new RongIMLib.ChrmKVNotificationMessage({ key: key, value: value, extra: extra, type: chatroomEntryOpt }); msgModules.setSessionId(RongIMLib.RongIMClient.MessageParams[msg.messageName].msgTag.getMessageTag()); msgModules.setClassname(RongIMLib.RongIMClient.MessageParams[msg.messageName].objectName); msgModules.setContent(msg.encode()); modules.setNotification(msgModules); // 默认设置为 聊天室消息 modules.setType(RongIMLib.ConversationType.CHATROOM); } RongIMLib.RongIMClient.bridge.queryMsg(topic, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), chatroomId, { onSuccess: function (ret) { var currentUserId = RongIMLib.RongIMClient.getInstance().getCurrentUserId(); RongIMLib.ChrmKVHandler.setEntry(chatroomId, chatroomEntry, status, currentUserId); setTimeout(function () { callback.onSuccess(!!ret); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }, 'ChrmOutput'); }; ServerDataProvider.prototype.getChatroomEntry = function (chatroomId, key, callback) { var value = RongIMLib.ChrmKVHandler.getEntityValue(chatroomId, key); setTimeout(function () { if (RongIMLib.RongUtil.isEmpty(value)) { callback.onError(RongIMLib.ErrorCode.CHATROOM_KEY_NOT_EXIST); } else { callback.onSuccess(value); } }); }; ServerDataProvider.prototype.getAllChatroomEntries = function (chatroomId, callback) { setTimeout(function () { var entries = RongIMLib.ChrmKVHandler.getAllEntityValue(chatroomId); callback.onSuccess(entries); }); }; ServerDataProvider.prototype.pullChatroomEntry = function (chatroomId, time, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.QueryChrmKV(); modules.setTimestamp(time); RongIMLib.RongIMClient.bridge.queryMsg('pullKV', RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), chatroomId, { onSuccess: function (data) { setTimeout(function () { callback.onSuccess(data); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }, "ChrmKVOutput"); }; ServerDataProvider.prototype.setMessageStatus = function (conversationType, targetId, timestamp, status, callback) { setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.addToBlacklist = function (userId, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.Add2BlackListInput(); modules.setUserId(userId); RongIMLib.RongIMClient.bridge.queryMsg(21, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.getBlacklist = function (callback) { var modules = new RongIMLib.RongIMClient.Protobuf.QueryBlackListInput(); modules.setNothing(1); RongIMLib.RongIMClient.bridge.queryMsg(23, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (list) { setTimeout(function () { callback.onSuccess(list); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }, "QueryBlackListOutput"); }; ServerDataProvider.prototype.getBlacklistStatus = function (userId, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.BlackListStatusInput(); modules.setUserId(userId); RongIMLib.RongIMClient.bridge.queryMsg(24, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function (status) { setTimeout(function () { callback.onSuccess(RongIMLib.BlacklistStatus[status]); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.removeFromBlacklist = function (userId, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RemoveFromBlackListInput(); modules.setUserId(userId); RongIMLib.RongIMClient.bridge.queryMsg(22, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.getFileToken = function (fileType, callback) { if (!(/(1|2|3|4)/.test(fileType.toString()))) { setTimeout(function () { callback.onError(RongIMLib.ErrorCode.QNTKN_FILETYPE_ERROR); }); return; } var modules = new RongIMLib.RongIMClient.Protobuf.GetQNupTokenInput(); modules.setType(fileType); RongIMLib.RongIMClient.bridge.queryMsg(30, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (data) { setTimeout(function () { callback.onSuccess(data); }); }, onError: function (errcode) { setTimeout(function () { callback.onError(errcode); }); } }, "GetQNupTokenOutput"); }; ServerDataProvider.prototype.getFileUrl = function (fileType, fileName, oriName, callback) { if (!(/(1|2|3|4)/.test(fileType.toString()))) { setTimeout(function () { callback.onError(RongIMLib.ErrorCode.QNTKN_FILETYPE_ERROR); }); return; } var modules = new RongIMLib.RongIMClient.Protobuf.GetQNdownloadUrlInput(); modules.setType(fileType); modules.setKey(fileName); if (oriName) { modules.setFileName(oriName); } RongIMLib.RongIMClient.bridge.queryMsg(31, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (data) { setTimeout(function () { callback.onSuccess(data); }); }, onError: function (errcode) { setTimeout(function () { callback.onError(errcode); }); } }, "GetQNdownloadUrlOutput"); }; ServerDataProvider.prototype.getPullSetting = function (callback) { var modules = new RongIMLib.RongIMClient.Protobuf.PullUserSettingInput(); var version = parseInt(RongIMLib.RongIMClient.sdkver); modules.setVersion(version); RongIMLib.RongIMClient.bridge.queryMsg('pullUS', RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (result) { result = result || {}; result.version = RongIMLib.MessageUtil.int64ToTimestamp(result.version); setTimeout(function () { callback.onSuccess(result); }); }, onError: function (errcode) { setTimeout(function () { callback.onError(errcode); }); } }, 'PullUserSettingOutput'); }; ServerDataProvider.prototype.setOfflineMessageDuration = function (duration, callback) { this.getPullSetting({ onSuccess: function (result) { /** * GetQNupTokenOutput 第一位为 int64, 第二位为 string, 与设置离线消息一致 * 为避免修改 Protobuf 带来的更新成本. 仅复用, 不重新命名 */ var modules = new RongIMLib.RongIMClient.Protobuf.GetQNupTokenOutput(); var version = result.version; modules.setDeadline(version); modules.setToken(duration + ''); RongIMLib.RongIMClient.bridge.queryMsg('setOfflineMsgDur', RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (data) { setTimeout(function () { callback.onSuccess(data); }); }, onError: function (errcode) { setTimeout(function () { callback.onError(errcode); }); } }); }, onError: callback.onError }); }; /* methodType 1 : 多客服(客服后台使用); 2 : 消息撤回 params.userIds : 定向消息接收者 */ ServerDataProvider.prototype.sendMessage = function (conversationType, targetId, messageContent, sendCallback, mentiondMsg, pushText, appData, methodType, params) { if (!RongIMLib.Bridge._client.channel) { setTimeout(function () { sendCallback.onError(RongIMLib.ErrorCode.RC_NET_UNAVAILABLE, null); }); return; } if (!RongIMLib.Bridge._client.channel.socket.socket.connected) { setTimeout(function () { sendCallback.onError(RongIMLib.ErrorCode.TIMEOUT, null); }); throw new Error("connect is timeout! postion:sendMessage"); } var isGroup = (conversationType == RongIMLib.ConversationType.DISCUSSION || conversationType == RongIMLib.ConversationType.GROUP); var modules = new RongIMLib.RongIMClient.Protobuf.UpStreamMessage(); if (mentiondMsg && isGroup) { modules.setSessionId(7); } else { modules.setSessionId(RongIMLib.RongIMClient.MessageParams[messageContent.messageName].msgTag.getMessageTag()); } pushText && modules.setPushText(pushText); appData && modules.setAppData(appData); if (isGroup && messageContent.messageName == RongIMLib.RongIMClient.MessageType["ReadReceiptResponseMessage"]) { var rspMsg = messageContent; if (rspMsg.receiptMessageDic) { var ids = []; for (var key in rspMsg.receiptMessageDic) { ids.push(key); } modules.setUserId(ids); } } if (isGroup && messageContent.messageName == RongIMLib.RongIMClient.MessageType["SyncReadStatusMessage"]) { modules.setUserId(RongIMLib.Bridge._client.userId); } params = params || {}; var userIds = params.userIds; if (userIds) { modules.setUserId(userIds); } var flag = 0; if (params.isPush || params.isVoipPush) { flag |= 0x01; } if (params.isFilerWhiteBlacklist) { flag |= 0x02; } modules.setConfigFlag(flag); modules.setClassname(RongIMLib.RongIMClient.MessageParams[messageContent.messageName].objectName); var encodedContent = messageContent.encode(); if (RongIMLib.RongUtil.getByteLength(encodedContent) > RongIMLib.RongIMClient.MaxMessageContentBytes) { setTimeout(function () { sendCallback.onError(RongIMLib.ErrorCode.RC_MSG_CONTENT_EXCEED_LIMIT); }); return; } modules.setContent(encodedContent); var content = modules.toArrayBuffer(); if (Object.prototype.toString.call(content) == "[object ArrayBuffer]") { content = [].slice.call(new Int8Array(content)); } var me = this, msg = new RongIMLib.Message(); var c = this.getConversation(conversationType, targetId); if (RongIMLib.RongIMClient.MessageParams[messageContent.messageName].msgTag.getMessageTag() == 3) { if (!c) { c = RongIMLib.RongIMClient.getInstance().createConversation(conversationType, targetId, ""); } c.sentTime = new Date().getTime(); c.sentStatus = RongIMLib.SentStatus.SENDING; c.senderUserName = ""; c.senderUserId = RongIMLib.Bridge._client.userId; c.notificationStatus = RongIMLib.ConversationNotificationStatus.DO_NOT_DISTURB; c.latestMessage = msg; c.unreadMessageCount = 0; RongIMLib.RongIMClient._dataAccessProvider.addConversation(c, { onSuccess: function (data) { } }); } RongIMLib.RongIMClient._memoryStore.converStore = c; msg.content = messageContent; msg.conversationType = conversationType; msg.senderUserId = RongIMLib.Bridge._client.userId; msg.objectName = RongIMLib.RongIMClient.MessageParams[messageContent.messageName].objectName; msg.targetId = targetId; msg.sentTime = new Date().getTime(); msg.messageDirection = RongIMLib.MessageDirection.SEND; msg.sentStatus = RongIMLib.SentStatus.SENT; msg.messageType = messageContent.messageName; RongIMLib.RongIMClient.bridge.pubMsg(conversationType.valueOf(), content, targetId, { onSuccess: function (data) { if (data && data.timestamp) { RongIMLib.RongIMClient._memoryStore.lastReadTime.set('converST_' + RongIMLib.Bridge._client.userId + conversationType + targetId, data.timestamp); } if ((conversationType == RongIMLib.ConversationType.DISCUSSION || conversationType == RongIMLib.ConversationType.GROUP) && messageContent.messageName == RongIMLib.RongIMClient.MessageType["ReadReceiptRequestMessage"]) { var reqMsg = msg.content; var sentkey = RongIMLib.Bridge._client.userId + reqMsg.messageUId + "SENT"; RongIMLib.RongIMClient._storageProvider.setItem(sentkey, JSON.stringify({ count: 0, dealtime: data.timestamp, userIds: {} })); } if (RongIMLib.RongIMClient.MessageParams[msg.messageType].msgTag.getMessageTag() == 3) { var cacheConversation = RongIMLib.RongIMClient._memoryStore.converStore; cacheConversation.sentStatus = msg.sentStatus; cacheConversation.latestMessage = msg; me.updateConversation(cacheConversation); var Conversation = RongIMLib.RongIMClient._dataAccessProvider.Conversation; Conversation._notify(RongIMLib.RongIMClient._memoryStore.conversationList); RongIMLib.RongIMClient._dataAccessProvider.addMessage(conversationType, targetId, msg, { onSuccess: function (ret) { msg = ret; msg.messageUId = data.messageUId; msg.sentTime = data.timestamp; msg.sentStatus = RongIMLib.SentStatus.SENT; msg.messageId = data.messageId; RongIMLib.RongIMClient._dataAccessProvider.updateMessage(msg); }, onError: function () { } }); } setTimeout(function () { cacheConversation && me.updateConversation(cacheConversation); msg.sentTime = data.timestamp; msg.messageUId = data.messageUId; sendCallback.onSuccess(msg); }); }, onError: function (errorCode, _msg) { msg.sentStatus = RongIMLib.SentStatus.FAILED; if (_msg) { msg.messageUId = _msg.messageUId; msg.sentTime = _msg.sentTime; } if (RongIMLib.RongIMClient.MessageParams[msg.messageType].msgTag.getMessageTag() == 3) { RongIMLib.RongIMClient._memoryStore.converStore.latestMessage = msg; } RongIMLib.RongIMClient._dataAccessProvider.addMessage(conversationType, targetId, msg, { onSuccess: function (ret) { msg.messageId = ret.messageId; RongIMLib.RongIMClient._dataAccessProvider.updateMessage(msg); }, onError: function () { } }); setTimeout(function () { sendCallback.onError(errorCode, msg); }); } }, null, methodType); sendCallback.onBefore && sendCallback.onBefore(RongIMLib.MessageIdHandler.messageId); msg.messageId = RongIMLib.MessageIdHandler.messageId + ""; }; ServerDataProvider.prototype.setConnectionStatusListener = function (listener) { if (RongIMLib.RongUtil.isObject(listener) && RongIMLib.RongUtil.isFunction(listener.onChanged)) { RongIMLib.RongIMClient.statusListeners.push(listener.onChanged); } }; ServerDataProvider.prototype.setOnReceiveMessageListener = function (listener) { if (RongIMLib.RongUtil.isObject(listener) && RongIMLib.RongUtil.isFunction(listener.onReceived)) { RongIMLib.RongIMClient.messageListeners.push(listener.onReceived); } }; ServerDataProvider.prototype.registerMessageType = function (messageType, objectName, messageTag, messageContent, searchProps) { if (!messageType) { throw new Error("messageType can't be empty,postion -> registerMessageType"); } if (!objectName) { throw new Error("objectName can't be empty,postion -> registerMessageType"); } if (Object.prototype.toString.call(messageContent) == "[object Array]") { var regMsg = RongIMLib.ModelUtil.modleCreate(messageContent, messageType); RongIMLib.RongIMClient.RegisterMessage[messageType] = regMsg; } else if (Object.prototype.toString.call(messageContent) == "[object Function]" || Object.prototype.toString.call(messageContent) == "[object Object]") { if (!messageContent.encode) { throw new Error("encode method has not realized or messageName is undefined-> registerMessageType"); } if (!messageContent.decode) { throw new Error("decode method has not realized -> registerMessageType"); } } else { throw new Error("The index of 3 parameter was wrong type must be object or function or array-> registerMessageType"); } registerMessageTypeMapping[objectName] = messageType; }; ServerDataProvider.prototype.registerMessageTypes = function (messages) { var types = []; var getProtos = function (proto) { var protos = []; for (var p in proto) { protos.push(p); } return protos; }; //转换消息为自定义消息参数格式 for (var name in messages) { var message = messages[name]; var proto = message.proto; var protos = getProtos(proto); var flag = message.flag || 3; var tag = RongIMLib.MessageTag.getTagByStatus(flag); flag = new RongIMLib.MessageTag(tag.isCounted, tag.isPersited); types.push({ type: name, name: message.name, flag: flag, protos: protos }); } var register = function (message) { var type = message.type; var name = message.name; var flag = message.flag; var protos = message.protos; RongIMLib.RongIMClient.registerMessageType(type, name, flag, protos); }; for (var i = 0, len = types.length; i < len; i++) { var message = types[i]; register(message); } }; ServerDataProvider.prototype.addConversation = function (conversation, callback) { var isAdd = true; for (var i = 0, len = RongIMLib.RongIMClient._memoryStore.conversationList.length; i < len; i++) { if (RongIMLib.RongIMClient._memoryStore.conversationList[i].conversationType === conversation.conversationType && RongIMLib.RongIMClient._memoryStore.conversationList[i].targetId === conversation.targetId) { // RongIMClient._memoryStore.conversationList[i] = conversation; RongIMLib.RongIMClient._memoryStore.conversationList.unshift(RongIMLib.RongIMClient._memoryStore.conversationList.splice(i, 1)[0]); isAdd = false; break; } } if (isAdd) { RongIMLib.RongIMClient._memoryStore.conversationList.unshift(conversation); } callback && callback.onSuccess(true); }; ServerDataProvider.prototype.updateConversation = function (conversation) { var conver; for (var i = 0, len = RongIMLib.RongIMClient._memoryStore.conversationList.length; i < len; i++) { var item = RongIMLib.RongIMClient._memoryStore.conversationList[i]; if (conversation.conversationType === item.conversationType && conversation.targetId === item.targetId) { conversation.conversationTitle && (item.conversationTitle = conversation.conversationTitle); conversation.senderUserName && (item.senderUserName = conversation.senderUserName); conversation.senderPortraitUri && (item.senderPortraitUri = conversation.senderPortraitUri); conversation.latestMessage && (item.latestMessage = conversation.latestMessage); conversation.sentStatus && (item.sentStatus = conversation.sentStatus); break; } } return conver; }; ServerDataProvider.prototype.removeConversation = function (conversationType, targetId, callback) { var mod = new RongIMLib.RongIMClient.Protobuf.RelationsInput(); mod.setType(conversationType); RongIMLib.RongIMClient.bridge.queryMsg(27, RongIMLib.MessageUtil.ArrayForm(mod.toArrayBuffer()), targetId, { onSuccess: function () { var isRemoved = false; var conversations = RongIMLib.RongIMClient._memoryStore.conversationList; var len = conversations.length; for (var i = 0; i < len; i++) { if (conversations[i].conversationType == conversationType && targetId == conversations[i].targetId) { conversations.splice(i, 1); isRemoved = true; break; } } isRemoved && RongIMLib.RongIMClient._dataAccessProvider.Conversation._notify(RongIMLib.RongIMClient._memoryStore.conversationList); callback.onSuccess(true); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.getMessage = function (messageId, callback) { callback.onSuccess(new RongIMLib.Message()); }; ServerDataProvider.prototype.addMessage = function (conversationType, targetId, message, callback) { if (callback) { callback.onSuccess(message); } }; ServerDataProvider.prototype.removeMessage = function (conversationType, targetId, messages, callback) { RongIMLib.RongIMClient.getInstance().deleteRemoteMessages(conversationType, targetId, messages, callback); }; ServerDataProvider.prototype.removeLocalMessage = function (conversationType, targetId, timestamps, callback) { callback.onSuccess(true); }; ServerDataProvider.prototype.updateMessage = function (message, callback) { if (callback) { callback.onSuccess(message); } }; ServerDataProvider.prototype.deleteRemoteMessages = function (conversationType, targetId, messages, callback) { if (!RongIMLib.RongIMClient.Protobuf.DeleteMsgInput) { throw new Error('SDK Protobuf version is too low'); } var modules = new RongIMLib.RongIMClient.Protobuf.DeleteMsgInput(); var msgs = []; RongIMLib.RongUtil.forEach(messages, function (msg) { msgs.push({ msgId: msg.messageUId, msgDataTime: msg.sentTime, direct: msg.messageDirection }); }); modules.setType(conversationType); modules.setConversationId(targetId); modules.setMsgs(msgs); RongIMLib.RongIMClient.bridge.queryMsg('delMsg', RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), targetId, { onSuccess: function (result) { callback.onSuccess(result); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }, 'DeleteMsgOutput'); }; ServerDataProvider.prototype.clearRemoteHistoryMessages = function (params, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.CleanHisMsgInput(); var conversationType = params.conversationType; var _topic = { 1: 'cleanPMsg', 2: 'cleanDMsg', 3: 'cleanGMsg', 5: 'cleanCMsg', 6: 'cleanSMsg' }; var topic = _topic[conversationType]; if (!topic) { callback.onError(RongIMLib.ErrorCode.CLEAR_HIS_TYPE_ERROR); return; } var timestamp = params.timestamp; if (typeof timestamp != 'number') { callback.onError(RongIMLib.ErrorCode.CLEAR_HIS_TIME_ERROR); return; } modules.setDataTime(timestamp); var targetId = params.targetId; modules.setTargetId(targetId); RongIMLib.RongIMClient.bridge.queryMsg(topic, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), targetId, { onSuccess: function (result) { callback.onSuccess(!result); }, onError: function (error) { // error 1 历史消息云存储没有开通、传入时间大于服务器时间 清除失败,1 与其他错误码冲突,所以自定义错误码返回 if (error == 1) { error = RongIMLib.ErrorCode.CLEAR_HIS_ERROR; } setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.clearHistoryMessages = function (params, callback) { this.clearRemoteHistoryMessages(params, callback); }; // 兼容老版本 ServerDataProvider.prototype.clearMessages = function (conversationType, targetId, callback) { }; ServerDataProvider.prototype.updateMessages = function (conversationType, targetId, key, value, callback) { var me = this; if (key == "readStatus") { if (RongIMLib.RongIMClient._memoryStore.conversationList.length > 0) { me.getConversationList({ onSuccess: function (list) { Array.forEach(list, function (conver) { if (conver.conversationType == conversationType && conver.targetId == targetId) { conver.unreadMessageCount = 0; } }); }, onError: function (errorCode) { setTimeout(function () { callback.onError(errorCode); }); } }, null); } } setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.getConversation = function (conversationType, targetId, callback) { var conver = null; for (var i = 0, len = RongIMLib.RongIMClient._memoryStore.conversationList.length; i < len; i++) { if (RongIMLib.RongIMClient._memoryStore.conversationList[i].conversationType == conversationType && RongIMLib.RongIMClient._memoryStore.conversationList[i].targetId == targetId) { conver = RongIMLib.RongIMClient._memoryStore.conversationList[i]; if (RongIMLib.RongUtil.supportLocalStorage()) { // var count = RongIMClient._storageProvider.getItem("cu" + Bridge._client.userId + conversationType + targetId); var count = RongIMLib.UnreadCountHandler.get(conversationType, targetId); if (conver.unreadMessageCount == 0) { conver.unreadMessageCount = Number(count); } } } } setTimeout(function () { callback && callback.onSuccess(conver); }); return conver; }; ServerDataProvider.prototype.filterConversations = function (types, list) { var conversaions = []; RongIMLib.RongUtil.forEach(types, function (type) { RongIMLib.RongUtil.forEach(list, function (conversation) { if (conversation.conversationType == type) { conversaions.push(conversation); } }); }); return conversaions; }; ServerDataProvider.prototype.getConversationList = function (callback, conversationTypes, count, isHidden) { var that = this; var isSync = RongIMLib.RongIMClient._memoryStore.isSyncRemoteConverList; var list = RongIMLib.RongIMClient._memoryStore.conversationList; var isLocalInclude = list.length > count; if (!isSync && isLocalInclude) { setTimeout(function () { var localList = list.slice(0, count); if (conversationTypes) { localList = that.filterConversations(conversationTypes, localList); } callback.onSuccess(localList); }); return; } RongIMLib.RongIMClient.getInstance().getRemoteConversationList({ onSuccess: function (list) { if (RongIMLib.RongUtil.supportLocalStorage()) { Array.forEach(RongIMLib.RongIMClient._memoryStore.conversationList, function (item) { // var count = RongIMClient._storageProvider.getItem("cu" + Bridge._client.userId + item.conversationType + item.targetId); var count = RongIMLib.UnreadCountHandler.get(item.conversationType, item.targetId); if (item.unreadMessageCount == 0) { item.unreadMessageCount = Number(count); } }); } RongIMLib.RongIMClient._memoryStore.isSyncRemoteConverList = false; setTimeout(function () { callback.onSuccess(list); }); }, onError: function (errorcode) { setTimeout(function () { callback.onError(errorcode); }); } }, conversationTypes, count, isHidden); }; ServerDataProvider.prototype.clearCache = function () { var memoryStore = RongIMLib.RongIMClient._memoryStore || {}; memoryStore.conversationList = []; memoryStore.isSyncRemoteConverList = true; }; ServerDataProvider.prototype.clearConversations = function (conversationTypes, callback) { Array.forEach(conversationTypes, function (conversationType) { Array.forEach(RongIMLib.RongIMClient._memoryStore.conversationList, function (conver) { if (conversationType == conver.conversationType) { RongIMLib.RongIMClient.getInstance().removeConversation(conver.conversationType, conver.targetId, { onSuccess: function () { }, onError: function () { } }); } }); }); setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.setMessageContent = function (messageId, content, objectname) { }; ; ServerDataProvider.prototype.setMessageSearchField = function (messageId, content, searchFiles) { }; ; ServerDataProvider.prototype.getHistoryMessages = function (conversationType, targetId, timestamp, count, callback, objectname, order) { var config = { objectname: objectname, order: order }; RongIMLib.RongIMClient.getInstance().getRemoteHistoryMessages(conversationType, targetId, timestamp, count, callback, config); }; ServerDataProvider.prototype.getTotalUnreadCount = function (callback, conversationTypes) { var count = RongIMLib.UnreadCountHandler.getAll(conversationTypes); callback.onSuccess(count); }; ServerDataProvider.prototype.getConversationUnreadCount = function (conversationTypes, callback) { var count = 0; Array.forEach(conversationTypes, function (converType) { Array.forEach(RongIMLib.RongIMClient._memoryStore.conversationList, function (conver) { if (conver.conversationType == converType) { count += conver.unreadMessageCount; } }); }); setTimeout(function () { callback.onSuccess(count); }); }; //由于 Web 端未读消息数按会话统计,撤回消息会导致未读数不准确,提供设置未读数接口,桌面版不实现此方法 ServerDataProvider.prototype.setUnreadCount = function (conversationType, targetId, count, sentTime) { sentTime = sentTime || new Date().getTime(); RongIMLib.UnreadCountHandler.set(conversationType, targetId, count, sentTime); }; ServerDataProvider.prototype.getUnreadCount = function (conversationType, targetId, callback) { var unreadCount = RongIMLib.UnreadCountHandler.get(conversationType, targetId); setTimeout(function () { callback.onSuccess(unreadCount || 0); }); }; ServerDataProvider.prototype.cleanMentioneds = function (conver) { if (conver) { conver.mentionedMsg = null; var targetId = conver.targetId; var conversationType = conver.conversationType; var mentioneds = RongIMLib.RongIMClient._storageProvider.getItem("mentioneds_" + RongIMLib.Bridge._client.userId + '_' + conversationType + '_' + targetId); if (mentioneds) { var info = JSON.parse(mentioneds); delete info[conversationType + "_" + targetId]; if (!RongIMLib.MessageUtil.isEmpty(info)) { RongIMLib.RongIMClient._storageProvider.setItem("mentioneds_" + RongIMLib.Bridge._client.userId + '_' + conversationType + '_' + targetId, JSON.stringify(info)); } else { RongIMLib.RongIMClient._storageProvider.removeItem("mentioneds_" + RongIMLib.Bridge._client.userId + '_' + conversationType + '_' + targetId); } } } }; ServerDataProvider.prototype.clearUnreadCountByTimestamp = function (conversationType, targetId, timestamp, callback) { setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.clearUnreadCount = function (conversationType, targetId, callback) { var me = this; // RongIMClient._storageProvider.removeItem("cu" + Bridge._client.userId + conversationType + targetId); RongIMLib.UnreadCountHandler.remove(conversationType, targetId); this.getConversation(conversationType, targetId, { onSuccess: function (conver) { conver = conver || new RongIMLib.Conversation(); var isNotifyConversation = conver.unreadMessageCount; if (conver) { conver.unreadMessageCount = 0; me.cleanMentioneds(conver); } setTimeout(function () { callback.onSuccess(true); isNotifyConversation && RongIMLib.RongIMClient._dataAccessProvider.Conversation._notify(RongIMLib.RongIMClient._memoryStore.conversationList); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.clearTotalUnreadCount = function (callback) { var list = RongIMLib.RongIMClient._memoryStore.conversationList; var me = this; var isNotifyConversation = false; if (list) { // 清除 mentioneds、清除 list 中的 unreadMessageCount for (var i = 0; i < list.length; i++) { var conver = list[i]; if (conver) { isNotifyConversation = conver.unreadMessageCount ? true : isNotifyConversation; conver.unreadMessageCount = 0; me.cleanMentioneds(conver); } } } RongIMLib.UnreadCountHandler.clear(); setTimeout(function () { callback.onSuccess(true); isNotifyConversation && RongIMLib.RongIMClient._dataAccessProvider.Conversation._notify(RongIMLib.RongIMClient._memoryStore.conversationList); }); }; ServerDataProvider.prototype.setConversationToTop = function (conversationType, targetId, isTop, callback) { var me = this; this.getConversation(conversationType, targetId, { onSuccess: function (conver) { conver.isTop = isTop; me.addConversation(conver, callback); setTimeout(function () { callback.onSuccess(true); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.getConversationNotificationStatus = function (params, callback) { var targetId = params.targetId; var conversationType = params.conversationType; var notification = RongIMLib.RongIMClient._memoryStore.notification; var getKey = function () { return conversationType + '_' + targetId; }; var key = getKey(); var status = notification[key]; if (typeof status == 'number') { callback.onSuccess(status); return; } var topics = { 1: 'qryPPush', 3: 'qryDPush' }; var topic = topics[conversationType]; if (!topic) { var error = 8001; callback.onError(error); return; } var modules = new RongIMLib.RongIMClient.Protobuf.BlockPushInput(); modules.setBlockeeId(targetId); var userId = RongIMLib.Bridge._client.userId; var success = function (status) { notification[key] = status; setTimeout(function () { callback.onSuccess(status); }); }; RongIMLib.RongIMClient.bridge.queryMsg(topic, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function (status) { success(status); }, onError: function (e) { if (e == 1) { success(e); } else { setTimeout(function () { callback.onError(e); }); } } }); }; ServerDataProvider.prototype.setConversationNotificationStatus = function (params, callback) { var conversationType = params.conversationType; var targetId = params.targetId; var status = params.status; var getKey = function () { return conversationType + '_' + status; }; var topics = { '1_1': 'blkPPush', '3_1': 'blkDPush', '1_0': 'unblkPPush', '3_0': 'unblkDPush' }; var key = getKey(); var notification = RongIMLib.RongIMClient._memoryStore.notification; notification[key] = status; var topic = topics[key]; if (!topic) { var error = 8001; setTimeout(function () { callback.onError(error); }); return; } var modules = new RongIMLib.RongIMClient.Protobuf.BlockPushInput(); modules.setBlockeeId(targetId); var userId = RongIMLib.Bridge._client.userId; RongIMLib.RongIMClient.bridge.queryMsg(topic, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function (status) { setTimeout(function () { callback.onSuccess(status); }); }, onError: function (e) { setTimeout(function () { callback.onError(e); }); } }); }; ServerDataProvider.prototype.getUserStatus = function (userId, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.GetUserStatusInput(); userId = RongIMLib.Bridge._client.userId; RongIMLib.RongIMClient.bridge.queryMsg(35, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function (status) { status = RongIMLib.RongInnerTools.convertUserStatus(status); setTimeout(function () { callback.onSuccess(status); }); }, onError: function (e) { setTimeout(function () { callback.onError(e); }); } }, 'GetUserStatusOutput'); // callback.onSuccess(new UserStatus()); }; ServerDataProvider.prototype.setUserStatus = function (status, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.SetUserStatusInput(); var userId = RongIMLib.Bridge._client.userId; if (status) { modules.setStatus(status); } RongIMLib.RongIMClient.bridge.queryMsg(36, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function (status) { setTimeout(function () { callback.onSuccess(true); }); }, onError: function (e) { setTimeout(function () { callback.onError(e); }); } }, 'SetUserStatusOutput'); }; ServerDataProvider.prototype.subscribeUserStatus = function (userIds, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.SubUserStatusInput(); var userId = RongIMLib.Bridge._client.userId; modules.setUserid(userIds); RongIMLib.RongIMClient.bridge.queryMsg(37, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function (status) { setTimeout(function () { callback && callback.onSuccess(true); }); }, onError: function (e) { setTimeout(function () { callback && callback.onError(e); }); } }, 'SubUserStatusOutput'); }; ServerDataProvider.prototype.setUserStatusListener = function (params, callback) { RongIMLib.RongIMClient.userStatusListener = callback; var userIds = params.userIds || []; if (userIds.length) { RongIMLib.RongIMClient._dataAccessProvider.subscribeUserStatus(userIds); } }; ServerDataProvider.prototype.clearListeners = function () { }; ServerDataProvider.prototype.setServerInfo = function (info) { }; ServerDataProvider.prototype.getUnreadMentionedMessages = function (conversationType, targetId) { return null; }; ServerDataProvider.prototype.setConversationHidden = function (conversationType, targetId, isHidden) { }; ServerDataProvider.prototype.setMessageExtra = function (messageId, value, callback) { setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.setMessageReceivedStatus = function (messageId, receivedStatus, callback) { setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.setMessageSentStatus = function (messageId, sentStatus, callback) { setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.getAllConversations = function (callback) { setTimeout(function () { callback.onSuccess([]); }); }; ServerDataProvider.prototype.getConversationByContent = function (keywords, callback) { setTimeout(function () { callback.onSuccess([]); }); }; ServerDataProvider.prototype.getMessagesFromConversation = function (conversationType, targetId, keywords, callback) { setTimeout(function () { callback.onSuccess([]); }); }; ServerDataProvider.prototype.searchConversationByContent = function (keyword, callback, conversationTypes) { setTimeout(function () { callback.onSuccess([]); }); }; ServerDataProvider.prototype.searchMessageByContent = function (conversationType, targetId, keyword, timestamp, count, total, callback) { setTimeout(function () { callback.onSuccess([]); }); }; ServerDataProvider.prototype.getDelaTime = function () { return RongIMLib.RongIMClient._memoryStore.deltaTime; }; ServerDataProvider.prototype.getCurrentConnectionStatus = function () { var client = RongIMLib.Bridge._client || {}; var channel = client.channel || {}; var status = RongIMLib.ConnectionStatus.CONNECTION_CLOSED; if (typeof channel.connectionStatus == 'number') { status = channel.connectionStatus; } return status; }; ServerDataProvider.prototype.getAgoraDynamicKey = function (engineType, channelName, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.VoipDynamicInput(); modules.setEngineType(engineType); modules.setChannelName(channelName); RongIMLib.RongIMClient.bridge.queryMsg(32, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (result) { setTimeout(function () { callback.onSuccess(result); }); }, onError: function (errorCode) { setTimeout(function () { callback.onError(errorCode); }); } }, "VoipDynamicOutput"); }; ServerDataProvider.prototype.setDeviceInfo = function (deviceId) { }; ServerDataProvider.prototype.setEnvironment = function (isPrivate) { }; ServerDataProvider.prototype.clearData = function () { return true; }; ServerDataProvider.prototype.getPublicServiceProfile = function (publicServiceType, publicServiceId, callback) { var profile = RongIMLib.RongIMClient._memoryStore.publicServiceMap.get(publicServiceType, publicServiceId); setTimeout(function () { callback.onSuccess(profile); }); }; ServerDataProvider.prototype.getRemotePublicServiceList = function (callback, pullMessageTime) { if (RongIMLib.RongIMClient._memoryStore.depend.openMp) { var modules = new RongIMLib.RongIMClient.Protobuf.PullMpInput(), self = this; if (!pullMessageTime) { modules.setTime(0); } else { modules.setTime(pullMessageTime); } modules.setMpid(""); RongIMLib.RongIMClient.bridge.queryMsg(28, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (data) { //TODO 找出最大时间 // self.lastReadTime.set(conversationType + targetId, MessageUtil.int64ToTimestamp(data.syncTime)); RongIMLib.RongIMClient._memoryStore.publicServiceMap.publicServiceList.length = 0; RongIMLib.RongIMClient._memoryStore.publicServiceMap.publicServiceList = data; setTimeout(function () { callback && callback.onSuccess(data); }); }, onError: function (errorCode) { setTimeout(function () { callback && callback.onError(errorCode); }); } }, "PullMpOutput"); } }; ServerDataProvider.prototype.getRTCUserInfoList = function (room, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcQueryListInput(); // 1 是正序,2是倒序 modules.setOrder(2); RongIMLib.RongIMClient.bridge.queryMsg("rtcUData", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function (result) { var users = {}; var list = result.list; RongIMLib.RongUtil.forEach(list, function (item) { var userId = item.userId; var tmpData = {}; RongIMLib.RongUtil.forEach(item.userData, function (data) { var key = data.key; var value = data.value; tmpData[key] = value; }); users[userId] = tmpData; }); callback.onSuccess(users); }, onError: function (errorCode) { callback.onError(errorCode); } }, "RtcUserListOutput"); }; ServerDataProvider.prototype.getRTCUserList = function (room, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcQueryListInput(); modules.setOrder(2); RongIMLib.RongIMClient.bridge.queryMsg("rtcUList", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function (result) { callback.onSuccess({ users: result.list }); }, onError: function (errorCode) { callback.onError(errorCode); } }, "RtcUserListOutput"); }; ServerDataProvider.prototype.setRTCUserInfo = function (room, info, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcValueInfo(); modules.setKey(info.key); modules.setValue(info.value); RongIMLib.RongIMClient.bridge.queryMsg("rtcUPut", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function () { callback.onSuccess(true); }, onError: function (errorCode) { callback.onError(errorCode); } }); }; ServerDataProvider.prototype.removeRTCUserInfo = function (room, info, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcKeyDeleteInput(); var keys = info.keys || []; if (!RongIMLib.RongUtil.isArray(keys)) { keys = [keys]; } modules.setKey(keys); RongIMLib.RongIMClient.bridge.queryMsg("rtcUDel", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function () { callback.onSuccess(true); }, onError: function (errorCode) { callback.onError(errorCode); } }); }; ServerDataProvider.prototype.getRTCRoomInfo = function (room, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcQueryListInput(); modules.setOrder(2); RongIMLib.RongIMClient.bridge.queryMsg("rtcRInfo", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function (result) { var room = { id: result.roomId, total: result.userCount }; RongIMLib.RongUtil.forEach(result.roomData, function (data) { room[data.key] = data.value; }); callback.onSuccess(room); }, onError: function (errorCode) { callback.onError(errorCode); } }, "RtcRoomInfoOutput"); }; ServerDataProvider.prototype.setRTCRoomInfo = function (room, info, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcValueInfo(); modules.setKey(info.key); modules.setValue(info.value); RongIMLib.RongIMClient.bridge.queryMsg("rtcRPut", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function () { callback.onSuccess(true); }, onError: function (errorCode) { callback.onError(errorCode); } }); }; ServerDataProvider.prototype.removeRTCRoomInfo = function (room, info, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcKeyDeleteInput(); var keys = info.keys || []; if (!RongIMLib.RongUtil.isArray(keys)) { keys = [keys]; } modules.setKey(keys); RongIMLib.RongIMClient.bridge.queryMsg("rtcRDel", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function () { callback.onSuccess(true); }, onError: function (errorCode) { callback.onError(errorCode); } }); }; ServerDataProvider.prototype.joinRTCRoom = function (room, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcInput(); var mode = room.mode || 0; modules.setRoomType(mode); if (room.broadcastType) { modules.setBroadcastType(room.broadcastType); } RongIMLib.RongIMClient.bridge.queryMsg("rtcRJoin_data", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function (result) { var users = {}; var list = result.list, token = result.token, sessionId = result.sessionId; RongIMLib.RongUtil.forEach(list, function (item) { var userId = item.userId; var tmpData = {}; RongIMLib.RongUtil.forEach(item.userData, function (data) { var key = data.key; var value = data.value; tmpData[key] = value; }); users[userId] = tmpData; }); callback.onSuccess({ users: users, token: token, sessionId: sessionId }); }, onError: function (errorCode) { callback.onError(errorCode); } }, "RtcUserListOutput"); }; ServerDataProvider.prototype.quitRTCRoom = function (room, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.SetUserStatusInput(); RongIMLib.RongIMClient.bridge.queryMsg("rtcRExit", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function () { callback.onSuccess(true); }, onError: function (errorCode) { callback.onError(errorCode); } }); }; ServerDataProvider.prototype.RTCPing = function (room, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcInput(); var mode = room.mode || 0; modules.setRoomType(mode); if (room.broadcastType) { modules.setBroadcastType(room.broadcastType); } RongIMLib.RongIMClient.bridge.queryMsg("rtcPing", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, callback); }; ServerDataProvider.prototype.setRTCData = function (roomId, key, value, isInner, apiType, callback, message) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcSetDataInput(); modules.setInterior(isInner); modules.setTarget(apiType); modules.setKey(key); modules.setValue(value); message = message || {}; var name = message.name; var content = message.content; if (name) { modules.setObjectName(name); } if (content) { if (!RongIMLib.RongUtil.isString(content)) { content = JSON.stringify(content); } modules.setContent(content); } RongIMLib.RongIMClient.bridge.queryMsg("rtcSetData", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), roomId, callback, "RtcOutput"); }; ServerDataProvider.prototype.getRTCData = function (roomId, keys, isInner, apiType, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcDataInput(); modules.setInterior(isInner); modules.setTarget(apiType); modules.setKey(keys); RongIMLib.RongIMClient.bridge.queryMsg("rtcQryData", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), roomId, { onSuccess: function (result) { var props = {}; var list = result.outInfo; RongIMLib.RongUtil.forEach(list, function (item) { props[item.key] = item.value; }); callback.onSuccess(props); }, onError: callback.onError }, "RtcQryOutput"); }; ServerDataProvider.prototype.removeRTCData = function (roomId, keys, isInner, apiType, callback, message) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcDataInput(); modules.setInterior(isInner); modules.setTarget(apiType); modules.setKey(keys); message = message || {}; var name = message.name; var content = message.content; if (name) { modules.setObjectName(name); } if (content) { if (!RongIMLib.RongUtil.isString(content)) { content = JSON.stringify(content); } modules.setContent(content); } RongIMLib.RongIMClient.bridge.queryMsg("rtcDelData", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), roomId, callback, "RtcOutput"); }; ServerDataProvider.prototype.setRTCUserData = function (roomId, key, value, isInner, callback, message) { this.setRTCData(roomId, key, value, isInner, RongIMLib.RTCAPIType.PERSON, callback, message); }; ServerDataProvider.prototype.getRTCUserData = function (roomId, keys, isInner, callback, message) { this.getRTCData(roomId, keys, isInner, RongIMLib.RTCAPIType.PERSON, callback); }; ServerDataProvider.prototype.removeRTCUserData = function (roomId, keys, isInner, callback, message) { this.removeRTCData(roomId, keys, isInner, RongIMLib.RTCAPIType.PERSON, callback, message); }; ServerDataProvider.prototype.setRTCRoomData = function (roomId, key, value, isInner, callback, message) { this.setRTCData(roomId, key, value, isInner, RongIMLib.RTCAPIType.ROOM, callback, message); }; ServerDataProvider.prototype.getRTCRoomData = function (roomId, keys, isInner, callback, message) { this.getRTCData(roomId, keys, isInner, RongIMLib.RTCAPIType.ROOM, callback); }; ServerDataProvider.prototype.removeRTCRoomData = function (roomId, keys, isInner, callback, message) { this.removeRTCData(roomId, keys, isInner, RongIMLib.RTCAPIType.ROOM, callback, message); }; // 信令 SDK 新增 ServerDataProvider.prototype.setRTCOutData = function (roomId, data, type, callback, message) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcSetOutDataInput(); modules.setTarget(type); if (!RongIMLib.RongUtil.isArray(data)) { data = [data]; } for (var i = 0; i < data.length; i++) { var item = data[i]; if (item.key) { item.key = item.key.toString(); } if (item.value) { item.value = item.value.toString(); } } modules.setValueInfo(data); message = message || {}; var name = message.name; var content = message.content; if (name) { modules.setObjectName(name); } if (content) { if (!RongIMLib.RongUtil.isString(content)) { content = JSON.stringify(content); } modules.setContent(content); } RongIMLib.RongIMClient.bridge.queryMsg("rtcSetOutData", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), roomId, callback, "RtcOutput"); }; // 信令 SDK 新增 ServerDataProvider.prototype.getRTCOutData = function (roomId, userIds, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcQryUserOutDataInput(); modules.setUserId(userIds); RongIMLib.RongIMClient.bridge.queryMsg("rtcQryUserOutData", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), roomId, callback, "RtcUserOutDataOutput"); }; ServerDataProvider.prototype.getNavi = function () { var navi = RongIMLib.RongIMClient._storageProvider.getItem("fullnavi") || "{}"; return JSON.parse(navi); }; ServerDataProvider.prototype.getRTCToken = function (room, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcInput(); var mode = room.mode || 0; modules.setRoomType(mode); if (room.broadcastType) { modules.setBroadcastType(room.broadcastType); } RongIMLib.RongIMClient.bridge.queryMsg("rtcToken", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function (result) { callback.onSuccess(result); }, onError: function (errorCode) { callback.onError(errorCode); } }, "RtcTokenOutput"); }; ServerDataProvider.prototype.setRTCState = function (room, content, callback) { // MCFollowInput 为 PB 复用,字段:一个必传 string(第一位) var modules = new RongIMLib.RongIMClient.Protobuf.MCFollowInput(); var report = content.report; modules.setId(report); RongIMLib.RongIMClient.bridge.queryMsg("rtcUserState", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function (result) { callback.onSuccess(result); }, onError: function (errorCode) { callback.onError(errorCode); } }, "RtcOutput"); }; return ServerDataProvider; })(); RongIMLib.ServerDataProvider = ServerDataProvider; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var VCDataProvider = (function () { function VCDataProvider(addon) { this.Conversation = { watcher: new RongIMLib.Observer(), watch: function (_watcher) { }, unwatch: function (_watcher) { }, _notify: function (conversationList) { } }; // C++ 需要的 SDK 版本号 this.version = '2.8.27'; this.userId = ""; this.useConsole = false; this.appKey = ""; this.token = ""; this.connectionStatus = RongIMLib.ConnectionStatus.DISCONNECTED; this.addon = addon; } VCDataProvider.prototype.init = function (appKey, config) { this.appKey = appKey; this.useConsole && console.log("init"); config = config || {}; config.version = this.version; var sdkInfo = this.addon.initWithAppkey(appKey, config.dbPath, config); if (sdkInfo) { sdkInfo = JSON.parse(sdkInfo); } // 0 不存不计数 1 只存不计数 3 存且计数 this.addon.registerMessageType("RC:VcMsg", 3); this.addon.registerMessageType("RC:ImgTextMsg", 3); this.addon.registerMessageType("RC:FileMsg", 3); this.addon.registerMessageType("RC:LBSMsg", 3); this.addon.registerMessageType("RC:PSImgTxtMsg", 3); this.addon.registerMessageType("RC:PSMultiImgTxtMsg", 3); this.addon.registerMessageType("RCJrmf:RpMsg", 3); this.addon.registerMessageType("RCJrmf:RpOpendMsg", 1); this.addon.registerMessageType("RC:GrpNtf", 1); this.addon.registerMessageType("RC:DizNtf", 0); this.addon.registerMessageType("RC:InfoNtf", 0); this.addon.registerMessageType("RC:ContactNtf", 0); this.addon.registerMessageType("RC:ProfileNtf", 0); this.addon.registerMessageType("RC:CmdNtf", 0); this.addon.registerMessageType("RC:CmdMsg", 0); this.addon.registerMessageType("RC:TypSts", 0); this.addon.registerMessageType("RC:CsChaR", 0); this.addon.registerMessageType("RC:CsHsR", 0); this.addon.registerMessageType("RC:CsEnd", 0); this.addon.registerMessageType("RC:CsSp", 0); this.addon.registerMessageType("RC:CsUpdate", 0); this.addon.registerMessageType("RC:CsContact", 0); this.addon.registerMessageType("RC:ReadNtf", 0); this.addon.registerMessageType("RC:VCAccept", 0); this.addon.registerMessageType("RC:VCRinging", 0); this.addon.registerMessageType("RC:VCSummary", 0); this.addon.registerMessageType("RC:VCHangup", 0); this.addon.registerMessageType("RC:VCInvite", 0); this.addon.registerMessageType("RC:VCModifyMedia", 0); this.addon.registerMessageType("RC:VCModifyMem", 0); this.addon.registerMessageType("RC:PSCmd", 0); this.addon.registerMessageType("RC:RcCmd", 0); this.addon.registerMessageType("RC:SRSMsg", 0); this.addon.registerMessageType("RC:RRReqMsg", 0); this.addon.registerMessageType("RC:RRRspMsg", 0); return sdkInfo; }; VCDataProvider.prototype.connect = function (token, callback, userId, serverConf) { this.useConsole && console.log("connect"); this.userId = userId; this.connectCallback = callback; RongIMLib.Bridge._client = { userId: userId, token: token }; serverConf = serverConf || {}; var openmp = !!serverConf.openMp; var openus = !!serverConf.openUS; if (serverConf.type) { this.addon.setEnvironment(true); } var me = this; // this.addon.connectWithToken(token, userId, serverConf.serverList, openmp, openus); this.addon.connectWithToken(token, userId, function (userId) { me.userId = userId; RongIMLib.Bridge._client.userId = userId; }); }; VCDataProvider.prototype.setServerInfo = function (info) { 'setServerInfo' in this.addon && this.addon.setServerInfo(info.navi); }; VCDataProvider.prototype.logout = function () { this.useConsole && console.log("logout"); this.disconnect(); }; VCDataProvider.prototype.disconnect = function () { this.useConsole && console.log("disconnect"); this.connectionStatus = RongIMLib.ConnectionStatus.DISCONNECTED; this.addon.disconnect(true); }; VCDataProvider.prototype.clearListeners = function () { this.addon.setOnReceiveStatusListener(); this.addon.setConnectionStatusListener(); this.addon.setOnReceiveMessageListener(); }; VCDataProvider.prototype.clearData = function () { this.useConsole && console.log("clearData"); return this.addon.clearData(); }; VCDataProvider.prototype.setConnectionStatusListener = function (listener) { var me = this; /** ConnectionStatus_TokenIncorrect = 31004, ConnectionStatus_Connected = 0, ConnectionStatus_KickedOff = 6, // 其他设备登录 ConnectionStatus_Connecting = 10,// 连接中 ConnectionStatus_SignUp = 12, // 未登录 ConnectionStatus_NetworkUnavailable = 1, // 连接断开 ConnectionStatus_ServerInvalid = 8, // 断开 ConnectionStatus_ValidateFailure = 9,//断开 ConnectionStatus_Unconnected = 11,//断开 ConnectionStatus_DisconnExecption = 31011 //断开 RC_NAVI_MALLOC_ERROR = 30000,//断开 RC_NAVI_NET_UNAVAILABLE= 30002,//断开 RC_NAVI_SEND_FAIL = 30004,//断开 RC_NAVI_REQ_TIMEOUT = 30005,//断开 RC_NAVI_RECV_FAIL = 30006,//断开 RC_NAVI_RESOURCE_ERROR = 30007,//断开 RC_NAVI_NODE_NOT_FOUND = 30008,//断开 RC_NAVI_DNS_ERROR = 30009,//断开 */ me.connectListener = listener; this.useConsole && console.log("setConnectionStatusListener"); me.addon && me.addon.setConnectionStatusListener(function (result) { var isCurrentConnected = me.connectionStatus === RongIMLib.ConnectionStatus.CONNECTED; var code = result; switch (result) { case 10: code = RongIMLib.ConnectionStatus.CONNECTING; break; case 31004: setTimeout(function () { me.connectCallback.onTokenIncorrect(); }); return; case 1: case 8: case 9: case 11: case 12: case 31011: case 30000: case 30002: case 30010: if (!isCurrentConnected) { return; } code = RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE; break; case 0: case 33005: code = RongIMLib.ConnectionStatus.CONNECTED; setTimeout(function () { me.connectCallback.onSuccess(me.userId); }); break; case 6: code = RongIMLib.ConnectionStatus.KICKED_OFFLINE_BY_OTHER_CLIENT; break; default: code = result; break; } me.connectionStatus = code; setTimeout(function () { listener.onChanged(code); }); }); }; VCDataProvider.prototype.setOnReceiveMessageListener = function (listener) { var me = this, localCount = 0; me.messageListener = listener; this.useConsole && console.log("setOnReceiveMessageListener"); me.addon && me.addon.setOnReceiveMessageListener(function (result, leftCount, offline, hasMore) { var message = me.buildMessage(result); message.offLineMessage = offline; setTimeout(function () { var voipMsgTypes = ['AcceptMessage', 'RingingMessage', 'HungupMessage', 'InviteMessage', 'MediaModifyMessage', 'MemberModifyMessage']; var isVoIPMsg = voipMsgTypes.indexOf(message.messageType) > -1; if (isVoIPMsg) { RongIMLib.RongIMClient._voipProvider && RongIMLib.RongIMClient._voipProvider.onReceived(message); } else if (message.conversationType == 12) { RongIMLib.RongIMClient.RTCListener(message); RongIMLib.RongIMClient.RTCInnerListener(message); RongIMLib.RongIMClient.RTCSignalLisener(message); } else { listener.onReceived(message, leftCount, hasMore); } }); }); }; VCDataProvider.prototype.sendTypingStatusMessage = function (conversationType, targetId, messageName, sendCallback) { var me = this; this.useConsole && console.log("sendTypingStatusMessage"); if (messageName in RongIMLib.RongIMClient.MessageParams) { me.sendMessage(conversationType, targetId, RongIMLib.TypingStatusMessage.obtain(RongIMLib.RongIMClient.MessageParams[messageName].objectName, ""), { onSuccess: function () { setTimeout(function () { sendCallback.onSuccess(); }); }, onError: function (errorCode) { setTimeout(function () { sendCallback.onError(errorCode, null); }); }, onBefore: function () { } }); } }; VCDataProvider.prototype.setMessageStatus = function (conversationType, targetId, timestamp, status, callback) { this.addon.updateMessageReceiptStatus(conversationType, targetId, timestamp); callback.onSuccess(true); }; VCDataProvider.prototype.sendTextMessage = function (conversationType, targetId, content, sendMessageCallback) { var msgContent = RongIMLib.TextMessage.obtain(content); this.useConsole && console.log("sendTextMessage"); this.sendMessage(conversationType, targetId, msgContent, sendMessageCallback); }; VCDataProvider.prototype.getRemoteHistoryMessages = function (conversationType, targetId, timestamp, count, callback, config) { try { var me = this; me.useConsole && console.log("getRemoteHistoryMessages"); me.addon.getRemoteHistoryMessages(conversationType, targetId, timestamp ? timestamp : 0, count, function (ret, hasMore) { var list = ret ? JSON.parse(ret).list : [], msgs = []; list.reverse(); for (var i = 0, len = list.length; i < len; i++) { var message = me.buildMessage(list[i].obj); message.sentStatus = RongIMLib.SentStatus.READ; msgs[i] = message; } callback.onSuccess(msgs, hasMore ? true : false); }, function (errorCode) { callback.onError(errorCode); }); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.getRemoteConversationList = function (callback, conversationTypes, count, isGetHiddenConvers) { try { this.useConsole && console.log("getRemoteConversationList"); var converTypes = conversationTypes || [1, 2, 3, 4, 5, 6, 7, 8]; var result = this.addon.getConversationList(converTypes); var list = JSON.parse(result).list, convers = [], me = this, index = 0; list.reverse(); isGetHiddenConvers = typeof isGetHiddenConvers === 'boolean' ? isGetHiddenConvers : false; for (var i = 0, len_1 = list.length; i < len_1; i++) { var tmpObj = list[i].obj, obj = JSON.parse(tmpObj); if (obj != "") { if (obj.isHidden == 1 && isGetHiddenConvers) { continue; } convers[index] = me.buildConversation(tmpObj); index++; } } convers.reverse(); var len = convers.length; count = count || len; if (len > count) { convers.length = count; } callback.onSuccess(convers); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.removeConversation = function (conversationType, targetId, callback) { try { this.useConsole && console.log("removeConversation"); this.addon.removeConversation(conversationType, targetId); var conversations = RongIMLib.RongIMClient._memoryStore.conversationList; var len = conversations.length; for (var i = 0; i < len; i++) { if (conversations[i].conversationType == conversationType && targetId == conversations[i].targetId) { conversations.splice(i, 1); break; } } callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.joinChatRoom = function (chatRoomId, messageCount, callback) { this.useConsole && console.log("joinChatRoom"); this.addon.joinChatRoom(chatRoomId, messageCount, function () { callback.onSuccess(); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.quitChatRoom = function (chatRoomId, callback) { this.useConsole && console.log("quitChatRoom"); this.addon.quitChatRoom(chatRoomId, function () { callback.onSuccess(); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.setChatroomEntry = function (chatroomId, chatroomEntry, callback) { }; VCDataProvider.prototype.forceSetChatroomEntry = function (chatroomId, chatroomEntry, callback) { }; VCDataProvider.prototype.getChatroomEntry = function (chatroomId, key, callback) { }; VCDataProvider.prototype.getAllChatroomEntries = function (chatroomId, callback) { }; VCDataProvider.prototype.removeChatroomEntry = function (chatroomId, chatroomEntry, callback) { }; VCDataProvider.prototype.forceRemoveChatroomEntry = function (chatroomId, chatroomEntry, callback) { }; VCDataProvider.prototype.pullChatroomEntry = function (chatroomId, time, callback) { }; VCDataProvider.prototype.addToBlacklist = function (userId, callback) { this.useConsole && console.log("addToBlacklist"); this.addon.addToBlacklist(userId, function () { callback.onSuccess(); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.getBlacklist = function (callback) { this.useConsole && console.log("getBlacklist"); this.addon.getBlacklist(function (blacklistors) { callback.onSuccess(blacklistors); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.getBlacklistStatus = function (userId, callback) { this.useConsole && console.log("getBlacklistStatus"); this.addon.getBlacklistStatus(userId, function (result) { callback.onSuccess(result); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.removeFromBlacklist = function (userId, callback) { this.useConsole && console.log("removeFromBlacklist"); this.addon.removeFromBlacklist(userId, function () { callback.onSuccess(); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.sendMessage = function (conversationType, targetId, messageContent, sendCallback, mentiondMsg, pushText, appData, methodType, params) { var me = this, users = []; me.useConsole && console.log("sendMessage"); params = params || {}; var isGroup = (conversationType == RongIMLib.ConversationType.DISCUSSION || conversationType == RongIMLib.ConversationType.GROUP); if (isGroup && messageContent.messageName == RongIMLib.RongIMClient.MessageType["ReadReceiptResponseMessage"]) { users = []; var rspMsg = messageContent; if (rspMsg.receiptMessageDic) { var ids = []; for (var key in rspMsg.receiptMessageDic) { ids.push(key); } users = ids; } } if (isGroup && messageContent.messageName == RongIMLib.RongIMClient.MessageType["SyncReadStatusMessage"]) { users = []; users.push(me.userId); } var userIds = params.userIds; if (isGroup && userIds) { users = userIds; } var msg = me.addon.sendMessage(conversationType, targetId, RongIMLib.RongIMClient.MessageParams[messageContent.messageName].objectName, messageContent.encode(), pushText || "", appData || "", function (progress) { }, function (message, code) { var msg = me.buildMessage(message); var errorCode = RongIMLib.ErrorCode.SENSITIVE_REPLACE; if (code == errorCode) { return sendCallback.onError(errorCode, msg); } sendCallback.onSuccess(msg); }, function (message, code) { sendCallback.onError(code, me.buildMessage(message)); }, users, mentiondMsg); var tempMessage = JSON.parse(msg); sendCallback.onBefore && sendCallback.onBefore(tempMessage.messageId); RongIMLib.MessageIdHandler.messageId = tempMessage.messageId; }; VCDataProvider.prototype.registerMessageType = function (messageType, objectName, messageTag, messageContent, searchProps) { this.useConsole && console.log("registerMessageType"); this.addon.registerMessageType(objectName, messageTag.getMessageTag(), searchProps); var regMsg = RongIMLib.ModelUtil.modleCreate(messageContent, messageType); RongIMLib.RongIMClient.RegisterMessage[messageType] = regMsg; RongIMLib.RongIMClient.RegisterMessage[messageType].messageName = messageType; registerMessageTypeMapping[objectName] = messageType; RongIMLib.RongIMClient.MessageType[messageType] = messageType; RongIMLib.RongIMClient.MessageParams[messageType] = { objectName: objectName, msgTag: messageTag }; typeMapping[objectName] = messageType; }; VCDataProvider.prototype.registerMessageTypes = function (messages) { var types = []; var getProtos = function (proto) { var protos = []; for (var p in proto) { protos.push(p); } return protos; }; //转换消息为自定义消息参数格式 for (var name in messages) { var message = messages[name]; var proto = message.proto; var protos = getProtos(proto); var flag = message.flag || 3; var tag = RongIMLib.MessageTag.getTagByStatus(flag); flag = new RongIMLib.MessageTag(tag.isCounted, tag.isPersited); types.push({ type: name, name: message.name, flag: flag, protos: protos }); } var register = function (message) { var type = message.type; var name = message.name; var flag = message.flag; var protos = message.protos; RongIMLib.RongIMClient.registerMessageType(type, name, flag, protos); }; for (var i = 0, len = types.length; i < len; i++) { var message = types[i]; register(message); } }; VCDataProvider.prototype.addMessage = function (conversationType, targetId, message, callback) { this.useConsole && console.log("addMessage"); var direction = message.direction; var msg = this.addon.insertMessage(conversationType, targetId, message.senderUserId, message.objectName, JSON.stringify(message.content), function () { callback.onSuccess(me.buildMessage(msg)); }, function () { callback.onError(RongIMLib.ErrorCode.MSG_INSERT_ERROR); }, direction), me = this; }; VCDataProvider.prototype.removeMessage = function (conversationType, targetId, messages, callback) { }; VCDataProvider.prototype.deleteRemoteMessages = function (conversationType, targetId, messages, callback) { }; VCDataProvider.prototype.removeLocalMessage = function (conversationType, targetId, timestamps, callback) { try { this.useConsole && console.log("removeLocalMessage"); this.addon.deleteMessages(timestamps); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.getMessage = function (messageId, callback) { try { this.useConsole && console.log("getMessage"); var msg = this.buildMessage(this.addon.getMessage(messageId)); callback.onSuccess(msg); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.clearMessages = function (conversationType, targetId, callback) { try { this.useConsole && console.log("clearMessages"); this.addon.clearMessages(conversationType, targetId); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; // Web 端接口,桌面版无需实现 VCDataProvider.prototype.setUnreadCount = function (conversationType, targetId, count) { }; VCDataProvider.prototype.getConversation = function (conversationType, targetId, callback) { try { this.useConsole && console.log("getConversation"); var ret = this.addon.getConversation(conversationType, targetId); callback.onSuccess(this.buildConversation(ret)); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.getConversationList = function (callback, conversationTypes, count, isGetHiddenConvers) { this.useConsole && console.log("getConversationList"); this.getRemoteConversationList(callback, conversationTypes, count, isGetHiddenConvers); }; VCDataProvider.prototype.clearCache = function () { var memoryStore = RongIMLib.RongIMClient._memoryStore || {}; memoryStore.conversationList = []; memoryStore.isSyncRemoteConverList; }; VCDataProvider.prototype.clearConversations = function (conversationTypes, callback) { try { this.useConsole && console.log("clearConversations"); this.addon.clearConversations(); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.setMessageContent = function (messageId, content, objectName) { content = JSON.stringify(content); this.addon.setMessageContent(messageId, content, objectName); }; VCDataProvider.prototype.setMessageSearchField = function (messageId, content, searchFiles) { this.addon.setMessageSearchField(messageId, content, searchFiles); }; VCDataProvider.prototype.getHistoryMessages = function (conversationType, targetId, timestamp, count, callback, objectname, direction) { this.useConsole && console.log("getHistoryMessages"); if (count <= 0) { callback.onError(RongIMLib.ErrorCode.TIMEOUT); return; } objectname = objectname || ''; direction = typeof direction == 'undefined' || direction; try { var ret = this.addon.getHistoryMessages(conversationType, targetId, timestamp ? timestamp : 0, count, objectname, direction); var list = ret ? JSON.parse(ret).list : [], msgs = [], me = this; list.reverse(); for (var i = 0, len = list.length; i < len; i++) { var message = me.buildMessage(list[i].obj); msgs[i] = message; } callback.onSuccess(msgs, len == count); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.clearRemoteHistoryMessages = function (params, callback) { var conversationType = params.conversationType; var targetId = params.targetId; var timestamp = params.timestamp; var _topic = { 1: true, 2: true, 3: true, 5: true, 6: true }; var topic = _topic[conversationType]; if (!topic) { callback.onError(RongIMLib.ErrorCode.CLEAR_HIS_TYPE_ERROR); return; } if (typeof timestamp != 'number') { callback.onError(RongIMLib.ErrorCode.CLEAR_HIS_TIME_ERROR); return; } this.addon.clearRemoteHistoryMessages(+conversationType, targetId, timestamp, function () { callback.onSuccess(true); }, function (errorCode) { if (errorCode == 1) { // 没有开通历史消息云存储 errorCode = RongIMLib.ErrorCode.CLEAR_HIS_ERROR; } callback.onError(errorCode); }); }; VCDataProvider.prototype.clearHistoryMessages = function (params, callback) { var conversationType = +params.conversationType; var targetId = params.targetId; try { this.addon.clearMessages(conversationType, targetId); var isSuccess = true; callback.onSuccess(isSuccess); } catch (e) { console.log(e); callback.onError(RongIMLib.ErrorCode.CLEAR_HIS_ERROR); } }; VCDataProvider.prototype.getTotalUnreadCount = function (callback, conversationTypes) { try { var result; this.useConsole && console.log("getTotalUnreadCount"); if (conversationTypes) { result = this.addon.getTotalUnreadCount(conversationTypes); } else { result = this.addon.getTotalUnreadCount(); } callback.onSuccess(result); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.getConversationUnreadCount = function (conversationTypes, callback) { this.useConsole && console.log("getConversationUnreadCount"); this.getTotalUnreadCount(callback, conversationTypes); }; VCDataProvider.prototype.getUnreadCount = function (conversationType, targetId, callback) { try { this.useConsole && console.log("getUnreadCount"); var result = this.addon.getUnreadCount(conversationType, targetId); callback.onSuccess(result); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.clearUnreadCount = function (conversationType, targetId, callback) { try { this.useConsole && console.log("clearUnreadCount"); var result = this.addon.clearUnreadCount(conversationType, targetId); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.clearTotalUnreadCount = function (callback) { this.useConsole && console.log("clearTotalUnreadCount"); }; VCDataProvider.prototype.clearUnreadCountByTimestamp = function (conversationType, targetId, timestamp, callback) { try { this.useConsole && console.log("clearUnreadCountByTimestamp"); var result = this.addon.clearUnreadCountByTimestamp(conversationType, targetId, timestamp); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.setConversationToTop = function (conversationType, targetId, isTop, callback) { try { this.useConsole && console.log("setConversationToTop"); this.addon.setConversationToTop(conversationType, targetId, isTop); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.setConversationHidden = function (conversationType, targetId, isHidden) { this.addon.setConversationHidden(conversationType, targetId, isHidden); }; VCDataProvider.prototype.setMessageReceivedStatus = function (messageId, receivedStatus, callback) { try { this.useConsole && console.log("setMessageReceivedStatus"); this.addon.setMessageReceivedStatus(messageId, receivedStatus); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.setMessageSentStatus = function (messageId, sentStatus, callback) { try { this.useConsole && console.log("setMessageSentStatus"); this.addon.setMessageSentStatus(messageId, sentStatus); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.getFileToken = function (fileType, callback) { this.useConsole && console.log("getFileToken"); this.addon.getUploadToken(fileType, function (token) { callback.onSuccess({ token: token }); }, function (errorCode) { callback.onError(errorCode); }); }; VCDataProvider.prototype.getFileUrl = function (fileType, fileName, oriName, callback) { this.useConsole && console.log("getFileUrl"); this.addon.getDownloadUrl(fileType, fileName, oriName, function (url) { callback.onSuccess({ downloadUrl: url }); }, function (errorCode) { callback.onError(errorCode); }); }; VCDataProvider.prototype.getPullSetting = function (callback) { this.useConsole && console.log("getPullSetting"); }; VCDataProvider.prototype.setOfflineMessageDuration = function (duration, callback) { this.useConsole && console.log("setOfflineMessageDuration"); }; VCDataProvider.prototype.searchConversationByContent = function (keyword, callback, conversationTypes) { var converTypes = []; if (typeof conversationTypes == 'undefined') { converTypes = [1, 2, 3, 4, 5, 6, 7]; } else { converTypes = conversationTypes; } try { this.useConsole && console.log("searchConversationByContent"); var result = this.addon.searchConversationByContent(converTypes, keyword); var list = JSON.parse(result).list, convers = [], me = this; list.reverse(); for (var i = 0, len = list.length; i < len; i++) { convers[i] = me.buildConversation(list[i].obj); } callback.onSuccess(convers); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.searchMessageByContent = function (conversationType, targetId, keyword, timestamp, count, total, callback) { var me = this; try { this.useConsole && console.log("searchMessageByContent"); this.addon.searchMessageByContent(conversationType, targetId, keyword, timestamp, count, total, function (ret, matched) { var list = ret ? JSON.parse(ret).list : [], msgs = []; list.reverse(); for (var i = 0, len = list.length; i < len; i++) { msgs[i] = me.buildMessage(list[i].obj); } callback.onSuccess(msgs, matched); }); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.getChatRoomInfo = function (chatRoomId, count, order, callback) { this.useConsole && console.log("getChatRoomInfo"); this.addon.getChatroomInfo(chatRoomId, count, order, function (ret, count) { var list = ret ? JSON.parse(ret).list : [], chatRoomInfo = { userInfos: [], userTotalNums: count }; if (list.length > 0) { for (var i = 0, len = list.length; i < len; i++) { chatRoomInfo.userInfos.push(JSON.parse(list[i].obj)); } } callback.onSuccess(chatRoomInfo); }, function (errcode) { callback.onError(errcode); }); }; VCDataProvider.prototype.setChatroomHisMessageTimestamp = function (chatRoomId, timestamp) { }; VCDataProvider.prototype.getChatRoomHistoryMessages = function (chatRoomId, count, order, callback) { }; VCDataProvider.prototype.getDelaTime = function () { return this.addon.getDeltaTime(); }; VCDataProvider.prototype.getUserStatus = function (userId, callback) { var me = this; this.addon.getUserStatus(userId, function (status) { var entity = RongIMLib.RongInnerTools.convertUserStatus({ status: status, userId: '' }); callback.onSuccess(entity); }, function (code) { callback.onError(code); }); }; VCDataProvider.prototype.setUserStatus = function (status, callback) { this.addon.setUserStatus(status, function () { callback.onSuccess(true); }, function (code) { callback.onError(code); }); }; VCDataProvider.prototype.subscribeUserStatus = function (userIds, callback) { this.addon.subscribeUserStatus(userIds, function () { callback && callback.onSuccess(true); }, function (code) { callback && callback.onError(code); }); }; VCDataProvider.prototype.setUserStatusListener = function (params, callback) { var me = this; this.addon.setOnReceiveStatusListener(function (userId, status) { var entity = RongIMLib.RongInnerTools.convertUserStatus({ userId: userId, status: status }); RongIMLib.RongIMClient.userStatusObserver.notify({ key: userId, entity: entity }); }); var userIds = params.userIds || []; if (userIds.length) { RongIMLib.RongIMClient._dataAccessProvider.subscribeUserStatus(userIds); } }; VCDataProvider.prototype.getUnreadMentionedMessages = function (conversationType, targetId) { var me = this; var mentions = JSON.parse(me.addon.getUnreadMentionedMessages(conversationType, targetId)).list; for (var i = 0, len = mentions.length; i < len; i++) { var temp = JSON.parse(mentions[i].obj); temp.content = JSON.parse(temp.content); mentions[i] = temp; } return mentions; }; VCDataProvider.prototype.hasRemoteUnreadMessages = function (token, callback) { callback.onSuccess(false); }; VCDataProvider.prototype.sendRecallMessage = function (content, sendMessageCallback) { var me = this; me.addon.recallMessage("RC:RcCmd", JSON.stringify(content), content.push || "", function () { content.objectName = 'RC:RcCmd'; sendMessageCallback.onSuccess(me.buildMessage(JSON.stringify(content))); }, function (errorCode) { sendMessageCallback.onError(errorCode); }); }; VCDataProvider.prototype.updateMessage = function (message, callback) { }; VCDataProvider.prototype.updateMessages = function (conversationType, targetId, key, value, callback) { }; VCDataProvider.prototype.reconnect = function (callback) { var token = RongIMLib.Bridge._client.token; this.disconnect(); this.connect(token, callback); }; VCDataProvider.prototype.sendReceiptResponse = function (conversationType, targetId, sendCallback) { }; VCDataProvider.prototype.setMessageExtra = function (messageId, value, callback) { }; VCDataProvider.prototype.addMemberToDiscussion = function (discussionId, userIdList, callback) { }; VCDataProvider.prototype.createDiscussion = function (name, userIdList, callback) { }; VCDataProvider.prototype.getDiscussion = function (discussionId, callback) { }; VCDataProvider.prototype.quitDiscussion = function (discussionId, callback) { }; VCDataProvider.prototype.removeMemberFromDiscussion = function (discussionId, userId, callback) { }; VCDataProvider.prototype.setDiscussionInviteStatus = function (discussionId, status, callback) { }; VCDataProvider.prototype.setDiscussionName = function (discussionId, name, callback) { }; VCDataProvider.prototype.setEnvironment = function (isPrivate) { this.addon.setEnvironment(isPrivate); }; VCDataProvider.prototype.addConversation = function (conversation, callback) { }; VCDataProvider.prototype.updateConversation = function (conversation) { return null; }; VCDataProvider.prototype.getConversationNotificationStatus = function (params, callback) { var conversationType = params.conversationType; var targetId = params.targetId; var notification = RongIMLib.RongIMClient._memoryStore.notification; var key = conversationType + '_' + targetId; var status = notification[key]; if (typeof status == 'number') { callback.onSuccess(status); return; } this.addon.getConversationNotificationStatus(conversationType, targetId, function (status) { notification[key] = status; callback.onSuccess(status); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.setConversationNotificationStatus = function (params, callback) { var conversationType = params.conversationType; var targetId = params.targetId; var status = params.status; var notification = RongIMLib.RongIMClient._memoryStore.notification; var key = conversationType + '_' + targetId; notification[key] = status; var notify = !!status; this.addon.setConversationNotificationStatus(conversationType, targetId, notify, function () { callback.onSuccess(status); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.getCurrentConnectionStatus = function () { return this.addon.getConnectionStatus(); }; VCDataProvider.prototype.getAgoraDynamicKey = function (engineType, channelName, callback) { var extra = ""; this.addon.getVoIPKey(engineType, channelName, extra, function (token) { callback.onSuccess(token); }, function (errorCode) { callback.onError(errorCode); }); }; VCDataProvider.prototype.getPublicServiceProfile = function (publicServiceType, publicServiceId, callback) { var profile = RongIMLib.RongIMClient._memoryStore.publicServiceMap.get(publicServiceType, publicServiceId); callback.onSuccess(profile); }; VCDataProvider.prototype.setDeviceInfo = function (device) { var id = device.id || ''; this.addon.setDeviceId(id); }; VCDataProvider.prototype.getRemotePublicServiceList = function (callback, pullMessageTime) { var publicList = []; var ret = this.addon.getAccounts(); var transformProto = function (ret) { var result = { hasFollowed: false, isGlobal: false, menu: null }; if (!ret.obj) { var error = { error: ret }; throw new Error('公众账号数据格式错误: ' + JSON.stringify(error)); } var obj = JSON.parse(ret.obj); var protoMap = { aType: 'conversationType', aId: 'publicServiceId', aName: 'introduction', aUri: 'portraitUri', follow: 'hasFollowed', isGlobal: 'isGlobal' }; for (var key in obj) { var val = obj[key]; if (key == 'aExtra') { var extra = JSON.parse(val); result["hasFollowed"] = extra.follow; result["isGlobal"] = extra.isGlobal; result["menu"] = extra.menu; } var uId = protoMap[key]; if (uId) { result[uId] = val; } } return result; }; if (ret) { ret = JSON.parse(ret); var list = ret.list; for (var i = 0, len = list.length; i < len; i++) { var item = list[i]; item = transformProto(item); publicList.push(item); } } if (publicList.length > 0) { RongIMLib.RongIMClient._memoryStore.publicServiceMap.publicServiceList.length = 0; RongIMLib.RongIMClient._memoryStore.publicServiceMap.publicServiceList = publicList; } callback.onSuccess(RongIMLib.RongIMClient._memoryStore.publicServiceMap.publicServiceList); }; VCDataProvider.prototype.buildMessage = function (result) { var message = new RongIMLib.Message(), ret = JSON.parse(result); message.conversationType = ret.conversationType; message.targetId = ret.targetId; message.messageDirection = ret.direction; message.senderUserId = ret.senderUserId; if (ret.direction == RongIMLib.MessageDirection.RECEIVE) { message.receivedStatus = ret.status; } else if (ret.direction == RongIMLib.MessageDirection.SEND) { message.sentStatus = ret.status; } message.sentTime = ret.sentTime; message.objectName = ret.objectName; var content = ret.content ? JSON.parse(ret.content) : ret.content; var messageType = typeMapping[ret.objectName] || registerMessageTypeMapping[ret.objectName]; if (content) { content.messageName = messageType; } message.content = content; message.messageId = ret.messageId; message.messageUId = ret.messageUid; message.messageType = messageType; return message; }; VCDataProvider.prototype.buildConversation = function (val) { if (val === '') { return null; } var conver = new RongIMLib.Conversation(), c = JSON.parse(val), lastestMsg = c.lastestMsg ? this.buildMessage(c.lastestMsg) : {}; conver.conversationTitle = c.title; conver.conversationType = c.conversationType; conver.draft = c.draft; conver.isTop = c.isTop; conver.isHidden = c.isHidden; lastestMsg.conversationType = c.conversationType; lastestMsg.targetId = c.targetId; conver.latestMessage = lastestMsg; conver.latestMessageId = lastestMsg.messageId; conver.latestMessage.messageType = typeMapping[lastestMsg.objectName] || registerMessageTypeMapping[lastestMsg.objectName]; conver.objectName = lastestMsg.objectName; conver.receivedStatus = RongIMLib.ReceivedStatus.READ; conver.sentTime = lastestMsg.sentTime; conver.senderUserId = lastestMsg.senderUserId; conver.sentStatus = lastestMsg.status; conver.targetId = c.targetId; conver.unreadMessageCount = c.unreadCount; conver.hasUnreadMention = c.m_hasUnreadMention; var mentions = this.getUnreadMentionedMessages(c.conversationType, c.targetId); if (mentions.length > 0) { // 取最后一条 @ 消息,原因:和 web 互相兼容 var mention = mentions.pop(); conver.mentionedMsg = { uid: mention.messageUid, time: mention.sentTime, mentionedInfo: mention.content.mentionedInfo, sendUserId: mention.senderUserId }; } return conver; }; VCDataProvider.prototype.getRTCUserInfoList = function (room, callback) { this.addon.getRTCUsers(room.id, 1, function (result) { callback.onSuccess(result); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.getRTCRoomInfo = function (room, callback) { var order = 2; this.addon.getRTCResouce(room.id, order, function (result) { callback.onSuccess(JSON.parse(result)); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.joinRTCRoom = function (room, callback) { var id = room.id; var type = room.type || 0; this.addon.joinRTCRoom(id, type, function (result, token) { var res = JSON.parse(result); var users = {}; var list = res.list; RongIMLib.RongUtil.forEach(list, function (item) { var userId = item.id; var tmpData = {}; RongIMLib.RongUtil.forEach(item.data, function (data) { var key = data.key; var value = data.value; tmpData[key] = value; }); users[userId] = tmpData; }); callback.onSuccess({ users: users, token: token }); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.quitRTCRoom = function (room, callback) { this.addon.exitRTCRoom(room.id, function () { callback.onSuccess(true); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.RTCPing = function (room, callback) { this.addon.sendRTCPing(room.id, function () { callback.onSuccess(true); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.setRTCData = function (roomId, key, value, isInner, apiType, callback, message) { var context = this; var hanlders = { room_inner: function (roomId, key, value, name, content, success, error) { context.addon.setRTCInnerData(roomId, RongIMLib.RTCAPIType.ROOM, key, value, name, content, success, error); }, room_outer: function (roomId, key, value, name, content, success, error) { context.addon.setRTCOuterData(roomId, RongIMLib.RTCAPIType.ROOM, key, value, name, content, success, error); }, user_inner: function (roomId, key, value, name, content, success, error) { context.addon.setRTCInnerData(roomId, RongIMLib.RTCAPIType.PERSON, key, value, name, content, success, error); }, user_outer: function (roomId, key, value, name, content, success, error) { context.addon.setRTCOuterData(roomId, RongIMLib.RTCAPIType.PERSON, key, value, name, content, success, error); } }; var type = RongIMLib.RTCAPIType.PERSON == apiType ? 'user' : 'room'; var direction = isInner ? 'inner' : 'outer'; var tpl = '{type}_{direction}'; var name = RongIMLib.RongUtil.tplEngine(tpl, { type: type, direction: direction }); var handler = hanlders[name]; if (handler) { message = message || {}; var name = message.name; var content = message.content; handler(roomId, key, value, name, content, function () { callback.onSuccess(true); }, function (code) { callback.onError(code); }); } }; VCDataProvider.prototype.setRTCRoomData = function (roomId, key, value, isInner, callback, message) { this.setRTCData(roomId, key, value, isInner, RongIMLib.RTCAPIType.ROOM, callback, message); }; VCDataProvider.prototype.getRTCData = function (roomId, keys, isInner, apiType, callback) { var context = this; var hanlders = { room_inner: function (roomId, keys, success, error) { context.addon.getRTCInnerData(roomId, RongIMLib.RTCAPIType.ROOM, keys, success, error); }, room_outer: function (roomId, keys, success, error) { context.addon.getRTCOuterData(roomId, RongIMLib.RTCAPIType.ROOM, keys, success, error); } }; var type = RongIMLib.RTCAPIType.PERSON == apiType ? 'user' : 'room'; var direction = isInner ? 'inner' : 'outer'; var tpl = '{type}_{direction}'; var name = RongIMLib.RongUtil.tplEngine(tpl, { type: type, direction: direction }); var handler = hanlders[name]; if (handler) { handler(roomId, keys, function (result) { var res = JSON.parse(result); var props = {}; var list = res.list; RongIMLib.RongUtil.forEach(list, function (item) { props[item.key] = item.value; }); callback.onSuccess(props); }, function (code) { callback.onError(code); }); } }; VCDataProvider.prototype.getRTCRoomData = function (roomId, keys, isInner, callback, message) { this.getRTCData(roomId, keys, isInner, RongIMLib.RTCAPIType.ROOM, callback); }; VCDataProvider.prototype.removeRTCData = function (roomId, keys, isInner, apiType, callback, message) { var context = this; var hanlders = { room_inner: function (roomId, keys, name, content, success, error) { context.addon.deleteRTCInnerData(roomId, RongIMLib.RTCAPIType.ROOM, keys, name, content, success, error); }, room_outer: function (roomId, keys, name, content, success, error) { context.addon.deleteRTCOuterData(roomId, RongIMLib.RTCAPIType.ROOM, keys, name, content, success, error); }, user_inner: function (roomId, keys, name, content, success, error) { }, user_outer: function (roomId, keys, name, content, success, error) { } }; var type = RongIMLib.RTCAPIType.PERSON == apiType ? 'user' : 'room'; var direction = isInner ? 'inner' : 'outer'; var tpl = '{type}_{direction}'; var name = RongIMLib.RongUtil.tplEngine(tpl, { type: type, direction: direction }); var handler = hanlders[name]; if (handler) { message = message || {}; var name = message.name || ''; var content = message.content || ''; handler(roomId, keys, name, content, function () { callback.onSuccess(true); }, function (code) { callback.onError(code); }); } }; VCDataProvider.prototype.removeRTCRoomData = function (roomId, keys, isInner, callback, message) { this.removeRTCData(roomId, keys, isInner, RongIMLib.RTCAPIType.ROOM, callback); }; VCDataProvider.prototype.getNavi = function () { var nav = this.addon.getNav(); return nav[this.userId]; }; // 信令 SDK 新增 VCDataProvider.prototype.setRTCOutData = function (roomId, data, type, callback, message) { }; // 信令 SDK 新增 VCDataProvider.prototype.getRTCOutData = function (roomId, userId, callback) { }; VCDataProvider.prototype.setRTCUserInfo = function (room, info, callback) { }; VCDataProvider.prototype.removeRTCUserInfo = function (room, info, callback) { }; VCDataProvider.prototype.getRTCUserList = function (room, callback) { }; VCDataProvider.prototype.setRTCRoomInfo = function (room, data, callback) { }; VCDataProvider.prototype.removeRTCRoomInfo = function (room, data, callback) { }; VCDataProvider.prototype.setRTCUserData = function (roomId, key, value, isInner, callback, message) { this.setRTCData(roomId, key, value, isInner, RongIMLib.RTCAPIType.PERSON, callback, message); }; VCDataProvider.prototype.getRTCUserData = function (roomId, key, isInner, callback, message) { }; VCDataProvider.prototype.removeRTCUserData = function (roomId, key, isInner, callback, message) { }; VCDataProvider.prototype.getRTCToken = function (room, callback) { }; VCDataProvider.prototype.setRTCState = function (room, content, callback) { }; return VCDataProvider; })(); RongIMLib.VCDataProvider = VCDataProvider; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var MemeoryProvider = (function () { function MemeoryProvider() { this._memeoryStore = {}; this.prefix = "rong_"; } MemeoryProvider.prototype.setItem = function (composedKey, object) { this._memeoryStore[composedKey] = decodeURIComponent(object); }; MemeoryProvider.prototype.getItem = function (composedKey) { return this._memeoryStore[composedKey]; }; MemeoryProvider.prototype.removeItem = function (composedKey) { if (this.getItem(composedKey)) { delete this._memeoryStore[composedKey]; } }; MemeoryProvider.prototype.getItemKey = function (regStr) { var me = this, item = null, reg = new RegExp(regStr + "\\w+"); for (var key in me._memeoryStore) { var arr = key.match(reg); if (arr) { item = key; } } return item; }; MemeoryProvider.prototype.getItemKeyList = function (regStr) { var prefix = this.prefix; var me = this, itemList = [], reg = new RegExp(regStr + "\\w+"); for (var key in me._memeoryStore) { var arr = key.match(reg); if (arr) { key = key.substring(prefix.length); itemList.push(key); } } return itemList; }; MemeoryProvider.prototype.clearItem = function () { var me = this; for (var key in me._memeoryStore) { delete me._memeoryStore[key]; } }; //单位:字节 MemeoryProvider.prototype.onOutOfQuota = function () { return 4 * 1024; }; return MemeoryProvider; })(); RongIMLib.MemeoryProvider = MemeoryProvider; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var LocalStorageProvider = (function () { // static _instance: LocalStorageProvider = new LocalStorageProvider(); function LocalStorageProvider() { this.prefix = 'rong_'; this._host = ""; var d = new Date(), m = d.getMonth() + 1, date = d.getFullYear() + '/' + (m.toString().length == 1 ? '0' + m : m) + '/' + d.getDate(), nowDate = new Date(date).getTime(); for (var key in localStorage) { if (key.lastIndexOf('RECEIVED') > -1) { var recObj = JSON.parse(localStorage.getItem(key)); for (var key_1 in recObj) { nowDate - recObj[key_1].dealtime > 0 && (delete recObj[key_1]); } if (RongIMLib.RongUtil.isEmpty(recObj)) { localStorage.removeItem(key); } else { localStorage.setItem(key, JSON.stringify(recObj)); } } if (key.lastIndexOf('SENT') > -1) { var sentObj = JSON.parse(localStorage.getItem(key)); nowDate - sentObj.dealtime > 0 && (localStorage.removeItem(key)); } } } LocalStorageProvider.prototype.setItem = function (composedKey, object) { if (composedKey) { composedKey.indexOf(this.prefix) == -1 && (composedKey = this.prefix + composedKey); localStorage.setItem(composedKey, object); } }; LocalStorageProvider.prototype.getItem = function (composedKey) { if (composedKey) { composedKey.indexOf(this.prefix) == -1 && (composedKey = this.prefix + composedKey); return localStorage.getItem(composedKey ? composedKey : ""); } return ""; }; LocalStorageProvider.prototype.getItemKey = function (composedStr) { var item = ""; var _key = this.prefix + composedStr; for (var key in localStorage) { if (key.indexOf(_key) == 0) { item = key; break; } } return item; }; LocalStorageProvider.prototype.getItemKeyList = function (composedStr) { var itemList = []; var prefix = this.prefix; var _key = prefix + composedStr; for (var key in localStorage) { if (key.indexOf(_key) == 0) { key = key.substring(prefix.length); itemList.push(key); } } return itemList; }; LocalStorageProvider.prototype.removeItem = function (composedKey) { if (composedKey) { composedKey.indexOf(this.prefix) == -1 && (composedKey = this.prefix + composedKey); localStorage.removeItem(composedKey.toString()); } }; LocalStorageProvider.prototype.clearItem = function () { var me = this; for (var key in localStorage) { if (key.indexOf(me.prefix) > -1) { me.removeItem(key); } } }; //单位:字节 LocalStorageProvider.prototype.onOutOfQuota = function () { return JSON.stringify(localStorage).length; }; return LocalStorageProvider; })(); RongIMLib.LocalStorageProvider = LocalStorageProvider; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var UserDataProvider = (function () { function UserDataProvider() { this.opersistName = 'RongIMLib'; this.keyManager = 'RongUserDataKeyManager'; this._host = ""; this.prefix = "rong_"; this.oPersist = document.createElement("div"); this.oPersist.style.display = "none"; this.oPersist.style.behavior = "url('#default#userData')"; document.body.appendChild(this.oPersist); this.oPersist.load(this.opersistName); } UserDataProvider.prototype.setItem = function (key, value) { key && key.indexOf(this.prefix) == -1 && (key = this.prefix + key); this.oPersist.setAttribute(key, value); var keyNames = this.getItem(this.keyManager); keyNames ? keyNames.indexOf(key) == -1 && (keyNames += ',' + key) : (keyNames = key); this.oPersist.setAttribute(this.prefix + this.keyManager, keyNames); this.oPersist.save(this.opersistName); }; UserDataProvider.prototype.getItem = function (key) { key && key.indexOf(this.prefix) == -1 && (key = this.prefix + key); return key ? this.oPersist.getAttribute(key) : key; }; UserDataProvider.prototype.removeItem = function (key) { key && key.indexOf(this.prefix) == -1 && (key = this.prefix + key); this.oPersist.removeAttribute(key); this.oPersist.save(this.opersistName); var keyNames = this.getItem(this.keyManager), keyNameArray = keyNames && keyNames.split(',') || []; for (var i = 0, len = keyNameArray.length; i < len; i++) { if (keyNameArray[i] == key) { keyNameArray.splice(i, 1); } } this.oPersist.setAttribute(this.prefix + this.keyManager, keyNameArray.join(',')); this.oPersist.save(this.opersistName); }; UserDataProvider.prototype.getItemKey = function (composedStr) { var item = null, keyNames = this.getItem(this.keyManager), keyNameArray = keyNames && keyNames.split(',') || [], me = this; var _key = this.prefix + composedStr; if (keyNameArray.length) { for (var i = 0, len = keyNameArray.length; i < len; i++) { if (keyNameArray[i] && keyNameArray[i].indexOf(_key) == 0) { item = keyNameArray[i]; break; } } } return item; }; UserDataProvider.prototype.getItemKeyList = function (composedStr) { var itemList = [], keyNames = this.getItem(this.keyManager), keyNameArray = keyNames && keyNames.split(',') || []; var prefix = this.prefix; var _key = prefix + composedStr; if (keyNameArray.length) { for (var i = 0, len = keyNameArray.length; i < len; i++) { if (keyNameArray[i] && keyNameArray[i].indexOf(_key) == 0) { var keyName = keyNameArray[i]; keyName = keyName.substring(prefix.length); itemList.push(keyNameArray[i]); } } } return itemList; }; UserDataProvider.prototype.clearItem = function () { var keyNames = this.getItem(this.keyManager), keyNameArray = [], me = this; keyNames && (keyNameArray = keyNames.split(',')); if (keyNameArray.length) { for (var i = 0, len = keyNameArray.length; i < len; i++) { keyNameArray[i] && me.removeItem(keyNameArray[i]); } me.removeItem(me.keyManager); } }; UserDataProvider.prototype.onOutOfQuota = function () { return 10 * 1024 * 1024; }; return UserDataProvider; })(); RongIMLib.UserDataProvider = UserDataProvider; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var FeatureDectector = (function () { function FeatureDectector(callback) { this.script = document.createElement("script"); this.head = document.getElementsByTagName("head")[0]; if ("WebSocket" in window && "ArrayBuffer" in window && WebSocket.prototype.CLOSED === 3 && !RongIMLib.RongIMClient._memoryStore.depend.isPolling) { RongIMLib.Transportations._TransportType = RongIMLib.Socket.WEBSOCKET; if (!RongIMLib.RongIMClient.Protobuf) { var url = RongIMLib.RongIMClient._memoryStore.depend.protobuf; var script = this.script; script.src = url; this.head.appendChild(script); script.onload = script.onreadystatechange = function () { var isLoaded = (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete'); if (isLoaded) { // 防止 IE6、7 下偶发触发两次 loaded script.onload = script.onreadystatechange = null; if (callback) { callback(); } if (!callback) { var token = RongIMLib.RongIMClient._memoryStore.token; var connectCallback = RongIMLib.RongIMClient._memoryStore.callback; token && RongIMLib.RongIMClient.connect(token, connectCallback); } } }; } } else { RongIMLib.Transportations._TransportType = "xhr-polling"; RongIMLib.RongIMClient.Protobuf = Polling; } } return FeatureDectector; })(); RongIMLib.FeatureDectector = FeatureDectector; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var FeaturePatcher = (function () { function FeaturePatcher() { } FeaturePatcher.prototype.patchAll = function () { this.patchJSON(); this.patchForEach(); }; FeaturePatcher.prototype.patchForEach = function () { if (!Array.forEach) { Array.forEach = function (arr, func) { for (var i = 0; i < arr.length; i++) { func.call(arr, arr[i], i, arr); } }; } }; FeaturePatcher.prototype.patchJSON = function () { if (!window["JSON"]) { window["JSON"] = (function () { function JSON() { } JSON.parse = function (sJSON) { return eval('(' + sJSON + ')'); }; JSON.stringify = function (value) { return this.str("", { "": value }); }; JSON.str = function (key, holder) { var i, k, v, length, mind = "", partial, value = holder[key], me = this; if (value && typeof value === "object" && typeof value.toJSON === "function") { value = value.toJSON(key); } switch (typeof value) { case "string": return me.quote(value); case "number": return isFinite(value) ? String(value) : "null"; case "boolean": case "null": return String(value); case "object": if (!value) { return "null"; } partial = []; if (Object.prototype.toString.apply(value) === "[object Array]") { length = value.length; for (i = 0; i < length; i += 1) { partial[i] = me.str(i, value) || "null"; } v = partial.length === 0 ? "[]" : "[" + partial.join(",") + "]"; return v; } for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = me.str(k, value); if (v) { partial.push(me.quote(k) + ":" + v); } } } v = partial.length === 0 ? "{}" : "{" + partial.join(",") + "}"; return v; } }; JSON.quote = function (string) { var me = this; me.rx_escapable.lastIndex = 0; return me.rx_escapable.test(string) ? '"' + string.replace(me.rx_escapable, function (a) { var c = me.meta[a]; return typeof c === "string" ? c : "\\u" + ("0000" + a.charCodeAt(0).toString(16)).slice(-4); }) + '"' : '"' + string + '"'; }; JSON.rx_escapable = new RegExp('[\\\"\\\\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]', "g"); JSON.meta = { "\b": "\\b", " ": "\\t", "\n": "\\n", "\f": "\\f", "\r": "\\r", '"': '\\"', "''": "\\''", "\\": "\\\\" }; return JSON; })(); } }; return FeaturePatcher; })(); RongIMLib.FeaturePatcher = FeaturePatcher; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var ScriptLoader = (function () { function ScriptLoader() { } ScriptLoader.prototype.load = function (src, onLoad, onError) { var script = document.createElement("script"); script.async = true; if (onLoad) { if (script.addEventListener) { script.addEventListener("load", function (event) { var target = event.target || event.srcElement; onLoad(target.src); }, false); } else if (script.readyState) { script.onreadystatechange = function (event) { var target = event.srcElement; onLoad(target.src); }; } } if (onError) { script.onerror = function (event) { var target = event.target || event.srcElement; onError(target.src); }; } (document.head || document.getElementsByTagName("head")[0]).appendChild(script); script.src = src; }; return ScriptLoader; })(); })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var PublicServiceMap = (function () { function PublicServiceMap() { this.publicServiceList = []; } PublicServiceMap.prototype.get = function (publicServiceType, publicServiceId) { for (var i = 0, len = this.publicServiceList.length; i < len; i++) { if (this.publicServiceList[i].conversationType == publicServiceType && publicServiceId == this.publicServiceList[i].publicServiceId) { return this.publicServiceList[i]; } } }; PublicServiceMap.prototype.add = function (publicServiceProfile) { var isAdd = true, me = this; for (var i = 0, len = this.publicServiceList.length; i < len; i++) { if (me.publicServiceList[i].conversationType == publicServiceProfile.conversationType && publicServiceProfile.publicServiceId == me.publicServiceList[i].publicServiceId) { this.publicServiceList.unshift(this.publicServiceList.splice(i, 1)[0]); isAdd = false; break; } } if (isAdd) { this.publicServiceList.unshift(publicServiceProfile); } }; PublicServiceMap.prototype.replace = function (publicServiceProfile) { var me = this; for (var i = 0, len = this.publicServiceList.length; i < len; i++) { if (me.publicServiceList[i].conversationType == publicServiceProfile.conversationType && publicServiceProfile.publicServiceId == me.publicServiceList[i].publicServiceId) { me.publicServiceList.splice(i, 1, publicServiceProfile); break; } } }; PublicServiceMap.prototype.remove = function (conversationType, publicServiceId) { var me = this; for (var i = 0, len = this.publicServiceList.length; i < len; i++) { if (me.publicServiceList[i].conversationType == conversationType && publicServiceId == me.publicServiceList[i].publicServiceId) { this.publicServiceList.splice(i, 1); break; } } }; return PublicServiceMap; })(); RongIMLib.PublicServiceMap = PublicServiceMap; /** * 会话工具类。 */ var ConversationMap = (function () { function ConversationMap() { this.conversationList = []; } ConversationMap.prototype.get = function (conversavtionType, targetId) { for (var i = 0, len = this.conversationList.length; i < len; i++) { if (this.conversationList[i].conversationType == conversavtionType && this.conversationList[i].targetId == targetId) { return this.conversationList[i]; } } return null; }; ConversationMap.prototype.add = function (conversation) { var isAdd = true; for (var i = 0, len = this.conversationList.length; i < len; i++) { if (this.conversationList[i].conversationType === conversation.conversationType && this.conversationList[i].targetId === conversation.targetId) { this.conversationList.unshift(this.conversationList.splice(i, 1)[0]); isAdd = false; break; } } if (isAdd) { this.conversationList.unshift(conversation); } }; /** * [replace 替换会话] * 会话数组存在的情况下调用add方法会是当前会话被替换且返回到第一个位置,导致用户本地一些设置失效,所以提供replace方法 */ ConversationMap.prototype.replace = function (conversation) { for (var i = 0, len = this.conversationList.length; i < len; i++) { if (this.conversationList[i].conversationType === conversation.conversationType && this.conversationList[i].targetId === conversation.targetId) { this.conversationList.splice(i, 1, conversation); break; } } }; ConversationMap.prototype.remove = function (conversation) { for (var i = 0, len = this.conversationList.length; i < len; i++) { if (this.conversationList[i].conversationType === conversation.conversationType && this.conversationList[i].targetId === conversation.targetId) { this.conversationList.splice(i, 1); break; } } }; return ConversationMap; })(); RongIMLib.ConversationMap = ConversationMap; var CheckParam = (function () { function CheckParam() { } CheckParam.getInstance = function () { if (!CheckParam._instance) { CheckParam._instance = new CheckParam(); } return CheckParam._instance; }; CheckParam.prototype.logger = function (code, funcName, msg) { RongIMLib.RongIMClient.logger({ code: code, funcName: funcName, msg: msg }); }; CheckParam.prototype.check = function (f, position, d, c) { if (RongIMLib.RongIMClient._dataAccessProvider || d) { for (var g = 0, e = c.length; g < e; g++) { if (!new RegExp(this.getType(c[g])).test(f[g])) { // throw new Error("The index of " + g + " parameter was wrong type " + this.getType(c[g]) + " [" + f[g] + "] -> position:" + position); var msg = "第" + (g + 1) + "个参数错误, 错误类型:" + this.getType(c[g]) + " [" + f[g] + "] -> 位置:" + position; this.logger("-3", position, msg); } } } else { var msg = "该参数不正确或尚未实例化RongIMClient -> 位置:" + position; this.logger("-4", position, msg); } }; CheckParam.prototype.getType = function (str) { var temp = Object.prototype.toString.call(str).toLowerCase(); return temp.slice(8, temp.length - 1); }; CheckParam.prototype.checkCookieDisable = function () { document.cookie = "checkCookie=1"; var arr = document.cookie.match(new RegExp("(^| )checkCookie=([^;]*)(;|$)")), isDisable = false; if (!arr) { isDisable = true; } document.cookie = "checkCookie=1;expires=Thu, 01-Jan-1970 00:00:01 GMT"; return isDisable; }; return CheckParam; })(); RongIMLib.CheckParam = CheckParam; var LimitableMap = (function () { function LimitableMap(limit) { this.map = {}; this.keys = []; this.limit = limit || 10; } LimitableMap.prototype.set = function (key, value) { this.map[key] = value; }; LimitableMap.prototype.get = function (key) { return this.map[key] || 0; }; LimitableMap.prototype.remove = function (key) { delete this.map[key]; }; return LimitableMap; })(); RongIMLib.LimitableMap = LimitableMap; var MemoryCache = (function () { function MemoryCache() { this.cache = {}; } MemoryCache.prototype.set = function (key, value) { this.cache[key] = value; }; MemoryCache.prototype.get = function (key) { return this.cache[key]; }; MemoryCache.prototype.remove = function (key) { delete this.cache[key]; }; return MemoryCache; })(); RongIMLib.MemoryCache = MemoryCache; var RongAjax = (function () { function RongAjax(options) { var me = this; me.xmlhttp = null; me.options = options; var hasCORS = typeof XMLHttpRequest !== "undefined" && "withCredentials" in new XMLHttpRequest(); if ("undefined" != typeof XMLHttpRequest && hasCORS) { me.xmlhttp = new XMLHttpRequest(); } else if ("undefined" != typeof XDomainRequest) { me.xmlhttp = new XDomainRequest(); } else { me.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } } RongAjax.prototype.send = function (callback) { var me = this; me.options.url || (me.options.url = "http://upload.qiniu.com/putb64/-1"); me.xmlhttp.onreadystatechange = function () { if (me.xmlhttp.readyState == 4) { if (me.options.type) { callback(); } else { callback(JSON.parse(me.xmlhttp.responseText.replace(/'/g, '"'))); } } }; me.xmlhttp.open("POST", me.options.url, true); me.xmlhttp.withCredentials = false; if ("setRequestHeader" in me.xmlhttp) { if (me.options.type) { me.xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=utf-8"); } else { me.xmlhttp.setRequestHeader("Content-type", "application/octet-stream"); me.xmlhttp.setRequestHeader('Authorization', "UpToken " + me.options.token); } } me.xmlhttp.send(me.options.type ? "appKey=" + me.options.appKey + "&deviceId=" + me.options.deviceId + "×tamp=" + me.options.timestamp + "&deviceInfo=" + me.options.deviceInfo + "&privateInfo=" + JSON.stringify(me.options.privateInfo) : me.options.base64); }; return RongAjax; })(); RongIMLib.RongAjax = RongAjax; function Prosumer() { var data = [], isConsuming = false; this.produce = function (res) { data.push(res); }; this.consume = function (callback, finished) { if (isConsuming) { return; } isConsuming = true; var next = function () { var res = data.shift(); if (RongUtil.isUndefined(res)) { isConsuming = false; finished && finished(); return; } callback(res, next); }; next(); }; this.isExeuting = function () { return isConsuming; }; } var RongUtil = (function () { function RongUtil() { } RongUtil.noop = function () { }; RongUtil.isEmpty = function (obj) { var result = true; if (RongUtil.isObject(obj)) { RongUtil.forEach(obj, function () { result = false; }); } if (RongUtil.isString(obj) || RongUtil.isArray(obj)) { return obj.length === 0; } if (RongUtil.isNumber(obj)) { return obj === 0; } return result; }; RongUtil.isLengthLimit = function (str, maxLen, minLen) { minLen = minLen || 0; var strLen = str.length; return strLen <= maxLen && strLen >= minLen; }; RongUtil.MD5 = function (str, key, raw) { return md5(str, key, raw); }; RongUtil.isObject = function (obj) { return Object.prototype.toString.call(obj) == '[object Object]'; }; RongUtil.isArray = function (array) { return Object.prototype.toString.call(array) == '[object Array]'; }; RongUtil.isString = function (array) { return Object.prototype.toString.call(array) == '[object String]'; }; RongUtil.isFunction = function (fun) { return Object.prototype.toString.call(fun) == '[object Function]'; }; ; RongUtil.isUndefined = function (str) { return Object.prototype.toString.call(str) == '[object Undefined]'; }; ; RongUtil.isEqual = function (a, b) { return a === b; }; ; RongUtil.indexOf = function (arrs, item) { var index = -1; for (var i = 0; i < arrs.length; i++) { if (item === arrs[i]) { index = i; break; } } return index; }; RongUtil.stringFormat = function (tmpl, vals) { for (var i = 0, len = vals.length; i < len; i++) { var val = vals[i], reg = new RegExp("\\{" + (i) + "\\}", "g"); tmpl = tmpl.replace(reg, val); } return tmpl; }; RongUtil.tplEngine = function (temp, data, regexp) { if (!(Object.prototype.toString.call(data) === "[object Array]")) { data = [data]; } var ret = []; for (var i = 0, j = data.length; i < j; i++) { ret.push(replaceAction(data[i])); } return ret.join(""); function replaceAction(object) { return temp.replace(regexp || (/{([^}]+)}/g), function (match, name) { if (match.charAt(0) == '\\') { return match.slice(1); } return (object[name] != undefined) ? object[name] : '{' + name + '}'; }); } }; ; RongUtil.forEach = function (obj, callback) { callback = callback || RongUtil.noop; var loopObj = function () { for (var key in obj) { if (obj.hasOwnProperty(key)) { callback(obj[key], key, obj); } } }; var loopArr = function () { for (var i = 0, len = obj.length; i < len; i++) { callback(obj[i], i); } }; if (RongUtil.isObject(obj)) { loopObj(); } if (RongUtil.isArray(obj)) { loopArr(); } }; RongUtil.extend = function (source, target, callback, force) { RongUtil.forEach(source, function (val, key) { var hasProto = (key in target); if (force && hasProto) { target[key] = val; } if (!hasProto) { target[key] = val; } }); return target; }; RongUtil.createXHR = function () { var item = { XMLHttpRequest: function () { return new XMLHttpRequest(); }, XDomainRequest: function () { return new XDomainRequest(); }, ActiveXObject: function () { return new ActiveXObject('Microsoft.XMLHTTP'); } }; var isXHR = typeof XMLHttpRequest !== "undefined" && "withCredentials" in new XMLHttpRequest(); var isXDR = typeof XDomainRequest == 'function'; var key = isXHR ? 'XMLHttpRequest' : isXDR ? 'XDomainRequest' : 'ActiveXObject'; return item[key](); }; RongUtil.request = function (opts) { var url = opts.url; var success = opts.success; var error = opts.error || RongUtil.noop; var method = opts.method || 'GET'; var xhr = RongUtil.createXHR(); if ('onload' in xhr) { xhr.onload = function () { xhr.onload = RongUtil.noop; success(xhr.responseText); }; xhr.onerror = function () { error(xhr.status, xhr.responseText); xhr.onerror = RongUtil.noop; }; } else { xhr.onreadystatechange = function () { if (xhr.readyState == 4) { var status = xhr.status; if (status == 200) { success(xhr.responseText); } else { error(status, xhr.responseText); } } }; } xhr.open(method, url, true); xhr.send(null); return xhr; }; RongUtil.formatProtoclPath = function (config) { var path = config.path; var protocol = config.protocol; var tmpl = config.tmpl || '{0}{1}'; var sub = config.sub; var flag = '://'; var index = path.indexOf(flag); var hasProtocol = (index > -1); if (hasProtocol) { index += flag.length; path = path.substring(index); } if (sub) { index = path.indexOf('/'); var hasPath = (index > -1); if (hasPath) { path = path.substr(0, index); } } return RongUtil.stringFormat(tmpl, [protocol, path]); }; ; RongUtil.getUrlHost = function (url) { var index = RongUtil.indexOf(url, '/'); return url.substring(0, index); }; RongUtil.supportLocalStorage = function () { var support = false; if (typeof localStorage == 'object') { try { var key = 'RC_TMP_KEY', value = 'RC_TMP_VAL'; localStorage.setItem(key, value); var localVal = localStorage.getItem(key); if (localVal == value) { support = true; } } catch (err) { console.log('localStorage is disabled.'); } } return support; }; /* //返回新引用,不破坏原始对象 rename({n: 'martin'}, {n: 'name'}); => {name: 'martin'} rename([{n: 'martin'}, {a: 18}], {n: 'name', a: 'age'}); => [{name: 'martin'}, {age: 18}] */ RongUtil.rename = function (origin, newNames) { var isObject = RongUtil.isObject(origin); if (isObject) { origin = [origin]; } origin = JSON.parse(JSON.stringify(origin)); var updateProperty = function (val, key, obj) { delete obj[key]; key = newNames[key]; obj[key] = val; }; RongUtil.forEach(origin, function (item) { RongUtil.forEach(item, function (val, key, obj) { var isRename = (key in newNames); (isRename ? updateProperty : RongUtil.noop)(val, key, obj); }); }); return isObject ? origin[0] : origin; }; RongUtil.some = function (arrs, callback) { var has = false; for (var i = 0, len = arrs.length; i < len; i++) { if (callback(arrs[i])) { has = true; break; } } return has; }; RongUtil.keys = function (obj) { var props = []; for (var key in obj) { props.push(key); } return props; }; RongUtil.isNumber = function (num) { return Object.prototype.toString.call(num) == '[object Number]'; }; RongUtil.getTimestamp = function () { var date = new Date(); return date.getTime(); }; RongUtil.isSupportRequestHeaders = function () { var userAgent = navigator.userAgent; var isIE = window.ActiveXObject || 'ActiveXObject' in window; if (isIE) { var reIE = new RegExp('MSIE (\\d+\\.\\d+);'); reIE.test(userAgent); var fIEVersion = parseFloat(RegExp['$1']); return fIEVersion > 9; } return true; }; RongUtil.hasValidWsUrl = function (urls) { try { urls = JSON.parse(urls); } catch (e) { return false; } var validUrlList = RongUtil.getValidWsUrlList(urls); return validUrlList.length > 0; }; RongUtil.getValidWsUrlList = function (urls) { var invalidWsUrls = RongIMLib.RongIMClient.invalidWsUrls; var validUrlList = []; RongUtil.forEach(urls, function (url) { if (RongUtil.indexOf(invalidWsUrls, url) === -1) { validUrlList.push(url); } }); return validUrlList; }; RongUtil.getByteLength = function (str, charset) { charset = charset || 'utf-8'; var total = 0, chatCode; if (charset === 'utf-16') { for (var i = 0, max = str.length; i < max; i++) { chatCode = str.charCodeAt(i); if (chatCode <= 0xffff) { total += 2; } else { total += 4; } } } else { for (var i = 0, max = str.length; i < max; i++) { chatCode = str.charCodeAt(i); if (chatCode < 0x007f) { total += 1; } else if (chatCode <= 0x07ff) { total += 2; } else if (chatCode <= 0xffff) { total += 3; } else { total += 4; } } } return total; }; RongUtil.Prosumer = Prosumer; return RongUtil; })(); RongIMLib.RongUtil = RongUtil; /* var observer = new RongObserver(); observer.watch({ key: 'key', func: function(entity){ } }); */ var RongObserver = (function () { function RongObserver() { this.watchers = {}; } RongObserver.prototype.genUId = function (key) { var time = new Date().getTime(); return [key, time].join('_'); }; RongObserver.prototype.watch = function (params) { var me = this; var key = params.key; var multiple = params.multiple; key = RongUtil.isArray(key) ? key : [key]; var func = params.func; RongUtil.forEach(key, function (k) { k = multiple ? me.genUId(k) : k; me.watchers[k] = func; }); }; RongObserver.prototype.notify = function (params) { var me = this; var key = params.key; var entity = params.entity; for (var k in me.watchers) { var isNotify = (k.indexOf(key) == 0); if (isNotify) { me.watchers[k](entity); } } }; RongObserver.prototype.remove = function () { }; return RongObserver; })(); RongIMLib.RongObserver = RongObserver; var Observer = (function () { function Observer() { this.observers = []; } Observer.prototype.add = function (observer, force) { if (force) { this.observers = [observer]; } if (RongUtil.isFunction(observer)) { this.observers.push(observer); } }; Observer.prototype.emit = function (data) { RongUtil.forEach(this.observers, function (observer) { observer(data); }); }; Observer.prototype.clear = function () { this.observers = []; }; Observer.prototype.checkIndexOutBound = function (index, bound) { var isOutBound = (index > -1 && index < bound); return isOutBound; }; Observer.prototype.removeAt = function (index) { var isOutBound = this.checkIndexOutBound(index, this.observers.length); if (isOutBound) { this.observers.splice(index, 1); } }; Observer.prototype.remove = function (observer) { var me = this; if (!observer) { me.clear(); return; } if (!RongUtil.isFunction(observer)) { return; } var observerList = me.observers; for (var i = observerList.length - 1; i >= 0; i--) { if (observer === observerList[i]) { me.removeAt(i); } } }; return Observer; })(); RongIMLib.Observer = Observer; var Timer = (function () { function Timer(config) { this.timeout = 0; this.timers = []; this.timeout = config.timeout; } Timer.prototype.resume = function (callback) { var timer = setTimeout(callback, this.timeout); this.timers.push(timer); }; Timer.prototype.pause = function () { RongUtil.forEach(this.timers, function (timer) { clearTimeout(timer); }); }; return Timer; })(); RongIMLib.Timer = Timer; var IndexTools = (function () { function IndexTools(config) { this.items = []; this.index = 0; this.onwheel = function () { }; this.items = config.items; this.onwheel = config.onwheel; } IndexTools.prototype.get = function () { var context = this; var items = context.items; var index = context.index; var isWheel = index >= items.length; if (isWheel) { context.onwheel(); } return isWheel ? 0 : index; }; IndexTools.prototype.add = function () { this.index += 1; }; return IndexTools; })(); RongIMLib.IndexTools = IndexTools; var InnerUtil = (function () { function InnerUtil() { } InnerUtil.getUId = function (token) { return md5(token).slice(8, 16); }; return InnerUtil; })(); RongIMLib.InnerUtil = InnerUtil; })(RongIMLib || (RongIMLib = {})); // {WebEnd} WebSDK 内容开始的标识, 方便小程序 SDK 定位 /* 说明: 请勿修改 header.js 和 footer.js 用途: 自动拼接暴露方式 命令: grunt release 中 concat */ return RongIMLib; }); ================================================ FILE: api-test-v2/lib/js/RongIMLib-2.5.9-release.js ================================================ /* 说明: 请勿修改 header.js 和 footer.js 用途: 自动拼接暴露方式 命令: grunt release 中 concat Release Date: Tue Jul 14 2020 16:33:19 GMT+0800 (China Standard Time) CodeVersion: 551c131e1273bd80ea99d41ca71b08df49f6b87a */ (function(global, factory) { if (typeof exports === 'object' && typeof module !== 'undefined') { module.exports = factory(); } else if (typeof define === 'function' && (define.amd || define.cmd)) { define(factory); } else { var tempIMLib = factory(); var tempClient = tempIMLib.RongIMClient; var isExists = (!!global.RongIMLib); if (isExists) { var currentClient = RongIMLib.RongIMClient || {}; for(var key in currentClient){ tempClient[key] = currentClient[key]; } } global.RongIMLib = tempIMLib; global.RongIMClient = tempClient; } })(window, function(){ // {WebStart} WebSDK 内容开始的标识, 方便小程序 SDK 定位 // console.warn('SDK VERSION:', '551c131e1273bd80ea99d41ca71b08df49f6b87a') var Polling = { SetUserStatusInput: function(){ var a = {}; this.setStatus = function(b){ a.status = b; }; this.toArrayBuffer = function(){ return a; }; }, SetUserStatusOutput: function(){ var a = {}; this.setNothing = function(b){ a.nothing = b; }; this.toArrayBuffer = function(){ return a; }; }, GetUserStatusInput: function(){ var a = {}; this.setNothing = function(b){ a.nothing = b; }; this.toArrayBuffer = function(){ return a; }; }, GetUserStatusOutput: function(){ var a = {}; this.setStatus = function(b){ a.status = b; }; this.setSubUserId = function(b){ a.subUserId = b; }; this.toArrayBuffer = function(){ return a; }; }, VoipDynamicInput: function(){ var a = {}; this.setEngineType = function(b){ a.engineType = b; }; this.setChannelName = function(b){ a.channelName = b; }; this.setChannelExtra = function(b){ a.channelExtra = b; }; this.toArrayBuffer = function(){ return a; }; }, VoipDynamicOutput: function(){ var a = {}; this.setDynamicKey = function(b){ a.dynamicKey = b; }; this.toArrayBuffer = function(){ return a; }; }, SubUserStatusInput: function(){ var a = {}; this.setUserid = function(b){ a.userid = b; }; this.toArrayBuffer = function(){ return a; }; }, SubUserStatusOutput: function(){ var a = {}; this.setNothing = function(b){ a.nothing = b; }; this.toArrayBuffer = function(){ return a; }; }, CleanHisMsgInput: function(){ var a = {}; this.setTargetId = function(b){ a.targetId = b; }; this.setDataTime = function(b){ a.dataTime = b; }; this.setConversationType = function(b){ a.conversationType = b; }; this.toArrayBuffer = function(){ return a; }; }, DeleteMsgInput:function(){ var a = {}; this.setType = function(b){ a.type = b; }; this.setConversationId = function(b){ a.conversationId = b; }; this.setMsgs = function(b){ a.msgs = b; }; this.toArrayBuffer = function () { return a; } }, DeleteMsg:function(){ var a = {}; this.setMsgId = function(b){ a.msgId = b; }; this.setMsgDataTime = function(b){ a.msgDataTime = b; }; this.setDirect = function(b){ a.direct = b; }; this.toArrayBuffer = function () { return a; } }, DeleteMsgOutput:function(){ var a = {}; this.setNothing = function(b){ a.nothing = b; }; this.toArrayBuffer = function () { return a; } }, SearchMpInput:function(){ var a = {}; this.setType = function (b) { a.type = b; }; this.setId = function (b) { a.id = b; }; this.toArrayBuffer = function () { return a; } }, SearchMpOutput:function(){ var a = {}; this.setNothing = function (b) { a.nothing = b; }; this.setInfo = function (b) { a.info = b; }; this.toArrayBuffer = function () { return a; } }, MpInfo:function(){ var a = {}; this.setMpid = function(b){ a.mpid = b; }; this.setName = function(b){ a.name = b; }; this.setType = function(b){ a.type = b; }; this.setTime = function(b){ a.time = b; }; this.setPortraitUri = function(b){ a.portraitUrl = b; }; this.setExtra = function(b){ a.extra = b; }; this.toArrayBuffer = function () { return a; } }, PullMpInput:function(){ var a = {}; this.setMpid = function(b){ a.mpid = b; }; this.setTime = function(b){ a.time = b; }; this.toArrayBuffer = function () { return a; }; }, PullMpOutput:function(){ var a = {}; this.setStatus = function(b){ a.status = b; } this.setInfo = function(b){ a.info = b; }; this.toArrayBuffer = function () { return a; }; }, MPFollowInput:function(){ var a = {}; this.setId = function(b){ a.id = b; }; this.toArrayBuffer = function () { return a; }; }, MPFollowOutput:function(){ var a = {}; this.setNothing = function(b){ a.nothing = b; }; this.setInfo = function(b){ a.info = b; }; this.toArrayBuffer = function () { return a; }; }, NotifyMsg: function () { var a = {}; this.setType = function (b) { a.type = b; }; this.setTime = function (b) { a.time = b; }; this.setChrmId = function(b){ a.chrmId = b; }; this.toArrayBuffer = function () { return a; }; }, SyncRequestMsg: function () { var a = {}; this.setSyncTime = function (b) { a.syncTime = b || 0; }; this.setIspolling = function (b) { a.ispolling = !!b; }; this.setIsweb = function (b) { a.isweb = !!b; }; this.setIsPullSend = function (b) { a.isPullSend = !!b; }; this.setSendBoxSyncTime = function (b) { a.sendBoxSyncTime = b; }; this.toArrayBuffer = function () { return a; }; }, UpStreamMessage: function () { var a = {}; this.setSessionId = function (b) { a.sessionId = b }; this.setClassname = function (b) { a.classname = b }; this.setContent = function (b) { if (b) a.content = b; }; this.setPushText = function (b) { a.pushText = b }; this.setUserId = function(b){ a.userId = b; }; this.setConfigFlag = function (b) { a.configFlag = b; }; this.setAppData = function(b){ a.appData = b; }; this.toArrayBuffer = function () { return a }; }, DownStreamMessages: function () { var a = {}; this.setList = function (b) { a.list = b }; this.setSyncTime = function (b) { a.syncTime = b; }; this.setFinished = function(b){ a.finished = b; }; this.toArrayBuffer = function () { return a }; }, DownStreamMessage: function () { var a = {}; this.setFromUserId = function (b) { a.fromUserId = b }; this.setType = function (b) { a.type = b }; this.setGroupId = function (b) { a.groupId = b }; this.setClassname = function (b) { a.classname = b }; this.setContent = function (b) { if (b) a.content = b }; this.setDataTime = function (b) { a.dataTime = b; }; this.setStatus = function (b) { a.status = b; }; this.setMsgId = function (b) { a.msgId = b; }; this.toArrayBuffer = function () { return a; }; }, CreateDiscussionInput: function () { var a = {}; this.setName = function (b) { a.name = b }; this.toArrayBuffer = function () { return a } }, CreateDiscussionOutput: function () { var a = {}; this.setId = function (b) { a.id = b }; this.toArrayBuffer = function () { return a }; }, ChannelInvitationInput: function () { var a = {}; this.setUsers = function (b) { a.users = b }; this.toArrayBuffer = function () { return a }; }, LeaveChannelInput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b }; this.toArrayBuffer = function () { return a }; }, QueryChatroomInfoInput:function(){ var a = {}; this.setCount = function (b) { a.count = b; }; this.setOrder = function (b) { a.order = b; }; this.toArrayBuffer = function () { return a }; }, QueryChatroomInfoOutput:function(){ var a = {}; this.setUserTotalNums = function (b) { a.userTotalNums = b; }; this.setUserInfos = function (b) { a.userInfos = b; }; this.toArrayBuffer = function () { return a; }; }, ChannelEvictionInput: function () { var a = {}; this.setUser = function (b) { a.user = b }; this.toArrayBuffer = function () { return a }; }, RenameChannelInput: function () { var a = {}; this.setName = function (b) { a.name = b }; this.toArrayBuffer = function () { return a } }, ChannelInfoInput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b }; this.toArrayBuffer = function () { return a } }, ChannelInfoOutput: function () { var a = {}; this.setType = function (b) { a.type = b }; this.setChannelId = function (b) { a.channelId = b }; this.setChannelName = function (b) { a.channelName = b }; this.setAdminUserId = function (b) { a.adminUserId = b }; this.setFirstTenUserIds = function (b) { a.firstTenUserIds = b }; this.setOpenStatus = function (b) { a.openStatus = b }; this.toArrayBuffer = function () { return a } }, ChannelInfosInput: function () { var a = {}; this.setPage = function (b) { a.page = b }; this.setNumber = function (b) { a.number = b }; this.toArrayBuffer = function () { return a }; }, ChannelInfosOutput: function () { var a = {}; this.setChannels = function (b) { a.channels = b }; this.setTotal = function (b) { a.total = b }; this.toArrayBuffer = function () { return a }; }, MemberInfo: function () { var a = {}; this.setUserId = function (b) { a.userId = b }; this.setUserName = function (b) { a.userName = b }; this.setUserPortrait = function (b) { a.userPortrait = b }; this.setExtension = function (b) { a.extension = b }; this.toArrayBuffer = function () { return a }; }, GroupMembersInput: function () { var a = {}; this.setPage = function (b) { a.page = b }; this.setNumber = function (b) { a.number = b }; this.toArrayBuffer = function () { return a }; }, GroupMembersOutput: function () { var a = {}; this.setMembers = function (b) { a.members = b }; this.setTotal = function (b) { a.total = b }; this.toArrayBuffer = function () { return a }; }, GetUserInfoInput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b }; this.toArrayBuffer = function () { return a }; }, GetUserInfoOutput: function () { var a = {}; this.setUserId = function (b) { a.userId = b }; this.setUserName = function (b) { a.userName = b }; this.setUserPortrait = function (b) { a.userPortrait = b }; this.toArrayBuffer = function () { return a }; }, GetSessionIdInput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b }; this.toArrayBuffer = function () { return a }; }, GetSessionIdOutput: function () { var a = {}; this.setSessionId = function (b) { a.sessionId = b }; this.toArrayBuffer = function () { return a }; }, GetQNupTokenInput: function () { var a = {}; this.setType = function (b) { a.type = b; } this.toArrayBuffer = function () { return a } }, GetQNupTokenOutput: function () { var a = {}; this.setDeadline = function (b) { a.deadline = b }; this.setToken = function (b) { a.token = b; }; this.toArrayBuffer = function () { return a } }, GetQNdownloadUrlInput: function () { var a = {}; this.setType = function (b) { a.type = b; }; this.setKey = function (b) { a.key = b; }; this.setFileName = function(b){ a.fileName = b; }; this.toArrayBuffer = function () { return a } }, GetQNdownloadUrlOutput: function () { var a = {}; this.setDownloadUrl = function (b) { a.downloadUrl = b; }; this.toArrayBuffer = function () { return a } }, Add2BlackListInput: function () { var a = {}; this.setUserId = function (b) { a.userId = b; }; this.toArrayBuffer = function () { return a } }, RemoveFromBlackListInput: function () { var a = {}; this.setUserId = function (b) { a.userId = b; }; this.toArrayBuffer = function () { return a } }, QueryBlackListInput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b; }; this.toArrayBuffer = function () { return a } }, QueryBlackListOutput: function () { var a = {}; this.setUserIds = function (b) { a.userIds = b; }; this.toArrayBuffer = function () { return a } }, BlackListStatusInput: function () { var a = {}; this.setUserId = function (b) { a.userId = b; }; this.toArrayBuffer = function () { return a } }, BlockPushInput: function () { var a = {}; this.setBlockeeId = function (b) { a.blockeeId = b; }; this.toArrayBuffer = function () { return a } }, ModifyPermissionInput: function () { var a = {}; this.setOpenStatus = function (b) { a.openStatus = b; }; this.toArrayBuffer = function () { return a }; }, GroupInput: function () { var a = {}; this.setGroupInfo = function (b) { for (var i = 0, arr = []; i < b.length; i++) { arr.push({id: b[i].getContent().id, name: b[i].getContent().name}) } a.groupInfo = arr; }; this.toArrayBuffer = function () { return a }; }, GroupOutput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b; }; this.toArrayBuffer = function () { return a }; }, GroupInfo: function () { var a = {}; this.setId = function (b) { a.id = b; }; this.setName = function (b) { a.name = b; }; this.getContent = function () { return a; }; this.toArrayBuffer = function () { return a }; }, GroupHashInput: function () { var a = {}; this.setUserId = function (b) { a.userId = b; }; this.setGroupHashCode = function (b) { a.groupHashCode = b; }; this.toArrayBuffer = function () { return a }; }, GroupHashOutput: function () { var a = {}; this.setResult = function (b) { a.result = b; }; this.toArrayBuffer = function () { return a }; }, ChrmInput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b; }; this.toArrayBuffer = function () { return a }; }, ChrmOutput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b; }; this.toArrayBuffer = function () { return a }; }, ChrmPullMsg: function () { var a = {}; this.setSyncTime = function (b) { a.syncTime = b }; this.setCount = function (b) { a.count = b; }; this.toArrayBuffer = function () { return a }; }, RelationsInput: function () { var a = {}; this.setType = function (b) { a.type = b; }; this.setMsg = function(b){ a.msg = b; }; this.setCount = function(b){ a.count = b; }; this.toArrayBuffer = function () { return a }; }, RelationsOutput: function () { var a = {}; this.setInfo = function (b) { a.info = b; }; this.toArrayBuffer = function () { return a } }, RelationInfo: function () { var a = {}; this.setType = function (b) { a.type = b; }; this.setUserId = function (b) { a.userId = b; }; this.setMsg = function(b){ a.msg = b; }; this.toArrayBuffer = function () { return a } }, HistoryMessageInput: function () { var a={}; this.setTargetId=function(b){ a.targetId=b; }; this.setDataTime=function(b){ a.dataTime=b; }; this.setSize=function(b){ a.size=b; }; this.toArrayBuffer = function () { return a } }, HistoryMessagesOuput: function () { var a={}; this.setList=function(b){ a.list=b; }; this.setSyncTime=function(b){ a.syncTime=b; }; this.setHasMsg=function(b){ a.hasMsg=b; }; this.toArrayBuffer = function () { return a } }, HistoryMsgInput: function(){ var a = {}; this.setTargetId = function(b){ a.targetId = b; }; this.setTime = function(b){ a.time = b; }; this.setCount = function(b){ a.count = b; }; this.setOrder = function(b){ a.order = b; }; this.toArrayBuffer = function(){ return a; }; }, HistoryMsgOuput: function(){ var a = {}; this.setList = function(b){ a.list = b; }; this.setSyncTime = function(b){ a.syncTime = b; }; this.setHasMsg = function(b){ a.hasMsg = b; }; this.toArrayBuffer = function(){ return a; }; }, RtcQueryListInput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setOrder = function (b) { a.order = b; }; }, RtcKeyDeleteInput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setKey = function (b) { a.key = b; }; }, RtcValueInfo: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setKey = function (b) { a.key = b; }; this.setValue = function (b) { a.value = b; }; }, // RtcUserInfo: function () { // var a = {}; // }, RtcUserListOutput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setList = function (b) { a.list = b; }; this.setToken = function (b) { a.token = b; }; }, RtcRoomInfoOutput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setRoomId = function (b) { a.roomId = b; }; this.setRoomData = function (b) { a.roomData = b; }; this.setUserCount = function (b) { a.userCount = b; }; this.setList = function (b) { a.list = b; } }, RtcInput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setRoomType = function (b) { a.roomType = b; }; this.setBroadcastType = function (b) { a.broadcastType = b; } }, // RtcQryInput: function () { // var a = {}; // }, RtcQryOutput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setOutInfo = function (b) { a.outInfo = b; }; }, // RtcDelDataInput: function () { // var a = {}; // }, RtcDataInput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setInterior = function (b) { a.interior = b; }; this.setTarget = function (b) { a.target = b; }; this.setKey = function (b) { a.key = b; }; this.setObjectName = function (b) { a.objectName = b; }; this.setContent = function (b) { a.content = b; }; }, RtcSetDataInput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setInterior = function (b) { a.interior = b; }; this.setTarget = function (b) { a.target = b; }; this.setKey = function (b) { a.key = b; }; this.setValue = function (b) { a.value = b; }; this.setObjectName = function (b) { a.objectName = b; }; this.setContent = function (b) { a.content = b; }; }, RtcOutput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setNothing = function (b) { a.nothing = b; }; }, RtcTokenOutput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setRtcToken = function (b) { a.rtcToken = b; } }, /** * 聊天室 KV 存储 */ ChrmNotifyMsg: function () { var a = {}; this.toArrayBuffer = function () { return a; }; this.setType = function (b) { a.type = b; }; this.setTime = function (b) { a.time = b; }; this.setChrmId = function (b) { a.chrmId = b; }; }, ChrmKVEntity: function () { var a = {}; this.toArrayBuffer = function () { return a; }; this.setKey = function (key) { a.key = key; }; this.setValue = function (value) { a.value = value; }; this.setStatus = function (b) { a.status = b; }; this.setTimestamp = function (b) { a.timestamp = b; }; this.setUid = function (b) { a.uid = b; }; }, SetChrmKV: function () { var a = {}; this.toArrayBuffer = function () { return a; }; this.setEntry = function (b) { a.entry = b; }; this.setNotification = function (b) { a.notification = b.toArrayBuffer(); }; this.setBNotify = function (b) { a.bNotify = b; }; this.setType = function (b) { a.type = b; }; }, ChrmKVOutput: function () { var a = {}; this.toArrayBuffer = function () { return a; }; this.setEntries = function (b) { this.entries = b; }; this.setBFullUpdate = function (b) { this.bFullUpdate = b; }; this.setSyncTime = function (b) { this.syncTime = b; }; }, QueryChrmKV: function () { var a = {}; this.toArrayBuffer = function () { return a; }; this.setTimestamp = function (b) { a.timestamp = b; }; }, DeleteChrmKV: function () { var a = {}; this.toArrayBuffer = function () { return a; }; this.setEntry = function (b) { a.entry = b; }; this.setBNotify = function (b) { a.bNotify = b; }; this.setNotification = function (b) { a.notification = b.toArrayBuffer(); }; this.setType = function (b) { a.type = b; }; } }; for (var f in Polling) { Polling[f].decode = function (b) { var back = {}, val = JSON.parse(b) || eval("(" + b + ")"); for (var i in val) { back[i]=val[i]; back["get"+ i.charAt(0).toUpperCase()+i.slice(1)]=function(){ return val[i]; } } return back; } } /* * JavaScript MD5 * https://github.com/blueimp/JavaScript-MD5 * * Copyright 2011, Sebastian Tschan * https://blueimp.net * * Licensed under the MIT license: * http://www.opensource.org/licenses/MIT * * Based on * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message * Digest Algorithm, as defined in RFC 1321. * Version 2.2 Copyright (C) Paul Johnston 1999 - 2009 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet * Distributed under the BSD License * See http://pajhome.org.uk/crypt/md5 for more info. */ /*jslint bitwise: true */ /*global unescape, define, module */ var md5 = (function () { 'use strict'; /* * Add integers, wrapping at 2^32. This uses 16-bit operations internally * to work around bugs in some JS interpreters. */ function safe_add(x, y) { var lsw = (x & 0xFFFF) + (y & 0xFFFF), msw = (x >> 16) + (y >> 16) + (lsw >> 16); return (msw << 16) | (lsw & 0xFFFF); } /* * Bitwise rotate a 32-bit number to the left. */ function bit_rol(num, cnt) { return (num << cnt) | (num >>> (32 - cnt)); } /* * These functions implement the four basic operations the algorithm uses. */ function md5_cmn(q, a, b, x, s, t) { return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s), b); } function md5_ff(a, b, c, d, x, s, t) { return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t); } function md5_gg(a, b, c, d, x, s, t) { return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t); } function md5_hh(a, b, c, d, x, s, t) { return md5_cmn(b ^ c ^ d, a, b, x, s, t); } function md5_ii(a, b, c, d, x, s, t) { return md5_cmn(c ^ (b | (~d)), a, b, x, s, t); } /* * Calculate the MD5 of an array of little-endian words, and a bit length. */ function binl_md5(x, len) { /* append padding */ x[len >> 5] |= 0x80 << (len % 32); x[(((len + 64) >>> 9) << 4) + 14] = len; var i, olda, oldb, oldc, oldd, a = 1732584193, b = -271733879, c = -1732584194, d = 271733878; for (i = 0; i < x.length; i += 16) { olda = a; oldb = b; oldc = c; oldd = d; a = md5_ff(a, b, c, d, x[i], 7, -680876936); d = md5_ff(d, a, b, c, x[i + 1], 12, -389564586); c = md5_ff(c, d, a, b, x[i + 2], 17, 606105819); b = md5_ff(b, c, d, a, x[i + 3], 22, -1044525330); a = md5_ff(a, b, c, d, x[i + 4], 7, -176418897); d = md5_ff(d, a, b, c, x[i + 5], 12, 1200080426); c = md5_ff(c, d, a, b, x[i + 6], 17, -1473231341); b = md5_ff(b, c, d, a, x[i + 7], 22, -45705983); a = md5_ff(a, b, c, d, x[i + 8], 7, 1770035416); d = md5_ff(d, a, b, c, x[i + 9], 12, -1958414417); c = md5_ff(c, d, a, b, x[i + 10], 17, -42063); b = md5_ff(b, c, d, a, x[i + 11], 22, -1990404162); a = md5_ff(a, b, c, d, x[i + 12], 7, 1804603682); d = md5_ff(d, a, b, c, x[i + 13], 12, -40341101); c = md5_ff(c, d, a, b, x[i + 14], 17, -1502002290); b = md5_ff(b, c, d, a, x[i + 15], 22, 1236535329); a = md5_gg(a, b, c, d, x[i + 1], 5, -165796510); d = md5_gg(d, a, b, c, x[i + 6], 9, -1069501632); c = md5_gg(c, d, a, b, x[i + 11], 14, 643717713); b = md5_gg(b, c, d, a, x[i], 20, -373897302); a = md5_gg(a, b, c, d, x[i + 5], 5, -701558691); d = md5_gg(d, a, b, c, x[i + 10], 9, 38016083); c = md5_gg(c, d, a, b, x[i + 15], 14, -660478335); b = md5_gg(b, c, d, a, x[i + 4], 20, -405537848); a = md5_gg(a, b, c, d, x[i + 9], 5, 568446438); d = md5_gg(d, a, b, c, x[i + 14], 9, -1019803690); c = md5_gg(c, d, a, b, x[i + 3], 14, -187363961); b = md5_gg(b, c, d, a, x[i + 8], 20, 1163531501); a = md5_gg(a, b, c, d, x[i + 13], 5, -1444681467); d = md5_gg(d, a, b, c, x[i + 2], 9, -51403784); c = md5_gg(c, d, a, b, x[i + 7], 14, 1735328473); b = md5_gg(b, c, d, a, x[i + 12], 20, -1926607734); a = md5_hh(a, b, c, d, x[i + 5], 4, -378558); d = md5_hh(d, a, b, c, x[i + 8], 11, -2022574463); c = md5_hh(c, d, a, b, x[i + 11], 16, 1839030562); b = md5_hh(b, c, d, a, x[i + 14], 23, -35309556); a = md5_hh(a, b, c, d, x[i + 1], 4, -1530992060); d = md5_hh(d, a, b, c, x[i + 4], 11, 1272893353); c = md5_hh(c, d, a, b, x[i + 7], 16, -155497632); b = md5_hh(b, c, d, a, x[i + 10], 23, -1094730640); a = md5_hh(a, b, c, d, x[i + 13], 4, 681279174); d = md5_hh(d, a, b, c, x[i], 11, -358537222); c = md5_hh(c, d, a, b, x[i + 3], 16, -722521979); b = md5_hh(b, c, d, a, x[i + 6], 23, 76029189); a = md5_hh(a, b, c, d, x[i + 9], 4, -640364487); d = md5_hh(d, a, b, c, x[i + 12], 11, -421815835); c = md5_hh(c, d, a, b, x[i + 15], 16, 530742520); b = md5_hh(b, c, d, a, x[i + 2], 23, -995338651); a = md5_ii(a, b, c, d, x[i], 6, -198630844); d = md5_ii(d, a, b, c, x[i + 7], 10, 1126891415); c = md5_ii(c, d, a, b, x[i + 14], 15, -1416354905); b = md5_ii(b, c, d, a, x[i + 5], 21, -57434055); a = md5_ii(a, b, c, d, x[i + 12], 6, 1700485571); d = md5_ii(d, a, b, c, x[i + 3], 10, -1894986606); c = md5_ii(c, d, a, b, x[i + 10], 15, -1051523); b = md5_ii(b, c, d, a, x[i + 1], 21, -2054922799); a = md5_ii(a, b, c, d, x[i + 8], 6, 1873313359); d = md5_ii(d, a, b, c, x[i + 15], 10, -30611744); c = md5_ii(c, d, a, b, x[i + 6], 15, -1560198380); b = md5_ii(b, c, d, a, x[i + 13], 21, 1309151649); a = md5_ii(a, b, c, d, x[i + 4], 6, -145523070); d = md5_ii(d, a, b, c, x[i + 11], 10, -1120210379); c = md5_ii(c, d, a, b, x[i + 2], 15, 718787259); b = md5_ii(b, c, d, a, x[i + 9], 21, -343485551); a = safe_add(a, olda); b = safe_add(b, oldb); c = safe_add(c, oldc); d = safe_add(d, oldd); } return [a, b, c, d]; } /* * Convert an array of little-endian words to a string */ function binl2rstr(input) { var i, output = ''; for (i = 0; i < input.length * 32; i += 8) { output += String.fromCharCode((input[i >> 5] >>> (i % 32)) & 0xFF); } return output; } /* * Convert a raw string to an array of little-endian words * Characters >255 have their high-byte silently ignored. */ function rstr2binl(input) { var i, output = []; output[(input.length >> 2) - 1] = undefined; for (i = 0; i < output.length; i += 1) { output[i] = 0; } for (i = 0; i < input.length * 8; i += 8) { output[i >> 5] |= (input.charCodeAt(i / 8) & 0xFF) << (i % 32); } return output; } /* * Calculate the MD5 of a raw string */ function rstr_md5(s) { return binl2rstr(binl_md5(rstr2binl(s), s.length * 8)); } /* * Calculate the HMAC-MD5, of a key and some data (raw strings) */ function rstr_hmac_md5(key, data) { var i, bkey = rstr2binl(key), ipad = [], opad = [], hash; ipad[15] = opad[15] = undefined; if (bkey.length > 16) { bkey = binl_md5(bkey, key.length * 8); } for (i = 0; i < 16; i += 1) { ipad[i] = bkey[i] ^ 0x36363636; opad[i] = bkey[i] ^ 0x5C5C5C5C; } hash = binl_md5(ipad.concat(rstr2binl(data)), 512 + data.length * 8); return binl2rstr(binl_md5(opad.concat(hash), 512 + 128)); } /* * Convert a raw string to a hex string */ function rstr2hex(input) { var hex_tab = '0123456789abcdef', output = '', x, i; for (i = 0; i < input.length; i += 1) { x = input.charCodeAt(i); output += hex_tab.charAt((x >>> 4) & 0x0F) + hex_tab.charAt(x & 0x0F); } return output; } /* * Encode a string as utf-8 */ function str2rstr_utf8(input) { return unescape(encodeURIComponent(input)); } /* * Take string arguments and return either raw or hex encoded strings */ function raw_md5(s) { return rstr_md5(str2rstr_utf8(s)); } function hex_md5(s) { return rstr2hex(raw_md5(s)); } function raw_hmac_md5(k, d) { return rstr_hmac_md5(str2rstr_utf8(k), str2rstr_utf8(d)); } function hex_hmac_md5(k, d) { return rstr2hex(raw_hmac_md5(k, d)); } function md5(string, key, raw) { if (!key) { if (!raw) { return hex_md5(string); } return raw_md5(string); } if (!raw) { return hex_hmac_md5(key, string); } return raw_hmac_md5(key, string); } return md5; }()); var RongIMLib; (function (RongIMLib) { (function (MentionedType) { MentionedType[MentionedType["ALL"] = 1] = "ALL"; MentionedType[MentionedType["PART"] = 2] = "PART"; })(RongIMLib.MentionedType || (RongIMLib.MentionedType = {})); var MentionedType = RongIMLib.MentionedType; (function (MethodType) { MethodType[MethodType["CUSTOMER_SERVICE"] = 1] = "CUSTOMER_SERVICE"; MethodType[MethodType["RECALL"] = 2] = "RECALL"; })(RongIMLib.MethodType || (RongIMLib.MethodType = {})); var MethodType = RongIMLib.MethodType; (function (BlacklistStatus) { /** * 在黑名单中。 */ BlacklistStatus[BlacklistStatus["IN_BLACK_LIST"] = 0] = "IN_BLACK_LIST"; /** * 不在黑名单中。 */ BlacklistStatus[BlacklistStatus["NOT_IN_BLACK_LIST"] = 1] = "NOT_IN_BLACK_LIST"; })(RongIMLib.BlacklistStatus || (RongIMLib.BlacklistStatus = {})); var BlacklistStatus = RongIMLib.BlacklistStatus; (function (ConnectionChannel) { ConnectionChannel[ConnectionChannel["XHR_POLLING"] = 0] = "XHR_POLLING"; ConnectionChannel[ConnectionChannel["WEBSOCKET"] = 1] = "WEBSOCKET"; //外部调用 ConnectionChannel[ConnectionChannel["HTTP"] = 0] = "HTTP"; //外部调用 ConnectionChannel[ConnectionChannel["HTTPS"] = 1] = "HTTPS"; })(RongIMLib.ConnectionChannel || (RongIMLib.ConnectionChannel = {})); var ConnectionChannel = RongIMLib.ConnectionChannel; (function (CustomerType) { CustomerType[CustomerType["ONLY_ROBOT"] = 1] = "ONLY_ROBOT"; CustomerType[CustomerType["ONLY_HUMAN"] = 2] = "ONLY_HUMAN"; CustomerType[CustomerType["ROBOT_FIRST"] = 3] = "ROBOT_FIRST"; CustomerType[CustomerType["HUMAN_FIRST"] = 4] = "HUMAN_FIRST"; })(RongIMLib.CustomerType || (RongIMLib.CustomerType = {})); var CustomerType = RongIMLib.CustomerType; (function (GetChatRoomType) { GetChatRoomType[GetChatRoomType["NONE"] = 0] = "NONE"; GetChatRoomType[GetChatRoomType["SQQUENCE"] = 1] = "SQQUENCE"; GetChatRoomType[GetChatRoomType["REVERSE"] = 2] = "REVERSE"; })(RongIMLib.GetChatRoomType || (RongIMLib.GetChatRoomType = {})); var GetChatRoomType = RongIMLib.GetChatRoomType; (function (ConnectionStatus) { /** * 连接成功。 */ ConnectionStatus[ConnectionStatus["CONNECTED"] = 0] = "CONNECTED"; /** * 连接中。 */ ConnectionStatus[ConnectionStatus["CONNECTING"] = 1] = "CONNECTING"; /** * 断开连接。 */ ConnectionStatus[ConnectionStatus["DISCONNECTED"] = 2] = "DISCONNECTED"; /** * 用户账户在其他设备登录,本机会被踢掉线。 */ ConnectionStatus[ConnectionStatus["KICKED_OFFLINE_BY_OTHER_CLIENT"] = 6] = "KICKED_OFFLINE_BY_OTHER_CLIENT"; /** * websocket 连接失败 */ ConnectionStatus[ConnectionStatus["WEBSOCKET_UNAVAILABLE"] = 7] = "WEBSOCKET_UNAVAILABLE"; /** * websocket 报错 */ ConnectionStatus[ConnectionStatus["WEBSOCKET_ERROR"] = 8] = "WEBSOCKET_ERROR"; /** * 网络不可用。 */ ConnectionStatus[ConnectionStatus["NETWORK_UNAVAILABLE"] = 3] = "NETWORK_UNAVAILABLE"; /** * 域名错误 */ ConnectionStatus[ConnectionStatus["DOMAIN_INCORRECT"] = 12] = "DOMAIN_INCORRECT"; /** * appkey 不正确 */ ConnectionStatus[ConnectionStatus["APPKEY_IS_FAKE"] = 20] = "APPKEY_IS_FAKE"; /** * 连接关闭。 */ ConnectionStatus[ConnectionStatus["CONNECTION_CLOSED"] = 4] = "CONNECTION_CLOSED"; /* 互踢次数过多(count > 5),此时可能出现:在其它他设备登陆有 reconnect 逻辑 */ ConnectionStatus[ConnectionStatus["ULTRALIMIT"] = 1101] = "ULTRALIMIT"; /* 开始请求导航 */ ConnectionStatus[ConnectionStatus["REQUEST_NAVI"] = 201] = "REQUEST_NAVI"; /* 请求导航结束 */ ConnectionStatus[ConnectionStatus["RESPONSE_NAVI"] = 202] = "RESPONSE_NAVI"; /* 请求导航失败 */ ConnectionStatus[ConnectionStatus["RESPONSE_NAVI_ERROR"] = 203] = "RESPONSE_NAVI_ERROR"; /* 请求导航超时 */ ConnectionStatus[ConnectionStatus["RESPONSE_NAVI_TIMEOUT"] = 204] = "RESPONSE_NAVI_TIMEOUT"; })(RongIMLib.ConnectionStatus || (RongIMLib.ConnectionStatus = {})); var ConnectionStatus = RongIMLib.ConnectionStatus; (function (ConversationNotificationStatus) { /** * 免打扰状态,关闭对应会话的通知提醒。 */ ConversationNotificationStatus[ConversationNotificationStatus["DO_NOT_DISTURB"] = 1] = "DO_NOT_DISTURB"; /** * 提醒。 */ ConversationNotificationStatus[ConversationNotificationStatus["NOTIFY"] = 2] = "NOTIFY"; })(RongIMLib.ConversationNotificationStatus || (RongIMLib.ConversationNotificationStatus = {})); var ConversationNotificationStatus = RongIMLib.ConversationNotificationStatus; (function (ConversationType) { ConversationType[ConversationType["NONE"] = 0] = "NONE"; ConversationType[ConversationType["PRIVATE"] = 1] = "PRIVATE"; ConversationType[ConversationType["DISCUSSION"] = 2] = "DISCUSSION"; ConversationType[ConversationType["GROUP"] = 3] = "GROUP"; ConversationType[ConversationType["CHATROOM"] = 4] = "CHATROOM"; ConversationType[ConversationType["CUSTOMER_SERVICE"] = 5] = "CUSTOMER_SERVICE"; ConversationType[ConversationType["SYSTEM"] = 6] = "SYSTEM"; //默认关注 MC ConversationType[ConversationType["APP_PUBLIC_SERVICE"] = 7] = "APP_PUBLIC_SERVICE"; //手工关注 MP ConversationType[ConversationType["PUBLIC_SERVICE"] = 8] = "PUBLIC_SERVICE"; })(RongIMLib.ConversationType || (RongIMLib.ConversationType = {})); var ConversationType = RongIMLib.ConversationType; (function (DiscussionInviteStatus) { /** * 开放邀请。 */ DiscussionInviteStatus[DiscussionInviteStatus["OPENED"] = 0] = "OPENED"; /** * 关闭邀请。 */ DiscussionInviteStatus[DiscussionInviteStatus["CLOSED"] = 1] = "CLOSED"; })(RongIMLib.DiscussionInviteStatus || (RongIMLib.DiscussionInviteStatus = {})); var DiscussionInviteStatus = RongIMLib.DiscussionInviteStatus; (function (ErrorCode) { /* 超时 */ ErrorCode[ErrorCode["TIMEOUT"] = -1] = "TIMEOUT"; /** * 未知原因失败。 */ ErrorCode[ErrorCode["UNKNOWN"] = -2] = "UNKNOWN"; /* 参数错误 */ ErrorCode[ErrorCode["PARAMETER_ERROR"] = -3] = "PARAMETER_ERROR"; ErrorCode[ErrorCode["RECALL_MESSAGE"] = 25101] = "RECALL_MESSAGE"; /** * 发送频率过快 */ ErrorCode[ErrorCode["SEND_FREQUENCY_TOO_FAST"] = 20604] = "SEND_FREQUENCY_TOO_FAST"; ErrorCode[ErrorCode["RC_MSG_UNAUTHORIZED"] = 20406] = "RC_MSG_UNAUTHORIZED"; /** * 群组 Id 无效 */ ErrorCode[ErrorCode["RC_DISCUSSION_GROUP_ID_INVALID"] = 20407] = "RC_DISCUSSION_GROUP_ID_INVALID"; /** * 群组被禁言 */ ErrorCode[ErrorCode["FORBIDDEN_IN_GROUP"] = 22408] = "FORBIDDEN_IN_GROUP"; /** * 不在讨论组。 */ ErrorCode[ErrorCode["NOT_IN_DISCUSSION"] = 21406] = "NOT_IN_DISCUSSION"; /** * 不在群组。 */ ErrorCode[ErrorCode["NOT_IN_GROUP"] = 22406] = "NOT_IN_GROUP"; /** * 不在聊天室。 */ ErrorCode[ErrorCode["NOT_IN_CHATROOM"] = 23406] = "NOT_IN_CHATROOM"; /** *聊天室被禁言 */ ErrorCode[ErrorCode["FORBIDDEN_IN_CHATROOM"] = 23408] = "FORBIDDEN_IN_CHATROOM"; /** * 聊天室中成员被踢出 */ ErrorCode[ErrorCode["RC_CHATROOM_USER_KICKED"] = 23409] = "RC_CHATROOM_USER_KICKED"; /** * 聊天室不存在 */ ErrorCode[ErrorCode["RC_CHATROOM_NOT_EXIST"] = 23410] = "RC_CHATROOM_NOT_EXIST"; /** * 聊天室成员已满 */ ErrorCode[ErrorCode["RC_CHATROOM_IS_FULL"] = 23411] = "RC_CHATROOM_IS_FULL"; /** * 获取聊天室信息参数无效 */ ErrorCode[ErrorCode["RC_CHATROOM_PATAMETER_INVALID"] = 23412] = "RC_CHATROOM_PATAMETER_INVALID"; /** * 聊天室异常 */ ErrorCode[ErrorCode["CHATROOM_GET_HISTORYMSG_ERROR"] = 23413] = "CHATROOM_GET_HISTORYMSG_ERROR"; /** * 没有打开聊天室消息存储 */ ErrorCode[ErrorCode["CHATROOM_NOT_OPEN_HISTORYMSG_STORE"] = 23414] = "CHATROOM_NOT_OPEN_HISTORYMSG_STORE"; /** * 聊天室 KV 设置超出最大值(已满, 默认最多设置 100 个) */ ErrorCode[ErrorCode["CHATROOM_KV_EXCEED"] = 23423] = "CHATROOM_KV_EXCEED"; /** * 聊天室 KV 设置失败(kv 已存在, 需覆盖设置) */ ErrorCode[ErrorCode["CHATROOM_KV_OVERWRITE_INVALID"] = 23424] = "CHATROOM_KV_OVERWRITE_INVALID"; /** * 聊天室 KV 存储功能没有开通 */ ErrorCode[ErrorCode["CHATROOM_KV_STORE_NOT_OPEN"] = 23426] = "CHATROOM_KV_STORE_NOT_OPEN"; /** * 聊天室Key不存在 */ ErrorCode[ErrorCode["CHATROOM_KEY_NOT_EXIST"] = 23427] = "CHATROOM_KEY_NOT_EXIST"; /** * 敏感词屏蔽 */ ErrorCode[ErrorCode["SENSITIVE_SHIELD"] = 21501] = "SENSITIVE_SHIELD"; ErrorCode[ErrorCode["SENSITIVE_REPLACE"] = 21502] = "SENSITIVE_REPLACE"; /** * 加入讨论失败 */ ErrorCode[ErrorCode["JOIN_IN_DISCUSSION"] = 21407] = "JOIN_IN_DISCUSSION"; /** * 创建讨论组失败 */ ErrorCode[ErrorCode["CREATE_DISCUSSION"] = 21408] = "CREATE_DISCUSSION"; /** * 设置讨论组邀请状态失败 */ ErrorCode[ErrorCode["INVITE_DICUSSION"] = 21409] = "INVITE_DICUSSION"; /** *获取用户失败 */ ErrorCode[ErrorCode["GET_USERINFO_ERROR"] = 23407] = "GET_USERINFO_ERROR"; /** * 在黑名单中。 */ ErrorCode[ErrorCode["REJECTED_BY_BLACKLIST"] = 405] = "REJECTED_BY_BLACKLIST"; /** * 通信过程中,当前 Socket 不存在。 */ ErrorCode[ErrorCode["RC_NET_CHANNEL_INVALID"] = 30001] = "RC_NET_CHANNEL_INVALID"; /** * Socket 连接不可用。 */ ErrorCode[ErrorCode["RC_NET_UNAVAILABLE"] = 30002] = "RC_NET_UNAVAILABLE"; /** * 通信超时。 */ ErrorCode[ErrorCode["RC_MSG_RESP_TIMEOUT"] = 30003] = "RC_MSG_RESP_TIMEOUT"; /** * 导航操作时,Http 请求失败。 */ ErrorCode[ErrorCode["RC_HTTP_SEND_FAIL"] = 30004] = "RC_HTTP_SEND_FAIL"; /** * HTTP 请求失败。 */ ErrorCode[ErrorCode["RC_HTTP_REQ_TIMEOUT"] = 30005] = "RC_HTTP_REQ_TIMEOUT"; /** * HTTP 接收失败。 */ ErrorCode[ErrorCode["RC_HTTP_RECV_FAIL"] = 30006] = "RC_HTTP_RECV_FAIL"; /** * 导航操作的 HTTP 请求,返回不是200。 */ ErrorCode[ErrorCode["RC_NAVI_RESOURCE_ERROR"] = 30007] = "RC_NAVI_RESOURCE_ERROR"; /** * 导航数据解析后,其中不存在有效数据。 */ ErrorCode[ErrorCode["RC_NODE_NOT_FOUND"] = 30008] = "RC_NODE_NOT_FOUND"; /** * 导航数据解析后,其中不存在有效 IP 地址。 */ ErrorCode[ErrorCode["RC_DOMAIN_NOT_RESOLVE"] = 30009] = "RC_DOMAIN_NOT_RESOLVE"; /** * 创建 Socket 失败。 */ ErrorCode[ErrorCode["RC_SOCKET_NOT_CREATED"] = 30010] = "RC_SOCKET_NOT_CREATED"; /** * Socket 被断开。 */ ErrorCode[ErrorCode["RC_SOCKET_DISCONNECTED"] = 30011] = "RC_SOCKET_DISCONNECTED"; /** * PING 操作失败。 */ ErrorCode[ErrorCode["RC_PING_SEND_FAIL"] = 30012] = "RC_PING_SEND_FAIL"; /** * PING 超时。 */ ErrorCode[ErrorCode["RC_PONG_RECV_FAIL"] = 30013] = "RC_PONG_RECV_FAIL"; /** * 消息发送失败。 */ ErrorCode[ErrorCode["RC_MSG_SEND_FAIL"] = 30014] = "RC_MSG_SEND_FAIL"; /** * JSON 后的消息体超限, 目前最大 128kb * */ ErrorCode[ErrorCode["RC_MSG_CONTENT_EXCEED_LIMIT"] = 30016] = "RC_MSG_CONTENT_EXCEED_LIMIT"; /** * 做 connect 连接时,收到的 ACK 超时。 */ ErrorCode[ErrorCode["RC_CONN_ACK_TIMEOUT"] = 31000] = "RC_CONN_ACK_TIMEOUT"; /** * 参数错误。 */ ErrorCode[ErrorCode["RC_CONN_PROTO_VERSION_ERROR"] = 31001] = "RC_CONN_PROTO_VERSION_ERROR"; /** * 参数错误,App Id 错误。 */ ErrorCode[ErrorCode["RC_CONN_ID_REJECT"] = 31002] = "RC_CONN_ID_REJECT"; /** * 服务器不可用。 */ ErrorCode[ErrorCode["RC_CONN_SERVER_UNAVAILABLE"] = 31003] = "RC_CONN_SERVER_UNAVAILABLE"; /** * Token 错误。 */ ErrorCode[ErrorCode["RC_CONN_USER_OR_PASSWD_ERROR"] = 31004] = "RC_CONN_USER_OR_PASSWD_ERROR"; /** * App Id 与 Token 不匹配。 */ ErrorCode[ErrorCode["RC_CONN_NOT_AUTHRORIZED"] = 31005] = "RC_CONN_NOT_AUTHRORIZED"; /** * 重定向,地址错误。 */ ErrorCode[ErrorCode["RC_CONN_REDIRECTED"] = 31006] = "RC_CONN_REDIRECTED"; /** * NAME 与后台注册信息不一致。 */ ErrorCode[ErrorCode["RC_CONN_PACKAGE_NAME_INVALID"] = 31007] = "RC_CONN_PACKAGE_NAME_INVALID"; /** * APP 被屏蔽、删除或不存在。 */ ErrorCode[ErrorCode["RC_CONN_APP_BLOCKED_OR_DELETED"] = 31008] = "RC_CONN_APP_BLOCKED_OR_DELETED"; /** * 用户被屏蔽。 */ ErrorCode[ErrorCode["RC_CONN_USER_BLOCKED"] = 31009] = "RC_CONN_USER_BLOCKED"; /** * Disconnect,由服务器返回,比如用户互踢。 */ ErrorCode[ErrorCode["RC_DISCONN_KICK"] = 31010] = "RC_DISCONN_KICK"; /** * Disconnect,由服务器返回,比如用户互踢。 */ ErrorCode[ErrorCode["RC_DISCONN_EXCEPTION"] = 31011] = "RC_DISCONN_EXCEPTION"; /** * 协议层内部错误。query,上传下载过程中数据错误。 */ ErrorCode[ErrorCode["RC_QUERY_ACK_NO_DATA"] = 32001] = "RC_QUERY_ACK_NO_DATA"; /** * 协议层内部错误。 */ ErrorCode[ErrorCode["RC_MSG_DATA_INCOMPLETE"] = 32002] = "RC_MSG_DATA_INCOMPLETE"; /** * 未调用 init 初始化函数。 */ ErrorCode[ErrorCode["BIZ_ERROR_CLIENT_NOT_INIT"] = 33001] = "BIZ_ERROR_CLIENT_NOT_INIT"; /** * 数据库初始化失败。 */ ErrorCode[ErrorCode["BIZ_ERROR_DATABASE_ERROR"] = 33002] = "BIZ_ERROR_DATABASE_ERROR"; /** * 传入参数无效。 */ ErrorCode[ErrorCode["BIZ_ERROR_INVALID_PARAMETER"] = 33003] = "BIZ_ERROR_INVALID_PARAMETER"; /** * 通道无效。 */ ErrorCode[ErrorCode["BIZ_ERROR_NO_CHANNEL"] = 33004] = "BIZ_ERROR_NO_CHANNEL"; /** * 重新连接成功。 */ ErrorCode[ErrorCode["BIZ_ERROR_RECONNECT_SUCCESS"] = 33005] = "BIZ_ERROR_RECONNECT_SUCCESS"; /** * 连接中,再调用 connect 被拒绝。 */ ErrorCode[ErrorCode["BIZ_ERROR_CONNECTING"] = 33006] = "BIZ_ERROR_CONNECTING"; /** * 消息漫游服务未开通 */ ErrorCode[ErrorCode["MSG_ROAMING_SERVICE_UNAVAILABLE"] = 33007] = "MSG_ROAMING_SERVICE_UNAVAILABLE"; ErrorCode[ErrorCode["MSG_INSERT_ERROR"] = 33008] = "MSG_INSERT_ERROR"; ErrorCode[ErrorCode["MSG_DEL_ERROR"] = 33009] = "MSG_DEL_ERROR"; /** * 删除会话失败 */ ErrorCode[ErrorCode["CONVER_REMOVE_ERROR"] = 34001] = "CONVER_REMOVE_ERROR"; /** *拉取历史消息 */ ErrorCode[ErrorCode["CONVER_GETLIST_ERROR"] = 34002] = "CONVER_GETLIST_ERROR"; /** * 会话指定异常 */ ErrorCode[ErrorCode["CONVER_SETOP_ERROR"] = 34003] = "CONVER_SETOP_ERROR"; /** * 获取会话未读消息总数失败 */ ErrorCode[ErrorCode["CONVER_TOTAL_UNREAD_ERROR"] = 34004] = "CONVER_TOTAL_UNREAD_ERROR"; /** * 获取指定会话类型未读消息数异常 */ ErrorCode[ErrorCode["CONVER_TYPE_UNREAD_ERROR"] = 34005] = "CONVER_TYPE_UNREAD_ERROR"; /** * 获取指定用户ID&会话类型未读消息数异常 */ ErrorCode[ErrorCode["CONVER_ID_TYPE_UNREAD_ERROR"] = 34006] = "CONVER_ID_TYPE_UNREAD_ERROR"; ErrorCode[ErrorCode["CONVER_CLEAR_ERROR"] = 34007] = "CONVER_CLEAR_ERROR"; ErrorCode[ErrorCode["CLEAR_HIS_ERROR"] = 34010] = "CLEAR_HIS_ERROR"; ErrorCode[ErrorCode["CLEAR_HIS_TYPE_ERROR"] = 34008] = "CLEAR_HIS_TYPE_ERROR"; ErrorCode[ErrorCode["CLEAR_HIS_TIME_ERROR"] = 34011] = "CLEAR_HIS_TIME_ERROR"; /* */ ErrorCode[ErrorCode["CONVER_GET_ERROR"] = 34009] = "CONVER_GET_ERROR"; //群组异常信息 /** * */ ErrorCode[ErrorCode["GROUP_SYNC_ERROR"] = 35001] = "GROUP_SYNC_ERROR"; /** * 匹配群信息异常 */ ErrorCode[ErrorCode["GROUP_MATCH_ERROR"] = 35002] = "GROUP_MATCH_ERROR"; //聊天室异常 /** * 加入聊天室Id为空 */ ErrorCode[ErrorCode["CHATROOM_ID_ISNULL"] = 36001] = "CHATROOM_ID_ISNULL"; /** * 加入聊天室失败 */ ErrorCode[ErrorCode["CHARTOOM_JOIN_ERROR"] = 36002] = "CHARTOOM_JOIN_ERROR"; /** * 拉取聊天室历史消息失败 */ ErrorCode[ErrorCode["CHATROOM_HISMESSAGE_ERROR"] = 36003] = "CHATROOM_HISMESSAGE_ERROR"; /** * 聊天室 kv 未找到 * */ ErrorCode[ErrorCode["CHATROOM_KV_NOT_FOUND"] = 36004] = "CHATROOM_KV_NOT_FOUND"; //黑名单异常 /** * 加入黑名单异常 */ ErrorCode[ErrorCode["BLACK_ADD_ERROR"] = 37001] = "BLACK_ADD_ERROR"; /** * 获得指定人员再黑名单中的状态异常 */ ErrorCode[ErrorCode["BLACK_GETSTATUS_ERROR"] = 37002] = "BLACK_GETSTATUS_ERROR"; /** * 移除黑名单异常 */ ErrorCode[ErrorCode["BLACK_REMOVE_ERROR"] = 37003] = "BLACK_REMOVE_ERROR"; /** * 获取草稿失败 */ ErrorCode[ErrorCode["DRAF_GET_ERROR"] = 38001] = "DRAF_GET_ERROR"; /** * 保存草稿失败 */ ErrorCode[ErrorCode["DRAF_SAVE_ERROR"] = 38002] = "DRAF_SAVE_ERROR"; /** * 删除草稿失败 */ ErrorCode[ErrorCode["DRAF_REMOVE_ERROR"] = 38003] = "DRAF_REMOVE_ERROR"; /** * 关注公众号失败 */ ErrorCode[ErrorCode["SUBSCRIBE_ERROR"] = 39001] = "SUBSCRIBE_ERROR"; /** * 关注公众号失败 */ ErrorCode[ErrorCode["QNTKN_FILETYPE_ERROR"] = 41001] = "QNTKN_FILETYPE_ERROR"; /** * 获取七牛token失败 */ ErrorCode[ErrorCode["QNTKN_GET_ERROR"] = 41002] = "QNTKN_GET_ERROR"; /** * cookie被禁用 */ ErrorCode[ErrorCode["COOKIE_ENABLE"] = 51001] = "COOKIE_ENABLE"; ErrorCode[ErrorCode["GET_MESSAGE_BY_ID_ERROR"] = 61001] = "GET_MESSAGE_BY_ID_ERROR"; // 没有注册DeviveId 也就是用户没有登陆 ErrorCode[ErrorCode["HAVNODEVICEID"] = 24001] = "HAVNODEVICEID"; // 已经存在 ErrorCode[ErrorCode["DEVICEIDISHAVE"] = 24002] = "DEVICEIDISHAVE"; // 成功 ErrorCode[ErrorCode["SUCCESS"] = 0] = "SUCCESS"; // 没有对应的用户或token ErrorCode[ErrorCode["FEILD"] = 24009] = "FEILD"; // voip为空 ErrorCode[ErrorCode["VOIPISNULL"] = 24013] = "VOIPISNULL"; // 不支持的Voip引擎 ErrorCode[ErrorCode["NOENGINETYPE"] = 24010] = "NOENGINETYPE"; // channleName 是空 ErrorCode[ErrorCode["NULLCHANNELNAME"] = 24011] = "NULLCHANNELNAME"; // 生成Voipkey失败 ErrorCode[ErrorCode["VOIPDYANMICERROR"] = 24012] = "VOIPDYANMICERROR"; // 没有配置voip ErrorCode[ErrorCode["NOVOIP"] = 24014] = "NOVOIP"; // 服务器内部错误 ErrorCode[ErrorCode["INTERNALERRROR"] = 24015] = "INTERNALERRROR"; //VOIP close ErrorCode[ErrorCode["VOIPCLOSE"] = 24016] = "VOIPCLOSE"; ErrorCode[ErrorCode["CLOSE_BEFORE_OPEN"] = 51001] = "CLOSE_BEFORE_OPEN"; ErrorCode[ErrorCode["ALREADY_IN_USE"] = 51002] = "ALREADY_IN_USE"; ErrorCode[ErrorCode["INVALID_CHANNEL_NAME"] = 51003] = "INVALID_CHANNEL_NAME"; ErrorCode[ErrorCode["VIDEO_CONTAINER_IS_NULL"] = 51004] = "VIDEO_CONTAINER_IS_NULL"; /** * 删除消息数组长度为 0 . */ ErrorCode[ErrorCode["DELETE_MESSAGE_ID_IS_NULL"] = 61001] = "DELETE_MESSAGE_ID_IS_NULL"; /*! 己方取消已发出的通话请求 */ ErrorCode[ErrorCode["CANCEL"] = 1] = "CANCEL"; /*! 己方拒绝收到的通话请求 */ ErrorCode[ErrorCode["REJECT"] = 2] = "REJECT"; /*! 己方挂断 */ ErrorCode[ErrorCode["HANGUP"] = 3] = "HANGUP"; /*! 己方忙碌 */ ErrorCode[ErrorCode["BUSYLINE"] = 4] = "BUSYLINE"; /*! 己方未接听 */ ErrorCode[ErrorCode["NO_RESPONSE"] = 5] = "NO_RESPONSE"; /*! 己方不支持当前引擎 */ ErrorCode[ErrorCode["ENGINE_UN_SUPPORTED"] = 6] = "ENGINE_UN_SUPPORTED"; /*! 己方网络出错 */ ErrorCode[ErrorCode["NETWORK_ERROR"] = 7] = "NETWORK_ERROR"; /*! 对方取消已发出的通话请求 */ ErrorCode[ErrorCode["REMOTE_CANCEL"] = 11] = "REMOTE_CANCEL"; /*! 对方拒绝收到的通话请求 */ ErrorCode[ErrorCode["REMOTE_REJECT"] = 12] = "REMOTE_REJECT"; /*! 通话过程对方挂断 */ ErrorCode[ErrorCode["REMOTE_HANGUP"] = 13] = "REMOTE_HANGUP"; /*! 对方忙碌 */ ErrorCode[ErrorCode["REMOTE_BUSYLINE"] = 14] = "REMOTE_BUSYLINE"; /*! 对方未接听 */ ErrorCode[ErrorCode["REMOTE_NO_RESPONSE"] = 15] = "REMOTE_NO_RESPONSE"; /*! 对方网络错误 */ ErrorCode[ErrorCode["REMOTE_ENGINE_UN_SUPPORTED"] = 16] = "REMOTE_ENGINE_UN_SUPPORTED"; /*! 对方网络错误 */ ErrorCode[ErrorCode["REMOTE_NETWORK_ERROR"] = 17] = "REMOTE_NETWORK_ERROR"; /*! VoIP 不可用 */ ErrorCode[ErrorCode["VOIP_NOT_AVALIABLE"] = 18] = "VOIP_NOT_AVALIABLE"; })(RongIMLib.ErrorCode || (RongIMLib.ErrorCode = {})); var ErrorCode = RongIMLib.ErrorCode; (function (VoIPMediaType) { VoIPMediaType[VoIPMediaType["MEDIA_AUDIO"] = 1] = "MEDIA_AUDIO"; VoIPMediaType[VoIPMediaType["MEDIA_VEDIO"] = 2] = "MEDIA_VEDIO"; VoIPMediaType[VoIPMediaType["MEDIA_VIDEO"] = 2] = "MEDIA_VIDEO"; })(RongIMLib.VoIPMediaType || (RongIMLib.VoIPMediaType = {})); var VoIPMediaType = RongIMLib.VoIPMediaType; (function (MediaType) { /** * 图片。 */ MediaType[MediaType["IMAGE"] = 1] = "IMAGE"; /** * 声音。 */ MediaType[MediaType["AUDIO"] = 2] = "AUDIO"; /** * 视频。 */ MediaType[MediaType["VIDEO"] = 3] = "VIDEO"; /** * 通用文件。 */ MediaType[MediaType["FILE"] = 100] = "FILE"; })(RongIMLib.MediaType || (RongIMLib.MediaType = {})); var MediaType = RongIMLib.MediaType; (function (MessageDirection) { /** * 发送消息。 */ MessageDirection[MessageDirection["SEND"] = 1] = "SEND"; /** * 接收消息。 */ MessageDirection[MessageDirection["RECEIVE"] = 2] = "RECEIVE"; })(RongIMLib.MessageDirection || (RongIMLib.MessageDirection = {})); var MessageDirection = RongIMLib.MessageDirection; (function (FileType) { FileType[FileType["IMAGE"] = 1] = "IMAGE"; FileType[FileType["AUDIO"] = 2] = "AUDIO"; FileType[FileType["VIDEO"] = 3] = "VIDEO"; FileType[FileType["FILE"] = 4] = "FILE"; })(RongIMLib.FileType || (RongIMLib.FileType = {})); var FileType = RongIMLib.FileType; (function (RealTimeLocationErrorCode) { /** * 未初始化 RealTimeLocation 实例 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_NOT_INIT"] = -1] = "RC_REAL_TIME_LOCATION_NOT_INIT"; /** * 执行成功。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_SUCCESS"] = 0] = "RC_REAL_TIME_LOCATION_SUCCESS"; /** * 获取 RealTimeLocation 实例时返回 * GPS 未打开。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_GPS_DISABLED"] = 1] = "RC_REAL_TIME_LOCATION_GPS_DISABLED"; /** * 获取 RealTimeLocation 实例时返回 * 当前会话不支持位置共享。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_CONVERSATION_NOT_SUPPORT"] = 2] = "RC_REAL_TIME_LOCATION_CONVERSATION_NOT_SUPPORT"; /** * 获取 RealTimeLocation 实例时返回 * 对方已发起位置共享。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_IS_ON_GOING"] = 3] = "RC_REAL_TIME_LOCATION_IS_ON_GOING"; /** * Join 时返回 * 当前位置共享已超过最大支持人数。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_EXCEED_MAX_PARTICIPANT"] = 4] = "RC_REAL_TIME_LOCATION_EXCEED_MAX_PARTICIPANT"; /** * Join 时返回 * 加入位置共享失败。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_JOIN_FAILURE"] = 5] = "RC_REAL_TIME_LOCATION_JOIN_FAILURE"; /** * Start 时返回 * 发起位置共享失败。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_START_FAILURE"] = 6] = "RC_REAL_TIME_LOCATION_START_FAILURE"; /** * 网络不可用。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_NETWORK_UNAVAILABLE"] = 7] = "RC_REAL_TIME_LOCATION_NETWORK_UNAVAILABLE"; })(RongIMLib.RealTimeLocationErrorCode || (RongIMLib.RealTimeLocationErrorCode = {})); var RealTimeLocationErrorCode = RongIMLib.RealTimeLocationErrorCode; (function (RealTimeLocationStatus) { /** * 空闲状态 (默认状态) * 对方或者自己都未发起位置共享业务,或者位置共享业务已结束。 */ RealTimeLocationStatus[RealTimeLocationStatus["RC_REAL_TIME_LOCATION_STATUS_IDLE"] = 0] = "RC_REAL_TIME_LOCATION_STATUS_IDLE"; /** * 呼入状态 (待加入) * 1. 对方发起了位置共享业务,此状态下,自己只能选择加入。 * 2. 自己从已连接的位置共享中退出。 */ RealTimeLocationStatus[RealTimeLocationStatus["RC_REAL_TIME_LOCATION_STATUS_INCOMING"] = 1] = "RC_REAL_TIME_LOCATION_STATUS_INCOMING"; /** * 呼出状态 =(自己创建) * 1. 自己发起位置共享业务,对方只能选择加入。 * 2. 对方从已连接的位置共享业务中退出。 */ RealTimeLocationStatus[RealTimeLocationStatus["RC_REAL_TIME_LOCATION_STATUS_OUTGOING"] = 2] = "RC_REAL_TIME_LOCATION_STATUS_OUTGOING"; /** * 连接状态 (自己加入) * 对方加入了自己发起的位置共享,或者自己加入了对方发起的位置共享。 */ RealTimeLocationStatus[RealTimeLocationStatus["RC_REAL_TIME_LOCATION_STATUS_CONNECTED"] = 3] = "RC_REAL_TIME_LOCATION_STATUS_CONNECTED"; })(RongIMLib.RealTimeLocationStatus || (RongIMLib.RealTimeLocationStatus = {})); var RealTimeLocationStatus = RongIMLib.RealTimeLocationStatus; (function (ReceivedStatus) { ReceivedStatus[ReceivedStatus["READ"] = 1] = "READ"; ReceivedStatus[ReceivedStatus["LISTENED"] = 2] = "LISTENED"; ReceivedStatus[ReceivedStatus["DOWNLOADED"] = 4] = "DOWNLOADED"; ReceivedStatus[ReceivedStatus["RETRIEVED"] = 8] = "RETRIEVED"; ReceivedStatus[ReceivedStatus["UNREAD"] = 0] = "UNREAD"; })(RongIMLib.ReceivedStatus || (RongIMLib.ReceivedStatus = {})); var ReceivedStatus = RongIMLib.ReceivedStatus; (function (ReadStatus) { ReadStatus[ReadStatus["READ"] = 1] = "READ"; ReadStatus[ReadStatus["LISTENED"] = 2] = "LISTENED"; ReadStatus[ReadStatus["DOWNLOADED"] = 4] = "DOWNLOADED"; ReadStatus[ReadStatus["RETRIEVED"] = 8] = "RETRIEVED"; ReadStatus[ReadStatus["UNREAD"] = 0] = "UNREAD"; })(RongIMLib.ReadStatus || (RongIMLib.ReadStatus = {})); var ReadStatus = RongIMLib.ReadStatus; (function (SearchType) { /** * 精确。 */ SearchType[SearchType["EXACT"] = 0] = "EXACT"; /** * 模糊。 */ SearchType[SearchType["FUZZY"] = 1] = "FUZZY"; })(RongIMLib.SearchType || (RongIMLib.SearchType = {})); var SearchType = RongIMLib.SearchType; (function (SentStatus) { /** * 发送中。 */ SentStatus[SentStatus["SENDING"] = 10] = "SENDING"; /** * 发送失败。 */ SentStatus[SentStatus["FAILED"] = 20] = "FAILED"; /** * 已发送。 */ SentStatus[SentStatus["SENT"] = 30] = "SENT"; /** * 对方已接收。 */ SentStatus[SentStatus["RECEIVED"] = 40] = "RECEIVED"; /** * 对方已读。 */ SentStatus[SentStatus["READ"] = 50] = "READ"; /** * 对方已销毁。 */ SentStatus[SentStatus["DESTROYED"] = 60] = "DESTROYED"; })(RongIMLib.SentStatus || (RongIMLib.SentStatus = {})); var SentStatus = RongIMLib.SentStatus; (function (ConnectionState) { ConnectionState[ConnectionState["ACCEPTED"] = 0] = "ACCEPTED"; ConnectionState[ConnectionState["UNACCEPTABLE_PROTOCOL_VERSION"] = 1] = "UNACCEPTABLE_PROTOCOL_VERSION"; ConnectionState[ConnectionState["IDENTIFIER_REJECTED"] = 2] = "IDENTIFIER_REJECTED"; ConnectionState[ConnectionState["SERVER_UNAVAILABLE"] = 3] = "SERVER_UNAVAILABLE"; /** * token无效 */ ConnectionState[ConnectionState["TOKEN_INCORRECT"] = 4] = "TOKEN_INCORRECT"; ConnectionState[ConnectionState["NOT_AUTHORIZED"] = 5] = "NOT_AUTHORIZED"; ConnectionState[ConnectionState["REDIRECT"] = 6] = "REDIRECT"; ConnectionState[ConnectionState["PACKAGE_ERROR"] = 7] = "PACKAGE_ERROR"; ConnectionState[ConnectionState["APP_BLOCK_OR_DELETE"] = 8] = "APP_BLOCK_OR_DELETE"; ConnectionState[ConnectionState["BLOCK"] = 9] = "BLOCK"; ConnectionState[ConnectionState["TOKEN_EXPIRE"] = 10] = "TOKEN_EXPIRE"; ConnectionState[ConnectionState["DEVICE_ERROR"] = 11] = "DEVICE_ERROR"; })(RongIMLib.ConnectionState || (RongIMLib.ConnectionState = {})); var ConnectionState = RongIMLib.ConnectionState; (function (RTCAPIType) { RTCAPIType[RTCAPIType["ROOM"] = 1] = "ROOM"; RTCAPIType[RTCAPIType["PERSON"] = 2] = "PERSON"; })(RongIMLib.RTCAPIType || (RongIMLib.RTCAPIType = {})); var RTCAPIType = RongIMLib.RTCAPIType; (function (ChatroomEntityOpt) { ChatroomEntityOpt[ChatroomEntityOpt["UPDATE"] = 1] = "UPDATE"; ChatroomEntityOpt[ChatroomEntityOpt["DELETE"] = 2] = "DELETE"; })(RongIMLib.ChatroomEntityOpt || (RongIMLib.ChatroomEntityOpt = {})); var ChatroomEntityOpt = RongIMLib.ChatroomEntityOpt; (function (ChatroomEntityLimit) { ChatroomEntityLimit[ChatroomEntityLimit["KEY"] = 128] = "KEY"; ChatroomEntityLimit[ChatroomEntityLimit["VALUE"] = 4096] = "VALUE"; })(RongIMLib.ChatroomEntityLimit || (RongIMLib.ChatroomEntityLimit = {})); var ChatroomEntityLimit = RongIMLib.ChatroomEntityLimit; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var RongIMClient = (function () { function RongIMClient() { } RongIMClient.getInstance = function () { if (!RongIMClient._instance) { throw new Error("RongIMClient is not initialized. Call .init() method first."); } return RongIMClient._instance; }; RongIMClient.showError = function (errorInfo) { var hasConsole = (console && console.error); if (hasConsole) { console.error(JSON.stringify(errorInfo)); } }; RongIMClient.logger = function (params) { var code = params.code; var errorInfo = RongIMClient.LogFactory[code] || params; errorInfo.funcName = params.funcName; errorInfo.msg = params.msg || errorInfo.msg; if (RongIMClient._memoryStore.depend.showError) { RongIMClient.showError(errorInfo); } }; RongIMClient.logCallback = function (callback, funcName) { return { onSuccess: callback.onSuccess, onError: function (errorCode) { RongIMClient.logger({ code: errorCode, funcName: funcName }); callback.onError(errorCode); } }; }; ; RongIMClient.logSendCallback = function (callback, funcName) { return { onSuccess: callback.onSuccess, onError: function (errorCode, result) { RongIMClient.logger({ code: errorCode, funcName: funcName }); callback.onError(errorCode, result); }, onBefore: callback.onBefore }; }; ; /** * 初始化 SDK,在整个应用全局只需要调用一次。 * @param appKey 开发者后台申请的 AppKey,用来标识应用。 * @param dataAccessProvider 必须是DataAccessProvider的实例 */ RongIMClient.init = function (appKey, dataAccessProvider, options, callback) { RongIMClient.statusListeners = []; RongIMClient.messageListeners = []; RongIMClient.settingListeners = []; RongIMClient.conversationStatusListeners = []; if (RongIMClient._instance) { return RongIMClient._memoryStore.sdkInfo; } RongIMClient._instance = new RongIMClient(); options = options || {}; var protocol = "http://", wsScheme = 'ws://'; var isLocationInvalid = typeof location !== 'object'; // 未找到全局 location 变量, 则协议为 https. 比如小程序 if (isLocationInvalid || location.protocol == 'https:') { wsScheme = 'wss://'; protocol = 'https://'; } var isPolling = false; if (typeof WebSocket != 'function') { isPolling = true; } var isIntegrity = function () { //iOS 9 var hasWS = (typeof WebSocket); var integrity = (typeof WebSocket.OPEN == 'number'); return (hasWS && integrity); }; if (typeof WebSocket == 'object' && isIntegrity()) { isPolling = false; } var supportUserData = function () { var element = document.documentElement; return element.addBehavior; }; if (RongIMLib.RongUtil.supportLocalStorage()) { RongIMClient._storageProvider = new RongIMLib.LocalStorageProvider(); } else if (supportUserData()) { RongIMClient._storageProvider = new RongIMLib.UserDataProvider(); } else { RongIMClient._storageProvider = new RongIMLib.MemeoryProvider(); } var serverIndex = RongIMClient._storageProvider.getItem('serverIndex'); RongIMClient.serverStore.index = serverIndex || 0; var pathTmpl = '{0}{1}'; var _serverPath = { api: 'api.cn.ronghub.com' }; RongIMLib.RongUtil.forEach(_serverPath, function (path, key) { _serverPath[key] = RongIMLib.RongUtil.stringFormat(pathTmpl, [protocol, path]); }); RongIMLib.RongUtil.forEach(_serverPath, function (path, key) { var hasProto = (key in options); var config = { path: options[key], tmpl: pathTmpl, protocol: protocol, sub: true }; path = hasProto ? RongIMLib.RongUtil.formatProtoclPath(config) : path; options[key] = path; }); var navigaters = options.navigaters || []; if (options.navi) { navigaters = [options.navi]; } if (!options.navi && RongIMLib.RongUtil.isEqual(navigaters.length, 0)) { navigaters = ['nav.cn.ronghub.com', 'nav2-cn.ronghub.com']; } var _sourcePath = { protobuf: 'cdn.ronghub.com/protobuf-2.3.9.min.js' }; RongIMLib.RongUtil.forEach(_sourcePath, function (path, key) { _sourcePath[key] = RongIMLib.RongUtil.stringFormat(pathTmpl, [protocol, path]); }); RongIMLib.RongUtil.extend(_sourcePath, options); var _defaultOpts = { isPolling: isPolling, wsScheme: wsScheme, protocol: protocol, showError: true, openMp: true, snifferTime: 2000, naviTimeout: 5000, navigaters: navigaters, maxNaviRetry: 10, isNaviJSONP: false, isWSPingJSONP: false, isNotifyConversationList: false, maxConversationCount: 300, cmpUrl: '' // 若传入 cmpUrl, 则优先链接此地址 }; delete options.navigaters; RongIMLib.RongUtil.extend(_defaultOpts, options); if (RongIMLib.RongUtil.isFunction(options.protobuf)) { RongIMClient.Protobuf = options.protobuf; } RongIMClient.userStatusObserver = new RongIMLib.RongObserver(); var pather = new RongIMLib.FeaturePatcher(); pather.patchAll(); var tempStore = { token: "", callback: null, lastReadTime: new RongIMLib.LimitableMap(), historyMessageLimit: new RongIMLib.MemoryCache(), conversationList: [], isFullConversations: false, appKey: appKey, publicServiceMap: new RongIMLib.PublicServiceMap(), providerType: 1, deltaTime: 0, filterMessages: [], isSyncRemoteConverList: true, otherDevice: false, custStore: {}, converStore: { latestMessage: {} }, connectAckTime: 0, voipStategy: 0, isFirstPingMsg: true, depend: options, notification: {}, networkUnavailable: false, loggerSwitch: options.loggerSwitch || 'on', autoReconnectTimer: null // 自动重连定时器编号 }; RongIMClient._memoryStore = tempStore; var isCPlusSDK = dataAccessProvider && Object.prototype.toString.call(dataAccessProvider) == "[object Object]"; if (isCPlusSDK) { RongIMClient._dataAccessProvider = dataAccessProvider; } else { RongIMClient._dataAccessProvider = new RongIMLib.ServerDataProvider(); } options.appCallback = callback; var sdkInfo = RongIMClient._dataAccessProvider.init(appKey, options); RongIMClient._memoryStore.sdkInfo = sdkInfo; if (isCPlusSDK) { // 兼容 c++ 设置导航,Web 端不生效 RongIMClient._dataAccessProvider.setServerInfo({ navi: location.protocol + options.navi + '/navi.xml' }); } RongIMClient.MessageParams = { TextMessage: { objectName: "RC:TxtMsg", msgTag: new RongIMLib.MessageTag(true, true) }, ImageMessage: { objectName: "RC:ImgMsg", msgTag: new RongIMLib.MessageTag(true, true) }, DiscussionNotificationMessage: { objectName: "RC:DizNtf", msgTag: new RongIMLib.MessageTag(false, true) }, VoiceMessage: { objectName: "RC:VcMsg", msgTag: new RongIMLib.MessageTag(true, true) }, ReferenceMessage: { objectName: "RC:ReferenceMsg", msgTag: new RongIMLib.MessageTag(true, true) }, RichContentMessage: { objectName: "RC:ImgTextMsg", msgTag: new RongIMLib.MessageTag(true, true) }, FileMessage: { objectName: "RC:FileMsg", msgTag: new RongIMLib.MessageTag(true, true) }, HQVoiceMessage: { objectName: "RC:HQVCMsg", msgTag: new RongIMLib.MessageTag(true, true) }, GIFMessage: { objectName: "RC:GIFMsg", msgTag: new RongIMLib.MessageTag(true, true) }, SightMessage: { objectName: "RC:SightMsg", msgTag: new RongIMLib.MessageTag(true, true) }, HandshakeMessage: { objectName: "", msgTag: new RongIMLib.MessageTag(true, true) }, UnknownMessage: { objectName: "", msgTag: new RongIMLib.MessageTag(true, true) }, LocationMessage: { objectName: "RC:LBSMsg", msgTag: new RongIMLib.MessageTag(true, true) }, InformationNotificationMessage: { objectName: "RC:InfoNtf", msgTag: new RongIMLib.MessageTag(false, true) }, ContactNotificationMessage: { objectName: "RC:ContactNtf", msgTag: new RongIMLib.MessageTag(false, true) }, ProfileNotificationMessage: { objectName: "RC:ProfileNtf", msgTag: new RongIMLib.MessageTag(false, true) }, CommandNotificationMessage: { objectName: "RC:CmdNtf", msgTag: new RongIMLib.MessageTag(false, true) }, PublicServiceRichContentMessage: { objectName: "RC:PSImgTxtMsg", msgTag: new RongIMLib.MessageTag(true, true) }, PublicServiceMultiRichContentMessage: { objectName: "RC:PSMultiImgTxtMsg", msgTag: new RongIMLib.MessageTag(true, true) }, JrmfRedPacketMessage: { objectName: "RCJrmf:RpMsg", msgTag: new RongIMLib.MessageTag(true, true) }, JrmfRedPacketOpenedMessage: { objectName: "RCJrmf:RpOpendMsg", msgTag: new RongIMLib.MessageTag(true, true) }, GroupNotificationMessage: { objectName: "RC:GrpNtf", msgTag: new RongIMLib.MessageTag(false, true) }, CommandMessage: { objectName: "RC:CmdMsg", msgTag: new RongIMLib.MessageTag(false, false) }, TypingStatusMessage: { objectName: "RC:TypSts", msgTag: new RongIMLib.MessageTag(false, false) }, PublicServiceCommandMessage: { objectName: "RC:PSCmd", msgTag: new RongIMLib.MessageTag(false, false) }, RecallCommandMessage: { objectName: "RC:RcCmd", msgTag: new RongIMLib.MessageTag(false, true) }, SyncReadStatusMessage: { objectName: "RC:SRSMsg", msgTag: new RongIMLib.MessageTag(false, false) }, ReadReceiptRequestMessage: { objectName: "RC:RRReqMsg", msgTag: new RongIMLib.MessageTag(false, false) }, ReadReceiptResponseMessage: { objectName: "RC:RRRspMsg", msgTag: new RongIMLib.MessageTag(false, false) }, ChangeModeResponseMessage: { objectName: "RC:CsChaR", msgTag: new RongIMLib.MessageTag(false, false) }, ChangeModeMessage: { objectName: "RC:CSCha", msgTag: new RongIMLib.MessageTag(false, false) }, EvaluateMessage: { objectName: "RC:CsEva", msgTag: new RongIMLib.MessageTag(false, false) }, CustomerContact: { objectName: "RC:CsContact", msgTag: new RongIMLib.MessageTag(false, false) }, HandShakeMessage: { objectName: "RC:CsHs", msgTag: new RongIMLib.MessageTag(false, false) }, HandShakeResponseMessage: { objectName: "RC:CsHsR", msgTag: new RongIMLib.MessageTag(false, false) }, SuspendMessage: { objectName: "RC:CsSp", msgTag: new RongIMLib.MessageTag(false, false) }, TerminateMessage: { objectName: "RC:CsEnd", msgTag: new RongIMLib.MessageTag(false, false) }, CustomerStatusUpdateMessage: { objectName: "RC:CsUpdate", msgTag: new RongIMLib.MessageTag(false, false) }, ReadReceiptMessage: { objectName: "RC:ReadNtf", msgTag: new RongIMLib.MessageTag(false, false) }, RCCombineMessage: { objectName: "RC:CombineMsg", msgTag: new RongIMLib.MessageTag(true, true) }, ChrmKVNotificationMessage: { objectName: 'RC:chrmKVNotiMsg', msgTag: new RongIMLib.MessageTag(false, false) }, LogCommandMessage: { objectName: 'RC:LogCmdMsg', msgTag: new RongIMLib.MessageTag(false, false) } }; RongIMClient.MessageParams["AcceptMessage"] = { objectName: "RC:VCAccept", msgTag: new RongIMLib.MessageTag(false, false) }; RongIMClient.MessageParams["RingingMessage"] = { objectName: "RC:VCRinging", msgTag: new RongIMLib.MessageTag(false, false) }; RongIMClient.MessageParams["SummaryMessage"] = { objectName: "RC:VCSummary", msgTag: new RongIMLib.MessageTag(false, false) }; RongIMClient.MessageParams["HungupMessage"] = { objectName: "RC:VCHangup", msgTag: new RongIMLib.MessageTag(false, false) }; RongIMClient.MessageParams["InviteMessage"] = { objectName: "RC:VCInvite", msgTag: new RongIMLib.MessageTag(false, false) }; RongIMClient.MessageParams["MediaModifyMessage"] = { objectName: "RC:VCModifyMedia", msgTag: new RongIMLib.MessageTag(false, false) }; RongIMClient.MessageParams["MemberModifyMessage"] = { objectName: "RC:VCModifyMem", msgTag: new RongIMLib.MessageTag(false, false) }; RongIMClient.MessageType = { TextMessage: "TextMessage", ImageMessage: "ImageMessage", ReferenceMessage: "ReferenceMessage", DiscussionNotificationMessage: "DiscussionNotificationMessage", VoiceMessage: "VoiceMessage", RichContentMessage: "RichContentMessage", HandshakeMessage: "HandshakeMessage", UnknownMessage: "UnknownMessage", LocationMessage: "LocationMessage", InformationNotificationMessage: "InformationNotificationMessage", ContactNotificationMessage: "ContactNotificationMessage", ProfileNotificationMessage: "ProfileNotificationMessage", CommandNotificationMessage: "CommandNotificationMessage", CommandMessage: "CommandMessage", TypingStatusMessage: "TypingStatusMessage", ChangeModeResponseMessage: "ChangeModeResponseMessage", ChangeModeMessage: "ChangeModeMessage", EvaluateMessage: "EvaluateMessage", HandShakeMessage: "HandShakeMessage", HandShakeResponseMessage: "HandShakeResponseMessage", SuspendMessage: "SuspendMessage", TerminateMessage: "TerminateMessage", CustomerContact: "CustomerContact", CustomerStatusUpdateMessage: "CustomerStatusUpdateMessage", SyncReadStatusMessage: "SyncReadStatusMessage", ReadReceiptRequestMessage: "ReadReceiptRequestMessage", ReadReceiptResponseMessage: "ReadReceiptResponseMessage", FileMessage: 'FileMessage', HQVoiceMessage: 'HQVoiceMessage', GIFMessage: 'GIFMessage', SightMessage: 'SightMessage', AcceptMessage: "AcceptMessage", RingingMessage: "RingingMessage", SummaryMessage: "SummaryMessage", HungupMessage: "HungupMessage", InviteMessage: "InviteMessage", MediaModifyMessage: "MediaModifyMessage", MemberModifyMessage: "MemberModifyMessage", JrmfRedPacketMessage: "JrmfRedPacketMessage", JrmfRedPacketOpenedMessage: "JrmfRedPacketOpenedMessage", GroupNotificationMessage: "GroupNotificationMessage", PublicServiceRichContentMessage: "PublicServiceRichContentMessage", PublicServiceMultiRichContentMessage: "PublicServiceMultiRichContentMessage", PublicServiceCommandMessage: "PublicServiceCommandMessage", RecallCommandMessage: "RecallCommandMessage", ReadReceiptMessage: "ReadReceiptMessage", RCCombineMessage: "RCCombineMessage", ChrmKVNotificationMessage: 'ChrmKVNotificationMessage', LogCommandMessage: 'LogCommandMessage' }; RongIMClient.LogFactory = { /** * 个人 */ "-1": { code: "-1", msg: "服务器超时" }, "-2": { code: "-2", msg: "未知原因失败" }, "-3": { code: "-3", msg: "参数错误" }, "-4": { code: "-4", msg: "参数不正确或尚未实例化" }, "25101": { code: "25101", msg: "撤回消息参数错误", desc: "请检查撤回消息参数 https://rongcloud.github.io/websdk-demo/api-test.html" }, "25102": { code: "25101", msg: "只能撤回自发发送的消息" }, "20604": { code: "20604", msg: "发送频率过快", desc: "https://developer.rongcloud.cn/ticket/info/9Q3L6vRKd1cLS7rycA==?type=1" }, "20406": { code: "20406", msg: "被禁言" }, "23407": { code: "23407", msg: "获取用户失败" }, /** * 群组 */ "20407": { code: "20407", msg: "群组Id无效" }, "22408": { code: "22408", msg: "群组被禁言" }, "22406": { code: "22406", msg: "不在群组" }, "35001": { code: "35001", msg: "群组同步异常" }, "35002": { code: "35002", msg: "匹配群信息异常" }, /** * 讨论组 */ "21406": { code: "21406", msg: "不在讨论组" }, "21407": { code: "21407", msg: "加入讨论失败" }, "21408": { code: "21408", msg: "创建讨论组失败" }, "21409": { code: "21409", msg: "设置讨论组邀请状态失败" }, /** * 聊天室 */ "23406": { code: "23406", msg: "不在聊天室" }, "23408": { code: "23408", msg: "聊天室被禁言" }, "23409": { code: "23409", msg: "聊天室中成员被踢出" }, "23410": { code: "23410", msg: "聊天室不存在" }, "23411": { code: "23411", msg: "聊天室成员已满" }, "23412": { code: "23412", msg: "获取聊天室信息参数无效" }, "23413": { code: "23413", msg: "聊天室异常" }, "23414": { code: "23414", msg: "没有打开聊天室消息存储" }, "36001": { code: "36001", msg: "加入聊天室Id为空" }, "36002": { code: "36002", msg: "加入聊天室失败" }, "36003": { code: "36003", msg: "拉取聊天室历史消息失败" }, /** * voip */ "24001": { code: "24001", msg: "没有注册DeviveId 也就是用户没有登陆" }, "24002": { code: "24002", msg: "用户已经存在" }, "0": { code: "0", msg: "成功" }, "24009": { code: "24009", msg: "没有对应的用户或token" }, "24013": { code: "24013", msg: "voip为空" }, "24010": { code: "24010", msg: "不支持的Voip引擎" }, "24011": { code: "24011", msg: "channelName 是空" }, "24012": { code: "24012", msg: "生成Voipkey失败" }, "24014": { code: "24014", msg: "没有配置voip" }, "24015": { code: "24015", msg: "服务器内部错误" }, "24016": { code: "24016", msg: "VOIP close" }, /** * 通讯、导航 */ "30001": { code: "30001", msg: "通信过程中,当前Socket不存在" }, "30002": { code: "30002", msg: "Socket连接不可用" }, "30003": { code: "30003", msg: "通信超时" }, "30004": { code: "30004", msg: "导航操作时,Http请求失败" }, "30005": { code: "30005", msg: "HTTP请求失败" }, "30006": { code: "30006", msg: "HTTP接收失败" }, "30007": { code: "30007", msg: "导航资源错误" }, "30008": { code: "30008", msg: "没有有效数据" }, "30009": { code: "30009", msg: "不存在有效 IP 地址" }, "30010": { code: "30010", msg: "创建 Socket 失败" }, "30011": { code: "30011", msg: " Socket 被断开" }, "30012": { code: "30012", msg: "PING 操作失败" }, "30013": { code: "30013", msg: "PING 超时" }, "30014": { code: "30014", msg: "消息发送失败" }, "30016": { code: "30016", msg: "消息大小超限,最大 128 KB" }, /** * 连接 */ "31000": { code: "31000", msg: "做 connect 连接时,收到的 ACK 超时" }, "31001": { code: "31001", msg: "参数错误" }, "31002": { code: "31002", msg: "参数错误,App Id 错误" }, "31003": { code: "31003", msg: "服务器不可用" }, "31004": { code: "31004", msg: "Token 错误" }, "31005": { code: "31005", msg: "App Id 与 Token 不匹配" }, "31006": { code: "31006", msg: "重定向,地址错误" }, "31007": { code: "31007", msg: "NAME 与后台注册信息不一致" }, "31008": { code: "31008", msg: "APP 被屏蔽、删除或不存在" }, "31009": { code: "31009", msg: "用户被屏蔽" }, "31010": { code: "31010", msg: "Disconnect,由服务器返回,比如用户互踢" }, "31011": { code: "31011", msg: "Disconnect,由服务器返回,比如用户互踢" }, /** * 协议 */ "32001": { code: "32001", msg: "协议层内部错误。query,上传下载过程中数据错误" }, "32002": { code: "32002", msg: "协议层内部错误" }, /** * BIZ */ "33001": { code: "33001", msg: "未调用 init 初始化函数" }, "33002": { code: "33002", msg: "数据库初始化失败" }, "33003": { code: "33003", msg: "传入参数无效" }, "33004": { code: "33004", msg: "通道无效" }, "33005": { code: "33005", msg: "重新连接成功" }, "33006": { code: "33006", msg: "连接中,再调用 connect 被拒绝" }, "33007": { code: "33007", msg: "消息漫游服务未开通" }, "33008": { code: "33008", msg: "消息添加失败" }, "33009": { code: "33009", msg: "消息删除失败" }, /** * 会话 */ "34001": { code: "34001", msg: "删除会话失败" }, "34002": { code: "34002", msg: "拉取历史消息失败" }, "34003": { code: "34003", msg: "会话指定异常" }, "34004": { code: "34004", msg: "获取会话未读消息总数失败" }, "34005": { code: "34005", msg: "获取指定会话类型未读消息数异常" }, "34006": { code: "34006", msg: "获取指定用户ID&会话类型未读消息数异常" }, "34007": { code: "34007", msg: "清除会话消息异常" }, "34008": { code: "34008", msg: "获取会话消息异常" }, "34009": { code: "34009", msg: "清除历史消息会话类型不正确" }, "34010": { code: "34010", msg: "清除历史消息失败,请检查传入参数" }, /** * 黑名单异常 */ "37001": { code: "37001", msg: "加入黑名单异常" }, "37002": { code: "37002", msg: "获得指定人员再黑名单中的状态异常" }, "37003": { code: "37003", msg: "移除黑名单异常" }, "405": { code: "405", msg: "在黑名单中" }, /** * 草稿 */ "38001": { code: "38001", msg: "获取草稿失败" }, "38002": { code: "38002", msg: "保存草稿失败" }, "38003": { code: "38003", msg: "删除草稿失败" }, /** * 公众号 */ "39001": { code: "39001", msg: "关注公众号失败" }, /** * 文件 */ "41001": { code: "41001", msg: "文件类型错误" }, "41002": { code: "41002", msg: "获取七牛token失败" }, /** * */ "51001": { code: "51001", msg: "未安装或未启动插件" }, "51002": { code: "51002", msg: "视频已经存在" }, "51003": { code: "51003", msg: "无效的channelName" }, "51004": { code: "51004", msg: "视频内容为空" }, /** * */ "61001": { code: "61001", msg: "删除消息数组长度为 0" } }; var handler = function (message, uris, callback) { var userId = message.senderUserId; var _uris = RongIMClient.roomInfo.users[userId].uris || '[]'; if (RongIMLib.RongUtil.isString(_uris)) { _uris = JSON.parse(_uris); } var tUris = JSON.parse(JSON.stringify(_uris)); RongIMLib.RongUtil.forEach(tUris, function (_uri, index) { RongIMLib.RongUtil.forEach(uris, function (uri) { if (uri.uri == _uri.uri) { callback(_uri, uri, _uris, index); } }); }); RongIMClient.roomInfo.users[userId].uris = JSON.stringify(_uris); }; var RTCMessage = { RTCPublishResourceMessage: function (message, uris) { var userId = message.senderUserId; var user = RongIMClient.roomInfo.users[userId]; if (!user) { user = {}; RongIMClient.roomInfo.users[userId] = {}; } var _uris = user.uris || '[]'; if (RongIMLib.RongUtil.isString(_uris)) { _uris = JSON.parse(_uris); } _uris = _uris.concat(uris); RongIMClient.roomInfo.users[userId].uris = JSON.stringify(_uris); }, RTCUnpublishResourceMessage: function (message, uris) { handler(message, uris, function (_uri, uri, _uris, index) { _uris.splice(index, 1); }); }, RTCModifyResourceMessage: function (message, uris) { handler(message, uris, function (_uri, uri) { _uri.state = uri.state; }); }, RTCUserChangeMessage: function (message) { var content = message.content; var users = content.users; var UserState = { JOINED: 0, LEFT: 1, OFFLINE: 2 }; RongIMLib.RongUtil.forEach(users, function (user) { var state = user.state; var userId = user.userId; switch (+state) { case UserState.JOINED: RongIMClient.roomInfo.users[userId] = {}; break; case UserState.LEFT: case UserState.OFFLINE: delete RongIMClient.roomInfo.users[userId]; break; } }); } }; RongIMClient.RTCInnerListener = function (message) { var func = RTCMessage[message.messageType] || function () { }; var content = message.content; var uris = content.uris; func(message, uris); }; RongIMClient.Conversation = RongIMClient._dataAccessProvider.Conversation; RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.A_INIT_O, level: RongIMLib.LoggerLevel.I, type: RongIMLib.LoggerType.IM, content: { appKey: appKey } }); return sdkInfo; }; ; RongIMClient.setProtocol = function (protocol) { RongIMClient._memoryStore.depend = RongIMClient._memoryStore.depend || {}; var HttpProtocol = RongIMClient.HttpProtocol; var WsProtocol = RongIMClient.WsProtocol; if (protocol === HttpProtocol.http) { RongIMClient._memoryStore.depend.protocol = HttpProtocol.http; RongIMClient._memoryStore.depend.wsScheme = WsProtocol.ws; } else { RongIMClient._memoryStore.depend.protocol = HttpProtocol.https; RongIMClient._memoryStore.depend.wsScheme = WsProtocol.wss; } }; RongIMClient.getProtocol = function () { RongIMClient._memoryStore.depend = RongIMClient._memoryStore.depend || {}; var depend = RongIMClient._memoryStore.depend; var protocol = depend.protocol, wsScheme = depend.wsScheme; if (!protocol || !wsScheme) { protocol = RongIMClient.HttpProtocol.https; wsScheme = RongIMClient.WsProtocol.wss; } return { protocol: protocol, wsScheme: wsScheme }; }; /** var config = { appkey: appkey, token: token, dataAccessProvider:dataAccessProvider, opts: opts }; callback(_instance, userId); */ RongIMClient.initApp = function (config, callback) { RongIMClient.init(config.appkey, config.dataAccessProvider, config.opts, function () { var instance = RongIMClient._instance; //备用 var error = null; callback(error, instance); }); }; /** * 连接服务器,在整个应用全局只需要调用一次,断线后 SDK 会自动重连。 * * @param token 从服务端获取的用户身份令牌(Token)。 * @param callback 连接回调,返回连接的成功或者失败状态。 */ RongIMClient.connect = function (token, _callback, userId, serverConf) { RongIMLib.CheckParam.getInstance().check(["string", "object", "string|null|object|global|undefined", "object|null|global|undefined"], "connect", true, arguments); if (RongIMLib.IMHandler.isIncludeNavi(token)) { var protocol = RongIMClient._memoryStore.depend.protocol; var currentNavs = RongIMClient._memoryStore.depend.navigaters; var navList = RongIMLib.IMHandler.getNavsByToken(token, protocol); token = RongIMLib.IMHandler.getToken(token); RongIMClient._memoryStore.depend.navigaters = RongIMLib.RongUtil.concat(navList, currentNavs, true); } var connectCallback = { onSuccess: _callback.onSuccess, onTokenIncorrect: _callback.onTokenIncorrect, onError: function (errorCode) { RongIMClient.logger({ code: errorCode, funcName: "connect" }); _callback.onError(errorCode); } }; RongIMClient._dataAccessProvider.connect(token, connectCallback, userId, serverConf); }; RongIMClient.reconnect = function (callback, config) { var connectCallback = { onSuccess: callback.onSuccess, onTokenIncorrect: callback.onTokenIncorrect, onError: function (errorCode) { RongIMClient.logger({ code: errorCode, funcName: "connect" }); callback.onError(errorCode); } }; RongIMClient._dataAccessProvider.reconnect(connectCallback, config); }; /** * 注册消息类型,用于注册用户自定义的消息。 * 内建的消息类型已经注册过,不需要再次注册。 * 自定义消息声明需放在执行顺序最高的位置(在RongIMClient.init(appkey)之后即可) * @param objectName 消息内置名称 */ RongIMClient.registerMessageType = function (messageType, objectName, messageTag, messageContent, searchProps) { RongIMClient._dataAccessProvider.registerMessageType(messageType, objectName, messageTag, messageContent, searchProps); RongIMClient.RegisterMessage[messageType].messageName = messageType; RongIMClient.MessageType[messageType] = messageType; RongIMClient.MessageParams[messageType] = { objectName: objectName, msgTag: messageTag }; }; RongIMClient.prototype.registerMessageTypes = function (types) { types = types || {}; RongIMClient._dataAccessProvider.registerMessageTypes(types); }; /** * 设置连接状态变化的监听器。 * * @param listener 连接状态变化的监听器。 */ RongIMClient.setConnectionStatusListener = function (listener) { if (RongIMClient._dataAccessProvider) { RongIMClient._dataAccessProvider.setConnectionStatusListener(listener); } else { if (RongIMLib.RongUtil.isObject(listener) && RongIMLib.RongUtil.isFunction(listener.onChanged)) { RongIMClient.statusListeners.push(listener.onChanged); } } }; RongIMClient.setConversationStatusListener = function (listener) { if (listener && listener.onChanged && RongIMLib.RongUtil.isFunction(listener.onChanged)) { RongIMClient.conversationStatusListeners.push(listener.onChanged); } }; RongIMClient.statusWatch = function (watcher) { if (RongIMLib.RongUtil.isFunction(watcher)) { RongIMClient.statusListeners.push(watcher); } }; RongIMClient.watch = function (watchers) { watchers = watchers || {}; var setting = watchers.setting; if (RongIMLib.RongUtil.isFunction(setting)) { RongIMClient.settingListeners.push(setting); } }; /** * 设置接收消息的监听器。 * * @param listener 接收消息的监听器。 */ RongIMClient.setOnReceiveMessageListener = function (listener) { if (RongIMClient._dataAccessProvider) { RongIMClient._dataAccessProvider.setOnReceiveMessageListener(listener); } else { if (RongIMLib.RongUtil.isObject(listener) && RongIMLib.RongUtil.isFunction(listener.onReceived)) { RongIMClient.messageListeners.push(listener.onReceived); } } }; /** * 清理所有连接相关的变量 */ RongIMClient.prototype.logout = function () { RongIMClient._dataAccessProvider.logout(); }; /** * 断开连接。 */ RongIMClient.prototype.disconnect = function () { RongIMClient._dataAccessProvider.disconnect(); RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.A_DISC_O, level: RongIMLib.LoggerLevel.I, type: RongIMLib.LoggerType.IM }); }; RongIMClient.prototype.startCustomService = function (custId, callback, content) { if (!custId || !callback) return; var msg = new RongIMLib.HandShakeMessage(content); var me = this; RongIMLib.RongIMClient._memoryStore.custStore["isInit"] = true; RongIMClient.getInstance().sendMessage(RongIMLib.ConversationType.CUSTOMER_SERVICE, custId, msg, { onSuccess: function (data) { if (data.isBlack) { callback.onError(); me.stopCustomeService(custId, { onSuccess: function () { }, onError: function () { } }); } else { callback.onSuccess(); } }, onError: function () { callback.onError(); }, onBefore: function () { } }); }; RongIMClient.prototype.stopCustomeService = function (custId, callback) { if (!custId || !callback) return; var session = RongIMClient._memoryStore.custStore[custId]; if (!session) return; var msg = new RongIMLib.SuspendMessage({ sid: session.sid, uid: session.uid, pid: session.pid }); this.sendCustMessage(custId, msg, { onSuccess: function () { // delete RongIMClient._memoryStore.custStore[custId]; setTimeout(function () { callback.onSuccess(); }); }, onError: function () { setTimeout(function () { callback.onError(); }); } }); }; RongIMClient.prototype.switchToHumanMode = function (custId, callback) { if (!custId || !callback) return; var session = RongIMClient._memoryStore.custStore[custId]; if (!session) return; var msg = new RongIMLib.ChangeModeMessage({ sid: session.sid, uid: session.uid, pid: session.pid }); this.sendCustMessage(custId, msg, callback); }; RongIMClient.prototype.evaluateRebotCustomService = function (custId, isRobotResolved, sugest, callback) { if (!custId || !callback) return; var session = RongIMClient._memoryStore.custStore[custId]; if (!session) return; var msg = new RongIMLib.EvaluateMessage({ sid: session.sid, uid: session.uid, pid: session.pid, isRobotResolved: isRobotResolved, sugest: sugest, type: 0 }); this.sendCustMessage(custId, msg, callback); }; RongIMClient.prototype.evaluateHumanCustomService = function (custId, humanValue, sugest, callback) { if (!custId || !callback) return; var session = RongIMClient._memoryStore.custStore[custId]; if (!session) return; var msg = new RongIMLib.EvaluateMessage({ sid: session.sid, uid: session.uid, pid: session.pid, humanValue: humanValue, sugest: sugest, type: 1 }); this.sendCustMessage(custId, msg, callback); }; RongIMClient.prototype.sendCustMessage = function (custId, msg, callback) { RongIMClient.getInstance().sendMessage(RongIMLib.ConversationType.CUSTOMER_SERVICE, custId, msg, { onSuccess: function (data) { callback.onSuccess(); }, onError: function () { callback.onError(); }, onBefore: function () { } }); }; /** * 获取当前连接的状态。 */ RongIMClient.prototype.getCurrentConnectionStatus = function () { return RongIMClient._dataAccessProvider.getCurrentConnectionStatus(); }; /** * 获取当前使用的连接通道。 */ RongIMClient.prototype.getConnectionChannel = function () { if (RongIMLib.Transportations._TransportType == RongIMLib.Socket.XHR_POLLING) { return RongIMLib.ConnectionChannel.XHR_POLLING; } else if (RongIMLib.Transportations._TransportType == RongIMLib.Socket.WEBSOCKET) { return RongIMLib.ConnectionChannel.WEBSOCKET; } }; /** * 获取当前使用的本地储存提供者。 TODO */ RongIMClient.prototype.getStorageProvider = function () { if (RongIMClient._memoryStore.providerType == 1) { return "ServerDataProvider"; } else { return "OtherDataProvider"; } }; /** * 过滤聊天室消息(拉取最近聊天消息) * @param {string[]} msgFilterNames */ RongIMClient.prototype.setFilterMessages = function (msgFilterNames) { if (Object.prototype.toString.call(msgFilterNames) == "[object Array]") { RongIMClient._memoryStore.filterMessages = msgFilterNames; } }; RongIMClient.prototype.getAgoraDynamicKey = function (engineType, channelName, callback) { RongIMClient._dataAccessProvider.getAgoraDynamicKey(engineType, channelName, callback); }; /** * 获取当前连接用户的 UserId。 */ RongIMClient.prototype.getCurrentUserId = function () { return RongIMLib.Bridge._client.userId; }; /** * 获取服务器时间与本地时间的差值,单位为毫秒。 * 计算公式:差值 = 本地时间毫秒数 - 服务器时间毫秒数 * @param callback 获取的回调,返回差值。 */ RongIMClient.prototype.getDeltaTime = function () { return RongIMClient._dataAccessProvider.getDelaTime(); }; // #region Message RongIMClient.prototype.getMessage = function (messageId, callback) { RongIMClient._dataAccessProvider.getMessage(messageId, RongIMClient.logCallback(callback, "getMessage")); }; RongIMClient.prototype.deleteLocalMessages = function (conversationType, targetId, messageIds, callback) { RongIMClient._dataAccessProvider.removeLocalMessage(conversationType, targetId, messageIds, RongIMClient.logCallback(callback, "deleteLocalMessages")); }; RongIMClient.prototype.updateMessage = function (message, callback) { RongIMClient._dataAccessProvider.updateMessage(message, RongIMClient.logCallback(callback, "updateMessage")); }; RongIMClient.prototype.clearData = function () { return RongIMClient._dataAccessProvider.clearData(); }; RongIMClient.prototype.clearMessages = function (conversationType, targetId, callback) { RongIMClient._dataAccessProvider.clearMessages(conversationType, targetId, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "clearMessages" }); callback.onError(errorCode); }); } }); }; /**TODO 清楚本地存储的未读消息,目前清空内存中的未读消息 * [clearMessagesUnreadStatus 清空指定会话未读消息] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [用户id] * @param {ResultCallback} callback [返回值,参数回调] */ RongIMClient.prototype.clearMessagesUnreadStatus = function (conversationType, targetId, callback) { RongIMClient._dataAccessProvider.updateMessages(conversationType, targetId, "readStatus", null, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "clearMessagesUnreadStatus" }); callback.onError(errorCode); }); } }); }; // deleteRemoteMessages(conversationType: ConversationType, targetId: string, delMsgs: DeleteMessage[], callback: ResultCallback) { // CheckParam.getInstance().check(["number", "string|number", "array", "object"], "deleteRemoteMessages", false, arguments); // if (delMsgs.length == 0) { // var errorCode = ErrorCode.DELETE_MESSAGE_ID_IS_NULL; // RongIMClient.logger({ // code: errorCode, // funcName: "deleteRemoteMessages" // }); // callback.onError(ErrorCode.DELETE_MESSAGE_ID_IS_NULL); // return; // } else if (delMsgs.length > 100) { // delMsgs.length = 100; // } // // 后续增加,去掉注释即可 // callback.onSuccess(true); // // var modules = new RongIMClient.Protobuf.DeleteMsgInput(); // // modules.setType(conversationType); // // modules.setConversationId(targetId); // // modules.setMsgs(delMsgs); // // RongIMClient.bridge.queryMsg(33, MessageUtil.ArrayForm(modules.toArrayBuffer()), Bridge._client.userId, { // // onSuccess: function(info: any) { // // callback.onSuccess(true); // // }, // // onError: function(err: any) { // // callback.onError(err); // // } // // }, "DeleteMsgOutput"); // } /** * [deleteMessages 删除消息记录。] * @param {ConversationType} conversationType [description] * @param {string} targetId [description] * @param {number[]} messageIds [description] * @param {ResultCallback} callback [description] */ RongIMClient.prototype.deleteMessages = function (conversationType, targetId, messages, callback) { RongIMClient._dataAccessProvider.removeMessage(conversationType, targetId, messages, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "deleteMessages" }); callback.onError(errorCode); }); } }); }; RongIMClient.prototype.sendLocalMessage = function (message, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object"], "sendLocalMessage", false, arguments); RongIMClient._dataAccessProvider.updateMessage(message); this.sendMessage(message.conversationType, message.targetId, message.content, RongIMClient.logSendCallback(callback, "sendLocalMessage")); }; RongIMClient.prototype.getPullSetting = function (callback, version) { RongIMClient._dataAccessProvider.getPullSetting(callback, version); }; RongIMClient.prototype.setOfflineMessageDuration = function (duration, callback) { RongIMLib.CheckParam.getInstance().check(["number", "object"], "setOfflineMessageDuration", true, arguments); RongIMClient._dataAccessProvider.setOfflineMessageDuration(duration, callback); }; /** * [sendMessage 发送消息。] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [目标Id] * @param {MessageContent} messageContent [消息类型] * @param {SendMessageCallback} sendCallback [] * @param {ResultCallback} resultCallback [返回值,函数回调] * @param {string} pushContent [] * @param {string} pushData [] */ RongIMClient.prototype.sendMessage = function (conversationType, targetId, messageContent, sendCallback, mentiondMsg, pushText, appData, methodType, params) { RongIMLib.CheckParam.getInstance().check(["number", "string", "object", "object", "undefined|object|null|global|boolean", "undefined|object|null|global|string", "undefined|object|null|global|string", "undefined|object|null|global|number", "undefined|object|null|global|boolean"], "sendMessage", false, arguments); if (!RongIMLib.RongUtil.isString(targetId)) { return sendCallback.onError(RongIMLib.ErrorCode.PARAMETER_ERROR); } RongIMClient._dataAccessProvider.sendMessage(conversationType, targetId, messageContent, RongIMClient.logSendCallback(sendCallback, "sendMessage"), mentiondMsg, pushText, appData, methodType, params); }; RongIMClient.prototype.setConversationStatus = function (type, targetId, statusItem, callback) { RongIMClient._dataAccessProvider.setConversationStatus(type, targetId, statusItem, callback); }; RongIMClient.prototype.sendReceiptResponse = function (conversationType, targetId, sendCallback) { RongIMClient._dataAccessProvider.sendReceiptResponse(conversationType, targetId, RongIMClient.logSendCallback(sendCallback, "sendReceiptResponse")); }; RongIMClient.prototype.sendTypingStatusMessage = function (conversationType, targetId, messageName, sendCallback) { RongIMClient._dataAccessProvider.sendTypingStatusMessage(conversationType, targetId, messageName, RongIMClient.logSendCallback(sendCallback, "sendTypingStatusMessage")); }; /** * [sendStatusMessage description] * @param {MessageContent} messageContent [description] * @param {SendMessageCallback} sendCallback [description] * @param {ResultCallback} resultCallback [description] */ RongIMClient.prototype.sendStatusMessage = function (messageContent, sendCallback, resultCallback) { throw new Error("Not implemented yet"); }; /** * [sendTextMessage 发送TextMessage快捷方式] * @param {string} content [消息内容] * @param {ResultCallback} resultCallback [返回值,参数回调] */ RongIMClient.prototype.sendTextMessage = function (conversationType, targetId, content, sendMessageCallback) { RongIMClient._dataAccessProvider.sendTextMessage(conversationType, targetId, content, RongIMClient.logSendCallback(sendMessageCallback, "sendTextMessage")); }; RongIMClient.prototype.sendRecallMessage = function (content, sendMessageCallback, params) { var callback = RongIMClient.logSendCallback(sendMessageCallback, "sendRecallMessage"); var senderUserId = content.senderUserId; var userId = RongIMLib.Bridge._client.userId; var isOther = (senderUserId != userId); if (isOther) { var callback = RongIMClient.logSendCallback(sendMessageCallback, "sendRecallMessage"); callback.onError(RongIMLib.ErrorCode.RECALL_MESSAGE, content); return; } RongIMClient._dataAccessProvider.sendRecallMessage(content, callback, params); }; /** * [insertMessage 向本地插入一条消息,不发送到服务器。] * @param {ConversationType} conversationType [description] * @param {string} targetId [description] * @param {string} senderUserId [description] * @param {MessageContent} content [description] * @param {ResultCallback} callback [description] */ RongIMClient.prototype.insertMessage = function (conversationType, targetId, content, callback) { RongIMClient._dataAccessProvider.addMessage(conversationType, targetId, content, RongIMClient.logCallback(callback, "insertMessage")); }; RongIMClient.prototype.setMessageContent = function (messageId, content, objectName) { RongIMClient._dataAccessProvider.setMessageContent(messageId, content, objectName); }; ; RongIMClient.prototype.setMessageSearchField = function (messageId, content, searchFiles) { RongIMClient._dataAccessProvider.setMessageSearchField(messageId, content, searchFiles); }; ; /** * [getHistoryMessages 拉取历史消息记录。] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [用户Id] * @param {number|null} pullMessageTime [拉取历史消息起始位置(格式为毫秒数),可以为null] * @param {number} count [历史消息数量] * @param {ResultCallback} callback [回调函数] * @param {string} objectName [objectName] */ RongIMClient.prototype.getHistoryMessages = function (conversationType, targetId, timestamp, count, callback, objectname, order) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "number|null|global|object", "number", "object", "undefined|object|null|global|string", "number|null|global|object"], "getHistoryMessages", false, arguments); if (count > 20) { throw new Error("HistroyMessage count must be less than or equal to 20!"); } if (conversationType.valueOf() < 0) { throw new Error("ConversationType must be greater than -1"); } RongIMClient._dataAccessProvider.getHistoryMessages(conversationType, targetId, timestamp, count, RongIMClient.logCallback(callback, "getHistoryMessages"), objectname, order); }; /** * [getRemoteHistoryMessages 拉取某个时间戳之前的消息] * @param {ConversationType} conversationType [description] * @param {string} targetId [description] * @param {Date} dateTime [description] * @param {number} count [description] * @param {ResultCallback} callback [description] */ RongIMClient.prototype.getRemoteHistoryMessages = function (conversationType, targetId, timestamp, count, callback, config) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "number|null|global|object", "number", "object", "undefined|null|global|object"], "getRemoteHistoryMessages", false, arguments); var funcName = "getRemoteHistoryMessages"; var log = { errorCode: RongIMLib.ErrorCode.RC_CONN_PROTO_VERSION_ERROR, funcName: "getRemoteHistoryMessages" }; if (count > 20) { RongIMClient.logger(log); callback.onError(RongIMLib.ErrorCode.RC_CONN_PROTO_VERSION_ERROR); return; } if (conversationType.valueOf() < 0) { RongIMClient.logger(log); callback.onError(RongIMLib.ErrorCode.RC_CONN_PROTO_VERSION_ERROR); return; } RongIMClient._dataAccessProvider.getRemoteHistoryMessages(conversationType, targetId, timestamp, count, RongIMClient.logCallback(callback, funcName), config); }; RongIMClient.prototype.clearHistoryMessages = function (params, callback) { RongIMClient._dataAccessProvider.clearHistoryMessages(params, callback); }; RongIMClient.prototype.clearRemoteHistoryMessages = function (params, callback) { RongIMClient._dataAccessProvider.clearRemoteHistoryMessages(params, RongIMClient.logCallback(callback, "clearRemoteHistoryMessages")); }; RongIMClient.prototype.deleteRemoteMessages = function (conversationType, targetId, messages, callback) { RongIMClient._dataAccessProvider.deleteRemoteMessages(conversationType, targetId, messages, RongIMClient.logCallback(callback, "deleteRemoteMessages")); }; /** * [hasRemoteUnreadMessages 是否有未接收的消息,jsonp方法] * @param {string} appkey [appkey] * @param {string} token [token] * @param {ConnectCallback} callback [返回值,参数回调] */ RongIMClient.prototype.hasRemoteUnreadMessages = function (token, callback) { RongIMClient._dataAccessProvider.hasRemoteUnreadMessages(token, RongIMClient.logCallback(callback, "hasRemoteUnreadMessages")); }; RongIMClient.prototype.getTotalUnreadCount = function (callback, conversationTypes) { return RongIMClient._dataAccessProvider.getTotalUnreadCount({ onSuccess: function (count) { setTimeout(function () { callback.onSuccess(count); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "getTotalUnreadCount" }); callback.onError(errorCode); }); } }, conversationTypes); }; /** * [getConversationUnreadCount 指定多种会话类型获取未读消息数] * @param {ResultCallback} callback [返回值,参数回调。] * @param {ConversationType[]} ...conversationTypes [会话类型。] */ RongIMClient.prototype.getConversationUnreadCount = function (conversationTypes, callback) { RongIMClient._dataAccessProvider.getConversationUnreadCount(conversationTypes, { onSuccess: function (count) { setTimeout(function () { callback.onSuccess(count); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "getConversationUnreadCount" }); callback.onError(errorCode); }); } }); }; /** * [getUnreadCount 指定用户、会话类型的未读消息总数。] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [用户Id] */ RongIMClient.prototype.getUnreadCount = function (conversationType, targetId, callback) { RongIMClient._dataAccessProvider.getUnreadCount(conversationType, targetId, { onSuccess: function (count) { setTimeout(function () { callback.onSuccess(count); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "getUnreadCount" }); callback.onError(errorCode); }); } }); }; RongIMClient.prototype.setUnreadCount = function (conversationType, targetId, count) { RongIMLib.CheckParam.getInstance().check(["number", "string", "number"], "setUnreadCount", false, arguments); RongIMClient._dataAccessProvider.setUnreadCount(conversationType, targetId, count); }; RongIMClient.prototype.clearUnreadCountByTimestamp = function (conversationType, targetId, timestamp, callback) { RongIMClient._dataAccessProvider.clearUnreadCountByTimestamp(conversationType, targetId, timestamp, RongIMClient.logCallback(callback, "clearUnreadCountByTimestamp")); }; /** * 清楚会话未读消息数 * @param {ConversationType} conversationType 会话类型 * @param {string} targetId 目标Id * @param {ResultCallback} callback 返回值,函数回调 */ RongIMClient.prototype.clearUnreadCount = function (conversationType, targetId, callback) { RongIMClient._dataAccessProvider.clearUnreadCount(conversationType, targetId, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "clearUnreadCount" }); callback.onError(errorCode); }); } }); }; RongIMClient.prototype.clearTotalUnreadCount = function (callback) { RongIMClient._dataAccessProvider.clearTotalUnreadCount({ onSuccess: function (bool) { callback.onSuccess(bool); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: 'clearTotalUnreadCount' }); callback.onError(errorCode); }); } }); }; RongIMClient.prototype.clearLocalStorage = function (callback) { RongIMClient._storageProvider.clearItem(); callback(); }; RongIMClient.prototype.setMessageExtra = function (messageId, value, callback) { RongIMClient._dataAccessProvider.setMessageExtra(messageId, value, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "setMessageExtra" }); callback.onError(errorCode); }); } }); }; RongIMClient.prototype.setMessageReceivedStatus = function (messageUId, receivedStatus, callback) { RongIMClient._dataAccessProvider.setMessageReceivedStatus(messageUId, receivedStatus, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "setMessageReceivedStatus" }); callback.onError(errorCode); }); } }); }; RongIMClient.prototype.setMessageStatus = function (conersationType, targetId, timestamp, status, callback) { RongIMClient._dataAccessProvider.setMessageStatus(conersationType, targetId, timestamp, status, RongIMClient.logCallback(callback, "setMessageStatus")); }; RongIMClient.prototype.setMessageSentStatus = function (messageId, sentStatus, callback) { RongIMClient._dataAccessProvider.setMessageSentStatus(messageId, sentStatus, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "setMessageSentStatus" }); callback.onError(errorCode); }); } }); }; // #endregion Message // #region TextMessage Draft /** * clearTextMessageDraft 清除指定会话和消息类型的草稿。 * @param {ConversationType} conversationType 会话类型 * @param {string} targetId 目标Id */ RongIMClient.prototype.clearTextMessageDraft = function (conversationType, targetId) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "clearTextMessageDraft", false, arguments); var key = "darf_" + conversationType + "_" + targetId; delete RongIMClient._memoryStore[key]; return true; }; /** * [getTextMessageDraft 获取指定消息和会话的草稿。] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [目标Id] */ RongIMClient.prototype.getTextMessageDraft = function (conversationType, targetId) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "getTextMessageDraft", false, arguments); if (targetId == "" || conversationType < 0) { throw new Error("params error : " + RongIMLib.ErrorCode.DRAF_GET_ERROR); } var key = "darf_" + conversationType + "_" + targetId; return RongIMClient._memoryStore[key]; }; /** * [saveTextMessageDraft description] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [目标Id] * @param {string} value [草稿值] */ RongIMClient.prototype.saveTextMessageDraft = function (conversationType, targetId, value) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "string", "object"], "saveTextMessageDraft", false, arguments); var key = "darf_" + conversationType + "_" + targetId; RongIMClient._memoryStore[key] = value; return true; }; // #endregion TextMessage Draft // #region Conversation RongIMClient.prototype.searchConversationByContent = function (keyword, callback, conversationTypes) { RongIMClient._dataAccessProvider.searchConversationByContent(keyword, RongIMClient.logCallback(callback, "searchConversationByContent"), conversationTypes); }; RongIMClient.prototype.searchMessageByContent = function (conversationType, targetId, keyword, timestamp, count, total, callback) { RongIMClient._dataAccessProvider.searchMessageByContent(conversationType, targetId, keyword, timestamp, count, total, RongIMClient.logCallback(callback, "searchMessageByContent")); }; RongIMClient.prototype.clearCache = function () { RongIMClient._dataAccessProvider.clearCache(); }; RongIMClient.prototype.clearConversations = function (callback) { var conversationTypes = []; for (var _i = 1; _i < arguments.length; _i++) { conversationTypes[_i - 1] = arguments[_i]; } if (conversationTypes.length == 0) { conversationTypes = [RongIMLib.ConversationType.CHATROOM, RongIMLib.ConversationType.CUSTOMER_SERVICE, RongIMLib.ConversationType.DISCUSSION, RongIMLib.ConversationType.GROUP, RongIMLib.ConversationType.PRIVATE, RongIMLib.ConversationType.SYSTEM, RongIMLib.ConversationType.PUBLIC_SERVICE, RongIMLib.ConversationType.APP_PUBLIC_SERVICE]; } RongIMClient._dataAccessProvider.clearConversations(conversationTypes, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "clearConversations" }); callback.onError(errorCode); }); } }); }; /** * [getConversation 获取指定会话,此方法需在getConversationList之后执行] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [目标Id] * @param {ResultCallback} callback [返回值,函数回调] */ RongIMClient.prototype.getConversation = function (conversationType, targetId, callback) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "getConversation", false, arguments); RongIMClient._dataAccessProvider.getConversation(conversationType, targetId, { onSuccess: function (conver) { setTimeout(function () { callback.onSuccess(conver); }); }, onError: function (error) { setTimeout(function () { RongIMClient.logger({ code: error, funcName: "getConversation" }); callback.onError(error); }); } }); }; /** * [pottingConversation 组装会话列表] * @param {any} tempConver [临时会话] * conver_conversationType_targetId_no. * msg_conversationType_targetId_no. */ RongIMClient.prototype.pottingConversation = function (tempConver) { var self = this, isUseReplace = false; RongIMClient._dataAccessProvider.getConversation(tempConver.type, tempConver.userId, { onSuccess: function (conver) { if (!conver) { conver = new RongIMLib.Conversation(); } else { isUseReplace = true; } conver.conversationType = tempConver.type; conver.targetId = tempConver.userId; if (tempConver.msg) { conver.latestMessage = RongIMLib.MessageUtil.messageParser(tempConver.msg); conver.latestMessageId = conver.latestMessage.messageId; conver.objectName = conver.latestMessage.objectName; conver.receivedStatus = conver.latestMessage.receivedStatus; conver.receivedTime = conver.latestMessage.receiveTime; conver.sentStatus = conver.latestMessage.sentStatus; conver.sentTime = conver.latestMessage.sentTime; } var mentioneds = RongIMClient._storageProvider.getItem("mentioneds_" + RongIMLib.Bridge._client.userId + '_' + conver.conversationType + '_' + conver.targetId); if (mentioneds) { var info = JSON.parse(mentioneds); conver.mentionedMsg = info[tempConver.type + "_" + tempConver.userId]; } if (!isUseReplace) { if (RongIMLib.RongUtil.supportLocalStorage()) { // var count = RongIMClient._storageProvider.getItem("cu" + Bridge._client.userId + tempConver.type + tempConver.userId); conver.unreadMessageCount = RongIMLib.UnreadCountHandler.get(tempConver.type, tempConver.userId); } else { conver.unreadMessageCount = 0; } } if (conver.conversationType == RongIMLib.ConversationType.DISCUSSION) { self.getDiscussion(tempConver.userId, { onSuccess: function (info) { conver.conversationTitle = info.name; }, onError: function (error) { } }); } var status = RongIMClient._dataAccessProvider.conversationStatusManager.get(tempConver.type, tempConver.userId); conver.notificationStatus = status.notificationStatus; conver.isTop = status.isTop; RongIMClient._dataAccessProvider.addConversation(conver, { onSuccess: function (data) { } }); }, onError: function (error) { } }); }; RongIMClient.prototype.addConversation = function (conversation, callback) { RongIMClient._dataAccessProvider.addConversation(conversation, callback); }; RongIMClient.prototype.sortConversationList = function (conversationList) { var convers = []; for (var i = 0, len = conversationList.length; i < len; i++) { if (!conversationList[i]) { continue; } if (conversationList[i].isTop) { convers.push(conversationList[i]); conversationList.splice(i, 1); continue; } for (var j = 0; j < len - i - 1; j++) { if (conversationList[j].sentTime < conversationList[j + 1].sentTime) { var swap = conversationList[j]; conversationList[j] = conversationList[j + 1]; conversationList[j + 1] = swap; } } } return RongIMClient._memoryStore.conversationList = convers.concat(conversationList); }; RongIMClient.prototype.getConversationList = function (callback, conversationTypes, count, isGetHiddenConvers) { RongIMLib.CheckParam.getInstance().check(["object", "null|undefined|array|object|global", "number|undefined|null|object|global", "boolean|undefined|null|object|global"], "getConversationList", false, arguments); var me = this; RongIMClient._dataAccessProvider.getConversationList({ onSuccess: function (data) { if (conversationTypes || RongIMClient._dataAccessProvider) { setTimeout(function () { callback.onSuccess(data); }); } else { setTimeout(function () { callback.onSuccess(RongIMClient._memoryStore.conversationList); }); } }, onError: function (error) { setTimeout(function () { RongIMClient.logger({ code: error, funcName: "getConversationList" }); callback.onError(error); }); } }, conversationTypes, count, isGetHiddenConvers); }; RongIMClient.prototype.getRemoteConversationList = function (callback, conversationTypes, count, isGetHiddenConvers) { RongIMLib.CheckParam.getInstance().check(["object", "null|array|object|global", "number|undefined|null|object|global", "boolean|undefined|null|object|global"], "getRemoteConversationList", false, arguments); RongIMClient._dataAccessProvider.getRemoteConversationList(RongIMClient.logCallback(callback, "getRemoteConversationList"), conversationTypes, count, isGetHiddenConvers); }; RongIMClient.prototype.updateConversation = function (conversation) { return RongIMClient._dataAccessProvider.updateConversation(conversation); }; /** * [createConversation 创建会话。] * @param {number} conversationType [会话类型] * @param {string} targetId [目标Id] * @param {string} converTitle [会话标题] * @param {boolean} islocal [是否同步到服务器,ture:同步,false:不同步] */ RongIMClient.prototype.createConversation = function (conversationType, targetId, converTitle) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "string"], "createConversation", false, arguments); var conver = new RongIMLib.Conversation(); // var unreadContent: string = RongIMClient._storageProvider.getItem("cu" + Bridge._client.userId + conversationType + targetId); // var unreadCount = Number(unreadContent) || 0; conver.targetId = targetId; conver.conversationType = conversationType; conver.conversationTitle = converTitle; conver.latestMessage = {}; conver.unreadMessageCount = 0; return conver; }; //TODO 删除本地和服务器、删除本地和服务器分开 RongIMClient.prototype.removeConversation = function (conversationType, targetId, callback) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "removeConversation", false, arguments); RongIMClient._dataAccessProvider.removeConversation(conversationType, targetId, RongIMClient.logCallback(callback, "removeConversation")); }; RongIMClient.prototype.setConversationHidden = function (conversationType, targetId, isHidden) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "boolean"], "setConversationHidden", false, arguments); RongIMClient._dataAccessProvider.setConversationHidden(conversationType, targetId, isHidden); }; RongIMClient.prototype.setConversationToTop = function (conversationType, targetId, isTop, callback) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "boolean", "object"], "setConversationToTop", false, arguments); RongIMClient._dataAccessProvider.setConversationToTop(conversationType, targetId, isTop, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "setConversationToTop" }); callback.onError(errorCode); }); } }); }; // #endregion Conversation // #region Notifications /** * [getConversationNotificationStatus 获取指定用户和会话类型免提醒。] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [目标Id] * @param {ResultCallback} callback [返回值,函数回调] */ RongIMClient.prototype.getConversationNotificationStatus = function (conversationType, targetId, callback) { var params = { conversationType: conversationType, targetId: targetId }; RongIMClient._dataAccessProvider.getConversationNotificationStatus(params, RongIMClient.logCallback(callback, "getConversationNotificationStatus")); }; /** * [setConversationNotificationStatus 设置指定用户和会话类型免提醒。] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [目标Id] * @param {ResultCallback} callback [返回值,函数回调] */ RongIMClient.prototype.setConversationNotificationStatus = function (conversationType, targetId, notificationStatus, callback) { var params = { conversationType: conversationType, targetId: targetId, status: status }; RongIMClient._dataAccessProvider.setConversationNotificationStatus(params, RongIMClient.logCallback(callback, "setConversationNotificationStatus")); }; /** * [getNotificationQuietHours 获取免提醒消息时间。] * @param {GetNotificationQuietHoursCallback} callback [返回值,函数回调] */ RongIMClient.prototype.getNotificationQuietHours = function (callback) { throw new Error("Not implemented yet"); }; /** * [removeNotificationQuietHours 移除免提醒消息时间。] * @param {GetNotificationQuietHoursCallback} callback [返回值,函数回调] */ RongIMClient.prototype.removeNotificationQuietHours = function (callback) { throw new Error("Not implemented yet"); }; /** * [setNotificationQuietHours 设置免提醒消息时间。] * @param {GetNotificationQuietHoursCallback} callback [返回值,函数回调] */ RongIMClient.prototype.setNotificationQuietHours = function (startTime, spanMinutes, callback) { throw new Error("Not implemented yet"); }; // #endregion Notifications // #region Discussion /** * [addMemberToDiscussion 加入讨论组] * @param {string} discussionId [讨论组Id] * @param {string[]} userIdList [讨论中成员] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.addMemberToDiscussion = function (discussionId, userIdList, callback) { RongIMLib.CheckParam.getInstance().check(["string", "array", "object"], "addMemberToDiscussion", false, arguments); RongIMClient._dataAccessProvider.addMemberToDiscussion(discussionId, userIdList, RongIMClient.logCallback(callback, "addMemberToDiscussion")); }; /** * [createDiscussion 创建讨论组] * @param {string} name [讨论组名称] * @param {string[]} userIdList [讨论组成员] * @param {CreateDiscussionCallback} callback [返回值,函数回调] */ RongIMClient.prototype.createDiscussion = function (name, userIdList, callback) { RongIMLib.CheckParam.getInstance().check(["string", "array", "object"], "createDiscussion", false, arguments); RongIMClient._dataAccessProvider.createDiscussion(name, userIdList, callback); }; /** * [getDiscussion 获取讨论组信息] * @param {string} discussionId [讨论组Id] * @param {ResultCallback} callback [返回值,函数回调] */ RongIMClient.prototype.getDiscussion = function (discussionId, callback) { RongIMLib.CheckParam.getInstance().check(["string", "object"], "getDiscussion", false, arguments); RongIMClient._dataAccessProvider.getDiscussion(discussionId, RongIMClient.logCallback(callback, "getDiscussion")); }; /** * [quitDiscussion 退出讨论组] * @param {string} discussionId [讨论组Id] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.quitDiscussion = function (discussionId, callback) { RongIMLib.CheckParam.getInstance().check(["string", "object"], "quitDiscussion", false, arguments); RongIMClient._dataAccessProvider.quitDiscussion(discussionId, RongIMClient.logCallback(callback, "quitDiscussion")); }; /** * [removeMemberFromDiscussion 将指定成员移除讨论租] * @param {string} discussionId [讨论组Id] * @param {string} userId [被移除的用户Id] * @param {OperationCallback} callback [返回值,参数回调] */ RongIMClient.prototype.removeMemberFromDiscussion = function (discussionId, userId, callback) { RongIMLib.CheckParam.getInstance().check(["string", "string", "object"], "removeMemberFromDiscussion", false, arguments); RongIMClient._dataAccessProvider.removeMemberFromDiscussion(discussionId, userId, RongIMClient.logCallback(callback, "removeMemberFromDiscussion")); }; /** * [setDiscussionInviteStatus 设置讨论组邀请状态] * @param {string} discussionId [讨论组Id] * @param {DiscussionInviteStatus} status [邀请状态] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.setDiscussionInviteStatus = function (discussionId, status, callback) { RongIMLib.CheckParam.getInstance().check(["string", "number", "object"], "setDiscussionInviteStatus", false, arguments); RongIMClient._dataAccessProvider.setDiscussionInviteStatus(discussionId, status, RongIMClient.logCallback(callback, "setDiscussionInviteStatus")); }; /** * [setDiscussionName 设置讨论组名称] * @param {string} discussionId [讨论组Id] * @param {string} name [讨论组名称] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.setDiscussionName = function (discussionId, name, callback) { RongIMLib.CheckParam.getInstance().check(["string", "string", "object"], "setDiscussionName", false, arguments); RongIMClient._dataAccessProvider.setDiscussionName(discussionId, name, RongIMClient.logCallback(callback, "setDiscussionName")); }; // #endregion Discussion // #region ChatRoom /** * [加入聊天室。] * @param {string} chatroomId [聊天室Id] * @param {number} messageCount [拉取消息数量,-1为不拉去消息] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.joinChatRoom = function (chatroomId, messageCount, callback) { RongIMLib.CheckParam.getInstance().check(["string", "number", "object"], "joinChatRoom", false, arguments); if (chatroomId == "") { setTimeout(function () { var errorCode = RongIMLib.ErrorCode.CHATROOM_ID_ISNULL; RongIMClient.logger({ code: errorCode, funcName: "joinChatRoom" }); callback.onError(RongIMLib.ErrorCode.CHATROOM_ID_ISNULL); }); return; } RongIMClient._dataAccessProvider.joinChatRoom(chatroomId, messageCount, RongIMClient.logCallback(callback, "joinChatRoom")); }; RongIMClient.prototype.setDeviceInfo = function (device) { RongIMClient._dataAccessProvider.setDeviceInfo(device); }; RongIMClient.prototype.setChatroomHisMessageTimestamp = function (chatRoomId, timestamp) { RongIMLib.CheckParam.getInstance().check(["string", "number"], "setChatroomHisMessageTimestamp", false, arguments); RongIMClient._dataAccessProvider.setChatroomHisMessageTimestamp(chatRoomId, timestamp); }; RongIMClient.prototype.getChatRoomHistoryMessages = function (chatRoomId, count, order, callback) { RongIMLib.CheckParam.getInstance().check(["string", "number", "number", "object"], "getChatRoomHistoryMessages", false, arguments); RongIMClient._dataAccessProvider.getChatRoomHistoryMessages(chatRoomId, count, order, RongIMClient.logCallback(callback, "getChatRoomHistoryMessages")); }; RongIMClient.prototype.getChatRoomInfo = function (chatRoomId, count, order, callback) { RongIMLib.CheckParam.getInstance().check(["string", "number", "number", "object"], "getChatRoomInfo", false, arguments); RongIMClient._dataAccessProvider.getChatRoomInfo(chatRoomId, count, order, RongIMClient.logCallback(callback, "getChatRoomInfo")); }; /** * [退出聊天室] * @param {string} chatroomId [聊天室Id] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.quitChatRoom = function (chatroomId, callback) { RongIMLib.CheckParam.getInstance().check(["string", "object"], "quitChatRoom", false, arguments); RongIMClient._dataAccessProvider.quitChatRoom(chatroomId, RongIMClient.logCallback(callback, "quitChatRoom")); }; RongIMClient.prototype.setChatroomEntry = function (chatroomId, chatroomEntry, callback) { RongIMLib.CheckParam.getInstance().check(['string', 'object', 'object'], 'setChatroomEntry', false, arguments); RongIMClient._dataAccessProvider.setChatroomEntry(chatroomId, chatroomEntry, RongIMClient.logCallback(callback, "setChatroomEntry")); }; RongIMClient.prototype.forceSetChatroomEntry = function (chatroomId, chatroomEntry, callback) { RongIMLib.CheckParam.getInstance().check(['string', 'object', 'object'], 'setChatroomEntry', false, arguments); RongIMClient._dataAccessProvider.forceSetChatroomEntry(chatroomId, chatroomEntry, RongIMClient.logCallback(callback, "setChatroomEntry")); }; RongIMClient.prototype.getChatroomEntry = function (chatroomId, key, callback) { RongIMLib.CheckParam.getInstance().check(['string', 'string', 'object'], 'getChatroomEntry', false, arguments); RongIMClient._dataAccessProvider.getChatroomEntry(chatroomId, key, RongIMClient.logCallback(callback, "setChatroomEntry")); }; RongIMClient.prototype.getAllChatroomEntries = function (chatroomId, callback) { RongIMLib.CheckParam.getInstance().check(['string', 'object'], 'getAllChatroomEntries', false, arguments); RongIMClient._dataAccessProvider.getAllChatroomEntries(chatroomId, RongIMClient.logCallback(callback, "setChatroomEntry")); }; RongIMClient.prototype.removeChatroomEntry = function (chatroomId, chatroomEntry, callback) { RongIMLib.CheckParam.getInstance().check(['string', 'object', 'object'], 'removeChatroomEntry', false, arguments); RongIMClient._dataAccessProvider.removeChatroomEntry(chatroomId, chatroomEntry, RongIMClient.logCallback(callback, "setChatroomEntry")); }; RongIMClient.prototype.forceRemoveChatroomEntry = function (chatroomId, chatroomEntry, callback) { RongIMLib.CheckParam.getInstance().check(['string', 'object', 'object'], 'removeChatroomEntry', false, arguments); RongIMClient._dataAccessProvider.forceRemoveChatroomEntry(chatroomId, chatroomEntry, RongIMClient.logCallback(callback, "setChatroomEntry")); }; // #endregion ChatRoom // #region Public Service RongIMClient.prototype.getRemotePublicServiceList = function (callback, pullMessageTime) { RongIMClient._dataAccessProvider.getRemotePublicServiceList(RongIMClient.logCallback(callback, "getRemotePublicServiceList"), pullMessageTime); }; /** * [getPublicServiceList ]获取本地的公共账号列表 * @param {ResultCallback} callback [返回值,参数回调] */ RongIMClient.prototype.getPublicServiceList = function (callback) { if (RongIMClient._memoryStore.depend.openMp) { RongIMLib.CheckParam.getInstance().check(["object"], "getPublicServiceList", false, arguments); this.getRemotePublicServiceList(RongIMClient.logCallback(callback, "getPublicServiceList")); } }; /** * [getPublicServiceProfile ] 获取某公共服务信息。 * @param {PublicServiceType} publicServiceType [公众服务类型。] * @param {string} publicServiceId [公共服务 Id。] * @param {ResultCallback} callback [公共账号信息回调。] */ RongIMClient.prototype.getPublicServiceProfile = function (publicServiceType, publicServiceId, callback) { if (RongIMClient._memoryStore.depend.openMp) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "getPublicServiceProfile", false, arguments); RongIMClient._dataAccessProvider.getPublicServiceProfile(publicServiceType, publicServiceId, RongIMClient.logCallback(callback, "getPublicServiceProfile")); } }; /** * [pottingPublicSearchType ] 公众好查询类型 * @param {number} bussinessType [ 0-all 1-mp 2-mc] * @param {number} searchType [0-exact 1-fuzzy] */ RongIMClient.prototype.pottingPublicSearchType = function (bussinessType, searchType) { if (RongIMClient._memoryStore.depend.openMp) { var bits = 0; if (bussinessType == 0) { bits |= 3; if (searchType == 0) { bits |= 12; } else { bits |= 48; } } else if (bussinessType == 1) { bits |= 1; if (searchType == 0) { bits |= 8; } else { bits |= 32; } } else { bits |= 2; if (bussinessType == 0) { bits |= 4; } else { bits |= 16; } } return bits; } }; /** * [searchPublicService ]按公众服务类型搜索公众服务。 * @param {SearchType} searchType [搜索类型枚举。] * @param {string} keywords [搜索关键字。] * @param {ResultCallback} callback [搜索结果回调。] */ RongIMClient.prototype.searchPublicService = function (searchType, keywords, callback) { if (RongIMClient._memoryStore.depend.openMp) { RongIMLib.CheckParam.getInstance().check(["number", "string", "object"], "searchPublicService", false, arguments); var modules = new RongIMClient.Protobuf.SearchMpInput(); modules.setType(this.pottingPublicSearchType(0, searchType)); modules.setId(keywords); RongIMClient.bridge.queryMsg(29, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, RongIMClient.logCallback(callback, "searchPublicService"), "SearchMpOutput"); } }; /** * [searchPublicServiceByType ]按公众服务类型搜索公众服务。 * @param {PublicServiceType} publicServiceType [公众服务类型。] * @param {SearchType} searchType [搜索类型枚举。] * @param {string} keywords [搜索关键字。] * @param {ResultCallback} callback [搜索结果回调。] */ RongIMClient.prototype.searchPublicServiceByType = function (publicServiceType, searchType, keywords, callback) { if (RongIMClient._memoryStore.depend.openMp) { RongIMLib.CheckParam.getInstance().check(["number", "number", "string", "object"], "searchPublicServiceByType", false, arguments); var type = publicServiceType == RongIMLib.ConversationType.APP_PUBLIC_SERVICE ? 2 : 1; var modules = new RongIMClient.Protobuf.SearchMpInput(); modules.setType(this.pottingPublicSearchType(type, searchType)); modules.setId(keywords); RongIMClient.bridge.queryMsg(29, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, RongIMClient.logCallback(callback, "searchPublicServiceByType"), "SearchMpOutput"); } }; /** * [subscribePublicService ] 订阅公众号。 * @param {PublicServiceType} publicServiceType [公众服务类型。] * @param {string} publicServiceId [公共服务 Id。] * @param {OperationCallback} callback [订阅公众号回调。] */ RongIMClient.prototype.subscribePublicService = function (publicServiceType, publicServiceId, callback) { if (RongIMClient._memoryStore.depend.openMp) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "subscribePublicService", false, arguments); var modules = new RongIMClient.Protobuf.MPFollowInput(), me = this, follow = publicServiceType == RongIMLib.ConversationType.APP_PUBLIC_SERVICE ? "mcFollow" : "mpFollow"; modules.setId(publicServiceId); RongIMClient.bridge.queryMsg(follow, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function () { me.getRemotePublicServiceList({ onSuccess: function () { }, onError: function () { } }); callback.onSuccess(); }, onError: function (code) { var errorCode = code; RongIMClient.logger({ code: errorCode, funcName: "subscribePublicService" }); callback.onError(code); } }, "MPFollowOutput"); } }; /** * [unsubscribePublicService ] 取消订阅公众号。 * @param {PublicServiceType} publicServiceType [公众服务类型。] * @param {string} publicServiceId [公共服务 Id。] * @param {OperationCallback} callback [取消订阅公众号回调。] */ RongIMClient.prototype.unsubscribePublicService = function (publicServiceType, publicServiceId, callback) { if (RongIMClient._memoryStore.depend.openMp) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "unsubscribePublicService", false, arguments); var modules = new RongIMClient.Protobuf.MPFollowInput(), me = this, follow = publicServiceType == RongIMLib.ConversationType.APP_PUBLIC_SERVICE ? "mcUnFollow" : "mpUnFollow"; modules.setId(publicServiceId); RongIMClient.bridge.queryMsg(follow, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function () { RongIMClient._memoryStore.publicServiceMap.remove(publicServiceType, publicServiceId); callback.onSuccess(); }, onError: function (code) { var errorCode = code; RongIMClient.logger({ code: errorCode, funcName: "unsubscribePublicService" }); callback.onError(code); } }, "MPFollowOutput"); } }; // #endregion Public Service // #region Blacklist /** * [加入黑名单] * @param {string} userId [将被加入黑名单的用户Id] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.addToBlacklist = function (userId, callback) { RongIMLib.CheckParam.getInstance().check(["string|number", "object"], "addToBlacklist", false, arguments); RongIMClient._dataAccessProvider.addToBlacklist(userId, RongIMClient.logCallback(callback, "addToBlacklist")); }; /** * [获取黑名单列表] * @param {GetBlacklistCallback} callback [返回值,函数回调] */ RongIMClient.prototype.getBlacklist = function (callback) { RongIMLib.CheckParam.getInstance().check(["object"], "getBlacklist", false, arguments); RongIMClient._dataAccessProvider.getBlacklist(callback); }; /** * [得到指定人员再黑名单中的状态] * @param {string} userId [description] * @param {ResultCallback} callback [返回值,函数回调] */ //TODO 如果人员不在黑名单中,获取状态会出现异常 RongIMClient.prototype.getBlacklistStatus = function (userId, callback) { RongIMLib.CheckParam.getInstance().check(["string|number", "object"], "getBlacklistStatus", false, arguments); RongIMClient._dataAccessProvider.getBlacklistStatus(userId, RongIMClient.logCallback(callback, "getBlacklistStatus")); }; /** * [将指定用户移除黑名单] * @param {string} userId [将被移除的用户Id] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.removeFromBlacklist = function (userId, callback) { RongIMLib.CheckParam.getInstance().check(["string|number", "object"], "removeFromBlacklist", false, arguments); RongIMClient._dataAccessProvider.removeFromBlacklist(userId, RongIMClient.logCallback(callback, "removeFromBlacklist")); }; RongIMClient.prototype.getFileToken = function (fileType, callback, fileName) { RongIMLib.CheckParam.getInstance().check(["number", "object", "undefined|null|string"], "getQngetFileTokenTkn", false, arguments); RongIMClient._dataAccessProvider.getFileToken(fileType, RongIMClient.logCallback(callback, "getFileToken"), fileName); }; RongIMClient.prototype.getFileUrl = function (fileType, fileName, oriName, callback, data) { RongIMLib.CheckParam.getInstance().check(["number", "string", "string|global|object|null", "object", "undefined|null|object"], "getFileUrl", false, arguments); RongIMClient._dataAccessProvider.getFileUrl(fileType, fileName, oriName, RongIMClient.logCallback(callback, "getFileUrl"), data); }; ; // #endregion Blacklist // #region Real-time Location Service RongIMClient.prototype.addRealTimeLocationListener = function (conversationType, targetId, listener) { throw new Error("Not implemented yet"); }; RongIMClient.prototype.getRealTimeLocation = function (conversationType, targetId) { throw new Error("Not implemented yet"); }; RongIMClient.prototype.getRealTimeLocationCurrentState = function (conversationType, targetId) { throw new Error("Not implemented yet"); }; RongIMClient.prototype.getRealTimeLocationParticipants = function (conversationType, targetId) { throw new Error("Not implemented yet"); }; RongIMClient.prototype.joinRealTimeLocation = function (conversationType, targetId) { throw new Error("Not implemented yet"); }; RongIMClient.prototype.quitRealTimeLocation = function (conversationType, targetId) { throw new Error("Not implemented yet"); }; RongIMClient.prototype.startRealTimeLocation = function (conversationType, targetId) { throw new Error("Not implemented yet"); }; RongIMClient.prototype.updateRealTimeLocationStatus = function (conversationType, targetId, latitude, longitude) { throw new Error("Not implemented yet"); }; // #endregion Real-time Location Service // # startVoIP RongIMClient.prototype.startCall = function (converType, targetId, userIds, mediaType, extra, callback) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "array", "number", "string", "object"], "startCall", false, arguments); if (RongIMClient._memoryStore.voipStategy) { RongIMClient._voipProvider.startCall(converType, targetId, userIds, mediaType, extra, RongIMClient.logCallback(callback, "startCall")); } else { var errorCode = RongIMLib.ErrorCode.VOIP_NOT_AVALIABLE; RongIMClient.logger({ code: errorCode, funcName: "startCall" }); callback.onError(RongIMLib.ErrorCode.VOIP_NOT_AVALIABLE); } }; RongIMClient.prototype.joinCall = function (mediaType, callback) { RongIMLib.CheckParam.getInstance().check(['number', 'object'], "joinCall", false, arguments); if (RongIMClient._memoryStore.voipStategy) { RongIMClient._voipProvider.joinCall(mediaType, RongIMClient.logCallback(callback, "joinCall")); } else { var errorCode = RongIMLib.ErrorCode.VOIP_NOT_AVALIABLE; RongIMClient.logger({ code: errorCode, funcName: "joinCall" }); callback.onError(RongIMLib.ErrorCode.VOIP_NOT_AVALIABLE); } }; RongIMClient.prototype.hungupCall = function (converType, targetId, reason) { RongIMLib.CheckParam.getInstance().check(["number", "string", "number"], "hungupCall", false, arguments); if (RongIMClient._memoryStore.voipStategy) { RongIMClient._voipProvider.hungupCall(converType, targetId, reason); } }; RongIMClient.prototype.changeMediaType = function (converType, targetId, mediaType, callback) { RongIMLib.CheckParam.getInstance().check(["number", "string", "number", "object"], "changeMediaType", false, arguments); if (RongIMClient._memoryStore.voipStategy) { RongIMClient._voipProvider.changeMediaType(converType, targetId, mediaType, RongIMClient.logCallback(callback, "changeMediaType")); } else { var errorCode = RongIMLib.ErrorCode.VOIP_NOT_AVALIABLE; RongIMClient.logger({ code: errorCode, funcName: "changeMediaType" }); callback.onError(RongIMLib.ErrorCode.VOIP_NOT_AVALIABLE); } }; // # endVoIP RongIMClient.prototype.getUnreadMentionedMessages = function (conversationType, targetId) { return RongIMClient._dataAccessProvider.getUnreadMentionedMessages(conversationType, targetId); }; RongIMClient.prototype.clearListeners = function () { RongIMClient._dataAccessProvider.clearListeners(); }; // UserStatus start RongIMClient.prototype.getUserStatus = function (userId, callback) { RongIMClient._dataAccessProvider.getUserStatus(userId, RongIMClient.logCallback(callback, "getUserStatus")); }; RongIMClient.prototype.setUserStatus = function (status, callback) { RongIMClient._dataAccessProvider.setUserStatus(status, RongIMClient.logCallback(callback, "setUserStatus")); }; RongIMClient.prototype.setUserStatusListener = function (params, callback) { var userIds = params.userIds; var multiple = params.multiple; RongIMClient.userStatusObserver.watch({ key: userIds, func: callback, multiple: multiple }); RongIMClient._dataAccessProvider.setUserStatusListener(params, callback); }; // UserStaus end // RTC start RongIMClient.messageWatch = function (watcher) { RongIMClient.RTCListener = watcher; }; RongIMClient.messageSignalWatch = function (watcher) { RongIMClient.RTCSignalLisener = watcher; }; /* var data = { key1: 123, key2: 345 }; */ RongIMClient.prototype.getRTCUserInfoList = function (room, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object"], "getRTCUserInfoList", false, arguments); RongIMClient._dataAccessProvider.getRTCUserInfoList(room, callback); }; RongIMClient.prototype.getRTCUserList = function (room, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object"], "getRTCUserList", false, arguments); RongIMClient._dataAccessProvider.getRTCUserList(room, callback); }; RongIMClient.prototype.setRTCUserInfo = function (room, info, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object", "object"], "setRTCUserInfo", false, arguments); RongIMClient._dataAccessProvider.setRTCUserInfo(room, info, callback); }; RongIMClient.prototype.removeRTCUserInfo = function (room, info, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object", "object"], "removeRTCUserInfo", false, arguments); RongIMClient._dataAccessProvider.removeRTCUserInfo(room, info, callback); }; RongIMClient.prototype.getRTCRoomInfo = function (room, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object"], "getRTCRoomInfo", false, arguments); RongIMClient._dataAccessProvider.getRTCRoomInfo(room, callback); }; RongIMClient.prototype.setRTCRoomInfo = function (room, info, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object", "object"], "setRTCRoomInfo", false, arguments); RongIMClient._dataAccessProvider.setRTCRoomInfo(room, info, callback); }; RongIMClient.prototype.removeRTCRoomInfo = function (room, info, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object", "object"], "removeRTCRoomInfo", false, arguments); RongIMClient._dataAccessProvider.removeRTCRoomInfo(room, info, callback); }; RongIMClient.prototype.joinRTCRoom = function (room, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object"], "joinRTCRoom", false, arguments); if (RongIMClient.isJoinedRTCRoom) { return callback.onSuccess(RongIMClient.roomInfo); } RongIMClient._dataAccessProvider.joinRTCRoom(room, { onSuccess: function (result) { RongIMClient.roomInfo = result; RongIMClient.isJoinedRTCRoom = true; callback.onSuccess(result); }, onError: callback.onError }); }; RongIMClient.prototype.quitRTCRoom = function (room, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object"], "quitRTCRoom", false, arguments); RongIMClient.isJoinedRTCRoom = false; RongIMClient._dataAccessProvider.quitRTCRoom(room, { onSuccess: function () { RongIMClient.roomInfo = { users: {}, token: '' }; callback.onSuccess(true); }, onError: callback.onError }); }; RongIMClient.prototype.RTCPing = function (room, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object"], "RTCPing", false, arguments); RongIMClient._dataAccessProvider.RTCPing(room, callback); }; RongIMClient.prototype.setRTCUserData = function (roomId, key, value, isInner, callback, message) { RongIMLib.CheckParam.getInstance().check(["string", "string", "string", "boolean", "object", "global|object|null|undefined"], "setRTCUserData", false, arguments); RongIMClient._dataAccessProvider.setRTCUserData(roomId, key, value, isInner, callback, message); }; RongIMClient.prototype.setRTCUserTotalRes = function (roomId, message, valueInfo, objectName, callback) { RongIMLib.CheckParam.getInstance().check(["string", 'object', "string", "string", "object"], "setRTCUserTotalRes", false, arguments); RongIMClient._dataAccessProvider.setRTCUserTotalRes(roomId, message, valueInfo, objectName, callback); }; RongIMClient.prototype.getRTCUserData = function (roomId, keys, isInner, callback) { RongIMLib.CheckParam.getInstance().check(["string", "array", "boolean", "object", "global|object|null"], "getRTCUserData", false, arguments); RongIMClient._dataAccessProvider.getRTCUserData(roomId, keys, isInner, callback); }; RongIMClient.prototype.removeRTCUserData = function (roomId, keys, isInner, callback, message) { RongIMLib.CheckParam.getInstance().check(["string", "array", "boolean", "object", "global|object|null|undefined"], "removeRTCUserData", false, arguments); RongIMClient._dataAccessProvider.removeRTCUserData(roomId, keys, isInner, callback, message); }; RongIMClient.prototype.setRTCRoomData = function (roomId, key, value, isInner, callback, message) { RongIMLib.CheckParam.getInstance().check(["string", "string", "string", "boolean", "object", "global|object|null|undefined"], "setRTCRoomData", false, arguments); RongIMClient._dataAccessProvider.setRTCRoomData(roomId, key, value, isInner, callback, message); }; RongIMClient.prototype.getRTCRoomData = function (roomId, keys, isInner, callback) { RongIMLib.CheckParam.getInstance().check(["string", "array", "boolean", "object"], "getRTCRoomData", false, arguments); RongIMClient._dataAccessProvider.getRTCRoomData(roomId, keys, isInner, callback); }; RongIMClient.prototype.removeRTCRoomData = function (roomId, keys, isInner, callback, message) { RongIMLib.CheckParam.getInstance().check(["string", "array", "boolean", "object", "global|object|null|undefined"], "removeRTCRoomData", false, arguments); RongIMClient._dataAccessProvider.removeRTCRoomData(roomId, keys, isInner, callback, message); }; RongIMClient.prototype.setRTCOutData = function (roomId, data, type, callback, message) { RongIMClient._dataAccessProvider.setRTCOutData(roomId, data, type, callback, message); }; // 信令 SDK 新增 RongIMClient.prototype.getRTCOutData = function (roomId, userIds, callback) { RongIMClient._dataAccessProvider.getRTCOutData(roomId, userIds, callback); }; RongIMClient.prototype.getNavi = function () { return RongIMClient._dataAccessProvider.getNavi(); }; RongIMClient.prototype.getRTCToken = function (room, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object"], "getRTCToken", false, arguments); return RongIMClient._dataAccessProvider.getRTCToken(room, callback); }; RongIMClient.prototype.setRTCState = function (room, content, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object", "object"], "setRTCState", false, arguments); return RongIMClient._dataAccessProvider.setRTCState(room, content, callback); }; RongIMClient.prototype.getAppInfo = function () { var appKey = RongIMClient._memoryStore.appKey; return { appKey: appKey }; }; RongIMClient.prototype.getSDKInfo = function () { return { version: RongIMClient.sdkver }; }; RongIMClient.HttpProtocol = { http: 'http://', https: 'https://' }; RongIMClient.WsProtocol = { ws: 'ws://', wss: 'wss://' }; RongIMClient.RTCListener = function () { }; RongIMClient.RTCInnerListener = function () { }; RongIMClient.RTCSignalLisener = function () { }; RongIMClient.MaxMessageContentBytes = 131072; // 128kb RongIMClient.NavMarkInToken = '@'; RongIMClient.NavSeparatorInToken = ';'; RongIMClient.NavExpiredTime = 7200000; // 2 小时 RongIMClient.currentServer = ''; RongIMClient.LogFactory = {}; RongIMClient.MessageType = {}; RongIMClient.RegisterMessage = {}; RongIMClient._memoryStore = { isPullFinished: false, syncMsgQueue: [] }; RongIMClient.isNotPullMsg = false; RongIMClient.userStatusObserver = null; RongIMClient.sdkver = '2.5.9'; RongIMClient.otherDeviceLoginCount = 0; RongIMClient.serverStore = { index: 0 }; RongIMClient.isFirstConnect = true; RongIMClient.roomInfo = { users: {}, token: '' }; RongIMClient.invalidWsUrls = []; RongIMClient.isJoinedRTCRoom = false; RongIMClient.statusListeners = []; RongIMClient.messageListeners = []; RongIMClient.settingListeners = []; RongIMClient.conversationStatusListeners = []; RongIMClient.userStatusListener = null; return RongIMClient; })(); RongIMLib.RongIMClient = RongIMClient; })(RongIMLib || (RongIMLib = {})); //用于连接通道 var RongIMLib; (function (RongIMLib) { (function (Qos) { Qos[Qos["AT_MOST_ONCE"] = 0] = "AT_MOST_ONCE"; Qos[Qos["AT_LEAST_ONCE"] = 1] = "AT_LEAST_ONCE"; Qos[Qos["EXACTLY_ONCE"] = 2] = "EXACTLY_ONCE"; Qos[Qos["DEFAULT"] = 3] = "DEFAULT"; })(RongIMLib.Qos || (RongIMLib.Qos = {})); var Qos = RongIMLib.Qos; (function (Type) { Type[Type["CONNECT"] = 1] = "CONNECT"; Type[Type["CONNACK"] = 2] = "CONNACK"; Type[Type["PUBLISH"] = 3] = "PUBLISH"; Type[Type["PUBACK"] = 4] = "PUBACK"; Type[Type["QUERY"] = 5] = "QUERY"; Type[Type["QUERYACK"] = 6] = "QUERYACK"; Type[Type["QUERYCON"] = 7] = "QUERYCON"; Type[Type["SUBSCRIBE"] = 8] = "SUBSCRIBE"; Type[Type["SUBACK"] = 9] = "SUBACK"; Type[Type["UNSUBSCRIBE"] = 10] = "UNSUBSCRIBE"; Type[Type["UNSUBACK"] = 11] = "UNSUBACK"; Type[Type["PINGREQ"] = 12] = "PINGREQ"; Type[Type["PINGRESP"] = 13] = "PINGRESP"; Type[Type["DISCONNECT"] = 14] = "DISCONNECT"; })(RongIMLib.Type || (RongIMLib.Type = {})); var Type = RongIMLib.Type; RongIMLib.StatusTopic = (function () { var ConversationType = RongIMLib.ConversationType; var topic = {}; topic[ConversationType.PRIVATE] = 'ppMsgS'; topic[ConversationType.GROUP] = 'pgMsgS'; return topic; })(); var _topic = [ "invtDiz", "crDiz", "qnUrl", "userInf", "dizInf", "userInf", "joinGrp", "quitDiz", "exitGrp", "evctDiz", ["", "ppMsgP", "pdMsgP", "pgMsgP", "chatMsg", "pcMsgP", "", "pmcMsgN", "pmpMsgN", "", "", "", "prMsgS", "prMsgP"], "pdOpen", "rename", "uGcmpr", "qnTkn", "destroyChrm", "createChrm", "exitChrm", "queryChrm", "joinChrm", "pGrps", "addBlack", "rmBlack", "getBlack", "blackStat", "addRelation", "qryRelation", "delRelation", "pullMp", "schMp", "qnTkn", "qnUrl", "qryVoipK", "delMsg", "qryCHMsg", "getUserStatus", "setUserStatus", "subUserStatus", "cleanHisMsg" ]; var Channel = (function () { function Channel(cb, self) { this.connectionStatus = -1; var appId = self.appId; var token = encodeURIComponent(self.token); var sdkVer = self.sdkVer; var apiVer = self.apiVer; this.self = self; this.socket = Socket.getInstance().createServer(); var that = this; var storage = RongIMLib.RongIMClient._storageProvider; var servers = storage.getItem('servers'); servers = JSON.parse(servers) || []; var depend = RongIMLib.RongIMClient._memoryStore.depend; var customCmpUrl = depend.cmpUrl; if (RongIMLib.RongUtil.isValidWsUrl(customCmpUrl)) { servers = [customCmpUrl]; } else { servers = RongIMLib.RongUtil.getValidWsUrlList(servers); } var startConnect = function (host) { var tpl = '{host}/websocket?appId={appId}&token={token}&sdkVer={sdkVer}&apiVer={apiVer}'; that.url = RongIMLib.RongUtil.tplEngine(tpl, { host: host, appId: appId, token: token, sdkVer: sdkVer, apiVer: apiVer }); that.socket.connect(that.url, cb); // 临时兼容 Comet 逻辑,Comet 中用到 var userId = storage.getItem('rong_current_user'); RongIMLib.Navigation.Endpoint = { host: host, userId: userId }; }; var connectMap = { get: function () { // 所有链接计算器,超过 15 秒后认为所有 CMP 地址均不可用 var totalTimer = new RongIMLib.Timer({ timeout: 1 * 1000 * 15 }); var timers = []; var xhrs = []; var isFinished = false; var clearHandler = function () { for (var i = 0; i < timers.length; i++) { var timer = timers[i]; clearTimeout(timer); } for (var i = 0; i < xhrs.length; i++) { var xhr = xhrs[i]; xhr.abort(); } timers.length = 0; xhrs.length = 0; }; var request = function (config, callback) { var url = config.url; var time = config.time; if (isFinished) { return; } var timer = setTimeout(function () { var onSuccess = function () { if (isFinished) { return; } clearHandler(); isFinished = true; totalTimer.pause(); callback(url); RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.L_PING_WS_R, level: RongIMLib.LoggerLevel.I, type: RongIMLib.LoggerType.IM, content: { url: url } }); }; var xhr = RongIMLib.MessageUtil.detectCMP({ url: url, success: onSuccess, fail: function (code) { console.log(code); RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.L_PING_WS_R, level: RongIMLib.LoggerLevel.E, type: RongIMLib.LoggerType.IM, content: { url: url, code: code } }); } }); xhrs.push(xhr); }, time); timers.push(timer); }; var snifferCallback = function (url) { var reg = /(http|https):\/\/([^\/]+)/i; var host = url.match(reg)[2]; RongIMLib.RongIMClient.currentServer = host; startConnect(host); }; var snifferTpl = '{protocol}{server}/ping?r={random}'; for (var i = 0; i < servers.length; i++) { var server = servers[i]; if (server) { server = RongIMLib.RongUtil.tplEngine(snifferTpl, { protocol: depend.protocol, server: server, random: RongIMLib.RongUtil.getTimestamp() }); request({ url: server, time: i * 1000 }, snifferCallback); RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.L_PING_WS_T, level: RongIMLib.LoggerLevel.I, type: RongIMLib.LoggerType.IM, content: { url: server } }); } } totalTimer.resume(function () { RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.L_PING_WS_R, level: RongIMLib.LoggerLevel.F, type: RongIMLib.LoggerType.IM, content: { desc: 'all websocket addresses are unavailable', cmp: servers, ConnectionStatus: RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE, available: false } }); clearHandler(); for (var i = 0; i < servers.length; i++) { RongIMLib.RongIMClient.invalidWsUrls.push(servers[i]); } var storeServers = storage.getItem('servers'); try { storeServers = JSON.parse(storeServers); !RongIMLib.RongUtil.getValidWsUrlList(storeServers).length && RongIMLib.Navigation.clear(); } catch (e) { } that.socket.fire("StatusChanged", RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE); }); }, element: function () { var totalTimer = new RongIMLib.Timer({ timeout: 1 * 1000 * 15 }); var timers = []; var elements = []; var isFinished = false; var clearHandler = function () { for (var i = 0; i < timers.length; i++) { var timer = timers[i]; clearTimeout(timer); } for (var i = 0; i < elements.length; i++) { var el = elements[i]; document.body.removeChild(el); } }; var request = function (config, callback) { var url = config.url; var time = config.time; if (isFinished) { return; } var timer = setTimeout(function () { var el = document.createElement('script'); el.src = url; document.body.appendChild(el); el.onerror = function () { if (isFinished) { return; } clearHandler(); isFinished = true; totalTimer.pause(); var url = el.src; callback(url); }; elements.push(el); }, time); timers.push(timer); }; var snifferCallback = function (url) { var reg = /(http|https):\/\/([^\/]+)/i; var host = url.match(reg)[2]; startConnect(host); }; var snifferTpl = '//{server}/{path}'; for (var i = 0; i < servers.length; i++) { var server = RongIMLib.RongUtil.tplEngine(snifferTpl, { server: servers[i], path: i }); request({ url: server, time: i * 1000 }, snifferCallback); } totalTimer.resume(function () { for (var i = 0; i < servers.length; i++) { RongIMLib.RongIMClient.invalidWsUrls.push(servers[i]); } clearHandler(); that.socket.fire("StatusChanged", RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE); }); } }; var isWSPingJSONP = depend.isWSPingJSONP; var connectType = isWSPingJSONP ? 'element' : 'get'; connectMap[connectType](); //注册状态改变观察者 var StatusEvent = Channel._ConnectionStatusListener; var hasEvent = (typeof StatusEvent == "object"); var me = this; me.socket.on("StatusChanged", function (code) { if (RongIMLib.Bridge && RongIMLib.Bridge._client && RongIMLib.Bridge._client.channel && me !== RongIMLib.Bridge._client.channel) { me.connectionStatus = code; return; } if (!hasEvent) { throw new Error("setConnectStatusListener:Parameter format is incorrect"); } var isNetworkUnavailable = (code == RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE); var isWebSocket = !RongIMLib.RongIMClient._memoryStore.depend.isPolling; if (RongIMLib.RongIMClient.isFirstConnect && isNetworkUnavailable && isWebSocket) { code = RongIMLib.ConnectionStatus.WEBSOCKET_UNAVAILABLE; } if (isNetworkUnavailable) { var storage = RongIMLib.RongIMClient._storageProvider; var servers = storage.getItem('servers'); servers = JSON.parse(servers); var currentServer = RongIMLib.RongIMClient.currentServer; if (currentServer) { var index = RongIMLib.RongUtil.indexOf(servers, currentServer); // 如果 currentServer 是 servers 的最后一个,不再替换位置 if (!RongIMLib.RongUtil.isEqual(index, -1)) { var server = servers.splice(index, 1)[0]; servers.push(server); storage.setItem('servers', JSON.stringify(servers)); } } } me.connectionStatus = code; setTimeout(function () { StatusEvent.onChanged(code); var unReportCodes = [RongIMLib.ConnectionStatus.CONNECTING, RongIMLib.ConnectionStatus.REQUEST_NAVI, RongIMLib.ConnectionStatus.RESPONSE_NAVI]; var isReportCode = RongIMLib.RongUtil.indexOf(unReportCodes, code) === -1; if (isReportCode) { RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.L_NETC_S, level: RongIMLib.LoggerLevel.I, type: RongIMLib.LoggerType.IM, content: { ConnectionStatus: code, available: false } }); } }); var isDisconnected = (code == RongIMLib.ConnectionStatus.DISCONNECTED); if (isDisconnected) { self.clearHeartbeat(); } var isOtherDevice = (code == RongIMLib.ConnectionStatus.KICKED_OFFLINE_BY_OTHER_CLIENT); if (isOtherDevice) { // 累计其他设备登陆次数,超过 5 次后,自动销毁内部对象 // 删除位置:ServerDataProivder.prototype.connect RongIMLib.RongIMClient.otherDeviceLoginCount++; } var isConnected = (code == RongIMLib.ConnectionStatus.CONNECTED); if (isConnected) { RongIMLib.RongIMClient.isFirstConnect = false; } var isWebsocketUnAvailable = (code == RongIMLib.ConnectionStatus.WEBSOCKET_UNAVAILABLE); if (isWebsocketUnAvailable) { if (RongIMLib.RongUtil.getValidWsUrlList(servers).length) { RongIMLib.RongIMClient._storageProvider.setItem("rongSDK", RongIMLib.Transportations._TransportType); RongIMLib.RongIMClient.connect(self.token, RongIMLib.RongIMClient._memoryStore.callback); } else { me.changeConnectType(); RongIMLib.RongIMClient.isFirstConnect = false; RongIMLib.RongIMClient.connect(self.token, RongIMLib.RongIMClient._memoryStore.callback); } } }); //注册message观察者 this.socket.on("message", self.handler.handleMessage); //注册断开连接观察者 this.socket.on("disconnect", function (status) { that.socket.fire("StatusChanged", status ? status : 2); }); } Channel.prototype.changeConnectType = function () { RongIMLib.RongIMClient._memoryStore.depend.isPolling = !RongIMLib.RongIMClient._memoryStore.depend.isPolling; new RongIMLib.FeatureDectector(); }; Channel.prototype.writeAndFlush = function (val) { this.socket.send(val); }; Channel.prototype.reconnect = function (callback) { RongIMLib.MessageIdHandler.clearMessageId(); this.socket = this.socket.reconnect(); if (callback) { this.self.reconnectObj = callback; } }; Channel.prototype.disconnect = function (status) { this.socket.disconnect(status); }; return Channel; })(); RongIMLib.Channel = Channel; var Socket = (function () { function Socket() { this.socket = null; this._events = {}; } Socket.getInstance = function () { return new Socket(); }; Socket.prototype.connect = function (url, cb) { if (this.socket) { if (url) { RongIMLib.RongIMClient._storageProvider.setItem("rongSDK", this.checkTransport()); this.on("connect", cb || new Function); } if (url) { this.currentURL = url; } this.socket.createTransport(url); } return this; }; Socket.prototype.createServer = function () { var transport = this.getTransport(this.checkTransport()); if (transport === null) { throw new Error("the channel was not supported"); } return transport; }; Socket.prototype.getTransport = function (transportType) { if (transportType == Socket.XHR_POLLING) { this.socket = new RongIMLib.PollingTransportation(this); } else if (transportType == Socket.WEBSOCKET) { this.socket = new RongIMLib.SocketTransportation(this); } return this; }; Socket.prototype.send = function (data) { if (this.socket) { if (this.checkTransport() == Socket.WEBSOCKET) { this.socket.send(data); } else { this.socket.send(this._encode(data)); } } }; Socket.prototype.onMessage = function (data) { this.fire("message", data); }; Socket.prototype.disconnect = function (status) { this.socket.disconnect(status); this.fire("disconnect", status); return this; }; Socket.prototype.reconnect = function () { if (this.currentURL && RongIMLib.RongIMClient._storageProvider.getItem("rongSDK")) { return this.connect(this.currentURL, null); } else { throw new Error("reconnect:no have URL"); } }; /** * [checkTransport 返回通道类型] */ Socket.prototype.checkTransport = function () { if (RongIMLib.RongIMClient._memoryStore.depend.isPolling) { RongIMLib.Transportations._TransportType = Socket.XHR_POLLING; } return RongIMLib.Transportations._TransportType; }; Socket.prototype.fire = function (x, args) { if (x in this._events) { for (var i = 0, ii = this._events[x].length; i < ii; i++) { this._events[x][i](args); } } return this; }; Socket.prototype.on = function (x, func) { if (!(typeof func == "function" && x)) { return this; } if (x in this._events) { RongIMLib.MessageUtil.indexOf(this._events, func) == -1 && this._events[x].push(func); } else { this._events[x] = [func]; } return this; }; Socket.prototype.removeEvent = function (x, fn) { if (x in this._events) { for (var a = 0, l = this._events[x].length; a < l; a++) { if (this._events[x][a] == fn) { this._events[x].splice(a, 1); } } } return this; }; Socket.prototype._encode = function (x) { var str = "?messageid=" + x.getMessageId() + "&header=" + x.getHeaderFlag() + "&sessionid=" + RongIMLib.RongIMClient._storageProvider.getItem("sId" + RongIMLib.Navigation.Endpoint.userId); if (!/(PubAckMessage|QueryConMessage)/.test(x._name)) { str += "&topic=" + x.getTopic() + "&targetid=" + (x.getTargetId() || ""); } return { url: str, data: "getData" in x ? x.getData() : "" }; }; //消息通道常量,所有和通道相关判断均用 XHR_POLLING WEBSOCKET两属性 Socket.XHR_POLLING = "xhr-polling"; Socket.WEBSOCKET = "websocket"; return Socket; })(); RongIMLib.Socket = Socket; //连接端消息累 var Client = (function () { function Client(token, appId) { this.timeoutMillis = 6000; this.timeout_ = 0; this.sdkVer = ''; this.apiVer = Math.floor(Math.random() * 1e6); this.channel = null; this.handler = null; this.userId = ""; this.reconnectObj = {}; this.heartbeat = 0; this.pullMsgHearbeat = 0; this.chatroomId = ""; this.SyncTimeQueue = []; this.cacheMessageIds = []; this.token = token; this.appId = appId; this.SyncTimeQueue.state = "complete"; this.sdkVer = RongIMLib.RongIMClient.sdkver; } Client.prototype.resumeTimer = function () { var me = this; this.timeout_ = setTimeout(function () { me.channel.disconnect(RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE); }, this.timeoutMillis); }; Client.prototype.pauseTimer = function () { if (this.timeout_) { clearTimeout(this.timeout_); this.timeout_ = 0; } }; Client.prototype.connect = function (_callback) { //实例消息处理类 this.handler = new MessageHandler(this); //设置连接回调 this.handler.setConnectCallback(_callback); //实例通道类型 var me = this; this.channel = new Channel(function () { RongIMLib.Transportations._TransportType == Socket.WEBSOCKET && me.keepLive(); }, this); //触发状态改变观察者 this.channel.socket.fire("StatusChanged", RongIMLib.ConnectionStatus.CONNECTING); //没有返回地址就手动抛出错误 //_callback.onError(ConnectionState.NOT_AUTHORIZED); }; Client.prototype.checkSocket = function (callback) { var me = this; me.channel.writeAndFlush(new RongIMLib.PingReqMessage()); var count = 0; var checkTimeout = setInterval(function () { if (!RongIMLib.RongIMClient._memoryStore.isFirstPingMsg) { clearInterval(checkTimeout); callback.onSuccess(); } else { if (count > 15) { clearInterval(checkTimeout); callback.onError(); } } count++; }, 100); }; Client.prototype.keepLive = function () { if (this.heartbeat > 0) { clearInterval(this.heartbeat); } var me = this; me.heartbeat = setInterval(function () { me.resumeTimer(); me.channel.writeAndFlush(new RongIMLib.PingReqMessage()); }, 30000); if (me.pullMsgHearbeat > 0) { clearInterval(me.pullMsgHearbeat); } me.pullMsgHearbeat = setInterval(function () { me.syncTime(true, undefined, undefined, false); }, 180000); }; Client.prototype.clearHeartbeat = function () { clearInterval(this.heartbeat); this.heartbeat = 0; this.pauseTimer(); clearInterval(this.pullMsgHearbeat); this.pullMsgHearbeat = 0; }; Client.prototype.publishMessage = function (_topic, _data, _targetId, _callback, _msg, option) { option = option || {}; var isNoAck = option.isNoAck; var hasCallback = !!_callback; var msgId = RongIMLib.MessageIdHandler.messageIdPlus(this.channel.reconnect); if (!msgId) { return; } var msg = new RongIMLib.PublishMessage(_topic, _data, _targetId); msg.setMessageId(msgId); if (isNoAck) { msg.setQos(Qos.AT_LEAST_ONCE); _callback.onSuccess(msg); } else if (hasCallback) { msg.setQos(Qos.AT_LEAST_ONCE); this.handler.putCallback(new RongIMLib.PublishCallback(_callback.onSuccess, _callback.onError), msg.getMessageId(), _msg); } else { msg.setQos(Qos.AT_MOST_ONCE); } this.channel.writeAndFlush(msg); }; Client.prototype.queryMessage = function (_topic, _data, _targetId, _qos, _callback, pbtype) { if (_topic == "userInf") { if (Client.userInfoMapping[_targetId]) { _callback.onSuccess(Client.userInfoMapping[_targetId]); return; } } var msgId = RongIMLib.MessageIdHandler.messageIdPlus(this.channel.reconnect); if (!msgId) { return; } var msg = new RongIMLib.QueryMessage(_topic, _data, _targetId); msg.setMessageId(msgId); msg.setQos(_qos); this.handler.putCallback(new RongIMLib.QueryCallback(_callback.onSuccess, _callback.onError), msg.getMessageId(), pbtype); this.channel.writeAndFlush(msg); }; Client.prototype.invoke = function (isPullMsg, chrmId, offlineMsg) { var time, modules, str, me = this, target, temp = this.SyncTimeQueue.shift(); if (temp == undefined) { return; } this.SyncTimeQueue.state = "pending"; var localSyncTime = RongIMLib.SyncTimeUtil.get(); var sentBoxTime = localSyncTime.sent; var isPullChatroom = temp.type === 2; if (temp.type != 2) { //普通消息 time = localSyncTime.received; modules = new RongIMLib.RongIMClient.Protobuf.SyncRequestMsg(); modules.setIspolling(false); str = "pullMsg"; target = this.userId; modules.setSendBoxSyncTime(sentBoxTime); } else { //聊天室消息 target = temp.chrmId || me.chatroomId; time = RongIMLib.RongIMClient._memoryStore.lastReadTime.get(target + Bridge._client.userId + "CST") || 0; modules = new RongIMLib.RongIMClient.Protobuf.ChrmPullMsg(); modules.setCount(0); str = "chrmPull"; if (!target) { var errorMsg = "syncTime:Received messages of chatroom but was not init"; RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.L_CHRM_PULL_E, level: RongIMLib.LoggerLevel.E, type: RongIMLib.LoggerType.IM, content: { msg: errorMsg } }); throw new Error(errorMsg); } } //判断服务器给的时间是否消息本地存储的时间,小于的话不执行拉取操作,进行一下步队列操作 if (temp.pulltime <= time) { this.SyncTimeQueue.state = "complete"; this.invoke(isPullMsg, target, offlineMsg); return; } if (isPullMsg && 'setIsPullSend' in modules) { modules.setIsPullSend(true); } modules.setSyncTime(time); //发送queryMessage请求 this.queryMessage(str, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), target, Qos.AT_LEAST_ONCE, { onSuccess: function (collection) { var sync = RongIMLib.MessageUtil.int64ToTimestamp(collection.syncTime), symbol = target; //把返回时间戳存入本地,普通消息key为userid,聊天室消息key为userid+'CST';value都为服务器返回的时间戳 var isChrmPull = str == 'chrmPull'; if (isChrmPull) { symbol += Bridge._client.userId + "CST"; RongIMLib.RongIMClient._memoryStore.lastReadTime.set(symbol, sync); } else { var storage = RongIMLib.RongIMClient._storageProvider; if (sync > storage.getItem(symbol)) { storage.setItem(symbol, sync); } } //把拉取到的消息逐条传给消息监听器 var list = collection.list; var isPullFinished = collection.finished; // chrmPull 没有 finished 字段,自动设置为拉取完成 if (isChrmPull) { isPullFinished = true; } // 兼容长轮训 finished 为空的造成丢消息情况 if (typeof isPullFinished == 'undefined') { isPullFinished = true; } RongIMLib.RongIMClient._memoryStore.isPullFinished = isPullFinished; var connectAckTime = RongIMLib.RongIMClient._memoryStore.connectAckTime; var len = list.length; for (var i = 0, count = len; i < len; i++) { count -= 1; var message = list[i]; var sentTime = RongIMLib.MessageUtil.int64ToTimestamp(message.dataTime); var isSender = message.direction == RongIMLib.MessageDirection.SEND; var compareTime = isSender ? sentBoxTime : time; if (sentTime > compareTime || isPullChatroom) { var isSyncMessage = false; var isOffLineMessage = sentTime < connectAckTime; try { Bridge._client.handler.onReceived(message, undefined, isOffLineMessage, count, isSyncMessage, isPullFinished); } catch (e) { console.log(e); } } } if (len <= 200 && str == 'pullMsg') { var Conversation = RongIMLib.RongIMClient._dataAccessProvider.Conversation; var conversationList = RongIMLib.RongIMClient._memoryStore.conversationList; Conversation._notify(conversationList); } me.SyncTimeQueue.state = "complete"; me.invoke(isPullMsg, target, offlineMsg); }, onError: function (error) { me.SyncTimeQueue.state = "complete"; me.invoke(isPullMsg, target, offlineMsg); RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.L_QUERY_MSG_E, level: RongIMLib.LoggerLevel.E, type: RongIMLib.LoggerType.IM, content: { action: 'invoke -> queryMessage', error: error } }); } }, "DownStreamMessages"); }; Client.prototype.syncTime = function (_type, pullTime, chrmId, offlineMsg) { this.SyncTimeQueue.push({ type: _type, pulltime: pullTime, chrmId: chrmId }); //如果队列中只有一个成员并且状态已经完成就执行invoke方法 if (this.SyncTimeQueue.length == 1 && this.SyncTimeQueue.state == "complete") { this.invoke(!_type, chrmId, offlineMsg); } }; Client.prototype.__init = function (f) { this.handler = new MessageHandler(this); //设置连接回调 this.handler.setConnectCallback(RongIMLib.RongIMClient._memoryStore.callback); this.channel = new Channel(f, this); }; Client.userInfoMapping = {}; return Client; })(); RongIMLib.Client = Client; //连接类,实现imclient与connect_client的连接 var Bridge = (function () { function Bridge() { } Bridge.getInstance = function () { return new Bridge(); }; //连接服务器 Bridge.prototype.connect = function (appKey, token, callback) { if (!RongIMLib.RongIMClient.Protobuf) { return; } Bridge._client = new RongIMLib.Navigation().connect(appKey, token, callback); return Bridge._client; }; Bridge.prototype.setListener = function () { Channel._ConnectionStatusListener = { onChanged: function (status) { RongIMLib.RongUtil.forEach(RongIMLib.RongIMClient.statusListeners, function (watch) { RongIMLib.RongUtil.isFunction(watch) && watch(status); }); if (status == RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE) { RongIMLib.RongIMClient._memoryStore.networkUnavailable = true; } } }; Channel._ReceiveMessageListener = { onReceived: function (msg, count, hasMore) { RongIMLib.RongUtil.forEach(RongIMLib.RongIMClient.messageListeners, function (watch) { RongIMLib.RongUtil.isFunction(watch) && watch(msg, count, hasMore); }); } }; }; Bridge.prototype.reconnect = function (callabck) { Bridge._client.channel.reconnect(callabck); }; Bridge.prototype.disconnect = function () { Bridge._client.channel.disconnect(2); }; //执行queryMessage请求 Bridge.prototype.queryMsg = function (topic, content, targetId, callback, pbname) { if (typeof topic != "string") { topic = _topic[topic]; } Bridge._client.queryMessage(topic, content, targetId, Qos.AT_MOST_ONCE, callback, pbname); }; //发送消息 执行publishMessage 请求 Bridge.prototype.pubMsg = function (topic, content, targetId, callback, msg, methodType, params) { params = params || {}; if (typeof methodType == 'number') { if (methodType == RongIMLib.MethodType.CUSTOMER_SERVICE) { Bridge._client.publishMessage("pcuMsgP", content, targetId, callback, msg); } else if (methodType == RongIMLib.MethodType.RECALL) { Bridge._client.publishMessage("recallMsg", content, targetId, callback, msg); } } else { var isStatusMessage = params.isStatus; var statusTopic = RongIMLib.StatusTopic[topic]; if (isStatusMessage && statusTopic) { Bridge._client.publishMessage(statusTopic, content, targetId, callback, msg, { isNoAck: true }); } else { Bridge._client.publishMessage(_topic[10][topic], content, targetId, callback, msg); // 非状态消息, 逻辑不变 } } }; return Bridge; })(); RongIMLib.Bridge = Bridge; var MessageHandler = (function () { function MessageHandler(client) { this.map = {}; this.connectCallback = null; if (!Channel._ReceiveMessageListener) { throw new Error("please set onReceiveMessageListener"); } this._onReceived = Channel._ReceiveMessageListener.onReceived; this._client = client; this.syncMsgMap = new Object; } //把对象推入回调对象队列中,并启动定时器 MessageHandler.prototype.putCallback = function (callbackObj, _publishMessageId, _msg) { var item = { Callback: callbackObj, Message: _msg }; item.Callback.resumeTimer(); this.map[_publishMessageId] = item; }; //设置连接回调对象,启动定时器 MessageHandler.prototype.setConnectCallback = function (_connectCallback) { if (_connectCallback) { this.connectCallback = new RongIMLib.ConnectAck(_connectCallback.onSuccess, _connectCallback.onError, this._client); } }; MessageHandler.prototype.handleChrmKVPullMsg = function (msg) { try { var pbtype = 'NotifyMsg'; var data = RongIMLib.CallbackMapping.getInstance().mapping(RongIMLib.RongIMClient.Protobuf[pbtype].decode(msg.data), pbtype); var timestamp = RongIMLib.MessageUtil.int64ToTimestamp(data.time); if (data.type === 2) { RongIMLib.ChrmKVHandler.pull(data.chrmId, timestamp); } else if (data.type === 3) { RongIMLib.RongIMClient._dataAccessProvider.conversationStatusManager.pull({ time: timestamp }); } } catch (e) { } }; MessageHandler.prototype.onReceived = function (msg, pubAckItem, offlineMsg, leftCount, isSync) { if (!msg) { return; } //实体对象 var entity, //解析完成的消息对象 message, //会话对象 con, // 是否为直发消息 isStraightMsg = false; if (msg._name != "PublishMessage") { entity = msg; RongIMLib.RongIMClient._storageProvider.setItem(this._client.userId, RongIMLib.MessageUtil.int64ToTimestamp(entity.dataTime)); } else { if (msg.getTopic() == "s_ntf") { entity = RongIMLib.RongIMClient.Protobuf.NotifyMsg.decode(msg.getData()); this._client.syncTime(entity.type, RongIMLib.MessageUtil.int64ToTimestamp(entity.time), entity.chrmId); return; } else if (msg.getTopic() == "s_msg") { isStraightMsg = true; entity = RongIMLib.RongIMClient.Protobuf.DownStreamMessage.decode(msg.getData()); var timestamp = RongIMLib.MessageUtil.int64ToTimestamp(entity.dataTime); RongIMLib.RongIMClient._storageProvider.setItem(this._client.userId, timestamp); RongIMLib.RongIMClient._memoryStore.lastReadTime.get(this._client.userId, timestamp); } else if (msg.getTopic() == "s_stat") { entity = RongIMLib.RongIMClient.Protobuf.GetUserStatusOutput.decode(msg.getData()); entity = RongIMLib.RongInnerTools.convertUserStatus(entity); RongIMLib.RongIMClient.userStatusObserver.notify({ key: entity.userId, entity: entity }); return; } else if (msg.getTopic() === 's_cmd') { this.handleChrmKVPullMsg(msg); return; } else { if (Bridge._client.sdkVer && Bridge._client.sdkVer == "1.0.0") { return; } try { entity = RongIMLib.RongIMClient.Protobuf.UpStreamMessage.decode(msg.getData()); } catch (e) { RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.L_DECODE_MSG_E, level: RongIMLib.LoggerLevel.E, type: RongIMLib.LoggerType.IM, content: { stack: e, msg: 'MessageHandler -> onReceived' } }); return; } var tmpTopic = msg.getTopic(); var tmpType = tmpTopic.substr(0, 2); if (tmpType == "pp") { entity.type = 1; } else if (tmpType == "pd") { entity.type = 2; } else if (tmpType == "pg") { entity.type = 3; } else if (tmpType == "ch") { entity.type = 4; } else if (tmpType == "pc") { entity.type = 5; } //复用字段,targetId 以此为准 entity.groupId = msg.getTargetId(); entity.fromUserId = this._client.userId; entity.dataTime = Date.parse(new Date().toString()); } if (!entity) { return; } } var isPullFinished = RongIMLib.RongIMClient._memoryStore.isPullFinished; // PullMsg 没有拉取完成,抛弃所有直发在线消息,抛弃的消息会在 PullMsg 中返回 if (!isPullFinished && !offlineMsg && isStraightMsg) { return; } //解析实体对象为消息对象。 message = RongIMLib.MessageUtil.messageParser(entity, this._onReceived, offlineMsg); var isRTCMessage = message.conversationType == 12; if (isRTCMessage) { RongIMLib.RongIMClient.RTCListener(message); RongIMLib.RongIMClient.RTCInnerListener(message); RongIMLib.RongIMClient.RTCSignalLisener(message); return; } var isRecall = (msg.getTopic && msg.getTopic() == "recallMsg"); if (isRecall) { var content = message.content; message.conversationType = content.conversationType; message.targetId = content.targetId; message.messageId = null; } if (pubAckItem) { message.messageUId = pubAckItem.getMessageUId(); message.sentTime = pubAckItem.getTimestamp(); RongIMLib.RongIMClient._storageProvider.setItem(this._client.userId, message.sentTime); } if (message === null) { return; } var isChatroomMessage = message.conversationType == RongIMLib.ConversationType.CHATROOM; if (!isChatroomMessage) { var msgTag = RongIMLib.RongIMClient.MessageParams[message.messageType].msgTag.getMessageTag(); if (msgTag >= 0) { RongIMLib.SyncTimeUtil.set(message); } var isSend = (message.messageDirection == RongIMLib.MessageDirection.SEND); if (isSend) { var storageProvider = RongIMLib.RongIMClient._storageProvider; var userId = RongIMLib.Bridge._client.userId; var lastSentTime = storageProvider.getItem('last_sentTime_' + userId) || 0; if (message.sentTime <= lastSentTime && !isSync) { return; } } } // 设置会话时间戳并且判断是否传递 message 发送消息未处理会话时间戳 // key:'converST_' + 当前用户 + conversationType + targetId // RongIMClient._storageProvider.setItem('converST_' + Bridge._client.userId + message.conversationType + message.targetId, message.sentTime); // var isPersited = (RongIMClient.MessageParams[message.messageType].msgTag.getMessageTag() > 0); var msgTag = RongIMLib.RongIMClient.MessageParams[message.messageType].msgTag.getMessageTag(); var isPersited = msgTag === 3 || msgTag === 2; if (isPersited) { con = RongIMLib.RongIMClient._dataAccessProvider.getConversation(message.conversationType, message.targetId, { onSuccess: function () { }, onError: function () { } }); if (!con) { con = RongIMLib.RongIMClient.getInstance().createConversation(message.conversationType, message.targetId, ""); } if (message.messageDirection == RongIMLib.MessageDirection.RECEIVE && (entity.status & 64) == 64) { var mentioneds = RongIMLib.RongIMClient._storageProvider.getItem("mentioneds_" + Bridge._client.userId + '_' + message.conversationType + '_' + message.targetId); var key = message.conversationType + '_' + message.targetId, info = {}; if (message.content && message.content.mentionedInfo) { info[key] = { uid: message.messageUId, time: message.sentTime, mentionedInfo: message.content.mentionedInfo }; RongIMLib.RongIMClient._storageProvider.setItem("mentioneds_" + Bridge._client.userId + '_' + message.conversationType + '_' + message.targetId, JSON.stringify(info)); mentioneds = JSON.stringify(info); } if (mentioneds) { var info = JSON.parse(mentioneds); con.mentionedMsg = info[key]; } } var isReceiver = message.messageDirection == RongIMLib.MessageDirection.RECEIVE; if (isReceiver && message.senderUserId != Bridge._client.userId) { con.unreadMessageCount = con.unreadMessageCount + 1; if (RongIMLib.RongUtil.supportLocalStorage()) { // var originUnreadCount = RongIMClient._storageProvider.getItem("cu" + Bridge._client.userId + con.conversationType + con.targetId); // 与本地存储会话合并 // var newUnreadCount = Number(originUnreadCount) + 1; // RongIMClient._storageProvider.setItem("cu" + Bridge._client.userId + con.conversationType + message.targetId, newUnreadCount); var newUnreadCount = RongIMLib.UnreadCountHandler.add(con.conversationType, message.targetId, 1, message.sentTime); con.unreadMessageCount = newUnreadCount; } } var receivedTime = new Date().getTime(); con.receivedTime = RongIMLib.MessageUtil.getCheckedTime(receivedTime); con.receivedStatus = message.receivedStatus; con.senderUserId = message.sendUserId; con.notificationStatus = RongIMLib.ConversationNotificationStatus.DO_NOT_DISTURB; con.isTop = false; con.latestMessageId = message.messageId; con.latestMessage = message; con.sentTime = message.sentTime; RongIMLib.RongIMClient._dataAccessProvider.addConversation(con, { onSuccess: function (data) { if (!offlineMsg) { var Conversation_1 = RongIMLib.RongIMClient._dataAccessProvider.Conversation; var conversationList = RongIMLib.RongIMClient._memoryStore.conversationList; Conversation_1._notify(conversationList); } }, onError: function () { } }); } if (message.conversationType == RongIMLib.ConversationType.CUSTOMER_SERVICE && (message.messageType == "ChangeModeResponseMessage" || message.messageType == "SuspendMessage" || message.messageType == "HandShakeResponseMessage" || message.messageType == "TerminateMessage" || message.messageType == "CustomerStatusUpdateMessage" || message.messageType == "TextMessage" || message.messageType == "InformationNotificationMessage")) { if (!RongIMLib.RongIMClient._memoryStore.custStore["isInit"]) { return; } } if (message.conversationType == RongIMLib.ConversationType.CUSTOMER_SERVICE && message.messageType != "HandShakeResponseMessage") { if (!RongIMLib.RongIMClient._memoryStore.custStore[message.targetId]) { return; } if (message.messageType == "TerminateMessage") { if (RongIMLib.RongIMClient._memoryStore.custStore[message.targetId].sid != message.content.sid) { return; } } } if (message.messageType === RongIMLib.RongIMClient.MessageType["HandShakeResponseMessage"]) { var session = message.content.data; RongIMLib.RongIMClient._memoryStore.custStore[message.targetId] = session; if (session.serviceType == RongIMLib.CustomerType.ONLY_HUMAN || session.serviceType == RongIMLib.CustomerType.HUMAN_FIRST) { if (session.notAutoCha == "1") { RongIMLib.RongIMClient.getInstance().switchToHumanMode(message.targetId, { onSuccess: function () { }, onError: function () { } }); } } } if (RongIMLib.LoggerUtil.isLogCmdMsg(message)) { RongIMLib.Logger.reportMNLog(message.content); return; } var d = new Date(), m = d.getMonth() + 1, date = d.getFullYear() + '/' + (m.toString().length == 1 ? '0' + m : m) + '/' + d.getDate(); //new Date(date).getTime() - message.sentTime < 1 逻辑判断 超过 1 天未收的 ReadReceiptRequestMessage 离线消息自动忽略。 var dealtime = new Date(date).getTime() - message.sentTime < 0; if (RongIMLib.RongUtil.supportLocalStorage() && message.messageType === RongIMLib.RongIMClient.MessageType["ReadReceiptRequestMessage"] && dealtime && message.messageDirection == RongIMLib.MessageDirection.SEND) { var sentkey = Bridge._client.userId + message.content.messageUId + "SENT"; RongIMLib.RongIMClient._storageProvider.setItem(sentkey, JSON.stringify({ count: 0, dealtime: message.sentTime, userIds: {} })); } else if (RongIMLib.RongUtil.supportLocalStorage() && message.messageType === RongIMLib.RongIMClient.MessageType["ReadReceiptRequestMessage"] && dealtime) { var reckey = Bridge._client.userId + message.conversationType + message.targetId + 'RECEIVED', recData = JSON.parse(RongIMLib.RongIMClient._storageProvider.getItem(reckey)); if (recData) { if (message.senderUserId in recData) { if (recData[message.senderUserId].uIds && recData[message.senderUserId].uIds && recData[message.senderUserId].uIds.indexOf(message.content.messageUId) == -1) { recData[message.senderUserId].uIds.push(message.content.messageUId); recData[message.senderUserId].dealtime = message.sentTime; recData[message.senderUserId].isResponse = false; RongIMLib.RongIMClient._storageProvider.setItem(reckey, JSON.stringify(recData)); } else { return; } } else { var objSon = { uIds: [message.content.messageUId], dealtime: message.sentTime, isResponse: false }; recData[message.senderUserId] = objSon; RongIMLib.RongIMClient._storageProvider.setItem(reckey, JSON.stringify(recData)); } } else { var obj = {}; obj[message.senderUserId] = { uIds: [message.content.messageUId], dealtime: message.sentTime, isResponse: false }; RongIMLib.RongIMClient._storageProvider.setItem(reckey, JSON.stringify(obj)); } } if (RongIMLib.RongUtil.supportLocalStorage() && message.messageType === RongIMLib.RongIMClient.MessageType["ReadReceiptResponseMessage"] && dealtime) { var receiptResponseMsg = message.content; if (RongIMLib.RongUtil.isUndefined(receiptResponseMsg) || RongIMLib.RongUtil.isNull(receiptResponseMsg)) { receiptResponseMsg = new RongIMLib.ReadReceiptResponseMessage({}); } var receiptMessageDic = receiptResponseMsg.receiptMessageDic || {}, uIds = receiptMessageDic[Bridge._client.userId], sentkey = "", sentObj; message.receiptResponse || (message.receiptResponse = {}); if (uIds) { var cbuIds = []; for (var i = 0, len = uIds.length; i < len; i++) { sentkey = Bridge._client.userId + uIds[i] + "SENT"; sentObj = JSON.parse(RongIMLib.RongIMClient._storageProvider.getItem(sentkey)); if (sentObj && !(message.senderUserId in sentObj.userIds)) { cbuIds.push(uIds[i]); sentObj.count += 1; sentObj.userIds[message.senderUserId] = message.sentTime; message.receiptResponse[uIds[i]] = sentObj.count; RongIMLib.RongIMClient._storageProvider.setItem(sentkey, JSON.stringify(sentObj)); } } receiptResponseMsg.receiptMessageDic[Bridge._client.userId] = cbuIds; message.content = receiptResponseMsg; } } var that = this; if (RongIMLib.RongIMClient._voipProvider && ['AcceptMessage', 'RingingMessage', 'HungupMessage', 'InviteMessage', 'MediaModifyMessage', 'MemberModifyMessage'].indexOf(message.messageType) > -1) { setTimeout(function () { RongIMLib.RongIMClient._voipProvider.onReceived(message); }); } else { var count = leftCount || 0; var hasMore = !isPullFinished; try { that._onReceived(message, count, hasMore); } catch (e) { console.error(e); } } }; MessageHandler.prototype.handleMessage = function (msg) { if (!msg) { return; } if (msg && RongIMLib.RongUtil.isObject(msg) && msg.timestamp) { RongIMLib.MessageUtil.setDeltaTime(msg.timestamp); } switch (msg._name) { case "ConnAckMessage": Bridge._client.handler.connectCallback.process(msg.getStatus(), msg.getUserId(), msg.getTimestamp()); break; case "PublishMessage": if (!msg.getSyncMsg() && msg.getQos() != 0) { Bridge._client.channel.writeAndFlush(new RongIMLib.PubAckMessage(msg.getMessageId())); } // TODO && -> if (msg.getSyncMsg() && !RongIMLib.RongIMClient._memoryStore.depend.isPolling) { Bridge._client.handler.syncMsgMap[msg.getMessageId()] = msg; } else { //如果是PublishMessage就把该对象给onReceived方法执行处理 Bridge._client.handler.onReceived(msg); } break; case "QueryAckMessage": if (msg.getQos() != 0) { Bridge._client.channel.writeAndFlush(new RongIMLib.QueryConMessage(msg.getMessageId())); } var temp = Bridge._client.handler.map[msg.getMessageId()]; if (temp) { //执行回调操作 temp.Callback.process(msg.getStatus(), msg.getData(), msg.getDate(), temp.Message); delete Bridge._client.handler.map[msg.getMessageId()]; } break; case "PubAckMessage": var item = Bridge._client.handler.map[msg.getMessageId()]; if (item) { item.Callback.process(msg.getStatus() || 0, msg.getMessageUId(), msg.getTimestamp(), item.Message, msg.getMessageId()); delete Bridge._client.handler.map[msg.getMessageId()]; } else { var userId = RongIMLib.Bridge._client.userId; RongIMLib.RongIMClient._storageProvider.setItem('last_sentTime_' + userId, msg.timestamp); Bridge._client.handler.onReceived(Bridge._client.handler.syncMsgMap[msg.messageId], msg, null, null, true); delete Bridge._client.handler.syncMsgMap[msg.getMessageId()]; } break; case "PingRespMessage": if (RongIMLib.RongIMClient._memoryStore.isFirstPingMsg) { RongIMLib.RongIMClient._memoryStore.isFirstPingMsg = false; } else { Bridge._client.pauseTimer(); } break; case "DisconnectMessage": Bridge._client.channel.disconnect(msg.getStatus()); break; default: RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.L_CATCH_UNKNOWN_MSG_E, level: RongIMLib.LoggerLevel.E, type: RongIMLib.LoggerType.IM, content: { action: 'MessageHandler -> handleMessage', msg: msg } }); } }; return MessageHandler; })(); RongIMLib.MessageHandler = MessageHandler; })(RongIMLib || (RongIMLib = {})); var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; /// var RongIMLib; (function (RongIMLib) { var MessageCallback = (function () { function MessageCallback(error) { this.timeout = null; this.onError = null; if (error && typeof error == "number") { this.timeoutMillis = error; } else { this.timeoutMillis = 30000; this.onError = error; } } MessageCallback.prototype.resumeTimer = function () { var me = this; if (this.timeoutMillis > 0 && !this.timeout) { this.timeout = setTimeout(function () { me.readTimeOut(true); }, this.timeoutMillis); } }; MessageCallback.prototype.pauseTimer = function () { if (this.timeout) { clearTimeout(this.timeout); this.timeout = null; } }; MessageCallback.prototype.readTimeOut = function (isTimeout) { if (isTimeout && this.onError) { this.onError(RongIMLib.ErrorCode.TIMEOUT); } else { this.pauseTimer(); } }; return MessageCallback; })(); RongIMLib.MessageCallback = MessageCallback; var CallbackMapping = (function () { function CallbackMapping() { this.publicServiceList = []; } CallbackMapping.getInstance = function () { return new CallbackMapping(); }; CallbackMapping.prototype.pottingProfile = function (item) { var temp; this.profile = new RongIMLib.PublicServiceProfile(); temp = JSON.parse(item.extra); this.profile.isGlobal = temp.isGlobal; this.profile.introduction = temp.introduction; this.profile.menu = temp.menu; this.profile.hasFollowed = temp.follow; this.profile.publicServiceId = item.mpid; this.profile.name = item.name; this.profile.portraitUri = item.portraitUrl; this.profile.conversationType = item.type == "mc" ? RongIMLib.ConversationType.APP_PUBLIC_SERVICE : RongIMLib.ConversationType.PUBLIC_SERVICE; this.publicServiceList.push(this.profile); }; CallbackMapping.prototype.mapping = function (entity, tag) { switch (tag) { case "GetUserInfoOutput": var userInfo = new RongIMLib.UserInfo(entity.userId, entity.userName, entity.userPortrait); return userInfo; case "GetQNupTokenOutput": return { deadline: RongIMLib.MessageUtil.int64ToTimestamp(entity.deadline), token: entity.token, bosToken: entity.bosToken, bosDate: entity.bosDate, path: entity.path }; case "GetQNdownloadUrlOutput": return { downloadUrl: entity.downloadUrl }; case "CreateDiscussionOutput": return entity.id; case "ChannelInfoOutput": var disInfo = new RongIMLib.Discussion(); disInfo.creatorId = entity.adminUserId; disInfo.id = entity.channelId; disInfo.memberIdList = entity.firstTenUserIds; disInfo.name = entity.channelName; disInfo.isOpen = entity.openStatus; return disInfo; case "GroupHashOutput": return entity.result; case "QueryBlackListOutput": return entity.userIds; case "SearchMpOutput": case "PullMpOutput": if (entity.info) { var self = this; Array.forEach(entity.info, function (item) { setTimeout(function () { self.pottingProfile(item); }, 100); }); } return this.publicServiceList; default: return entity; } }; return CallbackMapping; })(); RongIMLib.CallbackMapping = CallbackMapping; var PublishCallback = (function (_super) { __extends(PublishCallback, _super); function PublishCallback(_cb, _timeout) { _super.call(this, _timeout); this._cb = _cb; this._timeout = _timeout; } PublishCallback.prototype.process = function (_status, messageUId, timestamp, _msg, messageId) { this.readTimeOut(); if (_status == 0) { if (_msg) { _msg.setSentStatus = _status; } var isPullFinished = RongIMLib.RongIMClient._memoryStore.isPullFinished; if (isPullFinished) { var userId = RongIMLib.Bridge._client.userId; var stroageProvider = RongIMLib.RongIMClient._storageProvider; stroageProvider.setItem('last_sentTime_' + userId, timestamp); RongIMLib.SyncTimeUtil.set({ messageDirection: RongIMLib.MessageDirection.SEND, sentTime: timestamp }); } this._cb({ messageUId: messageUId, timestamp: timestamp, messageId: messageId }); } else { this._timeout(_status, { messageUId: messageUId, sentTime: timestamp }); } }; PublishCallback.prototype.readTimeOut = function (x) { MessageCallback.prototype.readTimeOut.call(this, x); }; return PublishCallback; })(MessageCallback); RongIMLib.PublishCallback = PublishCallback; var QueryCallback = (function (_super) { __extends(QueryCallback, _super); function QueryCallback(_cb, _timeout) { _super.call(this, _timeout); this._cb = _cb; this._timeout = _timeout; } QueryCallback.prototype.process = function (status, data, serverTime, pbtype) { this.readTimeOut(); if (pbtype && data && status == 0) { try { data = CallbackMapping.getInstance().mapping(RongIMLib.RongIMClient.Protobuf[pbtype].decode(data), pbtype); } catch (e) { this._timeout(RongIMLib.ErrorCode.UNKNOWN); RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.L_DECODE_QUERY_DATA_E, level: RongIMLib.LoggerLevel.E, type: RongIMLib.LoggerType.IM, content: { stack: e, msg: 'QueryCallback -> process' } }); return; } if ("GetUserInfoOutput" == pbtype) { //pb类型为GetUserInfoOutput的话就把data放入userinfo缓存队列 RongIMLib.Client.userInfoMapping[data.userId] = data; } this._cb(data); } else { status > 0 ? this._timeout(status) : this._cb(status); } }; QueryCallback.prototype.readTimeOut = function (x) { MessageCallback.prototype.readTimeOut.call(this, x); }; return QueryCallback; })(MessageCallback); RongIMLib.QueryCallback = QueryCallback; var ConnectAck = (function (_super) { __extends(ConnectAck, _super); function ConnectAck(_cb, _timeout, client) { _super.call(this, _timeout); this._client = client; this._cb = _cb; this._timeout = _timeout; } ConnectAck.prototype.process = function (status, userId, timestamp) { this.readTimeOut(); if (status == 0) { this._client.userId = userId; var self = this; if (!RongIMLib.RongIMClient._memoryStore.depend.isPolling && RongIMLib.RongIMClient._memoryStore.isFirstPingMsg) { RongIMLib.Bridge._client.checkSocket({ onSuccess: function () { if (!RongIMLib.RongIMClient.isNotPullMsg) { self._client.syncTime(undefined, undefined, undefined, true); } }, onError: function () { RongIMLib.RongIMClient._memoryStore.isFirstPingMsg = false; RongIMLib.RongIMClient.getInstance().disconnect(); RongIMLib.RongIMClient.connect(RongIMLib.RongIMClient._memoryStore.token, RongIMLib.RongIMClient._memoryStore.callback); } }); } else { if (!RongIMLib.RongIMClient.isNotPullMsg) { self._client.syncTime(undefined, undefined, undefined, true); } } RongIMLib.Bridge._client.channel.socket.fire("StatusChanged", 0); if (this._client.reconnectObj.onSuccess) { this._client.reconnectObj.onSuccess(userId); delete this._client.reconnectObj.onSuccess; } else { var me = this; me._cb(userId); // setTimeout(function() { me._cb(userId); }, 500); var depend = RongIMLib.RongIMClient._memoryStore.depend; var maxConversationCount = depend.maxConversationCount; var isNotifyConversationList = depend.isNotifyConversationList; isNotifyConversationList && RongIMLib.RongIMClient._dataAccessProvider.getRemoteConversationList({ onSuccess: function (conversationList) { var Conversation = RongIMLib.RongIMClient._dataAccessProvider.Conversation; Conversation._notify(conversationList); }, onError: function (code) { console.log('内部获取列表失败: %d', code); } }, null, maxConversationCount); } RongIMLib.RongIMClient._memoryStore.connectAckTime = timestamp; RongIMLib.MessageUtil.setDeltaTime(timestamp); } else if (status == 6) { RongIMLib.RongIMClient.getInstance().disconnect(); //重定向 连错 CMP var me = this; var _client = me._client; var appId = _client.appId, token = _client.token; new RongIMLib.Navigation().requestNavi(token, appId, function () { _client.clearHeartbeat(); var newClient = new RongIMLib.Client(token, appId); RongIMLib.Bridge._client = newClient; newClient.__init(function () { RongIMLib.Transportations._TransportType == "websocket" && newClient.keepLive(); }); }, me._timeout, false); } else { RongIMLib.Bridge._client.channel.socket.socket._status = status; if (this._client.reconnectObj.onError) { this._client.reconnectObj.onError(status); delete this._client.reconnectObj.onError; } else { this._timeout(status); } } }; ConnectAck.prototype.readTimeOut = function (x) { MessageCallback.prototype.readTimeOut.call(this, x); }; return ConnectAck; })(MessageCallback); RongIMLib.ConnectAck = ConnectAck; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var Navigation = (function () { function Navigation() { } Navigation.clear = function () { var storage = RongIMLib.RongIMClient._storageProvider; storage.removeItem('rc_uid'); storage.removeItem('serverIndex'); storage.removeItem('rongSDK'); }; Navigation.prototype.getNaviSuccess = function (result, naviUrl) { var storage = RongIMLib.RongIMClient._storageProvider; storage.setItem('fullnavi', JSON.stringify(result)); var successNaviProtocol = RongIMLib.RongUtil.getUrlProtocol(naviUrl); // navi 请求成功后, 根据 navi 协议头, 设置连接 websocket 协议头 RongIMLib.RongIMClient.setProtocol(successNaviProtocol); storage.setItem(Navigation.StoreProtocolKey, successNaviProtocol); var server = result.server; if (server) { server += ','; } var backupServer = result.backupServer || ''; var tpl = '{server}{backupServer}'; var servers = RongIMLib.RongUtil.tplEngine(tpl, { server: server, backupServer: backupServer }); servers = servers.split(','); storage.setItem('servers', JSON.stringify(servers)); var token = RongIMLib.RongIMClient._memoryStore.token; var uid = RongIMLib.InnerUtil.getUId(token); storage.setItem('rc_uid', uid); var userId = result.userId; storage.setItem('current_user', userId); storage.setItem('navi_time', RongIMLib.RongUtil.getTimestamp()); if (result.voipCallInfo) { var callInfo = JSON.parse(result.voipCallInfo); RongIMLib.RongIMClient._memoryStore.voipStategy = callInfo.strategy; storage.setItem("voipStrategy", callInfo.strategy); } var uploadDomains = { qiniu: result.uploadServer || '', bos: result.bosAddr || '' }; storage.setItem('upload_domains', JSON.stringify(uploadDomains)); //替换本地存储的导航信息 var openMp = result.openMp; storage.setItem('openMp' + uid, openMp); RongIMLib.RongIMClient._memoryStore.depend.openMp = openMp; }; ; Navigation.prototype.connect = function (appId, token, callback) { var oldAppId = RongIMLib.RongIMClient._storageProvider.getItem("appId"); //如果appid和本地存储的不一样,清空所有本地存储数据 if (oldAppId && oldAppId != appId) { RongIMLib.RongIMClient._storageProvider.clearItem(); RongIMLib.RongIMClient._storageProvider.setItem("appId", appId); } if (!oldAppId) { RongIMLib.RongIMClient._storageProvider.setItem("appId", appId); } var client = new RongIMLib.Client(token, appId); this.requestNavi(token, appId, function () { client.connect(callback); }, callback.onError, true); return client; }; Navigation.prototype.requestNavi = function (token, appId, _onsuccess, _onerror, unignore) { if (unignore) { //根据token生成MD5截取8-16下标的数据与本地存储的导航信息进行比对 //如果信息和上次的通道类型都一样,不执行navi请求,用本地存储的导航信息连接服务器 var uId = md5(token).slice(8, 16); var storage = RongIMLib.RongIMClient._storageProvider; var transportType = storage.getItem("rongSDK"); var isSameType = (RongIMLib.Transportations._TransportType == transportType); var _old = storage.getItem('rc_uid'); var isSameUser = (_old == uId); var servers = storage.getItem('servers'); var hasServers = (typeof servers == 'string'); var currentTime = RongIMLib.RongUtil.getTimestamp(); var naviSavedTime = Number(storage.getItem('navi_time')) || 0; var isNotExpired = currentTime - naviSavedTime < RongIMLib.RongIMClient.NavExpiredTime; if (isSameUser && isSameType && hasServers && RongIMLib.RongUtil.hasValidWsUrl(servers) && isNotExpired) { RongIMLib.RongIMClient._memoryStore.voipStategy = storage.getItem("voipStrategy"); var openMp = storage.getItem('openMp' + uId); RongIMLib.RongIMClient._memoryStore.depend.openMp = openMp; var storageProtocol = storage.getItem(Navigation.StoreProtocolKey); storageProtocol && RongIMLib.RongIMClient.setProtocol(storageProtocol); _onsuccess(); return; } } Navigation.clear(); RongIMLib.RongIMClient.invalidWsUrls = []; var context = this; var StatusEvent = RongIMLib.Channel._ConnectionStatusListener; var depend = RongIMLib.RongIMClient._memoryStore.depend; var navigaters = depend.navigaters; var naviTimeout = depend.naviTimeout; var maxNaviRetry = depend.maxNaviRetry; var isNaviJSONP = depend.isNaviJSONP; var isWSPingJSONP = depend.isWSPingJSONP; var isSupportRequestHeaders = RongIMLib.RongUtil.isSupportRequestHeaders(); var isRequestJSONP = !isSupportRequestHeaders || isNaviJSONP; var requestFunc = isRequestJSONP ? context.requestJSONP : context.request; var timer = new RongIMLib.Timer({ timeout: naviTimeout }); var internalRetry = 1; var isRange = function () { return internalRetry >= maxNaviRetry; }; var indexTools = new RongIMLib.IndexTools({ items: navigaters, onwheel: function () { internalRetry += 1; } }); var consume = function () { if (isRange()) { if (isNaviJSONP && isWSPingJSONP) { return _onerror(RongIMLib.ConnectionStatus.RESPONSE_NAVI_ERROR); } // 所有导航请求失败,及所有重试失败后,返回预埋导航配置信息,进行连接。预埋导航配置仅适用公有云环境,私有云仍直接抛出 var naviResp = RongIMLib.FixedNaviRespHandler.getResp(); var naviHost = navigaters[0]; context.getNaviSuccess(naviResp, RongIMLib.RongUtil.getValidNavi(naviHost)); _onsuccess(); return; } var index = indexTools.get(); var navi = navigaters[index]; navi = RongIMLib.RongUtil.getValidNavi(navi); indexTools.add(); RongIMLib.LoggerUtil.recordFatalLogOfNavi(internalRetry, navigaters); var success = function (result) { timer.pause(); StatusEvent.onChanged(RongIMLib.ConnectionStatus.RESPONSE_NAVI); var code = result.code; if (RongIMLib.RongUtil.isEqual(code, 200)) { context.getNaviSuccess(result, navi); _onsuccess(); } if (RongIMLib.RongUtil.isEqual(code, 401)) { _onerror(RongIMLib.ConnectionState.TOKEN_INCORRECT); } if (RongIMLib.RongUtil.isEqual(code, 403)) { StatusEvent.onChanged(RongIMLib.ConnectionStatus.APPKEY_IS_FAKE); } }; var error = function (status) { if (RongIMLib.RongUtil.isEqual(status, 0)) { return; } timer.pause(); StatusEvent.onChanged(RongIMLib.ConnectionStatus.RESPONSE_NAVI_ERROR); consume(); }; StatusEvent.onChanged(RongIMLib.ConnectionStatus.REQUEST_NAVI); var xhr = requestFunc.call(context, navi, appId, token, success, error); timer.resume(function () { StatusEvent.onChanged(RongIMLib.ConnectionStatus.RESPONSE_NAVI_TIMEOUT); xhr.abort(); consume(); }); }; consume(); RongIMLib.Logger.loggerCache.isNewNavi = true; }; Navigation.prototype.getPath = function (navi, appId, token, callbackName) { var depend = RongIMLib.RongIMClient._memoryStore.depend; var path = (depend.isPolling ? 'cometnavi' : 'navi'); token = encodeURIComponent(token); var sdkver = RongIMLib.RongIMClient.sdkver; var random = RongIMLib.RongUtil.getTimestamp(); var tpl = '{navi}/{path}.js?appId={appId}&token={token}&callBack={callback}&v={sdkver}&r={random}'; var url = RongIMLib.RongUtil.tplEngine(tpl, { navi: navi, path: path, appId: appId, token: token, sdkver: sdkver, random: random, callback: callbackName }); return url; }; Navigation.prototype.request = function (navi, appId, token, success, error) { var url = this.getPath(navi, appId, token, 'getServerEndpoint'); var requestType = "HTTP"; RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.L_GETN_T, level: RongIMLib.LoggerLevel.I, type: RongIMLib.LoggerType.IM, content: { url: url, requestType: requestType } }); return RongIMLib.RongUtil.request({ url: url, success: function (result) { result = result.replace('getServerEndpoint(', '').replace(');', ''); // 兼容私有云无分号 var lastIndex = result.lastIndexOf(')'); var maxIndex = result.length - 1; if (lastIndex == maxIndex) { result = result.substr(0, lastIndex); } result = JSON.parse(result); RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.L_GETN_R, level: RongIMLib.LoggerLevel.I, type: RongIMLib.LoggerType.IM, content: { code: 0, result: result, url: url, requestType: requestType } }); success(result); }, error: function (status, result) { if (status == 401 || status == 403) { success(JSON.parse(result)); } else { error(status); } RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.L_GETN_R, level: RongIMLib.LoggerLevel.E, type: RongIMLib.LoggerType.IM, content: { code: status, result: result, url: url, requestType: requestType } }); } }); }; Navigation.prototype.requestJSONP = function (navi, appId, token, success, error) { var callbackName = 'getServerEndpoint'; var requestType = "JSONP"; RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.L_GETN_T, level: RongIMLib.LoggerLevel.I, type: RongIMLib.LoggerType.IM, content: { url: url, requestType: requestType } }); var loggerResult = function (status, result) { RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.L_GETN_R, level: RongIMLib.LoggerLevel.E, type: RongIMLib.LoggerType.IM, content: { code: status, result: result, url: url, requestType: requestType } }); }; window.getServerEndpoint = function (result) { var code = result.code; loggerResult(code, result); if (code !== 200) { return error(RongIMLib.ConnectionState.TOKEN_INCORRECT); } success(result); }; var url = this.getPath(navi, appId, token, callbackName); var xss = document.createElement('script'); xss.src = url; document.body.appendChild(xss); xss.onerror = function () { error(RongIMLib.ConnectionState.TOKEN_INCORRECT); loggerResult(RongIMLib.ConnectionState.TOKEN_INCORRECT, {}); }; }; Navigation.StoreProtocolKey = 'navprotocol'; Navigation.Endpoint = new Object; return Navigation; })(); RongIMLib.Navigation = Navigation; })(RongIMLib || (RongIMLib = {})); // TODO: 统一变量、方法等命名规范 var RongIMLib; (function (RongIMLib) { /** * 消息基类 */ var BaseMessage = (function () { function BaseMessage(arg) { this._name = "BaseMessage"; this.lengthSize = 0; if (arg instanceof RongIMLib.Header) { this._header = arg; } else { this._header = new RongIMLib.Header(arg, false, RongIMLib.Qos.AT_MOST_ONCE, false); } } BaseMessage.prototype.read = function (In, length) { this.readMessage(In, length); }; BaseMessage.prototype.write = function (Out) { var binaryHelper = new RongIMLib.BinaryHelper(); var out = binaryHelper.convertStream(Out); this._headerCode = this.getHeaderFlag(); out.write(this._headerCode); this.writeMessage(out); return out; }; BaseMessage.prototype.getHeaderFlag = function () { return this._header.encode(); }; BaseMessage.prototype.getLengthSize = function () { return this.lengthSize; }; BaseMessage.prototype.toBytes = function () { return this.write([]).getBytesArray(); }; BaseMessage.prototype.isRetained = function () { return this._header.retain; }; BaseMessage.prototype.setRetained = function (retain) { this._header.retain = retain; }; BaseMessage.prototype.setQos = function (qos) { this._header.qos = Object.prototype.toString.call(qos) == "[object Object]" ? qos : RongIMLib.Qos[qos]; }; BaseMessage.prototype.setDup = function (dup) { this._header.dup = dup; }; BaseMessage.prototype.isDup = function () { return this._header.dup; }; BaseMessage.prototype.getType = function () { return this._header.type; }; BaseMessage.prototype.getQos = function () { return this._header.qos; }; BaseMessage.prototype.messageLength = function () { return 0; }; BaseMessage.prototype.writeMessage = function (out) { }; BaseMessage.prototype.readMessage = function (In, length) { }; BaseMessage.prototype.init = function (args) { var valName, nana, me = this; for (nana in args) { if (!args.hasOwnProperty(nana)) { continue; } valName = nana.replace(/^\w/, function (x) { var tt = x.charCodeAt(0); return "set" + (tt >= 0x61 ? String.fromCharCode(tt & ~32) : x); }); if (valName in me) { if (nana == "status") { me[valName](disconnectStatus[args[nana]] ? disconnectStatus[args[nana]] : args[nana]); } else { me[valName](args[nana]); } } } }; return BaseMessage; })(); RongIMLib.BaseMessage = BaseMessage; /** *连接消息类型 */ var ConnectMessage = (function (_super) { __extends(ConnectMessage, _super); function ConnectMessage(header) { _super.call(this, arguments.length == 0 || arguments.length == 3 ? RongIMLib.Type.CONNECT : arguments[0]); this._name = "ConnectMessage"; this.CONNECT_HEADER_SIZE = 12; this.protocolId = "RCloud"; this.binaryHelper = new RongIMLib.BinaryHelper(); this.protocolVersion = 3; switch (arguments.length) { case 0: case 1: case 3: if (!arguments[0] || arguments[0].length > 64) { throw new Error("ConnectMessage:Client Id cannot be null and must be at most 64 characters long: " + arguments[0]); } this.clientId = arguments[0]; this.cleanSession = arguments[1]; this.keepAlive = arguments[2]; break; } } ConnectMessage.prototype.messageLength = function () { var payloadSize = this.binaryHelper.toMQttString(this.clientId).length; payloadSize += this.binaryHelper.toMQttString(this.willTopic).length; payloadSize += this.binaryHelper.toMQttString(this.will).length; payloadSize += this.binaryHelper.toMQttString(this.appId).length; payloadSize += this.binaryHelper.toMQttString(this.token).length; return payloadSize + this.CONNECT_HEADER_SIZE; }; ConnectMessage.prototype.readMessage = function (stream) { this.protocolId = stream.readUTF(); this.protocolVersion = stream.readByte(); var cFlags = stream.readByte(); this.hasAppId = (cFlags & 128) > 0; this.hasToken = (cFlags & 64) > 0; this.retainWill = (cFlags & 32) > 0; this.willQos = cFlags >> 3 & 3; this.hasWill = (cFlags & 4) > 0; this.cleanSession = (cFlags & 32) > 0; this.keepAlive = stream.read() * 256 + stream.read(); this.clientId = stream.readUTF(); if (this.hasWill) { this.willTopic = stream.readUTF(); this.will = stream.readUTF(); } if (this.hasAppId) { try { this.appId = stream.readUTF(); } catch (ex) { throw new Error(ex); } } if (this.hasToken) { try { this.token = stream.readUTF(); } catch (ex) { throw new Error(ex); } } return stream; }; ConnectMessage.prototype.writeMessage = function (out) { var stream = this.binaryHelper.convertStream(out); stream.writeUTF(this.protocolId); stream.write(this.protocolVersion); var flags = this.cleanSession ? 2 : 0; flags |= this.hasWill ? 4 : 0; flags |= this.willQos ? this.willQos >> 3 : 0; flags |= this.retainWill ? 32 : 0; flags |= this.hasToken ? 64 : 0; flags |= this.hasAppId ? 128 : 0; stream.write(flags); stream.writeChar(this.keepAlive); stream.writeUTF(this.clientId); if (this.hasWill) { stream.writeUTF(this.willTopic); stream.writeUTF(this.will); } if (this.hasAppId) { stream.writeUTF(this.appId); } if (this.hasToken) { stream.writeUTF(this.token); } return stream; }; return ConnectMessage; })(BaseMessage); RongIMLib.ConnectMessage = ConnectMessage; /** *连接应答类型 */ var ConnAckMessage = (function (_super) { __extends(ConnAckMessage, _super); function ConnAckMessage(header) { _super.call(this, arguments.length == 0 ? RongIMLib.Type.CONNACK : arguments.length == 1 ? arguments[0] instanceof RongIMLib.Header ? arguments[0] : RongIMLib.Type.CONNACK : null); this._name = "ConnAckMessage"; this.MESSAGE_LENGTH = 2; this.binaryHelper = new RongIMLib.BinaryHelper(); var me = this; switch (arguments.length) { case 0: case 1: if (!(arguments[0] instanceof RongIMLib.Header)) { if (arguments[0] in RongIMLib.ConnectionState) { if (arguments[0] == null) { throw new Error("ConnAckMessage:The status of ConnAskMessage can't be null"); } me.setStatus(arguments[0]); } } break; } } ; ConnAckMessage.prototype.messageLength = function () { var length = this.MESSAGE_LENGTH; if (this.userId) { length += this.binaryHelper.toMQttString(this.userId).length; } return length; }; ; ConnAckMessage.prototype.readMessage = function (_in, msglength) { _in.read(); var result = +_in.read(); if (result >= 0 && result <= 12) { this.setStatus(result); } else { throw new Error("Unsupported CONNACK code:" + result); } if (msglength > this.MESSAGE_LENGTH) { this.setUserId(_in.readUTF()); var sessionId = _in.readUTF(); var timestamp = _in.readLong(); this.setTimestamp(timestamp); } }; ; ConnAckMessage.prototype.writeMessage = function (out) { var stream = this.binaryHelper.convertStream(out); stream.write(128); switch (+status) { case 0: case 1: case 2: case 5: case 6: stream.write(+status); break; case 3: case 4: stream.write(3); break; default: throw new Error("Unsupported CONNACK code:" + status); } if (this.userId) { stream.writeUTF(this.userId); } return stream; }; ; ConnAckMessage.prototype.setStatus = function (x) { this.status = x; }; ; ConnAckMessage.prototype.setUserId = function (_userId) { this.userId = _userId; }; ; ConnAckMessage.prototype.getStatus = function () { return this.status; }; ; ConnAckMessage.prototype.getUserId = function () { return this.userId; }; ; ConnAckMessage.prototype.setTimestamp = function (x) { this.timestrap = x; }; ; ConnAckMessage.prototype.getTimestamp = function () { return this.timestrap; }; return ConnAckMessage; })(BaseMessage); RongIMLib.ConnAckMessage = ConnAckMessage; /** *断开消息类型 */ var DisconnectMessage = (function (_super) { __extends(DisconnectMessage, _super); function DisconnectMessage(header) { _super.call(this, header instanceof RongIMLib.Header ? header : RongIMLib.Type.DISCONNECT); this._name = "DisconnectMessage"; this.MESSAGE_LENGTH = 2; this.binaryHelper = new RongIMLib.BinaryHelper(); if (!(header instanceof RongIMLib.Header)) { if (header in RongIMLib.ConnectionStatus) { this.status = header; } } } DisconnectMessage.prototype.messageLength = function () { return this.MESSAGE_LENGTH; }; DisconnectMessage.prototype.readMessage = function (_in) { _in.read(); var result = +_in.read(); if (result >= 0 && result <= 5) { this.setStatus(disconnectStatus[result] ? disconnectStatus[result] : result); } else { throw new Error("Unsupported CONNACK code:" + result); } }; DisconnectMessage.prototype.writeMessage = function (Out) { var out = this.binaryHelper.convertStream(Out); out.write(0); if (+status >= 1 && +status <= 3) { out.write((+status) - 1); } else { throw new Error("Unsupported CONNACK code:" + status); } }; DisconnectMessage.prototype.setStatus = function (x) { this.status = x; }; ; DisconnectMessage.prototype.getStatus = function () { return this.status; }; ; return DisconnectMessage; })(BaseMessage); RongIMLib.DisconnectMessage = DisconnectMessage; /** *请求消息信令 */ var PingReqMessage = (function (_super) { __extends(PingReqMessage, _super); function PingReqMessage(header) { _super.call(this, (header && header instanceof RongIMLib.Header) ? header : RongIMLib.Type.PINGREQ); this._name = "PingReqMessage"; } return PingReqMessage; })(BaseMessage); RongIMLib.PingReqMessage = PingReqMessage; /** *响应消息信令 */ var PingRespMessage = (function (_super) { __extends(PingRespMessage, _super); function PingRespMessage(header) { _super.call(this, (header && header instanceof RongIMLib.Header) ? header : RongIMLib.Type.PINGRESP); this._name = "PingRespMessage"; } return PingRespMessage; })(BaseMessage); RongIMLib.PingRespMessage = PingRespMessage; /** *封装MesssageId */ var RetryableMessage = (function (_super) { __extends(RetryableMessage, _super); function RetryableMessage(argu) { _super.call(this, argu); this._name = "RetryableMessage"; this.binaryHelper = new RongIMLib.BinaryHelper(); } RetryableMessage.prototype.messageLength = function () { return 2; }; RetryableMessage.prototype.writeMessage = function (Out) { var out = this.binaryHelper.convertStream(Out), Id = this.getMessageId(), lsb = Id & 255, msb = (Id & 65280) >> 8; out.write(msb); out.write(lsb); return out; }; RetryableMessage.prototype.readMessage = function (_in, msgLength) { var msgId = _in.read() * 256 + _in.read(); this.setMessageId(parseInt(msgId, 10)); }; RetryableMessage.prototype.setMessageId = function (_messageId) { this.messageId = _messageId; }; RetryableMessage.prototype.getMessageId = function () { return this.messageId; }; return RetryableMessage; })(BaseMessage); RongIMLib.RetryableMessage = RetryableMessage; /** *发送消息应答(双向) *qos为1必须给出应答(所有消息类型一样) */ var PubAckMessage = (function (_super) { __extends(PubAckMessage, _super); function PubAckMessage(header) { _super.call(this, (header instanceof RongIMLib.Header) ? header : RongIMLib.Type.PUBACK); this.msgLen = 2; this.date = 0; this.millisecond = 0; this.timestamp = 0; this.binaryHelper = new RongIMLib.BinaryHelper(); this._name = "PubAckMessage"; if (!(header instanceof RongIMLib.Header)) { _super.prototype.setMessageId.call(this, header); } } PubAckMessage.prototype.messageLength = function () { return this.msgLen; }; PubAckMessage.prototype.writeMessage = function (Out) { var out = this.binaryHelper.convertStream(Out); RetryableMessage.prototype.writeMessage.call(this, out); }; PubAckMessage.prototype.readMessage = function (_in, msgLength) { RetryableMessage.prototype.readMessage.call(this, _in); this.date = _in.readInt(); this.status = _in.read() * 256 + _in.read(); this.millisecond = _in.read() * 256 + _in.read(); this.timestamp = this.date * 1000 + this.millisecond; this.messageUId = _in.readUTF(); }; PubAckMessage.prototype.setStatus = function (x) { this.status = x; }; PubAckMessage.prototype.setTimestamp = function (timestamp) { this.timestamp = timestamp; }; PubAckMessage.prototype.setMessageUId = function (messageUId) { this.messageUId = messageUId; }; PubAckMessage.prototype.getStatus = function () { return this.status; }; PubAckMessage.prototype.getDate = function () { return this.date; }; PubAckMessage.prototype.getTimestamp = function () { return this.timestamp; }; PubAckMessage.prototype.getMessageUId = function () { return this.messageUId; }; return PubAckMessage; })(RetryableMessage); RongIMLib.PubAckMessage = PubAckMessage; /** *发布消息 */ var PublishMessage = (function (_super) { __extends(PublishMessage, _super); function PublishMessage(header, two, three) { _super.call(this, (arguments.length == 1 && header instanceof RongIMLib.Header) ? header : arguments.length == 3 ? RongIMLib.Type.PUBLISH : 0); this._name = "PublishMessage"; this.binaryHelper = new RongIMLib.BinaryHelper(); this.syncMsg = false; if (arguments.length == 3) { this.topic = header; this.targetId = three; this.data = typeof two == "string" ? this.binaryHelper.toMQttString(two) : two; } } PublishMessage.prototype.messageLength = function () { var length = 10; length += this.binaryHelper.toMQttString(this.topic).length; length += this.binaryHelper.toMQttString(this.targetId).length; length += this.data.length; return length; }; PublishMessage.prototype.writeMessage = function (Out) { var out = this.binaryHelper.convertStream(Out); out.writeUTF(this.topic); out.writeUTF(this.targetId); RetryableMessage.prototype.writeMessage.apply(this, arguments); out.write(this.data); }; ; PublishMessage.prototype.readMessage = function (_in, msgLength) { var pos = 6; this.date = _in.readInt(); this.topic = _in.readUTF(); pos += this.binaryHelper.toMQttString(this.topic).length; this.targetId = _in.readUTF(); pos += this.binaryHelper.toMQttString(this.targetId).length; RetryableMessage.prototype.readMessage.apply(this, arguments); this.data = new Array(msgLength - pos); this.data = _in.read(this.data); }; ; PublishMessage.prototype.setTopic = function (x) { this.topic = x; }; PublishMessage.prototype.setData = function (x) { this.data = x; }; PublishMessage.prototype.setTargetId = function (x) { this.targetId = x; }; PublishMessage.prototype.setDate = function (x) { this.date = x; }; PublishMessage.prototype.setSyncMsg = function (x) { this.syncMsg = x; }; //是否是其他端同步过来的消息 PublishMessage.prototype.getSyncMsg = function () { return this.syncMsg; }; PublishMessage.prototype.getTopic = function () { return this.topic; }; PublishMessage.prototype.getData = function () { return this.data; }; PublishMessage.prototype.getTargetId = function () { return this.targetId; }; PublishMessage.prototype.getDate = function () { return this.date; }; return PublishMessage; })(RetryableMessage); RongIMLib.PublishMessage = PublishMessage; /** *请求查询 */ var QueryMessage = (function (_super) { __extends(QueryMessage, _super); function QueryMessage(header, two, three) { _super.call(this, header instanceof RongIMLib.Header ? header : arguments.length == 3 ? RongIMLib.Type.QUERY : null); this.binaryHelper = new RongIMLib.BinaryHelper(); this._name = "QueryMessage"; if (arguments.length == 3) { this.data = typeof two == "string" ? this.binaryHelper.toMQttString(two) : two; this.topic = header; this.targetId = three; } } QueryMessage.prototype.messageLength = function () { var length = 0; length += this.binaryHelper.toMQttString(this.topic).length; length += this.binaryHelper.toMQttString(this.targetId).length; length += 2; length += this.data.length; return length; }; QueryMessage.prototype.writeMessage = function (Out) { var out = this.binaryHelper.convertStream(Out); out.writeUTF(this.topic); out.writeUTF(this.targetId); RetryableMessage.prototype.writeMessage.call(this, out); out.write(this.data); }; QueryMessage.prototype.readMessage = function (_in, msgLength) { var pos = 0; this.topic = _in.readUTF(); this.targetId = _in.readUTF(); pos += this.binaryHelper.toMQttString(this.topic).length; pos += this.binaryHelper.toMQttString(this.targetId).length; this.readMessage.apply(this, arguments); pos += 2; this.data = new Array(msgLength - pos); _in.read(this.data); }; QueryMessage.prototype.setTopic = function (x) { this.topic = x; }; QueryMessage.prototype.setData = function (x) { this.data = x; }; QueryMessage.prototype.setTargetId = function (x) { this.targetId = x; }; QueryMessage.prototype.getTopic = function () { return this.topic; }; QueryMessage.prototype.getData = function () { return this.data; }; QueryMessage.prototype.getTargetId = function () { return this.targetId; }; return QueryMessage; })(RetryableMessage); RongIMLib.QueryMessage = QueryMessage; /** *请求查询确认 */ var QueryConMessage = (function (_super) { __extends(QueryConMessage, _super); function QueryConMessage(messageId) { _super.call(this, (messageId instanceof RongIMLib.Header) ? messageId : RongIMLib.Type.QUERYCON); this._name = "QueryConMessage"; if (!(messageId instanceof RongIMLib.Header)) { _super.prototype.setMessageId.call(this, messageId); } } return QueryConMessage; })(RetryableMessage); RongIMLib.QueryConMessage = QueryConMessage; /** *请求查询应答 */ var QueryAckMessage = (function (_super) { __extends(QueryAckMessage, _super); function QueryAckMessage(header) { _super.call(this, header); this._name = "QueryAckMessage"; this.binaryHelper = new RongIMLib.BinaryHelper(); } QueryAckMessage.prototype.readMessage = function (In, msgLength) { RetryableMessage.prototype.readMessage.call(this, In); this.date = In.readInt(); this.setStatus(In.read() * 256 + In.read()); if (msgLength > 0) { this.data = new Array(msgLength - 8); this.data = In.read(this.data); } }; QueryAckMessage.prototype.getData = function () { return this.data; }; QueryAckMessage.prototype.getStatus = function () { return this.status; }; QueryAckMessage.prototype.getDate = function () { return this.date; }; QueryAckMessage.prototype.setDate = function (x) { this.date = x; }; QueryAckMessage.prototype.setStatus = function (x) { this.status = x; }; QueryAckMessage.prototype.setData = function (x) { this.data = x; }; return QueryAckMessage; })(RetryableMessage); RongIMLib.QueryAckMessage = QueryAckMessage; })(RongIMLib || (RongIMLib = {})); /// var RongIMLib; (function (RongIMLib) { /** * 把消息对象写入流中 * 发送消息时用到 */ var MessageOutputStream = (function () { function MessageOutputStream(_out) { var binaryHelper = new RongIMLib.BinaryHelper(); this.out = binaryHelper.convertStream(_out); } MessageOutputStream.prototype.writeMessage = function (msg) { if (msg instanceof RongIMLib.BaseMessage) { msg.write(this.out); } }; return MessageOutputStream; })(); RongIMLib.MessageOutputStream = MessageOutputStream; /** * 流转换为消息对象 * 服务器返回消息时用到 */ var MessageInputStream = (function () { function MessageInputStream(In, isPolling) { if (!isPolling) { var _in = new RongIMLib.BinaryHelper().convertStream(In); this.flags = _in.readByte(); this._in = _in; } else { this.flags = In["headerCode"]; } this.header = new RongIMLib.Header(this.flags); this.isPolling = isPolling; this.In = In; } MessageInputStream.prototype.readMessage = function () { switch (this.header.getType()) { case 1: this.msg = new RongIMLib.ConnectMessage(this.header); break; case 2: this.msg = new RongIMLib.ConnAckMessage(this.header); break; case 3: this.msg = new RongIMLib.PublishMessage(this.header); this.msg.setSyncMsg(this.header.getSyncMsg()); break; case 4: this.msg = new RongIMLib.PubAckMessage(this.header); break; case 5: this.msg = new RongIMLib.QueryMessage(this.header); break; case 6: this.msg = new RongIMLib.QueryAckMessage(this.header); break; case 7: this.msg = new RongIMLib.QueryConMessage(this.header); break; case 9: case 11: case 13: this.msg = new RongIMLib.PingRespMessage(this.header); break; case 8: case 10: case 12: this.msg = new RongIMLib.PingReqMessage(this.header); break; case 14: this.msg = new RongIMLib.DisconnectMessage(this.header); break; default: throw new Error("No support for deserializing " + this.header.getType() + " messages"); } if (this.isPolling) { this.msg.init(this.In); } else { this.msg.read(this._in, this.In.length - 1); } return this.msg; }; return MessageInputStream; })(); RongIMLib.MessageInputStream = MessageInputStream; var Header = (function () { function Header(_type, _retain, _qos, _dup) { this.retain = false; this.qos = RongIMLib.Qos.AT_LEAST_ONCE; this.dup = false; this.syncMsg = false; if (_type && +_type == _type && arguments.length == 1) { this.retain = (_type & 1) > 0; this.qos = (_type & 6) >> 1; this.dup = (_type & 8) > 0; this.type = (_type >> 4) & 15; this.syncMsg = (_type & 8) == 8; } else { this.type = _type; this.retain = _retain; this.qos = _qos; this.dup = _dup; } } Header.prototype.getSyncMsg = function () { return this.syncMsg; }; Header.prototype.getType = function () { return this.type; }; Header.prototype.encode = function () { var me = this; switch (this.qos) { case RongIMLib.Qos[0]: me.qos = RongIMLib.Qos.AT_MOST_ONCE; break; case RongIMLib.Qos[1]: me.qos = RongIMLib.Qos.AT_LEAST_ONCE; break; case RongIMLib.Qos[2]: me.qos = RongIMLib.Qos.EXACTLY_ONCE; break; case RongIMLib.Qos[3]: me.qos = RongIMLib.Qos.DEFAULT; break; } var _byte = (this.type << 4); _byte |= this.retain ? 1 : 0; _byte |= this.qos << 1; _byte |= this.dup ? 8 : 0; return _byte; }; Header.prototype.toString = function () { return "Header [type=" + this.type + ",retain=" + this.retain + ",qos=" + this.qos + ",dup=" + this.dup + "]"; }; return Header; })(); RongIMLib.Header = Header; /** * 二进制帮助对象 */ var BinaryHelper = (function () { function BinaryHelper() { } BinaryHelper.prototype.writeUTF = function (str, isGetBytes) { var back = [], byteSize = 0; for (var i = 0, len = str.length; i < len; i++) { var code = str.charCodeAt(i); if (code >= 0 && code <= 127) { byteSize += 1; back.push(code); } else if (code >= 128 && code <= 2047) { byteSize += 2; back.push((192 | (31 & (code >> 6)))); back.push((128 | (63 & code))); } else if (code >= 2048 && code <= 65535) { byteSize += 3; back.push((224 | (15 & (code >> 12)))); back.push((128 | (63 & (code >> 6)))); back.push((128 | (63 & code))); } } for (var i = 0, len = back.length; i < len; i++) { if (back[i] > 255) { back[i] &= 255; } } if (isGetBytes) { return back; } if (byteSize <= 255) { return [0, byteSize].concat(back); } else { return [byteSize >> 8, byteSize & 255].concat(back); } }; BinaryHelper.prototype.readUTF = function (arr) { if (Object.prototype.toString.call(arr) == "[object String]") { return arr; } var UTF = "", _arr = arr; for (var i = 0, len = _arr.length; i < len; i++) { if (_arr[i] < 0) { _arr[i] += 256; } ; var one = _arr[i].toString(2), v = one.match(/^1+?(?=0)/); if (v && one.length == 8) { var bytesLength = v[0].length, // store = _arr[i].toString(2).slice(7 - bytesLength); store = ''; for (var st = 0; st < bytesLength; st++) { store += _arr[st + i].toString(2).slice(2); } UTF += String.fromCharCode(parseInt(store, 2)); i += bytesLength - 1; } else { UTF += String.fromCharCode(_arr[i]); } } return UTF; }; /** * [convertStream 将参数x转化为RongIMStream对象] * @param {any} x [参数] */ BinaryHelper.prototype.convertStream = function (x) { if (x instanceof RongIMStream) { return x; } else { return new RongIMStream(x); } }; BinaryHelper.prototype.toMQttString = function (str) { return this.writeUTF(str); }; return BinaryHelper; })(); RongIMLib.BinaryHelper = BinaryHelper; var RongIMStream = (function () { function RongIMStream(arr) { //当前流执行的起始位置 this.position = 0; //当前流写入的多少字节 this.writen = 0; this.poolLen = 0; this.binaryHelper = new BinaryHelper(); this.pool = arr; this.poolLen = arr.length; } RongIMStream.prototype.check = function () { return this.position >= this.pool.length; }; RongIMStream.prototype.readInt = function () { if (this.check()) { return -1; } var end = ""; for (var i = 0; i < 4; i++) { var t = this.pool[this.position++].toString(16); if (t.length == 1) { t = "0" + t; } end += t.toString(16); } return parseInt(end, 16); }; RongIMStream.prototype.readLong = function () { if (this.check()) { return -1; } var end = ""; for (var i = 0; i < 8; i++) { var t = this.pool[this.position++].toString(16); if (t.length == 1) { t = "0" + t; } end += t; } return parseInt(end, 16); }; RongIMStream.prototype.readTimestamp = function () { if (this.check()) { return -1; } var end = ""; for (var i = 0; i < 8; i++) { end += this.pool[this.position++].toString(16); } end = end.substring(2, 8); return parseInt(end, 16); }; RongIMStream.prototype.readUTF = function () { if (this.check()) { return -1; } var big = (this.readByte() << 8) | this.readByte(); return this.binaryHelper.readUTF(this.pool.subarray(this.position, this.position += big)); }; RongIMStream.prototype.readByte = function () { if (this.check()) { return -1; } var val = this.pool[this.position++]; if (val > 255) { val &= 255; } return val; }; RongIMStream.prototype.read = function (bytesArray) { if (bytesArray) { return this.pool.subarray(this.position, this.poolLen); } else { return this.readByte(); } }; RongIMStream.prototype.write = function (_byte) { var b = _byte; if (Object.prototype.toString.call(b).toLowerCase() == "[object array]") { try { this.pool = this.pool.concat(b); } catch (e) { [].push.apply(this.pool, b); } } else { if (+b == b) { if (b > 255) { b &= 255; } this.pool.push(b); this.writen++; } } return b; }; RongIMStream.prototype.writeChar = function (v) { if (+v != v) { throw new Error("writeChar:arguments type is error"); } this.write(v >> 8 & 255); this.write(v & 255); this.writen += 2; }; RongIMStream.prototype.writeUTF = function (str) { var val = this.binaryHelper.writeUTF(str); [].push.apply(this.pool, val); this.writen += val.length; }; RongIMStream.prototype.toComplements = function () { var _tPool = this.pool; for (var i = 0; i < this.poolLen; i++) { if (_tPool[i] > 128) { _tPool[i] -= 256; } } return _tPool; }; RongIMStream.prototype.getBytesArray = function (isCom) { if (isCom) { return this.toComplements(); } return this.pool; }; return RongIMStream; })(); RongIMLib.RongIMStream = RongIMStream; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var SocketTransportation = (function () { /** * [constructor] * @param {string} url [连接地址:包含token、version] */ function SocketTransportation(_socket) { //连接状态 true:已连接 false:未连接 this.connected = false; //是否关闭: true:已关闭 false:未关闭 this.isClose = false; //存放消息队列的临时变量 this.queue = []; this.empty = new Function; this._socket = _socket; return this; } /** * [createTransport 创建WebScoket对象] */ SocketTransportation.prototype.createTransport = function (url, method) { if (!url) { throw new Error("URL can't be empty"); } ; this.url = url; var depend = RongIMLib.RongIMClient._memoryStore.depend; var wsScheme = depend.wsScheme; var tpl = '{wsScheme}{url}'; url = RongIMLib.RongUtil.tplEngine(tpl, { wsScheme: wsScheme, url: url }); this.socket = new WebSocket(url); this.socket.binaryType = "arraybuffer"; this.addEvent(); return this.socket; }; /** * [send 传送消息流] * @param {ArrayBuffer} data [二进制消息流] */ SocketTransportation.prototype.send = function (data) { if (!this.connected && !this.isClose) { //当通道不可用时,加入消息队列 this.queue.push(data); return; } if (this.isClose) { this._socket.fire("StatusChanged", RongIMLib.ConnectionStatus.CONNECTION_CLOSED); return; } var stream = new RongIMLib.RongIMStream([]), msg = new RongIMLib.MessageOutputStream(stream); msg.writeMessage(data); var val = stream.getBytesArray(true); var binary = new Int8Array(val); this.socket.send(binary.buffer); return this; }; /** * [onData 通道返回数据时调用的方法,用来想上层传递服务器返回的二进制消息流] * @param {ArrayBuffer} data [二进制消息流] */ SocketTransportation.prototype.onData = function (data) { if (RongIMLib.MessageUtil.isArray(data)) { this._socket.onMessage(new RongIMLib.MessageInputStream(data).readMessage()); } else { this._socket.onMessage(new RongIMLib.MessageInputStream(RongIMLib.MessageUtil.ArrayFormInput(data)).readMessage()); } return ""; }; /** * [onClose 通道关闭时触发的方法] */ SocketTransportation.prototype.onClose = function (ev) { var me = this; me.isClose = true; me.socket = this.empty; RongIMLib.Bridge._client.clearHeartbeat(); if (ev.code == 1006 && !this._status) { var currentTime = new Date().getTime(); if (!me.connectedTime || (currentTime - me.connectedTime <= SocketTransportation.MinConnectTime)) { var host = RongIMLib.RongUtil.getUrlHost(me.url); RongIMLib.RongIMClient.invalidWsUrls.push(host); } me._socket.fire("StatusChanged", RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE); } else { me._status = 0; } }; /** * [onError 通道报错时触发的方法] * @param {any} error [抛出异常] */ SocketTransportation.prototype.onError = function (error) { this._socket.fire("StatusChanged", RongIMLib.ConnectionStatus.WEBSOCKET_ERROR); RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.L_WS_ERR_E, level: RongIMLib.LoggerLevel.E, type: RongIMLib.LoggerType.IM, content: { error: RongIMLib.ConnectionStatus.WEBSOCKET_ERROR, msg: 'SocketTransportation -> onError' } }); throw new Error(error); }; /** * [addEvent 为通道绑定事件] */ SocketTransportation.prototype.addEvent = function () { var self = this; self.socket.onopen = function () { self.connected = true; self.isClose = false; //通道可以用后,调用发送队列方法,把所有等得发送的消息发出 self.doQueue(); self._socket.fire("connect"); self.connectedTime = new Date().getTime(); }; self.socket.onmessage = function (ev) { //判断数据是不是字符串,如果是字符串那么就是flash传过来的。 if (typeof ev.data == "string") { self.onData(ev.data.split(",")); } else { self.onData(ev.data); } }; self.socket.onerror = function (ev) { self.onError(ev); }; self.socket.onclose = function (ev) { self.onClose(ev); }; }; /** * [doQueue 消息队列,把队列中消息发出] */ SocketTransportation.prototype.doQueue = function () { var self = this; for (var i = 0, len = self.queue.length; i < len; i++) { self.send(self.queue[i]); } }; /** * [disconnect 断开连接] */ SocketTransportation.prototype.disconnect = function (status) { var me = this; if (me.socket.readyState) { me.isClose = true; if (status) { me._status = status; } me.socket.close(); } }; /** * [reconnect 重新连接] */ SocketTransportation.prototype.reconnect = function () { this.disconnect(); this.createTransport(this.url); }; SocketTransportation.prototype.close = function () { this.socket.close(); }; // 最短链接时长(若 5000ms 内, ws 自动断开, 此 ws 地址置为不可用) SocketTransportation.MinConnectTime = 5000; return SocketTransportation; })(); RongIMLib.SocketTransportation = SocketTransportation; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var PollingTransportation = (function () { function PollingTransportation(socket) { this.empty = new Function; this.connected = false; this.pid = +new Date + Math.random() + ""; this.queue = []; this.socket = socket; return this; } PollingTransportation.prototype.createTransport = function (url, method) { if (!url) { throw new Error("Url is empty,Please check it!"); } ; this.url = url; var sid = RongIMLib.RongIMClient._storageProvider.getItem("sId" + RongIMLib.Navigation.Endpoint.userId), me = this; if (sid) { setTimeout(function () { me.onSuccess("{\"status\":0,\"userId\":\"" + RongIMLib.Navigation.Endpoint.userId + "\",\"headerCode\":32,\"messageId\":0,\"sessionid\":\"" + sid + "\"}"); me.connected = true; }, 500); return this; } this.getRequest(url, true); return this; }; PollingTransportation.prototype.requestFactory = function (url, method, multipart) { var reqest = this.XmlHttpRequest(); if (multipart) { reqest.multipart = true; } // reqest.timeout = 60000; reqest.open(method || "GET", RongIMLib.RongIMClient._memoryStore.depend.protocol + url); if (method == "POST" && "setRequestHeader" in reqest) { reqest.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=utf-8"); } return reqest; }; PollingTransportation.prototype.getRequest = function (url, isconnect) { var me = this; me.xhr = this.requestFactory(url + "&pid=" + encodeURIComponent(me.pid), "GET"); var timer = new RongIMLib.Timer({ timeout: 45000 }); if ("onload" in me.xhr) { me.xhr.onload = function () { timer.pause(); me.xhr.onload = me.empty; if (this.responseText == "lost params") { me.onError(); } else { me.onSuccess(this.responseText, isconnect); } }; me.xhr.onerror = function () { timer.pause(); me.disconnect(); }; } else { me.xhr.onreadystatechange = function () { timer.pause(); if (me.xhr.readyState == 4) { me.xhr.onreadystatechange = me.empty; if (/^(200|202)$/.test(me.xhr.status)) { me.onSuccess(me.xhr.responseText, isconnect); } else if (/^(400|403)$/.test(me.xhr.status)) { me.onError(); } else { me.disconnect(); } } }; } timer.resume(function () { me.onError(); }); me.xhr.send(); }; /** * [send 发送消息,Method:POST] * queue 为消息队列,待通道可用发送所有等待消息 * @param {string} data [需要传入comet格式数据,此处只负责通讯通道,数据转换在外层处理] */ PollingTransportation.prototype.send = function (data) { var me = this; var _send = me.sendxhr = this.requestFactory(RongIMLib.Navigation.Endpoint.host + "/websocket" + data.url + "&pid=" + encodeURIComponent(me.pid), "POST"); if ("onload" in _send) { _send.onload = function () { _send.onload = me.empty; me.onData(_send.responseText); }; _send.onerror = function () { _send.onerror = me.empty; }; } else { _send.onreadystatechange = function () { if (_send.readyState == 4) { this.onreadystatechange = this.empty; if (/^(202|200)$/.test(_send.status)) { me.onData(_send.responseText); } } }; } _send.send(JSON.stringify(data.data)); }; PollingTransportation.prototype.onData = function (data, header) { if (!data || data == "lost params") { return; } var self = this, val = JSON.parse(data); if (val.userId) { RongIMLib.Navigation.Endpoint.userId = val.userId; } if (header) { RongIMLib.RongIMClient._storageProvider.setItem("sId" + RongIMLib.Navigation.Endpoint.userId, header); } if (!RongIMLib.MessageUtil.isArray(val)) { val = [val]; } Array.forEach(val, function (m) { self.socket.fire("message", new RongIMLib.MessageInputStream(m, true).readMessage()); }); return ""; }; PollingTransportation.prototype.XmlHttpRequest = function () { var hasCORS = typeof XMLHttpRequest !== "undefined" && "withCredentials" in new XMLHttpRequest(), self = this; if ("undefined" != typeof XMLHttpRequest && hasCORS) { return new XMLHttpRequest(); } else if ("undefined" != typeof XDomainRequest) { return new XDomainRequest(); } else { return new ActiveXObject("Microsoft.XMLHTTP"); } }; PollingTransportation.prototype.onClose = function () { if (this.xhr) { if (this.xhr.onload) { this.xhr.onreadystatechange = this.xhr.onload = this.empty; } else { this.xhr.onreadystatechange = this.empty; } this.xhr.abort(); this.xhr = null; } if (this.sendxhr) { if (this.sendxhr.onload) { this.sendxhr.onreadystatechange = this.sendxhr.onload = this.empty; } else { this.sendxhr.onreadystatechange = this.empty; } this.sendxhr.abort(); this.sendxhr = null; } }; PollingTransportation.prototype.disconnect = function () { RongIMLib.RongIMClient._storageProvider.removeItem("sId" + RongIMLib.Navigation.Endpoint.userId); RongIMLib.RongIMClient._storageProvider.removeItem(RongIMLib.Navigation.Endpoint.userId + "msgId"); this.onClose(); }; PollingTransportation.prototype.reconnect = function () { this.disconnect(); this.createTransport(this.url); }; PollingTransportation.prototype.onSuccess = function (responseText, isconnect) { var txt = responseText.match(/"sessionid":"\S+?(?=")/); this.onData(responseText, txt ? txt[0].slice(13) : 0); if (/"headerCode":-32,/.test(responseText)) { RongIMLib.RongIMClient._storageProvider.removeItem("sId" + RongIMLib.Navigation.Endpoint.userId); RongIMLib.RongIMClient._storageProvider.removeItem(RongIMLib.Navigation.Endpoint.userId + "msgId"); return; } this.getRequest(RongIMLib.Navigation.Endpoint.host + "/pullmsg.js?sessionid=" + RongIMLib.RongIMClient._storageProvider.getItem("sId" + RongIMLib.Navigation.Endpoint.userId) + "×trap=" + encodeURIComponent(new Date().getTime() + Math.random() + "")); this.connected = true; isconnect && this.socket.fire("connect"); }; PollingTransportation.prototype.onError = function () { RongIMLib.RongIMClient._storageProvider.removeItem("sId" + RongIMLib.Navigation.Endpoint.userId); RongIMLib.RongIMClient._storageProvider.removeItem(RongIMLib.Navigation.Endpoint.userId + "msgId"); this.onClose(); if (this.connected) { this.connected = false; var code = RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE; this.socket.fire("disconnect", code); } }; PollingTransportation.prototype.close = function () { this.xhr.abort(); this.sendxhr = null; }; return PollingTransportation; })(); RongIMLib.PollingTransportation = PollingTransportation; })(RongIMLib || (RongIMLib = {})); //objectname映射 var typeMapping = { "RC:TxtMsg": "TextMessage", "RC:ImgMsg": "ImageMessage", "RC:VcMsg": "VoiceMessage", "RC:ImgTextMsg": "RichContentMessage", "RC:ReferenceMsg": "ReferenceMessage", "RC:FileMsg": "FileMessage", "RC:HQVCMsg": "HQVoiceMessage", "RC:GIFMsg": "GIFMessage", "RC:SightMsg": "SightMessage", "RC:LBSMsg": "LocationMessage", "RC:InfoNtf": "InformationNotificationMessage", "RC:ContactNtf": "ContactNotificationMessage", "RC:ProfileNtf": "ProfileNotificationMessage", "RC:CmdNtf": "CommandNotificationMessage", "RC:DizNtf": "DiscussionNotificationMessage", "RC:CmdMsg": "CommandMessage", "RC:TypSts": "TypingStatusMessage", "RC:CsChaR": "ChangeModeResponseMessage", "RC:CsHsR": "HandShakeResponseMessage", "RC:CsEnd": "TerminateMessage", "RC:CsSp": "SuspendMessage", "RC:CsUpdate": "CustomerStatusUpdateMessage", "RC:ReadNtf": "ReadReceiptMessage", "RC:VCAccept": "AcceptMessage", "RC:VCRinging": "RingingMessage", "RC:VCSummary": "SummaryMessage", "RC:VCHangup": "HungupMessage", "RC:VCInvite": "InviteMessage", "RC:VCModifyMedia": "MediaModifyMessage", "RC:VCModifyMem": "MemberModifyMessage", "RC:CsContact": "CustomerContact", "RC:PSImgTxtMsg": "PublicServiceRichContentMessage", "RC:PSMultiImgTxtMsg": "PublicServiceMultiRichContentMessage", "RC:GrpNtf": "GroupNotificationMessage", "RC:PSCmd": "PublicServiceCommandMessage", "RC:RcCmd": "RecallCommandMessage", "RC:SRSMsg": "SyncReadStatusMessage", "RC:RRReqMsg": "ReadReceiptRequestMessage", "RC:RRRspMsg": "ReadReceiptResponseMessage", "RCJrmf:RpMsg": "JrmfRedPacketMessage", "RCJrmf:RpOpendMsg": "JrmfRedPacketOpenedMessage", "RC:CombineMsg": "RCCombineMessage", "RC:chrmKVNotiMsg": "ChrmKVNotificationMessage", "RC:LogCmdMsg": "LogCommandMessage" }, //自定义消息类型 registerMessageTypeMapping = {}, HistoryMsgType = { 4: "qryCMsg", 2: "qryDMsg", 3: "qryGMsg", 1: "qryPMsg", 6: "qrySMsg", 7: "qryPMsg", 8: "qryPMsg", 5: "qryCMsg" }, disconnectStatus = { 1: 6 }; var RongIMLib; (function (RongIMLib) { // 业务层公共方法处理 var IMHandler = (function () { function IMHandler() { } IMHandler.isIncludeNavi = function (token) { var navMarkIndex = RongIMLib.RongUtil.indexOf(token, RongIMLib.RongIMClient.NavMarkInToken); var hasNavMark = navMarkIndex !== -1; return hasNavMark; }; IMHandler.getToken = function (token) { var isIncludeNavi = IMHandler.isIncludeNavi(token); if (isIncludeNavi) { var navMarkIndex = RongIMLib.RongUtil.indexOf(token, RongIMLib.RongIMClient.NavMarkInToken); ; token = token.substring(0, navMarkIndex + 1); } return token; }; IMHandler.getNavsByToken = function (token, protocol) { var isIncludeNavi = IMHandler.isIncludeNavi(token); var navUrlList = []; if (isIncludeNavi) { var navMarkIndex = RongIMLib.RongUtil.indexOf(token, RongIMLib.RongIMClient.NavMarkInToken); ; var navsText = token.substring(navMarkIndex + 1, token.length); var navDomains = navsText.split(RongIMLib.RongIMClient.NavSeparatorInToken); RongIMLib.RongUtil.forEach(navDomains, function (domain) { if (RongIMLib.RongUtil.isEmpty(domain)) { return; } var navUrl = RongIMLib.RongUtil.formatProtoclPath({ path: domain, protocol: protocol, sub: true }); navUrlList.push(navUrl); }); } return navUrlList; }; IMHandler.getConversationKey = function (type, id) { return type + '_' + id; }; return IMHandler; })(); RongIMLib.IMHandler = IMHandler; ; /** * 通道标识类 */ var Transportations = (function () { function Transportations() { } Transportations._TransportType = RongIMLib.Socket.WEBSOCKET; return Transportations; })(); RongIMLib.Transportations = Transportations; var SyncTimeUtil = (function () { function SyncTimeUtil() { } SyncTimeUtil.$getKey = function (message) { var client = RongIMLib.Bridge._client; var userId = client.userId; var direction = (message.messageDirection == 1 ? 'send' : 'receive'); var appkey = RongIMLib.RongIMClient._memoryStore.appKey; var tpl = '{appkey}_{userId}_{direction}box'; return RongIMLib.RongUtil.tplEngine(tpl, { appkey: appkey, userId: userId, direction: direction }); }; SyncTimeUtil.set = function (message) { var key = SyncTimeUtil.$getKey(message); var sentTime = message.sentTime; var storage = RongIMLib.RongIMClient._storageProvider; storage.setItem(key, sentTime); // 向缓存中也设置拉消息时间戳 SyncTimeUtil._syncTimeCache[key] = sentTime; }; SyncTimeUtil.get = function () { var sent = SyncTimeUtil.$getKey({ messageDirection: RongIMLib.MessageDirection.SEND }); var received = SyncTimeUtil.$getKey({ messageDirection: RongIMLib.MessageDirection.RECEIVE }); /** * 先从缓存中获取时间戳,如果缓存中没有再从 localstorage 中取。 * 避免多端重连都从 localstorage 中取时间戳,重连成功时间不一致导致后重连的用户拉消息有断档情况 */ var pullMsgTimeBox = SyncTimeUtil._syncTimeCache; var storage = RongIMLib.RongIMClient._storageProvider; if (RongIMLib.RongUtil.isEmpty(pullMsgTimeBox)) { pullMsgTimeBox[sent] = storage.getItem(sent); pullMsgTimeBox[received] = storage.getItem(received); } return { sent: Number(pullMsgTimeBox[sent] || 0), received: Number(pullMsgTimeBox[received] || 0) }; }; SyncTimeUtil._syncTimeCache = {}; return SyncTimeUtil; })(); RongIMLib.SyncTimeUtil = SyncTimeUtil; var MessageUtil = (function () { function MessageUtil() { } /** *4680000 为localstorage最小容量5200000字节的90%,超过90%将删除之前过早的存储 */ MessageUtil.checkStorageSize = function () { return JSON.stringify(localStorage).length < 4680000; }; MessageUtil.getFirstKey = function (obj) { var str = ""; for (var key in obj) { str = key; break; } return str; }; MessageUtil.isEmpty = function (obj) { var empty = true; for (var key in obj) { empty = false; break; } return empty; }; MessageUtil.ArrayForm = function (typearray) { if (Object.prototype.toString.call(typearray) == "[object ArrayBuffer]") { var arr = new Int8Array(typearray); return [].slice.call(arr); } return typearray; }; MessageUtil.ArrayFormInput = function (typearray) { if (Object.prototype.toString.call(typearray) == "[object ArrayBuffer]") { var arr = new Uint8Array(typearray); return arr; } return typearray; }; MessageUtil.indexOf = function (arr, item, from) { for (var l = arr.length, i = (from < 0) ? Math.max(0, +from) : from || 0; i < l; i++) { if (arr[i] == item) { return i; } } return -1; }; MessageUtil.isArray = function (obj) { return Object.prototype.toString.call(obj) == "[object Array]"; }; //遍历,只能遍历数组 MessageUtil.forEach = function (arr, func) { if ([].forEach) { return function (arr, func) { [].forEach.call(arr, func); }; } else { return function (arr, func) { for (var i = 0; i < arr.length; i++) { func.call(arr, arr[i], i, arr); } }; } }; MessageUtil.remove = function (array, func) { for (var i = 0, len = array.length; i < len; i++) { if (func(array[i])) { return array.splice(i, 1)[0]; } } return null; }; MessageUtil.int64ToTimestamp = function (obj, isDate) { if (obj.low === undefined) { return obj; } var low = obj.low; if (low < 0) { low += 0xffffffff + 1; } low = low.toString(16); var timestamp = parseInt(obj.high.toString(16) + "00000000".replace(new RegExp("0{" + low.length + "}$"), low), 16); if (isDate) { return new Date(timestamp); } return timestamp; }; // 下行消息状态位判断, 第 9 位为 disableNotification 开关( 上行为第 5 位 ) MessageUtil.isDisableNotification = function (status) { return Boolean(status & 0x100); }; //消息转换方法 MessageUtil.messageParser = function (entity, onReceived, offlineMsg) { var message = new RongIMLib.Message(), content = entity.content, de, objectName = entity.classname, val, isUseDef = false; try { if (RongIMLib.RongIMClient._memoryStore.depend.isPolling) { val = new RongIMLib.BinaryHelper().readUTF(content.offset ? MessageUtil.ArrayForm(content.buffer).slice(content.offset, content.limit) : content); de = JSON.parse(val); } else { val = new RongIMLib.BinaryHelper().readUTF(content.offset ? MessageUtil.ArrayFormInput(content.buffer).subarray(content.offset, content.limit) : content); de = JSON.parse(val); } } catch (ex) { de = val; isUseDef = true; RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.L_PARSE_MSG_E, level: RongIMLib.LoggerLevel.E, type: RongIMLib.LoggerType.IM, content: { stack: ex, msg: 'MessageUtil -> messageParser' } }); } var IMLib = RongIMLib; //映射为具体消息对象 if (objectName in typeMapping) { var typeName = typeMapping[objectName]; message.content = new IMLib[typeName](de); message.messageType = typeMapping[objectName]; } else if (objectName in registerMessageTypeMapping) { var typeName = registerMessageTypeMapping[objectName]; var regMsg = new IMLib.RongIMClient.RegisterMessage[typeName](de); if (isUseDef) { message.content = regMsg.decode(de); } else { message.content = regMsg; } message.messageType = registerMessageTypeMapping[objectName]; } else { message.content = new RongIMLib.UnknownMessage({ content: de, objectName: objectName }); message.messageType = "UnknownMessage"; } //根据实体对象设置message对象] var dateTime = MessageUtil.int64ToTimestamp(entity.dataTime); if (dateTime > 0) { message.sentTime = dateTime; } else { message.sentTime = +new Date; } message.senderUserId = entity.fromUserId; message.conversationType = entity.type; if (entity.fromUserId == RongIMLib.Bridge._client.userId) { message.targetId = entity.groupId; } else { message.targetId = (/^[234]$/.test(entity.type || entity.getType()) ? entity.groupId : message.senderUserId); } var selfUserId = RongIMLib.Bridge._client.userId; // 解决多端在线收自己发的消息时, messageDirection 为 2(接收), 导致未读数增加 var isSelfSend = entity.direction == 1 || message.senderUserId === selfUserId; if (isSelfSend) { message.messageDirection = RongIMLib.MessageDirection.SEND; message.senderUserId = RongIMLib.Bridge._client.userId; } else { message.messageDirection = RongIMLib.MessageDirection.RECEIVE; } // 自己给自己发的消息, messageDirection 为 2(接收) var isSelfToSelf = message.senderUserId === selfUserId && message.targetId === selfUserId; if (isSelfToSelf) { message.messageDirection = RongIMLib.MessageDirection.RECEIVE; } var receivedTime = new Date().getTime(); message.messageUId = entity.msgId; message.receivedTime = RongIMLib.MessageUtil.getCheckedTime(receivedTime); message.messageId = (message.conversationType + "_" + ~~(Math.random() * 0xffffff)); message.objectName = objectName; message.receivedStatus = RongIMLib.ReceivedStatus.READ; if ((entity.status & 2) == 2) { message.receivedStatus = RongIMLib.ReceivedStatus.RETRIEVED; } message.offLineMessage = offlineMsg ? true : false; if (!offlineMsg) { if (RongIMLib.RongIMClient._memoryStore.connectAckTime > message.sentTime) { message.offLineMessage = true; } } try { var status = MessageUtil.int64ToTimestamp(entity.status); message.disableNotification = MessageUtil.isDisableNotification(status); } catch (error) { message.disableNotification = false; } return message; }; MessageUtil.detectCMP = function (options) { options.error = options.fail; return RongIMLib.RongUtil.request(options); }; MessageUtil.setDeltaTime = function (serverTime) { try { RongIMLib.RongIMClient._memoryStore.deltaTime = new Date().getTime() - serverTime; } catch (e) { } }; MessageUtil.getDeltaTime = function () { var _memoryStore = RongIMLib.RongIMClient._memoryStore || {}; return _memoryStore.deltaTime || 0; }; MessageUtil.getCheckedTime = function (time) { var deltaTime = MessageUtil.getDeltaTime(); return time - deltaTime; }; //适配SSL // static schemeArrs: Array = [["http", "ws"], ["https", "wss"]]; MessageUtil.sign = { converNum: 1, msgNum: 1, isMsgStart: true, isConvStart: true }; return MessageUtil; })(); RongIMLib.MessageUtil = MessageUtil; /** * 工具类 */ var MessageIdHandler = (function () { function MessageIdHandler() { } MessageIdHandler.init = function () { this.messageId = +(RongIMLib.RongIMClient._storageProvider.getItem(RongIMLib.Navigation.Endpoint.userId + "msgId") || RongIMLib.RongIMClient._storageProvider.setItem(RongIMLib.Navigation.Endpoint.userId + "msgId", 0) || 0); }; MessageIdHandler.messageIdPlus = function (method) { RongIMLib.RongIMClient._memoryStore.depend.isPolling && this.init(); if (this.messageId >= 65535) { this.messageId = 0; } this.messageId++; RongIMLib.RongIMClient._memoryStore.depend.isPolling && RongIMLib.RongIMClient._storageProvider.setItem(RongIMLib.Navigation.Endpoint.userId + "msgId", this.messageId); return this.messageId; }; MessageIdHandler.clearMessageId = function () { this.messageId = 0; RongIMLib.RongIMClient._memoryStore.depend.isPolling && RongIMLib.RongIMClient._storageProvider.setItem(RongIMLib.Navigation.Endpoint.userId + "msgId", this.messageId); }; MessageIdHandler.getMessageId = function () { RongIMLib.RongIMClient._memoryStore.depend.isPolling && this.init(); return this.messageId; }; MessageIdHandler.messageId = 0; return MessageIdHandler; })(); RongIMLib.MessageIdHandler = MessageIdHandler; var ChrmKVCaches = (function () { function ChrmKVCaches() { this.time = 0; this.cache = {}; } ChrmKVCaches.prototype.setTime = function (time) { this.time = time; }; ChrmKVCaches.prototype.getTime = function () { return this.time; }; ChrmKVCaches.prototype.setValue = function (kvContent) { var key = kvContent.key, timestamp = kvContent.timestamp; this.cache[key] = this.cache[key] || {}; this.cache[key] = { value: kvContent.value, userId: kvContent.userId, isDeleted: false, timestamp: timestamp }; }; ChrmKVCaches.prototype.removeValue = function (kvContent) { var key = kvContent.key, timestamp = kvContent.timestamp; this.cache[key] = this.cache[key] || {}; var cache = this.cache[key]; this.cache[key] = RongIMLib.RongUtil.extend(cache, { isDeleted: true, userId: kvContent.userId, timestamp: timestamp }); }; ChrmKVCaches.prototype.getValue = function (key) { this.cache[key] = this.cache[key] || {}; var cache = this.cache[key]; return cache.isDeleted ? null : cache.value; }; ChrmKVCaches.prototype.getAllKV = function () { var kv = {}; RongIMLib.RongUtil.forEach(this.cache, function (item, key) { if (!item.isDeleted) { kv[key] = item.value; } }); return kv; }; ChrmKVCaches.prototype.getSetUserId = function (key) { this.cache[key] = this.cache[key] || {}; return this.cache[key].userId; }; ChrmKVCaches.prototype.isKeyExisted = function (key) { this.cache[key] = this.cache[key] || {}; var cache = this.cache[key]; var hasValue = !RongIMLib.RongUtil.isEmpty(cache.value); return hasValue && !cache.isDeleted; }; ChrmKVCaches.prototype.clear = function () { this.cache = {}; }; return ChrmKVCaches; })(); var chrmKVCaches = {}; var chrmKVProsumerCaches = {}; var getKVCache = function (chrmId) { var chrmKVCache = chrmKVCaches[chrmId]; if (!chrmKVCache) { chrmKVCache = chrmKVCaches[chrmId] = new ChrmKVCaches(); } return chrmKVCache; }; var getKVProsumer = function (chrmId) { var kvProsumer = chrmKVProsumerCaches[chrmId]; if (!kvProsumer) { kvProsumer = chrmKVProsumerCaches[chrmId] = new RongIMLib.RongUtil.Prosumer(); } return kvProsumer; }; var ChrmKVHandler = (function () { function ChrmKVHandler() { } ChrmKVHandler.pull = function (chrmId, time) { var prosumer = getKVProsumer(chrmId); var event = RongIMLib.RongIMClient._dataAccessProvider.pullChatroomEntry; prosumer.produce({ event: event, chrmId: chrmId, time: time }); prosumer.consume(function (params, next) { var event = params.event, chrmId = params.chrmId, time = params.time; var kvCache = getKVCache(chrmId); var currentTime = kvCache.getTime(); var isKVNeedUpdated = currentTime < time; if (isKVNeedUpdated) { event(chrmId, currentTime, { onSuccess: function (result) { ChrmKVHandler.setEntries(chrmId, result); next(); }, onError: next }); } else { next(); } }); }; ChrmKVHandler.setEntries = function (chrmId, entity) { var entries = entity.entries, isFullUpdate = entity.bFullUpdate, syncTime = entity.syncTime; var event = isFullUpdate ? ChrmKVHandler.setFullEntries : ChrmKVHandler.setIncreEntries; var kvCache = getKVCache(chrmId); syncTime = MessageUtil.int64ToTimestamp(syncTime); if (RongIMLib.RongUtil.isArray(entries)) { RongIMLib.RongUtil.forEach(entries, function (item) { var setTime = item.timestamp; if (!RongIMLib.RongUtil.isNumber(setTime)) { item.timestamp = MessageUtil.int64ToTimestamp(setTime); } }); } kvCache.setTime(syncTime); // 更新拉取时间 event(chrmId, entries); // 更新 kv 值 }; ChrmKVHandler.setEntry = function (chrmId, chatroomEntry, status, userId) { var kvCache = getKVCache(chrmId); var timestamp = chatroomEntry.timestamp || +new Date(); var isDelete = RongInnerTools.getChrmEntityByStatus(status).isDelete; var eventName = isDelete ? 'removeValue' : 'setValue'; kvCache[eventName]({ key: chatroomEntry.key, value: chatroomEntry.value, userId: userId, timestamp: timestamp }); }; ChrmKVHandler.setFullEntries = function (chrmId, entries) { var kvCache = getKVCache(chrmId); kvCache.clear(); RongIMLib.RongUtil.forEach(entries, function (entity) { entity.timestamp = MessageUtil.int64ToTimestamp(entity.timestamp); kvCache.setValue({ key: entity.key, value: entity.value, userId: entity.uid, timestamp: entity.timestamp }); }); }; ChrmKVHandler.setIncreEntries = function (chrmId, entries) { var kvCache = getKVCache(chrmId); var currentUserId = RongIMLib.RongIMClient.getInstance().getCurrentUserId(); var optEvent = function (entity, isOverwrite, eventName) { var key = entity.key, value = entity.value; var isLatestedKeySetBySelf = kvCache.getSetUserId(key) === currentUserId; var isKeyNotExist = !kvCache.isKeyExisted(key); /* 1. 需覆盖时, 不管 key 是否已存在, 都直接设置 2. 不覆盖时, 必须最后一次 key 为自己设置的或此 key 还未设置过, 才能继续 */ if (isOverwrite || isLatestedKeySetBySelf || isKeyNotExist) { kvCache[eventName]({ key: key, value: value, userId: entity.uid, timestamp: entity.timestamp }); } }; RongIMLib.RongUtil.forEach(entries, function (entity) { var entityContent = RongInnerTools.getChrmEntityByStatus(entity.status); var eventName = entityContent.isDelete ? 'removeValue' : 'setValue'; optEvent(entity, entityContent.isOverwrite, eventName); }); }; ChrmKVHandler.getEntityValue = function (chrmId, key) { var kvCache = getKVCache(chrmId); return kvCache.getValue(key); }; ChrmKVHandler.getAllEntityValue = function (chrmId) { var kvCache = getKVCache(chrmId); return kvCache.getAllKV(); }; ChrmKVHandler.isKeyValid = function (key) { return /^[A-Za-z0-9_=+-]+$/.test(key); }; return ChrmKVHandler; })(); RongIMLib.ChrmKVHandler = ChrmKVHandler; var AutoDeleteCode = 0x0001; var OverwriteCode = 0x0002; var DeleteOperationCode = 0x0004; var RongInnerTools = (function () { function RongInnerTools() { } RongInnerTools.convertUserStatus = function (entity) { entity = RongIMLib.RongUtil.rename(entity, { subUserId: 'userId' }); var status = JSON.parse(entity.status); var us = status.us; if (!us) { return entity; } entity.status = RongIMLib.RongUtil.rename(us, { o: 'online', 'p': 'platform', s: 'status' }); return entity; }; RongInnerTools.getChrmEntityStatus = function (entity, chatroomOpt) { var status = 0; // 是否自动清理 if (entity.isAutoDelete) { status = status | AutoDeleteCode; } // 是否覆盖 if (entity.isOverwrite) { status = status | OverwriteCode; } // 操作类型 switch (chatroomOpt) { case RongIMLib.ChatroomEntityOpt.DELETE: status = status | DeleteOperationCode; break; default: break; } return status; }; RongInnerTools.getChrmEntityByStatus = function (status) { var isDelete = !!(status & DeleteOperationCode); var entityOpt = isDelete ? RongIMLib.ChatroomEntityOpt.DELETE : RongIMLib.ChatroomEntityOpt.UPDATE; return { isAutoDelete: !!(status & AutoDeleteCode), isOverwrite: !!(status & OverwriteCode), entityOpt: entityOpt, isDelete: isDelete }; }; return RongInnerTools; })(); RongIMLib.RongInnerTools = RongInnerTools; var UnreadCountHandler = (function () { function UnreadCountHandler() { } UnreadCountHandler.getKey = function (type, targetId) { var selfId = RongIMLib.RongIMClient.getInstance().getCurrentUserId(); return RongIMLib.RongUtil.tplEngine(UnreadCountHandler.KeyTemp, { selfId: selfId, type: type, targetId: targetId }); }; UnreadCountHandler.getDetailByKey = function (key) { var detail = { count: 0, sentTime: 0 }; var value = RongIMLib.RongIMClient._storageProvider.getItem(key); if (!value) { return detail; } value += ''; var unreadItems = value.split('_'); var hasUnderline = unreadItems.length > 1; detail.count = Number(unreadItems[0]); if (hasUnderline) { detail.sentTime = Number(unreadItems[1]); } return detail; }; UnreadCountHandler.getDetail = function (type, targetId) { var key = UnreadCountHandler.getKey(type, targetId); var detail = UnreadCountHandler.getDetailByKey(key); return detail; }; UnreadCountHandler.set = function (type, id, count, sentTime) { var key = UnreadCountHandler.getKey(type, id); var value = sentTime ? RongIMLib.RongUtil.tplEngine(UnreadCountHandler.ValueTemp, { count: count, sentTime: sentTime }) : count; RongIMLib.RongIMClient._storageProvider.setItem(key, value); return count; }; UnreadCountHandler.add = function (type, id, plusCount, sentTime) { var detail = UnreadCountHandler.getDetail(type, id), count = detail.count, oldSentTime = detail.sentTime; if (sentTime && sentTime > oldSentTime) { count = count + plusCount; UnreadCountHandler.set(type, id, count, sentTime); } return count; }; UnreadCountHandler.get = function (type, id) { var detail = UnreadCountHandler.getDetail(type, id); return detail.count; }; UnreadCountHandler.getAll = function (types) { var total = 0; var selfId = RongIMLib.RongIMClient.getInstance().getCurrentUserId(); var setTotal = function (keyList) { RongIMLib.RongUtil.forEach(keyList, function (key) { var detail = UnreadCountHandler.getDetailByKey(key); total += detail.count; }); }; if (types) { RongIMLib.RongUtil.forEach(types, function (type) { var key = UnreadCountHandler.getKey(type, ''); var unreadKeys = RongIMLib.RongIMClient._storageProvider.getItemKeyList(key); setTotal(unreadKeys); }); } else { var key = UnreadCountHandler.getKey('', ''); var unreadKeys = RongIMLib.RongIMClient._storageProvider.getItemKeyList(key); setTotal(unreadKeys); } return total; }; UnreadCountHandler.remove = function (type, targetId) { var key = UnreadCountHandler.getKey(type, targetId); RongIMLib.RongIMClient._storageProvider.removeItem(key); }; UnreadCountHandler.clear = function () { var key = UnreadCountHandler.getKey('', ''); var keyList = RongIMLib.RongIMClient._storageProvider.getItemKeyList(key); RongIMLib.RongUtil.forEach(keyList, function (key) { RongIMLib.RongIMClient._storageProvider.removeItem(key); }); }; UnreadCountHandler.KeyTemp = 'cu{selfId}{type}{targetId}'; UnreadCountHandler.ValueTemp = '{count}_{sentTime}'; return UnreadCountHandler; })(); RongIMLib.UnreadCountHandler = UnreadCountHandler; var ConversationStatusStoreUserKey = '{appkey}{userId}constas'; var ConversationStatusPullTimeStoreKey = 'time'; var ConversationStatusManager = (function () { function ConversationStatusManager(option) { this.updatedStatus = []; // 更新的会话状态 this.statusShangeObserver = new RongIMLib.Observer(); this.pullProsumer = new RongIMLib.RongUtil.Prosumer(); var appkey = option.appkey, userId = option.userId; this.option = option; this.storageKey = RongIMLib.RongUtil.tplEngine(ConversationStatusStoreUserKey, { appkey: appkey, userId: userId }); } ConversationStatusManager.prototype._formatUpdatedStatus = function (status, type, targetId) { var updatedStatus = { conversationType: type, targetId: targetId }; delete status.isLastInAPull; return RongIMLib.RongUtil.extend(updatedStatus, status); }; ConversationStatusManager.prototype.watchChanged = function (event) { this.statusShangeObserver.add(event); }; ConversationStatusManager.prototype.set = function (type, targetId, status) { var currentStatus = this.get(type, targetId); var updateTime = status.updateTime, isLastInAPull = status.isLastInAPull; if (updateTime >= currentStatus.updateTime) { var allStatus = RongIMLib.RongUtil.Storage.get(this.storageKey) || {}; var conversationStoreKey = IMHandler.getConversationKey(type, targetId); var storeStatus = allStatus[conversationStoreKey] || {}; RongIMLib.RongUtil.forEach(status, function (val, key) { if (!RongIMLib.RongUtil.isUndefined(val)) { storeStatus[key] = val; } }); allStatus[conversationStoreKey] = storeStatus; RongIMLib.RongUtil.Storage.set(this.storageKey, allStatus); var updatedStatusItem = this._formatUpdatedStatus(status, type, targetId); this.updatedStatus.push(updatedStatusItem); RongIMLib.RongIMClient.getInstance().pottingConversation({ type: type, userId: targetId }); } isLastInAPull && this.statusShangeObserver.emit(this.updatedStatus); this.updatedStatus = []; }; ConversationStatusManager.prototype.get = function (type, targetId) { var allStatus = RongIMLib.RongUtil.Storage.get(this.storageKey) || {}; var conversationStoreKey = IMHandler.getConversationKey(type, targetId); var status = allStatus[conversationStoreKey] || {}; var notificationStatus = status.notificationStatus, isTop = status.isTop, updateTime = status.updateTime; return { notificationStatus: notificationStatus || RongIMLib.ConversationNotificationStatus.NOTIFY, isTop: isTop || false, updateTime: updateTime || 0 }; }; ConversationStatusManager.prototype.pull = function (option) { if (RongIMLib.RongIMClient._memoryStore.depend.isPolling) return; //长轮训关闭会话状态设置 option = option || {}; var self = this; var _a = this, server = _a.option.server, pullProsumer = _a.pullProsumer, storageKey = _a.storageKey; pullProsumer.produce(option); pullProsumer.consume(function (params, next) { var allStatus = RongIMLib.RongUtil.Storage.get(storageKey) || {}; var lastUpdateTime = allStatus[ConversationStatusPullTimeStoreKey] || 0; var updateTime = params.time, isForce = params.isForce; if (lastUpdateTime > updateTime && !isForce) { return next(); } server.pullConversationStatus(lastUpdateTime, { onStatus: function (type, id, conversationStatus) { self.set(type, id, conversationStatus); }, onSuccess: function (updateTime) { var allStatus = RongIMLib.RongUtil.Storage.get(storageKey) || {}; allStatus[ConversationStatusPullTimeStoreKey] = updateTime; // 更新拉取时间戳 RongIMLib.RongUtil.Storage.set(self.storageKey, allStatus); next(); }, onError: next }); }); }; return ConversationStatusManager; })(); RongIMLib.ConversationStatusManager = ConversationStatusManager; var FixedNaviRespHandler = (function () { function FixedNaviRespHandler() { } FixedNaviRespHandler.modifyVoipCallInfoByAppKey = function () { var me = this; try { var naviResp = me.baseResp; var appKey = RongIMLib.RongIMClient._memoryStore.appKey; var voipCallInfo = naviResp.voipCallInfo; var parseVoipCallInfo = JSON.parse(voipCallInfo); RongIMLib.RongUtil.forEach(parseVoipCallInfo.callEngine, function (item) { if (item.engineType === 3) { item.vendorKey = appKey; } }); var jsonVoipCallInfo = JSON.stringify(parseVoipCallInfo); naviResp.voipCallInfo = jsonVoipCallInfo; } catch (error) { } return naviResp; }; FixedNaviRespHandler.modifyCmpByProtocol = function () { var me = this; var protocol = RongIMLib.RongIMClient._memoryStore.depend.protocol; var isHTTP = protocol === RongIMLib.RongIMClient.HttpProtocol.http; var cmpHost = isHTTP ? me.preparedCMP.WS : me.preparedCMP.WSS; me.baseResp.backupServer = cmpHost; }; FixedNaviRespHandler.genUserId = function () { var token = RongIMLib.RongIMClient._memoryStore.token; var uid = RongIMLib.InnerUtil.getUId(token); return uid; }; FixedNaviRespHandler.getResp = function () { var me = this; me.modifyCmpByProtocol(); var naviResp = me.modifyVoipCallInfoByAppKey(); naviResp.userId = me.genUserId(); return naviResp; }; FixedNaviRespHandler.baseResp = { isFixedNaviResp: true, code: 200, userId: '', server: '', backupServer: '', voipCallInfo: '{"strategy":1,"callEngine":[{"engineType":4,"mediaServer":"https://rtc-info.ronghub.com","maxStreamCount":20},{"engineType":3,"vendorKey":"","signKey":"","blinkCMPServer":"rtccmp.ronghub.com:80","blinkSnifferServer":"rtccmp.ronghub.com:80"}]}', kvStorage: 1, uploadServer: 'upload.qiniup.com', openMp: 1, openUS: 1, logSwitch: 1, logPolicy: '{"url": "logcollection.ronghub.com","level": 1,"itv": 6,"times": 5}', bosAddr: 'gz.bcebos.com' }; FixedNaviRespHandler.preparedCMP = { WSS: 'wsap-cn.ronghub.com:443', WS: 'wsap-cn.ronghub.com:80' }; return FixedNaviRespHandler; })(); RongIMLib.FixedNaviRespHandler = FixedNaviRespHandler; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var MessageContent = (function () { function MessageContent(data) { throw new Error("This method is abstract, you must implement this method in inherited class."); } MessageContent.obtain = function () { throw new Error("This method is abstract, you must implement this method in inherited class."); }; return MessageContent; })(); RongIMLib.MessageContent = MessageContent; var NotificationMessage = (function (_super) { __extends(NotificationMessage, _super); function NotificationMessage() { _super.apply(this, arguments); } return NotificationMessage; })(MessageContent); RongIMLib.NotificationMessage = NotificationMessage; var StatusMessage = (function (_super) { __extends(StatusMessage, _super); function StatusMessage() { _super.apply(this, arguments); } return StatusMessage; })(MessageContent); RongIMLib.StatusMessage = StatusMessage; var ModelUtil = (function () { function ModelUtil() { } ModelUtil.modelClone = function (object) { var obj = {}; for (var item in object) { if (item != "messageName" && "encode" != item) { obj[item] = object[item]; } } return obj; }; ModelUtil.modleCreate = function (fields, msgType) { // if (fields.length < 1) { // throw new Error("Array is empty -> registerMessageType.modleCreate"); // } var Object = function (message) { var me = this; for (var index in fields) { me[fields[index]] = message[fields[index]]; } Object.prototype.messageName = msgType; Object.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; }; return Object; }; return ModelUtil; })(); RongIMLib.ModelUtil = ModelUtil; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var CustomerStatusMessage = (function () { function CustomerStatusMessage(message) { this.messageName = "CustomerStatusMessage"; this.status = message.status; } CustomerStatusMessage.obtain = function () { return null; }; CustomerStatusMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return CustomerStatusMessage; })(); RongIMLib.CustomerStatusMessage = CustomerStatusMessage; /** * 客服转换响应消息的类型名 */ var ChangeModeResponseMessage = (function () { function ChangeModeResponseMessage(message) { this.messageName = "ChangeModeResponseMessage"; this.code = message.code; this.data = message.data; this.msg = message.msg; } ChangeModeResponseMessage.obtain = function () { return null; }; ChangeModeResponseMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ChangeModeResponseMessage; })(); RongIMLib.ChangeModeResponseMessage = ChangeModeResponseMessage; /** * 客服转换消息的类型名 * 此消息不计入未读消息数 */ var ChangeModeMessage = (function () { function ChangeModeMessage(message) { this.messageName = "ChangeModeMessage"; this.uid = message.uid; this.sid = message.sid; this.pid = message.pid; } ChangeModeMessage.obtain = function () { return null; }; ChangeModeMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ChangeModeMessage; })(); RongIMLib.ChangeModeMessage = ChangeModeMessage; var CustomerStatusUpdateMessage = (function () { function CustomerStatusUpdateMessage(message) { this.messageName = "CustomerStatusUpdateMessage"; this.serviceStatus = message.serviceStatus; this.sid = message.sid; } CustomerStatusUpdateMessage.obtain = function () { return null; }; CustomerStatusUpdateMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return CustomerStatusUpdateMessage; })(); RongIMLib.CustomerStatusUpdateMessage = CustomerStatusUpdateMessage; var HandShakeMessage = (function () { function HandShakeMessage(message) { this.messageName = "HandShakeMessage"; if (message) { this.requestInfo = message.requestInfo; this.userInfo = message.userInfo; } } HandShakeMessage.obtain = function () { return null; }; HandShakeMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return HandShakeMessage; })(); RongIMLib.HandShakeMessage = HandShakeMessage; var CustomerContact = (function () { function CustomerContact(message) { this.messageName = "CustomerContact"; this.page = message.page; this.nickName = message.nickName; this.routingInfo = message.routingInfo; this.info = message.info; this.requestInfo = message.requestInfo; } CustomerContact.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return CustomerContact; })(); RongIMLib.CustomerContact = CustomerContact; var EvaluateMessage = (function () { function EvaluateMessage(message) { this.messageName = "EvaluateMessage"; this.uid = message.uid; this.sid = message.sid; this.pid = message.pid; this.source = message.source; this.suggest = message.suggest; this.isresolve = message.isresolve; this.type = message.type; } EvaluateMessage.obtain = function () { return null; }; EvaluateMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return EvaluateMessage; })(); RongIMLib.EvaluateMessage = EvaluateMessage; /** * 客服握手响应消息的类型名 */ var HandShakeResponseMessage = (function () { function HandShakeResponseMessage(message) { this.messageName = "HandShakeResponseMessage"; this.msg = message.msg; this.status = message.status; this.data = message.data; } HandShakeResponseMessage.obtain = function () { return null; }; HandShakeResponseMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return HandShakeResponseMessage; })(); RongIMLib.HandShakeResponseMessage = HandShakeResponseMessage; var SuspendMessage = (function () { function SuspendMessage(message) { this.messageName = "SuspendMessage"; this.uid = message.uid; this.sid = message.sid; this.pid = message.pid; } SuspendMessage.obtain = function () { return null; }; SuspendMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return SuspendMessage; })(); RongIMLib.SuspendMessage = SuspendMessage; var TerminateMessage = (function () { function TerminateMessage(message) { this.messageName = "TerminateMessage"; this.code = message.code; this.msg = message.msg; this.sid = message.sid; } TerminateMessage.obtain = function () { return null; }; TerminateMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return TerminateMessage; })(); RongIMLib.TerminateMessage = TerminateMessage; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var IsTypingStatusMessage = (function () { function IsTypingStatusMessage(data) { this.messageName = "IsTypingStatusMessage"; var msg = data; } IsTypingStatusMessage.prototype.encode = function () { return undefined; }; IsTypingStatusMessage.prototype.getMessage = function () { return null; }; return IsTypingStatusMessage; })(); RongIMLib.IsTypingStatusMessage = IsTypingStatusMessage; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var InformationNotificationMessage = (function () { function InformationNotificationMessage(message) { this.messageName = "InformationNotificationMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> InformationNotificationMessage."); } this.message = message.message; this.extra = message.extra; if (message.user) { this.user = message.user; } } InformationNotificationMessage.obtain = function (message) { return new InformationNotificationMessage({ message: message, extra: "" }); }; InformationNotificationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return InformationNotificationMessage; })(); RongIMLib.InformationNotificationMessage = InformationNotificationMessage; var CommandMessage = (function () { function CommandMessage(message) { this.messageName = "CommandMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> CommandMessage."); } try { if (Object.prototype.toString.call(message.data) == "[object String]") { this.data = JSON.parse(message.data); } else { this.data = message.data; } } catch (e) { this.data = message.data; RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.A_INIT_CMD_MSG_E, level: RongIMLib.LoggerLevel.E, type: RongIMLib.LoggerType.IM, content: { stack: e, msg: message.data } }); } this.name = message.name; this.extra = message.extra; } CommandMessage.obtain = function (data) { return new CommandMessage({ data: data, extra: "" }); }; CommandMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return CommandMessage; })(); RongIMLib.CommandMessage = CommandMessage; var ContactNotificationMessage = (function () { function ContactNotificationMessage(message) { this.messageName = "ContactNotificationMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> ContactNotificationMessage."); } this.operation = message.operation; this.targetUserId = message.targetUserId; this.message = message.message; this.extra = message.extra; this.sourceUserId = message.sourceUserId; if (message.user) { this.user = message.user; } } ContactNotificationMessage.obtain = function (operation, sourceUserId, targetUserId, message) { return new InformationNotificationMessage({ operation: operation, sourceUserId: sourceUserId, targetUserId: targetUserId, message: message }); }; ContactNotificationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; ContactNotificationMessage.CONTACT_OPERATION_ACCEPT_RESPONSE = "ContactOperationAcceptResponse"; ContactNotificationMessage.CONTACT_OPERATION_REJECT_RESPONSE = "ContactOperationRejectResponse"; ContactNotificationMessage.CONTACT_OPERATION_REQUEST = "ContactOperationRequest"; return ContactNotificationMessage; })(); RongIMLib.ContactNotificationMessage = ContactNotificationMessage; var ProfileNotificationMessage = (function () { function ProfileNotificationMessage(message) { this.messageName = "ProfileNotificationMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> ProfileNotificationMessage."); } this.operation = message.operation; try { if (Object.prototype.toString.call(message.data) == "[object String]") { this.data = JSON.parse(message.data); } else { this.data = message.data; } } catch (e) { this.data = message.data; RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.A_INIT_PROFILE_MSG_E, level: RongIMLib.LoggerLevel.E, type: RongIMLib.LoggerType.IM, content: { stack: e, msg: message.data } }); } this.extra = message.extra; if (message.user) { this.user = message.user; } } ProfileNotificationMessage.obtain = function (operation, data) { return new ProfileNotificationMessage({ operation: operation, data: data }); }; ProfileNotificationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ProfileNotificationMessage; })(); RongIMLib.ProfileNotificationMessage = ProfileNotificationMessage; var CommandNotificationMessage = (function () { function CommandNotificationMessage(message) { this.messageName = "CommandNotificationMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> ProfileNotificationMessage."); } try { if (Object.prototype.toString.call(message.data) == "[object String]") { this.data = JSON.parse(message.data); } else { this.data = message.data; } } catch (e) { this.data = message.data; RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.A_INIT_CMD_NOTI_MSG_E, level: RongIMLib.LoggerLevel.E, type: RongIMLib.LoggerType.IM, content: { stack: e, msg: message.data } }); } this.name = message.name; this.extra = message.extra; if (message.user) { this.user = message.user; } } CommandNotificationMessage.obtain = function (name, data) { return new CommandNotificationMessage({ name: name, data: data, extra: "" }); }; CommandNotificationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return CommandNotificationMessage; })(); RongIMLib.CommandNotificationMessage = CommandNotificationMessage; var DiscussionNotificationMessage = (function () { function DiscussionNotificationMessage(message) { this.messageName = "DiscussionNotificationMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> DiscussionNotificationMessage."); } this.extra = message.extra; this.extension = message.extension; this.type = message.type; this.isHasReceived = message.isHasReceived; this.operation = message.operation; this.user = message.user; if (message.user) { this.user = message.user; } } DiscussionNotificationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return DiscussionNotificationMessage; })(); RongIMLib.DiscussionNotificationMessage = DiscussionNotificationMessage; var GroupNotificationMessage = (function () { function GroupNotificationMessage(msg) { this.messageName = "GroupNotificationMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> GroupNotificationMessage."); } msg.operatorUserId && (this.operatorUserId = msg.operatorUserId); msg.operation && (this.operation = msg.operation); msg.data && (this.data = msg.data); msg.message && (this.message = msg.message); msg.extra && (this.extra = msg.extra); } GroupNotificationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return GroupNotificationMessage; })(); RongIMLib.GroupNotificationMessage = GroupNotificationMessage; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var TextMessage = (function () { function TextMessage(message) { this.messageName = "TextMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> TextMessage."); } this.content = message.content; this.extra = message.extra; if (message.user) { this.user = message.user; } if (message.mentionedInfo) { this.mentionedInfo = message.mentionedInfo; } if (message.burnDuration) { this.burnDuration = message.burnDuration; } } TextMessage.obtain = function (text) { return new TextMessage({ extra: "", content: text }); }; TextMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return TextMessage; })(); RongIMLib.TextMessage = TextMessage; var TypingStatusMessage = (function () { function TypingStatusMessage(message) { this.messageName = "TypingStatusMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> TypingStatusMessage."); } this.typingContentType = message.typingContentType; this.data = message.data; } TypingStatusMessage.obtain = function (typingContentType, data) { return new TypingStatusMessage({ typingContentType: typingContentType, data: data }); }; TypingStatusMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return TypingStatusMessage; })(); RongIMLib.TypingStatusMessage = TypingStatusMessage; var ReadReceiptMessage = (function () { function ReadReceiptMessage(message) { this.messageName = "ReadReceiptMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> ReadReceiptMessage."); } this.lastMessageSendTime = message.lastMessageSendTime; this.messageUId = message.messageUId; this.type = message.type; } ReadReceiptMessage.obtain = function (messageUId, lastMessageSendTime, type) { return new ReadReceiptMessage({ messageUId: messageUId, lastMessageSendTime: lastMessageSendTime, type: type }); }; ReadReceiptMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ReadReceiptMessage; })(); RongIMLib.ReadReceiptMessage = ReadReceiptMessage; var VoiceMessage = (function () { function VoiceMessage(message) { this.messageName = "VoiceMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> VoiceMessage."); } this.content = message.content; this.duration = message.duration; this.extra = message.extra; if (message.user) { this.user = message.user; } if (message.mentionedInfo) { this.mentionedInfo = message.mentionedInfo; } if (message.burnDuration) { this.burnDuration = message.burnDuration; } } VoiceMessage.obtain = function (base64Content, duration) { return new VoiceMessage({ content: base64Content, duration: duration, extra: "" }); }; VoiceMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return VoiceMessage; })(); RongIMLib.VoiceMessage = VoiceMessage; var RecallCommandMessage = (function () { function RecallCommandMessage(message) { this.messageName = "RecallCommandMessage"; this.messageUId = message.messageUId; this.conversationType = message.conversationType; this.targetId = message.targetId; this.sentTime = message.sentTime; message.extra && (this.extra = message.extra); message.user && (this.user = message.user); } RecallCommandMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return RecallCommandMessage; })(); RongIMLib.RecallCommandMessage = RecallCommandMessage; var ImageMessage = (function () { function ImageMessage(message) { this.messageName = "ImageMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> ImageMessage."); } this.content = message.content; this.imageUri = message.imageUri; message.extra && (this.extra = message.extra); message.user && (this.user = message.user); if (message.mentionedInfo) { this.mentionedInfo = message.mentionedInfo; } if (message.burnDuration) { this.burnDuration = message.burnDuration; } } ImageMessage.obtain = function (content, imageUri) { return new ImageMessage({ content: content, imageUri: imageUri, extra: "" }); }; ImageMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ImageMessage; })(); RongIMLib.ImageMessage = ImageMessage; var LocationMessage = (function () { function LocationMessage(message) { this.messageName = "LocationMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> LocationMessage."); } this.latitude = message.latitude; this.longitude = message.longitude; this.poi = message.poi; this.content = message.content; this.extra = message.extra; if (message.user) { this.user = message.user; } if (message.mentionedInfo) { this.mentionedInfo = message.mentionedInfo; } } LocationMessage.obtain = function (latitude, longitude, poi, content) { return new LocationMessage({ latitude: latitude, longitude: longitude, poi: poi, content: content, extra: "" }); }; LocationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return LocationMessage; })(); RongIMLib.LocationMessage = LocationMessage; var RichContentMessage = (function () { function RichContentMessage(message) { this.messageName = "RichContentMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> RichContentMessage."); } this.title = message.title; this.content = message.content; this.imageUri = message.imageUri; this.extra = message.extra; this.url = message.url; if (message.user) { this.user = message.user; } } RichContentMessage.obtain = function (title, content, imageUri, url) { return new RichContentMessage({ title: title, content: content, imageUri: imageUri, url: url, extra: "" }); }; RichContentMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return RichContentMessage; })(); RongIMLib.RichContentMessage = RichContentMessage; var JrmfRedPacketMessage = (function () { function JrmfRedPacketMessage(message) { this.messageName = 'JrmfRedPacketMessage'; message && (this.message = message); } JrmfRedPacketMessage.prototype.encode = function () { return ""; }; return JrmfRedPacketMessage; })(); RongIMLib.JrmfRedPacketMessage = JrmfRedPacketMessage; var JrmfRedPacketOpenedMessage = (function () { function JrmfRedPacketOpenedMessage(message) { this.messageName = 'JrmfRedPacketOpenedMessage'; message && (this.message = message); } JrmfRedPacketOpenedMessage.prototype.encode = function () { return ""; }; return JrmfRedPacketOpenedMessage; })(); RongIMLib.JrmfRedPacketOpenedMessage = JrmfRedPacketOpenedMessage; var UnknownMessage = (function () { function UnknownMessage(message) { this.messageName = "UnknownMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> UnknownMessage."); } this.message = message; } UnknownMessage.prototype.encode = function () { return ""; }; return UnknownMessage; })(); RongIMLib.UnknownMessage = UnknownMessage; var PublicServiceCommandMessage = (function () { function PublicServiceCommandMessage(message) { this.messageName = "PublicServiceCommandMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> PublicServiceCommandMessage."); } this.content = message.content; this.extra = message.extra; this.menuItem = message.menuItem; if (message.user) { this.user = message.user; } if (message.mentionedInfo) { this.mentionedInfo = message.mentionedInfo; } } PublicServiceCommandMessage.obtain = function (item) { return new PublicServiceCommandMessage({ content: "", command: "", menuItem: item, extra: "" }); }; PublicServiceCommandMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return PublicServiceCommandMessage; })(); RongIMLib.PublicServiceCommandMessage = PublicServiceCommandMessage; var PublicServiceMultiRichContentMessage = (function () { function PublicServiceMultiRichContentMessage(messages) { this.messageName = "PublicServiceMultiRichContentMessage"; this.richContentMessages = messages; } PublicServiceMultiRichContentMessage.prototype.encode = function () { return null; }; return PublicServiceMultiRichContentMessage; })(); RongIMLib.PublicServiceMultiRichContentMessage = PublicServiceMultiRichContentMessage; var SyncReadStatusMessage = (function () { function SyncReadStatusMessage(message) { this.messageName = "SyncReadStatusMessage"; message.lastMessageSendTime && (this.lastMessageSendTime = message.lastMessageSendTime); } SyncReadStatusMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return SyncReadStatusMessage; })(); RongIMLib.SyncReadStatusMessage = SyncReadStatusMessage; var ReadReceiptRequestMessage = (function () { function ReadReceiptRequestMessage(message) { this.messageName = "ReadReceiptRequestMessage"; message.messageUId && (this.messageUId = message.messageUId); } ReadReceiptRequestMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ReadReceiptRequestMessage; })(); RongIMLib.ReadReceiptRequestMessage = ReadReceiptRequestMessage; var ReadReceiptResponseMessage = (function () { function ReadReceiptResponseMessage(message) { this.messageName = "ReadReceiptResponseMessage"; message.receiptMessageDic && (this.receiptMessageDic = message.receiptMessageDic); } ReadReceiptResponseMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ReadReceiptResponseMessage; })(); RongIMLib.ReadReceiptResponseMessage = ReadReceiptResponseMessage; var PublicServiceRichContentMessage = (function () { function PublicServiceRichContentMessage(message) { this.messageName = "PublicServiceRichContentMessage"; this.richContentMessage = message; } PublicServiceRichContentMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return PublicServiceRichContentMessage; })(); RongIMLib.PublicServiceRichContentMessage = PublicServiceRichContentMessage; var FileMessage = (function () { function FileMessage(message) { this.messageName = "FileMessage"; message.name && (this.name = message.name); message.size && (this.size = message.size); message.type && (this.type = message.type); message.fileUrl && (this.fileUrl = message.fileUrl); message.extra && (this.extra = message.extra); message.user && (this.user = message.user); } FileMessage.obtain = function (msg) { return new FileMessage({ name: msg.name, size: msg.size, type: msg.type, fileUrl: msg.fileUrl }); }; FileMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return FileMessage; })(); RongIMLib.FileMessage = FileMessage; var HQVoiceMessage = (function () { function HQVoiceMessage(message) { this.messageName = "HQVoiceMessage"; this.type = message.type || 'aac'; message.localPath && (this.localPath = message.localPath); message.remoteUrl && (this.remoteUrl = message.remoteUrl); message.duration && (this.duration = message.duration); message.extra && (this.extra = message.extra); message.user && (this.user = message.user); message.burnDuration && (this.burnDuration = message.burnDuration); } HQVoiceMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return HQVoiceMessage; })(); RongIMLib.HQVoiceMessage = HQVoiceMessage; var AcceptMessage = (function () { function AcceptMessage(message) { this.messageName = "AcceptMessage"; this.mediaId = message.mediaId; this.callId = message.callId; this.mediaType = message.mediaType; this.mode = message.mode; this.subInfo = message.subInfo; } AcceptMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return AcceptMessage; })(); RongIMLib.AcceptMessage = AcceptMessage; var RingingMessage = (function () { function RingingMessage(message) { this.messageName = "RingingMessage"; this.callId = message.callId; } RingingMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return RingingMessage; })(); RongIMLib.RingingMessage = RingingMessage; var SummaryMessage = (function () { function SummaryMessage(message) { this.messageName = "SummaryMessage"; this.caller = message.caller; this.inviter = message.inviter; this.mediaType = message.mediaType; this.memberIdList = message.memberIdList; this.startTime = message.startTime; this.connectedTime = message.connectedTime; this.duration = message.duration; this.status = message.status; } SummaryMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return SummaryMessage; })(); RongIMLib.SummaryMessage = SummaryMessage; var HungupMessage = (function () { function HungupMessage(message) { this.messageName = "HungupMessage"; this.callId = message.callId; this.reason = message.reason; this.mode = message.mode; this.subInfo = message.subInfo; } HungupMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return HungupMessage; })(); RongIMLib.HungupMessage = HungupMessage; var InviteMessage = (function () { function InviteMessage(message) { this.messageName = "InviteMessage"; this.mediaId = message.mediaId; this.callId = message.callId; this.engineType = message.engineType; this.channelInfo = message.channelInfo; this.mediaType = message.mediaType; this.extra = message.extra; this.inviteUserIds = message.inviteUserIds; this.observerUserIds = message.observerUserIds; this.mode = message.mode; this.subInfo = message.subInfo; } InviteMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return InviteMessage; })(); RongIMLib.InviteMessage = InviteMessage; var MediaModifyMessage = (function () { function MediaModifyMessage(message) { this.messageName = "MediaModifyMessage"; this.callId = message.callId; this.mediaType = message.mediaType; this.mode = message.mode; this.subInfo = message.subInfo; } MediaModifyMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return MediaModifyMessage; })(); RongIMLib.MediaModifyMessage = MediaModifyMessage; var MemberModifyMessage = (function () { function MemberModifyMessage(message) { this.messageName = "MemberModifyMessage"; this.modifyMemType = message.modifyMemType; this.callId = message.callId; this.caller = message.caller; this.engineType = message.engineType; this.channelInfo = message.channelInfo; this.mediaType = message.mediaType; this.extra = message.extra; this.inviteUserIds = message.inviteUserIds; this.existedMemberStatusList = message.existedMemberStatusList; this.existedUserPofiles = message.existedUserPofiles; this.observerUserIds = message.observerUserIds; this.mode = message.mode; this.subInfo = message.subInfo; } MemberModifyMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return MemberModifyMessage; })(); RongIMLib.MemberModifyMessage = MemberModifyMessage; var RCCombineMessage = (function () { function RCCombineMessage(message) { this.messageName = "RCCombineMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> RCCombineMessage."); } this.nameList = message.nameList; this.remoteUrl = message.remoteUrl; if (message.user) { this.user = message.user; } this.conversationType = message.conversationType; this.summaryList = message.summaryList; } RCCombineMessage.obtain = function (remoteUrl, nameList, summaryList, conversationType) { return new RCCombineMessage({ extra: "", content: remoteUrl, nameList: nameList, summaryList: summaryList, conversationType: conversationType }); }; RCCombineMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return RCCombineMessage; })(); RongIMLib.RCCombineMessage = RCCombineMessage; var ChrmKVNotificationMessage = (function () { function ChrmKVNotificationMessage(message) { this.messageName = "ChrmKVNotificationMessage"; message.key && (this.key = message.key); message.value && (this.value = message.value); message.type && (this.type = message.type); message.extra && (this.extra = message.extra); message.user && (this.user = message.user); } ChrmKVNotificationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ChrmKVNotificationMessage; })(); RongIMLib.ChrmKVNotificationMessage = ChrmKVNotificationMessage; var LogCommandMessage = (function () { function LogCommandMessage(message) { this.messageName = "LogCommandMessage"; message.uri && (this.uri = message.uri); message.logId && (this.logId = message.logId); message.platform && (this.platform = message.platform); message.packageName && (this.packageName = message.packageName); message.startTime && (this.startTime = message.startTime); message.endTime && (this.endTime = message.endTime); message.user && (this.user = message.user); } LogCommandMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return LogCommandMessage; })(); RongIMLib.LogCommandMessage = LogCommandMessage; var ReferenceMessage = (function () { function ReferenceMessage(message) { this.messageName = "ReferenceMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> ReferenceMessage."); } this.content = message.content; this.referMsgUserId = message.referMsgUserId; this.referMsg = message.referMsg; this.objName = message.objName; if (message.user) { this.user = message.user; } if (message.mentionedInfo) { this.mentionedInfo = message.mentionedInfo; } } ReferenceMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ReferenceMessage; })(); RongIMLib.ReferenceMessage = ReferenceMessage; var GIFMessage = (function () { function GIFMessage(message) { this.messageName = "GIFMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> ReferenceMessage."); } this.gifDataSize = message.gifDataSize; this.localPath = message.localPath; this.remoteUrl = message.remoteUrl; this.width = message.width; this.height = message.height; if (message.user) { this.user = message.user; } if (message.mentionedInfo) { this.mentionedInfo = message.mentionedInfo; } } GIFMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return GIFMessage; })(); RongIMLib.GIFMessage = GIFMessage; var SightMessage = (function () { function SightMessage(message) { this.messageName = "SightMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> ReferenceMessage."); } this.sightUrl = message.sightUrl; this.content = message.content; this.duration = message.duration; this.size = message.size; this.name = message.name; if (message.user) { this.user = message.user; } if (message.mentionedInfo) { this.mentionedInfo = message.mentionedInfo; } } SightMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return SightMessage; })(); RongIMLib.SightMessage = SightMessage; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var ChannelInfo = (function () { function ChannelInfo(Id, Key) { this.Id = Id; this.Key = Key; } return ChannelInfo; })(); RongIMLib.ChannelInfo = ChannelInfo; var UserStatus = (function () { function UserStatus(platform, online, status) { this.platform = platform; this.online = online; this.status = status; } return UserStatus; })(); RongIMLib.UserStatus = UserStatus; var MentionedInfo = (function () { function MentionedInfo(type, userIdList, mentionedContent) { } return MentionedInfo; })(); RongIMLib.MentionedInfo = MentionedInfo; var DeleteMessage = (function () { function DeleteMessage(msgId, msgDataTime, direct) { this.msgId = msgId; this.msgDataTime = msgDataTime; this.direct = direct; } return DeleteMessage; })(); RongIMLib.DeleteMessage = DeleteMessage; var CustomServiceConfig = (function () { function CustomServiceConfig(isBlack, companyName, companyUrl) { } return CustomServiceConfig; })(); RongIMLib.CustomServiceConfig = CustomServiceConfig; var CustomServiceSession = (function () { function CustomServiceSession(uid, cid, pid, isQuited, type, adminHelloWord, adminOfflineWord) { } return CustomServiceSession; })(); RongIMLib.CustomServiceSession = CustomServiceSession; var Conversation = (function () { function Conversation(conversationTitle, conversationType, draft, isTop, latestMessage, latestMessageId, notificationStatus, objectName, receivedStatus, receivedTime, senderUserId, senderUserName, sentStatus, sentTime, targetId, unreadMessageCount, senderPortraitUri, isHidden, mentionedMsg, hasUnreadMention, _readTime) { this.conversationTitle = conversationTitle; this.conversationType = conversationType; this.draft = draft; this.isTop = isTop; this.latestMessage = latestMessage; this.latestMessageId = latestMessageId; this.notificationStatus = notificationStatus; this.objectName = objectName; this.receivedStatus = receivedStatus; this.receivedTime = receivedTime; this.senderUserId = senderUserId; this.senderUserName = senderUserName; this.sentStatus = sentStatus; this.sentTime = sentTime; this.targetId = targetId; this.unreadMessageCount = unreadMessageCount; this.senderPortraitUri = senderPortraitUri; this.isHidden = isHidden; this.mentionedMsg = mentionedMsg; this.hasUnreadMention = hasUnreadMention; this._readTime = _readTime; } Conversation.prototype.setTop = function () { RongIMLib.RongIMClient._dataAccessProvider.addConversation(this, { onSuccess: function (data) { } }); }; return Conversation; })(); RongIMLib.Conversation = Conversation; var Discussion = (function () { function Discussion(creatorId, id, memberIdList, name, isOpen) { this.creatorId = creatorId; this.id = id; this.memberIdList = memberIdList; this.name = name; this.isOpen = isOpen; } return Discussion; })(); RongIMLib.Discussion = Discussion; var Group = (function () { function Group(id, name, portraitUri) { this.id = id; this.name = name; this.portraitUri = portraitUri; } return Group; })(); RongIMLib.Group = Group; var Message = (function () { function Message(content, conversationType, extra, objectName, messageDirection, messageId, receivedStatus, receivedTime, senderUserId, sentStatus, sentTime, targetId, messageType, messageUId, isLocalMessage, offLineMessage, receiptResponse, disableNotification) { this.content = content; this.conversationType = conversationType; this.extra = extra; this.objectName = objectName; this.messageDirection = messageDirection; this.messageId = messageId; this.receivedStatus = receivedStatus; this.receivedTime = receivedTime; this.senderUserId = senderUserId; this.sentStatus = sentStatus; this.sentTime = sentTime; this.targetId = targetId; this.messageType = messageType; this.messageUId = messageUId; this.isLocalMessage = isLocalMessage; this.offLineMessage = offLineMessage; this.receiptResponse = receiptResponse; this.disableNotification = disableNotification; } return Message; })(); RongIMLib.Message = Message; var MessageTag = (function () { function MessageTag(isCounted, isPersited) { this.isCounted = isCounted; this.isPersited = isPersited; } MessageTag.prototype.getMessageTag = function () { if (this.isCounted && this.isPersited) { return 3; } else if (this.isCounted) { return 2; } else if (this.isPersited) { return 1; } else if (!this.isCounted && !this.isPersited) { return 0; } }; MessageTag.getTagByStatus = function (status) { var statusMap = { 3: { isCounted: true, isPersited: true }, 2: { isCounted: true, isPersited: false }, 1: { isCounted: true, isPersited: true }, 0: { isCounted: true, isPersited: true } }; return statusMap[status] || statusMap[3]; }; return MessageTag; })(); RongIMLib.MessageTag = MessageTag; var PublicServiceMenuItem = (function () { function PublicServiceMenuItem(id, name, type, sunMenuItems, url) { this.id = id; this.name = name; this.type = type; this.sunMenuItems = sunMenuItems; this.url = url; } return PublicServiceMenuItem; })(); RongIMLib.PublicServiceMenuItem = PublicServiceMenuItem; // TODO: TBD var PublicServiceProfile = (function () { function PublicServiceProfile(conversationType, introduction, menu, name, portraitUri, publicServiceId, hasFollowed, isGlobal) { this.conversationType = conversationType; this.introduction = introduction; this.menu = menu; this.name = name; this.portraitUri = portraitUri; this.publicServiceId = publicServiceId; this.hasFollowed = hasFollowed; this.isGlobal = isGlobal; } return PublicServiceProfile; })(); RongIMLib.PublicServiceProfile = PublicServiceProfile; var UserInfo = (function () { function UserInfo(id, name, portraitUri) { this.id = id; this.name = name; this.portraitUri = portraitUri; } return UserInfo; })(); RongIMLib.UserInfo = UserInfo; var User = (function () { function User(id, token) { this.id = id; this.token = token; } return User; })(); RongIMLib.User = User; var Room = (function () { function Room(id, user, mode, broadcastType, type) { this.id = id; this.user = user; this.mode = mode; this.broadcastType = broadcastType; this.type = type; } return Room; })(); RongIMLib.Room = Room; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var ServerDataProvider = (function () { function ServerDataProvider() { this.userStatusListener = null; this.Conversation = { watcher: new RongIMLib.Observer(), watch: function (_watcher) { this.watcher.add(_watcher); var conversationList = RongIMLib.RongIMClient._memoryStore.conversationList; this.watcher.emit(conversationList); }, unwatch: function (_watcher) { this.watcher.remove(_watcher); }, _notify: function (conversationList) { this.watcher.emit(conversationList); } }; } ServerDataProvider.prototype.init = function (appKey, options) { new RongIMLib.FeatureDectector(options.appCallback); }; ServerDataProvider.prototype.connect = function (token, callback, userId, option) { var self = this; RongIMLib.Logger.reportRTLog(); option = option || {}; var isReconnect = option.isReconnect; var isIgnoreReportStart = option.isIgnoreReportStart; var StartReportTag = isReconnect ? RongIMLib.LoggerTag.IM.L_RECO_T : RongIMLib.LoggerTag.IM.A_CONN_T; var EndReportTag = isReconnect ? RongIMLib.LoggerTag.IM.L_RECO_R : RongIMLib.LoggerTag.IM.A_CONN_R; !isIgnoreReportStart && RongIMLib.Logger.writeLog({ tag: StartReportTag, level: RongIMLib.LoggerLevel.I, type: RongIMLib.LoggerType.IM, content: { "token": token } }); RongIMLib.RongIMClient.bridge = RongIMLib.Bridge.getInstance(); RongIMLib.RongIMClient._memoryStore.token = token; RongIMLib.RongIMClient._memoryStore.callback = callback; userId = userId || ''; option = option || {}; var isConnecting = false, isConnected = false; if (RongIMLib.Bridge._client && RongIMLib.Bridge._client.channel) { isConnecting = (RongIMLib.Bridge._client.channel.connectionStatus == RongIMLib.ConnectionStatus.CONNECTING); isConnected = (RongIMLib.Bridge._client.channel.connectionStatus == RongIMLib.ConnectionStatus.CONNECTED); } if (isConnected || isConnecting) { return; } var isGreater = (RongIMLib.RongIMClient.otherDeviceLoginCount > 5); if (isGreater) { callback.onError(RongIMLib.ConnectionStatus.ULTRALIMIT); return; } // 清除本地导航缓存 if (option.force) { RongIMLib.RongIMClient._storageProvider.removeItem('servers'); } RongIMLib.RongIMClient.bridge.setListener(); RongIMLib.RongIMClient.bridge.connect(RongIMLib.RongIMClient._memoryStore.appKey, token, { onSuccess: function (data) { setTimeout(function () { callback.onSuccess(data); RongIMLib.RongIMClient._memoryStore.networkUnavailable = false; RongIMLib.Logger.loggerCache.userId = data; RongIMLib.Logger.writeLog({ tag: EndReportTag, level: RongIMLib.LoggerLevel.I, type: RongIMLib.LoggerType.IM, content: { desc: 'connection succeeded' } }); self.conversationStatusManager = new RongIMLib.ConversationStatusManager({ appkey: RongIMLib.RongIMClient._memoryStore.appKey, userId: data, server: self }); self.conversationStatusManager.watchChanged(function (status) { RongIMLib.RongUtil.forEach(RongIMLib.RongIMClient.conversationStatusListeners, function (event) { event(status); }); }); self.conversationStatusManager.pull({ isForce: true }); }); var storage = RongIMLib.RongIMClient._storageProvider; var fullnavi = storage.getItem('fullnavi') || '{}'; try { fullnavi = JSON.parse(fullnavi); } catch (e) { fullnavi = {}; } var isAutoPull = fullnavi.openUS; isAutoPull && self.getVoipInfo({ onSuccess: function (VoipInfo) { try { VoipInfo && RongIMLib.RongUtil.forEach(RongIMLib.RongIMClient.settingListeners, function (listener) { listener({ VoipInfo: VoipInfo }); // 与 3.x 保持一致, 方便后续 3.x 兼容 }); if (VoipInfo) { var fullnavi_1 = storage.getItem('fullnavi') || '{}'; fullnavi_1 = JSON.parse(fullnavi_1); fullnavi_1.voipCallInfo = VoipInfo; storage.setItem('fullnavi', JSON.stringify(fullnavi_1)); } } catch (e) { } }, onError: function () { // do nothing } }); }, onError: function (e) { if (e == RongIMLib.ConnectionState.TOKEN_INCORRECT || !e) { setTimeout(function () { callback.onTokenIncorrect(); RongIMLib.Logger.writeLog({ tag: EndReportTag, level: RongIMLib.LoggerLevel.E, type: RongIMLib.LoggerType.IM, content: { ConnectionState: RongIMLib.ConnectionState.TOKEN_INCORRECT } }); }); } else { setTimeout(function () { callback.onError(e); RongIMLib.Logger.writeLog({ tag: EndReportTag, level: RongIMLib.LoggerLevel.E, type: RongIMLib.LoggerType.IM, content: { code: e } }); }); } } }); }; /* config.auto: 默认 false, true 启用自动重连,启用则为必选参数 config.rate: 重试频率 [100, 1000, 3000, 6000, 10000, 18000] 单位为毫秒,可选 config.url: 网络嗅探地址 [http(s)://]cdn.ronghub.com/RongIMLib-2.2.6.min.js 可选 */ ServerDataProvider.prototype.reconnect = function (callback, config) { var store = RongIMLib.RongIMClient._memoryStore; var token = store.token; if (!token) { throw new Error('reconnect: token is empty.'); } if (RongIMLib.Bridge._client && RongIMLib.Bridge._client.channel && RongIMLib.Bridge._client.channel.connectionStatus != RongIMLib.ConnectionStatus.CONNECTED && RongIMLib.Bridge._client.channel.connectionStatus != RongIMLib.ConnectionStatus.CONNECTING) { config = config || {}; var key = config.auto ? 'auto' : 'custom'; var handler = { auto: function () { var repeatConnect = function (options) { var step = options.step(); var done = 'done'; var url = options.url; var ping = function () { RongIMLib.RongUtil.request({ url: url, success: function () { options.done(); }, error: function () { repeat(); } }); }; var repeat = function () { var next = step(); if (next == 'done') { var error = RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE; options.done(error); return; } var timer = setTimeout(ping, next); RongIMLib.RongIMClient._memoryStore.autoReconnectTimer = timer; }; repeat(); }; var protocol = RongIMLib.RongIMClient._memoryStore.depend.protocol; var url = config.url || 'cdn.ronghub.com/RongIMLib-2.2.6.min.js'; var pathConfig = { protocol: protocol, path: url }; url = RongIMLib.RongUtil.formatProtoclPath(pathConfig); var rate = config.rate || [100, 1000, 3000, 6000, 10000, 18000]; //结束标识 rate.push('done'); var opts = { url: url, step: function () { var index = 0; return function () { var time = rate[index]; index++; return time; }; }, done: function (error) { if (error) { callback.onError(error); return; } RongIMLib.RongIMClient.connect(token, callback, null, { isIgnoreReportStart: true, isReconnect: true }); } }; repeatConnect(opts); }, custom: function () { RongIMLib.RongIMClient.connect(token, callback, null, { isIgnoreReportStart: true, isReconnect: true }); } }; handler[key](); } else { var _client = RongIMLib.Bridge._client || {}; var _channel = _client.channel || {}; RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.L_RECO_E, level: RongIMLib.LoggerLevel.E, type: RongIMLib.LoggerType.IM, content: { msg: { connectionStatus: _channel.connectionStatus }, action: 'reconnect' } }); } }; ServerDataProvider.prototype.logout = function () { RongIMLib.RongIMClient.bridge.disconnect(); RongIMLib.RongIMClient.bridge = null; }; ServerDataProvider.prototype.disconnect = function () { var timer = RongIMLib.RongIMClient._memoryStore.autoReconnectTimer; timer && clearTimeout(timer); RongIMLib.RongIMClient.bridge.disconnect(); }; ServerDataProvider.prototype.sendReceiptResponse = function (conversationType, targetId, sendCallback) { var rspkey = RongIMLib.Bridge._client.userId + conversationType + targetId + 'RECEIVED', me = this; if (RongIMLib.RongUtil.supportLocalStorage()) { var valObj = JSON.parse(RongIMLib.RongIMClient._storageProvider.getItem(rspkey)); if (valObj) { var vals = []; for (var key in valObj) { var tmp = {}; tmp[key] = valObj[key].uIds; valObj[key].isResponse || vals.push(tmp); } if (vals.length == 0) { sendCallback.onSuccess(); return; } var interval = setInterval(function () { if (vals.length == 1) { clearInterval(interval); } var obj = vals.splice(0, 1)[0]; var rspMsg = new RongIMLib.ReadReceiptResponseMessage({ receiptMessageDic: obj }); me.sendMessage(conversationType, targetId, rspMsg, { onSuccess: function (msg) { var senderUserId = RongIMLib.MessageUtil.getFirstKey(obj); valObj[senderUserId].isResponse = true; RongIMLib.RongIMClient._storageProvider.setItem(rspkey, JSON.stringify(valObj)); sendCallback.onSuccess(msg); }, onError: function (error, msg) { sendCallback.onError(error, msg); } }); }, 200); } else { sendCallback.onSuccess(); } } else { sendCallback.onSuccess(); } }; ServerDataProvider.prototype.sendTypingStatusMessage = function (conversationType, targetId, messageName, sendCallback) { var me = this; if (messageName in RongIMLib.RongIMClient.MessageParams) { me.sendMessage(conversationType, targetId, RongIMLib.TypingStatusMessage.obtain(RongIMLib.RongIMClient.MessageParams[messageName].objectName, ""), { onSuccess: function () { setTimeout(function () { sendCallback.onSuccess(); }); }, onError: function (errorCode) { setTimeout(function () { sendCallback.onError(errorCode, null); }); }, onBefore: function () { } }); } }; ServerDataProvider.prototype.sendRecallMessage = function (content, sendMessageCallback, params) { params = params || {}; var msg = new RongIMLib.RecallCommandMessage({ conversationType: content.conversationType, targetId: content.targetId, sentTime: content.sentTime, messageUId: content.messageUId, extra: content.extra, user: content.user }); this.sendMessage(content.conversationType, content.senderUserId, msg, sendMessageCallback, false, null, null, 2, params); }; ServerDataProvider.prototype.sendTextMessage = function (conversationType, targetId, content, sendMessageCallback) { var msgContent = RongIMLib.TextMessage.obtain(content); this.sendMessage(conversationType, targetId, msgContent, sendMessageCallback); }; ServerDataProvider.prototype.getRemoteHistoryMessages = function (conversationType, targetId, timestamp, count, callback, config) { if (count <= 1) { throw new Error("the count must be greater than 1."); } config = config || {}; var order = config.order || 0; var getKey = function () { return [conversationType, targetId, '_', order].join(''); }; var key = getKey(); if (!RongIMLib.RongUtil.isNumber(timestamp)) { timestamp = RongIMLib.RongIMClient._memoryStore.lastReadTime.get(key); } var memoryStore = RongIMLib.RongIMClient._memoryStore; var historyMessageLimit = memoryStore.historyMessageLimit; /* limit 属性: var limit = { time: '时间戳, 最后一次拉取时间', hasMore: '是否还有历史消息, bool 值' }; */ var limit = historyMessageLimit.get(key) || {}; var hasMore = limit.hasMore; var isFecth = (hasMore || limit.time != timestamp); // 正序获取消息时不做限制,防止有新消息导致无法获取 if (!isFecth && order == 0) { return callback.onSuccess([], hasMore); } var modules = new RongIMLib.RongIMClient.Protobuf.HistoryMsgInput(), self = this; modules.setTargetId(targetId); modules.setTime(timestamp); modules.setCount(count); modules.setOrder(order); var topic = HistoryMsgType[conversationType] || HistoryMsgType[RongIMLib.ConversationType.PRIVATE]; RongIMLib.RongIMClient.bridge.queryMsg(topic, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), targetId, { onSuccess: function (data) { var fetchTime = RongIMLib.MessageUtil.int64ToTimestamp(data.syncTime); RongIMLib.RongIMClient._memoryStore.lastReadTime.set(key, fetchTime); historyMessageLimit.set(key, { hasMore: !!data.hasMsg, time: fetchTime }); var list = data.list.reverse(), tempMsg = null, tempDir; var read = RongIMLib.SentStatus.READ; if (RongIMLib.RongUtil.supportLocalStorage()) { for (var i = 0, len = list.length; i < len; i++) { tempMsg = RongIMLib.MessageUtil.messageParser(list[i]); tempDir = JSON.parse(RongIMLib.RongIMClient._storageProvider.getItem(RongIMLib.Bridge._client.userId + tempMsg.messageUId + "SENT")); if (tempDir) { tempMsg.receiptResponse || (tempMsg.receiptResponse = {}); tempMsg.receiptResponse[tempMsg.messageUId] = tempDir.count; } tempMsg.sentStatus = read; tempMsg.targetId = targetId; list[i] = tempMsg; } } else { for (var i = 0, len = list.length; i < len; i++) { var tempMsg = RongIMLib.MessageUtil.messageParser(list[i]); tempMsg.sentStatus = read; list[i] = tempMsg; } } setTimeout(function () { callback.onSuccess(list, !!data.hasMsg); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }, "HistoryMessagesOuput"); }; ServerDataProvider.prototype.hasRemoteUnreadMessages = function (token, callback) { var xss = null; window.RCCallback = function (x) { setTimeout(function () { callback.onSuccess(!!+x.status); }); xss.parentNode.removeChild(xss); }; xss = document.createElement("script"); xss.src = RongIMLib.RongIMClient._memoryStore.depend.api + "/message/exist.js?appKey=" + encodeURIComponent(RongIMLib.RongIMClient._memoryStore.appKey) + "&token=" + encodeURIComponent(token) + "&callBack=RCCallback&_=" + RongIMLib.RongUtil.getTimestamp(); document.body.appendChild(xss); xss.onerror = function () { setTimeout(function () { callback.onError(RongIMLib.ErrorCode.UNKNOWN); }); xss.parentNode.removeChild(xss); }; }; ServerDataProvider.prototype.getRemoteConversationList = function (callback, conversationTypes, count) { var modules = new RongIMLib.RongIMClient.Protobuf.RelationsInput(), self = this; modules.setType(1); if (typeof count == 'undefined') { modules.setCount(0); } else { modules.setCount(count); } RongIMLib.RongIMClient.bridge.queryMsg(26, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (list) { if (list.info) { list.info = list.info.reverse(); for (var i = 0, len = list.info.length; i < len; i++) { RongIMLib.RongIMClient.getInstance().pottingConversation(list.info[i]); } } var conversations = RongIMLib.RongIMClient._memoryStore.conversationList; setTimeout(function () { if (conversationTypes) { return callback.onSuccess(self.filterConversations(conversationTypes, conversations)); } callback.onSuccess(conversations); }); }, onError: function (error) { callback.onError(error); } }, "RelationsOutput"); }; ServerDataProvider.prototype.addMemberToDiscussion = function (discussionId, userIdList, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.ChannelInvitationInput(); modules.setUsers(userIdList); RongIMLib.RongIMClient.bridge.queryMsg(0, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), discussionId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.createDiscussion = function (name, userIdList, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.CreateDiscussionInput(), self = this; modules.setName(name); RongIMLib.RongIMClient.bridge.queryMsg(1, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (discussId) { if (userIdList.length > 0) { self.addMemberToDiscussion(discussId, userIdList, { onSuccess: function () { }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); } setTimeout(function () { callback.onSuccess(discussId); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }, "CreateDiscussionOutput"); }; ServerDataProvider.prototype.getDiscussion = function (discussionId, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.ChannelInfoInput(); modules.setNothing(1); RongIMLib.RongIMClient.bridge.queryMsg(4, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), discussionId, { onSuccess: function (data) { setTimeout(function () { callback.onSuccess(data); }); }, onError: function (errorCode) { setTimeout(function () { callback.onError(errorCode); }); } }, "ChannelInfoOutput"); }; ServerDataProvider.prototype.quitDiscussion = function (discussionId, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.LeaveChannelInput(); modules.setNothing(1); RongIMLib.RongIMClient.bridge.queryMsg(7, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), discussionId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (errorCode) { setTimeout(function () { callback.onError(errorCode); }); } }); }; ServerDataProvider.prototype.removeMemberFromDiscussion = function (discussionId, userId, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.ChannelEvictionInput(); modules.setUser(userId); RongIMLib.RongIMClient.bridge.queryMsg(9, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), discussionId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (errorCode) { setTimeout(function () { callback.onError(errorCode); }); } }); }; ServerDataProvider.prototype.setDiscussionInviteStatus = function (discussionId, status, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.ModifyPermissionInput(); modules.setOpenStatus(status.valueOf()); RongIMLib.RongIMClient.bridge.queryMsg(11, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), discussionId, { onSuccess: function (x) { setTimeout(function () { callback.onSuccess(); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.setDiscussionName = function (discussionId, name, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RenameChannelInput(); modules.setName(name); RongIMLib.RongIMClient.bridge.queryMsg(12, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), discussionId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (errcode) { callback.onError(errcode); } }); }; ServerDataProvider.prototype.joinChatRoom = function (chatroomId, messageCount, callback) { RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.A_JCTR_T, level: RongIMLib.LoggerLevel.I, type: RongIMLib.LoggerType.IM, content: { chatroomId: chatroomId } }); var e = new RongIMLib.RongIMClient.Protobuf.ChrmInput(); e.setNothing(1); RongIMLib.Bridge._client.chatroomId = chatroomId; RongIMLib.RongIMClient.bridge.queryMsg(19, RongIMLib.MessageUtil.ArrayForm(e.toArrayBuffer()), chatroomId, { onSuccess: function () { var navi = RongIMLib.RongIMClient.getInstance().getNavi(); var isOpenKVStorage = navi.kvStorage; if (isOpenKVStorage) { RongIMLib.RongIMClient._dataAccessProvider.pullChatroomEntry(chatroomId, 0, { onSuccess: function (result) { RongIMLib.ChrmKVHandler.setEntries(chatroomId, result); setTimeout(function () { callback.onSuccess(); RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.A_JCTR_R, level: RongIMLib.LoggerLevel.I, type: RongIMLib.LoggerType.IM, content: { chatroomId: chatroomId } }); }); }, onError: function (errorCode) { setTimeout(function () { callback.onError(errorCode); RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.A_JCTR_R, level: RongIMLib.LoggerLevel.W, type: RongIMLib.LoggerType.IM, content: { chatroomId: chatroomId, error: errorCode } }); }); } }); } else { setTimeout(function () { RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.A_JCTR_R, level: RongIMLib.LoggerLevel.I, type: RongIMLib.LoggerType.IM, content: { chatroomId: chatroomId } }); callback.onSuccess(); }); } var modules = new RongIMLib.RongIMClient.Protobuf.ChrmPullMsg(); messageCount == 0 && (messageCount = -1); modules.setCount(messageCount); modules.setSyncTime(0); RongIMLib.Bridge._client.queryMessage("chrmPull", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), chatroomId, 1, { onSuccess: function (collection) { var list = collection.list; var sync = RongIMLib.MessageUtil.int64ToTimestamp(collection.syncTime); var latestMessage = list[list.length - 1]; if (latestMessage) { latestMessage = RongIMLib.MessageUtil.messageParser(latestMessage); sync = latestMessage.sentTime; } RongIMLib.RongIMClient._memoryStore.lastReadTime.set(chatroomId + RongIMLib.Bridge._client.userId + "CST", sync); var _client = RongIMLib.Bridge._client; for (var i = 0, mlen = list.length; i < mlen; i++) { var uId = 'R' + list[i].msgId; if (!(uId in _client.cacheMessageIds)) { _client.cacheMessageIds[uId] = true; var cacheUIds = RongIMLib.RongUtil.keys(_client.cacheMessageIds); if (cacheUIds.length > 10) { uId = cacheUIds[0]; delete _client.cacheMessageIds[uId]; } if (RongIMLib.RongIMClient._memoryStore.filterMessages.length > 0) { for (var j = 0, flen = RongIMLib.RongIMClient._memoryStore.filterMessages.length; j < flen; j++) { if (RongIMLib.RongIMClient.MessageParams[RongIMLib.RongIMClient._memoryStore.filterMessages[j]].objectName != list[i].classname) { _client.handler.onReceived(list[i]); } } } else { _client.handler.onReceived(list[i]); } } } }, onError: function (errcode) { setTimeout(function () { callback.onError(errcode); }); } }, "DownStreamMessages"); }, onError: function (error) { setTimeout(function () { RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.A_JCTR_R, level: RongIMLib.LoggerLevel.W, type: RongIMLib.LoggerType.IM, content: { chatroomId: chatroomId, error: error } }); callback.onError(error); }); } }, "ChrmOutput"); }; ServerDataProvider.prototype.getChatRoomInfo = function (chatRoomId, count, order, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.QueryChatroomInfoInput(); modules.setCount(count); modules.setOrder(order); RongIMLib.RongIMClient.bridge.queryMsg("queryChrmI", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), chatRoomId, { onSuccess: function (ret) { var userInfos = ret.userInfos; userInfos.forEach(function (item) { item.time = RongIMLib.MessageUtil.int64ToTimestamp(item.time); }); setTimeout(function () { callback.onSuccess(ret); }); }, onError: function (errcode) { setTimeout(function () { callback.onError(errcode); }); } }, "QueryChatroomInfoOutput"); }; ServerDataProvider.prototype.quitChatRoom = function (chatroomId, callback) { RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.A_QCTR_T, level: RongIMLib.LoggerLevel.I, type: RongIMLib.LoggerType.IM, content: { chatroomId: chatroomId } }); var e = new RongIMLib.RongIMClient.Protobuf.ChrmInput(); e.setNothing(1); RongIMLib.RongIMClient.bridge.queryMsg(17, RongIMLib.MessageUtil.ArrayForm(e.toArrayBuffer()), chatroomId, { onSuccess: function () { setTimeout(function () { RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.A_QCTR_R, level: RongIMLib.LoggerLevel.I, type: RongIMLib.LoggerType.IM, content: { chatroomId: chatroomId } }); callback.onSuccess(); }); }, onError: function (errcode) { setTimeout(function () { RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.A_QCTR_R, level: RongIMLib.LoggerLevel.W, type: RongIMLib.LoggerType.IM, content: { chatroomId: chatroomId, error: errcode } }); callback.onError(errcode); }); } }, "ChrmOutput"); }; ServerDataProvider.prototype.setChatroomHisMessageTimestamp = function (chatRoomId, timestamp) { RongIMLib.RongIMClient._memoryStore.lastReadTime.set('chrhis_' + chatRoomId, timestamp); }; ServerDataProvider.prototype.getChatRoomHistoryMessages = function (chatRoomId, count, order, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.HistoryMsgInput(); modules.setTargetId(chatRoomId); var timestamp = RongIMLib.RongIMClient._memoryStore.lastReadTime.get('chrhis_' + chatRoomId) || 0; modules.setTime(timestamp); modules.setCount(count); modules.setOrder(order); RongIMLib.RongIMClient.bridge.queryMsg(34, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (data) { RongIMLib.RongIMClient._memoryStore.lastReadTime.set('chrhis_' + chatRoomId, RongIMLib.MessageUtil.int64ToTimestamp(data.syncTime)); var list = data.list.reverse(); for (var i = 0, len = list.length; i < len; i++) { list[i] = RongIMLib.MessageUtil.messageParser(list[i]); } setTimeout(function () { callback.onSuccess(list, !!data.hasMsg); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }, "HistoryMsgOuput"); }; ServerDataProvider.prototype.setChatroomEntry = function (chatroomId, chatroomEntry, callback) { var opt = RongIMLib.ChatroomEntityOpt.UPDATE; var key = chatroomEntry.key, value = chatroomEntry.value; var isKeyInValid = !RongIMLib.RongUtil.isLengthLimit(key, RongIMLib.ChatroomEntityLimit.KEY, 1) || !RongIMLib.ChrmKVHandler.isKeyValid(key); var isValueInValid = !RongIMLib.RongUtil.isLengthLimit(value, RongIMLib.ChatroomEntityLimit.VALUE, 1); if (isKeyInValid || isValueInValid) { setTimeout(function () { callback.onError(RongIMLib.ErrorCode.BIZ_ERROR_INVALID_PARAMETER); }); } else { this.refreshChatroomEntry(chatroomId, chatroomEntry, opt, callback); } }; ServerDataProvider.prototype.forceSetChatroomEntry = function (chatroomId, chatroomEntry, callback) { chatroomEntry.isOverwrite = true; this.setChatroomEntry(chatroomId, chatroomEntry, callback); }; ServerDataProvider.prototype.removeChatroomEntry = function (chatroomId, chatroomEntry, callback) { var opt = RongIMLib.ChatroomEntityOpt.DELETE; var key = chatroomEntry.key; var isKeyInValid = !RongIMLib.RongUtil.isLengthLimit(key, RongIMLib.ChatroomEntityLimit.KEY, 1) || !RongIMLib.ChrmKVHandler.isKeyValid(key); if (isKeyInValid) { setTimeout(function () { callback.onError(RongIMLib.ErrorCode.BIZ_ERROR_INVALID_PARAMETER); }); } else { this.refreshChatroomEntry(chatroomId, chatroomEntry, opt, callback); } }; ServerDataProvider.prototype.forceRemoveChatroomEntry = function (chatroomId, chatroomEntry, callback) { chatroomEntry.isOverwrite = true; this.removeChatroomEntry(chatroomId, chatroomEntry, callback); }; ServerDataProvider.prototype.refreshChatroomEntry = function (chatroomId, chatroomEntry, chatroomEntryOpt, callback) { var modules, topic; var key = chatroomEntry.key, value = chatroomEntry.value || '', extra = chatroomEntry.notificationExtra; if (chatroomEntryOpt === RongIMLib.ChatroomEntityOpt.DELETE) { modules = new RongIMLib.RongIMClient.Protobuf.DeleteChrmKV(); topic = 'delKV'; } else { modules = new RongIMLib.RongIMClient.Protobuf.SetChrmKV(); topic = 'setKV'; } var status = RongIMLib.RongInnerTools.getChrmEntityStatus(chatroomEntry, chatroomEntryOpt); var currentUserId = RongIMLib.RongIMClient.getInstance().getCurrentUserId(); var entry = { key: key, value: value, uid: currentUserId }; if (status) { entry.status = status; } modules.setEntry(entry); if (chatroomEntry.isSendNotification) { modules.setBNotify(true); var msgModules = new RongIMLib.RongIMClient.Protobuf.UpStreamMessage(); var msg = new RongIMLib.ChrmKVNotificationMessage({ key: key, value: value, extra: extra, type: chatroomEntryOpt }); msgModules.setSessionId(RongIMLib.RongIMClient.MessageParams[msg.messageName].msgTag.getMessageTag()); msgModules.setClassname(RongIMLib.RongIMClient.MessageParams[msg.messageName].objectName); msgModules.setContent(msg.encode()); modules.setNotification(msgModules); // 默认设置为 聊天室消息 modules.setType(RongIMLib.ConversationType.CHATROOM); } RongIMLib.RongIMClient.bridge.queryMsg(topic, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), chatroomId, { onSuccess: function (ret) { var currentUserId = RongIMLib.RongIMClient.getInstance().getCurrentUserId(); RongIMLib.ChrmKVHandler.setEntry(chatroomId, chatroomEntry, status, currentUserId); setTimeout(function () { callback.onSuccess(!!ret); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }, 'ChrmOutput'); }; ServerDataProvider.prototype.getChatroomEntry = function (chatroomId, key, callback) { var value = RongIMLib.ChrmKVHandler.getEntityValue(chatroomId, key); setTimeout(function () { if (RongIMLib.RongUtil.isEmpty(value)) { callback.onError(RongIMLib.ErrorCode.CHATROOM_KEY_NOT_EXIST); } else { callback.onSuccess(value); } }); }; ServerDataProvider.prototype.getAllChatroomEntries = function (chatroomId, callback) { setTimeout(function () { var entries = RongIMLib.ChrmKVHandler.getAllEntityValue(chatroomId); callback.onSuccess(entries); }); }; ServerDataProvider.prototype.pullChatroomEntry = function (chatroomId, time, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.QueryChrmKV(); modules.setTimestamp(time); RongIMLib.RongIMClient.bridge.queryMsg('pullKV', RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), chatroomId, { onSuccess: function (data) { setTimeout(function () { callback.onSuccess(data); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }, "ChrmKVOutput"); }; ServerDataProvider.prototype.setMessageStatus = function (conversationType, targetId, timestamp, status, callback) { setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.addToBlacklist = function (userId, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.Add2BlackListInput(); modules.setUserId(userId); RongIMLib.RongIMClient.bridge.queryMsg(21, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.getBlacklist = function (callback) { var modules = new RongIMLib.RongIMClient.Protobuf.QueryBlackListInput(); modules.setNothing(1); RongIMLib.RongIMClient.bridge.queryMsg(23, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (list) { setTimeout(function () { callback.onSuccess(list); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }, "QueryBlackListOutput"); }; ServerDataProvider.prototype.getBlacklistStatus = function (userId, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.BlackListStatusInput(); modules.setUserId(userId); RongIMLib.RongIMClient.bridge.queryMsg(24, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function (status) { setTimeout(function () { callback.onSuccess(RongIMLib.BlacklistStatus[status]); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.removeFromBlacklist = function (userId, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RemoveFromBlackListInput(); modules.setUserId(userId); RongIMLib.RongIMClient.bridge.queryMsg(22, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.getFileToken = function (fileType, callback, fileName) { if (!(/(1|2|3|4)/.test(fileType.toString()))) { setTimeout(function () { callback.onError(RongIMLib.ErrorCode.QNTKN_FILETYPE_ERROR); }); return; } var fileName = RongIMLib.RongUtil.generateUploadFileName(fileType, fileName); // 获取上传地址 var domains = RongIMLib.RongIMClient._storageProvider.getItem('upload_domains') || '{}'; var modules = new RongIMLib.RongIMClient.Protobuf.GetQNupTokenInput(); modules.setType(fileType); modules.setKey(fileName); RongIMLib.RongIMClient.bridge.queryMsg(30, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (res) { setTimeout(function () { var data = RongIMLib.RongUtil.extend(JSON.parse(domains), res); callback.onSuccess(data); }); }, onError: function (errcode) { setTimeout(function () { callback.onError(errcode); }); } }, "GetQNupTokenOutput"); }; ServerDataProvider.prototype.getFileUrl = function (fileType, fileName, oriName, callback, data) { var data = data || {}; if (!(/(1|2|3|4)/.test(fileType.toString()))) { setTimeout(function () { callback.onError(RongIMLib.ErrorCode.QNTKN_FILETYPE_ERROR); }); return; } if (data.isBosRes) { callback.onSuccess(data); return; } var modules = new RongIMLib.RongIMClient.Protobuf.GetQNdownloadUrlInput(); modules.setType(fileType); modules.setKey(fileName); if (oriName) { modules.setFileName(oriName); } RongIMLib.RongIMClient.bridge.queryMsg(31, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (data) { setTimeout(function () { callback.onSuccess(data); }); }, onError: function (errcode) { setTimeout(function () { callback.onError(errcode); }); } }, "GetQNdownloadUrlOutput"); }; ServerDataProvider.prototype.getVoipInfo = function (callback) { if (RongIMLib.RongIMClient._memoryStore.depend.isPolling) return; //长轮训关闭实时配置,IE 现不支持音视频 // 获取最新值 return this.getPullSetting({ onSuccess: function (result) { result = result || {}; var items = result.items || []; var voipInfo = null; for (var i = 0, max = items.length; i < max; i++) { var item = items[i]; if (item.key === 'VoipInfo') { var value = item.value; if (RongIMLib.RongIMClient._memoryStore.depend.isPolling) { value = new RongIMLib.BinaryHelper().readUTF(value.offset ? RongIMLib.MessageUtil.ArrayForm(value.buffer).slice(value.offset, value.limit) : value); } else { value = new RongIMLib.BinaryHelper().readUTF(value.offset ? RongIMLib.MessageUtil.ArrayFormInput(value.buffer).subarray(value.offset, value.limit) : value); } voipInfo = value; } } callback.onSuccess(voipInfo); }, onError: callback.onError }, 0); }; ServerDataProvider.prototype.getPullSetting = function (callback, version) { var modules = new RongIMLib.RongIMClient.Protobuf.PullUserSettingInput(); version = version || parseInt(RongIMLib.RongIMClient.sdkver); modules.setVersion(version); RongIMLib.RongIMClient.bridge.queryMsg('pullUS', RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (result) { result = result || {}; result.version = RongIMLib.MessageUtil.int64ToTimestamp(result.version); setTimeout(function () { callback.onSuccess(result); }); }, onError: function (errcode) { setTimeout(function () { callback.onError(errcode); }); } }, 'PullUserSettingOutput'); }; ServerDataProvider.prototype.setOfflineMessageDuration = function (duration, callback) { this.getPullSetting({ onSuccess: function (result) { /** * GetQNupTokenOutput 第一位为 int64, 第二位为 string, 与设置离线消息一致 * 为避免修改 Protobuf 带来的更新成本. 仅复用, 不重新命名 */ var modules = new RongIMLib.RongIMClient.Protobuf.GetQNupTokenOutput(); var version = result.version; modules.setDeadline(version); modules.setToken(duration + ''); RongIMLib.RongIMClient.bridge.queryMsg('setOfflineMsgDur', RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (data) { setTimeout(function () { callback.onSuccess(data); }); }, onError: function (errcode) { setTimeout(function () { callback.onError(errcode); }); } }); }, onError: callback.onError }); }; /* methodType 1 : 多客服(客服后台使用); 2 : 消息撤回 params.userIds : 定向消息接收者 */ ServerDataProvider.prototype.sendMessage = function (conversationType, targetId, messageContent, sendCallback, mentiondMsg, pushText, appData, methodType, params) { if (!RongIMLib.Bridge._client.channel) { setTimeout(function () { sendCallback.onError(RongIMLib.ErrorCode.RC_NET_UNAVAILABLE, null); }); return; } if (!RongIMLib.Bridge._client.channel.socket.socket.connected) { setTimeout(function () { sendCallback.onError(RongIMLib.ErrorCode.TIMEOUT, null); }); throw new Error("connect is timeout! postion:sendMessage"); } params = params || {}; var isGroup = (conversationType == RongIMLib.ConversationType.DISCUSSION || conversationType == RongIMLib.ConversationType.GROUP); var modules = new RongIMLib.RongIMClient.Protobuf.UpStreamMessage(); var sessionId; if (mentiondMsg && isGroup) { sessionId = 7; params.disableNotification && (sessionId = sessionId | 0x10); modules.setSessionId(sessionId); } else { sessionId = RongIMLib.RongIMClient.MessageParams[messageContent.messageName].msgTag.getMessageTag(); params.disableNotification && (sessionId = sessionId | 0x10); modules.setSessionId(sessionId); } pushText && modules.setPushText(pushText); appData && modules.setAppData(appData); if (isGroup && messageContent.messageName == RongIMLib.RongIMClient.MessageType["ReadReceiptResponseMessage"]) { var rspMsg = messageContent; if (rspMsg.receiptMessageDic) { var ids = []; for (var key in rspMsg.receiptMessageDic) { ids.push(key); } modules.setUserId(ids); } } if (isGroup && messageContent.messageName == RongIMLib.RongIMClient.MessageType["SyncReadStatusMessage"]) { modules.setUserId(RongIMLib.Bridge._client.userId); } var userIds = params.userIds; if (userIds) { modules.setUserId(userIds); } var flag = 0; if (params.isPush || params.isVoipPush) { flag |= 0x01; } if (params.isFilerWhiteBlacklist) { flag |= 0x02; } modules.setConfigFlag(flag); modules.setClassname(RongIMLib.RongIMClient.MessageParams[messageContent.messageName].objectName); var encodedContent = messageContent.encode(); if (RongIMLib.RongUtil.getByteLength(encodedContent) > RongIMLib.RongIMClient.MaxMessageContentBytes) { setTimeout(function () { sendCallback.onError(RongIMLib.ErrorCode.RC_MSG_CONTENT_EXCEED_LIMIT); }); return; } modules.setContent(encodedContent); var content = modules.toArrayBuffer(); if (Object.prototype.toString.call(content) == "[object ArrayBuffer]") { content = [].slice.call(new Int8Array(content)); } var me = this, msg = new RongIMLib.Message(); var c = this.getConversation(conversationType, targetId); if (RongIMLib.RongIMClient.MessageParams[messageContent.messageName].msgTag.getMessageTag() == 3) { if (!c) { c = RongIMLib.RongIMClient.getInstance().createConversation(conversationType, targetId, ""); } c.sentTime = new Date().getTime(); c.sentStatus = RongIMLib.SentStatus.SENDING; c.senderUserName = ""; c.senderUserId = RongIMLib.Bridge._client.userId; c.notificationStatus = RongIMLib.ConversationNotificationStatus.DO_NOT_DISTURB; c.latestMessage = msg; c.unreadMessageCount = 0; RongIMLib.RongIMClient._dataAccessProvider.addConversation(c, { onSuccess: function (data) { } }); } RongIMLib.RongIMClient._memoryStore.converStore = c; msg.content = messageContent; msg.conversationType = conversationType; msg.senderUserId = RongIMLib.Bridge._client.userId; msg.objectName = RongIMLib.RongIMClient.MessageParams[messageContent.messageName].objectName; msg.targetId = targetId; msg.sentTime = new Date().getTime(); msg.messageDirection = RongIMLib.MessageDirection.SEND; msg.sentStatus = RongIMLib.SentStatus.SENT; msg.messageType = messageContent.messageName; msg.disableNotification = params.disableNotification || false; RongIMLib.RongIMClient.bridge.pubMsg(conversationType.valueOf(), content, targetId, { onSuccess: function (data) { if (data && data.timestamp) { RongIMLib.RongIMClient._memoryStore.lastReadTime.set('converST_' + RongIMLib.Bridge._client.userId + conversationType + targetId, data.timestamp); } if ((conversationType == RongIMLib.ConversationType.DISCUSSION || conversationType == RongIMLib.ConversationType.GROUP) && messageContent.messageName == RongIMLib.RongIMClient.MessageType["ReadReceiptRequestMessage"]) { var reqMsg = msg.content; var sentkey = RongIMLib.Bridge._client.userId + reqMsg.messageUId + "SENT"; RongIMLib.RongIMClient._storageProvider.setItem(sentkey, JSON.stringify({ count: 0, dealtime: data.timestamp, userIds: {} })); } if (RongIMLib.RongIMClient.MessageParams[msg.messageType].msgTag.getMessageTag() == 3) { var cacheConversation = RongIMLib.RongIMClient._memoryStore.converStore; cacheConversation.sentStatus = msg.sentStatus; cacheConversation.latestMessage = msg; me.updateConversation(cacheConversation); var Conversation = RongIMLib.RongIMClient._dataAccessProvider.Conversation; Conversation._notify(RongIMLib.RongIMClient._memoryStore.conversationList); RongIMLib.RongIMClient._dataAccessProvider.addMessage(conversationType, targetId, msg, { onSuccess: function (ret) { msg = ret; msg.messageUId = data.messageUId; msg.sentTime = data.timestamp; msg.sentStatus = RongIMLib.SentStatus.SENT; msg.messageId = data.messageId; RongIMLib.RongIMClient._dataAccessProvider.updateMessage(msg); }, onError: function () { } }); } setTimeout(function () { cacheConversation && me.updateConversation(cacheConversation); msg.sentTime = data.timestamp; msg.messageUId = data.messageUId; sendCallback.onSuccess(msg); }); }, onError: function (errorCode, _msg) { msg.sentStatus = RongIMLib.SentStatus.FAILED; if (_msg) { msg.messageUId = _msg.messageUId; msg.sentTime = _msg.sentTime; } if (RongIMLib.RongIMClient.MessageParams[msg.messageType].msgTag.getMessageTag() == 3) { RongIMLib.RongIMClient._memoryStore.converStore.latestMessage = msg; } RongIMLib.RongIMClient._dataAccessProvider.addMessage(conversationType, targetId, msg, { onSuccess: function (ret) { msg.messageId = ret.messageId; RongIMLib.RongIMClient._dataAccessProvider.updateMessage(msg); }, onError: function () { } }); setTimeout(function () { sendCallback.onError(errorCode, msg); }); } }, null, methodType, params); sendCallback.onBefore && sendCallback.onBefore(RongIMLib.MessageIdHandler.messageId); msg.messageId = RongIMLib.MessageIdHandler.messageId + ""; }; ServerDataProvider.prototype.setConnectionStatusListener = function (listener) { if (RongIMLib.RongUtil.isObject(listener) && RongIMLib.RongUtil.isFunction(listener.onChanged)) { RongIMLib.RongIMClient.statusListeners.push(listener.onChanged); } }; ServerDataProvider.prototype.setOnReceiveMessageListener = function (listener) { if (RongIMLib.RongUtil.isObject(listener) && RongIMLib.RongUtil.isFunction(listener.onReceived)) { RongIMLib.RongIMClient.messageListeners.push(listener.onReceived); } }; ServerDataProvider.prototype.registerMessageType = function (messageType, objectName, messageTag, messageContent, searchProps) { if (!messageType) { throw new Error("messageType can't be empty,postion -> registerMessageType"); } if (!objectName) { throw new Error("objectName can't be empty,postion -> registerMessageType"); } if (Object.prototype.toString.call(messageContent) == "[object Array]") { var regMsg = RongIMLib.ModelUtil.modleCreate(messageContent, messageType); RongIMLib.RongIMClient.RegisterMessage[messageType] = regMsg; } else if (Object.prototype.toString.call(messageContent) == "[object Function]" || Object.prototype.toString.call(messageContent) == "[object Object]") { if (!messageContent.encode) { throw new Error("encode method has not realized or messageName is undefined-> registerMessageType"); } if (!messageContent.decode) { throw new Error("decode method has not realized -> registerMessageType"); } } else { throw new Error("The index of 3 parameter was wrong type must be object or function or array-> registerMessageType"); } registerMessageTypeMapping[objectName] = messageType; }; ServerDataProvider.prototype.registerMessageTypes = function (messages) { var types = []; var getProtos = function (proto) { var protos = []; for (var p in proto) { protos.push(p); } return protos; }; //转换消息为自定义消息参数格式 for (var name in messages) { var message = messages[name]; var proto = message.proto; var protos = getProtos(proto); var flag = message.flag || 3; var tag = RongIMLib.MessageTag.getTagByStatus(flag); flag = new RongIMLib.MessageTag(tag.isCounted, tag.isPersited); types.push({ type: name, name: message.name, flag: flag, protos: protos }); } var register = function (message) { var type = message.type; var name = message.name; var flag = message.flag; var protos = message.protos; RongIMLib.RongIMClient.registerMessageType(type, name, flag, protos); }; for (var i = 0, len = types.length; i < len; i++) { var message = types[i]; register(message); } }; /** * 向缓存会话列表内添加新会话或更新会话 */ ServerDataProvider.prototype.addConversation = function (conversation, callback) { var isAdd = true; for (var i = 0, len = RongIMLib.RongIMClient._memoryStore.conversationList.length; i < len; i++) { if (RongIMLib.RongIMClient._memoryStore.conversationList[i].conversationType === conversation.conversationType && RongIMLib.RongIMClient._memoryStore.conversationList[i].targetId === conversation.targetId) { // RongIMClient._memoryStore.conversationList[i] = conversation; RongIMLib.RongIMClient._memoryStore.conversationList.unshift(RongIMLib.RongIMClient._memoryStore.conversationList.splice(i, 1)[0]); isAdd = false; break; } } if (isAdd) { RongIMLib.RongIMClient._memoryStore.conversationList.unshift(conversation); } callback && callback.onSuccess(true); }; /** * 更新缓存会话字段 */ ServerDataProvider.prototype.updateConversation = function (conversation) { var conver; for (var i = 0, len = RongIMLib.RongIMClient._memoryStore.conversationList.length; i < len; i++) { var item = RongIMLib.RongIMClient._memoryStore.conversationList[i]; if (conversation.conversationType === item.conversationType && conversation.targetId === item.targetId) { conversation.conversationTitle && (item.conversationTitle = conversation.conversationTitle); conversation.senderUserName && (item.senderUserName = conversation.senderUserName); conversation.senderPortraitUri && (item.senderPortraitUri = conversation.senderPortraitUri); conversation.latestMessage && (item.latestMessage = conversation.latestMessage); conversation.sentStatus && (item.sentStatus = conversation.sentStatus); break; } } return conver; }; /** * 移除 IM Server 端会话,并清除缓存内会话 */ ServerDataProvider.prototype.removeConversation = function (conversationType, targetId, callback) { var mod = new RongIMLib.RongIMClient.Protobuf.RelationsInput(); mod.setType(conversationType); RongIMLib.RongIMClient.bridge.queryMsg(27, RongIMLib.MessageUtil.ArrayForm(mod.toArrayBuffer()), targetId, { onSuccess: function () { var isRemoved = false; var conversations = RongIMLib.RongIMClient._memoryStore.conversationList; var len = conversations.length; for (var i = 0; i < len; i++) { if (conversations[i].conversationType == conversationType && targetId == conversations[i].targetId) { conversations.splice(i, 1); isRemoved = true; break; } } isRemoved && RongIMLib.RongIMClient._dataAccessProvider.Conversation._notify(RongIMLib.RongIMClient._memoryStore.conversationList); callback.onSuccess(true); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.getMessage = function (messageId, callback) { callback.onSuccess(new RongIMLib.Message()); }; ServerDataProvider.prototype.addMessage = function (conversationType, targetId, message, callback) { if (callback) { callback.onSuccess(message); } }; ServerDataProvider.prototype.removeMessage = function (conversationType, targetId, messages, callback) { RongIMLib.RongIMClient.getInstance().deleteRemoteMessages(conversationType, targetId, messages, callback); }; ServerDataProvider.prototype.removeLocalMessage = function (conversationType, targetId, timestamps, callback) { callback.onSuccess(true); }; ServerDataProvider.prototype.updateMessage = function (message, callback) { if (callback) { callback.onSuccess(message); } }; ServerDataProvider.prototype.deleteRemoteMessages = function (conversationType, targetId, messages, callback) { if (!RongIMLib.RongIMClient.Protobuf.DeleteMsgInput) { throw new Error('SDK Protobuf version is too low'); } var modules = new RongIMLib.RongIMClient.Protobuf.DeleteMsgInput(); var msgs = []; RongIMLib.RongUtil.forEach(messages, function (msg) { msgs.push({ msgId: msg.messageUId, msgDataTime: msg.sentTime, direct: msg.messageDirection }); }); modules.setType(conversationType); modules.setConversationId(targetId); modules.setMsgs(msgs); RongIMLib.RongIMClient.bridge.queryMsg('delMsg', RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), targetId, { onSuccess: function (result) { callback.onSuccess(result); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }, 'DeleteMsgOutput'); }; ServerDataProvider.prototype.clearRemoteHistoryMessages = function (params, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.CleanHisMsgInput(); var conversationType = params.conversationType; var _topic = { 1: 'cleanPMsg', 2: 'cleanDMsg', 3: 'cleanGMsg', 5: 'cleanCMsg', 6: 'cleanSMsg' }; var topic = _topic[conversationType]; if (!topic) { callback.onError(RongIMLib.ErrorCode.CLEAR_HIS_TYPE_ERROR); return; } var timestamp = params.timestamp; if (typeof timestamp != 'number') { callback.onError(RongIMLib.ErrorCode.CLEAR_HIS_TIME_ERROR); return; } modules.setDataTime(timestamp); var targetId = params.targetId; modules.setTargetId(targetId); RongIMLib.RongIMClient.bridge.queryMsg(topic, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), targetId, { onSuccess: function (result) { callback.onSuccess(!result); }, onError: function (error) { // error 1 历史消息云存储没有开通、传入时间大于服务器时间 清除失败,1 与其他错误码冲突,所以自定义错误码返回 if (error == 1) { error = RongIMLib.ErrorCode.CLEAR_HIS_ERROR; } setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.clearHistoryMessages = function (params, callback) { this.clearRemoteHistoryMessages(params, callback); }; // 兼容老版本 ServerDataProvider.prototype.clearMessages = function (conversationType, targetId, callback) { }; ServerDataProvider.prototype.updateMessages = function (conversationType, targetId, key, value, callback) { var me = this; if (key == "readStatus") { if (RongIMLib.RongIMClient._memoryStore.conversationList.length > 0) { me.getConversationList({ onSuccess: function (list) { Array.forEach(list, function (conver) { if (conver.conversationType == conversationType && conver.targetId == targetId) { conver.unreadMessageCount = 0; } }); }, onError: function (errorCode) { setTimeout(function () { callback.onError(errorCode); }); } }, null); } } setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.getConversation = function (conversationType, targetId, callback) { var conver = null; for (var i = 0, len = RongIMLib.RongIMClient._memoryStore.conversationList.length; i < len; i++) { if (RongIMLib.RongIMClient._memoryStore.conversationList[i].conversationType == conversationType && RongIMLib.RongIMClient._memoryStore.conversationList[i].targetId == targetId) { conver = RongIMLib.RongIMClient._memoryStore.conversationList[i]; if (RongIMLib.RongUtil.supportLocalStorage()) { // var count = RongIMClient._storageProvider.getItem("cu" + Bridge._client.userId + conversationType + targetId); var count = RongIMLib.UnreadCountHandler.get(conversationType, targetId); if (conver.unreadMessageCount == 0) { conver.unreadMessageCount = Number(count); } } } } setTimeout(function () { callback && callback.onSuccess(conver); }); return conver; }; ServerDataProvider.prototype.filterConversations = function (types, list) { var conversaions = []; RongIMLib.RongUtil.forEach(types, function (type) { RongIMLib.RongUtil.forEach(list, function (conversation) { if (conversation.conversationType == type) { conversaions.push(conversation); } }); }); return conversaions; }; ServerDataProvider.prototype.getConversationList = function (callback, conversationTypes, count, isHidden) { var that = this; var isSync = RongIMLib.RongIMClient._memoryStore.isSyncRemoteConverList; var list = RongIMLib.RongIMClient._memoryStore.conversationList; if (!RongIMLib.RongUtil.isNumber(count)) { count = 200; } var isLocalInclude = list.length >= count; if (!isSync && (isLocalInclude || RongIMLib.RongIMClient._memoryStore.isFullConversations)) { setTimeout(function () { var _list = JSON.parse(JSON.stringify(list)); var localList = _list.slice(0, count); if (conversationTypes) { localList = that.filterConversations(conversationTypes, localList); } callback.onSuccess(localList); }); return; } RongIMLib.RongIMClient.getInstance().getRemoteConversationList({ onSuccess: function (list) { if (RongIMLib.RongUtil.supportLocalStorage()) { Array.forEach(RongIMLib.RongIMClient._memoryStore.conversationList, function (item) { // var count = RongIMClient._storageProvider.getItem("cu" + Bridge._client.userId + item.conversationType + item.targetId); var count = RongIMLib.UnreadCountHandler.get(item.conversationType, item.targetId); if (item.unreadMessageCount == 0) { item.unreadMessageCount = Number(count); } }); } RongIMLib.RongIMClient._memoryStore.isSyncRemoteConverList = false; var isFullConversations = count > list.length; RongIMLib.RongIMClient._memoryStore.isFullConversations = isFullConversations; setTimeout(function () { callback.onSuccess(list); }); }, onError: function (errorcode) { setTimeout(function () { callback.onError(errorcode); }); } }, conversationTypes, count, isHidden); }; ServerDataProvider.prototype.clearCache = function () { var memoryStore = RongIMLib.RongIMClient._memoryStore || {}; memoryStore.conversationList = []; memoryStore.isSyncRemoteConverList = true; }; ServerDataProvider.prototype.clearConversations = function (conversationTypes, callback) { Array.forEach(conversationTypes, function (conversationType) { Array.forEach(RongIMLib.RongIMClient._memoryStore.conversationList, function (conver) { if (conversationType == conver.conversationType) { RongIMLib.RongIMClient.getInstance().removeConversation(conver.conversationType, conver.targetId, { onSuccess: function () { }, onError: function () { } }); } }); }); setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.setMessageContent = function (messageId, content, objectname) { }; ; ServerDataProvider.prototype.setMessageSearchField = function (messageId, content, searchFiles) { }; ; ServerDataProvider.prototype.getHistoryMessages = function (conversationType, targetId, timestamp, count, callback, objectname, order) { var config = { objectname: objectname, order: order }; RongIMLib.RongIMClient.getInstance().getRemoteHistoryMessages(conversationType, targetId, timestamp, count, callback, config); }; ServerDataProvider.prototype.getTotalUnreadCount = function (callback, conversationTypes) { var count = RongIMLib.UnreadCountHandler.getAll(conversationTypes); callback.onSuccess(count); return count; }; ServerDataProvider.prototype.getConversationUnreadCount = function (conversationTypes, callback) { var count = 0; Array.forEach(conversationTypes, function (converType) { Array.forEach(RongIMLib.RongIMClient._memoryStore.conversationList, function (conver) { if (conver.conversationType == converType) { count += conver.unreadMessageCount; } }); }); setTimeout(function () { callback.onSuccess(count); }); }; //由于 Web 端未读消息数按会话统计,撤回消息会导致未读数不准确,提供设置未读数接口,桌面版不实现此方法 ServerDataProvider.prototype.setUnreadCount = function (conversationType, targetId, count, sentTime) { sentTime = sentTime || new Date().getTime(); RongIMLib.UnreadCountHandler.set(conversationType, targetId, count, sentTime); }; ServerDataProvider.prototype.getUnreadCount = function (conversationType, targetId, callback) { var unreadCount = RongIMLib.UnreadCountHandler.get(conversationType, targetId); setTimeout(function () { callback.onSuccess(unreadCount || 0); }); }; ServerDataProvider.prototype.cleanMentioneds = function (conver) { if (conver) { conver.mentionedMsg = null; var targetId = conver.targetId; var conversationType = conver.conversationType; var mentioneds = RongIMLib.RongIMClient._storageProvider.getItem("mentioneds_" + RongIMLib.Bridge._client.userId + '_' + conversationType + '_' + targetId); if (mentioneds) { var info = JSON.parse(mentioneds); delete info[conversationType + "_" + targetId]; if (!RongIMLib.MessageUtil.isEmpty(info)) { RongIMLib.RongIMClient._storageProvider.setItem("mentioneds_" + RongIMLib.Bridge._client.userId + '_' + conversationType + '_' + targetId, JSON.stringify(info)); } else { RongIMLib.RongIMClient._storageProvider.removeItem("mentioneds_" + RongIMLib.Bridge._client.userId + '_' + conversationType + '_' + targetId); } } } }; ServerDataProvider.prototype.clearUnreadCountByTimestamp = function (conversationType, targetId, timestamp, callback) { setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.clearUnreadCount = function (conversationType, targetId, callback) { var me = this; // RongIMClient._storageProvider.removeItem("cu" + Bridge._client.userId + conversationType + targetId); RongIMLib.UnreadCountHandler.remove(conversationType, targetId); this.getConversation(conversationType, targetId, { onSuccess: function (conver) { conver = conver || new RongIMLib.Conversation(); var isNotifyConversation = conver.unreadMessageCount; if (conver) { conver.unreadMessageCount = 0; me.cleanMentioneds(conver); } setTimeout(function () { callback.onSuccess(true); isNotifyConversation && RongIMLib.RongIMClient._dataAccessProvider.Conversation._notify(RongIMLib.RongIMClient._memoryStore.conversationList); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.clearTotalUnreadCount = function (callback) { var list = RongIMLib.RongIMClient._memoryStore.conversationList; var me = this; var isNotifyConversation = false; if (list) { // 清除 mentioneds、清除 list 中的 unreadMessageCount for (var i = 0; i < list.length; i++) { var conver = list[i]; if (conver) { isNotifyConversation = conver.unreadMessageCount ? true : isNotifyConversation; conver.unreadMessageCount = 0; me.cleanMentioneds(conver); } } } RongIMLib.UnreadCountHandler.clear(); setTimeout(function () { callback.onSuccess(true); isNotifyConversation && RongIMLib.RongIMClient._dataAccessProvider.Conversation._notify(RongIMLib.RongIMClient._memoryStore.conversationList); }); }; ServerDataProvider.prototype.setConversationToTop = function (conversationType, targetId, isTop, callback) { var me = this; this.getConversation(conversationType, targetId, { onSuccess: function (conver) { conver.isTop = isTop; me.addConversation(conver, callback); setTimeout(function () { callback.onSuccess(true); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.getConversationNotificationStatus = function (params, callback) { var targetId = params.targetId; var conversationType = params.conversationType; var notification = RongIMLib.RongIMClient._memoryStore.notification; var getKey = function () { return conversationType + '_' + targetId; }; var key = getKey(); var status = notification[key]; if (typeof status == 'number') { callback.onSuccess(status); return; } var topics = { 1: 'qryPPush', 3: 'qryDPush' }; var topic = topics[conversationType]; if (!topic) { var error = 8001; callback.onError(error); return; } var modules = new RongIMLib.RongIMClient.Protobuf.BlockPushInput(); modules.setBlockeeId(targetId); var userId = RongIMLib.Bridge._client.userId; var success = function (status) { notification[key] = status; setTimeout(function () { callback.onSuccess(status); }); }; RongIMLib.RongIMClient.bridge.queryMsg(topic, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function (status) { success(status); }, onError: function (e) { if (e == 1) { success(e); } else { setTimeout(function () { callback.onError(e); }); } } }); }; ServerDataProvider.prototype.setConversationStatus = function (type, targetId, statusItem, callback) { var self = this; var modules = new RongIMLib.RongIMClient.Protobuf.SessionStateModifyReq(); var userId = RongIMLib.Bridge._client.userId; var time = +new Date(); var stateItemModules = []; if (!RongIMLib.RongUtil.isUndefined(statusItem.notificationStatus)) { var isNotDisturbe = statusItem.notificationStatus === RongIMLib.ConversationNotificationStatus.DO_NOT_DISTURB; stateItemModules.push({ sessionStateType: 1, value: isNotDisturbe ? '1' : '0' }); } if (!RongIMLib.RongUtil.isUndefined(statusItem.isTop)) { stateItemModules.push({ sessionStateType: 2, value: statusItem.isTop ? '1' : '0' }); } var stateModules = { type: type, channelId: targetId, time: time, stateItem: stateItemModules }; modules.setVersion(time); modules.setState([stateModules]); RongIMLib.RongIMClient.bridge.queryMsg('setSeAtt', RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function (result) { var time = RongIMLib.MessageUtil.int64ToTimestamp(result.version); statusItem.updateTime = time; statusItem.isLastInAPull = true; self.conversationStatusManager.set(type, targetId, statusItem); setTimeout(function () { callback.onSuccess(time); }); }, onError: function (e) { setTimeout(function () { callback.onError(e); }); } }, 'SessionStateModifyResp'); }; ServerDataProvider.prototype.pullConversationStatus = function (time, callback) { time = time || 0; var modules = new RongIMLib.RongIMClient.Protobuf.SessionReq(); modules.setTime(time); var userId = RongIMLib.Bridge._client.userId; RongIMLib.RongIMClient.bridge.queryMsg('pullSeAtts', RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function (result) { var sessionStateList = result.state, lastTime = result.version; var sessionLength = sessionStateList.length; RongIMLib.RongUtil.forEach(sessionStateList, function (state, index) { var type = state.type, targetId = state.channelId, updateTime = state.time, stateItem = state.stateItem; var isSilent = false, isTop = false; RongIMLib.RongUtil.forEach(stateItem, function (item) { var sessionStateType = item.sessionStateType, value = item.value; if (sessionStateType === 1) { isSilent = !!Number(value); } if (sessionStateType === 2) { isTop = !!Number(value); } }); var isLastInAPull = index === sessionLength - 1; callback.onStatus(type, targetId, { notificationStatus: isSilent ? RongIMLib.ConversationNotificationStatus.DO_NOT_DISTURB : RongIMLib.ConversationNotificationStatus.NOTIFY, isTop: isTop, updateTime: RongIMLib.MessageUtil.int64ToTimestamp(updateTime), isLastInAPull: isLastInAPull }); }); callback.onSuccess(RongIMLib.MessageUtil.int64ToTimestamp(lastTime)); }, onError: function (e) { setTimeout(function () { callback.onError(e); }); } }, 'SessionStates'); }; ServerDataProvider.prototype.setConversationNotificationStatus = function (params, callback) { var conversationType = params.conversationType; var targetId = params.targetId; var status = params.status; var getKey = function () { return conversationType + '_' + status; }; var topics = { '1_1': 'blkPPush', '3_1': 'blkDPush', '1_0': 'unblkPPush', '3_0': 'unblkDPush' }; var key = getKey(); var notification = RongIMLib.RongIMClient._memoryStore.notification; notification[key] = status; var topic = topics[key]; if (!topic) { var error = 8001; setTimeout(function () { callback.onError(error); }); return; } var modules = new RongIMLib.RongIMClient.Protobuf.BlockPushInput(); modules.setBlockeeId(targetId); var userId = RongIMLib.Bridge._client.userId; RongIMLib.RongIMClient.bridge.queryMsg(topic, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function (status) { setTimeout(function () { callback.onSuccess(status); }); }, onError: function (e) { setTimeout(function () { callback.onError(e); }); } }); }; ServerDataProvider.prototype.getUserStatus = function (userId, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.GetUserStatusInput(); userId = RongIMLib.Bridge._client.userId; RongIMLib.RongIMClient.bridge.queryMsg(35, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function (status) { status = RongIMLib.RongInnerTools.convertUserStatus(status); setTimeout(function () { callback.onSuccess(status); }); }, onError: function (e) { setTimeout(function () { callback.onError(e); }); } }, 'GetUserStatusOutput'); // callback.onSuccess(new UserStatus()); }; ServerDataProvider.prototype.setUserStatus = function (status, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.SetUserStatusInput(); var userId = RongIMLib.Bridge._client.userId; if (status) { modules.setStatus(status); } RongIMLib.RongIMClient.bridge.queryMsg(36, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function (status) { setTimeout(function () { callback.onSuccess(true); }); }, onError: function (e) { setTimeout(function () { callback.onError(e); }); } }, 'SetUserStatusOutput'); }; ServerDataProvider.prototype.subscribeUserStatus = function (userIds, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.SubUserStatusInput(); var userId = RongIMLib.Bridge._client.userId; modules.setUserid(userIds); RongIMLib.RongIMClient.bridge.queryMsg(37, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function (status) { setTimeout(function () { callback && callback.onSuccess(true); }); }, onError: function (e) { setTimeout(function () { callback && callback.onError(e); }); } }, 'SubUserStatusOutput'); }; ServerDataProvider.prototype.setUserStatusListener = function (params, callback) { RongIMLib.RongIMClient.userStatusListener = callback; var userIds = params.userIds || []; if (userIds.length) { RongIMLib.RongIMClient._dataAccessProvider.subscribeUserStatus(userIds); } }; ServerDataProvider.prototype.clearListeners = function () { }; ServerDataProvider.prototype.setServerInfo = function (info) { }; ServerDataProvider.prototype.getUnreadMentionedMessages = function (conversationType, targetId) { return null; }; ServerDataProvider.prototype.setConversationHidden = function (conversationType, targetId, isHidden) { }; ServerDataProvider.prototype.setMessageExtra = function (messageId, value, callback) { setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.setMessageReceivedStatus = function (messageId, receivedStatus, callback) { setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.setMessageSentStatus = function (messageId, sentStatus, callback) { setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.getAllConversations = function (callback) { setTimeout(function () { callback.onSuccess([]); }); }; ServerDataProvider.prototype.getConversationByContent = function (keywords, callback) { setTimeout(function () { callback.onSuccess([]); }); }; ServerDataProvider.prototype.getMessagesFromConversation = function (conversationType, targetId, keywords, callback) { setTimeout(function () { callback.onSuccess([]); }); }; ServerDataProvider.prototype.searchConversationByContent = function (keyword, callback, conversationTypes) { setTimeout(function () { callback.onSuccess([]); }); }; ServerDataProvider.prototype.searchMessageByContent = function (conversationType, targetId, keyword, timestamp, count, total, callback) { setTimeout(function () { callback.onSuccess([]); }); }; ServerDataProvider.prototype.getDelaTime = function () { return RongIMLib.RongIMClient._memoryStore.deltaTime; }; ServerDataProvider.prototype.getCurrentConnectionStatus = function () { var client = RongIMLib.Bridge._client || {}; var channel = client.channel || {}; var status = RongIMLib.ConnectionStatus.CONNECTION_CLOSED; if (typeof channel.connectionStatus == 'number') { status = channel.connectionStatus; } return status; }; ServerDataProvider.prototype.getAgoraDynamicKey = function (engineType, channelName, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.VoipDynamicInput(); modules.setEngineType(engineType); modules.setChannelName(channelName); RongIMLib.RongIMClient.bridge.queryMsg(32, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (result) { setTimeout(function () { callback.onSuccess(result); }); }, onError: function (errorCode) { setTimeout(function () { callback.onError(errorCode); }); } }, "VoipDynamicOutput"); }; ServerDataProvider.prototype.setDeviceInfo = function (deviceId) { }; ServerDataProvider.prototype.setEnvironment = function (isPrivate) { }; ServerDataProvider.prototype.clearData = function () { return true; }; ServerDataProvider.prototype.getPublicServiceProfile = function (publicServiceType, publicServiceId, callback) { var profile = RongIMLib.RongIMClient._memoryStore.publicServiceMap.get(publicServiceType, publicServiceId); setTimeout(function () { callback.onSuccess(profile); }); }; ServerDataProvider.prototype.getRemotePublicServiceList = function (callback, pullMessageTime) { if (RongIMLib.RongIMClient._memoryStore.depend.openMp) { var modules = new RongIMLib.RongIMClient.Protobuf.PullMpInput(), self = this; if (!pullMessageTime) { modules.setTime(0); } else { modules.setTime(pullMessageTime); } modules.setMpid(""); RongIMLib.RongIMClient.bridge.queryMsg(28, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (data) { //TODO 找出最大时间 // self.lastReadTime.set(conversationType + targetId, MessageUtil.int64ToTimestamp(data.syncTime)); RongIMLib.RongIMClient._memoryStore.publicServiceMap.publicServiceList.length = 0; RongIMLib.RongIMClient._memoryStore.publicServiceMap.publicServiceList = data; setTimeout(function () { callback && callback.onSuccess(data); }); }, onError: function (errorCode) { setTimeout(function () { callback && callback.onError(errorCode); }); } }, "PullMpOutput"); } }; ServerDataProvider.prototype.getRTCUserInfoList = function (room, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcQueryListInput(); // 1 是正序,2是倒序 modules.setOrder(2); RongIMLib.RongIMClient.bridge.queryMsg("rtcUData", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function (result) { var users = {}; var list = result.list; RongIMLib.RongUtil.forEach(list, function (item) { var userId = item.userId; var tmpData = {}; RongIMLib.RongUtil.forEach(item.userData, function (data) { var key = data.key; var value = data.value; tmpData[key] = value; }); users[userId] = tmpData; }); callback.onSuccess(users); }, onError: function (errorCode) { callback.onError(errorCode); } }, "RtcUserListOutput"); }; ServerDataProvider.prototype.getRTCUserList = function (room, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcQueryListInput(); modules.setOrder(2); RongIMLib.RongIMClient.bridge.queryMsg("rtcUList", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function (result) { callback.onSuccess({ users: result.list }); }, onError: function (errorCode) { callback.onError(errorCode); } }, "RtcUserListOutput"); }; ServerDataProvider.prototype.setRTCUserInfo = function (room, info, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcValueInfo(); modules.setKey(info.key); modules.setValue(info.value); RongIMLib.RongIMClient.bridge.queryMsg("rtcUPut", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function () { callback.onSuccess(true); }, onError: function (errorCode) { callback.onError(errorCode); } }); }; ServerDataProvider.prototype.removeRTCUserInfo = function (room, info, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcKeyDeleteInput(); var keys = info.keys || []; if (!RongIMLib.RongUtil.isArray(keys)) { keys = [keys]; } modules.setKey(keys); RongIMLib.RongIMClient.bridge.queryMsg("rtcUDel", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function () { callback.onSuccess(true); }, onError: function (errorCode) { callback.onError(errorCode); } }); }; ServerDataProvider.prototype.getRTCRoomInfo = function (room, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcQueryListInput(); modules.setOrder(2); RongIMLib.RongIMClient.bridge.queryMsg("rtcRInfo", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function (result) { var room = { id: result.roomId, total: result.userCount }; RongIMLib.RongUtil.forEach(result.roomData, function (data) { room[data.key] = data.value; }); callback.onSuccess(room); }, onError: function (errorCode) { callback.onError(errorCode); } }, "RtcRoomInfoOutput"); }; ServerDataProvider.prototype.setRTCRoomInfo = function (room, info, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcValueInfo(); modules.setKey(info.key); modules.setValue(info.value); RongIMLib.RongIMClient.bridge.queryMsg("rtcRPut", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function () { callback.onSuccess(true); }, onError: function (errorCode) { callback.onError(errorCode); } }); }; ServerDataProvider.prototype.removeRTCRoomInfo = function (room, info, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcKeyDeleteInput(); var keys = info.keys || []; if (!RongIMLib.RongUtil.isArray(keys)) { keys = [keys]; } modules.setKey(keys); RongIMLib.RongIMClient.bridge.queryMsg("rtcRDel", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function () { callback.onSuccess(true); }, onError: function (errorCode) { callback.onError(errorCode); } }); }; ServerDataProvider.prototype.joinRTCRoom = function (room, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcInput(); var mode = room.mode || 0; modules.setRoomType(mode); if (room.broadcastType) { modules.setBroadcastType(room.broadcastType); } RongIMLib.RongIMClient.bridge.queryMsg("rtcRJoin_data", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function (result) { var users = {}; var list = result.list, token = result.token, sessionId = result.sessionId; RongIMLib.RongUtil.forEach(list, function (item) { var userId = item.userId; var tmpData = {}; RongIMLib.RongUtil.forEach(item.userData, function (data) { var key = data.key; var value = data.value; tmpData[key] = value; }); users[userId] = tmpData; }); callback.onSuccess({ users: users, token: token, sessionId: sessionId }); }, onError: function (errorCode) { callback.onError(errorCode); } }, "RtcUserListOutput"); }; ServerDataProvider.prototype.quitRTCRoom = function (room, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.SetUserStatusInput(); RongIMLib.RongIMClient.bridge.queryMsg("rtcRExit", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function () { callback.onSuccess(true); }, onError: function (errorCode) { callback.onError(errorCode); } }); }; ServerDataProvider.prototype.RTCPing = function (room, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcInput(); var mode = room.mode || 0; modules.setRoomType(mode); if (room.broadcastType) { modules.setBroadcastType(room.broadcastType); } RongIMLib.RongIMClient.bridge.queryMsg("rtcPing", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, callback); }; /** * 全量订阅资源修改 * @param roomId 房间 Id * @param message 增量数据 * @param valueInfo 全量资源信息 * @param objectName 消息名称 * @param callback */ ServerDataProvider.prototype.setRTCTotalRes = function (roomId, message, valueInfo, objectName, callback) { // 全量 URI 新增 // 全量发布中 // valueInfo: key 为 uris,值为 全量的订阅信息 // content: key 为增量数据消息 RCRTC:ModifyResource,value 为增量订阅信息 var modules = new RongIMLib.RongIMClient.Protobuf.RtcUserSetDataInput(); modules.setObjectName(objectName); // content var val = new RongIMLib.RongIMClient.Protobuf.RtcValueInfo(); val.setKey(message.name); val.setValue(message.content); modules.setContent(val); // valueInfo val = new RongIMLib.RongIMClient.Protobuf.RtcValueInfo(); val.setKey('uris'); val.setValue(valueInfo); modules.setValueInfo(val); var arrayBuff = RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()); RongIMLib.RongIMClient.bridge.queryMsg("userSetData", arrayBuff, roomId, callback, "RtcOutput"); }; ServerDataProvider.prototype.setRTCData = function (roomId, key, value, isInner, apiType, callback, message) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcSetDataInput(); modules.setInterior(isInner); modules.setTarget(apiType); modules.setKey(key); modules.setValue(value); message = message || {}; var name = message.name; var content = message.content; if (name) { modules.setObjectName(name); } if (content) { if (!RongIMLib.RongUtil.isString(content)) { content = JSON.stringify(content); } modules.setContent(content); } RongIMLib.RongIMClient.bridge.queryMsg("rtcSetData", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), roomId, callback, "RtcOutput"); }; ServerDataProvider.prototype.getRTCData = function (roomId, keys, isInner, apiType, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcDataInput(); modules.setInterior(isInner); modules.setTarget(apiType); modules.setKey(keys); RongIMLib.RongIMClient.bridge.queryMsg("rtcQryData", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), roomId, { onSuccess: function (result) { var props = {}; var list = result.outInfo; RongIMLib.RongUtil.forEach(list, function (item) { props[item.key] = item.value; }); callback.onSuccess(props); }, onError: callback.onError }, "RtcQryOutput"); }; ServerDataProvider.prototype.removeRTCData = function (roomId, keys, isInner, apiType, callback, message) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcDataInput(); modules.setInterior(isInner); modules.setTarget(apiType); modules.setKey(keys); message = message || {}; var name = message.name; var content = message.content; if (name) { modules.setObjectName(name); } if (content) { if (!RongIMLib.RongUtil.isString(content)) { content = JSON.stringify(content); } modules.setContent(content); } RongIMLib.RongIMClient.bridge.queryMsg("rtcDelData", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), roomId, callback, "RtcOutput"); }; ServerDataProvider.prototype.setRTCUserData = function (roomId, key, value, isInner, callback, message) { this.setRTCData(roomId, key, value, isInner, RongIMLib.RTCAPIType.PERSON, callback, message); }; ServerDataProvider.prototype.setRTCUserTotalRes = function (roomId, message, valueInfo, objectName, callback) { this.setRTCTotalRes(roomId, message, valueInfo, objectName, callback); }; ServerDataProvider.prototype.getRTCUserData = function (roomId, keys, isInner, callback, message) { this.getRTCData(roomId, keys, isInner, RongIMLib.RTCAPIType.PERSON, callback); }; ServerDataProvider.prototype.removeRTCUserData = function (roomId, keys, isInner, callback, message) { this.removeRTCData(roomId, keys, isInner, RongIMLib.RTCAPIType.PERSON, callback, message); }; ServerDataProvider.prototype.setRTCRoomData = function (roomId, key, value, isInner, callback, message) { this.setRTCData(roomId, key, value, isInner, RongIMLib.RTCAPIType.ROOM, callback, message); }; ServerDataProvider.prototype.getRTCRoomData = function (roomId, keys, isInner, callback, message) { this.getRTCData(roomId, keys, isInner, RongIMLib.RTCAPIType.ROOM, callback); }; ServerDataProvider.prototype.removeRTCRoomData = function (roomId, keys, isInner, callback, message) { this.removeRTCData(roomId, keys, isInner, RongIMLib.RTCAPIType.ROOM, callback, message); }; // 信令 SDK 新增 ServerDataProvider.prototype.setRTCOutData = function (roomId, data, type, callback, message) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcSetOutDataInput(); modules.setTarget(type); if (!RongIMLib.RongUtil.isArray(data)) { data = [data]; } for (var i = 0; i < data.length; i++) { var item = data[i]; if (item.key) { item.key = item.key.toString(); } if (item.value) { item.value = item.value.toString(); } } modules.setValueInfo(data); message = message || {}; var name = message.name; var content = message.content; if (name) { modules.setObjectName(name); } if (content) { if (!RongIMLib.RongUtil.isString(content)) { content = JSON.stringify(content); } modules.setContent(content); } RongIMLib.RongIMClient.bridge.queryMsg("rtcSetOutData", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), roomId, callback, "RtcOutput"); }; // 信令 SDK 新增 ServerDataProvider.prototype.getRTCOutData = function (roomId, userIds, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcQryUserOutDataInput(); modules.setUserId(userIds); RongIMLib.RongIMClient.bridge.queryMsg("rtcQryUserOutData", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), roomId, callback, "RtcUserOutDataOutput"); }; ServerDataProvider.prototype.getNavi = function () { var navi = RongIMLib.RongIMClient._storageProvider.getItem("fullnavi") || "{}"; return JSON.parse(navi); }; ServerDataProvider.prototype.getRTCToken = function (room, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcInput(); var mode = room.mode || 0; modules.setRoomType(mode); if (room.broadcastType) { modules.setBroadcastType(room.broadcastType); } RongIMLib.RongIMClient.bridge.queryMsg("rtcToken", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function (result) { callback.onSuccess(result); }, onError: function (errorCode) { callback.onError(errorCode); } }, "RtcTokenOutput"); }; ServerDataProvider.prototype.setRTCState = function (room, content, callback) { // MCFollowInput 为 PB 复用,字段:一个必传 string(第一位) var modules = new RongIMLib.RongIMClient.Protobuf.MCFollowInput(); var report = content.report; modules.setId(report); RongIMLib.RongIMClient.bridge.queryMsg("rtcUserState", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function (result) { callback.onSuccess(result); }, onError: function (errorCode) { callback.onError(errorCode); } }, "RtcOutput"); }; return ServerDataProvider; })(); RongIMLib.ServerDataProvider = ServerDataProvider; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var VCDataProvider = (function () { function VCDataProvider(addon) { this.Conversation = { watcher: new RongIMLib.Observer(), watch: function (_watcher) { }, unwatch: function (_watcher) { }, _notify: function (conversationList) { } }; // C++ 需要的 SDK 版本号 this.version = '2.8.27'; this.userId = ""; this.useConsole = false; this.appKey = ""; this.token = ""; this.connectionStatus = RongIMLib.ConnectionStatus.DISCONNECTED; this.addon = addon; } VCDataProvider.prototype.init = function (appKey, config) { this.appKey = appKey; this.useConsole && console.log("init"); config = config || {}; config.version = this.version; var sdkInfo = this.addon.initWithAppkey(appKey, config.dbPath, config); if (sdkInfo) { sdkInfo = JSON.parse(sdkInfo); } // 0 不存不计数 1 只存不计数 3 存且计数 this.addon.registerMessageType("RC:VcMsg", 3); this.addon.registerMessageType("RC:ImgTextMsg", 3); this.addon.registerMessageType("RC:FileMsg", 3); this.addon.registerMessageType("RC:LBSMsg", 3); this.addon.registerMessageType("RC:PSImgTxtMsg", 3); this.addon.registerMessageType("RC:PSMultiImgTxtMsg", 3); this.addon.registerMessageType("RCJrmf:RpMsg", 3); this.addon.registerMessageType("RCJrmf:RpOpendMsg", 1); this.addon.registerMessageType("RC:GrpNtf", 1); this.addon.registerMessageType("RC:DizNtf", 0); this.addon.registerMessageType("RC:InfoNtf", 0); this.addon.registerMessageType("RC:ContactNtf", 0); this.addon.registerMessageType("RC:ProfileNtf", 0); this.addon.registerMessageType("RC:CmdNtf", 0); this.addon.registerMessageType("RC:CmdMsg", 0); this.addon.registerMessageType("RC:TypSts", 0); this.addon.registerMessageType("RC:CsChaR", 0); this.addon.registerMessageType("RC:CsHsR", 0); this.addon.registerMessageType("RC:CsEnd", 0); this.addon.registerMessageType("RC:CsSp", 0); this.addon.registerMessageType("RC:CsUpdate", 0); this.addon.registerMessageType("RC:CsContact", 0); this.addon.registerMessageType("RC:ReadNtf", 0); this.addon.registerMessageType("RC:VCAccept", 0); this.addon.registerMessageType("RC:VCRinging", 0); this.addon.registerMessageType("RC:VCSummary", 0); this.addon.registerMessageType("RC:VCHangup", 0); this.addon.registerMessageType("RC:VCInvite", 0); this.addon.registerMessageType("RC:VCModifyMedia", 0); this.addon.registerMessageType("RC:VCModifyMem", 0); this.addon.registerMessageType("RC:PSCmd", 0); this.addon.registerMessageType("RC:RcCmd", 0); this.addon.registerMessageType("RC:SRSMsg", 0); this.addon.registerMessageType("RC:RRReqMsg", 0); this.addon.registerMessageType("RC:RRRspMsg", 0); return sdkInfo; }; VCDataProvider.prototype.connect = function (token, callback, userId, serverConf) { this.useConsole && console.log("connect"); this.userId = userId; this.connectCallback = callback; RongIMLib.Bridge._client = { userId: userId, token: token }; serverConf = serverConf || {}; var openmp = !!serverConf.openMp; var openus = !!serverConf.openUS; if (serverConf.type) { this.addon.setEnvironment(true); } var me = this; // this.addon.connectWithToken(token, userId, serverConf.serverList, openmp, openus); this.addon.connectWithToken(token, userId, function (userId) { me.userId = userId; RongIMLib.Bridge._client.userId = userId; }); }; VCDataProvider.prototype.setConversationStatus = function (type, targetId, statusItem, callback) { }; VCDataProvider.prototype.setServerInfo = function (info) { 'setServerInfo' in this.addon && this.addon.setServerInfo(info.navi); }; VCDataProvider.prototype.logout = function () { this.useConsole && console.log("logout"); this.disconnect(); }; VCDataProvider.prototype.disconnect = function () { this.useConsole && console.log("disconnect"); this.connectionStatus = RongIMLib.ConnectionStatus.DISCONNECTED; this.addon.disconnect(true); }; VCDataProvider.prototype.clearListeners = function () { this.addon.setOnReceiveStatusListener(); this.addon.setConnectionStatusListener(); this.addon.setOnReceiveMessageListener(); }; VCDataProvider.prototype.clearData = function () { this.useConsole && console.log("clearData"); return this.addon.clearData(); }; VCDataProvider.prototype.setConnectionStatusListener = function (listener) { var me = this; /** ConnectionStatus_TokenIncorrect = 31004, ConnectionStatus_Connected = 0, ConnectionStatus_KickedOff = 6, // 其他设备登录 ConnectionStatus_Connecting = 10,// 连接中 ConnectionStatus_SignUp = 12, // 未登录 ConnectionStatus_NetworkUnavailable = 1, // 连接断开 ConnectionStatus_ServerInvalid = 8, // 断开 ConnectionStatus_ValidateFailure = 9,//断开 ConnectionStatus_Unconnected = 11,//断开 ConnectionStatus_DisconnExecption = 31011 //断开 RC_NAVI_MALLOC_ERROR = 30000,//断开 RC_NAVI_NET_UNAVAILABLE= 30002,//断开 RC_NAVI_SEND_FAIL = 30004,//断开 RC_NAVI_REQ_TIMEOUT = 30005,//断开 RC_NAVI_RECV_FAIL = 30006,//断开 RC_NAVI_RESOURCE_ERROR = 30007,//断开 RC_NAVI_NODE_NOT_FOUND = 30008,//断开 RC_NAVI_DNS_ERROR = 30009,//断开 */ me.connectListener = listener; this.useConsole && console.log("setConnectionStatusListener"); me.addon && me.addon.setConnectionStatusListener(function (result) { var isCurrentConnected = me.connectionStatus === RongIMLib.ConnectionStatus.CONNECTED; var code = result; switch (result) { case 10: code = RongIMLib.ConnectionStatus.CONNECTING; break; case 31004: setTimeout(function () { me.connectCallback.onTokenIncorrect(); }); return; case 1: case 8: case 9: case 11: case 12: case 31011: case 30000: case 30002: case 30010: if (!isCurrentConnected) { return; } code = RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE; break; case 0: case 33005: code = RongIMLib.ConnectionStatus.CONNECTED; setTimeout(function () { me.connectCallback.onSuccess(me.userId); }); break; case 6: code = RongIMLib.ConnectionStatus.KICKED_OFFLINE_BY_OTHER_CLIENT; break; default: code = result; break; } me.connectionStatus = code; setTimeout(function () { listener.onChanged(code); }); }); }; VCDataProvider.prototype.setOnReceiveMessageListener = function (listener) { var me = this, localCount = 0; me.messageListener = listener; this.useConsole && console.log("setOnReceiveMessageListener"); me.addon && me.addon.setOnReceiveMessageListener(function (result, leftCount, offline, hasMore) { var message = me.buildMessage(result); message.offLineMessage = offline; setTimeout(function () { var voipMsgTypes = ['AcceptMessage', 'RingingMessage', 'HungupMessage', 'InviteMessage', 'MediaModifyMessage', 'MemberModifyMessage']; var isVoIPMsg = voipMsgTypes.indexOf(message.messageType) > -1; if (isVoIPMsg) { RongIMLib.RongIMClient._voipProvider && RongIMLib.RongIMClient._voipProvider.onReceived(message); } else if (message.conversationType == 12) { RongIMLib.RongIMClient.RTCListener(message); RongIMLib.RongIMClient.RTCInnerListener(message); RongIMLib.RongIMClient.RTCSignalLisener(message); } else { listener.onReceived(message, leftCount, hasMore); } }); }); }; VCDataProvider.prototype.sendTypingStatusMessage = function (conversationType, targetId, messageName, sendCallback) { var me = this; this.useConsole && console.log("sendTypingStatusMessage"); if (messageName in RongIMLib.RongIMClient.MessageParams) { me.sendMessage(conversationType, targetId, RongIMLib.TypingStatusMessage.obtain(RongIMLib.RongIMClient.MessageParams[messageName].objectName, ""), { onSuccess: function () { setTimeout(function () { sendCallback.onSuccess(); }); }, onError: function (errorCode) { setTimeout(function () { sendCallback.onError(errorCode, null); }); }, onBefore: function () { } }); } }; VCDataProvider.prototype.setMessageStatus = function (conversationType, targetId, timestamp, status, callback) { this.addon.updateMessageReceiptStatus(conversationType, targetId, timestamp); callback.onSuccess(true); }; VCDataProvider.prototype.sendTextMessage = function (conversationType, targetId, content, sendMessageCallback) { var msgContent = RongIMLib.TextMessage.obtain(content); this.useConsole && console.log("sendTextMessage"); this.sendMessage(conversationType, targetId, msgContent, sendMessageCallback); }; VCDataProvider.prototype.getRemoteHistoryMessages = function (conversationType, targetId, timestamp, count, callback, config) { try { var me = this; me.useConsole && console.log("getRemoteHistoryMessages"); me.addon.getRemoteHistoryMessages(conversationType, targetId, timestamp ? timestamp : 0, count, function (ret, hasMore) { var list = ret ? JSON.parse(ret).list : [], msgs = []; list.reverse(); for (var i = 0, len = list.length; i < len; i++) { var message = me.buildMessage(list[i].obj); message.sentStatus = RongIMLib.SentStatus.READ; msgs[i] = message; } callback.onSuccess(msgs, hasMore ? true : false); }, function (errorCode) { callback.onError(errorCode); }); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.getRemoteConversationList = function (callback, conversationTypes, count, isGetHiddenConvers) { try { this.useConsole && console.log("getRemoteConversationList"); var converTypes = conversationTypes || [1, 2, 3, 4, 5, 6, 7, 8]; var result = this.addon.getConversationList(converTypes); var list = JSON.parse(result).list, convers = [], me = this, index = 0; list.reverse(); isGetHiddenConvers = typeof isGetHiddenConvers === 'boolean' ? isGetHiddenConvers : false; for (var i = 0, len_1 = list.length; i < len_1; i++) { var tmpObj = list[i].obj, obj = JSON.parse(tmpObj); if (obj != "") { if (obj.isHidden == 1 && isGetHiddenConvers) { continue; } convers[index] = me.buildConversation(tmpObj); index++; } } convers.reverse(); var len = convers.length; count = count || len; if (len > count) { convers.length = count; } callback.onSuccess(convers); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.removeConversation = function (conversationType, targetId, callback) { try { this.useConsole && console.log("removeConversation"); this.addon.removeConversation(conversationType, targetId); var conversations = RongIMLib.RongIMClient._memoryStore.conversationList; var len = conversations.length; for (var i = 0; i < len; i++) { if (conversations[i].conversationType == conversationType && targetId == conversations[i].targetId) { conversations.splice(i, 1); break; } } callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.joinChatRoom = function (chatRoomId, messageCount, callback) { this.useConsole && console.log("joinChatRoom"); this.addon.joinChatRoom(chatRoomId, messageCount, function () { callback.onSuccess(); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.quitChatRoom = function (chatRoomId, callback) { this.useConsole && console.log("quitChatRoom"); this.addon.quitChatRoom(chatRoomId, function () { callback.onSuccess(); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.setChatroomEntry = function (chatroomId, chatroomEntry, callback) { }; VCDataProvider.prototype.forceSetChatroomEntry = function (chatroomId, chatroomEntry, callback) { }; VCDataProvider.prototype.getChatroomEntry = function (chatroomId, key, callback) { }; VCDataProvider.prototype.getAllChatroomEntries = function (chatroomId, callback) { }; VCDataProvider.prototype.removeChatroomEntry = function (chatroomId, chatroomEntry, callback) { }; VCDataProvider.prototype.forceRemoveChatroomEntry = function (chatroomId, chatroomEntry, callback) { }; VCDataProvider.prototype.pullChatroomEntry = function (chatroomId, time, callback) { }; VCDataProvider.prototype.addToBlacklist = function (userId, callback) { this.useConsole && console.log("addToBlacklist"); this.addon.addToBlacklist(userId, function () { callback.onSuccess(); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.getBlacklist = function (callback) { this.useConsole && console.log("getBlacklist"); this.addon.getBlacklist(function (blacklistors) { callback.onSuccess(blacklistors); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.getBlacklistStatus = function (userId, callback) { this.useConsole && console.log("getBlacklistStatus"); this.addon.getBlacklistStatus(userId, function (result) { callback.onSuccess(result); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.removeFromBlacklist = function (userId, callback) { this.useConsole && console.log("removeFromBlacklist"); this.addon.removeFromBlacklist(userId, function () { callback.onSuccess(); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.sendMessage = function (conversationType, targetId, messageContent, sendCallback, mentiondMsg, pushText, appData, methodType, params) { var me = this, users = []; me.useConsole && console.log("sendMessage"); params = params || {}; var isGroup = (conversationType == RongIMLib.ConversationType.DISCUSSION || conversationType == RongIMLib.ConversationType.GROUP); if (isGroup && messageContent.messageName == RongIMLib.RongIMClient.MessageType["ReadReceiptResponseMessage"]) { users = []; var rspMsg = messageContent; if (rspMsg.receiptMessageDic) { var ids = []; for (var key in rspMsg.receiptMessageDic) { ids.push(key); } users = ids; } } if (isGroup && messageContent.messageName == RongIMLib.RongIMClient.MessageType["SyncReadStatusMessage"]) { users = []; users.push(me.userId); } var userIds = params.userIds; if (isGroup && userIds) { users = userIds; } var msg = me.addon.sendMessage(conversationType, targetId, RongIMLib.RongIMClient.MessageParams[messageContent.messageName].objectName, messageContent.encode(), pushText || "", appData || "", function (progress) { }, function (message, code) { var msg = me.buildMessage(message); var errorCode = RongIMLib.ErrorCode.SENSITIVE_REPLACE; if (code == errorCode) { return sendCallback.onError(errorCode, msg); } sendCallback.onSuccess(msg); }, function (message, code) { sendCallback.onError(code, me.buildMessage(message)); }, users, mentiondMsg); var tempMessage = JSON.parse(msg); sendCallback.onBefore && sendCallback.onBefore(tempMessage.messageId); RongIMLib.MessageIdHandler.messageId = tempMessage.messageId; }; VCDataProvider.prototype.registerMessageType = function (messageType, objectName, messageTag, messageContent, searchProps) { this.useConsole && console.log("registerMessageType"); this.addon.registerMessageType(objectName, messageTag.getMessageTag(), searchProps); var regMsg = RongIMLib.ModelUtil.modleCreate(messageContent, messageType); RongIMLib.RongIMClient.RegisterMessage[messageType] = regMsg; RongIMLib.RongIMClient.RegisterMessage[messageType].messageName = messageType; registerMessageTypeMapping[objectName] = messageType; RongIMLib.RongIMClient.MessageType[messageType] = messageType; RongIMLib.RongIMClient.MessageParams[messageType] = { objectName: objectName, msgTag: messageTag }; typeMapping[objectName] = messageType; }; VCDataProvider.prototype.registerMessageTypes = function (messages) { var types = []; var getProtos = function (proto) { var protos = []; for (var p in proto) { protos.push(p); } return protos; }; //转换消息为自定义消息参数格式 for (var name in messages) { var message = messages[name]; var proto = message.proto; var protos = getProtos(proto); var flag = message.flag || 3; var tag = RongIMLib.MessageTag.getTagByStatus(flag); flag = new RongIMLib.MessageTag(tag.isCounted, tag.isPersited); types.push({ type: name, name: message.name, flag: flag, protos: protos }); } var register = function (message) { var type = message.type; var name = message.name; var flag = message.flag; var protos = message.protos; RongIMLib.RongIMClient.registerMessageType(type, name, flag, protos); }; for (var i = 0, len = types.length; i < len; i++) { var message = types[i]; register(message); } }; VCDataProvider.prototype.addMessage = function (conversationType, targetId, message, callback) { this.useConsole && console.log("addMessage"); var direction = message.direction; var msg = this.addon.insertMessage(conversationType, targetId, message.senderUserId, message.objectName, JSON.stringify(message.content), function () { callback.onSuccess(me.buildMessage(msg)); }, function () { callback.onError(RongIMLib.ErrorCode.MSG_INSERT_ERROR); }, direction), me = this; }; VCDataProvider.prototype.removeMessage = function (conversationType, targetId, messages, callback) { }; VCDataProvider.prototype.deleteRemoteMessages = function (conversationType, targetId, messages, callback) { }; VCDataProvider.prototype.removeLocalMessage = function (conversationType, targetId, timestamps, callback) { try { this.useConsole && console.log("removeLocalMessage"); this.addon.deleteMessages(timestamps); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.getMessage = function (messageId, callback) { try { this.useConsole && console.log("getMessage"); var msg = this.buildMessage(this.addon.getMessage(messageId)); callback.onSuccess(msg); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.clearMessages = function (conversationType, targetId, callback) { try { this.useConsole && console.log("clearMessages"); this.addon.clearMessages(conversationType, targetId); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; // Web 端接口,桌面版无需实现 VCDataProvider.prototype.setUnreadCount = function (conversationType, targetId, count) { }; VCDataProvider.prototype.getConversation = function (conversationType, targetId, callback) { try { this.useConsole && console.log("getConversation"); var ret = this.addon.getConversation(conversationType, targetId); callback.onSuccess(this.buildConversation(ret)); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.getConversationList = function (callback, conversationTypes, count, isGetHiddenConvers) { this.useConsole && console.log("getConversationList"); this.getRemoteConversationList(callback, conversationTypes, count, isGetHiddenConvers); }; VCDataProvider.prototype.clearCache = function () { var memoryStore = RongIMLib.RongIMClient._memoryStore || {}; memoryStore.conversationList = []; memoryStore.isSyncRemoteConverList; }; VCDataProvider.prototype.clearConversations = function (conversationTypes, callback) { try { this.useConsole && console.log("clearConversations"); this.addon.clearConversations(); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.setMessageContent = function (messageId, content, objectName) { content = JSON.stringify(content); this.addon.setMessageContent(messageId, content, objectName); }; VCDataProvider.prototype.setMessageSearchField = function (messageId, content, searchFiles) { this.addon.setMessageSearchField(messageId, content, searchFiles); }; VCDataProvider.prototype.getHistoryMessages = function (conversationType, targetId, timestamp, count, callback, objectname, direction) { this.useConsole && console.log("getHistoryMessages"); if (count <= 0) { callback.onError(RongIMLib.ErrorCode.TIMEOUT); return; } objectname = objectname || ''; direction = typeof direction == 'undefined' || direction; try { var ret = this.addon.getHistoryMessages(conversationType, targetId, timestamp ? timestamp : 0, count, objectname, direction); var list = ret ? JSON.parse(ret).list : [], msgs = [], me = this; list.reverse(); for (var i = 0, len = list.length; i < len; i++) { var message = me.buildMessage(list[i].obj); msgs[i] = message; } callback.onSuccess(msgs, len == count); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.clearRemoteHistoryMessages = function (params, callback) { var conversationType = params.conversationType; var targetId = params.targetId; var timestamp = params.timestamp; var _topic = { 1: true, 2: true, 3: true, 5: true, 6: true }; var topic = _topic[conversationType]; if (!topic) { callback.onError(RongIMLib.ErrorCode.CLEAR_HIS_TYPE_ERROR); return; } if (typeof timestamp != 'number') { callback.onError(RongIMLib.ErrorCode.CLEAR_HIS_TIME_ERROR); return; } this.addon.clearRemoteHistoryMessages(+conversationType, targetId, timestamp, function () { callback.onSuccess(true); }, function (errorCode) { if (errorCode == 1) { // 没有开通历史消息云存储 errorCode = RongIMLib.ErrorCode.CLEAR_HIS_ERROR; } callback.onError(errorCode); }); }; VCDataProvider.prototype.clearHistoryMessages = function (params, callback) { var conversationType = +params.conversationType; var targetId = params.targetId; try { this.addon.clearMessages(conversationType, targetId); var isSuccess = true; callback.onSuccess(isSuccess); } catch (e) { console.log(e); callback.onError(RongIMLib.ErrorCode.CLEAR_HIS_ERROR); } }; VCDataProvider.prototype.getTotalUnreadCount = function (callback, conversationTypes) { var result = 0; try { this.useConsole && console.log("getTotalUnreadCount"); if (conversationTypes) { result = this.addon.getTotalUnreadCount(conversationTypes); } else { result = this.addon.getTotalUnreadCount(); } callback.onSuccess(result); } catch (e) { callback.onError(e); } return result; }; VCDataProvider.prototype.getConversationUnreadCount = function (conversationTypes, callback) { this.useConsole && console.log("getConversationUnreadCount"); this.getTotalUnreadCount(callback, conversationTypes); }; VCDataProvider.prototype.getUnreadCount = function (conversationType, targetId, callback) { try { this.useConsole && console.log("getUnreadCount"); var result = this.addon.getUnreadCount(conversationType, targetId); callback.onSuccess(result); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.clearUnreadCount = function (conversationType, targetId, callback) { try { this.useConsole && console.log("clearUnreadCount"); var result = this.addon.clearUnreadCount(conversationType, targetId); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.clearTotalUnreadCount = function (callback) { this.useConsole && console.log("clearTotalUnreadCount"); }; VCDataProvider.prototype.clearUnreadCountByTimestamp = function (conversationType, targetId, timestamp, callback) { try { this.useConsole && console.log("clearUnreadCountByTimestamp"); var result = this.addon.clearUnreadCountByTimestamp(conversationType, targetId, timestamp); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.setConversationToTop = function (conversationType, targetId, isTop, callback) { try { this.useConsole && console.log("setConversationToTop"); this.addon.setConversationToTop(conversationType, targetId, isTop); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.setConversationHidden = function (conversationType, targetId, isHidden) { this.addon.setConversationHidden(conversationType, targetId, isHidden); }; VCDataProvider.prototype.setMessageReceivedStatus = function (messageId, receivedStatus, callback) { try { this.useConsole && console.log("setMessageReceivedStatus"); this.addon.setMessageReceivedStatus(messageId, receivedStatus); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.setMessageSentStatus = function (messageId, sentStatus, callback) { try { this.useConsole && console.log("setMessageSentStatus"); this.addon.setMessageSentStatus(messageId, sentStatus); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.getFileToken = function (fileType, callback) { this.useConsole && console.log("getFileToken"); this.addon.getUploadToken(fileType, function (token) { callback.onSuccess({ token: token }); }, function (errorCode) { callback.onError(errorCode); }); }; VCDataProvider.prototype.getFileUrl = function (fileType, fileName, oriName, callback) { this.useConsole && console.log("getFileUrl"); this.addon.getDownloadUrl(fileType, fileName, oriName, function (url) { callback.onSuccess({ downloadUrl: url }); }, function (errorCode) { callback.onError(errorCode); }); }; VCDataProvider.prototype.getPullSetting = function (callback) { this.useConsole && console.log("getPullSetting"); }; VCDataProvider.prototype.setOfflineMessageDuration = function (duration, callback) { this.useConsole && console.log("setOfflineMessageDuration"); }; VCDataProvider.prototype.searchConversationByContent = function (keyword, callback, conversationTypes) { var converTypes = []; if (typeof conversationTypes == 'undefined') { converTypes = [1, 2, 3, 4, 5, 6, 7]; } else { converTypes = conversationTypes; } try { this.useConsole && console.log("searchConversationByContent"); var result = this.addon.searchConversationByContent(converTypes, keyword); var list = JSON.parse(result).list, convers = [], me = this; list.reverse(); for (var i = 0, len = list.length; i < len; i++) { convers[i] = me.buildConversation(list[i].obj); } callback.onSuccess(convers); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.searchMessageByContent = function (conversationType, targetId, keyword, timestamp, count, total, callback) { var me = this; try { this.useConsole && console.log("searchMessageByContent"); this.addon.searchMessageByContent(conversationType, targetId, keyword, timestamp, count, total, function (ret, matched) { var list = ret ? JSON.parse(ret).list : [], msgs = []; list.reverse(); for (var i = 0, len = list.length; i < len; i++) { msgs[i] = me.buildMessage(list[i].obj); } callback.onSuccess(msgs, matched); }); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.getChatRoomInfo = function (chatRoomId, count, order, callback) { this.useConsole && console.log("getChatRoomInfo"); this.addon.getChatroomInfo(chatRoomId, count, order, function (ret, count) { var list = ret ? JSON.parse(ret).list : [], chatRoomInfo = { userInfos: [], userTotalNums: count }; if (list.length > 0) { for (var i = 0, len = list.length; i < len; i++) { chatRoomInfo.userInfos.push(JSON.parse(list[i].obj)); } } callback.onSuccess(chatRoomInfo); }, function (errcode) { callback.onError(errcode); }); }; VCDataProvider.prototype.setChatroomHisMessageTimestamp = function (chatRoomId, timestamp) { }; VCDataProvider.prototype.getChatRoomHistoryMessages = function (chatRoomId, count, order, callback) { }; VCDataProvider.prototype.getDelaTime = function () { return this.addon.getDeltaTime(); }; VCDataProvider.prototype.getUserStatus = function (userId, callback) { var me = this; this.addon.getUserStatus(userId, function (status) { var entity = RongIMLib.RongInnerTools.convertUserStatus({ status: status, userId: '' }); callback.onSuccess(entity); }, function (code) { callback.onError(code); }); }; VCDataProvider.prototype.setUserStatus = function (status, callback) { this.addon.setUserStatus(status, function () { callback.onSuccess(true); }, function (code) { callback.onError(code); }); }; VCDataProvider.prototype.subscribeUserStatus = function (userIds, callback) { this.addon.subscribeUserStatus(userIds, function () { callback && callback.onSuccess(true); }, function (code) { callback && callback.onError(code); }); }; VCDataProvider.prototype.setUserStatusListener = function (params, callback) { var me = this; this.addon.setOnReceiveStatusListener(function (userId, status) { var entity = RongIMLib.RongInnerTools.convertUserStatus({ userId: userId, status: status }); RongIMLib.RongIMClient.userStatusObserver.notify({ key: userId, entity: entity }); }); var userIds = params.userIds || []; if (userIds.length) { RongIMLib.RongIMClient._dataAccessProvider.subscribeUserStatus(userIds); } }; VCDataProvider.prototype.getUnreadMentionedMessages = function (conversationType, targetId) { var me = this; var mentions = JSON.parse(me.addon.getUnreadMentionedMessages(conversationType, targetId)).list; for (var i = 0, len = mentions.length; i < len; i++) { var temp = JSON.parse(mentions[i].obj); temp.content = JSON.parse(temp.content); mentions[i] = temp; } return mentions; }; VCDataProvider.prototype.hasRemoteUnreadMessages = function (token, callback) { callback.onSuccess(false); }; VCDataProvider.prototype.sendRecallMessage = function (content, sendMessageCallback) { var me = this; me.addon.recallMessage("RC:RcCmd", JSON.stringify(content), content.push || "", function () { content.objectName = 'RC:RcCmd'; sendMessageCallback.onSuccess(me.buildMessage(JSON.stringify(content))); }, function (errorCode) { sendMessageCallback.onError(errorCode); }); }; VCDataProvider.prototype.updateMessage = function (message, callback) { }; VCDataProvider.prototype.updateMessages = function (conversationType, targetId, key, value, callback) { }; VCDataProvider.prototype.reconnect = function (callback) { var token = RongIMLib.Bridge._client.token; this.disconnect(); this.connect(token, callback); }; VCDataProvider.prototype.sendReceiptResponse = function (conversationType, targetId, sendCallback) { }; VCDataProvider.prototype.setMessageExtra = function (messageId, value, callback) { }; VCDataProvider.prototype.addMemberToDiscussion = function (discussionId, userIdList, callback) { }; VCDataProvider.prototype.createDiscussion = function (name, userIdList, callback) { }; VCDataProvider.prototype.getDiscussion = function (discussionId, callback) { }; VCDataProvider.prototype.quitDiscussion = function (discussionId, callback) { }; VCDataProvider.prototype.removeMemberFromDiscussion = function (discussionId, userId, callback) { }; VCDataProvider.prototype.setDiscussionInviteStatus = function (discussionId, status, callback) { }; VCDataProvider.prototype.setDiscussionName = function (discussionId, name, callback) { }; VCDataProvider.prototype.setEnvironment = function (isPrivate) { this.addon.setEnvironment(isPrivate); }; VCDataProvider.prototype.addConversation = function (conversation, callback) { }; VCDataProvider.prototype.updateConversation = function (conversation) { return null; }; VCDataProvider.prototype.getConversationNotificationStatus = function (params, callback) { var conversationType = params.conversationType; var targetId = params.targetId; var notification = RongIMLib.RongIMClient._memoryStore.notification; var key = conversationType + '_' + targetId; var status = notification[key]; if (typeof status == 'number') { callback.onSuccess(status); return; } this.addon.getConversationNotificationStatus(conversationType, targetId, function (status) { notification[key] = status; callback.onSuccess(status); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.setConversationNotificationStatus = function (params, callback) { var conversationType = params.conversationType; var targetId = params.targetId; var status = params.status; var notification = RongIMLib.RongIMClient._memoryStore.notification; var key = conversationType + '_' + targetId; notification[key] = status; var notify = !!status; this.addon.setConversationNotificationStatus(conversationType, targetId, notify, function () { callback.onSuccess(status); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.getCurrentConnectionStatus = function () { return this.addon.getConnectionStatus(); }; VCDataProvider.prototype.getAgoraDynamicKey = function (engineType, channelName, callback) { var extra = ""; this.addon.getVoIPKey(engineType, channelName, extra, function (token) { callback.onSuccess(token); }, function (errorCode) { callback.onError(errorCode); }); }; VCDataProvider.prototype.getPublicServiceProfile = function (publicServiceType, publicServiceId, callback) { var profile = RongIMLib.RongIMClient._memoryStore.publicServiceMap.get(publicServiceType, publicServiceId); callback.onSuccess(profile); }; VCDataProvider.prototype.setDeviceInfo = function (device) { var id = device.id || ''; this.addon.setDeviceId(id); }; VCDataProvider.prototype.getRemotePublicServiceList = function (callback, pullMessageTime) { var publicList = []; var ret = this.addon.getAccounts(); var transformProto = function (ret) { var result = { hasFollowed: false, isGlobal: false, menu: null }; if (!ret.obj) { var error = { error: ret }; throw new Error('公众账号数据格式错误: ' + JSON.stringify(error)); } var obj = JSON.parse(ret.obj); var protoMap = { aType: 'conversationType', aId: 'publicServiceId', aName: 'introduction', aUri: 'portraitUri', follow: 'hasFollowed', isGlobal: 'isGlobal' }; for (var key in obj) { var val = obj[key]; if (key == 'aExtra') { var extra = JSON.parse(val); result["hasFollowed"] = extra.follow; result["isGlobal"] = extra.isGlobal; result["menu"] = extra.menu; } var uId = protoMap[key]; if (uId) { result[uId] = val; } } return result; }; if (ret) { ret = JSON.parse(ret); var list = ret.list; for (var i = 0, len = list.length; i < len; i++) { var item = list[i]; item = transformProto(item); publicList.push(item); } } if (publicList.length > 0) { RongIMLib.RongIMClient._memoryStore.publicServiceMap.publicServiceList.length = 0; RongIMLib.RongIMClient._memoryStore.publicServiceMap.publicServiceList = publicList; } callback.onSuccess(RongIMLib.RongIMClient._memoryStore.publicServiceMap.publicServiceList); }; VCDataProvider.prototype.buildMessage = function (result) { var message = new RongIMLib.Message(), ret = JSON.parse(result); message.conversationType = ret.conversationType; message.targetId = ret.targetId; message.messageDirection = ret.direction; message.senderUserId = ret.senderUserId; if (ret.direction == RongIMLib.MessageDirection.RECEIVE) { message.receivedStatus = ret.status; } else if (ret.direction == RongIMLib.MessageDirection.SEND) { message.sentStatus = ret.status; } message.sentTime = ret.sentTime; message.objectName = ret.objectName; var content = ret.content ? JSON.parse(ret.content) : ret.content; var messageType = typeMapping[ret.objectName] || registerMessageTypeMapping[ret.objectName]; if (content) { content.messageName = messageType; } message.content = content; message.messageId = ret.messageId; message.messageUId = ret.messageUid; message.messageType = messageType; return message; }; VCDataProvider.prototype.buildConversation = function (val) { if (val === '') { return null; } var conver = new RongIMLib.Conversation(), c = JSON.parse(val), lastestMsg = c.lastestMsg ? this.buildMessage(c.lastestMsg) : {}; conver.conversationTitle = c.title; conver.conversationType = c.conversationType; conver.draft = c.draft; conver.isTop = c.isTop; conver.isHidden = c.isHidden; lastestMsg.conversationType = c.conversationType; lastestMsg.targetId = c.targetId; conver.latestMessage = lastestMsg; conver.latestMessageId = lastestMsg.messageId; conver.latestMessage.messageType = typeMapping[lastestMsg.objectName] || registerMessageTypeMapping[lastestMsg.objectName]; conver.objectName = lastestMsg.objectName; conver.receivedStatus = RongIMLib.ReceivedStatus.READ; conver.sentTime = lastestMsg.sentTime; conver.senderUserId = lastestMsg.senderUserId; conver.sentStatus = lastestMsg.status; conver.targetId = c.targetId; conver.unreadMessageCount = c.unreadCount; conver.hasUnreadMention = c.m_hasUnreadMention; var mentions = this.getUnreadMentionedMessages(c.conversationType, c.targetId); if (mentions.length > 0) { // 取最后一条 @ 消息,原因:和 web 互相兼容 var mention = mentions.pop(); conver.mentionedMsg = { uid: mention.messageUid, time: mention.sentTime, mentionedInfo: mention.content.mentionedInfo, sendUserId: mention.senderUserId }; } return conver; }; VCDataProvider.prototype.getRTCUserInfoList = function (room, callback) { this.addon.getRTCUsers(room.id, 1, function (result) { callback.onSuccess(result); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.getRTCRoomInfo = function (room, callback) { var order = 2; this.addon.getRTCResouce(room.id, order, function (result) { callback.onSuccess(JSON.parse(result)); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.joinRTCRoom = function (room, callback) { var id = room.id; var type = room.type || 0; this.addon.joinRTCRoom(id, type, function (result, token) { var res = JSON.parse(result); var users = {}; var list = res.list; RongIMLib.RongUtil.forEach(list, function (item) { var userId = item.id; var tmpData = {}; RongIMLib.RongUtil.forEach(item.data, function (data) { var key = data.key; var value = data.value; tmpData[key] = value; }); users[userId] = tmpData; }); callback.onSuccess({ users: users, token: token }); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.quitRTCRoom = function (room, callback) { this.addon.exitRTCRoom(room.id, function () { callback.onSuccess(true); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.RTCPing = function (room, callback) { this.addon.sendRTCPing(room.id, function () { callback.onSuccess(true); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.setRTCData = function (roomId, key, value, isInner, apiType, callback, message) { var context = this; var hanlders = { room_inner: function (roomId, key, value, name, content, success, error) { context.addon.setRTCInnerData(roomId, RongIMLib.RTCAPIType.ROOM, key, value, name, content, success, error); }, room_outer: function (roomId, key, value, name, content, success, error) { context.addon.setRTCOuterData(roomId, RongIMLib.RTCAPIType.ROOM, key, value, name, content, success, error); }, user_inner: function (roomId, key, value, name, content, success, error) { context.addon.setRTCInnerData(roomId, RongIMLib.RTCAPIType.PERSON, key, value, name, content, success, error); }, user_outer: function (roomId, key, value, name, content, success, error) { context.addon.setRTCOuterData(roomId, RongIMLib.RTCAPIType.PERSON, key, value, name, content, success, error); } }; var type = RongIMLib.RTCAPIType.PERSON == apiType ? 'user' : 'room'; var direction = isInner ? 'inner' : 'outer'; var tpl = '{type}_{direction}'; var name = RongIMLib.RongUtil.tplEngine(tpl, { type: type, direction: direction }); var handler = hanlders[name]; if (handler) { message = message || {}; var name = message.name; var content = message.content; handler(roomId, key, value, name, content, function () { callback.onSuccess(true); }, function (code) { callback.onError(code); }); } }; VCDataProvider.prototype.setRTCRoomData = function (roomId, key, value, isInner, callback, message) { this.setRTCData(roomId, key, value, isInner, RongIMLib.RTCAPIType.ROOM, callback, message); }; VCDataProvider.prototype.getRTCData = function (roomId, keys, isInner, apiType, callback) { var context = this; var hanlders = { room_inner: function (roomId, keys, success, error) { context.addon.getRTCInnerData(roomId, RongIMLib.RTCAPIType.ROOM, keys, success, error); }, room_outer: function (roomId, keys, success, error) { context.addon.getRTCOuterData(roomId, RongIMLib.RTCAPIType.ROOM, keys, success, error); } }; var type = RongIMLib.RTCAPIType.PERSON == apiType ? 'user' : 'room'; var direction = isInner ? 'inner' : 'outer'; var tpl = '{type}_{direction}'; var name = RongIMLib.RongUtil.tplEngine(tpl, { type: type, direction: direction }); var handler = hanlders[name]; if (handler) { handler(roomId, keys, function (result) { var res = JSON.parse(result); var props = {}; var list = res.list; RongIMLib.RongUtil.forEach(list, function (item) { props[item.key] = item.value; }); callback.onSuccess(props); }, function (code) { callback.onError(code); }); } }; VCDataProvider.prototype.getRTCRoomData = function (roomId, keys, isInner, callback, message) { this.getRTCData(roomId, keys, isInner, RongIMLib.RTCAPIType.ROOM, callback); }; VCDataProvider.prototype.removeRTCData = function (roomId, keys, isInner, apiType, callback, message) { var context = this; var hanlders = { room_inner: function (roomId, keys, name, content, success, error) { context.addon.deleteRTCInnerData(roomId, RongIMLib.RTCAPIType.ROOM, keys, name, content, success, error); }, room_outer: function (roomId, keys, name, content, success, error) { context.addon.deleteRTCOuterData(roomId, RongIMLib.RTCAPIType.ROOM, keys, name, content, success, error); }, user_inner: function (roomId, keys, name, content, success, error) { }, user_outer: function (roomId, keys, name, content, success, error) { } }; var type = RongIMLib.RTCAPIType.PERSON == apiType ? 'user' : 'room'; var direction = isInner ? 'inner' : 'outer'; var tpl = '{type}_{direction}'; var name = RongIMLib.RongUtil.tplEngine(tpl, { type: type, direction: direction }); var handler = hanlders[name]; if (handler) { message = message || {}; var name = message.name || ''; var content = message.content || ''; handler(roomId, keys, name, content, function () { callback.onSuccess(true); }, function (code) { callback.onError(code); }); } }; VCDataProvider.prototype.removeRTCRoomData = function (roomId, keys, isInner, callback, message) { this.removeRTCData(roomId, keys, isInner, RongIMLib.RTCAPIType.ROOM, callback); }; VCDataProvider.prototype.getNavi = function () { var nav = this.addon.getNav(); return nav[this.userId]; }; // 信令 SDK 新增 VCDataProvider.prototype.setRTCOutData = function (roomId, data, type, callback, message) { }; // 信令 SDK 新增 VCDataProvider.prototype.getRTCOutData = function (roomId, userId, callback) { }; VCDataProvider.prototype.setRTCUserInfo = function (room, info, callback) { }; VCDataProvider.prototype.removeRTCUserInfo = function (room, info, callback) { }; VCDataProvider.prototype.getRTCUserList = function (room, callback) { }; VCDataProvider.prototype.setRTCRoomInfo = function (room, data, callback) { }; VCDataProvider.prototype.removeRTCRoomInfo = function (room, data, callback) { }; VCDataProvider.prototype.setRTCUserData = function (roomId, key, value, isInner, callback, message) { this.setRTCData(roomId, key, value, isInner, RongIMLib.RTCAPIType.PERSON, callback, message); }; VCDataProvider.prototype.setRTCUserTotalRes = function (roomId, message, valueInfo, objectName, callback) { // TODO }; VCDataProvider.prototype.getRTCUserData = function (roomId, key, isInner, callback, message) { }; VCDataProvider.prototype.removeRTCUserData = function (roomId, key, isInner, callback, message) { }; VCDataProvider.prototype.getRTCToken = function (room, callback) { }; VCDataProvider.prototype.setRTCState = function (room, content, callback) { }; return VCDataProvider; })(); RongIMLib.VCDataProvider = VCDataProvider; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { (function (LoggerLevel) { LoggerLevel[LoggerLevel["F"] = 0] = "F"; LoggerLevel[LoggerLevel["E"] = 1] = "E"; LoggerLevel[LoggerLevel["W"] = 2] = "W"; LoggerLevel[LoggerLevel["I"] = 3] = "I"; LoggerLevel[LoggerLevel["D"] = 4] = "D"; //debug })(RongIMLib.LoggerLevel || (RongIMLib.LoggerLevel = {})); var LoggerLevel = RongIMLib.LoggerLevel; (function (LoggerStoreSize) { LoggerStoreSize[LoggerStoreSize["ADVANCED"] = 500] = "ADVANCED"; LoggerStoreSize[LoggerStoreSize["LOW"] = 500] = "LOW"; })(RongIMLib.LoggerStoreSize || (RongIMLib.LoggerStoreSize = {})); var LoggerStoreSize = RongIMLib.LoggerStoreSize; var LoggerType = (function () { function LoggerType() { } LoggerType.IM = 'IM'; LoggerType.RTC = 'RTC'; return LoggerType; })(); RongIMLib.LoggerType = LoggerType; var LoggerTag = (function () { function LoggerTag() { } /** * 三段式关键字: "发起方-任务类型-结果类型" * A: App 层,L: Lib 层,N: 调用 Native 层接口,P: Protocol 层 * O: 操作,S: 状态,T: 任务,R: 结果,E: 错误 */ LoggerTag.IM = { A_INIT_O: 'A-init-O', A_CONN_T: 'A-connect-T', A_CONN_R: 'A-connect-R', A_CONN_E: 'A-connect-E', L_RECO_T: 'L-reconnect-T', L_RECO_R: 'L-reconnect-R', L_RECO_E: 'L-reconnect-E', L_GETN_T: 'L-get_navi-T', L_GETN_R: 'L-get_navi-R', L_PING_WS_T: 'L-ping_ws-T', L_PING_WS_R: 'L-ping_ws-R', L_NETC_S: 'L-network_changed-S', A_DISC_O: 'A-disconnect-O', A_JCTR_T: 'A-join_chatroom-T', A_JCTR_R: 'A-join_chatroom-R', A_QCTR_T: 'A-quit_chatroom-T', A_QCTR_R: 'A-quit_chatroom-R', A_INIT_CMD_MSG_E: 'A-instantiate_command_message-E', A_INIT_PROFILE_MSG_E: 'A-instantiate_profile_notify_message-E', A_INIT_CMD_NOTI_MSG_E: 'A-instantiate_command_notify_message-E', L_CHRM_PULL_E: 'L-chatroom_pull-E', L_QUERY_MSG_E: 'L-query_message-E', L_DECODE_MSG_E: 'L-decode_upstream_message-E', L_CATCH_UNKNOWN_MSG_E: 'L-catch_unknown_message-E', L_DECODE_QUERY_DATA_E: 'L-decode_query_data-E', L_PARSE_MSG_E: 'L-parse_message-E', L_WS_ERR_E: 'L-websocket-error-E', G_CRAW_E: 'G-crash-E', G_UP_LOG_S: 'G-upload_log-S', G_UP_LOG_E: 'G-upload_log-E' }; return LoggerTag; })(); RongIMLib.LoggerTag = LoggerTag; var LoggerReportType = (function () { function LoggerReportType() { } LoggerReportType.REAL_TIME_LOG = 'RealTimeLog'; LoggerReportType.MSG_NOTIF_LOG = 'MessageNotificationLog'; return LoggerReportType; })(); RongIMLib.LoggerReportType = LoggerReportType; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var Logger = (function () { function Logger() { } Logger.writeLog = function (log) { var self = this; if (RongIMLib.RongIMClient._memoryStore.loggerSwitch === "off") { return; } var networkUnavailable = RongIMLib.RongIMClient._memoryStore.networkUnavailable; var isLowLevelBro = RongIMLib.LoggerUtil.isLowLevelBro(); log.time = new Date().getTime(); log.sessionId = RongIMLib.LoggerUtil.getSessionId(); log.content = log.content && JSON.stringify(log.content); if (networkUnavailable) { if (log.level == RongIMLib.LoggerLevel.E || log.level == RongIMLib.LoggerLevel.W) { log.level = RongIMLib.LoggerLevel.I; } } self.logStore.push(log); var _handleOverflowLog = function (size) { if (self.logStore.length > size) { var delLength = self.logStore.length - size; self.logStore.splice(0, delLength); } }; if (isLowLevelBro) { _handleOverflowLog(RongIMLib.LoggerStoreSize.LOW); } else { _handleOverflowLog(RongIMLib.LoggerStoreSize.ADVANCED); } }; Logger.reportRTLog = function () { var self = this; var isUserCloseLogger = RongIMLib.RongIMClient._memoryStore.loggerSwitch === "off"; if (self.loggerCache.hasStarted || isUserCloseLogger) { return; } self.loggerCache.hasStarted = true; var policy = this.defaultLogPolicy; var isDefaultUpload = true; var currentTime = 1; var _robustUpload = function () { var isOpen = policy.logSwitch; var itv = policy.itv * 1000; var times = policy.times; var url = policy.url; var level = policy.level; var realItv = itv * Math.pow(2, currentTime - 1); if (currentTime < times) { currentTime++; } if (!isOpen) { return; } setTimeout(function () { var csvLog = RongIMLib.LoggerUtil.handleLog({ level: level, type: RongIMLib.LoggerReportType.REAL_TIME_LOG }); var encodeCsvLog = RongIMLib.TextCompressor.compress(csvLog); var entireUrl = RongIMLib.LoggerUtil.getEntireUrl({ url: url, type: RongIMLib.LoggerReportType.REAL_TIME_LOG }); if (self.loggerCache.isNewNavi) { currentTime = 1; policy = RongIMLib.LoggerUtil.getNaviPolicy(); self.loggerCache.isNewNavi = false; } if (isDefaultUpload) { currentTime = 1; isDefaultUpload = false; policy = RongIMLib.LoggerUtil.getNaviPolicy(); // 更新 navi 中配置下次用 } if (csvLog.length == 0) { policy = RongIMLib.LoggerUtil.getNaviPolicy(); _robustUpload(); return; } RongIMLib.RongUtil.request({ url: entireUrl, method: 'POST', body: encodeCsvLog, timeout: policy.timeout * 1000, success: function (data) { Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.G_UP_LOG_S, level: RongIMLib.LoggerLevel.D, type: RongIMLib.LoggerType.IM, content: { desc: 'report real-time log' } }); //第一次成功后,如果导航有数据使用导航数据,导航无数据关闭上传。第二次上传成功后返回数据使用返回数据 if (!isOpen) { return; } if (data) { data = JSON.parse(data); policy.itv = data.nextTime; policy.level = data.level; policy.logSwitch = data.logSwitch; currentTime = 1; } _robustUpload(); }, error: function (status, resText) { _robustUpload(); Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.G_UP_LOG_E, level: RongIMLib.LoggerLevel.D, type: RongIMLib.LoggerType.IM, content: { desc: 'report real-time log', status: status, resText: resText } }); } }); }, realItv); }; _robustUpload(); }; Logger.reportMNLog = function (policy) { var self = this; var currentTime = 1; var connectTime = RongIMLib.RongIMClient._memoryStore.connectAckTime; if (policy.platform !== 'Web' || policy.logId === self.loggerCache.logId) { return; } self.loggerCache.logId = policy.logId; var _robustUpload = function () { var itv = 5000; var times = 3; itv = itv * Math.pow(2, currentTime - 2); if (currentTime === 1) { itv = 0; } if (currentTime <= times) { currentTime++; } else { return; } setTimeout(function () { var csvLog = RongIMLib.LoggerUtil.handleLog({ level: RongIMLib.LoggerLevel.D, startTime: policy.startTime, endTime: policy.endTime, type: RongIMLib.LoggerReportType.MSG_NOTIF_LOG }); if (csvLog.length === 0 && policy.endTime < connectTime) { //没有日志且连接时间大于日志消息结束时间,说明此日志消息过期,无需上传 return; } else if (csvLog.length === 0 && policy.endTime > connectTime) { //没有日志且连接时间小于日志消息结束时间,说明用户连接时间在需要获取的时间内,没有日志上传 nodata csvLog = 'nodata'; } var encodeCsvLog = RongIMLib.TextCompressor.compress(csvLog); var entireUrl = RongIMLib.LoggerUtil.getEntireUrl({ url: policy.uri, logId: policy.logId, type: RongIMLib.LoggerReportType.MSG_NOTIF_LOG }); RongIMLib.RongUtil.request({ url: entireUrl, method: 'POST', body: encodeCsvLog, timeout: self.defaultLogPolicy.timeout * 1000, success: function () { Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.G_UP_LOG_S, level: RongIMLib.LoggerLevel.D, type: RongIMLib.LoggerType.IM, content: { desc: 'report message notification log' } }); }, error: function (status, resText) { _robustUpload(); Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.G_UP_LOG_E, level: RongIMLib.LoggerLevel.D, type: RongIMLib.LoggerType.IM, content: { desc: 'report message notification log', status: status, resText: resText } }); } }); }, itv); }; _robustUpload(); }; Logger.logStore = []; Logger.defaultLogPolicy = { "logSwitch": 1, "url": 'logcollection.ronghub.com/', "level": RongIMLib.LoggerLevel.E, "itv": 20, "times": 5, "timeout": 15 }; Logger.loggerCache = { userId: '', logId: 'none', isNewNavi: false, hasStarted: false }; return Logger; })(); RongIMLib.Logger = Logger; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var LoggerUtil = (function () { function LoggerUtil() { } LoggerUtil.isLowLevelBro = function () { var flag = false; var bro = RongIMLib.RongUtil.getBrower(); if (bro.type == 'IE' && bro.version < 9) { flag = true; } return flag; }; LoggerUtil.isRealTimeLogType = function (type) { return type === RongIMLib.LoggerReportType.REAL_TIME_LOG; }; LoggerUtil.handleLog = function (conf) { var self = this; var csvLog = ''; var logs = RongIMLib.Logger.logStore; var lastIndex = 0; if (self.isRealTimeLogType(conf.type)) { RongIMLib.RongUtil.forEach(logs, function (log, index) { if (log.time > self.lastTime && log.level <= conf.level) { csvLog += self.genCSVLog(log); lastIndex = index; } }); if (csvLog.length !== 0) { self.lastTime = logs[lastIndex].time; } } else { RongIMLib.RongUtil.forEach(logs, function (log) { if (log.level <= conf.level && log.time >= conf.startTime && log.time <= conf.endTime) { csvLog += self.genCSVLog(log); } }); } return csvLog; }; LoggerUtil.getNaviPolicy = function () { var navi = RongIMLib.RongIMClient._storageProvider.getItem("fullnavi") || "{}"; var fullNavi = navi && JSON.parse(navi); var policy = {}; var logPolicy = fullNavi.logPolicy || "{}"; var logSwitch = fullNavi.logSwitch; policy = logPolicy && JSON.parse(logPolicy); policy.logSwitch = logSwitch; return policy; }; LoggerUtil.genDeviceId = function () { var deviceId = ''; var key = 'deviceId'; var isSupportLS = RongIMLib.RongUtil.supportLocalStorage(); var isSupportSS = RongIMLib.RongUtil.supportSessionStorage(); var loggerStorage; if (isSupportLS) { loggerStorage = new RongIMLib.LocalStorageProvider(); } else if (isSupportSS) { loggerStorage = new RongIMLib.sessionStorageProvider(); } else { loggerStorage = new RongIMLib.MemeoryProvider(); } var hasDeviceId = loggerStorage.getItem(key); if (hasDeviceId) { deviceId = loggerStorage.getItem(key); } else { loggerStorage.removeItem(key); var uuid = RongIMLib.RongUtil.getUUID22(); loggerStorage.setItem(key, uuid); deviceId = uuid; } return deviceId; }; LoggerUtil.getSessionId = function () { var sessionId = ''; var key = 'sessionId'; var sessionStorage; var isSupportSS = RongIMLib.RongUtil.supportSessionStorage(); if (isSupportSS) { sessionStorage = new RongIMLib.sessionStorageProvider(); } else { sessionStorage = new RongIMLib.MemeoryProvider(); } var hasSessionId = sessionStorage.getItem(key); if (hasSessionId) { sessionId = sessionStorage.getItem(key); } else { sessionStorage.removeItem(key); var val = RongIMLib.RongUtil.getUUID22(); sessionStorage.setItem(key, val); sessionId = val; } return sessionId; }; LoggerUtil.getDeviceInfo = function () { var self = this; var browerInfo = RongIMLib.RongUtil.getBrower(); var sessionId = self.getSessionId().slice(0, 10); var infoTpl = '{brower}|{version}|{sessionId}'; return RongIMLib.RongUtil.tplEngine(infoTpl, { brower: browerInfo.type, version: browerInfo.version, sessionId: sessionId }); }; LoggerUtil.getEntireUrl = function (opt) { var self = this; var tLogTpl = '{protocol}{url}?version={version}&appkey={appkey}&userId={userId}&deviceId={deviceId}&deviceInfo={deviceInfo}&platform={platform}'; var mLogTpl = '{protocol}{url}?version={version}&appkey={appkey}&userId={userId}&logId={logId}&deviceId={deviceId}&deviceInfo={deviceInfo}&platform={platform}'; var entireUrl = ''; var protocol = "https://"; if (location.protocol == "http:") { protocol = "http://"; } var paramObj = { protocol: protocol, url: opt.url, version: RongIMLib.RongIMClient.sdkver || 'Unknown version', appkey: RongIMLib.RongIMClient._memoryStore.appKey || 'Unknown appkey', deviceId: self.genDeviceId(), deviceInfo: self.getDeviceInfo(), platform: 'Web', userId: RongIMLib.Logger.loggerCache.userId || '' }; if (self.isRealTimeLogType(opt.type)) { entireUrl = RongIMLib.RongUtil.tplEngine(tLogTpl, paramObj); } else { entireUrl = RongIMLib.RongUtil.tplEngine(mLogTpl, RongIMLib.RongUtil.extend(paramObj, { logId: opt.logId })); } return entireUrl; }; LoggerUtil.genCSVLog = function (log) { var tpl = '{sessionId},{time},{type},{level},{tag},{content}\n'; if (log.content) { var content = '"' + log.content.replace(/\"/g, '""') + '"'; } var csvLog = RongIMLib.RongUtil.tplEngine(tpl, { sessionId: log.sessionId, time: log.time, type: log.type, level: log.level, tag: log.tag, content: content || '""' }); return csvLog; }; LoggerUtil.isLogCmdMsg = function (message) { var flag = false; if (message.messageType === RongIMLib.RongIMClient.MessageType["LogCommandMessage"] && message.senderUserId === 'rongcloudsystem') { flag = true; } return flag; }; LoggerUtil.recordFatalLogOfNavi = function (internalRetry, navigators) { if (internalRetry === 3) { RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.L_GETN_R, level: RongIMLib.LoggerLevel.F, type: RongIMLib.LoggerType.IM, content: { desc: 'Request navigation failed 3 times', navigators: navigators } }); } }; LoggerUtil.lastTime = 0; return LoggerUtil; })(); RongIMLib.LoggerUtil = LoggerUtil; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var MemeoryProvider = (function () { function MemeoryProvider() { this._memeoryStore = {}; this.prefix = "rong_"; } MemeoryProvider.prototype.setItem = function (composedKey, object) { this._memeoryStore[composedKey] = decodeURIComponent(object); }; MemeoryProvider.prototype.getItem = function (composedKey) { return this._memeoryStore[composedKey]; }; MemeoryProvider.prototype.removeItem = function (composedKey) { if (this.getItem(composedKey)) { delete this._memeoryStore[composedKey]; } }; MemeoryProvider.prototype.getItemKey = function (regStr) { var me = this, item = null, reg = new RegExp(regStr + "\\w+"); for (var key in me._memeoryStore) { var arr = key.match(reg); if (arr) { item = key; } } return item; }; MemeoryProvider.prototype.getItemKeyList = function (regStr) { var prefix = this.prefix; var me = this, itemList = [], reg = new RegExp(regStr + "\\w+"); for (var key in me._memeoryStore) { var arr = key.match(reg); if (arr) { key = key.substring(prefix.length); itemList.push(key); } } return itemList; }; MemeoryProvider.prototype.clearItem = function () { var me = this; for (var key in me._memeoryStore) { delete me._memeoryStore[key]; } }; //单位:字节 MemeoryProvider.prototype.onOutOfQuota = function () { return 4 * 1024; }; return MemeoryProvider; })(); RongIMLib.MemeoryProvider = MemeoryProvider; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var LocalStorageProvider = (function () { // static _instance: LocalStorageProvider = new LocalStorageProvider(); function LocalStorageProvider() { this.prefix = 'rong_'; this._host = ""; var d = new Date(), m = d.getMonth() + 1, date = d.getFullYear() + '/' + (m.toString().length == 1 ? '0' + m : m) + '/' + d.getDate(), nowDate = new Date(date).getTime(); for (var key in localStorage) { if (key.lastIndexOf('RECEIVED') > -1) { var recObj = JSON.parse(localStorage.getItem(key)); for (var key_1 in recObj) { nowDate - recObj[key_1].dealtime > 0 && (delete recObj[key_1]); } if (RongIMLib.RongUtil.isEmpty(recObj)) { localStorage.removeItem(key); } else { localStorage.setItem(key, JSON.stringify(recObj)); } } if (key.lastIndexOf('SENT') > -1) { var sentObj = JSON.parse(localStorage.getItem(key)); nowDate - sentObj.dealtime > 0 && (localStorage.removeItem(key)); } } } LocalStorageProvider.prototype.setItem = function (composedKey, object) { if (composedKey) { composedKey.indexOf(this.prefix) == -1 && (composedKey = this.prefix + composedKey); localStorage.setItem(composedKey, object); } }; LocalStorageProvider.prototype.getItem = function (composedKey) { if (composedKey) { composedKey.indexOf(this.prefix) == -1 && (composedKey = this.prefix + composedKey); return localStorage.getItem(composedKey ? composedKey : ""); } return ""; }; LocalStorageProvider.prototype.getItemKey = function (composedStr) { var item = ""; var _key = this.prefix + composedStr; for (var key in localStorage) { if (key.indexOf(_key) == 0) { item = key; break; } } return item; }; LocalStorageProvider.prototype.getItemKeyList = function (composedStr) { var itemList = []; var prefix = this.prefix; var _key = prefix + composedStr; for (var key in localStorage) { if (key.indexOf(_key) == 0) { key = key.substring(prefix.length); itemList.push(key); } } return itemList; }; LocalStorageProvider.prototype.removeItem = function (composedKey) { if (composedKey) { composedKey.indexOf(this.prefix) == -1 && (composedKey = this.prefix + composedKey); localStorage.removeItem(composedKey.toString()); } }; LocalStorageProvider.prototype.clearItem = function () { var me = this; for (var key in localStorage) { if (key.indexOf(me.prefix) > -1) { me.removeItem(key); } } }; //单位:字节 LocalStorageProvider.prototype.onOutOfQuota = function () { return JSON.stringify(localStorage).length; }; return LocalStorageProvider; })(); RongIMLib.LocalStorageProvider = LocalStorageProvider; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var sessionStorageProvider = (function () { function sessionStorageProvider() { this.prefix = 'rong_'; this._host = ""; } sessionStorageProvider.prototype.setItem = function (composedKey, object) { if (composedKey) { composedKey.indexOf(this.prefix) == -1 && (composedKey = this.prefix + composedKey); sessionStorage.setItem(composedKey, object); } }; sessionStorageProvider.prototype.getItem = function (composedKey) { if (composedKey) { composedKey.indexOf(this.prefix) == -1 && (composedKey = this.prefix + composedKey); return sessionStorage.getItem(composedKey ? composedKey : ""); } return ''; }; sessionStorageProvider.prototype.getItemKey = function (composedStr) { var item = ""; var _key = this.prefix + composedStr; for (var key in sessionStorage) { if (key.indexOf(_key) == 0) { item = key; break; } } return item; }; sessionStorageProvider.prototype.getItemKeyList = function (composedStr) { var itemList = []; var prefix = this.prefix; var _key = prefix + composedStr; for (var key in sessionStorage) { if (key.indexOf(_key) == 0) { key = key.substring(prefix.length); itemList.push(key); } } return itemList; }; sessionStorageProvider.prototype.removeItem = function (composedKey) { if (composedKey) { composedKey.indexOf(this.prefix) == -1 && (composedKey = this.prefix + composedKey); sessionStorage.removeItem(composedKey.toString()); } }; sessionStorageProvider.prototype.clearItem = function () { var me = this; for (var key in sessionStorage) { if (key.indexOf(me.prefix) > -1) { me.removeItem(key); } } }; sessionStorageProvider.prototype.onOutOfQuota = function () { return JSON.stringify(sessionStorage).length; }; return sessionStorageProvider; })(); RongIMLib.sessionStorageProvider = sessionStorageProvider; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var UserDataProvider = (function () { function UserDataProvider() { this.opersistName = 'RongIMLib'; this.keyManager = 'RongUserDataKeyManager'; this._host = ""; this.prefix = "rong_"; this.oPersist = document.createElement("div"); this.oPersist.style.display = "none"; this.oPersist.style.behavior = "url('#default#userData')"; document.body.appendChild(this.oPersist); this.oPersist.load(this.opersistName); } UserDataProvider.prototype.setItem = function (key, value) { key && key.indexOf(this.prefix) == -1 && (key = this.prefix + key); this.oPersist.setAttribute(key, value); var keyNames = this.getItem(this.keyManager); keyNames ? keyNames.indexOf(key) == -1 && (keyNames += ',' + key) : (keyNames = key); this.oPersist.setAttribute(this.prefix + this.keyManager, keyNames); this.oPersist.save(this.opersistName); }; UserDataProvider.prototype.getItem = function (key) { key && key.indexOf(this.prefix) == -1 && (key = this.prefix + key); return key ? this.oPersist.getAttribute(key) : key; }; UserDataProvider.prototype.removeItem = function (key) { key && key.indexOf(this.prefix) == -1 && (key = this.prefix + key); this.oPersist.removeAttribute(key); this.oPersist.save(this.opersistName); var keyNames = this.getItem(this.keyManager), keyNameArray = keyNames && keyNames.split(',') || []; for (var i = 0, len = keyNameArray.length; i < len; i++) { if (keyNameArray[i] == key) { keyNameArray.splice(i, 1); } } this.oPersist.setAttribute(this.prefix + this.keyManager, keyNameArray.join(',')); this.oPersist.save(this.opersistName); }; UserDataProvider.prototype.getItemKey = function (composedStr) { var item = null, keyNames = this.getItem(this.keyManager), keyNameArray = keyNames && keyNames.split(',') || [], me = this; var _key = this.prefix + composedStr; if (keyNameArray.length) { for (var i = 0, len = keyNameArray.length; i < len; i++) { if (keyNameArray[i] && keyNameArray[i].indexOf(_key) == 0) { item = keyNameArray[i]; break; } } } return item; }; UserDataProvider.prototype.getItemKeyList = function (composedStr) { var itemList = [], keyNames = this.getItem(this.keyManager), keyNameArray = keyNames && keyNames.split(',') || []; var prefix = this.prefix; var _key = prefix + composedStr; if (keyNameArray.length) { for (var i = 0, len = keyNameArray.length; i < len; i++) { if (keyNameArray[i] && keyNameArray[i].indexOf(_key) == 0) { var keyName = keyNameArray[i]; keyName = keyName.substring(prefix.length); itemList.push(keyNameArray[i]); } } } return itemList; }; UserDataProvider.prototype.clearItem = function () { var keyNames = this.getItem(this.keyManager), keyNameArray = [], me = this; keyNames && (keyNameArray = keyNames.split(',')); if (keyNameArray.length) { for (var i = 0, len = keyNameArray.length; i < len; i++) { keyNameArray[i] && me.removeItem(keyNameArray[i]); } me.removeItem(me.keyManager); } }; UserDataProvider.prototype.onOutOfQuota = function () { return 10 * 1024 * 1024; }; return UserDataProvider; })(); RongIMLib.UserDataProvider = UserDataProvider; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var FeatureDectector = (function () { function FeatureDectector(callback) { this.script = document.createElement("script"); this.head = document.getElementsByTagName("head")[0]; if ("WebSocket" in window && "ArrayBuffer" in window && WebSocket.prototype.CLOSED === 3 && !RongIMLib.RongIMClient._memoryStore.depend.isPolling) { RongIMLib.Transportations._TransportType = RongIMLib.Socket.WEBSOCKET; if (!RongIMLib.RongIMClient.Protobuf) { var url = RongIMLib.RongIMClient._memoryStore.depend.protobuf; var script = this.script; script.src = url; this.head.appendChild(script); script.onload = script.onreadystatechange = function () { var isLoaded = (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete'); if (isLoaded) { // 防止 IE6、7 下偶发触发两次 loaded script.onload = script.onreadystatechange = null; if (callback) { callback(); } if (!callback) { var token = RongIMLib.RongIMClient._memoryStore.token; var connectCallback = RongIMLib.RongIMClient._memoryStore.callback; token && RongIMLib.RongIMClient.connect(token, connectCallback, null, { isIgnoreReportStart: true }); } } }; } } else { RongIMLib.Transportations._TransportType = "xhr-polling"; RongIMLib.RongIMClient.Protobuf = Polling; } } return FeatureDectector; })(); RongIMLib.FeatureDectector = FeatureDectector; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var FeaturePatcher = (function () { function FeaturePatcher() { } FeaturePatcher.prototype.patchAll = function () { this.patchJSON(); this.patchForEach(); }; FeaturePatcher.prototype.patchForEach = function () { if (!Array.forEach) { Array.forEach = function (arr, func) { for (var i = 0; i < arr.length; i++) { func.call(arr, arr[i], i, arr); } }; } }; FeaturePatcher.prototype.patchJSON = function () { if (!window["JSON"]) { window["JSON"] = (function () { function JSON() { } JSON.parse = function (sJSON) { return eval('(' + sJSON + ')'); }; JSON.stringify = function (value) { return this.str("", { "": value }); }; JSON.str = function (key, holder) { var i, k, v, length, mind = "", partial, value = holder[key], me = this; if (value && typeof value === "object" && typeof value.toJSON === "function") { value = value.toJSON(key); } switch (typeof value) { case "string": return me.quote(value); case "number": return isFinite(value) ? String(value) : "null"; case "boolean": case "null": return String(value); case "object": if (!value) { return "null"; } partial = []; if (Object.prototype.toString.apply(value) === "[object Array]") { length = value.length; for (i = 0; i < length; i += 1) { partial[i] = me.str(i, value) || "null"; } v = partial.length === 0 ? "[]" : "[" + partial.join(",") + "]"; return v; } for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = me.str(k, value); if (v) { partial.push(me.quote(k) + ":" + v); } } } v = partial.length === 0 ? "{}" : "{" + partial.join(",") + "}"; return v; } }; JSON.quote = function (string) { var me = this; me.rx_escapable.lastIndex = 0; return me.rx_escapable.test(string) ? '"' + string.replace(me.rx_escapable, function (a) { var c = me.meta[a]; return typeof c === "string" ? c : "\\u" + ("0000" + a.charCodeAt(0).toString(16)).slice(-4); }) + '"' : '"' + string + '"'; }; JSON.rx_escapable = new RegExp('[\\\"\\\\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]', "g"); JSON.meta = { "\b": "\\b", " ": "\\t", "\n": "\\n", "\f": "\\f", "\r": "\\r", '"': '\\"', "''": "\\''", "\\": "\\\\" }; return JSON; })(); } }; return FeaturePatcher; })(); RongIMLib.FeaturePatcher = FeaturePatcher; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var ScriptLoader = (function () { function ScriptLoader() { } ScriptLoader.prototype.load = function (src, onLoad, onError) { var script = document.createElement("script"); script.async = true; if (onLoad) { if (script.addEventListener) { script.addEventListener("load", function (event) { var target = event.target || event.srcElement; onLoad(target.src); }, false); } else if (script.readyState) { script.onreadystatechange = function (event) { var target = event.srcElement; onLoad(target.src); }; } } if (onError) { script.onerror = function (event) { var target = event.target || event.srcElement; onError(target.src); }; } (document.head || document.getElementsByTagName("head")[0]).appendChild(script); script.src = src; }; return ScriptLoader; })(); })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var PublicServiceMap = (function () { function PublicServiceMap() { this.publicServiceList = []; } PublicServiceMap.prototype.get = function (publicServiceType, publicServiceId) { for (var i = 0, len = this.publicServiceList.length; i < len; i++) { if (this.publicServiceList[i].conversationType == publicServiceType && publicServiceId == this.publicServiceList[i].publicServiceId) { return this.publicServiceList[i]; } } }; PublicServiceMap.prototype.add = function (publicServiceProfile) { var isAdd = true, me = this; for (var i = 0, len = this.publicServiceList.length; i < len; i++) { if (me.publicServiceList[i].conversationType == publicServiceProfile.conversationType && publicServiceProfile.publicServiceId == me.publicServiceList[i].publicServiceId) { this.publicServiceList.unshift(this.publicServiceList.splice(i, 1)[0]); isAdd = false; break; } } if (isAdd) { this.publicServiceList.unshift(publicServiceProfile); } }; PublicServiceMap.prototype.replace = function (publicServiceProfile) { var me = this; for (var i = 0, len = this.publicServiceList.length; i < len; i++) { if (me.publicServiceList[i].conversationType == publicServiceProfile.conversationType && publicServiceProfile.publicServiceId == me.publicServiceList[i].publicServiceId) { me.publicServiceList.splice(i, 1, publicServiceProfile); break; } } }; PublicServiceMap.prototype.remove = function (conversationType, publicServiceId) { var me = this; for (var i = 0, len = this.publicServiceList.length; i < len; i++) { if (me.publicServiceList[i].conversationType == conversationType && publicServiceId == me.publicServiceList[i].publicServiceId) { this.publicServiceList.splice(i, 1); break; } } }; return PublicServiceMap; })(); RongIMLib.PublicServiceMap = PublicServiceMap; /** * 会话工具类。 */ var ConversationMap = (function () { function ConversationMap() { this.conversationList = []; } ConversationMap.prototype.get = function (conversavtionType, targetId) { for (var i = 0, len = this.conversationList.length; i < len; i++) { if (this.conversationList[i].conversationType == conversavtionType && this.conversationList[i].targetId == targetId) { return this.conversationList[i]; } } return null; }; ConversationMap.prototype.add = function (conversation) { var isAdd = true; for (var i = 0, len = this.conversationList.length; i < len; i++) { if (this.conversationList[i].conversationType === conversation.conversationType && this.conversationList[i].targetId === conversation.targetId) { this.conversationList.unshift(this.conversationList.splice(i, 1)[0]); isAdd = false; break; } } if (isAdd) { this.conversationList.unshift(conversation); } }; /** * [replace 替换会话] * 会话数组存在的情况下调用add方法会是当前会话被替换且返回到第一个位置,导致用户本地一些设置失效,所以提供replace方法 */ ConversationMap.prototype.replace = function (conversation) { for (var i = 0, len = this.conversationList.length; i < len; i++) { if (this.conversationList[i].conversationType === conversation.conversationType && this.conversationList[i].targetId === conversation.targetId) { this.conversationList.splice(i, 1, conversation); break; } } }; ConversationMap.prototype.remove = function (conversation) { for (var i = 0, len = this.conversationList.length; i < len; i++) { if (this.conversationList[i].conversationType === conversation.conversationType && this.conversationList[i].targetId === conversation.targetId) { this.conversationList.splice(i, 1); break; } } }; return ConversationMap; })(); RongIMLib.ConversationMap = ConversationMap; var CheckParam = (function () { function CheckParam() { } CheckParam.getInstance = function () { if (!CheckParam._instance) { CheckParam._instance = new CheckParam(); } return CheckParam._instance; }; CheckParam.prototype.logger = function (code, funcName, msg) { RongIMLib.RongIMClient.logger({ code: code, funcName: funcName, msg: msg }); }; CheckParam.prototype.check = function (f, position, d, c) { if (RongIMLib.RongIMClient._dataAccessProvider || d) { for (var g = 0, e = c.length; g < e; g++) { if (!new RegExp(this.getType(c[g])).test(f[g])) { // throw new Error("The index of " + g + " parameter was wrong type " + this.getType(c[g]) + " [" + f[g] + "] -> position:" + position); var msg = "第" + (g + 1) + "个参数错误, 错误类型:" + this.getType(c[g]) + " [" + f[g] + "] -> 位置:" + position; this.logger("-3", position, msg); } } } else { var msg = "该参数不正确或尚未实例化RongIMClient -> 位置:" + position; this.logger("-4", position, msg); } }; CheckParam.prototype.getType = function (str) { var temp = Object.prototype.toString.call(str).toLowerCase(); return temp.slice(8, temp.length - 1); }; CheckParam.prototype.checkCookieDisable = function () { document.cookie = "checkCookie=1"; var arr = document.cookie.match(new RegExp("(^| )checkCookie=([^;]*)(;|$)")), isDisable = false; if (!arr) { isDisable = true; } document.cookie = "checkCookie=1;expires=Thu, 01-Jan-1970 00:00:01 GMT"; return isDisable; }; return CheckParam; })(); RongIMLib.CheckParam = CheckParam; var LimitableMap = (function () { function LimitableMap(limit) { this.map = {}; this.keys = []; this.limit = limit || 10; } LimitableMap.prototype.set = function (key, value) { this.map[key] = value; }; LimitableMap.prototype.get = function (key) { return this.map[key] || 0; }; LimitableMap.prototype.remove = function (key) { delete this.map[key]; }; return LimitableMap; })(); RongIMLib.LimitableMap = LimitableMap; var MemoryCache = (function () { function MemoryCache() { this.cache = {}; } MemoryCache.prototype.set = function (key, value) { this.cache[key] = value; }; MemoryCache.prototype.get = function (key) { return this.cache[key]; }; MemoryCache.prototype.remove = function (key) { delete this.cache[key]; }; return MemoryCache; })(); RongIMLib.MemoryCache = MemoryCache; var RongAjax = (function () { function RongAjax(options) { var me = this; me.xmlhttp = null; me.options = options; var hasCORS = typeof XMLHttpRequest !== "undefined" && "withCredentials" in new XMLHttpRequest(); if ("undefined" != typeof XMLHttpRequest && hasCORS) { me.xmlhttp = new XMLHttpRequest(); } else if ("undefined" != typeof XDomainRequest) { me.xmlhttp = new XDomainRequest(); } else { me.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } } RongAjax.prototype.send = function (callback) { var me = this; me.options.url || (me.options.url = "http://upload.qiniu.com/putb64/-1"); me.xmlhttp.onreadystatechange = function () { if (me.xmlhttp.readyState == 4) { if (me.options.type) { callback(); } else { callback(JSON.parse(me.xmlhttp.responseText.replace(/'/g, '"'))); } } }; me.xmlhttp.open("POST", me.options.url, true); me.xmlhttp.withCredentials = false; if ("setRequestHeader" in me.xmlhttp) { if (me.options.type) { me.xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=utf-8"); } else { me.xmlhttp.setRequestHeader("Content-type", "application/octet-stream"); me.xmlhttp.setRequestHeader('Authorization', "UpToken " + me.options.token); } } me.xmlhttp.send(me.options.type ? "appKey=" + me.options.appKey + "&deviceId=" + me.options.deviceId + "×tamp=" + me.options.timestamp + "&deviceInfo=" + me.options.deviceInfo + "&privateInfo=" + JSON.stringify(me.options.privateInfo) : me.options.base64); }; return RongAjax; })(); RongIMLib.RongAjax = RongAjax; function Prosumer() { var data = [], isConsuming = false; this.produce = function (res) { data.push(res); }; this.consume = function (callback, finished) { if (isConsuming) { return; } isConsuming = true; var next = function () { var res = data.shift(); if (RongUtil.isUndefined(res)) { isConsuming = false; finished && finished(); return; } callback(res, next); }; next(); }; this.isExeuting = function () { return isConsuming; }; } var RongUtil = (function () { function RongUtil() { } RongUtil.noop = function () { }; RongUtil.isEmpty = function (obj) { var result = true; if (RongUtil.isObject(obj)) { RongUtil.forEach(obj, function () { result = false; }); } if (RongUtil.isString(obj) || RongUtil.isArray(obj)) { return obj.length === 0; } if (RongUtil.isNumber(obj)) { return obj === 0; } return result; }; RongUtil.isLengthLimit = function (str, maxLen, minLen) { minLen = minLen || 0; var strLen = str.length; return strLen <= maxLen && strLen >= minLen; }; RongUtil.MD5 = function (str, key, raw) { return md5(str, key, raw); }; RongUtil.isObject = function (obj) { return Object.prototype.toString.call(obj) == '[object Object]'; }; RongUtil.isArray = function (array) { return Object.prototype.toString.call(array) == '[object Array]'; }; RongUtil.isString = function (array) { return Object.prototype.toString.call(array) == '[object String]'; }; RongUtil.isFunction = function (fun) { return Object.prototype.toString.call(fun) == '[object Function]'; }; ; RongUtil.isUndefined = function (str) { return Object.prototype.toString.call(str) == '[object Undefined]'; }; ; RongUtil.isNull = function (val) { return Object.prototype.toString.call(val) == '[object Null]'; }; RongUtil.isEqual = function (a, b) { return a === b; }; ; RongUtil.indexOf = function (arrs, item) { var index = -1; for (var i = 0; i < arrs.length; i++) { if (item === arrs[i]) { index = i; break; } } return index; }; RongUtil.stringFormat = function (tmpl, vals) { for (var i = 0, len = vals.length; i < len; i++) { var val = vals[i], reg = new RegExp("\\{" + (i) + "\\}", "g"); tmpl = tmpl.replace(reg, val); } return tmpl; }; RongUtil.tplEngine = function (temp, data, regexp) { if (!(Object.prototype.toString.call(data) === "[object Array]")) { data = [data]; } var ret = []; for (var i = 0, j = data.length; i < j; i++) { ret.push(replaceAction(data[i])); } return ret.join(""); function replaceAction(object) { return temp.replace(regexp || (/{([^}]+)}/g), function (match, name) { if (match.charAt(0) == '\\') { return match.slice(1); } return (object[name] != undefined) ? object[name] : '{' + name + '}'; }); } }; ; RongUtil.forEach = function (obj, callback) { callback = callback || RongUtil.noop; var loopObj = function () { for (var key in obj) { if (obj.hasOwnProperty(key)) { callback(obj[key], key, obj); } } }; var loopArr = function () { for (var i = 0, len = obj.length; i < len; i++) { callback(obj[i], i); } }; if (RongUtil.isObject(obj)) { loopObj(); } if (RongUtil.isArray(obj)) { loopArr(); } }; RongUtil.extend = function (source, target, callback, force) { RongUtil.forEach(source, function (val, key) { var hasProto = (key in target); if (force && hasProto) { target[key] = val; } if (!hasProto) { target[key] = val; } }); return target; }; RongUtil.createXHR = function () { var item = { XMLHttpRequest: function () { return new XMLHttpRequest(); }, XDomainRequest: function () { return new XDomainRequest(); }, ActiveXObject: function () { return new ActiveXObject('Microsoft.XMLHTTP'); } }; var isXHR = typeof XMLHttpRequest !== "undefined" && "withCredentials" in new XMLHttpRequest(); var isXDR = typeof XDomainRequest == 'function' || typeof XDomainRequest == 'object'; var key = isXHR ? 'XMLHttpRequest' : isXDR ? 'XDomainRequest' : 'ActiveXObject'; return item[key](); }; RongUtil.request = function (opts) { var url = opts.url; var body = opts.body; var success = opts.success; var error = opts.error || RongUtil.noop; var method = opts.method || 'GET'; var timeout = opts.timeout; var xhr = RongUtil.createXHR(); if ('onload' in xhr) { xhr.onload = function () { xhr.onload = RongUtil.noop; success(xhr.responseText); }; xhr.onerror = function () { error(xhr.status, xhr.responseText); xhr.onerror = RongUtil.noop; }; } else { xhr.onreadystatechange = function () { if (xhr.readyState == 4) { var status = xhr.status; if (status == 200) { success(xhr.responseText); } else { error(status, xhr.responseText); } } }; } xhr.open(method, url, true); if (timeout) { xhr.timeout = timeout; } if (body) { xhr.send(body); return xhr; } xhr.send(null); return xhr; }; RongUtil.getLocalProtocol = function () { var isLocationInvalid = typeof location !== 'object'; // 未找到全局 location 变量, 则协议为 https. 比如小程序 if (isLocationInvalid || location.protocol === 'https:') { return 'https://'; } else { return 'http://'; } }; RongUtil.formatProtoclPath = function (config) { var path = config.path; var protocol = config.protocol; var tmpl = config.tmpl || '{0}{1}'; var sub = config.sub; var flag = '://'; var index = path.indexOf(flag); var hasProtocol = (index > -1); if (hasProtocol) { index += flag.length; path = path.substring(index); } if (sub) { index = path.indexOf('/'); var hasPath = (index > -1); if (hasPath) { path = path.substr(0, index); } } return RongUtil.stringFormat(tmpl, [protocol, path]); }; ; RongUtil.getValidNavi = function (naviHost) { var HttpProtocol = RongIMLib.RongIMClient.HttpProtocol; var flag = '://'; var index = naviHost.indexOf(flag); var hasProtocol = index > -1; var navi = naviHost; if (!hasProtocol) { var protocol = RongIMLib.RongIMClient.getProtocol().protocol; navi = protocol + naviHost; } var naviProtocol = RongUtil.getUrlProtocol(navi), localProtocol = RongUtil.getLocalProtocol(); // 本地为 https, 但却传入 http 时, 强制转化为 https if (naviProtocol === HttpProtocol.http && localProtocol === 'https://') { navi = RongUtil.formatProtoclPath({ path: navi, tmpl: '{0}{1}', protocol: HttpProtocol.https, sub: true }); } return navi; }; RongUtil.getUrlProtocol = function (url) { var flag = '://'; var index = url.indexOf(flag); if (index > -1) { return url.substring(0, index + flag.length); } else { return 'https://'; } ; }; RongUtil.getUrlHost = function (url) { var index = RongUtil.indexOf(url, '/'); return url.substring(0, index); }; RongUtil.supportLocalStorage = function () { var support = false; if (typeof localStorage == 'object') { try { var key = 'RC_TMP_KEY', value = 'RC_TMP_VAL'; localStorage.setItem(key, value); var localVal = localStorage.getItem(key); if (localVal == value) { support = true; } } catch (err) { console.log('localStorage is disabled.'); } } return support; }; RongUtil.supportSessionStorage = function () { var support = false; if (typeof sessionStorage == 'object') { try { var key = 'RC_TMP_KEY', value = 'RC_TMP_VAL'; sessionStorage.setItem(key, value); var localVal = sessionStorage.getItem(key); if (localVal == value) { support = true; } } catch (err) { console.log('sessionStorage is disabled.'); } } return support; }; /* //返回新引用,不破坏原始对象 rename({n: 'martin'}, {n: 'name'}); => {name: 'martin'} rename([{n: 'martin'}, {a: 18}], {n: 'name', a: 'age'}); => [{name: 'martin'}, {age: 18}] */ RongUtil.rename = function (origin, newNames) { var isObject = RongUtil.isObject(origin); if (isObject) { origin = [origin]; } origin = JSON.parse(JSON.stringify(origin)); var updateProperty = function (val, key, obj) { delete obj[key]; key = newNames[key]; obj[key] = val; }; RongUtil.forEach(origin, function (item) { RongUtil.forEach(item, function (val, key, obj) { var isRename = (key in newNames); (isRename ? updateProperty : RongUtil.noop)(val, key, obj); }); }); return isObject ? origin[0] : origin; }; RongUtil.some = function (arrs, callback) { var has = false; for (var i = 0, len = arrs.length; i < len; i++) { if (callback(arrs[i])) { has = true; break; } } return has; }; RongUtil.keys = function (obj) { var props = []; for (var key in obj) { props.push(key); } return props; }; RongUtil.isNumber = function (num) { return Object.prototype.toString.call(num) == '[object Number]'; }; RongUtil.getTimestamp = function () { var date = new Date(); return date.getTime(); }; RongUtil.isSupportRequestHeaders = function () { var userAgent = navigator.userAgent; var isIE = window.ActiveXObject || 'ActiveXObject' in window; if (isIE) { var reIE = new RegExp('MSIE (\\d+\\.\\d+);'); reIE.test(userAgent); var fIEVersion = parseFloat(RegExp['$1']); return fIEVersion > 9; } return true; }; RongUtil.hasValidWsUrl = function (urls) { try { urls = JSON.parse(urls); } catch (e) { return false; } var validUrlList = RongUtil.getValidWsUrlList(urls); return validUrlList.length > 0; }; RongUtil.getValidWsUrlList = function (urls) { var invalidWsUrls = RongIMLib.RongIMClient.invalidWsUrls; var validUrlList = []; RongUtil.forEach(urls, function (url) { if (RongUtil.indexOf(invalidWsUrls, url) === -1) { validUrlList.push(url); } }); return validUrlList; }; RongUtil.isValidWsUrl = function (url) { var invalidWsUrls = RongIMLib.RongIMClient.invalidWsUrls; return invalidWsUrls.indexOf(url) === -1 && !RongUtil.isEmpty(url); }; RongUtil.getBrower = function () { var userAgent = navigator.userAgent; var version; var type; /* 记录各浏览器名字和匹配条件 */ var condition = { IE: /rv:([\d.]+)\) like Gecko|MSIE ([\d.]+)/, Edge: /Edge\/([\d.]+)/, Firefox: /Firefox\/([\d.]+)/, Opera: /(?:OPERA|OPR).([\d.]+)/, WeChat: /MicroMessenger\/([\d.]+)/, QQBrowser: /QQBrowser\/([\d.]+)/, Chrome: /Chrome\/([\d.]+)/, Safari: /Version\/([\d.]+).*Safari/, iOSChrome: /Mobile\/([\d.]+).*Safari/ }; for (var key in condition) { if (!condition.hasOwnProperty(key)) continue; var browserContent; if (browserContent = userAgent.match(condition[key])) { type = key; version = browserContent[1] || browserContent[2]; break; } } return { type: type || 'UnKonw', version: version || 'UnKonw' }; }; RongUtil.string10to64 = function (number) { var chars = '0123456789abcdefghigklmnopqrstuvwxyzABCDEFGHIGKLMNOPQRSTUVWXYZa0'.split(''), radix = chars.length + 1, qutient = +number, arr = []; do { var mod = qutient % radix; qutient = (qutient - mod) / radix; arr.unshift(chars[mod]); } while (qutient); return arr.join(''); }; RongUtil.getUUID = function () { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8); return v.toString(16); }); }; /* 获取 22 位的 UUID */ RongUtil.getUUID22 = function () { var uuid = this.getUUID(); uuid = uuid.replace(/-/g, '') + 'a'; uuid = parseInt(uuid, 16); uuid = this.string10to64(uuid); if (uuid.length > 22) { uuid = uuid.slice(0, 22); } if (uuid.length < 22) { var len = 22 - uuid.length; for (var i = 0; i < len; i++) { uuid = uuid + '0'; } } return uuid; }; RongUtil.getByteLength = function (str, charset) { charset = charset || 'utf-8'; var total = 0, chatCode; if (charset === 'utf-16') { for (var i = 0, max = str.length; i < max; i++) { chatCode = str.charCodeAt(i); if (chatCode <= 0xffff) { total += 2; } else { total += 4; } } } else { for (var i = 0, max = str.length; i < max; i++) { chatCode = str.charCodeAt(i); if (chatCode < 0x007f) { total += 1; } else if (chatCode <= 0x07ff) { total += 2; } else if (chatCode <= 0xffff) { total += 3; } else { total += 4; } } } return total; }; RongUtil.concat = function (before, after, isDedup) { RongUtil.forEach(after, function (item) { if (!isDedup || RongUtil.indexOf(before, item) === -1) { before.push(item); } }); return before; }; RongUtil.getCurrentDate = function (seperator) { var date = new Date(); var year = date.getFullYear(); var month = date.getMonth() + 1; var day = date.getDate(); return RongUtil.tplEngine('{year}{seperator}{month}{seperator}{day}', { year: year, month: month, day: day, seperator: seperator }); }; RongUtil.generateUploadFileName = function (type, fileName) { var tpl = '{type}__RC-{date}_{random}_{timestamp}{uuid}{extension}'; var random = Math.floor((Math.random() * 1000) % 10000); var uuid = this.getUUID(); var fileNameArr, extension; if (fileName) { fileNameArr = fileName.split('.'); extension = '.' + fileNameArr[fileNameArr.length - 1]; } return RongUtil.tplEngine(tpl, { type: type, date: RongUtil.getCurrentDate('-'), random: random, uuid: uuid, timestamp: RongUtil.getTimestamp(), extension: extension || '' }); }; RongUtil.Prosumer = Prosumer; RongUtil.Storage = { set: function (key, value) { try { RongIMLib.RongIMClient._storageProvider.setItem(key, JSON.stringify(value)); } catch (e) { } }, get: function (key) { var value = RongIMLib.RongIMClient._storageProvider.getItem(key); try { return JSON.parse(value); } catch (e) { return {}; } } }; return RongUtil; })(); RongIMLib.RongUtil = RongUtil; /* var observer = new RongObserver(); observer.watch({ key: 'key', func: function(entity){ } }); */ var RongObserver = (function () { function RongObserver() { this.watchers = {}; } RongObserver.prototype.genUId = function (key) { var time = new Date().getTime(); return [key, time].join('_'); }; RongObserver.prototype.watch = function (params) { var me = this; var key = params.key; var multiple = params.multiple; key = RongUtil.isArray(key) ? key : [key]; var func = params.func; RongUtil.forEach(key, function (k) { k = multiple ? me.genUId(k) : k; me.watchers[k] = func; }); }; RongObserver.prototype.notify = function (params) { var me = this; var key = params.key; var entity = params.entity; for (var k in me.watchers) { var isNotify = (k.indexOf(key) == 0); if (isNotify) { me.watchers[k](entity); } } }; RongObserver.prototype.remove = function () { }; return RongObserver; })(); RongIMLib.RongObserver = RongObserver; var Observer = (function () { function Observer() { this.observers = []; } Observer.prototype.add = function (observer, force) { if (force) { this.observers = [observer]; } if (RongUtil.isFunction(observer)) { this.observers.push(observer); } }; Observer.prototype.emit = function (data) { RongUtil.forEach(this.observers, function (observer) { observer(data); }); }; Observer.prototype.clear = function () { this.observers = []; }; Observer.prototype.checkIndexOutBound = function (index, bound) { var isOutBound = (index > -1 && index < bound); return isOutBound; }; Observer.prototype.removeAt = function (index) { var isOutBound = this.checkIndexOutBound(index, this.observers.length); if (isOutBound) { this.observers.splice(index, 1); } }; Observer.prototype.remove = function (observer) { var me = this; if (!observer) { me.clear(); return; } if (!RongUtil.isFunction(observer)) { return; } var observerList = me.observers; for (var i = observerList.length - 1; i >= 0; i--) { if (observer === observerList[i]) { me.removeAt(i); } } }; return Observer; })(); RongIMLib.Observer = Observer; var Timer = (function () { function Timer(config) { this.timeout = 0; this.timers = []; this.timeout = config.timeout; } Timer.prototype.resume = function (callback) { var timer = setTimeout(callback, this.timeout); this.timers.push(timer); }; Timer.prototype.pause = function () { RongUtil.forEach(this.timers, function (timer) { clearTimeout(timer); }); }; return Timer; })(); RongIMLib.Timer = Timer; var IndexTools = (function () { function IndexTools(config) { this.items = []; this.index = 0; this.onwheel = function () { }; this.items = config.items; this.onwheel = config.onwheel; } IndexTools.prototype.get = function () { var context = this; var items = context.items; var index = context.index; var isWheel = index >= items.length; if (isWheel) { context.onwheel(); } return isWheel ? 0 : index; }; IndexTools.prototype.add = function () { this.index += 1; }; return IndexTools; })(); RongIMLib.IndexTools = IndexTools; var InnerUtil = (function () { function InnerUtil() { } InnerUtil.getUId = function (token) { return md5(token).slice(8, 16); }; return InnerUtil; })(); RongIMLib.InnerUtil = InnerUtil; var Base64 = (function () { function Base64() { } Base64.utf8_encode = function (string) { string = string.replace(/\r\n/g, "\n"); var utftext = ""; for (var n = 0; n < string.length; n++) { var c = string.charCodeAt(n); if (c < 128) { utftext += String.fromCharCode(c); } else if ((c > 127) && (c < 2048)) { utftext += String.fromCharCode((c >> 6) | 192); utftext += String.fromCharCode((c & 63) | 128); } else { utftext += String.fromCharCode((c >> 12) | 224); utftext += String.fromCharCode(((c >> 6) & 63) | 128); utftext += String.fromCharCode((c & 63) | 128); } } return utftext; }; Base64.utf8_decode = function (utftext) { var string = ""; var i = 0; var c = 0, c1 = 0, c2 = 0, c3; while (i < utftext.length) { c = utftext.charCodeAt(i); if (c < 128) { string += String.fromCharCode(c); i++; } else if ((c > 191) && (c < 224)) { c2 = utftext.charCodeAt(i + 1); string += String.fromCharCode(((c & 31) << 6) | (c2 & 63)); i += 2; } else { c2 = utftext.charCodeAt(i + 1); c3 = utftext.charCodeAt(i + 2); string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)); i += 3; } } return string; }; Base64.encode = function (input) { var output = ""; var chr1, chr2, chr3, enc1, enc2, enc3, enc4; var i = 0; input = this.utf8_encode(input); while (i < input.length) { chr1 = input.charCodeAt(i++); chr2 = input.charCodeAt(i++); chr3 = input.charCodeAt(i++); enc1 = chr1 >> 2; enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); enc4 = chr3 & 63; if (isNaN(chr2)) { enc3 = enc4 = 64; } else if (isNaN(chr3)) { enc4 = 64; } output = output + this.keyStr.charAt(enc1) + this.keyStr.charAt(enc2) + this.keyStr.charAt(enc3) + this.keyStr.charAt(enc4); } return output; }; Base64.decode = function (input) { var output = ""; var chr1, chr2, chr3; var enc1, enc2, enc3, enc4; var i = 0; input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ""); while (i < input.length) { enc1 = this.keyStr.indexOf(input.charAt(i++)); enc2 = this.keyStr.indexOf(input.charAt(i++)); enc3 = this.keyStr.indexOf(input.charAt(i++)); enc4 = this.keyStr.indexOf(input.charAt(i++)); chr1 = (enc1 << 2) | (enc2 >> 4); chr2 = ((enc2 & 15) << 4) | (enc3 >> 2); chr3 = ((enc3 & 3) << 6) | enc4; output = output + String.fromCharCode(chr1); if (enc3 != 64) { output = output + String.fromCharCode(chr2); } if (enc4 != 64) { output = output + String.fromCharCode(chr3); } } output = this.utf8_decode(output); return output; }; Base64.keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; return Base64; })(); RongIMLib.Base64 = Base64; var TextCompressor = (function () { function TextCompressor() { } TextCompressor.compress = function (data) { var self = this; var map = {}; //构建一个用于反向查询字符位置的 map for (var p = 0; p < data.length - 1; p++) { var c1 = data.charAt(p); var c2 = data.charAt(p + 1); var c = c1 + c2; if (!map.hasOwnProperty(c)) { map[c] = [p]; continue; } map[c].push(p); } var compressedData = [], normalBlockBuffer = []; //编码未压缩数据块 var encodeNormalBlock = function () { if (normalBlockBuffer.length > 0) { var normalBlock = normalBlockBuffer.join(''); normalBlockBuffer = []; if (normalBlock.length > 26) { var normalExtBlockLength = self.numberEncode(normalBlock.length); var normalExtBlockHeader = String.fromCharCode(self.dataType.NormalExt | normalExtBlockLength.length); compressedData.push(normalExtBlockHeader + normalExtBlockLength); } else { var normalBlockHeader = String.fromCharCode(self.dataType.Normal | normalBlock.length); compressedData.push(normalBlockHeader); } compressedData.push(normalBlock); } }; var i = 0; while (i < data.length) { var r = self.indexOf(map, data, i); if (r.length < 2) { normalBlockBuffer.push(data.charAt(i++)); continue; } if (r.length < 4) { normalBlockBuffer.push(data.substr(i, r.length)); i += r.length; continue; } var offset = self.numberEncode(i - r.offset); var length = self.numberEncode(r.length); //欲压缩的数据与数据编码后的长度一致,则不进行压缩 if (offset.length + length.length >= r.length) { normalBlockBuffer.push(data.substr(i, r.length)); i += r.length; continue; } //编码未压缩数据块 encodeNormalBlock(); //编码压缩数据块 var compressedBlockHeader = String.fromCharCode(self.dataType.Compressed | (offset.length << 2) | length.length); compressedData.push(compressedBlockHeader + offset + length); i += r.length; } //编码剩余未压缩数据块 encodeNormalBlock(); //在数据尾部添加校验和 var dataLengthTo62 = self.numberEncode(data.length); var tailBlockHeader = String.fromCharCode(self.dataType.Tail | dataLengthTo62.length); compressedData.push(tailBlockHeader + dataLengthTo62); return compressedData.join(''); }; TextCompressor.uncompress = function (data) { var self = this; var i = 0; var result = ""; label1: do { var header = data.charCodeAt(i++); var headerType = header & self.dataType.Mark; var headerVal = header & 0xF; switch (headerType) { case self.dataType.Compressed: var p1 = headerVal >> 2; var p2 = headerVal & 3; if (p1 == 0 || p2 == 0) { throw new Error("Data parsing error,at " + i); } var offset = self.numberDecode(data.substr(i, p1)); var len = self.numberDecode(data.substr(i += p1, p2)); offset = result.length - offset; if (offset + len > result.length) { throw new Error("Data parsing error,at " + i); } i += p2; result += result.substr(offset, len); break; case self.dataType.Tail: var num = self.numberDecode(data.substr(i, headerVal)); if (num != result.length) { console.log(result.length); console.log(num); throw new Error("Data parsing error,at " + i); } i += headerVal; break label1; case self.dataType.NormalExt: var num = self.numberDecode(data.substr(i, headerVal)); result += data.substr(i += headerVal, num); i += num; break; case self.dataType.Normal: result += data.substr(i, headerVal); i += headerVal; break; case self.dataType.Mark: if (headerVal > 10) { throw new Error("Data parsing error,at " + i); } result += data.substr(i, 16 + headerVal); i += (16 + headerVal); break; default: throw new Error("Data parsing error,at " + i + " header:" + headerType); } } while (i < data.length); return result; }; TextCompressor.indexOf = function (map, source, fromIndex) { var self = this; var result = { length: 0, offset: -1 }; var sourceLength = source.length; if (fromIndex >= source.length - 1) { return result; } var c1 = source.charAt(fromIndex); var c2 = source.charAt(fromIndex + 1); var items = map[c1 + c2]; if (items[0] == fromIndex) { return result; } var space1 = source.length - fromIndex; var lastChar; for (var i = 0, len = items.length; i < len; i++) { var item = items[i]; var space2 = fromIndex - item; if (space2 > self.max) { continue; } var end = Math.min(space1, space2); if (end <= result.length) { break; } if (result.length > 2) { if (source.charAt(item + result.length - 1) != source.charAt(fromIndex + result.length - 1)) { continue; } } var m = 2; for (var j = m; j < end; j++) { if (source.charAt(item + j) == source.charAt(fromIndex + j)) { m++; } else { break; } } if (m >= result.length) { result.length = m; result.offset = item; } } return result; }; /* * 将数字转化为 62 进制字符串。 */ TextCompressor.numberEncode = function (num) { var self = this; var result = [], remainder = 0; do { remainder = num % self.scale; result.push(self.chars.charAt(remainder)); num = (num - remainder) / self.scale; } while (num > 0); return result.join(''); }; /* * 将 62 进制字符串还原为数字。 */ TextCompressor.numberDecode = function (str) { var self = this; var num = 0, index = 0; for (var i = str.length - 1; i >= 0; i--) { index = self.chars.indexOf(str.charAt(i)); if (index == -1) { throw new Error("decode number error, data is \"" + str + "\""); } num = num * self.scale + index; } return num; }; TextCompressor.dataType = { Tail: 0x30, Compressed: 0x40, NormalExt: 0x50, Normal: 0x60, Mark: 0x70 }; TextCompressor.chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; TextCompressor.scale = TextCompressor.chars.length; TextCompressor.max = 238327; return TextCompressor; })(); RongIMLib.TextCompressor = TextCompressor; })(RongIMLib || (RongIMLib = {})); // {WebEnd} WebSDK 内容开始的标识, 方便小程序 SDK 定位 /* 说明: 请勿修改 header.js 和 footer.js 用途: 自动拼接暴露方式 命令: grunt release 中 concat */ return RongIMLib; }); ================================================ FILE: api-test-v2/lib/js/RongIMLib-2.5.9-silent.js ================================================ /* 说明: 请勿修改 header.js 和 footer.js 用途: 自动拼接暴露方式 命令: grunt release 中 concat Release Date: Mon Jul 06 2020 10:14:50 GMT+0800 (China Standard Time) CodeVersion: 88160473e1cc2f0ef6ab3ca5954447d815cb8f51 */ (function(global, factory) { if (typeof exports === 'object' && typeof module !== 'undefined') { module.exports = factory(); } else if (typeof define === 'function' && (define.amd || define.cmd)) { define(factory); } else { var tempIMLib = factory(); var tempClient = tempIMLib.RongIMClient; var isExists = (!!global.RongIMLib); if (isExists) { var currentClient = RongIMLib.RongIMClient || {}; for(var key in currentClient){ tempClient[key] = currentClient[key]; } } global.RongIMLib = tempIMLib; global.RongIMClient = tempClient; } })(window, function(){ // {WebStart} WebSDK 内容开始的标识, 方便小程序 SDK 定位 console.warn('SDK VERSION:', '88160473e1cc2f0ef6ab3ca5954447d815cb8f51') var Polling = { SetUserStatusInput: function(){ var a = {}; this.setStatus = function(b){ a.status = b; }; this.toArrayBuffer = function(){ return a; }; }, SetUserStatusOutput: function(){ var a = {}; this.setNothing = function(b){ a.nothing = b; }; this.toArrayBuffer = function(){ return a; }; }, GetUserStatusInput: function(){ var a = {}; this.setNothing = function(b){ a.nothing = b; }; this.toArrayBuffer = function(){ return a; }; }, GetUserStatusOutput: function(){ var a = {}; this.setStatus = function(b){ a.status = b; }; this.setSubUserId = function(b){ a.subUserId = b; }; this.toArrayBuffer = function(){ return a; }; }, VoipDynamicInput: function(){ var a = {}; this.setEngineType = function(b){ a.engineType = b; }; this.setChannelName = function(b){ a.channelName = b; }; this.setChannelExtra = function(b){ a.channelExtra = b; }; this.toArrayBuffer = function(){ return a; }; }, VoipDynamicOutput: function(){ var a = {}; this.setDynamicKey = function(b){ a.dynamicKey = b; }; this.toArrayBuffer = function(){ return a; }; }, SubUserStatusInput: function(){ var a = {}; this.setUserid = function(b){ a.userid = b; }; this.toArrayBuffer = function(){ return a; }; }, SubUserStatusOutput: function(){ var a = {}; this.setNothing = function(b){ a.nothing = b; }; this.toArrayBuffer = function(){ return a; }; }, CleanHisMsgInput: function(){ var a = {}; this.setTargetId = function(b){ a.targetId = b; }; this.setDataTime = function(b){ a.dataTime = b; }; this.setConversationType = function(b){ a.conversationType = b; }; this.toArrayBuffer = function(){ return a; }; }, DeleteMsgInput:function(){ var a = {}; this.setType = function(b){ a.type = b; }; this.setConversationId = function(b){ a.conversationId = b; }; this.setMsgs = function(b){ a.msgs = b; }; this.toArrayBuffer = function () { return a; } }, DeleteMsg:function(){ var a = {}; this.setMsgId = function(b){ a.msgId = b; }; this.setMsgDataTime = function(b){ a.msgDataTime = b; }; this.setDirect = function(b){ a.direct = b; }; this.toArrayBuffer = function () { return a; } }, DeleteMsgOutput:function(){ var a = {}; this.setNothing = function(b){ a.nothing = b; }; this.toArrayBuffer = function () { return a; } }, SearchMpInput:function(){ var a = {}; this.setType = function (b) { a.type = b; }; this.setId = function (b) { a.id = b; }; this.toArrayBuffer = function () { return a; } }, SearchMpOutput:function(){ var a = {}; this.setNothing = function (b) { a.nothing = b; }; this.setInfo = function (b) { a.info = b; }; this.toArrayBuffer = function () { return a; } }, MpInfo:function(){ var a = {}; this.setMpid = function(b){ a.mpid = b; }; this.setName = function(b){ a.name = b; }; this.setType = function(b){ a.type = b; }; this.setTime = function(b){ a.time = b; }; this.setPortraitUri = function(b){ a.portraitUrl = b; }; this.setExtra = function(b){ a.extra = b; }; this.toArrayBuffer = function () { return a; } }, PullMpInput:function(){ var a = {}; this.setMpid = function(b){ a.mpid = b; }; this.setTime = function(b){ a.time = b; }; this.toArrayBuffer = function () { return a; }; }, PullMpOutput:function(){ var a = {}; this.setStatus = function(b){ a.status = b; } this.setInfo = function(b){ a.info = b; }; this.toArrayBuffer = function () { return a; }; }, MPFollowInput:function(){ var a = {}; this.setId = function(b){ a.id = b; }; this.toArrayBuffer = function () { return a; }; }, MPFollowOutput:function(){ var a = {}; this.setNothing = function(b){ a.nothing = b; }; this.setInfo = function(b){ a.info = b; }; this.toArrayBuffer = function () { return a; }; }, NotifyMsg: function () { var a = {}; this.setType = function (b) { a.type = b; }; this.setTime = function (b) { a.time = b; }; this.setChrmId = function(b){ a.chrmId = b; }; this.toArrayBuffer = function () { return a; }; }, SyncRequestMsg: function () { var a = {}; this.setSyncTime = function (b) { a.syncTime = b || 0; }; this.setIspolling = function (b) { a.ispolling = !!b; }; this.setIsweb = function (b) { a.isweb = !!b; }; this.setIsPullSend = function (b) { a.isPullSend = !!b; }; this.setSendBoxSyncTime = function (b) { a.sendBoxSyncTime = b; }; this.toArrayBuffer = function () { return a; }; }, UpStreamMessage: function () { var a = {}; this.setSessionId = function (b) { a.sessionId = b }; this.setClassname = function (b) { a.classname = b }; this.setContent = function (b) { if (b) a.content = b; }; this.setPushText = function (b) { a.pushText = b }; this.setUserId = function(b){ a.userId = b; }; this.setConfigFlag = function (b) { a.configFlag = b; }; this.setAppData = function(b){ a.appData = b; }; this.toArrayBuffer = function () { return a }; }, DownStreamMessages: function () { var a = {}; this.setList = function (b) { a.list = b }; this.setSyncTime = function (b) { a.syncTime = b; }; this.setFinished = function(b){ a.finished = b; }; this.toArrayBuffer = function () { return a }; }, DownStreamMessage: function () { var a = {}; this.setFromUserId = function (b) { a.fromUserId = b }; this.setType = function (b) { a.type = b }; this.setGroupId = function (b) { a.groupId = b }; this.setClassname = function (b) { a.classname = b }; this.setContent = function (b) { if (b) a.content = b }; this.setDataTime = function (b) { a.dataTime = b; }; this.setStatus = function (b) { a.status = b; }; this.setMsgId = function (b) { a.msgId = b; }; this.toArrayBuffer = function () { return a; }; }, CreateDiscussionInput: function () { var a = {}; this.setName = function (b) { a.name = b }; this.toArrayBuffer = function () { return a } }, CreateDiscussionOutput: function () { var a = {}; this.setId = function (b) { a.id = b }; this.toArrayBuffer = function () { return a }; }, ChannelInvitationInput: function () { var a = {}; this.setUsers = function (b) { a.users = b }; this.toArrayBuffer = function () { return a }; }, LeaveChannelInput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b }; this.toArrayBuffer = function () { return a }; }, QueryChatroomInfoInput:function(){ var a = {}; this.setCount = function (b) { a.count = b; }; this.setOrder = function (b) { a.order = b; }; this.toArrayBuffer = function () { return a }; }, QueryChatroomInfoOutput:function(){ var a = {}; this.setUserTotalNums = function (b) { a.userTotalNums = b; }; this.setUserInfos = function (b) { a.userInfos = b; }; this.toArrayBuffer = function () { return a; }; }, ChannelEvictionInput: function () { var a = {}; this.setUser = function (b) { a.user = b }; this.toArrayBuffer = function () { return a }; }, RenameChannelInput: function () { var a = {}; this.setName = function (b) { a.name = b }; this.toArrayBuffer = function () { return a } }, ChannelInfoInput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b }; this.toArrayBuffer = function () { return a } }, ChannelInfoOutput: function () { var a = {}; this.setType = function (b) { a.type = b }; this.setChannelId = function (b) { a.channelId = b }; this.setChannelName = function (b) { a.channelName = b }; this.setAdminUserId = function (b) { a.adminUserId = b }; this.setFirstTenUserIds = function (b) { a.firstTenUserIds = b }; this.setOpenStatus = function (b) { a.openStatus = b }; this.toArrayBuffer = function () { return a } }, ChannelInfosInput: function () { var a = {}; this.setPage = function (b) { a.page = b }; this.setNumber = function (b) { a.number = b }; this.toArrayBuffer = function () { return a }; }, ChannelInfosOutput: function () { var a = {}; this.setChannels = function (b) { a.channels = b }; this.setTotal = function (b) { a.total = b }; this.toArrayBuffer = function () { return a }; }, MemberInfo: function () { var a = {}; this.setUserId = function (b) { a.userId = b }; this.setUserName = function (b) { a.userName = b }; this.setUserPortrait = function (b) { a.userPortrait = b }; this.setExtension = function (b) { a.extension = b }; this.toArrayBuffer = function () { return a }; }, GroupMembersInput: function () { var a = {}; this.setPage = function (b) { a.page = b }; this.setNumber = function (b) { a.number = b }; this.toArrayBuffer = function () { return a }; }, GroupMembersOutput: function () { var a = {}; this.setMembers = function (b) { a.members = b }; this.setTotal = function (b) { a.total = b }; this.toArrayBuffer = function () { return a }; }, GetUserInfoInput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b }; this.toArrayBuffer = function () { return a }; }, GetUserInfoOutput: function () { var a = {}; this.setUserId = function (b) { a.userId = b }; this.setUserName = function (b) { a.userName = b }; this.setUserPortrait = function (b) { a.userPortrait = b }; this.toArrayBuffer = function () { return a }; }, GetSessionIdInput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b }; this.toArrayBuffer = function () { return a }; }, GetSessionIdOutput: function () { var a = {}; this.setSessionId = function (b) { a.sessionId = b }; this.toArrayBuffer = function () { return a }; }, GetQNupTokenInput: function () { var a = {}; this.setType = function (b) { a.type = b; } this.toArrayBuffer = function () { return a } }, GetQNupTokenOutput: function () { var a = {}; this.setDeadline = function (b) { a.deadline = b }; this.setToken = function (b) { a.token = b; }; this.toArrayBuffer = function () { return a } }, GetQNdownloadUrlInput: function () { var a = {}; this.setType = function (b) { a.type = b; }; this.setKey = function (b) { a.key = b; }; this.setFileName = function(b){ a.fileName = b; }; this.toArrayBuffer = function () { return a } }, GetQNdownloadUrlOutput: function () { var a = {}; this.setDownloadUrl = function (b) { a.downloadUrl = b; }; this.toArrayBuffer = function () { return a } }, Add2BlackListInput: function () { var a = {}; this.setUserId = function (b) { a.userId = b; }; this.toArrayBuffer = function () { return a } }, RemoveFromBlackListInput: function () { var a = {}; this.setUserId = function (b) { a.userId = b; }; this.toArrayBuffer = function () { return a } }, QueryBlackListInput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b; }; this.toArrayBuffer = function () { return a } }, QueryBlackListOutput: function () { var a = {}; this.setUserIds = function (b) { a.userIds = b; }; this.toArrayBuffer = function () { return a } }, BlackListStatusInput: function () { var a = {}; this.setUserId = function (b) { a.userId = b; }; this.toArrayBuffer = function () { return a } }, BlockPushInput: function () { var a = {}; this.setBlockeeId = function (b) { a.blockeeId = b; }; this.toArrayBuffer = function () { return a } }, ModifyPermissionInput: function () { var a = {}; this.setOpenStatus = function (b) { a.openStatus = b; }; this.toArrayBuffer = function () { return a }; }, GroupInput: function () { var a = {}; this.setGroupInfo = function (b) { for (var i = 0, arr = []; i < b.length; i++) { arr.push({id: b[i].getContent().id, name: b[i].getContent().name}) } a.groupInfo = arr; }; this.toArrayBuffer = function () { return a }; }, GroupOutput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b; }; this.toArrayBuffer = function () { return a }; }, GroupInfo: function () { var a = {}; this.setId = function (b) { a.id = b; }; this.setName = function (b) { a.name = b; }; this.getContent = function () { return a; }; this.toArrayBuffer = function () { return a }; }, GroupHashInput: function () { var a = {}; this.setUserId = function (b) { a.userId = b; }; this.setGroupHashCode = function (b) { a.groupHashCode = b; }; this.toArrayBuffer = function () { return a }; }, GroupHashOutput: function () { var a = {}; this.setResult = function (b) { a.result = b; }; this.toArrayBuffer = function () { return a }; }, ChrmInput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b; }; this.toArrayBuffer = function () { return a }; }, ChrmOutput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b; }; this.toArrayBuffer = function () { return a }; }, ChrmPullMsg: function () { var a = {}; this.setSyncTime = function (b) { a.syncTime = b }; this.setCount = function (b) { a.count = b; }; this.toArrayBuffer = function () { return a }; }, RelationsInput: function () { var a = {}; this.setType = function (b) { a.type = b; }; this.setMsg = function(b){ a.msg = b; }; this.setCount = function(b){ a.count = b; }; this.toArrayBuffer = function () { return a }; }, RelationsOutput: function () { var a = {}; this.setInfo = function (b) { a.info = b; }; this.toArrayBuffer = function () { return a } }, RelationInfo: function () { var a = {}; this.setType = function (b) { a.type = b; }; this.setUserId = function (b) { a.userId = b; }; this.setMsg = function(b){ a.msg = b; }; this.toArrayBuffer = function () { return a } }, HistoryMessageInput: function () { var a={}; this.setTargetId=function(b){ a.targetId=b; }; this.setDataTime=function(b){ a.dataTime=b; }; this.setSize=function(b){ a.size=b; }; this.toArrayBuffer = function () { return a } }, HistoryMessagesOuput: function () { var a={}; this.setList=function(b){ a.list=b; }; this.setSyncTime=function(b){ a.syncTime=b; }; this.setHasMsg=function(b){ a.hasMsg=b; }; this.toArrayBuffer = function () { return a } }, HistoryMsgInput: function(){ var a = {}; this.setTargetId = function(b){ a.targetId = b; }; this.setTime = function(b){ a.time = b; }; this.setCount = function(b){ a.count = b; }; this.setOrder = function(b){ a.order = b; }; this.toArrayBuffer = function(){ return a; }; }, HistoryMsgOuput: function(){ var a = {}; this.setList = function(b){ a.list = b; }; this.setSyncTime = function(b){ a.syncTime = b; }; this.setHasMsg = function(b){ a.hasMsg = b; }; this.toArrayBuffer = function(){ return a; }; }, RtcQueryListInput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setOrder = function (b) { a.order = b; }; }, RtcKeyDeleteInput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setKey = function (b) { a.key = b; }; }, RtcValueInfo: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setKey = function (b) { a.key = b; }; this.setValue = function (b) { a.value = b; }; }, // RtcUserInfo: function () { // var a = {}; // }, RtcUserListOutput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setList = function (b) { a.list = b; }; this.setToken = function (b) { a.token = b; }; }, RtcRoomInfoOutput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setRoomId = function (b) { a.roomId = b; }; this.setRoomData = function (b) { a.roomData = b; }; this.setUserCount = function (b) { a.userCount = b; }; this.setList = function (b) { a.list = b; } }, RtcInput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setRoomType = function (b) { a.roomType = b; }; this.setBroadcastType = function (b) { a.broadcastType = b; } }, // RtcQryInput: function () { // var a = {}; // }, RtcQryOutput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setOutInfo = function (b) { a.outInfo = b; }; }, // RtcDelDataInput: function () { // var a = {}; // }, RtcDataInput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setInterior = function (b) { a.interior = b; }; this.setTarget = function (b) { a.target = b; }; this.setKey = function (b) { a.key = b; }; this.setObjectName = function (b) { a.objectName = b; }; this.setContent = function (b) { a.content = b; }; }, RtcSetDataInput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setInterior = function (b) { a.interior = b; }; this.setTarget = function (b) { a.target = b; }; this.setKey = function (b) { a.key = b; }; this.setValue = function (b) { a.value = b; }; this.setObjectName = function (b) { a.objectName = b; }; this.setContent = function (b) { a.content = b; }; }, RtcOutput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setNothing = function (b) { a.nothing = b; }; }, RtcTokenOutput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setRtcToken = function (b) { a.rtcToken = b; } }, /** * 聊天室 KV 存储 */ ChrmNotifyMsg: function () { var a = {}; this.toArrayBuffer = function () { return a; }; this.setType = function (b) { a.type = b; }; this.setTime = function (b) { a.time = b; }; this.setChrmId = function (b) { a.chrmId = b; }; }, ChrmKVEntity: function () { var a = {}; this.toArrayBuffer = function () { return a; }; this.setKey = function (key) { a.key = key; }; this.setValue = function (value) { a.value = value; }; this.setStatus = function (b) { a.status = b; }; this.setTimestamp = function (b) { a.timestamp = b; }; this.setUid = function (b) { a.uid = b; }; }, SetChrmKV: function () { var a = {}; this.toArrayBuffer = function () { return a; }; this.setEntry = function (b) { a.entry = b; }; this.setNotification = function (b) { a.notification = b.toArrayBuffer(); }; this.setBNotify = function (b) { a.bNotify = b; }; this.setType = function (b) { a.type = b; }; }, ChrmKVOutput: function () { var a = {}; this.toArrayBuffer = function () { return a; }; this.setEntries = function (b) { this.entries = b; }; this.setBFullUpdate = function (b) { this.bFullUpdate = b; }; this.setSyncTime = function (b) { this.syncTime = b; }; }, QueryChrmKV: function () { var a = {}; this.toArrayBuffer = function () { return a; }; this.setTimestamp = function (b) { a.timestamp = b; }; }, DeleteChrmKV: function () { var a = {}; this.toArrayBuffer = function () { return a; }; this.setEntry = function (b) { a.entry = b; }; this.setBNotify = function (b) { a.bNotify = b; }; this.setNotification = function (b) { a.notification = b.toArrayBuffer(); }; this.setType = function (b) { a.type = b; }; } }; for (var f in Polling) { Polling[f].decode = function (b) { var back = {}, val = JSON.parse(b) || eval("(" + b + ")"); for (var i in val) { back[i]=val[i]; back["get"+ i.charAt(0).toUpperCase()+i.slice(1)]=function(){ return val[i]; } } return back; } } /* * JavaScript MD5 * https://github.com/blueimp/JavaScript-MD5 * * Copyright 2011, Sebastian Tschan * https://blueimp.net * * Licensed under the MIT license: * http://www.opensource.org/licenses/MIT * * Based on * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message * Digest Algorithm, as defined in RFC 1321. * Version 2.2 Copyright (C) Paul Johnston 1999 - 2009 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet * Distributed under the BSD License * See http://pajhome.org.uk/crypt/md5 for more info. */ /*jslint bitwise: true */ /*global unescape, define, module */ var md5 = (function () { 'use strict'; /* * Add integers, wrapping at 2^32. This uses 16-bit operations internally * to work around bugs in some JS interpreters. */ function safe_add(x, y) { var lsw = (x & 0xFFFF) + (y & 0xFFFF), msw = (x >> 16) + (y >> 16) + (lsw >> 16); return (msw << 16) | (lsw & 0xFFFF); } /* * Bitwise rotate a 32-bit number to the left. */ function bit_rol(num, cnt) { return (num << cnt) | (num >>> (32 - cnt)); } /* * These functions implement the four basic operations the algorithm uses. */ function md5_cmn(q, a, b, x, s, t) { return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s), b); } function md5_ff(a, b, c, d, x, s, t) { return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t); } function md5_gg(a, b, c, d, x, s, t) { return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t); } function md5_hh(a, b, c, d, x, s, t) { return md5_cmn(b ^ c ^ d, a, b, x, s, t); } function md5_ii(a, b, c, d, x, s, t) { return md5_cmn(c ^ (b | (~d)), a, b, x, s, t); } /* * Calculate the MD5 of an array of little-endian words, and a bit length. */ function binl_md5(x, len) { /* append padding */ x[len >> 5] |= 0x80 << (len % 32); x[(((len + 64) >>> 9) << 4) + 14] = len; var i, olda, oldb, oldc, oldd, a = 1732584193, b = -271733879, c = -1732584194, d = 271733878; for (i = 0; i < x.length; i += 16) { olda = a; oldb = b; oldc = c; oldd = d; a = md5_ff(a, b, c, d, x[i], 7, -680876936); d = md5_ff(d, a, b, c, x[i + 1], 12, -389564586); c = md5_ff(c, d, a, b, x[i + 2], 17, 606105819); b = md5_ff(b, c, d, a, x[i + 3], 22, -1044525330); a = md5_ff(a, b, c, d, x[i + 4], 7, -176418897); d = md5_ff(d, a, b, c, x[i + 5], 12, 1200080426); c = md5_ff(c, d, a, b, x[i + 6], 17, -1473231341); b = md5_ff(b, c, d, a, x[i + 7], 22, -45705983); a = md5_ff(a, b, c, d, x[i + 8], 7, 1770035416); d = md5_ff(d, a, b, c, x[i + 9], 12, -1958414417); c = md5_ff(c, d, a, b, x[i + 10], 17, -42063); b = md5_ff(b, c, d, a, x[i + 11], 22, -1990404162); a = md5_ff(a, b, c, d, x[i + 12], 7, 1804603682); d = md5_ff(d, a, b, c, x[i + 13], 12, -40341101); c = md5_ff(c, d, a, b, x[i + 14], 17, -1502002290); b = md5_ff(b, c, d, a, x[i + 15], 22, 1236535329); a = md5_gg(a, b, c, d, x[i + 1], 5, -165796510); d = md5_gg(d, a, b, c, x[i + 6], 9, -1069501632); c = md5_gg(c, d, a, b, x[i + 11], 14, 643717713); b = md5_gg(b, c, d, a, x[i], 20, -373897302); a = md5_gg(a, b, c, d, x[i + 5], 5, -701558691); d = md5_gg(d, a, b, c, x[i + 10], 9, 38016083); c = md5_gg(c, d, a, b, x[i + 15], 14, -660478335); b = md5_gg(b, c, d, a, x[i + 4], 20, -405537848); a = md5_gg(a, b, c, d, x[i + 9], 5, 568446438); d = md5_gg(d, a, b, c, x[i + 14], 9, -1019803690); c = md5_gg(c, d, a, b, x[i + 3], 14, -187363961); b = md5_gg(b, c, d, a, x[i + 8], 20, 1163531501); a = md5_gg(a, b, c, d, x[i + 13], 5, -1444681467); d = md5_gg(d, a, b, c, x[i + 2], 9, -51403784); c = md5_gg(c, d, a, b, x[i + 7], 14, 1735328473); b = md5_gg(b, c, d, a, x[i + 12], 20, -1926607734); a = md5_hh(a, b, c, d, x[i + 5], 4, -378558); d = md5_hh(d, a, b, c, x[i + 8], 11, -2022574463); c = md5_hh(c, d, a, b, x[i + 11], 16, 1839030562); b = md5_hh(b, c, d, a, x[i + 14], 23, -35309556); a = md5_hh(a, b, c, d, x[i + 1], 4, -1530992060); d = md5_hh(d, a, b, c, x[i + 4], 11, 1272893353); c = md5_hh(c, d, a, b, x[i + 7], 16, -155497632); b = md5_hh(b, c, d, a, x[i + 10], 23, -1094730640); a = md5_hh(a, b, c, d, x[i + 13], 4, 681279174); d = md5_hh(d, a, b, c, x[i], 11, -358537222); c = md5_hh(c, d, a, b, x[i + 3], 16, -722521979); b = md5_hh(b, c, d, a, x[i + 6], 23, 76029189); a = md5_hh(a, b, c, d, x[i + 9], 4, -640364487); d = md5_hh(d, a, b, c, x[i + 12], 11, -421815835); c = md5_hh(c, d, a, b, x[i + 15], 16, 530742520); b = md5_hh(b, c, d, a, x[i + 2], 23, -995338651); a = md5_ii(a, b, c, d, x[i], 6, -198630844); d = md5_ii(d, a, b, c, x[i + 7], 10, 1126891415); c = md5_ii(c, d, a, b, x[i + 14], 15, -1416354905); b = md5_ii(b, c, d, a, x[i + 5], 21, -57434055); a = md5_ii(a, b, c, d, x[i + 12], 6, 1700485571); d = md5_ii(d, a, b, c, x[i + 3], 10, -1894986606); c = md5_ii(c, d, a, b, x[i + 10], 15, -1051523); b = md5_ii(b, c, d, a, x[i + 1], 21, -2054922799); a = md5_ii(a, b, c, d, x[i + 8], 6, 1873313359); d = md5_ii(d, a, b, c, x[i + 15], 10, -30611744); c = md5_ii(c, d, a, b, x[i + 6], 15, -1560198380); b = md5_ii(b, c, d, a, x[i + 13], 21, 1309151649); a = md5_ii(a, b, c, d, x[i + 4], 6, -145523070); d = md5_ii(d, a, b, c, x[i + 11], 10, -1120210379); c = md5_ii(c, d, a, b, x[i + 2], 15, 718787259); b = md5_ii(b, c, d, a, x[i + 9], 21, -343485551); a = safe_add(a, olda); b = safe_add(b, oldb); c = safe_add(c, oldc); d = safe_add(d, oldd); } return [a, b, c, d]; } /* * Convert an array of little-endian words to a string */ function binl2rstr(input) { var i, output = ''; for (i = 0; i < input.length * 32; i += 8) { output += String.fromCharCode((input[i >> 5] >>> (i % 32)) & 0xFF); } return output; } /* * Convert a raw string to an array of little-endian words * Characters >255 have their high-byte silently ignored. */ function rstr2binl(input) { var i, output = []; output[(input.length >> 2) - 1] = undefined; for (i = 0; i < output.length; i += 1) { output[i] = 0; } for (i = 0; i < input.length * 8; i += 8) { output[i >> 5] |= (input.charCodeAt(i / 8) & 0xFF) << (i % 32); } return output; } /* * Calculate the MD5 of a raw string */ function rstr_md5(s) { return binl2rstr(binl_md5(rstr2binl(s), s.length * 8)); } /* * Calculate the HMAC-MD5, of a key and some data (raw strings) */ function rstr_hmac_md5(key, data) { var i, bkey = rstr2binl(key), ipad = [], opad = [], hash; ipad[15] = opad[15] = undefined; if (bkey.length > 16) { bkey = binl_md5(bkey, key.length * 8); } for (i = 0; i < 16; i += 1) { ipad[i] = bkey[i] ^ 0x36363636; opad[i] = bkey[i] ^ 0x5C5C5C5C; } hash = binl_md5(ipad.concat(rstr2binl(data)), 512 + data.length * 8); return binl2rstr(binl_md5(opad.concat(hash), 512 + 128)); } /* * Convert a raw string to a hex string */ function rstr2hex(input) { var hex_tab = '0123456789abcdef', output = '', x, i; for (i = 0; i < input.length; i += 1) { x = input.charCodeAt(i); output += hex_tab.charAt((x >>> 4) & 0x0F) + hex_tab.charAt(x & 0x0F); } return output; } /* * Encode a string as utf-8 */ function str2rstr_utf8(input) { return unescape(encodeURIComponent(input)); } /* * Take string arguments and return either raw or hex encoded strings */ function raw_md5(s) { return rstr_md5(str2rstr_utf8(s)); } function hex_md5(s) { return rstr2hex(raw_md5(s)); } function raw_hmac_md5(k, d) { return rstr_hmac_md5(str2rstr_utf8(k), str2rstr_utf8(d)); } function hex_hmac_md5(k, d) { return rstr2hex(raw_hmac_md5(k, d)); } function md5(string, key, raw) { if (!key) { if (!raw) { return hex_md5(string); } return raw_md5(string); } if (!raw) { return hex_hmac_md5(key, string); } return raw_hmac_md5(key, string); } return md5; }()); var RongIMLib; (function (RongIMLib) { (function (MentionedType) { MentionedType[MentionedType["ALL"] = 1] = "ALL"; MentionedType[MentionedType["PART"] = 2] = "PART"; })(RongIMLib.MentionedType || (RongIMLib.MentionedType = {})); var MentionedType = RongIMLib.MentionedType; (function (MethodType) { MethodType[MethodType["CUSTOMER_SERVICE"] = 1] = "CUSTOMER_SERVICE"; MethodType[MethodType["RECALL"] = 2] = "RECALL"; })(RongIMLib.MethodType || (RongIMLib.MethodType = {})); var MethodType = RongIMLib.MethodType; (function (BlacklistStatus) { /** * 在黑名单中。 */ BlacklistStatus[BlacklistStatus["IN_BLACK_LIST"] = 0] = "IN_BLACK_LIST"; /** * 不在黑名单中。 */ BlacklistStatus[BlacklistStatus["NOT_IN_BLACK_LIST"] = 1] = "NOT_IN_BLACK_LIST"; })(RongIMLib.BlacklistStatus || (RongIMLib.BlacklistStatus = {})); var BlacklistStatus = RongIMLib.BlacklistStatus; (function (ConnectionChannel) { ConnectionChannel[ConnectionChannel["XHR_POLLING"] = 0] = "XHR_POLLING"; ConnectionChannel[ConnectionChannel["WEBSOCKET"] = 1] = "WEBSOCKET"; //外部调用 ConnectionChannel[ConnectionChannel["HTTP"] = 0] = "HTTP"; //外部调用 ConnectionChannel[ConnectionChannel["HTTPS"] = 1] = "HTTPS"; })(RongIMLib.ConnectionChannel || (RongIMLib.ConnectionChannel = {})); var ConnectionChannel = RongIMLib.ConnectionChannel; (function (CustomerType) { CustomerType[CustomerType["ONLY_ROBOT"] = 1] = "ONLY_ROBOT"; CustomerType[CustomerType["ONLY_HUMAN"] = 2] = "ONLY_HUMAN"; CustomerType[CustomerType["ROBOT_FIRST"] = 3] = "ROBOT_FIRST"; CustomerType[CustomerType["HUMAN_FIRST"] = 4] = "HUMAN_FIRST"; })(RongIMLib.CustomerType || (RongIMLib.CustomerType = {})); var CustomerType = RongIMLib.CustomerType; (function (GetChatRoomType) { GetChatRoomType[GetChatRoomType["NONE"] = 0] = "NONE"; GetChatRoomType[GetChatRoomType["SQQUENCE"] = 1] = "SQQUENCE"; GetChatRoomType[GetChatRoomType["REVERSE"] = 2] = "REVERSE"; })(RongIMLib.GetChatRoomType || (RongIMLib.GetChatRoomType = {})); var GetChatRoomType = RongIMLib.GetChatRoomType; (function (ConnectionStatus) { /** * 连接成功。 */ ConnectionStatus[ConnectionStatus["CONNECTED"] = 0] = "CONNECTED"; /** * 连接中。 */ ConnectionStatus[ConnectionStatus["CONNECTING"] = 1] = "CONNECTING"; /** * 断开连接。 */ ConnectionStatus[ConnectionStatus["DISCONNECTED"] = 2] = "DISCONNECTED"; /** * 用户账户在其他设备登录,本机会被踢掉线。 */ ConnectionStatus[ConnectionStatus["KICKED_OFFLINE_BY_OTHER_CLIENT"] = 6] = "KICKED_OFFLINE_BY_OTHER_CLIENT"; /** * websocket 连接失败 */ ConnectionStatus[ConnectionStatus["WEBSOCKET_UNAVAILABLE"] = 7] = "WEBSOCKET_UNAVAILABLE"; /** * websocket 报错 */ ConnectionStatus[ConnectionStatus["WEBSOCKET_ERROR"] = 8] = "WEBSOCKET_ERROR"; /** * 网络不可用。 */ ConnectionStatus[ConnectionStatus["NETWORK_UNAVAILABLE"] = 3] = "NETWORK_UNAVAILABLE"; /** * 域名错误 */ ConnectionStatus[ConnectionStatus["DOMAIN_INCORRECT"] = 12] = "DOMAIN_INCORRECT"; /** * appkey 不正确 */ ConnectionStatus[ConnectionStatus["APPKEY_IS_FAKE"] = 20] = "APPKEY_IS_FAKE"; /** * 连接关闭。 */ ConnectionStatus[ConnectionStatus["CONNECTION_CLOSED"] = 4] = "CONNECTION_CLOSED"; /* 互踢次数过多(count > 5),此时可能出现:在其它他设备登陆有 reconnect 逻辑 */ ConnectionStatus[ConnectionStatus["ULTRALIMIT"] = 1101] = "ULTRALIMIT"; /* 开始请求导航 */ ConnectionStatus[ConnectionStatus["REQUEST_NAVI"] = 201] = "REQUEST_NAVI"; /* 请求导航结束 */ ConnectionStatus[ConnectionStatus["RESPONSE_NAVI"] = 202] = "RESPONSE_NAVI"; /* 请求导航失败 */ ConnectionStatus[ConnectionStatus["RESPONSE_NAVI_ERROR"] = 203] = "RESPONSE_NAVI_ERROR"; /* 请求导航超时 */ ConnectionStatus[ConnectionStatus["RESPONSE_NAVI_TIMEOUT"] = 204] = "RESPONSE_NAVI_TIMEOUT"; })(RongIMLib.ConnectionStatus || (RongIMLib.ConnectionStatus = {})); var ConnectionStatus = RongIMLib.ConnectionStatus; (function (ConversationNotificationStatus) { /** * 免打扰状态,关闭对应会话的通知提醒。 */ ConversationNotificationStatus[ConversationNotificationStatus["DO_NOT_DISTURB"] = 1] = "DO_NOT_DISTURB"; /** * 提醒。 */ ConversationNotificationStatus[ConversationNotificationStatus["NOTIFY"] = 2] = "NOTIFY"; })(RongIMLib.ConversationNotificationStatus || (RongIMLib.ConversationNotificationStatus = {})); var ConversationNotificationStatus = RongIMLib.ConversationNotificationStatus; (function (ConversationType) { ConversationType[ConversationType["NONE"] = 0] = "NONE"; ConversationType[ConversationType["PRIVATE"] = 1] = "PRIVATE"; ConversationType[ConversationType["DISCUSSION"] = 2] = "DISCUSSION"; ConversationType[ConversationType["GROUP"] = 3] = "GROUP"; ConversationType[ConversationType["CHATROOM"] = 4] = "CHATROOM"; ConversationType[ConversationType["CUSTOMER_SERVICE"] = 5] = "CUSTOMER_SERVICE"; ConversationType[ConversationType["SYSTEM"] = 6] = "SYSTEM"; //默认关注 MC ConversationType[ConversationType["APP_PUBLIC_SERVICE"] = 7] = "APP_PUBLIC_SERVICE"; //手工关注 MP ConversationType[ConversationType["PUBLIC_SERVICE"] = 8] = "PUBLIC_SERVICE"; })(RongIMLib.ConversationType || (RongIMLib.ConversationType = {})); var ConversationType = RongIMLib.ConversationType; (function (DiscussionInviteStatus) { /** * 开放邀请。 */ DiscussionInviteStatus[DiscussionInviteStatus["OPENED"] = 0] = "OPENED"; /** * 关闭邀请。 */ DiscussionInviteStatus[DiscussionInviteStatus["CLOSED"] = 1] = "CLOSED"; })(RongIMLib.DiscussionInviteStatus || (RongIMLib.DiscussionInviteStatus = {})); var DiscussionInviteStatus = RongIMLib.DiscussionInviteStatus; (function (ErrorCode) { /* 超时 */ ErrorCode[ErrorCode["TIMEOUT"] = -1] = "TIMEOUT"; /** * 未知原因失败。 */ ErrorCode[ErrorCode["UNKNOWN"] = -2] = "UNKNOWN"; /* 参数错误 */ ErrorCode[ErrorCode["PARAMETER_ERROR"] = -3] = "PARAMETER_ERROR"; ErrorCode[ErrorCode["RECALL_MESSAGE"] = 25101] = "RECALL_MESSAGE"; /** * 发送频率过快 */ ErrorCode[ErrorCode["SEND_FREQUENCY_TOO_FAST"] = 20604] = "SEND_FREQUENCY_TOO_FAST"; ErrorCode[ErrorCode["RC_MSG_UNAUTHORIZED"] = 20406] = "RC_MSG_UNAUTHORIZED"; /** * 群组 Id 无效 */ ErrorCode[ErrorCode["RC_DISCUSSION_GROUP_ID_INVALID"] = 20407] = "RC_DISCUSSION_GROUP_ID_INVALID"; /** * 群组被禁言 */ ErrorCode[ErrorCode["FORBIDDEN_IN_GROUP"] = 22408] = "FORBIDDEN_IN_GROUP"; /** * 不在讨论组。 */ ErrorCode[ErrorCode["NOT_IN_DISCUSSION"] = 21406] = "NOT_IN_DISCUSSION"; /** * 不在群组。 */ ErrorCode[ErrorCode["NOT_IN_GROUP"] = 22406] = "NOT_IN_GROUP"; /** * 不在聊天室。 */ ErrorCode[ErrorCode["NOT_IN_CHATROOM"] = 23406] = "NOT_IN_CHATROOM"; /** *聊天室被禁言 */ ErrorCode[ErrorCode["FORBIDDEN_IN_CHATROOM"] = 23408] = "FORBIDDEN_IN_CHATROOM"; /** * 聊天室中成员被踢出 */ ErrorCode[ErrorCode["RC_CHATROOM_USER_KICKED"] = 23409] = "RC_CHATROOM_USER_KICKED"; /** * 聊天室不存在 */ ErrorCode[ErrorCode["RC_CHATROOM_NOT_EXIST"] = 23410] = "RC_CHATROOM_NOT_EXIST"; /** * 聊天室成员已满 */ ErrorCode[ErrorCode["RC_CHATROOM_IS_FULL"] = 23411] = "RC_CHATROOM_IS_FULL"; /** * 获取聊天室信息参数无效 */ ErrorCode[ErrorCode["RC_CHATROOM_PATAMETER_INVALID"] = 23412] = "RC_CHATROOM_PATAMETER_INVALID"; /** * 聊天室异常 */ ErrorCode[ErrorCode["CHATROOM_GET_HISTORYMSG_ERROR"] = 23413] = "CHATROOM_GET_HISTORYMSG_ERROR"; /** * 没有打开聊天室消息存储 */ ErrorCode[ErrorCode["CHATROOM_NOT_OPEN_HISTORYMSG_STORE"] = 23414] = "CHATROOM_NOT_OPEN_HISTORYMSG_STORE"; /** * 聊天室 KV 设置超出最大值(已满, 默认最多设置 100 个) */ ErrorCode[ErrorCode["CHATROOM_KV_EXCEED"] = 23423] = "CHATROOM_KV_EXCEED"; /** * 聊天室 KV 设置失败(kv 已存在, 需覆盖设置) */ ErrorCode[ErrorCode["CHATROOM_KV_OVERWRITE_INVALID"] = 23424] = "CHATROOM_KV_OVERWRITE_INVALID"; /** * 聊天室 KV 存储功能没有开通 */ ErrorCode[ErrorCode["CHATROOM_KV_STORE_NOT_OPEN"] = 23426] = "CHATROOM_KV_STORE_NOT_OPEN"; /** * 聊天室Key不存在 */ ErrorCode[ErrorCode["CHATROOM_KEY_NOT_EXIST"] = 23427] = "CHATROOM_KEY_NOT_EXIST"; /** * 敏感词屏蔽 */ ErrorCode[ErrorCode["SENSITIVE_SHIELD"] = 21501] = "SENSITIVE_SHIELD"; ErrorCode[ErrorCode["SENSITIVE_REPLACE"] = 21502] = "SENSITIVE_REPLACE"; /** * 加入讨论失败 */ ErrorCode[ErrorCode["JOIN_IN_DISCUSSION"] = 21407] = "JOIN_IN_DISCUSSION"; /** * 创建讨论组失败 */ ErrorCode[ErrorCode["CREATE_DISCUSSION"] = 21408] = "CREATE_DISCUSSION"; /** * 设置讨论组邀请状态失败 */ ErrorCode[ErrorCode["INVITE_DICUSSION"] = 21409] = "INVITE_DICUSSION"; /** *获取用户失败 */ ErrorCode[ErrorCode["GET_USERINFO_ERROR"] = 23407] = "GET_USERINFO_ERROR"; /** * 在黑名单中。 */ ErrorCode[ErrorCode["REJECTED_BY_BLACKLIST"] = 405] = "REJECTED_BY_BLACKLIST"; /** * 通信过程中,当前 Socket 不存在。 */ ErrorCode[ErrorCode["RC_NET_CHANNEL_INVALID"] = 30001] = "RC_NET_CHANNEL_INVALID"; /** * Socket 连接不可用。 */ ErrorCode[ErrorCode["RC_NET_UNAVAILABLE"] = 30002] = "RC_NET_UNAVAILABLE"; /** * 通信超时。 */ ErrorCode[ErrorCode["RC_MSG_RESP_TIMEOUT"] = 30003] = "RC_MSG_RESP_TIMEOUT"; /** * 导航操作时,Http 请求失败。 */ ErrorCode[ErrorCode["RC_HTTP_SEND_FAIL"] = 30004] = "RC_HTTP_SEND_FAIL"; /** * HTTP 请求失败。 */ ErrorCode[ErrorCode["RC_HTTP_REQ_TIMEOUT"] = 30005] = "RC_HTTP_REQ_TIMEOUT"; /** * HTTP 接收失败。 */ ErrorCode[ErrorCode["RC_HTTP_RECV_FAIL"] = 30006] = "RC_HTTP_RECV_FAIL"; /** * 导航操作的 HTTP 请求,返回不是200。 */ ErrorCode[ErrorCode["RC_NAVI_RESOURCE_ERROR"] = 30007] = "RC_NAVI_RESOURCE_ERROR"; /** * 导航数据解析后,其中不存在有效数据。 */ ErrorCode[ErrorCode["RC_NODE_NOT_FOUND"] = 30008] = "RC_NODE_NOT_FOUND"; /** * 导航数据解析后,其中不存在有效 IP 地址。 */ ErrorCode[ErrorCode["RC_DOMAIN_NOT_RESOLVE"] = 30009] = "RC_DOMAIN_NOT_RESOLVE"; /** * 创建 Socket 失败。 */ ErrorCode[ErrorCode["RC_SOCKET_NOT_CREATED"] = 30010] = "RC_SOCKET_NOT_CREATED"; /** * Socket 被断开。 */ ErrorCode[ErrorCode["RC_SOCKET_DISCONNECTED"] = 30011] = "RC_SOCKET_DISCONNECTED"; /** * PING 操作失败。 */ ErrorCode[ErrorCode["RC_PING_SEND_FAIL"] = 30012] = "RC_PING_SEND_FAIL"; /** * PING 超时。 */ ErrorCode[ErrorCode["RC_PONG_RECV_FAIL"] = 30013] = "RC_PONG_RECV_FAIL"; /** * 消息发送失败。 */ ErrorCode[ErrorCode["RC_MSG_SEND_FAIL"] = 30014] = "RC_MSG_SEND_FAIL"; /** * JSON 后的消息体超限, 目前最大 128kb * */ ErrorCode[ErrorCode["RC_MSG_CONTENT_EXCEED_LIMIT"] = 30016] = "RC_MSG_CONTENT_EXCEED_LIMIT"; /** * 做 connect 连接时,收到的 ACK 超时。 */ ErrorCode[ErrorCode["RC_CONN_ACK_TIMEOUT"] = 31000] = "RC_CONN_ACK_TIMEOUT"; /** * 参数错误。 */ ErrorCode[ErrorCode["RC_CONN_PROTO_VERSION_ERROR"] = 31001] = "RC_CONN_PROTO_VERSION_ERROR"; /** * 参数错误,App Id 错误。 */ ErrorCode[ErrorCode["RC_CONN_ID_REJECT"] = 31002] = "RC_CONN_ID_REJECT"; /** * 服务器不可用。 */ ErrorCode[ErrorCode["RC_CONN_SERVER_UNAVAILABLE"] = 31003] = "RC_CONN_SERVER_UNAVAILABLE"; /** * Token 错误。 */ ErrorCode[ErrorCode["RC_CONN_USER_OR_PASSWD_ERROR"] = 31004] = "RC_CONN_USER_OR_PASSWD_ERROR"; /** * App Id 与 Token 不匹配。 */ ErrorCode[ErrorCode["RC_CONN_NOT_AUTHRORIZED"] = 31005] = "RC_CONN_NOT_AUTHRORIZED"; /** * 重定向,地址错误。 */ ErrorCode[ErrorCode["RC_CONN_REDIRECTED"] = 31006] = "RC_CONN_REDIRECTED"; /** * NAME 与后台注册信息不一致。 */ ErrorCode[ErrorCode["RC_CONN_PACKAGE_NAME_INVALID"] = 31007] = "RC_CONN_PACKAGE_NAME_INVALID"; /** * APP 被屏蔽、删除或不存在。 */ ErrorCode[ErrorCode["RC_CONN_APP_BLOCKED_OR_DELETED"] = 31008] = "RC_CONN_APP_BLOCKED_OR_DELETED"; /** * 用户被屏蔽。 */ ErrorCode[ErrorCode["RC_CONN_USER_BLOCKED"] = 31009] = "RC_CONN_USER_BLOCKED"; /** * Disconnect,由服务器返回,比如用户互踢。 */ ErrorCode[ErrorCode["RC_DISCONN_KICK"] = 31010] = "RC_DISCONN_KICK"; /** * Disconnect,由服务器返回,比如用户互踢。 */ ErrorCode[ErrorCode["RC_DISCONN_EXCEPTION"] = 31011] = "RC_DISCONN_EXCEPTION"; /** * 协议层内部错误。query,上传下载过程中数据错误。 */ ErrorCode[ErrorCode["RC_QUERY_ACK_NO_DATA"] = 32001] = "RC_QUERY_ACK_NO_DATA"; /** * 协议层内部错误。 */ ErrorCode[ErrorCode["RC_MSG_DATA_INCOMPLETE"] = 32002] = "RC_MSG_DATA_INCOMPLETE"; /** * 未调用 init 初始化函数。 */ ErrorCode[ErrorCode["BIZ_ERROR_CLIENT_NOT_INIT"] = 33001] = "BIZ_ERROR_CLIENT_NOT_INIT"; /** * 数据库初始化失败。 */ ErrorCode[ErrorCode["BIZ_ERROR_DATABASE_ERROR"] = 33002] = "BIZ_ERROR_DATABASE_ERROR"; /** * 传入参数无效。 */ ErrorCode[ErrorCode["BIZ_ERROR_INVALID_PARAMETER"] = 33003] = "BIZ_ERROR_INVALID_PARAMETER"; /** * 通道无效。 */ ErrorCode[ErrorCode["BIZ_ERROR_NO_CHANNEL"] = 33004] = "BIZ_ERROR_NO_CHANNEL"; /** * 重新连接成功。 */ ErrorCode[ErrorCode["BIZ_ERROR_RECONNECT_SUCCESS"] = 33005] = "BIZ_ERROR_RECONNECT_SUCCESS"; /** * 连接中,再调用 connect 被拒绝。 */ ErrorCode[ErrorCode["BIZ_ERROR_CONNECTING"] = 33006] = "BIZ_ERROR_CONNECTING"; /** * 消息漫游服务未开通 */ ErrorCode[ErrorCode["MSG_ROAMING_SERVICE_UNAVAILABLE"] = 33007] = "MSG_ROAMING_SERVICE_UNAVAILABLE"; ErrorCode[ErrorCode["MSG_INSERT_ERROR"] = 33008] = "MSG_INSERT_ERROR"; ErrorCode[ErrorCode["MSG_DEL_ERROR"] = 33009] = "MSG_DEL_ERROR"; /** * 删除会话失败 */ ErrorCode[ErrorCode["CONVER_REMOVE_ERROR"] = 34001] = "CONVER_REMOVE_ERROR"; /** *拉取历史消息 */ ErrorCode[ErrorCode["CONVER_GETLIST_ERROR"] = 34002] = "CONVER_GETLIST_ERROR"; /** * 会话指定异常 */ ErrorCode[ErrorCode["CONVER_SETOP_ERROR"] = 34003] = "CONVER_SETOP_ERROR"; /** * 获取会话未读消息总数失败 */ ErrorCode[ErrorCode["CONVER_TOTAL_UNREAD_ERROR"] = 34004] = "CONVER_TOTAL_UNREAD_ERROR"; /** * 获取指定会话类型未读消息数异常 */ ErrorCode[ErrorCode["CONVER_TYPE_UNREAD_ERROR"] = 34005] = "CONVER_TYPE_UNREAD_ERROR"; /** * 获取指定用户ID&会话类型未读消息数异常 */ ErrorCode[ErrorCode["CONVER_ID_TYPE_UNREAD_ERROR"] = 34006] = "CONVER_ID_TYPE_UNREAD_ERROR"; ErrorCode[ErrorCode["CONVER_CLEAR_ERROR"] = 34007] = "CONVER_CLEAR_ERROR"; ErrorCode[ErrorCode["CLEAR_HIS_ERROR"] = 34010] = "CLEAR_HIS_ERROR"; ErrorCode[ErrorCode["CLEAR_HIS_TYPE_ERROR"] = 34008] = "CLEAR_HIS_TYPE_ERROR"; ErrorCode[ErrorCode["CLEAR_HIS_TIME_ERROR"] = 34011] = "CLEAR_HIS_TIME_ERROR"; /* */ ErrorCode[ErrorCode["CONVER_GET_ERROR"] = 34009] = "CONVER_GET_ERROR"; //群组异常信息 /** * */ ErrorCode[ErrorCode["GROUP_SYNC_ERROR"] = 35001] = "GROUP_SYNC_ERROR"; /** * 匹配群信息异常 */ ErrorCode[ErrorCode["GROUP_MATCH_ERROR"] = 35002] = "GROUP_MATCH_ERROR"; //聊天室异常 /** * 加入聊天室Id为空 */ ErrorCode[ErrorCode["CHATROOM_ID_ISNULL"] = 36001] = "CHATROOM_ID_ISNULL"; /** * 加入聊天室失败 */ ErrorCode[ErrorCode["CHARTOOM_JOIN_ERROR"] = 36002] = "CHARTOOM_JOIN_ERROR"; /** * 拉取聊天室历史消息失败 */ ErrorCode[ErrorCode["CHATROOM_HISMESSAGE_ERROR"] = 36003] = "CHATROOM_HISMESSAGE_ERROR"; /** * 聊天室 kv 未找到 * */ ErrorCode[ErrorCode["CHATROOM_KV_NOT_FOUND"] = 36004] = "CHATROOM_KV_NOT_FOUND"; //黑名单异常 /** * 加入黑名单异常 */ ErrorCode[ErrorCode["BLACK_ADD_ERROR"] = 37001] = "BLACK_ADD_ERROR"; /** * 获得指定人员再黑名单中的状态异常 */ ErrorCode[ErrorCode["BLACK_GETSTATUS_ERROR"] = 37002] = "BLACK_GETSTATUS_ERROR"; /** * 移除黑名单异常 */ ErrorCode[ErrorCode["BLACK_REMOVE_ERROR"] = 37003] = "BLACK_REMOVE_ERROR"; /** * 获取草稿失败 */ ErrorCode[ErrorCode["DRAF_GET_ERROR"] = 38001] = "DRAF_GET_ERROR"; /** * 保存草稿失败 */ ErrorCode[ErrorCode["DRAF_SAVE_ERROR"] = 38002] = "DRAF_SAVE_ERROR"; /** * 删除草稿失败 */ ErrorCode[ErrorCode["DRAF_REMOVE_ERROR"] = 38003] = "DRAF_REMOVE_ERROR"; /** * 关注公众号失败 */ ErrorCode[ErrorCode["SUBSCRIBE_ERROR"] = 39001] = "SUBSCRIBE_ERROR"; /** * 关注公众号失败 */ ErrorCode[ErrorCode["QNTKN_FILETYPE_ERROR"] = 41001] = "QNTKN_FILETYPE_ERROR"; /** * 获取七牛token失败 */ ErrorCode[ErrorCode["QNTKN_GET_ERROR"] = 41002] = "QNTKN_GET_ERROR"; /** * cookie被禁用 */ ErrorCode[ErrorCode["COOKIE_ENABLE"] = 51001] = "COOKIE_ENABLE"; ErrorCode[ErrorCode["GET_MESSAGE_BY_ID_ERROR"] = 61001] = "GET_MESSAGE_BY_ID_ERROR"; // 没有注册DeviveId 也就是用户没有登陆 ErrorCode[ErrorCode["HAVNODEVICEID"] = 24001] = "HAVNODEVICEID"; // 已经存在 ErrorCode[ErrorCode["DEVICEIDISHAVE"] = 24002] = "DEVICEIDISHAVE"; // 成功 ErrorCode[ErrorCode["SUCCESS"] = 0] = "SUCCESS"; // 没有对应的用户或token ErrorCode[ErrorCode["FEILD"] = 24009] = "FEILD"; // voip为空 ErrorCode[ErrorCode["VOIPISNULL"] = 24013] = "VOIPISNULL"; // 不支持的Voip引擎 ErrorCode[ErrorCode["NOENGINETYPE"] = 24010] = "NOENGINETYPE"; // channleName 是空 ErrorCode[ErrorCode["NULLCHANNELNAME"] = 24011] = "NULLCHANNELNAME"; // 生成Voipkey失败 ErrorCode[ErrorCode["VOIPDYANMICERROR"] = 24012] = "VOIPDYANMICERROR"; // 没有配置voip ErrorCode[ErrorCode["NOVOIP"] = 24014] = "NOVOIP"; // 服务器内部错误 ErrorCode[ErrorCode["INTERNALERRROR"] = 24015] = "INTERNALERRROR"; //VOIP close ErrorCode[ErrorCode["VOIPCLOSE"] = 24016] = "VOIPCLOSE"; ErrorCode[ErrorCode["CLOSE_BEFORE_OPEN"] = 51001] = "CLOSE_BEFORE_OPEN"; ErrorCode[ErrorCode["ALREADY_IN_USE"] = 51002] = "ALREADY_IN_USE"; ErrorCode[ErrorCode["INVALID_CHANNEL_NAME"] = 51003] = "INVALID_CHANNEL_NAME"; ErrorCode[ErrorCode["VIDEO_CONTAINER_IS_NULL"] = 51004] = "VIDEO_CONTAINER_IS_NULL"; /** * 删除消息数组长度为 0 . */ ErrorCode[ErrorCode["DELETE_MESSAGE_ID_IS_NULL"] = 61001] = "DELETE_MESSAGE_ID_IS_NULL"; /*! 己方取消已发出的通话请求 */ ErrorCode[ErrorCode["CANCEL"] = 1] = "CANCEL"; /*! 己方拒绝收到的通话请求 */ ErrorCode[ErrorCode["REJECT"] = 2] = "REJECT"; /*! 己方挂断 */ ErrorCode[ErrorCode["HANGUP"] = 3] = "HANGUP"; /*! 己方忙碌 */ ErrorCode[ErrorCode["BUSYLINE"] = 4] = "BUSYLINE"; /*! 己方未接听 */ ErrorCode[ErrorCode["NO_RESPONSE"] = 5] = "NO_RESPONSE"; /*! 己方不支持当前引擎 */ ErrorCode[ErrorCode["ENGINE_UN_SUPPORTED"] = 6] = "ENGINE_UN_SUPPORTED"; /*! 己方网络出错 */ ErrorCode[ErrorCode["NETWORK_ERROR"] = 7] = "NETWORK_ERROR"; /*! 对方取消已发出的通话请求 */ ErrorCode[ErrorCode["REMOTE_CANCEL"] = 11] = "REMOTE_CANCEL"; /*! 对方拒绝收到的通话请求 */ ErrorCode[ErrorCode["REMOTE_REJECT"] = 12] = "REMOTE_REJECT"; /*! 通话过程对方挂断 */ ErrorCode[ErrorCode["REMOTE_HANGUP"] = 13] = "REMOTE_HANGUP"; /*! 对方忙碌 */ ErrorCode[ErrorCode["REMOTE_BUSYLINE"] = 14] = "REMOTE_BUSYLINE"; /*! 对方未接听 */ ErrorCode[ErrorCode["REMOTE_NO_RESPONSE"] = 15] = "REMOTE_NO_RESPONSE"; /*! 对方网络错误 */ ErrorCode[ErrorCode["REMOTE_ENGINE_UN_SUPPORTED"] = 16] = "REMOTE_ENGINE_UN_SUPPORTED"; /*! 对方网络错误 */ ErrorCode[ErrorCode["REMOTE_NETWORK_ERROR"] = 17] = "REMOTE_NETWORK_ERROR"; /*! VoIP 不可用 */ ErrorCode[ErrorCode["VOIP_NOT_AVALIABLE"] = 18] = "VOIP_NOT_AVALIABLE"; })(RongIMLib.ErrorCode || (RongIMLib.ErrorCode = {})); var ErrorCode = RongIMLib.ErrorCode; (function (VoIPMediaType) { VoIPMediaType[VoIPMediaType["MEDIA_AUDIO"] = 1] = "MEDIA_AUDIO"; VoIPMediaType[VoIPMediaType["MEDIA_VEDIO"] = 2] = "MEDIA_VEDIO"; VoIPMediaType[VoIPMediaType["MEDIA_VIDEO"] = 2] = "MEDIA_VIDEO"; })(RongIMLib.VoIPMediaType || (RongIMLib.VoIPMediaType = {})); var VoIPMediaType = RongIMLib.VoIPMediaType; (function (MediaType) { /** * 图片。 */ MediaType[MediaType["IMAGE"] = 1] = "IMAGE"; /** * 声音。 */ MediaType[MediaType["AUDIO"] = 2] = "AUDIO"; /** * 视频。 */ MediaType[MediaType["VIDEO"] = 3] = "VIDEO"; /** * 通用文件。 */ MediaType[MediaType["FILE"] = 100] = "FILE"; })(RongIMLib.MediaType || (RongIMLib.MediaType = {})); var MediaType = RongIMLib.MediaType; (function (MessageDirection) { /** * 发送消息。 */ MessageDirection[MessageDirection["SEND"] = 1] = "SEND"; /** * 接收消息。 */ MessageDirection[MessageDirection["RECEIVE"] = 2] = "RECEIVE"; })(RongIMLib.MessageDirection || (RongIMLib.MessageDirection = {})); var MessageDirection = RongIMLib.MessageDirection; (function (FileType) { FileType[FileType["IMAGE"] = 1] = "IMAGE"; FileType[FileType["AUDIO"] = 2] = "AUDIO"; FileType[FileType["VIDEO"] = 3] = "VIDEO"; FileType[FileType["FILE"] = 4] = "FILE"; })(RongIMLib.FileType || (RongIMLib.FileType = {})); var FileType = RongIMLib.FileType; (function (RealTimeLocationErrorCode) { /** * 未初始化 RealTimeLocation 实例 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_NOT_INIT"] = -1] = "RC_REAL_TIME_LOCATION_NOT_INIT"; /** * 执行成功。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_SUCCESS"] = 0] = "RC_REAL_TIME_LOCATION_SUCCESS"; /** * 获取 RealTimeLocation 实例时返回 * GPS 未打开。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_GPS_DISABLED"] = 1] = "RC_REAL_TIME_LOCATION_GPS_DISABLED"; /** * 获取 RealTimeLocation 实例时返回 * 当前会话不支持位置共享。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_CONVERSATION_NOT_SUPPORT"] = 2] = "RC_REAL_TIME_LOCATION_CONVERSATION_NOT_SUPPORT"; /** * 获取 RealTimeLocation 实例时返回 * 对方已发起位置共享。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_IS_ON_GOING"] = 3] = "RC_REAL_TIME_LOCATION_IS_ON_GOING"; /** * Join 时返回 * 当前位置共享已超过最大支持人数。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_EXCEED_MAX_PARTICIPANT"] = 4] = "RC_REAL_TIME_LOCATION_EXCEED_MAX_PARTICIPANT"; /** * Join 时返回 * 加入位置共享失败。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_JOIN_FAILURE"] = 5] = "RC_REAL_TIME_LOCATION_JOIN_FAILURE"; /** * Start 时返回 * 发起位置共享失败。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_START_FAILURE"] = 6] = "RC_REAL_TIME_LOCATION_START_FAILURE"; /** * 网络不可用。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_NETWORK_UNAVAILABLE"] = 7] = "RC_REAL_TIME_LOCATION_NETWORK_UNAVAILABLE"; })(RongIMLib.RealTimeLocationErrorCode || (RongIMLib.RealTimeLocationErrorCode = {})); var RealTimeLocationErrorCode = RongIMLib.RealTimeLocationErrorCode; (function (RealTimeLocationStatus) { /** * 空闲状态 (默认状态) * 对方或者自己都未发起位置共享业务,或者位置共享业务已结束。 */ RealTimeLocationStatus[RealTimeLocationStatus["RC_REAL_TIME_LOCATION_STATUS_IDLE"] = 0] = "RC_REAL_TIME_LOCATION_STATUS_IDLE"; /** * 呼入状态 (待加入) * 1. 对方发起了位置共享业务,此状态下,自己只能选择加入。 * 2. 自己从已连接的位置共享中退出。 */ RealTimeLocationStatus[RealTimeLocationStatus["RC_REAL_TIME_LOCATION_STATUS_INCOMING"] = 1] = "RC_REAL_TIME_LOCATION_STATUS_INCOMING"; /** * 呼出状态 =(自己创建) * 1. 自己发起位置共享业务,对方只能选择加入。 * 2. 对方从已连接的位置共享业务中退出。 */ RealTimeLocationStatus[RealTimeLocationStatus["RC_REAL_TIME_LOCATION_STATUS_OUTGOING"] = 2] = "RC_REAL_TIME_LOCATION_STATUS_OUTGOING"; /** * 连接状态 (自己加入) * 对方加入了自己发起的位置共享,或者自己加入了对方发起的位置共享。 */ RealTimeLocationStatus[RealTimeLocationStatus["RC_REAL_TIME_LOCATION_STATUS_CONNECTED"] = 3] = "RC_REAL_TIME_LOCATION_STATUS_CONNECTED"; })(RongIMLib.RealTimeLocationStatus || (RongIMLib.RealTimeLocationStatus = {})); var RealTimeLocationStatus = RongIMLib.RealTimeLocationStatus; (function (ReceivedStatus) { ReceivedStatus[ReceivedStatus["READ"] = 1] = "READ"; ReceivedStatus[ReceivedStatus["LISTENED"] = 2] = "LISTENED"; ReceivedStatus[ReceivedStatus["DOWNLOADED"] = 4] = "DOWNLOADED"; ReceivedStatus[ReceivedStatus["RETRIEVED"] = 8] = "RETRIEVED"; ReceivedStatus[ReceivedStatus["UNREAD"] = 0] = "UNREAD"; })(RongIMLib.ReceivedStatus || (RongIMLib.ReceivedStatus = {})); var ReceivedStatus = RongIMLib.ReceivedStatus; (function (ReadStatus) { ReadStatus[ReadStatus["READ"] = 1] = "READ"; ReadStatus[ReadStatus["LISTENED"] = 2] = "LISTENED"; ReadStatus[ReadStatus["DOWNLOADED"] = 4] = "DOWNLOADED"; ReadStatus[ReadStatus["RETRIEVED"] = 8] = "RETRIEVED"; ReadStatus[ReadStatus["UNREAD"] = 0] = "UNREAD"; })(RongIMLib.ReadStatus || (RongIMLib.ReadStatus = {})); var ReadStatus = RongIMLib.ReadStatus; (function (SearchType) { /** * 精确。 */ SearchType[SearchType["EXACT"] = 0] = "EXACT"; /** * 模糊。 */ SearchType[SearchType["FUZZY"] = 1] = "FUZZY"; })(RongIMLib.SearchType || (RongIMLib.SearchType = {})); var SearchType = RongIMLib.SearchType; (function (SentStatus) { /** * 发送中。 */ SentStatus[SentStatus["SENDING"] = 10] = "SENDING"; /** * 发送失败。 */ SentStatus[SentStatus["FAILED"] = 20] = "FAILED"; /** * 已发送。 */ SentStatus[SentStatus["SENT"] = 30] = "SENT"; /** * 对方已接收。 */ SentStatus[SentStatus["RECEIVED"] = 40] = "RECEIVED"; /** * 对方已读。 */ SentStatus[SentStatus["READ"] = 50] = "READ"; /** * 对方已销毁。 */ SentStatus[SentStatus["DESTROYED"] = 60] = "DESTROYED"; })(RongIMLib.SentStatus || (RongIMLib.SentStatus = {})); var SentStatus = RongIMLib.SentStatus; (function (ConnectionState) { ConnectionState[ConnectionState["ACCEPTED"] = 0] = "ACCEPTED"; ConnectionState[ConnectionState["UNACCEPTABLE_PROTOCOL_VERSION"] = 1] = "UNACCEPTABLE_PROTOCOL_VERSION"; ConnectionState[ConnectionState["IDENTIFIER_REJECTED"] = 2] = "IDENTIFIER_REJECTED"; ConnectionState[ConnectionState["SERVER_UNAVAILABLE"] = 3] = "SERVER_UNAVAILABLE"; /** * token无效 */ ConnectionState[ConnectionState["TOKEN_INCORRECT"] = 4] = "TOKEN_INCORRECT"; ConnectionState[ConnectionState["NOT_AUTHORIZED"] = 5] = "NOT_AUTHORIZED"; ConnectionState[ConnectionState["REDIRECT"] = 6] = "REDIRECT"; ConnectionState[ConnectionState["PACKAGE_ERROR"] = 7] = "PACKAGE_ERROR"; ConnectionState[ConnectionState["APP_BLOCK_OR_DELETE"] = 8] = "APP_BLOCK_OR_DELETE"; ConnectionState[ConnectionState["BLOCK"] = 9] = "BLOCK"; ConnectionState[ConnectionState["TOKEN_EXPIRE"] = 10] = "TOKEN_EXPIRE"; ConnectionState[ConnectionState["DEVICE_ERROR"] = 11] = "DEVICE_ERROR"; })(RongIMLib.ConnectionState || (RongIMLib.ConnectionState = {})); var ConnectionState = RongIMLib.ConnectionState; (function (RTCAPIType) { RTCAPIType[RTCAPIType["ROOM"] = 1] = "ROOM"; RTCAPIType[RTCAPIType["PERSON"] = 2] = "PERSON"; })(RongIMLib.RTCAPIType || (RongIMLib.RTCAPIType = {})); var RTCAPIType = RongIMLib.RTCAPIType; (function (ChatroomEntityOpt) { ChatroomEntityOpt[ChatroomEntityOpt["UPDATE"] = 1] = "UPDATE"; ChatroomEntityOpt[ChatroomEntityOpt["DELETE"] = 2] = "DELETE"; })(RongIMLib.ChatroomEntityOpt || (RongIMLib.ChatroomEntityOpt = {})); var ChatroomEntityOpt = RongIMLib.ChatroomEntityOpt; (function (ChatroomEntityLimit) { ChatroomEntityLimit[ChatroomEntityLimit["KEY"] = 128] = "KEY"; ChatroomEntityLimit[ChatroomEntityLimit["VALUE"] = 4096] = "VALUE"; })(RongIMLib.ChatroomEntityLimit || (RongIMLib.ChatroomEntityLimit = {})); var ChatroomEntityLimit = RongIMLib.ChatroomEntityLimit; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var RongIMClient = (function () { function RongIMClient() { } RongIMClient.getInstance = function () { if (!RongIMClient._instance) { throw new Error("RongIMClient is not initialized. Call .init() method first."); } return RongIMClient._instance; }; RongIMClient.showError = function (errorInfo) { var hasConsole = (console && console.error); if (hasConsole) { console.error(JSON.stringify(errorInfo)); } }; RongIMClient.logger = function (params) { var code = params.code; var errorInfo = RongIMClient.LogFactory[code] || params; errorInfo.funcName = params.funcName; errorInfo.msg = params.msg || errorInfo.msg; if (RongIMClient._memoryStore.depend.showError) { RongIMClient.showError(errorInfo); } }; RongIMClient.logCallback = function (callback, funcName) { return { onSuccess: callback.onSuccess, onError: function (errorCode) { RongIMClient.logger({ code: errorCode, funcName: funcName }); callback.onError(errorCode); } }; }; ; RongIMClient.logSendCallback = function (callback, funcName) { return { onSuccess: callback.onSuccess, onError: function (errorCode, result) { RongIMClient.logger({ code: errorCode, funcName: funcName }); callback.onError(errorCode, result); }, onBefore: callback.onBefore }; }; ; /** * 初始化 SDK,在整个应用全局只需要调用一次。 * @param appKey 开发者后台申请的 AppKey,用来标识应用。 * @param dataAccessProvider 必须是DataAccessProvider的实例 */ RongIMClient.init = function (appKey, dataAccessProvider, options, callback) { RongIMClient.statusListeners = []; RongIMClient.messageListeners = []; RongIMClient.settingListeners = []; RongIMClient.conversationStatusListeners = []; if (RongIMClient._instance) { return RongIMClient._memoryStore.sdkInfo; } RongIMClient._instance = new RongIMClient(); options = options || {}; var protocol = "http://", wsScheme = 'ws://'; var isLocationInvalid = typeof location !== 'object'; // 未找到全局 location 变量, 则协议为 https. 比如小程序 if (isLocationInvalid || location.protocol == 'https:') { wsScheme = 'wss://'; protocol = 'https://'; } var isPolling = false; if (typeof WebSocket != 'function') { isPolling = true; } var isIntegrity = function () { //iOS 9 var hasWS = (typeof WebSocket); var integrity = (typeof WebSocket.OPEN == 'number'); return (hasWS && integrity); }; if (typeof WebSocket == 'object' && isIntegrity()) { isPolling = false; } var supportUserData = function () { var element = document.documentElement; return element.addBehavior; }; if (RongIMLib.RongUtil.supportLocalStorage()) { RongIMClient._storageProvider = new RongIMLib.LocalStorageProvider(); } else if (supportUserData()) { RongIMClient._storageProvider = new RongIMLib.UserDataProvider(); } else { RongIMClient._storageProvider = new RongIMLib.MemeoryProvider(); } var serverIndex = RongIMClient._storageProvider.getItem('serverIndex'); RongIMClient.serverStore.index = serverIndex || 0; var pathTmpl = '{0}{1}'; var _serverPath = { api: 'api.cn.ronghub.com' }; RongIMLib.RongUtil.forEach(_serverPath, function (path, key) { _serverPath[key] = RongIMLib.RongUtil.stringFormat(pathTmpl, [protocol, path]); }); RongIMLib.RongUtil.forEach(_serverPath, function (path, key) { var hasProto = (key in options); var config = { path: options[key], tmpl: pathTmpl, protocol: protocol, sub: true }; path = hasProto ? RongIMLib.RongUtil.formatProtoclPath(config) : path; options[key] = path; }); var navigaters = options.navigaters || []; if (options.navi) { navigaters = [options.navi]; } if (!options.navi && RongIMLib.RongUtil.isEqual(navigaters.length, 0)) { navigaters = ['nav.cn.ronghub.com', 'nav2-cn.ronghub.com']; } var _sourcePath = { protobuf: 'cdn.ronghub.com/protobuf-2.3.8.min.js' }; RongIMLib.RongUtil.forEach(_sourcePath, function (path, key) { _sourcePath[key] = RongIMLib.RongUtil.stringFormat(pathTmpl, [protocol, path]); }); RongIMLib.RongUtil.extend(_sourcePath, options); var _defaultOpts = { isPolling: isPolling, wsScheme: wsScheme, protocol: protocol, showError: true, openMp: true, snifferTime: 2000, naviTimeout: 5000, navigaters: navigaters, maxNaviRetry: 10, isNaviJSONP: false, isWSPingJSONP: false, isNotifyConversationList: false, maxConversationCount: 300, cmpUrl: '' // 若传入 cmpUrl, 则优先链接此地址 }; delete options.navigaters; RongIMLib.RongUtil.extend(_defaultOpts, options); if (RongIMLib.RongUtil.isFunction(options.protobuf)) { RongIMClient.Protobuf = options.protobuf; } RongIMClient.userStatusObserver = new RongIMLib.RongObserver(); var pather = new RongIMLib.FeaturePatcher(); pather.patchAll(); var tempStore = { token: "", callback: null, lastReadTime: new RongIMLib.LimitableMap(), historyMessageLimit: new RongIMLib.MemoryCache(), conversationList: [], isFullConversations: false, appKey: appKey, publicServiceMap: new RongIMLib.PublicServiceMap(), providerType: 1, deltaTime: 0, filterMessages: [], isSyncRemoteConverList: true, otherDevice: false, custStore: {}, converStore: { latestMessage: {} }, connectAckTime: 0, voipStategy: 0, isFirstPingMsg: true, depend: options, notification: {}, networkUnavailable: false, loggerSwitch: options.loggerSwitch || 'on', autoReconnectTimer: null // 自动重连定时器编号 }; RongIMClient._memoryStore = tempStore; var isCPlusSDK = dataAccessProvider && Object.prototype.toString.call(dataAccessProvider) == "[object Object]"; if (isCPlusSDK) { RongIMClient._dataAccessProvider = dataAccessProvider; } else { RongIMClient._dataAccessProvider = new RongIMLib.ServerDataProvider(); } options.appCallback = callback; var sdkInfo = RongIMClient._dataAccessProvider.init(appKey, options); RongIMClient._memoryStore.sdkInfo = sdkInfo; if (isCPlusSDK) { // 兼容 c++ 设置导航,Web 端不生效 RongIMClient._dataAccessProvider.setServerInfo({ navi: location.protocol + options.navi + '/navi.xml' }); } RongIMClient.MessageParams = { TextMessage: { objectName: "RC:TxtMsg", msgTag: new RongIMLib.MessageTag(true, true) }, ImageMessage: { objectName: "RC:ImgMsg", msgTag: new RongIMLib.MessageTag(true, true) }, DiscussionNotificationMessage: { objectName: "RC:DizNtf", msgTag: new RongIMLib.MessageTag(false, true) }, VoiceMessage: { objectName: "RC:VcMsg", msgTag: new RongIMLib.MessageTag(true, true) }, ReferenceMessage: { objectName: "RC:ReferenceMsg", msgTag: new RongIMLib.MessageTag(true, true) }, RichContentMessage: { objectName: "RC:ImgTextMsg", msgTag: new RongIMLib.MessageTag(true, true) }, FileMessage: { objectName: "RC:FileMsg", msgTag: new RongIMLib.MessageTag(true, true) }, HQVoiceMessage: { objectName: "RC:HQVCMsg", msgTag: new RongIMLib.MessageTag(true, true) }, GIFMessage: { objectName: "RC:GIFMsg", msgTag: new RongIMLib.MessageTag(true, true) }, SightMessage: { objectName: "RC:SightMsg", msgTag: new RongIMLib.MessageTag(true, true) }, HandshakeMessage: { objectName: "", msgTag: new RongIMLib.MessageTag(true, true) }, UnknownMessage: { objectName: "", msgTag: new RongIMLib.MessageTag(true, true) }, LocationMessage: { objectName: "RC:LBSMsg", msgTag: new RongIMLib.MessageTag(true, true) }, InformationNotificationMessage: { objectName: "RC:InfoNtf", msgTag: new RongIMLib.MessageTag(false, true) }, ContactNotificationMessage: { objectName: "RC:ContactNtf", msgTag: new RongIMLib.MessageTag(false, true) }, ProfileNotificationMessage: { objectName: "RC:ProfileNtf", msgTag: new RongIMLib.MessageTag(false, true) }, CommandNotificationMessage: { objectName: "RC:CmdNtf", msgTag: new RongIMLib.MessageTag(false, true) }, PublicServiceRichContentMessage: { objectName: "RC:PSImgTxtMsg", msgTag: new RongIMLib.MessageTag(true, true) }, PublicServiceMultiRichContentMessage: { objectName: "RC:PSMultiImgTxtMsg", msgTag: new RongIMLib.MessageTag(true, true) }, JrmfRedPacketMessage: { objectName: "RCJrmf:RpMsg", msgTag: new RongIMLib.MessageTag(true, true) }, JrmfRedPacketOpenedMessage: { objectName: "RCJrmf:RpOpendMsg", msgTag: new RongIMLib.MessageTag(true, true) }, GroupNotificationMessage: { objectName: "RC:GrpNtf", msgTag: new RongIMLib.MessageTag(false, true) }, CommandMessage: { objectName: "RC:CmdMsg", msgTag: new RongIMLib.MessageTag(false, false) }, TypingStatusMessage: { objectName: "RC:TypSts", msgTag: new RongIMLib.MessageTag(false, false) }, PublicServiceCommandMessage: { objectName: "RC:PSCmd", msgTag: new RongIMLib.MessageTag(false, false) }, RecallCommandMessage: { objectName: "RC:RcCmd", msgTag: new RongIMLib.MessageTag(false, true) }, SyncReadStatusMessage: { objectName: "RC:SRSMsg", msgTag: new RongIMLib.MessageTag(false, false) }, ReadReceiptRequestMessage: { objectName: "RC:RRReqMsg", msgTag: new RongIMLib.MessageTag(false, false) }, ReadReceiptResponseMessage: { objectName: "RC:RRRspMsg", msgTag: new RongIMLib.MessageTag(false, false) }, ChangeModeResponseMessage: { objectName: "RC:CsChaR", msgTag: new RongIMLib.MessageTag(false, false) }, ChangeModeMessage: { objectName: "RC:CSCha", msgTag: new RongIMLib.MessageTag(false, false) }, EvaluateMessage: { objectName: "RC:CsEva", msgTag: new RongIMLib.MessageTag(false, false) }, CustomerContact: { objectName: "RC:CsContact", msgTag: new RongIMLib.MessageTag(false, false) }, HandShakeMessage: { objectName: "RC:CsHs", msgTag: new RongIMLib.MessageTag(false, false) }, HandShakeResponseMessage: { objectName: "RC:CsHsR", msgTag: new RongIMLib.MessageTag(false, false) }, SuspendMessage: { objectName: "RC:CsSp", msgTag: new RongIMLib.MessageTag(false, false) }, TerminateMessage: { objectName: "RC:CsEnd", msgTag: new RongIMLib.MessageTag(false, false) }, CustomerStatusUpdateMessage: { objectName: "RC:CsUpdate", msgTag: new RongIMLib.MessageTag(false, false) }, ReadReceiptMessage: { objectName: "RC:ReadNtf", msgTag: new RongIMLib.MessageTag(false, false) }, RCCombineMessage: { objectName: "RC:CombineMsg", msgTag: new RongIMLib.MessageTag(true, true) }, ChrmKVNotificationMessage: { objectName: 'RC:chrmKVNotiMsg', msgTag: new RongIMLib.MessageTag(false, false) }, LogCommandMessage: { objectName: 'RC:LogCmdMsg', msgTag: new RongIMLib.MessageTag(false, false) } }; RongIMClient.MessageParams["AcceptMessage"] = { objectName: "RC:VCAccept", msgTag: new RongIMLib.MessageTag(false, false) }; RongIMClient.MessageParams["RingingMessage"] = { objectName: "RC:VCRinging", msgTag: new RongIMLib.MessageTag(false, false) }; RongIMClient.MessageParams["SummaryMessage"] = { objectName: "RC:VCSummary", msgTag: new RongIMLib.MessageTag(false, false) }; RongIMClient.MessageParams["HungupMessage"] = { objectName: "RC:VCHangup", msgTag: new RongIMLib.MessageTag(false, false) }; RongIMClient.MessageParams["InviteMessage"] = { objectName: "RC:VCInvite", msgTag: new RongIMLib.MessageTag(false, false) }; RongIMClient.MessageParams["MediaModifyMessage"] = { objectName: "RC:VCModifyMedia", msgTag: new RongIMLib.MessageTag(false, false) }; RongIMClient.MessageParams["MemberModifyMessage"] = { objectName: "RC:VCModifyMem", msgTag: new RongIMLib.MessageTag(false, false) }; RongIMClient.MessageType = { TextMessage: "TextMessage", ImageMessage: "ImageMessage", ReferenceMessage: "ReferenceMessage", DiscussionNotificationMessage: "DiscussionNotificationMessage", VoiceMessage: "VoiceMessage", RichContentMessage: "RichContentMessage", HandshakeMessage: "HandshakeMessage", UnknownMessage: "UnknownMessage", LocationMessage: "LocationMessage", InformationNotificationMessage: "InformationNotificationMessage", ContactNotificationMessage: "ContactNotificationMessage", ProfileNotificationMessage: "ProfileNotificationMessage", CommandNotificationMessage: "CommandNotificationMessage", CommandMessage: "CommandMessage", TypingStatusMessage: "TypingStatusMessage", ChangeModeResponseMessage: "ChangeModeResponseMessage", ChangeModeMessage: "ChangeModeMessage", EvaluateMessage: "EvaluateMessage", HandShakeMessage: "HandShakeMessage", HandShakeResponseMessage: "HandShakeResponseMessage", SuspendMessage: "SuspendMessage", TerminateMessage: "TerminateMessage", CustomerContact: "CustomerContact", CustomerStatusUpdateMessage: "CustomerStatusUpdateMessage", SyncReadStatusMessage: "SyncReadStatusMessage", ReadReceiptRequestMessage: "ReadReceiptRequestMessage", ReadReceiptResponseMessage: "ReadReceiptResponseMessage", FileMessage: 'FileMessage', HQVoiceMessage: 'HQVoiceMessage', GIFMessage: 'GIFMessage', SightMessage: 'SightMessage', AcceptMessage: "AcceptMessage", RingingMessage: "RingingMessage", SummaryMessage: "SummaryMessage", HungupMessage: "HungupMessage", InviteMessage: "InviteMessage", MediaModifyMessage: "MediaModifyMessage", MemberModifyMessage: "MemberModifyMessage", JrmfRedPacketMessage: "JrmfRedPacketMessage", JrmfRedPacketOpenedMessage: "JrmfRedPacketOpenedMessage", GroupNotificationMessage: "GroupNotificationMessage", PublicServiceRichContentMessage: "PublicServiceRichContentMessage", PublicServiceMultiRichContentMessage: "PublicServiceMultiRichContentMessage", PublicServiceCommandMessage: "PublicServiceCommandMessage", RecallCommandMessage: "RecallCommandMessage", ReadReceiptMessage: "ReadReceiptMessage", RCCombineMessage: "RCCombineMessage", ChrmKVNotificationMessage: 'ChrmKVNotificationMessage', LogCommandMessage: 'LogCommandMessage' }; RongIMClient.LogFactory = { /** * 个人 */ "-1": { code: "-1", msg: "服务器超时" }, "-2": { code: "-2", msg: "未知原因失败" }, "-3": { code: "-3", msg: "参数错误" }, "-4": { code: "-4", msg: "参数不正确或尚未实例化" }, "25101": { code: "25101", msg: "撤回消息参数错误", desc: "请检查撤回消息参数 https://rongcloud.github.io/websdk-demo/api-test.html" }, "25102": { code: "25101", msg: "只能撤回自发发送的消息" }, "20604": { code: "20604", msg: "发送频率过快", desc: "https://developer.rongcloud.cn/ticket/info/9Q3L6vRKd1cLS7rycA==?type=1" }, "20406": { code: "20406", msg: "被禁言" }, "23407": { code: "23407", msg: "获取用户失败" }, /** * 群组 */ "20407": { code: "20407", msg: "群组Id无效" }, "22408": { code: "22408", msg: "群组被禁言" }, "22406": { code: "22406", msg: "不在群组" }, "35001": { code: "35001", msg: "群组同步异常" }, "35002": { code: "35002", msg: "匹配群信息异常" }, /** * 讨论组 */ "21406": { code: "21406", msg: "不在讨论组" }, "21407": { code: "21407", msg: "加入讨论失败" }, "21408": { code: "21408", msg: "创建讨论组失败" }, "21409": { code: "21409", msg: "设置讨论组邀请状态失败" }, /** * 聊天室 */ "23406": { code: "23406", msg: "不在聊天室" }, "23408": { code: "23408", msg: "聊天室被禁言" }, "23409": { code: "23409", msg: "聊天室中成员被踢出" }, "23410": { code: "23410", msg: "聊天室不存在" }, "23411": { code: "23411", msg: "聊天室成员已满" }, "23412": { code: "23412", msg: "获取聊天室信息参数无效" }, "23413": { code: "23413", msg: "聊天室异常" }, "23414": { code: "23414", msg: "没有打开聊天室消息存储" }, "36001": { code: "36001", msg: "加入聊天室Id为空" }, "36002": { code: "36002", msg: "加入聊天室失败" }, "36003": { code: "36003", msg: "拉取聊天室历史消息失败" }, /** * voip */ "24001": { code: "24001", msg: "没有注册DeviveId 也就是用户没有登陆" }, "24002": { code: "24002", msg: "用户已经存在" }, "0": { code: "0", msg: "成功" }, "24009": { code: "24009", msg: "没有对应的用户或token" }, "24013": { code: "24013", msg: "voip为空" }, "24010": { code: "24010", msg: "不支持的Voip引擎" }, "24011": { code: "24011", msg: "channelName 是空" }, "24012": { code: "24012", msg: "生成Voipkey失败" }, "24014": { code: "24014", msg: "没有配置voip" }, "24015": { code: "24015", msg: "服务器内部错误" }, "24016": { code: "24016", msg: "VOIP close" }, /** * 通讯、导航 */ "30001": { code: "30001", msg: "通信过程中,当前Socket不存在" }, "30002": { code: "30002", msg: "Socket连接不可用" }, "30003": { code: "30003", msg: "通信超时" }, "30004": { code: "30004", msg: "导航操作时,Http请求失败" }, "30005": { code: "30005", msg: "HTTP请求失败" }, "30006": { code: "30006", msg: "HTTP接收失败" }, "30007": { code: "30007", msg: "导航资源错误" }, "30008": { code: "30008", msg: "没有有效数据" }, "30009": { code: "30009", msg: "不存在有效 IP 地址" }, "30010": { code: "30010", msg: "创建 Socket 失败" }, "30011": { code: "30011", msg: " Socket 被断开" }, "30012": { code: "30012", msg: "PING 操作失败" }, "30013": { code: "30013", msg: "PING 超时" }, "30014": { code: "30014", msg: "消息发送失败" }, "30016": { code: "30016", msg: "消息大小超限,最大 128 KB" }, /** * 连接 */ "31000": { code: "31000", msg: "做 connect 连接时,收到的 ACK 超时" }, "31001": { code: "31001", msg: "参数错误" }, "31002": { code: "31002", msg: "参数错误,App Id 错误" }, "31003": { code: "31003", msg: "服务器不可用" }, "31004": { code: "31004", msg: "Token 错误" }, "31005": { code: "31005", msg: "App Id 与 Token 不匹配" }, "31006": { code: "31006", msg: "重定向,地址错误" }, "31007": { code: "31007", msg: "NAME 与后台注册信息不一致" }, "31008": { code: "31008", msg: "APP 被屏蔽、删除或不存在" }, "31009": { code: "31009", msg: "用户被屏蔽" }, "31010": { code: "31010", msg: "Disconnect,由服务器返回,比如用户互踢" }, "31011": { code: "31011", msg: "Disconnect,由服务器返回,比如用户互踢" }, /** * 协议 */ "32001": { code: "32001", msg: "协议层内部错误。query,上传下载过程中数据错误" }, "32002": { code: "32002", msg: "协议层内部错误" }, /** * BIZ */ "33001": { code: "33001", msg: "未调用 init 初始化函数" }, "33002": { code: "33002", msg: "数据库初始化失败" }, "33003": { code: "33003", msg: "传入参数无效" }, "33004": { code: "33004", msg: "通道无效" }, "33005": { code: "33005", msg: "重新连接成功" }, "33006": { code: "33006", msg: "连接中,再调用 connect 被拒绝" }, "33007": { code: "33007", msg: "消息漫游服务未开通" }, "33008": { code: "33008", msg: "消息添加失败" }, "33009": { code: "33009", msg: "消息删除失败" }, /** * 会话 */ "34001": { code: "34001", msg: "删除会话失败" }, "34002": { code: "34002", msg: "拉取历史消息失败" }, "34003": { code: "34003", msg: "会话指定异常" }, "34004": { code: "34004", msg: "获取会话未读消息总数失败" }, "34005": { code: "34005", msg: "获取指定会话类型未读消息数异常" }, "34006": { code: "34006", msg: "获取指定用户ID&会话类型未读消息数异常" }, "34007": { code: "34007", msg: "清除会话消息异常" }, "34008": { code: "34008", msg: "获取会话消息异常" }, "34009": { code: "34009", msg: "清除历史消息会话类型不正确" }, "34010": { code: "34010", msg: "清除历史消息失败,请检查传入参数" }, /** * 黑名单异常 */ "37001": { code: "37001", msg: "加入黑名单异常" }, "37002": { code: "37002", msg: "获得指定人员再黑名单中的状态异常" }, "37003": { code: "37003", msg: "移除黑名单异常" }, "405": { code: "405", msg: "在黑名单中" }, /** * 草稿 */ "38001": { code: "38001", msg: "获取草稿失败" }, "38002": { code: "38002", msg: "保存草稿失败" }, "38003": { code: "38003", msg: "删除草稿失败" }, /** * 公众号 */ "39001": { code: "39001", msg: "关注公众号失败" }, /** * 文件 */ "41001": { code: "41001", msg: "文件类型错误" }, "41002": { code: "41002", msg: "获取七牛token失败" }, /** * */ "51001": { code: "51001", msg: "未安装或未启动插件" }, "51002": { code: "51002", msg: "视频已经存在" }, "51003": { code: "51003", msg: "无效的channelName" }, "51004": { code: "51004", msg: "视频内容为空" }, /** * */ "61001": { code: "61001", msg: "删除消息数组长度为 0" } }; var handler = function (message, uris, callback) { var userId = message.senderUserId; var _uris = RongIMClient.roomInfo.users[userId].uris || '[]'; if (RongIMLib.RongUtil.isString(_uris)) { _uris = JSON.parse(_uris); } var tUris = JSON.parse(JSON.stringify(_uris)); RongIMLib.RongUtil.forEach(tUris, function (_uri, index) { RongIMLib.RongUtil.forEach(uris, function (uri) { if (uri.uri == _uri.uri) { callback(_uri, uri, _uris, index); } }); }); RongIMClient.roomInfo.users[userId].uris = JSON.stringify(_uris); }; var RTCMessage = { RTCPublishResourceMessage: function (message, uris) { var userId = message.senderUserId; var user = RongIMClient.roomInfo.users[userId]; if (!user) { user = {}; RongIMClient.roomInfo.users[userId] = {}; } var _uris = user.uris || '[]'; if (RongIMLib.RongUtil.isString(_uris)) { _uris = JSON.parse(_uris); } _uris = _uris.concat(uris); RongIMClient.roomInfo.users[userId].uris = JSON.stringify(_uris); }, RTCUnpublishResourceMessage: function (message, uris) { handler(message, uris, function (_uri, uri, _uris, index) { _uris.splice(index, 1); }); }, RTCModifyResourceMessage: function (message, uris) { handler(message, uris, function (_uri, uri) { _uri.state = uri.state; }); }, RTCUserChangeMessage: function (message) { var content = message.content; var users = content.users; var UserState = { JOINED: 0, LEFT: 1, OFFLINE: 2 }; RongIMLib.RongUtil.forEach(users, function (user) { var state = user.state; var userId = user.userId; switch (+state) { case UserState.JOINED: RongIMClient.roomInfo.users[userId] = {}; break; case UserState.LEFT: case UserState.OFFLINE: delete RongIMClient.roomInfo.users[userId]; break; } }); } }; RongIMClient.RTCInnerListener = function (message) { var func = RTCMessage[message.messageType] || function () { }; var content = message.content; var uris = content.uris; func(message, uris); }; RongIMClient.Conversation = RongIMClient._dataAccessProvider.Conversation; RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.A_INIT_O, level: RongIMLib.LoggerLevel.I, type: RongIMLib.LoggerType.IM, content: { appKey: appKey } }); return sdkInfo; }; ; RongIMClient.setProtocol = function (protocol) { RongIMClient._memoryStore.depend = RongIMClient._memoryStore.depend || {}; var HttpProtocol = RongIMClient.HttpProtocol; var WsProtocol = RongIMClient.WsProtocol; if (protocol === HttpProtocol.http) { RongIMClient._memoryStore.depend.protocol = HttpProtocol.http; RongIMClient._memoryStore.depend.wsScheme = WsProtocol.ws; } else { RongIMClient._memoryStore.depend.protocol = HttpProtocol.https; RongIMClient._memoryStore.depend.wsScheme = WsProtocol.wss; } }; RongIMClient.getProtocol = function () { RongIMClient._memoryStore.depend = RongIMClient._memoryStore.depend || {}; var depend = RongIMClient._memoryStore.depend; var protocol = depend.protocol, wsScheme = depend.wsScheme; if (!protocol || !wsScheme) { protocol = RongIMClient.HttpProtocol.https; wsScheme = RongIMClient.WsProtocol.wss; } return { protocol: protocol, wsScheme: wsScheme }; }; /** var config = { appkey: appkey, token: token, dataAccessProvider:dataAccessProvider, opts: opts }; callback(_instance, userId); */ RongIMClient.initApp = function (config, callback) { RongIMClient.init(config.appkey, config.dataAccessProvider, config.opts, function () { var instance = RongIMClient._instance; //备用 var error = null; callback(error, instance); }); }; /** * 连接服务器,在整个应用全局只需要调用一次,断线后 SDK 会自动重连。 * * @param token 从服务端获取的用户身份令牌(Token)。 * @param callback 连接回调,返回连接的成功或者失败状态。 */ RongIMClient.connect = function (token, _callback, userId, serverConf) { RongIMLib.CheckParam.getInstance().check(["string", "object", "string|null|object|global|undefined", "object|null|global|undefined"], "connect", true, arguments); if (RongIMLib.IMHandler.isIncludeNavi(token)) { var protocol = RongIMClient._memoryStore.depend.protocol; var currentNavs = RongIMClient._memoryStore.depend.navigaters; var navList = RongIMLib.IMHandler.getNavsByToken(token, protocol); token = RongIMLib.IMHandler.getToken(token); RongIMClient._memoryStore.depend.navigaters = RongIMLib.RongUtil.concat(navList, currentNavs, true); } var connectCallback = { onSuccess: _callback.onSuccess, onTokenIncorrect: _callback.onTokenIncorrect, onError: function (errorCode) { RongIMClient.logger({ code: errorCode, funcName: "connect" }); _callback.onError(errorCode); } }; RongIMClient._dataAccessProvider.connect(token, connectCallback, userId, serverConf); }; RongIMClient.reconnect = function (callback, config) { var connectCallback = { onSuccess: callback.onSuccess, onTokenIncorrect: callback.onTokenIncorrect, onError: function (errorCode) { RongIMClient.logger({ code: errorCode, funcName: "connect" }); callback.onError(errorCode); } }; RongIMClient._dataAccessProvider.reconnect(connectCallback, config); }; /** * 注册消息类型,用于注册用户自定义的消息。 * 内建的消息类型已经注册过,不需要再次注册。 * 自定义消息声明需放在执行顺序最高的位置(在RongIMClient.init(appkey)之后即可) * @param objectName 消息内置名称 */ RongIMClient.registerMessageType = function (messageType, objectName, messageTag, messageContent, searchProps) { RongIMClient._dataAccessProvider.registerMessageType(messageType, objectName, messageTag, messageContent, searchProps); RongIMClient.RegisterMessage[messageType].messageName = messageType; RongIMClient.MessageType[messageType] = messageType; RongIMClient.MessageParams[messageType] = { objectName: objectName, msgTag: messageTag }; }; RongIMClient.prototype.registerMessageTypes = function (types) { types = types || {}; RongIMClient._dataAccessProvider.registerMessageTypes(types); }; /** * 设置连接状态变化的监听器。 * * @param listener 连接状态变化的监听器。 */ RongIMClient.setConnectionStatusListener = function (listener) { if (RongIMClient._dataAccessProvider) { RongIMClient._dataAccessProvider.setConnectionStatusListener(listener); } else { if (RongIMLib.RongUtil.isObject(listener) && RongIMLib.RongUtil.isFunction(listener.onChanged)) { RongIMClient.statusListeners.push(listener.onChanged); } } }; RongIMClient.setConversationStatusListener = function (listener) { if (listener && listener.onChanged && RongIMLib.RongUtil.isFunction(listener.onChanged)) { RongIMClient.conversationStatusListeners.push(listener.onChanged); } }; RongIMClient.statusWatch = function (watcher) { if (RongIMLib.RongUtil.isFunction(watcher)) { RongIMClient.statusListeners.push(watcher); } }; RongIMClient.watch = function (watchers) { watchers = watchers || {}; var setting = watchers.setting; if (RongIMLib.RongUtil.isFunction(setting)) { RongIMClient.settingListeners.push(setting); } }; /** * 设置接收消息的监听器。 * * @param listener 接收消息的监听器。 */ RongIMClient.setOnReceiveMessageListener = function (listener) { if (RongIMClient._dataAccessProvider) { RongIMClient._dataAccessProvider.setOnReceiveMessageListener(listener); } else { if (RongIMLib.RongUtil.isObject(listener) && RongIMLib.RongUtil.isFunction(listener.onReceived)) { RongIMClient.messageListeners.push(listener.onReceived); } } }; /** * 清理所有连接相关的变量 */ RongIMClient.prototype.logout = function () { RongIMClient._dataAccessProvider.logout(); }; /** * 断开连接。 */ RongIMClient.prototype.disconnect = function () { RongIMClient._dataAccessProvider.disconnect(); RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.A_DISC_O, level: RongIMLib.LoggerLevel.I, type: RongIMLib.LoggerType.IM }); }; RongIMClient.prototype.startCustomService = function (custId, callback, content) { if (!custId || !callback) return; var msg = new RongIMLib.HandShakeMessage(content); var me = this; RongIMLib.RongIMClient._memoryStore.custStore["isInit"] = true; RongIMClient.getInstance().sendMessage(RongIMLib.ConversationType.CUSTOMER_SERVICE, custId, msg, { onSuccess: function (data) { if (data.isBlack) { callback.onError(); me.stopCustomeService(custId, { onSuccess: function () { }, onError: function () { } }); } else { callback.onSuccess(); } }, onError: function () { callback.onError(); }, onBefore: function () { } }); }; RongIMClient.prototype.stopCustomeService = function (custId, callback) { if (!custId || !callback) return; var session = RongIMClient._memoryStore.custStore[custId]; if (!session) return; var msg = new RongIMLib.SuspendMessage({ sid: session.sid, uid: session.uid, pid: session.pid }); this.sendCustMessage(custId, msg, { onSuccess: function () { // delete RongIMClient._memoryStore.custStore[custId]; setTimeout(function () { callback.onSuccess(); }); }, onError: function () { setTimeout(function () { callback.onError(); }); } }); }; RongIMClient.prototype.switchToHumanMode = function (custId, callback) { if (!custId || !callback) return; var session = RongIMClient._memoryStore.custStore[custId]; if (!session) return; var msg = new RongIMLib.ChangeModeMessage({ sid: session.sid, uid: session.uid, pid: session.pid }); this.sendCustMessage(custId, msg, callback); }; RongIMClient.prototype.evaluateRebotCustomService = function (custId, isRobotResolved, sugest, callback) { if (!custId || !callback) return; var session = RongIMClient._memoryStore.custStore[custId]; if (!session) return; var msg = new RongIMLib.EvaluateMessage({ sid: session.sid, uid: session.uid, pid: session.pid, isRobotResolved: isRobotResolved, sugest: sugest, type: 0 }); this.sendCustMessage(custId, msg, callback); }; RongIMClient.prototype.evaluateHumanCustomService = function (custId, humanValue, sugest, callback) { if (!custId || !callback) return; var session = RongIMClient._memoryStore.custStore[custId]; if (!session) return; var msg = new RongIMLib.EvaluateMessage({ sid: session.sid, uid: session.uid, pid: session.pid, humanValue: humanValue, sugest: sugest, type: 1 }); this.sendCustMessage(custId, msg, callback); }; RongIMClient.prototype.sendCustMessage = function (custId, msg, callback) { RongIMClient.getInstance().sendMessage(RongIMLib.ConversationType.CUSTOMER_SERVICE, custId, msg, { onSuccess: function (data) { callback.onSuccess(); }, onError: function () { callback.onError(); }, onBefore: function () { } }); }; /** * 获取当前连接的状态。 */ RongIMClient.prototype.getCurrentConnectionStatus = function () { return RongIMClient._dataAccessProvider.getCurrentConnectionStatus(); }; /** * 获取当前使用的连接通道。 */ RongIMClient.prototype.getConnectionChannel = function () { if (RongIMLib.Transportations._TransportType == RongIMLib.Socket.XHR_POLLING) { return RongIMLib.ConnectionChannel.XHR_POLLING; } else if (RongIMLib.Transportations._TransportType == RongIMLib.Socket.WEBSOCKET) { return RongIMLib.ConnectionChannel.WEBSOCKET; } }; /** * 获取当前使用的本地储存提供者。 TODO */ RongIMClient.prototype.getStorageProvider = function () { if (RongIMClient._memoryStore.providerType == 1) { return "ServerDataProvider"; } else { return "OtherDataProvider"; } }; /** * 过滤聊天室消息(拉取最近聊天消息) * @param {string[]} msgFilterNames */ RongIMClient.prototype.setFilterMessages = function (msgFilterNames) { if (Object.prototype.toString.call(msgFilterNames) == "[object Array]") { RongIMClient._memoryStore.filterMessages = msgFilterNames; } }; RongIMClient.prototype.getAgoraDynamicKey = function (engineType, channelName, callback) { RongIMClient._dataAccessProvider.getAgoraDynamicKey(engineType, channelName, callback); }; /** * 获取当前连接用户的 UserId。 */ RongIMClient.prototype.getCurrentUserId = function () { return RongIMLib.Bridge._client.userId; }; /** * 获取服务器时间与本地时间的差值,单位为毫秒。 * 计算公式:差值 = 本地时间毫秒数 - 服务器时间毫秒数 * @param callback 获取的回调,返回差值。 */ RongIMClient.prototype.getDeltaTime = function () { return RongIMClient._dataAccessProvider.getDelaTime(); }; // #region Message RongIMClient.prototype.getMessage = function (messageId, callback) { RongIMClient._dataAccessProvider.getMessage(messageId, RongIMClient.logCallback(callback, "getMessage")); }; RongIMClient.prototype.deleteLocalMessages = function (conversationType, targetId, messageIds, callback) { RongIMClient._dataAccessProvider.removeLocalMessage(conversationType, targetId, messageIds, RongIMClient.logCallback(callback, "deleteLocalMessages")); }; RongIMClient.prototype.updateMessage = function (message, callback) { RongIMClient._dataAccessProvider.updateMessage(message, RongIMClient.logCallback(callback, "updateMessage")); }; RongIMClient.prototype.clearData = function () { return RongIMClient._dataAccessProvider.clearData(); }; RongIMClient.prototype.clearMessages = function (conversationType, targetId, callback) { RongIMClient._dataAccessProvider.clearMessages(conversationType, targetId, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "clearMessages" }); callback.onError(errorCode); }); } }); }; /**TODO 清楚本地存储的未读消息,目前清空内存中的未读消息 * [clearMessagesUnreadStatus 清空指定会话未读消息] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [用户id] * @param {ResultCallback} callback [返回值,参数回调] */ RongIMClient.prototype.clearMessagesUnreadStatus = function (conversationType, targetId, callback) { RongIMClient._dataAccessProvider.updateMessages(conversationType, targetId, "readStatus", null, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "clearMessagesUnreadStatus" }); callback.onError(errorCode); }); } }); }; // deleteRemoteMessages(conversationType: ConversationType, targetId: string, delMsgs: DeleteMessage[], callback: ResultCallback) { // CheckParam.getInstance().check(["number", "string|number", "array", "object"], "deleteRemoteMessages", false, arguments); // if (delMsgs.length == 0) { // var errorCode = ErrorCode.DELETE_MESSAGE_ID_IS_NULL; // RongIMClient.logger({ // code: errorCode, // funcName: "deleteRemoteMessages" // }); // callback.onError(ErrorCode.DELETE_MESSAGE_ID_IS_NULL); // return; // } else if (delMsgs.length > 100) { // delMsgs.length = 100; // } // // 后续增加,去掉注释即可 // callback.onSuccess(true); // // var modules = new RongIMClient.Protobuf.DeleteMsgInput(); // // modules.setType(conversationType); // // modules.setConversationId(targetId); // // modules.setMsgs(delMsgs); // // RongIMClient.bridge.queryMsg(33, MessageUtil.ArrayForm(modules.toArrayBuffer()), Bridge._client.userId, { // // onSuccess: function(info: any) { // // callback.onSuccess(true); // // }, // // onError: function(err: any) { // // callback.onError(err); // // } // // }, "DeleteMsgOutput"); // } /** * [deleteMessages 删除消息记录。] * @param {ConversationType} conversationType [description] * @param {string} targetId [description] * @param {number[]} messageIds [description] * @param {ResultCallback} callback [description] */ RongIMClient.prototype.deleteMessages = function (conversationType, targetId, messages, callback) { RongIMClient._dataAccessProvider.removeMessage(conversationType, targetId, messages, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "deleteMessages" }); callback.onError(errorCode); }); } }); }; RongIMClient.prototype.sendLocalMessage = function (message, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object"], "sendLocalMessage", false, arguments); RongIMClient._dataAccessProvider.updateMessage(message); this.sendMessage(message.conversationType, message.targetId, message.content, RongIMClient.logSendCallback(callback, "sendLocalMessage")); }; RongIMClient.prototype.getPullSetting = function (callback, version) { RongIMClient._dataAccessProvider.getPullSetting(callback, version); }; RongIMClient.prototype.setOfflineMessageDuration = function (duration, callback) { RongIMLib.CheckParam.getInstance().check(["number", "object"], "setOfflineMessageDuration", true, arguments); RongIMClient._dataAccessProvider.setOfflineMessageDuration(duration, callback); }; /** * [sendMessage 发送消息。] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [目标Id] * @param {MessageContent} messageContent [消息类型] * @param {SendMessageCallback} sendCallback [] * @param {ResultCallback} resultCallback [返回值,函数回调] * @param {string} pushContent [] * @param {string} pushData [] */ RongIMClient.prototype.sendMessage = function (conversationType, targetId, messageContent, sendCallback, mentiondMsg, pushText, appData, methodType, params) { RongIMLib.CheckParam.getInstance().check(["number", "string", "object", "object", "undefined|object|null|global|boolean", "undefined|object|null|global|string", "undefined|object|null|global|string", "undefined|object|null|global|number", "undefined|object|null|global|boolean"], "sendMessage", false, arguments); if (!RongIMLib.RongUtil.isString(targetId)) { return sendCallback.onError(RongIMLib.ErrorCode.PARAMETER_ERROR); } RongIMClient._dataAccessProvider.sendMessage(conversationType, targetId, messageContent, RongIMClient.logSendCallback(sendCallback, "sendMessage"), mentiondMsg, pushText, appData, methodType, params); }; RongIMClient.prototype.setConversationStatus = function (type, targetId, statusItem, callback) { RongIMClient._dataAccessProvider.setConversationStatus(type, targetId, statusItem, callback); }; RongIMClient.prototype.sendReceiptResponse = function (conversationType, targetId, sendCallback) { RongIMClient._dataAccessProvider.sendReceiptResponse(conversationType, targetId, RongIMClient.logSendCallback(sendCallback, "sendReceiptResponse")); }; RongIMClient.prototype.sendTypingStatusMessage = function (conversationType, targetId, messageName, sendCallback) { RongIMClient._dataAccessProvider.sendTypingStatusMessage(conversationType, targetId, messageName, RongIMClient.logSendCallback(sendCallback, "sendTypingStatusMessage")); }; /** * [sendStatusMessage description] * @param {MessageContent} messageContent [description] * @param {SendMessageCallback} sendCallback [description] * @param {ResultCallback} resultCallback [description] */ RongIMClient.prototype.sendStatusMessage = function (messageContent, sendCallback, resultCallback) { throw new Error("Not implemented yet"); }; /** * [sendTextMessage 发送TextMessage快捷方式] * @param {string} content [消息内容] * @param {ResultCallback} resultCallback [返回值,参数回调] */ RongIMClient.prototype.sendTextMessage = function (conversationType, targetId, content, sendMessageCallback) { RongIMClient._dataAccessProvider.sendTextMessage(conversationType, targetId, content, RongIMClient.logSendCallback(sendMessageCallback, "sendTextMessage")); }; RongIMClient.prototype.sendRecallMessage = function (content, sendMessageCallback, params) { var callback = RongIMClient.logSendCallback(sendMessageCallback, "sendRecallMessage"); var senderUserId = content.senderUserId; var userId = RongIMLib.Bridge._client.userId; var isOther = (senderUserId != userId); if (isOther) { var callback = RongIMClient.logSendCallback(sendMessageCallback, "sendRecallMessage"); callback.onError(RongIMLib.ErrorCode.RECALL_MESSAGE, content); return; } RongIMClient._dataAccessProvider.sendRecallMessage(content, callback, params); }; /** * [insertMessage 向本地插入一条消息,不发送到服务器。] * @param {ConversationType} conversationType [description] * @param {string} targetId [description] * @param {string} senderUserId [description] * @param {MessageContent} content [description] * @param {ResultCallback} callback [description] */ RongIMClient.prototype.insertMessage = function (conversationType, targetId, content, callback) { RongIMClient._dataAccessProvider.addMessage(conversationType, targetId, content, RongIMClient.logCallback(callback, "insertMessage")); }; RongIMClient.prototype.setMessageContent = function (messageId, content, objectName) { RongIMClient._dataAccessProvider.setMessageContent(messageId, content, objectName); }; ; RongIMClient.prototype.setMessageSearchField = function (messageId, content, searchFiles) { RongIMClient._dataAccessProvider.setMessageSearchField(messageId, content, searchFiles); }; ; /** * [getHistoryMessages 拉取历史消息记录。] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [用户Id] * @param {number|null} pullMessageTime [拉取历史消息起始位置(格式为毫秒数),可以为null] * @param {number} count [历史消息数量] * @param {ResultCallback} callback [回调函数] * @param {string} objectName [objectName] */ RongIMClient.prototype.getHistoryMessages = function (conversationType, targetId, timestamp, count, callback, objectname, order) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "number|null|global|object", "number", "object", "undefined|object|null|global|string", "number|null|global|object"], "getHistoryMessages", false, arguments); if (count > 20) { throw new Error("HistroyMessage count must be less than or equal to 20!"); } if (conversationType.valueOf() < 0) { throw new Error("ConversationType must be greater than -1"); } RongIMClient._dataAccessProvider.getHistoryMessages(conversationType, targetId, timestamp, count, RongIMClient.logCallback(callback, "getHistoryMessages"), objectname, order); }; /** * [getRemoteHistoryMessages 拉取某个时间戳之前的消息] * @param {ConversationType} conversationType [description] * @param {string} targetId [description] * @param {Date} dateTime [description] * @param {number} count [description] * @param {ResultCallback} callback [description] */ RongIMClient.prototype.getRemoteHistoryMessages = function (conversationType, targetId, timestamp, count, callback, config) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "number|null|global|object", "number", "object", "undefined|null|global|object"], "getRemoteHistoryMessages", false, arguments); var funcName = "getRemoteHistoryMessages"; var log = { errorCode: RongIMLib.ErrorCode.RC_CONN_PROTO_VERSION_ERROR, funcName: "getRemoteHistoryMessages" }; if (count > 20) { RongIMClient.logger(log); callback.onError(RongIMLib.ErrorCode.RC_CONN_PROTO_VERSION_ERROR); return; } if (conversationType.valueOf() < 0) { RongIMClient.logger(log); callback.onError(RongIMLib.ErrorCode.RC_CONN_PROTO_VERSION_ERROR); return; } RongIMClient._dataAccessProvider.getRemoteHistoryMessages(conversationType, targetId, timestamp, count, RongIMClient.logCallback(callback, funcName), config); }; RongIMClient.prototype.clearHistoryMessages = function (params, callback) { RongIMClient._dataAccessProvider.clearHistoryMessages(params, callback); }; RongIMClient.prototype.clearRemoteHistoryMessages = function (params, callback) { RongIMClient._dataAccessProvider.clearRemoteHistoryMessages(params, RongIMClient.logCallback(callback, "clearRemoteHistoryMessages")); }; RongIMClient.prototype.deleteRemoteMessages = function (conversationType, targetId, messages, callback) { RongIMClient._dataAccessProvider.deleteRemoteMessages(conversationType, targetId, messages, RongIMClient.logCallback(callback, "deleteRemoteMessages")); }; /** * [hasRemoteUnreadMessages 是否有未接收的消息,jsonp方法] * @param {string} appkey [appkey] * @param {string} token [token] * @param {ConnectCallback} callback [返回值,参数回调] */ RongIMClient.prototype.hasRemoteUnreadMessages = function (token, callback) { RongIMClient._dataAccessProvider.hasRemoteUnreadMessages(token, RongIMClient.logCallback(callback, "hasRemoteUnreadMessages")); }; RongIMClient.prototype.getTotalUnreadCount = function (callback, conversationTypes) { return RongIMClient._dataAccessProvider.getTotalUnreadCount({ onSuccess: function (count) { setTimeout(function () { callback.onSuccess(count); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "getTotalUnreadCount" }); callback.onError(errorCode); }); } }, conversationTypes); }; /** * [getConversationUnreadCount 指定多种会话类型获取未读消息数] * @param {ResultCallback} callback [返回值,参数回调。] * @param {ConversationType[]} ...conversationTypes [会话类型。] */ RongIMClient.prototype.getConversationUnreadCount = function (conversationTypes, callback) { RongIMClient._dataAccessProvider.getConversationUnreadCount(conversationTypes, { onSuccess: function (count) { setTimeout(function () { callback.onSuccess(count); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "getConversationUnreadCount" }); callback.onError(errorCode); }); } }); }; /** * [getUnreadCount 指定用户、会话类型的未读消息总数。] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [用户Id] */ RongIMClient.prototype.getUnreadCount = function (conversationType, targetId, callback) { RongIMClient._dataAccessProvider.getUnreadCount(conversationType, targetId, { onSuccess: function (count) { setTimeout(function () { callback.onSuccess(count); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "getUnreadCount" }); callback.onError(errorCode); }); } }); }; RongIMClient.prototype.setUnreadCount = function (conversationType, targetId, count) { RongIMLib.CheckParam.getInstance().check(["number", "string", "number"], "setUnreadCount", false, arguments); RongIMClient._dataAccessProvider.setUnreadCount(conversationType, targetId, count); }; RongIMClient.prototype.clearUnreadCountByTimestamp = function (conversationType, targetId, timestamp, callback) { RongIMClient._dataAccessProvider.clearUnreadCountByTimestamp(conversationType, targetId, timestamp, RongIMClient.logCallback(callback, "clearUnreadCountByTimestamp")); }; /** * 清楚会话未读消息数 * @param {ConversationType} conversationType 会话类型 * @param {string} targetId 目标Id * @param {ResultCallback} callback 返回值,函数回调 */ RongIMClient.prototype.clearUnreadCount = function (conversationType, targetId, callback) { RongIMClient._dataAccessProvider.clearUnreadCount(conversationType, targetId, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "clearUnreadCount" }); callback.onError(errorCode); }); } }); }; RongIMClient.prototype.clearTotalUnreadCount = function (callback) { RongIMClient._dataAccessProvider.clearTotalUnreadCount({ onSuccess: function (bool) { callback.onSuccess(bool); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: 'clearTotalUnreadCount' }); callback.onError(errorCode); }); } }); }; RongIMClient.prototype.clearLocalStorage = function (callback) { RongIMClient._storageProvider.clearItem(); callback(); }; RongIMClient.prototype.setMessageExtra = function (messageId, value, callback) { RongIMClient._dataAccessProvider.setMessageExtra(messageId, value, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "setMessageExtra" }); callback.onError(errorCode); }); } }); }; RongIMClient.prototype.setMessageReceivedStatus = function (messageUId, receivedStatus, callback) { RongIMClient._dataAccessProvider.setMessageReceivedStatus(messageUId, receivedStatus, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "setMessageReceivedStatus" }); callback.onError(errorCode); }); } }); }; RongIMClient.prototype.setMessageStatus = function (conersationType, targetId, timestamp, status, callback) { RongIMClient._dataAccessProvider.setMessageStatus(conersationType, targetId, timestamp, status, RongIMClient.logCallback(callback, "setMessageStatus")); }; RongIMClient.prototype.setMessageSentStatus = function (messageId, sentStatus, callback) { RongIMClient._dataAccessProvider.setMessageSentStatus(messageId, sentStatus, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "setMessageSentStatus" }); callback.onError(errorCode); }); } }); }; // #endregion Message // #region TextMessage Draft /** * clearTextMessageDraft 清除指定会话和消息类型的草稿。 * @param {ConversationType} conversationType 会话类型 * @param {string} targetId 目标Id */ RongIMClient.prototype.clearTextMessageDraft = function (conversationType, targetId) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "clearTextMessageDraft", false, arguments); var key = "darf_" + conversationType + "_" + targetId; delete RongIMClient._memoryStore[key]; return true; }; /** * [getTextMessageDraft 获取指定消息和会话的草稿。] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [目标Id] */ RongIMClient.prototype.getTextMessageDraft = function (conversationType, targetId) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "getTextMessageDraft", false, arguments); if (targetId == "" || conversationType < 0) { throw new Error("params error : " + RongIMLib.ErrorCode.DRAF_GET_ERROR); } var key = "darf_" + conversationType + "_" + targetId; return RongIMClient._memoryStore[key]; }; /** * [saveTextMessageDraft description] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [目标Id] * @param {string} value [草稿值] */ RongIMClient.prototype.saveTextMessageDraft = function (conversationType, targetId, value) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "string", "object"], "saveTextMessageDraft", false, arguments); var key = "darf_" + conversationType + "_" + targetId; RongIMClient._memoryStore[key] = value; return true; }; // #endregion TextMessage Draft // #region Conversation RongIMClient.prototype.searchConversationByContent = function (keyword, callback, conversationTypes) { RongIMClient._dataAccessProvider.searchConversationByContent(keyword, RongIMClient.logCallback(callback, "searchConversationByContent"), conversationTypes); }; RongIMClient.prototype.searchMessageByContent = function (conversationType, targetId, keyword, timestamp, count, total, callback) { RongIMClient._dataAccessProvider.searchMessageByContent(conversationType, targetId, keyword, timestamp, count, total, RongIMClient.logCallback(callback, "searchMessageByContent")); }; RongIMClient.prototype.clearCache = function () { RongIMClient._dataAccessProvider.clearCache(); }; RongIMClient.prototype.clearConversations = function (callback) { var conversationTypes = []; for (var _i = 1; _i < arguments.length; _i++) { conversationTypes[_i - 1] = arguments[_i]; } if (conversationTypes.length == 0) { conversationTypes = [RongIMLib.ConversationType.CHATROOM, RongIMLib.ConversationType.CUSTOMER_SERVICE, RongIMLib.ConversationType.DISCUSSION, RongIMLib.ConversationType.GROUP, RongIMLib.ConversationType.PRIVATE, RongIMLib.ConversationType.SYSTEM, RongIMLib.ConversationType.PUBLIC_SERVICE, RongIMLib.ConversationType.APP_PUBLIC_SERVICE]; } RongIMClient._dataAccessProvider.clearConversations(conversationTypes, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "clearConversations" }); callback.onError(errorCode); }); } }); }; /** * [getConversation 获取指定会话,此方法需在getConversationList之后执行] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [目标Id] * @param {ResultCallback} callback [返回值,函数回调] */ RongIMClient.prototype.getConversation = function (conversationType, targetId, callback) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "getConversation", false, arguments); RongIMClient._dataAccessProvider.getConversation(conversationType, targetId, { onSuccess: function (conver) { setTimeout(function () { callback.onSuccess(conver); }); }, onError: function (error) { setTimeout(function () { RongIMClient.logger({ code: error, funcName: "getConversation" }); callback.onError(error); }); } }); }; /** * [pottingConversation 组装会话列表] * @param {any} tempConver [临时会话] * conver_conversationType_targetId_no. * msg_conversationType_targetId_no. */ RongIMClient.prototype.pottingConversation = function (tempConver) { var self = this, isUseReplace = false; RongIMClient._dataAccessProvider.getConversation(tempConver.type, tempConver.userId, { onSuccess: function (conver) { if (!conver) { conver = new RongIMLib.Conversation(); } else { isUseReplace = true; } conver.conversationType = tempConver.type; conver.targetId = tempConver.userId; if (tempConver.msg) { conver.latestMessage = RongIMLib.MessageUtil.messageParser(tempConver.msg); conver.latestMessageId = conver.latestMessage.messageId; conver.objectName = conver.latestMessage.objectName; conver.receivedStatus = conver.latestMessage.receivedStatus; conver.receivedTime = conver.latestMessage.receiveTime; conver.sentStatus = conver.latestMessage.sentStatus; conver.sentTime = conver.latestMessage.sentTime; } var mentioneds = RongIMClient._storageProvider.getItem("mentioneds_" + RongIMLib.Bridge._client.userId + '_' + conver.conversationType + '_' + conver.targetId); if (mentioneds) { var info = JSON.parse(mentioneds); conver.mentionedMsg = info[tempConver.type + "_" + tempConver.userId]; } if (!isUseReplace) { if (RongIMLib.RongUtil.supportLocalStorage()) { // var count = RongIMClient._storageProvider.getItem("cu" + Bridge._client.userId + tempConver.type + tempConver.userId); conver.unreadMessageCount = RongIMLib.UnreadCountHandler.get(tempConver.type, tempConver.userId); } else { conver.unreadMessageCount = 0; } } if (conver.conversationType == RongIMLib.ConversationType.DISCUSSION) { self.getDiscussion(tempConver.userId, { onSuccess: function (info) { conver.conversationTitle = info.name; }, onError: function (error) { } }); } var status = RongIMClient._dataAccessProvider.conversationStatusManager.get(tempConver.type, tempConver.userId); conver.notificationStatus = status.notificationStatus; conver.isTop = status.isTop; RongIMClient._dataAccessProvider.addConversation(conver, { onSuccess: function (data) { } }); }, onError: function (error) { } }); }; RongIMClient.prototype.addConversation = function (conversation, callback) { RongIMClient._dataAccessProvider.addConversation(conversation, callback); }; RongIMClient.prototype.sortConversationList = function (conversationList) { var convers = []; for (var i = 0, len = conversationList.length; i < len; i++) { if (!conversationList[i]) { continue; } if (conversationList[i].isTop) { convers.push(conversationList[i]); conversationList.splice(i, 1); continue; } for (var j = 0; j < len - i - 1; j++) { if (conversationList[j].sentTime < conversationList[j + 1].sentTime) { var swap = conversationList[j]; conversationList[j] = conversationList[j + 1]; conversationList[j + 1] = swap; } } } return RongIMClient._memoryStore.conversationList = convers.concat(conversationList); }; RongIMClient.prototype.getConversationList = function (callback, conversationTypes, count, isGetHiddenConvers) { RongIMLib.CheckParam.getInstance().check(["object", "null|undefined|array|object|global", "number|undefined|null|object|global", "boolean|undefined|null|object|global"], "getConversationList", false, arguments); var me = this; RongIMClient._dataAccessProvider.getConversationList({ onSuccess: function (data) { if (conversationTypes || RongIMClient._dataAccessProvider) { setTimeout(function () { callback.onSuccess(data); }); } else { setTimeout(function () { callback.onSuccess(RongIMClient._memoryStore.conversationList); }); } }, onError: function (error) { setTimeout(function () { RongIMClient.logger({ code: error, funcName: "getConversationList" }); callback.onError(error); }); } }, conversationTypes, count, isGetHiddenConvers); }; RongIMClient.prototype.getRemoteConversationList = function (callback, conversationTypes, count, isGetHiddenConvers) { RongIMLib.CheckParam.getInstance().check(["object", "null|array|object|global", "number|undefined|null|object|global", "boolean|undefined|null|object|global"], "getRemoteConversationList", false, arguments); RongIMClient._dataAccessProvider.getRemoteConversationList(RongIMClient.logCallback(callback, "getRemoteConversationList"), conversationTypes, count, isGetHiddenConvers); }; RongIMClient.prototype.updateConversation = function (conversation) { return RongIMClient._dataAccessProvider.updateConversation(conversation); }; /** * [createConversation 创建会话。] * @param {number} conversationType [会话类型] * @param {string} targetId [目标Id] * @param {string} converTitle [会话标题] * @param {boolean} islocal [是否同步到服务器,ture:同步,false:不同步] */ RongIMClient.prototype.createConversation = function (conversationType, targetId, converTitle) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "string"], "createConversation", false, arguments); var conver = new RongIMLib.Conversation(); // var unreadContent: string = RongIMClient._storageProvider.getItem("cu" + Bridge._client.userId + conversationType + targetId); // var unreadCount = Number(unreadContent) || 0; conver.targetId = targetId; conver.conversationType = conversationType; conver.conversationTitle = converTitle; conver.latestMessage = {}; conver.unreadMessageCount = 0; return conver; }; //TODO 删除本地和服务器、删除本地和服务器分开 RongIMClient.prototype.removeConversation = function (conversationType, targetId, callback) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "removeConversation", false, arguments); RongIMClient._dataAccessProvider.removeConversation(conversationType, targetId, RongIMClient.logCallback(callback, "removeConversation")); }; RongIMClient.prototype.setConversationHidden = function (conversationType, targetId, isHidden) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "boolean"], "setConversationHidden", false, arguments); RongIMClient._dataAccessProvider.setConversationHidden(conversationType, targetId, isHidden); }; RongIMClient.prototype.setConversationToTop = function (conversationType, targetId, isTop, callback) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "boolean", "object"], "setConversationToTop", false, arguments); RongIMClient._dataAccessProvider.setConversationToTop(conversationType, targetId, isTop, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "setConversationToTop" }); callback.onError(errorCode); }); } }); }; // #endregion Conversation // #region Notifications /** * [getConversationNotificationStatus 获取指定用户和会话类型免提醒。] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [目标Id] * @param {ResultCallback} callback [返回值,函数回调] */ RongIMClient.prototype.getConversationNotificationStatus = function (conversationType, targetId, callback) { var params = { conversationType: conversationType, targetId: targetId }; RongIMClient._dataAccessProvider.getConversationNotificationStatus(params, RongIMClient.logCallback(callback, "getConversationNotificationStatus")); }; /** * [setConversationNotificationStatus 设置指定用户和会话类型免提醒。] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [目标Id] * @param {ResultCallback} callback [返回值,函数回调] */ RongIMClient.prototype.setConversationNotificationStatus = function (conversationType, targetId, notificationStatus, callback) { var params = { conversationType: conversationType, targetId: targetId, status: status }; RongIMClient._dataAccessProvider.setConversationNotificationStatus(params, RongIMClient.logCallback(callback, "setConversationNotificationStatus")); }; /** * [getNotificationQuietHours 获取免提醒消息时间。] * @param {GetNotificationQuietHoursCallback} callback [返回值,函数回调] */ RongIMClient.prototype.getNotificationQuietHours = function (callback) { throw new Error("Not implemented yet"); }; /** * [removeNotificationQuietHours 移除免提醒消息时间。] * @param {GetNotificationQuietHoursCallback} callback [返回值,函数回调] */ RongIMClient.prototype.removeNotificationQuietHours = function (callback) { throw new Error("Not implemented yet"); }; /** * [setNotificationQuietHours 设置免提醒消息时间。] * @param {GetNotificationQuietHoursCallback} callback [返回值,函数回调] */ RongIMClient.prototype.setNotificationQuietHours = function (startTime, spanMinutes, callback) { throw new Error("Not implemented yet"); }; // #endregion Notifications // #region Discussion /** * [addMemberToDiscussion 加入讨论组] * @param {string} discussionId [讨论组Id] * @param {string[]} userIdList [讨论中成员] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.addMemberToDiscussion = function (discussionId, userIdList, callback) { RongIMLib.CheckParam.getInstance().check(["string", "array", "object"], "addMemberToDiscussion", false, arguments); RongIMClient._dataAccessProvider.addMemberToDiscussion(discussionId, userIdList, RongIMClient.logCallback(callback, "addMemberToDiscussion")); }; /** * [createDiscussion 创建讨论组] * @param {string} name [讨论组名称] * @param {string[]} userIdList [讨论组成员] * @param {CreateDiscussionCallback} callback [返回值,函数回调] */ RongIMClient.prototype.createDiscussion = function (name, userIdList, callback) { RongIMLib.CheckParam.getInstance().check(["string", "array", "object"], "createDiscussion", false, arguments); RongIMClient._dataAccessProvider.createDiscussion(name, userIdList, callback); }; /** * [getDiscussion 获取讨论组信息] * @param {string} discussionId [讨论组Id] * @param {ResultCallback} callback [返回值,函数回调] */ RongIMClient.prototype.getDiscussion = function (discussionId, callback) { RongIMLib.CheckParam.getInstance().check(["string", "object"], "getDiscussion", false, arguments); RongIMClient._dataAccessProvider.getDiscussion(discussionId, RongIMClient.logCallback(callback, "getDiscussion")); }; /** * [quitDiscussion 退出讨论组] * @param {string} discussionId [讨论组Id] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.quitDiscussion = function (discussionId, callback) { RongIMLib.CheckParam.getInstance().check(["string", "object"], "quitDiscussion", false, arguments); RongIMClient._dataAccessProvider.quitDiscussion(discussionId, RongIMClient.logCallback(callback, "quitDiscussion")); }; /** * [removeMemberFromDiscussion 将指定成员移除讨论租] * @param {string} discussionId [讨论组Id] * @param {string} userId [被移除的用户Id] * @param {OperationCallback} callback [返回值,参数回调] */ RongIMClient.prototype.removeMemberFromDiscussion = function (discussionId, userId, callback) { RongIMLib.CheckParam.getInstance().check(["string", "string", "object"], "removeMemberFromDiscussion", false, arguments); RongIMClient._dataAccessProvider.removeMemberFromDiscussion(discussionId, userId, RongIMClient.logCallback(callback, "removeMemberFromDiscussion")); }; /** * [setDiscussionInviteStatus 设置讨论组邀请状态] * @param {string} discussionId [讨论组Id] * @param {DiscussionInviteStatus} status [邀请状态] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.setDiscussionInviteStatus = function (discussionId, status, callback) { RongIMLib.CheckParam.getInstance().check(["string", "number", "object"], "setDiscussionInviteStatus", false, arguments); RongIMClient._dataAccessProvider.setDiscussionInviteStatus(discussionId, status, RongIMClient.logCallback(callback, "setDiscussionInviteStatus")); }; /** * [setDiscussionName 设置讨论组名称] * @param {string} discussionId [讨论组Id] * @param {string} name [讨论组名称] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.setDiscussionName = function (discussionId, name, callback) { RongIMLib.CheckParam.getInstance().check(["string", "string", "object"], "setDiscussionName", false, arguments); RongIMClient._dataAccessProvider.setDiscussionName(discussionId, name, RongIMClient.logCallback(callback, "setDiscussionName")); }; // #endregion Discussion // #region ChatRoom /** * [加入聊天室。] * @param {string} chatroomId [聊天室Id] * @param {number} messageCount [拉取消息数量,-1为不拉去消息] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.joinChatRoom = function (chatroomId, messageCount, callback) { RongIMLib.CheckParam.getInstance().check(["string", "number", "object"], "joinChatRoom", false, arguments); if (chatroomId == "") { setTimeout(function () { var errorCode = RongIMLib.ErrorCode.CHATROOM_ID_ISNULL; RongIMClient.logger({ code: errorCode, funcName: "joinChatRoom" }); callback.onError(RongIMLib.ErrorCode.CHATROOM_ID_ISNULL); }); return; } RongIMClient._dataAccessProvider.joinChatRoom(chatroomId, messageCount, RongIMClient.logCallback(callback, "joinChatRoom")); }; RongIMClient.prototype.setDeviceInfo = function (device) { RongIMClient._dataAccessProvider.setDeviceInfo(device); }; RongIMClient.prototype.setChatroomHisMessageTimestamp = function (chatRoomId, timestamp) { RongIMLib.CheckParam.getInstance().check(["string", "number"], "setChatroomHisMessageTimestamp", false, arguments); RongIMClient._dataAccessProvider.setChatroomHisMessageTimestamp(chatRoomId, timestamp); }; RongIMClient.prototype.getChatRoomHistoryMessages = function (chatRoomId, count, order, callback) { RongIMLib.CheckParam.getInstance().check(["string", "number", "number", "object"], "getChatRoomHistoryMessages", false, arguments); RongIMClient._dataAccessProvider.getChatRoomHistoryMessages(chatRoomId, count, order, RongIMClient.logCallback(callback, "getChatRoomHistoryMessages")); }; RongIMClient.prototype.getChatRoomInfo = function (chatRoomId, count, order, callback) { RongIMLib.CheckParam.getInstance().check(["string", "number", "number", "object"], "getChatRoomInfo", false, arguments); RongIMClient._dataAccessProvider.getChatRoomInfo(chatRoomId, count, order, RongIMClient.logCallback(callback, "getChatRoomInfo")); }; /** * [退出聊天室] * @param {string} chatroomId [聊天室Id] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.quitChatRoom = function (chatroomId, callback) { RongIMLib.CheckParam.getInstance().check(["string", "object"], "quitChatRoom", false, arguments); RongIMClient._dataAccessProvider.quitChatRoom(chatroomId, RongIMClient.logCallback(callback, "quitChatRoom")); }; RongIMClient.prototype.setChatroomEntry = function (chatroomId, chatroomEntry, callback) { RongIMLib.CheckParam.getInstance().check(['string', 'object', 'object'], 'setChatroomEntry', false, arguments); RongIMClient._dataAccessProvider.setChatroomEntry(chatroomId, chatroomEntry, RongIMClient.logCallback(callback, "setChatroomEntry")); }; RongIMClient.prototype.forceSetChatroomEntry = function (chatroomId, chatroomEntry, callback) { RongIMLib.CheckParam.getInstance().check(['string', 'object', 'object'], 'setChatroomEntry', false, arguments); RongIMClient._dataAccessProvider.forceSetChatroomEntry(chatroomId, chatroomEntry, RongIMClient.logCallback(callback, "setChatroomEntry")); }; RongIMClient.prototype.getChatroomEntry = function (chatroomId, key, callback) { RongIMLib.CheckParam.getInstance().check(['string', 'string', 'object'], 'getChatroomEntry', false, arguments); RongIMClient._dataAccessProvider.getChatroomEntry(chatroomId, key, RongIMClient.logCallback(callback, "setChatroomEntry")); }; RongIMClient.prototype.getAllChatroomEntries = function (chatroomId, callback) { RongIMLib.CheckParam.getInstance().check(['string', 'object'], 'getAllChatroomEntries', false, arguments); RongIMClient._dataAccessProvider.getAllChatroomEntries(chatroomId, RongIMClient.logCallback(callback, "setChatroomEntry")); }; RongIMClient.prototype.removeChatroomEntry = function (chatroomId, chatroomEntry, callback) { RongIMLib.CheckParam.getInstance().check(['string', 'object', 'object'], 'removeChatroomEntry', false, arguments); RongIMClient._dataAccessProvider.removeChatroomEntry(chatroomId, chatroomEntry, RongIMClient.logCallback(callback, "setChatroomEntry")); }; RongIMClient.prototype.forceRemoveChatroomEntry = function (chatroomId, chatroomEntry, callback) { RongIMLib.CheckParam.getInstance().check(['string', 'object', 'object'], 'removeChatroomEntry', false, arguments); RongIMClient._dataAccessProvider.forceRemoveChatroomEntry(chatroomId, chatroomEntry, RongIMClient.logCallback(callback, "setChatroomEntry")); }; // #endregion ChatRoom // #region Public Service RongIMClient.prototype.getRemotePublicServiceList = function (callback, pullMessageTime) { RongIMClient._dataAccessProvider.getRemotePublicServiceList(RongIMClient.logCallback(callback, "getRemotePublicServiceList"), pullMessageTime); }; /** * [getPublicServiceList ]获取本地的公共账号列表 * @param {ResultCallback} callback [返回值,参数回调] */ RongIMClient.prototype.getPublicServiceList = function (callback) { if (RongIMClient._memoryStore.depend.openMp) { RongIMLib.CheckParam.getInstance().check(["object"], "getPublicServiceList", false, arguments); this.getRemotePublicServiceList(RongIMClient.logCallback(callback, "getPublicServiceList")); } }; /** * [getPublicServiceProfile ] 获取某公共服务信息。 * @param {PublicServiceType} publicServiceType [公众服务类型。] * @param {string} publicServiceId [公共服务 Id。] * @param {ResultCallback} callback [公共账号信息回调。] */ RongIMClient.prototype.getPublicServiceProfile = function (publicServiceType, publicServiceId, callback) { if (RongIMClient._memoryStore.depend.openMp) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "getPublicServiceProfile", false, arguments); RongIMClient._dataAccessProvider.getPublicServiceProfile(publicServiceType, publicServiceId, RongIMClient.logCallback(callback, "getPublicServiceProfile")); } }; /** * [pottingPublicSearchType ] 公众好查询类型 * @param {number} bussinessType [ 0-all 1-mp 2-mc] * @param {number} searchType [0-exact 1-fuzzy] */ RongIMClient.prototype.pottingPublicSearchType = function (bussinessType, searchType) { if (RongIMClient._memoryStore.depend.openMp) { var bits = 0; if (bussinessType == 0) { bits |= 3; if (searchType == 0) { bits |= 12; } else { bits |= 48; } } else if (bussinessType == 1) { bits |= 1; if (searchType == 0) { bits |= 8; } else { bits |= 32; } } else { bits |= 2; if (bussinessType == 0) { bits |= 4; } else { bits |= 16; } } return bits; } }; /** * [searchPublicService ]按公众服务类型搜索公众服务。 * @param {SearchType} searchType [搜索类型枚举。] * @param {string} keywords [搜索关键字。] * @param {ResultCallback} callback [搜索结果回调。] */ RongIMClient.prototype.searchPublicService = function (searchType, keywords, callback) { if (RongIMClient._memoryStore.depend.openMp) { RongIMLib.CheckParam.getInstance().check(["number", "string", "object"], "searchPublicService", false, arguments); var modules = new RongIMClient.Protobuf.SearchMpInput(); modules.setType(this.pottingPublicSearchType(0, searchType)); modules.setId(keywords); RongIMClient.bridge.queryMsg(29, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, RongIMClient.logCallback(callback, "searchPublicService"), "SearchMpOutput"); } }; /** * [searchPublicServiceByType ]按公众服务类型搜索公众服务。 * @param {PublicServiceType} publicServiceType [公众服务类型。] * @param {SearchType} searchType [搜索类型枚举。] * @param {string} keywords [搜索关键字。] * @param {ResultCallback} callback [搜索结果回调。] */ RongIMClient.prototype.searchPublicServiceByType = function (publicServiceType, searchType, keywords, callback) { if (RongIMClient._memoryStore.depend.openMp) { RongIMLib.CheckParam.getInstance().check(["number", "number", "string", "object"], "searchPublicServiceByType", false, arguments); var type = publicServiceType == RongIMLib.ConversationType.APP_PUBLIC_SERVICE ? 2 : 1; var modules = new RongIMClient.Protobuf.SearchMpInput(); modules.setType(this.pottingPublicSearchType(type, searchType)); modules.setId(keywords); RongIMClient.bridge.queryMsg(29, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, RongIMClient.logCallback(callback, "searchPublicServiceByType"), "SearchMpOutput"); } }; /** * [subscribePublicService ] 订阅公众号。 * @param {PublicServiceType} publicServiceType [公众服务类型。] * @param {string} publicServiceId [公共服务 Id。] * @param {OperationCallback} callback [订阅公众号回调。] */ RongIMClient.prototype.subscribePublicService = function (publicServiceType, publicServiceId, callback) { if (RongIMClient._memoryStore.depend.openMp) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "subscribePublicService", false, arguments); var modules = new RongIMClient.Protobuf.MPFollowInput(), me = this, follow = publicServiceType == RongIMLib.ConversationType.APP_PUBLIC_SERVICE ? "mcFollow" : "mpFollow"; modules.setId(publicServiceId); RongIMClient.bridge.queryMsg(follow, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function () { me.getRemotePublicServiceList({ onSuccess: function () { }, onError: function () { } }); callback.onSuccess(); }, onError: function (code) { var errorCode = code; RongIMClient.logger({ code: errorCode, funcName: "subscribePublicService" }); callback.onError(code); } }, "MPFollowOutput"); } }; /** * [unsubscribePublicService ] 取消订阅公众号。 * @param {PublicServiceType} publicServiceType [公众服务类型。] * @param {string} publicServiceId [公共服务 Id。] * @param {OperationCallback} callback [取消订阅公众号回调。] */ RongIMClient.prototype.unsubscribePublicService = function (publicServiceType, publicServiceId, callback) { if (RongIMClient._memoryStore.depend.openMp) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "unsubscribePublicService", false, arguments); var modules = new RongIMClient.Protobuf.MPFollowInput(), me = this, follow = publicServiceType == RongIMLib.ConversationType.APP_PUBLIC_SERVICE ? "mcUnFollow" : "mpUnFollow"; modules.setId(publicServiceId); RongIMClient.bridge.queryMsg(follow, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function () { RongIMClient._memoryStore.publicServiceMap.remove(publicServiceType, publicServiceId); callback.onSuccess(); }, onError: function (code) { var errorCode = code; RongIMClient.logger({ code: errorCode, funcName: "unsubscribePublicService" }); callback.onError(code); } }, "MPFollowOutput"); } }; // #endregion Public Service // #region Blacklist /** * [加入黑名单] * @param {string} userId [将被加入黑名单的用户Id] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.addToBlacklist = function (userId, callback) { RongIMLib.CheckParam.getInstance().check(["string|number", "object"], "addToBlacklist", false, arguments); RongIMClient._dataAccessProvider.addToBlacklist(userId, RongIMClient.logCallback(callback, "addToBlacklist")); }; /** * [获取黑名单列表] * @param {GetBlacklistCallback} callback [返回值,函数回调] */ RongIMClient.prototype.getBlacklist = function (callback) { RongIMLib.CheckParam.getInstance().check(["object"], "getBlacklist", false, arguments); RongIMClient._dataAccessProvider.getBlacklist(callback); }; /** * [得到指定人员再黑名单中的状态] * @param {string} userId [description] * @param {ResultCallback} callback [返回值,函数回调] */ //TODO 如果人员不在黑名单中,获取状态会出现异常 RongIMClient.prototype.getBlacklistStatus = function (userId, callback) { RongIMLib.CheckParam.getInstance().check(["string|number", "object"], "getBlacklistStatus", false, arguments); RongIMClient._dataAccessProvider.getBlacklistStatus(userId, RongIMClient.logCallback(callback, "getBlacklistStatus")); }; /** * [将指定用户移除黑名单] * @param {string} userId [将被移除的用户Id] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.removeFromBlacklist = function (userId, callback) { RongIMLib.CheckParam.getInstance().check(["string|number", "object"], "removeFromBlacklist", false, arguments); RongIMClient._dataAccessProvider.removeFromBlacklist(userId, RongIMClient.logCallback(callback, "removeFromBlacklist")); }; RongIMClient.prototype.getFileToken = function (fileType, callback, fileName) { RongIMLib.CheckParam.getInstance().check(["number", "object", "undefined|null|string"], "getQngetFileTokenTkn", false, arguments); RongIMClient._dataAccessProvider.getFileToken(fileType, RongIMClient.logCallback(callback, "getFileToken"), fileName); }; RongIMClient.prototype.getFileUrl = function (fileType, fileName, oriName, callback, data) { RongIMLib.CheckParam.getInstance().check(["number", "string", "string|global|object|null", "object", "undefined|null|object"], "getFileUrl", false, arguments); RongIMClient._dataAccessProvider.getFileUrl(fileType, fileName, oriName, RongIMClient.logCallback(callback, "getFileUrl"), data); }; ; // #endregion Blacklist // #region Real-time Location Service RongIMClient.prototype.addRealTimeLocationListener = function (conversationType, targetId, listener) { throw new Error("Not implemented yet"); }; RongIMClient.prototype.getRealTimeLocation = function (conversationType, targetId) { throw new Error("Not implemented yet"); }; RongIMClient.prototype.getRealTimeLocationCurrentState = function (conversationType, targetId) { throw new Error("Not implemented yet"); }; RongIMClient.prototype.getRealTimeLocationParticipants = function (conversationType, targetId) { throw new Error("Not implemented yet"); }; RongIMClient.prototype.joinRealTimeLocation = function (conversationType, targetId) { throw new Error("Not implemented yet"); }; RongIMClient.prototype.quitRealTimeLocation = function (conversationType, targetId) { throw new Error("Not implemented yet"); }; RongIMClient.prototype.startRealTimeLocation = function (conversationType, targetId) { throw new Error("Not implemented yet"); }; RongIMClient.prototype.updateRealTimeLocationStatus = function (conversationType, targetId, latitude, longitude) { throw new Error("Not implemented yet"); }; // #endregion Real-time Location Service // # startVoIP RongIMClient.prototype.startCall = function (converType, targetId, userIds, mediaType, extra, callback) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "array", "number", "string", "object"], "startCall", false, arguments); if (RongIMClient._memoryStore.voipStategy) { RongIMClient._voipProvider.startCall(converType, targetId, userIds, mediaType, extra, RongIMClient.logCallback(callback, "startCall")); } else { var errorCode = RongIMLib.ErrorCode.VOIP_NOT_AVALIABLE; RongIMClient.logger({ code: errorCode, funcName: "startCall" }); callback.onError(RongIMLib.ErrorCode.VOIP_NOT_AVALIABLE); } }; RongIMClient.prototype.joinCall = function (mediaType, callback) { RongIMLib.CheckParam.getInstance().check(['number', 'object'], "joinCall", false, arguments); if (RongIMClient._memoryStore.voipStategy) { RongIMClient._voipProvider.joinCall(mediaType, RongIMClient.logCallback(callback, "joinCall")); } else { var errorCode = RongIMLib.ErrorCode.VOIP_NOT_AVALIABLE; RongIMClient.logger({ code: errorCode, funcName: "joinCall" }); callback.onError(RongIMLib.ErrorCode.VOIP_NOT_AVALIABLE); } }; RongIMClient.prototype.hungupCall = function (converType, targetId, reason) { RongIMLib.CheckParam.getInstance().check(["number", "string", "number"], "hungupCall", false, arguments); if (RongIMClient._memoryStore.voipStategy) { RongIMClient._voipProvider.hungupCall(converType, targetId, reason); } }; RongIMClient.prototype.changeMediaType = function (converType, targetId, mediaType, callback) { RongIMLib.CheckParam.getInstance().check(["number", "string", "number", "object"], "changeMediaType", false, arguments); if (RongIMClient._memoryStore.voipStategy) { RongIMClient._voipProvider.changeMediaType(converType, targetId, mediaType, RongIMClient.logCallback(callback, "changeMediaType")); } else { var errorCode = RongIMLib.ErrorCode.VOIP_NOT_AVALIABLE; RongIMClient.logger({ code: errorCode, funcName: "changeMediaType" }); callback.onError(RongIMLib.ErrorCode.VOIP_NOT_AVALIABLE); } }; // # endVoIP RongIMClient.prototype.getUnreadMentionedMessages = function (conversationType, targetId) { return RongIMClient._dataAccessProvider.getUnreadMentionedMessages(conversationType, targetId); }; RongIMClient.prototype.clearListeners = function () { RongIMClient._dataAccessProvider.clearListeners(); }; // UserStatus start RongIMClient.prototype.getUserStatus = function (userId, callback) { RongIMClient._dataAccessProvider.getUserStatus(userId, RongIMClient.logCallback(callback, "getUserStatus")); }; RongIMClient.prototype.setUserStatus = function (status, callback) { RongIMClient._dataAccessProvider.setUserStatus(status, RongIMClient.logCallback(callback, "setUserStatus")); }; RongIMClient.prototype.setUserStatusListener = function (params, callback) { var userIds = params.userIds; var multiple = params.multiple; RongIMClient.userStatusObserver.watch({ key: userIds, func: callback, multiple: multiple }); RongIMClient._dataAccessProvider.setUserStatusListener(params, callback); }; // UserStaus end // RTC start RongIMClient.messageWatch = function (watcher) { RongIMClient.RTCListener = watcher; }; RongIMClient.messageSignalWatch = function (watcher) { RongIMClient.RTCSignalLisener = watcher; }; /* var data = { key1: 123, key2: 345 }; */ RongIMClient.prototype.getRTCUserInfoList = function (room, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object"], "getRTCUserInfoList", false, arguments); RongIMClient._dataAccessProvider.getRTCUserInfoList(room, callback); }; RongIMClient.prototype.getRTCUserList = function (room, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object"], "getRTCUserList", false, arguments); RongIMClient._dataAccessProvider.getRTCUserList(room, callback); }; RongIMClient.prototype.setRTCUserInfo = function (room, info, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object", "object"], "setRTCUserInfo", false, arguments); RongIMClient._dataAccessProvider.setRTCUserInfo(room, info, callback); }; RongIMClient.prototype.removeRTCUserInfo = function (room, info, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object", "object"], "removeRTCUserInfo", false, arguments); RongIMClient._dataAccessProvider.removeRTCUserInfo(room, info, callback); }; RongIMClient.prototype.getRTCRoomInfo = function (room, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object"], "getRTCRoomInfo", false, arguments); RongIMClient._dataAccessProvider.getRTCRoomInfo(room, callback); }; RongIMClient.prototype.setRTCRoomInfo = function (room, info, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object", "object"], "setRTCRoomInfo", false, arguments); RongIMClient._dataAccessProvider.setRTCRoomInfo(room, info, callback); }; RongIMClient.prototype.removeRTCRoomInfo = function (room, info, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object", "object"], "removeRTCRoomInfo", false, arguments); RongIMClient._dataAccessProvider.removeRTCRoomInfo(room, info, callback); }; RongIMClient.prototype.joinRTCRoom = function (room, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object"], "joinRTCRoom", false, arguments); if (RongIMClient.isJoinedRTCRoom) { return callback.onSuccess(RongIMClient.roomInfo); } RongIMClient._dataAccessProvider.joinRTCRoom(room, { onSuccess: function (result) { RongIMClient.roomInfo = result; RongIMClient.isJoinedRTCRoom = true; callback.onSuccess(result); }, onError: callback.onError }); }; RongIMClient.prototype.quitRTCRoom = function (room, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object"], "quitRTCRoom", false, arguments); RongIMClient.isJoinedRTCRoom = false; RongIMClient._dataAccessProvider.quitRTCRoom(room, { onSuccess: function () { RongIMClient.roomInfo = { users: {}, token: '' }; callback.onSuccess(true); }, onError: callback.onError }); }; RongIMClient.prototype.RTCPing = function (room, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object"], "RTCPing", false, arguments); RongIMClient._dataAccessProvider.RTCPing(room, callback); }; RongIMClient.prototype.setRTCUserData = function (roomId, key, value, isInner, callback, message) { RongIMLib.CheckParam.getInstance().check(["string", "string", "string", "boolean", "object", "global|object|null|undefined"], "setRTCUserData", false, arguments); RongIMClient._dataAccessProvider.setRTCUserData(roomId, key, value, isInner, callback, message); }; RongIMClient.prototype.getRTCUserData = function (roomId, keys, isInner, callback) { RongIMLib.CheckParam.getInstance().check(["string", "array", "boolean", "object", "global|object|null"], "getRTCUserData", false, arguments); RongIMClient._dataAccessProvider.getRTCUserData(roomId, keys, isInner, callback); }; RongIMClient.prototype.removeRTCUserData = function (roomId, keys, isInner, callback, message) { RongIMLib.CheckParam.getInstance().check(["string", "array", "boolean", "object", "global|object|null|undefined"], "removeRTCUserData", false, arguments); RongIMClient._dataAccessProvider.removeRTCUserData(roomId, keys, isInner, callback, message); }; RongIMClient.prototype.setRTCRoomData = function (roomId, key, value, isInner, callback, message) { RongIMLib.CheckParam.getInstance().check(["string", "string", "string", "boolean", "object", "global|object|null|undefined"], "setRTCRoomData", false, arguments); RongIMClient._dataAccessProvider.setRTCRoomData(roomId, key, value, isInner, callback, message); }; RongIMClient.prototype.getRTCRoomData = function (roomId, keys, isInner, callback) { RongIMLib.CheckParam.getInstance().check(["string", "array", "boolean", "object"], "getRTCRoomData", false, arguments); RongIMClient._dataAccessProvider.getRTCRoomData(roomId, keys, isInner, callback); }; RongIMClient.prototype.removeRTCRoomData = function (roomId, keys, isInner, callback, message) { RongIMLib.CheckParam.getInstance().check(["string", "array", "boolean", "object", "global|object|null|undefined"], "removeRTCRoomData", false, arguments); RongIMClient._dataAccessProvider.removeRTCRoomData(roomId, keys, isInner, callback, message); }; RongIMClient.prototype.setRTCOutData = function (roomId, data, type, callback, message) { RongIMClient._dataAccessProvider.setRTCOutData(roomId, data, type, callback, message); }; // 信令 SDK 新增 RongIMClient.prototype.getRTCOutData = function (roomId, userIds, callback) { RongIMClient._dataAccessProvider.getRTCOutData(roomId, userIds, callback); }; RongIMClient.prototype.getNavi = function () { return RongIMClient._dataAccessProvider.getNavi(); }; RongIMClient.prototype.getRTCToken = function (room, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object"], "getRTCToken", false, arguments); return RongIMClient._dataAccessProvider.getRTCToken(room, callback); }; RongIMClient.prototype.setRTCState = function (room, content, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object", "object"], "setRTCState", false, arguments); return RongIMClient._dataAccessProvider.setRTCState(room, content, callback); }; RongIMClient.prototype.getAppInfo = function () { var appKey = RongIMClient._memoryStore.appKey; return { appKey: appKey }; }; RongIMClient.prototype.getSDKInfo = function () { return { version: RongIMClient.sdkver }; }; RongIMClient.HttpProtocol = { http: 'http://', https: 'https://' }; RongIMClient.WsProtocol = { ws: 'ws://', wss: 'wss://' }; RongIMClient.RTCListener = function () { }; RongIMClient.RTCInnerListener = function () { }; RongIMClient.RTCSignalLisener = function () { }; RongIMClient.MaxMessageContentBytes = 131072; // 128kb RongIMClient.NavMarkInToken = '@'; RongIMClient.NavSeparatorInToken = ';'; RongIMClient.NavExpiredTime = 7200000; // 2 小时 RongIMClient.currentServer = ''; RongIMClient.LogFactory = {}; RongIMClient.MessageType = {}; RongIMClient.RegisterMessage = {}; RongIMClient._memoryStore = { isPullFinished: false, syncMsgQueue: [] }; RongIMClient.isNotPullMsg = false; RongIMClient.userStatusObserver = null; RongIMClient.sdkver = '2.5.8.1'; RongIMClient.otherDeviceLoginCount = 0; RongIMClient.serverStore = { index: 0 }; RongIMClient.isFirstConnect = true; RongIMClient.roomInfo = { users: {}, token: '' }; RongIMClient.invalidWsUrls = []; RongIMClient.isJoinedRTCRoom = false; RongIMClient.statusListeners = []; RongIMClient.messageListeners = []; RongIMClient.settingListeners = []; RongIMClient.conversationStatusListeners = []; RongIMClient.userStatusListener = null; return RongIMClient; })(); RongIMLib.RongIMClient = RongIMClient; })(RongIMLib || (RongIMLib = {})); //用于连接通道 var RongIMLib; (function (RongIMLib) { (function (Qos) { Qos[Qos["AT_MOST_ONCE"] = 0] = "AT_MOST_ONCE"; Qos[Qos["AT_LEAST_ONCE"] = 1] = "AT_LEAST_ONCE"; Qos[Qos["EXACTLY_ONCE"] = 2] = "EXACTLY_ONCE"; Qos[Qos["DEFAULT"] = 3] = "DEFAULT"; })(RongIMLib.Qos || (RongIMLib.Qos = {})); var Qos = RongIMLib.Qos; (function (Type) { Type[Type["CONNECT"] = 1] = "CONNECT"; Type[Type["CONNACK"] = 2] = "CONNACK"; Type[Type["PUBLISH"] = 3] = "PUBLISH"; Type[Type["PUBACK"] = 4] = "PUBACK"; Type[Type["QUERY"] = 5] = "QUERY"; Type[Type["QUERYACK"] = 6] = "QUERYACK"; Type[Type["QUERYCON"] = 7] = "QUERYCON"; Type[Type["SUBSCRIBE"] = 8] = "SUBSCRIBE"; Type[Type["SUBACK"] = 9] = "SUBACK"; Type[Type["UNSUBSCRIBE"] = 10] = "UNSUBSCRIBE"; Type[Type["UNSUBACK"] = 11] = "UNSUBACK"; Type[Type["PINGREQ"] = 12] = "PINGREQ"; Type[Type["PINGRESP"] = 13] = "PINGRESP"; Type[Type["DISCONNECT"] = 14] = "DISCONNECT"; })(RongIMLib.Type || (RongIMLib.Type = {})); var Type = RongIMLib.Type; RongIMLib.StatusTopic = (function () { var ConversationType = RongIMLib.ConversationType; var topic = {}; topic[ConversationType.PRIVATE] = 'ppMsgS'; topic[ConversationType.GROUP] = 'pgMsgS'; return topic; })(); var _topic = [ "invtDiz", "crDiz", "qnUrl", "userInf", "dizInf", "userInf", "joinGrp", "quitDiz", "exitGrp", "evctDiz", ["", "ppMsgP", "pdMsgP", "pgMsgP", "chatMsg", "pcMsgP", "", "pmcMsgN", "pmpMsgN", "", "", "", "prMsgS", "prMsgP"], "pdOpen", "rename", "uGcmpr", "qnTkn", "destroyChrm", "createChrm", "exitChrm", "queryChrm", "joinChrm", "pGrps", "addBlack", "rmBlack", "getBlack", "blackStat", "addRelation", "qryRelation", "delRelation", "pullMp", "schMp", "qnTkn", "qnUrl", "qryVoipK", "delMsg", "qryCHMsg", "getUserStatus", "setUserStatus", "subUserStatus", "cleanHisMsg" ]; var Channel = (function () { function Channel(cb, self) { this.connectionStatus = -1; var appId = self.appId; var token = encodeURIComponent(self.token); var sdkVer = self.sdkVer; var apiVer = self.apiVer; this.self = self; this.socket = Socket.getInstance().createServer(); var that = this; var storage = RongIMLib.RongIMClient._storageProvider; var servers = storage.getItem('servers'); servers = JSON.parse(servers) || []; var depend = RongIMLib.RongIMClient._memoryStore.depend; var customCmpUrl = depend.cmpUrl; if (RongIMLib.RongUtil.isValidWsUrl(customCmpUrl)) { servers = [customCmpUrl]; } else { servers = RongIMLib.RongUtil.getValidWsUrlList(servers); } var startConnect = function (host) { var tpl = '{host}/websocket?appId={appId}&token={token}&sdkVer={sdkVer}&apiVer={apiVer}'; that.url = RongIMLib.RongUtil.tplEngine(tpl, { host: host, appId: appId, token: token, sdkVer: sdkVer, apiVer: apiVer }); that.socket.connect(that.url, cb); // 临时兼容 Comet 逻辑,Comet 中用到 var userId = storage.getItem('rong_current_user'); RongIMLib.Navigation.Endpoint = { host: host, userId: userId }; }; var connectMap = { get: function () { // 所有链接计算器,超过 15 秒后认为所有 CMP 地址均不可用 var totalTimer = new RongIMLib.Timer({ timeout: 1 * 1000 * 15 }); var timers = []; var xhrs = []; var isFinished = false; var clearHandler = function () { for (var i = 0; i < timers.length; i++) { var timer = timers[i]; clearTimeout(timer); } for (var i = 0; i < xhrs.length; i++) { var xhr = xhrs[i]; xhr.abort(); } timers.length = 0; xhrs.length = 0; }; var request = function (config, callback) { var url = config.url; var time = config.time; if (isFinished) { return; } var timer = setTimeout(function () { var onSuccess = function () { if (isFinished) { return; } clearHandler(); isFinished = true; totalTimer.pause(); callback(url); RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.L_PING_WS_R, level: RongIMLib.LoggerLevel.I, type: RongIMLib.LoggerType.IM, content: { url: url } }); }; var xhr = RongIMLib.MessageUtil.detectCMP({ url: url, success: onSuccess, fail: function (code) { console.log(code); RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.L_PING_WS_R, level: RongIMLib.LoggerLevel.E, type: RongIMLib.LoggerType.IM, content: { url: url, code: code } }); } }); xhrs.push(xhr); }, time); timers.push(timer); }; var snifferCallback = function (url) { var reg = /(http|https):\/\/([^\/]+)/i; var host = url.match(reg)[2]; RongIMLib.RongIMClient.currentServer = host; startConnect(host); }; var snifferTpl = '{protocol}{server}/ping?r={random}'; for (var i = 0; i < servers.length; i++) { var server = servers[i]; if (server) { server = RongIMLib.RongUtil.tplEngine(snifferTpl, { protocol: depend.protocol, server: server, random: RongIMLib.RongUtil.getTimestamp() }); request({ url: server, time: i * 1000 }, snifferCallback); RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.L_PING_WS_T, level: RongIMLib.LoggerLevel.I, type: RongIMLib.LoggerType.IM, content: { url: server } }); } } totalTimer.resume(function () { RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.L_PING_WS_R, level: RongIMLib.LoggerLevel.F, type: RongIMLib.LoggerType.IM, content: { desc: 'all websocket addresses are unavailable', cmp: servers, ConnectionStatus: RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE, available: false } }); clearHandler(); for (var i = 0; i < servers.length; i++) { RongIMLib.RongIMClient.invalidWsUrls.push(servers[i]); } var storeServers = storage.getItem('servers'); try { storeServers = JSON.parse(storeServers); !RongIMLib.RongUtil.getValidWsUrlList(storeServers).length && RongIMLib.Navigation.clear(); } catch (e) { } that.socket.fire("StatusChanged", RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE); }); }, element: function () { var totalTimer = new RongIMLib.Timer({ timeout: 1 * 1000 * 15 }); var timers = []; var elements = []; var isFinished = false; var clearHandler = function () { for (var i = 0; i < timers.length; i++) { var timer = timers[i]; clearTimeout(timer); } for (var i = 0; i < elements.length; i++) { var el = elements[i]; document.body.removeChild(el); } }; var request = function (config, callback) { var url = config.url; var time = config.time; if (isFinished) { return; } var timer = setTimeout(function () { var el = document.createElement('script'); el.src = url; document.body.appendChild(el); el.onerror = function () { if (isFinished) { return; } clearHandler(); isFinished = true; totalTimer.pause(); var url = el.src; callback(url); }; elements.push(el); }, time); timers.push(timer); }; var snifferCallback = function (url) { var reg = /(http|https):\/\/([^\/]+)/i; var host = url.match(reg)[2]; startConnect(host); }; var snifferTpl = '//{server}/{path}'; for (var i = 0; i < servers.length; i++) { var server = RongIMLib.RongUtil.tplEngine(snifferTpl, { server: servers[i], path: i }); request({ url: server, time: i * 1000 }, snifferCallback); } totalTimer.resume(function () { for (var i = 0; i < servers.length; i++) { RongIMLib.RongIMClient.invalidWsUrls.push(servers[i]); } clearHandler(); that.socket.fire("StatusChanged", RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE); }); } }; var isWSPingJSONP = depend.isWSPingJSONP; var connectType = isWSPingJSONP ? 'element' : 'get'; connectMap[connectType](); //注册状态改变观察者 var StatusEvent = Channel._ConnectionStatusListener; var hasEvent = (typeof StatusEvent == "object"); var me = this; me.socket.on("StatusChanged", function (code) { if (RongIMLib.Bridge && RongIMLib.Bridge._client && RongIMLib.Bridge._client.channel && me !== RongIMLib.Bridge._client.channel) { me.connectionStatus = code; return; } if (!hasEvent) { throw new Error("setConnectStatusListener:Parameter format is incorrect"); } var isNetworkUnavailable = (code == RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE); var isWebSocket = !RongIMLib.RongIMClient._memoryStore.depend.isPolling; if (RongIMLib.RongIMClient.isFirstConnect && isNetworkUnavailable && isWebSocket) { code = RongIMLib.ConnectionStatus.WEBSOCKET_UNAVAILABLE; } if (isNetworkUnavailable) { var storage = RongIMLib.RongIMClient._storageProvider; var servers = storage.getItem('servers'); servers = JSON.parse(servers); var currentServer = RongIMLib.RongIMClient.currentServer; if (currentServer) { var index = RongIMLib.RongUtil.indexOf(servers, currentServer); // 如果 currentServer 是 servers 的最后一个,不再替换位置 if (!RongIMLib.RongUtil.isEqual(index, -1)) { var server = servers.splice(index, 1)[0]; servers.push(server); storage.setItem('servers', JSON.stringify(servers)); } } } me.connectionStatus = code; setTimeout(function () { StatusEvent.onChanged(code); var unReportCodes = [RongIMLib.ConnectionStatus.CONNECTING, RongIMLib.ConnectionStatus.REQUEST_NAVI, RongIMLib.ConnectionStatus.RESPONSE_NAVI]; var isReportCode = RongIMLib.RongUtil.indexOf(unReportCodes, code) === -1; if (isReportCode) { RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.L_NETC_S, level: RongIMLib.LoggerLevel.I, type: RongIMLib.LoggerType.IM, content: { ConnectionStatus: code, available: false } }); } }); var isDisconnected = (code == RongIMLib.ConnectionStatus.DISCONNECTED); if (isDisconnected) { self.clearHeartbeat(); } var isOtherDevice = (code == RongIMLib.ConnectionStatus.KICKED_OFFLINE_BY_OTHER_CLIENT); if (isOtherDevice) { // 累计其他设备登陆次数,超过 5 次后,自动销毁内部对象 // 删除位置:ServerDataProivder.prototype.connect RongIMLib.RongIMClient.otherDeviceLoginCount++; } var isConnected = (code == RongIMLib.ConnectionStatus.CONNECTED); if (isConnected) { RongIMLib.RongIMClient.isFirstConnect = false; } var isWebsocketUnAvailable = (code == RongIMLib.ConnectionStatus.WEBSOCKET_UNAVAILABLE); if (isWebsocketUnAvailable) { if (RongIMLib.RongUtil.getValidWsUrlList(servers).length) { RongIMLib.RongIMClient._storageProvider.setItem("rongSDK", RongIMLib.Transportations._TransportType); RongIMLib.RongIMClient.connect(self.token, RongIMLib.RongIMClient._memoryStore.callback); } else { me.changeConnectType(); RongIMLib.RongIMClient.isFirstConnect = false; RongIMLib.RongIMClient.connect(self.token, RongIMLib.RongIMClient._memoryStore.callback); } } }); //注册message观察者 this.socket.on("message", self.handler.handleMessage); //注册断开连接观察者 this.socket.on("disconnect", function (status) { that.socket.fire("StatusChanged", status ? status : 2); }); } Channel.prototype.changeConnectType = function () { RongIMLib.RongIMClient._memoryStore.depend.isPolling = !RongIMLib.RongIMClient._memoryStore.depend.isPolling; new RongIMLib.FeatureDectector(); }; Channel.prototype.writeAndFlush = function (val) { this.socket.send(val); }; Channel.prototype.reconnect = function (callback) { RongIMLib.MessageIdHandler.clearMessageId(); this.socket = this.socket.reconnect(); if (callback) { this.self.reconnectObj = callback; } }; Channel.prototype.disconnect = function (status) { this.socket.disconnect(status); }; return Channel; })(); RongIMLib.Channel = Channel; var Socket = (function () { function Socket() { this.socket = null; this._events = {}; } Socket.getInstance = function () { return new Socket(); }; Socket.prototype.connect = function (url, cb) { if (this.socket) { if (url) { RongIMLib.RongIMClient._storageProvider.setItem("rongSDK", this.checkTransport()); this.on("connect", cb || new Function); } if (url) { this.currentURL = url; } this.socket.createTransport(url); } return this; }; Socket.prototype.createServer = function () { var transport = this.getTransport(this.checkTransport()); if (transport === null) { throw new Error("the channel was not supported"); } return transport; }; Socket.prototype.getTransport = function (transportType) { if (transportType == Socket.XHR_POLLING) { this.socket = new RongIMLib.PollingTransportation(this); } else if (transportType == Socket.WEBSOCKET) { this.socket = new RongIMLib.SocketTransportation(this); } return this; }; Socket.prototype.send = function (data) { if (this.socket) { if (this.checkTransport() == Socket.WEBSOCKET) { this.socket.send(data); } else { this.socket.send(this._encode(data)); } } }; Socket.prototype.onMessage = function (data) { this.fire("message", data); }; Socket.prototype.disconnect = function (status) { this.socket.disconnect(status); this.fire("disconnect", status); return this; }; Socket.prototype.reconnect = function () { if (this.currentURL && RongIMLib.RongIMClient._storageProvider.getItem("rongSDK")) { return this.connect(this.currentURL, null); } else { throw new Error("reconnect:no have URL"); } }; /** * [checkTransport 返回通道类型] */ Socket.prototype.checkTransport = function () { if (RongIMLib.RongIMClient._memoryStore.depend.isPolling) { RongIMLib.Transportations._TransportType = Socket.XHR_POLLING; } return RongIMLib.Transportations._TransportType; }; Socket.prototype.fire = function (x, args) { if (x in this._events) { for (var i = 0, ii = this._events[x].length; i < ii; i++) { this._events[x][i](args); } } return this; }; Socket.prototype.on = function (x, func) { if (!(typeof func == "function" && x)) { return this; } if (x in this._events) { RongIMLib.MessageUtil.indexOf(this._events, func) == -1 && this._events[x].push(func); } else { this._events[x] = [func]; } return this; }; Socket.prototype.removeEvent = function (x, fn) { if (x in this._events) { for (var a = 0, l = this._events[x].length; a < l; a++) { if (this._events[x][a] == fn) { this._events[x].splice(a, 1); } } } return this; }; Socket.prototype._encode = function (x) { var str = "?messageid=" + x.getMessageId() + "&header=" + x.getHeaderFlag() + "&sessionid=" + RongIMLib.RongIMClient._storageProvider.getItem("sId" + RongIMLib.Navigation.Endpoint.userId); if (!/(PubAckMessage|QueryConMessage)/.test(x._name)) { str += "&topic=" + x.getTopic() + "&targetid=" + (x.getTargetId() || ""); } return { url: str, data: "getData" in x ? x.getData() : "" }; }; //消息通道常量,所有和通道相关判断均用 XHR_POLLING WEBSOCKET两属性 Socket.XHR_POLLING = "xhr-polling"; Socket.WEBSOCKET = "websocket"; return Socket; })(); RongIMLib.Socket = Socket; //连接端消息累 var Client = (function () { function Client(token, appId) { this.timeoutMillis = 6000; this.timeout_ = 0; this.sdkVer = ''; this.apiVer = Math.floor(Math.random() * 1e6); this.channel = null; this.handler = null; this.userId = ""; this.reconnectObj = {}; this.heartbeat = 0; this.pullMsgHearbeat = 0; this.chatroomId = ""; this.SyncTimeQueue = []; this.cacheMessageIds = []; this.token = token; this.appId = appId; this.SyncTimeQueue.state = "complete"; this.sdkVer = RongIMLib.RongIMClient.sdkver; } Client.prototype.resumeTimer = function () { var me = this; this.timeout_ = setTimeout(function () { me.channel.disconnect(RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE); }, this.timeoutMillis); }; Client.prototype.pauseTimer = function () { if (this.timeout_) { clearTimeout(this.timeout_); this.timeout_ = 0; } }; Client.prototype.connect = function (_callback) { //实例消息处理类 this.handler = new MessageHandler(this); //设置连接回调 this.handler.setConnectCallback(_callback); //实例通道类型 var me = this; this.channel = new Channel(function () { RongIMLib.Transportations._TransportType == Socket.WEBSOCKET && me.keepLive(); }, this); //触发状态改变观察者 this.channel.socket.fire("StatusChanged", RongIMLib.ConnectionStatus.CONNECTING); //没有返回地址就手动抛出错误 //_callback.onError(ConnectionState.NOT_AUTHORIZED); }; Client.prototype.checkSocket = function (callback) { var me = this; me.channel.writeAndFlush(new RongIMLib.PingReqMessage()); var count = 0; var checkTimeout = setInterval(function () { if (!RongIMLib.RongIMClient._memoryStore.isFirstPingMsg) { clearInterval(checkTimeout); callback.onSuccess(); } else { if (count > 15) { clearInterval(checkTimeout); callback.onError(); } } count++; }, 100); }; Client.prototype.keepLive = function () { if (this.heartbeat > 0) { clearInterval(this.heartbeat); } var me = this; me.heartbeat = setInterval(function () { me.resumeTimer(); me.channel.writeAndFlush(new RongIMLib.PingReqMessage()); }, 30000); if (me.pullMsgHearbeat > 0) { clearInterval(me.pullMsgHearbeat); } me.pullMsgHearbeat = setInterval(function () { me.syncTime(true, undefined, undefined, false); }, 180000); }; Client.prototype.clearHeartbeat = function () { clearInterval(this.heartbeat); this.heartbeat = 0; this.pauseTimer(); clearInterval(this.pullMsgHearbeat); this.pullMsgHearbeat = 0; }; Client.prototype.publishMessage = function (_topic, _data, _targetId, _callback, _msg, option) { option = option || {}; var isNoAck = option.isNoAck; var hasCallback = !!_callback; var msgId = RongIMLib.MessageIdHandler.messageIdPlus(this.channel.reconnect); if (!msgId) { return; } var msg = new RongIMLib.PublishMessage(_topic, _data, _targetId); msg.setMessageId(msgId); if (isNoAck) { msg.setQos(Qos.AT_LEAST_ONCE); _callback.onSuccess(msg); } else if (hasCallback) { msg.setQos(Qos.AT_LEAST_ONCE); this.handler.putCallback(new RongIMLib.PublishCallback(_callback.onSuccess, _callback.onError), msg.getMessageId(), _msg); } else { msg.setQos(Qos.AT_MOST_ONCE); } this.channel.writeAndFlush(msg); }; Client.prototype.queryMessage = function (_topic, _data, _targetId, _qos, _callback, pbtype) { if (_topic == "userInf") { if (Client.userInfoMapping[_targetId]) { _callback.onSuccess(Client.userInfoMapping[_targetId]); return; } } var msgId = RongIMLib.MessageIdHandler.messageIdPlus(this.channel.reconnect); if (!msgId) { return; } var msg = new RongIMLib.QueryMessage(_topic, _data, _targetId); msg.setMessageId(msgId); msg.setQos(_qos); this.handler.putCallback(new RongIMLib.QueryCallback(_callback.onSuccess, _callback.onError), msg.getMessageId(), pbtype); this.channel.writeAndFlush(msg); }; Client.prototype.invoke = function (isPullMsg, chrmId, offlineMsg) { var time, modules, str, me = this, target, temp = this.SyncTimeQueue.shift(); if (temp == undefined) { return; } this.SyncTimeQueue.state = "pending"; var localSyncTime = RongIMLib.SyncTimeUtil.get(); var sentBoxTime = localSyncTime.sent; var isPullChatroom = temp.type === 2; if (temp.type != 2) { //普通消息 time = localSyncTime.received; modules = new RongIMLib.RongIMClient.Protobuf.SyncRequestMsg(); modules.setIspolling(false); str = "pullMsg"; target = this.userId; modules.setSendBoxSyncTime(sentBoxTime); } else { //聊天室消息 target = temp.chrmId || me.chatroomId; time = RongIMLib.RongIMClient._memoryStore.lastReadTime.get(target + Bridge._client.userId + "CST") || 0; modules = new RongIMLib.RongIMClient.Protobuf.ChrmPullMsg(); modules.setCount(0); str = "chrmPull"; if (!target) { var errorMsg = "syncTime:Received messages of chatroom but was not init"; RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.L_CHRM_PULL_E, level: RongIMLib.LoggerLevel.E, type: RongIMLib.LoggerType.IM, content: { msg: errorMsg } }); throw new Error(errorMsg); } } //判断服务器给的时间是否消息本地存储的时间,小于的话不执行拉取操作,进行一下步队列操作 if (temp.pulltime <= time) { this.SyncTimeQueue.state = "complete"; this.invoke(isPullMsg, target, offlineMsg); return; } if (isPullMsg && 'setIsPullSend' in modules) { modules.setIsPullSend(true); } modules.setSyncTime(time); //发送queryMessage请求 this.queryMessage(str, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), target, Qos.AT_LEAST_ONCE, { onSuccess: function (collection) { var sync = RongIMLib.MessageUtil.int64ToTimestamp(collection.syncTime), symbol = target; //把返回时间戳存入本地,普通消息key为userid,聊天室消息key为userid+'CST';value都为服务器返回的时间戳 var isChrmPull = str == 'chrmPull'; if (isChrmPull) { symbol += Bridge._client.userId + "CST"; RongIMLib.RongIMClient._memoryStore.lastReadTime.set(symbol, sync); } else { var storage = RongIMLib.RongIMClient._storageProvider; if (sync > storage.getItem(symbol)) { storage.setItem(symbol, sync); } } //把拉取到的消息逐条传给消息监听器 var list = collection.list; var isPullFinished = collection.finished; // chrmPull 没有 finished 字段,自动设置为拉取完成 if (isChrmPull) { isPullFinished = true; } // 兼容长轮训 finished 为空的造成丢消息情况 if (typeof isPullFinished == 'undefined') { isPullFinished = true; } RongIMLib.RongIMClient._memoryStore.isPullFinished = isPullFinished; var connectAckTime = RongIMLib.RongIMClient._memoryStore.connectAckTime; var len = list.length; for (var i = 0, count = len; i < len; i++) { count -= 1; var message = list[i]; var sentTime = RongIMLib.MessageUtil.int64ToTimestamp(message.dataTime); var isSender = message.direction == RongIMLib.MessageDirection.SEND; var compareTime = isSender ? sentBoxTime : time; if (sentTime > compareTime || isPullChatroom) { var isSyncMessage = false; var isOffLineMessage = sentTime < connectAckTime; Bridge._client.handler.onReceived(message, undefined, isOffLineMessage, count, isSyncMessage, isPullFinished); } } if (len <= 200 && str == 'pullMsg') { var Conversation = RongIMLib.RongIMClient._dataAccessProvider.Conversation; var conversationList = RongIMLib.RongIMClient._memoryStore.conversationList; Conversation._notify(conversationList); } me.SyncTimeQueue.state = "complete"; me.invoke(isPullMsg, target, offlineMsg); }, onError: function (error) { me.SyncTimeQueue.state = "complete"; me.invoke(isPullMsg, target, offlineMsg); RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.L_QUERY_MSG_E, level: RongIMLib.LoggerLevel.E, type: RongIMLib.LoggerType.IM, content: { action: 'invoke -> queryMessage', error: error } }); } }, "DownStreamMessages"); }; Client.prototype.syncTime = function (_type, pullTime, chrmId, offlineMsg) { this.SyncTimeQueue.push({ type: _type, pulltime: pullTime, chrmId: chrmId }); //如果队列中只有一个成员并且状态已经完成就执行invoke方法 if (this.SyncTimeQueue.length == 1 && this.SyncTimeQueue.state == "complete") { this.invoke(!_type, chrmId, offlineMsg); } }; Client.prototype.__init = function (f) { this.handler = new MessageHandler(this); //设置连接回调 this.handler.setConnectCallback(RongIMLib.RongIMClient._memoryStore.callback); this.channel = new Channel(f, this); }; Client.userInfoMapping = {}; return Client; })(); RongIMLib.Client = Client; //连接类,实现imclient与connect_client的连接 var Bridge = (function () { function Bridge() { } Bridge.getInstance = function () { return new Bridge(); }; //连接服务器 Bridge.prototype.connect = function (appKey, token, callback) { if (!RongIMLib.RongIMClient.Protobuf) { return; } Bridge._client = new RongIMLib.Navigation().connect(appKey, token, callback); return Bridge._client; }; Bridge.prototype.setListener = function () { Channel._ConnectionStatusListener = { onChanged: function (status) { RongIMLib.RongUtil.forEach(RongIMLib.RongIMClient.statusListeners, function (watch) { RongIMLib.RongUtil.isFunction(watch) && watch(status); }); if (status == RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE) { RongIMLib.RongIMClient._memoryStore.networkUnavailable = true; } } }; Channel._ReceiveMessageListener = { onReceived: function (msg, count, hasMore) { RongIMLib.RongUtil.forEach(RongIMLib.RongIMClient.messageListeners, function (watch) { RongIMLib.RongUtil.isFunction(watch) && watch(msg, count, hasMore); }); } }; }; Bridge.prototype.reconnect = function (callabck) { Bridge._client.channel.reconnect(callabck); }; Bridge.prototype.disconnect = function () { Bridge._client.channel.disconnect(2); }; //执行queryMessage请求 Bridge.prototype.queryMsg = function (topic, content, targetId, callback, pbname) { if (typeof topic != "string") { topic = _topic[topic]; } Bridge._client.queryMessage(topic, content, targetId, Qos.AT_MOST_ONCE, callback, pbname); }; //发送消息 执行publishMessage 请求 Bridge.prototype.pubMsg = function (topic, content, targetId, callback, msg, methodType, params) { params = params || {}; if (typeof methodType == 'number') { if (methodType == RongIMLib.MethodType.CUSTOMER_SERVICE) { Bridge._client.publishMessage("pcuMsgP", content, targetId, callback, msg); } else if (methodType == RongIMLib.MethodType.RECALL) { Bridge._client.publishMessage("recallMsg", content, targetId, callback, msg); } } else { var isStatusMessage = params.isStatus; var statusTopic = RongIMLib.StatusTopic[topic]; if (isStatusMessage && statusTopic) { Bridge._client.publishMessage(statusTopic, content, targetId, callback, msg, { isNoAck: true }); } else { Bridge._client.publishMessage(_topic[10][topic], content, targetId, callback, msg); // 非状态消息, 逻辑不变 } } }; return Bridge; })(); RongIMLib.Bridge = Bridge; var MessageHandler = (function () { function MessageHandler(client) { this.map = {}; this.connectCallback = null; if (!Channel._ReceiveMessageListener) { throw new Error("please set onReceiveMessageListener"); } this._onReceived = Channel._ReceiveMessageListener.onReceived; this._client = client; this.syncMsgMap = new Object; } //把对象推入回调对象队列中,并启动定时器 MessageHandler.prototype.putCallback = function (callbackObj, _publishMessageId, _msg) { var item = { Callback: callbackObj, Message: _msg }; item.Callback.resumeTimer(); this.map[_publishMessageId] = item; }; //设置连接回调对象,启动定时器 MessageHandler.prototype.setConnectCallback = function (_connectCallback) { if (_connectCallback) { this.connectCallback = new RongIMLib.ConnectAck(_connectCallback.onSuccess, _connectCallback.onError, this._client); } }; MessageHandler.prototype.handleChrmKVPullMsg = function (msg) { try { var pbtype = 'NotifyMsg'; var data = RongIMLib.CallbackMapping.getInstance().mapping(RongIMLib.RongIMClient.Protobuf[pbtype].decode(msg.data), pbtype); var timestamp = RongIMLib.MessageUtil.int64ToTimestamp(data.time); if (data.type === 2) { RongIMLib.ChrmKVHandler.pull(data.chrmId, timestamp); } else if (data.type === 3) { RongIMLib.RongIMClient._dataAccessProvider.conversationStatusManager.pull({ time: timestamp }); } } catch (e) { } }; MessageHandler.prototype.onReceived = function (msg, pubAckItem, offlineMsg, leftCount, isSync) { if (!msg) { return; } //实体对象 var entity, //解析完成的消息对象 message, //会话对象 con, // 是否为直发消息 isStraightMsg = false; if (msg._name != "PublishMessage") { entity = msg; RongIMLib.RongIMClient._storageProvider.setItem(this._client.userId, RongIMLib.MessageUtil.int64ToTimestamp(entity.dataTime)); } else { if (msg.getTopic() == "s_ntf") { entity = RongIMLib.RongIMClient.Protobuf.NotifyMsg.decode(msg.getData()); this._client.syncTime(entity.type, RongIMLib.MessageUtil.int64ToTimestamp(entity.time), entity.chrmId); return; } else if (msg.getTopic() == "s_msg") { isStraightMsg = true; entity = RongIMLib.RongIMClient.Protobuf.DownStreamMessage.decode(msg.getData()); var timestamp = RongIMLib.MessageUtil.int64ToTimestamp(entity.dataTime); RongIMLib.RongIMClient._storageProvider.setItem(this._client.userId, timestamp); RongIMLib.RongIMClient._memoryStore.lastReadTime.get(this._client.userId, timestamp); } else if (msg.getTopic() == "s_stat") { entity = RongIMLib.RongIMClient.Protobuf.GetUserStatusOutput.decode(msg.getData()); entity = RongIMLib.RongInnerTools.convertUserStatus(entity); RongIMLib.RongIMClient.userStatusObserver.notify({ key: entity.userId, entity: entity }); return; } else if (msg.getTopic() === 's_cmd') { this.handleChrmKVPullMsg(msg); return; } else { if (Bridge._client.sdkVer && Bridge._client.sdkVer == "1.0.0") { return; } try { entity = RongIMLib.RongIMClient.Protobuf.UpStreamMessage.decode(msg.getData()); } catch (e) { RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.L_DECODE_MSG_E, level: RongIMLib.LoggerLevel.E, type: RongIMLib.LoggerType.IM, content: { stack: e, msg: 'MessageHandler -> onReceived' } }); return; } var tmpTopic = msg.getTopic(); var tmpType = tmpTopic.substr(0, 2); if (tmpType == "pp") { entity.type = 1; } else if (tmpType == "pd") { entity.type = 2; } else if (tmpType == "pg") { entity.type = 3; } else if (tmpType == "ch") { entity.type = 4; } else if (tmpType == "pc") { entity.type = 5; } //复用字段,targetId 以此为准 entity.groupId = msg.getTargetId(); entity.fromUserId = this._client.userId; entity.dataTime = Date.parse(new Date().toString()); } if (!entity) { return; } } var isPullFinished = RongIMLib.RongIMClient._memoryStore.isPullFinished; // PullMsg 没有拉取完成,抛弃所有直发在线消息,抛弃的消息会在 PullMsg 中返回 if (!isPullFinished && !offlineMsg && isStraightMsg) { return; } //解析实体对象为消息对象。 message = RongIMLib.MessageUtil.messageParser(entity, this._onReceived, offlineMsg); var isRTCMessage = message.conversationType == 12; if (isRTCMessage) { RongIMLib.RongIMClient.RTCListener(message); RongIMLib.RongIMClient.RTCInnerListener(message); RongIMLib.RongIMClient.RTCSignalLisener(message); return; } var isRecall = (msg.getTopic && msg.getTopic() == "recallMsg"); if (isRecall) { var content = message.content; message.conversationType = content.conversationType; message.targetId = content.targetId; message.messageId = null; } if (pubAckItem) { message.messageUId = pubAckItem.getMessageUId(); message.sentTime = pubAckItem.getTimestamp(); RongIMLib.RongIMClient._storageProvider.setItem(this._client.userId, message.sentTime); } if (message === null) { return; } var isChatroomMessage = message.conversationType == RongIMLib.ConversationType.CHATROOM; if (!isChatroomMessage) { var msgTag = RongIMLib.RongIMClient.MessageParams[message.messageType].msgTag.getMessageTag(); if (msgTag >= 0) { RongIMLib.SyncTimeUtil.set(message); } var isSend = (message.messageDirection == RongIMLib.MessageDirection.SEND); if (isSend) { var storageProvider = RongIMLib.RongIMClient._storageProvider; var userId = RongIMLib.Bridge._client.userId; var lastSentTime = storageProvider.getItem('last_sentTime_' + userId) || 0; if (message.sentTime <= lastSentTime && !isSync) { return; } } } // 设置会话时间戳并且判断是否传递 message 发送消息未处理会话时间戳 // key:'converST_' + 当前用户 + conversationType + targetId // RongIMClient._storageProvider.setItem('converST_' + Bridge._client.userId + message.conversationType + message.targetId, message.sentTime); // var isPersited = (RongIMClient.MessageParams[message.messageType].msgTag.getMessageTag() > 0); var msgTag = RongIMLib.RongIMClient.MessageParams[message.messageType].msgTag.getMessageTag(); var isPersited = msgTag === 3 || msgTag === 2; if (isPersited) { con = RongIMLib.RongIMClient._dataAccessProvider.getConversation(message.conversationType, message.targetId, { onSuccess: function () { }, onError: function () { } }); if (!con) { con = RongIMLib.RongIMClient.getInstance().createConversation(message.conversationType, message.targetId, ""); } if (message.messageDirection == RongIMLib.MessageDirection.RECEIVE && (entity.status & 64) == 64) { var mentioneds = RongIMLib.RongIMClient._storageProvider.getItem("mentioneds_" + Bridge._client.userId + '_' + message.conversationType + '_' + message.targetId); var key = message.conversationType + '_' + message.targetId, info = {}; if (message.content && message.content.mentionedInfo) { info[key] = { uid: message.messageUId, time: message.sentTime, mentionedInfo: message.content.mentionedInfo }; RongIMLib.RongIMClient._storageProvider.setItem("mentioneds_" + Bridge._client.userId + '_' + message.conversationType + '_' + message.targetId, JSON.stringify(info)); mentioneds = JSON.stringify(info); } if (mentioneds) { var info = JSON.parse(mentioneds); con.mentionedMsg = info[key]; } } var isReceiver = message.messageDirection == RongIMLib.MessageDirection.RECEIVE; if (isReceiver && message.senderUserId != Bridge._client.userId) { con.unreadMessageCount = con.unreadMessageCount + 1; if (RongIMLib.RongUtil.supportLocalStorage()) { // var originUnreadCount = RongIMClient._storageProvider.getItem("cu" + Bridge._client.userId + con.conversationType + con.targetId); // 与本地存储会话合并 // var newUnreadCount = Number(originUnreadCount) + 1; // RongIMClient._storageProvider.setItem("cu" + Bridge._client.userId + con.conversationType + message.targetId, newUnreadCount); var newUnreadCount = RongIMLib.UnreadCountHandler.add(con.conversationType, message.targetId, 1, message.sentTime); con.unreadMessageCount = newUnreadCount; } } var receivedTime = new Date().getTime(); con.receivedTime = RongIMLib.MessageUtil.getCheckedTime(receivedTime); con.receivedStatus = message.receivedStatus; con.senderUserId = message.sendUserId; con.notificationStatus = RongIMLib.ConversationNotificationStatus.DO_NOT_DISTURB; con.isTop = false; con.latestMessageId = message.messageId; con.latestMessage = message; con.sentTime = message.sentTime; RongIMLib.RongIMClient._dataAccessProvider.addConversation(con, { onSuccess: function (data) { if (!offlineMsg) { var Conversation_1 = RongIMLib.RongIMClient._dataAccessProvider.Conversation; var conversationList = RongIMLib.RongIMClient._memoryStore.conversationList; Conversation_1._notify(conversationList); } }, onError: function () { } }); } if (message.conversationType == RongIMLib.ConversationType.CUSTOMER_SERVICE && (message.messageType == "ChangeModeResponseMessage" || message.messageType == "SuspendMessage" || message.messageType == "HandShakeResponseMessage" || message.messageType == "TerminateMessage" || message.messageType == "CustomerStatusUpdateMessage" || message.messageType == "TextMessage" || message.messageType == "InformationNotificationMessage")) { if (!RongIMLib.RongIMClient._memoryStore.custStore["isInit"]) { return; } } if (message.conversationType == RongIMLib.ConversationType.CUSTOMER_SERVICE && message.messageType != "HandShakeResponseMessage") { if (!RongIMLib.RongIMClient._memoryStore.custStore[message.targetId]) { return; } if (message.messageType == "TerminateMessage") { if (RongIMLib.RongIMClient._memoryStore.custStore[message.targetId].sid != message.content.sid) { return; } } } if (message.messageType === RongIMLib.RongIMClient.MessageType["HandShakeResponseMessage"]) { var session = message.content.data; RongIMLib.RongIMClient._memoryStore.custStore[message.targetId] = session; if (session.serviceType == RongIMLib.CustomerType.ONLY_HUMAN || session.serviceType == RongIMLib.CustomerType.HUMAN_FIRST) { if (session.notAutoCha == "1") { RongIMLib.RongIMClient.getInstance().switchToHumanMode(message.targetId, { onSuccess: function () { }, onError: function () { } }); } } } if (RongIMLib.LoggerUtil.isLogCmdMsg(message)) { RongIMLib.Logger.reportMNLog(message.content); return; } var d = new Date(), m = d.getMonth() + 1, date = d.getFullYear() + '/' + (m.toString().length == 1 ? '0' + m : m) + '/' + d.getDate(); //new Date(date).getTime() - message.sentTime < 1 逻辑判断 超过 1 天未收的 ReadReceiptRequestMessage 离线消息自动忽略。 var dealtime = new Date(date).getTime() - message.sentTime < 0; if (RongIMLib.RongUtil.supportLocalStorage() && message.messageType === RongIMLib.RongIMClient.MessageType["ReadReceiptRequestMessage"] && dealtime && message.messageDirection == RongIMLib.MessageDirection.SEND) { var sentkey = Bridge._client.userId + message.content.messageUId + "SENT"; RongIMLib.RongIMClient._storageProvider.setItem(sentkey, JSON.stringify({ count: 0, dealtime: message.sentTime, userIds: {} })); } else if (RongIMLib.RongUtil.supportLocalStorage() && message.messageType === RongIMLib.RongIMClient.MessageType["ReadReceiptRequestMessage"] && dealtime) { var reckey = Bridge._client.userId + message.conversationType + message.targetId + 'RECEIVED', recData = JSON.parse(RongIMLib.RongIMClient._storageProvider.getItem(reckey)); if (recData) { if (message.senderUserId in recData) { if (recData[message.senderUserId].uIds && recData[message.senderUserId].uIds && recData[message.senderUserId].uIds.indexOf(message.content.messageUId) == -1) { recData[message.senderUserId].uIds.push(message.content.messageUId); recData[message.senderUserId].dealtime = message.sentTime; recData[message.senderUserId].isResponse = false; RongIMLib.RongIMClient._storageProvider.setItem(reckey, JSON.stringify(recData)); } else { return; } } else { var objSon = { uIds: [message.content.messageUId], dealtime: message.sentTime, isResponse: false }; recData[message.senderUserId] = objSon; RongIMLib.RongIMClient._storageProvider.setItem(reckey, JSON.stringify(recData)); } } else { var obj = {}; obj[message.senderUserId] = { uIds: [message.content.messageUId], dealtime: message.sentTime, isResponse: false }; RongIMLib.RongIMClient._storageProvider.setItem(reckey, JSON.stringify(obj)); } } if (RongIMLib.RongUtil.supportLocalStorage() && message.messageType === RongIMLib.RongIMClient.MessageType["ReadReceiptResponseMessage"] && dealtime) { var receiptResponseMsg = message.content; if (RongIMLib.RongUtil.isUndefined(receiptResponseMsg) || RongIMLib.RongUtil.isNull(receiptResponseMsg)) { receiptResponseMsg = new RongIMLib.ReadReceiptResponseMessage({}); } var receiptMessageDic = receiptResponseMsg.receiptMessageDic || {}, uIds = receiptMessageDic[Bridge._client.userId], sentkey = "", sentObj; message.receiptResponse || (message.receiptResponse = {}); if (uIds) { var cbuIds = []; for (var i = 0, len = uIds.length; i < len; i++) { sentkey = Bridge._client.userId + uIds[i] + "SENT"; sentObj = JSON.parse(RongIMLib.RongIMClient._storageProvider.getItem(sentkey)); if (sentObj && !(message.senderUserId in sentObj.userIds)) { cbuIds.push(uIds[i]); sentObj.count += 1; sentObj.userIds[message.senderUserId] = message.sentTime; message.receiptResponse[uIds[i]] = sentObj.count; RongIMLib.RongIMClient._storageProvider.setItem(sentkey, JSON.stringify(sentObj)); } } receiptResponseMsg.receiptMessageDic[Bridge._client.userId] = cbuIds; message.content = receiptResponseMsg; } } var that = this; if (RongIMLib.RongIMClient._voipProvider && ['AcceptMessage', 'RingingMessage', 'HungupMessage', 'InviteMessage', 'MediaModifyMessage', 'MemberModifyMessage'].indexOf(message.messageType) > -1) { setTimeout(function () { RongIMLib.RongIMClient._voipProvider.onReceived(message); }); } else { var count = leftCount || 0; var hasMore = !isPullFinished; try { that._onReceived(message, count, hasMore); } catch (e) { console.error(e); } } }; MessageHandler.prototype.handleMessage = function (msg) { if (!msg) { return; } if (msg && RongIMLib.RongUtil.isObject(msg) && msg.timestamp) { RongIMLib.MessageUtil.setDeltaTime(msg.timestamp); } switch (msg._name) { case "ConnAckMessage": Bridge._client.handler.connectCallback.process(msg.getStatus(), msg.getUserId(), msg.getTimestamp()); break; case "PublishMessage": if (!msg.getSyncMsg() && msg.getQos() != 0) { Bridge._client.channel.writeAndFlush(new RongIMLib.PubAckMessage(msg.getMessageId())); } // TODO && -> if (msg.getSyncMsg() && !RongIMLib.RongIMClient._memoryStore.depend.isPolling) { Bridge._client.handler.syncMsgMap[msg.getMessageId()] = msg; } else { //如果是PublishMessage就把该对象给onReceived方法执行处理 Bridge._client.handler.onReceived(msg); } break; case "QueryAckMessage": if (msg.getQos() != 0) { Bridge._client.channel.writeAndFlush(new RongIMLib.QueryConMessage(msg.getMessageId())); } var temp = Bridge._client.handler.map[msg.getMessageId()]; if (temp) { //执行回调操作 temp.Callback.process(msg.getStatus(), msg.getData(), msg.getDate(), temp.Message); delete Bridge._client.handler.map[msg.getMessageId()]; } break; case "PubAckMessage": var item = Bridge._client.handler.map[msg.getMessageId()]; if (item) { item.Callback.process(msg.getStatus() || 0, msg.getMessageUId(), msg.getTimestamp(), item.Message, msg.getMessageId()); delete Bridge._client.handler.map[msg.getMessageId()]; } else { var userId = RongIMLib.Bridge._client.userId; RongIMLib.RongIMClient._storageProvider.setItem('last_sentTime_' + userId, msg.timestamp); Bridge._client.handler.onReceived(Bridge._client.handler.syncMsgMap[msg.messageId], msg, null, null, true); delete Bridge._client.handler.syncMsgMap[msg.getMessageId()]; } break; case "PingRespMessage": if (RongIMLib.RongIMClient._memoryStore.isFirstPingMsg) { RongIMLib.RongIMClient._memoryStore.isFirstPingMsg = false; } else { Bridge._client.pauseTimer(); } break; case "DisconnectMessage": Bridge._client.channel.disconnect(msg.getStatus()); break; default: RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.L_CATCH_UNKNOWN_MSG_E, level: RongIMLib.LoggerLevel.E, type: RongIMLib.LoggerType.IM, content: { action: 'MessageHandler -> handleMessage', msg: msg } }); } }; return MessageHandler; })(); RongIMLib.MessageHandler = MessageHandler; })(RongIMLib || (RongIMLib = {})); var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; /// var RongIMLib; (function (RongIMLib) { var MessageCallback = (function () { function MessageCallback(error) { this.timeout = null; this.onError = null; if (error && typeof error == "number") { this.timeoutMillis = error; } else { this.timeoutMillis = 30000; this.onError = error; } } MessageCallback.prototype.resumeTimer = function () { var me = this; if (this.timeoutMillis > 0 && !this.timeout) { this.timeout = setTimeout(function () { me.readTimeOut(true); }, this.timeoutMillis); } }; MessageCallback.prototype.pauseTimer = function () { if (this.timeout) { clearTimeout(this.timeout); this.timeout = null; } }; MessageCallback.prototype.readTimeOut = function (isTimeout) { if (isTimeout && this.onError) { this.onError(RongIMLib.ErrorCode.TIMEOUT); } else { this.pauseTimer(); } }; return MessageCallback; })(); RongIMLib.MessageCallback = MessageCallback; var CallbackMapping = (function () { function CallbackMapping() { this.publicServiceList = []; } CallbackMapping.getInstance = function () { return new CallbackMapping(); }; CallbackMapping.prototype.pottingProfile = function (item) { var temp; this.profile = new RongIMLib.PublicServiceProfile(); temp = JSON.parse(item.extra); this.profile.isGlobal = temp.isGlobal; this.profile.introduction = temp.introduction; this.profile.menu = temp.menu; this.profile.hasFollowed = temp.follow; this.profile.publicServiceId = item.mpid; this.profile.name = item.name; this.profile.portraitUri = item.portraitUrl; this.profile.conversationType = item.type == "mc" ? RongIMLib.ConversationType.APP_PUBLIC_SERVICE : RongIMLib.ConversationType.PUBLIC_SERVICE; this.publicServiceList.push(this.profile); }; CallbackMapping.prototype.mapping = function (entity, tag) { switch (tag) { case "GetUserInfoOutput": var userInfo = new RongIMLib.UserInfo(entity.userId, entity.userName, entity.userPortrait); return userInfo; case "GetQNupTokenOutput": return { deadline: RongIMLib.MessageUtil.int64ToTimestamp(entity.deadline), token: entity.token, bosToken: entity.bosToken, bosDate: entity.bosDate, path: entity.path }; case "GetQNdownloadUrlOutput": return { downloadUrl: entity.downloadUrl }; case "CreateDiscussionOutput": return entity.id; case "ChannelInfoOutput": var disInfo = new RongIMLib.Discussion(); disInfo.creatorId = entity.adminUserId; disInfo.id = entity.channelId; disInfo.memberIdList = entity.firstTenUserIds; disInfo.name = entity.channelName; disInfo.isOpen = entity.openStatus; return disInfo; case "GroupHashOutput": return entity.result; case "QueryBlackListOutput": return entity.userIds; case "SearchMpOutput": case "PullMpOutput": if (entity.info) { var self = this; Array.forEach(entity.info, function (item) { setTimeout(function () { self.pottingProfile(item); }, 100); }); } return this.publicServiceList; default: return entity; } }; return CallbackMapping; })(); RongIMLib.CallbackMapping = CallbackMapping; var PublishCallback = (function (_super) { __extends(PublishCallback, _super); function PublishCallback(_cb, _timeout) { _super.call(this, _timeout); this._cb = _cb; this._timeout = _timeout; } PublishCallback.prototype.process = function (_status, messageUId, timestamp, _msg, messageId) { this.readTimeOut(); if (_status == 0) { if (_msg) { _msg.setSentStatus = _status; } var isPullFinished = RongIMLib.RongIMClient._memoryStore.isPullFinished; if (isPullFinished) { var userId = RongIMLib.Bridge._client.userId; var stroageProvider = RongIMLib.RongIMClient._storageProvider; stroageProvider.setItem('last_sentTime_' + userId, timestamp); RongIMLib.SyncTimeUtil.set({ messageDirection: RongIMLib.MessageDirection.SEND, sentTime: timestamp }); } this._cb({ messageUId: messageUId, timestamp: timestamp, messageId: messageId }); } else { this._timeout(_status, { messageUId: messageUId, sentTime: timestamp }); } }; PublishCallback.prototype.readTimeOut = function (x) { MessageCallback.prototype.readTimeOut.call(this, x); }; return PublishCallback; })(MessageCallback); RongIMLib.PublishCallback = PublishCallback; var QueryCallback = (function (_super) { __extends(QueryCallback, _super); function QueryCallback(_cb, _timeout) { _super.call(this, _timeout); this._cb = _cb; this._timeout = _timeout; } QueryCallback.prototype.process = function (status, data, serverTime, pbtype) { this.readTimeOut(); if (pbtype && data && status == 0) { try { data = CallbackMapping.getInstance().mapping(RongIMLib.RongIMClient.Protobuf[pbtype].decode(data), pbtype); } catch (e) { this._timeout(RongIMLib.ErrorCode.UNKNOWN); RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.L_DECODE_QUERY_DATA_E, level: RongIMLib.LoggerLevel.E, type: RongIMLib.LoggerType.IM, content: { stack: e, msg: 'QueryCallback -> process' } }); return; } if ("GetUserInfoOutput" == pbtype) { //pb类型为GetUserInfoOutput的话就把data放入userinfo缓存队列 RongIMLib.Client.userInfoMapping[data.userId] = data; } this._cb(data); } else { status > 0 ? this._timeout(status) : this._cb(status); } }; QueryCallback.prototype.readTimeOut = function (x) { MessageCallback.prototype.readTimeOut.call(this, x); }; return QueryCallback; })(MessageCallback); RongIMLib.QueryCallback = QueryCallback; var ConnectAck = (function (_super) { __extends(ConnectAck, _super); function ConnectAck(_cb, _timeout, client) { _super.call(this, _timeout); this._client = client; this._cb = _cb; this._timeout = _timeout; } ConnectAck.prototype.process = function (status, userId, timestamp) { this.readTimeOut(); if (status == 0) { this._client.userId = userId; var self = this; if (!RongIMLib.RongIMClient._memoryStore.depend.isPolling && RongIMLib.RongIMClient._memoryStore.isFirstPingMsg) { RongIMLib.Bridge._client.checkSocket({ onSuccess: function () { if (!RongIMLib.RongIMClient.isNotPullMsg) { self._client.syncTime(undefined, undefined, undefined, true); } }, onError: function () { RongIMLib.RongIMClient._memoryStore.isFirstPingMsg = false; RongIMLib.RongIMClient.getInstance().disconnect(); RongIMLib.RongIMClient.connect(RongIMLib.RongIMClient._memoryStore.token, RongIMLib.RongIMClient._memoryStore.callback); } }); } else { if (!RongIMLib.RongIMClient.isNotPullMsg) { self._client.syncTime(undefined, undefined, undefined, true); } } RongIMLib.Bridge._client.channel.socket.fire("StatusChanged", 0); if (this._client.reconnectObj.onSuccess) { this._client.reconnectObj.onSuccess(userId); delete this._client.reconnectObj.onSuccess; } else { var me = this; me._cb(userId); // setTimeout(function() { me._cb(userId); }, 500); var depend = RongIMLib.RongIMClient._memoryStore.depend; var maxConversationCount = depend.maxConversationCount; var isNotifyConversationList = depend.isNotifyConversationList; isNotifyConversationList && RongIMLib.RongIMClient._dataAccessProvider.getRemoteConversationList({ onSuccess: function (conversationList) { var Conversation = RongIMLib.RongIMClient._dataAccessProvider.Conversation; Conversation._notify(conversationList); }, onError: function (code) { console.log('内部获取列表失败: %d', code); } }, null, maxConversationCount); } RongIMLib.RongIMClient._memoryStore.connectAckTime = timestamp; RongIMLib.MessageUtil.setDeltaTime(timestamp); } else if (status == 6) { RongIMLib.RongIMClient.getInstance().disconnect(); //重定向 连错 CMP var me = this; var _client = me._client; var appId = _client.appId, token = _client.token; new RongIMLib.Navigation().requestNavi(token, appId, function () { _client.clearHeartbeat(); var newClient = new RongIMLib.Client(token, appId); RongIMLib.Bridge._client = newClient; newClient.__init(function () { RongIMLib.Transportations._TransportType == "websocket" && newClient.keepLive(); }); }, me._timeout, false); } else { RongIMLib.Bridge._client.channel.socket.socket._status = status; if (this._client.reconnectObj.onError) { this._client.reconnectObj.onError(status); delete this._client.reconnectObj.onError; } else { this._timeout(status); } } }; ConnectAck.prototype.readTimeOut = function (x) { MessageCallback.prototype.readTimeOut.call(this, x); }; return ConnectAck; })(MessageCallback); RongIMLib.ConnectAck = ConnectAck; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var Navigation = (function () { function Navigation() { } Navigation.clear = function () { var storage = RongIMLib.RongIMClient._storageProvider; storage.removeItem('rc_uid'); storage.removeItem('serverIndex'); storage.removeItem('rongSDK'); }; Navigation.prototype.getNaviSuccess = function (result, naviUrl) { var storage = RongIMLib.RongIMClient._storageProvider; storage.setItem('fullnavi', JSON.stringify(result)); var successNaviProtocol = RongIMLib.RongUtil.getUrlProtocol(naviUrl); // navi 请求成功后, 根据 navi 协议头, 设置连接 websocket 协议头 RongIMLib.RongIMClient.setProtocol(successNaviProtocol); storage.setItem(Navigation.StoreProtocolKey, successNaviProtocol); var server = result.server; if (server) { server += ','; } var backupServer = result.backupServer || ''; var tpl = '{server}{backupServer}'; var servers = RongIMLib.RongUtil.tplEngine(tpl, { server: server, backupServer: backupServer }); servers = servers.split(','); storage.setItem('servers', JSON.stringify(servers)); var token = RongIMLib.RongIMClient._memoryStore.token; var uid = RongIMLib.InnerUtil.getUId(token); storage.setItem('rc_uid', uid); var userId = result.userId; storage.setItem('current_user', userId); storage.setItem('navi_time', RongIMLib.RongUtil.getTimestamp()); if (result.voipCallInfo) { var callInfo = JSON.parse(result.voipCallInfo); RongIMLib.RongIMClient._memoryStore.voipStategy = callInfo.strategy; storage.setItem("voipStrategy", callInfo.strategy); } var uploadDomains = { qiniu: result.uploadServer || '', bos: result.bosAddr || '' }; storage.setItem('upload_domains', JSON.stringify(uploadDomains)); //替换本地存储的导航信息 var openMp = result.openMp; storage.setItem('openMp' + uid, openMp); RongIMLib.RongIMClient._memoryStore.depend.openMp = openMp; }; ; Navigation.prototype.connect = function (appId, token, callback) { var oldAppId = RongIMLib.RongIMClient._storageProvider.getItem("appId"); //如果appid和本地存储的不一样,清空所有本地存储数据 if (oldAppId && oldAppId != appId) { RongIMLib.RongIMClient._storageProvider.clearItem(); RongIMLib.RongIMClient._storageProvider.setItem("appId", appId); } if (!oldAppId) { RongIMLib.RongIMClient._storageProvider.setItem("appId", appId); } var client = new RongIMLib.Client(token, appId); this.requestNavi(token, appId, function () { client.connect(callback); }, callback.onError, true); return client; }; Navigation.prototype.requestNavi = function (token, appId, _onsuccess, _onerror, unignore) { if (unignore) { //根据token生成MD5截取8-16下标的数据与本地存储的导航信息进行比对 //如果信息和上次的通道类型都一样,不执行navi请求,用本地存储的导航信息连接服务器 var uId = md5(token).slice(8, 16); var storage = RongIMLib.RongIMClient._storageProvider; var transportType = storage.getItem("rongSDK"); var isSameType = (RongIMLib.Transportations._TransportType == transportType); var _old = storage.getItem('rc_uid'); var isSameUser = (_old == uId); var servers = storage.getItem('servers'); var hasServers = (typeof servers == 'string'); var currentTime = RongIMLib.RongUtil.getTimestamp(); var naviSavedTime = Number(storage.getItem('navi_time')) || 0; var isNotExpired = currentTime - naviSavedTime < RongIMLib.RongIMClient.NavExpiredTime; if (isSameUser && isSameType && hasServers && RongIMLib.RongUtil.hasValidWsUrl(servers) && isNotExpired) { RongIMLib.RongIMClient._memoryStore.voipStategy = storage.getItem("voipStrategy"); var openMp = storage.getItem('openMp' + uId); RongIMLib.RongIMClient._memoryStore.depend.openMp = openMp; var storageProtocol = storage.getItem(Navigation.StoreProtocolKey); storageProtocol && RongIMLib.RongIMClient.setProtocol(storageProtocol); _onsuccess(); return; } } Navigation.clear(); RongIMLib.RongIMClient.invalidWsUrls = []; var context = this; var StatusEvent = RongIMLib.Channel._ConnectionStatusListener; var depend = RongIMLib.RongIMClient._memoryStore.depend; var navigaters = depend.navigaters; var naviTimeout = depend.naviTimeout; var maxNaviRetry = depend.maxNaviRetry; var isNaviJSONP = depend.isNaviJSONP; var isSupportRequestHeaders = RongIMLib.RongUtil.isSupportRequestHeaders(); var isRequestJSONP = !isSupportRequestHeaders || isNaviJSONP; var requestFunc = isRequestJSONP ? context.requestJSONP : context.request; var timer = new RongIMLib.Timer({ timeout: naviTimeout }); var internalRetry = 1; var isRange = function () { return internalRetry >= maxNaviRetry; }; var indexTools = new RongIMLib.IndexTools({ items: navigaters, onwheel: function () { internalRetry += 1; } }); var consume = function () { if (isRange()) { _onerror(RongIMLib.ConnectionStatus.RESPONSE_NAVI_ERROR); return; } var index = indexTools.get(); var navi = navigaters[index]; navi = RongIMLib.RongUtil.getValidNavi(navi); indexTools.add(); RongIMLib.LoggerUtil.recordFatalLogOfNavi(internalRetry, navigaters); var success = function (result) { timer.pause(); StatusEvent.onChanged(RongIMLib.ConnectionStatus.RESPONSE_NAVI); var code = result.code; if (RongIMLib.RongUtil.isEqual(code, 200)) { context.getNaviSuccess(result, navi); _onsuccess(); } if (RongIMLib.RongUtil.isEqual(code, 401)) { _onerror(RongIMLib.ConnectionState.TOKEN_INCORRECT); } if (RongIMLib.RongUtil.isEqual(code, 403)) { StatusEvent.onChanged(RongIMLib.ConnectionStatus.APPKEY_IS_FAKE); } }; var error = function (status) { if (RongIMLib.RongUtil.isEqual(status, 0)) { return; } timer.pause(); StatusEvent.onChanged(RongIMLib.ConnectionStatus.RESPONSE_NAVI_ERROR); consume(); }; StatusEvent.onChanged(RongIMLib.ConnectionStatus.REQUEST_NAVI); var xhr = requestFunc.call(context, navi, appId, token, success, error); timer.resume(function () { StatusEvent.onChanged(RongIMLib.ConnectionStatus.RESPONSE_NAVI_TIMEOUT); xhr.abort(); consume(); }); }; consume(); RongIMLib.Logger.loggerCache.isNewNavi = true; }; Navigation.prototype.getPath = function (navi, appId, token, callbackName) { var depend = RongIMLib.RongIMClient._memoryStore.depend; var path = (depend.isPolling ? 'cometnavi' : 'navi'); token = encodeURIComponent(token); var sdkver = RongIMLib.RongIMClient.sdkver; var random = RongIMLib.RongUtil.getTimestamp(); var tpl = '{navi}/{path}.js?appId={appId}&token={token}&callBack={callback}&v={sdkver}&r={random}'; var url = RongIMLib.RongUtil.tplEngine(tpl, { navi: navi, path: path, appId: appId, token: token, sdkver: sdkver, random: random, callback: callbackName }); return url; }; Navigation.prototype.request = function (navi, appId, token, success, error) { var url = this.getPath(navi, appId, token, 'getServerEndpoint'); var requestType = "HTTP"; RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.L_GETN_T, level: RongIMLib.LoggerLevel.I, type: RongIMLib.LoggerType.IM, content: { url: url, requestType: requestType } }); return RongIMLib.RongUtil.request({ url: url, success: function (result) { result = result.replace('getServerEndpoint(', '').replace(');', ''); // 兼容私有云无分号 var lastIndex = result.lastIndexOf(')'); var maxIndex = result.length - 1; if (lastIndex == maxIndex) { result = result.substr(0, lastIndex); } result = JSON.parse(result); RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.L_GETN_R, level: RongIMLib.LoggerLevel.I, type: RongIMLib.LoggerType.IM, content: { code: 0, result: result, url: url, requestType: requestType } }); success(result); }, error: function (status, result) { if (status == 401 || status == 403) { success(JSON.parse(result)); } else { error(status); } RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.L_GETN_R, level: RongIMLib.LoggerLevel.E, type: RongIMLib.LoggerType.IM, content: { code: status, result: result, url: url, requestType: requestType } }); } }); }; Navigation.prototype.requestJSONP = function (navi, appId, token, success, error) { var callbackName = 'getServerEndpoint'; var requestType = "JSONP"; RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.L_GETN_T, level: RongIMLib.LoggerLevel.I, type: RongIMLib.LoggerType.IM, content: { url: url, requestType: requestType } }); var loggerResult = function (status, result) { RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.L_GETN_R, level: RongIMLib.LoggerLevel.E, type: RongIMLib.LoggerType.IM, content: { code: status, result: result, url: url, requestType: requestType } }); }; window.getServerEndpoint = function (result) { var code = result.code; loggerResult(code, result); if (code !== 200) { return error(RongIMLib.ConnectionState.TOKEN_INCORRECT); } success(result); }; var url = this.getPath(navi, appId, token, callbackName); var xss = document.createElement('script'); xss.src = url; document.body.appendChild(xss); xss.onerror = function () { error(RongIMLib.ConnectionState.TOKEN_INCORRECT); loggerResult(RongIMLib.ConnectionState.TOKEN_INCORRECT, {}); }; }; Navigation.StoreProtocolKey = 'navprotocol'; Navigation.Endpoint = new Object; return Navigation; })(); RongIMLib.Navigation = Navigation; })(RongIMLib || (RongIMLib = {})); // TODO: 统一变量、方法等命名规范 var RongIMLib; (function (RongIMLib) { /** * 消息基类 */ var BaseMessage = (function () { function BaseMessage(arg) { this._name = "BaseMessage"; this.lengthSize = 0; if (arg instanceof RongIMLib.Header) { this._header = arg; } else { this._header = new RongIMLib.Header(arg, false, RongIMLib.Qos.AT_MOST_ONCE, false); } } BaseMessage.prototype.read = function (In, length) { this.readMessage(In, length); }; BaseMessage.prototype.write = function (Out) { var binaryHelper = new RongIMLib.BinaryHelper(); var out = binaryHelper.convertStream(Out); this._headerCode = this.getHeaderFlag(); out.write(this._headerCode); this.writeMessage(out); return out; }; BaseMessage.prototype.getHeaderFlag = function () { return this._header.encode(); }; BaseMessage.prototype.getLengthSize = function () { return this.lengthSize; }; BaseMessage.prototype.toBytes = function () { return this.write([]).getBytesArray(); }; BaseMessage.prototype.isRetained = function () { return this._header.retain; }; BaseMessage.prototype.setRetained = function (retain) { this._header.retain = retain; }; BaseMessage.prototype.setQos = function (qos) { this._header.qos = Object.prototype.toString.call(qos) == "[object Object]" ? qos : RongIMLib.Qos[qos]; }; BaseMessage.prototype.setDup = function (dup) { this._header.dup = dup; }; BaseMessage.prototype.isDup = function () { return this._header.dup; }; BaseMessage.prototype.getType = function () { return this._header.type; }; BaseMessage.prototype.getQos = function () { return this._header.qos; }; BaseMessage.prototype.messageLength = function () { return 0; }; BaseMessage.prototype.writeMessage = function (out) { }; BaseMessage.prototype.readMessage = function (In, length) { }; BaseMessage.prototype.init = function (args) { var valName, nana, me = this; for (nana in args) { if (!args.hasOwnProperty(nana)) { continue; } valName = nana.replace(/^\w/, function (x) { var tt = x.charCodeAt(0); return "set" + (tt >= 0x61 ? String.fromCharCode(tt & ~32) : x); }); if (valName in me) { if (nana == "status") { me[valName](disconnectStatus[args[nana]] ? disconnectStatus[args[nana]] : args[nana]); } else { me[valName](args[nana]); } } } }; return BaseMessage; })(); RongIMLib.BaseMessage = BaseMessage; /** *连接消息类型 */ var ConnectMessage = (function (_super) { __extends(ConnectMessage, _super); function ConnectMessage(header) { _super.call(this, arguments.length == 0 || arguments.length == 3 ? RongIMLib.Type.CONNECT : arguments[0]); this._name = "ConnectMessage"; this.CONNECT_HEADER_SIZE = 12; this.protocolId = "RCloud"; this.binaryHelper = new RongIMLib.BinaryHelper(); this.protocolVersion = 3; switch (arguments.length) { case 0: case 1: case 3: if (!arguments[0] || arguments[0].length > 64) { throw new Error("ConnectMessage:Client Id cannot be null and must be at most 64 characters long: " + arguments[0]); } this.clientId = arguments[0]; this.cleanSession = arguments[1]; this.keepAlive = arguments[2]; break; } } ConnectMessage.prototype.messageLength = function () { var payloadSize = this.binaryHelper.toMQttString(this.clientId).length; payloadSize += this.binaryHelper.toMQttString(this.willTopic).length; payloadSize += this.binaryHelper.toMQttString(this.will).length; payloadSize += this.binaryHelper.toMQttString(this.appId).length; payloadSize += this.binaryHelper.toMQttString(this.token).length; return payloadSize + this.CONNECT_HEADER_SIZE; }; ConnectMessage.prototype.readMessage = function (stream) { this.protocolId = stream.readUTF(); this.protocolVersion = stream.readByte(); var cFlags = stream.readByte(); this.hasAppId = (cFlags & 128) > 0; this.hasToken = (cFlags & 64) > 0; this.retainWill = (cFlags & 32) > 0; this.willQos = cFlags >> 3 & 3; this.hasWill = (cFlags & 4) > 0; this.cleanSession = (cFlags & 32) > 0; this.keepAlive = stream.read() * 256 + stream.read(); this.clientId = stream.readUTF(); if (this.hasWill) { this.willTopic = stream.readUTF(); this.will = stream.readUTF(); } if (this.hasAppId) { try { this.appId = stream.readUTF(); } catch (ex) { throw new Error(ex); } } if (this.hasToken) { try { this.token = stream.readUTF(); } catch (ex) { throw new Error(ex); } } return stream; }; ConnectMessage.prototype.writeMessage = function (out) { var stream = this.binaryHelper.convertStream(out); stream.writeUTF(this.protocolId); stream.write(this.protocolVersion); var flags = this.cleanSession ? 2 : 0; flags |= this.hasWill ? 4 : 0; flags |= this.willQos ? this.willQos >> 3 : 0; flags |= this.retainWill ? 32 : 0; flags |= this.hasToken ? 64 : 0; flags |= this.hasAppId ? 128 : 0; stream.write(flags); stream.writeChar(this.keepAlive); stream.writeUTF(this.clientId); if (this.hasWill) { stream.writeUTF(this.willTopic); stream.writeUTF(this.will); } if (this.hasAppId) { stream.writeUTF(this.appId); } if (this.hasToken) { stream.writeUTF(this.token); } return stream; }; return ConnectMessage; })(BaseMessage); RongIMLib.ConnectMessage = ConnectMessage; /** *连接应答类型 */ var ConnAckMessage = (function (_super) { __extends(ConnAckMessage, _super); function ConnAckMessage(header) { _super.call(this, arguments.length == 0 ? RongIMLib.Type.CONNACK : arguments.length == 1 ? arguments[0] instanceof RongIMLib.Header ? arguments[0] : RongIMLib.Type.CONNACK : null); this._name = "ConnAckMessage"; this.MESSAGE_LENGTH = 2; this.binaryHelper = new RongIMLib.BinaryHelper(); var me = this; switch (arguments.length) { case 0: case 1: if (!(arguments[0] instanceof RongIMLib.Header)) { if (arguments[0] in RongIMLib.ConnectionState) { if (arguments[0] == null) { throw new Error("ConnAckMessage:The status of ConnAskMessage can't be null"); } me.setStatus(arguments[0]); } } break; } } ; ConnAckMessage.prototype.messageLength = function () { var length = this.MESSAGE_LENGTH; if (this.userId) { length += this.binaryHelper.toMQttString(this.userId).length; } return length; }; ; ConnAckMessage.prototype.readMessage = function (_in, msglength) { _in.read(); var result = +_in.read(); if (result >= 0 && result <= 12) { this.setStatus(result); } else { throw new Error("Unsupported CONNACK code:" + result); } if (msglength > this.MESSAGE_LENGTH) { this.setUserId(_in.readUTF()); var sessionId = _in.readUTF(); var timestamp = _in.readLong(); this.setTimestamp(timestamp); } }; ; ConnAckMessage.prototype.writeMessage = function (out) { var stream = this.binaryHelper.convertStream(out); stream.write(128); switch (+status) { case 0: case 1: case 2: case 5: case 6: stream.write(+status); break; case 3: case 4: stream.write(3); break; default: throw new Error("Unsupported CONNACK code:" + status); } if (this.userId) { stream.writeUTF(this.userId); } return stream; }; ; ConnAckMessage.prototype.setStatus = function (x) { this.status = x; }; ; ConnAckMessage.prototype.setUserId = function (_userId) { this.userId = _userId; }; ; ConnAckMessage.prototype.getStatus = function () { return this.status; }; ; ConnAckMessage.prototype.getUserId = function () { return this.userId; }; ; ConnAckMessage.prototype.setTimestamp = function (x) { this.timestrap = x; }; ; ConnAckMessage.prototype.getTimestamp = function () { return this.timestrap; }; return ConnAckMessage; })(BaseMessage); RongIMLib.ConnAckMessage = ConnAckMessage; /** *断开消息类型 */ var DisconnectMessage = (function (_super) { __extends(DisconnectMessage, _super); function DisconnectMessage(header) { _super.call(this, header instanceof RongIMLib.Header ? header : RongIMLib.Type.DISCONNECT); this._name = "DisconnectMessage"; this.MESSAGE_LENGTH = 2; this.binaryHelper = new RongIMLib.BinaryHelper(); if (!(header instanceof RongIMLib.Header)) { if (header in RongIMLib.ConnectionStatus) { this.status = header; } } } DisconnectMessage.prototype.messageLength = function () { return this.MESSAGE_LENGTH; }; DisconnectMessage.prototype.readMessage = function (_in) { _in.read(); var result = +_in.read(); if (result >= 0 && result <= 5) { this.setStatus(disconnectStatus[result] ? disconnectStatus[result] : result); } else { throw new Error("Unsupported CONNACK code:" + result); } }; DisconnectMessage.prototype.writeMessage = function (Out) { var out = this.binaryHelper.convertStream(Out); out.write(0); if (+status >= 1 && +status <= 3) { out.write((+status) - 1); } else { throw new Error("Unsupported CONNACK code:" + status); } }; DisconnectMessage.prototype.setStatus = function (x) { this.status = x; }; ; DisconnectMessage.prototype.getStatus = function () { return this.status; }; ; return DisconnectMessage; })(BaseMessage); RongIMLib.DisconnectMessage = DisconnectMessage; /** *请求消息信令 */ var PingReqMessage = (function (_super) { __extends(PingReqMessage, _super); function PingReqMessage(header) { _super.call(this, (header && header instanceof RongIMLib.Header) ? header : RongIMLib.Type.PINGREQ); this._name = "PingReqMessage"; } return PingReqMessage; })(BaseMessage); RongIMLib.PingReqMessage = PingReqMessage; /** *响应消息信令 */ var PingRespMessage = (function (_super) { __extends(PingRespMessage, _super); function PingRespMessage(header) { _super.call(this, (header && header instanceof RongIMLib.Header) ? header : RongIMLib.Type.PINGRESP); this._name = "PingRespMessage"; } return PingRespMessage; })(BaseMessage); RongIMLib.PingRespMessage = PingRespMessage; /** *封装MesssageId */ var RetryableMessage = (function (_super) { __extends(RetryableMessage, _super); function RetryableMessage(argu) { _super.call(this, argu); this._name = "RetryableMessage"; this.binaryHelper = new RongIMLib.BinaryHelper(); } RetryableMessage.prototype.messageLength = function () { return 2; }; RetryableMessage.prototype.writeMessage = function (Out) { var out = this.binaryHelper.convertStream(Out), Id = this.getMessageId(), lsb = Id & 255, msb = (Id & 65280) >> 8; out.write(msb); out.write(lsb); return out; }; RetryableMessage.prototype.readMessage = function (_in, msgLength) { var msgId = _in.read() * 256 + _in.read(); this.setMessageId(parseInt(msgId, 10)); }; RetryableMessage.prototype.setMessageId = function (_messageId) { this.messageId = _messageId; }; RetryableMessage.prototype.getMessageId = function () { return this.messageId; }; return RetryableMessage; })(BaseMessage); RongIMLib.RetryableMessage = RetryableMessage; /** *发送消息应答(双向) *qos为1必须给出应答(所有消息类型一样) */ var PubAckMessage = (function (_super) { __extends(PubAckMessage, _super); function PubAckMessage(header) { _super.call(this, (header instanceof RongIMLib.Header) ? header : RongIMLib.Type.PUBACK); this.msgLen = 2; this.date = 0; this.millisecond = 0; this.timestamp = 0; this.binaryHelper = new RongIMLib.BinaryHelper(); this._name = "PubAckMessage"; if (!(header instanceof RongIMLib.Header)) { _super.prototype.setMessageId.call(this, header); } } PubAckMessage.prototype.messageLength = function () { return this.msgLen; }; PubAckMessage.prototype.writeMessage = function (Out) { var out = this.binaryHelper.convertStream(Out); RetryableMessage.prototype.writeMessage.call(this, out); }; PubAckMessage.prototype.readMessage = function (_in, msgLength) { RetryableMessage.prototype.readMessage.call(this, _in); this.date = _in.readInt(); this.status = _in.read() * 256 + _in.read(); this.millisecond = _in.read() * 256 + _in.read(); this.timestamp = this.date * 1000 + this.millisecond; this.messageUId = _in.readUTF(); }; PubAckMessage.prototype.setStatus = function (x) { this.status = x; }; PubAckMessage.prototype.setTimestamp = function (timestamp) { this.timestamp = timestamp; }; PubAckMessage.prototype.setMessageUId = function (messageUId) { this.messageUId = messageUId; }; PubAckMessage.prototype.getStatus = function () { return this.status; }; PubAckMessage.prototype.getDate = function () { return this.date; }; PubAckMessage.prototype.getTimestamp = function () { return this.timestamp; }; PubAckMessage.prototype.getMessageUId = function () { return this.messageUId; }; return PubAckMessage; })(RetryableMessage); RongIMLib.PubAckMessage = PubAckMessage; /** *发布消息 */ var PublishMessage = (function (_super) { __extends(PublishMessage, _super); function PublishMessage(header, two, three) { _super.call(this, (arguments.length == 1 && header instanceof RongIMLib.Header) ? header : arguments.length == 3 ? RongIMLib.Type.PUBLISH : 0); this._name = "PublishMessage"; this.binaryHelper = new RongIMLib.BinaryHelper(); this.syncMsg = false; if (arguments.length == 3) { this.topic = header; this.targetId = three; this.data = typeof two == "string" ? this.binaryHelper.toMQttString(two) : two; } } PublishMessage.prototype.messageLength = function () { var length = 10; length += this.binaryHelper.toMQttString(this.topic).length; length += this.binaryHelper.toMQttString(this.targetId).length; length += this.data.length; return length; }; PublishMessage.prototype.writeMessage = function (Out) { var out = this.binaryHelper.convertStream(Out); out.writeUTF(this.topic); out.writeUTF(this.targetId); RetryableMessage.prototype.writeMessage.apply(this, arguments); out.write(this.data); }; ; PublishMessage.prototype.readMessage = function (_in, msgLength) { var pos = 6; this.date = _in.readInt(); this.topic = _in.readUTF(); pos += this.binaryHelper.toMQttString(this.topic).length; this.targetId = _in.readUTF(); pos += this.binaryHelper.toMQttString(this.targetId).length; RetryableMessage.prototype.readMessage.apply(this, arguments); this.data = new Array(msgLength - pos); this.data = _in.read(this.data); }; ; PublishMessage.prototype.setTopic = function (x) { this.topic = x; }; PublishMessage.prototype.setData = function (x) { this.data = x; }; PublishMessage.prototype.setTargetId = function (x) { this.targetId = x; }; PublishMessage.prototype.setDate = function (x) { this.date = x; }; PublishMessage.prototype.setSyncMsg = function (x) { this.syncMsg = x; }; //是否是其他端同步过来的消息 PublishMessage.prototype.getSyncMsg = function () { return this.syncMsg; }; PublishMessage.prototype.getTopic = function () { return this.topic; }; PublishMessage.prototype.getData = function () { return this.data; }; PublishMessage.prototype.getTargetId = function () { return this.targetId; }; PublishMessage.prototype.getDate = function () { return this.date; }; return PublishMessage; })(RetryableMessage); RongIMLib.PublishMessage = PublishMessage; /** *请求查询 */ var QueryMessage = (function (_super) { __extends(QueryMessage, _super); function QueryMessage(header, two, three) { _super.call(this, header instanceof RongIMLib.Header ? header : arguments.length == 3 ? RongIMLib.Type.QUERY : null); this.binaryHelper = new RongIMLib.BinaryHelper(); this._name = "QueryMessage"; if (arguments.length == 3) { this.data = typeof two == "string" ? this.binaryHelper.toMQttString(two) : two; this.topic = header; this.targetId = three; } } QueryMessage.prototype.messageLength = function () { var length = 0; length += this.binaryHelper.toMQttString(this.topic).length; length += this.binaryHelper.toMQttString(this.targetId).length; length += 2; length += this.data.length; return length; }; QueryMessage.prototype.writeMessage = function (Out) { var out = this.binaryHelper.convertStream(Out); out.writeUTF(this.topic); out.writeUTF(this.targetId); RetryableMessage.prototype.writeMessage.call(this, out); out.write(this.data); }; QueryMessage.prototype.readMessage = function (_in, msgLength) { var pos = 0; this.topic = _in.readUTF(); this.targetId = _in.readUTF(); pos += this.binaryHelper.toMQttString(this.topic).length; pos += this.binaryHelper.toMQttString(this.targetId).length; this.readMessage.apply(this, arguments); pos += 2; this.data = new Array(msgLength - pos); _in.read(this.data); }; QueryMessage.prototype.setTopic = function (x) { this.topic = x; }; QueryMessage.prototype.setData = function (x) { this.data = x; }; QueryMessage.prototype.setTargetId = function (x) { this.targetId = x; }; QueryMessage.prototype.getTopic = function () { return this.topic; }; QueryMessage.prototype.getData = function () { return this.data; }; QueryMessage.prototype.getTargetId = function () { return this.targetId; }; return QueryMessage; })(RetryableMessage); RongIMLib.QueryMessage = QueryMessage; /** *请求查询确认 */ var QueryConMessage = (function (_super) { __extends(QueryConMessage, _super); function QueryConMessage(messageId) { _super.call(this, (messageId instanceof RongIMLib.Header) ? messageId : RongIMLib.Type.QUERYCON); this._name = "QueryConMessage"; if (!(messageId instanceof RongIMLib.Header)) { _super.prototype.setMessageId.call(this, messageId); } } return QueryConMessage; })(RetryableMessage); RongIMLib.QueryConMessage = QueryConMessage; /** *请求查询应答 */ var QueryAckMessage = (function (_super) { __extends(QueryAckMessage, _super); function QueryAckMessage(header) { _super.call(this, header); this._name = "QueryAckMessage"; this.binaryHelper = new RongIMLib.BinaryHelper(); } QueryAckMessage.prototype.readMessage = function (In, msgLength) { RetryableMessage.prototype.readMessage.call(this, In); this.date = In.readInt(); this.setStatus(In.read() * 256 + In.read()); if (msgLength > 0) { this.data = new Array(msgLength - 8); this.data = In.read(this.data); } }; QueryAckMessage.prototype.getData = function () { return this.data; }; QueryAckMessage.prototype.getStatus = function () { return this.status; }; QueryAckMessage.prototype.getDate = function () { return this.date; }; QueryAckMessage.prototype.setDate = function (x) { this.date = x; }; QueryAckMessage.prototype.setStatus = function (x) { this.status = x; }; QueryAckMessage.prototype.setData = function (x) { this.data = x; }; return QueryAckMessage; })(RetryableMessage); RongIMLib.QueryAckMessage = QueryAckMessage; })(RongIMLib || (RongIMLib = {})); /// var RongIMLib; (function (RongIMLib) { /** * 把消息对象写入流中 * 发送消息时用到 */ var MessageOutputStream = (function () { function MessageOutputStream(_out) { var binaryHelper = new RongIMLib.BinaryHelper(); this.out = binaryHelper.convertStream(_out); } MessageOutputStream.prototype.writeMessage = function (msg) { if (msg instanceof RongIMLib.BaseMessage) { msg.write(this.out); } }; return MessageOutputStream; })(); RongIMLib.MessageOutputStream = MessageOutputStream; /** * 流转换为消息对象 * 服务器返回消息时用到 */ var MessageInputStream = (function () { function MessageInputStream(In, isPolling) { if (!isPolling) { var _in = new RongIMLib.BinaryHelper().convertStream(In); this.flags = _in.readByte(); this._in = _in; } else { this.flags = In["headerCode"]; } this.header = new RongIMLib.Header(this.flags); this.isPolling = isPolling; this.In = In; } MessageInputStream.prototype.readMessage = function () { switch (this.header.getType()) { case 1: this.msg = new RongIMLib.ConnectMessage(this.header); break; case 2: this.msg = new RongIMLib.ConnAckMessage(this.header); break; case 3: this.msg = new RongIMLib.PublishMessage(this.header); this.msg.setSyncMsg(this.header.getSyncMsg()); break; case 4: this.msg = new RongIMLib.PubAckMessage(this.header); break; case 5: this.msg = new RongIMLib.QueryMessage(this.header); break; case 6: this.msg = new RongIMLib.QueryAckMessage(this.header); break; case 7: this.msg = new RongIMLib.QueryConMessage(this.header); break; case 9: case 11: case 13: this.msg = new RongIMLib.PingRespMessage(this.header); break; case 8: case 10: case 12: this.msg = new RongIMLib.PingReqMessage(this.header); break; case 14: this.msg = new RongIMLib.DisconnectMessage(this.header); break; default: throw new Error("No support for deserializing " + this.header.getType() + " messages"); } if (this.isPolling) { this.msg.init(this.In); } else { this.msg.read(this._in, this.In.length - 1); } return this.msg; }; return MessageInputStream; })(); RongIMLib.MessageInputStream = MessageInputStream; var Header = (function () { function Header(_type, _retain, _qos, _dup) { this.retain = false; this.qos = RongIMLib.Qos.AT_LEAST_ONCE; this.dup = false; this.syncMsg = false; if (_type && +_type == _type && arguments.length == 1) { this.retain = (_type & 1) > 0; this.qos = (_type & 6) >> 1; this.dup = (_type & 8) > 0; this.type = (_type >> 4) & 15; this.syncMsg = (_type & 8) == 8; } else { this.type = _type; this.retain = _retain; this.qos = _qos; this.dup = _dup; } } Header.prototype.getSyncMsg = function () { return this.syncMsg; }; Header.prototype.getType = function () { return this.type; }; Header.prototype.encode = function () { var me = this; switch (this.qos) { case RongIMLib.Qos[0]: me.qos = RongIMLib.Qos.AT_MOST_ONCE; break; case RongIMLib.Qos[1]: me.qos = RongIMLib.Qos.AT_LEAST_ONCE; break; case RongIMLib.Qos[2]: me.qos = RongIMLib.Qos.EXACTLY_ONCE; break; case RongIMLib.Qos[3]: me.qos = RongIMLib.Qos.DEFAULT; break; } var _byte = (this.type << 4); _byte |= this.retain ? 1 : 0; _byte |= this.qos << 1; _byte |= this.dup ? 8 : 0; return _byte; }; Header.prototype.toString = function () { return "Header [type=" + this.type + ",retain=" + this.retain + ",qos=" + this.qos + ",dup=" + this.dup + "]"; }; return Header; })(); RongIMLib.Header = Header; /** * 二进制帮助对象 */ var BinaryHelper = (function () { function BinaryHelper() { } BinaryHelper.prototype.writeUTF = function (str, isGetBytes) { var back = [], byteSize = 0; for (var i = 0, len = str.length; i < len; i++) { var code = str.charCodeAt(i); if (code >= 0 && code <= 127) { byteSize += 1; back.push(code); } else if (code >= 128 && code <= 2047) { byteSize += 2; back.push((192 | (31 & (code >> 6)))); back.push((128 | (63 & code))); } else if (code >= 2048 && code <= 65535) { byteSize += 3; back.push((224 | (15 & (code >> 12)))); back.push((128 | (63 & (code >> 6)))); back.push((128 | (63 & code))); } } for (var i = 0, len = back.length; i < len; i++) { if (back[i] > 255) { back[i] &= 255; } } if (isGetBytes) { return back; } if (byteSize <= 255) { return [0, byteSize].concat(back); } else { return [byteSize >> 8, byteSize & 255].concat(back); } }; BinaryHelper.prototype.readUTF = function (arr) { if (Object.prototype.toString.call(arr) == "[object String]") { return arr; } var UTF = "", _arr = arr; for (var i = 0, len = _arr.length; i < len; i++) { if (_arr[i] < 0) { _arr[i] += 256; } ; var one = _arr[i].toString(2), v = one.match(/^1+?(?=0)/); if (v && one.length == 8) { var bytesLength = v[0].length, // store = _arr[i].toString(2).slice(7 - bytesLength); store = ''; for (var st = 0; st < bytesLength; st++) { store += _arr[st + i].toString(2).slice(2); } UTF += String.fromCharCode(parseInt(store, 2)); i += bytesLength - 1; } else { UTF += String.fromCharCode(_arr[i]); } } return UTF; }; /** * [convertStream 将参数x转化为RongIMStream对象] * @param {any} x [参数] */ BinaryHelper.prototype.convertStream = function (x) { if (x instanceof RongIMStream) { return x; } else { return new RongIMStream(x); } }; BinaryHelper.prototype.toMQttString = function (str) { return this.writeUTF(str); }; return BinaryHelper; })(); RongIMLib.BinaryHelper = BinaryHelper; var RongIMStream = (function () { function RongIMStream(arr) { //当前流执行的起始位置 this.position = 0; //当前流写入的多少字节 this.writen = 0; this.poolLen = 0; this.binaryHelper = new BinaryHelper(); this.pool = arr; this.poolLen = arr.length; } RongIMStream.prototype.check = function () { return this.position >= this.pool.length; }; RongIMStream.prototype.readInt = function () { if (this.check()) { return -1; } var end = ""; for (var i = 0; i < 4; i++) { var t = this.pool[this.position++].toString(16); if (t.length == 1) { t = "0" + t; } end += t.toString(16); } return parseInt(end, 16); }; RongIMStream.prototype.readLong = function () { if (this.check()) { return -1; } var end = ""; for (var i = 0; i < 8; i++) { var t = this.pool[this.position++].toString(16); if (t.length == 1) { t = "0" + t; } end += t; } return parseInt(end, 16); }; RongIMStream.prototype.readTimestamp = function () { if (this.check()) { return -1; } var end = ""; for (var i = 0; i < 8; i++) { end += this.pool[this.position++].toString(16); } end = end.substring(2, 8); return parseInt(end, 16); }; RongIMStream.prototype.readUTF = function () { if (this.check()) { return -1; } var big = (this.readByte() << 8) | this.readByte(); return this.binaryHelper.readUTF(this.pool.subarray(this.position, this.position += big)); }; RongIMStream.prototype.readByte = function () { if (this.check()) { return -1; } var val = this.pool[this.position++]; if (val > 255) { val &= 255; } return val; }; RongIMStream.prototype.read = function (bytesArray) { if (bytesArray) { return this.pool.subarray(this.position, this.poolLen); } else { return this.readByte(); } }; RongIMStream.prototype.write = function (_byte) { var b = _byte; if (Object.prototype.toString.call(b).toLowerCase() == "[object array]") { try { this.pool = this.pool.concat(b); } catch (e) { [].push.apply(this.pool, b); } } else { if (+b == b) { if (b > 255) { b &= 255; } this.pool.push(b); this.writen++; } } return b; }; RongIMStream.prototype.writeChar = function (v) { if (+v != v) { throw new Error("writeChar:arguments type is error"); } this.write(v >> 8 & 255); this.write(v & 255); this.writen += 2; }; RongIMStream.prototype.writeUTF = function (str) { var val = this.binaryHelper.writeUTF(str); [].push.apply(this.pool, val); this.writen += val.length; }; RongIMStream.prototype.toComplements = function () { var _tPool = this.pool; for (var i = 0; i < this.poolLen; i++) { if (_tPool[i] > 128) { _tPool[i] -= 256; } } return _tPool; }; RongIMStream.prototype.getBytesArray = function (isCom) { if (isCom) { return this.toComplements(); } return this.pool; }; return RongIMStream; })(); RongIMLib.RongIMStream = RongIMStream; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var SocketTransportation = (function () { /** * [constructor] * @param {string} url [连接地址:包含token、version] */ function SocketTransportation(_socket) { //连接状态 true:已连接 false:未连接 this.connected = false; //是否关闭: true:已关闭 false:未关闭 this.isClose = false; //存放消息队列的临时变量 this.queue = []; this.empty = new Function; this._socket = _socket; return this; } /** * [createTransport 创建WebScoket对象] */ SocketTransportation.prototype.createTransport = function (url, method) { if (!url) { throw new Error("URL can't be empty"); } ; this.url = url; var depend = RongIMLib.RongIMClient._memoryStore.depend; var wsScheme = depend.wsScheme; var tpl = '{wsScheme}{url}'; url = RongIMLib.RongUtil.tplEngine(tpl, { wsScheme: wsScheme, url: url }); this.socket = new WebSocket(url); this.socket.binaryType = "arraybuffer"; this.addEvent(); return this.socket; }; /** * [send 传送消息流] * @param {ArrayBuffer} data [二进制消息流] */ SocketTransportation.prototype.send = function (data) { if (!this.connected && !this.isClose) { //当通道不可用时,加入消息队列 this.queue.push(data); return; } if (this.isClose) { this._socket.fire("StatusChanged", RongIMLib.ConnectionStatus.CONNECTION_CLOSED); return; } var stream = new RongIMLib.RongIMStream([]), msg = new RongIMLib.MessageOutputStream(stream); msg.writeMessage(data); var val = stream.getBytesArray(true); var binary = new Int8Array(val); this.socket.send(binary.buffer); return this; }; /** * [onData 通道返回数据时调用的方法,用来想上层传递服务器返回的二进制消息流] * @param {ArrayBuffer} data [二进制消息流] */ SocketTransportation.prototype.onData = function (data) { if (RongIMLib.MessageUtil.isArray(data)) { this._socket.onMessage(new RongIMLib.MessageInputStream(data).readMessage()); } else { this._socket.onMessage(new RongIMLib.MessageInputStream(RongIMLib.MessageUtil.ArrayFormInput(data)).readMessage()); } return ""; }; /** * [onClose 通道关闭时触发的方法] */ SocketTransportation.prototype.onClose = function (ev) { var me = this; me.isClose = true; me.socket = this.empty; RongIMLib.Bridge._client.clearHeartbeat(); if (ev.code == 1006 && !this._status) { var currentTime = new Date().getTime(); if (!me.connectedTime || (currentTime - me.connectedTime <= SocketTransportation.MinConnectTime)) { var host = RongIMLib.RongUtil.getUrlHost(me.url); RongIMLib.RongIMClient.invalidWsUrls.push(host); } me._socket.fire("StatusChanged", RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE); } else { me._status = 0; } }; /** * [onError 通道报错时触发的方法] * @param {any} error [抛出异常] */ SocketTransportation.prototype.onError = function (error) { this._socket.fire("StatusChanged", RongIMLib.ConnectionStatus.WEBSOCKET_ERROR); RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.L_WS_ERR_E, level: RongIMLib.LoggerLevel.E, type: RongIMLib.LoggerType.IM, content: { error: RongIMLib.ConnectionStatus.WEBSOCKET_ERROR, msg: 'SocketTransportation -> onError' } }); throw new Error(error); }; /** * [addEvent 为通道绑定事件] */ SocketTransportation.prototype.addEvent = function () { var self = this; self.socket.onopen = function () { self.connected = true; self.isClose = false; //通道可以用后,调用发送队列方法,把所有等得发送的消息发出 self.doQueue(); self._socket.fire("connect"); self.connectedTime = new Date().getTime(); }; self.socket.onmessage = function (ev) { //判断数据是不是字符串,如果是字符串那么就是flash传过来的。 if (typeof ev.data == "string") { self.onData(ev.data.split(",")); } else { self.onData(ev.data); } }; self.socket.onerror = function (ev) { self.onError(ev); }; self.socket.onclose = function (ev) { self.onClose(ev); }; }; /** * [doQueue 消息队列,把队列中消息发出] */ SocketTransportation.prototype.doQueue = function () { var self = this; for (var i = 0, len = self.queue.length; i < len; i++) { self.send(self.queue[i]); } }; /** * [disconnect 断开连接] */ SocketTransportation.prototype.disconnect = function (status) { var me = this; if (me.socket.readyState) { me.isClose = true; if (status) { me._status = status; } me.socket.close(); } }; /** * [reconnect 重新连接] */ SocketTransportation.prototype.reconnect = function () { this.disconnect(); this.createTransport(this.url); }; SocketTransportation.prototype.close = function () { this.socket.close(); }; // 最短链接时长(若 5000ms 内, ws 自动断开, 此 ws 地址置为不可用) SocketTransportation.MinConnectTime = 5000; return SocketTransportation; })(); RongIMLib.SocketTransportation = SocketTransportation; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var PollingTransportation = (function () { function PollingTransportation(socket) { this.empty = new Function; this.connected = false; this.pid = +new Date + Math.random() + ""; this.queue = []; this.socket = socket; return this; } PollingTransportation.prototype.createTransport = function (url, method) { if (!url) { throw new Error("Url is empty,Please check it!"); } ; this.url = url; var sid = RongIMLib.RongIMClient._storageProvider.getItem("sId" + RongIMLib.Navigation.Endpoint.userId), me = this; if (sid) { setTimeout(function () { me.onSuccess("{\"status\":0,\"userId\":\"" + RongIMLib.Navigation.Endpoint.userId + "\",\"headerCode\":32,\"messageId\":0,\"sessionid\":\"" + sid + "\"}"); me.connected = true; }, 500); return this; } this.getRequest(url, true); return this; }; PollingTransportation.prototype.requestFactory = function (url, method, multipart) { var reqest = this.XmlHttpRequest(); if (multipart) { reqest.multipart = true; } // reqest.timeout = 60000; reqest.open(method || "GET", RongIMLib.RongIMClient._memoryStore.depend.protocol + url); if (method == "POST" && "setRequestHeader" in reqest) { reqest.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=utf-8"); } return reqest; }; PollingTransportation.prototype.getRequest = function (url, isconnect) { var me = this; me.xhr = this.requestFactory(url + "&pid=" + encodeURIComponent(me.pid), "GET"); var timer = new RongIMLib.Timer({ timeout: 45000 }); if ("onload" in me.xhr) { me.xhr.onload = function () { timer.pause(); me.xhr.onload = me.empty; if (this.responseText == "lost params") { me.onError(); } else { me.onSuccess(this.responseText, isconnect); } }; me.xhr.onerror = function () { timer.pause(); me.disconnect(); }; } else { me.xhr.onreadystatechange = function () { timer.pause(); if (me.xhr.readyState == 4) { me.xhr.onreadystatechange = me.empty; if (/^(200|202)$/.test(me.xhr.status)) { me.onSuccess(me.xhr.responseText, isconnect); } else if (/^(400|403)$/.test(me.xhr.status)) { me.onError(); } else { me.disconnect(); } } }; } timer.resume(function () { me.onError(); }); me.xhr.send(); }; /** * [send 发送消息,Method:POST] * queue 为消息队列,待通道可用发送所有等待消息 * @param {string} data [需要传入comet格式数据,此处只负责通讯通道,数据转换在外层处理] */ PollingTransportation.prototype.send = function (data) { var me = this; var _send = me.sendxhr = this.requestFactory(RongIMLib.Navigation.Endpoint.host + "/websocket" + data.url + "&pid=" + encodeURIComponent(me.pid), "POST"); if ("onload" in _send) { _send.onload = function () { _send.onload = me.empty; me.onData(_send.responseText); }; _send.onerror = function () { _send.onerror = me.empty; }; } else { _send.onreadystatechange = function () { if (_send.readyState == 4) { this.onreadystatechange = this.empty; if (/^(202|200)$/.test(_send.status)) { me.onData(_send.responseText); } } }; } _send.send(JSON.stringify(data.data)); }; PollingTransportation.prototype.onData = function (data, header) { if (!data || data == "lost params") { return; } var self = this, val = JSON.parse(data); if (val.userId) { RongIMLib.Navigation.Endpoint.userId = val.userId; } if (header) { RongIMLib.RongIMClient._storageProvider.setItem("sId" + RongIMLib.Navigation.Endpoint.userId, header); } if (!RongIMLib.MessageUtil.isArray(val)) { val = [val]; } Array.forEach(val, function (m) { self.socket.fire("message", new RongIMLib.MessageInputStream(m, true).readMessage()); }); return ""; }; PollingTransportation.prototype.XmlHttpRequest = function () { var hasCORS = typeof XMLHttpRequest !== "undefined" && "withCredentials" in new XMLHttpRequest(), self = this; if ("undefined" != typeof XMLHttpRequest && hasCORS) { return new XMLHttpRequest(); } else if ("undefined" != typeof XDomainRequest) { return new XDomainRequest(); } else { return new ActiveXObject("Microsoft.XMLHTTP"); } }; PollingTransportation.prototype.onClose = function () { if (this.xhr) { if (this.xhr.onload) { this.xhr.onreadystatechange = this.xhr.onload = this.empty; } else { this.xhr.onreadystatechange = this.empty; } this.xhr.abort(); this.xhr = null; } if (this.sendxhr) { if (this.sendxhr.onload) { this.sendxhr.onreadystatechange = this.sendxhr.onload = this.empty; } else { this.sendxhr.onreadystatechange = this.empty; } this.sendxhr.abort(); this.sendxhr = null; } }; PollingTransportation.prototype.disconnect = function () { RongIMLib.RongIMClient._storageProvider.removeItem("sId" + RongIMLib.Navigation.Endpoint.userId); RongIMLib.RongIMClient._storageProvider.removeItem(RongIMLib.Navigation.Endpoint.userId + "msgId"); this.onClose(); }; PollingTransportation.prototype.reconnect = function () { this.disconnect(); this.createTransport(this.url); }; PollingTransportation.prototype.onSuccess = function (responseText, isconnect) { var txt = responseText.match(/"sessionid":"\S+?(?=")/); this.onData(responseText, txt ? txt[0].slice(13) : 0); if (/"headerCode":-32,/.test(responseText)) { RongIMLib.RongIMClient._storageProvider.removeItem("sId" + RongIMLib.Navigation.Endpoint.userId); RongIMLib.RongIMClient._storageProvider.removeItem(RongIMLib.Navigation.Endpoint.userId + "msgId"); return; } this.getRequest(RongIMLib.Navigation.Endpoint.host + "/pullmsg.js?sessionid=" + RongIMLib.RongIMClient._storageProvider.getItem("sId" + RongIMLib.Navigation.Endpoint.userId) + "×trap=" + encodeURIComponent(new Date().getTime() + Math.random() + "")); this.connected = true; isconnect && this.socket.fire("connect"); }; PollingTransportation.prototype.onError = function () { RongIMLib.RongIMClient._storageProvider.removeItem("sId" + RongIMLib.Navigation.Endpoint.userId); RongIMLib.RongIMClient._storageProvider.removeItem(RongIMLib.Navigation.Endpoint.userId + "msgId"); this.onClose(); if (this.connected) { this.connected = false; var code = RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE; this.socket.fire("disconnect", code); } }; PollingTransportation.prototype.close = function () { this.xhr.abort(); this.sendxhr = null; }; return PollingTransportation; })(); RongIMLib.PollingTransportation = PollingTransportation; })(RongIMLib || (RongIMLib = {})); //objectname映射 var typeMapping = { "RC:TxtMsg": "TextMessage", "RC:ImgMsg": "ImageMessage", "RC:VcMsg": "VoiceMessage", "RC:ImgTextMsg": "RichContentMessage", "RC:ReferenceMsg": "ReferenceMessage", "RC:FileMsg": "FileMessage", "RC:HQVCMsg": "HQVoiceMessage", "RC:GIFMsg": "GIFMessage", "RC:SightMsg": "SightMessage", "RC:LBSMsg": "LocationMessage", "RC:InfoNtf": "InformationNotificationMessage", "RC:ContactNtf": "ContactNotificationMessage", "RC:ProfileNtf": "ProfileNotificationMessage", "RC:CmdNtf": "CommandNotificationMessage", "RC:DizNtf": "DiscussionNotificationMessage", "RC:CmdMsg": "CommandMessage", "RC:TypSts": "TypingStatusMessage", "RC:CsChaR": "ChangeModeResponseMessage", "RC:CsHsR": "HandShakeResponseMessage", "RC:CsEnd": "TerminateMessage", "RC:CsSp": "SuspendMessage", "RC:CsUpdate": "CustomerStatusUpdateMessage", "RC:ReadNtf": "ReadReceiptMessage", "RC:VCAccept": "AcceptMessage", "RC:VCRinging": "RingingMessage", "RC:VCSummary": "SummaryMessage", "RC:VCHangup": "HungupMessage", "RC:VCInvite": "InviteMessage", "RC:VCModifyMedia": "MediaModifyMessage", "RC:VCModifyMem": "MemberModifyMessage", "RC:CsContact": "CustomerContact", "RC:PSImgTxtMsg": "PublicServiceRichContentMessage", "RC:PSMultiImgTxtMsg": "PublicServiceMultiRichContentMessage", "RC:GrpNtf": "GroupNotificationMessage", "RC:PSCmd": "PublicServiceCommandMessage", "RC:RcCmd": "RecallCommandMessage", "RC:SRSMsg": "SyncReadStatusMessage", "RC:RRReqMsg": "ReadReceiptRequestMessage", "RC:RRRspMsg": "ReadReceiptResponseMessage", "RCJrmf:RpMsg": "JrmfRedPacketMessage", "RCJrmf:RpOpendMsg": "JrmfRedPacketOpenedMessage", "RC:CombineMsg": "RCCombineMessage", "RC:chrmKVNotiMsg": "ChrmKVNotificationMessage", "RC:LogCmdMsg": "LogCommandMessage" }, //自定义消息类型 registerMessageTypeMapping = {}, HistoryMsgType = { 4: "qryCMsg", 2: "qryDMsg", 3: "qryGMsg", 1: "qryPMsg", 6: "qrySMsg", 7: "qryPMsg", 8: "qryPMsg", 5: "qryCMsg" }, disconnectStatus = { 1: 6 }; var RongIMLib; (function (RongIMLib) { // 业务层公共方法处理 var IMHandler = (function () { function IMHandler() { } IMHandler.isIncludeNavi = function (token) { var navMarkIndex = RongIMLib.RongUtil.indexOf(token, RongIMLib.RongIMClient.NavMarkInToken); var hasNavMark = navMarkIndex !== -1; return hasNavMark; }; IMHandler.getToken = function (token) { var isIncludeNavi = IMHandler.isIncludeNavi(token); if (isIncludeNavi) { var navMarkIndex = RongIMLib.RongUtil.indexOf(token, RongIMLib.RongIMClient.NavMarkInToken); ; token = token.substring(0, navMarkIndex + 1); } return token; }; IMHandler.getNavsByToken = function (token, protocol) { var isIncludeNavi = IMHandler.isIncludeNavi(token); var navUrlList = []; if (isIncludeNavi) { var navMarkIndex = RongIMLib.RongUtil.indexOf(token, RongIMLib.RongIMClient.NavMarkInToken); ; var navsText = token.substring(navMarkIndex + 1, token.length); var navDomains = navsText.split(RongIMLib.RongIMClient.NavSeparatorInToken); RongIMLib.RongUtil.forEach(navDomains, function (domain) { if (RongIMLib.RongUtil.isEmpty(domain)) { return; } var navUrl = RongIMLib.RongUtil.formatProtoclPath({ path: domain, protocol: protocol, sub: true }); navUrlList.push(navUrl); }); } return navUrlList; }; IMHandler.getConversationKey = function (type, id) { return type + '_' + id; }; return IMHandler; })(); RongIMLib.IMHandler = IMHandler; ; /** * 通道标识类 */ var Transportations = (function () { function Transportations() { } Transportations._TransportType = RongIMLib.Socket.WEBSOCKET; return Transportations; })(); RongIMLib.Transportations = Transportations; var SyncTimeUtil = (function () { function SyncTimeUtil() { } SyncTimeUtil.$getKey = function (message) { var client = RongIMLib.Bridge._client; var userId = client.userId; var direction = (message.messageDirection == 1 ? 'send' : 'receive'); var appkey = RongIMLib.RongIMClient._memoryStore.appKey; var tpl = '{appkey}_{userId}_{direction}box'; return RongIMLib.RongUtil.tplEngine(tpl, { appkey: appkey, userId: userId, direction: direction }); }; SyncTimeUtil.set = function (message) { var key = SyncTimeUtil.$getKey(message); var sentTime = message.sentTime; var storage = RongIMLib.RongIMClient._storageProvider; storage.setItem(key, sentTime); }; SyncTimeUtil.get = function () { var sent = SyncTimeUtil.$getKey({ messageDirection: RongIMLib.MessageDirection.SEND }); var received = SyncTimeUtil.$getKey({ messageDirection: RongIMLib.MessageDirection.RECEIVE }); var storage = RongIMLib.RongIMClient._storageProvider; return { sent: Number(storage.getItem(sent) || 0), received: Number(storage.getItem(received) || 0) }; }; return SyncTimeUtil; })(); RongIMLib.SyncTimeUtil = SyncTimeUtil; var MessageUtil = (function () { function MessageUtil() { } /** *4680000 为localstorage最小容量5200000字节的90%,超过90%将删除之前过早的存储 */ MessageUtil.checkStorageSize = function () { return JSON.stringify(localStorage).length < 4680000; }; MessageUtil.getFirstKey = function (obj) { var str = ""; for (var key in obj) { str = key; break; } return str; }; MessageUtil.isEmpty = function (obj) { var empty = true; for (var key in obj) { empty = false; break; } return empty; }; MessageUtil.ArrayForm = function (typearray) { if (Object.prototype.toString.call(typearray) == "[object ArrayBuffer]") { var arr = new Int8Array(typearray); return [].slice.call(arr); } return typearray; }; MessageUtil.ArrayFormInput = function (typearray) { if (Object.prototype.toString.call(typearray) == "[object ArrayBuffer]") { var arr = new Uint8Array(typearray); return arr; } return typearray; }; MessageUtil.indexOf = function (arr, item, from) { for (var l = arr.length, i = (from < 0) ? Math.max(0, +from) : from || 0; i < l; i++) { if (arr[i] == item) { return i; } } return -1; }; MessageUtil.isArray = function (obj) { return Object.prototype.toString.call(obj) == "[object Array]"; }; //遍历,只能遍历数组 MessageUtil.forEach = function (arr, func) { if ([].forEach) { return function (arr, func) { [].forEach.call(arr, func); }; } else { return function (arr, func) { for (var i = 0; i < arr.length; i++) { func.call(arr, arr[i], i, arr); } }; } }; MessageUtil.remove = function (array, func) { for (var i = 0, len = array.length; i < len; i++) { if (func(array[i])) { return array.splice(i, 1)[0]; } } return null; }; MessageUtil.int64ToTimestamp = function (obj, isDate) { if (obj.low === undefined) { return obj; } var low = obj.low; if (low < 0) { low += 0xffffffff + 1; } low = low.toString(16); var timestamp = parseInt(obj.high.toString(16) + "00000000".replace(new RegExp("0{" + low.length + "}$"), low), 16); if (isDate) { return new Date(timestamp); } return timestamp; }; // 下行消息状态位判断, 第 9 位为 disableNotification 开关( 上行为第 5 位 ) MessageUtil.isDisableNotification = function (status) { return Boolean(status & 0x100); }; //消息转换方法 MessageUtil.messageParser = function (entity, onReceived, offlineMsg) { var message = new RongIMLib.Message(), content = entity.content, de, objectName = entity.classname, val, isUseDef = false; try { if (RongIMLib.RongIMClient._memoryStore.depend.isPolling) { val = new RongIMLib.BinaryHelper().readUTF(content.offset ? MessageUtil.ArrayForm(content.buffer).slice(content.offset, content.limit) : content); de = JSON.parse(val); } else { val = new RongIMLib.BinaryHelper().readUTF(content.offset ? MessageUtil.ArrayFormInput(content.buffer).subarray(content.offset, content.limit) : content); de = JSON.parse(val); } } catch (ex) { de = val; isUseDef = true; RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.L_PARSE_MSG_E, level: RongIMLib.LoggerLevel.E, type: RongIMLib.LoggerType.IM, content: { stack: ex, msg: 'MessageUtil -> messageParser' } }); } var IMLib = RongIMLib; //映射为具体消息对象 if (objectName in typeMapping) { var typeName = typeMapping[objectName]; message.content = new IMLib[typeName](de); message.messageType = typeMapping[objectName]; } else if (objectName in registerMessageTypeMapping) { var typeName = registerMessageTypeMapping[objectName]; var regMsg = new IMLib.RongIMClient.RegisterMessage[typeName](de); if (isUseDef) { message.content = regMsg.decode(de); } else { message.content = regMsg; } message.messageType = registerMessageTypeMapping[objectName]; } else { message.content = new RongIMLib.UnknownMessage({ content: de, objectName: objectName }); message.messageType = "UnknownMessage"; } //根据实体对象设置message对象] var dateTime = MessageUtil.int64ToTimestamp(entity.dataTime); if (dateTime > 0) { message.sentTime = dateTime; } else { message.sentTime = +new Date; } message.senderUserId = entity.fromUserId; message.conversationType = entity.type; if (entity.fromUserId == RongIMLib.Bridge._client.userId) { message.targetId = entity.groupId; } else { message.targetId = (/^[234]$/.test(entity.type || entity.getType()) ? entity.groupId : message.senderUserId); } var selfUserId = RongIMLib.Bridge._client.userId; // 解决多端在线收自己发的消息时, messageDirection 为 2(接收), 导致未读数增加 var isSelfSend = entity.direction == 1 || message.senderUserId === selfUserId; if (isSelfSend) { message.messageDirection = RongIMLib.MessageDirection.SEND; message.senderUserId = RongIMLib.Bridge._client.userId; } else { message.messageDirection = RongIMLib.MessageDirection.RECEIVE; } // 自己给自己发的消息, messageDirection 为 2(接收) var isSelfToSelf = message.senderUserId === selfUserId && message.targetId === selfUserId; if (isSelfToSelf) { message.messageDirection = RongIMLib.MessageDirection.RECEIVE; } var receivedTime = new Date().getTime(); message.messageUId = entity.msgId; message.receivedTime = RongIMLib.MessageUtil.getCheckedTime(receivedTime); message.messageId = (message.conversationType + "_" + ~~(Math.random() * 0xffffff)); message.objectName = objectName; message.receivedStatus = RongIMLib.ReceivedStatus.READ; if ((entity.status & 2) == 2) { message.receivedStatus = RongIMLib.ReceivedStatus.RETRIEVED; } message.offLineMessage = offlineMsg ? true : false; if (!offlineMsg) { if (RongIMLib.RongIMClient._memoryStore.connectAckTime > message.sentTime) { message.offLineMessage = true; } } try { var status = MessageUtil.int64ToTimestamp(entity.status); message.disableNotification = MessageUtil.isDisableNotification(status); } catch (error) { message.disableNotification = false; } return message; }; MessageUtil.detectCMP = function (options) { options.error = options.fail; return RongIMLib.RongUtil.request(options); }; MessageUtil.setDeltaTime = function (serverTime) { try { RongIMLib.RongIMClient._memoryStore.deltaTime = new Date().getTime() - serverTime; } catch (e) { } }; MessageUtil.getDeltaTime = function () { var _memoryStore = RongIMLib.RongIMClient._memoryStore || {}; return _memoryStore.deltaTime || 0; }; MessageUtil.getCheckedTime = function (time) { var deltaTime = MessageUtil.getDeltaTime(); return time - deltaTime; }; //适配SSL // static schemeArrs: Array = [["http", "ws"], ["https", "wss"]]; MessageUtil.sign = { converNum: 1, msgNum: 1, isMsgStart: true, isConvStart: true }; return MessageUtil; })(); RongIMLib.MessageUtil = MessageUtil; /** * 工具类 */ var MessageIdHandler = (function () { function MessageIdHandler() { } MessageIdHandler.init = function () { this.messageId = +(RongIMLib.RongIMClient._storageProvider.getItem(RongIMLib.Navigation.Endpoint.userId + "msgId") || RongIMLib.RongIMClient._storageProvider.setItem(RongIMLib.Navigation.Endpoint.userId + "msgId", 0) || 0); }; MessageIdHandler.messageIdPlus = function (method) { RongIMLib.RongIMClient._memoryStore.depend.isPolling && this.init(); if (this.messageId >= 65535) { this.messageId = 0; } this.messageId++; RongIMLib.RongIMClient._memoryStore.depend.isPolling && RongIMLib.RongIMClient._storageProvider.setItem(RongIMLib.Navigation.Endpoint.userId + "msgId", this.messageId); return this.messageId; }; MessageIdHandler.clearMessageId = function () { this.messageId = 0; RongIMLib.RongIMClient._memoryStore.depend.isPolling && RongIMLib.RongIMClient._storageProvider.setItem(RongIMLib.Navigation.Endpoint.userId + "msgId", this.messageId); }; MessageIdHandler.getMessageId = function () { RongIMLib.RongIMClient._memoryStore.depend.isPolling && this.init(); return this.messageId; }; MessageIdHandler.messageId = 0; return MessageIdHandler; })(); RongIMLib.MessageIdHandler = MessageIdHandler; var ChrmKVCaches = (function () { function ChrmKVCaches() { this.time = 0; this.cache = {}; } ChrmKVCaches.prototype.setTime = function (time) { this.time = time; }; ChrmKVCaches.prototype.getTime = function () { return this.time; }; ChrmKVCaches.prototype.setValue = function (kvContent) { var key = kvContent.key, timestamp = kvContent.timestamp; this.cache[key] = this.cache[key] || {}; this.cache[key] = { value: kvContent.value, userId: kvContent.userId, isDeleted: false, timestamp: timestamp }; }; ChrmKVCaches.prototype.removeValue = function (kvContent) { var key = kvContent.key, timestamp = kvContent.timestamp; this.cache[key] = this.cache[key] || {}; var cache = this.cache[key]; this.cache[key] = RongIMLib.RongUtil.extend(cache, { isDeleted: true, userId: kvContent.userId, timestamp: timestamp }); }; ChrmKVCaches.prototype.getValue = function (key) { this.cache[key] = this.cache[key] || {}; var cache = this.cache[key]; return cache.isDeleted ? null : cache.value; }; ChrmKVCaches.prototype.getAllKV = function () { var kv = {}; RongIMLib.RongUtil.forEach(this.cache, function (item, key) { if (!item.isDeleted) { kv[key] = item.value; } }); return kv; }; ChrmKVCaches.prototype.getSetUserId = function (key) { this.cache[key] = this.cache[key] || {}; return this.cache[key].userId; }; ChrmKVCaches.prototype.isKeyExisted = function (key) { this.cache[key] = this.cache[key] || {}; var cache = this.cache[key]; var hasValue = !RongIMLib.RongUtil.isEmpty(cache.value); return hasValue && !cache.isDeleted; }; ChrmKVCaches.prototype.clear = function () { this.cache = {}; }; return ChrmKVCaches; })(); var chrmKVCaches = {}; var chrmKVProsumerCaches = {}; var getKVCache = function (chrmId) { var chrmKVCache = chrmKVCaches[chrmId]; if (!chrmKVCache) { chrmKVCache = chrmKVCaches[chrmId] = new ChrmKVCaches(); } return chrmKVCache; }; var getKVProsumer = function (chrmId) { var kvProsumer = chrmKVProsumerCaches[chrmId]; if (!kvProsumer) { kvProsumer = chrmKVProsumerCaches[chrmId] = new RongIMLib.RongUtil.Prosumer(); } return kvProsumer; }; var ChrmKVHandler = (function () { function ChrmKVHandler() { } ChrmKVHandler.pull = function (chrmId, time) { var prosumer = getKVProsumer(chrmId); var event = RongIMLib.RongIMClient._dataAccessProvider.pullChatroomEntry; prosumer.produce({ event: event, chrmId: chrmId, time: time }); prosumer.consume(function (params, next) { var event = params.event, chrmId = params.chrmId, time = params.time; var kvCache = getKVCache(chrmId); var currentTime = kvCache.getTime(); var isKVNeedUpdated = currentTime < time; if (isKVNeedUpdated) { event(chrmId, currentTime, { onSuccess: function (result) { ChrmKVHandler.setEntries(chrmId, result); next(); }, onError: next }); } else { next(); } }); }; ChrmKVHandler.setEntries = function (chrmId, entity) { var entries = entity.entries, isFullUpdate = entity.bFullUpdate, syncTime = entity.syncTime; var event = isFullUpdate ? ChrmKVHandler.setFullEntries : ChrmKVHandler.setIncreEntries; var kvCache = getKVCache(chrmId); syncTime = MessageUtil.int64ToTimestamp(syncTime); if (RongIMLib.RongUtil.isArray(entries)) { RongIMLib.RongUtil.forEach(entries, function (item) { var setTime = item.timestamp; if (!RongIMLib.RongUtil.isNumber(setTime)) { item.timestamp = MessageUtil.int64ToTimestamp(setTime); } }); } kvCache.setTime(syncTime); // 更新拉取时间 event(chrmId, entries); // 更新 kv 值 }; ChrmKVHandler.setEntry = function (chrmId, chatroomEntry, status, userId) { var kvCache = getKVCache(chrmId); var timestamp = chatroomEntry.timestamp || +new Date(); var isDelete = RongInnerTools.getChrmEntityByStatus(status).isDelete; var eventName = isDelete ? 'removeValue' : 'setValue'; kvCache[eventName]({ key: chatroomEntry.key, value: chatroomEntry.value, userId: userId, timestamp: timestamp }); }; ChrmKVHandler.setFullEntries = function (chrmId, entries) { var kvCache = getKVCache(chrmId); kvCache.clear(); RongIMLib.RongUtil.forEach(entries, function (entity) { entity.timestamp = MessageUtil.int64ToTimestamp(entity.timestamp); kvCache.setValue({ key: entity.key, value: entity.value, userId: entity.uid, timestamp: entity.timestamp }); }); }; ChrmKVHandler.setIncreEntries = function (chrmId, entries) { var kvCache = getKVCache(chrmId); var currentUserId = RongIMLib.RongIMClient.getInstance().getCurrentUserId(); var optEvent = function (entity, isOverwrite, eventName) { var key = entity.key, value = entity.value; var isLatestedKeySetBySelf = kvCache.getSetUserId(key) === currentUserId; var isKeyNotExist = !kvCache.isKeyExisted(key); /* 1. 需覆盖时, 不管 key 是否已存在, 都直接设置 2. 不覆盖时, 必须最后一次 key 为自己设置的或此 key 还未设置过, 才能继续 */ if (isOverwrite || isLatestedKeySetBySelf || isKeyNotExist) { kvCache[eventName]({ key: key, value: value, userId: entity.uid, timestamp: entity.timestamp }); } }; RongIMLib.RongUtil.forEach(entries, function (entity) { var entityContent = RongInnerTools.getChrmEntityByStatus(entity.status); var eventName = entityContent.isDelete ? 'removeValue' : 'setValue'; optEvent(entity, entityContent.isOverwrite, eventName); }); }; ChrmKVHandler.getEntityValue = function (chrmId, key) { var kvCache = getKVCache(chrmId); return kvCache.getValue(key); }; ChrmKVHandler.getAllEntityValue = function (chrmId) { var kvCache = getKVCache(chrmId); return kvCache.getAllKV(); }; ChrmKVHandler.isKeyValid = function (key) { return /^[A-Za-z0-9_=+-]+$/.test(key); }; return ChrmKVHandler; })(); RongIMLib.ChrmKVHandler = ChrmKVHandler; var AutoDeleteCode = 0x0001; var OverwriteCode = 0x0002; var DeleteOperationCode = 0x0004; var RongInnerTools = (function () { function RongInnerTools() { } RongInnerTools.convertUserStatus = function (entity) { entity = RongIMLib.RongUtil.rename(entity, { subUserId: 'userId' }); var status = JSON.parse(entity.status); var us = status.us; if (!us) { return entity; } entity.status = RongIMLib.RongUtil.rename(us, { o: 'online', 'p': 'platform', s: 'status' }); return entity; }; RongInnerTools.getChrmEntityStatus = function (entity, chatroomOpt) { var status = 0; // 是否自动清理 if (entity.isAutoDelete) { status = status | AutoDeleteCode; } // 是否覆盖 if (entity.isOverwrite) { status = status | OverwriteCode; } // 操作类型 switch (chatroomOpt) { case RongIMLib.ChatroomEntityOpt.DELETE: status = status | DeleteOperationCode; break; default: break; } return status; }; RongInnerTools.getChrmEntityByStatus = function (status) { var isDelete = !!(status & DeleteOperationCode); var entityOpt = isDelete ? RongIMLib.ChatroomEntityOpt.DELETE : RongIMLib.ChatroomEntityOpt.UPDATE; return { isAutoDelete: !!(status & AutoDeleteCode), isOverwrite: !!(status & OverwriteCode), entityOpt: entityOpt, isDelete: isDelete }; }; return RongInnerTools; })(); RongIMLib.RongInnerTools = RongInnerTools; var UnreadCountHandler = (function () { function UnreadCountHandler() { } UnreadCountHandler.getKey = function (type, targetId) { var selfId = RongIMLib.RongIMClient.getInstance().getCurrentUserId(); return RongIMLib.RongUtil.tplEngine(UnreadCountHandler.KeyTemp, { selfId: selfId, type: type, targetId: targetId }); }; UnreadCountHandler.getDetailByKey = function (key) { var detail = { count: 0, sentTime: 0 }; var value = RongIMLib.RongIMClient._storageProvider.getItem(key); if (!value) { return detail; } value += ''; var unreadItems = value.split('_'); var hasUnderline = unreadItems.length > 1; detail.count = Number(unreadItems[0]); if (hasUnderline) { detail.sentTime = Number(unreadItems[1]); } return detail; }; UnreadCountHandler.getDetail = function (type, targetId) { var key = UnreadCountHandler.getKey(type, targetId); var detail = UnreadCountHandler.getDetailByKey(key); return detail; }; UnreadCountHandler.set = function (type, id, count, sentTime) { var key = UnreadCountHandler.getKey(type, id); var value = sentTime ? RongIMLib.RongUtil.tplEngine(UnreadCountHandler.ValueTemp, { count: count, sentTime: sentTime }) : count; RongIMLib.RongIMClient._storageProvider.setItem(key, value); return count; }; UnreadCountHandler.add = function (type, id, plusCount, sentTime) { var detail = UnreadCountHandler.getDetail(type, id), count = detail.count, oldSentTime = detail.sentTime; if (sentTime && sentTime > oldSentTime) { count = count + plusCount; UnreadCountHandler.set(type, id, count, sentTime); } return count; }; UnreadCountHandler.get = function (type, id) { var detail = UnreadCountHandler.getDetail(type, id); return detail.count; }; UnreadCountHandler.getAll = function (types) { var total = 0; var selfId = RongIMLib.RongIMClient.getInstance().getCurrentUserId(); var setTotal = function (keyList) { RongIMLib.RongUtil.forEach(keyList, function (key) { var detail = UnreadCountHandler.getDetailByKey(key); total += detail.count; }); }; if (types) { RongIMLib.RongUtil.forEach(types, function (type) { var key = UnreadCountHandler.getKey(type, ''); var unreadKeys = RongIMLib.RongIMClient._storageProvider.getItemKeyList(key); setTotal(unreadKeys); }); } else { var key = UnreadCountHandler.getKey('', ''); var unreadKeys = RongIMLib.RongIMClient._storageProvider.getItemKeyList(key); setTotal(unreadKeys); } return total; }; UnreadCountHandler.remove = function (type, targetId) { var key = UnreadCountHandler.getKey(type, targetId); RongIMLib.RongIMClient._storageProvider.removeItem(key); }; UnreadCountHandler.clear = function () { var key = UnreadCountHandler.getKey('', ''); var keyList = RongIMLib.RongIMClient._storageProvider.getItemKeyList(key); RongIMLib.RongUtil.forEach(keyList, function (key) { RongIMLib.RongIMClient._storageProvider.removeItem(key); }); }; UnreadCountHandler.KeyTemp = 'cu{selfId}{type}{targetId}'; UnreadCountHandler.ValueTemp = '{count}_{sentTime}'; return UnreadCountHandler; })(); RongIMLib.UnreadCountHandler = UnreadCountHandler; var ConversationStatusStoreUserKey = '{appkey}{userId}constas'; var ConversationStatusPullTimeStoreKey = 'time'; var ConversationStatusManager = (function () { function ConversationStatusManager(option) { this.updatedStatus = []; // 更新的会话状态 this.statusShangeObserver = new RongIMLib.Observer(); this.pullProsumer = new RongIMLib.RongUtil.Prosumer(); var appkey = option.appkey, userId = option.userId; this.option = option; this.storageKey = RongIMLib.RongUtil.tplEngine(ConversationStatusStoreUserKey, { appkey: appkey, userId: userId }); } ConversationStatusManager.prototype._formatUpdatedStatus = function (status, type, targetId) { var updatedStatus = { conversationType: type, targetId: targetId }; delete status.isLastInAPull; return RongIMLib.RongUtil.extend(updatedStatus, status); }; ConversationStatusManager.prototype.watchChanged = function (event) { this.statusShangeObserver.add(event); }; ConversationStatusManager.prototype.set = function (type, targetId, status) { var currentStatus = this.get(type, targetId); var updateTime = status.updateTime, isLastInAPull = status.isLastInAPull; if (updateTime >= currentStatus.updateTime) { var allStatus = RongIMLib.RongUtil.Storage.get(this.storageKey) || {}; var conversationStoreKey = IMHandler.getConversationKey(type, targetId); var storeStatus = allStatus[conversationStoreKey] || {}; RongIMLib.RongUtil.forEach(status, function (val, key) { if (!RongIMLib.RongUtil.isUndefined(val)) { storeStatus[key] = val; } }); allStatus[conversationStoreKey] = storeStatus; RongIMLib.RongUtil.Storage.set(this.storageKey, allStatus); var updatedStatusItem = this._formatUpdatedStatus(status, type, targetId); this.updatedStatus.push(updatedStatusItem); RongIMLib.RongIMClient.getInstance().pottingConversation({ type: type, userId: targetId }); } isLastInAPull && this.statusShangeObserver.emit(this.updatedStatus); this.updatedStatus = []; }; ConversationStatusManager.prototype.get = function (type, targetId) { var allStatus = RongIMLib.RongUtil.Storage.get(this.storageKey) || {}; var conversationStoreKey = IMHandler.getConversationKey(type, targetId); var status = allStatus[conversationStoreKey] || {}; var notificationStatus = status.notificationStatus, isTop = status.isTop, updateTime = status.updateTime; return { notificationStatus: notificationStatus || RongIMLib.ConversationNotificationStatus.NOTIFY, isTop: isTop || false, updateTime: updateTime || 0 }; }; ConversationStatusManager.prototype.pull = function (option) { if (RongIMLib.RongIMClient._memoryStore.depend.isPolling) return; //长轮训关闭会话状态设置 option = option || {}; var self = this; var _a = this, server = _a.option.server, pullProsumer = _a.pullProsumer, storageKey = _a.storageKey; pullProsumer.produce(option); pullProsumer.consume(function (params, next) { var allStatus = RongIMLib.RongUtil.Storage.get(storageKey) || {}; var lastUpdateTime = allStatus[ConversationStatusPullTimeStoreKey] || 0; var updateTime = params.time, isForce = params.isForce; if (lastUpdateTime > updateTime && !isForce) { return next(); } server.pullConversationStatus(lastUpdateTime, { onStatus: function (type, id, conversationStatus) { self.set(type, id, conversationStatus); }, onSuccess: function (updateTime) { var allStatus = RongIMLib.RongUtil.Storage.get(storageKey) || {}; allStatus[ConversationStatusPullTimeStoreKey] = updateTime; // 更新拉取时间戳 RongIMLib.RongUtil.Storage.set(self.storageKey, allStatus); next(); }, onError: next }); }); }; return ConversationStatusManager; })(); RongIMLib.ConversationStatusManager = ConversationStatusManager; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var MessageContent = (function () { function MessageContent(data) { throw new Error("This method is abstract, you must implement this method in inherited class."); } MessageContent.obtain = function () { throw new Error("This method is abstract, you must implement this method in inherited class."); }; return MessageContent; })(); RongIMLib.MessageContent = MessageContent; var NotificationMessage = (function (_super) { __extends(NotificationMessage, _super); function NotificationMessage() { _super.apply(this, arguments); } return NotificationMessage; })(MessageContent); RongIMLib.NotificationMessage = NotificationMessage; var StatusMessage = (function (_super) { __extends(StatusMessage, _super); function StatusMessage() { _super.apply(this, arguments); } return StatusMessage; })(MessageContent); RongIMLib.StatusMessage = StatusMessage; var ModelUtil = (function () { function ModelUtil() { } ModelUtil.modelClone = function (object) { var obj = {}; for (var item in object) { if (item != "messageName" && "encode" != item) { obj[item] = object[item]; } } return obj; }; ModelUtil.modleCreate = function (fields, msgType) { // if (fields.length < 1) { // throw new Error("Array is empty -> registerMessageType.modleCreate"); // } var Object = function (message) { var me = this; for (var index in fields) { me[fields[index]] = message[fields[index]]; } Object.prototype.messageName = msgType; Object.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; }; return Object; }; return ModelUtil; })(); RongIMLib.ModelUtil = ModelUtil; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var CustomerStatusMessage = (function () { function CustomerStatusMessage(message) { this.messageName = "CustomerStatusMessage"; this.status = message.status; } CustomerStatusMessage.obtain = function () { return null; }; CustomerStatusMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return CustomerStatusMessage; })(); RongIMLib.CustomerStatusMessage = CustomerStatusMessage; /** * 客服转换响应消息的类型名 */ var ChangeModeResponseMessage = (function () { function ChangeModeResponseMessage(message) { this.messageName = "ChangeModeResponseMessage"; this.code = message.code; this.data = message.data; this.msg = message.msg; } ChangeModeResponseMessage.obtain = function () { return null; }; ChangeModeResponseMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ChangeModeResponseMessage; })(); RongIMLib.ChangeModeResponseMessage = ChangeModeResponseMessage; /** * 客服转换消息的类型名 * 此消息不计入未读消息数 */ var ChangeModeMessage = (function () { function ChangeModeMessage(message) { this.messageName = "ChangeModeMessage"; this.uid = message.uid; this.sid = message.sid; this.pid = message.pid; } ChangeModeMessage.obtain = function () { return null; }; ChangeModeMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ChangeModeMessage; })(); RongIMLib.ChangeModeMessage = ChangeModeMessage; var CustomerStatusUpdateMessage = (function () { function CustomerStatusUpdateMessage(message) { this.messageName = "CustomerStatusUpdateMessage"; this.serviceStatus = message.serviceStatus; this.sid = message.sid; } CustomerStatusUpdateMessage.obtain = function () { return null; }; CustomerStatusUpdateMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return CustomerStatusUpdateMessage; })(); RongIMLib.CustomerStatusUpdateMessage = CustomerStatusUpdateMessage; var HandShakeMessage = (function () { function HandShakeMessage(message) { this.messageName = "HandShakeMessage"; if (message) { this.requestInfo = message.requestInfo; this.userInfo = message.userInfo; } } HandShakeMessage.obtain = function () { return null; }; HandShakeMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return HandShakeMessage; })(); RongIMLib.HandShakeMessage = HandShakeMessage; var CustomerContact = (function () { function CustomerContact(message) { this.messageName = "CustomerContact"; this.page = message.page; this.nickName = message.nickName; this.routingInfo = message.routingInfo; this.info = message.info; this.requestInfo = message.requestInfo; } CustomerContact.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return CustomerContact; })(); RongIMLib.CustomerContact = CustomerContact; var EvaluateMessage = (function () { function EvaluateMessage(message) { this.messageName = "EvaluateMessage"; this.uid = message.uid; this.sid = message.sid; this.pid = message.pid; this.source = message.source; this.suggest = message.suggest; this.isresolve = message.isresolve; this.type = message.type; } EvaluateMessage.obtain = function () { return null; }; EvaluateMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return EvaluateMessage; })(); RongIMLib.EvaluateMessage = EvaluateMessage; /** * 客服握手响应消息的类型名 */ var HandShakeResponseMessage = (function () { function HandShakeResponseMessage(message) { this.messageName = "HandShakeResponseMessage"; this.msg = message.msg; this.status = message.status; this.data = message.data; } HandShakeResponseMessage.obtain = function () { return null; }; HandShakeResponseMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return HandShakeResponseMessage; })(); RongIMLib.HandShakeResponseMessage = HandShakeResponseMessage; var SuspendMessage = (function () { function SuspendMessage(message) { this.messageName = "SuspendMessage"; this.uid = message.uid; this.sid = message.sid; this.pid = message.pid; } SuspendMessage.obtain = function () { return null; }; SuspendMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return SuspendMessage; })(); RongIMLib.SuspendMessage = SuspendMessage; var TerminateMessage = (function () { function TerminateMessage(message) { this.messageName = "TerminateMessage"; this.code = message.code; this.msg = message.msg; this.sid = message.sid; } TerminateMessage.obtain = function () { return null; }; TerminateMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return TerminateMessage; })(); RongIMLib.TerminateMessage = TerminateMessage; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var IsTypingStatusMessage = (function () { function IsTypingStatusMessage(data) { this.messageName = "IsTypingStatusMessage"; var msg = data; } IsTypingStatusMessage.prototype.encode = function () { return undefined; }; IsTypingStatusMessage.prototype.getMessage = function () { return null; }; return IsTypingStatusMessage; })(); RongIMLib.IsTypingStatusMessage = IsTypingStatusMessage; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var InformationNotificationMessage = (function () { function InformationNotificationMessage(message) { this.messageName = "InformationNotificationMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> InformationNotificationMessage."); } this.message = message.message; this.extra = message.extra; if (message.user) { this.user = message.user; } } InformationNotificationMessage.obtain = function (message) { return new InformationNotificationMessage({ message: message, extra: "" }); }; InformationNotificationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return InformationNotificationMessage; })(); RongIMLib.InformationNotificationMessage = InformationNotificationMessage; var CommandMessage = (function () { function CommandMessage(message) { this.messageName = "CommandMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> CommandMessage."); } try { if (Object.prototype.toString.call(message.data) == "[object String]") { this.data = JSON.parse(message.data); } else { this.data = message.data; } } catch (e) { this.data = message.data; RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.A_INIT_CMD_MSG_E, level: RongIMLib.LoggerLevel.E, type: RongIMLib.LoggerType.IM, content: { stack: e, msg: message.data } }); } this.name = message.name; this.extra = message.extra; } CommandMessage.obtain = function (data) { return new CommandMessage({ data: data, extra: "" }); }; CommandMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return CommandMessage; })(); RongIMLib.CommandMessage = CommandMessage; var ContactNotificationMessage = (function () { function ContactNotificationMessage(message) { this.messageName = "ContactNotificationMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> ContactNotificationMessage."); } this.operation = message.operation; this.targetUserId = message.targetUserId; this.message = message.message; this.extra = message.extra; this.sourceUserId = message.sourceUserId; if (message.user) { this.user = message.user; } } ContactNotificationMessage.obtain = function (operation, sourceUserId, targetUserId, message) { return new InformationNotificationMessage({ operation: operation, sourceUserId: sourceUserId, targetUserId: targetUserId, message: message }); }; ContactNotificationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; ContactNotificationMessage.CONTACT_OPERATION_ACCEPT_RESPONSE = "ContactOperationAcceptResponse"; ContactNotificationMessage.CONTACT_OPERATION_REJECT_RESPONSE = "ContactOperationRejectResponse"; ContactNotificationMessage.CONTACT_OPERATION_REQUEST = "ContactOperationRequest"; return ContactNotificationMessage; })(); RongIMLib.ContactNotificationMessage = ContactNotificationMessage; var ProfileNotificationMessage = (function () { function ProfileNotificationMessage(message) { this.messageName = "ProfileNotificationMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> ProfileNotificationMessage."); } this.operation = message.operation; try { if (Object.prototype.toString.call(message.data) == "[object String]") { this.data = JSON.parse(message.data); } else { this.data = message.data; } } catch (e) { this.data = message.data; RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.A_INIT_PROFILE_MSG_E, level: RongIMLib.LoggerLevel.E, type: RongIMLib.LoggerType.IM, content: { stack: e, msg: message.data } }); } this.extra = message.extra; if (message.user) { this.user = message.user; } } ProfileNotificationMessage.obtain = function (operation, data) { return new ProfileNotificationMessage({ operation: operation, data: data }); }; ProfileNotificationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ProfileNotificationMessage; })(); RongIMLib.ProfileNotificationMessage = ProfileNotificationMessage; var CommandNotificationMessage = (function () { function CommandNotificationMessage(message) { this.messageName = "CommandNotificationMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> ProfileNotificationMessage."); } try { if (Object.prototype.toString.call(message.data) == "[object String]") { this.data = JSON.parse(message.data); } else { this.data = message.data; } } catch (e) { this.data = message.data; RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.A_INIT_CMD_NOTI_MSG_E, level: RongIMLib.LoggerLevel.E, type: RongIMLib.LoggerType.IM, content: { stack: e, msg: message.data } }); } this.name = message.name; this.extra = message.extra; if (message.user) { this.user = message.user; } } CommandNotificationMessage.obtain = function (name, data) { return new CommandNotificationMessage({ name: name, data: data, extra: "" }); }; CommandNotificationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return CommandNotificationMessage; })(); RongIMLib.CommandNotificationMessage = CommandNotificationMessage; var DiscussionNotificationMessage = (function () { function DiscussionNotificationMessage(message) { this.messageName = "DiscussionNotificationMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> DiscussionNotificationMessage."); } this.extra = message.extra; this.extension = message.extension; this.type = message.type; this.isHasReceived = message.isHasReceived; this.operation = message.operation; this.user = message.user; if (message.user) { this.user = message.user; } } DiscussionNotificationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return DiscussionNotificationMessage; })(); RongIMLib.DiscussionNotificationMessage = DiscussionNotificationMessage; var GroupNotificationMessage = (function () { function GroupNotificationMessage(msg) { this.messageName = "GroupNotificationMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> GroupNotificationMessage."); } msg.operatorUserId && (this.operatorUserId = msg.operatorUserId); msg.operation && (this.operation = msg.operation); msg.data && (this.data = msg.data); msg.message && (this.message = msg.message); msg.extra && (this.extra = msg.extra); } GroupNotificationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return GroupNotificationMessage; })(); RongIMLib.GroupNotificationMessage = GroupNotificationMessage; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var TextMessage = (function () { function TextMessage(message) { this.messageName = "TextMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> TextMessage."); } this.content = message.content; this.extra = message.extra; if (message.user) { this.user = message.user; } if (message.mentionedInfo) { this.mentionedInfo = message.mentionedInfo; } if (message.burnDuration) { this.burnDuration = message.burnDuration; } } TextMessage.obtain = function (text) { return new TextMessage({ extra: "", content: text }); }; TextMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return TextMessage; })(); RongIMLib.TextMessage = TextMessage; var TypingStatusMessage = (function () { function TypingStatusMessage(message) { this.messageName = "TypingStatusMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> TypingStatusMessage."); } this.typingContentType = message.typingContentType; this.data = message.data; } TypingStatusMessage.obtain = function (typingContentType, data) { return new TypingStatusMessage({ typingContentType: typingContentType, data: data }); }; TypingStatusMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return TypingStatusMessage; })(); RongIMLib.TypingStatusMessage = TypingStatusMessage; var ReadReceiptMessage = (function () { function ReadReceiptMessage(message) { this.messageName = "ReadReceiptMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> ReadReceiptMessage."); } this.lastMessageSendTime = message.lastMessageSendTime; this.messageUId = message.messageUId; this.type = message.type; } ReadReceiptMessage.obtain = function (messageUId, lastMessageSendTime, type) { return new ReadReceiptMessage({ messageUId: messageUId, lastMessageSendTime: lastMessageSendTime, type: type }); }; ReadReceiptMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ReadReceiptMessage; })(); RongIMLib.ReadReceiptMessage = ReadReceiptMessage; var VoiceMessage = (function () { function VoiceMessage(message) { this.messageName = "VoiceMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> VoiceMessage."); } this.content = message.content; this.duration = message.duration; this.extra = message.extra; if (message.user) { this.user = message.user; } if (message.mentionedInfo) { this.mentionedInfo = message.mentionedInfo; } if (message.burnDuration) { this.burnDuration = message.burnDuration; } } VoiceMessage.obtain = function (base64Content, duration) { return new VoiceMessage({ content: base64Content, duration: duration, extra: "" }); }; VoiceMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return VoiceMessage; })(); RongIMLib.VoiceMessage = VoiceMessage; var RecallCommandMessage = (function () { function RecallCommandMessage(message) { this.messageName = "RecallCommandMessage"; this.messageUId = message.messageUId; this.conversationType = message.conversationType; this.targetId = message.targetId; this.sentTime = message.sentTime; message.extra && (this.extra = message.extra); message.user && (this.user = message.user); } RecallCommandMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return RecallCommandMessage; })(); RongIMLib.RecallCommandMessage = RecallCommandMessage; var ImageMessage = (function () { function ImageMessage(message) { this.messageName = "ImageMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> ImageMessage."); } this.content = message.content; this.imageUri = message.imageUri; message.extra && (this.extra = message.extra); message.user && (this.user = message.user); if (message.mentionedInfo) { this.mentionedInfo = message.mentionedInfo; } if (message.burnDuration) { this.burnDuration = message.burnDuration; } } ImageMessage.obtain = function (content, imageUri) { return new ImageMessage({ content: content, imageUri: imageUri, extra: "" }); }; ImageMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ImageMessage; })(); RongIMLib.ImageMessage = ImageMessage; var LocationMessage = (function () { function LocationMessage(message) { this.messageName = "LocationMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> LocationMessage."); } this.latitude = message.latitude; this.longitude = message.longitude; this.poi = message.poi; this.content = message.content; this.extra = message.extra; if (message.user) { this.user = message.user; } if (message.mentionedInfo) { this.mentionedInfo = message.mentionedInfo; } } LocationMessage.obtain = function (latitude, longitude, poi, content) { return new LocationMessage({ latitude: latitude, longitude: longitude, poi: poi, content: content, extra: "" }); }; LocationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return LocationMessage; })(); RongIMLib.LocationMessage = LocationMessage; var RichContentMessage = (function () { function RichContentMessage(message) { this.messageName = "RichContentMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> RichContentMessage."); } this.title = message.title; this.content = message.content; this.imageUri = message.imageUri; this.extra = message.extra; this.url = message.url; if (message.user) { this.user = message.user; } } RichContentMessage.obtain = function (title, content, imageUri, url) { return new RichContentMessage({ title: title, content: content, imageUri: imageUri, url: url, extra: "" }); }; RichContentMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return RichContentMessage; })(); RongIMLib.RichContentMessage = RichContentMessage; var JrmfRedPacketMessage = (function () { function JrmfRedPacketMessage(message) { this.messageName = 'JrmfRedPacketMessage'; message && (this.message = message); } JrmfRedPacketMessage.prototype.encode = function () { return ""; }; return JrmfRedPacketMessage; })(); RongIMLib.JrmfRedPacketMessage = JrmfRedPacketMessage; var JrmfRedPacketOpenedMessage = (function () { function JrmfRedPacketOpenedMessage(message) { this.messageName = 'JrmfRedPacketOpenedMessage'; message && (this.message = message); } JrmfRedPacketOpenedMessage.prototype.encode = function () { return ""; }; return JrmfRedPacketOpenedMessage; })(); RongIMLib.JrmfRedPacketOpenedMessage = JrmfRedPacketOpenedMessage; var UnknownMessage = (function () { function UnknownMessage(message) { this.messageName = "UnknownMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> UnknownMessage."); } this.message = message; } UnknownMessage.prototype.encode = function () { return ""; }; return UnknownMessage; })(); RongIMLib.UnknownMessage = UnknownMessage; var PublicServiceCommandMessage = (function () { function PublicServiceCommandMessage(message) { this.messageName = "PublicServiceCommandMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> PublicServiceCommandMessage."); } this.content = message.content; this.extra = message.extra; this.menuItem = message.menuItem; if (message.user) { this.user = message.user; } if (message.mentionedInfo) { this.mentionedInfo = message.mentionedInfo; } } PublicServiceCommandMessage.obtain = function (item) { return new PublicServiceCommandMessage({ content: "", command: "", menuItem: item, extra: "" }); }; PublicServiceCommandMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return PublicServiceCommandMessage; })(); RongIMLib.PublicServiceCommandMessage = PublicServiceCommandMessage; var PublicServiceMultiRichContentMessage = (function () { function PublicServiceMultiRichContentMessage(messages) { this.messageName = "PublicServiceMultiRichContentMessage"; this.richContentMessages = messages; } PublicServiceMultiRichContentMessage.prototype.encode = function () { return null; }; return PublicServiceMultiRichContentMessage; })(); RongIMLib.PublicServiceMultiRichContentMessage = PublicServiceMultiRichContentMessage; var SyncReadStatusMessage = (function () { function SyncReadStatusMessage(message) { this.messageName = "SyncReadStatusMessage"; message.lastMessageSendTime && (this.lastMessageSendTime = message.lastMessageSendTime); } SyncReadStatusMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return SyncReadStatusMessage; })(); RongIMLib.SyncReadStatusMessage = SyncReadStatusMessage; var ReadReceiptRequestMessage = (function () { function ReadReceiptRequestMessage(message) { this.messageName = "ReadReceiptRequestMessage"; message.messageUId && (this.messageUId = message.messageUId); } ReadReceiptRequestMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ReadReceiptRequestMessage; })(); RongIMLib.ReadReceiptRequestMessage = ReadReceiptRequestMessage; var ReadReceiptResponseMessage = (function () { function ReadReceiptResponseMessage(message) { this.messageName = "ReadReceiptResponseMessage"; message.receiptMessageDic && (this.receiptMessageDic = message.receiptMessageDic); } ReadReceiptResponseMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ReadReceiptResponseMessage; })(); RongIMLib.ReadReceiptResponseMessage = ReadReceiptResponseMessage; var PublicServiceRichContentMessage = (function () { function PublicServiceRichContentMessage(message) { this.messageName = "PublicServiceRichContentMessage"; this.richContentMessage = message; } PublicServiceRichContentMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return PublicServiceRichContentMessage; })(); RongIMLib.PublicServiceRichContentMessage = PublicServiceRichContentMessage; var FileMessage = (function () { function FileMessage(message) { this.messageName = "FileMessage"; message.name && (this.name = message.name); message.size && (this.size = message.size); message.type && (this.type = message.type); message.fileUrl && (this.fileUrl = message.fileUrl); message.extra && (this.extra = message.extra); message.user && (this.user = message.user); } FileMessage.obtain = function (msg) { return new FileMessage({ name: msg.name, size: msg.size, type: msg.type, fileUrl: msg.fileUrl }); }; FileMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return FileMessage; })(); RongIMLib.FileMessage = FileMessage; var HQVoiceMessage = (function () { function HQVoiceMessage(message) { this.messageName = "HQVoiceMessage"; this.type = message.type || 'aac'; message.localPath && (this.localPath = message.localPath); message.remoteUrl && (this.remoteUrl = message.remoteUrl); message.duration && (this.duration = message.duration); message.extra && (this.extra = message.extra); message.user && (this.user = message.user); message.burnDuration && (this.burnDuration = message.burnDuration); } HQVoiceMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return HQVoiceMessage; })(); RongIMLib.HQVoiceMessage = HQVoiceMessage; var AcceptMessage = (function () { function AcceptMessage(message) { this.messageName = "AcceptMessage"; this.mediaId = message.mediaId; this.callId = message.callId; this.mediaType = message.mediaType; this.mode = message.mode; this.subInfo = message.subInfo; } AcceptMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return AcceptMessage; })(); RongIMLib.AcceptMessage = AcceptMessage; var RingingMessage = (function () { function RingingMessage(message) { this.messageName = "RingingMessage"; this.callId = message.callId; } RingingMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return RingingMessage; })(); RongIMLib.RingingMessage = RingingMessage; var SummaryMessage = (function () { function SummaryMessage(message) { this.messageName = "SummaryMessage"; this.caller = message.caller; this.inviter = message.inviter; this.mediaType = message.mediaType; this.memberIdList = message.memberIdList; this.startTime = message.startTime; this.connectedTime = message.connectedTime; this.duration = message.duration; this.status = message.status; } SummaryMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return SummaryMessage; })(); RongIMLib.SummaryMessage = SummaryMessage; var HungupMessage = (function () { function HungupMessage(message) { this.messageName = "HungupMessage"; this.callId = message.callId; this.reason = message.reason; this.mode = message.mode; this.subInfo = message.subInfo; } HungupMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return HungupMessage; })(); RongIMLib.HungupMessage = HungupMessage; var InviteMessage = (function () { function InviteMessage(message) { this.messageName = "InviteMessage"; this.mediaId = message.mediaId; this.callId = message.callId; this.engineType = message.engineType; this.channelInfo = message.channelInfo; this.mediaType = message.mediaType; this.extra = message.extra; this.inviteUserIds = message.inviteUserIds; this.observerUserIds = message.observerUserIds; this.mode = message.mode; this.subInfo = message.subInfo; } InviteMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return InviteMessage; })(); RongIMLib.InviteMessage = InviteMessage; var MediaModifyMessage = (function () { function MediaModifyMessage(message) { this.messageName = "MediaModifyMessage"; this.callId = message.callId; this.mediaType = message.mediaType; this.mode = message.mode; this.subInfo = message.subInfo; } MediaModifyMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return MediaModifyMessage; })(); RongIMLib.MediaModifyMessage = MediaModifyMessage; var MemberModifyMessage = (function () { function MemberModifyMessage(message) { this.messageName = "MemberModifyMessage"; this.modifyMemType = message.modifyMemType; this.callId = message.callId; this.caller = message.caller; this.engineType = message.engineType; this.channelInfo = message.channelInfo; this.mediaType = message.mediaType; this.extra = message.extra; this.inviteUserIds = message.inviteUserIds; this.existedMemberStatusList = message.existedMemberStatusList; this.existedUserPofiles = message.existedUserPofiles; this.observerUserIds = message.observerUserIds; this.mode = message.mode; this.subInfo = message.subInfo; } MemberModifyMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return MemberModifyMessage; })(); RongIMLib.MemberModifyMessage = MemberModifyMessage; var RCCombineMessage = (function () { function RCCombineMessage(message) { this.messageName = "RCCombineMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> RCCombineMessage."); } this.nameList = message.nameList; this.remoteUrl = message.remoteUrl; if (message.user) { this.user = message.user; } this.summaryList = message.summaryList; } RCCombineMessage.obtain = function (remoteUrl, nameList, summaryList) { return new RCCombineMessage({ extra: "", content: remoteUrl, nameList: nameList, summaryList: summaryList }); }; RCCombineMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return RCCombineMessage; })(); RongIMLib.RCCombineMessage = RCCombineMessage; var ChrmKVNotificationMessage = (function () { function ChrmKVNotificationMessage(message) { this.messageName = "ChrmKVNotificationMessage"; message.key && (this.key = message.key); message.value && (this.value = message.value); message.type && (this.type = message.type); message.extra && (this.extra = message.extra); message.user && (this.user = message.user); } ChrmKVNotificationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ChrmKVNotificationMessage; })(); RongIMLib.ChrmKVNotificationMessage = ChrmKVNotificationMessage; var LogCommandMessage = (function () { function LogCommandMessage(message) { this.messageName = "LogCommandMessage"; message.uri && (this.uri = message.uri); message.logId && (this.logId = message.logId); message.platform && (this.platform = message.platform); message.packageName && (this.packageName = message.packageName); message.startTime && (this.startTime = message.startTime); message.endTime && (this.endTime = message.endTime); message.user && (this.user = message.user); } LogCommandMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return LogCommandMessage; })(); RongIMLib.LogCommandMessage = LogCommandMessage; var ReferenceMessage = (function () { function ReferenceMessage(message) { this.messageName = "ReferenceMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> ReferenceMessage."); } this.content = message.content; this.referMsgUserId = message.referMsgUserId; this.referMsg = message.referMsg; this.objName = message.objName; if (message.user) { this.user = message.user; } if (message.mentionedInfo) { this.mentionedInfo = message.mentionedInfo; } } ReferenceMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ReferenceMessage; })(); RongIMLib.ReferenceMessage = ReferenceMessage; var GIFMessage = (function () { function GIFMessage(message) { this.messageName = "GIFMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> ReferenceMessage."); } this.gifDataSize = message.gifDataSize; this.localPath = message.localPath; this.remoteUrl = message.remoteUrl; this.width = message.width; this.height = message.height; if (message.user) { this.user = message.user; } if (message.mentionedInfo) { this.mentionedInfo = message.mentionedInfo; } } GIFMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return GIFMessage; })(); RongIMLib.GIFMessage = GIFMessage; var SightMessage = (function () { function SightMessage(message) { this.messageName = "SightMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> ReferenceMessage."); } this.sightUrl = message.sightUrl; this.content = message.content; this.duration = message.duration; this.size = message.size; this.name = message.name; if (message.user) { this.user = message.user; } if (message.mentionedInfo) { this.mentionedInfo = message.mentionedInfo; } } SightMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return SightMessage; })(); RongIMLib.SightMessage = SightMessage; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var ChannelInfo = (function () { function ChannelInfo(Id, Key) { this.Id = Id; this.Key = Key; } return ChannelInfo; })(); RongIMLib.ChannelInfo = ChannelInfo; var UserStatus = (function () { function UserStatus(platform, online, status) { this.platform = platform; this.online = online; this.status = status; } return UserStatus; })(); RongIMLib.UserStatus = UserStatus; var MentionedInfo = (function () { function MentionedInfo(type, userIdList, mentionedContent) { } return MentionedInfo; })(); RongIMLib.MentionedInfo = MentionedInfo; var DeleteMessage = (function () { function DeleteMessage(msgId, msgDataTime, direct) { this.msgId = msgId; this.msgDataTime = msgDataTime; this.direct = direct; } return DeleteMessage; })(); RongIMLib.DeleteMessage = DeleteMessage; var CustomServiceConfig = (function () { function CustomServiceConfig(isBlack, companyName, companyUrl) { } return CustomServiceConfig; })(); RongIMLib.CustomServiceConfig = CustomServiceConfig; var CustomServiceSession = (function () { function CustomServiceSession(uid, cid, pid, isQuited, type, adminHelloWord, adminOfflineWord) { } return CustomServiceSession; })(); RongIMLib.CustomServiceSession = CustomServiceSession; var Conversation = (function () { function Conversation(conversationTitle, conversationType, draft, isTop, latestMessage, latestMessageId, notificationStatus, objectName, receivedStatus, receivedTime, senderUserId, senderUserName, sentStatus, sentTime, targetId, unreadMessageCount, senderPortraitUri, isHidden, mentionedMsg, hasUnreadMention, _readTime) { this.conversationTitle = conversationTitle; this.conversationType = conversationType; this.draft = draft; this.isTop = isTop; this.latestMessage = latestMessage; this.latestMessageId = latestMessageId; this.notificationStatus = notificationStatus; this.objectName = objectName; this.receivedStatus = receivedStatus; this.receivedTime = receivedTime; this.senderUserId = senderUserId; this.senderUserName = senderUserName; this.sentStatus = sentStatus; this.sentTime = sentTime; this.targetId = targetId; this.unreadMessageCount = unreadMessageCount; this.senderPortraitUri = senderPortraitUri; this.isHidden = isHidden; this.mentionedMsg = mentionedMsg; this.hasUnreadMention = hasUnreadMention; this._readTime = _readTime; } Conversation.prototype.setTop = function () { RongIMLib.RongIMClient._dataAccessProvider.addConversation(this, { onSuccess: function (data) { } }); }; return Conversation; })(); RongIMLib.Conversation = Conversation; var Discussion = (function () { function Discussion(creatorId, id, memberIdList, name, isOpen) { this.creatorId = creatorId; this.id = id; this.memberIdList = memberIdList; this.name = name; this.isOpen = isOpen; } return Discussion; })(); RongIMLib.Discussion = Discussion; var Group = (function () { function Group(id, name, portraitUri) { this.id = id; this.name = name; this.portraitUri = portraitUri; } return Group; })(); RongIMLib.Group = Group; var Message = (function () { function Message(content, conversationType, extra, objectName, messageDirection, messageId, receivedStatus, receivedTime, senderUserId, sentStatus, sentTime, targetId, messageType, messageUId, isLocalMessage, offLineMessage, receiptResponse, disableNotification) { this.content = content; this.conversationType = conversationType; this.extra = extra; this.objectName = objectName; this.messageDirection = messageDirection; this.messageId = messageId; this.receivedStatus = receivedStatus; this.receivedTime = receivedTime; this.senderUserId = senderUserId; this.sentStatus = sentStatus; this.sentTime = sentTime; this.targetId = targetId; this.messageType = messageType; this.messageUId = messageUId; this.isLocalMessage = isLocalMessage; this.offLineMessage = offLineMessage; this.receiptResponse = receiptResponse; this.disableNotification = disableNotification; } return Message; })(); RongIMLib.Message = Message; var MessageTag = (function () { function MessageTag(isCounted, isPersited) { this.isCounted = isCounted; this.isPersited = isPersited; } MessageTag.prototype.getMessageTag = function () { if (this.isCounted && this.isPersited) { return 3; } else if (this.isCounted) { return 2; } else if (this.isPersited) { return 1; } else if (!this.isCounted && !this.isPersited) { return 0; } }; MessageTag.getTagByStatus = function (status) { var statusMap = { 3: { isCounted: true, isPersited: true }, 2: { isCounted: true, isPersited: false }, 1: { isCounted: true, isPersited: true }, 0: { isCounted: true, isPersited: true } }; return statusMap[status] || statusMap[3]; }; return MessageTag; })(); RongIMLib.MessageTag = MessageTag; var PublicServiceMenuItem = (function () { function PublicServiceMenuItem(id, name, type, sunMenuItems, url) { this.id = id; this.name = name; this.type = type; this.sunMenuItems = sunMenuItems; this.url = url; } return PublicServiceMenuItem; })(); RongIMLib.PublicServiceMenuItem = PublicServiceMenuItem; // TODO: TBD var PublicServiceProfile = (function () { function PublicServiceProfile(conversationType, introduction, menu, name, portraitUri, publicServiceId, hasFollowed, isGlobal) { this.conversationType = conversationType; this.introduction = introduction; this.menu = menu; this.name = name; this.portraitUri = portraitUri; this.publicServiceId = publicServiceId; this.hasFollowed = hasFollowed; this.isGlobal = isGlobal; } return PublicServiceProfile; })(); RongIMLib.PublicServiceProfile = PublicServiceProfile; var UserInfo = (function () { function UserInfo(id, name, portraitUri) { this.id = id; this.name = name; this.portraitUri = portraitUri; } return UserInfo; })(); RongIMLib.UserInfo = UserInfo; var User = (function () { function User(id, token) { this.id = id; this.token = token; } return User; })(); RongIMLib.User = User; var Room = (function () { function Room(id, user, mode, broadcastType, type) { this.id = id; this.user = user; this.mode = mode; this.broadcastType = broadcastType; this.type = type; } return Room; })(); RongIMLib.Room = Room; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var ServerDataProvider = (function () { function ServerDataProvider() { this.userStatusListener = null; this.Conversation = { watcher: new RongIMLib.Observer(), watch: function (_watcher) { this.watcher.add(_watcher); var conversationList = RongIMLib.RongIMClient._memoryStore.conversationList; this.watcher.emit(conversationList); }, unwatch: function (_watcher) { this.watcher.remove(_watcher); }, _notify: function (conversationList) { this.watcher.emit(conversationList); } }; } ServerDataProvider.prototype.init = function (appKey, options) { new RongIMLib.FeatureDectector(options.appCallback); }; ServerDataProvider.prototype.connect = function (token, callback, userId, option) { var self = this; RongIMLib.Logger.reportRTLog(); option = option || {}; var isReconnect = option.isReconnect; var isIgnoreReportStart = option.isIgnoreReportStart; var StartReportTag = isReconnect ? RongIMLib.LoggerTag.IM.L_RECO_T : RongIMLib.LoggerTag.IM.A_CONN_T; var EndReportTag = isReconnect ? RongIMLib.LoggerTag.IM.L_RECO_R : RongIMLib.LoggerTag.IM.A_CONN_R; !isIgnoreReportStart && RongIMLib.Logger.writeLog({ tag: StartReportTag, level: RongIMLib.LoggerLevel.I, type: RongIMLib.LoggerType.IM, content: { "token": token } }); RongIMLib.RongIMClient.bridge = RongIMLib.Bridge.getInstance(); RongIMLib.RongIMClient._memoryStore.token = token; RongIMLib.RongIMClient._memoryStore.callback = callback; userId = userId || ''; option = option || {}; var isConnecting = false, isConnected = false; if (RongIMLib.Bridge._client && RongIMLib.Bridge._client.channel) { isConnecting = (RongIMLib.Bridge._client.channel.connectionStatus == RongIMLib.ConnectionStatus.CONNECTING); isConnected = (RongIMLib.Bridge._client.channel.connectionStatus == RongIMLib.ConnectionStatus.CONNECTED); } if (isConnected || isConnecting) { return; } var isGreater = (RongIMLib.RongIMClient.otherDeviceLoginCount > 5); if (isGreater) { callback.onError(RongIMLib.ConnectionStatus.ULTRALIMIT); return; } // 清除本地导航缓存 if (option.force) { RongIMLib.RongIMClient._storageProvider.removeItem('servers'); } RongIMLib.RongIMClient.bridge.setListener(); RongIMLib.RongIMClient.bridge.connect(RongIMLib.RongIMClient._memoryStore.appKey, token, { onSuccess: function (data) { setTimeout(function () { callback.onSuccess(data); RongIMLib.RongIMClient._memoryStore.networkUnavailable = false; RongIMLib.Logger.loggerCache.userId = data; RongIMLib.Logger.writeLog({ tag: EndReportTag, level: RongIMLib.LoggerLevel.I, type: RongIMLib.LoggerType.IM, content: { desc: 'connection succeeded' } }); self.conversationStatusManager = new RongIMLib.ConversationStatusManager({ appkey: RongIMLib.RongIMClient._memoryStore.appKey, userId: data, server: self }); self.conversationStatusManager.watchChanged(function (status) { RongIMLib.RongUtil.forEach(RongIMLib.RongIMClient.conversationStatusListeners, function (event) { event(status); }); }); self.conversationStatusManager.pull({ isForce: true }); }); var storage = RongIMLib.RongIMClient._storageProvider; var fullnavi = storage.getItem('fullnavi') || '{}'; try { fullnavi = JSON.parse(fullnavi); } catch (e) { fullnavi = {}; } var isAutoPull = fullnavi.openUS; isAutoPull && self.getVoipInfo({ onSuccess: function (VoipInfo) { try { VoipInfo && RongIMLib.RongUtil.forEach(RongIMLib.RongIMClient.settingListeners, function (listener) { listener({ VoipInfo: VoipInfo }); // 与 3.x 保持一致, 方便后续 3.x 兼容 }); if (VoipInfo) { var fullnavi_1 = storage.getItem('fullnavi') || '{}'; fullnavi_1 = JSON.parse(fullnavi_1); fullnavi_1.voipCallInfo = VoipInfo; storage.setItem('fullnavi', JSON.stringify(fullnavi_1)); } } catch (e) { } }, onError: function () { // do nothing } }); }, onError: function (e) { if (e == RongIMLib.ConnectionState.TOKEN_INCORRECT || !e) { setTimeout(function () { callback.onTokenIncorrect(); RongIMLib.Logger.writeLog({ tag: EndReportTag, level: RongIMLib.LoggerLevel.E, type: RongIMLib.LoggerType.IM, content: { ConnectionState: RongIMLib.ConnectionState.TOKEN_INCORRECT } }); }); } else { setTimeout(function () { callback.onError(e); RongIMLib.Logger.writeLog({ tag: EndReportTag, level: RongIMLib.LoggerLevel.E, type: RongIMLib.LoggerType.IM, content: { code: e } }); }); } } }); }; /* config.auto: 默认 false, true 启用自动重连,启用则为必选参数 config.rate: 重试频率 [100, 1000, 3000, 6000, 10000, 18000] 单位为毫秒,可选 config.url: 网络嗅探地址 [http(s)://]cdn.ronghub.com/RongIMLib-2.2.6.min.js 可选 */ ServerDataProvider.prototype.reconnect = function (callback, config) { var store = RongIMLib.RongIMClient._memoryStore; var token = store.token; if (!token) { throw new Error('reconnect: token is empty.'); } if (RongIMLib.Bridge._client && RongIMLib.Bridge._client.channel && RongIMLib.Bridge._client.channel.connectionStatus != RongIMLib.ConnectionStatus.CONNECTED && RongIMLib.Bridge._client.channel.connectionStatus != RongIMLib.ConnectionStatus.CONNECTING) { config = config || {}; var key = config.auto ? 'auto' : 'custom'; var handler = { auto: function () { var repeatConnect = function (options) { var step = options.step(); var done = 'done'; var url = options.url; var ping = function () { RongIMLib.RongUtil.request({ url: url, success: function () { options.done(); }, error: function () { repeat(); } }); }; var repeat = function () { var next = step(); if (next == 'done') { var error = RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE; options.done(error); return; } var timer = setTimeout(ping, next); RongIMLib.RongIMClient._memoryStore.autoReconnectTimer = timer; }; repeat(); }; var protocol = RongIMLib.RongIMClient._memoryStore.depend.protocol; var url = config.url || 'cdn.ronghub.com/RongIMLib-2.2.6.min.js'; var pathConfig = { protocol: protocol, path: url }; url = RongIMLib.RongUtil.formatProtoclPath(pathConfig); var rate = config.rate || [100, 1000, 3000, 6000, 10000, 18000]; //结束标识 rate.push('done'); var opts = { url: url, step: function () { var index = 0; return function () { var time = rate[index]; index++; return time; }; }, done: function (error) { if (error) { callback.onError(error); return; } RongIMLib.RongIMClient.connect(token, callback, null, { isIgnoreReportStart: true, isReconnect: true }); } }; repeatConnect(opts); }, custom: function () { RongIMLib.RongIMClient.connect(token, callback, null, { isIgnoreReportStart: true, isReconnect: true }); } }; handler[key](); } else { var _client = RongIMLib.Bridge._client || {}; var _channel = _client.channel || {}; RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.L_RECO_E, level: RongIMLib.LoggerLevel.E, type: RongIMLib.LoggerType.IM, content: { msg: { connectionStatus: _channel.connectionStatus }, action: 'reconnect' } }); } }; ServerDataProvider.prototype.logout = function () { RongIMLib.RongIMClient.bridge.disconnect(); RongIMLib.RongIMClient.bridge = null; }; ServerDataProvider.prototype.disconnect = function () { var timer = RongIMLib.RongIMClient._memoryStore.autoReconnectTimer; timer && clearTimeout(timer); RongIMLib.RongIMClient.bridge.disconnect(); }; ServerDataProvider.prototype.sendReceiptResponse = function (conversationType, targetId, sendCallback) { var rspkey = RongIMLib.Bridge._client.userId + conversationType + targetId + 'RECEIVED', me = this; if (RongIMLib.RongUtil.supportLocalStorage()) { var valObj = JSON.parse(RongIMLib.RongIMClient._storageProvider.getItem(rspkey)); if (valObj) { var vals = []; for (var key in valObj) { var tmp = {}; tmp[key] = valObj[key].uIds; valObj[key].isResponse || vals.push(tmp); } if (vals.length == 0) { sendCallback.onSuccess(); return; } var interval = setInterval(function () { if (vals.length == 1) { clearInterval(interval); } var obj = vals.splice(0, 1)[0]; var rspMsg = new RongIMLib.ReadReceiptResponseMessage({ receiptMessageDic: obj }); me.sendMessage(conversationType, targetId, rspMsg, { onSuccess: function (msg) { var senderUserId = RongIMLib.MessageUtil.getFirstKey(obj); valObj[senderUserId].isResponse = true; RongIMLib.RongIMClient._storageProvider.setItem(rspkey, JSON.stringify(valObj)); sendCallback.onSuccess(msg); }, onError: function (error, msg) { sendCallback.onError(error, msg); } }); }, 200); } else { sendCallback.onSuccess(); } } else { sendCallback.onSuccess(); } }; ServerDataProvider.prototype.sendTypingStatusMessage = function (conversationType, targetId, messageName, sendCallback) { var me = this; if (messageName in RongIMLib.RongIMClient.MessageParams) { me.sendMessage(conversationType, targetId, RongIMLib.TypingStatusMessage.obtain(RongIMLib.RongIMClient.MessageParams[messageName].objectName, ""), { onSuccess: function () { setTimeout(function () { sendCallback.onSuccess(); }); }, onError: function (errorCode) { setTimeout(function () { sendCallback.onError(errorCode, null); }); }, onBefore: function () { } }); } }; ServerDataProvider.prototype.sendRecallMessage = function (content, sendMessageCallback, params) { params = params || {}; var msg = new RongIMLib.RecallCommandMessage({ conversationType: content.conversationType, targetId: content.targetId, sentTime: content.sentTime, messageUId: content.messageUId, extra: content.extra, user: content.user }); this.sendMessage(content.conversationType, content.senderUserId, msg, sendMessageCallback, false, null, null, 2, params); }; ServerDataProvider.prototype.sendTextMessage = function (conversationType, targetId, content, sendMessageCallback) { var msgContent = RongIMLib.TextMessage.obtain(content); this.sendMessage(conversationType, targetId, msgContent, sendMessageCallback); }; ServerDataProvider.prototype.getRemoteHistoryMessages = function (conversationType, targetId, timestamp, count, callback, config) { if (count <= 1) { throw new Error("the count must be greater than 1."); } config = config || {}; var order = config.order || 0; var getKey = function () { return [conversationType, targetId, '_', order].join(''); }; var key = getKey(); if (!RongIMLib.RongUtil.isNumber(timestamp)) { timestamp = RongIMLib.RongIMClient._memoryStore.lastReadTime.get(key); } var memoryStore = RongIMLib.RongIMClient._memoryStore; var historyMessageLimit = memoryStore.historyMessageLimit; /* limit 属性: var limit = { time: '时间戳, 最后一次拉取时间', hasMore: '是否还有历史消息, bool 值' }; */ var limit = historyMessageLimit.get(key) || {}; var hasMore = limit.hasMore; var isFecth = (hasMore || limit.time != timestamp); // 正序获取消息时不做限制,防止有新消息导致无法获取 if (!isFecth && order == 0) { return callback.onSuccess([], hasMore); } var modules = new RongIMLib.RongIMClient.Protobuf.HistoryMsgInput(), self = this; modules.setTargetId(targetId); modules.setTime(timestamp); modules.setCount(count); modules.setOrder(order); var topic = HistoryMsgType[conversationType] || HistoryMsgType[RongIMLib.ConversationType.PRIVATE]; RongIMLib.RongIMClient.bridge.queryMsg(topic, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), targetId, { onSuccess: function (data) { var fetchTime = RongIMLib.MessageUtil.int64ToTimestamp(data.syncTime); RongIMLib.RongIMClient._memoryStore.lastReadTime.set(key, fetchTime); historyMessageLimit.set(key, { hasMore: !!data.hasMsg, time: fetchTime }); var list = data.list.reverse(), tempMsg = null, tempDir; var read = RongIMLib.SentStatus.READ; if (RongIMLib.RongUtil.supportLocalStorage()) { for (var i = 0, len = list.length; i < len; i++) { tempMsg = RongIMLib.MessageUtil.messageParser(list[i]); tempDir = JSON.parse(RongIMLib.RongIMClient._storageProvider.getItem(RongIMLib.Bridge._client.userId + tempMsg.messageUId + "SENT")); if (tempDir) { tempMsg.receiptResponse || (tempMsg.receiptResponse = {}); tempMsg.receiptResponse[tempMsg.messageUId] = tempDir.count; } tempMsg.sentStatus = read; tempMsg.targetId = targetId; list[i] = tempMsg; } } else { for (var i = 0, len = list.length; i < len; i++) { var tempMsg = RongIMLib.MessageUtil.messageParser(list[i]); tempMsg.sentStatus = read; list[i] = tempMsg; } } setTimeout(function () { callback.onSuccess(list, !!data.hasMsg); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }, "HistoryMessagesOuput"); }; ServerDataProvider.prototype.hasRemoteUnreadMessages = function (token, callback) { var xss = null; window.RCCallback = function (x) { setTimeout(function () { callback.onSuccess(!!+x.status); }); xss.parentNode.removeChild(xss); }; xss = document.createElement("script"); xss.src = RongIMLib.RongIMClient._memoryStore.depend.api + "/message/exist.js?appKey=" + encodeURIComponent(RongIMLib.RongIMClient._memoryStore.appKey) + "&token=" + encodeURIComponent(token) + "&callBack=RCCallback&_=" + RongIMLib.RongUtil.getTimestamp(); document.body.appendChild(xss); xss.onerror = function () { setTimeout(function () { callback.onError(RongIMLib.ErrorCode.UNKNOWN); }); xss.parentNode.removeChild(xss); }; }; ServerDataProvider.prototype.getRemoteConversationList = function (callback, conversationTypes, count) { var modules = new RongIMLib.RongIMClient.Protobuf.RelationsInput(), self = this; modules.setType(1); if (typeof count == 'undefined') { modules.setCount(0); } else { modules.setCount(count); } RongIMLib.RongIMClient.bridge.queryMsg(26, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (list) { if (list.info) { list.info = list.info.reverse(); for (var i = 0, len = list.info.length; i < len; i++) { RongIMLib.RongIMClient.getInstance().pottingConversation(list.info[i]); } } var conversations = RongIMLib.RongIMClient._memoryStore.conversationList; setTimeout(function () { if (conversationTypes) { return callback.onSuccess(self.filterConversations(conversationTypes, conversations)); } callback.onSuccess(conversations); }); }, onError: function (error) { callback.onError(error); } }, "RelationsOutput"); }; ServerDataProvider.prototype.addMemberToDiscussion = function (discussionId, userIdList, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.ChannelInvitationInput(); modules.setUsers(userIdList); RongIMLib.RongIMClient.bridge.queryMsg(0, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), discussionId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.createDiscussion = function (name, userIdList, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.CreateDiscussionInput(), self = this; modules.setName(name); RongIMLib.RongIMClient.bridge.queryMsg(1, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (discussId) { if (userIdList.length > 0) { self.addMemberToDiscussion(discussId, userIdList, { onSuccess: function () { }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); } setTimeout(function () { callback.onSuccess(discussId); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }, "CreateDiscussionOutput"); }; ServerDataProvider.prototype.getDiscussion = function (discussionId, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.ChannelInfoInput(); modules.setNothing(1); RongIMLib.RongIMClient.bridge.queryMsg(4, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), discussionId, { onSuccess: function (data) { setTimeout(function () { callback.onSuccess(data); }); }, onError: function (errorCode) { setTimeout(function () { callback.onError(errorCode); }); } }, "ChannelInfoOutput"); }; ServerDataProvider.prototype.quitDiscussion = function (discussionId, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.LeaveChannelInput(); modules.setNothing(1); RongIMLib.RongIMClient.bridge.queryMsg(7, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), discussionId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (errorCode) { setTimeout(function () { callback.onError(errorCode); }); } }); }; ServerDataProvider.prototype.removeMemberFromDiscussion = function (discussionId, userId, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.ChannelEvictionInput(); modules.setUser(userId); RongIMLib.RongIMClient.bridge.queryMsg(9, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), discussionId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (errorCode) { setTimeout(function () { callback.onError(errorCode); }); } }); }; ServerDataProvider.prototype.setDiscussionInviteStatus = function (discussionId, status, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.ModifyPermissionInput(); modules.setOpenStatus(status.valueOf()); RongIMLib.RongIMClient.bridge.queryMsg(11, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), discussionId, { onSuccess: function (x) { setTimeout(function () { callback.onSuccess(); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.setDiscussionName = function (discussionId, name, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RenameChannelInput(); modules.setName(name); RongIMLib.RongIMClient.bridge.queryMsg(12, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), discussionId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (errcode) { callback.onError(errcode); } }); }; ServerDataProvider.prototype.joinChatRoom = function (chatroomId, messageCount, callback) { RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.A_JCTR_T, level: RongIMLib.LoggerLevel.I, type: RongIMLib.LoggerType.IM, content: { chatroomId: chatroomId } }); var e = new RongIMLib.RongIMClient.Protobuf.ChrmInput(); e.setNothing(1); RongIMLib.Bridge._client.chatroomId = chatroomId; RongIMLib.RongIMClient.bridge.queryMsg(19, RongIMLib.MessageUtil.ArrayForm(e.toArrayBuffer()), chatroomId, { onSuccess: function () { var navi = RongIMLib.RongIMClient.getInstance().getNavi(); var isOpenKVStorage = navi.kvStorage; if (isOpenKVStorage) { RongIMLib.RongIMClient._dataAccessProvider.pullChatroomEntry(chatroomId, 0, { onSuccess: function (result) { RongIMLib.ChrmKVHandler.setEntries(chatroomId, result); setTimeout(function () { callback.onSuccess(); RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.A_JCTR_R, level: RongIMLib.LoggerLevel.I, type: RongIMLib.LoggerType.IM, content: { chatroomId: chatroomId } }); }); }, onError: function (errorCode) { setTimeout(function () { callback.onError(errorCode); RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.A_JCTR_R, level: RongIMLib.LoggerLevel.W, type: RongIMLib.LoggerType.IM, content: { chatroomId: chatroomId, error: errorCode } }); }); } }); } else { setTimeout(function () { RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.A_JCTR_R, level: RongIMLib.LoggerLevel.I, type: RongIMLib.LoggerType.IM, content: { chatroomId: chatroomId } }); callback.onSuccess(); }); } var modules = new RongIMLib.RongIMClient.Protobuf.ChrmPullMsg(); messageCount == 0 && (messageCount = -1); modules.setCount(messageCount); modules.setSyncTime(0); RongIMLib.Bridge._client.queryMessage("chrmPull", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), chatroomId, 1, { onSuccess: function (collection) { var list = collection.list; var sync = RongIMLib.MessageUtil.int64ToTimestamp(collection.syncTime); var latestMessage = list[list.length - 1]; if (latestMessage) { latestMessage = RongIMLib.MessageUtil.messageParser(latestMessage); sync = latestMessage.sentTime; } RongIMLib.RongIMClient._memoryStore.lastReadTime.set(chatroomId + RongIMLib.Bridge._client.userId + "CST", sync); var _client = RongIMLib.Bridge._client; for (var i = 0, mlen = list.length; i < mlen; i++) { var uId = 'R' + list[i].msgId; if (!(uId in _client.cacheMessageIds)) { _client.cacheMessageIds[uId] = true; var cacheUIds = RongIMLib.RongUtil.keys(_client.cacheMessageIds); if (cacheUIds.length > 10) { uId = cacheUIds[0]; delete _client.cacheMessageIds[uId]; } if (RongIMLib.RongIMClient._memoryStore.filterMessages.length > 0) { for (var j = 0, flen = RongIMLib.RongIMClient._memoryStore.filterMessages.length; j < flen; j++) { if (RongIMLib.RongIMClient.MessageParams[RongIMLib.RongIMClient._memoryStore.filterMessages[j]].objectName != list[i].classname) { _client.handler.onReceived(list[i]); } } } else { _client.handler.onReceived(list[i]); } } } }, onError: function (errcode) { setTimeout(function () { callback.onError(errcode); }); } }, "DownStreamMessages"); }, onError: function (error) { setTimeout(function () { RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.A_JCTR_R, level: RongIMLib.LoggerLevel.W, type: RongIMLib.LoggerType.IM, content: { chatroomId: chatroomId, error: error } }); callback.onError(error); }); } }, "ChrmOutput"); }; ServerDataProvider.prototype.getChatRoomInfo = function (chatRoomId, count, order, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.QueryChatroomInfoInput(); modules.setCount(count); modules.setOrder(order); RongIMLib.RongIMClient.bridge.queryMsg("queryChrmI", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), chatRoomId, { onSuccess: function (ret) { var userInfos = ret.userInfos; userInfos.forEach(function (item) { item.time = RongIMLib.MessageUtil.int64ToTimestamp(item.time); }); setTimeout(function () { callback.onSuccess(ret); }); }, onError: function (errcode) { setTimeout(function () { callback.onError(errcode); }); } }, "QueryChatroomInfoOutput"); }; ServerDataProvider.prototype.quitChatRoom = function (chatroomId, callback) { RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.A_QCTR_T, level: RongIMLib.LoggerLevel.I, type: RongIMLib.LoggerType.IM, content: { chatroomId: chatroomId } }); var e = new RongIMLib.RongIMClient.Protobuf.ChrmInput(); e.setNothing(1); RongIMLib.RongIMClient.bridge.queryMsg(17, RongIMLib.MessageUtil.ArrayForm(e.toArrayBuffer()), chatroomId, { onSuccess: function () { setTimeout(function () { RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.A_QCTR_R, level: RongIMLib.LoggerLevel.I, type: RongIMLib.LoggerType.IM, content: { chatroomId: chatroomId } }); callback.onSuccess(); }); }, onError: function (errcode) { setTimeout(function () { RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.A_QCTR_R, level: RongIMLib.LoggerLevel.W, type: RongIMLib.LoggerType.IM, content: { chatroomId: chatroomId, error: errcode } }); callback.onError(errcode); }); } }, "ChrmOutput"); }; ServerDataProvider.prototype.setChatroomHisMessageTimestamp = function (chatRoomId, timestamp) { RongIMLib.RongIMClient._memoryStore.lastReadTime.set('chrhis_' + chatRoomId, timestamp); }; ServerDataProvider.prototype.getChatRoomHistoryMessages = function (chatRoomId, count, order, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.HistoryMsgInput(); modules.setTargetId(chatRoomId); var timestamp = RongIMLib.RongIMClient._memoryStore.lastReadTime.get('chrhis_' + chatRoomId) || 0; modules.setTime(timestamp); modules.setCount(count); modules.setOrder(order); RongIMLib.RongIMClient.bridge.queryMsg(34, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (data) { RongIMLib.RongIMClient._memoryStore.lastReadTime.set('chrhis_' + chatRoomId, RongIMLib.MessageUtil.int64ToTimestamp(data.syncTime)); var list = data.list.reverse(); for (var i = 0, len = list.length; i < len; i++) { list[i] = RongIMLib.MessageUtil.messageParser(list[i]); } setTimeout(function () { callback.onSuccess(list, !!data.hasMsg); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }, "HistoryMsgOuput"); }; ServerDataProvider.prototype.setChatroomEntry = function (chatroomId, chatroomEntry, callback) { var opt = RongIMLib.ChatroomEntityOpt.UPDATE; var key = chatroomEntry.key, value = chatroomEntry.value; var isKeyInValid = !RongIMLib.RongUtil.isLengthLimit(key, RongIMLib.ChatroomEntityLimit.KEY, 1) || !RongIMLib.ChrmKVHandler.isKeyValid(key); var isValueInValid = !RongIMLib.RongUtil.isLengthLimit(value, RongIMLib.ChatroomEntityLimit.VALUE, 1); if (isKeyInValid || isValueInValid) { setTimeout(function () { callback.onError(RongIMLib.ErrorCode.BIZ_ERROR_INVALID_PARAMETER); }); } else { this.refreshChatroomEntry(chatroomId, chatroomEntry, opt, callback); } }; ServerDataProvider.prototype.forceSetChatroomEntry = function (chatroomId, chatroomEntry, callback) { chatroomEntry.isOverwrite = true; this.setChatroomEntry(chatroomId, chatroomEntry, callback); }; ServerDataProvider.prototype.removeChatroomEntry = function (chatroomId, chatroomEntry, callback) { var opt = RongIMLib.ChatroomEntityOpt.DELETE; var key = chatroomEntry.key; var isKeyInValid = !RongIMLib.RongUtil.isLengthLimit(key, RongIMLib.ChatroomEntityLimit.KEY, 1) || !RongIMLib.ChrmKVHandler.isKeyValid(key); if (isKeyInValid) { setTimeout(function () { callback.onError(RongIMLib.ErrorCode.BIZ_ERROR_INVALID_PARAMETER); }); } else { this.refreshChatroomEntry(chatroomId, chatroomEntry, opt, callback); } }; ServerDataProvider.prototype.forceRemoveChatroomEntry = function (chatroomId, chatroomEntry, callback) { chatroomEntry.isOverwrite = true; this.removeChatroomEntry(chatroomId, chatroomEntry, callback); }; ServerDataProvider.prototype.refreshChatroomEntry = function (chatroomId, chatroomEntry, chatroomEntryOpt, callback) { var modules, topic; var key = chatroomEntry.key, value = chatroomEntry.value || '', extra = chatroomEntry.notificationExtra; if (chatroomEntryOpt === RongIMLib.ChatroomEntityOpt.DELETE) { modules = new RongIMLib.RongIMClient.Protobuf.DeleteChrmKV(); topic = 'delKV'; } else { modules = new RongIMLib.RongIMClient.Protobuf.SetChrmKV(); topic = 'setKV'; } var status = RongIMLib.RongInnerTools.getChrmEntityStatus(chatroomEntry, chatroomEntryOpt); var currentUserId = RongIMLib.RongIMClient.getInstance().getCurrentUserId(); var entry = { key: key, value: value, uid: currentUserId }; if (status) { entry.status = status; } modules.setEntry(entry); if (chatroomEntry.isSendNotification) { modules.setBNotify(true); var msgModules = new RongIMLib.RongIMClient.Protobuf.UpStreamMessage(); var msg = new RongIMLib.ChrmKVNotificationMessage({ key: key, value: value, extra: extra, type: chatroomEntryOpt }); msgModules.setSessionId(RongIMLib.RongIMClient.MessageParams[msg.messageName].msgTag.getMessageTag()); msgModules.setClassname(RongIMLib.RongIMClient.MessageParams[msg.messageName].objectName); msgModules.setContent(msg.encode()); modules.setNotification(msgModules); // 默认设置为 聊天室消息 modules.setType(RongIMLib.ConversationType.CHATROOM); } RongIMLib.RongIMClient.bridge.queryMsg(topic, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), chatroomId, { onSuccess: function (ret) { var currentUserId = RongIMLib.RongIMClient.getInstance().getCurrentUserId(); RongIMLib.ChrmKVHandler.setEntry(chatroomId, chatroomEntry, status, currentUserId); setTimeout(function () { callback.onSuccess(!!ret); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }, 'ChrmOutput'); }; ServerDataProvider.prototype.getChatroomEntry = function (chatroomId, key, callback) { var value = RongIMLib.ChrmKVHandler.getEntityValue(chatroomId, key); setTimeout(function () { if (RongIMLib.RongUtil.isEmpty(value)) { callback.onError(RongIMLib.ErrorCode.CHATROOM_KEY_NOT_EXIST); } else { callback.onSuccess(value); } }); }; ServerDataProvider.prototype.getAllChatroomEntries = function (chatroomId, callback) { setTimeout(function () { var entries = RongIMLib.ChrmKVHandler.getAllEntityValue(chatroomId); callback.onSuccess(entries); }); }; ServerDataProvider.prototype.pullChatroomEntry = function (chatroomId, time, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.QueryChrmKV(); modules.setTimestamp(time); RongIMLib.RongIMClient.bridge.queryMsg('pullKV', RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), chatroomId, { onSuccess: function (data) { setTimeout(function () { callback.onSuccess(data); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }, "ChrmKVOutput"); }; ServerDataProvider.prototype.setMessageStatus = function (conversationType, targetId, timestamp, status, callback) { setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.addToBlacklist = function (userId, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.Add2BlackListInput(); modules.setUserId(userId); RongIMLib.RongIMClient.bridge.queryMsg(21, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.getBlacklist = function (callback) { var modules = new RongIMLib.RongIMClient.Protobuf.QueryBlackListInput(); modules.setNothing(1); RongIMLib.RongIMClient.bridge.queryMsg(23, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (list) { setTimeout(function () { callback.onSuccess(list); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }, "QueryBlackListOutput"); }; ServerDataProvider.prototype.getBlacklistStatus = function (userId, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.BlackListStatusInput(); modules.setUserId(userId); RongIMLib.RongIMClient.bridge.queryMsg(24, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function (status) { setTimeout(function () { callback.onSuccess(RongIMLib.BlacklistStatus[status]); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.removeFromBlacklist = function (userId, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RemoveFromBlackListInput(); modules.setUserId(userId); RongIMLib.RongIMClient.bridge.queryMsg(22, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.getFileToken = function (fileType, callback, fileName) { if (!(/(1|2|3|4)/.test(fileType.toString()))) { setTimeout(function () { callback.onError(RongIMLib.ErrorCode.QNTKN_FILETYPE_ERROR); }); return; } var fileName = RongIMLib.RongUtil.generateUploadFileName(fileType, fileName); // 获取上传地址 var domains = RongIMLib.RongIMClient._storageProvider.getItem('upload_domains') || '{}'; var modules = new RongIMLib.RongIMClient.Protobuf.GetQNupTokenInput(); modules.setType(fileType); modules.setKey(fileName); RongIMLib.RongIMClient.bridge.queryMsg(30, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (res) { setTimeout(function () { var data = RongIMLib.RongUtil.extend(JSON.parse(domains), res); callback.onSuccess(data); }); }, onError: function (errcode) { setTimeout(function () { callback.onError(errcode); }); } }, "GetQNupTokenOutput"); }; ServerDataProvider.prototype.getFileUrl = function (fileType, fileName, oriName, callback, data) { var data = data || {}; if (!(/(1|2|3|4)/.test(fileType.toString()))) { setTimeout(function () { callback.onError(RongIMLib.ErrorCode.QNTKN_FILETYPE_ERROR); }); return; } if (data.isBosRes) { callback.onSuccess(data); return; } var modules = new RongIMLib.RongIMClient.Protobuf.GetQNdownloadUrlInput(); modules.setType(fileType); modules.setKey(fileName); if (oriName) { modules.setFileName(oriName); } RongIMLib.RongIMClient.bridge.queryMsg(31, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (data) { setTimeout(function () { callback.onSuccess(data); }); }, onError: function (errcode) { setTimeout(function () { callback.onError(errcode); }); } }, "GetQNdownloadUrlOutput"); }; ServerDataProvider.prototype.getVoipInfo = function (callback) { if (RongIMLib.RongIMClient._memoryStore.depend.isPolling) return; //长轮训关闭实时配置,IE 现不支持音视频 // 获取最新值 return this.getPullSetting({ onSuccess: function (result) { result = result || {}; var items = result.items || []; var voipInfo = null; for (var i = 0, max = items.length; i < max; i++) { var item = items[i]; if (item.key === 'VoipInfo') { var value = item.value; if (RongIMLib.RongIMClient._memoryStore.depend.isPolling) { value = new RongIMLib.BinaryHelper().readUTF(value.offset ? RongIMLib.MessageUtil.ArrayForm(value.buffer).slice(value.offset, value.limit) : value); } else { value = new RongIMLib.BinaryHelper().readUTF(value.offset ? RongIMLib.MessageUtil.ArrayFormInput(value.buffer).subarray(value.offset, value.limit) : value); } voipInfo = value; } } callback.onSuccess(voipInfo); }, onError: callback.onError }, 0); }; ServerDataProvider.prototype.getPullSetting = function (callback, version) { var modules = new RongIMLib.RongIMClient.Protobuf.PullUserSettingInput(); version = version || parseInt(RongIMLib.RongIMClient.sdkver); modules.setVersion(version); RongIMLib.RongIMClient.bridge.queryMsg('pullUS', RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (result) { result = result || {}; result.version = RongIMLib.MessageUtil.int64ToTimestamp(result.version); setTimeout(function () { callback.onSuccess(result); }); }, onError: function (errcode) { setTimeout(function () { callback.onError(errcode); }); } }, 'PullUserSettingOutput'); }; ServerDataProvider.prototype.setOfflineMessageDuration = function (duration, callback) { this.getPullSetting({ onSuccess: function (result) { /** * GetQNupTokenOutput 第一位为 int64, 第二位为 string, 与设置离线消息一致 * 为避免修改 Protobuf 带来的更新成本. 仅复用, 不重新命名 */ var modules = new RongIMLib.RongIMClient.Protobuf.GetQNupTokenOutput(); var version = result.version; modules.setDeadline(version); modules.setToken(duration + ''); RongIMLib.RongIMClient.bridge.queryMsg('setOfflineMsgDur', RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (data) { setTimeout(function () { callback.onSuccess(data); }); }, onError: function (errcode) { setTimeout(function () { callback.onError(errcode); }); } }); }, onError: callback.onError }); }; /* methodType 1 : 多客服(客服后台使用); 2 : 消息撤回 params.userIds : 定向消息接收者 */ ServerDataProvider.prototype.sendMessage = function (conversationType, targetId, messageContent, sendCallback, mentiondMsg, pushText, appData, methodType, params) { if (!RongIMLib.Bridge._client.channel) { setTimeout(function () { sendCallback.onError(RongIMLib.ErrorCode.RC_NET_UNAVAILABLE, null); }); return; } if (!RongIMLib.Bridge._client.channel.socket.socket.connected) { setTimeout(function () { sendCallback.onError(RongIMLib.ErrorCode.TIMEOUT, null); }); throw new Error("connect is timeout! postion:sendMessage"); } params = params || {}; var isGroup = (conversationType == RongIMLib.ConversationType.DISCUSSION || conversationType == RongIMLib.ConversationType.GROUP); var modules = new RongIMLib.RongIMClient.Protobuf.UpStreamMessage(); var sessionId; if (mentiondMsg && isGroup) { sessionId = 7; params.disableNotification && (sessionId = sessionId | 0x10); modules.setSessionId(sessionId); } else { sessionId = RongIMLib.RongIMClient.MessageParams[messageContent.messageName].msgTag.getMessageTag(); params.disableNotification && (sessionId = sessionId | 0x10); modules.setSessionId(sessionId); } pushText && modules.setPushText(pushText); appData && modules.setAppData(appData); if (isGroup && messageContent.messageName == RongIMLib.RongIMClient.MessageType["ReadReceiptResponseMessage"]) { var rspMsg = messageContent; if (rspMsg.receiptMessageDic) { var ids = []; for (var key in rspMsg.receiptMessageDic) { ids.push(key); } modules.setUserId(ids); } } if (isGroup && messageContent.messageName == RongIMLib.RongIMClient.MessageType["SyncReadStatusMessage"]) { modules.setUserId(RongIMLib.Bridge._client.userId); } var userIds = params.userIds; if (userIds) { modules.setUserId(userIds); } var flag = 0; if (params.isPush || params.isVoipPush) { flag |= 0x01; } if (params.isFilerWhiteBlacklist) { flag |= 0x02; } modules.setConfigFlag(flag); modules.setClassname(RongIMLib.RongIMClient.MessageParams[messageContent.messageName].objectName); var encodedContent = messageContent.encode(); if (RongIMLib.RongUtil.getByteLength(encodedContent) > RongIMLib.RongIMClient.MaxMessageContentBytes) { setTimeout(function () { sendCallback.onError(RongIMLib.ErrorCode.RC_MSG_CONTENT_EXCEED_LIMIT); }); return; } modules.setContent(encodedContent); var content = modules.toArrayBuffer(); if (Object.prototype.toString.call(content) == "[object ArrayBuffer]") { content = [].slice.call(new Int8Array(content)); } var me = this, msg = new RongIMLib.Message(); var c = this.getConversation(conversationType, targetId); if (RongIMLib.RongIMClient.MessageParams[messageContent.messageName].msgTag.getMessageTag() == 3) { if (!c) { c = RongIMLib.RongIMClient.getInstance().createConversation(conversationType, targetId, ""); } c.sentTime = new Date().getTime(); c.sentStatus = RongIMLib.SentStatus.SENDING; c.senderUserName = ""; c.senderUserId = RongIMLib.Bridge._client.userId; c.notificationStatus = RongIMLib.ConversationNotificationStatus.DO_NOT_DISTURB; c.latestMessage = msg; c.unreadMessageCount = 0; RongIMLib.RongIMClient._dataAccessProvider.addConversation(c, { onSuccess: function (data) { } }); } RongIMLib.RongIMClient._memoryStore.converStore = c; msg.content = messageContent; msg.conversationType = conversationType; msg.senderUserId = RongIMLib.Bridge._client.userId; msg.objectName = RongIMLib.RongIMClient.MessageParams[messageContent.messageName].objectName; msg.targetId = targetId; msg.sentTime = new Date().getTime(); msg.messageDirection = RongIMLib.MessageDirection.SEND; msg.sentStatus = RongIMLib.SentStatus.SENT; msg.messageType = messageContent.messageName; msg.disableNotification = params.disableNotification || false; RongIMLib.RongIMClient.bridge.pubMsg(conversationType.valueOf(), content, targetId, { onSuccess: function (data) { if (data && data.timestamp) { RongIMLib.RongIMClient._memoryStore.lastReadTime.set('converST_' + RongIMLib.Bridge._client.userId + conversationType + targetId, data.timestamp); } if ((conversationType == RongIMLib.ConversationType.DISCUSSION || conversationType == RongIMLib.ConversationType.GROUP) && messageContent.messageName == RongIMLib.RongIMClient.MessageType["ReadReceiptRequestMessage"]) { var reqMsg = msg.content; var sentkey = RongIMLib.Bridge._client.userId + reqMsg.messageUId + "SENT"; RongIMLib.RongIMClient._storageProvider.setItem(sentkey, JSON.stringify({ count: 0, dealtime: data.timestamp, userIds: {} })); } if (RongIMLib.RongIMClient.MessageParams[msg.messageType].msgTag.getMessageTag() == 3) { var cacheConversation = RongIMLib.RongIMClient._memoryStore.converStore; cacheConversation.sentStatus = msg.sentStatus; cacheConversation.latestMessage = msg; me.updateConversation(cacheConversation); var Conversation = RongIMLib.RongIMClient._dataAccessProvider.Conversation; Conversation._notify(RongIMLib.RongIMClient._memoryStore.conversationList); RongIMLib.RongIMClient._dataAccessProvider.addMessage(conversationType, targetId, msg, { onSuccess: function (ret) { msg = ret; msg.messageUId = data.messageUId; msg.sentTime = data.timestamp; msg.sentStatus = RongIMLib.SentStatus.SENT; msg.messageId = data.messageId; RongIMLib.RongIMClient._dataAccessProvider.updateMessage(msg); }, onError: function () { } }); } setTimeout(function () { cacheConversation && me.updateConversation(cacheConversation); msg.sentTime = data.timestamp; msg.messageUId = data.messageUId; sendCallback.onSuccess(msg); }); }, onError: function (errorCode, _msg) { msg.sentStatus = RongIMLib.SentStatus.FAILED; if (_msg) { msg.messageUId = _msg.messageUId; msg.sentTime = _msg.sentTime; } if (RongIMLib.RongIMClient.MessageParams[msg.messageType].msgTag.getMessageTag() == 3) { RongIMLib.RongIMClient._memoryStore.converStore.latestMessage = msg; } RongIMLib.RongIMClient._dataAccessProvider.addMessage(conversationType, targetId, msg, { onSuccess: function (ret) { msg.messageId = ret.messageId; RongIMLib.RongIMClient._dataAccessProvider.updateMessage(msg); }, onError: function () { } }); setTimeout(function () { sendCallback.onError(errorCode, msg); }); } }, null, methodType, params); sendCallback.onBefore && sendCallback.onBefore(RongIMLib.MessageIdHandler.messageId); msg.messageId = RongIMLib.MessageIdHandler.messageId + ""; }; ServerDataProvider.prototype.setConnectionStatusListener = function (listener) { if (RongIMLib.RongUtil.isObject(listener) && RongIMLib.RongUtil.isFunction(listener.onChanged)) { RongIMLib.RongIMClient.statusListeners.push(listener.onChanged); } }; ServerDataProvider.prototype.setOnReceiveMessageListener = function (listener) { if (RongIMLib.RongUtil.isObject(listener) && RongIMLib.RongUtil.isFunction(listener.onReceived)) { RongIMLib.RongIMClient.messageListeners.push(listener.onReceived); } }; ServerDataProvider.prototype.registerMessageType = function (messageType, objectName, messageTag, messageContent, searchProps) { if (!messageType) { throw new Error("messageType can't be empty,postion -> registerMessageType"); } if (!objectName) { throw new Error("objectName can't be empty,postion -> registerMessageType"); } if (Object.prototype.toString.call(messageContent) == "[object Array]") { var regMsg = RongIMLib.ModelUtil.modleCreate(messageContent, messageType); RongIMLib.RongIMClient.RegisterMessage[messageType] = regMsg; } else if (Object.prototype.toString.call(messageContent) == "[object Function]" || Object.prototype.toString.call(messageContent) == "[object Object]") { if (!messageContent.encode) { throw new Error("encode method has not realized or messageName is undefined-> registerMessageType"); } if (!messageContent.decode) { throw new Error("decode method has not realized -> registerMessageType"); } } else { throw new Error("The index of 3 parameter was wrong type must be object or function or array-> registerMessageType"); } registerMessageTypeMapping[objectName] = messageType; }; ServerDataProvider.prototype.registerMessageTypes = function (messages) { var types = []; var getProtos = function (proto) { var protos = []; for (var p in proto) { protos.push(p); } return protos; }; //转换消息为自定义消息参数格式 for (var name in messages) { var message = messages[name]; var proto = message.proto; var protos = getProtos(proto); var flag = message.flag || 3; var tag = RongIMLib.MessageTag.getTagByStatus(flag); flag = new RongIMLib.MessageTag(tag.isCounted, tag.isPersited); types.push({ type: name, name: message.name, flag: flag, protos: protos }); } var register = function (message) { var type = message.type; var name = message.name; var flag = message.flag; var protos = message.protos; RongIMLib.RongIMClient.registerMessageType(type, name, flag, protos); }; for (var i = 0, len = types.length; i < len; i++) { var message = types[i]; register(message); } }; /** * 向缓存会话列表内添加新会话或更新会话 */ ServerDataProvider.prototype.addConversation = function (conversation, callback) { var isAdd = true; for (var i = 0, len = RongIMLib.RongIMClient._memoryStore.conversationList.length; i < len; i++) { if (RongIMLib.RongIMClient._memoryStore.conversationList[i].conversationType === conversation.conversationType && RongIMLib.RongIMClient._memoryStore.conversationList[i].targetId === conversation.targetId) { // RongIMClient._memoryStore.conversationList[i] = conversation; RongIMLib.RongIMClient._memoryStore.conversationList.unshift(RongIMLib.RongIMClient._memoryStore.conversationList.splice(i, 1)[0]); isAdd = false; break; } } if (isAdd) { RongIMLib.RongIMClient._memoryStore.conversationList.unshift(conversation); } callback && callback.onSuccess(true); }; /** * 更新缓存会话字段 */ ServerDataProvider.prototype.updateConversation = function (conversation) { var conver; for (var i = 0, len = RongIMLib.RongIMClient._memoryStore.conversationList.length; i < len; i++) { var item = RongIMLib.RongIMClient._memoryStore.conversationList[i]; if (conversation.conversationType === item.conversationType && conversation.targetId === item.targetId) { conversation.conversationTitle && (item.conversationTitle = conversation.conversationTitle); conversation.senderUserName && (item.senderUserName = conversation.senderUserName); conversation.senderPortraitUri && (item.senderPortraitUri = conversation.senderPortraitUri); conversation.latestMessage && (item.latestMessage = conversation.latestMessage); conversation.sentStatus && (item.sentStatus = conversation.sentStatus); break; } } return conver; }; /** * 移除 IM Server 端会话,并清除缓存内会话 */ ServerDataProvider.prototype.removeConversation = function (conversationType, targetId, callback) { var mod = new RongIMLib.RongIMClient.Protobuf.RelationsInput(); mod.setType(conversationType); RongIMLib.RongIMClient.bridge.queryMsg(27, RongIMLib.MessageUtil.ArrayForm(mod.toArrayBuffer()), targetId, { onSuccess: function () { var isRemoved = false; var conversations = RongIMLib.RongIMClient._memoryStore.conversationList; var len = conversations.length; for (var i = 0; i < len; i++) { if (conversations[i].conversationType == conversationType && targetId == conversations[i].targetId) { conversations.splice(i, 1); isRemoved = true; break; } } isRemoved && RongIMLib.RongIMClient._dataAccessProvider.Conversation._notify(RongIMLib.RongIMClient._memoryStore.conversationList); callback.onSuccess(true); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.getMessage = function (messageId, callback) { callback.onSuccess(new RongIMLib.Message()); }; ServerDataProvider.prototype.addMessage = function (conversationType, targetId, message, callback) { if (callback) { callback.onSuccess(message); } }; ServerDataProvider.prototype.removeMessage = function (conversationType, targetId, messages, callback) { RongIMLib.RongIMClient.getInstance().deleteRemoteMessages(conversationType, targetId, messages, callback); }; ServerDataProvider.prototype.removeLocalMessage = function (conversationType, targetId, timestamps, callback) { callback.onSuccess(true); }; ServerDataProvider.prototype.updateMessage = function (message, callback) { if (callback) { callback.onSuccess(message); } }; ServerDataProvider.prototype.deleteRemoteMessages = function (conversationType, targetId, messages, callback) { if (!RongIMLib.RongIMClient.Protobuf.DeleteMsgInput) { throw new Error('SDK Protobuf version is too low'); } var modules = new RongIMLib.RongIMClient.Protobuf.DeleteMsgInput(); var msgs = []; RongIMLib.RongUtil.forEach(messages, function (msg) { msgs.push({ msgId: msg.messageUId, msgDataTime: msg.sentTime, direct: msg.messageDirection }); }); modules.setType(conversationType); modules.setConversationId(targetId); modules.setMsgs(msgs); RongIMLib.RongIMClient.bridge.queryMsg('delMsg', RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), targetId, { onSuccess: function (result) { callback.onSuccess(result); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }, 'DeleteMsgOutput'); }; ServerDataProvider.prototype.clearRemoteHistoryMessages = function (params, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.CleanHisMsgInput(); var conversationType = params.conversationType; var _topic = { 1: 'cleanPMsg', 2: 'cleanDMsg', 3: 'cleanGMsg', 5: 'cleanCMsg', 6: 'cleanSMsg' }; var topic = _topic[conversationType]; if (!topic) { callback.onError(RongIMLib.ErrorCode.CLEAR_HIS_TYPE_ERROR); return; } var timestamp = params.timestamp; if (typeof timestamp != 'number') { callback.onError(RongIMLib.ErrorCode.CLEAR_HIS_TIME_ERROR); return; } modules.setDataTime(timestamp); var targetId = params.targetId; modules.setTargetId(targetId); RongIMLib.RongIMClient.bridge.queryMsg(topic, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), targetId, { onSuccess: function (result) { callback.onSuccess(!result); }, onError: function (error) { // error 1 历史消息云存储没有开通、传入时间大于服务器时间 清除失败,1 与其他错误码冲突,所以自定义错误码返回 if (error == 1) { error = RongIMLib.ErrorCode.CLEAR_HIS_ERROR; } setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.clearHistoryMessages = function (params, callback) { this.clearRemoteHistoryMessages(params, callback); }; // 兼容老版本 ServerDataProvider.prototype.clearMessages = function (conversationType, targetId, callback) { }; ServerDataProvider.prototype.updateMessages = function (conversationType, targetId, key, value, callback) { var me = this; if (key == "readStatus") { if (RongIMLib.RongIMClient._memoryStore.conversationList.length > 0) { me.getConversationList({ onSuccess: function (list) { Array.forEach(list, function (conver) { if (conver.conversationType == conversationType && conver.targetId == targetId) { conver.unreadMessageCount = 0; } }); }, onError: function (errorCode) { setTimeout(function () { callback.onError(errorCode); }); } }, null); } } setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.getConversation = function (conversationType, targetId, callback) { var conver = null; for (var i = 0, len = RongIMLib.RongIMClient._memoryStore.conversationList.length; i < len; i++) { if (RongIMLib.RongIMClient._memoryStore.conversationList[i].conversationType == conversationType && RongIMLib.RongIMClient._memoryStore.conversationList[i].targetId == targetId) { conver = RongIMLib.RongIMClient._memoryStore.conversationList[i]; if (RongIMLib.RongUtil.supportLocalStorage()) { // var count = RongIMClient._storageProvider.getItem("cu" + Bridge._client.userId + conversationType + targetId); var count = RongIMLib.UnreadCountHandler.get(conversationType, targetId); if (conver.unreadMessageCount == 0) { conver.unreadMessageCount = Number(count); } } } } setTimeout(function () { callback && callback.onSuccess(conver); }); return conver; }; ServerDataProvider.prototype.filterConversations = function (types, list) { var conversaions = []; RongIMLib.RongUtil.forEach(types, function (type) { RongIMLib.RongUtil.forEach(list, function (conversation) { if (conversation.conversationType == type) { conversaions.push(conversation); } }); }); return conversaions; }; ServerDataProvider.prototype.getConversationList = function (callback, conversationTypes, count, isHidden) { var that = this; var isSync = RongIMLib.RongIMClient._memoryStore.isSyncRemoteConverList; var list = RongIMLib.RongIMClient._memoryStore.conversationList; if (!RongIMLib.RongUtil.isNumber(count)) { count = 200; } var isLocalInclude = list.length >= count; if (!isSync && (isLocalInclude || RongIMLib.RongIMClient._memoryStore.isFullConversations)) { setTimeout(function () { var _list = JSON.parse(JSON.stringify(list)); var localList = _list.slice(0, count); if (conversationTypes) { localList = that.filterConversations(conversationTypes, localList); } callback.onSuccess(localList); }); return; } RongIMLib.RongIMClient.getInstance().getRemoteConversationList({ onSuccess: function (list) { if (RongIMLib.RongUtil.supportLocalStorage()) { Array.forEach(RongIMLib.RongIMClient._memoryStore.conversationList, function (item) { // var count = RongIMClient._storageProvider.getItem("cu" + Bridge._client.userId + item.conversationType + item.targetId); var count = RongIMLib.UnreadCountHandler.get(item.conversationType, item.targetId); if (item.unreadMessageCount == 0) { item.unreadMessageCount = Number(count); } }); } RongIMLib.RongIMClient._memoryStore.isSyncRemoteConverList = false; var isFullConversations = count > list.length; RongIMLib.RongIMClient._memoryStore.isFullConversations = isFullConversations; setTimeout(function () { callback.onSuccess(list); }); }, onError: function (errorcode) { setTimeout(function () { callback.onError(errorcode); }); } }, conversationTypes, count, isHidden); }; ServerDataProvider.prototype.clearCache = function () { var memoryStore = RongIMLib.RongIMClient._memoryStore || {}; memoryStore.conversationList = []; memoryStore.isSyncRemoteConverList = true; }; ServerDataProvider.prototype.clearConversations = function (conversationTypes, callback) { Array.forEach(conversationTypes, function (conversationType) { Array.forEach(RongIMLib.RongIMClient._memoryStore.conversationList, function (conver) { if (conversationType == conver.conversationType) { RongIMLib.RongIMClient.getInstance().removeConversation(conver.conversationType, conver.targetId, { onSuccess: function () { }, onError: function () { } }); } }); }); setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.setMessageContent = function (messageId, content, objectname) { }; ; ServerDataProvider.prototype.setMessageSearchField = function (messageId, content, searchFiles) { }; ; ServerDataProvider.prototype.getHistoryMessages = function (conversationType, targetId, timestamp, count, callback, objectname, order) { var config = { objectname: objectname, order: order }; RongIMLib.RongIMClient.getInstance().getRemoteHistoryMessages(conversationType, targetId, timestamp, count, callback, config); }; ServerDataProvider.prototype.getTotalUnreadCount = function (callback, conversationTypes) { var count = RongIMLib.UnreadCountHandler.getAll(conversationTypes); callback.onSuccess(count); return count; }; ServerDataProvider.prototype.getConversationUnreadCount = function (conversationTypes, callback) { var count = 0; Array.forEach(conversationTypes, function (converType) { Array.forEach(RongIMLib.RongIMClient._memoryStore.conversationList, function (conver) { if (conver.conversationType == converType) { count += conver.unreadMessageCount; } }); }); setTimeout(function () { callback.onSuccess(count); }); }; //由于 Web 端未读消息数按会话统计,撤回消息会导致未读数不准确,提供设置未读数接口,桌面版不实现此方法 ServerDataProvider.prototype.setUnreadCount = function (conversationType, targetId, count, sentTime) { sentTime = sentTime || new Date().getTime(); RongIMLib.UnreadCountHandler.set(conversationType, targetId, count, sentTime); }; ServerDataProvider.prototype.getUnreadCount = function (conversationType, targetId, callback) { var unreadCount = RongIMLib.UnreadCountHandler.get(conversationType, targetId); setTimeout(function () { callback.onSuccess(unreadCount || 0); }); }; ServerDataProvider.prototype.cleanMentioneds = function (conver) { if (conver) { conver.mentionedMsg = null; var targetId = conver.targetId; var conversationType = conver.conversationType; var mentioneds = RongIMLib.RongIMClient._storageProvider.getItem("mentioneds_" + RongIMLib.Bridge._client.userId + '_' + conversationType + '_' + targetId); if (mentioneds) { var info = JSON.parse(mentioneds); delete info[conversationType + "_" + targetId]; if (!RongIMLib.MessageUtil.isEmpty(info)) { RongIMLib.RongIMClient._storageProvider.setItem("mentioneds_" + RongIMLib.Bridge._client.userId + '_' + conversationType + '_' + targetId, JSON.stringify(info)); } else { RongIMLib.RongIMClient._storageProvider.removeItem("mentioneds_" + RongIMLib.Bridge._client.userId + '_' + conversationType + '_' + targetId); } } } }; ServerDataProvider.prototype.clearUnreadCountByTimestamp = function (conversationType, targetId, timestamp, callback) { setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.clearUnreadCount = function (conversationType, targetId, callback) { var me = this; // RongIMClient._storageProvider.removeItem("cu" + Bridge._client.userId + conversationType + targetId); RongIMLib.UnreadCountHandler.remove(conversationType, targetId); this.getConversation(conversationType, targetId, { onSuccess: function (conver) { conver = conver || new RongIMLib.Conversation(); var isNotifyConversation = conver.unreadMessageCount; if (conver) { conver.unreadMessageCount = 0; me.cleanMentioneds(conver); } setTimeout(function () { callback.onSuccess(true); isNotifyConversation && RongIMLib.RongIMClient._dataAccessProvider.Conversation._notify(RongIMLib.RongIMClient._memoryStore.conversationList); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.clearTotalUnreadCount = function (callback) { var list = RongIMLib.RongIMClient._memoryStore.conversationList; var me = this; var isNotifyConversation = false; if (list) { // 清除 mentioneds、清除 list 中的 unreadMessageCount for (var i = 0; i < list.length; i++) { var conver = list[i]; if (conver) { isNotifyConversation = conver.unreadMessageCount ? true : isNotifyConversation; conver.unreadMessageCount = 0; me.cleanMentioneds(conver); } } } RongIMLib.UnreadCountHandler.clear(); setTimeout(function () { callback.onSuccess(true); isNotifyConversation && RongIMLib.RongIMClient._dataAccessProvider.Conversation._notify(RongIMLib.RongIMClient._memoryStore.conversationList); }); }; ServerDataProvider.prototype.setConversationToTop = function (conversationType, targetId, isTop, callback) { var me = this; this.getConversation(conversationType, targetId, { onSuccess: function (conver) { conver.isTop = isTop; me.addConversation(conver, callback); setTimeout(function () { callback.onSuccess(true); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.getConversationNotificationStatus = function (params, callback) { var targetId = params.targetId; var conversationType = params.conversationType; var notification = RongIMLib.RongIMClient._memoryStore.notification; var getKey = function () { return conversationType + '_' + targetId; }; var key = getKey(); var status = notification[key]; if (typeof status == 'number') { callback.onSuccess(status); return; } var topics = { 1: 'qryPPush', 3: 'qryDPush' }; var topic = topics[conversationType]; if (!topic) { var error = 8001; callback.onError(error); return; } var modules = new RongIMLib.RongIMClient.Protobuf.BlockPushInput(); modules.setBlockeeId(targetId); var userId = RongIMLib.Bridge._client.userId; var success = function (status) { notification[key] = status; setTimeout(function () { callback.onSuccess(status); }); }; RongIMLib.RongIMClient.bridge.queryMsg(topic, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function (status) { success(status); }, onError: function (e) { if (e == 1) { success(e); } else { setTimeout(function () { callback.onError(e); }); } } }); }; ServerDataProvider.prototype.setConversationStatus = function (type, targetId, statusItem, callback) { var self = this; var modules = new RongIMLib.RongIMClient.Protobuf.SessionStateModifyReq(); var userId = RongIMLib.Bridge._client.userId; var time = +new Date(); var stateItemModules = []; if (!RongIMLib.RongUtil.isUndefined(statusItem.notificationStatus)) { var isNotDisturbe = statusItem.notificationStatus === RongIMLib.ConversationNotificationStatus.DO_NOT_DISTURB; stateItemModules.push({ sessionStateType: 1, value: isNotDisturbe ? '1' : '0' }); } if (!RongIMLib.RongUtil.isUndefined(statusItem.isTop)) { stateItemModules.push({ sessionStateType: 2, value: statusItem.isTop ? '1' : '0' }); } var stateModules = { type: type, channelId: targetId, time: time, stateItem: stateItemModules }; modules.setVersion(time); modules.setState([stateModules]); RongIMLib.RongIMClient.bridge.queryMsg('setSeAtt', RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function (result) { var time = RongIMLib.MessageUtil.int64ToTimestamp(result.version); statusItem.updateTime = time; statusItem.isLastInAPull = true; self.conversationStatusManager.set(type, targetId, statusItem); setTimeout(function () { callback.onSuccess(time); }); }, onError: function (e) { setTimeout(function () { callback.onError(e); }); } }, 'SessionStateModifyResp'); }; ServerDataProvider.prototype.pullConversationStatus = function (time, callback) { time = time || 0; var modules = new RongIMLib.RongIMClient.Protobuf.SessionReq(); modules.setTime(time); var userId = RongIMLib.Bridge._client.userId; RongIMLib.RongIMClient.bridge.queryMsg('pullSeAtts', RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function (result) { var sessionStateList = result.state, lastTime = result.version; var sessionLength = sessionStateList.length; RongIMLib.RongUtil.forEach(sessionStateList, function (state, index) { var type = state.type, targetId = state.channelId, updateTime = state.time, stateItem = state.stateItem; var isSilent = false, isTop = false; RongIMLib.RongUtil.forEach(stateItem, function (item) { var sessionStateType = item.sessionStateType, value = item.value; if (sessionStateType === 1) { isSilent = !!Number(value); } if (sessionStateType === 2) { isTop = !!Number(value); } }); var isLastInAPull = index === sessionLength - 1; callback.onStatus(type, targetId, { notificationStatus: isSilent ? RongIMLib.ConversationNotificationStatus.DO_NOT_DISTURB : RongIMLib.ConversationNotificationStatus.NOTIFY, isTop: isTop, updateTime: RongIMLib.MessageUtil.int64ToTimestamp(updateTime), isLastInAPull: isLastInAPull }); }); callback.onSuccess(RongIMLib.MessageUtil.int64ToTimestamp(lastTime)); }, onError: function (e) { setTimeout(function () { callback.onError(e); }); } }, 'SessionStates'); }; ServerDataProvider.prototype.setConversationNotificationStatus = function (params, callback) { var conversationType = params.conversationType; var targetId = params.targetId; var status = params.status; var getKey = function () { return conversationType + '_' + status; }; var topics = { '1_1': 'blkPPush', '3_1': 'blkDPush', '1_0': 'unblkPPush', '3_0': 'unblkDPush' }; var key = getKey(); var notification = RongIMLib.RongIMClient._memoryStore.notification; notification[key] = status; var topic = topics[key]; if (!topic) { var error = 8001; setTimeout(function () { callback.onError(error); }); return; } var modules = new RongIMLib.RongIMClient.Protobuf.BlockPushInput(); modules.setBlockeeId(targetId); var userId = RongIMLib.Bridge._client.userId; RongIMLib.RongIMClient.bridge.queryMsg(topic, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function (status) { setTimeout(function () { callback.onSuccess(status); }); }, onError: function (e) { setTimeout(function () { callback.onError(e); }); } }); }; ServerDataProvider.prototype.getUserStatus = function (userId, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.GetUserStatusInput(); userId = RongIMLib.Bridge._client.userId; RongIMLib.RongIMClient.bridge.queryMsg(35, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function (status) { status = RongIMLib.RongInnerTools.convertUserStatus(status); setTimeout(function () { callback.onSuccess(status); }); }, onError: function (e) { setTimeout(function () { callback.onError(e); }); } }, 'GetUserStatusOutput'); // callback.onSuccess(new UserStatus()); }; ServerDataProvider.prototype.setUserStatus = function (status, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.SetUserStatusInput(); var userId = RongIMLib.Bridge._client.userId; if (status) { modules.setStatus(status); } RongIMLib.RongIMClient.bridge.queryMsg(36, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function (status) { setTimeout(function () { callback.onSuccess(true); }); }, onError: function (e) { setTimeout(function () { callback.onError(e); }); } }, 'SetUserStatusOutput'); }; ServerDataProvider.prototype.subscribeUserStatus = function (userIds, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.SubUserStatusInput(); var userId = RongIMLib.Bridge._client.userId; modules.setUserid(userIds); RongIMLib.RongIMClient.bridge.queryMsg(37, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function (status) { setTimeout(function () { callback && callback.onSuccess(true); }); }, onError: function (e) { setTimeout(function () { callback && callback.onError(e); }); } }, 'SubUserStatusOutput'); }; ServerDataProvider.prototype.setUserStatusListener = function (params, callback) { RongIMLib.RongIMClient.userStatusListener = callback; var userIds = params.userIds || []; if (userIds.length) { RongIMLib.RongIMClient._dataAccessProvider.subscribeUserStatus(userIds); } }; ServerDataProvider.prototype.clearListeners = function () { }; ServerDataProvider.prototype.setServerInfo = function (info) { }; ServerDataProvider.prototype.getUnreadMentionedMessages = function (conversationType, targetId) { return null; }; ServerDataProvider.prototype.setConversationHidden = function (conversationType, targetId, isHidden) { }; ServerDataProvider.prototype.setMessageExtra = function (messageId, value, callback) { setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.setMessageReceivedStatus = function (messageId, receivedStatus, callback) { setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.setMessageSentStatus = function (messageId, sentStatus, callback) { setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.getAllConversations = function (callback) { setTimeout(function () { callback.onSuccess([]); }); }; ServerDataProvider.prototype.getConversationByContent = function (keywords, callback) { setTimeout(function () { callback.onSuccess([]); }); }; ServerDataProvider.prototype.getMessagesFromConversation = function (conversationType, targetId, keywords, callback) { setTimeout(function () { callback.onSuccess([]); }); }; ServerDataProvider.prototype.searchConversationByContent = function (keyword, callback, conversationTypes) { setTimeout(function () { callback.onSuccess([]); }); }; ServerDataProvider.prototype.searchMessageByContent = function (conversationType, targetId, keyword, timestamp, count, total, callback) { setTimeout(function () { callback.onSuccess([]); }); }; ServerDataProvider.prototype.getDelaTime = function () { return RongIMLib.RongIMClient._memoryStore.deltaTime; }; ServerDataProvider.prototype.getCurrentConnectionStatus = function () { var client = RongIMLib.Bridge._client || {}; var channel = client.channel || {}; var status = RongIMLib.ConnectionStatus.CONNECTION_CLOSED; if (typeof channel.connectionStatus == 'number') { status = channel.connectionStatus; } return status; }; ServerDataProvider.prototype.getAgoraDynamicKey = function (engineType, channelName, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.VoipDynamicInput(); modules.setEngineType(engineType); modules.setChannelName(channelName); RongIMLib.RongIMClient.bridge.queryMsg(32, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (result) { setTimeout(function () { callback.onSuccess(result); }); }, onError: function (errorCode) { setTimeout(function () { callback.onError(errorCode); }); } }, "VoipDynamicOutput"); }; ServerDataProvider.prototype.setDeviceInfo = function (deviceId) { }; ServerDataProvider.prototype.setEnvironment = function (isPrivate) { }; ServerDataProvider.prototype.clearData = function () { return true; }; ServerDataProvider.prototype.getPublicServiceProfile = function (publicServiceType, publicServiceId, callback) { var profile = RongIMLib.RongIMClient._memoryStore.publicServiceMap.get(publicServiceType, publicServiceId); setTimeout(function () { callback.onSuccess(profile); }); }; ServerDataProvider.prototype.getRemotePublicServiceList = function (callback, pullMessageTime) { if (RongIMLib.RongIMClient._memoryStore.depend.openMp) { var modules = new RongIMLib.RongIMClient.Protobuf.PullMpInput(), self = this; if (!pullMessageTime) { modules.setTime(0); } else { modules.setTime(pullMessageTime); } modules.setMpid(""); RongIMLib.RongIMClient.bridge.queryMsg(28, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (data) { //TODO 找出最大时间 // self.lastReadTime.set(conversationType + targetId, MessageUtil.int64ToTimestamp(data.syncTime)); RongIMLib.RongIMClient._memoryStore.publicServiceMap.publicServiceList.length = 0; RongIMLib.RongIMClient._memoryStore.publicServiceMap.publicServiceList = data; setTimeout(function () { callback && callback.onSuccess(data); }); }, onError: function (errorCode) { setTimeout(function () { callback && callback.onError(errorCode); }); } }, "PullMpOutput"); } }; ServerDataProvider.prototype.getRTCUserInfoList = function (room, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcQueryListInput(); // 1 是正序,2是倒序 modules.setOrder(2); RongIMLib.RongIMClient.bridge.queryMsg("rtcUData", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function (result) { var users = {}; var list = result.list; RongIMLib.RongUtil.forEach(list, function (item) { var userId = item.userId; var tmpData = {}; RongIMLib.RongUtil.forEach(item.userData, function (data) { var key = data.key; var value = data.value; tmpData[key] = value; }); users[userId] = tmpData; }); callback.onSuccess(users); }, onError: function (errorCode) { callback.onError(errorCode); } }, "RtcUserListOutput"); }; ServerDataProvider.prototype.getRTCUserList = function (room, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcQueryListInput(); modules.setOrder(2); RongIMLib.RongIMClient.bridge.queryMsg("rtcUList", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function (result) { callback.onSuccess({ users: result.list }); }, onError: function (errorCode) { callback.onError(errorCode); } }, "RtcUserListOutput"); }; ServerDataProvider.prototype.setRTCUserInfo = function (room, info, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcValueInfo(); modules.setKey(info.key); modules.setValue(info.value); RongIMLib.RongIMClient.bridge.queryMsg("rtcUPut", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function () { callback.onSuccess(true); }, onError: function (errorCode) { callback.onError(errorCode); } }); }; ServerDataProvider.prototype.removeRTCUserInfo = function (room, info, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcKeyDeleteInput(); var keys = info.keys || []; if (!RongIMLib.RongUtil.isArray(keys)) { keys = [keys]; } modules.setKey(keys); RongIMLib.RongIMClient.bridge.queryMsg("rtcUDel", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function () { callback.onSuccess(true); }, onError: function (errorCode) { callback.onError(errorCode); } }); }; ServerDataProvider.prototype.getRTCRoomInfo = function (room, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcQueryListInput(); modules.setOrder(2); RongIMLib.RongIMClient.bridge.queryMsg("rtcRInfo", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function (result) { var room = { id: result.roomId, total: result.userCount }; RongIMLib.RongUtil.forEach(result.roomData, function (data) { room[data.key] = data.value; }); callback.onSuccess(room); }, onError: function (errorCode) { callback.onError(errorCode); } }, "RtcRoomInfoOutput"); }; ServerDataProvider.prototype.setRTCRoomInfo = function (room, info, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcValueInfo(); modules.setKey(info.key); modules.setValue(info.value); RongIMLib.RongIMClient.bridge.queryMsg("rtcRPut", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function () { callback.onSuccess(true); }, onError: function (errorCode) { callback.onError(errorCode); } }); }; ServerDataProvider.prototype.removeRTCRoomInfo = function (room, info, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcKeyDeleteInput(); var keys = info.keys || []; if (!RongIMLib.RongUtil.isArray(keys)) { keys = [keys]; } modules.setKey(keys); RongIMLib.RongIMClient.bridge.queryMsg("rtcRDel", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function () { callback.onSuccess(true); }, onError: function (errorCode) { callback.onError(errorCode); } }); }; ServerDataProvider.prototype.joinRTCRoom = function (room, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcInput(); var mode = room.mode || 0; modules.setRoomType(mode); if (room.broadcastType) { modules.setBroadcastType(room.broadcastType); } RongIMLib.RongIMClient.bridge.queryMsg("rtcRJoin_data", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function (result) { var users = {}; var list = result.list, token = result.token, sessionId = result.sessionId; RongIMLib.RongUtil.forEach(list, function (item) { var userId = item.userId; var tmpData = {}; RongIMLib.RongUtil.forEach(item.userData, function (data) { var key = data.key; var value = data.value; tmpData[key] = value; }); users[userId] = tmpData; }); callback.onSuccess({ users: users, token: token, sessionId: sessionId }); }, onError: function (errorCode) { callback.onError(errorCode); } }, "RtcUserListOutput"); }; ServerDataProvider.prototype.quitRTCRoom = function (room, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.SetUserStatusInput(); RongIMLib.RongIMClient.bridge.queryMsg("rtcRExit", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function () { callback.onSuccess(true); }, onError: function (errorCode) { callback.onError(errorCode); } }); }; ServerDataProvider.prototype.RTCPing = function (room, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcInput(); var mode = room.mode || 0; modules.setRoomType(mode); if (room.broadcastType) { modules.setBroadcastType(room.broadcastType); } RongIMLib.RongIMClient.bridge.queryMsg("rtcPing", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, callback); }; ServerDataProvider.prototype.setRTCData = function (roomId, key, value, isInner, apiType, callback, message) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcSetDataInput(); modules.setInterior(isInner); modules.setTarget(apiType); modules.setKey(key); modules.setValue(value); message = message || {}; var name = message.name; var content = message.content; if (name) { modules.setObjectName(name); } if (content) { if (!RongIMLib.RongUtil.isString(content)) { content = JSON.stringify(content); } modules.setContent(content); } RongIMLib.RongIMClient.bridge.queryMsg("rtcSetData", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), roomId, callback, "RtcOutput"); }; ServerDataProvider.prototype.getRTCData = function (roomId, keys, isInner, apiType, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcDataInput(); modules.setInterior(isInner); modules.setTarget(apiType); modules.setKey(keys); RongIMLib.RongIMClient.bridge.queryMsg("rtcQryData", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), roomId, { onSuccess: function (result) { var props = {}; var list = result.outInfo; RongIMLib.RongUtil.forEach(list, function (item) { props[item.key] = item.value; }); callback.onSuccess(props); }, onError: callback.onError }, "RtcQryOutput"); }; ServerDataProvider.prototype.removeRTCData = function (roomId, keys, isInner, apiType, callback, message) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcDataInput(); modules.setInterior(isInner); modules.setTarget(apiType); modules.setKey(keys); message = message || {}; var name = message.name; var content = message.content; if (name) { modules.setObjectName(name); } if (content) { if (!RongIMLib.RongUtil.isString(content)) { content = JSON.stringify(content); } modules.setContent(content); } RongIMLib.RongIMClient.bridge.queryMsg("rtcDelData", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), roomId, callback, "RtcOutput"); }; ServerDataProvider.prototype.setRTCUserData = function (roomId, key, value, isInner, callback, message) { this.setRTCData(roomId, key, value, isInner, RongIMLib.RTCAPIType.PERSON, callback, message); }; ServerDataProvider.prototype.getRTCUserData = function (roomId, keys, isInner, callback, message) { this.getRTCData(roomId, keys, isInner, RongIMLib.RTCAPIType.PERSON, callback); }; ServerDataProvider.prototype.removeRTCUserData = function (roomId, keys, isInner, callback, message) { this.removeRTCData(roomId, keys, isInner, RongIMLib.RTCAPIType.PERSON, callback, message); }; ServerDataProvider.prototype.setRTCRoomData = function (roomId, key, value, isInner, callback, message) { this.setRTCData(roomId, key, value, isInner, RongIMLib.RTCAPIType.ROOM, callback, message); }; ServerDataProvider.prototype.getRTCRoomData = function (roomId, keys, isInner, callback, message) { this.getRTCData(roomId, keys, isInner, RongIMLib.RTCAPIType.ROOM, callback); }; ServerDataProvider.prototype.removeRTCRoomData = function (roomId, keys, isInner, callback, message) { this.removeRTCData(roomId, keys, isInner, RongIMLib.RTCAPIType.ROOM, callback, message); }; // 信令 SDK 新增 ServerDataProvider.prototype.setRTCOutData = function (roomId, data, type, callback, message) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcSetOutDataInput(); modules.setTarget(type); if (!RongIMLib.RongUtil.isArray(data)) { data = [data]; } for (var i = 0; i < data.length; i++) { var item = data[i]; if (item.key) { item.key = item.key.toString(); } if (item.value) { item.value = item.value.toString(); } } modules.setValueInfo(data); message = message || {}; var name = message.name; var content = message.content; if (name) { modules.setObjectName(name); } if (content) { if (!RongIMLib.RongUtil.isString(content)) { content = JSON.stringify(content); } modules.setContent(content); } RongIMLib.RongIMClient.bridge.queryMsg("rtcSetOutData", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), roomId, callback, "RtcOutput"); }; // 信令 SDK 新增 ServerDataProvider.prototype.getRTCOutData = function (roomId, userIds, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcQryUserOutDataInput(); modules.setUserId(userIds); RongIMLib.RongIMClient.bridge.queryMsg("rtcQryUserOutData", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), roomId, callback, "RtcUserOutDataOutput"); }; ServerDataProvider.prototype.getNavi = function () { var navi = RongIMLib.RongIMClient._storageProvider.getItem("fullnavi") || "{}"; return JSON.parse(navi); }; ServerDataProvider.prototype.getRTCToken = function (room, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcInput(); var mode = room.mode || 0; modules.setRoomType(mode); if (room.broadcastType) { modules.setBroadcastType(room.broadcastType); } RongIMLib.RongIMClient.bridge.queryMsg("rtcToken", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function (result) { callback.onSuccess(result); }, onError: function (errorCode) { callback.onError(errorCode); } }, "RtcTokenOutput"); }; ServerDataProvider.prototype.setRTCState = function (room, content, callback) { // MCFollowInput 为 PB 复用,字段:一个必传 string(第一位) var modules = new RongIMLib.RongIMClient.Protobuf.MCFollowInput(); var report = content.report; modules.setId(report); RongIMLib.RongIMClient.bridge.queryMsg("rtcUserState", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function (result) { callback.onSuccess(result); }, onError: function (errorCode) { callback.onError(errorCode); } }, "RtcOutput"); }; return ServerDataProvider; })(); RongIMLib.ServerDataProvider = ServerDataProvider; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var VCDataProvider = (function () { function VCDataProvider(addon) { this.Conversation = { watcher: new RongIMLib.Observer(), watch: function (_watcher) { }, unwatch: function (_watcher) { }, _notify: function (conversationList) { } }; // C++ 需要的 SDK 版本号 this.version = '2.8.27'; this.userId = ""; this.useConsole = false; this.appKey = ""; this.token = ""; this.connectionStatus = RongIMLib.ConnectionStatus.DISCONNECTED; this.addon = addon; } VCDataProvider.prototype.init = function (appKey, config) { this.appKey = appKey; this.useConsole && console.log("init"); config = config || {}; config.version = this.version; var sdkInfo = this.addon.initWithAppkey(appKey, config.dbPath, config); if (sdkInfo) { sdkInfo = JSON.parse(sdkInfo); } // 0 不存不计数 1 只存不计数 3 存且计数 this.addon.registerMessageType("RC:VcMsg", 3); this.addon.registerMessageType("RC:ImgTextMsg", 3); this.addon.registerMessageType("RC:FileMsg", 3); this.addon.registerMessageType("RC:LBSMsg", 3); this.addon.registerMessageType("RC:PSImgTxtMsg", 3); this.addon.registerMessageType("RC:PSMultiImgTxtMsg", 3); this.addon.registerMessageType("RCJrmf:RpMsg", 3); this.addon.registerMessageType("RCJrmf:RpOpendMsg", 1); this.addon.registerMessageType("RC:GrpNtf", 1); this.addon.registerMessageType("RC:DizNtf", 0); this.addon.registerMessageType("RC:InfoNtf", 0); this.addon.registerMessageType("RC:ContactNtf", 0); this.addon.registerMessageType("RC:ProfileNtf", 0); this.addon.registerMessageType("RC:CmdNtf", 0); this.addon.registerMessageType("RC:CmdMsg", 0); this.addon.registerMessageType("RC:TypSts", 0); this.addon.registerMessageType("RC:CsChaR", 0); this.addon.registerMessageType("RC:CsHsR", 0); this.addon.registerMessageType("RC:CsEnd", 0); this.addon.registerMessageType("RC:CsSp", 0); this.addon.registerMessageType("RC:CsUpdate", 0); this.addon.registerMessageType("RC:CsContact", 0); this.addon.registerMessageType("RC:ReadNtf", 0); this.addon.registerMessageType("RC:VCAccept", 0); this.addon.registerMessageType("RC:VCRinging", 0); this.addon.registerMessageType("RC:VCSummary", 0); this.addon.registerMessageType("RC:VCHangup", 0); this.addon.registerMessageType("RC:VCInvite", 0); this.addon.registerMessageType("RC:VCModifyMedia", 0); this.addon.registerMessageType("RC:VCModifyMem", 0); this.addon.registerMessageType("RC:PSCmd", 0); this.addon.registerMessageType("RC:RcCmd", 0); this.addon.registerMessageType("RC:SRSMsg", 0); this.addon.registerMessageType("RC:RRReqMsg", 0); this.addon.registerMessageType("RC:RRRspMsg", 0); return sdkInfo; }; VCDataProvider.prototype.connect = function (token, callback, userId, serverConf) { this.useConsole && console.log("connect"); this.userId = userId; this.connectCallback = callback; RongIMLib.Bridge._client = { userId: userId, token: token }; serverConf = serverConf || {}; var openmp = !!serverConf.openMp; var openus = !!serverConf.openUS; if (serverConf.type) { this.addon.setEnvironment(true); } var me = this; // this.addon.connectWithToken(token, userId, serverConf.serverList, openmp, openus); this.addon.connectWithToken(token, userId, function (userId) { me.userId = userId; RongIMLib.Bridge._client.userId = userId; }); }; VCDataProvider.prototype.setConversationStatus = function (type, targetId, statusItem, callback) { }; VCDataProvider.prototype.setServerInfo = function (info) { 'setServerInfo' in this.addon && this.addon.setServerInfo(info.navi); }; VCDataProvider.prototype.logout = function () { this.useConsole && console.log("logout"); this.disconnect(); }; VCDataProvider.prototype.disconnect = function () { this.useConsole && console.log("disconnect"); this.connectionStatus = RongIMLib.ConnectionStatus.DISCONNECTED; this.addon.disconnect(true); }; VCDataProvider.prototype.clearListeners = function () { this.addon.setOnReceiveStatusListener(); this.addon.setConnectionStatusListener(); this.addon.setOnReceiveMessageListener(); }; VCDataProvider.prototype.clearData = function () { this.useConsole && console.log("clearData"); return this.addon.clearData(); }; VCDataProvider.prototype.setConnectionStatusListener = function (listener) { var me = this; /** ConnectionStatus_TokenIncorrect = 31004, ConnectionStatus_Connected = 0, ConnectionStatus_KickedOff = 6, // 其他设备登录 ConnectionStatus_Connecting = 10,// 连接中 ConnectionStatus_SignUp = 12, // 未登录 ConnectionStatus_NetworkUnavailable = 1, // 连接断开 ConnectionStatus_ServerInvalid = 8, // 断开 ConnectionStatus_ValidateFailure = 9,//断开 ConnectionStatus_Unconnected = 11,//断开 ConnectionStatus_DisconnExecption = 31011 //断开 RC_NAVI_MALLOC_ERROR = 30000,//断开 RC_NAVI_NET_UNAVAILABLE= 30002,//断开 RC_NAVI_SEND_FAIL = 30004,//断开 RC_NAVI_REQ_TIMEOUT = 30005,//断开 RC_NAVI_RECV_FAIL = 30006,//断开 RC_NAVI_RESOURCE_ERROR = 30007,//断开 RC_NAVI_NODE_NOT_FOUND = 30008,//断开 RC_NAVI_DNS_ERROR = 30009,//断开 */ me.connectListener = listener; this.useConsole && console.log("setConnectionStatusListener"); me.addon && me.addon.setConnectionStatusListener(function (result) { var isCurrentConnected = me.connectionStatus === RongIMLib.ConnectionStatus.CONNECTED; var code = result; switch (result) { case 10: code = RongIMLib.ConnectionStatus.CONNECTING; break; case 31004: setTimeout(function () { me.connectCallback.onTokenIncorrect(); }); return; case 1: case 8: case 9: case 11: case 12: case 31011: case 30000: case 30002: case 30010: if (!isCurrentConnected) { return; } code = RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE; break; case 0: case 33005: code = RongIMLib.ConnectionStatus.CONNECTED; setTimeout(function () { me.connectCallback.onSuccess(me.userId); }); break; case 6: code = RongIMLib.ConnectionStatus.KICKED_OFFLINE_BY_OTHER_CLIENT; break; default: code = result; break; } me.connectionStatus = code; setTimeout(function () { listener.onChanged(code); }); }); }; VCDataProvider.prototype.setOnReceiveMessageListener = function (listener) { var me = this, localCount = 0; me.messageListener = listener; this.useConsole && console.log("setOnReceiveMessageListener"); me.addon && me.addon.setOnReceiveMessageListener(function (result, leftCount, offline, hasMore) { var message = me.buildMessage(result); message.offLineMessage = offline; setTimeout(function () { var voipMsgTypes = ['AcceptMessage', 'RingingMessage', 'HungupMessage', 'InviteMessage', 'MediaModifyMessage', 'MemberModifyMessage']; var isVoIPMsg = voipMsgTypes.indexOf(message.messageType) > -1; if (isVoIPMsg) { RongIMLib.RongIMClient._voipProvider && RongIMLib.RongIMClient._voipProvider.onReceived(message); } else if (message.conversationType == 12) { RongIMLib.RongIMClient.RTCListener(message); RongIMLib.RongIMClient.RTCInnerListener(message); RongIMLib.RongIMClient.RTCSignalLisener(message); } else { listener.onReceived(message, leftCount, hasMore); } }); }); }; VCDataProvider.prototype.sendTypingStatusMessage = function (conversationType, targetId, messageName, sendCallback) { var me = this; this.useConsole && console.log("sendTypingStatusMessage"); if (messageName in RongIMLib.RongIMClient.MessageParams) { me.sendMessage(conversationType, targetId, RongIMLib.TypingStatusMessage.obtain(RongIMLib.RongIMClient.MessageParams[messageName].objectName, ""), { onSuccess: function () { setTimeout(function () { sendCallback.onSuccess(); }); }, onError: function (errorCode) { setTimeout(function () { sendCallback.onError(errorCode, null); }); }, onBefore: function () { } }); } }; VCDataProvider.prototype.setMessageStatus = function (conversationType, targetId, timestamp, status, callback) { this.addon.updateMessageReceiptStatus(conversationType, targetId, timestamp); callback.onSuccess(true); }; VCDataProvider.prototype.sendTextMessage = function (conversationType, targetId, content, sendMessageCallback) { var msgContent = RongIMLib.TextMessage.obtain(content); this.useConsole && console.log("sendTextMessage"); this.sendMessage(conversationType, targetId, msgContent, sendMessageCallback); }; VCDataProvider.prototype.getRemoteHistoryMessages = function (conversationType, targetId, timestamp, count, callback, config) { try { var me = this; me.useConsole && console.log("getRemoteHistoryMessages"); me.addon.getRemoteHistoryMessages(conversationType, targetId, timestamp ? timestamp : 0, count, function (ret, hasMore) { var list = ret ? JSON.parse(ret).list : [], msgs = []; list.reverse(); for (var i = 0, len = list.length; i < len; i++) { var message = me.buildMessage(list[i].obj); message.sentStatus = RongIMLib.SentStatus.READ; msgs[i] = message; } callback.onSuccess(msgs, hasMore ? true : false); }, function (errorCode) { callback.onError(errorCode); }); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.getRemoteConversationList = function (callback, conversationTypes, count, isGetHiddenConvers) { try { this.useConsole && console.log("getRemoteConversationList"); var converTypes = conversationTypes || [1, 2, 3, 4, 5, 6, 7, 8]; var result = this.addon.getConversationList(converTypes); var list = JSON.parse(result).list, convers = [], me = this, index = 0; list.reverse(); isGetHiddenConvers = typeof isGetHiddenConvers === 'boolean' ? isGetHiddenConvers : false; for (var i = 0, len_1 = list.length; i < len_1; i++) { var tmpObj = list[i].obj, obj = JSON.parse(tmpObj); if (obj != "") { if (obj.isHidden == 1 && isGetHiddenConvers) { continue; } convers[index] = me.buildConversation(tmpObj); index++; } } convers.reverse(); var len = convers.length; count = count || len; if (len > count) { convers.length = count; } callback.onSuccess(convers); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.removeConversation = function (conversationType, targetId, callback) { try { this.useConsole && console.log("removeConversation"); this.addon.removeConversation(conversationType, targetId); var conversations = RongIMLib.RongIMClient._memoryStore.conversationList; var len = conversations.length; for (var i = 0; i < len; i++) { if (conversations[i].conversationType == conversationType && targetId == conversations[i].targetId) { conversations.splice(i, 1); break; } } callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.joinChatRoom = function (chatRoomId, messageCount, callback) { this.useConsole && console.log("joinChatRoom"); this.addon.joinChatRoom(chatRoomId, messageCount, function () { callback.onSuccess(); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.quitChatRoom = function (chatRoomId, callback) { this.useConsole && console.log("quitChatRoom"); this.addon.quitChatRoom(chatRoomId, function () { callback.onSuccess(); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.setChatroomEntry = function (chatroomId, chatroomEntry, callback) { }; VCDataProvider.prototype.forceSetChatroomEntry = function (chatroomId, chatroomEntry, callback) { }; VCDataProvider.prototype.getChatroomEntry = function (chatroomId, key, callback) { }; VCDataProvider.prototype.getAllChatroomEntries = function (chatroomId, callback) { }; VCDataProvider.prototype.removeChatroomEntry = function (chatroomId, chatroomEntry, callback) { }; VCDataProvider.prototype.forceRemoveChatroomEntry = function (chatroomId, chatroomEntry, callback) { }; VCDataProvider.prototype.pullChatroomEntry = function (chatroomId, time, callback) { }; VCDataProvider.prototype.addToBlacklist = function (userId, callback) { this.useConsole && console.log("addToBlacklist"); this.addon.addToBlacklist(userId, function () { callback.onSuccess(); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.getBlacklist = function (callback) { this.useConsole && console.log("getBlacklist"); this.addon.getBlacklist(function (blacklistors) { callback.onSuccess(blacklistors); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.getBlacklistStatus = function (userId, callback) { this.useConsole && console.log("getBlacklistStatus"); this.addon.getBlacklistStatus(userId, function (result) { callback.onSuccess(result); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.removeFromBlacklist = function (userId, callback) { this.useConsole && console.log("removeFromBlacklist"); this.addon.removeFromBlacklist(userId, function () { callback.onSuccess(); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.sendMessage = function (conversationType, targetId, messageContent, sendCallback, mentiondMsg, pushText, appData, methodType, params) { var me = this, users = []; me.useConsole && console.log("sendMessage"); params = params || {}; var isGroup = (conversationType == RongIMLib.ConversationType.DISCUSSION || conversationType == RongIMLib.ConversationType.GROUP); if (isGroup && messageContent.messageName == RongIMLib.RongIMClient.MessageType["ReadReceiptResponseMessage"]) { users = []; var rspMsg = messageContent; if (rspMsg.receiptMessageDic) { var ids = []; for (var key in rspMsg.receiptMessageDic) { ids.push(key); } users = ids; } } if (isGroup && messageContent.messageName == RongIMLib.RongIMClient.MessageType["SyncReadStatusMessage"]) { users = []; users.push(me.userId); } var userIds = params.userIds; if (isGroup && userIds) { users = userIds; } var msg = me.addon.sendMessage(conversationType, targetId, RongIMLib.RongIMClient.MessageParams[messageContent.messageName].objectName, messageContent.encode(), pushText || "", appData || "", function (progress) { }, function (message, code) { var msg = me.buildMessage(message); var errorCode = RongIMLib.ErrorCode.SENSITIVE_REPLACE; if (code == errorCode) { return sendCallback.onError(errorCode, msg); } sendCallback.onSuccess(msg); }, function (message, code) { sendCallback.onError(code, me.buildMessage(message)); }, users, mentiondMsg); var tempMessage = JSON.parse(msg); sendCallback.onBefore && sendCallback.onBefore(tempMessage.messageId); RongIMLib.MessageIdHandler.messageId = tempMessage.messageId; }; VCDataProvider.prototype.registerMessageType = function (messageType, objectName, messageTag, messageContent, searchProps) { this.useConsole && console.log("registerMessageType"); this.addon.registerMessageType(objectName, messageTag.getMessageTag(), searchProps); var regMsg = RongIMLib.ModelUtil.modleCreate(messageContent, messageType); RongIMLib.RongIMClient.RegisterMessage[messageType] = regMsg; RongIMLib.RongIMClient.RegisterMessage[messageType].messageName = messageType; registerMessageTypeMapping[objectName] = messageType; RongIMLib.RongIMClient.MessageType[messageType] = messageType; RongIMLib.RongIMClient.MessageParams[messageType] = { objectName: objectName, msgTag: messageTag }; typeMapping[objectName] = messageType; }; VCDataProvider.prototype.registerMessageTypes = function (messages) { var types = []; var getProtos = function (proto) { var protos = []; for (var p in proto) { protos.push(p); } return protos; }; //转换消息为自定义消息参数格式 for (var name in messages) { var message = messages[name]; var proto = message.proto; var protos = getProtos(proto); var flag = message.flag || 3; var tag = RongIMLib.MessageTag.getTagByStatus(flag); flag = new RongIMLib.MessageTag(tag.isCounted, tag.isPersited); types.push({ type: name, name: message.name, flag: flag, protos: protos }); } var register = function (message) { var type = message.type; var name = message.name; var flag = message.flag; var protos = message.protos; RongIMLib.RongIMClient.registerMessageType(type, name, flag, protos); }; for (var i = 0, len = types.length; i < len; i++) { var message = types[i]; register(message); } }; VCDataProvider.prototype.addMessage = function (conversationType, targetId, message, callback) { this.useConsole && console.log("addMessage"); var direction = message.direction; var msg = this.addon.insertMessage(conversationType, targetId, message.senderUserId, message.objectName, JSON.stringify(message.content), function () { callback.onSuccess(me.buildMessage(msg)); }, function () { callback.onError(RongIMLib.ErrorCode.MSG_INSERT_ERROR); }, direction), me = this; }; VCDataProvider.prototype.removeMessage = function (conversationType, targetId, messages, callback) { }; VCDataProvider.prototype.deleteRemoteMessages = function (conversationType, targetId, messages, callback) { }; VCDataProvider.prototype.removeLocalMessage = function (conversationType, targetId, timestamps, callback) { try { this.useConsole && console.log("removeLocalMessage"); this.addon.deleteMessages(timestamps); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.getMessage = function (messageId, callback) { try { this.useConsole && console.log("getMessage"); var msg = this.buildMessage(this.addon.getMessage(messageId)); callback.onSuccess(msg); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.clearMessages = function (conversationType, targetId, callback) { try { this.useConsole && console.log("clearMessages"); this.addon.clearMessages(conversationType, targetId); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; // Web 端接口,桌面版无需实现 VCDataProvider.prototype.setUnreadCount = function (conversationType, targetId, count) { }; VCDataProvider.prototype.getConversation = function (conversationType, targetId, callback) { try { this.useConsole && console.log("getConversation"); var ret = this.addon.getConversation(conversationType, targetId); callback.onSuccess(this.buildConversation(ret)); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.getConversationList = function (callback, conversationTypes, count, isGetHiddenConvers) { this.useConsole && console.log("getConversationList"); this.getRemoteConversationList(callback, conversationTypes, count, isGetHiddenConvers); }; VCDataProvider.prototype.clearCache = function () { var memoryStore = RongIMLib.RongIMClient._memoryStore || {}; memoryStore.conversationList = []; memoryStore.isSyncRemoteConverList; }; VCDataProvider.prototype.clearConversations = function (conversationTypes, callback) { try { this.useConsole && console.log("clearConversations"); this.addon.clearConversations(); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.setMessageContent = function (messageId, content, objectName) { content = JSON.stringify(content); this.addon.setMessageContent(messageId, content, objectName); }; VCDataProvider.prototype.setMessageSearchField = function (messageId, content, searchFiles) { this.addon.setMessageSearchField(messageId, content, searchFiles); }; VCDataProvider.prototype.getHistoryMessages = function (conversationType, targetId, timestamp, count, callback, objectname, direction) { this.useConsole && console.log("getHistoryMessages"); if (count <= 0) { callback.onError(RongIMLib.ErrorCode.TIMEOUT); return; } objectname = objectname || ''; direction = typeof direction == 'undefined' || direction; try { var ret = this.addon.getHistoryMessages(conversationType, targetId, timestamp ? timestamp : 0, count, objectname, direction); var list = ret ? JSON.parse(ret).list : [], msgs = [], me = this; list.reverse(); for (var i = 0, len = list.length; i < len; i++) { var message = me.buildMessage(list[i].obj); msgs[i] = message; } callback.onSuccess(msgs, len == count); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.clearRemoteHistoryMessages = function (params, callback) { var conversationType = params.conversationType; var targetId = params.targetId; var timestamp = params.timestamp; var _topic = { 1: true, 2: true, 3: true, 5: true, 6: true }; var topic = _topic[conversationType]; if (!topic) { callback.onError(RongIMLib.ErrorCode.CLEAR_HIS_TYPE_ERROR); return; } if (typeof timestamp != 'number') { callback.onError(RongIMLib.ErrorCode.CLEAR_HIS_TIME_ERROR); return; } this.addon.clearRemoteHistoryMessages(+conversationType, targetId, timestamp, function () { callback.onSuccess(true); }, function (errorCode) { if (errorCode == 1) { // 没有开通历史消息云存储 errorCode = RongIMLib.ErrorCode.CLEAR_HIS_ERROR; } callback.onError(errorCode); }); }; VCDataProvider.prototype.clearHistoryMessages = function (params, callback) { var conversationType = +params.conversationType; var targetId = params.targetId; try { this.addon.clearMessages(conversationType, targetId); var isSuccess = true; callback.onSuccess(isSuccess); } catch (e) { console.log(e); callback.onError(RongIMLib.ErrorCode.CLEAR_HIS_ERROR); } }; VCDataProvider.prototype.getTotalUnreadCount = function (callback, conversationTypes) { var result = 0; try { this.useConsole && console.log("getTotalUnreadCount"); if (conversationTypes) { result = this.addon.getTotalUnreadCount(conversationTypes); } else { result = this.addon.getTotalUnreadCount(); } callback.onSuccess(result); } catch (e) { callback.onError(e); } return result; }; VCDataProvider.prototype.getConversationUnreadCount = function (conversationTypes, callback) { this.useConsole && console.log("getConversationUnreadCount"); this.getTotalUnreadCount(callback, conversationTypes); }; VCDataProvider.prototype.getUnreadCount = function (conversationType, targetId, callback) { try { this.useConsole && console.log("getUnreadCount"); var result = this.addon.getUnreadCount(conversationType, targetId); callback.onSuccess(result); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.clearUnreadCount = function (conversationType, targetId, callback) { try { this.useConsole && console.log("clearUnreadCount"); var result = this.addon.clearUnreadCount(conversationType, targetId); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.clearTotalUnreadCount = function (callback) { this.useConsole && console.log("clearTotalUnreadCount"); }; VCDataProvider.prototype.clearUnreadCountByTimestamp = function (conversationType, targetId, timestamp, callback) { try { this.useConsole && console.log("clearUnreadCountByTimestamp"); var result = this.addon.clearUnreadCountByTimestamp(conversationType, targetId, timestamp); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.setConversationToTop = function (conversationType, targetId, isTop, callback) { try { this.useConsole && console.log("setConversationToTop"); this.addon.setConversationToTop(conversationType, targetId, isTop); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.setConversationHidden = function (conversationType, targetId, isHidden) { this.addon.setConversationHidden(conversationType, targetId, isHidden); }; VCDataProvider.prototype.setMessageReceivedStatus = function (messageId, receivedStatus, callback) { try { this.useConsole && console.log("setMessageReceivedStatus"); this.addon.setMessageReceivedStatus(messageId, receivedStatus); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.setMessageSentStatus = function (messageId, sentStatus, callback) { try { this.useConsole && console.log("setMessageSentStatus"); this.addon.setMessageSentStatus(messageId, sentStatus); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.getFileToken = function (fileType, callback) { this.useConsole && console.log("getFileToken"); this.addon.getUploadToken(fileType, function (token) { callback.onSuccess({ token: token }); }, function (errorCode) { callback.onError(errorCode); }); }; VCDataProvider.prototype.getFileUrl = function (fileType, fileName, oriName, callback) { this.useConsole && console.log("getFileUrl"); this.addon.getDownloadUrl(fileType, fileName, oriName, function (url) { callback.onSuccess({ downloadUrl: url }); }, function (errorCode) { callback.onError(errorCode); }); }; VCDataProvider.prototype.getPullSetting = function (callback) { this.useConsole && console.log("getPullSetting"); }; VCDataProvider.prototype.setOfflineMessageDuration = function (duration, callback) { this.useConsole && console.log("setOfflineMessageDuration"); }; VCDataProvider.prototype.searchConversationByContent = function (keyword, callback, conversationTypes) { var converTypes = []; if (typeof conversationTypes == 'undefined') { converTypes = [1, 2, 3, 4, 5, 6, 7]; } else { converTypes = conversationTypes; } try { this.useConsole && console.log("searchConversationByContent"); var result = this.addon.searchConversationByContent(converTypes, keyword); var list = JSON.parse(result).list, convers = [], me = this; list.reverse(); for (var i = 0, len = list.length; i < len; i++) { convers[i] = me.buildConversation(list[i].obj); } callback.onSuccess(convers); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.searchMessageByContent = function (conversationType, targetId, keyword, timestamp, count, total, callback) { var me = this; try { this.useConsole && console.log("searchMessageByContent"); this.addon.searchMessageByContent(conversationType, targetId, keyword, timestamp, count, total, function (ret, matched) { var list = ret ? JSON.parse(ret).list : [], msgs = []; list.reverse(); for (var i = 0, len = list.length; i < len; i++) { msgs[i] = me.buildMessage(list[i].obj); } callback.onSuccess(msgs, matched); }); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.getChatRoomInfo = function (chatRoomId, count, order, callback) { this.useConsole && console.log("getChatRoomInfo"); this.addon.getChatroomInfo(chatRoomId, count, order, function (ret, count) { var list = ret ? JSON.parse(ret).list : [], chatRoomInfo = { userInfos: [], userTotalNums: count }; if (list.length > 0) { for (var i = 0, len = list.length; i < len; i++) { chatRoomInfo.userInfos.push(JSON.parse(list[i].obj)); } } callback.onSuccess(chatRoomInfo); }, function (errcode) { callback.onError(errcode); }); }; VCDataProvider.prototype.setChatroomHisMessageTimestamp = function (chatRoomId, timestamp) { }; VCDataProvider.prototype.getChatRoomHistoryMessages = function (chatRoomId, count, order, callback) { }; VCDataProvider.prototype.getDelaTime = function () { return this.addon.getDeltaTime(); }; VCDataProvider.prototype.getUserStatus = function (userId, callback) { var me = this; this.addon.getUserStatus(userId, function (status) { var entity = RongIMLib.RongInnerTools.convertUserStatus({ status: status, userId: '' }); callback.onSuccess(entity); }, function (code) { callback.onError(code); }); }; VCDataProvider.prototype.setUserStatus = function (status, callback) { this.addon.setUserStatus(status, function () { callback.onSuccess(true); }, function (code) { callback.onError(code); }); }; VCDataProvider.prototype.subscribeUserStatus = function (userIds, callback) { this.addon.subscribeUserStatus(userIds, function () { callback && callback.onSuccess(true); }, function (code) { callback && callback.onError(code); }); }; VCDataProvider.prototype.setUserStatusListener = function (params, callback) { var me = this; this.addon.setOnReceiveStatusListener(function (userId, status) { var entity = RongIMLib.RongInnerTools.convertUserStatus({ userId: userId, status: status }); RongIMLib.RongIMClient.userStatusObserver.notify({ key: userId, entity: entity }); }); var userIds = params.userIds || []; if (userIds.length) { RongIMLib.RongIMClient._dataAccessProvider.subscribeUserStatus(userIds); } }; VCDataProvider.prototype.getUnreadMentionedMessages = function (conversationType, targetId) { var me = this; var mentions = JSON.parse(me.addon.getUnreadMentionedMessages(conversationType, targetId)).list; for (var i = 0, len = mentions.length; i < len; i++) { var temp = JSON.parse(mentions[i].obj); temp.content = JSON.parse(temp.content); mentions[i] = temp; } return mentions; }; VCDataProvider.prototype.hasRemoteUnreadMessages = function (token, callback) { callback.onSuccess(false); }; VCDataProvider.prototype.sendRecallMessage = function (content, sendMessageCallback) { var me = this; me.addon.recallMessage("RC:RcCmd", JSON.stringify(content), content.push || "", function () { content.objectName = 'RC:RcCmd'; sendMessageCallback.onSuccess(me.buildMessage(JSON.stringify(content))); }, function (errorCode) { sendMessageCallback.onError(errorCode); }); }; VCDataProvider.prototype.updateMessage = function (message, callback) { }; VCDataProvider.prototype.updateMessages = function (conversationType, targetId, key, value, callback) { }; VCDataProvider.prototype.reconnect = function (callback) { var token = RongIMLib.Bridge._client.token; this.disconnect(); this.connect(token, callback); }; VCDataProvider.prototype.sendReceiptResponse = function (conversationType, targetId, sendCallback) { }; VCDataProvider.prototype.setMessageExtra = function (messageId, value, callback) { }; VCDataProvider.prototype.addMemberToDiscussion = function (discussionId, userIdList, callback) { }; VCDataProvider.prototype.createDiscussion = function (name, userIdList, callback) { }; VCDataProvider.prototype.getDiscussion = function (discussionId, callback) { }; VCDataProvider.prototype.quitDiscussion = function (discussionId, callback) { }; VCDataProvider.prototype.removeMemberFromDiscussion = function (discussionId, userId, callback) { }; VCDataProvider.prototype.setDiscussionInviteStatus = function (discussionId, status, callback) { }; VCDataProvider.prototype.setDiscussionName = function (discussionId, name, callback) { }; VCDataProvider.prototype.setEnvironment = function (isPrivate) { this.addon.setEnvironment(isPrivate); }; VCDataProvider.prototype.addConversation = function (conversation, callback) { }; VCDataProvider.prototype.updateConversation = function (conversation) { return null; }; VCDataProvider.prototype.getConversationNotificationStatus = function (params, callback) { var conversationType = params.conversationType; var targetId = params.targetId; var notification = RongIMLib.RongIMClient._memoryStore.notification; var key = conversationType + '_' + targetId; var status = notification[key]; if (typeof status == 'number') { callback.onSuccess(status); return; } this.addon.getConversationNotificationStatus(conversationType, targetId, function (status) { notification[key] = status; callback.onSuccess(status); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.setConversationNotificationStatus = function (params, callback) { var conversationType = params.conversationType; var targetId = params.targetId; var status = params.status; var notification = RongIMLib.RongIMClient._memoryStore.notification; var key = conversationType + '_' + targetId; notification[key] = status; var notify = !!status; this.addon.setConversationNotificationStatus(conversationType, targetId, notify, function () { callback.onSuccess(status); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.getCurrentConnectionStatus = function () { return this.addon.getConnectionStatus(); }; VCDataProvider.prototype.getAgoraDynamicKey = function (engineType, channelName, callback) { var extra = ""; this.addon.getVoIPKey(engineType, channelName, extra, function (token) { callback.onSuccess(token); }, function (errorCode) { callback.onError(errorCode); }); }; VCDataProvider.prototype.getPublicServiceProfile = function (publicServiceType, publicServiceId, callback) { var profile = RongIMLib.RongIMClient._memoryStore.publicServiceMap.get(publicServiceType, publicServiceId); callback.onSuccess(profile); }; VCDataProvider.prototype.setDeviceInfo = function (device) { var id = device.id || ''; this.addon.setDeviceId(id); }; VCDataProvider.prototype.getRemotePublicServiceList = function (callback, pullMessageTime) { var publicList = []; var ret = this.addon.getAccounts(); var transformProto = function (ret) { var result = { hasFollowed: false, isGlobal: false, menu: null }; if (!ret.obj) { var error = { error: ret }; throw new Error('公众账号数据格式错误: ' + JSON.stringify(error)); } var obj = JSON.parse(ret.obj); var protoMap = { aType: 'conversationType', aId: 'publicServiceId', aName: 'introduction', aUri: 'portraitUri', follow: 'hasFollowed', isGlobal: 'isGlobal' }; for (var key in obj) { var val = obj[key]; if (key == 'aExtra') { var extra = JSON.parse(val); result["hasFollowed"] = extra.follow; result["isGlobal"] = extra.isGlobal; result["menu"] = extra.menu; } var uId = protoMap[key]; if (uId) { result[uId] = val; } } return result; }; if (ret) { ret = JSON.parse(ret); var list = ret.list; for (var i = 0, len = list.length; i < len; i++) { var item = list[i]; item = transformProto(item); publicList.push(item); } } if (publicList.length > 0) { RongIMLib.RongIMClient._memoryStore.publicServiceMap.publicServiceList.length = 0; RongIMLib.RongIMClient._memoryStore.publicServiceMap.publicServiceList = publicList; } callback.onSuccess(RongIMLib.RongIMClient._memoryStore.publicServiceMap.publicServiceList); }; VCDataProvider.prototype.buildMessage = function (result) { var message = new RongIMLib.Message(), ret = JSON.parse(result); message.conversationType = ret.conversationType; message.targetId = ret.targetId; message.messageDirection = ret.direction; message.senderUserId = ret.senderUserId; if (ret.direction == RongIMLib.MessageDirection.RECEIVE) { message.receivedStatus = ret.status; } else if (ret.direction == RongIMLib.MessageDirection.SEND) { message.sentStatus = ret.status; } message.sentTime = ret.sentTime; message.objectName = ret.objectName; var content = ret.content ? JSON.parse(ret.content) : ret.content; var messageType = typeMapping[ret.objectName] || registerMessageTypeMapping[ret.objectName]; if (content) { content.messageName = messageType; } message.content = content; message.messageId = ret.messageId; message.messageUId = ret.messageUid; message.messageType = messageType; return message; }; VCDataProvider.prototype.buildConversation = function (val) { if (val === '') { return null; } var conver = new RongIMLib.Conversation(), c = JSON.parse(val), lastestMsg = c.lastestMsg ? this.buildMessage(c.lastestMsg) : {}; conver.conversationTitle = c.title; conver.conversationType = c.conversationType; conver.draft = c.draft; conver.isTop = c.isTop; conver.isHidden = c.isHidden; lastestMsg.conversationType = c.conversationType; lastestMsg.targetId = c.targetId; conver.latestMessage = lastestMsg; conver.latestMessageId = lastestMsg.messageId; conver.latestMessage.messageType = typeMapping[lastestMsg.objectName] || registerMessageTypeMapping[lastestMsg.objectName]; conver.objectName = lastestMsg.objectName; conver.receivedStatus = RongIMLib.ReceivedStatus.READ; conver.sentTime = lastestMsg.sentTime; conver.senderUserId = lastestMsg.senderUserId; conver.sentStatus = lastestMsg.status; conver.targetId = c.targetId; conver.unreadMessageCount = c.unreadCount; conver.hasUnreadMention = c.m_hasUnreadMention; var mentions = this.getUnreadMentionedMessages(c.conversationType, c.targetId); if (mentions.length > 0) { // 取最后一条 @ 消息,原因:和 web 互相兼容 var mention = mentions.pop(); conver.mentionedMsg = { uid: mention.messageUid, time: mention.sentTime, mentionedInfo: mention.content.mentionedInfo, sendUserId: mention.senderUserId }; } return conver; }; VCDataProvider.prototype.getRTCUserInfoList = function (room, callback) { this.addon.getRTCUsers(room.id, 1, function (result) { callback.onSuccess(result); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.getRTCRoomInfo = function (room, callback) { var order = 2; this.addon.getRTCResouce(room.id, order, function (result) { callback.onSuccess(JSON.parse(result)); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.joinRTCRoom = function (room, callback) { var id = room.id; var type = room.type || 0; this.addon.joinRTCRoom(id, type, function (result, token) { var res = JSON.parse(result); var users = {}; var list = res.list; RongIMLib.RongUtil.forEach(list, function (item) { var userId = item.id; var tmpData = {}; RongIMLib.RongUtil.forEach(item.data, function (data) { var key = data.key; var value = data.value; tmpData[key] = value; }); users[userId] = tmpData; }); callback.onSuccess({ users: users, token: token }); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.quitRTCRoom = function (room, callback) { this.addon.exitRTCRoom(room.id, function () { callback.onSuccess(true); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.RTCPing = function (room, callback) { this.addon.sendRTCPing(room.id, function () { callback.onSuccess(true); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.setRTCData = function (roomId, key, value, isInner, apiType, callback, message) { var context = this; var hanlders = { room_inner: function (roomId, key, value, name, content, success, error) { context.addon.setRTCInnerData(roomId, RongIMLib.RTCAPIType.ROOM, key, value, name, content, success, error); }, room_outer: function (roomId, key, value, name, content, success, error) { context.addon.setRTCOuterData(roomId, RongIMLib.RTCAPIType.ROOM, key, value, name, content, success, error); }, user_inner: function (roomId, key, value, name, content, success, error) { context.addon.setRTCInnerData(roomId, RongIMLib.RTCAPIType.PERSON, key, value, name, content, success, error); }, user_outer: function (roomId, key, value, name, content, success, error) { context.addon.setRTCOuterData(roomId, RongIMLib.RTCAPIType.PERSON, key, value, name, content, success, error); } }; var type = RongIMLib.RTCAPIType.PERSON == apiType ? 'user' : 'room'; var direction = isInner ? 'inner' : 'outer'; var tpl = '{type}_{direction}'; var name = RongIMLib.RongUtil.tplEngine(tpl, { type: type, direction: direction }); var handler = hanlders[name]; if (handler) { message = message || {}; var name = message.name; var content = message.content; handler(roomId, key, value, name, content, function () { callback.onSuccess(true); }, function (code) { callback.onError(code); }); } }; VCDataProvider.prototype.setRTCRoomData = function (roomId, key, value, isInner, callback, message) { this.setRTCData(roomId, key, value, isInner, RongIMLib.RTCAPIType.ROOM, callback, message); }; VCDataProvider.prototype.getRTCData = function (roomId, keys, isInner, apiType, callback) { var context = this; var hanlders = { room_inner: function (roomId, keys, success, error) { context.addon.getRTCInnerData(roomId, RongIMLib.RTCAPIType.ROOM, keys, success, error); }, room_outer: function (roomId, keys, success, error) { context.addon.getRTCOuterData(roomId, RongIMLib.RTCAPIType.ROOM, keys, success, error); } }; var type = RongIMLib.RTCAPIType.PERSON == apiType ? 'user' : 'room'; var direction = isInner ? 'inner' : 'outer'; var tpl = '{type}_{direction}'; var name = RongIMLib.RongUtil.tplEngine(tpl, { type: type, direction: direction }); var handler = hanlders[name]; if (handler) { handler(roomId, keys, function (result) { var res = JSON.parse(result); var props = {}; var list = res.list; RongIMLib.RongUtil.forEach(list, function (item) { props[item.key] = item.value; }); callback.onSuccess(props); }, function (code) { callback.onError(code); }); } }; VCDataProvider.prototype.getRTCRoomData = function (roomId, keys, isInner, callback, message) { this.getRTCData(roomId, keys, isInner, RongIMLib.RTCAPIType.ROOM, callback); }; VCDataProvider.prototype.removeRTCData = function (roomId, keys, isInner, apiType, callback, message) { var context = this; var hanlders = { room_inner: function (roomId, keys, name, content, success, error) { context.addon.deleteRTCInnerData(roomId, RongIMLib.RTCAPIType.ROOM, keys, name, content, success, error); }, room_outer: function (roomId, keys, name, content, success, error) { context.addon.deleteRTCOuterData(roomId, RongIMLib.RTCAPIType.ROOM, keys, name, content, success, error); }, user_inner: function (roomId, keys, name, content, success, error) { }, user_outer: function (roomId, keys, name, content, success, error) { } }; var type = RongIMLib.RTCAPIType.PERSON == apiType ? 'user' : 'room'; var direction = isInner ? 'inner' : 'outer'; var tpl = '{type}_{direction}'; var name = RongIMLib.RongUtil.tplEngine(tpl, { type: type, direction: direction }); var handler = hanlders[name]; if (handler) { message = message || {}; var name = message.name || ''; var content = message.content || ''; handler(roomId, keys, name, content, function () { callback.onSuccess(true); }, function (code) { callback.onError(code); }); } }; VCDataProvider.prototype.removeRTCRoomData = function (roomId, keys, isInner, callback, message) { this.removeRTCData(roomId, keys, isInner, RongIMLib.RTCAPIType.ROOM, callback); }; VCDataProvider.prototype.getNavi = function () { var nav = this.addon.getNav(); return nav[this.userId]; }; // 信令 SDK 新增 VCDataProvider.prototype.setRTCOutData = function (roomId, data, type, callback, message) { }; // 信令 SDK 新增 VCDataProvider.prototype.getRTCOutData = function (roomId, userId, callback) { }; VCDataProvider.prototype.setRTCUserInfo = function (room, info, callback) { }; VCDataProvider.prototype.removeRTCUserInfo = function (room, info, callback) { }; VCDataProvider.prototype.getRTCUserList = function (room, callback) { }; VCDataProvider.prototype.setRTCRoomInfo = function (room, data, callback) { }; VCDataProvider.prototype.removeRTCRoomInfo = function (room, data, callback) { }; VCDataProvider.prototype.setRTCUserData = function (roomId, key, value, isInner, callback, message) { this.setRTCData(roomId, key, value, isInner, RongIMLib.RTCAPIType.PERSON, callback, message); }; VCDataProvider.prototype.getRTCUserData = function (roomId, key, isInner, callback, message) { }; VCDataProvider.prototype.removeRTCUserData = function (roomId, key, isInner, callback, message) { }; VCDataProvider.prototype.getRTCToken = function (room, callback) { }; VCDataProvider.prototype.setRTCState = function (room, content, callback) { }; return VCDataProvider; })(); RongIMLib.VCDataProvider = VCDataProvider; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { (function (LoggerLevel) { LoggerLevel[LoggerLevel["F"] = 0] = "F"; LoggerLevel[LoggerLevel["E"] = 1] = "E"; LoggerLevel[LoggerLevel["W"] = 2] = "W"; LoggerLevel[LoggerLevel["I"] = 3] = "I"; LoggerLevel[LoggerLevel["D"] = 4] = "D"; //debug })(RongIMLib.LoggerLevel || (RongIMLib.LoggerLevel = {})); var LoggerLevel = RongIMLib.LoggerLevel; (function (LoggerStoreSize) { LoggerStoreSize[LoggerStoreSize["ADVANCED"] = 500] = "ADVANCED"; LoggerStoreSize[LoggerStoreSize["LOW"] = 500] = "LOW"; })(RongIMLib.LoggerStoreSize || (RongIMLib.LoggerStoreSize = {})); var LoggerStoreSize = RongIMLib.LoggerStoreSize; var LoggerType = (function () { function LoggerType() { } LoggerType.IM = 'IM'; LoggerType.RTC = 'RTC'; return LoggerType; })(); RongIMLib.LoggerType = LoggerType; var LoggerTag = (function () { function LoggerTag() { } /** * 三段式关键字: "发起方-任务类型-结果类型" * A: App 层,L: Lib 层,N: 调用 Native 层接口,P: Protocol 层 * O: 操作,S: 状态,T: 任务,R: 结果,E: 错误 */ LoggerTag.IM = { A_INIT_O: 'A-init-O', A_CONN_T: 'A-connect-T', A_CONN_R: 'A-connect-R', A_CONN_E: 'A-connect-E', L_RECO_T: 'L-reconnect-T', L_RECO_R: 'L-reconnect-R', L_RECO_E: 'L-reconnect-E', L_GETN_T: 'L-get_navi-T', L_GETN_R: 'L-get_navi-R', L_PING_WS_T: 'L-ping_ws-T', L_PING_WS_R: 'L-ping_ws-R', L_NETC_S: 'L-network_changed-S', A_DISC_O: 'A-disconnect-O', A_JCTR_T: 'A-join_chatroom-T', A_JCTR_R: 'A-join_chatroom-R', A_QCTR_T: 'A-quit_chatroom-T', A_QCTR_R: 'A-quit_chatroom-R', A_INIT_CMD_MSG_E: 'A-instantiate_command_message-E', A_INIT_PROFILE_MSG_E: 'A-instantiate_profile_notify_message-E', A_INIT_CMD_NOTI_MSG_E: 'A-instantiate_command_notify_message-E', L_CHRM_PULL_E: 'L-chatroom_pull-E', L_QUERY_MSG_E: 'L-query_message-E', L_DECODE_MSG_E: 'L-decode_upstream_message-E', L_CATCH_UNKNOWN_MSG_E: 'L-catch_unknown_message-E', L_DECODE_QUERY_DATA_E: 'L-decode_query_data-E', L_PARSE_MSG_E: 'L-parse_message-E', L_WS_ERR_E: 'L-websocket-error-E', G_CRAW_E: 'G-crash-E', G_UP_LOG_S: 'G-upload_log-S', G_UP_LOG_E: 'G-upload_log-E' }; return LoggerTag; })(); RongIMLib.LoggerTag = LoggerTag; var LoggerReportType = (function () { function LoggerReportType() { } LoggerReportType.REAL_TIME_LOG = 'RealTimeLog'; LoggerReportType.MSG_NOTIF_LOG = 'MessageNotificationLog'; return LoggerReportType; })(); RongIMLib.LoggerReportType = LoggerReportType; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var Logger = (function () { function Logger() { } Logger.writeLog = function (log) { var self = this; if (RongIMLib.RongIMClient._memoryStore.loggerSwitch === "off") { return; } var networkUnavailable = RongIMLib.RongIMClient._memoryStore.networkUnavailable; var isLowLevelBro = RongIMLib.LoggerUtil.isLowLevelBro(); log.time = new Date().getTime(); log.sessionId = RongIMLib.LoggerUtil.getSessionId(); log.content = log.content && JSON.stringify(log.content); if (networkUnavailable) { if (log.level == RongIMLib.LoggerLevel.E || log.level == RongIMLib.LoggerLevel.W) { log.level = RongIMLib.LoggerLevel.I; } } self.logStore.push(log); var _handleOverflowLog = function (size) { if (self.logStore.length > size) { var delLength = self.logStore.length - size; self.logStore.splice(0, delLength); } }; if (isLowLevelBro) { _handleOverflowLog(RongIMLib.LoggerStoreSize.LOW); } else { _handleOverflowLog(RongIMLib.LoggerStoreSize.ADVANCED); } }; Logger.reportRTLog = function () { var self = this; var isUserCloseLogger = RongIMLib.RongIMClient._memoryStore.loggerSwitch === "off"; if (self.loggerCache.hasStarted || isUserCloseLogger) { return; } self.loggerCache.hasStarted = true; var policy = this.defaultLogPolicy; var isDefaultUpload = true; var currentTime = 1; var _robustUpload = function () { var isOpen = policy.logSwitch; var itv = policy.itv * 1000; var times = policy.times; var url = policy.url; var level = policy.level; var realItv = itv * Math.pow(2, currentTime - 1); if (currentTime < times) { currentTime++; } if (!isOpen) { return; } setTimeout(function () { var csvLog = RongIMLib.LoggerUtil.handleLog({ level: level, type: RongIMLib.LoggerReportType.REAL_TIME_LOG }); var encodeCsvLog = RongIMLib.TextCompressor.compress(csvLog); var entireUrl = RongIMLib.LoggerUtil.getEntireUrl({ url: url, type: RongIMLib.LoggerReportType.REAL_TIME_LOG }); if (self.loggerCache.isNewNavi) { currentTime = 1; policy = RongIMLib.LoggerUtil.getNaviPolicy(); self.loggerCache.isNewNavi = false; } if (isDefaultUpload) { currentTime = 1; isDefaultUpload = false; policy = RongIMLib.LoggerUtil.getNaviPolicy(); // 更新 navi 中配置下次用 } if (csvLog.length == 0) { policy = RongIMLib.LoggerUtil.getNaviPolicy(); _robustUpload(); return; } RongIMLib.RongUtil.request({ url: entireUrl, method: 'POST', body: encodeCsvLog, timeout: policy.timeout * 1000, success: function (data) { Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.G_UP_LOG_S, level: RongIMLib.LoggerLevel.D, type: RongIMLib.LoggerType.IM, content: { desc: 'report real-time log' } }); //第一次成功后,如果导航有数据使用导航数据,导航无数据关闭上传。第二次上传成功后返回数据使用返回数据 if (!isOpen) { return; } if (data) { data = JSON.parse(data); policy.itv = data.nextTime; policy.level = data.level; policy.logSwitch = data.logSwitch; currentTime = 1; } _robustUpload(); }, error: function (status, resText) { _robustUpload(); Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.G_UP_LOG_E, level: RongIMLib.LoggerLevel.D, type: RongIMLib.LoggerType.IM, content: { desc: 'report real-time log', status: status, resText: resText } }); } }); }, realItv); }; _robustUpload(); }; Logger.reportMNLog = function (policy) { var self = this; var currentTime = 1; var connectTime = RongIMLib.RongIMClient._memoryStore.connectAckTime; if (policy.platform !== 'Web' || policy.logId === self.loggerCache.logId) { return; } self.loggerCache.logId = policy.logId; var _robustUpload = function () { var itv = 5000; var times = 3; itv = itv * Math.pow(2, currentTime - 2); if (currentTime === 1) { itv = 0; } if (currentTime <= times) { currentTime++; } else { return; } setTimeout(function () { var csvLog = RongIMLib.LoggerUtil.handleLog({ level: RongIMLib.LoggerLevel.D, startTime: policy.startTime, endTime: policy.endTime, type: RongIMLib.LoggerReportType.MSG_NOTIF_LOG }); if (csvLog.length === 0 && policy.endTime < connectTime) { //没有日志且连接时间大于日志消息结束时间,说明此日志消息过期,无需上传 return; } else if (csvLog.length === 0 && policy.endTime > connectTime) { //没有日志且连接时间小于日志消息结束时间,说明用户连接时间在需要获取的时间内,没有日志上传 nodata csvLog = 'nodata'; } var encodeCsvLog = RongIMLib.TextCompressor.compress(csvLog); var entireUrl = RongIMLib.LoggerUtil.getEntireUrl({ url: policy.uri, logId: policy.logId, type: RongIMLib.LoggerReportType.MSG_NOTIF_LOG }); RongIMLib.RongUtil.request({ url: entireUrl, method: 'POST', body: encodeCsvLog, timeout: self.defaultLogPolicy.timeout * 1000, success: function () { Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.G_UP_LOG_S, level: RongIMLib.LoggerLevel.D, type: RongIMLib.LoggerType.IM, content: { desc: 'report message notification log' } }); }, error: function (status, resText) { _robustUpload(); Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.G_UP_LOG_E, level: RongIMLib.LoggerLevel.D, type: RongIMLib.LoggerType.IM, content: { desc: 'report message notification log', status: status, resText: resText } }); } }); }, itv); }; _robustUpload(); }; Logger.logStore = []; Logger.defaultLogPolicy = { "logSwitch": 1, "url": 'logcollection.ronghub.com/', "level": RongIMLib.LoggerLevel.E, "itv": 20, "times": 5, "timeout": 15 }; Logger.loggerCache = { userId: '', logId: 'none', isNewNavi: false, hasStarted: false }; return Logger; })(); RongIMLib.Logger = Logger; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var LoggerUtil = (function () { function LoggerUtil() { } LoggerUtil.isLowLevelBro = function () { var flag = false; var bro = RongIMLib.RongUtil.getBrower(); if (bro.type == 'IE' && bro.version < 9) { flag = true; } return flag; }; LoggerUtil.isRealTimeLogType = function (type) { return type === RongIMLib.LoggerReportType.REAL_TIME_LOG; }; LoggerUtil.handleLog = function (conf) { var self = this; var csvLog = ''; var logs = RongIMLib.Logger.logStore; var lastIndex = 0; if (self.isRealTimeLogType(conf.type)) { RongIMLib.RongUtil.forEach(logs, function (log, index) { if (log.time > self.lastTime && log.level <= conf.level) { csvLog += self.genCSVLog(log); lastIndex = index; } }); if (csvLog.length !== 0) { self.lastTime = logs[lastIndex].time; } } else { RongIMLib.RongUtil.forEach(logs, function (log) { if (log.level <= conf.level && log.time >= conf.startTime && log.time <= conf.endTime) { csvLog += self.genCSVLog(log); } }); } return csvLog; }; LoggerUtil.getNaviPolicy = function () { var navi = RongIMLib.RongIMClient._storageProvider.getItem("fullnavi") || "{}"; var fullNavi = navi && JSON.parse(navi); var policy = {}; var logPolicy = fullNavi.logPolicy || "{}"; var logSwitch = fullNavi.logSwitch; policy = logPolicy && JSON.parse(logPolicy); policy.logSwitch = logSwitch; return policy; }; LoggerUtil.genDeviceId = function () { var deviceId = ''; var key = 'deviceId'; var isSupportLS = RongIMLib.RongUtil.supportLocalStorage(); var isSupportSS = RongIMLib.RongUtil.supportSessionStorage(); var loggerStorage; if (isSupportLS) { loggerStorage = new RongIMLib.LocalStorageProvider(); } else if (isSupportSS) { loggerStorage = new RongIMLib.sessionStorageProvider(); } else { loggerStorage = new RongIMLib.MemeoryProvider(); } var hasDeviceId = loggerStorage.getItem(key); if (hasDeviceId) { deviceId = loggerStorage.getItem(key); } else { loggerStorage.removeItem(key); var uuid = RongIMLib.RongUtil.getUUID22(); loggerStorage.setItem(key, uuid); deviceId = uuid; } return deviceId; }; LoggerUtil.getSessionId = function () { var sessionId = ''; var key = 'sessionId'; var sessionStorage; var isSupportSS = RongIMLib.RongUtil.supportSessionStorage(); if (isSupportSS) { sessionStorage = new RongIMLib.sessionStorageProvider(); } else { sessionStorage = new RongIMLib.MemeoryProvider(); } var hasSessionId = sessionStorage.getItem(key); if (hasSessionId) { sessionId = sessionStorage.getItem(key); } else { sessionStorage.removeItem(key); var val = RongIMLib.RongUtil.getUUID22(); sessionStorage.setItem(key, val); sessionId = val; } return sessionId; }; LoggerUtil.getDeviceInfo = function () { var self = this; var browerInfo = RongIMLib.RongUtil.getBrower(); var sessionId = self.getSessionId().slice(0, 10); var infoTpl = '{brower}|{version}|{sessionId}'; return RongIMLib.RongUtil.tplEngine(infoTpl, { brower: browerInfo.type, version: browerInfo.version, sessionId: sessionId }); }; LoggerUtil.getEntireUrl = function (opt) { var self = this; var tLogTpl = '{protocol}{url}?version={version}&appkey={appkey}&userId={userId}&deviceId={deviceId}&deviceInfo={deviceInfo}&platform={platform}'; var mLogTpl = '{protocol}{url}?version={version}&appkey={appkey}&userId={userId}&logId={logId}&deviceId={deviceId}&deviceInfo={deviceInfo}&platform={platform}'; var entireUrl = ''; var protocol = "https://"; if (location.protocol == "http:") { protocol = "http://"; } var paramObj = { protocol: protocol, url: opt.url, version: RongIMLib.RongIMClient.sdkver || 'Unknown version', appkey: RongIMLib.RongIMClient._memoryStore.appKey || 'Unknown appkey', deviceId: self.genDeviceId(), deviceInfo: self.getDeviceInfo(), platform: 'Web', userId: RongIMLib.Logger.loggerCache.userId || '' }; if (self.isRealTimeLogType(opt.type)) { entireUrl = RongIMLib.RongUtil.tplEngine(tLogTpl, paramObj); } else { entireUrl = RongIMLib.RongUtil.tplEngine(mLogTpl, RongIMLib.RongUtil.extend(paramObj, { logId: opt.logId })); } return entireUrl; }; LoggerUtil.genCSVLog = function (log) { var tpl = '{sessionId},{time},{type},{level},{tag},{content}\n'; if (log.content) { var content = '"' + log.content.replace(/\"/g, '""') + '"'; } var csvLog = RongIMLib.RongUtil.tplEngine(tpl, { sessionId: log.sessionId, time: log.time, type: log.type, level: log.level, tag: log.tag, content: content || '""' }); return csvLog; }; LoggerUtil.isLogCmdMsg = function (message) { var flag = false; if (message.messageType === RongIMLib.RongIMClient.MessageType["LogCommandMessage"] && message.senderUserId === 'rongcloudsystem') { flag = true; } return flag; }; LoggerUtil.recordFatalLogOfNavi = function (internalRetry, navigators) { if (internalRetry === 3) { RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.L_GETN_R, level: RongIMLib.LoggerLevel.F, type: RongIMLib.LoggerType.IM, content: { desc: 'Request navigation failed 3 times', navigators: navigators } }); } }; LoggerUtil.lastTime = 0; return LoggerUtil; })(); RongIMLib.LoggerUtil = LoggerUtil; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var MemeoryProvider = (function () { function MemeoryProvider() { this._memeoryStore = {}; this.prefix = "rong_"; } MemeoryProvider.prototype.setItem = function (composedKey, object) { this._memeoryStore[composedKey] = decodeURIComponent(object); }; MemeoryProvider.prototype.getItem = function (composedKey) { return this._memeoryStore[composedKey]; }; MemeoryProvider.prototype.removeItem = function (composedKey) { if (this.getItem(composedKey)) { delete this._memeoryStore[composedKey]; } }; MemeoryProvider.prototype.getItemKey = function (regStr) { var me = this, item = null, reg = new RegExp(regStr + "\\w+"); for (var key in me._memeoryStore) { var arr = key.match(reg); if (arr) { item = key; } } return item; }; MemeoryProvider.prototype.getItemKeyList = function (regStr) { var prefix = this.prefix; var me = this, itemList = [], reg = new RegExp(regStr + "\\w+"); for (var key in me._memeoryStore) { var arr = key.match(reg); if (arr) { key = key.substring(prefix.length); itemList.push(key); } } return itemList; }; MemeoryProvider.prototype.clearItem = function () { var me = this; for (var key in me._memeoryStore) { delete me._memeoryStore[key]; } }; //单位:字节 MemeoryProvider.prototype.onOutOfQuota = function () { return 4 * 1024; }; return MemeoryProvider; })(); RongIMLib.MemeoryProvider = MemeoryProvider; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var LocalStorageProvider = (function () { // static _instance: LocalStorageProvider = new LocalStorageProvider(); function LocalStorageProvider() { this.prefix = 'rong_'; this._host = ""; var d = new Date(), m = d.getMonth() + 1, date = d.getFullYear() + '/' + (m.toString().length == 1 ? '0' + m : m) + '/' + d.getDate(), nowDate = new Date(date).getTime(); for (var key in localStorage) { if (key.lastIndexOf('RECEIVED') > -1) { var recObj = JSON.parse(localStorage.getItem(key)); for (var key_1 in recObj) { nowDate - recObj[key_1].dealtime > 0 && (delete recObj[key_1]); } if (RongIMLib.RongUtil.isEmpty(recObj)) { localStorage.removeItem(key); } else { localStorage.setItem(key, JSON.stringify(recObj)); } } if (key.lastIndexOf('SENT') > -1) { var sentObj = JSON.parse(localStorage.getItem(key)); nowDate - sentObj.dealtime > 0 && (localStorage.removeItem(key)); } } } LocalStorageProvider.prototype.setItem = function (composedKey, object) { if (composedKey) { composedKey.indexOf(this.prefix) == -1 && (composedKey = this.prefix + composedKey); localStorage.setItem(composedKey, object); } }; LocalStorageProvider.prototype.getItem = function (composedKey) { if (composedKey) { composedKey.indexOf(this.prefix) == -1 && (composedKey = this.prefix + composedKey); return localStorage.getItem(composedKey ? composedKey : ""); } return ""; }; LocalStorageProvider.prototype.getItemKey = function (composedStr) { var item = ""; var _key = this.prefix + composedStr; for (var key in localStorage) { if (key.indexOf(_key) == 0) { item = key; break; } } return item; }; LocalStorageProvider.prototype.getItemKeyList = function (composedStr) { var itemList = []; var prefix = this.prefix; var _key = prefix + composedStr; for (var key in localStorage) { if (key.indexOf(_key) == 0) { key = key.substring(prefix.length); itemList.push(key); } } return itemList; }; LocalStorageProvider.prototype.removeItem = function (composedKey) { if (composedKey) { composedKey.indexOf(this.prefix) == -1 && (composedKey = this.prefix + composedKey); localStorage.removeItem(composedKey.toString()); } }; LocalStorageProvider.prototype.clearItem = function () { var me = this; for (var key in localStorage) { if (key.indexOf(me.prefix) > -1) { me.removeItem(key); } } }; //单位:字节 LocalStorageProvider.prototype.onOutOfQuota = function () { return JSON.stringify(localStorage).length; }; return LocalStorageProvider; })(); RongIMLib.LocalStorageProvider = LocalStorageProvider; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var sessionStorageProvider = (function () { function sessionStorageProvider() { this.prefix = 'rong_'; this._host = ""; } sessionStorageProvider.prototype.setItem = function (composedKey, object) { if (composedKey) { composedKey.indexOf(this.prefix) == -1 && (composedKey = this.prefix + composedKey); sessionStorage.setItem(composedKey, object); } }; sessionStorageProvider.prototype.getItem = function (composedKey) { if (composedKey) { composedKey.indexOf(this.prefix) == -1 && (composedKey = this.prefix + composedKey); return sessionStorage.getItem(composedKey ? composedKey : ""); } return ''; }; sessionStorageProvider.prototype.getItemKey = function (composedStr) { var item = ""; var _key = this.prefix + composedStr; for (var key in sessionStorage) { if (key.indexOf(_key) == 0) { item = key; break; } } return item; }; sessionStorageProvider.prototype.getItemKeyList = function (composedStr) { var itemList = []; var prefix = this.prefix; var _key = prefix + composedStr; for (var key in sessionStorage) { if (key.indexOf(_key) == 0) { key = key.substring(prefix.length); itemList.push(key); } } return itemList; }; sessionStorageProvider.prototype.removeItem = function (composedKey) { if (composedKey) { composedKey.indexOf(this.prefix) == -1 && (composedKey = this.prefix + composedKey); sessionStorage.removeItem(composedKey.toString()); } }; sessionStorageProvider.prototype.clearItem = function () { var me = this; for (var key in sessionStorage) { if (key.indexOf(me.prefix) > -1) { me.removeItem(key); } } }; sessionStorageProvider.prototype.onOutOfQuota = function () { return JSON.stringify(sessionStorage).length; }; return sessionStorageProvider; })(); RongIMLib.sessionStorageProvider = sessionStorageProvider; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var UserDataProvider = (function () { function UserDataProvider() { this.opersistName = 'RongIMLib'; this.keyManager = 'RongUserDataKeyManager'; this._host = ""; this.prefix = "rong_"; this.oPersist = document.createElement("div"); this.oPersist.style.display = "none"; this.oPersist.style.behavior = "url('#default#userData')"; document.body.appendChild(this.oPersist); this.oPersist.load(this.opersistName); } UserDataProvider.prototype.setItem = function (key, value) { key && key.indexOf(this.prefix) == -1 && (key = this.prefix + key); this.oPersist.setAttribute(key, value); var keyNames = this.getItem(this.keyManager); keyNames ? keyNames.indexOf(key) == -1 && (keyNames += ',' + key) : (keyNames = key); this.oPersist.setAttribute(this.prefix + this.keyManager, keyNames); this.oPersist.save(this.opersistName); }; UserDataProvider.prototype.getItem = function (key) { key && key.indexOf(this.prefix) == -1 && (key = this.prefix + key); return key ? this.oPersist.getAttribute(key) : key; }; UserDataProvider.prototype.removeItem = function (key) { key && key.indexOf(this.prefix) == -1 && (key = this.prefix + key); this.oPersist.removeAttribute(key); this.oPersist.save(this.opersistName); var keyNames = this.getItem(this.keyManager), keyNameArray = keyNames && keyNames.split(',') || []; for (var i = 0, len = keyNameArray.length; i < len; i++) { if (keyNameArray[i] == key) { keyNameArray.splice(i, 1); } } this.oPersist.setAttribute(this.prefix + this.keyManager, keyNameArray.join(',')); this.oPersist.save(this.opersistName); }; UserDataProvider.prototype.getItemKey = function (composedStr) { var item = null, keyNames = this.getItem(this.keyManager), keyNameArray = keyNames && keyNames.split(',') || [], me = this; var _key = this.prefix + composedStr; if (keyNameArray.length) { for (var i = 0, len = keyNameArray.length; i < len; i++) { if (keyNameArray[i] && keyNameArray[i].indexOf(_key) == 0) { item = keyNameArray[i]; break; } } } return item; }; UserDataProvider.prototype.getItemKeyList = function (composedStr) { var itemList = [], keyNames = this.getItem(this.keyManager), keyNameArray = keyNames && keyNames.split(',') || []; var prefix = this.prefix; var _key = prefix + composedStr; if (keyNameArray.length) { for (var i = 0, len = keyNameArray.length; i < len; i++) { if (keyNameArray[i] && keyNameArray[i].indexOf(_key) == 0) { var keyName = keyNameArray[i]; keyName = keyName.substring(prefix.length); itemList.push(keyNameArray[i]); } } } return itemList; }; UserDataProvider.prototype.clearItem = function () { var keyNames = this.getItem(this.keyManager), keyNameArray = [], me = this; keyNames && (keyNameArray = keyNames.split(',')); if (keyNameArray.length) { for (var i = 0, len = keyNameArray.length; i < len; i++) { keyNameArray[i] && me.removeItem(keyNameArray[i]); } me.removeItem(me.keyManager); } }; UserDataProvider.prototype.onOutOfQuota = function () { return 10 * 1024 * 1024; }; return UserDataProvider; })(); RongIMLib.UserDataProvider = UserDataProvider; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var FeatureDectector = (function () { function FeatureDectector(callback) { this.script = document.createElement("script"); this.head = document.getElementsByTagName("head")[0]; if ("WebSocket" in window && "ArrayBuffer" in window && WebSocket.prototype.CLOSED === 3 && !RongIMLib.RongIMClient._memoryStore.depend.isPolling) { RongIMLib.Transportations._TransportType = RongIMLib.Socket.WEBSOCKET; if (!RongIMLib.RongIMClient.Protobuf) { var url = RongIMLib.RongIMClient._memoryStore.depend.protobuf; var script = this.script; script.src = url; this.head.appendChild(script); script.onload = script.onreadystatechange = function () { var isLoaded = (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete'); if (isLoaded) { // 防止 IE6、7 下偶发触发两次 loaded script.onload = script.onreadystatechange = null; if (callback) { callback(); } if (!callback) { var token = RongIMLib.RongIMClient._memoryStore.token; var connectCallback = RongIMLib.RongIMClient._memoryStore.callback; token && RongIMLib.RongIMClient.connect(token, connectCallback, null, { isIgnoreReportStart: true }); } } }; } } else { RongIMLib.Transportations._TransportType = "xhr-polling"; RongIMLib.RongIMClient.Protobuf = Polling; } } return FeatureDectector; })(); RongIMLib.FeatureDectector = FeatureDectector; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var FeaturePatcher = (function () { function FeaturePatcher() { } FeaturePatcher.prototype.patchAll = function () { this.patchJSON(); this.patchForEach(); }; FeaturePatcher.prototype.patchForEach = function () { if (!Array.forEach) { Array.forEach = function (arr, func) { for (var i = 0; i < arr.length; i++) { func.call(arr, arr[i], i, arr); } }; } }; FeaturePatcher.prototype.patchJSON = function () { if (!window["JSON"]) { window["JSON"] = (function () { function JSON() { } JSON.parse = function (sJSON) { return eval('(' + sJSON + ')'); }; JSON.stringify = function (value) { return this.str("", { "": value }); }; JSON.str = function (key, holder) { var i, k, v, length, mind = "", partial, value = holder[key], me = this; if (value && typeof value === "object" && typeof value.toJSON === "function") { value = value.toJSON(key); } switch (typeof value) { case "string": return me.quote(value); case "number": return isFinite(value) ? String(value) : "null"; case "boolean": case "null": return String(value); case "object": if (!value) { return "null"; } partial = []; if (Object.prototype.toString.apply(value) === "[object Array]") { length = value.length; for (i = 0; i < length; i += 1) { partial[i] = me.str(i, value) || "null"; } v = partial.length === 0 ? "[]" : "[" + partial.join(",") + "]"; return v; } for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = me.str(k, value); if (v) { partial.push(me.quote(k) + ":" + v); } } } v = partial.length === 0 ? "{}" : "{" + partial.join(",") + "}"; return v; } }; JSON.quote = function (string) { var me = this; me.rx_escapable.lastIndex = 0; return me.rx_escapable.test(string) ? '"' + string.replace(me.rx_escapable, function (a) { var c = me.meta[a]; return typeof c === "string" ? c : "\\u" + ("0000" + a.charCodeAt(0).toString(16)).slice(-4); }) + '"' : '"' + string + '"'; }; JSON.rx_escapable = new RegExp('[\\\"\\\\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]', "g"); JSON.meta = { "\b": "\\b", " ": "\\t", "\n": "\\n", "\f": "\\f", "\r": "\\r", '"': '\\"', "''": "\\''", "\\": "\\\\" }; return JSON; })(); } }; return FeaturePatcher; })(); RongIMLib.FeaturePatcher = FeaturePatcher; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var ScriptLoader = (function () { function ScriptLoader() { } ScriptLoader.prototype.load = function (src, onLoad, onError) { var script = document.createElement("script"); script.async = true; if (onLoad) { if (script.addEventListener) { script.addEventListener("load", function (event) { var target = event.target || event.srcElement; onLoad(target.src); }, false); } else if (script.readyState) { script.onreadystatechange = function (event) { var target = event.srcElement; onLoad(target.src); }; } } if (onError) { script.onerror = function (event) { var target = event.target || event.srcElement; onError(target.src); }; } (document.head || document.getElementsByTagName("head")[0]).appendChild(script); script.src = src; }; return ScriptLoader; })(); })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var PublicServiceMap = (function () { function PublicServiceMap() { this.publicServiceList = []; } PublicServiceMap.prototype.get = function (publicServiceType, publicServiceId) { for (var i = 0, len = this.publicServiceList.length; i < len; i++) { if (this.publicServiceList[i].conversationType == publicServiceType && publicServiceId == this.publicServiceList[i].publicServiceId) { return this.publicServiceList[i]; } } }; PublicServiceMap.prototype.add = function (publicServiceProfile) { var isAdd = true, me = this; for (var i = 0, len = this.publicServiceList.length; i < len; i++) { if (me.publicServiceList[i].conversationType == publicServiceProfile.conversationType && publicServiceProfile.publicServiceId == me.publicServiceList[i].publicServiceId) { this.publicServiceList.unshift(this.publicServiceList.splice(i, 1)[0]); isAdd = false; break; } } if (isAdd) { this.publicServiceList.unshift(publicServiceProfile); } }; PublicServiceMap.prototype.replace = function (publicServiceProfile) { var me = this; for (var i = 0, len = this.publicServiceList.length; i < len; i++) { if (me.publicServiceList[i].conversationType == publicServiceProfile.conversationType && publicServiceProfile.publicServiceId == me.publicServiceList[i].publicServiceId) { me.publicServiceList.splice(i, 1, publicServiceProfile); break; } } }; PublicServiceMap.prototype.remove = function (conversationType, publicServiceId) { var me = this; for (var i = 0, len = this.publicServiceList.length; i < len; i++) { if (me.publicServiceList[i].conversationType == conversationType && publicServiceId == me.publicServiceList[i].publicServiceId) { this.publicServiceList.splice(i, 1); break; } } }; return PublicServiceMap; })(); RongIMLib.PublicServiceMap = PublicServiceMap; /** * 会话工具类。 */ var ConversationMap = (function () { function ConversationMap() { this.conversationList = []; } ConversationMap.prototype.get = function (conversavtionType, targetId) { for (var i = 0, len = this.conversationList.length; i < len; i++) { if (this.conversationList[i].conversationType == conversavtionType && this.conversationList[i].targetId == targetId) { return this.conversationList[i]; } } return null; }; ConversationMap.prototype.add = function (conversation) { var isAdd = true; for (var i = 0, len = this.conversationList.length; i < len; i++) { if (this.conversationList[i].conversationType === conversation.conversationType && this.conversationList[i].targetId === conversation.targetId) { this.conversationList.unshift(this.conversationList.splice(i, 1)[0]); isAdd = false; break; } } if (isAdd) { this.conversationList.unshift(conversation); } }; /** * [replace 替换会话] * 会话数组存在的情况下调用add方法会是当前会话被替换且返回到第一个位置,导致用户本地一些设置失效,所以提供replace方法 */ ConversationMap.prototype.replace = function (conversation) { for (var i = 0, len = this.conversationList.length; i < len; i++) { if (this.conversationList[i].conversationType === conversation.conversationType && this.conversationList[i].targetId === conversation.targetId) { this.conversationList.splice(i, 1, conversation); break; } } }; ConversationMap.prototype.remove = function (conversation) { for (var i = 0, len = this.conversationList.length; i < len; i++) { if (this.conversationList[i].conversationType === conversation.conversationType && this.conversationList[i].targetId === conversation.targetId) { this.conversationList.splice(i, 1); break; } } }; return ConversationMap; })(); RongIMLib.ConversationMap = ConversationMap; var CheckParam = (function () { function CheckParam() { } CheckParam.getInstance = function () { if (!CheckParam._instance) { CheckParam._instance = new CheckParam(); } return CheckParam._instance; }; CheckParam.prototype.logger = function (code, funcName, msg) { RongIMLib.RongIMClient.logger({ code: code, funcName: funcName, msg: msg }); }; CheckParam.prototype.check = function (f, position, d, c) { if (RongIMLib.RongIMClient._dataAccessProvider || d) { for (var g = 0, e = c.length; g < e; g++) { if (!new RegExp(this.getType(c[g])).test(f[g])) { // throw new Error("The index of " + g + " parameter was wrong type " + this.getType(c[g]) + " [" + f[g] + "] -> position:" + position); var msg = "第" + (g + 1) + "个参数错误, 错误类型:" + this.getType(c[g]) + " [" + f[g] + "] -> 位置:" + position; this.logger("-3", position, msg); } } } else { var msg = "该参数不正确或尚未实例化RongIMClient -> 位置:" + position; this.logger("-4", position, msg); } }; CheckParam.prototype.getType = function (str) { var temp = Object.prototype.toString.call(str).toLowerCase(); return temp.slice(8, temp.length - 1); }; CheckParam.prototype.checkCookieDisable = function () { document.cookie = "checkCookie=1"; var arr = document.cookie.match(new RegExp("(^| )checkCookie=([^;]*)(;|$)")), isDisable = false; if (!arr) { isDisable = true; } document.cookie = "checkCookie=1;expires=Thu, 01-Jan-1970 00:00:01 GMT"; return isDisable; }; return CheckParam; })(); RongIMLib.CheckParam = CheckParam; var LimitableMap = (function () { function LimitableMap(limit) { this.map = {}; this.keys = []; this.limit = limit || 10; } LimitableMap.prototype.set = function (key, value) { this.map[key] = value; }; LimitableMap.prototype.get = function (key) { return this.map[key] || 0; }; LimitableMap.prototype.remove = function (key) { delete this.map[key]; }; return LimitableMap; })(); RongIMLib.LimitableMap = LimitableMap; var MemoryCache = (function () { function MemoryCache() { this.cache = {}; } MemoryCache.prototype.set = function (key, value) { this.cache[key] = value; }; MemoryCache.prototype.get = function (key) { return this.cache[key]; }; MemoryCache.prototype.remove = function (key) { delete this.cache[key]; }; return MemoryCache; })(); RongIMLib.MemoryCache = MemoryCache; var RongAjax = (function () { function RongAjax(options) { var me = this; me.xmlhttp = null; me.options = options; var hasCORS = typeof XMLHttpRequest !== "undefined" && "withCredentials" in new XMLHttpRequest(); if ("undefined" != typeof XMLHttpRequest && hasCORS) { me.xmlhttp = new XMLHttpRequest(); } else if ("undefined" != typeof XDomainRequest) { me.xmlhttp = new XDomainRequest(); } else { me.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } } RongAjax.prototype.send = function (callback) { var me = this; me.options.url || (me.options.url = "http://upload.qiniu.com/putb64/-1"); me.xmlhttp.onreadystatechange = function () { if (me.xmlhttp.readyState == 4) { if (me.options.type) { callback(); } else { callback(JSON.parse(me.xmlhttp.responseText.replace(/'/g, '"'))); } } }; me.xmlhttp.open("POST", me.options.url, true); me.xmlhttp.withCredentials = false; if ("setRequestHeader" in me.xmlhttp) { if (me.options.type) { me.xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=utf-8"); } else { me.xmlhttp.setRequestHeader("Content-type", "application/octet-stream"); me.xmlhttp.setRequestHeader('Authorization', "UpToken " + me.options.token); } } me.xmlhttp.send(me.options.type ? "appKey=" + me.options.appKey + "&deviceId=" + me.options.deviceId + "×tamp=" + me.options.timestamp + "&deviceInfo=" + me.options.deviceInfo + "&privateInfo=" + JSON.stringify(me.options.privateInfo) : me.options.base64); }; return RongAjax; })(); RongIMLib.RongAjax = RongAjax; function Prosumer() { var data = [], isConsuming = false; this.produce = function (res) { data.push(res); }; this.consume = function (callback, finished) { if (isConsuming) { return; } isConsuming = true; var next = function () { var res = data.shift(); if (RongUtil.isUndefined(res)) { isConsuming = false; finished && finished(); return; } callback(res, next); }; next(); }; this.isExeuting = function () { return isConsuming; }; } var RongUtil = (function () { function RongUtil() { } RongUtil.noop = function () { }; RongUtil.isEmpty = function (obj) { var result = true; if (RongUtil.isObject(obj)) { RongUtil.forEach(obj, function () { result = false; }); } if (RongUtil.isString(obj) || RongUtil.isArray(obj)) { return obj.length === 0; } if (RongUtil.isNumber(obj)) { return obj === 0; } return result; }; RongUtil.isLengthLimit = function (str, maxLen, minLen) { minLen = minLen || 0; var strLen = str.length; return strLen <= maxLen && strLen >= minLen; }; RongUtil.MD5 = function (str, key, raw) { return md5(str, key, raw); }; RongUtil.isObject = function (obj) { return Object.prototype.toString.call(obj) == '[object Object]'; }; RongUtil.isArray = function (array) { return Object.prototype.toString.call(array) == '[object Array]'; }; RongUtil.isString = function (array) { return Object.prototype.toString.call(array) == '[object String]'; }; RongUtil.isFunction = function (fun) { return Object.prototype.toString.call(fun) == '[object Function]'; }; ; RongUtil.isUndefined = function (str) { return Object.prototype.toString.call(str) == '[object Undefined]'; }; ; RongUtil.isNull = function (val) { return Object.prototype.toString.call(val) == '[object Null]'; }; RongUtil.isEqual = function (a, b) { return a === b; }; ; RongUtil.indexOf = function (arrs, item) { var index = -1; for (var i = 0; i < arrs.length; i++) { if (item === arrs[i]) { index = i; break; } } return index; }; RongUtil.stringFormat = function (tmpl, vals) { for (var i = 0, len = vals.length; i < len; i++) { var val = vals[i], reg = new RegExp("\\{" + (i) + "\\}", "g"); tmpl = tmpl.replace(reg, val); } return tmpl; }; RongUtil.tplEngine = function (temp, data, regexp) { if (!(Object.prototype.toString.call(data) === "[object Array]")) { data = [data]; } var ret = []; for (var i = 0, j = data.length; i < j; i++) { ret.push(replaceAction(data[i])); } return ret.join(""); function replaceAction(object) { return temp.replace(regexp || (/{([^}]+)}/g), function (match, name) { if (match.charAt(0) == '\\') { return match.slice(1); } return (object[name] != undefined) ? object[name] : '{' + name + '}'; }); } }; ; RongUtil.forEach = function (obj, callback) { callback = callback || RongUtil.noop; var loopObj = function () { for (var key in obj) { if (obj.hasOwnProperty(key)) { callback(obj[key], key, obj); } } }; var loopArr = function () { for (var i = 0, len = obj.length; i < len; i++) { callback(obj[i], i); } }; if (RongUtil.isObject(obj)) { loopObj(); } if (RongUtil.isArray(obj)) { loopArr(); } }; RongUtil.extend = function (source, target, callback, force) { RongUtil.forEach(source, function (val, key) { var hasProto = (key in target); if (force && hasProto) { target[key] = val; } if (!hasProto) { target[key] = val; } }); return target; }; RongUtil.createXHR = function () { var item = { XMLHttpRequest: function () { return new XMLHttpRequest(); }, XDomainRequest: function () { return new XDomainRequest(); }, ActiveXObject: function () { return new ActiveXObject('Microsoft.XMLHTTP'); } }; var isXHR = typeof XMLHttpRequest !== "undefined" && "withCredentials" in new XMLHttpRequest(); var isXDR = typeof XDomainRequest == 'function' || typeof XDomainRequest == 'object'; var key = isXHR ? 'XMLHttpRequest' : isXDR ? 'XDomainRequest' : 'ActiveXObject'; return item[key](); }; RongUtil.request = function (opts) { var url = opts.url; var body = opts.body; var success = opts.success; var error = opts.error || RongUtil.noop; var method = opts.method || 'GET'; var timeout = opts.timeout; var xhr = RongUtil.createXHR(); if ('onload' in xhr) { xhr.onload = function () { xhr.onload = RongUtil.noop; success(xhr.responseText); }; xhr.onerror = function () { error(xhr.status, xhr.responseText); xhr.onerror = RongUtil.noop; }; } else { xhr.onreadystatechange = function () { if (xhr.readyState == 4) { var status = xhr.status; if (status == 200) { success(xhr.responseText); } else { error(status, xhr.responseText); } } }; } xhr.open(method, url, true); if (timeout) { xhr.timeout = timeout; } if (body) { xhr.send(body); return xhr; } xhr.send(null); return xhr; }; RongUtil.getLocalProtocol = function () { var isLocationInvalid = typeof location !== 'object'; // 未找到全局 location 变量, 则协议为 https. 比如小程序 if (isLocationInvalid || location.protocol === 'https:') { return 'https://'; } else { return 'http://'; } }; RongUtil.formatProtoclPath = function (config) { var path = config.path; var protocol = config.protocol; var tmpl = config.tmpl || '{0}{1}'; var sub = config.sub; var flag = '://'; var index = path.indexOf(flag); var hasProtocol = (index > -1); if (hasProtocol) { index += flag.length; path = path.substring(index); } if (sub) { index = path.indexOf('/'); var hasPath = (index > -1); if (hasPath) { path = path.substr(0, index); } } return RongUtil.stringFormat(tmpl, [protocol, path]); }; ; RongUtil.getValidNavi = function (naviHost) { var HttpProtocol = RongIMLib.RongIMClient.HttpProtocol; var flag = '://'; var index = naviHost.indexOf(flag); var hasProtocol = index > -1; var navi = naviHost; if (!hasProtocol) { var protocol = RongIMLib.RongIMClient.getProtocol().protocol; navi = protocol + naviHost; } var naviProtocol = RongUtil.getUrlProtocol(navi), localProtocol = RongUtil.getLocalProtocol(); // 本地为 https, 但却传入 http 时, 强制转化为 https if (naviProtocol === HttpProtocol.http && localProtocol === 'https://') { navi = RongUtil.formatProtoclPath({ path: navi, tmpl: '{0}{1}', protocol: HttpProtocol.https, sub: true }); } return navi; }; RongUtil.getUrlProtocol = function (url) { var flag = '://'; var index = url.indexOf(flag); if (index > -1) { return url.substring(0, index + flag.length); } else { return 'https://'; } ; }; RongUtil.getUrlHost = function (url) { var index = RongUtil.indexOf(url, '/'); return url.substring(0, index); }; RongUtil.supportLocalStorage = function () { var support = false; if (typeof localStorage == 'object') { try { var key = 'RC_TMP_KEY', value = 'RC_TMP_VAL'; localStorage.setItem(key, value); var localVal = localStorage.getItem(key); if (localVal == value) { support = true; } } catch (err) { console.log('localStorage is disabled.'); } } return support; }; RongUtil.supportSessionStorage = function () { var support = false; if (typeof sessionStorage == 'object') { try { var key = 'RC_TMP_KEY', value = 'RC_TMP_VAL'; sessionStorage.setItem(key, value); var localVal = sessionStorage.getItem(key); if (localVal == value) { support = true; } } catch (err) { console.log('sessionStorage is disabled.'); } } return support; }; /* //返回新引用,不破坏原始对象 rename({n: 'martin'}, {n: 'name'}); => {name: 'martin'} rename([{n: 'martin'}, {a: 18}], {n: 'name', a: 'age'}); => [{name: 'martin'}, {age: 18}] */ RongUtil.rename = function (origin, newNames) { var isObject = RongUtil.isObject(origin); if (isObject) { origin = [origin]; } origin = JSON.parse(JSON.stringify(origin)); var updateProperty = function (val, key, obj) { delete obj[key]; key = newNames[key]; obj[key] = val; }; RongUtil.forEach(origin, function (item) { RongUtil.forEach(item, function (val, key, obj) { var isRename = (key in newNames); (isRename ? updateProperty : RongUtil.noop)(val, key, obj); }); }); return isObject ? origin[0] : origin; }; RongUtil.some = function (arrs, callback) { var has = false; for (var i = 0, len = arrs.length; i < len; i++) { if (callback(arrs[i])) { has = true; break; } } return has; }; RongUtil.keys = function (obj) { var props = []; for (var key in obj) { props.push(key); } return props; }; RongUtil.isNumber = function (num) { return Object.prototype.toString.call(num) == '[object Number]'; }; RongUtil.getTimestamp = function () { var date = new Date(); return date.getTime(); }; RongUtil.isSupportRequestHeaders = function () { var userAgent = navigator.userAgent; var isIE = window.ActiveXObject || 'ActiveXObject' in window; if (isIE) { var reIE = new RegExp('MSIE (\\d+\\.\\d+);'); reIE.test(userAgent); var fIEVersion = parseFloat(RegExp['$1']); return fIEVersion > 9; } return true; }; RongUtil.hasValidWsUrl = function (urls) { try { urls = JSON.parse(urls); } catch (e) { return false; } var validUrlList = RongUtil.getValidWsUrlList(urls); return validUrlList.length > 0; }; RongUtil.getValidWsUrlList = function (urls) { var invalidWsUrls = RongIMLib.RongIMClient.invalidWsUrls; var validUrlList = []; RongUtil.forEach(urls, function (url) { if (RongUtil.indexOf(invalidWsUrls, url) === -1) { validUrlList.push(url); } }); return validUrlList; }; RongUtil.isValidWsUrl = function (url) { var invalidWsUrls = RongIMLib.RongIMClient.invalidWsUrls; return invalidWsUrls.indexOf(url) === -1 && !RongUtil.isEmpty(url); }; RongUtil.getBrower = function () { var userAgent = navigator.userAgent; var version; var type; /* 记录各浏览器名字和匹配条件 */ var condition = { IE: /rv:([\d.]+)\) like Gecko|MSIE ([\d.]+)/, Edge: /Edge\/([\d.]+)/, Firefox: /Firefox\/([\d.]+)/, Opera: /(?:OPERA|OPR).([\d.]+)/, WeChat: /MicroMessenger\/([\d.]+)/, QQBrowser: /QQBrowser\/([\d.]+)/, Chrome: /Chrome\/([\d.]+)/, Safari: /Version\/([\d.]+).*Safari/, iOSChrome: /Mobile\/([\d.]+).*Safari/ }; for (var key in condition) { if (!condition.hasOwnProperty(key)) continue; var browserContent; if (browserContent = userAgent.match(condition[key])) { type = key; version = browserContent[1] || browserContent[2]; break; } } return { type: type || 'UnKonw', version: version || 'UnKonw' }; }; RongUtil.string10to64 = function (number) { var chars = '0123456789abcdefghigklmnopqrstuvwxyzABCDEFGHIGKLMNOPQRSTUVWXYZa0'.split(''), radix = chars.length + 1, qutient = +number, arr = []; do { var mod = qutient % radix; qutient = (qutient - mod) / radix; arr.unshift(chars[mod]); } while (qutient); return arr.join(''); }; RongUtil.getUUID = function () { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8); return v.toString(16); }); }; /* 获取 22 位的 UUID */ RongUtil.getUUID22 = function () { var uuid = this.getUUID(); uuid = uuid.replace(/-/g, '') + 'a'; uuid = parseInt(uuid, 16); uuid = this.string10to64(uuid); if (uuid.length > 22) { uuid = uuid.slice(0, 22); } if (uuid.length < 22) { var len = 22 - uuid.length; for (var i = 0; i < len; i++) { uuid = uuid + '0'; } } return uuid; }; RongUtil.getByteLength = function (str, charset) { charset = charset || 'utf-8'; var total = 0, chatCode; if (charset === 'utf-16') { for (var i = 0, max = str.length; i < max; i++) { chatCode = str.charCodeAt(i); if (chatCode <= 0xffff) { total += 2; } else { total += 4; } } } else { for (var i = 0, max = str.length; i < max; i++) { chatCode = str.charCodeAt(i); if (chatCode < 0x007f) { total += 1; } else if (chatCode <= 0x07ff) { total += 2; } else if (chatCode <= 0xffff) { total += 3; } else { total += 4; } } } return total; }; RongUtil.concat = function (before, after, isDedup) { RongUtil.forEach(after, function (item) { if (!isDedup || RongUtil.indexOf(before, item) === -1) { before.push(item); } }); return before; }; RongUtil.getCurrentDate = function (seperator) { var date = new Date(); var year = date.getFullYear(); var month = date.getMonth() + 1; var day = date.getDate(); return RongUtil.tplEngine('{year}{seperator}{month}{seperator}{day}', { year: year, month: month, day: day, seperator: seperator }); }; RongUtil.generateUploadFileName = function (type, fileName) { var tpl = '{type}__RC-{date}_{random}_{timestamp}{uuid}{extension}'; var random = Math.floor((Math.random() * 1000) % 10000); var uuid = this.getUUID(); var fileNameArr, extension; if (fileName) { fileNameArr = fileName.split('.'); extension = '.' + fileNameArr[fileNameArr.length - 1]; } return RongUtil.tplEngine(tpl, { type: type, date: RongUtil.getCurrentDate('-'), random: random, uuid: uuid, timestamp: RongUtil.getTimestamp(), extension: extension || '' }); }; RongUtil.Prosumer = Prosumer; RongUtil.Storage = { set: function (key, value) { try { RongIMLib.RongIMClient._storageProvider.setItem(key, JSON.stringify(value)); } catch (e) { } }, get: function (key) { var value = RongIMLib.RongIMClient._storageProvider.getItem(key); try { return JSON.parse(value); } catch (e) { return {}; } } }; return RongUtil; })(); RongIMLib.RongUtil = RongUtil; /* var observer = new RongObserver(); observer.watch({ key: 'key', func: function(entity){ } }); */ var RongObserver = (function () { function RongObserver() { this.watchers = {}; } RongObserver.prototype.genUId = function (key) { var time = new Date().getTime(); return [key, time].join('_'); }; RongObserver.prototype.watch = function (params) { var me = this; var key = params.key; var multiple = params.multiple; key = RongUtil.isArray(key) ? key : [key]; var func = params.func; RongUtil.forEach(key, function (k) { k = multiple ? me.genUId(k) : k; me.watchers[k] = func; }); }; RongObserver.prototype.notify = function (params) { var me = this; var key = params.key; var entity = params.entity; for (var k in me.watchers) { var isNotify = (k.indexOf(key) == 0); if (isNotify) { me.watchers[k](entity); } } }; RongObserver.prototype.remove = function () { }; return RongObserver; })(); RongIMLib.RongObserver = RongObserver; var Observer = (function () { function Observer() { this.observers = []; } Observer.prototype.add = function (observer, force) { if (force) { this.observers = [observer]; } if (RongUtil.isFunction(observer)) { this.observers.push(observer); } }; Observer.prototype.emit = function (data) { RongUtil.forEach(this.observers, function (observer) { observer(data); }); }; Observer.prototype.clear = function () { this.observers = []; }; Observer.prototype.checkIndexOutBound = function (index, bound) { var isOutBound = (index > -1 && index < bound); return isOutBound; }; Observer.prototype.removeAt = function (index) { var isOutBound = this.checkIndexOutBound(index, this.observers.length); if (isOutBound) { this.observers.splice(index, 1); } }; Observer.prototype.remove = function (observer) { var me = this; if (!observer) { me.clear(); return; } if (!RongUtil.isFunction(observer)) { return; } var observerList = me.observers; for (var i = observerList.length - 1; i >= 0; i--) { if (observer === observerList[i]) { me.removeAt(i); } } }; return Observer; })(); RongIMLib.Observer = Observer; var Timer = (function () { function Timer(config) { this.timeout = 0; this.timers = []; this.timeout = config.timeout; } Timer.prototype.resume = function (callback) { var timer = setTimeout(callback, this.timeout); this.timers.push(timer); }; Timer.prototype.pause = function () { RongUtil.forEach(this.timers, function (timer) { clearTimeout(timer); }); }; return Timer; })(); RongIMLib.Timer = Timer; var IndexTools = (function () { function IndexTools(config) { this.items = []; this.index = 0; this.onwheel = function () { }; this.items = config.items; this.onwheel = config.onwheel; } IndexTools.prototype.get = function () { var context = this; var items = context.items; var index = context.index; var isWheel = index >= items.length; if (isWheel) { context.onwheel(); } return isWheel ? 0 : index; }; IndexTools.prototype.add = function () { this.index += 1; }; return IndexTools; })(); RongIMLib.IndexTools = IndexTools; var InnerUtil = (function () { function InnerUtil() { } InnerUtil.getUId = function (token) { return md5(token).slice(8, 16); }; return InnerUtil; })(); RongIMLib.InnerUtil = InnerUtil; var Base64 = (function () { function Base64() { } Base64.utf8_encode = function (string) { string = string.replace(/\r\n/g, "\n"); var utftext = ""; for (var n = 0; n < string.length; n++) { var c = string.charCodeAt(n); if (c < 128) { utftext += String.fromCharCode(c); } else if ((c > 127) && (c < 2048)) { utftext += String.fromCharCode((c >> 6) | 192); utftext += String.fromCharCode((c & 63) | 128); } else { utftext += String.fromCharCode((c >> 12) | 224); utftext += String.fromCharCode(((c >> 6) & 63) | 128); utftext += String.fromCharCode((c & 63) | 128); } } return utftext; }; Base64.utf8_decode = function (utftext) { var string = ""; var i = 0; var c = 0, c1 = 0, c2 = 0, c3; while (i < utftext.length) { c = utftext.charCodeAt(i); if (c < 128) { string += String.fromCharCode(c); i++; } else if ((c > 191) && (c < 224)) { c2 = utftext.charCodeAt(i + 1); string += String.fromCharCode(((c & 31) << 6) | (c2 & 63)); i += 2; } else { c2 = utftext.charCodeAt(i + 1); c3 = utftext.charCodeAt(i + 2); string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)); i += 3; } } return string; }; Base64.encode = function (input) { var output = ""; var chr1, chr2, chr3, enc1, enc2, enc3, enc4; var i = 0; input = this.utf8_encode(input); while (i < input.length) { chr1 = input.charCodeAt(i++); chr2 = input.charCodeAt(i++); chr3 = input.charCodeAt(i++); enc1 = chr1 >> 2; enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); enc4 = chr3 & 63; if (isNaN(chr2)) { enc3 = enc4 = 64; } else if (isNaN(chr3)) { enc4 = 64; } output = output + this.keyStr.charAt(enc1) + this.keyStr.charAt(enc2) + this.keyStr.charAt(enc3) + this.keyStr.charAt(enc4); } return output; }; Base64.decode = function (input) { var output = ""; var chr1, chr2, chr3; var enc1, enc2, enc3, enc4; var i = 0; input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ""); while (i < input.length) { enc1 = this.keyStr.indexOf(input.charAt(i++)); enc2 = this.keyStr.indexOf(input.charAt(i++)); enc3 = this.keyStr.indexOf(input.charAt(i++)); enc4 = this.keyStr.indexOf(input.charAt(i++)); chr1 = (enc1 << 2) | (enc2 >> 4); chr2 = ((enc2 & 15) << 4) | (enc3 >> 2); chr3 = ((enc3 & 3) << 6) | enc4; output = output + String.fromCharCode(chr1); if (enc3 != 64) { output = output + String.fromCharCode(chr2); } if (enc4 != 64) { output = output + String.fromCharCode(chr3); } } output = this.utf8_decode(output); return output; }; Base64.keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; return Base64; })(); RongIMLib.Base64 = Base64; var TextCompressor = (function () { function TextCompressor() { } TextCompressor.compress = function (data) { var self = this; var map = {}; //构建一个用于反向查询字符位置的 map for (var p = 0; p < data.length - 1; p++) { var c1 = data.charAt(p); var c2 = data.charAt(p + 1); var c = c1 + c2; if (!map.hasOwnProperty(c)) { map[c] = [p]; continue; } map[c].push(p); } var compressedData = [], normalBlockBuffer = []; //编码未压缩数据块 var encodeNormalBlock = function () { if (normalBlockBuffer.length > 0) { var normalBlock = normalBlockBuffer.join(''); normalBlockBuffer = []; if (normalBlock.length > 26) { var normalExtBlockLength = self.numberEncode(normalBlock.length); var normalExtBlockHeader = String.fromCharCode(self.dataType.NormalExt | normalExtBlockLength.length); compressedData.push(normalExtBlockHeader + normalExtBlockLength); } else { var normalBlockHeader = String.fromCharCode(self.dataType.Normal | normalBlock.length); compressedData.push(normalBlockHeader); } compressedData.push(normalBlock); } }; var i = 0; while (i < data.length) { var r = self.indexOf(map, data, i); if (r.length < 2) { normalBlockBuffer.push(data.charAt(i++)); continue; } if (r.length < 4) { normalBlockBuffer.push(data.substr(i, r.length)); i += r.length; continue; } var offset = self.numberEncode(i - r.offset); var length = self.numberEncode(r.length); //欲压缩的数据与数据编码后的长度一致,则不进行压缩 if (offset.length + length.length >= r.length) { normalBlockBuffer.push(data.substr(i, r.length)); i += r.length; continue; } //编码未压缩数据块 encodeNormalBlock(); //编码压缩数据块 var compressedBlockHeader = String.fromCharCode(self.dataType.Compressed | (offset.length << 2) | length.length); compressedData.push(compressedBlockHeader + offset + length); i += r.length; } //编码剩余未压缩数据块 encodeNormalBlock(); //在数据尾部添加校验和 var dataLengthTo62 = self.numberEncode(data.length); var tailBlockHeader = String.fromCharCode(self.dataType.Tail | dataLengthTo62.length); compressedData.push(tailBlockHeader + dataLengthTo62); return compressedData.join(''); }; TextCompressor.uncompress = function (data) { var self = this; var i = 0; var result = ""; label1: do { var header = data.charCodeAt(i++); var headerType = header & self.dataType.Mark; var headerVal = header & 0xF; switch (headerType) { case self.dataType.Compressed: var p1 = headerVal >> 2; var p2 = headerVal & 3; if (p1 == 0 || p2 == 0) { throw new Error("Data parsing error,at " + i); } var offset = self.numberDecode(data.substr(i, p1)); var len = self.numberDecode(data.substr(i += p1, p2)); offset = result.length - offset; if (offset + len > result.length) { throw new Error("Data parsing error,at " + i); } i += p2; result += result.substr(offset, len); break; case self.dataType.Tail: var num = self.numberDecode(data.substr(i, headerVal)); if (num != result.length) { console.log(result.length); console.log(num); throw new Error("Data parsing error,at " + i); } i += headerVal; break label1; case self.dataType.NormalExt: var num = self.numberDecode(data.substr(i, headerVal)); result += data.substr(i += headerVal, num); i += num; break; case self.dataType.Normal: result += data.substr(i, headerVal); i += headerVal; break; case self.dataType.Mark: if (headerVal > 10) { throw new Error("Data parsing error,at " + i); } result += data.substr(i, 16 + headerVal); i += (16 + headerVal); break; default: throw new Error("Data parsing error,at " + i + " header:" + headerType); } } while (i < data.length); return result; }; TextCompressor.indexOf = function (map, source, fromIndex) { var self = this; var result = { length: 0, offset: -1 }; var sourceLength = source.length; if (fromIndex >= source.length - 1) { return result; } var c1 = source.charAt(fromIndex); var c2 = source.charAt(fromIndex + 1); var items = map[c1 + c2]; if (items[0] == fromIndex) { return result; } var space1 = source.length - fromIndex; var lastChar; for (var i = 0, len = items.length; i < len; i++) { var item = items[i]; var space2 = fromIndex - item; if (space2 > self.max) { continue; } var end = Math.min(space1, space2); if (end <= result.length) { break; } if (result.length > 2) { if (source.charAt(item + result.length - 1) != source.charAt(fromIndex + result.length - 1)) { continue; } } var m = 2; for (var j = m; j < end; j++) { if (source.charAt(item + j) == source.charAt(fromIndex + j)) { m++; } else { break; } } if (m >= result.length) { result.length = m; result.offset = item; } } return result; }; /* * 将数字转化为 62 进制字符串。 */ TextCompressor.numberEncode = function (num) { var self = this; var result = [], remainder = 0; do { remainder = num % self.scale; result.push(self.chars.charAt(remainder)); num = (num - remainder) / self.scale; } while (num > 0); return result.join(''); }; /* * 将 62 进制字符串还原为数字。 */ TextCompressor.numberDecode = function (str) { var self = this; var num = 0, index = 0; for (var i = str.length - 1; i >= 0; i--) { index = self.chars.indexOf(str.charAt(i)); if (index == -1) { throw new Error("decode number error, data is \"" + str + "\""); } num = num * self.scale + index; } return num; }; TextCompressor.dataType = { Tail: 0x30, Compressed: 0x40, NormalExt: 0x50, Normal: 0x60, Mark: 0x70 }; TextCompressor.chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; TextCompressor.scale = TextCompressor.chars.length; TextCompressor.max = 238327; return TextCompressor; })(); RongIMLib.TextCompressor = TextCompressor; })(RongIMLib || (RongIMLib = {})); // {WebEnd} WebSDK 内容开始的标识, 方便小程序 SDK 定位 /* 说明: 请勿修改 header.js 和 footer.js 用途: 自动拼接暴露方式 命令: grunt release 中 concat */ return RongIMLib; }); ================================================ FILE: api-test-v2/lib/js/RongIMLib.js ================================================ /* 说明: 请勿修改 header.js 和 footer.js 用途: 自动拼接暴露方式 命令: grunt release 中 concat */ (function(global, factory) { if (typeof exports === 'object' && typeof module !== 'undefined') { module.exports = factory(); } else if (typeof define === 'function' && (define.amd || define.cmd)) { define(factory); } else { var tempIMLib = factory(); var tempClient = tempIMLib.RongIMClient; var isExists = (!!global.RongIMLib); if (isExists) { var currentClient = RongIMLib.RongIMClient || {}; for(var key in currentClient){ tempClient[key] = currentClient[key]; } } global.RongIMLib = tempIMLib; global.RongIMClient = tempClient; } })(window, function(){ // {WebStart} WebSDK 内容开始的标识, 方便小程序 SDK 定位 var Polling = { SetUserStatusInput: function(){ var a = {}; this.setStatus = function(b){ a.status = b; }; this.toArrayBuffer = function(){ return a; }; }, SetUserStatusOutput: function(){ var a = {}; this.setNothing = function(b){ a.nothing = b; }; this.toArrayBuffer = function(){ return a; }; }, GetUserStatusInput: function(){ var a = {}; this.setNothing = function(b){ a.nothing = b; }; this.toArrayBuffer = function(){ return a; }; }, GetUserStatusOutput: function(){ var a = {}; this.setStatus = function(b){ a.status = b; }; this.setSubUserId = function(b){ a.subUserId = b; }; this.toArrayBuffer = function(){ return a; }; }, VoipDynamicInput: function(){ var a = {}; this.setEngineType = function(b){ a.engineType = b; }; this.setChannelName = function(b){ a.channelName = b; }; this.setChannelExtra = function(b){ a.channelExtra = b; }; this.toArrayBuffer = function(){ return a; }; }, VoipDynamicOutput: function(){ var a = {}; this.setDynamicKey = function(b){ a.dynamicKey = b; }; this.toArrayBuffer = function(){ return a; }; }, SubUserStatusInput: function(){ var a = {}; this.setUserid = function(b){ a.userid = b; }; this.toArrayBuffer = function(){ return a; }; }, SubUserStatusOutput: function(){ var a = {}; this.setNothing = function(b){ a.nothing = b; }; this.toArrayBuffer = function(){ return a; }; }, CleanHisMsgInput: function(){ var a = {}; this.setTargetId = function(b){ a.targetId = b; }; this.setDataTime = function(b){ a.dataTime = b; }; this.setConversationType = function(b){ a.conversationType = b; }; this.toArrayBuffer = function(){ return a; }; }, DeleteMsgInput:function(){ var a = {}; this.setType = function(b){ a.type = b; }; this.setConversationId = function(b){ a.conversationId = b; }; this.setMsgs = function(b){ a.msgs = b; }; this.toArrayBuffer = function () { return a; } }, DeleteMsg:function(){ var a = {}; this.setMsgId = function(b){ a.msgId = b; }; this.setMsgDataTime = function(b){ a.msgDataTime = b; }; this.setDirect = function(b){ a.direct = b; }; this.toArrayBuffer = function () { return a; } }, DeleteMsgOutput:function(){ var a = {}; this.setNothing = function(b){ a.nothing = b; }; this.toArrayBuffer = function () { return a; } }, SearchMpInput:function(){ var a = {}; this.setType = function (b) { a.type = b; }; this.setId = function (b) { a.id = b; }; this.toArrayBuffer = function () { return a; } }, SearchMpOutput:function(){ var a = {}; this.setNothing = function (b) { a.nothing = b; }; this.setInfo = function (b) { a.info = b; }; this.toArrayBuffer = function () { return a; } }, MpInfo:function(){ var a = {}; this.setMpid = function(b){ a.mpid = b; }; this.setName = function(b){ a.name = b; }; this.setType = function(b){ a.type = b; }; this.setTime = function(b){ a.time = b; }; this.setPortraitUri = function(b){ a.portraitUrl = b; }; this.setExtra = function(b){ a.extra = b; }; this.toArrayBuffer = function () { return a; } }, PullMpInput:function(){ var a = {}; this.setMpid = function(b){ a.mpid = b; }; this.setTime = function(b){ a.time = b; }; this.toArrayBuffer = function () { return a; }; }, PullMpOutput:function(){ var a = {}; this.setStatus = function(b){ a.status = b; } this.setInfo = function(b){ a.info = b; }; this.toArrayBuffer = function () { return a; }; }, MPFollowInput:function(){ var a = {}; this.setId = function(b){ a.id = b; }; this.toArrayBuffer = function () { return a; }; }, MPFollowOutput:function(){ var a = {}; this.setNothing = function(b){ a.nothing = b; }; this.setInfo = function(b){ a.info = b; }; this.toArrayBuffer = function () { return a; }; }, NotifyMsg: function () { var a = {}; this.setType = function (b) { a.type = b; }; this.setTime = function (b) { a.time = b; }; this.setChrmId = function(b){ a.chrmId = b; }; this.toArrayBuffer = function () { return a; }; }, SyncRequestMsg: function () { var a = {}; this.setSyncTime = function (b) { a.syncTime = b || 0; }; this.setIspolling = function (b) { a.ispolling = !!b; }; this.setIsweb = function (b) { a.isweb = !!b; }; this.setIsPullSend = function (b) { a.isPullSend = !!b; }; this.setSendBoxSyncTime = function (b) { a.sendBoxSyncTime = b; }; this.toArrayBuffer = function () { return a; }; }, UpStreamMessage: function () { var a = {}; this.setSessionId = function (b) { a.sessionId = b }; this.setClassname = function (b) { a.classname = b }; this.setContent = function (b) { if (b) a.content = b; }; this.setPushText = function (b) { a.pushText = b }; this.setUserId = function(b){ a.userId = b; }; this.setConfigFlag = function (b) { a.configFlag = b; }; this.setAppData = function(b){ a.appData = b; }; this.toArrayBuffer = function () { return a }; }, DownStreamMessages: function () { var a = {}; this.setList = function (b) { a.list = b }; this.setSyncTime = function (b) { a.syncTime = b; }; this.setFinished = function(b){ a.finished = b; }; this.toArrayBuffer = function () { return a }; }, DownStreamMessage: function () { var a = {}; this.setFromUserId = function (b) { a.fromUserId = b }; this.setType = function (b) { a.type = b }; this.setGroupId = function (b) { a.groupId = b }; this.setClassname = function (b) { a.classname = b }; this.setContent = function (b) { if (b) a.content = b }; this.setDataTime = function (b) { a.dataTime = b; }; this.setStatus = function (b) { a.status = b; }; this.setMsgId = function (b) { a.msgId = b; }; this.toArrayBuffer = function () { return a; }; }, CreateDiscussionInput: function () { var a = {}; this.setName = function (b) { a.name = b }; this.toArrayBuffer = function () { return a } }, CreateDiscussionOutput: function () { var a = {}; this.setId = function (b) { a.id = b }; this.toArrayBuffer = function () { return a }; }, ChannelInvitationInput: function () { var a = {}; this.setUsers = function (b) { a.users = b }; this.toArrayBuffer = function () { return a }; }, LeaveChannelInput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b }; this.toArrayBuffer = function () { return a }; }, QueryChatroomInfoInput:function(){ var a = {}; this.setCount = function (b) { a.count = b; }; this.setOrder = function (b) { a.order = b; }; this.toArrayBuffer = function () { return a }; }, QueryChatroomInfoOutput:function(){ var a = {}; this.setUserTotalNums = function (b) { a.userTotalNums = b; }; this.setUserInfos = function (b) { a.userInfos = b; }; this.toArrayBuffer = function () { return a; }; }, ChannelEvictionInput: function () { var a = {}; this.setUser = function (b) { a.user = b }; this.toArrayBuffer = function () { return a }; }, RenameChannelInput: function () { var a = {}; this.setName = function (b) { a.name = b }; this.toArrayBuffer = function () { return a } }, ChannelInfoInput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b }; this.toArrayBuffer = function () { return a } }, ChannelInfoOutput: function () { var a = {}; this.setType = function (b) { a.type = b }; this.setChannelId = function (b) { a.channelId = b }; this.setChannelName = function (b) { a.channelName = b }; this.setAdminUserId = function (b) { a.adminUserId = b }; this.setFirstTenUserIds = function (b) { a.firstTenUserIds = b }; this.setOpenStatus = function (b) { a.openStatus = b }; this.toArrayBuffer = function () { return a } }, ChannelInfosInput: function () { var a = {}; this.setPage = function (b) { a.page = b }; this.setNumber = function (b) { a.number = b }; this.toArrayBuffer = function () { return a }; }, ChannelInfosOutput: function () { var a = {}; this.setChannels = function (b) { a.channels = b }; this.setTotal = function (b) { a.total = b }; this.toArrayBuffer = function () { return a }; }, MemberInfo: function () { var a = {}; this.setUserId = function (b) { a.userId = b }; this.setUserName = function (b) { a.userName = b }; this.setUserPortrait = function (b) { a.userPortrait = b }; this.setExtension = function (b) { a.extension = b }; this.toArrayBuffer = function () { return a }; }, GroupMembersInput: function () { var a = {}; this.setPage = function (b) { a.page = b }; this.setNumber = function (b) { a.number = b }; this.toArrayBuffer = function () { return a }; }, GroupMembersOutput: function () { var a = {}; this.setMembers = function (b) { a.members = b }; this.setTotal = function (b) { a.total = b }; this.toArrayBuffer = function () { return a }; }, GetUserInfoInput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b }; this.toArrayBuffer = function () { return a }; }, GetUserInfoOutput: function () { var a = {}; this.setUserId = function (b) { a.userId = b }; this.setUserName = function (b) { a.userName = b }; this.setUserPortrait = function (b) { a.userPortrait = b }; this.toArrayBuffer = function () { return a }; }, GetSessionIdInput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b }; this.toArrayBuffer = function () { return a }; }, GetSessionIdOutput: function () { var a = {}; this.setSessionId = function (b) { a.sessionId = b }; this.toArrayBuffer = function () { return a }; }, GetQNupTokenInput: function () { var a = {}; this.setType = function (b) { a.type = b; } this.toArrayBuffer = function () { return a } }, GetQNupTokenOutput: function () { var a = {}; this.setDeadline = function (b) { a.deadline = b }; this.setToken = function (b) { a.token = b; }; this.toArrayBuffer = function () { return a } }, GetQNdownloadUrlInput: function () { var a = {}; this.setType = function (b) { a.type = b; }; this.setKey = function (b) { a.key = b; }; this.setFileName = function(b){ a.fileName = b; }; this.toArrayBuffer = function () { return a } }, GetQNdownloadUrlOutput: function () { var a = {}; this.setDownloadUrl = function (b) { a.downloadUrl = b; }; this.toArrayBuffer = function () { return a } }, Add2BlackListInput: function () { var a = {}; this.setUserId = function (b) { a.userId = b; }; this.toArrayBuffer = function () { return a } }, RemoveFromBlackListInput: function () { var a = {}; this.setUserId = function (b) { a.userId = b; }; this.toArrayBuffer = function () { return a } }, QueryBlackListInput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b; }; this.toArrayBuffer = function () { return a } }, QueryBlackListOutput: function () { var a = {}; this.setUserIds = function (b) { a.userIds = b; }; this.toArrayBuffer = function () { return a } }, BlackListStatusInput: function () { var a = {}; this.setUserId = function (b) { a.userId = b; }; this.toArrayBuffer = function () { return a } }, BlockPushInput: function () { var a = {}; this.setBlockeeId = function (b) { a.blockeeId = b; }; this.toArrayBuffer = function () { return a } }, ModifyPermissionInput: function () { var a = {}; this.setOpenStatus = function (b) { a.openStatus = b; }; this.toArrayBuffer = function () { return a }; }, GroupInput: function () { var a = {}; this.setGroupInfo = function (b) { for (var i = 0, arr = []; i < b.length; i++) { arr.push({id: b[i].getContent().id, name: b[i].getContent().name}) } a.groupInfo = arr; }; this.toArrayBuffer = function () { return a }; }, GroupOutput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b; }; this.toArrayBuffer = function () { return a }; }, GroupInfo: function () { var a = {}; this.setId = function (b) { a.id = b; }; this.setName = function (b) { a.name = b; }; this.getContent = function () { return a; }; this.toArrayBuffer = function () { return a }; }, GroupHashInput: function () { var a = {}; this.setUserId = function (b) { a.userId = b; }; this.setGroupHashCode = function (b) { a.groupHashCode = b; }; this.toArrayBuffer = function () { return a }; }, GroupHashOutput: function () { var a = {}; this.setResult = function (b) { a.result = b; }; this.toArrayBuffer = function () { return a }; }, ChrmInput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b; }; this.toArrayBuffer = function () { return a }; }, ChrmOutput: function () { var a = {}; this.setNothing = function (b) { a.nothing = b; }; this.toArrayBuffer = function () { return a }; }, ChrmPullMsg: function () { var a = {}; this.setSyncTime = function (b) { a.syncTime = b }; this.setCount = function (b) { a.count = b; }; this.toArrayBuffer = function () { return a }; }, RelationsInput: function () { var a = {}; this.setType = function (b) { a.type = b; }; this.setMsg = function(b){ a.msg = b; }; this.setCount = function(b){ a.count = b; }; this.toArrayBuffer = function () { return a }; }, RelationsOutput: function () { var a = {}; this.setInfo = function (b) { a.info = b; }; this.toArrayBuffer = function () { return a } }, RelationInfo: function () { var a = {}; this.setType = function (b) { a.type = b; }; this.setUserId = function (b) { a.userId = b; }; this.setMsg = function(b){ a.msg = b; }; this.toArrayBuffer = function () { return a } }, HistoryMessageInput: function () { var a={}; this.setTargetId=function(b){ a.targetId=b; }; this.setDataTime=function(b){ a.dataTime=b; }; this.setSize=function(b){ a.size=b; }; this.toArrayBuffer = function () { return a } }, HistoryMessagesOuput: function () { var a={}; this.setList=function(b){ a.list=b; }; this.setSyncTime=function(b){ a.syncTime=b; }; this.setHasMsg=function(b){ a.hasMsg=b; }; this.toArrayBuffer = function () { return a } }, HistoryMsgInput: function(){ var a = {}; this.setTargetId = function(b){ a.targetId = b; }; this.setTime = function(b){ a.time = b; }; this.setCount = function(b){ a.count = b; }; this.setOrder = function(b){ a.order = b; }; this.toArrayBuffer = function(){ return a; }; }, HistoryMsgOuput: function(){ var a = {}; this.setList = function(b){ a.list = b; }; this.setSyncTime = function(b){ a.syncTime = b; }; this.setHasMsg = function(b){ a.hasMsg = b; }; this.toArrayBuffer = function(){ return a; }; }, RtcQueryListInput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setOrder = function (b) { a.order = b; }; }, RtcKeyDeleteInput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setKey = function (b) { a.key = b; }; }, RtcValueInfo: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setKey = function (b) { a.key = b; }; this.setValue = function (b) { a.value = b; }; }, // RtcUserInfo: function () { // var a = {}; // }, RtcUserListOutput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setList = function (b) { a.list = b; }; this.setToken = function (b) { a.token = b; }; }, RtcRoomInfoOutput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setRoomId = function (b) { a.roomId = b; }; this.setRoomData = function (b) { a.roomData = b; }; this.setUserCount = function (b) { a.userCount = b; }; this.setList = function (b) { a.list = b; } }, RtcInput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setRoomType = function (b) { a.roomType = b; }; this.setBroadcastType = function (b) { a.broadcastType = b; } }, // RtcQryInput: function () { // var a = {}; // }, RtcQryOutput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setOutInfo = function (b) { a.outInfo = b; }; }, // RtcDelDataInput: function () { // var a = {}; // }, RtcDataInput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setInterior = function (b) { a.interior = b; }; this.setTarget = function (b) { a.target = b; }; this.setKey = function (b) { a.key = b; }; this.setObjectName = function (b) { a.objectName = b; }; this.setContent = function (b) { a.content = b; }; }, RtcSetDataInput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setInterior = function (b) { a.interior = b; }; this.setTarget = function (b) { a.target = b; }; this.setKey = function (b) { a.key = b; }; this.setValue = function (b) { a.value = b; }; this.setObjectName = function (b) { a.objectName = b; }; this.setContent = function (b) { a.content = b; }; }, RtcOutput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setNothing = function (b) { a.nothing = b; }; }, RtcTokenOutput: function () { var a = {}; this.toArrayBuffer = function(){ return a; }; this.setRtcToken = function (b) { a.rtcToken = b; } }, /** * 聊天室 KV 存储 */ ChrmNotifyMsg: function () { var a = {}; this.toArrayBuffer = function () { return a; }; this.setType = function (b) { a.type = b; }; this.setTime = function (b) { a.time = b; }; this.setChrmId = function (b) { a.chrmId = b; }; }, ChrmKVEntity: function () { var a = {}; this.toArrayBuffer = function () { return a; }; this.setKey = function (key) { a.key = key; }; this.setValue = function (value) { a.value = value; }; this.setStatus = function (b) { a.status = b; }; this.setTimestamp = function (b) { a.timestamp = b; }; this.setUid = function (b) { a.uid = b; }; }, SetChrmKV: function () { var a = {}; this.toArrayBuffer = function () { return a; }; this.setEntry = function (b) { a.entry = b; }; this.setNotification = function (b) { a.notification = b.toArrayBuffer(); }; this.setBNotify = function (b) { a.bNotify = b; }; this.setType = function (b) { a.type = b; }; }, ChrmKVOutput: function () { var a = {}; this.toArrayBuffer = function () { return a; }; this.setEntries = function (b) { this.entries = b; }; this.setBFullUpdate = function (b) { this.bFullUpdate = b; }; this.setSyncTime = function (b) { this.syncTime = b; }; }, QueryChrmKV: function () { var a = {}; this.toArrayBuffer = function () { return a; }; this.setTimestamp = function (b) { a.timestamp = b; }; }, DeleteChrmKV: function () { var a = {}; this.toArrayBuffer = function () { return a; }; this.setEntry = function (b) { a.entry = b; }; this.setBNotify = function (b) { a.bNotify = b; }; this.setNotification = function (b) { a.notification = b.toArrayBuffer(); }; this.setType = function (b) { a.type = b; }; } }; for (var f in Polling) { Polling[f].decode = function (b) { var back = {}, val = JSON.parse(b) || eval("(" + b + ")"); for (var i in val) { back[i]=val[i]; back["get"+ i.charAt(0).toUpperCase()+i.slice(1)]=function(){ return val[i]; } } return back; } } /* * JavaScript MD5 * https://github.com/blueimp/JavaScript-MD5 * * Copyright 2011, Sebastian Tschan * https://blueimp.net * * Licensed under the MIT license: * http://www.opensource.org/licenses/MIT * * Based on * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message * Digest Algorithm, as defined in RFC 1321. * Version 2.2 Copyright (C) Paul Johnston 1999 - 2009 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet * Distributed under the BSD License * See http://pajhome.org.uk/crypt/md5 for more info. */ /*jslint bitwise: true */ /*global unescape, define, module */ var md5 = (function () { 'use strict'; /* * Add integers, wrapping at 2^32. This uses 16-bit operations internally * to work around bugs in some JS interpreters. */ function safe_add(x, y) { var lsw = (x & 0xFFFF) + (y & 0xFFFF), msw = (x >> 16) + (y >> 16) + (lsw >> 16); return (msw << 16) | (lsw & 0xFFFF); } /* * Bitwise rotate a 32-bit number to the left. */ function bit_rol(num, cnt) { return (num << cnt) | (num >>> (32 - cnt)); } /* * These functions implement the four basic operations the algorithm uses. */ function md5_cmn(q, a, b, x, s, t) { return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s), b); } function md5_ff(a, b, c, d, x, s, t) { return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t); } function md5_gg(a, b, c, d, x, s, t) { return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t); } function md5_hh(a, b, c, d, x, s, t) { return md5_cmn(b ^ c ^ d, a, b, x, s, t); } function md5_ii(a, b, c, d, x, s, t) { return md5_cmn(c ^ (b | (~d)), a, b, x, s, t); } /* * Calculate the MD5 of an array of little-endian words, and a bit length. */ function binl_md5(x, len) { /* append padding */ x[len >> 5] |= 0x80 << (len % 32); x[(((len + 64) >>> 9) << 4) + 14] = len; var i, olda, oldb, oldc, oldd, a = 1732584193, b = -271733879, c = -1732584194, d = 271733878; for (i = 0; i < x.length; i += 16) { olda = a; oldb = b; oldc = c; oldd = d; a = md5_ff(a, b, c, d, x[i], 7, -680876936); d = md5_ff(d, a, b, c, x[i + 1], 12, -389564586); c = md5_ff(c, d, a, b, x[i + 2], 17, 606105819); b = md5_ff(b, c, d, a, x[i + 3], 22, -1044525330); a = md5_ff(a, b, c, d, x[i + 4], 7, -176418897); d = md5_ff(d, a, b, c, x[i + 5], 12, 1200080426); c = md5_ff(c, d, a, b, x[i + 6], 17, -1473231341); b = md5_ff(b, c, d, a, x[i + 7], 22, -45705983); a = md5_ff(a, b, c, d, x[i + 8], 7, 1770035416); d = md5_ff(d, a, b, c, x[i + 9], 12, -1958414417); c = md5_ff(c, d, a, b, x[i + 10], 17, -42063); b = md5_ff(b, c, d, a, x[i + 11], 22, -1990404162); a = md5_ff(a, b, c, d, x[i + 12], 7, 1804603682); d = md5_ff(d, a, b, c, x[i + 13], 12, -40341101); c = md5_ff(c, d, a, b, x[i + 14], 17, -1502002290); b = md5_ff(b, c, d, a, x[i + 15], 22, 1236535329); a = md5_gg(a, b, c, d, x[i + 1], 5, -165796510); d = md5_gg(d, a, b, c, x[i + 6], 9, -1069501632); c = md5_gg(c, d, a, b, x[i + 11], 14, 643717713); b = md5_gg(b, c, d, a, x[i], 20, -373897302); a = md5_gg(a, b, c, d, x[i + 5], 5, -701558691); d = md5_gg(d, a, b, c, x[i + 10], 9, 38016083); c = md5_gg(c, d, a, b, x[i + 15], 14, -660478335); b = md5_gg(b, c, d, a, x[i + 4], 20, -405537848); a = md5_gg(a, b, c, d, x[i + 9], 5, 568446438); d = md5_gg(d, a, b, c, x[i + 14], 9, -1019803690); c = md5_gg(c, d, a, b, x[i + 3], 14, -187363961); b = md5_gg(b, c, d, a, x[i + 8], 20, 1163531501); a = md5_gg(a, b, c, d, x[i + 13], 5, -1444681467); d = md5_gg(d, a, b, c, x[i + 2], 9, -51403784); c = md5_gg(c, d, a, b, x[i + 7], 14, 1735328473); b = md5_gg(b, c, d, a, x[i + 12], 20, -1926607734); a = md5_hh(a, b, c, d, x[i + 5], 4, -378558); d = md5_hh(d, a, b, c, x[i + 8], 11, -2022574463); c = md5_hh(c, d, a, b, x[i + 11], 16, 1839030562); b = md5_hh(b, c, d, a, x[i + 14], 23, -35309556); a = md5_hh(a, b, c, d, x[i + 1], 4, -1530992060); d = md5_hh(d, a, b, c, x[i + 4], 11, 1272893353); c = md5_hh(c, d, a, b, x[i + 7], 16, -155497632); b = md5_hh(b, c, d, a, x[i + 10], 23, -1094730640); a = md5_hh(a, b, c, d, x[i + 13], 4, 681279174); d = md5_hh(d, a, b, c, x[i], 11, -358537222); c = md5_hh(c, d, a, b, x[i + 3], 16, -722521979); b = md5_hh(b, c, d, a, x[i + 6], 23, 76029189); a = md5_hh(a, b, c, d, x[i + 9], 4, -640364487); d = md5_hh(d, a, b, c, x[i + 12], 11, -421815835); c = md5_hh(c, d, a, b, x[i + 15], 16, 530742520); b = md5_hh(b, c, d, a, x[i + 2], 23, -995338651); a = md5_ii(a, b, c, d, x[i], 6, -198630844); d = md5_ii(d, a, b, c, x[i + 7], 10, 1126891415); c = md5_ii(c, d, a, b, x[i + 14], 15, -1416354905); b = md5_ii(b, c, d, a, x[i + 5], 21, -57434055); a = md5_ii(a, b, c, d, x[i + 12], 6, 1700485571); d = md5_ii(d, a, b, c, x[i + 3], 10, -1894986606); c = md5_ii(c, d, a, b, x[i + 10], 15, -1051523); b = md5_ii(b, c, d, a, x[i + 1], 21, -2054922799); a = md5_ii(a, b, c, d, x[i + 8], 6, 1873313359); d = md5_ii(d, a, b, c, x[i + 15], 10, -30611744); c = md5_ii(c, d, a, b, x[i + 6], 15, -1560198380); b = md5_ii(b, c, d, a, x[i + 13], 21, 1309151649); a = md5_ii(a, b, c, d, x[i + 4], 6, -145523070); d = md5_ii(d, a, b, c, x[i + 11], 10, -1120210379); c = md5_ii(c, d, a, b, x[i + 2], 15, 718787259); b = md5_ii(b, c, d, a, x[i + 9], 21, -343485551); a = safe_add(a, olda); b = safe_add(b, oldb); c = safe_add(c, oldc); d = safe_add(d, oldd); } return [a, b, c, d]; } /* * Convert an array of little-endian words to a string */ function binl2rstr(input) { var i, output = ''; for (i = 0; i < input.length * 32; i += 8) { output += String.fromCharCode((input[i >> 5] >>> (i % 32)) & 0xFF); } return output; } /* * Convert a raw string to an array of little-endian words * Characters >255 have their high-byte silently ignored. */ function rstr2binl(input) { var i, output = []; output[(input.length >> 2) - 1] = undefined; for (i = 0; i < output.length; i += 1) { output[i] = 0; } for (i = 0; i < input.length * 8; i += 8) { output[i >> 5] |= (input.charCodeAt(i / 8) & 0xFF) << (i % 32); } return output; } /* * Calculate the MD5 of a raw string */ function rstr_md5(s) { return binl2rstr(binl_md5(rstr2binl(s), s.length * 8)); } /* * Calculate the HMAC-MD5, of a key and some data (raw strings) */ function rstr_hmac_md5(key, data) { var i, bkey = rstr2binl(key), ipad = [], opad = [], hash; ipad[15] = opad[15] = undefined; if (bkey.length > 16) { bkey = binl_md5(bkey, key.length * 8); } for (i = 0; i < 16; i += 1) { ipad[i] = bkey[i] ^ 0x36363636; opad[i] = bkey[i] ^ 0x5C5C5C5C; } hash = binl_md5(ipad.concat(rstr2binl(data)), 512 + data.length * 8); return binl2rstr(binl_md5(opad.concat(hash), 512 + 128)); } /* * Convert a raw string to a hex string */ function rstr2hex(input) { var hex_tab = '0123456789abcdef', output = '', x, i; for (i = 0; i < input.length; i += 1) { x = input.charCodeAt(i); output += hex_tab.charAt((x >>> 4) & 0x0F) + hex_tab.charAt(x & 0x0F); } return output; } /* * Encode a string as utf-8 */ function str2rstr_utf8(input) { return unescape(encodeURIComponent(input)); } /* * Take string arguments and return either raw or hex encoded strings */ function raw_md5(s) { return rstr_md5(str2rstr_utf8(s)); } function hex_md5(s) { return rstr2hex(raw_md5(s)); } function raw_hmac_md5(k, d) { return rstr_hmac_md5(str2rstr_utf8(k), str2rstr_utf8(d)); } function hex_hmac_md5(k, d) { return rstr2hex(raw_hmac_md5(k, d)); } function md5(string, key, raw) { if (!key) { if (!raw) { return hex_md5(string); } return raw_md5(string); } if (!raw) { return hex_hmac_md5(key, string); } return raw_hmac_md5(key, string); } return md5; }()); var RongIMLib; (function (RongIMLib) { (function (MentionedType) { MentionedType[MentionedType["ALL"] = 1] = "ALL"; MentionedType[MentionedType["PART"] = 2] = "PART"; })(RongIMLib.MentionedType || (RongIMLib.MentionedType = {})); var MentionedType = RongIMLib.MentionedType; (function (MethodType) { MethodType[MethodType["CUSTOMER_SERVICE"] = 1] = "CUSTOMER_SERVICE"; MethodType[MethodType["RECALL"] = 2] = "RECALL"; })(RongIMLib.MethodType || (RongIMLib.MethodType = {})); var MethodType = RongIMLib.MethodType; (function (BlacklistStatus) { /** * 在黑名单中。 */ BlacklistStatus[BlacklistStatus["IN_BLACK_LIST"] = 0] = "IN_BLACK_LIST"; /** * 不在黑名单中。 */ BlacklistStatus[BlacklistStatus["NOT_IN_BLACK_LIST"] = 1] = "NOT_IN_BLACK_LIST"; })(RongIMLib.BlacklistStatus || (RongIMLib.BlacklistStatus = {})); var BlacklistStatus = RongIMLib.BlacklistStatus; (function (ConnectionChannel) { ConnectionChannel[ConnectionChannel["XHR_POLLING"] = 0] = "XHR_POLLING"; ConnectionChannel[ConnectionChannel["WEBSOCKET"] = 1] = "WEBSOCKET"; //外部调用 ConnectionChannel[ConnectionChannel["HTTP"] = 0] = "HTTP"; //外部调用 ConnectionChannel[ConnectionChannel["HTTPS"] = 1] = "HTTPS"; })(RongIMLib.ConnectionChannel || (RongIMLib.ConnectionChannel = {})); var ConnectionChannel = RongIMLib.ConnectionChannel; (function (CustomerType) { CustomerType[CustomerType["ONLY_ROBOT"] = 1] = "ONLY_ROBOT"; CustomerType[CustomerType["ONLY_HUMAN"] = 2] = "ONLY_HUMAN"; CustomerType[CustomerType["ROBOT_FIRST"] = 3] = "ROBOT_FIRST"; CustomerType[CustomerType["HUMAN_FIRST"] = 4] = "HUMAN_FIRST"; })(RongIMLib.CustomerType || (RongIMLib.CustomerType = {})); var CustomerType = RongIMLib.CustomerType; (function (GetChatRoomType) { GetChatRoomType[GetChatRoomType["NONE"] = 0] = "NONE"; GetChatRoomType[GetChatRoomType["SQQUENCE"] = 1] = "SQQUENCE"; GetChatRoomType[GetChatRoomType["REVERSE"] = 2] = "REVERSE"; })(RongIMLib.GetChatRoomType || (RongIMLib.GetChatRoomType = {})); var GetChatRoomType = RongIMLib.GetChatRoomType; (function (ConnectionStatus) { /** * 连接成功。 */ ConnectionStatus[ConnectionStatus["CONNECTED"] = 0] = "CONNECTED"; /** * 连接中。 */ ConnectionStatus[ConnectionStatus["CONNECTING"] = 1] = "CONNECTING"; /** * 断开连接。 */ ConnectionStatus[ConnectionStatus["DISCONNECTED"] = 2] = "DISCONNECTED"; /** * 用户账户在其他设备登录,本机会被踢掉线。 */ ConnectionStatus[ConnectionStatus["KICKED_OFFLINE_BY_OTHER_CLIENT"] = 6] = "KICKED_OFFLINE_BY_OTHER_CLIENT"; /** * websocket 连接失败 */ ConnectionStatus[ConnectionStatus["WEBSOCKET_UNAVAILABLE"] = 7] = "WEBSOCKET_UNAVAILABLE"; /** * websocket 报错 */ ConnectionStatus[ConnectionStatus["WEBSOCKET_ERROR"] = 8] = "WEBSOCKET_ERROR"; /** * 网络不可用。 */ ConnectionStatus[ConnectionStatus["NETWORK_UNAVAILABLE"] = 3] = "NETWORK_UNAVAILABLE"; /** * 域名错误 */ ConnectionStatus[ConnectionStatus["DOMAIN_INCORRECT"] = 12] = "DOMAIN_INCORRECT"; /** * appkey 不正确 */ ConnectionStatus[ConnectionStatus["APPKEY_IS_FAKE"] = 20] = "APPKEY_IS_FAKE"; /** * 连接关闭。 */ ConnectionStatus[ConnectionStatus["CONNECTION_CLOSED"] = 4] = "CONNECTION_CLOSED"; /* 互踢次数过多(count > 5),此时可能出现:在其它他设备登陆有 reconnect 逻辑 */ ConnectionStatus[ConnectionStatus["ULTRALIMIT"] = 1101] = "ULTRALIMIT"; /* 开始请求导航 */ ConnectionStatus[ConnectionStatus["REQUEST_NAVI"] = 201] = "REQUEST_NAVI"; /* 请求导航结束 */ ConnectionStatus[ConnectionStatus["RESPONSE_NAVI"] = 202] = "RESPONSE_NAVI"; /* 请求导航失败 */ ConnectionStatus[ConnectionStatus["RESPONSE_NAVI_ERROR"] = 203] = "RESPONSE_NAVI_ERROR"; /* 请求导航超时 */ ConnectionStatus[ConnectionStatus["RESPONSE_NAVI_TIMEOUT"] = 204] = "RESPONSE_NAVI_TIMEOUT"; })(RongIMLib.ConnectionStatus || (RongIMLib.ConnectionStatus = {})); var ConnectionStatus = RongIMLib.ConnectionStatus; (function (ConversationNotificationStatus) { /** * 免打扰状态,关闭对应会话的通知提醒。 */ ConversationNotificationStatus[ConversationNotificationStatus["DO_NOT_DISTURB"] = 1] = "DO_NOT_DISTURB"; /** * 提醒。 */ ConversationNotificationStatus[ConversationNotificationStatus["NOTIFY"] = 2] = "NOTIFY"; })(RongIMLib.ConversationNotificationStatus || (RongIMLib.ConversationNotificationStatus = {})); var ConversationNotificationStatus = RongIMLib.ConversationNotificationStatus; (function (ConversationType) { ConversationType[ConversationType["NONE"] = 0] = "NONE"; ConversationType[ConversationType["PRIVATE"] = 1] = "PRIVATE"; ConversationType[ConversationType["DISCUSSION"] = 2] = "DISCUSSION"; ConversationType[ConversationType["GROUP"] = 3] = "GROUP"; ConversationType[ConversationType["CHATROOM"] = 4] = "CHATROOM"; ConversationType[ConversationType["CUSTOMER_SERVICE"] = 5] = "CUSTOMER_SERVICE"; ConversationType[ConversationType["SYSTEM"] = 6] = "SYSTEM"; //默认关注 MC ConversationType[ConversationType["APP_PUBLIC_SERVICE"] = 7] = "APP_PUBLIC_SERVICE"; //手工关注 MP ConversationType[ConversationType["PUBLIC_SERVICE"] = 8] = "PUBLIC_SERVICE"; })(RongIMLib.ConversationType || (RongIMLib.ConversationType = {})); var ConversationType = RongIMLib.ConversationType; (function (DiscussionInviteStatus) { /** * 开放邀请。 */ DiscussionInviteStatus[DiscussionInviteStatus["OPENED"] = 0] = "OPENED"; /** * 关闭邀请。 */ DiscussionInviteStatus[DiscussionInviteStatus["CLOSED"] = 1] = "CLOSED"; })(RongIMLib.DiscussionInviteStatus || (RongIMLib.DiscussionInviteStatus = {})); var DiscussionInviteStatus = RongIMLib.DiscussionInviteStatus; (function (ErrorCode) { /* 超时 */ ErrorCode[ErrorCode["TIMEOUT"] = -1] = "TIMEOUT"; /** * 未知原因失败。 */ ErrorCode[ErrorCode["UNKNOWN"] = -2] = "UNKNOWN"; /* 参数错误 */ ErrorCode[ErrorCode["PARAMETER_ERROR"] = -3] = "PARAMETER_ERROR"; ErrorCode[ErrorCode["RECALL_MESSAGE"] = 25101] = "RECALL_MESSAGE"; /** * 发送频率过快 */ ErrorCode[ErrorCode["SEND_FREQUENCY_TOO_FAST"] = 20604] = "SEND_FREQUENCY_TOO_FAST"; ErrorCode[ErrorCode["RC_MSG_UNAUTHORIZED"] = 20406] = "RC_MSG_UNAUTHORIZED"; /** * 群组 Id 无效 */ ErrorCode[ErrorCode["RC_DISCUSSION_GROUP_ID_INVALID"] = 20407] = "RC_DISCUSSION_GROUP_ID_INVALID"; /** * 群组被禁言 */ ErrorCode[ErrorCode["FORBIDDEN_IN_GROUP"] = 22408] = "FORBIDDEN_IN_GROUP"; /** * 不在讨论组。 */ ErrorCode[ErrorCode["NOT_IN_DISCUSSION"] = 21406] = "NOT_IN_DISCUSSION"; /** * 不在群组。 */ ErrorCode[ErrorCode["NOT_IN_GROUP"] = 22406] = "NOT_IN_GROUP"; /** * 不在聊天室。 */ ErrorCode[ErrorCode["NOT_IN_CHATROOM"] = 23406] = "NOT_IN_CHATROOM"; /** *聊天室被禁言 */ ErrorCode[ErrorCode["FORBIDDEN_IN_CHATROOM"] = 23408] = "FORBIDDEN_IN_CHATROOM"; /** * 聊天室中成员被踢出 */ ErrorCode[ErrorCode["RC_CHATROOM_USER_KICKED"] = 23409] = "RC_CHATROOM_USER_KICKED"; /** * 聊天室不存在 */ ErrorCode[ErrorCode["RC_CHATROOM_NOT_EXIST"] = 23410] = "RC_CHATROOM_NOT_EXIST"; /** * 聊天室成员已满 */ ErrorCode[ErrorCode["RC_CHATROOM_IS_FULL"] = 23411] = "RC_CHATROOM_IS_FULL"; /** * 获取聊天室信息参数无效 */ ErrorCode[ErrorCode["RC_CHATROOM_PATAMETER_INVALID"] = 23412] = "RC_CHATROOM_PATAMETER_INVALID"; /** * 聊天室异常 */ ErrorCode[ErrorCode["CHATROOM_GET_HISTORYMSG_ERROR"] = 23413] = "CHATROOM_GET_HISTORYMSG_ERROR"; /** * 没有打开聊天室消息存储 */ ErrorCode[ErrorCode["CHATROOM_NOT_OPEN_HISTORYMSG_STORE"] = 23414] = "CHATROOM_NOT_OPEN_HISTORYMSG_STORE"; /** * 聊天室 KV 设置超出最大值(已满, 默认最多设置 100 个) */ ErrorCode[ErrorCode["CHATROOM_KV_EXCEED"] = 23423] = "CHATROOM_KV_EXCEED"; /** * 聊天室 KV 设置失败(kv 已存在, 需覆盖设置) */ ErrorCode[ErrorCode["CHATROOM_KV_OVERWRITE_INVALID"] = 23424] = "CHATROOM_KV_OVERWRITE_INVALID"; /** * 聊天室 KV 存储功能没有开通 */ ErrorCode[ErrorCode["CHATROOM_KV_STORE_NOT_OPEN"] = 23426] = "CHATROOM_KV_STORE_NOT_OPEN"; /** * 聊天室Key不存在 */ ErrorCode[ErrorCode["CHATROOM_KEY_NOT_EXIST"] = 23427] = "CHATROOM_KEY_NOT_EXIST"; /** * 敏感词屏蔽 */ ErrorCode[ErrorCode["SENSITIVE_SHIELD"] = 21501] = "SENSITIVE_SHIELD"; ErrorCode[ErrorCode["SENSITIVE_REPLACE"] = 21502] = "SENSITIVE_REPLACE"; /** * 加入讨论失败 */ ErrorCode[ErrorCode["JOIN_IN_DISCUSSION"] = 21407] = "JOIN_IN_DISCUSSION"; /** * 创建讨论组失败 */ ErrorCode[ErrorCode["CREATE_DISCUSSION"] = 21408] = "CREATE_DISCUSSION"; /** * 设置讨论组邀请状态失败 */ ErrorCode[ErrorCode["INVITE_DICUSSION"] = 21409] = "INVITE_DICUSSION"; /** *获取用户失败 */ ErrorCode[ErrorCode["GET_USERINFO_ERROR"] = 23407] = "GET_USERINFO_ERROR"; /** * 在黑名单中。 */ ErrorCode[ErrorCode["REJECTED_BY_BLACKLIST"] = 405] = "REJECTED_BY_BLACKLIST"; /** * 通信过程中,当前 Socket 不存在。 */ ErrorCode[ErrorCode["RC_NET_CHANNEL_INVALID"] = 30001] = "RC_NET_CHANNEL_INVALID"; /** * Socket 连接不可用。 */ ErrorCode[ErrorCode["RC_NET_UNAVAILABLE"] = 30002] = "RC_NET_UNAVAILABLE"; /** * 通信超时。 */ ErrorCode[ErrorCode["RC_MSG_RESP_TIMEOUT"] = 30003] = "RC_MSG_RESP_TIMEOUT"; /** * 导航操作时,Http 请求失败。 */ ErrorCode[ErrorCode["RC_HTTP_SEND_FAIL"] = 30004] = "RC_HTTP_SEND_FAIL"; /** * HTTP 请求失败。 */ ErrorCode[ErrorCode["RC_HTTP_REQ_TIMEOUT"] = 30005] = "RC_HTTP_REQ_TIMEOUT"; /** * HTTP 接收失败。 */ ErrorCode[ErrorCode["RC_HTTP_RECV_FAIL"] = 30006] = "RC_HTTP_RECV_FAIL"; /** * 导航操作的 HTTP 请求,返回不是200。 */ ErrorCode[ErrorCode["RC_NAVI_RESOURCE_ERROR"] = 30007] = "RC_NAVI_RESOURCE_ERROR"; /** * 导航数据解析后,其中不存在有效数据。 */ ErrorCode[ErrorCode["RC_NODE_NOT_FOUND"] = 30008] = "RC_NODE_NOT_FOUND"; /** * 导航数据解析后,其中不存在有效 IP 地址。 */ ErrorCode[ErrorCode["RC_DOMAIN_NOT_RESOLVE"] = 30009] = "RC_DOMAIN_NOT_RESOLVE"; /** * 创建 Socket 失败。 */ ErrorCode[ErrorCode["RC_SOCKET_NOT_CREATED"] = 30010] = "RC_SOCKET_NOT_CREATED"; /** * Socket 被断开。 */ ErrorCode[ErrorCode["RC_SOCKET_DISCONNECTED"] = 30011] = "RC_SOCKET_DISCONNECTED"; /** * PING 操作失败。 */ ErrorCode[ErrorCode["RC_PING_SEND_FAIL"] = 30012] = "RC_PING_SEND_FAIL"; /** * PING 超时。 */ ErrorCode[ErrorCode["RC_PONG_RECV_FAIL"] = 30013] = "RC_PONG_RECV_FAIL"; /** * 消息发送失败。 */ ErrorCode[ErrorCode["RC_MSG_SEND_FAIL"] = 30014] = "RC_MSG_SEND_FAIL"; /** * JSON 后的消息体超限, 目前最大 128kb * */ ErrorCode[ErrorCode["RC_MSG_CONTENT_EXCEED_LIMIT"] = 30016] = "RC_MSG_CONTENT_EXCEED_LIMIT"; /** * 做 connect 连接时,收到的 ACK 超时。 */ ErrorCode[ErrorCode["RC_CONN_ACK_TIMEOUT"] = 31000] = "RC_CONN_ACK_TIMEOUT"; /** * 参数错误。 */ ErrorCode[ErrorCode["RC_CONN_PROTO_VERSION_ERROR"] = 31001] = "RC_CONN_PROTO_VERSION_ERROR"; /** * 参数错误,App Id 错误。 */ ErrorCode[ErrorCode["RC_CONN_ID_REJECT"] = 31002] = "RC_CONN_ID_REJECT"; /** * 服务器不可用。 */ ErrorCode[ErrorCode["RC_CONN_SERVER_UNAVAILABLE"] = 31003] = "RC_CONN_SERVER_UNAVAILABLE"; /** * Token 错误。 */ ErrorCode[ErrorCode["RC_CONN_USER_OR_PASSWD_ERROR"] = 31004] = "RC_CONN_USER_OR_PASSWD_ERROR"; /** * App Id 与 Token 不匹配。 */ ErrorCode[ErrorCode["RC_CONN_NOT_AUTHRORIZED"] = 31005] = "RC_CONN_NOT_AUTHRORIZED"; /** * 重定向,地址错误。 */ ErrorCode[ErrorCode["RC_CONN_REDIRECTED"] = 31006] = "RC_CONN_REDIRECTED"; /** * NAME 与后台注册信息不一致。 */ ErrorCode[ErrorCode["RC_CONN_PACKAGE_NAME_INVALID"] = 31007] = "RC_CONN_PACKAGE_NAME_INVALID"; /** * APP 被屏蔽、删除或不存在。 */ ErrorCode[ErrorCode["RC_CONN_APP_BLOCKED_OR_DELETED"] = 31008] = "RC_CONN_APP_BLOCKED_OR_DELETED"; /** * 用户被屏蔽。 */ ErrorCode[ErrorCode["RC_CONN_USER_BLOCKED"] = 31009] = "RC_CONN_USER_BLOCKED"; /** * Disconnect,由服务器返回,比如用户互踢。 */ ErrorCode[ErrorCode["RC_DISCONN_KICK"] = 31010] = "RC_DISCONN_KICK"; /** * Disconnect,由服务器返回,比如用户互踢。 */ ErrorCode[ErrorCode["RC_DISCONN_EXCEPTION"] = 31011] = "RC_DISCONN_EXCEPTION"; /** * 协议层内部错误。query,上传下载过程中数据错误。 */ ErrorCode[ErrorCode["RC_QUERY_ACK_NO_DATA"] = 32001] = "RC_QUERY_ACK_NO_DATA"; /** * 协议层内部错误。 */ ErrorCode[ErrorCode["RC_MSG_DATA_INCOMPLETE"] = 32002] = "RC_MSG_DATA_INCOMPLETE"; /** * 未调用 init 初始化函数。 */ ErrorCode[ErrorCode["BIZ_ERROR_CLIENT_NOT_INIT"] = 33001] = "BIZ_ERROR_CLIENT_NOT_INIT"; /** * 数据库初始化失败。 */ ErrorCode[ErrorCode["BIZ_ERROR_DATABASE_ERROR"] = 33002] = "BIZ_ERROR_DATABASE_ERROR"; /** * 传入参数无效。 */ ErrorCode[ErrorCode["BIZ_ERROR_INVALID_PARAMETER"] = 33003] = "BIZ_ERROR_INVALID_PARAMETER"; /** * 通道无效。 */ ErrorCode[ErrorCode["BIZ_ERROR_NO_CHANNEL"] = 33004] = "BIZ_ERROR_NO_CHANNEL"; /** * 重新连接成功。 */ ErrorCode[ErrorCode["BIZ_ERROR_RECONNECT_SUCCESS"] = 33005] = "BIZ_ERROR_RECONNECT_SUCCESS"; /** * 连接中,再调用 connect 被拒绝。 */ ErrorCode[ErrorCode["BIZ_ERROR_CONNECTING"] = 33006] = "BIZ_ERROR_CONNECTING"; /** * 消息漫游服务未开通 */ ErrorCode[ErrorCode["MSG_ROAMING_SERVICE_UNAVAILABLE"] = 33007] = "MSG_ROAMING_SERVICE_UNAVAILABLE"; ErrorCode[ErrorCode["MSG_INSERT_ERROR"] = 33008] = "MSG_INSERT_ERROR"; ErrorCode[ErrorCode["MSG_DEL_ERROR"] = 33009] = "MSG_DEL_ERROR"; /** * 删除会话失败 */ ErrorCode[ErrorCode["CONVER_REMOVE_ERROR"] = 34001] = "CONVER_REMOVE_ERROR"; /** *拉取历史消息 */ ErrorCode[ErrorCode["CONVER_GETLIST_ERROR"] = 34002] = "CONVER_GETLIST_ERROR"; /** * 会话指定异常 */ ErrorCode[ErrorCode["CONVER_SETOP_ERROR"] = 34003] = "CONVER_SETOP_ERROR"; /** * 获取会话未读消息总数失败 */ ErrorCode[ErrorCode["CONVER_TOTAL_UNREAD_ERROR"] = 34004] = "CONVER_TOTAL_UNREAD_ERROR"; /** * 获取指定会话类型未读消息数异常 */ ErrorCode[ErrorCode["CONVER_TYPE_UNREAD_ERROR"] = 34005] = "CONVER_TYPE_UNREAD_ERROR"; /** * 获取指定用户ID&会话类型未读消息数异常 */ ErrorCode[ErrorCode["CONVER_ID_TYPE_UNREAD_ERROR"] = 34006] = "CONVER_ID_TYPE_UNREAD_ERROR"; ErrorCode[ErrorCode["CONVER_CLEAR_ERROR"] = 34007] = "CONVER_CLEAR_ERROR"; ErrorCode[ErrorCode["CLEAR_HIS_ERROR"] = 34010] = "CLEAR_HIS_ERROR"; ErrorCode[ErrorCode["CLEAR_HIS_TYPE_ERROR"] = 34008] = "CLEAR_HIS_TYPE_ERROR"; ErrorCode[ErrorCode["CLEAR_HIS_TIME_ERROR"] = 34011] = "CLEAR_HIS_TIME_ERROR"; /* */ ErrorCode[ErrorCode["CONVER_GET_ERROR"] = 34009] = "CONVER_GET_ERROR"; //群组异常信息 /** * */ ErrorCode[ErrorCode["GROUP_SYNC_ERROR"] = 35001] = "GROUP_SYNC_ERROR"; /** * 匹配群信息异常 */ ErrorCode[ErrorCode["GROUP_MATCH_ERROR"] = 35002] = "GROUP_MATCH_ERROR"; //聊天室异常 /** * 加入聊天室Id为空 */ ErrorCode[ErrorCode["CHATROOM_ID_ISNULL"] = 36001] = "CHATROOM_ID_ISNULL"; /** * 加入聊天室失败 */ ErrorCode[ErrorCode["CHARTOOM_JOIN_ERROR"] = 36002] = "CHARTOOM_JOIN_ERROR"; /** * 拉取聊天室历史消息失败 */ ErrorCode[ErrorCode["CHATROOM_HISMESSAGE_ERROR"] = 36003] = "CHATROOM_HISMESSAGE_ERROR"; /** * 聊天室 kv 未找到 * */ ErrorCode[ErrorCode["CHATROOM_KV_NOT_FOUND"] = 36004] = "CHATROOM_KV_NOT_FOUND"; //黑名单异常 /** * 加入黑名单异常 */ ErrorCode[ErrorCode["BLACK_ADD_ERROR"] = 37001] = "BLACK_ADD_ERROR"; /** * 获得指定人员再黑名单中的状态异常 */ ErrorCode[ErrorCode["BLACK_GETSTATUS_ERROR"] = 37002] = "BLACK_GETSTATUS_ERROR"; /** * 移除黑名单异常 */ ErrorCode[ErrorCode["BLACK_REMOVE_ERROR"] = 37003] = "BLACK_REMOVE_ERROR"; /** * 获取草稿失败 */ ErrorCode[ErrorCode["DRAF_GET_ERROR"] = 38001] = "DRAF_GET_ERROR"; /** * 保存草稿失败 */ ErrorCode[ErrorCode["DRAF_SAVE_ERROR"] = 38002] = "DRAF_SAVE_ERROR"; /** * 删除草稿失败 */ ErrorCode[ErrorCode["DRAF_REMOVE_ERROR"] = 38003] = "DRAF_REMOVE_ERROR"; /** * 关注公众号失败 */ ErrorCode[ErrorCode["SUBSCRIBE_ERROR"] = 39001] = "SUBSCRIBE_ERROR"; /** * 关注公众号失败 */ ErrorCode[ErrorCode["QNTKN_FILETYPE_ERROR"] = 41001] = "QNTKN_FILETYPE_ERROR"; /** * 获取七牛token失败 */ ErrorCode[ErrorCode["QNTKN_GET_ERROR"] = 41002] = "QNTKN_GET_ERROR"; /** * cookie被禁用 */ ErrorCode[ErrorCode["COOKIE_ENABLE"] = 51001] = "COOKIE_ENABLE"; ErrorCode[ErrorCode["GET_MESSAGE_BY_ID_ERROR"] = 61001] = "GET_MESSAGE_BY_ID_ERROR"; // 没有注册DeviveId 也就是用户没有登陆 ErrorCode[ErrorCode["HAVNODEVICEID"] = 24001] = "HAVNODEVICEID"; // 已经存在 ErrorCode[ErrorCode["DEVICEIDISHAVE"] = 24002] = "DEVICEIDISHAVE"; // 成功 ErrorCode[ErrorCode["SUCCESS"] = 0] = "SUCCESS"; // 没有对应的用户或token ErrorCode[ErrorCode["FEILD"] = 24009] = "FEILD"; // voip为空 ErrorCode[ErrorCode["VOIPISNULL"] = 24013] = "VOIPISNULL"; // 不支持的Voip引擎 ErrorCode[ErrorCode["NOENGINETYPE"] = 24010] = "NOENGINETYPE"; // channleName 是空 ErrorCode[ErrorCode["NULLCHANNELNAME"] = 24011] = "NULLCHANNELNAME"; // 生成Voipkey失败 ErrorCode[ErrorCode["VOIPDYANMICERROR"] = 24012] = "VOIPDYANMICERROR"; // 没有配置voip ErrorCode[ErrorCode["NOVOIP"] = 24014] = "NOVOIP"; // 服务器内部错误 ErrorCode[ErrorCode["INTERNALERRROR"] = 24015] = "INTERNALERRROR"; //VOIP close ErrorCode[ErrorCode["VOIPCLOSE"] = 24016] = "VOIPCLOSE"; ErrorCode[ErrorCode["CLOSE_BEFORE_OPEN"] = 51001] = "CLOSE_BEFORE_OPEN"; ErrorCode[ErrorCode["ALREADY_IN_USE"] = 51002] = "ALREADY_IN_USE"; ErrorCode[ErrorCode["INVALID_CHANNEL_NAME"] = 51003] = "INVALID_CHANNEL_NAME"; ErrorCode[ErrorCode["VIDEO_CONTAINER_IS_NULL"] = 51004] = "VIDEO_CONTAINER_IS_NULL"; /** * 删除消息数组长度为 0 . */ ErrorCode[ErrorCode["DELETE_MESSAGE_ID_IS_NULL"] = 61001] = "DELETE_MESSAGE_ID_IS_NULL"; /*! 己方取消已发出的通话请求 */ ErrorCode[ErrorCode["CANCEL"] = 1] = "CANCEL"; /*! 己方拒绝收到的通话请求 */ ErrorCode[ErrorCode["REJECT"] = 2] = "REJECT"; /*! 己方挂断 */ ErrorCode[ErrorCode["HANGUP"] = 3] = "HANGUP"; /*! 己方忙碌 */ ErrorCode[ErrorCode["BUSYLINE"] = 4] = "BUSYLINE"; /*! 己方未接听 */ ErrorCode[ErrorCode["NO_RESPONSE"] = 5] = "NO_RESPONSE"; /*! 己方不支持当前引擎 */ ErrorCode[ErrorCode["ENGINE_UN_SUPPORTED"] = 6] = "ENGINE_UN_SUPPORTED"; /*! 己方网络出错 */ ErrorCode[ErrorCode["NETWORK_ERROR"] = 7] = "NETWORK_ERROR"; /*! 对方取消已发出的通话请求 */ ErrorCode[ErrorCode["REMOTE_CANCEL"] = 11] = "REMOTE_CANCEL"; /*! 对方拒绝收到的通话请求 */ ErrorCode[ErrorCode["REMOTE_REJECT"] = 12] = "REMOTE_REJECT"; /*! 通话过程对方挂断 */ ErrorCode[ErrorCode["REMOTE_HANGUP"] = 13] = "REMOTE_HANGUP"; /*! 对方忙碌 */ ErrorCode[ErrorCode["REMOTE_BUSYLINE"] = 14] = "REMOTE_BUSYLINE"; /*! 对方未接听 */ ErrorCode[ErrorCode["REMOTE_NO_RESPONSE"] = 15] = "REMOTE_NO_RESPONSE"; /*! 对方网络错误 */ ErrorCode[ErrorCode["REMOTE_ENGINE_UN_SUPPORTED"] = 16] = "REMOTE_ENGINE_UN_SUPPORTED"; /*! 对方网络错误 */ ErrorCode[ErrorCode["REMOTE_NETWORK_ERROR"] = 17] = "REMOTE_NETWORK_ERROR"; /*! VoIP 不可用 */ ErrorCode[ErrorCode["VOIP_NOT_AVALIABLE"] = 18] = "VOIP_NOT_AVALIABLE"; })(RongIMLib.ErrorCode || (RongIMLib.ErrorCode = {})); var ErrorCode = RongIMLib.ErrorCode; (function (VoIPMediaType) { VoIPMediaType[VoIPMediaType["MEDIA_AUDIO"] = 1] = "MEDIA_AUDIO"; VoIPMediaType[VoIPMediaType["MEDIA_VEDIO"] = 2] = "MEDIA_VEDIO"; VoIPMediaType[VoIPMediaType["MEDIA_VIDEO"] = 2] = "MEDIA_VIDEO"; })(RongIMLib.VoIPMediaType || (RongIMLib.VoIPMediaType = {})); var VoIPMediaType = RongIMLib.VoIPMediaType; (function (MediaType) { /** * 图片。 */ MediaType[MediaType["IMAGE"] = 1] = "IMAGE"; /** * 声音。 */ MediaType[MediaType["AUDIO"] = 2] = "AUDIO"; /** * 视频。 */ MediaType[MediaType["VIDEO"] = 3] = "VIDEO"; /** * 通用文件。 */ MediaType[MediaType["FILE"] = 100] = "FILE"; })(RongIMLib.MediaType || (RongIMLib.MediaType = {})); var MediaType = RongIMLib.MediaType; (function (MessageDirection) { /** * 发送消息。 */ MessageDirection[MessageDirection["SEND"] = 1] = "SEND"; /** * 接收消息。 */ MessageDirection[MessageDirection["RECEIVE"] = 2] = "RECEIVE"; })(RongIMLib.MessageDirection || (RongIMLib.MessageDirection = {})); var MessageDirection = RongIMLib.MessageDirection; (function (FileType) { FileType[FileType["IMAGE"] = 1] = "IMAGE"; FileType[FileType["AUDIO"] = 2] = "AUDIO"; FileType[FileType["VIDEO"] = 3] = "VIDEO"; FileType[FileType["FILE"] = 4] = "FILE"; })(RongIMLib.FileType || (RongIMLib.FileType = {})); var FileType = RongIMLib.FileType; (function (RealTimeLocationErrorCode) { /** * 未初始化 RealTimeLocation 实例 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_NOT_INIT"] = -1] = "RC_REAL_TIME_LOCATION_NOT_INIT"; /** * 执行成功。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_SUCCESS"] = 0] = "RC_REAL_TIME_LOCATION_SUCCESS"; /** * 获取 RealTimeLocation 实例时返回 * GPS 未打开。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_GPS_DISABLED"] = 1] = "RC_REAL_TIME_LOCATION_GPS_DISABLED"; /** * 获取 RealTimeLocation 实例时返回 * 当前会话不支持位置共享。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_CONVERSATION_NOT_SUPPORT"] = 2] = "RC_REAL_TIME_LOCATION_CONVERSATION_NOT_SUPPORT"; /** * 获取 RealTimeLocation 实例时返回 * 对方已发起位置共享。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_IS_ON_GOING"] = 3] = "RC_REAL_TIME_LOCATION_IS_ON_GOING"; /** * Join 时返回 * 当前位置共享已超过最大支持人数。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_EXCEED_MAX_PARTICIPANT"] = 4] = "RC_REAL_TIME_LOCATION_EXCEED_MAX_PARTICIPANT"; /** * Join 时返回 * 加入位置共享失败。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_JOIN_FAILURE"] = 5] = "RC_REAL_TIME_LOCATION_JOIN_FAILURE"; /** * Start 时返回 * 发起位置共享失败。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_START_FAILURE"] = 6] = "RC_REAL_TIME_LOCATION_START_FAILURE"; /** * 网络不可用。 */ RealTimeLocationErrorCode[RealTimeLocationErrorCode["RC_REAL_TIME_LOCATION_NETWORK_UNAVAILABLE"] = 7] = "RC_REAL_TIME_LOCATION_NETWORK_UNAVAILABLE"; })(RongIMLib.RealTimeLocationErrorCode || (RongIMLib.RealTimeLocationErrorCode = {})); var RealTimeLocationErrorCode = RongIMLib.RealTimeLocationErrorCode; (function (RealTimeLocationStatus) { /** * 空闲状态 (默认状态) * 对方或者自己都未发起位置共享业务,或者位置共享业务已结束。 */ RealTimeLocationStatus[RealTimeLocationStatus["RC_REAL_TIME_LOCATION_STATUS_IDLE"] = 0] = "RC_REAL_TIME_LOCATION_STATUS_IDLE"; /** * 呼入状态 (待加入) * 1. 对方发起了位置共享业务,此状态下,自己只能选择加入。 * 2. 自己从已连接的位置共享中退出。 */ RealTimeLocationStatus[RealTimeLocationStatus["RC_REAL_TIME_LOCATION_STATUS_INCOMING"] = 1] = "RC_REAL_TIME_LOCATION_STATUS_INCOMING"; /** * 呼出状态 =(自己创建) * 1. 自己发起位置共享业务,对方只能选择加入。 * 2. 对方从已连接的位置共享业务中退出。 */ RealTimeLocationStatus[RealTimeLocationStatus["RC_REAL_TIME_LOCATION_STATUS_OUTGOING"] = 2] = "RC_REAL_TIME_LOCATION_STATUS_OUTGOING"; /** * 连接状态 (自己加入) * 对方加入了自己发起的位置共享,或者自己加入了对方发起的位置共享。 */ RealTimeLocationStatus[RealTimeLocationStatus["RC_REAL_TIME_LOCATION_STATUS_CONNECTED"] = 3] = "RC_REAL_TIME_LOCATION_STATUS_CONNECTED"; })(RongIMLib.RealTimeLocationStatus || (RongIMLib.RealTimeLocationStatus = {})); var RealTimeLocationStatus = RongIMLib.RealTimeLocationStatus; (function (ReceivedStatus) { ReceivedStatus[ReceivedStatus["READ"] = 1] = "READ"; ReceivedStatus[ReceivedStatus["LISTENED"] = 2] = "LISTENED"; ReceivedStatus[ReceivedStatus["DOWNLOADED"] = 4] = "DOWNLOADED"; ReceivedStatus[ReceivedStatus["RETRIEVED"] = 8] = "RETRIEVED"; ReceivedStatus[ReceivedStatus["UNREAD"] = 0] = "UNREAD"; })(RongIMLib.ReceivedStatus || (RongIMLib.ReceivedStatus = {})); var ReceivedStatus = RongIMLib.ReceivedStatus; (function (ReadStatus) { ReadStatus[ReadStatus["READ"] = 1] = "READ"; ReadStatus[ReadStatus["LISTENED"] = 2] = "LISTENED"; ReadStatus[ReadStatus["DOWNLOADED"] = 4] = "DOWNLOADED"; ReadStatus[ReadStatus["RETRIEVED"] = 8] = "RETRIEVED"; ReadStatus[ReadStatus["UNREAD"] = 0] = "UNREAD"; })(RongIMLib.ReadStatus || (RongIMLib.ReadStatus = {})); var ReadStatus = RongIMLib.ReadStatus; (function (SearchType) { /** * 精确。 */ SearchType[SearchType["EXACT"] = 0] = "EXACT"; /** * 模糊。 */ SearchType[SearchType["FUZZY"] = 1] = "FUZZY"; })(RongIMLib.SearchType || (RongIMLib.SearchType = {})); var SearchType = RongIMLib.SearchType; (function (SentStatus) { /** * 发送中。 */ SentStatus[SentStatus["SENDING"] = 10] = "SENDING"; /** * 发送失败。 */ SentStatus[SentStatus["FAILED"] = 20] = "FAILED"; /** * 已发送。 */ SentStatus[SentStatus["SENT"] = 30] = "SENT"; /** * 对方已接收。 */ SentStatus[SentStatus["RECEIVED"] = 40] = "RECEIVED"; /** * 对方已读。 */ SentStatus[SentStatus["READ"] = 50] = "READ"; /** * 对方已销毁。 */ SentStatus[SentStatus["DESTROYED"] = 60] = "DESTROYED"; })(RongIMLib.SentStatus || (RongIMLib.SentStatus = {})); var SentStatus = RongIMLib.SentStatus; (function (ConnectionState) { ConnectionState[ConnectionState["ACCEPTED"] = 0] = "ACCEPTED"; ConnectionState[ConnectionState["UNACCEPTABLE_PROTOCOL_VERSION"] = 1] = "UNACCEPTABLE_PROTOCOL_VERSION"; ConnectionState[ConnectionState["IDENTIFIER_REJECTED"] = 2] = "IDENTIFIER_REJECTED"; ConnectionState[ConnectionState["SERVER_UNAVAILABLE"] = 3] = "SERVER_UNAVAILABLE"; /** * token无效 */ ConnectionState[ConnectionState["TOKEN_INCORRECT"] = 4] = "TOKEN_INCORRECT"; ConnectionState[ConnectionState["NOT_AUTHORIZED"] = 5] = "NOT_AUTHORIZED"; ConnectionState[ConnectionState["REDIRECT"] = 6] = "REDIRECT"; ConnectionState[ConnectionState["PACKAGE_ERROR"] = 7] = "PACKAGE_ERROR"; ConnectionState[ConnectionState["APP_BLOCK_OR_DELETE"] = 8] = "APP_BLOCK_OR_DELETE"; ConnectionState[ConnectionState["BLOCK"] = 9] = "BLOCK"; ConnectionState[ConnectionState["TOKEN_EXPIRE"] = 10] = "TOKEN_EXPIRE"; ConnectionState[ConnectionState["DEVICE_ERROR"] = 11] = "DEVICE_ERROR"; })(RongIMLib.ConnectionState || (RongIMLib.ConnectionState = {})); var ConnectionState = RongIMLib.ConnectionState; (function (RTCAPIType) { RTCAPIType[RTCAPIType["ROOM"] = 1] = "ROOM"; RTCAPIType[RTCAPIType["PERSON"] = 2] = "PERSON"; })(RongIMLib.RTCAPIType || (RongIMLib.RTCAPIType = {})); var RTCAPIType = RongIMLib.RTCAPIType; (function (ChatroomEntityOpt) { ChatroomEntityOpt[ChatroomEntityOpt["UPDATE"] = 1] = "UPDATE"; ChatroomEntityOpt[ChatroomEntityOpt["DELETE"] = 2] = "DELETE"; })(RongIMLib.ChatroomEntityOpt || (RongIMLib.ChatroomEntityOpt = {})); var ChatroomEntityOpt = RongIMLib.ChatroomEntityOpt; (function (ChatroomEntityLimit) { ChatroomEntityLimit[ChatroomEntityLimit["KEY"] = 128] = "KEY"; ChatroomEntityLimit[ChatroomEntityLimit["VALUE"] = 4096] = "VALUE"; })(RongIMLib.ChatroomEntityLimit || (RongIMLib.ChatroomEntityLimit = {})); var ChatroomEntityLimit = RongIMLib.ChatroomEntityLimit; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var RongIMClient = (function () { function RongIMClient() { } RongIMClient.getInstance = function () { if (!RongIMClient._instance) { throw new Error("RongIMClient is not initialized. Call .init() method first."); } return RongIMClient._instance; }; RongIMClient.showError = function (errorInfo) { var hasConsole = (console && console.error); if (hasConsole) { console.error(JSON.stringify(errorInfo)); } }; RongIMClient.logger = function (params) { var code = params.code; var errorInfo = RongIMClient.LogFactory[code] || params; errorInfo.funcName = params.funcName; errorInfo.msg = params.msg || errorInfo.msg; if (RongIMClient._memoryStore.depend.showError) { RongIMClient.showError(errorInfo); } RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.L_CRAW_F, level: RongIMLib.LoggerLevel.W, type: RongIMLib.LoggerType.IM, content: { errorCode: code, message: errorInfo.msg || errorInfo.funcName, parameter: params.parameter, action: errorInfo.funcName } }); }; RongIMClient.logCallback = function (callback, funcName) { return { onSuccess: callback.onSuccess, onError: function (errorCode) { RongIMClient.logger({ code: errorCode, funcName: funcName }); callback.onError(errorCode); } }; }; ; RongIMClient.logSendCallback = function (callback, funcName) { return { onSuccess: callback.onSuccess, onError: function (errorCode, result) { RongIMClient.logger({ code: errorCode, funcName: funcName }); callback.onError(errorCode, result); }, onBefore: callback.onBefore }; }; ; /** * 初始化 SDK,在整个应用全局只需要调用一次。 * @param appKey 开发者后台申请的 AppKey,用来标识应用。 * @param dataAccessProvider 必须是DataAccessProvider的实例 */ RongIMClient.init = function (appKey, dataAccessProvider, options, callback) { RongIMClient.statusListeners = []; RongIMClient.messageListeners = []; RongIMClient.conversationStatusListeners = []; if (RongIMClient._instance) { return RongIMClient._memoryStore.sdkInfo; } RongIMClient._instance = new RongIMClient(); options = options || {}; var protocol = "http://", wsScheme = 'ws://'; var isLocationInvalid = typeof location !== 'object'; // 未找到全局 location 变量, 则协议为 https. 比如小程序 if (isLocationInvalid || location.protocol == 'https:') { wsScheme = 'wss://'; protocol = 'https://'; } var isPolling = false; if (typeof WebSocket != 'function') { isPolling = true; } var isIntegrity = function () { //iOS 9 var hasWS = (typeof WebSocket); var integrity = (typeof WebSocket.OPEN == 'number'); return (hasWS && integrity); }; if (typeof WebSocket == 'object' && isIntegrity()) { isPolling = false; } var supportUserData = function () { var element = document.documentElement; return element.addBehavior; }; if (RongIMLib.RongUtil.supportLocalStorage()) { RongIMClient._storageProvider = new RongIMLib.LocalStorageProvider(); } else if (supportUserData()) { RongIMClient._storageProvider = new RongIMLib.UserDataProvider(); } else { RongIMClient._storageProvider = new RongIMLib.MemeoryProvider(); } var serverIndex = RongIMClient._storageProvider.getItem('serverIndex'); RongIMClient.serverStore.index = serverIndex || 0; var pathTmpl = '{0}{1}'; var _serverPath = { api: 'api.cn.ronghub.com' }; RongIMLib.RongUtil.forEach(_serverPath, function (path, key) { _serverPath[key] = RongIMLib.RongUtil.stringFormat(pathTmpl, [protocol, path]); }); RongIMLib.RongUtil.forEach(_serverPath, function (path, key) { var hasProto = (key in options); var config = { path: options[key], tmpl: pathTmpl, protocol: protocol, sub: true }; path = hasProto ? RongIMLib.RongUtil.formatProtoclPath(config) : path; options[key] = path; }); var navigaters = options.navigaters || []; if (options.navi) { navigaters = [options.navi]; } if (!options.navi && RongIMLib.RongUtil.isEqual(navigaters.length, 0)) { navigaters = ['nav.cn.ronghub.com', 'nav2-cn.ronghub.com']; } var _sourcePath = { protobuf: 'cdn.ronghub.com/protobuf-2.3.7.min.js' }; RongIMLib.RongUtil.forEach(_sourcePath, function (path, key) { _sourcePath[key] = RongIMLib.RongUtil.stringFormat(pathTmpl, [protocol, path]); }); RongIMLib.RongUtil.extend(_sourcePath, options); var _defaultOpts = { isPolling: isPolling, wsScheme: wsScheme, protocol: protocol, showError: true, openMp: true, snifferTime: 2000, naviTimeout: 5000, navigaters: navigaters, maxNaviRetry: 10, isNaviJSONP: false, isWSPingJSONP: false, isNotifyConversationList: false, maxConversationCount: 300, cmpUrl: '' // 若传入 cmpUrl, 则优先链接此地址 }; delete options.navigaters; RongIMLib.RongUtil.extend(_defaultOpts, options); if (RongIMLib.RongUtil.isFunction(options.protobuf)) { RongIMClient.Protobuf = options.protobuf; } RongIMClient.userStatusObserver = new RongIMLib.RongObserver(); var pather = new RongIMLib.FeaturePatcher(); pather.patchAll(); var tempStore = { token: "", callback: null, lastReadTime: new RongIMLib.LimitableMap(), historyMessageLimit: new RongIMLib.MemoryCache(), conversationList: [], appKey: appKey, publicServiceMap: new RongIMLib.PublicServiceMap(), providerType: 1, deltaTime: 0, filterMessages: [], isSyncRemoteConverList: true, otherDevice: false, custStore: {}, converStore: { latestMessage: {} }, connectAckTime: 0, voipStategy: 0, isFirstPingMsg: true, depend: options, notification: {}, networkUnavailable: false, loggerSwitch: options.loggerSwitch || 'on' }; RongIMClient._memoryStore = tempStore; var isCPlusSDK = dataAccessProvider && Object.prototype.toString.call(dataAccessProvider) == "[object Object]"; if (isCPlusSDK) { RongIMClient._dataAccessProvider = dataAccessProvider; } else { RongIMClient._dataAccessProvider = new RongIMLib.ServerDataProvider(); } options.appCallback = callback; var sdkInfo = RongIMClient._dataAccessProvider.init(appKey, options); RongIMClient._memoryStore.sdkInfo = sdkInfo; if (isCPlusSDK) { // 兼容 c++ 设置导航,Web 端不生效 RongIMClient._dataAccessProvider.setServerInfo({ navi: location.protocol + options.navi + '/navi.xml' }); } RongIMClient.MessageParams = { TextMessage: { objectName: "RC:TxtMsg", msgTag: new RongIMLib.MessageTag(true, true) }, ImageMessage: { objectName: "RC:ImgMsg", msgTag: new RongIMLib.MessageTag(true, true) }, DiscussionNotificationMessage: { objectName: "RC:DizNtf", msgTag: new RongIMLib.MessageTag(false, true) }, VoiceMessage: { objectName: "RC:VcMsg", msgTag: new RongIMLib.MessageTag(true, true) }, ReferenceMessage: { objectName: "RC:ReferenceMsg", msgTag: new RongIMLib.MessageTag(true, true) }, RichContentMessage: { objectName: "RC:ImgTextMsg", msgTag: new RongIMLib.MessageTag(true, true) }, FileMessage: { objectName: "RC:FileMsg", msgTag: new RongIMLib.MessageTag(true, true) }, HQVoiceMessage: { objectName: "RC:HQVCMsg", msgTag: new RongIMLib.MessageTag(true, true) }, GIFMessage: { objectName: "RC:GIFMsg", msgTag: new RongIMLib.MessageTag(true, true) }, SightMessage: { objectName: "RC:SightMsg", msgTag: new RongIMLib.MessageTag(true, true) }, HandshakeMessage: { objectName: "", msgTag: new RongIMLib.MessageTag(true, true) }, UnknownMessage: { objectName: "", msgTag: new RongIMLib.MessageTag(true, true) }, LocationMessage: { objectName: "RC:LBSMsg", msgTag: new RongIMLib.MessageTag(true, true) }, InformationNotificationMessage: { objectName: "RC:InfoNtf", msgTag: new RongIMLib.MessageTag(false, true) }, ContactNotificationMessage: { objectName: "RC:ContactNtf", msgTag: new RongIMLib.MessageTag(false, true) }, ProfileNotificationMessage: { objectName: "RC:ProfileNtf", msgTag: new RongIMLib.MessageTag(false, true) }, CommandNotificationMessage: { objectName: "RC:CmdNtf", msgTag: new RongIMLib.MessageTag(false, true) }, PublicServiceRichContentMessage: { objectName: "RC:PSImgTxtMsg", msgTag: new RongIMLib.MessageTag(true, true) }, PublicServiceMultiRichContentMessage: { objectName: "RC:PSMultiImgTxtMsg", msgTag: new RongIMLib.MessageTag(true, true) }, JrmfRedPacketMessage: { objectName: "RCJrmf:RpMsg", msgTag: new RongIMLib.MessageTag(true, true) }, JrmfRedPacketOpenedMessage: { objectName: "RCJrmf:RpOpendMsg", msgTag: new RongIMLib.MessageTag(true, true) }, GroupNotificationMessage: { objectName: "RC:GrpNtf", msgTag: new RongIMLib.MessageTag(false, true) }, CommandMessage: { objectName: "RC:CmdMsg", msgTag: new RongIMLib.MessageTag(false, false) }, TypingStatusMessage: { objectName: "RC:TypSts", msgTag: new RongIMLib.MessageTag(false, false) }, PublicServiceCommandMessage: { objectName: "RC:PSCmd", msgTag: new RongIMLib.MessageTag(false, false) }, RecallCommandMessage: { objectName: "RC:RcCmd", msgTag: new RongIMLib.MessageTag(false, true) }, SyncReadStatusMessage: { objectName: "RC:SRSMsg", msgTag: new RongIMLib.MessageTag(false, false) }, ReadReceiptRequestMessage: { objectName: "RC:RRReqMsg", msgTag: new RongIMLib.MessageTag(false, false) }, ReadReceiptResponseMessage: { objectName: "RC:RRRspMsg", msgTag: new RongIMLib.MessageTag(false, false) }, ChangeModeResponseMessage: { objectName: "RC:CsChaR", msgTag: new RongIMLib.MessageTag(false, false) }, ChangeModeMessage: { objectName: "RC:CSCha", msgTag: new RongIMLib.MessageTag(false, false) }, EvaluateMessage: { objectName: "RC:CsEva", msgTag: new RongIMLib.MessageTag(false, false) }, CustomerContact: { objectName: "RC:CsContact", msgTag: new RongIMLib.MessageTag(false, false) }, HandShakeMessage: { objectName: "RC:CsHs", msgTag: new RongIMLib.MessageTag(false, false) }, HandShakeResponseMessage: { objectName: "RC:CsHsR", msgTag: new RongIMLib.MessageTag(false, false) }, SuspendMessage: { objectName: "RC:CsSp", msgTag: new RongIMLib.MessageTag(false, false) }, TerminateMessage: { objectName: "RC:CsEnd", msgTag: new RongIMLib.MessageTag(false, false) }, CustomerStatusUpdateMessage: { objectName: "RC:CsUpdate", msgTag: new RongIMLib.MessageTag(false, false) }, ReadReceiptMessage: { objectName: "RC:ReadNtf", msgTag: new RongIMLib.MessageTag(false, false) }, RCCombineMessage: { objectName: "RC:CombineMsg", msgTag: new RongIMLib.MessageTag(true, true) }, ChrmKVNotificationMessage: { objectName: 'RC:chrmKVNotiMsg', msgTag: new RongIMLib.MessageTag(false, false) }, LogCommandMessage: { objectName: 'RC:LogCmdMsg', msgTag: new RongIMLib.MessageTag(false, false) } }; RongIMClient.MessageParams["AcceptMessage"] = { objectName: "RC:VCAccept", msgTag: new RongIMLib.MessageTag(false, false) }; RongIMClient.MessageParams["RingingMessage"] = { objectName: "RC:VCRinging", msgTag: new RongIMLib.MessageTag(false, false) }; RongIMClient.MessageParams["SummaryMessage"] = { objectName: "RC:VCSummary", msgTag: new RongIMLib.MessageTag(false, false) }; RongIMClient.MessageParams["HungupMessage"] = { objectName: "RC:VCHangup", msgTag: new RongIMLib.MessageTag(false, false) }; RongIMClient.MessageParams["InviteMessage"] = { objectName: "RC:VCInvite", msgTag: new RongIMLib.MessageTag(false, false) }; RongIMClient.MessageParams["MediaModifyMessage"] = { objectName: "RC:VCModifyMedia", msgTag: new RongIMLib.MessageTag(false, false) }; RongIMClient.MessageParams["MemberModifyMessage"] = { objectName: "RC:VCModifyMem", msgTag: new RongIMLib.MessageTag(false, false) }; RongIMClient.MessageType = { TextMessage: "TextMessage", ImageMessage: "ImageMessage", ReferenceMessage: "ReferenceMessage", DiscussionNotificationMessage: "DiscussionNotificationMessage", VoiceMessage: "VoiceMessage", RichContentMessage: "RichContentMessage", HandshakeMessage: "HandshakeMessage", UnknownMessage: "UnknownMessage", LocationMessage: "LocationMessage", InformationNotificationMessage: "InformationNotificationMessage", ContactNotificationMessage: "ContactNotificationMessage", ProfileNotificationMessage: "ProfileNotificationMessage", CommandNotificationMessage: "CommandNotificationMessage", CommandMessage: "CommandMessage", TypingStatusMessage: "TypingStatusMessage", ChangeModeResponseMessage: "ChangeModeResponseMessage", ChangeModeMessage: "ChangeModeMessage", EvaluateMessage: "EvaluateMessage", HandShakeMessage: "HandShakeMessage", HandShakeResponseMessage: "HandShakeResponseMessage", SuspendMessage: "SuspendMessage", TerminateMessage: "TerminateMessage", CustomerContact: "CustomerContact", CustomerStatusUpdateMessage: "CustomerStatusUpdateMessage", SyncReadStatusMessage: "SyncReadStatusMessage", ReadReceiptRequestMessage: "ReadReceiptRequestMessage", ReadReceiptResponseMessage: "ReadReceiptResponseMessage", FileMessage: 'FileMessage', HQVoiceMessage: 'HQVoiceMessage', GIFMessage: 'GIFMessage', SightMessage: 'SightMessage', AcceptMessage: "AcceptMessage", RingingMessage: "RingingMessage", SummaryMessage: "SummaryMessage", HungupMessage: "HungupMessage", InviteMessage: "InviteMessage", MediaModifyMessage: "MediaModifyMessage", MemberModifyMessage: "MemberModifyMessage", JrmfRedPacketMessage: "JrmfRedPacketMessage", JrmfRedPacketOpenedMessage: "JrmfRedPacketOpenedMessage", GroupNotificationMessage: "GroupNotificationMessage", PublicServiceRichContentMessage: "PublicServiceRichContentMessage", PublicServiceMultiRichContentMessage: "PublicServiceMultiRichContentMessage", PublicServiceCommandMessage: "PublicServiceCommandMessage", RecallCommandMessage: "RecallCommandMessage", ReadReceiptMessage: "ReadReceiptMessage", RCCombineMessage: "RCCombineMessage", ChrmKVNotificationMessage: 'ChrmKVNotificationMessage', LogCommandMessage: 'LogCommandMessage' }; RongIMClient.LogFactory = { /** * 个人 */ "-1": { code: "-1", msg: "服务器超时" }, "-2": { code: "-2", msg: "未知原因失败" }, "-3": { code: "-3", msg: "参数错误" }, "-4": { code: "-4", msg: "参数不正确或尚未实例化" }, "25101": { code: "25101", msg: "撤回消息参数错误", desc: "请检查撤回消息参数 https://rongcloud.github.io/websdk-demo/api-test.html" }, "25102": { code: "25101", msg: "只能撤回自发发送的消息" }, "20604": { code: "20604", msg: "发送频率过快", desc: "https://developer.rongcloud.cn/ticket/info/9Q3L6vRKd1cLS7rycA==?type=1" }, "20406": { code: "20406", msg: "被禁言" }, "23407": { code: "23407", msg: "获取用户失败" }, /** * 群组 */ "20407": { code: "20407", msg: "群组Id无效" }, "22408": { code: "22408", msg: "群组被禁言" }, "22406": { code: "22406", msg: "不在群组" }, "35001": { code: "35001", msg: "群组同步异常" }, "35002": { code: "35002", msg: "匹配群信息异常" }, /** * 讨论组 */ "21406": { code: "21406", msg: "不在讨论组" }, "21407": { code: "21407", msg: "加入讨论失败" }, "21408": { code: "21408", msg: "创建讨论组失败" }, "21409": { code: "21409", msg: "设置讨论组邀请状态失败" }, /** * 聊天室 */ "23406": { code: "23406", msg: "不在聊天室" }, "23408": { code: "23408", msg: "聊天室被禁言" }, "23409": { code: "23409", msg: "聊天室中成员被踢出" }, "23410": { code: "23410", msg: "聊天室不存在" }, "23411": { code: "23411", msg: "聊天室成员已满" }, "23412": { code: "23412", msg: "获取聊天室信息参数无效" }, "23413": { code: "23413", msg: "聊天室异常" }, "23414": { code: "23414", msg: "没有打开聊天室消息存储" }, "36001": { code: "36001", msg: "加入聊天室Id为空" }, "36002": { code: "36002", msg: "加入聊天室失败" }, "36003": { code: "36003", msg: "拉取聊天室历史消息失败" }, /** * voip */ "24001": { code: "24001", msg: "没有注册DeviveId 也就是用户没有登陆" }, "24002": { code: "24002", msg: "用户已经存在" }, "0": { code: "0", msg: "成功" }, "24009": { code: "24009", msg: "没有对应的用户或token" }, "24013": { code: "24013", msg: "voip为空" }, "24010": { code: "24010", msg: "不支持的Voip引擎" }, "24011": { code: "24011", msg: "channelName 是空" }, "24012": { code: "24012", msg: "生成Voipkey失败" }, "24014": { code: "24014", msg: "没有配置voip" }, "24015": { code: "24015", msg: "服务器内部错误" }, "24016": { code: "24016", msg: "VOIP close" }, /** * 通讯、导航 */ "30001": { code: "30001", msg: "通信过程中,当前Socket不存在" }, "30002": { code: "30002", msg: "Socket连接不可用" }, "30003": { code: "30003", msg: "通信超时" }, "30004": { code: "30004", msg: "导航操作时,Http请求失败" }, "30005": { code: "30005", msg: "HTTP请求失败" }, "30006": { code: "30006", msg: "HTTP接收失败" }, "30007": { code: "30007", msg: "导航资源错误" }, "30008": { code: "30008", msg: "没有有效数据" }, "30009": { code: "30009", msg: "不存在有效 IP 地址" }, "30010": { code: "30010", msg: "创建 Socket 失败" }, "30011": { code: "30011", msg: " Socket 被断开" }, "30012": { code: "30012", msg: "PING 操作失败" }, "30013": { code: "30013", msg: "PING 超时" }, "30014": { code: "30014", msg: "消息发送失败" }, "30016": { code: "30016", msg: "消息大小超限,最大 128 KB" }, /** * 连接 */ "31000": { code: "31000", msg: "做 connect 连接时,收到的 ACK 超时" }, "31001": { code: "31001", msg: "参数错误" }, "31002": { code: "31002", msg: "参数错误,App Id 错误" }, "31003": { code: "31003", msg: "服务器不可用" }, "31004": { code: "31004", msg: "Token 错误" }, "31005": { code: "31005", msg: "App Id 与 Token 不匹配" }, "31006": { code: "31006", msg: "重定向,地址错误" }, "31007": { code: "31007", msg: "NAME 与后台注册信息不一致" }, "31008": { code: "31008", msg: "APP 被屏蔽、删除或不存在" }, "31009": { code: "31009", msg: "用户被屏蔽" }, "31010": { code: "31010", msg: "Disconnect,由服务器返回,比如用户互踢" }, "31011": { code: "31011", msg: "Disconnect,由服务器返回,比如用户互踢" }, /** * 协议 */ "32001": { code: "32001", msg: "协议层内部错误。query,上传下载过程中数据错误" }, "32002": { code: "32002", msg: "协议层内部错误" }, /** * BIZ */ "33001": { code: "33001", msg: "未调用 init 初始化函数" }, "33002": { code: "33002", msg: "数据库初始化失败" }, "33003": { code: "33003", msg: "传入参数无效" }, "33004": { code: "33004", msg: "通道无效" }, "33005": { code: "33005", msg: "重新连接成功" }, "33006": { code: "33006", msg: "连接中,再调用 connect 被拒绝" }, "33007": { code: "33007", msg: "消息漫游服务未开通" }, "33008": { code: "33008", msg: "消息添加失败" }, "33009": { code: "33009", msg: "消息删除失败" }, /** * 会话 */ "34001": { code: "34001", msg: "删除会话失败" }, "34002": { code: "34002", msg: "拉取历史消息失败" }, "34003": { code: "34003", msg: "会话指定异常" }, "34004": { code: "34004", msg: "获取会话未读消息总数失败" }, "34005": { code: "34005", msg: "获取指定会话类型未读消息数异常" }, "34006": { code: "34006", msg: "获取指定用户ID&会话类型未读消息数异常" }, "34007": { code: "34007", msg: "清除会话消息异常" }, "34008": { code: "34008", msg: "获取会话消息异常" }, "34009": { code: "34009", msg: "清除历史消息会话类型不正确" }, "34010": { code: "34010", msg: "清除历史消息失败,请检查传入参数" }, /** * 黑名单异常 */ "37001": { code: "37001", msg: "加入黑名单异常" }, "37002": { code: "37002", msg: "获得指定人员再黑名单中的状态异常" }, "37003": { code: "37003", msg: "移除黑名单异常" }, "405": { code: "405", msg: "在黑名单中" }, /** * 草稿 */ "38001": { code: "38001", msg: "获取草稿失败" }, "38002": { code: "38002", msg: "保存草稿失败" }, "38003": { code: "38003", msg: "删除草稿失败" }, /** * 公众号 */ "39001": { code: "39001", msg: "关注公众号失败" }, /** * 文件 */ "41001": { code: "41001", msg: "文件类型错误" }, "41002": { code: "41002", msg: "获取七牛token失败" }, /** * */ "51001": { code: "51001", msg: "未安装或未启动插件" }, "51002": { code: "51002", msg: "视频已经存在" }, "51003": { code: "51003", msg: "无效的channelName" }, "51004": { code: "51004", msg: "视频内容为空" }, /** * */ "61001": { code: "61001", msg: "删除消息数组长度为 0" } }; var handler = function (message, uris, callback) { var userId = message.senderUserId; var _uris = RongIMClient.roomInfo.users[userId].uris || '[]'; if (RongIMLib.RongUtil.isString(_uris)) { _uris = JSON.parse(_uris); } var tUris = JSON.parse(JSON.stringify(_uris)); RongIMLib.RongUtil.forEach(tUris, function (_uri, index) { RongIMLib.RongUtil.forEach(uris, function (uri) { if (uri.uri == _uri.uri) { callback(_uri, uri, _uris, index); } }); }); RongIMClient.roomInfo.users[userId].uris = JSON.stringify(_uris); }; var RTCMessage = { RTCPublishResourceMessage: function (message, uris) { var userId = message.senderUserId; var user = RongIMClient.roomInfo.users[userId]; if (!user) { user = {}; RongIMClient.roomInfo.users[userId] = {}; } var _uris = user.uris || '[]'; if (RongIMLib.RongUtil.isString(_uris)) { _uris = JSON.parse(_uris); } _uris = _uris.concat(uris); RongIMClient.roomInfo.users[userId].uris = JSON.stringify(_uris); }, RTCUnpublishResourceMessage: function (message, uris) { handler(message, uris, function (_uri, uri, _uris, index) { _uris.splice(index, 1); }); }, RTCModifyResourceMessage: function (message, uris) { handler(message, uris, function (_uri, uri) { _uri.state = uri.state; }); }, RTCUserChangeMessage: function (message) { var content = message.content; var users = content.users; var UserState = { JOINED: 0, LEFT: 1, OFFLINE: 2 }; RongIMLib.RongUtil.forEach(users, function (user) { var state = user.state; var userId = user.userId; switch (+state) { case UserState.JOINED: RongIMClient.roomInfo.users[userId] = {}; break; case UserState.LEFT: case UserState.OFFLINE: delete RongIMClient.roomInfo.users[userId]; break; } }); } }; RongIMClient.RTCInnerListener = function (message) { var func = RTCMessage[message.messageType] || function () { }; var content = message.content; var uris = content.uris; func(message, uris); }; RongIMClient.Conversation = RongIMClient._dataAccessProvider.Conversation; RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.A_INIT_O, level: RongIMLib.LoggerLevel.I, type: RongIMLib.LoggerType.IM, content: { appKey: appKey } }); return sdkInfo; }; ; RongIMClient.setProtocol = function (protocol) { RongIMClient._memoryStore.depend = RongIMClient._memoryStore.depend || {}; var HttpProtocol = RongIMClient.HttpProtocol; var WsProtocol = RongIMClient.WsProtocol; if (protocol === HttpProtocol.http) { RongIMClient._memoryStore.depend.protocol = HttpProtocol.http; RongIMClient._memoryStore.depend.wsScheme = WsProtocol.ws; } else { RongIMClient._memoryStore.depend.protocol = HttpProtocol.https; RongIMClient._memoryStore.depend.wsScheme = WsProtocol.wss; } }; RongIMClient.getProtocol = function () { RongIMClient._memoryStore.depend = RongIMClient._memoryStore.depend || {}; var depend = RongIMClient._memoryStore.depend; var protocol = depend.protocol, wsScheme = depend.wsScheme; if (!protocol || !wsScheme) { protocol = RongIMClient.HttpProtocol.https; wsScheme = RongIMClient.WsProtocol.wss; } return { protocol: protocol, wsScheme: wsScheme }; }; /** var config = { appkey: appkey, token: token, dataAccessProvider:dataAccessProvider, opts: opts }; callback(_instance, userId); */ RongIMClient.initApp = function (config, callback) { RongIMClient.init(config.appkey, config.dataAccessProvider, config.opts, function () { var instance = RongIMClient._instance; //备用 var error = null; callback(error, instance); }); }; /** * 连接服务器,在整个应用全局只需要调用一次,断线后 SDK 会自动重连。 * * @param token 从服务端获取的用户身份令牌(Token)。 * @param callback 连接回调,返回连接的成功或者失败状态。 */ RongIMClient.connect = function (token, _callback, userId, serverConf) { RongIMLib.CheckParam.getInstance().check(["string", "object", "string|null|object|global|undefined", "object|null|global|undefined"], "connect", true, arguments); if (RongIMLib.IMHandler.isIncludeNavi(token)) { var protocol = RongIMClient._memoryStore.depend.protocol; var currentNavs = RongIMClient._memoryStore.depend.navigaters; var navList = RongIMLib.IMHandler.getNavsByToken(token, protocol); token = RongIMLib.IMHandler.getToken(token); RongIMClient._memoryStore.depend.navigaters = RongIMLib.RongUtil.concat(navList, currentNavs, true); } var connectCallback = { onSuccess: _callback.onSuccess, onTokenIncorrect: _callback.onTokenIncorrect, onError: function (errorCode) { RongIMClient.logger({ code: errorCode, funcName: "connect" }); _callback.onError(errorCode); } }; RongIMClient._dataAccessProvider.connect(token, connectCallback, userId, serverConf); }; RongIMClient.reconnect = function (callback, config) { var connectCallback = { onSuccess: callback.onSuccess, onTokenIncorrect: callback.onTokenIncorrect, onError: function (errorCode) { RongIMClient.logger({ code: errorCode, funcName: "connect" }); callback.onError(errorCode); } }; RongIMClient._dataAccessProvider.reconnect(connectCallback, config); }; /** * 注册消息类型,用于注册用户自定义的消息。 * 内建的消息类型已经注册过,不需要再次注册。 * 自定义消息声明需放在执行顺序最高的位置(在RongIMClient.init(appkey)之后即可) * @param objectName 消息内置名称 */ RongIMClient.registerMessageType = function (messageType, objectName, messageTag, messageContent, searchProps) { RongIMClient._dataAccessProvider.registerMessageType(messageType, objectName, messageTag, messageContent, searchProps); RongIMClient.RegisterMessage[messageType].messageName = messageType; RongIMClient.MessageType[messageType] = messageType; RongIMClient.MessageParams[messageType] = { objectName: objectName, msgTag: messageTag }; }; RongIMClient.prototype.registerMessageTypes = function (types) { types = types || {}; RongIMClient._dataAccessProvider.registerMessageTypes(types); }; /** * 设置连接状态变化的监听器。 * * @param listener 连接状态变化的监听器。 */ RongIMClient.setConnectionStatusListener = function (listener) { if (RongIMClient._dataAccessProvider) { RongIMClient._dataAccessProvider.setConnectionStatusListener(listener); } else { if (RongIMLib.RongUtil.isObject(listener) && RongIMLib.RongUtil.isFunction(listener.onChanged)) { RongIMClient.statusListeners.push(listener.onChanged); } } }; RongIMClient.setConversationStatusListener = function (listener) { if (listener && listener.onChanged && RongIMLib.RongUtil.isFunction(listener.onChanged)) { RongIMClient.conversationStatusListeners.push(listener.onChanged); } }; RongIMClient.statusWatch = function (watcher) { if (RongIMLib.RongUtil.isFunction(watcher)) { RongIMClient.statusListeners.push(watcher); } }; /** * 设置接收消息的监听器。 * * @param listener 接收消息的监听器。 */ RongIMClient.setOnReceiveMessageListener = function (listener) { if (RongIMClient._dataAccessProvider) { RongIMClient._dataAccessProvider.setOnReceiveMessageListener(listener); } else { if (RongIMLib.RongUtil.isObject(listener) && RongIMLib.RongUtil.isFunction(listener.onReceived)) { RongIMClient.messageListeners.push(listener.onReceived); } } }; /** * 清理所有连接相关的变量 */ RongIMClient.prototype.logout = function () { RongIMClient._dataAccessProvider.logout(); }; /** * 断开连接。 */ RongIMClient.prototype.disconnect = function () { RongIMClient._dataAccessProvider.disconnect(); RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.A_DISC_O, level: RongIMLib.LoggerLevel.I, type: RongIMLib.LoggerType.IM }); }; RongIMClient.prototype.startCustomService = function (custId, callback, content) { if (!custId || !callback) return; var msg = new RongIMLib.HandShakeMessage(content); var me = this; RongIMLib.RongIMClient._memoryStore.custStore["isInit"] = true; RongIMClient.getInstance().sendMessage(RongIMLib.ConversationType.CUSTOMER_SERVICE, custId, msg, { onSuccess: function (data) { if (data.isBlack) { callback.onError(); me.stopCustomeService(custId, { onSuccess: function () { }, onError: function () { } }); } else { callback.onSuccess(); } }, onError: function () { callback.onError(); }, onBefore: function () { } }); }; RongIMClient.prototype.stopCustomeService = function (custId, callback) { if (!custId || !callback) return; var session = RongIMClient._memoryStore.custStore[custId]; if (!session) return; var msg = new RongIMLib.SuspendMessage({ sid: session.sid, uid: session.uid, pid: session.pid }); this.sendCustMessage(custId, msg, { onSuccess: function () { // delete RongIMClient._memoryStore.custStore[custId]; setTimeout(function () { callback.onSuccess(); }); }, onError: function () { setTimeout(function () { callback.onError(); }); } }); }; RongIMClient.prototype.switchToHumanMode = function (custId, callback) { if (!custId || !callback) return; var session = RongIMClient._memoryStore.custStore[custId]; if (!session) return; var msg = new RongIMLib.ChangeModeMessage({ sid: session.sid, uid: session.uid, pid: session.pid }); this.sendCustMessage(custId, msg, callback); }; RongIMClient.prototype.evaluateRebotCustomService = function (custId, isRobotResolved, sugest, callback) { if (!custId || !callback) return; var session = RongIMClient._memoryStore.custStore[custId]; if (!session) return; var msg = new RongIMLib.EvaluateMessage({ sid: session.sid, uid: session.uid, pid: session.pid, isRobotResolved: isRobotResolved, sugest: sugest, type: 0 }); this.sendCustMessage(custId, msg, callback); }; RongIMClient.prototype.evaluateHumanCustomService = function (custId, humanValue, sugest, callback) { if (!custId || !callback) return; var session = RongIMClient._memoryStore.custStore[custId]; if (!session) return; var msg = new RongIMLib.EvaluateMessage({ sid: session.sid, uid: session.uid, pid: session.pid, humanValue: humanValue, sugest: sugest, type: 1 }); this.sendCustMessage(custId, msg, callback); }; RongIMClient.prototype.sendCustMessage = function (custId, msg, callback) { RongIMClient.getInstance().sendMessage(RongIMLib.ConversationType.CUSTOMER_SERVICE, custId, msg, { onSuccess: function (data) { callback.onSuccess(); }, onError: function () { callback.onError(); }, onBefore: function () { } }); }; /** * 获取当前连接的状态。 */ RongIMClient.prototype.getCurrentConnectionStatus = function () { return RongIMClient._dataAccessProvider.getCurrentConnectionStatus(); }; /** * 获取当前使用的连接通道。 */ RongIMClient.prototype.getConnectionChannel = function () { if (RongIMLib.Transportations._TransportType == RongIMLib.Socket.XHR_POLLING) { return RongIMLib.ConnectionChannel.XHR_POLLING; } else if (RongIMLib.Transportations._TransportType == RongIMLib.Socket.WEBSOCKET) { return RongIMLib.ConnectionChannel.WEBSOCKET; } }; /** * 获取当前使用的本地储存提供者。 TODO */ RongIMClient.prototype.getStorageProvider = function () { if (RongIMClient._memoryStore.providerType == 1) { return "ServerDataProvider"; } else { return "OtherDataProvider"; } }; /** * 过滤聊天室消息(拉取最近聊天消息) * @param {string[]} msgFilterNames */ RongIMClient.prototype.setFilterMessages = function (msgFilterNames) { if (Object.prototype.toString.call(msgFilterNames) == "[object Array]") { RongIMClient._memoryStore.filterMessages = msgFilterNames; } }; RongIMClient.prototype.getAgoraDynamicKey = function (engineType, channelName, callback) { RongIMClient._dataAccessProvider.getAgoraDynamicKey(engineType, channelName, callback); }; /** * 获取当前连接用户的 UserId。 */ RongIMClient.prototype.getCurrentUserId = function () { return RongIMLib.Bridge._client.userId; }; /** * 获取服务器时间与本地时间的差值,单位为毫秒。 * 计算公式:差值 = 本地时间毫秒数 - 服务器时间毫秒数 * @param callback 获取的回调,返回差值。 */ RongIMClient.prototype.getDeltaTime = function () { return RongIMClient._dataAccessProvider.getDelaTime(); }; // #region Message RongIMClient.prototype.getMessage = function (messageId, callback) { RongIMClient._dataAccessProvider.getMessage(messageId, RongIMClient.logCallback(callback, "getMessage")); }; RongIMClient.prototype.deleteLocalMessages = function (conversationType, targetId, messageIds, callback) { RongIMClient._dataAccessProvider.removeLocalMessage(conversationType, targetId, messageIds, RongIMClient.logCallback(callback, "deleteLocalMessages")); }; RongIMClient.prototype.updateMessage = function (message, callback) { RongIMClient._dataAccessProvider.updateMessage(message, RongIMClient.logCallback(callback, "updateMessage")); }; RongIMClient.prototype.clearData = function () { return RongIMClient._dataAccessProvider.clearData(); }; RongIMClient.prototype.clearMessages = function (conversationType, targetId, callback) { RongIMClient._dataAccessProvider.clearMessages(conversationType, targetId, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "clearMessages" }); callback.onError(errorCode); }); } }); }; /**TODO 清楚本地存储的未读消息,目前清空内存中的未读消息 * [clearMessagesUnreadStatus 清空指定会话未读消息] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [用户id] * @param {ResultCallback} callback [返回值,参数回调] */ RongIMClient.prototype.clearMessagesUnreadStatus = function (conversationType, targetId, callback) { RongIMClient._dataAccessProvider.updateMessages(conversationType, targetId, "readStatus", null, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "clearMessagesUnreadStatus" }); callback.onError(errorCode); }); } }); }; // deleteRemoteMessages(conversationType: ConversationType, targetId: string, delMsgs: DeleteMessage[], callback: ResultCallback) { // CheckParam.getInstance().check(["number", "string|number", "array", "object"], "deleteRemoteMessages", false, arguments); // if (delMsgs.length == 0) { // var errorCode = ErrorCode.DELETE_MESSAGE_ID_IS_NULL; // RongIMClient.logger({ // code: errorCode, // funcName: "deleteRemoteMessages" // }); // callback.onError(ErrorCode.DELETE_MESSAGE_ID_IS_NULL); // return; // } else if (delMsgs.length > 100) { // delMsgs.length = 100; // } // // 后续增加,去掉注释即可 // callback.onSuccess(true); // // var modules = new RongIMClient.Protobuf.DeleteMsgInput(); // // modules.setType(conversationType); // // modules.setConversationId(targetId); // // modules.setMsgs(delMsgs); // // RongIMClient.bridge.queryMsg(33, MessageUtil.ArrayForm(modules.toArrayBuffer()), Bridge._client.userId, { // // onSuccess: function(info: any) { // // callback.onSuccess(true); // // }, // // onError: function(err: any) { // // callback.onError(err); // // } // // }, "DeleteMsgOutput"); // } /** * [deleteMessages 删除消息记录。] * @param {ConversationType} conversationType [description] * @param {string} targetId [description] * @param {number[]} messageIds [description] * @param {ResultCallback} callback [description] */ RongIMClient.prototype.deleteMessages = function (conversationType, targetId, messages, callback) { RongIMClient._dataAccessProvider.removeMessage(conversationType, targetId, messages, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "deleteMessages" }); callback.onError(errorCode); }); } }); }; RongIMClient.prototype.sendLocalMessage = function (message, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object"], "sendLocalMessage", false, arguments); RongIMClient._dataAccessProvider.updateMessage(message); this.sendMessage(message.conversationType, message.targetId, message.content, RongIMClient.logSendCallback(callback, "sendLocalMessage")); }; RongIMClient.prototype.getPullSetting = function (callback) { RongIMClient._dataAccessProvider.getPullSetting(callback); }; RongIMClient.prototype.setOfflineMessageDuration = function (duration, callback) { RongIMLib.CheckParam.getInstance().check(["number", "object"], "setOfflineMessageDuration", true, arguments); RongIMClient._dataAccessProvider.setOfflineMessageDuration(duration, callback); }; /** * [sendMessage 发送消息。] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [目标Id] * @param {MessageContent} messageContent [消息类型] * @param {SendMessageCallback} sendCallback [] * @param {ResultCallback} resultCallback [返回值,函数回调] * @param {string} pushContent [] * @param {string} pushData [] */ RongIMClient.prototype.sendMessage = function (conversationType, targetId, messageContent, sendCallback, mentiondMsg, pushText, appData, methodType, params) { RongIMLib.CheckParam.getInstance().check(["number", "string", "object", "object", "undefined|object|null|global|boolean", "undefined|object|null|global|string", "undefined|object|null|global|string", "undefined|object|null|global|number", "undefined|object|null|global"], "sendMessage", false, arguments); if (!RongIMLib.RongUtil.isString(targetId)) { return sendCallback.onError(RongIMLib.ErrorCode.PARAMETER_ERROR); } RongIMClient._dataAccessProvider.sendMessage(conversationType, targetId, messageContent, RongIMClient.logSendCallback(sendCallback, "sendMessage"), mentiondMsg, pushText, appData, methodType, params); }; RongIMClient.prototype.setConversationStatus = function (type, targetId, statusItem, callback) { RongIMClient._dataAccessProvider.setConversationStatus(type, targetId, statusItem, callback); }; RongIMClient.prototype.sendReceiptResponse = function (conversationType, targetId, sendCallback) { RongIMClient._dataAccessProvider.sendReceiptResponse(conversationType, targetId, RongIMClient.logSendCallback(sendCallback, "sendReceiptResponse")); }; RongIMClient.prototype.sendTypingStatusMessage = function (conversationType, targetId, messageName, sendCallback) { RongIMClient._dataAccessProvider.sendTypingStatusMessage(conversationType, targetId, messageName, RongIMClient.logSendCallback(sendCallback, "sendTypingStatusMessage")); }; /** * [sendStatusMessage description] * @param {MessageContent} messageContent [description] * @param {SendMessageCallback} sendCallback [description] * @param {ResultCallback} resultCallback [description] */ RongIMClient.prototype.sendStatusMessage = function (messageContent, sendCallback, resultCallback) { throw new Error("Not implemented yet"); }; /** * [sendTextMessage 发送TextMessage快捷方式] * @param {string} content [消息内容] * @param {ResultCallback} resultCallback [返回值,参数回调] */ RongIMClient.prototype.sendTextMessage = function (conversationType, targetId, content, sendMessageCallback) { RongIMClient._dataAccessProvider.sendTextMessage(conversationType, targetId, content, RongIMClient.logSendCallback(sendMessageCallback, "sendTextMessage")); }; RongIMClient.prototype.sendRecallMessage = function (content, sendMessageCallback) { var callback = RongIMClient.logSendCallback(sendMessageCallback, "sendRecallMessage"); var senderUserId = content.senderUserId; var userId = RongIMLib.Bridge._client.userId; var isOther = (senderUserId != userId); if (isOther) { var callback = RongIMClient.logSendCallback(sendMessageCallback, "sendRecallMessage"); callback.onError(RongIMLib.ErrorCode.RECALL_MESSAGE, content); return; } RongIMClient._dataAccessProvider.sendRecallMessage(content, callback); }; /** * [insertMessage 向本地插入一条消息,不发送到服务器。] * @param {ConversationType} conversationType [description] * @param {string} targetId [description] * @param {string} senderUserId [description] * @param {MessageContent} content [description] * @param {ResultCallback} callback [description] */ RongIMClient.prototype.insertMessage = function (conversationType, targetId, content, callback) { RongIMClient._dataAccessProvider.addMessage(conversationType, targetId, content, RongIMClient.logCallback(callback, "insertMessage")); }; RongIMClient.prototype.setMessageContent = function (messageId, content, objectName) { RongIMClient._dataAccessProvider.setMessageContent(messageId, content, objectName); }; ; RongIMClient.prototype.setMessageSearchField = function (messageId, content, searchFiles) { RongIMClient._dataAccessProvider.setMessageSearchField(messageId, content, searchFiles); }; ; /** * [getHistoryMessages 拉取历史消息记录。] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [用户Id] * @param {number|null} pullMessageTime [拉取历史消息起始位置(格式为毫秒数),可以为null] * @param {number} count [历史消息数量] * @param {ResultCallback} callback [回调函数] * @param {string} objectName [objectName] */ RongIMClient.prototype.getHistoryMessages = function (conversationType, targetId, timestamp, count, callback, objectname, order) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "number|null|global|object", "number", "object", "undefined|object|null|global|string", "number|null|global|object"], "getHistoryMessages", false, arguments); if (count > 20) { throw new Error("HistroyMessage count must be less than or equal to 20!"); } if (conversationType.valueOf() < 0) { throw new Error("ConversationType must be greater than -1"); } RongIMClient._dataAccessProvider.getHistoryMessages(conversationType, targetId, timestamp, count, RongIMClient.logCallback(callback, "getHistoryMessages"), objectname, order); }; /** * [getRemoteHistoryMessages 拉取某个时间戳之前的消息] * @param {ConversationType} conversationType [description] * @param {string} targetId [description] * @param {Date} dateTime [description] * @param {number} count [description] * @param {ResultCallback} callback [description] */ RongIMClient.prototype.getRemoteHistoryMessages = function (conversationType, targetId, timestamp, count, callback, config) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "number|null|global|object", "number", "object", "undefined|null|global|object"], "getRemoteHistoryMessages", false, arguments); var funcName = "getRemoteHistoryMessages"; var log = { errorCode: RongIMLib.ErrorCode.RC_CONN_PROTO_VERSION_ERROR, funcName: "getRemoteHistoryMessages" }; if (count > 20) { RongIMClient.logger(log); callback.onError(RongIMLib.ErrorCode.RC_CONN_PROTO_VERSION_ERROR); return; } if (conversationType.valueOf() < 0) { RongIMClient.logger(log); callback.onError(RongIMLib.ErrorCode.RC_CONN_PROTO_VERSION_ERROR); return; } RongIMClient._dataAccessProvider.getRemoteHistoryMessages(conversationType, targetId, timestamp, count, RongIMClient.logCallback(callback, funcName), config); }; RongIMClient.prototype.clearHistoryMessages = function (params, callback) { RongIMClient._dataAccessProvider.clearHistoryMessages(params, callback); }; RongIMClient.prototype.clearRemoteHistoryMessages = function (params, callback) { RongIMClient._dataAccessProvider.clearRemoteHistoryMessages(params, RongIMClient.logCallback(callback, "clearRemoteHistoryMessages")); }; RongIMClient.prototype.deleteRemoteMessages = function (conversationType, targetId, messages, callback) { RongIMClient._dataAccessProvider.deleteRemoteMessages(conversationType, targetId, messages, RongIMClient.logCallback(callback, "deleteRemoteMessages")); }; /** * [hasRemoteUnreadMessages 是否有未接收的消息,jsonp方法] * @param {string} appkey [appkey] * @param {string} token [token] * @param {ConnectCallback} callback [返回值,参数回调] */ RongIMClient.prototype.hasRemoteUnreadMessages = function (token, callback) { RongIMClient._dataAccessProvider.hasRemoteUnreadMessages(token, RongIMClient.logCallback(callback, "hasRemoteUnreadMessages")); }; RongIMClient.prototype.getTotalUnreadCount = function (callback, conversationTypes) { return RongIMClient._dataAccessProvider.getTotalUnreadCount({ onSuccess: function (count) { setTimeout(function () { callback.onSuccess(count); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "getTotalUnreadCount" }); callback.onError(errorCode); }); } }, conversationTypes); }; /** * [getConversationUnreadCount 指定多种会话类型获取未读消息数] * @param {ResultCallback} callback [返回值,参数回调。] * @param {ConversationType[]} ...conversationTypes [会话类型。] */ RongIMClient.prototype.getConversationUnreadCount = function (conversationTypes, callback) { RongIMClient._dataAccessProvider.getConversationUnreadCount(conversationTypes, { onSuccess: function (count) { setTimeout(function () { callback.onSuccess(count); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "getConversationUnreadCount" }); callback.onError(errorCode); }); } }); }; /** * [getUnreadCount 指定用户、会话类型的未读消息总数。] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [用户Id] */ RongIMClient.prototype.getUnreadCount = function (conversationType, targetId, callback) { RongIMClient._dataAccessProvider.getUnreadCount(conversationType, targetId, { onSuccess: function (count) { setTimeout(function () { callback.onSuccess(count); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "getUnreadCount" }); callback.onError(errorCode); }); } }); }; RongIMClient.prototype.setUnreadCount = function (conversationType, targetId, count) { RongIMLib.CheckParam.getInstance().check(["number", "string", "number"], "setUnreadCount", false, arguments); RongIMClient._dataAccessProvider.setUnreadCount(conversationType, targetId, count); }; RongIMClient.prototype.clearUnreadCountByTimestamp = function (conversationType, targetId, timestamp, callback) { RongIMClient._dataAccessProvider.clearUnreadCountByTimestamp(conversationType, targetId, timestamp, RongIMClient.logCallback(callback, "clearUnreadCountByTimestamp")); }; /** * 清楚会话未读消息数 * @param {ConversationType} conversationType 会话类型 * @param {string} targetId 目标Id * @param {ResultCallback} callback 返回值,函数回调 */ RongIMClient.prototype.clearUnreadCount = function (conversationType, targetId, callback) { RongIMClient._dataAccessProvider.clearUnreadCount(conversationType, targetId, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "clearUnreadCount" }); callback.onError(errorCode); }); } }); }; RongIMClient.prototype.clearTotalUnreadCount = function (callback) { RongIMClient._dataAccessProvider.clearTotalUnreadCount({ onSuccess: function (bool) { callback.onSuccess(bool); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: 'clearTotalUnreadCount' }); callback.onError(errorCode); }); } }); }; RongIMClient.prototype.clearLocalStorage = function (callback) { RongIMClient._storageProvider.clearItem(); callback(); }; RongIMClient.prototype.setMessageExtra = function (messageId, value, callback) { RongIMClient._dataAccessProvider.setMessageExtra(messageId, value, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "setMessageExtra" }); callback.onError(errorCode); }); } }); }; RongIMClient.prototype.setMessageReceivedStatus = function (messageUId, receivedStatus, callback) { RongIMClient._dataAccessProvider.setMessageReceivedStatus(messageUId, receivedStatus, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "setMessageReceivedStatus" }); callback.onError(errorCode); }); } }); }; RongIMClient.prototype.setMessageStatus = function (conersationType, targetId, timestamp, status, callback) { RongIMClient._dataAccessProvider.setMessageStatus(conersationType, targetId, timestamp, status, RongIMClient.logCallback(callback, "setMessageStatus")); }; RongIMClient.prototype.setMessageSentStatus = function (messageId, sentStatus, callback) { RongIMClient._dataAccessProvider.setMessageSentStatus(messageId, sentStatus, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "setMessageSentStatus" }); callback.onError(errorCode); }); } }); }; // #endregion Message // #region TextMessage Draft /** * clearTextMessageDraft 清除指定会话和消息类型的草稿。 * @param {ConversationType} conversationType 会话类型 * @param {string} targetId 目标Id */ RongIMClient.prototype.clearTextMessageDraft = function (conversationType, targetId) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "clearTextMessageDraft", false, arguments); var key = "darf_" + conversationType + "_" + targetId; delete RongIMClient._memoryStore[key]; return true; }; /** * [getTextMessageDraft 获取指定消息和会话的草稿。] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [目标Id] */ RongIMClient.prototype.getTextMessageDraft = function (conversationType, targetId) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "getTextMessageDraft", false, arguments); if (targetId == "" || conversationType < 0) { throw new Error("params error : " + RongIMLib.ErrorCode.DRAF_GET_ERROR); } var key = "darf_" + conversationType + "_" + targetId; return RongIMClient._memoryStore[key]; }; /** * [saveTextMessageDraft description] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [目标Id] * @param {string} value [草稿值] */ RongIMClient.prototype.saveTextMessageDraft = function (conversationType, targetId, value) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "string", "object"], "saveTextMessageDraft", false, arguments); var key = "darf_" + conversationType + "_" + targetId; RongIMClient._memoryStore[key] = value; return true; }; // #endregion TextMessage Draft // #region Conversation RongIMClient.prototype.searchConversationByContent = function (keyword, callback, conversationTypes) { RongIMClient._dataAccessProvider.searchConversationByContent(keyword, RongIMClient.logCallback(callback, "searchConversationByContent"), conversationTypes); }; RongIMClient.prototype.searchMessageByContent = function (conversationType, targetId, keyword, timestamp, count, total, callback) { RongIMClient._dataAccessProvider.searchMessageByContent(conversationType, targetId, keyword, timestamp, count, total, RongIMClient.logCallback(callback, "searchMessageByContent")); }; RongIMClient.prototype.clearCache = function () { RongIMClient._dataAccessProvider.clearCache(); }; RongIMClient.prototype.clearConversations = function (callback) { var conversationTypes = []; for (var _i = 1; _i < arguments.length; _i++) { conversationTypes[_i - 1] = arguments[_i]; } if (conversationTypes.length == 0) { conversationTypes = [RongIMLib.ConversationType.CHATROOM, RongIMLib.ConversationType.CUSTOMER_SERVICE, RongIMLib.ConversationType.DISCUSSION, RongIMLib.ConversationType.GROUP, RongIMLib.ConversationType.PRIVATE, RongIMLib.ConversationType.SYSTEM, RongIMLib.ConversationType.PUBLIC_SERVICE, RongIMLib.ConversationType.APP_PUBLIC_SERVICE]; } RongIMClient._dataAccessProvider.clearConversations(conversationTypes, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "clearConversations" }); callback.onError(errorCode); }); } }); }; /** * [getConversation 获取指定会话,此方法需在getConversationList之后执行] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [目标Id] * @param {ResultCallback} callback [返回值,函数回调] */ RongIMClient.prototype.getConversation = function (conversationType, targetId, callback) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "getConversation", false, arguments); RongIMClient._dataAccessProvider.getConversation(conversationType, targetId, { onSuccess: function (conver) { setTimeout(function () { callback.onSuccess(conver); }); }, onError: function (error) { setTimeout(function () { RongIMClient.logger({ code: error, funcName: "getConversation" }); callback.onError(error); }); } }); }; /** * [pottingConversation 组装会话列表] * @param {any} tempConver [临时会话] * conver_conversationType_targetId_no. * msg_conversationType_targetId_no. */ RongIMClient.prototype.pottingConversation = function (tempConver) { var self = this, isUseReplace = false; RongIMClient._dataAccessProvider.getConversation(tempConver.type, tempConver.userId, { onSuccess: function (conver) { if (!conver) { conver = new RongIMLib.Conversation(); } else { isUseReplace = true; } conver.conversationType = tempConver.type; conver.targetId = tempConver.userId; if (tempConver.msg) { conver.latestMessage = RongIMLib.MessageUtil.messageParser(tempConver.msg); conver.latestMessageId = conver.latestMessage.messageId; conver.objectName = conver.latestMessage.objectName; conver.receivedStatus = conver.latestMessage.receivedStatus; conver.receivedTime = conver.latestMessage.receiveTime; conver.sentStatus = conver.latestMessage.sentStatus; conver.sentTime = conver.latestMessage.sentTime; } var mentioneds = RongIMClient._storageProvider.getItem("mentioneds_" + RongIMLib.Bridge._client.userId + '_' + conver.conversationType + '_' + conver.targetId); if (mentioneds) { var info = JSON.parse(mentioneds); conver.mentionedMsg = info[tempConver.type + "_" + tempConver.userId]; } if (!isUseReplace) { if (RongIMLib.RongUtil.supportLocalStorage()) { // var count = RongIMClient._storageProvider.getItem("cu" + Bridge._client.userId + tempConver.type + tempConver.userId); conver.unreadMessageCount = RongIMLib.UnreadCountHandler.get(tempConver.type, tempConver.userId); } else { conver.unreadMessageCount = 0; } } if (conver.conversationType == RongIMLib.ConversationType.DISCUSSION) { self.getDiscussion(tempConver.userId, { onSuccess: function (info) { conver.conversationTitle = info.name; }, onError: function (error) { } }); } var status = RongIMClient._dataAccessProvider.conversationStatusManager.get(tempConver.type, tempConver.userId); conver.notificationStatus = status.notificationStatus; conver.isTop = status.isTop; RongIMClient._dataAccessProvider.addConversation(conver, { onSuccess: function (data) { } }); }, onError: function (error) { } }); }; RongIMClient.prototype.addConversation = function (conversation, callback) { RongIMClient._dataAccessProvider.addConversation(conversation, callback); }; RongIMClient.prototype.sortConversationList = function (conversationList) { var convers = []; for (var i = 0, len = conversationList.length; i < len; i++) { if (!conversationList[i]) { continue; } if (conversationList[i].isTop) { convers.push(conversationList[i]); conversationList.splice(i, 1); continue; } for (var j = 0; j < len - i - 1; j++) { if (conversationList[j].sentTime < conversationList[j + 1].sentTime) { var swap = conversationList[j]; conversationList[j] = conversationList[j + 1]; conversationList[j + 1] = swap; } } } return RongIMClient._memoryStore.conversationList = convers.concat(conversationList); }; RongIMClient.prototype.getConversationList = function (callback, conversationTypes, count, isGetHiddenConvers) { RongIMLib.CheckParam.getInstance().check(["object", "null|undefined|array|object|global", "number|undefined|null|object|global", "boolean|undefined|null|object|global"], "getConversationList", false, arguments); var me = this; RongIMClient._dataAccessProvider.getConversationList({ onSuccess: function (data) { if (conversationTypes || RongIMClient._dataAccessProvider) { setTimeout(function () { callback.onSuccess(data); }); } else { setTimeout(function () { callback.onSuccess(RongIMClient._memoryStore.conversationList); }); } }, onError: function (error) { setTimeout(function () { RongIMClient.logger({ code: error, funcName: "getConversationList" }); callback.onError(error); }); } }, conversationTypes, count, isGetHiddenConvers); }; RongIMClient.prototype.getRemoteConversationList = function (callback, conversationTypes, count, isGetHiddenConvers) { RongIMLib.CheckParam.getInstance().check(["object", "null|array|object|global", "number|undefined|null|object|global", "boolean|undefined|null|object|global"], "getRemoteConversationList", false, arguments); RongIMClient._dataAccessProvider.getRemoteConversationList(RongIMClient.logCallback(callback, "getRemoteConversationList"), conversationTypes, count, isGetHiddenConvers); }; RongIMClient.prototype.updateConversation = function (conversation) { return RongIMClient._dataAccessProvider.updateConversation(conversation); }; /** * [createConversation 创建会话。] * @param {number} conversationType [会话类型] * @param {string} targetId [目标Id] * @param {string} converTitle [会话标题] * @param {boolean} islocal [是否同步到服务器,ture:同步,false:不同步] */ RongIMClient.prototype.createConversation = function (conversationType, targetId, converTitle) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "string"], "createConversation", false, arguments); var conver = new RongIMLib.Conversation(); // var unreadContent: string = RongIMClient._storageProvider.getItem("cu" + Bridge._client.userId + conversationType + targetId); // var unreadCount = Number(unreadContent) || 0; conver.targetId = targetId; conver.conversationType = conversationType; conver.conversationTitle = converTitle; conver.latestMessage = {}; conver.unreadMessageCount = 0; return conver; }; //TODO 删除本地和服务器、删除本地和服务器分开 RongIMClient.prototype.removeConversation = function (conversationType, targetId, callback) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "removeConversation", false, arguments); RongIMClient._dataAccessProvider.removeConversation(conversationType, targetId, RongIMClient.logCallback(callback, "removeConversation")); }; RongIMClient.prototype.setConversationHidden = function (conversationType, targetId, isHidden) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "boolean"], "setConversationHidden", false, arguments); RongIMClient._dataAccessProvider.setConversationHidden(conversationType, targetId, isHidden); }; RongIMClient.prototype.setConversationToTop = function (conversationType, targetId, isTop, callback) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "boolean", "object"], "setConversationToTop", false, arguments); RongIMClient._dataAccessProvider.setConversationToTop(conversationType, targetId, isTop, { onSuccess: function (bool) { setTimeout(function () { callback.onSuccess(bool); }); }, onError: function (errorCode) { setTimeout(function () { RongIMClient.logger({ code: errorCode, funcName: "setConversationToTop" }); callback.onError(errorCode); }); } }); }; // #endregion Conversation // #region Notifications /** * [getConversationNotificationStatus 获取指定用户和会话类型免提醒。] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [目标Id] * @param {ResultCallback} callback [返回值,函数回调] */ RongIMClient.prototype.getConversationNotificationStatus = function (conversationType, targetId, callback) { var params = { conversationType: conversationType, targetId: targetId }; RongIMClient._dataAccessProvider.getConversationNotificationStatus(params, RongIMClient.logCallback(callback, "getConversationNotificationStatus")); }; /** * [setConversationNotificationStatus 设置指定用户和会话类型免提醒。] * @param {ConversationType} conversationType [会话类型] * @param {string} targetId [目标Id] * @param {ResultCallback} callback [返回值,函数回调] */ RongIMClient.prototype.setConversationNotificationStatus = function (conversationType, targetId, notificationStatus, callback) { var params = { conversationType: conversationType, targetId: targetId, status: status }; RongIMClient._dataAccessProvider.setConversationNotificationStatus(params, RongIMClient.logCallback(callback, "setConversationNotificationStatus")); }; /** * [getNotificationQuietHours 获取免提醒消息时间。] * @param {GetNotificationQuietHoursCallback} callback [返回值,函数回调] */ RongIMClient.prototype.getNotificationQuietHours = function (callback) { throw new Error("Not implemented yet"); }; /** * [removeNotificationQuietHours 移除免提醒消息时间。] * @param {GetNotificationQuietHoursCallback} callback [返回值,函数回调] */ RongIMClient.prototype.removeNotificationQuietHours = function (callback) { throw new Error("Not implemented yet"); }; /** * [setNotificationQuietHours 设置免提醒消息时间。] * @param {GetNotificationQuietHoursCallback} callback [返回值,函数回调] */ RongIMClient.prototype.setNotificationQuietHours = function (startTime, spanMinutes, callback) { throw new Error("Not implemented yet"); }; // #endregion Notifications // #region Discussion /** * [addMemberToDiscussion 加入讨论组] * @param {string} discussionId [讨论组Id] * @param {string[]} userIdList [讨论中成员] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.addMemberToDiscussion = function (discussionId, userIdList, callback) { RongIMLib.CheckParam.getInstance().check(["string", "array", "object"], "addMemberToDiscussion", false, arguments); RongIMClient._dataAccessProvider.addMemberToDiscussion(discussionId, userIdList, RongIMClient.logCallback(callback, "addMemberToDiscussion")); }; /** * [createDiscussion 创建讨论组] * @param {string} name [讨论组名称] * @param {string[]} userIdList [讨论组成员] * @param {CreateDiscussionCallback} callback [返回值,函数回调] */ RongIMClient.prototype.createDiscussion = function (name, userIdList, callback) { RongIMLib.CheckParam.getInstance().check(["string", "array", "object"], "createDiscussion", false, arguments); RongIMClient._dataAccessProvider.createDiscussion(name, userIdList, callback); }; /** * [getDiscussion 获取讨论组信息] * @param {string} discussionId [讨论组Id] * @param {ResultCallback} callback [返回值,函数回调] */ RongIMClient.prototype.getDiscussion = function (discussionId, callback) { RongIMLib.CheckParam.getInstance().check(["string", "object"], "getDiscussion", false, arguments); RongIMClient._dataAccessProvider.getDiscussion(discussionId, RongIMClient.logCallback(callback, "getDiscussion")); }; /** * [quitDiscussion 退出讨论组] * @param {string} discussionId [讨论组Id] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.quitDiscussion = function (discussionId, callback) { RongIMLib.CheckParam.getInstance().check(["string", "object"], "quitDiscussion", false, arguments); RongIMClient._dataAccessProvider.quitDiscussion(discussionId, RongIMClient.logCallback(callback, "quitDiscussion")); }; /** * [removeMemberFromDiscussion 将指定成员移除讨论租] * @param {string} discussionId [讨论组Id] * @param {string} userId [被移除的用户Id] * @param {OperationCallback} callback [返回值,参数回调] */ RongIMClient.prototype.removeMemberFromDiscussion = function (discussionId, userId, callback) { RongIMLib.CheckParam.getInstance().check(["string", "string", "object"], "removeMemberFromDiscussion", false, arguments); RongIMClient._dataAccessProvider.removeMemberFromDiscussion(discussionId, userId, RongIMClient.logCallback(callback, "removeMemberFromDiscussion")); }; /** * [setDiscussionInviteStatus 设置讨论组邀请状态] * @param {string} discussionId [讨论组Id] * @param {DiscussionInviteStatus} status [邀请状态] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.setDiscussionInviteStatus = function (discussionId, status, callback) { RongIMLib.CheckParam.getInstance().check(["string", "number", "object"], "setDiscussionInviteStatus", false, arguments); RongIMClient._dataAccessProvider.setDiscussionInviteStatus(discussionId, status, RongIMClient.logCallback(callback, "setDiscussionInviteStatus")); }; /** * [setDiscussionName 设置讨论组名称] * @param {string} discussionId [讨论组Id] * @param {string} name [讨论组名称] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.setDiscussionName = function (discussionId, name, callback) { RongIMLib.CheckParam.getInstance().check(["string", "string", "object"], "setDiscussionName", false, arguments); RongIMClient._dataAccessProvider.setDiscussionName(discussionId, name, RongIMClient.logCallback(callback, "setDiscussionName")); }; // #endregion Discussion // #region ChatRoom /** * [加入聊天室。] * @param {string} chatroomId [聊天室Id] * @param {number} messageCount [拉取消息数量,-1为不拉去消息] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.joinChatRoom = function (chatroomId, messageCount, callback) { RongIMLib.CheckParam.getInstance().check(["string", "number", "object"], "joinChatRoom", false, arguments); if (chatroomId == "") { setTimeout(function () { var errorCode = RongIMLib.ErrorCode.CHATROOM_ID_ISNULL; RongIMClient.logger({ code: errorCode, funcName: "joinChatRoom" }); callback.onError(RongIMLib.ErrorCode.CHATROOM_ID_ISNULL); }); return; } RongIMClient._dataAccessProvider.joinChatRoom(chatroomId, messageCount, RongIMClient.logCallback(callback, "joinChatRoom")); }; RongIMClient.prototype.setDeviceInfo = function (device) { RongIMClient._dataAccessProvider.setDeviceInfo(device); }; RongIMClient.prototype.setChatroomHisMessageTimestamp = function (chatRoomId, timestamp) { RongIMLib.CheckParam.getInstance().check(["string", "number"], "setChatroomHisMessageTimestamp", false, arguments); RongIMClient._dataAccessProvider.setChatroomHisMessageTimestamp(chatRoomId, timestamp); }; RongIMClient.prototype.getChatRoomHistoryMessages = function (chatRoomId, count, order, callback) { RongIMLib.CheckParam.getInstance().check(["string", "number", "number", "object"], "getChatRoomHistoryMessages", false, arguments); RongIMClient._dataAccessProvider.getChatRoomHistoryMessages(chatRoomId, count, order, RongIMClient.logCallback(callback, "getChatRoomHistoryMessages")); }; RongIMClient.prototype.getChatRoomInfo = function (chatRoomId, count, order, callback) { RongIMLib.CheckParam.getInstance().check(["string", "number", "number", "object"], "getChatRoomInfo", false, arguments); RongIMClient._dataAccessProvider.getChatRoomInfo(chatRoomId, count, order, RongIMClient.logCallback(callback, "getChatRoomInfo")); }; /** * [退出聊天室] * @param {string} chatroomId [聊天室Id] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.quitChatRoom = function (chatroomId, callback) { RongIMLib.CheckParam.getInstance().check(["string", "object"], "quitChatRoom", false, arguments); RongIMClient._dataAccessProvider.quitChatRoom(chatroomId, RongIMClient.logCallback(callback, "quitChatRoom")); }; RongIMClient.prototype.setChatroomEntry = function (chatroomId, chatroomEntry, callback) { RongIMLib.CheckParam.getInstance().check(['string', 'object', 'object'], 'setChatroomEntry', false, arguments); RongIMClient._dataAccessProvider.setChatroomEntry(chatroomId, chatroomEntry, RongIMClient.logCallback(callback, "setChatroomEntry")); }; RongIMClient.prototype.forceSetChatroomEntry = function (chatroomId, chatroomEntry, callback) { RongIMLib.CheckParam.getInstance().check(['string', 'object', 'object'], 'setChatroomEntry', false, arguments); RongIMClient._dataAccessProvider.forceSetChatroomEntry(chatroomId, chatroomEntry, RongIMClient.logCallback(callback, "setChatroomEntry")); }; RongIMClient.prototype.getChatroomEntry = function (chatroomId, key, callback) { RongIMLib.CheckParam.getInstance().check(['string', 'string', 'object'], 'getChatroomEntry', false, arguments); RongIMClient._dataAccessProvider.getChatroomEntry(chatroomId, key, RongIMClient.logCallback(callback, "setChatroomEntry")); }; RongIMClient.prototype.getAllChatroomEntries = function (chatroomId, callback) { RongIMLib.CheckParam.getInstance().check(['string', 'object'], 'getAllChatroomEntries', false, arguments); RongIMClient._dataAccessProvider.getAllChatroomEntries(chatroomId, RongIMClient.logCallback(callback, "setChatroomEntry")); }; RongIMClient.prototype.removeChatroomEntry = function (chatroomId, chatroomEntry, callback) { RongIMLib.CheckParam.getInstance().check(['string', 'object', 'object'], 'removeChatroomEntry', false, arguments); RongIMClient._dataAccessProvider.removeChatroomEntry(chatroomId, chatroomEntry, RongIMClient.logCallback(callback, "setChatroomEntry")); }; RongIMClient.prototype.forceRemoveChatroomEntry = function (chatroomId, chatroomEntry, callback) { RongIMLib.CheckParam.getInstance().check(['string', 'object', 'object'], 'removeChatroomEntry', false, arguments); RongIMClient._dataAccessProvider.forceRemoveChatroomEntry(chatroomId, chatroomEntry, RongIMClient.logCallback(callback, "setChatroomEntry")); }; // #endregion ChatRoom // #region Public Service RongIMClient.prototype.getRemotePublicServiceList = function (callback, pullMessageTime) { RongIMClient._dataAccessProvider.getRemotePublicServiceList(RongIMClient.logCallback(callback, "getRemotePublicServiceList"), pullMessageTime); }; /** * [getPublicServiceList ]获取本地的公共账号列表 * @param {ResultCallback} callback [返回值,参数回调] */ RongIMClient.prototype.getPublicServiceList = function (callback) { if (RongIMClient._memoryStore.depend.openMp) { RongIMLib.CheckParam.getInstance().check(["object"], "getPublicServiceList", false, arguments); this.getRemotePublicServiceList(RongIMClient.logCallback(callback, "getPublicServiceList")); } }; /** * [getPublicServiceProfile ] 获取某公共服务信息。 * @param {PublicServiceType} publicServiceType [公众服务类型。] * @param {string} publicServiceId [公共服务 Id。] * @param {ResultCallback} callback [公共账号信息回调。] */ RongIMClient.prototype.getPublicServiceProfile = function (publicServiceType, publicServiceId, callback) { if (RongIMClient._memoryStore.depend.openMp) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "getPublicServiceProfile", false, arguments); RongIMClient._dataAccessProvider.getPublicServiceProfile(publicServiceType, publicServiceId, RongIMClient.logCallback(callback, "getPublicServiceProfile")); } }; /** * [pottingPublicSearchType ] 公众好查询类型 * @param {number} bussinessType [ 0-all 1-mp 2-mc] * @param {number} searchType [0-exact 1-fuzzy] */ RongIMClient.prototype.pottingPublicSearchType = function (bussinessType, searchType) { if (RongIMClient._memoryStore.depend.openMp) { var bits = 0; if (bussinessType == 0) { bits |= 3; if (searchType == 0) { bits |= 12; } else { bits |= 48; } } else if (bussinessType == 1) { bits |= 1; if (searchType == 0) { bits |= 8; } else { bits |= 32; } } else { bits |= 2; if (bussinessType == 0) { bits |= 4; } else { bits |= 16; } } return bits; } }; /** * [searchPublicService ]按公众服务类型搜索公众服务。 * @param {SearchType} searchType [搜索类型枚举。] * @param {string} keywords [搜索关键字。] * @param {ResultCallback} callback [搜索结果回调。] */ RongIMClient.prototype.searchPublicService = function (searchType, keywords, callback) { if (RongIMClient._memoryStore.depend.openMp) { RongIMLib.CheckParam.getInstance().check(["number", "string", "object"], "searchPublicService", false, arguments); var modules = new RongIMClient.Protobuf.SearchMpInput(); modules.setType(this.pottingPublicSearchType(0, searchType)); modules.setId(keywords); RongIMClient.bridge.queryMsg(29, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, RongIMClient.logCallback(callback, "searchPublicService"), "SearchMpOutput"); } }; /** * [searchPublicServiceByType ]按公众服务类型搜索公众服务。 * @param {PublicServiceType} publicServiceType [公众服务类型。] * @param {SearchType} searchType [搜索类型枚举。] * @param {string} keywords [搜索关键字。] * @param {ResultCallback} callback [搜索结果回调。] */ RongIMClient.prototype.searchPublicServiceByType = function (publicServiceType, searchType, keywords, callback) { if (RongIMClient._memoryStore.depend.openMp) { RongIMLib.CheckParam.getInstance().check(["number", "number", "string", "object"], "searchPublicServiceByType", false, arguments); var type = publicServiceType == RongIMLib.ConversationType.APP_PUBLIC_SERVICE ? 2 : 1; var modules = new RongIMClient.Protobuf.SearchMpInput(); modules.setType(this.pottingPublicSearchType(type, searchType)); modules.setId(keywords); RongIMClient.bridge.queryMsg(29, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, RongIMClient.logCallback(callback, "searchPublicServiceByType"), "SearchMpOutput"); } }; /** * [subscribePublicService ] 订阅公众号。 * @param {PublicServiceType} publicServiceType [公众服务类型。] * @param {string} publicServiceId [公共服务 Id。] * @param {OperationCallback} callback [订阅公众号回调。] */ RongIMClient.prototype.subscribePublicService = function (publicServiceType, publicServiceId, callback) { if (RongIMClient._memoryStore.depend.openMp) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "subscribePublicService", false, arguments); var modules = new RongIMClient.Protobuf.MPFollowInput(), me = this, follow = publicServiceType == RongIMLib.ConversationType.APP_PUBLIC_SERVICE ? "mcFollow" : "mpFollow"; modules.setId(publicServiceId); RongIMClient.bridge.queryMsg(follow, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function () { me.getRemotePublicServiceList({ onSuccess: function () { }, onError: function () { } }); callback.onSuccess(); }, onError: function (code) { var errorCode = code; RongIMClient.logger({ code: errorCode, funcName: "subscribePublicService" }); callback.onError(code); } }, "MPFollowOutput"); } }; /** * [unsubscribePublicService ] 取消订阅公众号。 * @param {PublicServiceType} publicServiceType [公众服务类型。] * @param {string} publicServiceId [公共服务 Id。] * @param {OperationCallback} callback [取消订阅公众号回调。] */ RongIMClient.prototype.unsubscribePublicService = function (publicServiceType, publicServiceId, callback) { if (RongIMClient._memoryStore.depend.openMp) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "object"], "unsubscribePublicService", false, arguments); var modules = new RongIMClient.Protobuf.MPFollowInput(), me = this, follow = publicServiceType == RongIMLib.ConversationType.APP_PUBLIC_SERVICE ? "mcUnFollow" : "mpUnFollow"; modules.setId(publicServiceId); RongIMClient.bridge.queryMsg(follow, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function () { RongIMClient._memoryStore.publicServiceMap.remove(publicServiceType, publicServiceId); callback.onSuccess(); }, onError: function (code) { var errorCode = code; RongIMClient.logger({ code: errorCode, funcName: "unsubscribePublicService" }); callback.onError(code); } }, "MPFollowOutput"); } }; // #endregion Public Service // #region Blacklist /** * [加入黑名单] * @param {string} userId [将被加入黑名单的用户Id] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.addToBlacklist = function (userId, callback) { RongIMLib.CheckParam.getInstance().check(["string|number", "object"], "addToBlacklist", false, arguments); RongIMClient._dataAccessProvider.addToBlacklist(userId, RongIMClient.logCallback(callback, "addToBlacklist")); }; /** * [获取黑名单列表] * @param {GetBlacklistCallback} callback [返回值,函数回调] */ RongIMClient.prototype.getBlacklist = function (callback) { RongIMLib.CheckParam.getInstance().check(["object"], "getBlacklist", false, arguments); RongIMClient._dataAccessProvider.getBlacklist(callback); }; /** * [得到指定人员再黑名单中的状态] * @param {string} userId [description] * @param {ResultCallback} callback [返回值,函数回调] */ //TODO 如果人员不在黑名单中,获取状态会出现异常 RongIMClient.prototype.getBlacklistStatus = function (userId, callback) { RongIMLib.CheckParam.getInstance().check(["string|number", "object"], "getBlacklistStatus", false, arguments); RongIMClient._dataAccessProvider.getBlacklistStatus(userId, RongIMClient.logCallback(callback, "getBlacklistStatus")); }; /** * [将指定用户移除黑名单] * @param {string} userId [将被移除的用户Id] * @param {OperationCallback} callback [返回值,函数回调] */ RongIMClient.prototype.removeFromBlacklist = function (userId, callback) { RongIMLib.CheckParam.getInstance().check(["string|number", "object"], "removeFromBlacklist", false, arguments); RongIMClient._dataAccessProvider.removeFromBlacklist(userId, RongIMClient.logCallback(callback, "removeFromBlacklist")); }; RongIMClient.prototype.getFileToken = function (fileType, callback) { RongIMLib.CheckParam.getInstance().check(["number", "object"], "getQngetFileTokenTkn", false, arguments); RongIMClient._dataAccessProvider.getFileToken(fileType, RongIMClient.logCallback(callback, "getFileToken")); }; RongIMClient.prototype.getFileUrl = function (fileType, fileName, oriName, callback) { RongIMLib.CheckParam.getInstance().check(["number", "string", "string|global|object|null", "object"], "getFileUrl", false, arguments); RongIMClient._dataAccessProvider.getFileUrl(fileType, fileName, oriName, RongIMClient.logCallback(callback, "getFileUrl")); }; ; // #endregion Blacklist // #region Real-time Location Service RongIMClient.prototype.addRealTimeLocationListener = function (conversationType, targetId, listener) { throw new Error("Not implemented yet"); }; RongIMClient.prototype.getRealTimeLocation = function (conversationType, targetId) { throw new Error("Not implemented yet"); }; RongIMClient.prototype.getRealTimeLocationCurrentState = function (conversationType, targetId) { throw new Error("Not implemented yet"); }; RongIMClient.prototype.getRealTimeLocationParticipants = function (conversationType, targetId) { throw new Error("Not implemented yet"); }; RongIMClient.prototype.joinRealTimeLocation = function (conversationType, targetId) { throw new Error("Not implemented yet"); }; RongIMClient.prototype.quitRealTimeLocation = function (conversationType, targetId) { throw new Error("Not implemented yet"); }; RongIMClient.prototype.startRealTimeLocation = function (conversationType, targetId) { throw new Error("Not implemented yet"); }; RongIMClient.prototype.updateRealTimeLocationStatus = function (conversationType, targetId, latitude, longitude) { throw new Error("Not implemented yet"); }; // #endregion Real-time Location Service // # startVoIP RongIMClient.prototype.startCall = function (converType, targetId, userIds, mediaType, extra, callback) { RongIMLib.CheckParam.getInstance().check(["number", "string|number", "array", "number", "string", "object"], "startCall", false, arguments); if (RongIMClient._memoryStore.voipStategy) { RongIMClient._voipProvider.startCall(converType, targetId, userIds, mediaType, extra, RongIMClient.logCallback(callback, "startCall")); } else { var errorCode = RongIMLib.ErrorCode.VOIP_NOT_AVALIABLE; RongIMClient.logger({ code: errorCode, funcName: "startCall" }); callback.onError(RongIMLib.ErrorCode.VOIP_NOT_AVALIABLE); } }; RongIMClient.prototype.joinCall = function (mediaType, callback) { RongIMLib.CheckParam.getInstance().check(['number', 'object'], "joinCall", false, arguments); if (RongIMClient._memoryStore.voipStategy) { RongIMClient._voipProvider.joinCall(mediaType, RongIMClient.logCallback(callback, "joinCall")); } else { var errorCode = RongIMLib.ErrorCode.VOIP_NOT_AVALIABLE; RongIMClient.logger({ code: errorCode, funcName: "joinCall" }); callback.onError(RongIMLib.ErrorCode.VOIP_NOT_AVALIABLE); } }; RongIMClient.prototype.hungupCall = function (converType, targetId, reason) { RongIMLib.CheckParam.getInstance().check(["number", "string", "number"], "hungupCall", false, arguments); if (RongIMClient._memoryStore.voipStategy) { RongIMClient._voipProvider.hungupCall(converType, targetId, reason); } }; RongIMClient.prototype.changeMediaType = function (converType, targetId, mediaType, callback) { RongIMLib.CheckParam.getInstance().check(["number", "string", "number", "object"], "changeMediaType", false, arguments); if (RongIMClient._memoryStore.voipStategy) { RongIMClient._voipProvider.changeMediaType(converType, targetId, mediaType, RongIMClient.logCallback(callback, "changeMediaType")); } else { var errorCode = RongIMLib.ErrorCode.VOIP_NOT_AVALIABLE; RongIMClient.logger({ code: errorCode, funcName: "changeMediaType" }); callback.onError(RongIMLib.ErrorCode.VOIP_NOT_AVALIABLE); } }; // # endVoIP RongIMClient.prototype.getUnreadMentionedMessages = function (conversationType, targetId) { return RongIMClient._dataAccessProvider.getUnreadMentionedMessages(conversationType, targetId); }; RongIMClient.prototype.clearListeners = function () { RongIMClient._dataAccessProvider.clearListeners(); }; // UserStatus start RongIMClient.prototype.getUserStatus = function (userId, callback) { RongIMClient._dataAccessProvider.getUserStatus(userId, RongIMClient.logCallback(callback, "getUserStatus")); }; RongIMClient.prototype.setUserStatus = function (status, callback) { RongIMClient._dataAccessProvider.setUserStatus(status, RongIMClient.logCallback(callback, "setUserStatus")); }; RongIMClient.prototype.setUserStatusListener = function (params, callback) { var userIds = params.userIds; var multiple = params.multiple; RongIMClient.userStatusObserver.watch({ key: userIds, func: callback, multiple: multiple }); RongIMClient._dataAccessProvider.setUserStatusListener(params, callback); }; // UserStaus end // RTC start RongIMClient.messageWatch = function (watcher) { RongIMClient.RTCListener = watcher; }; RongIMClient.messageSignalWatch = function (watcher) { RongIMClient.RTCSignalLisener = watcher; }; /* var data = { key1: 123, key2: 345 }; */ RongIMClient.prototype.getRTCUserInfoList = function (room, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object"], "getRTCUserInfoList", false, arguments); RongIMClient._dataAccessProvider.getRTCUserInfoList(room, callback); }; RongIMClient.prototype.getRTCUserList = function (room, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object"], "getRTCUserList", false, arguments); RongIMClient._dataAccessProvider.getRTCUserList(room, callback); }; RongIMClient.prototype.setRTCUserInfo = function (room, info, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object", "object"], "setRTCUserInfo", false, arguments); RongIMClient._dataAccessProvider.setRTCUserInfo(room, info, callback); }; RongIMClient.prototype.removeRTCUserInfo = function (room, info, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object", "object"], "removeRTCUserInfo", false, arguments); RongIMClient._dataAccessProvider.removeRTCUserInfo(room, info, callback); }; RongIMClient.prototype.getRTCRoomInfo = function (room, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object"], "getRTCRoomInfo", false, arguments); RongIMClient._dataAccessProvider.getRTCRoomInfo(room, callback); }; RongIMClient.prototype.setRTCRoomInfo = function (room, info, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object", "object"], "setRTCRoomInfo", false, arguments); RongIMClient._dataAccessProvider.setRTCRoomInfo(room, info, callback); }; RongIMClient.prototype.removeRTCRoomInfo = function (room, info, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object", "object"], "removeRTCRoomInfo", false, arguments); RongIMClient._dataAccessProvider.removeRTCRoomInfo(room, info, callback); }; RongIMClient.prototype.joinRTCRoom = function (room, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object"], "joinRTCRoom", false, arguments); if (RongIMClient.isJoinedRTCRoom) { return callback.onSuccess(RongIMClient.roomInfo); } RongIMClient._dataAccessProvider.joinRTCRoom(room, { onSuccess: function (result) { RongIMClient.roomInfo = result; RongIMClient.isJoinedRTCRoom = true; callback.onSuccess(result); }, onError: callback.onError }); }; RongIMClient.prototype.quitRTCRoom = function (room, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object"], "quitRTCRoom", false, arguments); RongIMClient.isJoinedRTCRoom = false; RongIMClient._dataAccessProvider.quitRTCRoom(room, { onSuccess: function () { RongIMClient.roomInfo = { users: {}, token: '' }; callback.onSuccess(true); }, onError: callback.onError }); }; RongIMClient.prototype.RTCPing = function (room, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object"], "RTCPing", false, arguments); RongIMClient._dataAccessProvider.RTCPing(room, callback); }; RongIMClient.prototype.setRTCUserData = function (roomId, key, value, isInner, callback, message) { RongIMLib.CheckParam.getInstance().check(["string", "string", "string", "boolean", "object", "global|object|null|undefined"], "setRTCUserData", false, arguments); RongIMClient._dataAccessProvider.setRTCUserData(roomId, key, value, isInner, callback, message); }; RongIMClient.prototype.getRTCUserData = function (roomId, keys, isInner, callback) { RongIMLib.CheckParam.getInstance().check(["string", "array", "boolean", "object", "global|object|null"], "getRTCUserData", false, arguments); RongIMClient._dataAccessProvider.getRTCUserData(roomId, keys, isInner, callback); }; RongIMClient.prototype.removeRTCUserData = function (roomId, keys, isInner, callback, message) { RongIMLib.CheckParam.getInstance().check(["string", "array", "boolean", "object", "global|object|null|undefined"], "removeRTCUserData", false, arguments); RongIMClient._dataAccessProvider.removeRTCUserData(roomId, keys, isInner, callback, message); }; RongIMClient.prototype.setRTCRoomData = function (roomId, key, value, isInner, callback, message) { RongIMLib.CheckParam.getInstance().check(["string", "string", "string", "boolean", "object", "global|object|null|undefined"], "setRTCRoomData", false, arguments); RongIMClient._dataAccessProvider.setRTCRoomData(roomId, key, value, isInner, callback, message); }; RongIMClient.prototype.getRTCRoomData = function (roomId, keys, isInner, callback) { RongIMLib.CheckParam.getInstance().check(["string", "array", "boolean", "object"], "getRTCRoomData", false, arguments); RongIMClient._dataAccessProvider.getRTCRoomData(roomId, keys, isInner, callback); }; RongIMClient.prototype.removeRTCRoomData = function (roomId, keys, isInner, callback, message) { RongIMLib.CheckParam.getInstance().check(["string", "array", "boolean", "object", "global|object|null|undefined"], "removeRTCRoomData", false, arguments); RongIMClient._dataAccessProvider.removeRTCRoomData(roomId, keys, isInner, callback, message); }; RongIMClient.prototype.setRTCOutData = function (roomId, data, type, callback, message) { RongIMClient._dataAccessProvider.setRTCOutData(roomId, data, type, callback, message); }; // 信令 SDK 新增 RongIMClient.prototype.getRTCOutData = function (roomId, userIds, callback) { RongIMClient._dataAccessProvider.getRTCOutData(roomId, userIds, callback); }; RongIMClient.prototype.getNavi = function () { return RongIMClient._dataAccessProvider.getNavi(); }; RongIMClient.prototype.getRTCToken = function (room, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object"], "getRTCToken", false, arguments); return RongIMClient._dataAccessProvider.getRTCToken(room, callback); }; RongIMClient.prototype.setRTCState = function (room, content, callback) { RongIMLib.CheckParam.getInstance().check(["object", "object", "object"], "setRTCState", false, arguments); return RongIMClient._dataAccessProvider.setRTCState(room, content, callback); }; RongIMClient.prototype.getAppInfo = function () { var appKey = RongIMClient._memoryStore.appKey; return { appKey: appKey }; }; RongIMClient.prototype.getSDKInfo = function () { return { version: RongIMClient.sdkver }; }; RongIMClient.HttpProtocol = { http: 'http://', https: 'https://' }; RongIMClient.WsProtocol = { ws: 'ws://', wss: 'wss://' }; RongIMClient.RTCListener = function () { }; RongIMClient.RTCInnerListener = function () { }; RongIMClient.RTCSignalLisener = function () { }; RongIMClient.MaxMessageContentBytes = 131072; // 128kb RongIMClient.NavMarkInToken = '@'; RongIMClient.NavSeparatorInToken = ';'; RongIMClient.NavExpiredTime = 7200000; // 2 小时 RongIMClient.currentServer = ''; RongIMClient.LogFactory = {}; RongIMClient.MessageType = {}; RongIMClient.RegisterMessage = {}; RongIMClient._memoryStore = { isPullFinished: false, syncMsgQueue: [] }; RongIMClient.isNotPullMsg = false; RongIMClient.userStatusObserver = null; RongIMClient.sdkver = '2.5.7'; RongIMClient.otherDeviceLoginCount = 0; RongIMClient.serverStore = { index: 0 }; RongIMClient.isFirstConnect = true; RongIMClient.roomInfo = { users: {}, token: '' }; RongIMClient.invalidWsUrls = []; RongIMClient.isJoinedRTCRoom = false; RongIMClient.statusListeners = []; RongIMClient.messageListeners = []; RongIMClient.conversationStatusListeners = []; RongIMClient.userStatusListener = null; return RongIMClient; })(); RongIMLib.RongIMClient = RongIMClient; })(RongIMLib || (RongIMLib = {})); //用于连接通道 var RongIMLib; (function (RongIMLib) { (function (Qos) { Qos[Qos["AT_MOST_ONCE"] = 0] = "AT_MOST_ONCE"; Qos[Qos["AT_LEAST_ONCE"] = 1] = "AT_LEAST_ONCE"; Qos[Qos["EXACTLY_ONCE"] = 2] = "EXACTLY_ONCE"; Qos[Qos["DEFAULT"] = 3] = "DEFAULT"; })(RongIMLib.Qos || (RongIMLib.Qos = {})); var Qos = RongIMLib.Qos; (function (Type) { Type[Type["CONNECT"] = 1] = "CONNECT"; Type[Type["CONNACK"] = 2] = "CONNACK"; Type[Type["PUBLISH"] = 3] = "PUBLISH"; Type[Type["PUBACK"] = 4] = "PUBACK"; Type[Type["QUERY"] = 5] = "QUERY"; Type[Type["QUERYACK"] = 6] = "QUERYACK"; Type[Type["QUERYCON"] = 7] = "QUERYCON"; Type[Type["SUBSCRIBE"] = 8] = "SUBSCRIBE"; Type[Type["SUBACK"] = 9] = "SUBACK"; Type[Type["UNSUBSCRIBE"] = 10] = "UNSUBSCRIBE"; Type[Type["UNSUBACK"] = 11] = "UNSUBACK"; Type[Type["PINGREQ"] = 12] = "PINGREQ"; Type[Type["PINGRESP"] = 13] = "PINGRESP"; Type[Type["DISCONNECT"] = 14] = "DISCONNECT"; })(RongIMLib.Type || (RongIMLib.Type = {})); var Type = RongIMLib.Type; RongIMLib.StatusTopic = (function () { var ConversationType = RongIMLib.ConversationType; var topic = {}; topic[ConversationType.PRIVATE] = 'ppMsgS'; topic[ConversationType.GROUP] = 'pgMsgS'; return topic; })(); var _topic = [ "invtDiz", "crDiz", "qnUrl", "userInf", "dizInf", "userInf", "joinGrp", "quitDiz", "exitGrp", "evctDiz", ["", "ppMsgP", "pdMsgP", "pgMsgP", "chatMsg", "pcMsgP", "", "pmcMsgN", "pmpMsgN", "", "", "", "prMsgS", "prMsgP"], "pdOpen", "rename", "uGcmpr", "qnTkn", "destroyChrm", "createChrm", "exitChrm", "queryChrm", "joinChrm", "pGrps", "addBlack", "rmBlack", "getBlack", "blackStat", "addRelation", "qryRelation", "delRelation", "pullMp", "schMp", "qnTkn", "qnUrl", "qryVoipK", "delMsg", "qryCHMsg", "getUserStatus", "setUserStatus", "subUserStatus", "cleanHisMsg" ]; var Channel = (function () { function Channel(cb, self) { this.connectionStatus = -1; var appId = self.appId; var token = encodeURIComponent(self.token); var sdkVer = self.sdkVer; var apiVer = self.apiVer; this.self = self; this.socket = Socket.getInstance().createServer(); var that = this; var storage = RongIMLib.RongIMClient._storageProvider; var servers = storage.getItem('servers'); servers = JSON.parse(servers) || []; servers = RongIMLib.RongUtil.getValidWsUrlList(servers); var depend = RongIMLib.RongIMClient._memoryStore.depend; if (depend.cmpUrl) { servers = [depend.cmpUrl].concat(servers); } var startConnect = function (host) { var tpl = '{host}/websocket?appId={appId}&token={token}&sdkVer={sdkVer}&apiVer={apiVer}'; that.url = RongIMLib.RongUtil.tplEngine(tpl, { host: host, appId: appId, token: token, sdkVer: sdkVer, apiVer: apiVer }); that.socket.connect(that.url, cb); // 临时兼容 Comet 逻辑,Comet 中用到 var userId = storage.getItem('rong_current_user'); RongIMLib.Navigation.Endpoint = { host: host, userId: userId }; }; var connectMap = { get: function () { // 所有链接计算器,超过 15 秒后认为所有 CMP 地址均不可用 var totalTimer = new RongIMLib.Timer({ timeout: 1 * 1000 * 15 }); var timers = []; var xhrs = []; var isFinished = false; var clearHandler = function () { for (var i = 0; i < timers.length; i++) { var timer = timers[i]; clearTimeout(timer); } for (var i = 0; i < xhrs.length; i++) { var xhr = xhrs[i]; xhr.abort(); } timers.length = 0; xhrs.length = 0; }; var request = function (config, callback) { var url = config.url; var time = config.time; if (isFinished) { return; } var timer = setTimeout(function () { var onSuccess = function () { if (isFinished) { return; } clearHandler(); isFinished = true; totalTimer.pause(); callback(url); RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.L_PING_WS_R, level: RongIMLib.LoggerLevel.I, type: RongIMLib.LoggerType.IM, content: { url: url } }); }; var xhr = RongIMLib.MessageUtil.detectCMP({ url: url, success: onSuccess, fail: function (code) { console.log(code); RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.L_PING_WS_R, level: RongIMLib.LoggerLevel.E, type: RongIMLib.LoggerType.IM, content: { url: url, code: code } }); } }); xhrs.push(xhr); }, time); timers.push(timer); }; var snifferCallback = function (url) { var reg = /(http|https):\/\/([^\/]+)/i; var host = url.match(reg)[2]; RongIMLib.RongIMClient.currentServer = host; startConnect(host); }; var snifferTpl = '{protocol}{server}/ping?r={random}'; for (var i = 0; i < servers.length; i++) { var server = servers[i]; if (server) { server = RongIMLib.RongUtil.tplEngine(snifferTpl, { protocol: depend.protocol, server: server, random: RongIMLib.RongUtil.getTimestamp() }); request({ url: server, time: i * 1000 }, snifferCallback); RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.L_PING_WS_T, level: RongIMLib.LoggerLevel.I, type: RongIMLib.LoggerType.IM, content: { url: server } }); } } totalTimer.resume(function () { RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.L_PING_WS_R, level: RongIMLib.LoggerLevel.F, type: RongIMLib.LoggerType.IM, content: { desc: 'all websocket addresses are unavailable', cmp: servers, ConnectionStatus: RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE, available: false } }); RongIMLib.Navigation.clear(); clearHandler(); that.socket.fire("StatusChanged", RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE); }); }, element: function () { var totalTimer = new RongIMLib.Timer({ timeout: 1 * 1000 * 15 }); var timers = []; var elements = []; var isFinished = false; var clearHandler = function () { for (var i = 0; i < timers.length; i++) { var timer = timers[i]; clearTimeout(timer); } for (var i = 0; i < elements.length; i++) { var el = elements[i]; document.body.removeChild(el); } }; var request = function (config, callback) { var url = config.url; var time = config.time; if (isFinished) { return; } var timer = setTimeout(function () { var el = document.createElement('script'); el.src = url; document.body.appendChild(el); el.onerror = function () { if (isFinished) { return; } clearHandler(); isFinished = true; totalTimer.pause(); var url = el.src; callback(url); }; elements.push(el); }, time); timers.push(timer); }; var snifferCallback = function (url) { var reg = /(http|https):\/\/([^\/]+)/i; var host = url.match(reg)[2]; startConnect(host); }; var snifferTpl = '//{server}/{path}'; for (var i = 0; i < servers.length; i++) { var server = RongIMLib.RongUtil.tplEngine(snifferTpl, { server: servers[i], path: i }); request({ url: server, time: i * 1000 }, snifferCallback); } totalTimer.resume(function () { clearHandler(); that.socket.fire("StatusChanged", RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE); }); } }; var isWSPingJSONP = depend.isWSPingJSONP; var connectType = isWSPingJSONP ? 'element' : 'get'; connectMap[connectType](); //注册状态改变观察者 var StatusEvent = Channel._ConnectionStatusListener; var hasEvent = (typeof StatusEvent == "object"); var me = this; me.socket.on("StatusChanged", function (code) { if (RongIMLib.Bridge && RongIMLib.Bridge._client && RongIMLib.Bridge._client.channel && me !== RongIMLib.Bridge._client.channel) { me.connectionStatus = code; return; } if (!hasEvent) { throw new Error("setConnectStatusListener:Parameter format is incorrect"); } var isNetworkUnavailable = (code == RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE); var isWebSocket = !RongIMLib.RongIMClient._memoryStore.depend.isPolling; if (RongIMLib.RongIMClient.isFirstConnect && isNetworkUnavailable && isWebSocket) { code = RongIMLib.ConnectionStatus.WEBSOCKET_UNAVAILABLE; } if (isNetworkUnavailable) { var storage = RongIMLib.RongIMClient._storageProvider; var servers = storage.getItem('servers'); servers = JSON.parse(servers); var currentServer = RongIMLib.RongIMClient.currentServer; if (currentServer) { var index = RongIMLib.RongUtil.indexOf(servers, currentServer); // 如果 currentServer 是 servers 的最后一个,不再替换位置 if (!RongIMLib.RongUtil.isEqual(index, -1)) { var server = servers.splice(index, 1)[0]; servers.push(server); storage.setItem('servers', JSON.stringify(servers)); } } } me.connectionStatus = code; setTimeout(function () { StatusEvent.onChanged(code); var unReportCodes = [RongIMLib.ConnectionStatus.CONNECTING, RongIMLib.ConnectionStatus.REQUEST_NAVI, RongIMLib.ConnectionStatus.RESPONSE_NAVI]; var isReportCode = RongIMLib.RongUtil.indexOf(unReportCodes, code) === -1; if (isReportCode) { RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.L_NETC_S, level: RongIMLib.LoggerLevel.I, type: RongIMLib.LoggerType.IM, content: { ConnectionStatus: code, available: false } }); } }); var isDisconnected = (code == RongIMLib.ConnectionStatus.DISCONNECTED); if (isDisconnected) { self.clearHeartbeat(); } var isOtherDevice = (code == RongIMLib.ConnectionStatus.KICKED_OFFLINE_BY_OTHER_CLIENT); if (isOtherDevice) { // 累计其他设备登陆次数,超过 5 次后,自动销毁内部对象 // 删除位置:ServerDataProivder.prototype.connect RongIMLib.RongIMClient.otherDeviceLoginCount++; } var isConnected = (code == RongIMLib.ConnectionStatus.CONNECTED); if (isConnected) { RongIMLib.RongIMClient.isFirstConnect = false; } var isWebsocketUnAvailable = (code == RongIMLib.ConnectionStatus.WEBSOCKET_UNAVAILABLE); if (isWebsocketUnAvailable) { me.changeConnectType(); RongIMLib.RongIMClient.isFirstConnect = false; RongIMLib.RongIMClient.connect(self.token, RongIMLib.RongIMClient._memoryStore.callback); } }); //注册message观察者 this.socket.on("message", self.handler.handleMessage); //注册断开连接观察者 this.socket.on("disconnect", function (status) { that.socket.fire("StatusChanged", status ? status : 2); }); } Channel.prototype.changeConnectType = function () { RongIMLib.RongIMClient._memoryStore.depend.isPolling = !RongIMLib.RongIMClient._memoryStore.depend.isPolling; new RongIMLib.FeatureDectector(); }; Channel.prototype.writeAndFlush = function (val) { this.socket.send(val); }; Channel.prototype.reconnect = function (callback) { RongIMLib.MessageIdHandler.clearMessageId(); this.socket = this.socket.reconnect(); if (callback) { this.self.reconnectObj = callback; } }; Channel.prototype.disconnect = function (status) { this.socket.disconnect(status); }; return Channel; })(); RongIMLib.Channel = Channel; var Socket = (function () { function Socket() { this.socket = null; this._events = {}; } Socket.getInstance = function () { return new Socket(); }; Socket.prototype.connect = function (url, cb) { if (this.socket) { if (url) { RongIMLib.RongIMClient._storageProvider.setItem("rongSDK", this.checkTransport()); this.on("connect", cb || new Function); } if (url) { this.currentURL = url; } this.socket.createTransport(url); } return this; }; Socket.prototype.createServer = function () { var transport = this.getTransport(this.checkTransport()); if (transport === null) { throw new Error("the channel was not supported"); } return transport; }; Socket.prototype.getTransport = function (transportType) { if (transportType == Socket.XHR_POLLING) { this.socket = new RongIMLib.PollingTransportation(this); } else if (transportType == Socket.WEBSOCKET) { this.socket = new RongIMLib.SocketTransportation(this); } return this; }; Socket.prototype.send = function (data) { if (this.socket) { if (this.checkTransport() == Socket.WEBSOCKET) { this.socket.send(data); } else { this.socket.send(this._encode(data)); } } }; Socket.prototype.onMessage = function (data) { this.fire("message", data); }; Socket.prototype.disconnect = function (status) { this.socket.disconnect(status); this.fire("disconnect", status); return this; }; Socket.prototype.reconnect = function () { if (this.currentURL && RongIMLib.RongIMClient._storageProvider.getItem("rongSDK")) { return this.connect(this.currentURL, null); } else { throw new Error("reconnect:no have URL"); } }; /** * [checkTransport 返回通道类型] */ Socket.prototype.checkTransport = function () { if (RongIMLib.RongIMClient._memoryStore.depend.isPolling) { RongIMLib.Transportations._TransportType = Socket.XHR_POLLING; } return RongIMLib.Transportations._TransportType; }; Socket.prototype.fire = function (x, args) { if (x in this._events) { for (var i = 0, ii = this._events[x].length; i < ii; i++) { this._events[x][i](args); } } return this; }; Socket.prototype.on = function (x, func) { if (!(typeof func == "function" && x)) { return this; } if (x in this._events) { RongIMLib.MessageUtil.indexOf(this._events, func) == -1 && this._events[x].push(func); } else { this._events[x] = [func]; } return this; }; Socket.prototype.removeEvent = function (x, fn) { if (x in this._events) { for (var a = 0, l = this._events[x].length; a < l; a++) { if (this._events[x][a] == fn) { this._events[x].splice(a, 1); } } } return this; }; Socket.prototype._encode = function (x) { var str = "?messageid=" + x.getMessageId() + "&header=" + x.getHeaderFlag() + "&sessionid=" + RongIMLib.RongIMClient._storageProvider.getItem("sId" + RongIMLib.Navigation.Endpoint.userId); if (!/(PubAckMessage|QueryConMessage)/.test(x._name)) { str += "&topic=" + x.getTopic() + "&targetid=" + (x.getTargetId() || ""); } return { url: str, data: "getData" in x ? x.getData() : "" }; }; //消息通道常量,所有和通道相关判断均用 XHR_POLLING WEBSOCKET两属性 Socket.XHR_POLLING = "xhr-polling"; Socket.WEBSOCKET = "websocket"; return Socket; })(); RongIMLib.Socket = Socket; //连接端消息累 var Client = (function () { function Client(token, appId) { this.timeoutMillis = 6000; this.timeout_ = 0; this.sdkVer = ''; this.apiVer = Math.floor(Math.random() * 1e6); this.channel = null; this.handler = null; this.userId = ""; this.reconnectObj = {}; this.heartbeat = 0; this.pullMsgHearbeat = 0; this.chatroomId = ""; this.SyncTimeQueue = []; this.cacheMessageIds = []; this.token = token; this.appId = appId; this.SyncTimeQueue.state = "complete"; this.sdkVer = RongIMLib.RongIMClient.sdkver; } Client.prototype.resumeTimer = function () { var me = this; this.timeout_ = setTimeout(function () { me.channel.disconnect(RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE); }, this.timeoutMillis); }; Client.prototype.pauseTimer = function () { if (this.timeout_) { clearTimeout(this.timeout_); this.timeout_ = 0; } }; Client.prototype.connect = function (_callback) { //实例消息处理类 this.handler = new MessageHandler(this); //设置连接回调 this.handler.setConnectCallback(_callback); //实例通道类型 var me = this; this.channel = new Channel(function () { RongIMLib.Transportations._TransportType == Socket.WEBSOCKET && me.keepLive(); }, this); //触发状态改变观察者 this.channel.socket.fire("StatusChanged", RongIMLib.ConnectionStatus.CONNECTING); //没有返回地址就手动抛出错误 //_callback.onError(ConnectionState.NOT_AUTHORIZED); }; Client.prototype.checkSocket = function (callback) { var me = this; me.channel.writeAndFlush(new RongIMLib.PingReqMessage()); var count = 0; var checkTimeout = setInterval(function () { if (!RongIMLib.RongIMClient._memoryStore.isFirstPingMsg) { clearInterval(checkTimeout); callback.onSuccess(); } else { if (count > 15) { clearInterval(checkTimeout); callback.onError(); } } count++; }, 100); }; Client.prototype.keepLive = function () { if (this.heartbeat > 0) { clearInterval(this.heartbeat); } var me = this; me.heartbeat = setInterval(function () { me.resumeTimer(); me.channel.writeAndFlush(new RongIMLib.PingReqMessage()); }, 30000); if (me.pullMsgHearbeat > 0) { clearInterval(me.pullMsgHearbeat); } me.pullMsgHearbeat = setInterval(function () { me.syncTime(true, undefined, undefined, false); }, 180000); }; Client.prototype.clearHeartbeat = function () { clearInterval(this.heartbeat); this.heartbeat = 0; this.pauseTimer(); clearInterval(this.pullMsgHearbeat); this.pullMsgHearbeat = 0; }; Client.prototype.publishMessage = function (_topic, _data, _targetId, _callback, _msg, option) { option = option || {}; var isNoAck = option.isNoAck; var hasCallback = !!_callback; var msgId = RongIMLib.MessageIdHandler.messageIdPlus(this.channel.reconnect); if (!msgId) { return; } var msg = new RongIMLib.PublishMessage(_topic, _data, _targetId); msg.setMessageId(msgId); if (isNoAck) { msg.setQos(Qos.AT_LEAST_ONCE); _callback.onSuccess(msg); } else if (hasCallback) { msg.setQos(Qos.AT_LEAST_ONCE); this.handler.putCallback(new RongIMLib.PublishCallback(_callback.onSuccess, _callback.onError), msg.getMessageId(), _msg); } else { msg.setQos(Qos.AT_MOST_ONCE); } this.channel.writeAndFlush(msg); }; Client.prototype.queryMessage = function (_topic, _data, _targetId, _qos, _callback, pbtype) { if (_topic == "userInf") { if (Client.userInfoMapping[_targetId]) { _callback.onSuccess(Client.userInfoMapping[_targetId]); return; } } var msgId = RongIMLib.MessageIdHandler.messageIdPlus(this.channel.reconnect); if (!msgId) { return; } var msg = new RongIMLib.QueryMessage(_topic, _data, _targetId); msg.setMessageId(msgId); msg.setQos(_qos); this.handler.putCallback(new RongIMLib.QueryCallback(_callback.onSuccess, _callback.onError), msg.getMessageId(), pbtype); this.channel.writeAndFlush(msg); }; Client.prototype.invoke = function (isPullMsg, chrmId, offlineMsg) { var time, modules, str, me = this, target, temp = this.SyncTimeQueue.shift(); if (temp == undefined) { return; } this.SyncTimeQueue.state = "pending"; var localSyncTime = RongIMLib.SyncTimeUtil.get(); var sentBoxTime = localSyncTime.sent; var isPullChatroom = temp.type === 2; if (temp.type != 2) { //普通消息 time = localSyncTime.received; modules = new RongIMLib.RongIMClient.Protobuf.SyncRequestMsg(); modules.setIspolling(false); str = "pullMsg"; target = this.userId; modules.setSendBoxSyncTime(sentBoxTime); } else { //聊天室消息 target = temp.chrmId || me.chatroomId; time = RongIMLib.RongIMClient._memoryStore.lastReadTime.get(target + Bridge._client.userId + "CST") || 0; modules = new RongIMLib.RongIMClient.Protobuf.ChrmPullMsg(); modules.setCount(0); str = "chrmPull"; if (!target) { var errorMsg = "syncTime:Received messages of chatroom but was not init"; RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.L_CRAW_F, level: RongIMLib.LoggerLevel.E, type: RongIMLib.LoggerType.IM, content: { msg: errorMsg } }); throw new Error(errorMsg); } } //判断服务器给的时间是否消息本地存储的时间,小于的话不执行拉取操作,进行一下步队列操作 if (temp.pulltime <= time) { this.SyncTimeQueue.state = "complete"; this.invoke(isPullMsg, target, offlineMsg); return; } if (isPullMsg && 'setIsPullSend' in modules) { modules.setIsPullSend(true); } modules.setSyncTime(time); //发送queryMessage请求 this.queryMessage(str, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), target, Qos.AT_LEAST_ONCE, { onSuccess: function (collection) { var sync = RongIMLib.MessageUtil.int64ToTimestamp(collection.syncTime), symbol = target; //把返回时间戳存入本地,普通消息key为userid,聊天室消息key为userid+'CST';value都为服务器返回的时间戳 var isChrmPull = str == 'chrmPull'; if (isChrmPull) { symbol += Bridge._client.userId + "CST"; RongIMLib.RongIMClient._memoryStore.lastReadTime.set(symbol, sync); } else { var storage = RongIMLib.RongIMClient._storageProvider; if (sync > storage.getItem(symbol)) { storage.setItem(symbol, sync); } } //把拉取到的消息逐条传给消息监听器 var list = collection.list; var isPullFinished = collection.finished; // chrmPull 没有 finished 字段,自动设置为拉取完成 if (isChrmPull) { isPullFinished = true; } // 兼容长轮训 finished 为空的造成丢消息情况 if (typeof isPullFinished == 'undefined') { isPullFinished = true; } RongIMLib.RongIMClient._memoryStore.isPullFinished = isPullFinished; var connectAckTime = RongIMLib.RongIMClient._memoryStore.connectAckTime; var len = list.length; for (var i = 0, count = len; i < len; i++) { count -= 1; var message = list[i]; var sentTime = RongIMLib.MessageUtil.int64ToTimestamp(message.dataTime); var isSender = message.direction == RongIMLib.MessageDirection.SEND; var compareTime = isSender ? sentBoxTime : time; if (sentTime > compareTime || isPullChatroom) { var isSyncMessage = false; var isOffLineMessage = sentTime < connectAckTime; Bridge._client.handler.onReceived(message, undefined, isOffLineMessage, count, isSyncMessage, isPullFinished); } } if (len <= 200 && str == 'pullMsg') { var Conversation = RongIMLib.RongIMClient._dataAccessProvider.Conversation; var conversationList = RongIMLib.RongIMClient._memoryStore.conversationList; Conversation._notify(conversationList); } me.SyncTimeQueue.state = "complete"; me.invoke(isPullMsg, target, offlineMsg); }, onError: function (error) { me.SyncTimeQueue.state = "complete"; me.invoke(isPullMsg, target, offlineMsg); RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.L_CRAW_F, level: RongIMLib.LoggerLevel.E, type: RongIMLib.LoggerType.IM, content: { action: 'invoke -> queryMessage', error: error } }); } }, "DownStreamMessages"); }; Client.prototype.syncTime = function (_type, pullTime, chrmId, offlineMsg) { this.SyncTimeQueue.push({ type: _type, pulltime: pullTime, chrmId: chrmId }); //如果队列中只有一个成员并且状态已经完成就执行invoke方法 if (this.SyncTimeQueue.length == 1 && this.SyncTimeQueue.state == "complete") { this.invoke(!_type, chrmId, offlineMsg); } }; Client.prototype.__init = function (f) { this.handler = new MessageHandler(this); //设置连接回调 this.handler.setConnectCallback(RongIMLib.RongIMClient._memoryStore.callback); this.channel = new Channel(f, this); }; Client.userInfoMapping = {}; return Client; })(); RongIMLib.Client = Client; //连接类,实现imclient与connect_client的连接 var Bridge = (function () { function Bridge() { } Bridge.getInstance = function () { return new Bridge(); }; //连接服务器 Bridge.prototype.connect = function (appKey, token, callback) { if (!RongIMLib.RongIMClient.Protobuf) { return; } Bridge._client = new RongIMLib.Navigation().connect(appKey, token, callback); return Bridge._client; }; Bridge.prototype.setListener = function () { Channel._ConnectionStatusListener = { onChanged: function (status) { RongIMLib.RongUtil.forEach(RongIMLib.RongIMClient.statusListeners, function (watch) { RongIMLib.RongUtil.isFunction(watch) && watch(status); }); if (status == RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE) { RongIMLib.RongIMClient._memoryStore.networkUnavailable = true; } } }; Channel._ReceiveMessageListener = { onReceived: function (msg, count, hasMore) { RongIMLib.RongUtil.forEach(RongIMLib.RongIMClient.messageListeners, function (watch) { RongIMLib.RongUtil.isFunction(watch) && watch(msg, count, hasMore); }); } }; }; Bridge.prototype.reconnect = function (callabck) { Bridge._client.channel.reconnect(callabck); }; Bridge.prototype.disconnect = function () { Bridge._client.channel.disconnect(2); }; //执行queryMessage请求 Bridge.prototype.queryMsg = function (topic, content, targetId, callback, pbname) { if (typeof topic != "string") { topic = _topic[topic]; } Bridge._client.queryMessage(topic, content, targetId, Qos.AT_MOST_ONCE, callback, pbname); }; //发送消息 执行publishMessage 请求 Bridge.prototype.pubMsg = function (topic, content, targetId, callback, msg, methodType, params) { params = params || {}; if (typeof methodType == 'number') { if (methodType == RongIMLib.MethodType.CUSTOMER_SERVICE) { Bridge._client.publishMessage("pcuMsgP", content, targetId, callback, msg); } else if (methodType == RongIMLib.MethodType.RECALL) { Bridge._client.publishMessage("recallMsg", content, targetId, callback, msg); } } else { var isStatusMessage = params.isStatus; var statusTopic = RongIMLib.StatusTopic[topic]; if (isStatusMessage && statusTopic) { Bridge._client.publishMessage(statusTopic, content, targetId, callback, msg, { isNoAck: true }); } else { Bridge._client.publishMessage(_topic[10][topic], content, targetId, callback, msg); // 非状态消息, 逻辑不变 } } }; return Bridge; })(); RongIMLib.Bridge = Bridge; var MessageHandler = (function () { function MessageHandler(client) { this.map = {}; this.connectCallback = null; if (!Channel._ReceiveMessageListener) { throw new Error("please set onReceiveMessageListener"); } this._onReceived = Channel._ReceiveMessageListener.onReceived; this._client = client; this.syncMsgMap = new Object; } //把对象推入回调对象队列中,并启动定时器 MessageHandler.prototype.putCallback = function (callbackObj, _publishMessageId, _msg) { var item = { Callback: callbackObj, Message: _msg }; item.Callback.resumeTimer(); this.map[_publishMessageId] = item; }; //设置连接回调对象,启动定时器 MessageHandler.prototype.setConnectCallback = function (_connectCallback) { if (_connectCallback) { this.connectCallback = new RongIMLib.ConnectAck(_connectCallback.onSuccess, _connectCallback.onError, this._client); } }; MessageHandler.prototype.handleChrmKVPullMsg = function (msg) { try { var pbtype = 'NotifyMsg'; var data = RongIMLib.CallbackMapping.getInstance().mapping(RongIMLib.RongIMClient.Protobuf[pbtype].decode(msg.data), pbtype); var timestamp = RongIMLib.MessageUtil.int64ToTimestamp(data.time); if (data.type === 2) { RongIMLib.ChrmKVHandler.pull(data.chrmId, timestamp); } else if (data.type === 3) { RongIMLib.RongIMClient._dataAccessProvider.conversationStatusManager.pull({ time: timestamp }); } } catch (e) { } }; MessageHandler.prototype.onReceived = function (msg, pubAckItem, offlineMsg, leftCount, isSync) { //实体对象 var entity, //解析完成的消息对象 message, //会话对象 con, // 是否为直发消息 isStraightMsg = false; if (msg._name != "PublishMessage") { entity = msg; RongIMLib.RongIMClient._storageProvider.setItem(this._client.userId, RongIMLib.MessageUtil.int64ToTimestamp(entity.dataTime)); } else { if (msg.getTopic() == "s_ntf") { entity = RongIMLib.RongIMClient.Protobuf.NotifyMsg.decode(msg.getData()); this._client.syncTime(entity.type, RongIMLib.MessageUtil.int64ToTimestamp(entity.time), entity.chrmId); return; } else if (msg.getTopic() == "s_msg") { isStraightMsg = true; entity = RongIMLib.RongIMClient.Protobuf.DownStreamMessage.decode(msg.getData()); var timestamp = RongIMLib.MessageUtil.int64ToTimestamp(entity.dataTime); RongIMLib.RongIMClient._storageProvider.setItem(this._client.userId, timestamp); RongIMLib.RongIMClient._memoryStore.lastReadTime.get(this._client.userId, timestamp); } else if (msg.getTopic() == "s_stat") { entity = RongIMLib.RongIMClient.Protobuf.GetUserStatusOutput.decode(msg.getData()); entity = RongIMLib.RongInnerTools.convertUserStatus(entity); RongIMLib.RongIMClient.userStatusObserver.notify({ key: entity.userId, entity: entity }); return; } else if (msg.getTopic() === 's_cmd') { this.handleChrmKVPullMsg(msg); return; } else { if (Bridge._client.sdkVer && Bridge._client.sdkVer == "1.0.0") { return; } entity = RongIMLib.RongIMClient.Protobuf.UpStreamMessage.decode(msg.getData()); var tmpTopic = msg.getTopic(); var tmpType = tmpTopic.substr(0, 2); if (tmpType == "pp") { entity.type = 1; } else if (tmpType == "pd") { entity.type = 2; } else if (tmpType == "pg") { entity.type = 3; } else if (tmpType == "ch") { entity.type = 4; } else if (tmpType == "pc") { entity.type = 5; } //复用字段,targetId 以此为准 entity.groupId = msg.getTargetId(); entity.fromUserId = this._client.userId; entity.dataTime = Date.parse(new Date().toString()); } if (!entity) { return; } } var isPullFinished = RongIMLib.RongIMClient._memoryStore.isPullFinished; // PullMsg 没有拉取完成,抛弃所有直发在线消息,抛弃的消息会在 PullMsg 中返回 if (!isPullFinished && !offlineMsg && isStraightMsg) { return; } //解析实体对象为消息对象。 message = RongIMLib.MessageUtil.messageParser(entity, this._onReceived, offlineMsg); var isRTCMessage = message.conversationType == 12; if (isRTCMessage) { RongIMLib.RongIMClient.RTCListener(message); RongIMLib.RongIMClient.RTCInnerListener(message); RongIMLib.RongIMClient.RTCSignalLisener(message); return; } var isRecall = (msg.getTopic && msg.getTopic() == "recallMsg"); if (isRecall) { var content = message.content; message.conversationType = content.conversationType; message.targetId = content.targetId; message.messageId = null; } if (pubAckItem) { message.messageUId = pubAckItem.getMessageUId(); message.sentTime = pubAckItem.getTimestamp(); RongIMLib.RongIMClient._storageProvider.setItem(this._client.userId, message.sentTime); } if (message === null) { return; } var isChatroomMessage = message.conversationType == RongIMLib.ConversationType.CHATROOM; if (!isChatroomMessage) { var msgTag = RongIMLib.RongIMClient.MessageParams[message.messageType].msgTag.getMessageTag(); if (msgTag >= 0) { RongIMLib.SyncTimeUtil.set(message); } var isSend = (message.messageDirection == RongIMLib.MessageDirection.SEND); if (isSend) { var storageProvider = RongIMLib.RongIMClient._storageProvider; var userId = RongIMLib.Bridge._client.userId; var lastSentTime = storageProvider.getItem('last_sentTime_' + userId) || 0; if (message.sentTime <= lastSentTime && !isSync) { return; } } } // 设置会话时间戳并且判断是否传递 message 发送消息未处理会话时间戳 // key:'converST_' + 当前用户 + conversationType + targetId // RongIMClient._storageProvider.setItem('converST_' + Bridge._client.userId + message.conversationType + message.targetId, message.sentTime); // var isPersited = (RongIMClient.MessageParams[message.messageType].msgTag.getMessageTag() > 0); var msgTag = RongIMLib.RongIMClient.MessageParams[message.messageType].msgTag.getMessageTag(); var isPersited = msgTag === 3 || msgTag === 2; if (isPersited) { con = RongIMLib.RongIMClient._dataAccessProvider.getConversation(message.conversationType, message.targetId, { onSuccess: function () { }, onError: function () { } }); if (!con) { con = RongIMLib.RongIMClient.getInstance().createConversation(message.conversationType, message.targetId, ""); } if (message.messageDirection == RongIMLib.MessageDirection.RECEIVE && (entity.status & 64) == 64) { var mentioneds = RongIMLib.RongIMClient._storageProvider.getItem("mentioneds_" + Bridge._client.userId + '_' + message.conversationType + '_' + message.targetId); var key = message.conversationType + '_' + message.targetId, info = {}; if (message.content && message.content.mentionedInfo) { info[key] = { uid: message.messageUId, time: message.sentTime, mentionedInfo: message.content.mentionedInfo }; RongIMLib.RongIMClient._storageProvider.setItem("mentioneds_" + Bridge._client.userId + '_' + message.conversationType + '_' + message.targetId, JSON.stringify(info)); mentioneds = JSON.stringify(info); } if (mentioneds) { var info = JSON.parse(mentioneds); con.mentionedMsg = info[key]; } } var isReceiver = message.messageDirection == RongIMLib.MessageDirection.RECEIVE; if (isReceiver && message.senderUserId != Bridge._client.userId) { con.unreadMessageCount = con.unreadMessageCount + 1; if (RongIMLib.RongUtil.supportLocalStorage()) { // var originUnreadCount = RongIMClient._storageProvider.getItem("cu" + Bridge._client.userId + con.conversationType + con.targetId); // 与本地存储会话合并 // var newUnreadCount = Number(originUnreadCount) + 1; // RongIMClient._storageProvider.setItem("cu" + Bridge._client.userId + con.conversationType + message.targetId, newUnreadCount); var newUnreadCount = RongIMLib.UnreadCountHandler.add(con.conversationType, message.targetId, 1, message.sentTime); con.unreadMessageCount = newUnreadCount; } } var receivedTime = new Date().getTime(); con.receivedTime = RongIMLib.MessageUtil.getCheckedTime(receivedTime); con.receivedStatus = message.receivedStatus; con.senderUserId = message.sendUserId; con.notificationStatus = RongIMLib.ConversationNotificationStatus.DO_NOT_DISTURB; con.latestMessageId = message.messageId; con.latestMessage = message; con.sentTime = message.sentTime; RongIMLib.RongIMClient._dataAccessProvider.addConversation(con, { onSuccess: function (data) { if (!offlineMsg) { var Conversation_1 = RongIMLib.RongIMClient._dataAccessProvider.Conversation; var conversationList = RongIMLib.RongIMClient._memoryStore.conversationList; Conversation_1._notify(conversationList); } }, onError: function () { } }); } if (message.conversationType == RongIMLib.ConversationType.CUSTOMER_SERVICE && (message.messageType == "ChangeModeResponseMessage" || message.messageType == "SuspendMessage" || message.messageType == "HandShakeResponseMessage" || message.messageType == "TerminateMessage" || message.messageType == "CustomerStatusUpdateMessage" || message.messageType == "TextMessage" || message.messageType == "InformationNotificationMessage")) { if (!RongIMLib.RongIMClient._memoryStore.custStore["isInit"]) { return; } } if (message.conversationType == RongIMLib.ConversationType.CUSTOMER_SERVICE && message.messageType != "HandShakeResponseMessage") { if (!RongIMLib.RongIMClient._memoryStore.custStore[message.targetId]) { return; } if (message.messageType == "TerminateMessage") { if (RongIMLib.RongIMClient._memoryStore.custStore[message.targetId].sid != message.content.sid) { return; } } } if (message.messageType === RongIMLib.RongIMClient.MessageType["HandShakeResponseMessage"]) { var session = message.content.data; RongIMLib.RongIMClient._memoryStore.custStore[message.targetId] = session; if (session.serviceType == RongIMLib.CustomerType.ONLY_HUMAN || session.serviceType == RongIMLib.CustomerType.HUMAN_FIRST) { if (session.notAutoCha == "1") { RongIMLib.RongIMClient.getInstance().switchToHumanMode(message.targetId, { onSuccess: function () { }, onError: function () { } }); } } } if (RongIMLib.LoggerUtil.isLogCmdMsg(message)) { RongIMLib.Logger.reportMNLog(message.content); return; } var d = new Date(), m = d.getMonth() + 1, date = d.getFullYear() + '/' + (m.toString().length == 1 ? '0' + m : m) + '/' + d.getDate(); //new Date(date).getTime() - message.sentTime < 1 逻辑判断 超过 1 天未收的 ReadReceiptRequestMessage 离线消息自动忽略。 var dealtime = new Date(date).getTime() - message.sentTime < 0; if (RongIMLib.RongUtil.supportLocalStorage() && message.messageType === RongIMLib.RongIMClient.MessageType["ReadReceiptRequestMessage"] && dealtime && message.messageDirection == RongIMLib.MessageDirection.SEND) { var sentkey = Bridge._client.userId + message.content.messageUId + "SENT"; RongIMLib.RongIMClient._storageProvider.setItem(sentkey, JSON.stringify({ count: 0, dealtime: message.sentTime, userIds: {} })); } else if (RongIMLib.RongUtil.supportLocalStorage() && message.messageType === RongIMLib.RongIMClient.MessageType["ReadReceiptRequestMessage"] && dealtime) { var reckey = Bridge._client.userId + message.conversationType + message.targetId + 'RECEIVED', recData = JSON.parse(RongIMLib.RongIMClient._storageProvider.getItem(reckey)); if (recData) { if (message.senderUserId in recData) { if (recData[message.senderUserId].uIds && recData[message.senderUserId].uIds && recData[message.senderUserId].uIds.indexOf(message.content.messageUId) == -1) { recData[message.senderUserId].uIds.push(message.content.messageUId); recData[message.senderUserId].dealtime = message.sentTime; recData[message.senderUserId].isResponse = false; RongIMLib.RongIMClient._storageProvider.setItem(reckey, JSON.stringify(recData)); } else { return; } } else { var objSon = { uIds: [message.content.messageUId], dealtime: message.sentTime, isResponse: false }; recData[message.senderUserId] = objSon; RongIMLib.RongIMClient._storageProvider.setItem(reckey, JSON.stringify(recData)); } } else { var obj = {}; obj[message.senderUserId] = { uIds: [message.content.messageUId], dealtime: message.sentTime, isResponse: false }; RongIMLib.RongIMClient._storageProvider.setItem(reckey, JSON.stringify(obj)); } } if (RongIMLib.RongUtil.supportLocalStorage() && message.messageType === RongIMLib.RongIMClient.MessageType["ReadReceiptResponseMessage"] && dealtime) { var receiptResponseMsg = message.content, uIds = receiptResponseMsg.receiptMessageDic[Bridge._client.userId], sentkey = "", sentObj; message.receiptResponse || (message.receiptResponse = {}); if (uIds) { var cbuIds = []; for (var i = 0, len = uIds.length; i < len; i++) { sentkey = Bridge._client.userId + uIds[i] + "SENT"; sentObj = JSON.parse(RongIMLib.RongIMClient._storageProvider.getItem(sentkey)); if (sentObj && !(message.senderUserId in sentObj.userIds)) { cbuIds.push(uIds[i]); sentObj.count += 1; sentObj.userIds[message.senderUserId] = message.sentTime; message.receiptResponse[uIds[i]] = sentObj.count; RongIMLib.RongIMClient._storageProvider.setItem(sentkey, JSON.stringify(sentObj)); } } receiptResponseMsg.receiptMessageDic[Bridge._client.userId] = cbuIds; message.content = receiptResponseMsg; } } var that = this; if (RongIMLib.RongIMClient._voipProvider && ['AcceptMessage', 'RingingMessage', 'HungupMessage', 'InviteMessage', 'MediaModifyMessage', 'MemberModifyMessage'].indexOf(message.messageType) > -1) { setTimeout(function () { RongIMLib.RongIMClient._voipProvider.onReceived(message); }); } else { var count = leftCount || 0; var hasMore = !isPullFinished; try { that._onReceived(message, count, hasMore); } catch (e) { console.error(e); } } }; MessageHandler.prototype.handleMessage = function (msg) { if (!msg) { return; } if (msg && RongIMLib.RongUtil.isObject(msg) && msg.timestamp) { RongIMLib.MessageUtil.setDeltaTime(msg.timestamp); } switch (msg._name) { case "ConnAckMessage": Bridge._client.handler.connectCallback.process(msg.getStatus(), msg.getUserId(), msg.getTimestamp()); break; case "PublishMessage": if (!msg.getSyncMsg() && msg.getQos() != 0) { Bridge._client.channel.writeAndFlush(new RongIMLib.PubAckMessage(msg.getMessageId())); } // TODO && -> if (msg.getSyncMsg() && !RongIMLib.RongIMClient._memoryStore.depend.isPolling) { Bridge._client.handler.syncMsgMap[msg.getMessageId()] = msg; } else { //如果是PublishMessage就把该对象给onReceived方法执行处理 Bridge._client.handler.onReceived(msg); } break; case "QueryAckMessage": if (msg.getQos() != 0) { Bridge._client.channel.writeAndFlush(new RongIMLib.QueryConMessage(msg.getMessageId())); } var temp = Bridge._client.handler.map[msg.getMessageId()]; if (temp) { //执行回调操作 temp.Callback.process(msg.getStatus(), msg.getData(), msg.getDate(), temp.Message); delete Bridge._client.handler.map[msg.getMessageId()]; } break; case "PubAckMessage": var item = Bridge._client.handler.map[msg.getMessageId()]; if (item) { item.Callback.process(msg.getStatus() || 0, msg.getMessageUId(), msg.getTimestamp(), item.Message, msg.getMessageId()); delete Bridge._client.handler.map[msg.getMessageId()]; } else { var userId = RongIMLib.Bridge._client.userId; RongIMLib.RongIMClient._storageProvider.setItem('last_sentTime_' + userId, msg.timestamp); Bridge._client.handler.onReceived(Bridge._client.handler.syncMsgMap[msg.messageId], msg, null, null, true); delete Bridge._client.handler.syncMsgMap[msg.getMessageId()]; } break; case "PingRespMessage": if (RongIMLib.RongIMClient._memoryStore.isFirstPingMsg) { RongIMLib.RongIMClient._memoryStore.isFirstPingMsg = false; } else { Bridge._client.pauseTimer(); } break; case "DisconnectMessage": Bridge._client.channel.disconnect(msg.getStatus()); break; default: RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.L_CRAW_F, level: RongIMLib.LoggerLevel.E, type: RongIMLib.LoggerType.IM, content: { action: 'MessageHandler -> handleMessage', msg: msg } }); } }; return MessageHandler; })(); RongIMLib.MessageHandler = MessageHandler; })(RongIMLib || (RongIMLib = {})); var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; /// var RongIMLib; (function (RongIMLib) { var MessageCallback = (function () { function MessageCallback(error) { this.timeout = null; this.onError = null; if (error && typeof error == "number") { this.timeoutMillis = error; } else { this.timeoutMillis = 30000; this.onError = error; } } MessageCallback.prototype.resumeTimer = function () { var me = this; if (this.timeoutMillis > 0 && !this.timeout) { this.timeout = setTimeout(function () { me.readTimeOut(true); }, this.timeoutMillis); } }; MessageCallback.prototype.pauseTimer = function () { if (this.timeout) { clearTimeout(this.timeout); this.timeout = null; } }; MessageCallback.prototype.readTimeOut = function (isTimeout) { if (isTimeout && this.onError) { this.onError(RongIMLib.ErrorCode.TIMEOUT); } else { this.pauseTimer(); } }; return MessageCallback; })(); RongIMLib.MessageCallback = MessageCallback; var CallbackMapping = (function () { function CallbackMapping() { this.publicServiceList = []; } CallbackMapping.getInstance = function () { return new CallbackMapping(); }; CallbackMapping.prototype.pottingProfile = function (item) { var temp; this.profile = new RongIMLib.PublicServiceProfile(); temp = JSON.parse(item.extra); this.profile.isGlobal = temp.isGlobal; this.profile.introduction = temp.introduction; this.profile.menu = temp.menu; this.profile.hasFollowed = temp.follow; this.profile.publicServiceId = item.mpid; this.profile.name = item.name; this.profile.portraitUri = item.portraitUrl; this.profile.conversationType = item.type == "mc" ? RongIMLib.ConversationType.APP_PUBLIC_SERVICE : RongIMLib.ConversationType.PUBLIC_SERVICE; this.publicServiceList.push(this.profile); }; CallbackMapping.prototype.mapping = function (entity, tag) { switch (tag) { case "GetUserInfoOutput": var userInfo = new RongIMLib.UserInfo(entity.userId, entity.userName, entity.userPortrait); return userInfo; case "GetQNupTokenOutput": return { deadline: RongIMLib.MessageUtil.int64ToTimestamp(entity.deadline), token: entity.token }; case "GetQNdownloadUrlOutput": return { downloadUrl: entity.downloadUrl }; case "CreateDiscussionOutput": return entity.id; case "ChannelInfoOutput": var disInfo = new RongIMLib.Discussion(); disInfo.creatorId = entity.adminUserId; disInfo.id = entity.channelId; disInfo.memberIdList = entity.firstTenUserIds; disInfo.name = entity.channelName; disInfo.isOpen = entity.openStatus; return disInfo; case "GroupHashOutput": return entity.result; case "QueryBlackListOutput": return entity.userIds; case "SearchMpOutput": case "PullMpOutput": if (entity.info) { var self = this; Array.forEach(entity.info, function (item) { setTimeout(function () { self.pottingProfile(item); }, 100); }); } return this.publicServiceList; default: return entity; } }; return CallbackMapping; })(); RongIMLib.CallbackMapping = CallbackMapping; var PublishCallback = (function (_super) { __extends(PublishCallback, _super); function PublishCallback(_cb, _timeout) { _super.call(this, _timeout); this._cb = _cb; this._timeout = _timeout; } PublishCallback.prototype.process = function (_status, messageUId, timestamp, _msg, messageId) { this.readTimeOut(); if (_status == 0) { if (_msg) { _msg.setSentStatus = _status; } var isPullFinished = RongIMLib.RongIMClient._memoryStore.isPullFinished; if (isPullFinished) { var userId = RongIMLib.Bridge._client.userId; var stroageProvider = RongIMLib.RongIMClient._storageProvider; stroageProvider.setItem('last_sentTime_' + userId, timestamp); RongIMLib.SyncTimeUtil.set({ messageDirection: RongIMLib.MessageDirection.SEND, sentTime: timestamp }); } this._cb({ messageUId: messageUId, timestamp: timestamp, messageId: messageId }); } else { this._timeout(_status, { messageUId: messageUId, sentTime: timestamp }); } }; PublishCallback.prototype.readTimeOut = function (x) { MessageCallback.prototype.readTimeOut.call(this, x); }; return PublishCallback; })(MessageCallback); RongIMLib.PublishCallback = PublishCallback; var QueryCallback = (function (_super) { __extends(QueryCallback, _super); function QueryCallback(_cb, _timeout) { _super.call(this, _timeout); this._cb = _cb; this._timeout = _timeout; } QueryCallback.prototype.process = function (status, data, serverTime, pbtype) { this.readTimeOut(); if (pbtype && data && status == 0) { try { data = CallbackMapping.getInstance().mapping(RongIMLib.RongIMClient.Protobuf[pbtype].decode(data), pbtype); } catch (e) { this._timeout(RongIMLib.ErrorCode.UNKNOWN); RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.L_CRAW_F, level: RongIMLib.LoggerLevel.E, type: RongIMLib.LoggerType.IM, content: { stack: e, msg: 'QueryCallback -> process' } }); return; } if ("GetUserInfoOutput" == pbtype) { //pb类型为GetUserInfoOutput的话就把data放入userinfo缓存队列 RongIMLib.Client.userInfoMapping[data.userId] = data; } this._cb(data); } else { status > 0 ? this._timeout(status) : this._cb(status); } }; QueryCallback.prototype.readTimeOut = function (x) { MessageCallback.prototype.readTimeOut.call(this, x); }; return QueryCallback; })(MessageCallback); RongIMLib.QueryCallback = QueryCallback; var ConnectAck = (function (_super) { __extends(ConnectAck, _super); function ConnectAck(_cb, _timeout, client) { _super.call(this, _timeout); this._client = client; this._cb = _cb; this._timeout = _timeout; } ConnectAck.prototype.process = function (status, userId, timestamp) { this.readTimeOut(); if (status == 0) { this._client.userId = userId; var self = this; if (!RongIMLib.RongIMClient._memoryStore.depend.isPolling && RongIMLib.RongIMClient._memoryStore.isFirstPingMsg) { RongIMLib.Bridge._client.checkSocket({ onSuccess: function () { if (!RongIMLib.RongIMClient.isNotPullMsg) { self._client.syncTime(undefined, undefined, undefined, true); } }, onError: function () { RongIMLib.RongIMClient._memoryStore.isFirstPingMsg = false; RongIMLib.RongIMClient.getInstance().disconnect(); RongIMLib.RongIMClient.connect(RongIMLib.RongIMClient._memoryStore.token, RongIMLib.RongIMClient._memoryStore.callback); } }); } else { if (!RongIMLib.RongIMClient.isNotPullMsg) { self._client.syncTime(undefined, undefined, undefined, true); } } RongIMLib.Bridge._client.channel.socket.fire("StatusChanged", 0); if (this._client.reconnectObj.onSuccess) { this._client.reconnectObj.onSuccess(userId); delete this._client.reconnectObj.onSuccess; } else { var me = this; me._cb(userId); // setTimeout(function() { me._cb(userId); }, 500); var depend = RongIMLib.RongIMClient._memoryStore.depend; var maxConversationCount = depend.maxConversationCount; var isNotifyConversationList = depend.isNotifyConversationList; isNotifyConversationList && RongIMLib.RongIMClient._dataAccessProvider.getRemoteConversationList({ onSuccess: function (conversationList) { var Conversation = RongIMLib.RongIMClient._dataAccessProvider.Conversation; Conversation._notify(conversationList); }, onError: function (code) { console.log('内部获取列表失败: %d', code); } }, null, maxConversationCount); } RongIMLib.RongIMClient._memoryStore.connectAckTime = timestamp; RongIMLib.MessageUtil.setDeltaTime(timestamp); } else if (status == 6) { RongIMLib.RongIMClient.getInstance().disconnect(); //重定向 连错 CMP var me = this; var _client = me._client; var appId = _client.appId, token = _client.token; new RongIMLib.Navigation().requestNavi(token, appId, function () { _client.clearHeartbeat(); var newClient = new RongIMLib.Client(token, appId); RongIMLib.Bridge._client = newClient; newClient.__init(function () { RongIMLib.Transportations._TransportType == "websocket" && newClient.keepLive(); }); }, me._timeout, false); } else { RongIMLib.Bridge._client.channel.socket.socket._status = status; if (this._client.reconnectObj.onError) { this._client.reconnectObj.onError(status); delete this._client.reconnectObj.onError; } else { this._timeout(status); } } }; ConnectAck.prototype.readTimeOut = function (x) { MessageCallback.prototype.readTimeOut.call(this, x); }; return ConnectAck; })(MessageCallback); RongIMLib.ConnectAck = ConnectAck; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var Navigation = (function () { function Navigation() { } Navigation.clear = function () { var storage = RongIMLib.RongIMClient._storageProvider; storage.removeItem('rc_uid'); storage.removeItem('serverIndex'); storage.removeItem('rongSDK'); }; Navigation.prototype.getNaviSuccess = function (result, naviUrl) { var storage = RongIMLib.RongIMClient._storageProvider; storage.setItem('fullnavi', JSON.stringify(result)); var successNaviProtocol = RongIMLib.RongUtil.getUrlProtocol(naviUrl); // navi 请求成功后, 根据 navi 协议头, 设置连接 websocket 协议头 RongIMLib.RongIMClient.setProtocol(successNaviProtocol); storage.setItem(Navigation.StoreProtocolKey, successNaviProtocol); var server = result.server; if (server) { server += ','; } var backupServer = result.backupServer || ''; var tpl = '{server}{backupServer}'; var servers = RongIMLib.RongUtil.tplEngine(tpl, { server: server, backupServer: backupServer }); servers = servers.split(','); storage.setItem('servers', JSON.stringify(servers)); var token = RongIMLib.RongIMClient._memoryStore.token; var uid = RongIMLib.InnerUtil.getUId(token); storage.setItem('rc_uid', uid); var userId = result.userId; storage.setItem('current_user', userId); storage.setItem('navi_time', RongIMLib.RongUtil.getTimestamp()); if (result.voipCallInfo) { var callInfo = JSON.parse(result.voipCallInfo); RongIMLib.RongIMClient._memoryStore.voipStategy = callInfo.strategy; storage.setItem("voipStrategy", callInfo.strategy); } //替换本地存储的导航信息 var openMp = result.openMp; storage.setItem('openMp' + uid, openMp); RongIMLib.RongIMClient._memoryStore.depend.openMp = openMp; }; ; Navigation.prototype.connect = function (appId, token, callback) { var oldAppId = RongIMLib.RongIMClient._storageProvider.getItem("appId"); //如果appid和本地存储的不一样,清空所有本地存储数据 if (oldAppId && oldAppId != appId) { RongIMLib.RongIMClient._storageProvider.clearItem(); RongIMLib.RongIMClient._storageProvider.setItem("appId", appId); } if (!oldAppId) { RongIMLib.RongIMClient._storageProvider.setItem("appId", appId); } var client = new RongIMLib.Client(token, appId); this.requestNavi(token, appId, function () { client.connect(callback); }, callback.onError, true); return client; }; Navigation.prototype.requestNavi = function (token, appId, _onsuccess, _onerror, unignore) { if (unignore) { //根据token生成MD5截取8-16下标的数据与本地存储的导航信息进行比对 //如果信息和上次的通道类型都一样,不执行navi请求,用本地存储的导航信息连接服务器 var uId = md5(token).slice(8, 16); var storage = RongIMLib.RongIMClient._storageProvider; var transportType = storage.getItem("rongSDK"); var isSameType = (RongIMLib.Transportations._TransportType == transportType); var _old = storage.getItem('rc_uid'); var isSameUser = (_old == uId); var servers = storage.getItem('servers'); var hasServers = (typeof servers == 'string'); var currentTime = RongIMLib.RongUtil.getTimestamp(); var naviSavedTime = Number(storage.getItem('navi_time')) || 0; var isNotExpired = currentTime - naviSavedTime < RongIMLib.RongIMClient.NavExpiredTime; if (isSameUser && isSameType && hasServers && RongIMLib.RongUtil.hasValidWsUrl(servers) && isNotExpired) { RongIMLib.RongIMClient._memoryStore.voipStategy = storage.getItem("voipStrategy"); var openMp = storage.getItem('openMp' + uId); RongIMLib.RongIMClient._memoryStore.depend.openMp = openMp; var storageProtocol = storage.getItem(Navigation.StoreProtocolKey); storageProtocol && RongIMLib.RongIMClient.setProtocol(storageProtocol); _onsuccess(); return; } } Navigation.clear(); RongIMLib.RongIMClient.invalidWsUrls = []; var context = this; var StatusEvent = RongIMLib.Channel._ConnectionStatusListener; var depend = RongIMLib.RongIMClient._memoryStore.depend; var navigaters = depend.navigaters; var naviTimeout = depend.naviTimeout; var maxNaviRetry = depend.maxNaviRetry; var isNaviJSONP = depend.isNaviJSONP; var isSupportRequestHeaders = RongIMLib.RongUtil.isSupportRequestHeaders(); var isRequestJSONP = !isSupportRequestHeaders || isNaviJSONP; var requestFunc = isRequestJSONP ? context.requestJSONP : context.request; var timer = new RongIMLib.Timer({ timeout: naviTimeout }); var internalRetry = 1; var isRange = function () { return internalRetry >= maxNaviRetry; }; var indexTools = new RongIMLib.IndexTools({ items: navigaters, onwheel: function () { internalRetry += 1; } }); var consume = function () { if (isRange()) { _onerror(RongIMLib.ConnectionStatus.RESPONSE_NAVI_ERROR); return; } var index = indexTools.get(); var navi = navigaters[index]; navi = RongIMLib.RongUtil.getValidNavi(navi); indexTools.add(); RongIMLib.LoggerUtil.recordFatalLogOfNavi(internalRetry, navigaters); var success = function (result) { timer.pause(); StatusEvent.onChanged(RongIMLib.ConnectionStatus.RESPONSE_NAVI); var code = result.code; if (RongIMLib.RongUtil.isEqual(code, 200)) { context.getNaviSuccess(result, navi); _onsuccess(); } if (RongIMLib.RongUtil.isEqual(code, 401)) { _onerror(RongIMLib.ConnectionState.TOKEN_INCORRECT); } if (RongIMLib.RongUtil.isEqual(code, 403)) { StatusEvent.onChanged(RongIMLib.ConnectionStatus.APPKEY_IS_FAKE); } }; var error = function (status) { if (RongIMLib.RongUtil.isEqual(status, 0)) { return; } timer.pause(); StatusEvent.onChanged(RongIMLib.ConnectionStatus.RESPONSE_NAVI_ERROR); consume(); }; StatusEvent.onChanged(RongIMLib.ConnectionStatus.REQUEST_NAVI); var xhr = requestFunc.call(context, navi, appId, token, success, error); timer.resume(function () { StatusEvent.onChanged(RongIMLib.ConnectionStatus.RESPONSE_NAVI_TIMEOUT); xhr.abort(); consume(); }); }; consume(); RongIMLib.Logger.loggerCache.isNewNavi = true; }; Navigation.prototype.getPath = function (navi, appId, token, callbackName) { var depend = RongIMLib.RongIMClient._memoryStore.depend; var path = (depend.isPolling ? 'cometnavi' : 'navi'); token = encodeURIComponent(token); var sdkver = RongIMLib.RongIMClient.sdkver; var random = RongIMLib.RongUtil.getTimestamp(); var tpl = '{navi}/{path}.js?appId={appId}&token={token}&callBack={callback}&v={sdkver}&r={random}'; var url = RongIMLib.RongUtil.tplEngine(tpl, { navi: navi, path: path, appId: appId, token: token, sdkver: sdkver, random: random, callback: callbackName }); return url; }; Navigation.prototype.request = function (navi, appId, token, success, error) { var url = this.getPath(navi, appId, token, 'getServerEndpoint'); var requestType = "HTTP"; RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.L_GETN_T, level: RongIMLib.LoggerLevel.I, type: RongIMLib.LoggerType.IM, content: { url: url, requestType: requestType } }); return RongIMLib.RongUtil.request({ url: url, success: function (result) { result = result.replace('getServerEndpoint(', '').replace(');', ''); // 兼容私有云无分号 var lastIndex = result.lastIndexOf(')'); var maxIndex = result.length - 1; if (lastIndex == maxIndex) { result = result.substr(0, lastIndex); } result = JSON.parse(result); RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.L_GETN_R, level: RongIMLib.LoggerLevel.I, type: RongIMLib.LoggerType.IM, content: { code: 0, result: result, url: url, requestType: requestType } }); success(result); }, error: function (status, result) { if (status == 401 || status == 403) { success(JSON.parse(result)); } else { error(status); } RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.L_GETN_R, level: RongIMLib.LoggerLevel.E, type: RongIMLib.LoggerType.IM, content: { code: status, result: result, url: url, requestType: requestType } }); } }); }; Navigation.prototype.requestJSONP = function (navi, appId, token, success, error) { var callbackName = 'getServerEndpoint'; var requestType = "JSONP"; RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.L_GETN_T, level: RongIMLib.LoggerLevel.I, type: RongIMLib.LoggerType.IM, content: { url: url, requestType: requestType } }); var loggerResult = function (status, result) { RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.L_GETN_R, level: RongIMLib.LoggerLevel.E, type: RongIMLib.LoggerType.IM, content: { code: status, result: result, url: url, requestType: requestType } }); }; window.getServerEndpoint = function (result) { var code = result.code; loggerResult(code, result); if (code !== 200) { return error(RongIMLib.ConnectionState.TOKEN_INCORRECT); } success(result); }; var url = this.getPath(navi, appId, token, callbackName); var xss = document.createElement('script'); xss.src = url; document.body.appendChild(xss); xss.onerror = function () { error(RongIMLib.ConnectionState.TOKEN_INCORRECT); loggerResult(RongIMLib.ConnectionState.TOKEN_INCORRECT, {}); }; }; Navigation.StoreProtocolKey = 'navprotocol'; Navigation.Endpoint = new Object; return Navigation; })(); RongIMLib.Navigation = Navigation; })(RongIMLib || (RongIMLib = {})); // TODO: 统一变量、方法等命名规范 var RongIMLib; (function (RongIMLib) { /** * 消息基类 */ var BaseMessage = (function () { function BaseMessage(arg) { this._name = "BaseMessage"; this.lengthSize = 0; if (arg instanceof RongIMLib.Header) { this._header = arg; } else { this._header = new RongIMLib.Header(arg, false, RongIMLib.Qos.AT_MOST_ONCE, false); } } BaseMessage.prototype.read = function (In, length) { this.readMessage(In, length); }; BaseMessage.prototype.write = function (Out) { var binaryHelper = new RongIMLib.BinaryHelper(); var out = binaryHelper.convertStream(Out); this._headerCode = this.getHeaderFlag(); out.write(this._headerCode); this.writeMessage(out); return out; }; BaseMessage.prototype.getHeaderFlag = function () { return this._header.encode(); }; BaseMessage.prototype.getLengthSize = function () { return this.lengthSize; }; BaseMessage.prototype.toBytes = function () { return this.write([]).getBytesArray(); }; BaseMessage.prototype.isRetained = function () { return this._header.retain; }; BaseMessage.prototype.setRetained = function (retain) { this._header.retain = retain; }; BaseMessage.prototype.setQos = function (qos) { this._header.qos = Object.prototype.toString.call(qos) == "[object Object]" ? qos : RongIMLib.Qos[qos]; }; BaseMessage.prototype.setDup = function (dup) { this._header.dup = dup; }; BaseMessage.prototype.isDup = function () { return this._header.dup; }; BaseMessage.prototype.getType = function () { return this._header.type; }; BaseMessage.prototype.getQos = function () { return this._header.qos; }; BaseMessage.prototype.messageLength = function () { return 0; }; BaseMessage.prototype.writeMessage = function (out) { }; BaseMessage.prototype.readMessage = function (In, length) { }; BaseMessage.prototype.init = function (args) { var valName, nana, me = this; for (nana in args) { if (!args.hasOwnProperty(nana)) { continue; } valName = nana.replace(/^\w/, function (x) { var tt = x.charCodeAt(0); return "set" + (tt >= 0x61 ? String.fromCharCode(tt & ~32) : x); }); if (valName in me) { if (nana == "status") { me[valName](disconnectStatus[args[nana]] ? disconnectStatus[args[nana]] : args[nana]); } else { me[valName](args[nana]); } } } }; return BaseMessage; })(); RongIMLib.BaseMessage = BaseMessage; /** *连接消息类型 */ var ConnectMessage = (function (_super) { __extends(ConnectMessage, _super); function ConnectMessage(header) { _super.call(this, arguments.length == 0 || arguments.length == 3 ? RongIMLib.Type.CONNECT : arguments[0]); this._name = "ConnectMessage"; this.CONNECT_HEADER_SIZE = 12; this.protocolId = "RCloud"; this.binaryHelper = new RongIMLib.BinaryHelper(); this.protocolVersion = 3; switch (arguments.length) { case 0: case 1: case 3: if (!arguments[0] || arguments[0].length > 64) { throw new Error("ConnectMessage:Client Id cannot be null and must be at most 64 characters long: " + arguments[0]); } this.clientId = arguments[0]; this.cleanSession = arguments[1]; this.keepAlive = arguments[2]; break; } } ConnectMessage.prototype.messageLength = function () { var payloadSize = this.binaryHelper.toMQttString(this.clientId).length; payloadSize += this.binaryHelper.toMQttString(this.willTopic).length; payloadSize += this.binaryHelper.toMQttString(this.will).length; payloadSize += this.binaryHelper.toMQttString(this.appId).length; payloadSize += this.binaryHelper.toMQttString(this.token).length; return payloadSize + this.CONNECT_HEADER_SIZE; }; ConnectMessage.prototype.readMessage = function (stream) { this.protocolId = stream.readUTF(); this.protocolVersion = stream.readByte(); var cFlags = stream.readByte(); this.hasAppId = (cFlags & 128) > 0; this.hasToken = (cFlags & 64) > 0; this.retainWill = (cFlags & 32) > 0; this.willQos = cFlags >> 3 & 3; this.hasWill = (cFlags & 4) > 0; this.cleanSession = (cFlags & 32) > 0; this.keepAlive = stream.read() * 256 + stream.read(); this.clientId = stream.readUTF(); if (this.hasWill) { this.willTopic = stream.readUTF(); this.will = stream.readUTF(); } if (this.hasAppId) { try { this.appId = stream.readUTF(); } catch (ex) { throw new Error(ex); } } if (this.hasToken) { try { this.token = stream.readUTF(); } catch (ex) { throw new Error(ex); } } return stream; }; ConnectMessage.prototype.writeMessage = function (out) { var stream = this.binaryHelper.convertStream(out); stream.writeUTF(this.protocolId); stream.write(this.protocolVersion); var flags = this.cleanSession ? 2 : 0; flags |= this.hasWill ? 4 : 0; flags |= this.willQos ? this.willQos >> 3 : 0; flags |= this.retainWill ? 32 : 0; flags |= this.hasToken ? 64 : 0; flags |= this.hasAppId ? 128 : 0; stream.write(flags); stream.writeChar(this.keepAlive); stream.writeUTF(this.clientId); if (this.hasWill) { stream.writeUTF(this.willTopic); stream.writeUTF(this.will); } if (this.hasAppId) { stream.writeUTF(this.appId); } if (this.hasToken) { stream.writeUTF(this.token); } return stream; }; return ConnectMessage; })(BaseMessage); RongIMLib.ConnectMessage = ConnectMessage; /** *连接应答类型 */ var ConnAckMessage = (function (_super) { __extends(ConnAckMessage, _super); function ConnAckMessage(header) { _super.call(this, arguments.length == 0 ? RongIMLib.Type.CONNACK : arguments.length == 1 ? arguments[0] instanceof RongIMLib.Header ? arguments[0] : RongIMLib.Type.CONNACK : null); this._name = "ConnAckMessage"; this.MESSAGE_LENGTH = 2; this.binaryHelper = new RongIMLib.BinaryHelper(); var me = this; switch (arguments.length) { case 0: case 1: if (!(arguments[0] instanceof RongIMLib.Header)) { if (arguments[0] in RongIMLib.ConnectionState) { if (arguments[0] == null) { throw new Error("ConnAckMessage:The status of ConnAskMessage can't be null"); } me.setStatus(arguments[0]); } } break; } } ; ConnAckMessage.prototype.messageLength = function () { var length = this.MESSAGE_LENGTH; if (this.userId) { length += this.binaryHelper.toMQttString(this.userId).length; } return length; }; ; ConnAckMessage.prototype.readMessage = function (_in, msglength) { _in.read(); var result = +_in.read(); if (result >= 0 && result <= 12) { this.setStatus(result); } else { throw new Error("Unsupported CONNACK code:" + result); } if (msglength > this.MESSAGE_LENGTH) { this.setUserId(_in.readUTF()); var sessionId = _in.readUTF(); var timestamp = _in.readLong(); this.setTimestamp(timestamp); } }; ; ConnAckMessage.prototype.writeMessage = function (out) { var stream = this.binaryHelper.convertStream(out); stream.write(128); switch (+status) { case 0: case 1: case 2: case 5: case 6: stream.write(+status); break; case 3: case 4: stream.write(3); break; default: throw new Error("Unsupported CONNACK code:" + status); } if (this.userId) { stream.writeUTF(this.userId); } return stream; }; ; ConnAckMessage.prototype.setStatus = function (x) { this.status = x; }; ; ConnAckMessage.prototype.setUserId = function (_userId) { this.userId = _userId; }; ; ConnAckMessage.prototype.getStatus = function () { return this.status; }; ; ConnAckMessage.prototype.getUserId = function () { return this.userId; }; ; ConnAckMessage.prototype.setTimestamp = function (x) { this.timestrap = x; }; ; ConnAckMessage.prototype.getTimestamp = function () { return this.timestrap; }; return ConnAckMessage; })(BaseMessage); RongIMLib.ConnAckMessage = ConnAckMessage; /** *断开消息类型 */ var DisconnectMessage = (function (_super) { __extends(DisconnectMessage, _super); function DisconnectMessage(header) { _super.call(this, header instanceof RongIMLib.Header ? header : RongIMLib.Type.DISCONNECT); this._name = "DisconnectMessage"; this.MESSAGE_LENGTH = 2; this.binaryHelper = new RongIMLib.BinaryHelper(); if (!(header instanceof RongIMLib.Header)) { if (header in RongIMLib.ConnectionStatus) { this.status = header; } } } DisconnectMessage.prototype.messageLength = function () { return this.MESSAGE_LENGTH; }; DisconnectMessage.prototype.readMessage = function (_in) { _in.read(); var result = +_in.read(); if (result >= 0 && result <= 5) { this.setStatus(disconnectStatus[result] ? disconnectStatus[result] : result); } else { throw new Error("Unsupported CONNACK code:" + result); } }; DisconnectMessage.prototype.writeMessage = function (Out) { var out = this.binaryHelper.convertStream(Out); out.write(0); if (+status >= 1 && +status <= 3) { out.write((+status) - 1); } else { throw new Error("Unsupported CONNACK code:" + status); } }; DisconnectMessage.prototype.setStatus = function (x) { this.status = x; }; ; DisconnectMessage.prototype.getStatus = function () { return this.status; }; ; return DisconnectMessage; })(BaseMessage); RongIMLib.DisconnectMessage = DisconnectMessage; /** *请求消息信令 */ var PingReqMessage = (function (_super) { __extends(PingReqMessage, _super); function PingReqMessage(header) { _super.call(this, (header && header instanceof RongIMLib.Header) ? header : RongIMLib.Type.PINGREQ); this._name = "PingReqMessage"; } return PingReqMessage; })(BaseMessage); RongIMLib.PingReqMessage = PingReqMessage; /** *响应消息信令 */ var PingRespMessage = (function (_super) { __extends(PingRespMessage, _super); function PingRespMessage(header) { _super.call(this, (header && header instanceof RongIMLib.Header) ? header : RongIMLib.Type.PINGRESP); this._name = "PingRespMessage"; } return PingRespMessage; })(BaseMessage); RongIMLib.PingRespMessage = PingRespMessage; /** *封装MesssageId */ var RetryableMessage = (function (_super) { __extends(RetryableMessage, _super); function RetryableMessage(argu) { _super.call(this, argu); this._name = "RetryableMessage"; this.binaryHelper = new RongIMLib.BinaryHelper(); } RetryableMessage.prototype.messageLength = function () { return 2; }; RetryableMessage.prototype.writeMessage = function (Out) { var out = this.binaryHelper.convertStream(Out), Id = this.getMessageId(), lsb = Id & 255, msb = (Id & 65280) >> 8; out.write(msb); out.write(lsb); return out; }; RetryableMessage.prototype.readMessage = function (_in, msgLength) { var msgId = _in.read() * 256 + _in.read(); this.setMessageId(parseInt(msgId, 10)); }; RetryableMessage.prototype.setMessageId = function (_messageId) { this.messageId = _messageId; }; RetryableMessage.prototype.getMessageId = function () { return this.messageId; }; return RetryableMessage; })(BaseMessage); RongIMLib.RetryableMessage = RetryableMessage; /** *发送消息应答(双向) *qos为1必须给出应答(所有消息类型一样) */ var PubAckMessage = (function (_super) { __extends(PubAckMessage, _super); function PubAckMessage(header) { _super.call(this, (header instanceof RongIMLib.Header) ? header : RongIMLib.Type.PUBACK); this.msgLen = 2; this.date = 0; this.millisecond = 0; this.timestamp = 0; this.binaryHelper = new RongIMLib.BinaryHelper(); this._name = "PubAckMessage"; if (!(header instanceof RongIMLib.Header)) { _super.prototype.setMessageId.call(this, header); } } PubAckMessage.prototype.messageLength = function () { return this.msgLen; }; PubAckMessage.prototype.writeMessage = function (Out) { var out = this.binaryHelper.convertStream(Out); RetryableMessage.prototype.writeMessage.call(this, out); }; PubAckMessage.prototype.readMessage = function (_in, msgLength) { RetryableMessage.prototype.readMessage.call(this, _in); this.date = _in.readInt(); this.status = _in.read() * 256 + _in.read(); this.millisecond = _in.read() * 256 + _in.read(); this.timestamp = this.date * 1000 + this.millisecond; this.messageUId = _in.readUTF(); }; PubAckMessage.prototype.setStatus = function (x) { this.status = x; }; PubAckMessage.prototype.setTimestamp = function (timestamp) { this.timestamp = timestamp; }; PubAckMessage.prototype.setMessageUId = function (messageUId) { this.messageUId = messageUId; }; PubAckMessage.prototype.getStatus = function () { return this.status; }; PubAckMessage.prototype.getDate = function () { return this.date; }; PubAckMessage.prototype.getTimestamp = function () { return this.timestamp; }; PubAckMessage.prototype.getMessageUId = function () { return this.messageUId; }; return PubAckMessage; })(RetryableMessage); RongIMLib.PubAckMessage = PubAckMessage; /** *发布消息 */ var PublishMessage = (function (_super) { __extends(PublishMessage, _super); function PublishMessage(header, two, three) { _super.call(this, (arguments.length == 1 && header instanceof RongIMLib.Header) ? header : arguments.length == 3 ? RongIMLib.Type.PUBLISH : 0); this._name = "PublishMessage"; this.binaryHelper = new RongIMLib.BinaryHelper(); this.syncMsg = false; if (arguments.length == 3) { this.topic = header; this.targetId = three; this.data = typeof two == "string" ? this.binaryHelper.toMQttString(two) : two; } } PublishMessage.prototype.messageLength = function () { var length = 10; length += this.binaryHelper.toMQttString(this.topic).length; length += this.binaryHelper.toMQttString(this.targetId).length; length += this.data.length; return length; }; PublishMessage.prototype.writeMessage = function (Out) { var out = this.binaryHelper.convertStream(Out); out.writeUTF(this.topic); out.writeUTF(this.targetId); RetryableMessage.prototype.writeMessage.apply(this, arguments); out.write(this.data); }; ; PublishMessage.prototype.readMessage = function (_in, msgLength) { var pos = 6; this.date = _in.readInt(); this.topic = _in.readUTF(); pos += this.binaryHelper.toMQttString(this.topic).length; this.targetId = _in.readUTF(); pos += this.binaryHelper.toMQttString(this.targetId).length; RetryableMessage.prototype.readMessage.apply(this, arguments); this.data = new Array(msgLength - pos); this.data = _in.read(this.data); }; ; PublishMessage.prototype.setTopic = function (x) { this.topic = x; }; PublishMessage.prototype.setData = function (x) { this.data = x; }; PublishMessage.prototype.setTargetId = function (x) { this.targetId = x; }; PublishMessage.prototype.setDate = function (x) { this.date = x; }; PublishMessage.prototype.setSyncMsg = function (x) { this.syncMsg = x; }; //是否是其他端同步过来的消息 PublishMessage.prototype.getSyncMsg = function () { return this.syncMsg; }; PublishMessage.prototype.getTopic = function () { return this.topic; }; PublishMessage.prototype.getData = function () { return this.data; }; PublishMessage.prototype.getTargetId = function () { return this.targetId; }; PublishMessage.prototype.getDate = function () { return this.date; }; return PublishMessage; })(RetryableMessage); RongIMLib.PublishMessage = PublishMessage; /** *请求查询 */ var QueryMessage = (function (_super) { __extends(QueryMessage, _super); function QueryMessage(header, two, three) { _super.call(this, header instanceof RongIMLib.Header ? header : arguments.length == 3 ? RongIMLib.Type.QUERY : null); this.binaryHelper = new RongIMLib.BinaryHelper(); this._name = "QueryMessage"; if (arguments.length == 3) { this.data = typeof two == "string" ? this.binaryHelper.toMQttString(two) : two; this.topic = header; this.targetId = three; } } QueryMessage.prototype.messageLength = function () { var length = 0; length += this.binaryHelper.toMQttString(this.topic).length; length += this.binaryHelper.toMQttString(this.targetId).length; length += 2; length += this.data.length; return length; }; QueryMessage.prototype.writeMessage = function (Out) { var out = this.binaryHelper.convertStream(Out); out.writeUTF(this.topic); out.writeUTF(this.targetId); RetryableMessage.prototype.writeMessage.call(this, out); out.write(this.data); }; QueryMessage.prototype.readMessage = function (_in, msgLength) { var pos = 0; this.topic = _in.readUTF(); this.targetId = _in.readUTF(); pos += this.binaryHelper.toMQttString(this.topic).length; pos += this.binaryHelper.toMQttString(this.targetId).length; this.readMessage.apply(this, arguments); pos += 2; this.data = new Array(msgLength - pos); _in.read(this.data); }; QueryMessage.prototype.setTopic = function (x) { this.topic = x; }; QueryMessage.prototype.setData = function (x) { this.data = x; }; QueryMessage.prototype.setTargetId = function (x) { this.targetId = x; }; QueryMessage.prototype.getTopic = function () { return this.topic; }; QueryMessage.prototype.getData = function () { return this.data; }; QueryMessage.prototype.getTargetId = function () { return this.targetId; }; return QueryMessage; })(RetryableMessage); RongIMLib.QueryMessage = QueryMessage; /** *请求查询确认 */ var QueryConMessage = (function (_super) { __extends(QueryConMessage, _super); function QueryConMessage(messageId) { _super.call(this, (messageId instanceof RongIMLib.Header) ? messageId : RongIMLib.Type.QUERYCON); this._name = "QueryConMessage"; if (!(messageId instanceof RongIMLib.Header)) { _super.prototype.setMessageId.call(this, messageId); } } return QueryConMessage; })(RetryableMessage); RongIMLib.QueryConMessage = QueryConMessage; /** *请求查询应答 */ var QueryAckMessage = (function (_super) { __extends(QueryAckMessage, _super); function QueryAckMessage(header) { _super.call(this, header); this._name = "QueryAckMessage"; this.binaryHelper = new RongIMLib.BinaryHelper(); } QueryAckMessage.prototype.readMessage = function (In, msgLength) { RetryableMessage.prototype.readMessage.call(this, In); this.date = In.readInt(); this.setStatus(In.read() * 256 + In.read()); if (msgLength > 0) { this.data = new Array(msgLength - 8); this.data = In.read(this.data); } }; QueryAckMessage.prototype.getData = function () { return this.data; }; QueryAckMessage.prototype.getStatus = function () { return this.status; }; QueryAckMessage.prototype.getDate = function () { return this.date; }; QueryAckMessage.prototype.setDate = function (x) { this.date = x; }; QueryAckMessage.prototype.setStatus = function (x) { this.status = x; }; QueryAckMessage.prototype.setData = function (x) { this.data = x; }; return QueryAckMessage; })(RetryableMessage); RongIMLib.QueryAckMessage = QueryAckMessage; })(RongIMLib || (RongIMLib = {})); /// var RongIMLib; (function (RongIMLib) { /** * 把消息对象写入流中 * 发送消息时用到 */ var MessageOutputStream = (function () { function MessageOutputStream(_out) { var binaryHelper = new RongIMLib.BinaryHelper(); this.out = binaryHelper.convertStream(_out); } MessageOutputStream.prototype.writeMessage = function (msg) { if (msg instanceof RongIMLib.BaseMessage) { msg.write(this.out); } }; return MessageOutputStream; })(); RongIMLib.MessageOutputStream = MessageOutputStream; /** * 流转换为消息对象 * 服务器返回消息时用到 */ var MessageInputStream = (function () { function MessageInputStream(In, isPolling) { if (!isPolling) { var _in = new RongIMLib.BinaryHelper().convertStream(In); this.flags = _in.readByte(); this._in = _in; } else { this.flags = In["headerCode"]; } this.header = new RongIMLib.Header(this.flags); this.isPolling = isPolling; this.In = In; } MessageInputStream.prototype.readMessage = function () { switch (this.header.getType()) { case 1: this.msg = new RongIMLib.ConnectMessage(this.header); break; case 2: this.msg = new RongIMLib.ConnAckMessage(this.header); break; case 3: this.msg = new RongIMLib.PublishMessage(this.header); this.msg.setSyncMsg(this.header.getSyncMsg()); break; case 4: this.msg = new RongIMLib.PubAckMessage(this.header); break; case 5: this.msg = new RongIMLib.QueryMessage(this.header); break; case 6: this.msg = new RongIMLib.QueryAckMessage(this.header); break; case 7: this.msg = new RongIMLib.QueryConMessage(this.header); break; case 9: case 11: case 13: this.msg = new RongIMLib.PingRespMessage(this.header); break; case 8: case 10: case 12: this.msg = new RongIMLib.PingReqMessage(this.header); break; case 14: this.msg = new RongIMLib.DisconnectMessage(this.header); break; default: throw new Error("No support for deserializing " + this.header.getType() + " messages"); } if (this.isPolling) { this.msg.init(this.In); } else { this.msg.read(this._in, this.In.length - 1); } return this.msg; }; return MessageInputStream; })(); RongIMLib.MessageInputStream = MessageInputStream; var Header = (function () { function Header(_type, _retain, _qos, _dup) { this.retain = false; this.qos = RongIMLib.Qos.AT_LEAST_ONCE; this.dup = false; this.syncMsg = false; if (_type && +_type == _type && arguments.length == 1) { this.retain = (_type & 1) > 0; this.qos = (_type & 6) >> 1; this.dup = (_type & 8) > 0; this.type = (_type >> 4) & 15; this.syncMsg = (_type & 8) == 8; } else { this.type = _type; this.retain = _retain; this.qos = _qos; this.dup = _dup; } } Header.prototype.getSyncMsg = function () { return this.syncMsg; }; Header.prototype.getType = function () { return this.type; }; Header.prototype.encode = function () { var me = this; switch (this.qos) { case RongIMLib.Qos[0]: me.qos = RongIMLib.Qos.AT_MOST_ONCE; break; case RongIMLib.Qos[1]: me.qos = RongIMLib.Qos.AT_LEAST_ONCE; break; case RongIMLib.Qos[2]: me.qos = RongIMLib.Qos.EXACTLY_ONCE; break; case RongIMLib.Qos[3]: me.qos = RongIMLib.Qos.DEFAULT; break; } var _byte = (this.type << 4); _byte |= this.retain ? 1 : 0; _byte |= this.qos << 1; _byte |= this.dup ? 8 : 0; return _byte; }; Header.prototype.toString = function () { return "Header [type=" + this.type + ",retain=" + this.retain + ",qos=" + this.qos + ",dup=" + this.dup + "]"; }; return Header; })(); RongIMLib.Header = Header; /** * 二进制帮助对象 */ var BinaryHelper = (function () { function BinaryHelper() { } BinaryHelper.prototype.writeUTF = function (str, isGetBytes) { var back = [], byteSize = 0; for (var i = 0, len = str.length; i < len; i++) { var code = str.charCodeAt(i); if (code >= 0 && code <= 127) { byteSize += 1; back.push(code); } else if (code >= 128 && code <= 2047) { byteSize += 2; back.push((192 | (31 & (code >> 6)))); back.push((128 | (63 & code))); } else if (code >= 2048 && code <= 65535) { byteSize += 3; back.push((224 | (15 & (code >> 12)))); back.push((128 | (63 & (code >> 6)))); back.push((128 | (63 & code))); } } for (var i = 0, len = back.length; i < len; i++) { if (back[i] > 255) { back[i] &= 255; } } if (isGetBytes) { return back; } if (byteSize <= 255) { return [0, byteSize].concat(back); } else { return [byteSize >> 8, byteSize & 255].concat(back); } }; BinaryHelper.prototype.readUTF = function (arr) { if (Object.prototype.toString.call(arr) == "[object String]") { return arr; } var UTF = "", _arr = arr; for (var i = 0, len = _arr.length; i < len; i++) { if (_arr[i] < 0) { _arr[i] += 256; } ; var one = _arr[i].toString(2), v = one.match(/^1+?(?=0)/); if (v && one.length == 8) { var bytesLength = v[0].length, // store = _arr[i].toString(2).slice(7 - bytesLength); store = ''; for (var st = 0; st < bytesLength; st++) { store += _arr[st + i].toString(2).slice(2); } UTF += String.fromCharCode(parseInt(store, 2)); i += bytesLength - 1; } else { UTF += String.fromCharCode(_arr[i]); } } return UTF; }; /** * [convertStream 将参数x转化为RongIMStream对象] * @param {any} x [参数] */ BinaryHelper.prototype.convertStream = function (x) { if (x instanceof RongIMStream) { return x; } else { return new RongIMStream(x); } }; BinaryHelper.prototype.toMQttString = function (str) { return this.writeUTF(str); }; return BinaryHelper; })(); RongIMLib.BinaryHelper = BinaryHelper; var RongIMStream = (function () { function RongIMStream(arr) { //当前流执行的起始位置 this.position = 0; //当前流写入的多少字节 this.writen = 0; this.poolLen = 0; this.binaryHelper = new BinaryHelper(); this.pool = arr; this.poolLen = arr.length; } RongIMStream.prototype.check = function () { return this.position >= this.pool.length; }; RongIMStream.prototype.readInt = function () { if (this.check()) { return -1; } var end = ""; for (var i = 0; i < 4; i++) { var t = this.pool[this.position++].toString(16); if (t.length == 1) { t = "0" + t; } end += t.toString(16); } return parseInt(end, 16); }; RongIMStream.prototype.readLong = function () { if (this.check()) { return -1; } var end = ""; for (var i = 0; i < 8; i++) { var t = this.pool[this.position++].toString(16); if (t.length == 1) { t = "0" + t; } end += t; } return parseInt(end, 16); }; RongIMStream.prototype.readTimestamp = function () { if (this.check()) { return -1; } var end = ""; for (var i = 0; i < 8; i++) { end += this.pool[this.position++].toString(16); } end = end.substring(2, 8); return parseInt(end, 16); }; RongIMStream.prototype.readUTF = function () { if (this.check()) { return -1; } var big = (this.readByte() << 8) | this.readByte(); return this.binaryHelper.readUTF(this.pool.subarray(this.position, this.position += big)); }; RongIMStream.prototype.readByte = function () { if (this.check()) { return -1; } var val = this.pool[this.position++]; if (val > 255) { val &= 255; } return val; }; RongIMStream.prototype.read = function (bytesArray) { if (bytesArray) { return this.pool.subarray(this.position, this.poolLen); } else { return this.readByte(); } }; RongIMStream.prototype.write = function (_byte) { var b = _byte; if (Object.prototype.toString.call(b).toLowerCase() == "[object array]") { try { this.pool = this.pool.concat(b); } catch (e) { [].push.apply(this.pool, b); } } else { if (+b == b) { if (b > 255) { b &= 255; } this.pool.push(b); this.writen++; } } return b; }; RongIMStream.prototype.writeChar = function (v) { if (+v != v) { throw new Error("writeChar:arguments type is error"); } this.write(v >> 8 & 255); this.write(v & 255); this.writen += 2; }; RongIMStream.prototype.writeUTF = function (str) { var val = this.binaryHelper.writeUTF(str); [].push.apply(this.pool, val); this.writen += val.length; }; RongIMStream.prototype.toComplements = function () { var _tPool = this.pool; for (var i = 0; i < this.poolLen; i++) { if (_tPool[i] > 128) { _tPool[i] -= 256; } } return _tPool; }; RongIMStream.prototype.getBytesArray = function (isCom) { if (isCom) { return this.toComplements(); } return this.pool; }; return RongIMStream; })(); RongIMLib.RongIMStream = RongIMStream; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var SocketTransportation = (function () { /** * [constructor] * @param {string} url [连接地址:包含token、version] */ function SocketTransportation(_socket) { //连接状态 true:已连接 false:未连接 this.connected = false; //是否关闭: true:已关闭 false:未关闭 this.isClose = false; //存放消息队列的临时变量 this.queue = []; this.empty = new Function; this._socket = _socket; return this; } /** * [createTransport 创建WebScoket对象] */ SocketTransportation.prototype.createTransport = function (url, method) { if (!url) { throw new Error("URL can't be empty"); } ; this.url = url; var depend = RongIMLib.RongIMClient._memoryStore.depend; var wsScheme = depend.wsScheme; var tpl = '{wsScheme}{url}'; url = RongIMLib.RongUtil.tplEngine(tpl, { wsScheme: wsScheme, url: url }); this.socket = new WebSocket(url); this.socket.binaryType = "arraybuffer"; this.addEvent(); return this.socket; }; /** * [send 传送消息流] * @param {ArrayBuffer} data [二进制消息流] */ SocketTransportation.prototype.send = function (data) { if (!this.connected && !this.isClose) { //当通道不可用时,加入消息队列 this.queue.push(data); return; } if (this.isClose) { this._socket.fire("StatusChanged", RongIMLib.ConnectionStatus.CONNECTION_CLOSED); return; } var stream = new RongIMLib.RongIMStream([]), msg = new RongIMLib.MessageOutputStream(stream); msg.writeMessage(data); var val = stream.getBytesArray(true); var binary = new Int8Array(val); this.socket.send(binary.buffer); return this; }; /** * [onData 通道返回数据时调用的方法,用来想上层传递服务器返回的二进制消息流] * @param {ArrayBuffer} data [二进制消息流] */ SocketTransportation.prototype.onData = function (data) { if (RongIMLib.MessageUtil.isArray(data)) { this._socket.onMessage(new RongIMLib.MessageInputStream(data).readMessage()); } else { this._socket.onMessage(new RongIMLib.MessageInputStream(RongIMLib.MessageUtil.ArrayFormInput(data)).readMessage()); } return ""; }; /** * [onClose 通道关闭时触发的方法] */ SocketTransportation.prototype.onClose = function (ev) { var me = this; me.isClose = true; me.socket = this.empty; RongIMLib.Bridge._client.clearHeartbeat(); if (ev.code == 1006 && !this._status) { var currentTime = new Date().getTime(); if (currentTime - me.connectedTime <= SocketTransportation.MinConnectTime) { var host = RongIMLib.RongUtil.getUrlHost(me.url); RongIMLib.RongIMClient.invalidWsUrls.push(host); } me._socket.fire("StatusChanged", RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE); } else { me._status = 0; } }; /** * [onError 通道报错时触发的方法] * @param {any} error [抛出异常] */ SocketTransportation.prototype.onError = function (error) { this._socket.fire("StatusChanged", RongIMLib.ConnectionStatus.WEBSOCKET_ERROR); RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.L_CRAW_F, level: RongIMLib.LoggerLevel.E, type: RongIMLib.LoggerType.IM, content: { error: RongIMLib.ConnectionStatus.WEBSOCKET_ERROR, msg: 'SocketTransportation -> onError' } }); throw new Error(error); }; /** * [addEvent 为通道绑定事件] */ SocketTransportation.prototype.addEvent = function () { var self = this; self.socket.onopen = function () { self.connected = true; self.isClose = false; //通道可以用后,调用发送队列方法,把所有等得发送的消息发出 self.doQueue(); self._socket.fire("connect"); self.connectedTime = new Date().getTime(); }; self.socket.onmessage = function (ev) { //判断数据是不是字符串,如果是字符串那么就是flash传过来的。 if (typeof ev.data == "string") { self.onData(ev.data.split(",")); } else { self.onData(ev.data); } }; self.socket.onerror = function (ev) { self.onError(ev); }; self.socket.onclose = function (ev) { self.onClose(ev); }; }; /** * [doQueue 消息队列,把队列中消息发出] */ SocketTransportation.prototype.doQueue = function () { var self = this; for (var i = 0, len = self.queue.length; i < len; i++) { self.send(self.queue[i]); } }; /** * [disconnect 断开连接] */ SocketTransportation.prototype.disconnect = function (status) { var me = this; if (me.socket.readyState) { me.isClose = true; if (status) { me._status = status; } me.socket.close(); } }; /** * [reconnect 重新连接] */ SocketTransportation.prototype.reconnect = function () { this.disconnect(); this.createTransport(this.url); }; SocketTransportation.prototype.close = function () { this.socket.close(); }; // 最短链接时长(若 5000ms 内, ws 自动断开, 此 ws 地址置为不可用) SocketTransportation.MinConnectTime = 5000; return SocketTransportation; })(); RongIMLib.SocketTransportation = SocketTransportation; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var PollingTransportation = (function () { function PollingTransportation(socket) { this.empty = new Function; this.connected = false; this.pid = +new Date + Math.random() + ""; this.queue = []; this.socket = socket; return this; } PollingTransportation.prototype.createTransport = function (url, method) { if (!url) { throw new Error("Url is empty,Please check it!"); } ; this.url = url; var sid = RongIMLib.RongIMClient._storageProvider.getItem("sId" + RongIMLib.Navigation.Endpoint.userId), me = this; if (sid) { setTimeout(function () { me.onSuccess("{\"status\":0,\"userId\":\"" + RongIMLib.Navigation.Endpoint.userId + "\",\"headerCode\":32,\"messageId\":0,\"sessionid\":\"" + sid + "\"}"); me.connected = true; }, 500); return this; } this.getRequest(url, true); return this; }; PollingTransportation.prototype.requestFactory = function (url, method, multipart) { var reqest = this.XmlHttpRequest(); if (multipart) { reqest.multipart = true; } // reqest.timeout = 60000; reqest.open(method || "GET", RongIMLib.RongIMClient._memoryStore.depend.protocol + url); if (method == "POST" && "setRequestHeader" in reqest) { reqest.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=utf-8"); } return reqest; }; PollingTransportation.prototype.getRequest = function (url, isconnect) { var me = this; me.xhr = this.requestFactory(url + "&pid=" + encodeURIComponent(me.pid), "GET"); var timer = new RongIMLib.Timer({ timeout: 45000 }); if ("onload" in me.xhr) { me.xhr.onload = function () { timer.pause(); me.xhr.onload = me.empty; if (this.responseText == "lost params") { me.onError(); } else { me.onSuccess(this.responseText, isconnect); } }; me.xhr.onerror = function () { timer.pause(); me.disconnect(); }; } else { me.xhr.onreadystatechange = function () { timer.pause(); if (me.xhr.readyState == 4) { me.xhr.onreadystatechange = me.empty; if (/^(200|202)$/.test(me.xhr.status)) { me.onSuccess(me.xhr.responseText, isconnect); } else if (/^(400|403)$/.test(me.xhr.status)) { me.onError(); } else { me.disconnect(); } } }; } timer.resume(function () { me.onError(); }); me.xhr.send(); }; /** * [send 发送消息,Method:POST] * queue 为消息队列,待通道可用发送所有等待消息 * @param {string} data [需要传入comet格式数据,此处只负责通讯通道,数据转换在外层处理] */ PollingTransportation.prototype.send = function (data) { var me = this; var _send = me.sendxhr = this.requestFactory(RongIMLib.Navigation.Endpoint.host + "/websocket" + data.url + "&pid=" + encodeURIComponent(me.pid), "POST"); if ("onload" in _send) { _send.onload = function () { _send.onload = me.empty; me.onData(_send.responseText); }; _send.onerror = function () { _send.onerror = me.empty; }; } else { _send.onreadystatechange = function () { if (_send.readyState == 4) { this.onreadystatechange = this.empty; if (/^(202|200)$/.test(_send.status)) { me.onData(_send.responseText); } } }; } _send.send(JSON.stringify(data.data)); }; PollingTransportation.prototype.onData = function (data, header) { if (!data || data == "lost params") { return; } var self = this, val = JSON.parse(data); if (val.userId) { RongIMLib.Navigation.Endpoint.userId = val.userId; } if (header) { RongIMLib.RongIMClient._storageProvider.setItem("sId" + RongIMLib.Navigation.Endpoint.userId, header); } if (!RongIMLib.MessageUtil.isArray(val)) { val = [val]; } Array.forEach(val, function (m) { self.socket.fire("message", new RongIMLib.MessageInputStream(m, true).readMessage()); }); return ""; }; PollingTransportation.prototype.XmlHttpRequest = function () { var hasCORS = typeof XMLHttpRequest !== "undefined" && "withCredentials" in new XMLHttpRequest(), self = this; if ("undefined" != typeof XMLHttpRequest && hasCORS) { return new XMLHttpRequest(); } else if ("undefined" != typeof XDomainRequest) { return new XDomainRequest(); } else { return new ActiveXObject("Microsoft.XMLHTTP"); } }; PollingTransportation.prototype.onClose = function () { if (this.xhr) { if (this.xhr.onload) { this.xhr.onreadystatechange = this.xhr.onload = this.empty; } else { this.xhr.onreadystatechange = this.empty; } this.xhr.abort(); this.xhr = null; } if (this.sendxhr) { if (this.sendxhr.onload) { this.sendxhr.onreadystatechange = this.sendxhr.onload = this.empty; } else { this.sendxhr.onreadystatechange = this.empty; } this.sendxhr.abort(); this.sendxhr = null; } }; PollingTransportation.prototype.disconnect = function () { RongIMLib.RongIMClient._storageProvider.removeItem("sId" + RongIMLib.Navigation.Endpoint.userId); RongIMLib.RongIMClient._storageProvider.removeItem(RongIMLib.Navigation.Endpoint.userId + "msgId"); this.onClose(); }; PollingTransportation.prototype.reconnect = function () { this.disconnect(); this.createTransport(this.url); }; PollingTransportation.prototype.onSuccess = function (responseText, isconnect) { var txt = responseText.match(/"sessionid":"\S+?(?=")/); this.onData(responseText, txt ? txt[0].slice(13) : 0); if (/"headerCode":-32,/.test(responseText)) { RongIMLib.RongIMClient._storageProvider.removeItem("sId" + RongIMLib.Navigation.Endpoint.userId); RongIMLib.RongIMClient._storageProvider.removeItem(RongIMLib.Navigation.Endpoint.userId + "msgId"); return; } this.getRequest(RongIMLib.Navigation.Endpoint.host + "/pullmsg.js?sessionid=" + RongIMLib.RongIMClient._storageProvider.getItem("sId" + RongIMLib.Navigation.Endpoint.userId) + "×trap=" + encodeURIComponent(new Date().getTime() + Math.random() + "")); this.connected = true; isconnect && this.socket.fire("connect"); }; PollingTransportation.prototype.onError = function () { RongIMLib.RongIMClient._storageProvider.removeItem("sId" + RongIMLib.Navigation.Endpoint.userId); RongIMLib.RongIMClient._storageProvider.removeItem(RongIMLib.Navigation.Endpoint.userId + "msgId"); this.onClose(); if (this.connected) { this.connected = false; var code = RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE; this.socket.fire("disconnect", code); } }; PollingTransportation.prototype.close = function () { this.xhr.abort(); this.sendxhr = null; }; return PollingTransportation; })(); RongIMLib.PollingTransportation = PollingTransportation; })(RongIMLib || (RongIMLib = {})); //objectname映射 var typeMapping = { "RC:TxtMsg": "TextMessage", "RC:ImgMsg": "ImageMessage", "RC:VcMsg": "VoiceMessage", "RC:ImgTextMsg": "RichContentMessage", "RC:ReferenceMsg": "ReferenceMessage", "RC:FileMsg": "FileMessage", "RC:HQVCMsg": "HQVoiceMessage", "RC:GIFMsg": "GIFMessage", "RC:SightMsg": "SightMessage", "RC:LBSMsg": "LocationMessage", "RC:InfoNtf": "InformationNotificationMessage", "RC:ContactNtf": "ContactNotificationMessage", "RC:ProfileNtf": "ProfileNotificationMessage", "RC:CmdNtf": "CommandNotificationMessage", "RC:DizNtf": "DiscussionNotificationMessage", "RC:CmdMsg": "CommandMessage", "RC:TypSts": "TypingStatusMessage", "RC:CsChaR": "ChangeModeResponseMessage", "RC:CsHsR": "HandShakeResponseMessage", "RC:CsEnd": "TerminateMessage", "RC:CsSp": "SuspendMessage", "RC:CsUpdate": "CustomerStatusUpdateMessage", "RC:ReadNtf": "ReadReceiptMessage", "RC:VCAccept": "AcceptMessage", "RC:VCRinging": "RingingMessage", "RC:VCSummary": "SummaryMessage", "RC:VCHangup": "HungupMessage", "RC:VCInvite": "InviteMessage", "RC:VCModifyMedia": "MediaModifyMessage", "RC:VCModifyMem": "MemberModifyMessage", "RC:CsContact": "CustomerContact", "RC:PSImgTxtMsg": "PublicServiceRichContentMessage", "RC:PSMultiImgTxtMsg": "PublicServiceMultiRichContentMessage", "RC:GrpNtf": "GroupNotificationMessage", "RC:PSCmd": "PublicServiceCommandMessage", "RC:RcCmd": "RecallCommandMessage", "RC:SRSMsg": "SyncReadStatusMessage", "RC:RRReqMsg": "ReadReceiptRequestMessage", "RC:RRRspMsg": "ReadReceiptResponseMessage", "RCJrmf:RpMsg": "JrmfRedPacketMessage", "RCJrmf:RpOpendMsg": "JrmfRedPacketOpenedMessage", "RC:CombineMsg": "RCCombineMessage", "RC:chrmKVNotiMsg": "ChrmKVNotificationMessage", "RC:LogCmdMsg": "LogCommandMessage" }, //自定义消息类型 registerMessageTypeMapping = {}, HistoryMsgType = { 4: "qryCMsg", 2: "qryDMsg", 3: "qryGMsg", 1: "qryPMsg", 6: "qrySMsg", 7: "qryPMsg", 8: "qryPMsg", 5: "qryCMsg" }, disconnectStatus = { 1: 6 }; var RongIMLib; (function (RongIMLib) { // 业务层公共方法处理 var IMHandler = (function () { function IMHandler() { } IMHandler.isIncludeNavi = function (token) { var navMarkIndex = RongIMLib.RongUtil.indexOf(token, RongIMLib.RongIMClient.NavMarkInToken); var hasNavMark = navMarkIndex !== -1; return hasNavMark; }; IMHandler.getToken = function (token) { var isIncludeNavi = IMHandler.isIncludeNavi(token); if (isIncludeNavi) { var navMarkIndex = RongIMLib.RongUtil.indexOf(token, RongIMLib.RongIMClient.NavMarkInToken); ; token = token.substring(0, navMarkIndex + 1); } return token; }; IMHandler.getNavsByToken = function (token, protocol) { var isIncludeNavi = IMHandler.isIncludeNavi(token); var navUrlList = []; if (isIncludeNavi) { var navMarkIndex = RongIMLib.RongUtil.indexOf(token, RongIMLib.RongIMClient.NavMarkInToken); ; var navsText = token.substring(navMarkIndex + 1, token.length); var navDomains = navsText.split(RongIMLib.RongIMClient.NavSeparatorInToken); RongIMLib.RongUtil.forEach(navDomains, function (domain) { if (RongIMLib.RongUtil.isEmpty(domain)) { return; } var navUrl = RongIMLib.RongUtil.formatProtoclPath({ path: domain, protocol: protocol, sub: true }); navUrlList.push(navUrl); }); } return navUrlList; }; IMHandler.getConversationKey = function (type, id) { return type + '_' + id; }; return IMHandler; })(); RongIMLib.IMHandler = IMHandler; ; /** * 通道标识类 */ var Transportations = (function () { function Transportations() { } Transportations._TransportType = RongIMLib.Socket.WEBSOCKET; return Transportations; })(); RongIMLib.Transportations = Transportations; var SyncTimeUtil = (function () { function SyncTimeUtil() { } SyncTimeUtil.$getKey = function (message) { var client = RongIMLib.Bridge._client; var userId = client.userId; var direction = (message.messageDirection == 1 ? 'send' : 'receive'); var appkey = RongIMLib.RongIMClient._memoryStore.appKey; var tpl = '{appkey}_{userId}_{direction}box'; return RongIMLib.RongUtil.tplEngine(tpl, { appkey: appkey, userId: userId, direction: direction }); }; SyncTimeUtil.set = function (message) { var key = SyncTimeUtil.$getKey(message); var sentTime = message.sentTime; var storage = RongIMLib.RongIMClient._storageProvider; storage.setItem(key, sentTime); }; SyncTimeUtil.get = function () { var sent = SyncTimeUtil.$getKey({ messageDirection: RongIMLib.MessageDirection.SEND }); var received = SyncTimeUtil.$getKey({ messageDirection: RongIMLib.MessageDirection.RECEIVE }); var storage = RongIMLib.RongIMClient._storageProvider; return { sent: Number(storage.getItem(sent) || 0), received: Number(storage.getItem(received) || 0) }; }; return SyncTimeUtil; })(); RongIMLib.SyncTimeUtil = SyncTimeUtil; var MessageUtil = (function () { function MessageUtil() { } /** *4680000 为localstorage最小容量5200000字节的90%,超过90%将删除之前过早的存储 */ MessageUtil.checkStorageSize = function () { return JSON.stringify(localStorage).length < 4680000; }; MessageUtil.getFirstKey = function (obj) { var str = ""; for (var key in obj) { str = key; break; } return str; }; MessageUtil.isEmpty = function (obj) { var empty = true; for (var key in obj) { empty = false; break; } return empty; }; MessageUtil.ArrayForm = function (typearray) { if (Object.prototype.toString.call(typearray) == "[object ArrayBuffer]") { var arr = new Int8Array(typearray); return [].slice.call(arr); } return typearray; }; MessageUtil.ArrayFormInput = function (typearray) { if (Object.prototype.toString.call(typearray) == "[object ArrayBuffer]") { var arr = new Uint8Array(typearray); return arr; } return typearray; }; MessageUtil.indexOf = function (arr, item, from) { for (var l = arr.length, i = (from < 0) ? Math.max(0, +from) : from || 0; i < l; i++) { if (arr[i] == item) { return i; } } return -1; }; MessageUtil.isArray = function (obj) { return Object.prototype.toString.call(obj) == "[object Array]"; }; //遍历,只能遍历数组 MessageUtil.forEach = function (arr, func) { if ([].forEach) { return function (arr, func) { [].forEach.call(arr, func); }; } else { return function (arr, func) { for (var i = 0; i < arr.length; i++) { func.call(arr, arr[i], i, arr); } }; } }; MessageUtil.remove = function (array, func) { for (var i = 0, len = array.length; i < len; i++) { if (func(array[i])) { return array.splice(i, 1)[0]; } } return null; }; MessageUtil.int64ToTimestamp = function (obj, isDate) { if (obj.low === undefined) { return obj; } var low = obj.low; if (low < 0) { low += 0xffffffff + 1; } low = low.toString(16); var timestamp = parseInt(obj.high.toString(16) + "00000000".replace(new RegExp("0{" + low.length + "}$"), low), 16); if (isDate) { return new Date(timestamp); } return timestamp; }; //消息转换方法 MessageUtil.messageParser = function (entity, onReceived, offlineMsg) { var message = new RongIMLib.Message(), content = entity.content, de, objectName = entity.classname, val, isUseDef = false; try { if (RongIMLib.RongIMClient._memoryStore.depend.isPolling) { val = new RongIMLib.BinaryHelper().readUTF(content.offset ? MessageUtil.ArrayForm(content.buffer).slice(content.offset, content.limit) : content); de = JSON.parse(val); } else { val = new RongIMLib.BinaryHelper().readUTF(content.offset ? MessageUtil.ArrayFormInput(content.buffer).subarray(content.offset, content.limit) : content); de = JSON.parse(val); } } catch (ex) { de = val; isUseDef = true; RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.L_CRAW_F, level: RongIMLib.LoggerLevel.E, type: RongIMLib.LoggerType.IM, content: { stack: ex, msg: 'MessageUtil -> messageParser' } }); } var IMLib = RongIMLib; //映射为具体消息对象 if (objectName in typeMapping) { var typeName = typeMapping[objectName]; message.content = new IMLib[typeName](de); message.messageType = typeMapping[objectName]; } else if (objectName in registerMessageTypeMapping) { var typeName = registerMessageTypeMapping[objectName]; var regMsg = new IMLib.RongIMClient.RegisterMessage[typeName](de); if (isUseDef) { message.content = regMsg.decode(de); } else { message.content = regMsg; } message.messageType = registerMessageTypeMapping[objectName]; } else { message.content = new RongIMLib.UnknownMessage({ content: de, objectName: objectName }); message.messageType = "UnknownMessage"; } //根据实体对象设置message对象] var dateTime = MessageUtil.int64ToTimestamp(entity.dataTime); if (dateTime > 0) { message.sentTime = dateTime; } else { message.sentTime = +new Date; } message.senderUserId = entity.fromUserId; message.conversationType = entity.type; if (entity.fromUserId == RongIMLib.Bridge._client.userId) { message.targetId = entity.groupId; } else { message.targetId = (/^[234]$/.test(entity.type || entity.getType()) ? entity.groupId : message.senderUserId); } var selfUserId = RongIMLib.Bridge._client.userId; // 解决多端在线收自己发的消息时, messageDirection 为 2(接收), 导致未读数增加 var isSelfSend = entity.direction == 1 || message.senderUserId === selfUserId; if (isSelfSend) { message.messageDirection = RongIMLib.MessageDirection.SEND; message.senderUserId = RongIMLib.Bridge._client.userId; } else { message.messageDirection = RongIMLib.MessageDirection.RECEIVE; } // 自己给自己发的消息, messageDirection 为 2(接收) var isSelfToSelf = message.senderUserId === selfUserId && message.targetId === selfUserId; if (isSelfToSelf) { message.messageDirection = RongIMLib.MessageDirection.RECEIVE; } var receivedTime = new Date().getTime(); message.messageUId = entity.msgId; message.receivedTime = RongIMLib.MessageUtil.getCheckedTime(receivedTime); message.messageId = (message.conversationType + "_" + ~~(Math.random() * 0xffffff)); message.objectName = objectName; message.receivedStatus = RongIMLib.ReceivedStatus.READ; if ((entity.status & 2) == 2) { message.receivedStatus = RongIMLib.ReceivedStatus.RETRIEVED; } message.offLineMessage = offlineMsg ? true : false; if (!offlineMsg) { if (RongIMLib.RongIMClient._memoryStore.connectAckTime > message.sentTime) { message.offLineMessage = true; } } return message; }; MessageUtil.detectCMP = function (options) { options.error = options.fail; return RongIMLib.RongUtil.request(options); }; MessageUtil.setDeltaTime = function (serverTime) { try { RongIMLib.RongIMClient._memoryStore.deltaTime = new Date().getTime() - serverTime; } catch (e) { } }; MessageUtil.getDeltaTime = function () { var _memoryStore = RongIMLib.RongIMClient._memoryStore || {}; return _memoryStore.deltaTime || 0; }; MessageUtil.getCheckedTime = function (time) { var deltaTime = MessageUtil.getDeltaTime(); return time - deltaTime; }; //适配SSL // static schemeArrs: Array = [["http", "ws"], ["https", "wss"]]; MessageUtil.sign = { converNum: 1, msgNum: 1, isMsgStart: true, isConvStart: true }; return MessageUtil; })(); RongIMLib.MessageUtil = MessageUtil; /** * 工具类 */ var MessageIdHandler = (function () { function MessageIdHandler() { } MessageIdHandler.init = function () { this.messageId = +(RongIMLib.RongIMClient._storageProvider.getItem(RongIMLib.Navigation.Endpoint.userId + "msgId") || RongIMLib.RongIMClient._storageProvider.setItem(RongIMLib.Navigation.Endpoint.userId + "msgId", 0) || 0); }; MessageIdHandler.messageIdPlus = function (method) { RongIMLib.RongIMClient._memoryStore.depend.isPolling && this.init(); if (this.messageId >= 65535) { this.messageId = 0; } this.messageId++; RongIMLib.RongIMClient._memoryStore.depend.isPolling && RongIMLib.RongIMClient._storageProvider.setItem(RongIMLib.Navigation.Endpoint.userId + "msgId", this.messageId); return this.messageId; }; MessageIdHandler.clearMessageId = function () { this.messageId = 0; RongIMLib.RongIMClient._memoryStore.depend.isPolling && RongIMLib.RongIMClient._storageProvider.setItem(RongIMLib.Navigation.Endpoint.userId + "msgId", this.messageId); }; MessageIdHandler.getMessageId = function () { RongIMLib.RongIMClient._memoryStore.depend.isPolling && this.init(); return this.messageId; }; MessageIdHandler.messageId = 0; return MessageIdHandler; })(); RongIMLib.MessageIdHandler = MessageIdHandler; var ChrmKVCaches = (function () { function ChrmKVCaches() { this.time = 0; this.cache = {}; } ChrmKVCaches.prototype.setTime = function (time) { this.time = time; }; ChrmKVCaches.prototype.getTime = function () { return this.time; }; ChrmKVCaches.prototype.setValue = function (kvContent) { var key = kvContent.key, timestamp = kvContent.timestamp; this.cache[key] = this.cache[key] || {}; this.cache[key] = { value: kvContent.value, userId: kvContent.userId, isDeleted: false, timestamp: timestamp }; }; ChrmKVCaches.prototype.removeValue = function (kvContent) { var key = kvContent.key, timestamp = kvContent.timestamp; this.cache[key] = this.cache[key] || {}; var cache = this.cache[key]; this.cache[key] = RongIMLib.RongUtil.extend(cache, { isDeleted: true, userId: kvContent.userId, timestamp: timestamp }); }; ChrmKVCaches.prototype.getValue = function (key) { this.cache[key] = this.cache[key] || {}; var cache = this.cache[key]; return cache.isDeleted ? null : cache.value; }; ChrmKVCaches.prototype.getAllKV = function () { var kv = {}; RongIMLib.RongUtil.forEach(this.cache, function (item, key) { if (!item.isDeleted) { kv[key] = item.value; } }); return kv; }; ChrmKVCaches.prototype.getSetUserId = function (key) { this.cache[key] = this.cache[key] || {}; return this.cache[key].userId; }; ChrmKVCaches.prototype.isKeyExisted = function (key) { this.cache[key] = this.cache[key] || {}; var cache = this.cache[key]; var hasValue = !RongIMLib.RongUtil.isEmpty(cache.value); return hasValue && !cache.isDeleted; }; ChrmKVCaches.prototype.clear = function () { this.cache = {}; }; return ChrmKVCaches; })(); var chrmKVCaches = {}; var chrmKVProsumerCaches = {}; var getKVCache = function (chrmId) { var chrmKVCache = chrmKVCaches[chrmId]; if (!chrmKVCache) { chrmKVCache = chrmKVCaches[chrmId] = new ChrmKVCaches(); } return chrmKVCache; }; var getKVProsumer = function (chrmId) { var kvProsumer = chrmKVProsumerCaches[chrmId]; if (!kvProsumer) { kvProsumer = chrmKVProsumerCaches[chrmId] = new RongIMLib.RongUtil.Prosumer(); } return kvProsumer; }; var ChrmKVHandler = (function () { function ChrmKVHandler() { } ChrmKVHandler.pull = function (chrmId, time) { var prosumer = getKVProsumer(chrmId); var event = RongIMLib.RongIMClient._dataAccessProvider.pullChatroomEntry; prosumer.produce({ event: event, chrmId: chrmId, time: time }); prosumer.consume(function (params, next) { var event = params.event, chrmId = params.chrmId, time = params.time; var kvCache = getKVCache(chrmId); var currentTime = kvCache.getTime(); var isKVNeedUpdated = currentTime < time; if (isKVNeedUpdated) { event(chrmId, currentTime, { onSuccess: function (result) { ChrmKVHandler.setEntries(chrmId, result); next(); }, onError: next }); } else { next(); } }); }; ChrmKVHandler.setEntries = function (chrmId, entity) { var entries = entity.entries, isFullUpdate = entity.bFullUpdate, syncTime = entity.syncTime; var event = isFullUpdate ? ChrmKVHandler.setFullEntries : ChrmKVHandler.setIncreEntries; var kvCache = getKVCache(chrmId); syncTime = MessageUtil.int64ToTimestamp(syncTime); if (RongIMLib.RongUtil.isArray(entries)) { RongIMLib.RongUtil.forEach(entries, function (item) { var setTime = item.timestamp; if (!RongIMLib.RongUtil.isNumber(setTime)) { item.timestamp = MessageUtil.int64ToTimestamp(setTime); } }); } kvCache.setTime(syncTime); // 更新拉取时间 event(chrmId, entries); // 更新 kv 值 }; ChrmKVHandler.setEntry = function (chrmId, chatroomEntry, status, userId) { var kvCache = getKVCache(chrmId); var timestamp = chatroomEntry.timestamp || +new Date(); var isDelete = RongInnerTools.getChrmEntityByStatus(status).isDelete; var eventName = isDelete ? 'removeValue' : 'setValue'; kvCache[eventName]({ key: chatroomEntry.key, value: chatroomEntry.value, userId: userId, timestamp: timestamp }); }; ChrmKVHandler.setFullEntries = function (chrmId, entries) { var kvCache = getKVCache(chrmId); kvCache.clear(); RongIMLib.RongUtil.forEach(entries, function (entity) { entity.timestamp = MessageUtil.int64ToTimestamp(entity.timestamp); kvCache.setValue({ key: entity.key, value: entity.value, userId: entity.uid, timestamp: entity.timestamp }); }); }; ChrmKVHandler.setIncreEntries = function (chrmId, entries) { var kvCache = getKVCache(chrmId); var currentUserId = RongIMLib.RongIMClient.getInstance().getCurrentUserId(); var optEvent = function (entity, isOverwrite, eventName) { var key = entity.key, value = entity.value; var isLatestedKeySetBySelf = kvCache.getSetUserId(key) === currentUserId; var isKeyNotExist = !kvCache.isKeyExisted(key); /* 1. 需覆盖时, 不管 key 是否已存在, 都直接设置 2. 不覆盖时, 必须最后一次 key 为自己设置的或此 key 还未设置过, 才能继续 */ if (isOverwrite || isLatestedKeySetBySelf || isKeyNotExist) { kvCache[eventName]({ key: key, value: value, userId: entity.uid, timestamp: entity.timestamp }); } }; RongIMLib.RongUtil.forEach(entries, function (entity) { var entityContent = RongInnerTools.getChrmEntityByStatus(entity.status); var eventName = entityContent.isDelete ? 'removeValue' : 'setValue'; optEvent(entity, entityContent.isOverwrite, eventName); }); }; ChrmKVHandler.getEntityValue = function (chrmId, key) { var kvCache = getKVCache(chrmId); return kvCache.getValue(key); }; ChrmKVHandler.getAllEntityValue = function (chrmId) { var kvCache = getKVCache(chrmId); return kvCache.getAllKV(); }; ChrmKVHandler.isKeyValid = function (key) { return /^[A-Za-z0-9_=+-]+$/.test(key); }; return ChrmKVHandler; })(); RongIMLib.ChrmKVHandler = ChrmKVHandler; var AutoDeleteCode = 0x0001; var OverwriteCode = 0x0002; var DeleteOperationCode = 0x0004; var RongInnerTools = (function () { function RongInnerTools() { } RongInnerTools.convertUserStatus = function (entity) { entity = RongIMLib.RongUtil.rename(entity, { subUserId: 'userId' }); var status = JSON.parse(entity.status); var us = status.us; if (!us) { return entity; } entity.status = RongIMLib.RongUtil.rename(us, { o: 'online', 'p': 'platform', s: 'status' }); return entity; }; RongInnerTools.getChrmEntityStatus = function (entity, chatroomOpt) { var status = 0; // 是否自动清理 if (entity.isAutoDelete) { status = status | AutoDeleteCode; } // 是否覆盖 if (entity.isOverwrite) { status = status | OverwriteCode; } // 操作类型 switch (chatroomOpt) { case RongIMLib.ChatroomEntityOpt.DELETE: status = status | DeleteOperationCode; break; default: break; } return status; }; RongInnerTools.getChrmEntityByStatus = function (status) { var isDelete = !!(status & DeleteOperationCode); var entityOpt = isDelete ? RongIMLib.ChatroomEntityOpt.DELETE : RongIMLib.ChatroomEntityOpt.UPDATE; return { isAutoDelete: !!(status & AutoDeleteCode), isOverwrite: !!(status & OverwriteCode), entityOpt: entityOpt, isDelete: isDelete }; }; return RongInnerTools; })(); RongIMLib.RongInnerTools = RongInnerTools; var UnreadCountHandler = (function () { function UnreadCountHandler() { } UnreadCountHandler.getKey = function (type, targetId) { var selfId = RongIMLib.RongIMClient.getInstance().getCurrentUserId(); return RongIMLib.RongUtil.tplEngine(UnreadCountHandler.KeyTemp, { selfId: selfId, type: type, targetId: targetId }); }; UnreadCountHandler.getDetailByKey = function (key) { var detail = { count: 0, sentTime: 0 }; var value = RongIMLib.RongIMClient._storageProvider.getItem(key); if (!value) { return detail; } value += ''; var unreadItems = value.split('_'); var hasUnderline = unreadItems.length > 1; detail.count = Number(unreadItems[0]); if (hasUnderline) { detail.sentTime = Number(unreadItems[1]); } return detail; }; UnreadCountHandler.getDetail = function (type, targetId) { var key = UnreadCountHandler.getKey(type, targetId); var detail = UnreadCountHandler.getDetailByKey(key); return detail; }; UnreadCountHandler.set = function (type, id, count, sentTime) { var key = UnreadCountHandler.getKey(type, id); var value = sentTime ? RongIMLib.RongUtil.tplEngine(UnreadCountHandler.ValueTemp, { count: count, sentTime: sentTime }) : count; RongIMLib.RongIMClient._storageProvider.setItem(key, value); return count; }; UnreadCountHandler.add = function (type, id, plusCount, sentTime) { var detail = UnreadCountHandler.getDetail(type, id), count = detail.count, oldSentTime = detail.sentTime; if (sentTime && sentTime > oldSentTime) { count = count + plusCount; UnreadCountHandler.set(type, id, count, sentTime); } return count; }; UnreadCountHandler.get = function (type, id) { var detail = UnreadCountHandler.getDetail(type, id); return detail.count; }; UnreadCountHandler.getAll = function (types) { var total = 0; var selfId = RongIMLib.RongIMClient.getInstance().getCurrentUserId(); var setTotal = function (keyList) { RongIMLib.RongUtil.forEach(keyList, function (key) { var detail = UnreadCountHandler.getDetailByKey(key); total += detail.count; }); }; if (types) { RongIMLib.RongUtil.forEach(types, function (type) { var key = UnreadCountHandler.getKey(type, ''); var unreadKeys = RongIMLib.RongIMClient._storageProvider.getItemKeyList(key); setTotal(unreadKeys); }); } else { var key = UnreadCountHandler.getKey('', ''); var unreadKeys = RongIMLib.RongIMClient._storageProvider.getItemKeyList(key); setTotal(unreadKeys); } return total; }; UnreadCountHandler.remove = function (type, targetId) { var key = UnreadCountHandler.getKey(type, targetId); RongIMLib.RongIMClient._storageProvider.removeItem(key); }; UnreadCountHandler.clear = function () { var key = UnreadCountHandler.getKey('', ''); var keyList = RongIMLib.RongIMClient._storageProvider.getItemKeyList(key); RongIMLib.RongUtil.forEach(keyList, function (key) { RongIMLib.RongIMClient._storageProvider.removeItem(key); }); }; UnreadCountHandler.KeyTemp = 'cu{selfId}{type}{targetId}'; UnreadCountHandler.ValueTemp = '{count}_{sentTime}'; return UnreadCountHandler; })(); RongIMLib.UnreadCountHandler = UnreadCountHandler; var ConversationStatusStoreUserKey = '{appkey}{userId}constas'; var ConversationStatusPullTimeStoreKey = 'time'; var ConversationStatusManager = (function () { function ConversationStatusManager(option) { this.updatedStatus = {}; // 更新的会话状态 this.statusShangeObserver = new RongIMLib.Observer(); this.pullProsumer = new RongIMLib.RongUtil.Prosumer(); var appkey = option.appkey, userId = option.userId; this.option = option; this.storageKey = RongIMLib.RongUtil.tplEngine(ConversationStatusStoreUserKey, { appkey: appkey, userId: userId }); } ConversationStatusManager.prototype.watchChanged = function (event) { this.statusShangeObserver.add(event); }; ConversationStatusManager.prototype.set = function (type, targetId, status) { var currentStatus = this.get(type, targetId); var updateTime = status.updateTime, isLastInAPull = status.isLastInAPull; if (updateTime > currentStatus.updateTime) { var allStatus = RongIMLib.RongUtil.Storage.get(this.storageKey) || {}; var conversationStoreKey = IMHandler.getConversationKey(type, targetId); var storeStatus = allStatus[conversationStoreKey] || {}; RongIMLib.RongUtil.forEach(status, function (val, key) { if (!RongIMLib.RongUtil.isUndefined(val)) { storeStatus[key] = val; } }); allStatus[conversationStoreKey] = storeStatus; RongIMLib.RongUtil.Storage.set(this.storageKey, allStatus); this.updatedStatus[conversationStoreKey] = status; RongIMLib.RongIMClient.getInstance().pottingConversation({ type: type, userId: targetId }); } isLastInAPull && this.statusShangeObserver.emit(this.updatedStatus); this.updatedStatus = {}; }; ConversationStatusManager.prototype.get = function (type, targetId) { var allStatus = RongIMLib.RongUtil.Storage.get(this.storageKey) || {}; var conversationStoreKey = IMHandler.getConversationKey(type, targetId); var status = allStatus[conversationStoreKey] || {}; var notificationStatus = status.notificationStatus, isTop = status.isTop, updateTime = status.updateTime; return { notificationStatus: notificationStatus || RongIMLib.ConversationNotificationStatus.NOTIFY, isTop: isTop || false, updateTime: updateTime || 0 }; }; ConversationStatusManager.prototype.pull = function (option) { option = option || {}; var self = this; var _a = this, server = _a.option.server, pullProsumer = _a.pullProsumer, storageKey = _a.storageKey; pullProsumer.produce(option); pullProsumer.consume(function (params, next) { var allStatus = RongIMLib.RongUtil.Storage.get(storageKey) || {}; var lastUpdateTime = allStatus[ConversationStatusPullTimeStoreKey] || 0; var updateTime = params.time, isForce = params.isForce; if (lastUpdateTime > updateTime && !isForce) { return next(); } server.pullConversationStatus(lastUpdateTime, { onStatus: function (type, id, conversationStatus) { self.set(type, id, conversationStatus); }, onSuccess: function (updateTime) { var allStatus = RongIMLib.RongUtil.Storage.get(storageKey) || {}; allStatus[ConversationStatusPullTimeStoreKey] = updateTime; // 更新拉取时间戳 RongIMLib.RongUtil.Storage.set(self.storageKey, allStatus); next(); }, onError: next }); }); }; return ConversationStatusManager; })(); RongIMLib.ConversationStatusManager = ConversationStatusManager; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var MessageContent = (function () { function MessageContent(data) { throw new Error("This method is abstract, you must implement this method in inherited class."); } MessageContent.obtain = function () { throw new Error("This method is abstract, you must implement this method in inherited class."); }; return MessageContent; })(); RongIMLib.MessageContent = MessageContent; var NotificationMessage = (function (_super) { __extends(NotificationMessage, _super); function NotificationMessage() { _super.apply(this, arguments); } return NotificationMessage; })(MessageContent); RongIMLib.NotificationMessage = NotificationMessage; var StatusMessage = (function (_super) { __extends(StatusMessage, _super); function StatusMessage() { _super.apply(this, arguments); } return StatusMessage; })(MessageContent); RongIMLib.StatusMessage = StatusMessage; var ModelUtil = (function () { function ModelUtil() { } ModelUtil.modelClone = function (object) { var obj = {}; for (var item in object) { if (item != "messageName" && "encode" != item) { obj[item] = object[item]; } } return obj; }; ModelUtil.modleCreate = function (fields, msgType) { // if (fields.length < 1) { // throw new Error("Array is empty -> registerMessageType.modleCreate"); // } var Object = function (message) { var me = this; for (var index in fields) { me[fields[index]] = message[fields[index]]; } Object.prototype.messageName = msgType; Object.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; }; return Object; }; return ModelUtil; })(); RongIMLib.ModelUtil = ModelUtil; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var CustomerStatusMessage = (function () { function CustomerStatusMessage(message) { this.messageName = "CustomerStatusMessage"; this.status = message.status; } CustomerStatusMessage.obtain = function () { return null; }; CustomerStatusMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return CustomerStatusMessage; })(); RongIMLib.CustomerStatusMessage = CustomerStatusMessage; /** * 客服转换响应消息的类型名 */ var ChangeModeResponseMessage = (function () { function ChangeModeResponseMessage(message) { this.messageName = "ChangeModeResponseMessage"; this.code = message.code; this.data = message.data; this.msg = message.msg; } ChangeModeResponseMessage.obtain = function () { return null; }; ChangeModeResponseMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ChangeModeResponseMessage; })(); RongIMLib.ChangeModeResponseMessage = ChangeModeResponseMessage; /** * 客服转换消息的类型名 * 此消息不计入未读消息数 */ var ChangeModeMessage = (function () { function ChangeModeMessage(message) { this.messageName = "ChangeModeMessage"; this.uid = message.uid; this.sid = message.sid; this.pid = message.pid; } ChangeModeMessage.obtain = function () { return null; }; ChangeModeMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ChangeModeMessage; })(); RongIMLib.ChangeModeMessage = ChangeModeMessage; var CustomerStatusUpdateMessage = (function () { function CustomerStatusUpdateMessage(message) { this.messageName = "CustomerStatusUpdateMessage"; this.serviceStatus = message.serviceStatus; this.sid = message.sid; } CustomerStatusUpdateMessage.obtain = function () { return null; }; CustomerStatusUpdateMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return CustomerStatusUpdateMessage; })(); RongIMLib.CustomerStatusUpdateMessage = CustomerStatusUpdateMessage; var HandShakeMessage = (function () { function HandShakeMessage(message) { this.messageName = "HandShakeMessage"; if (message) { this.requestInfo = message.requestInfo; this.userInfo = message.userInfo; } } HandShakeMessage.obtain = function () { return null; }; HandShakeMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return HandShakeMessage; })(); RongIMLib.HandShakeMessage = HandShakeMessage; var CustomerContact = (function () { function CustomerContact(message) { this.messageName = "CustomerContact"; this.page = message.page; this.nickName = message.nickName; this.routingInfo = message.routingInfo; this.info = message.info; this.requestInfo = message.requestInfo; } CustomerContact.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return CustomerContact; })(); RongIMLib.CustomerContact = CustomerContact; var EvaluateMessage = (function () { function EvaluateMessage(message) { this.messageName = "EvaluateMessage"; this.uid = message.uid; this.sid = message.sid; this.pid = message.pid; this.source = message.source; this.suggest = message.suggest; this.isresolve = message.isresolve; this.type = message.type; } EvaluateMessage.obtain = function () { return null; }; EvaluateMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return EvaluateMessage; })(); RongIMLib.EvaluateMessage = EvaluateMessage; /** * 客服握手响应消息的类型名 */ var HandShakeResponseMessage = (function () { function HandShakeResponseMessage(message) { this.messageName = "HandShakeResponseMessage"; this.msg = message.msg; this.status = message.status; this.data = message.data; } HandShakeResponseMessage.obtain = function () { return null; }; HandShakeResponseMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return HandShakeResponseMessage; })(); RongIMLib.HandShakeResponseMessage = HandShakeResponseMessage; var SuspendMessage = (function () { function SuspendMessage(message) { this.messageName = "SuspendMessage"; this.uid = message.uid; this.sid = message.sid; this.pid = message.pid; } SuspendMessage.obtain = function () { return null; }; SuspendMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return SuspendMessage; })(); RongIMLib.SuspendMessage = SuspendMessage; var TerminateMessage = (function () { function TerminateMessage(message) { this.messageName = "TerminateMessage"; this.code = message.code; this.msg = message.msg; this.sid = message.sid; } TerminateMessage.obtain = function () { return null; }; TerminateMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return TerminateMessage; })(); RongIMLib.TerminateMessage = TerminateMessage; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var IsTypingStatusMessage = (function () { function IsTypingStatusMessage(data) { this.messageName = "IsTypingStatusMessage"; var msg = data; } IsTypingStatusMessage.prototype.encode = function () { return undefined; }; IsTypingStatusMessage.prototype.getMessage = function () { return null; }; return IsTypingStatusMessage; })(); RongIMLib.IsTypingStatusMessage = IsTypingStatusMessage; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var InformationNotificationMessage = (function () { function InformationNotificationMessage(message) { this.messageName = "InformationNotificationMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> InformationNotificationMessage."); } this.message = message.message; this.extra = message.extra; if (message.user) { this.user = message.user; } } InformationNotificationMessage.obtain = function (message) { return new InformationNotificationMessage({ message: message, extra: "" }); }; InformationNotificationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return InformationNotificationMessage; })(); RongIMLib.InformationNotificationMessage = InformationNotificationMessage; var CommandMessage = (function () { function CommandMessage(message) { this.messageName = "CommandMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> CommandMessage."); } try { if (Object.prototype.toString.call(message.data) == "[object String]") { this.data = JSON.parse(message.data); } else { this.data = message.data; } } catch (e) { this.data = message.data; RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.L_CRAW_F, level: RongIMLib.LoggerLevel.E, type: RongIMLib.LoggerType.IM, content: { stack: e, msg: message.data } }); } this.name = message.name; this.extra = message.extra; } CommandMessage.obtain = function (data) { return new CommandMessage({ data: data, extra: "" }); }; CommandMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return CommandMessage; })(); RongIMLib.CommandMessage = CommandMessage; var ContactNotificationMessage = (function () { function ContactNotificationMessage(message) { this.messageName = "ContactNotificationMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> ContactNotificationMessage."); } this.operation = message.operation; this.targetUserId = message.targetUserId; this.message = message.message; this.extra = message.extra; this.sourceUserId = message.sourceUserId; if (message.user) { this.user = message.user; } } ContactNotificationMessage.obtain = function (operation, sourceUserId, targetUserId, message) { return new InformationNotificationMessage({ operation: operation, sourceUserId: sourceUserId, targetUserId: targetUserId, message: message }); }; ContactNotificationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; ContactNotificationMessage.CONTACT_OPERATION_ACCEPT_RESPONSE = "ContactOperationAcceptResponse"; ContactNotificationMessage.CONTACT_OPERATION_REJECT_RESPONSE = "ContactOperationRejectResponse"; ContactNotificationMessage.CONTACT_OPERATION_REQUEST = "ContactOperationRequest"; return ContactNotificationMessage; })(); RongIMLib.ContactNotificationMessage = ContactNotificationMessage; var ProfileNotificationMessage = (function () { function ProfileNotificationMessage(message) { this.messageName = "ProfileNotificationMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> ProfileNotificationMessage."); } this.operation = message.operation; try { if (Object.prototype.toString.call(message.data) == "[object String]") { this.data = JSON.parse(message.data); } else { this.data = message.data; } } catch (e) { this.data = message.data; RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.L_CRAW_F, level: RongIMLib.LoggerLevel.E, type: RongIMLib.LoggerType.IM, content: { stack: e, msg: message.data } }); } this.extra = message.extra; if (message.user) { this.user = message.user; } } ProfileNotificationMessage.obtain = function (operation, data) { return new ProfileNotificationMessage({ operation: operation, data: data }); }; ProfileNotificationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ProfileNotificationMessage; })(); RongIMLib.ProfileNotificationMessage = ProfileNotificationMessage; var CommandNotificationMessage = (function () { function CommandNotificationMessage(message) { this.messageName = "CommandNotificationMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> ProfileNotificationMessage."); } try { if (Object.prototype.toString.call(message.data) == "[object String]") { this.data = JSON.parse(message.data); } else { this.data = message.data; } } catch (e) { this.data = message.data; RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.L_CRAW_F, level: RongIMLib.LoggerLevel.E, type: RongIMLib.LoggerType.IM, content: { stack: e, msg: message.data } }); } this.name = message.name; this.extra = message.extra; if (message.user) { this.user = message.user; } } CommandNotificationMessage.obtain = function (name, data) { return new CommandNotificationMessage({ name: name, data: data, extra: "" }); }; CommandNotificationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return CommandNotificationMessage; })(); RongIMLib.CommandNotificationMessage = CommandNotificationMessage; var DiscussionNotificationMessage = (function () { function DiscussionNotificationMessage(message) { this.messageName = "DiscussionNotificationMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> DiscussionNotificationMessage."); } this.extra = message.extra; this.extension = message.extension; this.type = message.type; this.isHasReceived = message.isHasReceived; this.operation = message.operation; this.user = message.user; if (message.user) { this.user = message.user; } } DiscussionNotificationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return DiscussionNotificationMessage; })(); RongIMLib.DiscussionNotificationMessage = DiscussionNotificationMessage; var GroupNotificationMessage = (function () { function GroupNotificationMessage(msg) { this.messageName = "GroupNotificationMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> GroupNotificationMessage."); } msg.operatorUserId && (this.operatorUserId = msg.operatorUserId); msg.operation && (this.operation = msg.operation); msg.data && (this.data = msg.data); msg.message && (this.message = msg.message); msg.extra && (this.extra = msg.extra); } GroupNotificationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return GroupNotificationMessage; })(); RongIMLib.GroupNotificationMessage = GroupNotificationMessage; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var TextMessage = (function () { function TextMessage(message) { this.messageName = "TextMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> TextMessage."); } this.content = message.content; this.extra = message.extra; if (message.user) { this.user = message.user; } if (message.mentionedInfo) { this.mentionedInfo = message.mentionedInfo; } if (message.burnDuration) { this.burnDuration = message.burnDuration; } } TextMessage.obtain = function (text) { return new TextMessage({ extra: "", content: text }); }; TextMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return TextMessage; })(); RongIMLib.TextMessage = TextMessage; var TypingStatusMessage = (function () { function TypingStatusMessage(message) { this.messageName = "TypingStatusMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> TypingStatusMessage."); } this.typingContentType = message.typingContentType; this.data = message.data; } TypingStatusMessage.obtain = function (typingContentType, data) { return new TypingStatusMessage({ typingContentType: typingContentType, data: data }); }; TypingStatusMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return TypingStatusMessage; })(); RongIMLib.TypingStatusMessage = TypingStatusMessage; var ReadReceiptMessage = (function () { function ReadReceiptMessage(message) { this.messageName = "ReadReceiptMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> ReadReceiptMessage."); } this.lastMessageSendTime = message.lastMessageSendTime; this.messageUId = message.messageUId; this.type = message.type; } ReadReceiptMessage.obtain = function (messageUId, lastMessageSendTime, type) { return new ReadReceiptMessage({ messageUId: messageUId, lastMessageSendTime: lastMessageSendTime, type: type }); }; ReadReceiptMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ReadReceiptMessage; })(); RongIMLib.ReadReceiptMessage = ReadReceiptMessage; var VoiceMessage = (function () { function VoiceMessage(message) { this.messageName = "VoiceMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> VoiceMessage."); } this.content = message.content; this.duration = message.duration; this.extra = message.extra; if (message.user) { this.user = message.user; } if (message.mentionedInfo) { this.mentionedInfo = message.mentionedInfo; } if (message.burnDuration) { this.burnDuration = message.burnDuration; } } VoiceMessage.obtain = function (base64Content, duration) { return new VoiceMessage({ content: base64Content, duration: duration, extra: "" }); }; VoiceMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return VoiceMessage; })(); RongIMLib.VoiceMessage = VoiceMessage; var RecallCommandMessage = (function () { function RecallCommandMessage(message) { this.messageName = "RecallCommandMessage"; this.messageUId = message.messageUId; this.conversationType = message.conversationType; this.targetId = message.targetId; this.sentTime = message.sentTime; message.extra && (this.extra = message.extra); message.user && (this.user = message.user); } RecallCommandMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return RecallCommandMessage; })(); RongIMLib.RecallCommandMessage = RecallCommandMessage; var ImageMessage = (function () { function ImageMessage(message) { this.messageName = "ImageMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> ImageMessage."); } this.content = message.content; this.imageUri = message.imageUri; message.extra && (this.extra = message.extra); message.user && (this.user = message.user); if (message.mentionedInfo) { this.mentionedInfo = message.mentionedInfo; } if (message.burnDuration) { this.burnDuration = message.burnDuration; } } ImageMessage.obtain = function (content, imageUri) { return new ImageMessage({ content: content, imageUri: imageUri, extra: "" }); }; ImageMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ImageMessage; })(); RongIMLib.ImageMessage = ImageMessage; var LocationMessage = (function () { function LocationMessage(message) { this.messageName = "LocationMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> LocationMessage."); } this.latitude = message.latitude; this.longitude = message.longitude; this.poi = message.poi; this.content = message.content; this.extra = message.extra; if (message.user) { this.user = message.user; } if (message.mentionedInfo) { this.mentionedInfo = message.mentionedInfo; } } LocationMessage.obtain = function (latitude, longitude, poi, content) { return new LocationMessage({ latitude: latitude, longitude: longitude, poi: poi, content: content, extra: "" }); }; LocationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return LocationMessage; })(); RongIMLib.LocationMessage = LocationMessage; var RichContentMessage = (function () { function RichContentMessage(message) { this.messageName = "RichContentMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> RichContentMessage."); } this.title = message.title; this.content = message.content; this.imageUri = message.imageUri; this.extra = message.extra; this.url = message.url; if (message.user) { this.user = message.user; } } RichContentMessage.obtain = function (title, content, imageUri, url) { return new RichContentMessage({ title: title, content: content, imageUri: imageUri, url: url, extra: "" }); }; RichContentMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return RichContentMessage; })(); RongIMLib.RichContentMessage = RichContentMessage; var JrmfRedPacketMessage = (function () { function JrmfRedPacketMessage(message) { this.messageName = 'JrmfRedPacketMessage'; message && (this.message = message); } JrmfRedPacketMessage.prototype.encode = function () { return ""; }; return JrmfRedPacketMessage; })(); RongIMLib.JrmfRedPacketMessage = JrmfRedPacketMessage; var JrmfRedPacketOpenedMessage = (function () { function JrmfRedPacketOpenedMessage(message) { this.messageName = 'JrmfRedPacketOpenedMessage'; message && (this.message = message); } JrmfRedPacketOpenedMessage.prototype.encode = function () { return ""; }; return JrmfRedPacketOpenedMessage; })(); RongIMLib.JrmfRedPacketOpenedMessage = JrmfRedPacketOpenedMessage; var UnknownMessage = (function () { function UnknownMessage(message) { this.messageName = "UnknownMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> UnknownMessage."); } this.message = message; } UnknownMessage.prototype.encode = function () { return ""; }; return UnknownMessage; })(); RongIMLib.UnknownMessage = UnknownMessage; var PublicServiceCommandMessage = (function () { function PublicServiceCommandMessage(message) { this.messageName = "PublicServiceCommandMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> PublicServiceCommandMessage."); } this.content = message.content; this.extra = message.extra; this.menuItem = message.menuItem; if (message.user) { this.user = message.user; } if (message.mentionedInfo) { this.mentionedInfo = message.mentionedInfo; } } PublicServiceCommandMessage.obtain = function (item) { return new PublicServiceCommandMessage({ content: "", command: "", menuItem: item, extra: "" }); }; PublicServiceCommandMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return PublicServiceCommandMessage; })(); RongIMLib.PublicServiceCommandMessage = PublicServiceCommandMessage; var PublicServiceMultiRichContentMessage = (function () { function PublicServiceMultiRichContentMessage(messages) { this.messageName = "PublicServiceMultiRichContentMessage"; this.richContentMessages = messages; } PublicServiceMultiRichContentMessage.prototype.encode = function () { return null; }; return PublicServiceMultiRichContentMessage; })(); RongIMLib.PublicServiceMultiRichContentMessage = PublicServiceMultiRichContentMessage; var SyncReadStatusMessage = (function () { function SyncReadStatusMessage(message) { this.messageName = "SyncReadStatusMessage"; message.lastMessageSendTime && (this.lastMessageSendTime = message.lastMessageSendTime); } SyncReadStatusMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return SyncReadStatusMessage; })(); RongIMLib.SyncReadStatusMessage = SyncReadStatusMessage; var ReadReceiptRequestMessage = (function () { function ReadReceiptRequestMessage(message) { this.messageName = "ReadReceiptRequestMessage"; message.messageUId && (this.messageUId = message.messageUId); } ReadReceiptRequestMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ReadReceiptRequestMessage; })(); RongIMLib.ReadReceiptRequestMessage = ReadReceiptRequestMessage; var ReadReceiptResponseMessage = (function () { function ReadReceiptResponseMessage(message) { this.messageName = "ReadReceiptResponseMessage"; message.receiptMessageDic && (this.receiptMessageDic = message.receiptMessageDic); } ReadReceiptResponseMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ReadReceiptResponseMessage; })(); RongIMLib.ReadReceiptResponseMessage = ReadReceiptResponseMessage; var PublicServiceRichContentMessage = (function () { function PublicServiceRichContentMessage(message) { this.messageName = "PublicServiceRichContentMessage"; this.richContentMessage = message; } PublicServiceRichContentMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return PublicServiceRichContentMessage; })(); RongIMLib.PublicServiceRichContentMessage = PublicServiceRichContentMessage; var FileMessage = (function () { function FileMessage(message) { this.messageName = "FileMessage"; message.name && (this.name = message.name); message.size && (this.size = message.size); message.type && (this.type = message.type); message.fileUrl && (this.fileUrl = message.fileUrl); message.extra && (this.extra = message.extra); message.user && (this.user = message.user); } FileMessage.obtain = function (msg) { return new FileMessage({ name: msg.name, size: msg.size, type: msg.type, fileUrl: msg.fileUrl }); }; FileMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return FileMessage; })(); RongIMLib.FileMessage = FileMessage; var HQVoiceMessage = (function () { function HQVoiceMessage(message) { this.messageName = "HQVoiceMessage"; this.type = message.type || 'aac'; message.localPath && (this.localPath = message.localPath); message.remoteUrl && (this.remoteUrl = message.remoteUrl); message.duration && (this.duration = message.duration); message.extra && (this.extra = message.extra); message.user && (this.user = message.user); message.burnDuration && (this.burnDuration = message.burnDuration); } HQVoiceMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return HQVoiceMessage; })(); RongIMLib.HQVoiceMessage = HQVoiceMessage; var AcceptMessage = (function () { function AcceptMessage(message) { this.messageName = "AcceptMessage"; this.mediaId = message.mediaId; this.callId = message.callId; this.mediaType = message.mediaType; this.mode = message.mode; this.subInfo = message.subInfo; } AcceptMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return AcceptMessage; })(); RongIMLib.AcceptMessage = AcceptMessage; var RingingMessage = (function () { function RingingMessage(message) { this.messageName = "RingingMessage"; this.callId = message.callId; } RingingMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return RingingMessage; })(); RongIMLib.RingingMessage = RingingMessage; var SummaryMessage = (function () { function SummaryMessage(message) { this.messageName = "SummaryMessage"; this.caller = message.caller; this.inviter = message.inviter; this.mediaType = message.mediaType; this.memberIdList = message.memberIdList; this.startTime = message.startTime; this.connectedTime = message.connectedTime; this.duration = message.duration; this.status = message.status; } SummaryMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return SummaryMessage; })(); RongIMLib.SummaryMessage = SummaryMessage; var HungupMessage = (function () { function HungupMessage(message) { this.messageName = "HungupMessage"; this.callId = message.callId; this.reason = message.reason; this.mode = message.mode; this.subInfo = message.subInfo; } HungupMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return HungupMessage; })(); RongIMLib.HungupMessage = HungupMessage; var InviteMessage = (function () { function InviteMessage(message) { this.messageName = "InviteMessage"; this.mediaId = message.mediaId; this.callId = message.callId; this.engineType = message.engineType; this.channelInfo = message.channelInfo; this.mediaType = message.mediaType; this.extra = message.extra; this.inviteUserIds = message.inviteUserIds; this.observerUserIds = message.observerUserIds; this.mode = message.mode; this.subInfo = message.subInfo; } InviteMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return InviteMessage; })(); RongIMLib.InviteMessage = InviteMessage; var MediaModifyMessage = (function () { function MediaModifyMessage(message) { this.messageName = "MediaModifyMessage"; this.callId = message.callId; this.mediaType = message.mediaType; this.mode = message.mode; this.subInfo = message.subInfo; } MediaModifyMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return MediaModifyMessage; })(); RongIMLib.MediaModifyMessage = MediaModifyMessage; var MemberModifyMessage = (function () { function MemberModifyMessage(message) { this.messageName = "MemberModifyMessage"; this.modifyMemType = message.modifyMemType; this.callId = message.callId; this.caller = message.caller; this.engineType = message.engineType; this.channelInfo = message.channelInfo; this.mediaType = message.mediaType; this.extra = message.extra; this.inviteUserIds = message.inviteUserIds; this.existedMemberStatusList = message.existedMemberStatusList; this.existedUserPofiles = message.existedUserPofiles; this.observerUserIds = message.observerUserIds; this.mode = message.mode; this.subInfo = message.subInfo; } MemberModifyMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return MemberModifyMessage; })(); RongIMLib.MemberModifyMessage = MemberModifyMessage; var RCCombineMessage = (function () { function RCCombineMessage(message) { this.messageName = "RCCombineMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> RCCombineMessage."); } this.nameList = message.nameList; this.remoteUrl = message.remoteUrl; if (message.user) { this.user = message.user; } this.summaryList = message.summaryList; } RCCombineMessage.obtain = function (remoteUrl, nameList, summaryList) { return new RCCombineMessage({ extra: "", content: remoteUrl, nameList: nameList, summaryList: summaryList }); }; RCCombineMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return RCCombineMessage; })(); RongIMLib.RCCombineMessage = RCCombineMessage; var ChrmKVNotificationMessage = (function () { function ChrmKVNotificationMessage(message) { this.messageName = "ChrmKVNotificationMessage"; message.key && (this.key = message.key); message.value && (this.value = message.value); message.type && (this.type = message.type); message.extra && (this.extra = message.extra); message.user && (this.user = message.user); } ChrmKVNotificationMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ChrmKVNotificationMessage; })(); RongIMLib.ChrmKVNotificationMessage = ChrmKVNotificationMessage; var LogCommandMessage = (function () { function LogCommandMessage(message) { this.messageName = "LogCommandMessage"; message.uri && (this.uri = message.uri); message.logId && (this.logId = message.logId); message.platform && (this.platform = message.platform); message.packageName && (this.packageName = message.packageName); message.startTime && (this.startTime = message.startTime); message.endTime && (this.endTime = message.endTime); message.user && (this.user = message.user); } LogCommandMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return LogCommandMessage; })(); RongIMLib.LogCommandMessage = LogCommandMessage; var ReferenceMessage = (function () { function ReferenceMessage(message) { this.messageName = "ReferenceMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> ReferenceMessage."); } this.content = message.content; this.referMsgUserId = message.referMsgUserId; this.referMsg = message.referMsg; this.objName = message.objName; if (message.user) { this.user = message.user; } if (message.mentionedInfo) { this.mentionedInfo = message.mentionedInfo; } } ReferenceMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return ReferenceMessage; })(); RongIMLib.ReferenceMessage = ReferenceMessage; var GIFMessage = (function () { function GIFMessage(message) { this.messageName = "GIFMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> ReferenceMessage."); } this.gifDataSize = message.gifDataSize; this.localPath = message.localPath; this.remoteUrl = message.remoteUrl; this.width = message.width; this.height = message.height; if (message.user) { this.user = message.user; } if (message.mentionedInfo) { this.mentionedInfo = message.mentionedInfo; } } GIFMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return GIFMessage; })(); RongIMLib.GIFMessage = GIFMessage; var SightMessage = (function () { function SightMessage(message) { this.messageName = "SightMessage"; if (arguments.length == 0) { throw new Error("Can not instantiate with empty parameters, use obtain method instead -> ReferenceMessage."); } this.sightUrl = message.sightUrl; this.content = message.content; this.duration = message.duration; this.size = message.size; this.name = message.name; if (message.user) { this.user = message.user; } if (message.mentionedInfo) { this.mentionedInfo = message.mentionedInfo; } } SightMessage.prototype.encode = function () { return JSON.stringify(RongIMLib.ModelUtil.modelClone(this)); }; return SightMessage; })(); RongIMLib.SightMessage = SightMessage; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var ChannelInfo = (function () { function ChannelInfo(Id, Key) { this.Id = Id; this.Key = Key; } return ChannelInfo; })(); RongIMLib.ChannelInfo = ChannelInfo; var UserStatus = (function () { function UserStatus(platform, online, status) { this.platform = platform; this.online = online; this.status = status; } return UserStatus; })(); RongIMLib.UserStatus = UserStatus; var MentionedInfo = (function () { function MentionedInfo(type, userIdList, mentionedContent) { } return MentionedInfo; })(); RongIMLib.MentionedInfo = MentionedInfo; var DeleteMessage = (function () { function DeleteMessage(msgId, msgDataTime, direct) { this.msgId = msgId; this.msgDataTime = msgDataTime; this.direct = direct; } return DeleteMessage; })(); RongIMLib.DeleteMessage = DeleteMessage; var CustomServiceConfig = (function () { function CustomServiceConfig(isBlack, companyName, companyUrl) { } return CustomServiceConfig; })(); RongIMLib.CustomServiceConfig = CustomServiceConfig; var CustomServiceSession = (function () { function CustomServiceSession(uid, cid, pid, isQuited, type, adminHelloWord, adminOfflineWord) { } return CustomServiceSession; })(); RongIMLib.CustomServiceSession = CustomServiceSession; var Conversation = (function () { function Conversation(conversationTitle, conversationType, draft, isTop, latestMessage, latestMessageId, notificationStatus, objectName, receivedStatus, receivedTime, senderUserId, senderUserName, sentStatus, sentTime, targetId, unreadMessageCount, senderPortraitUri, isHidden, mentionedMsg, hasUnreadMention, _readTime) { this.conversationTitle = conversationTitle; this.conversationType = conversationType; this.draft = draft; this.isTop = isTop; this.latestMessage = latestMessage; this.latestMessageId = latestMessageId; this.notificationStatus = notificationStatus; this.objectName = objectName; this.receivedStatus = receivedStatus; this.receivedTime = receivedTime; this.senderUserId = senderUserId; this.senderUserName = senderUserName; this.sentStatus = sentStatus; this.sentTime = sentTime; this.targetId = targetId; this.unreadMessageCount = unreadMessageCount; this.senderPortraitUri = senderPortraitUri; this.isHidden = isHidden; this.mentionedMsg = mentionedMsg; this.hasUnreadMention = hasUnreadMention; this._readTime = _readTime; } Conversation.prototype.setTop = function () { RongIMLib.RongIMClient._dataAccessProvider.addConversation(this, { onSuccess: function (data) { } }); }; return Conversation; })(); RongIMLib.Conversation = Conversation; var Discussion = (function () { function Discussion(creatorId, id, memberIdList, name, isOpen) { this.creatorId = creatorId; this.id = id; this.memberIdList = memberIdList; this.name = name; this.isOpen = isOpen; } return Discussion; })(); RongIMLib.Discussion = Discussion; var Group = (function () { function Group(id, name, portraitUri) { this.id = id; this.name = name; this.portraitUri = portraitUri; } return Group; })(); RongIMLib.Group = Group; var Message = (function () { function Message(content, conversationType, extra, objectName, messageDirection, messageId, receivedStatus, receivedTime, senderUserId, sentStatus, sentTime, targetId, messageType, messageUId, isLocalMessage, offLineMessage, receiptResponse) { this.content = content; this.conversationType = conversationType; this.extra = extra; this.objectName = objectName; this.messageDirection = messageDirection; this.messageId = messageId; this.receivedStatus = receivedStatus; this.receivedTime = receivedTime; this.senderUserId = senderUserId; this.sentStatus = sentStatus; this.sentTime = sentTime; this.targetId = targetId; this.messageType = messageType; this.messageUId = messageUId; this.isLocalMessage = isLocalMessage; this.offLineMessage = offLineMessage; this.receiptResponse = receiptResponse; } return Message; })(); RongIMLib.Message = Message; var MessageTag = (function () { function MessageTag(isCounted, isPersited) { this.isCounted = isCounted; this.isPersited = isPersited; } MessageTag.prototype.getMessageTag = function () { if (this.isCounted && this.isPersited) { return 3; } else if (this.isCounted) { return 2; } else if (this.isPersited) { return 1; } else if (!this.isCounted && !this.isPersited) { return 0; } }; MessageTag.getTagByStatus = function (status) { var statusMap = { 3: { isCounted: true, isPersited: true }, 2: { isCounted: true, isPersited: false }, 1: { isCounted: true, isPersited: true }, 0: { isCounted: true, isPersited: true } }; return statusMap[status] || statusMap[3]; }; return MessageTag; })(); RongIMLib.MessageTag = MessageTag; var PublicServiceMenuItem = (function () { function PublicServiceMenuItem(id, name, type, sunMenuItems, url) { this.id = id; this.name = name; this.type = type; this.sunMenuItems = sunMenuItems; this.url = url; } return PublicServiceMenuItem; })(); RongIMLib.PublicServiceMenuItem = PublicServiceMenuItem; // TODO: TBD var PublicServiceProfile = (function () { function PublicServiceProfile(conversationType, introduction, menu, name, portraitUri, publicServiceId, hasFollowed, isGlobal) { this.conversationType = conversationType; this.introduction = introduction; this.menu = menu; this.name = name; this.portraitUri = portraitUri; this.publicServiceId = publicServiceId; this.hasFollowed = hasFollowed; this.isGlobal = isGlobal; } return PublicServiceProfile; })(); RongIMLib.PublicServiceProfile = PublicServiceProfile; var UserInfo = (function () { function UserInfo(id, name, portraitUri) { this.id = id; this.name = name; this.portraitUri = portraitUri; } return UserInfo; })(); RongIMLib.UserInfo = UserInfo; var User = (function () { function User(id, token) { this.id = id; this.token = token; } return User; })(); RongIMLib.User = User; var Room = (function () { function Room(id, user, mode, broadcastType, type) { this.id = id; this.user = user; this.mode = mode; this.broadcastType = broadcastType; this.type = type; } return Room; })(); RongIMLib.Room = Room; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var ServerDataProvider = (function () { function ServerDataProvider() { this.userStatusListener = null; this.Conversation = { watcher: new RongIMLib.Observer(), watch: function (_watcher) { this.watcher.add(_watcher); var conversationList = RongIMLib.RongIMClient._memoryStore.conversationList; this.watcher.emit(conversationList); }, unwatch: function (_watcher) { this.watcher.remove(_watcher); }, _notify: function (conversationList) { this.watcher.emit(conversationList); } }; } ServerDataProvider.prototype.init = function (appKey, options) { new RongIMLib.FeatureDectector(options.appCallback); }; ServerDataProvider.prototype.connect = function (token, callback, userId, option) { RongIMLib.Logger.reportRTLog(); option = option || {}; var self = this; var isReconnect = option.isReconnect; var isIgnoreReportStart = option.isIgnoreReportStart; var StartReportTag = isReconnect ? RongIMLib.LoggerTag.IM.L_RECO_T : RongIMLib.LoggerTag.IM.A_CONN_T; var EndReportTag = isReconnect ? RongIMLib.LoggerTag.IM.L_RECO_R : RongIMLib.LoggerTag.IM.A_CONN_R; !isIgnoreReportStart && RongIMLib.Logger.writeLog({ tag: StartReportTag, level: RongIMLib.LoggerLevel.I, type: RongIMLib.LoggerType.IM, content: { "token": token } }); RongIMLib.RongIMClient.bridge = RongIMLib.Bridge.getInstance(); RongIMLib.RongIMClient._memoryStore.token = token; RongIMLib.RongIMClient._memoryStore.callback = callback; userId = userId || ''; option = option || {}; var isConnecting = false, isConnected = false; if (RongIMLib.Bridge._client && RongIMLib.Bridge._client.channel) { isConnecting = (RongIMLib.Bridge._client.channel.connectionStatus == RongIMLib.ConnectionStatus.CONNECTING); isConnected = (RongIMLib.Bridge._client.channel.connectionStatus == RongIMLib.ConnectionStatus.CONNECTED); } if (isConnected || isConnecting) { return; } var isGreater = (RongIMLib.RongIMClient.otherDeviceLoginCount > 5); if (isGreater) { callback.onError(RongIMLib.ConnectionStatus.ULTRALIMIT); return; } // 清除本地导航缓存 if (option.force) { RongIMLib.RongIMClient._storageProvider.removeItem('servers'); } RongIMLib.RongIMClient.bridge.setListener(); RongIMLib.RongIMClient.bridge.connect(RongIMLib.RongIMClient._memoryStore.appKey, token, { onSuccess: function (data) { setTimeout(function () { callback.onSuccess(data); RongIMLib.RongIMClient._memoryStore.networkUnavailable = false; RongIMLib.Logger.loggerCache.userId = data; RongIMLib.Logger.writeLog({ tag: EndReportTag, level: RongIMLib.LoggerLevel.I, type: RongIMLib.LoggerType.IM, content: { desc: 'connection succeeded' } }); self.conversationStatusManager = new RongIMLib.ConversationStatusManager({ appkey: RongIMLib.RongIMClient._memoryStore.appKey, userId: data, server: self }); self.conversationStatusManager.watchChanged(function (status) { RongIMLib.RongUtil.forEach(RongIMLib.RongIMClient.conversationStatusListeners, function (event) { event(status); }); }); self.conversationStatusManager.pull({ isForce: true }); }); }, onError: function (e) { if (e == RongIMLib.ConnectionState.TOKEN_INCORRECT || !e) { setTimeout(function () { callback.onTokenIncorrect(); RongIMLib.Logger.writeLog({ tag: EndReportTag, level: RongIMLib.LoggerLevel.E, type: RongIMLib.LoggerType.IM, content: { ConnectionState: RongIMLib.ConnectionState.TOKEN_INCORRECT } }); }); } else { setTimeout(function () { callback.onError(e); RongIMLib.Logger.writeLog({ tag: EndReportTag, level: RongIMLib.LoggerLevel.E, type: RongIMLib.LoggerType.IM, content: { code: e } }); }); } } }); }; /* config.auto: 默认 false, true 启用自动重连,启用则为必选参数 config.rate: 重试频率 [100, 1000, 3000, 6000, 10000, 18000] 单位为毫秒,可选 config.url: 网络嗅探地址 [http(s)://]cdn.ronghub.com/RongIMLib-2.2.6.min.js 可选 */ ServerDataProvider.prototype.reconnect = function (callback, config) { var store = RongIMLib.RongIMClient._memoryStore; var token = store.token; if (!token) { throw new Error('reconnect: token is empty.'); } if (RongIMLib.Bridge._client && RongIMLib.Bridge._client.channel && RongIMLib.Bridge._client.channel.connectionStatus != RongIMLib.ConnectionStatus.CONNECTED && RongIMLib.Bridge._client.channel.connectionStatus != RongIMLib.ConnectionStatus.CONNECTING) { config = config || {}; var key = config.auto ? 'auto' : 'custom'; var handler = { auto: function () { var repeatConnect = function (options) { var step = options.step(); var done = 'done'; var url = options.url; var ping = function () { RongIMLib.RongUtil.request({ url: url, success: function () { options.done(); }, error: function () { repeat(); } }); }; var repeat = function () { var next = step(); if (next == 'done') { var error = RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE; options.done(error); return; } setTimeout(ping, next); }; repeat(); }; var protocol = RongIMLib.RongIMClient._memoryStore.depend.protocol; var url = config.url || 'cdn.ronghub.com/RongIMLib-2.2.6.min.js'; var pathConfig = { protocol: protocol, path: url }; url = RongIMLib.RongUtil.formatProtoclPath(pathConfig); var rate = config.rate || [100, 1000, 3000, 6000, 10000, 18000]; //结束标识 rate.push('done'); var opts = { url: url, step: function () { var index = 0; return function () { var time = rate[index]; index++; return time; }; }, done: function (error) { if (error) { callback.onError(error); return; } RongIMLib.RongIMClient.connect(token, callback, null, { isIgnoreReportStart: true, isReconnect: true }); } }; repeatConnect(opts); }, custom: function () { RongIMLib.RongIMClient.connect(token, callback, null, { isIgnoreReportStart: true, isReconnect: true }); } }; handler[key](); } else { var _client = RongIMLib.Bridge._client || {}; var _channel = _client.channel || {}; RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.L_CRAW_F, level: RongIMLib.LoggerLevel.E, type: RongIMLib.LoggerType.IM, content: { msg: { connectionStatus: _channel.connectionStatus }, action: 'reconnect' } }); } }; ServerDataProvider.prototype.logout = function () { RongIMLib.RongIMClient.bridge.disconnect(); RongIMLib.RongIMClient.bridge = null; }; ServerDataProvider.prototype.disconnect = function () { RongIMLib.RongIMClient.bridge.disconnect(); }; ServerDataProvider.prototype.sendReceiptResponse = function (conversationType, targetId, sendCallback) { var rspkey = RongIMLib.Bridge._client.userId + conversationType + targetId + 'RECEIVED', me = this; if (RongIMLib.RongUtil.supportLocalStorage()) { var valObj = JSON.parse(RongIMLib.RongIMClient._storageProvider.getItem(rspkey)); if (valObj) { var vals = []; for (var key in valObj) { var tmp = {}; tmp[key] = valObj[key].uIds; valObj[key].isResponse || vals.push(tmp); } if (vals.length == 0) { sendCallback.onSuccess(); return; } var interval = setInterval(function () { if (vals.length == 1) { clearInterval(interval); } var obj = vals.splice(0, 1)[0]; var rspMsg = new RongIMLib.ReadReceiptResponseMessage({ receiptMessageDic: obj }); me.sendMessage(conversationType, targetId, rspMsg, { onSuccess: function (msg) { var senderUserId = RongIMLib.MessageUtil.getFirstKey(obj); valObj[senderUserId].isResponse = true; RongIMLib.RongIMClient._storageProvider.setItem(rspkey, JSON.stringify(valObj)); sendCallback.onSuccess(msg); }, onError: function (error, msg) { sendCallback.onError(error, msg); } }); }, 200); } else { sendCallback.onSuccess(); } } else { sendCallback.onSuccess(); } }; ServerDataProvider.prototype.sendTypingStatusMessage = function (conversationType, targetId, messageName, sendCallback) { var me = this; if (messageName in RongIMLib.RongIMClient.MessageParams) { me.sendMessage(conversationType, targetId, RongIMLib.TypingStatusMessage.obtain(RongIMLib.RongIMClient.MessageParams[messageName].objectName, ""), { onSuccess: function () { setTimeout(function () { sendCallback.onSuccess(); }); }, onError: function (errorCode) { setTimeout(function () { sendCallback.onError(errorCode, null); }); }, onBefore: function () { } }); } }; ServerDataProvider.prototype.sendRecallMessage = function (content, sendMessageCallback) { var msg = new RongIMLib.RecallCommandMessage({ conversationType: content.conversationType, targetId: content.targetId, sentTime: content.sentTime, messageUId: content.messageUId, extra: content.extra, user: content.user }); this.sendMessage(content.conversationType, content.senderUserId, msg, sendMessageCallback, false, null, null, 2); }; ServerDataProvider.prototype.sendTextMessage = function (conversationType, targetId, content, sendMessageCallback) { var msgContent = RongIMLib.TextMessage.obtain(content); this.sendMessage(conversationType, targetId, msgContent, sendMessageCallback); }; ServerDataProvider.prototype.getRemoteHistoryMessages = function (conversationType, targetId, timestamp, count, callback, config) { if (count <= 1) { throw new Error("the count must be greater than 1."); } config = config || {}; var order = config.order || 0; var getKey = function () { return [conversationType, targetId, '_', order].join(''); }; var key = getKey(); if (!RongIMLib.RongUtil.isNumber(timestamp)) { timestamp = RongIMLib.RongIMClient._memoryStore.lastReadTime.get(key); } var memoryStore = RongIMLib.RongIMClient._memoryStore; var historyMessageLimit = memoryStore.historyMessageLimit; /* limit 属性: var limit = { time: '时间戳, 最后一次拉取时间', hasMore: '是否还有历史消息, bool 值' }; */ var limit = historyMessageLimit.get(key) || {}; var hasMore = limit.hasMore; var isFecth = (hasMore || limit.time != timestamp); // 正序获取消息时不做限制,防止有新消息导致无法获取 if (!isFecth && order == 0) { return callback.onSuccess([], hasMore); } var modules = new RongIMLib.RongIMClient.Protobuf.HistoryMsgInput(), self = this; modules.setTargetId(targetId); modules.setTime(timestamp); modules.setCount(count); modules.setOrder(order); var topic = HistoryMsgType[conversationType] || HistoryMsgType[RongIMLib.ConversationType.PRIVATE]; RongIMLib.RongIMClient.bridge.queryMsg(topic, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), targetId, { onSuccess: function (data) { var fetchTime = RongIMLib.MessageUtil.int64ToTimestamp(data.syncTime); RongIMLib.RongIMClient._memoryStore.lastReadTime.set(key, fetchTime); historyMessageLimit.set(key, { hasMore: !!data.hasMsg, time: fetchTime }); var list = data.list.reverse(), tempMsg = null, tempDir; var read = RongIMLib.SentStatus.READ; if (RongIMLib.RongUtil.supportLocalStorage()) { for (var i = 0, len = list.length; i < len; i++) { tempMsg = RongIMLib.MessageUtil.messageParser(list[i]); tempDir = JSON.parse(RongIMLib.RongIMClient._storageProvider.getItem(RongIMLib.Bridge._client.userId + tempMsg.messageUId + "SENT")); if (tempDir) { tempMsg.receiptResponse || (tempMsg.receiptResponse = {}); tempMsg.receiptResponse[tempMsg.messageUId] = tempDir.count; } tempMsg.sentStatus = read; tempMsg.targetId = targetId; list[i] = tempMsg; } } else { for (var i = 0, len = list.length; i < len; i++) { var tempMsg = RongIMLib.MessageUtil.messageParser(list[i]); tempMsg.sentStatus = read; list[i] = tempMsg; } } setTimeout(function () { callback.onSuccess(list, !!data.hasMsg); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }, "HistoryMessagesOuput"); }; ServerDataProvider.prototype.hasRemoteUnreadMessages = function (token, callback) { var xss = null; window.RCCallback = function (x) { setTimeout(function () { callback.onSuccess(!!+x.status); }); xss.parentNode.removeChild(xss); }; xss = document.createElement("script"); xss.src = RongIMLib.RongIMClient._memoryStore.depend.api + "/message/exist.js?appKey=" + encodeURIComponent(RongIMLib.RongIMClient._memoryStore.appKey) + "&token=" + encodeURIComponent(token) + "&callBack=RCCallback&_=" + RongIMLib.RongUtil.getTimestamp(); document.body.appendChild(xss); xss.onerror = function () { setTimeout(function () { callback.onError(RongIMLib.ErrorCode.UNKNOWN); }); xss.parentNode.removeChild(xss); }; }; ServerDataProvider.prototype.getRemoteConversationList = function (callback, conversationTypes, count) { var modules = new RongIMLib.RongIMClient.Protobuf.RelationsInput(), self = this; modules.setType(1); if (typeof count == 'undefined') { modules.setCount(0); } else { modules.setCount(count); } RongIMLib.RongIMClient.bridge.queryMsg(26, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (list) { if (list.info) { list.info = list.info.reverse(); for (var i = 0, len = list.info.length; i < len; i++) { RongIMLib.RongIMClient.getInstance().pottingConversation(list.info[i]); } } var conversations = RongIMLib.RongIMClient._memoryStore.conversationList; setTimeout(function () { if (conversationTypes) { return callback.onSuccess(self.filterConversations(conversationTypes, conversations)); } callback.onSuccess(conversations); }); }, onError: function (error) { callback.onError(error); } }, "RelationsOutput"); }; ServerDataProvider.prototype.addMemberToDiscussion = function (discussionId, userIdList, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.ChannelInvitationInput(); modules.setUsers(userIdList); RongIMLib.RongIMClient.bridge.queryMsg(0, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), discussionId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.createDiscussion = function (name, userIdList, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.CreateDiscussionInput(), self = this; modules.setName(name); RongIMLib.RongIMClient.bridge.queryMsg(1, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (discussId) { if (userIdList.length > 0) { self.addMemberToDiscussion(discussId, userIdList, { onSuccess: function () { }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); } setTimeout(function () { callback.onSuccess(discussId); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }, "CreateDiscussionOutput"); }; ServerDataProvider.prototype.getDiscussion = function (discussionId, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.ChannelInfoInput(); modules.setNothing(1); RongIMLib.RongIMClient.bridge.queryMsg(4, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), discussionId, { onSuccess: function (data) { setTimeout(function () { callback.onSuccess(data); }); }, onError: function (errorCode) { setTimeout(function () { callback.onError(errorCode); }); } }, "ChannelInfoOutput"); }; ServerDataProvider.prototype.quitDiscussion = function (discussionId, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.LeaveChannelInput(); modules.setNothing(1); RongIMLib.RongIMClient.bridge.queryMsg(7, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), discussionId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (errorCode) { setTimeout(function () { callback.onError(errorCode); }); } }); }; ServerDataProvider.prototype.removeMemberFromDiscussion = function (discussionId, userId, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.ChannelEvictionInput(); modules.setUser(userId); RongIMLib.RongIMClient.bridge.queryMsg(9, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), discussionId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (errorCode) { setTimeout(function () { callback.onError(errorCode); }); } }); }; ServerDataProvider.prototype.setDiscussionInviteStatus = function (discussionId, status, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.ModifyPermissionInput(); modules.setOpenStatus(status.valueOf()); RongIMLib.RongIMClient.bridge.queryMsg(11, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), discussionId, { onSuccess: function (x) { setTimeout(function () { callback.onSuccess(); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.setDiscussionName = function (discussionId, name, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RenameChannelInput(); modules.setName(name); RongIMLib.RongIMClient.bridge.queryMsg(12, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), discussionId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (errcode) { callback.onError(errcode); } }); }; ServerDataProvider.prototype.joinChatRoom = function (chatroomId, messageCount, callback) { RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.A_JCTR_T, level: RongIMLib.LoggerLevel.I, type: RongIMLib.LoggerType.IM, content: { chatroomId: chatroomId } }); var e = new RongIMLib.RongIMClient.Protobuf.ChrmInput(); e.setNothing(1); RongIMLib.Bridge._client.chatroomId = chatroomId; RongIMLib.RongIMClient.bridge.queryMsg(19, RongIMLib.MessageUtil.ArrayForm(e.toArrayBuffer()), chatroomId, { onSuccess: function () { var navi = RongIMLib.RongIMClient.getInstance().getNavi(); var isOpenKVStorage = navi.kvStorage; if (isOpenKVStorage) { RongIMLib.RongIMClient._dataAccessProvider.pullChatroomEntry(chatroomId, 0, { onSuccess: function (result) { RongIMLib.ChrmKVHandler.setEntries(chatroomId, result); setTimeout(function () { callback.onSuccess(); RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.A_JCTR_R, level: RongIMLib.LoggerLevel.I, type: RongIMLib.LoggerType.IM, content: { chatroomId: chatroomId } }); }); }, onError: function (errorCode) { setTimeout(function () { callback.onError(errorCode); RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.A_JCTR_R, level: RongIMLib.LoggerLevel.W, type: RongIMLib.LoggerType.IM, content: { chatroomId: chatroomId, error: errorCode } }); }); } }); } else { setTimeout(function () { RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.A_JCTR_R, level: RongIMLib.LoggerLevel.I, type: RongIMLib.LoggerType.IM, content: { chatroomId: chatroomId } }); callback.onSuccess(); }); } var modules = new RongIMLib.RongIMClient.Protobuf.ChrmPullMsg(); messageCount == 0 && (messageCount = -1); modules.setCount(messageCount); modules.setSyncTime(0); RongIMLib.Bridge._client.queryMessage("chrmPull", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), chatroomId, 1, { onSuccess: function (collection) { var list = collection.list; var sync = RongIMLib.MessageUtil.int64ToTimestamp(collection.syncTime); var latestMessage = list[list.length - 1]; if (latestMessage) { latestMessage = RongIMLib.MessageUtil.messageParser(latestMessage); sync = latestMessage.sentTime; } RongIMLib.RongIMClient._memoryStore.lastReadTime.set(chatroomId + RongIMLib.Bridge._client.userId + "CST", sync); var _client = RongIMLib.Bridge._client; for (var i = 0, mlen = list.length; i < mlen; i++) { var uId = 'R' + list[i].msgId; if (!(uId in _client.cacheMessageIds)) { _client.cacheMessageIds[uId] = true; var cacheUIds = RongIMLib.RongUtil.keys(_client.cacheMessageIds); if (cacheUIds.length > 10) { uId = cacheUIds[0]; delete _client.cacheMessageIds[uId]; } if (RongIMLib.RongIMClient._memoryStore.filterMessages.length > 0) { for (var j = 0, flen = RongIMLib.RongIMClient._memoryStore.filterMessages.length; j < flen; j++) { if (RongIMLib.RongIMClient.MessageParams[RongIMLib.RongIMClient._memoryStore.filterMessages[j]].objectName != list[i].classname) { _client.handler.onReceived(list[i]); } } } else { _client.handler.onReceived(list[i]); } } } }, onError: function (errcode) { setTimeout(function () { callback.onError(errcode); }); } }, "DownStreamMessages"); }, onError: function (error) { setTimeout(function () { RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.A_JCTR_R, level: RongIMLib.LoggerLevel.W, type: RongIMLib.LoggerType.IM, content: { chatroomId: chatroomId, error: error } }); callback.onError(error); }); } }, "ChrmOutput"); }; ServerDataProvider.prototype.getChatRoomInfo = function (chatRoomId, count, order, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.QueryChatroomInfoInput(); modules.setCount(count); modules.setOrder(order); RongIMLib.RongIMClient.bridge.queryMsg("queryChrmI", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), chatRoomId, { onSuccess: function (ret) { var userInfos = ret.userInfos; userInfos.forEach(function (item) { item.time = RongIMLib.MessageUtil.int64ToTimestamp(item.time); }); setTimeout(function () { callback.onSuccess(ret); }); }, onError: function (errcode) { setTimeout(function () { callback.onError(errcode); }); } }, "QueryChatroomInfoOutput"); }; ServerDataProvider.prototype.quitChatRoom = function (chatroomId, callback) { RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.A_QCTR_T, level: RongIMLib.LoggerLevel.I, type: RongIMLib.LoggerType.IM, content: { chatroomId: chatroomId } }); var e = new RongIMLib.RongIMClient.Protobuf.ChrmInput(); e.setNothing(1); RongIMLib.RongIMClient.bridge.queryMsg(17, RongIMLib.MessageUtil.ArrayForm(e.toArrayBuffer()), chatroomId, { onSuccess: function () { setTimeout(function () { RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.A_QCTR_R, level: RongIMLib.LoggerLevel.I, type: RongIMLib.LoggerType.IM, content: { chatroomId: chatroomId } }); callback.onSuccess(); }); }, onError: function (errcode) { setTimeout(function () { RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.A_QCTR_R, level: RongIMLib.LoggerLevel.W, type: RongIMLib.LoggerType.IM, content: { chatroomId: chatroomId, error: errcode } }); callback.onError(errcode); }); } }, "ChrmOutput"); }; ServerDataProvider.prototype.setChatroomHisMessageTimestamp = function (chatRoomId, timestamp) { RongIMLib.RongIMClient._memoryStore.lastReadTime.set('chrhis_' + chatRoomId, timestamp); }; ServerDataProvider.prototype.getChatRoomHistoryMessages = function (chatRoomId, count, order, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.HistoryMsgInput(); modules.setTargetId(chatRoomId); var timestamp = RongIMLib.RongIMClient._memoryStore.lastReadTime.get('chrhis_' + chatRoomId) || 0; modules.setTime(timestamp); modules.setCount(count); modules.setOrder(order); RongIMLib.RongIMClient.bridge.queryMsg(34, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (data) { RongIMLib.RongIMClient._memoryStore.lastReadTime.set('chrhis_' + chatRoomId, RongIMLib.MessageUtil.int64ToTimestamp(data.syncTime)); var list = data.list.reverse(); for (var i = 0, len = list.length; i < len; i++) { list[i] = RongIMLib.MessageUtil.messageParser(list[i]); } setTimeout(function () { callback.onSuccess(list, !!data.hasMsg); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }, "HistoryMsgOuput"); }; ServerDataProvider.prototype.setChatroomEntry = function (chatroomId, chatroomEntry, callback) { var opt = RongIMLib.ChatroomEntityOpt.UPDATE; var key = chatroomEntry.key, value = chatroomEntry.value; var isKeyInValid = !RongIMLib.RongUtil.isLengthLimit(key, RongIMLib.ChatroomEntityLimit.KEY, 1) || !RongIMLib.ChrmKVHandler.isKeyValid(key); var isValueInValid = !RongIMLib.RongUtil.isLengthLimit(value, RongIMLib.ChatroomEntityLimit.VALUE, 1); if (isKeyInValid || isValueInValid) { setTimeout(function () { callback.onError(RongIMLib.ErrorCode.BIZ_ERROR_INVALID_PARAMETER); }); } else { this.refreshChatroomEntry(chatroomId, chatroomEntry, opt, callback); } }; ServerDataProvider.prototype.forceSetChatroomEntry = function (chatroomId, chatroomEntry, callback) { chatroomEntry.isOverwrite = true; this.setChatroomEntry(chatroomId, chatroomEntry, callback); }; ServerDataProvider.prototype.removeChatroomEntry = function (chatroomId, chatroomEntry, callback) { var opt = RongIMLib.ChatroomEntityOpt.DELETE; var key = chatroomEntry.key; var isKeyInValid = !RongIMLib.RongUtil.isLengthLimit(key, RongIMLib.ChatroomEntityLimit.KEY, 1) || !RongIMLib.ChrmKVHandler.isKeyValid(key); if (isKeyInValid) { setTimeout(function () { callback.onError(RongIMLib.ErrorCode.BIZ_ERROR_INVALID_PARAMETER); }); } else { this.refreshChatroomEntry(chatroomId, chatroomEntry, opt, callback); } }; ServerDataProvider.prototype.forceRemoveChatroomEntry = function (chatroomId, chatroomEntry, callback) { chatroomEntry.isOverwrite = true; this.removeChatroomEntry(chatroomId, chatroomEntry, callback); }; ServerDataProvider.prototype.refreshChatroomEntry = function (chatroomId, chatroomEntry, chatroomEntryOpt, callback) { var modules, topic; var key = chatroomEntry.key, value = chatroomEntry.value || '', extra = chatroomEntry.notificationExtra; if (chatroomEntryOpt === RongIMLib.ChatroomEntityOpt.DELETE) { modules = new RongIMLib.RongIMClient.Protobuf.DeleteChrmKV(); topic = 'delKV'; } else { modules = new RongIMLib.RongIMClient.Protobuf.SetChrmKV(); topic = 'setKV'; } var status = RongIMLib.RongInnerTools.getChrmEntityStatus(chatroomEntry, chatroomEntryOpt); var currentUserId = RongIMLib.RongIMClient.getInstance().getCurrentUserId(); var entry = { key: key, value: value, uid: currentUserId }; if (status) { entry.status = status; } modules.setEntry(entry); if (chatroomEntry.isSendNotification) { modules.setBNotify(true); var msgModules = new RongIMLib.RongIMClient.Protobuf.UpStreamMessage(); var msg = new RongIMLib.ChrmKVNotificationMessage({ key: key, value: value, extra: extra, type: chatroomEntryOpt }); msgModules.setSessionId(RongIMLib.RongIMClient.MessageParams[msg.messageName].msgTag.getMessageTag()); msgModules.setClassname(RongIMLib.RongIMClient.MessageParams[msg.messageName].objectName); msgModules.setContent(msg.encode()); modules.setNotification(msgModules); // 默认设置为 聊天室消息 modules.setType(RongIMLib.ConversationType.CHATROOM); } RongIMLib.RongIMClient.bridge.queryMsg(topic, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), chatroomId, { onSuccess: function (ret) { var currentUserId = RongIMLib.RongIMClient.getInstance().getCurrentUserId(); RongIMLib.ChrmKVHandler.setEntry(chatroomId, chatroomEntry, status, currentUserId); setTimeout(function () { callback.onSuccess(!!ret); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }, 'ChrmOutput'); }; ServerDataProvider.prototype.getChatroomEntry = function (chatroomId, key, callback) { var value = RongIMLib.ChrmKVHandler.getEntityValue(chatroomId, key); setTimeout(function () { if (RongIMLib.RongUtil.isEmpty(value)) { callback.onError(RongIMLib.ErrorCode.CHATROOM_KEY_NOT_EXIST); } else { callback.onSuccess(value); } }); }; ServerDataProvider.prototype.getAllChatroomEntries = function (chatroomId, callback) { setTimeout(function () { var entries = RongIMLib.ChrmKVHandler.getAllEntityValue(chatroomId); callback.onSuccess(entries); }); }; ServerDataProvider.prototype.pullChatroomEntry = function (chatroomId, time, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.QueryChrmKV(); modules.setTimestamp(time); RongIMLib.RongIMClient.bridge.queryMsg('pullKV', RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), chatroomId, { onSuccess: function (data) { setTimeout(function () { callback.onSuccess(data); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }, "ChrmKVOutput"); }; ServerDataProvider.prototype.setMessageStatus = function (conversationType, targetId, timestamp, status, callback) { setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.addToBlacklist = function (userId, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.Add2BlackListInput(); modules.setUserId(userId); RongIMLib.RongIMClient.bridge.queryMsg(21, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.getBlacklist = function (callback) { var modules = new RongIMLib.RongIMClient.Protobuf.QueryBlackListInput(); modules.setNothing(1); RongIMLib.RongIMClient.bridge.queryMsg(23, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (list) { setTimeout(function () { callback.onSuccess(list); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }, "QueryBlackListOutput"); }; ServerDataProvider.prototype.getBlacklistStatus = function (userId, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.BlackListStatusInput(); modules.setUserId(userId); RongIMLib.RongIMClient.bridge.queryMsg(24, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function (status) { setTimeout(function () { callback.onSuccess(RongIMLib.BlacklistStatus[status]); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.removeFromBlacklist = function (userId, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RemoveFromBlackListInput(); modules.setUserId(userId); RongIMLib.RongIMClient.bridge.queryMsg(22, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function () { setTimeout(function () { callback.onSuccess(); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.getFileToken = function (fileType, callback) { if (!(/(1|2|3|4)/.test(fileType.toString()))) { setTimeout(function () { callback.onError(RongIMLib.ErrorCode.QNTKN_FILETYPE_ERROR); }); return; } var modules = new RongIMLib.RongIMClient.Protobuf.GetQNupTokenInput(); modules.setType(fileType); RongIMLib.RongIMClient.bridge.queryMsg(30, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (data) { setTimeout(function () { callback.onSuccess(data); }); }, onError: function (errcode) { setTimeout(function () { callback.onError(errcode); }); } }, "GetQNupTokenOutput"); }; ServerDataProvider.prototype.getFileUrl = function (fileType, fileName, oriName, callback) { if (!(/(1|2|3|4)/.test(fileType.toString()))) { setTimeout(function () { callback.onError(RongIMLib.ErrorCode.QNTKN_FILETYPE_ERROR); }); return; } var modules = new RongIMLib.RongIMClient.Protobuf.GetQNdownloadUrlInput(); modules.setType(fileType); modules.setKey(fileName); if (oriName) { modules.setFileName(oriName); } RongIMLib.RongIMClient.bridge.queryMsg(31, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (data) { setTimeout(function () { callback.onSuccess(data); }); }, onError: function (errcode) { setTimeout(function () { callback.onError(errcode); }); } }, "GetQNdownloadUrlOutput"); }; ServerDataProvider.prototype.getPullSetting = function (callback) { var modules = new RongIMLib.RongIMClient.Protobuf.PullUserSettingInput(); var version = parseInt(RongIMLib.RongIMClient.sdkver); modules.setVersion(version); RongIMLib.RongIMClient.bridge.queryMsg('pullUS', RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (result) { result = result || {}; result.version = RongIMLib.MessageUtil.int64ToTimestamp(result.version); setTimeout(function () { callback.onSuccess(result); }); }, onError: function (errcode) { setTimeout(function () { callback.onError(errcode); }); } }, 'PullUserSettingOutput'); }; ServerDataProvider.prototype.setOfflineMessageDuration = function (duration, callback) { this.getPullSetting({ onSuccess: function (result) { /** * GetQNupTokenOutput 第一位为 int64, 第二位为 string, 与设置离线消息一致 * 为避免修改 Protobuf 带来的更新成本. 仅复用, 不重新命名 */ var modules = new RongIMLib.RongIMClient.Protobuf.GetQNupTokenOutput(); var version = result.version; modules.setDeadline(version); modules.setToken(duration + ''); RongIMLib.RongIMClient.bridge.queryMsg('setOfflineMsgDur', RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (data) { setTimeout(function () { callback.onSuccess(data); }); }, onError: function (errcode) { setTimeout(function () { callback.onError(errcode); }); } }); }, onError: callback.onError }); }; /* methodType 1 : 多客服(客服后台使用); 2 : 消息撤回 params.userIds : 定向消息接收者 */ ServerDataProvider.prototype.sendMessage = function (conversationType, targetId, messageContent, sendCallback, mentiondMsg, pushText, appData, methodType, params) { if (!RongIMLib.Bridge._client.channel) { setTimeout(function () { sendCallback.onError(RongIMLib.ErrorCode.RC_NET_UNAVAILABLE, null); }); return; } if (!RongIMLib.Bridge._client.channel.socket.socket.connected) { setTimeout(function () { sendCallback.onError(RongIMLib.ErrorCode.TIMEOUT, null); }); throw new Error("connect is timeout! postion:sendMessage"); } var isGroup = (conversationType == RongIMLib.ConversationType.DISCUSSION || conversationType == RongIMLib.ConversationType.GROUP); var modules = new RongIMLib.RongIMClient.Protobuf.UpStreamMessage(); if (mentiondMsg && isGroup) { modules.setSessionId(7); } else { modules.setSessionId(RongIMLib.RongIMClient.MessageParams[messageContent.messageName].msgTag.getMessageTag()); } pushText && modules.setPushText(pushText); appData && modules.setAppData(appData); if (isGroup && messageContent.messageName == RongIMLib.RongIMClient.MessageType["ReadReceiptResponseMessage"]) { var rspMsg = messageContent; if (rspMsg.receiptMessageDic) { var ids = []; for (var key in rspMsg.receiptMessageDic) { ids.push(key); } modules.setUserId(ids); } } if (isGroup && messageContent.messageName == RongIMLib.RongIMClient.MessageType["SyncReadStatusMessage"]) { modules.setUserId(RongIMLib.Bridge._client.userId); } params = params || {}; var userIds = params.userIds; if (userIds) { modules.setUserId(userIds); } var flag = 0; if (params.isPush || params.isVoipPush) { flag |= 0x01; } if (params.isFilerWhiteBlacklist) { flag |= 0x02; } modules.setConfigFlag(flag); modules.setClassname(RongIMLib.RongIMClient.MessageParams[messageContent.messageName].objectName); var encodedContent = messageContent.encode(); if (RongIMLib.RongUtil.getByteLength(encodedContent) > RongIMLib.RongIMClient.MaxMessageContentBytes) { setTimeout(function () { sendCallback.onError(RongIMLib.ErrorCode.RC_MSG_CONTENT_EXCEED_LIMIT); }); return; } modules.setContent(encodedContent); var content = modules.toArrayBuffer(); if (Object.prototype.toString.call(content) == "[object ArrayBuffer]") { content = [].slice.call(new Int8Array(content)); } var me = this, msg = new RongIMLib.Message(); var c = this.getConversation(conversationType, targetId); if (RongIMLib.RongIMClient.MessageParams[messageContent.messageName].msgTag.getMessageTag() == 3) { if (!c) { c = RongIMLib.RongIMClient.getInstance().createConversation(conversationType, targetId, ""); } c.sentTime = new Date().getTime(); c.sentStatus = RongIMLib.SentStatus.SENDING; c.senderUserName = ""; c.senderUserId = RongIMLib.Bridge._client.userId; c.notificationStatus = RongIMLib.ConversationNotificationStatus.DO_NOT_DISTURB; c.latestMessage = msg; c.unreadMessageCount = 0; RongIMLib.RongIMClient._dataAccessProvider.addConversation(c, { onSuccess: function (data) { } }); } RongIMLib.RongIMClient._memoryStore.converStore = c; msg.content = messageContent; msg.conversationType = conversationType; msg.senderUserId = RongIMLib.Bridge._client.userId; msg.objectName = RongIMLib.RongIMClient.MessageParams[messageContent.messageName].objectName; msg.targetId = targetId; msg.sentTime = new Date().getTime(); msg.messageDirection = RongIMLib.MessageDirection.SEND; msg.sentStatus = RongIMLib.SentStatus.SENT; msg.messageType = messageContent.messageName; RongIMLib.RongIMClient.bridge.pubMsg(conversationType.valueOf(), content, targetId, { onSuccess: function (data) { if (data && data.timestamp) { RongIMLib.RongIMClient._memoryStore.lastReadTime.set('converST_' + RongIMLib.Bridge._client.userId + conversationType + targetId, data.timestamp); } if ((conversationType == RongIMLib.ConversationType.DISCUSSION || conversationType == RongIMLib.ConversationType.GROUP) && messageContent.messageName == RongIMLib.RongIMClient.MessageType["ReadReceiptRequestMessage"]) { var reqMsg = msg.content; var sentkey = RongIMLib.Bridge._client.userId + reqMsg.messageUId + "SENT"; RongIMLib.RongIMClient._storageProvider.setItem(sentkey, JSON.stringify({ count: 0, dealtime: data.timestamp, userIds: {} })); } if (RongIMLib.RongIMClient.MessageParams[msg.messageType].msgTag.getMessageTag() == 3) { var cacheConversation = RongIMLib.RongIMClient._memoryStore.converStore; cacheConversation.sentStatus = msg.sentStatus; cacheConversation.latestMessage = msg; me.updateConversation(cacheConversation); var Conversation = RongIMLib.RongIMClient._dataAccessProvider.Conversation; Conversation._notify(RongIMLib.RongIMClient._memoryStore.conversationList); RongIMLib.RongIMClient._dataAccessProvider.addMessage(conversationType, targetId, msg, { onSuccess: function (ret) { msg = ret; msg.messageUId = data.messageUId; msg.sentTime = data.timestamp; msg.sentStatus = RongIMLib.SentStatus.SENT; msg.messageId = data.messageId; RongIMLib.RongIMClient._dataAccessProvider.updateMessage(msg); }, onError: function () { } }); } setTimeout(function () { cacheConversation && me.updateConversation(cacheConversation); msg.sentTime = data.timestamp; msg.messageUId = data.messageUId; sendCallback.onSuccess(msg); }); }, onError: function (errorCode, _msg) { msg.sentStatus = RongIMLib.SentStatus.FAILED; if (_msg) { msg.messageUId = _msg.messageUId; msg.sentTime = _msg.sentTime; } if (RongIMLib.RongIMClient.MessageParams[msg.messageType].msgTag.getMessageTag() == 3) { RongIMLib.RongIMClient._memoryStore.converStore.latestMessage = msg; } RongIMLib.RongIMClient._dataAccessProvider.addMessage(conversationType, targetId, msg, { onSuccess: function (ret) { msg.messageId = ret.messageId; RongIMLib.RongIMClient._dataAccessProvider.updateMessage(msg); }, onError: function () { } }); setTimeout(function () { sendCallback.onError(errorCode, msg); }); } }, null, methodType, params); sendCallback.onBefore && sendCallback.onBefore(RongIMLib.MessageIdHandler.messageId); msg.messageId = RongIMLib.MessageIdHandler.messageId + ""; }; ServerDataProvider.prototype.setConnectionStatusListener = function (listener) { if (RongIMLib.RongUtil.isObject(listener) && RongIMLib.RongUtil.isFunction(listener.onChanged)) { RongIMLib.RongIMClient.statusListeners.push(listener.onChanged); } }; ServerDataProvider.prototype.setOnReceiveMessageListener = function (listener) { if (RongIMLib.RongUtil.isObject(listener) && RongIMLib.RongUtil.isFunction(listener.onReceived)) { RongIMLib.RongIMClient.messageListeners.push(listener.onReceived); } }; ServerDataProvider.prototype.registerMessageType = function (messageType, objectName, messageTag, messageContent, searchProps) { if (!messageType) { throw new Error("messageType can't be empty,postion -> registerMessageType"); } if (!objectName) { throw new Error("objectName can't be empty,postion -> registerMessageType"); } if (Object.prototype.toString.call(messageContent) == "[object Array]") { var regMsg = RongIMLib.ModelUtil.modleCreate(messageContent, messageType); RongIMLib.RongIMClient.RegisterMessage[messageType] = regMsg; } else if (Object.prototype.toString.call(messageContent) == "[object Function]" || Object.prototype.toString.call(messageContent) == "[object Object]") { if (!messageContent.encode) { throw new Error("encode method has not realized or messageName is undefined-> registerMessageType"); } if (!messageContent.decode) { throw new Error("decode method has not realized -> registerMessageType"); } } else { throw new Error("The index of 3 parameter was wrong type must be object or function or array-> registerMessageType"); } registerMessageTypeMapping[objectName] = messageType; }; ServerDataProvider.prototype.registerMessageTypes = function (messages) { var types = []; var getProtos = function (proto) { var protos = []; for (var p in proto) { protos.push(p); } return protos; }; //转换消息为自定义消息参数格式 for (var name in messages) { var message = messages[name]; var proto = message.proto; var protos = getProtos(proto); var flag = message.flag || 3; var tag = RongIMLib.MessageTag.getTagByStatus(flag); flag = new RongIMLib.MessageTag(tag.isCounted, tag.isPersited); types.push({ type: name, name: message.name, flag: flag, protos: protos }); } var register = function (message) { var type = message.type; var name = message.name; var flag = message.flag; var protos = message.protos; RongIMLib.RongIMClient.registerMessageType(type, name, flag, protos); }; for (var i = 0, len = types.length; i < len; i++) { var message = types[i]; register(message); } }; ServerDataProvider.prototype.addConversation = function (conversation, callback) { var isAdd = true; for (var i = 0, len = RongIMLib.RongIMClient._memoryStore.conversationList.length; i < len; i++) { if (RongIMLib.RongIMClient._memoryStore.conversationList[i].conversationType === conversation.conversationType && RongIMLib.RongIMClient._memoryStore.conversationList[i].targetId === conversation.targetId) { // RongIMClient._memoryStore.conversationList[i] = conversation; RongIMLib.RongIMClient._memoryStore.conversationList.unshift(RongIMLib.RongIMClient._memoryStore.conversationList.splice(i, 1)[0]); isAdd = false; break; } } if (isAdd) { RongIMLib.RongIMClient._memoryStore.conversationList.unshift(conversation); } callback && callback.onSuccess(true); }; ServerDataProvider.prototype.updateConversation = function (conversation) { var conver; for (var i = 0, len = RongIMLib.RongIMClient._memoryStore.conversationList.length; i < len; i++) { var item = RongIMLib.RongIMClient._memoryStore.conversationList[i]; if (conversation.conversationType === item.conversationType && conversation.targetId === item.targetId) { conversation.conversationTitle && (item.conversationTitle = conversation.conversationTitle); conversation.senderUserName && (item.senderUserName = conversation.senderUserName); conversation.senderPortraitUri && (item.senderPortraitUri = conversation.senderPortraitUri); conversation.latestMessage && (item.latestMessage = conversation.latestMessage); conversation.sentStatus && (item.sentStatus = conversation.sentStatus); break; } } return conver; }; ServerDataProvider.prototype.removeConversation = function (conversationType, targetId, callback) { var mod = new RongIMLib.RongIMClient.Protobuf.RelationsInput(); mod.setType(conversationType); RongIMLib.RongIMClient.bridge.queryMsg(27, RongIMLib.MessageUtil.ArrayForm(mod.toArrayBuffer()), targetId, { onSuccess: function () { var isRemoved = false; var conversations = RongIMLib.RongIMClient._memoryStore.conversationList; var len = conversations.length; for (var i = 0; i < len; i++) { if (conversations[i].conversationType == conversationType && targetId == conversations[i].targetId) { conversations.splice(i, 1); isRemoved = true; break; } } isRemoved && RongIMLib.RongIMClient._dataAccessProvider.Conversation._notify(RongIMLib.RongIMClient._memoryStore.conversationList); callback.onSuccess(true); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.getMessage = function (messageId, callback) { callback.onSuccess(new RongIMLib.Message()); }; ServerDataProvider.prototype.addMessage = function (conversationType, targetId, message, callback) { if (callback) { callback.onSuccess(message); } }; ServerDataProvider.prototype.removeMessage = function (conversationType, targetId, messages, callback) { RongIMLib.RongIMClient.getInstance().deleteRemoteMessages(conversationType, targetId, messages, callback); }; ServerDataProvider.prototype.removeLocalMessage = function (conversationType, targetId, timestamps, callback) { callback.onSuccess(true); }; ServerDataProvider.prototype.updateMessage = function (message, callback) { if (callback) { callback.onSuccess(message); } }; ServerDataProvider.prototype.deleteRemoteMessages = function (conversationType, targetId, messages, callback) { if (!RongIMLib.RongIMClient.Protobuf.DeleteMsgInput) { throw new Error('SDK Protobuf version is too low'); } var modules = new RongIMLib.RongIMClient.Protobuf.DeleteMsgInput(); var msgs = []; RongIMLib.RongUtil.forEach(messages, function (msg) { msgs.push({ msgId: msg.messageUId, msgDataTime: msg.sentTime, direct: msg.messageDirection }); }); modules.setType(conversationType); modules.setConversationId(targetId); modules.setMsgs(msgs); RongIMLib.RongIMClient.bridge.queryMsg('delMsg', RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), targetId, { onSuccess: function (result) { callback.onSuccess(result); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }, 'DeleteMsgOutput'); }; ServerDataProvider.prototype.clearRemoteHistoryMessages = function (params, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.CleanHisMsgInput(); var conversationType = params.conversationType; var _topic = { 1: 'cleanPMsg', 2: 'cleanDMsg', 3: 'cleanGMsg', 5: 'cleanCMsg', 6: 'cleanSMsg' }; var topic = _topic[conversationType]; if (!topic) { callback.onError(RongIMLib.ErrorCode.CLEAR_HIS_TYPE_ERROR); return; } var timestamp = params.timestamp; if (typeof timestamp != 'number') { callback.onError(RongIMLib.ErrorCode.CLEAR_HIS_TIME_ERROR); return; } modules.setDataTime(timestamp); var targetId = params.targetId; modules.setTargetId(targetId); RongIMLib.RongIMClient.bridge.queryMsg(topic, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), targetId, { onSuccess: function (result) { callback.onSuccess(!result); }, onError: function (error) { // error 1 历史消息云存储没有开通、传入时间大于服务器时间 清除失败,1 与其他错误码冲突,所以自定义错误码返回 if (error == 1) { error = RongIMLib.ErrorCode.CLEAR_HIS_ERROR; } setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.clearHistoryMessages = function (params, callback) { this.clearRemoteHistoryMessages(params, callback); }; // 兼容老版本 ServerDataProvider.prototype.clearMessages = function (conversationType, targetId, callback) { }; ServerDataProvider.prototype.updateMessages = function (conversationType, targetId, key, value, callback) { var me = this; if (key == "readStatus") { if (RongIMLib.RongIMClient._memoryStore.conversationList.length > 0) { me.getConversationList({ onSuccess: function (list) { Array.forEach(list, function (conver) { if (conver.conversationType == conversationType && conver.targetId == targetId) { conver.unreadMessageCount = 0; } }); }, onError: function (errorCode) { setTimeout(function () { callback.onError(errorCode); }); } }, null); } } setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.getConversation = function (conversationType, targetId, callback) { var conver = null; for (var i = 0, len = RongIMLib.RongIMClient._memoryStore.conversationList.length; i < len; i++) { if (RongIMLib.RongIMClient._memoryStore.conversationList[i].conversationType == conversationType && RongIMLib.RongIMClient._memoryStore.conversationList[i].targetId == targetId) { conver = RongIMLib.RongIMClient._memoryStore.conversationList[i]; if (RongIMLib.RongUtil.supportLocalStorage()) { // var count = RongIMClient._storageProvider.getItem("cu" + Bridge._client.userId + conversationType + targetId); var count = RongIMLib.UnreadCountHandler.get(conversationType, targetId); if (conver.unreadMessageCount == 0) { conver.unreadMessageCount = Number(count); } } } } setTimeout(function () { callback && callback.onSuccess(conver); }); return conver; }; ServerDataProvider.prototype.filterConversations = function (types, list) { var conversaions = []; RongIMLib.RongUtil.forEach(types, function (type) { RongIMLib.RongUtil.forEach(list, function (conversation) { if (conversation.conversationType == type) { conversaions.push(conversation); } }); }); return conversaions; }; ServerDataProvider.prototype.getConversationList = function (callback, conversationTypes, count, isHidden) { var that = this; var isSync = RongIMLib.RongIMClient._memoryStore.isSyncRemoteConverList; var list = RongIMLib.RongIMClient._memoryStore.conversationList; var isLocalInclude = list.length > count; if (!isSync && isLocalInclude) { setTimeout(function () { var localList = list.slice(0, count); if (conversationTypes) { localList = that.filterConversations(conversationTypes, localList); } callback.onSuccess(localList); }); return; } RongIMLib.RongIMClient.getInstance().getRemoteConversationList({ onSuccess: function (list) { if (RongIMLib.RongUtil.supportLocalStorage()) { Array.forEach(RongIMLib.RongIMClient._memoryStore.conversationList, function (item) { // var count = RongIMClient._storageProvider.getItem("cu" + Bridge._client.userId + item.conversationType + item.targetId); var count = RongIMLib.UnreadCountHandler.get(item.conversationType, item.targetId); if (item.unreadMessageCount == 0) { item.unreadMessageCount = Number(count); } }); } RongIMLib.RongIMClient._memoryStore.isSyncRemoteConverList = false; setTimeout(function () { callback.onSuccess(list); }); }, onError: function (errorcode) { setTimeout(function () { callback.onError(errorcode); }); } }, conversationTypes, count, isHidden); }; ServerDataProvider.prototype.clearCache = function () { var memoryStore = RongIMLib.RongIMClient._memoryStore || {}; memoryStore.conversationList = []; memoryStore.isSyncRemoteConverList = true; }; ServerDataProvider.prototype.clearConversations = function (conversationTypes, callback) { Array.forEach(conversationTypes, function (conversationType) { Array.forEach(RongIMLib.RongIMClient._memoryStore.conversationList, function (conver) { if (conversationType == conver.conversationType) { RongIMLib.RongIMClient.getInstance().removeConversation(conver.conversationType, conver.targetId, { onSuccess: function () { }, onError: function () { } }); } }); }); setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.setMessageContent = function (messageId, content, objectname) { }; ; ServerDataProvider.prototype.setMessageSearchField = function (messageId, content, searchFiles) { }; ; ServerDataProvider.prototype.getHistoryMessages = function (conversationType, targetId, timestamp, count, callback, objectname, order) { var config = { objectname: objectname, order: order }; RongIMLib.RongIMClient.getInstance().getRemoteHistoryMessages(conversationType, targetId, timestamp, count, callback, config); }; ServerDataProvider.prototype.getTotalUnreadCount = function (callback, conversationTypes) { var count = RongIMLib.UnreadCountHandler.getAll(conversationTypes); callback.onSuccess(count); return count; }; ServerDataProvider.prototype.getConversationUnreadCount = function (conversationTypes, callback) { var count = 0; Array.forEach(conversationTypes, function (converType) { Array.forEach(RongIMLib.RongIMClient._memoryStore.conversationList, function (conver) { if (conver.conversationType == converType) { count += conver.unreadMessageCount; } }); }); setTimeout(function () { callback.onSuccess(count); }); }; //由于 Web 端未读消息数按会话统计,撤回消息会导致未读数不准确,提供设置未读数接口,桌面版不实现此方法 ServerDataProvider.prototype.setUnreadCount = function (conversationType, targetId, count, sentTime) { sentTime = sentTime || new Date().getTime(); RongIMLib.UnreadCountHandler.set(conversationType, targetId, count, sentTime); }; ServerDataProvider.prototype.getUnreadCount = function (conversationType, targetId, callback) { var unreadCount = RongIMLib.UnreadCountHandler.get(conversationType, targetId); setTimeout(function () { callback.onSuccess(unreadCount || 0); }); }; ServerDataProvider.prototype.cleanMentioneds = function (conver) { if (conver) { conver.mentionedMsg = null; var targetId = conver.targetId; var conversationType = conver.conversationType; var mentioneds = RongIMLib.RongIMClient._storageProvider.getItem("mentioneds_" + RongIMLib.Bridge._client.userId + '_' + conversationType + '_' + targetId); if (mentioneds) { var info = JSON.parse(mentioneds); delete info[conversationType + "_" + targetId]; if (!RongIMLib.MessageUtil.isEmpty(info)) { RongIMLib.RongIMClient._storageProvider.setItem("mentioneds_" + RongIMLib.Bridge._client.userId + '_' + conversationType + '_' + targetId, JSON.stringify(info)); } else { RongIMLib.RongIMClient._storageProvider.removeItem("mentioneds_" + RongIMLib.Bridge._client.userId + '_' + conversationType + '_' + targetId); } } } }; ServerDataProvider.prototype.clearUnreadCountByTimestamp = function (conversationType, targetId, timestamp, callback) { setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.clearUnreadCount = function (conversationType, targetId, callback) { var me = this; // RongIMClient._storageProvider.removeItem("cu" + Bridge._client.userId + conversationType + targetId); RongIMLib.UnreadCountHandler.remove(conversationType, targetId); this.getConversation(conversationType, targetId, { onSuccess: function (conver) { conver = conver || new RongIMLib.Conversation(); var isNotifyConversation = conver.unreadMessageCount; if (conver) { conver.unreadMessageCount = 0; me.cleanMentioneds(conver); } setTimeout(function () { callback.onSuccess(true); isNotifyConversation && RongIMLib.RongIMClient._dataAccessProvider.Conversation._notify(RongIMLib.RongIMClient._memoryStore.conversationList); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.clearTotalUnreadCount = function (callback) { var list = RongIMLib.RongIMClient._memoryStore.conversationList; var me = this; var isNotifyConversation = false; if (list) { // 清除 mentioneds、清除 list 中的 unreadMessageCount for (var i = 0; i < list.length; i++) { var conver = list[i]; if (conver) { isNotifyConversation = conver.unreadMessageCount ? true : isNotifyConversation; conver.unreadMessageCount = 0; me.cleanMentioneds(conver); } } } RongIMLib.UnreadCountHandler.clear(); setTimeout(function () { callback.onSuccess(true); isNotifyConversation && RongIMLib.RongIMClient._dataAccessProvider.Conversation._notify(RongIMLib.RongIMClient._memoryStore.conversationList); }); }; ServerDataProvider.prototype.setConversationToTop = function (conversationType, targetId, isTop, callback) { var me = this; this.getConversation(conversationType, targetId, { onSuccess: function (conver) { conver.isTop = isTop; me.addConversation(conver, callback); setTimeout(function () { callback.onSuccess(true); }); }, onError: function (error) { setTimeout(function () { callback.onError(error); }); } }); }; ServerDataProvider.prototype.getConversationNotificationStatus = function (params, callback) { var targetId = params.targetId; var conversationType = params.conversationType; var notification = RongIMLib.RongIMClient._memoryStore.notification; var getKey = function () { return conversationType + '_' + targetId; }; var key = getKey(); var status = notification[key]; if (typeof status == 'number') { callback.onSuccess(status); return; } var topics = { 1: 'qryPPush', 3: 'qryDPush' }; var topic = topics[conversationType]; if (!topic) { var error = 8001; callback.onError(error); return; } var modules = new RongIMLib.RongIMClient.Protobuf.BlockPushInput(); modules.setBlockeeId(targetId); var userId = RongIMLib.Bridge._client.userId; var success = function (status) { notification[key] = status; setTimeout(function () { callback.onSuccess(status); }); }; RongIMLib.RongIMClient.bridge.queryMsg(topic, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function (status) { success(status); }, onError: function (e) { if (e == 1) { success(e); } else { setTimeout(function () { callback.onError(e); }); } } }); }; ServerDataProvider.prototype.setConversationStatus = function (type, targetId, statusItem, callback) { var self = this; var modules = new RongIMLib.RongIMClient.Protobuf.SessionStateModifyReq(); var userId = RongIMLib.Bridge._client.userId; var time = +new Date(); var stateItemModules = []; if (!RongIMLib.RongUtil.isUndefined(statusItem.notificationStatus)) { var isNotDisturbe = statusItem.notificationStatus === RongIMLib.ConversationNotificationStatus.DO_NOT_DISTURB; stateItemModules.push({ sessionStateType: 1, value: isNotDisturbe ? '1' : '0' }); } if (!RongIMLib.RongUtil.isUndefined(statusItem.isTop)) { stateItemModules.push({ sessionStateType: 2, value: statusItem.isTop ? '1' : '0' }); } var stateModules = { type: type, channelId: targetId, time: time, stateItem: stateItemModules }; modules.setVersion(time); modules.setState([stateModules]); RongIMLib.RongIMClient.bridge.queryMsg('setSeAtt', RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function (result) { var time = RongIMLib.MessageUtil.int64ToTimestamp(result.version); statusItem.updateTime = time; statusItem.isLastInAPull = true; self.conversationStatusManager.set(type, targetId, statusItem); setTimeout(function () { callback.onSuccess(time); }); }, onError: function (e) { setTimeout(function () { callback.onError(e); }); } }, 'SessionStateModifyResp'); }; ServerDataProvider.prototype.pullConversationStatus = function (time, callback) { time = time || 0; var modules = new RongIMLib.RongIMClient.Protobuf.SessionReq(); modules.setTime(time); var userId = RongIMLib.Bridge._client.userId; RongIMLib.RongIMClient.bridge.queryMsg('pullSeAtts', RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function (result) { var sessionStateList = result.state, lastTime = result.version; var sessionLength = sessionStateList.length; RongIMLib.RongUtil.forEach(sessionStateList, function (state, index) { var type = state.type, targetId = state.channelId, updateTime = state.time, stateItem = state.stateItem; var isSilent = false, isTop = false; RongIMLib.RongUtil.forEach(stateItem, function (item) { var sessionStateType = item.sessionStateType, value = item.value; if (sessionStateType === 1) { isSilent = !!Number(value); } if (sessionStateType === 2) { isTop = !!Number(value); } }); var isLastInAPull = index === sessionLength - 1; callback.onStatus(type, targetId, { notificationStatus: isSilent ? RongIMLib.ConversationNotificationStatus.DO_NOT_DISTURB : RongIMLib.ConversationNotificationStatus.NOTIFY, isTop: isTop, updateTime: RongIMLib.MessageUtil.int64ToTimestamp(updateTime), isLastInAPull: isLastInAPull }); }); callback.onSuccess(RongIMLib.MessageUtil.int64ToTimestamp(lastTime)); }, onError: function (e) { setTimeout(function () { callback.onError(e); }); } }, 'SessionStates'); }; ServerDataProvider.prototype.setConversationNotificationStatus = function (params, callback) { var conversationType = params.conversationType; var targetId = params.targetId; var status = params.status; var getKey = function () { return conversationType + '_' + status; }; var topics = { '1_1': 'blkPPush', '3_1': 'blkDPush', '1_0': 'unblkPPush', '3_0': 'unblkDPush' }; var key = getKey(); var notification = RongIMLib.RongIMClient._memoryStore.notification; notification[key] = status; var topic = topics[key]; if (!topic) { var error = 8001; setTimeout(function () { callback.onError(error); }); return; } var modules = new RongIMLib.RongIMClient.Protobuf.BlockPushInput(); modules.setBlockeeId(targetId); var userId = RongIMLib.Bridge._client.userId; RongIMLib.RongIMClient.bridge.queryMsg(topic, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function (status) { setTimeout(function () { callback.onSuccess(status); }); }, onError: function (e) { setTimeout(function () { callback.onError(e); }); } }); }; ServerDataProvider.prototype.getUserStatus = function (userId, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.GetUserStatusInput(); userId = RongIMLib.Bridge._client.userId; RongIMLib.RongIMClient.bridge.queryMsg(35, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function (status) { status = RongIMLib.RongInnerTools.convertUserStatus(status); setTimeout(function () { callback.onSuccess(status); }); }, onError: function (e) { setTimeout(function () { callback.onError(e); }); } }, 'GetUserStatusOutput'); // callback.onSuccess(new UserStatus()); }; ServerDataProvider.prototype.setUserStatus = function (status, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.SetUserStatusInput(); var userId = RongIMLib.Bridge._client.userId; if (status) { modules.setStatus(status); } RongIMLib.RongIMClient.bridge.queryMsg(36, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function (status) { setTimeout(function () { callback.onSuccess(true); }); }, onError: function (e) { setTimeout(function () { callback.onError(e); }); } }, 'SetUserStatusOutput'); }; ServerDataProvider.prototype.subscribeUserStatus = function (userIds, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.SubUserStatusInput(); var userId = RongIMLib.Bridge._client.userId; modules.setUserid(userIds); RongIMLib.RongIMClient.bridge.queryMsg(37, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), userId, { onSuccess: function (status) { setTimeout(function () { callback && callback.onSuccess(true); }); }, onError: function (e) { setTimeout(function () { callback && callback.onError(e); }); } }, 'SubUserStatusOutput'); }; ServerDataProvider.prototype.setUserStatusListener = function (params, callback) { RongIMLib.RongIMClient.userStatusListener = callback; var userIds = params.userIds || []; if (userIds.length) { RongIMLib.RongIMClient._dataAccessProvider.subscribeUserStatus(userIds); } }; ServerDataProvider.prototype.clearListeners = function () { }; ServerDataProvider.prototype.setServerInfo = function (info) { }; ServerDataProvider.prototype.getUnreadMentionedMessages = function (conversationType, targetId) { return null; }; ServerDataProvider.prototype.setConversationHidden = function (conversationType, targetId, isHidden) { }; ServerDataProvider.prototype.setMessageExtra = function (messageId, value, callback) { setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.setMessageReceivedStatus = function (messageId, receivedStatus, callback) { setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.setMessageSentStatus = function (messageId, sentStatus, callback) { setTimeout(function () { callback.onSuccess(true); }); }; ServerDataProvider.prototype.getAllConversations = function (callback) { setTimeout(function () { callback.onSuccess([]); }); }; ServerDataProvider.prototype.getConversationByContent = function (keywords, callback) { setTimeout(function () { callback.onSuccess([]); }); }; ServerDataProvider.prototype.getMessagesFromConversation = function (conversationType, targetId, keywords, callback) { setTimeout(function () { callback.onSuccess([]); }); }; ServerDataProvider.prototype.searchConversationByContent = function (keyword, callback, conversationTypes) { setTimeout(function () { callback.onSuccess([]); }); }; ServerDataProvider.prototype.searchMessageByContent = function (conversationType, targetId, keyword, timestamp, count, total, callback) { setTimeout(function () { callback.onSuccess([]); }); }; ServerDataProvider.prototype.getDelaTime = function () { return RongIMLib.RongIMClient._memoryStore.deltaTime; }; ServerDataProvider.prototype.getCurrentConnectionStatus = function () { var client = RongIMLib.Bridge._client || {}; var channel = client.channel || {}; var status = RongIMLib.ConnectionStatus.CONNECTION_CLOSED; if (typeof channel.connectionStatus == 'number') { status = channel.connectionStatus; } return status; }; ServerDataProvider.prototype.getAgoraDynamicKey = function (engineType, channelName, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.VoipDynamicInput(); modules.setEngineType(engineType); modules.setChannelName(channelName); RongIMLib.RongIMClient.bridge.queryMsg(32, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (result) { setTimeout(function () { callback.onSuccess(result); }); }, onError: function (errorCode) { setTimeout(function () { callback.onError(errorCode); }); } }, "VoipDynamicOutput"); }; ServerDataProvider.prototype.setDeviceInfo = function (deviceId) { }; ServerDataProvider.prototype.setEnvironment = function (isPrivate) { }; ServerDataProvider.prototype.clearData = function () { return true; }; ServerDataProvider.prototype.getPublicServiceProfile = function (publicServiceType, publicServiceId, callback) { var profile = RongIMLib.RongIMClient._memoryStore.publicServiceMap.get(publicServiceType, publicServiceId); setTimeout(function () { callback.onSuccess(profile); }); }; ServerDataProvider.prototype.getRemotePublicServiceList = function (callback, pullMessageTime) { if (RongIMLib.RongIMClient._memoryStore.depend.openMp) { var modules = new RongIMLib.RongIMClient.Protobuf.PullMpInput(), self = this; if (!pullMessageTime) { modules.setTime(0); } else { modules.setTime(pullMessageTime); } modules.setMpid(""); RongIMLib.RongIMClient.bridge.queryMsg(28, RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), RongIMLib.Bridge._client.userId, { onSuccess: function (data) { //TODO 找出最大时间 // self.lastReadTime.set(conversationType + targetId, MessageUtil.int64ToTimestamp(data.syncTime)); RongIMLib.RongIMClient._memoryStore.publicServiceMap.publicServiceList.length = 0; RongIMLib.RongIMClient._memoryStore.publicServiceMap.publicServiceList = data; setTimeout(function () { callback && callback.onSuccess(data); }); }, onError: function (errorCode) { setTimeout(function () { callback && callback.onError(errorCode); }); } }, "PullMpOutput"); } }; ServerDataProvider.prototype.getRTCUserInfoList = function (room, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcQueryListInput(); // 1 是正序,2是倒序 modules.setOrder(2); RongIMLib.RongIMClient.bridge.queryMsg("rtcUData", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function (result) { var users = {}; var list = result.list; RongIMLib.RongUtil.forEach(list, function (item) { var userId = item.userId; var tmpData = {}; RongIMLib.RongUtil.forEach(item.userData, function (data) { var key = data.key; var value = data.value; tmpData[key] = value; }); users[userId] = tmpData; }); callback.onSuccess(users); }, onError: function (errorCode) { callback.onError(errorCode); } }, "RtcUserListOutput"); }; ServerDataProvider.prototype.getRTCUserList = function (room, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcQueryListInput(); modules.setOrder(2); RongIMLib.RongIMClient.bridge.queryMsg("rtcUList", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function (result) { callback.onSuccess({ users: result.list }); }, onError: function (errorCode) { callback.onError(errorCode); } }, "RtcUserListOutput"); }; ServerDataProvider.prototype.setRTCUserInfo = function (room, info, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcValueInfo(); modules.setKey(info.key); modules.setValue(info.value); RongIMLib.RongIMClient.bridge.queryMsg("rtcUPut", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function () { callback.onSuccess(true); }, onError: function (errorCode) { callback.onError(errorCode); } }); }; ServerDataProvider.prototype.removeRTCUserInfo = function (room, info, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcKeyDeleteInput(); var keys = info.keys || []; if (!RongIMLib.RongUtil.isArray(keys)) { keys = [keys]; } modules.setKey(keys); RongIMLib.RongIMClient.bridge.queryMsg("rtcUDel", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function () { callback.onSuccess(true); }, onError: function (errorCode) { callback.onError(errorCode); } }); }; ServerDataProvider.prototype.getRTCRoomInfo = function (room, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcQueryListInput(); modules.setOrder(2); RongIMLib.RongIMClient.bridge.queryMsg("rtcRInfo", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function (result) { var room = { id: result.roomId, total: result.userCount }; RongIMLib.RongUtil.forEach(result.roomData, function (data) { room[data.key] = data.value; }); callback.onSuccess(room); }, onError: function (errorCode) { callback.onError(errorCode); } }, "RtcRoomInfoOutput"); }; ServerDataProvider.prototype.setRTCRoomInfo = function (room, info, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcValueInfo(); modules.setKey(info.key); modules.setValue(info.value); RongIMLib.RongIMClient.bridge.queryMsg("rtcRPut", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function () { callback.onSuccess(true); }, onError: function (errorCode) { callback.onError(errorCode); } }); }; ServerDataProvider.prototype.removeRTCRoomInfo = function (room, info, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcKeyDeleteInput(); var keys = info.keys || []; if (!RongIMLib.RongUtil.isArray(keys)) { keys = [keys]; } modules.setKey(keys); RongIMLib.RongIMClient.bridge.queryMsg("rtcRDel", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function () { callback.onSuccess(true); }, onError: function (errorCode) { callback.onError(errorCode); } }); }; ServerDataProvider.prototype.joinRTCRoom = function (room, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcInput(); var mode = room.mode || 0; modules.setRoomType(mode); if (room.broadcastType) { modules.setBroadcastType(room.broadcastType); } RongIMLib.RongIMClient.bridge.queryMsg("rtcRJoin_data", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function (result) { var users = {}; var list = result.list, token = result.token, sessionId = result.sessionId; RongIMLib.RongUtil.forEach(list, function (item) { var userId = item.userId; var tmpData = {}; RongIMLib.RongUtil.forEach(item.userData, function (data) { var key = data.key; var value = data.value; tmpData[key] = value; }); users[userId] = tmpData; }); callback.onSuccess({ users: users, token: token, sessionId: sessionId }); }, onError: function (errorCode) { callback.onError(errorCode); } }, "RtcUserListOutput"); }; ServerDataProvider.prototype.quitRTCRoom = function (room, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.SetUserStatusInput(); RongIMLib.RongIMClient.bridge.queryMsg("rtcRExit", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function () { callback.onSuccess(true); }, onError: function (errorCode) { callback.onError(errorCode); } }); }; ServerDataProvider.prototype.RTCPing = function (room, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcInput(); var mode = room.mode || 0; modules.setRoomType(mode); if (room.broadcastType) { modules.setBroadcastType(room.broadcastType); } RongIMLib.RongIMClient.bridge.queryMsg("rtcPing", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, callback); }; ServerDataProvider.prototype.setRTCData = function (roomId, key, value, isInner, apiType, callback, message) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcSetDataInput(); modules.setInterior(isInner); modules.setTarget(apiType); modules.setKey(key); modules.setValue(value); message = message || {}; var name = message.name; var content = message.content; if (name) { modules.setObjectName(name); } if (content) { if (!RongIMLib.RongUtil.isString(content)) { content = JSON.stringify(content); } modules.setContent(content); } RongIMLib.RongIMClient.bridge.queryMsg("rtcSetData", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), roomId, callback, "RtcOutput"); }; ServerDataProvider.prototype.getRTCData = function (roomId, keys, isInner, apiType, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcDataInput(); modules.setInterior(isInner); modules.setTarget(apiType); modules.setKey(keys); RongIMLib.RongIMClient.bridge.queryMsg("rtcQryData", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), roomId, { onSuccess: function (result) { var props = {}; var list = result.outInfo; RongIMLib.RongUtil.forEach(list, function (item) { props[item.key] = item.value; }); callback.onSuccess(props); }, onError: callback.onError }, "RtcQryOutput"); }; ServerDataProvider.prototype.removeRTCData = function (roomId, keys, isInner, apiType, callback, message) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcDataInput(); modules.setInterior(isInner); modules.setTarget(apiType); modules.setKey(keys); message = message || {}; var name = message.name; var content = message.content; if (name) { modules.setObjectName(name); } if (content) { if (!RongIMLib.RongUtil.isString(content)) { content = JSON.stringify(content); } modules.setContent(content); } RongIMLib.RongIMClient.bridge.queryMsg("rtcDelData", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), roomId, callback, "RtcOutput"); }; ServerDataProvider.prototype.setRTCUserData = function (roomId, key, value, isInner, callback, message) { this.setRTCData(roomId, key, value, isInner, RongIMLib.RTCAPIType.PERSON, callback, message); }; ServerDataProvider.prototype.getRTCUserData = function (roomId, keys, isInner, callback, message) { this.getRTCData(roomId, keys, isInner, RongIMLib.RTCAPIType.PERSON, callback); }; ServerDataProvider.prototype.removeRTCUserData = function (roomId, keys, isInner, callback, message) { this.removeRTCData(roomId, keys, isInner, RongIMLib.RTCAPIType.PERSON, callback, message); }; ServerDataProvider.prototype.setRTCRoomData = function (roomId, key, value, isInner, callback, message) { this.setRTCData(roomId, key, value, isInner, RongIMLib.RTCAPIType.ROOM, callback, message); }; ServerDataProvider.prototype.getRTCRoomData = function (roomId, keys, isInner, callback, message) { this.getRTCData(roomId, keys, isInner, RongIMLib.RTCAPIType.ROOM, callback); }; ServerDataProvider.prototype.removeRTCRoomData = function (roomId, keys, isInner, callback, message) { this.removeRTCData(roomId, keys, isInner, RongIMLib.RTCAPIType.ROOM, callback, message); }; // 信令 SDK 新增 ServerDataProvider.prototype.setRTCOutData = function (roomId, data, type, callback, message) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcSetOutDataInput(); modules.setTarget(type); if (!RongIMLib.RongUtil.isArray(data)) { data = [data]; } for (var i = 0; i < data.length; i++) { var item = data[i]; if (item.key) { item.key = item.key.toString(); } if (item.value) { item.value = item.value.toString(); } } modules.setValueInfo(data); message = message || {}; var name = message.name; var content = message.content; if (name) { modules.setObjectName(name); } if (content) { if (!RongIMLib.RongUtil.isString(content)) { content = JSON.stringify(content); } modules.setContent(content); } RongIMLib.RongIMClient.bridge.queryMsg("rtcSetOutData", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), roomId, callback, "RtcOutput"); }; // 信令 SDK 新增 ServerDataProvider.prototype.getRTCOutData = function (roomId, userIds, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcQryUserOutDataInput(); modules.setUserId(userIds); RongIMLib.RongIMClient.bridge.queryMsg("rtcQryUserOutData", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), roomId, callback, "RtcUserOutDataOutput"); }; ServerDataProvider.prototype.getNavi = function () { var navi = RongIMLib.RongIMClient._storageProvider.getItem("fullnavi") || "{}"; return JSON.parse(navi); }; ServerDataProvider.prototype.getRTCToken = function (room, callback) { var modules = new RongIMLib.RongIMClient.Protobuf.RtcInput(); var mode = room.mode || 0; modules.setRoomType(mode); if (room.broadcastType) { modules.setBroadcastType(room.broadcastType); } RongIMLib.RongIMClient.bridge.queryMsg("rtcToken", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function (result) { callback.onSuccess(result); }, onError: function (errorCode) { callback.onError(errorCode); } }, "RtcTokenOutput"); }; ServerDataProvider.prototype.setRTCState = function (room, content, callback) { // MCFollowInput 为 PB 复用,字段:一个必传 string(第一位) var modules = new RongIMLib.RongIMClient.Protobuf.MCFollowInput(); var report = content.report; modules.setId(report); RongIMLib.RongIMClient.bridge.queryMsg("rtcUserState", RongIMLib.MessageUtil.ArrayForm(modules.toArrayBuffer()), room.id, { onSuccess: function (result) { callback.onSuccess(result); }, onError: function (errorCode) { callback.onError(errorCode); } }, "RtcOutput"); }; return ServerDataProvider; })(); RongIMLib.ServerDataProvider = ServerDataProvider; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var VCDataProvider = (function () { function VCDataProvider(addon) { this.Conversation = { watcher: new RongIMLib.Observer(), watch: function (_watcher) { }, unwatch: function (_watcher) { }, _notify: function (conversationList) { } }; // C++ 需要的 SDK 版本号 this.version = '2.8.27'; this.userId = ""; this.useConsole = false; this.appKey = ""; this.token = ""; this.connectionStatus = RongIMLib.ConnectionStatus.DISCONNECTED; this.addon = addon; } VCDataProvider.prototype.init = function (appKey, config) { this.appKey = appKey; this.useConsole && console.log("init"); config = config || {}; config.version = this.version; var sdkInfo = this.addon.initWithAppkey(appKey, config.dbPath, config); if (sdkInfo) { sdkInfo = JSON.parse(sdkInfo); } // 0 不存不计数 1 只存不计数 3 存且计数 this.addon.registerMessageType("RC:VcMsg", 3); this.addon.registerMessageType("RC:ImgTextMsg", 3); this.addon.registerMessageType("RC:FileMsg", 3); this.addon.registerMessageType("RC:LBSMsg", 3); this.addon.registerMessageType("RC:PSImgTxtMsg", 3); this.addon.registerMessageType("RC:PSMultiImgTxtMsg", 3); this.addon.registerMessageType("RCJrmf:RpMsg", 3); this.addon.registerMessageType("RCJrmf:RpOpendMsg", 1); this.addon.registerMessageType("RC:GrpNtf", 1); this.addon.registerMessageType("RC:DizNtf", 0); this.addon.registerMessageType("RC:InfoNtf", 0); this.addon.registerMessageType("RC:ContactNtf", 0); this.addon.registerMessageType("RC:ProfileNtf", 0); this.addon.registerMessageType("RC:CmdNtf", 0); this.addon.registerMessageType("RC:CmdMsg", 0); this.addon.registerMessageType("RC:TypSts", 0); this.addon.registerMessageType("RC:CsChaR", 0); this.addon.registerMessageType("RC:CsHsR", 0); this.addon.registerMessageType("RC:CsEnd", 0); this.addon.registerMessageType("RC:CsSp", 0); this.addon.registerMessageType("RC:CsUpdate", 0); this.addon.registerMessageType("RC:CsContact", 0); this.addon.registerMessageType("RC:ReadNtf", 0); this.addon.registerMessageType("RC:VCAccept", 0); this.addon.registerMessageType("RC:VCRinging", 0); this.addon.registerMessageType("RC:VCSummary", 0); this.addon.registerMessageType("RC:VCHangup", 0); this.addon.registerMessageType("RC:VCInvite", 0); this.addon.registerMessageType("RC:VCModifyMedia", 0); this.addon.registerMessageType("RC:VCModifyMem", 0); this.addon.registerMessageType("RC:PSCmd", 0); this.addon.registerMessageType("RC:RcCmd", 0); this.addon.registerMessageType("RC:SRSMsg", 0); this.addon.registerMessageType("RC:RRReqMsg", 0); this.addon.registerMessageType("RC:RRRspMsg", 0); return sdkInfo; }; VCDataProvider.prototype.connect = function (token, callback, userId, serverConf) { this.useConsole && console.log("connect"); this.userId = userId; this.connectCallback = callback; RongIMLib.Bridge._client = { userId: userId, token: token }; serverConf = serverConf || {}; var openmp = !!serverConf.openMp; var openus = !!serverConf.openUS; if (serverConf.type) { this.addon.setEnvironment(true); } var me = this; // this.addon.connectWithToken(token, userId, serverConf.serverList, openmp, openus); this.addon.connectWithToken(token, userId, function (userId) { me.userId = userId; RongIMLib.Bridge._client.userId = userId; }); }; VCDataProvider.prototype.setConversationStatus = function (type, targetId, statusItem, callback) { }; VCDataProvider.prototype.setServerInfo = function (info) { 'setServerInfo' in this.addon && this.addon.setServerInfo(info.navi); }; VCDataProvider.prototype.logout = function () { this.useConsole && console.log("logout"); this.disconnect(); }; VCDataProvider.prototype.disconnect = function () { this.useConsole && console.log("disconnect"); this.connectionStatus = RongIMLib.ConnectionStatus.DISCONNECTED; this.addon.disconnect(true); }; VCDataProvider.prototype.clearListeners = function () { this.addon.setOnReceiveStatusListener(); this.addon.setConnectionStatusListener(); this.addon.setOnReceiveMessageListener(); }; VCDataProvider.prototype.clearData = function () { this.useConsole && console.log("clearData"); return this.addon.clearData(); }; VCDataProvider.prototype.setConnectionStatusListener = function (listener) { var me = this; /** ConnectionStatus_TokenIncorrect = 31004, ConnectionStatus_Connected = 0, ConnectionStatus_KickedOff = 6, // 其他设备登录 ConnectionStatus_Connecting = 10,// 连接中 ConnectionStatus_SignUp = 12, // 未登录 ConnectionStatus_NetworkUnavailable = 1, // 连接断开 ConnectionStatus_ServerInvalid = 8, // 断开 ConnectionStatus_ValidateFailure = 9,//断开 ConnectionStatus_Unconnected = 11,//断开 ConnectionStatus_DisconnExecption = 31011 //断开 RC_NAVI_MALLOC_ERROR = 30000,//断开 RC_NAVI_NET_UNAVAILABLE= 30002,//断开 RC_NAVI_SEND_FAIL = 30004,//断开 RC_NAVI_REQ_TIMEOUT = 30005,//断开 RC_NAVI_RECV_FAIL = 30006,//断开 RC_NAVI_RESOURCE_ERROR = 30007,//断开 RC_NAVI_NODE_NOT_FOUND = 30008,//断开 RC_NAVI_DNS_ERROR = 30009,//断开 */ me.connectListener = listener; this.useConsole && console.log("setConnectionStatusListener"); me.addon && me.addon.setConnectionStatusListener(function (result) { var isCurrentConnected = me.connectionStatus === RongIMLib.ConnectionStatus.CONNECTED; var code = result; switch (result) { case 10: code = RongIMLib.ConnectionStatus.CONNECTING; break; case 31004: setTimeout(function () { me.connectCallback.onTokenIncorrect(); }); return; case 1: case 8: case 9: case 11: case 12: case 31011: case 30000: case 30002: case 30010: if (!isCurrentConnected) { return; } code = RongIMLib.ConnectionStatus.NETWORK_UNAVAILABLE; break; case 0: case 33005: code = RongIMLib.ConnectionStatus.CONNECTED; setTimeout(function () { me.connectCallback.onSuccess(me.userId); }); break; case 6: code = RongIMLib.ConnectionStatus.KICKED_OFFLINE_BY_OTHER_CLIENT; break; default: code = result; break; } me.connectionStatus = code; setTimeout(function () { listener.onChanged(code); }); }); }; VCDataProvider.prototype.setOnReceiveMessageListener = function (listener) { var me = this, localCount = 0; me.messageListener = listener; this.useConsole && console.log("setOnReceiveMessageListener"); me.addon && me.addon.setOnReceiveMessageListener(function (result, leftCount, offline, hasMore) { var message = me.buildMessage(result); message.offLineMessage = offline; setTimeout(function () { var voipMsgTypes = ['AcceptMessage', 'RingingMessage', 'HungupMessage', 'InviteMessage', 'MediaModifyMessage', 'MemberModifyMessage']; var isVoIPMsg = voipMsgTypes.indexOf(message.messageType) > -1; if (isVoIPMsg) { RongIMLib.RongIMClient._voipProvider && RongIMLib.RongIMClient._voipProvider.onReceived(message); } else if (message.conversationType == 12) { RongIMLib.RongIMClient.RTCListener(message); RongIMLib.RongIMClient.RTCInnerListener(message); RongIMLib.RongIMClient.RTCSignalLisener(message); } else { listener.onReceived(message, leftCount, hasMore); } }); }); }; VCDataProvider.prototype.sendTypingStatusMessage = function (conversationType, targetId, messageName, sendCallback) { var me = this; this.useConsole && console.log("sendTypingStatusMessage"); if (messageName in RongIMLib.RongIMClient.MessageParams) { me.sendMessage(conversationType, targetId, RongIMLib.TypingStatusMessage.obtain(RongIMLib.RongIMClient.MessageParams[messageName].objectName, ""), { onSuccess: function () { setTimeout(function () { sendCallback.onSuccess(); }); }, onError: function (errorCode) { setTimeout(function () { sendCallback.onError(errorCode, null); }); }, onBefore: function () { } }); } }; VCDataProvider.prototype.setMessageStatus = function (conversationType, targetId, timestamp, status, callback) { this.addon.updateMessageReceiptStatus(conversationType, targetId, timestamp); callback.onSuccess(true); }; VCDataProvider.prototype.sendTextMessage = function (conversationType, targetId, content, sendMessageCallback) { var msgContent = RongIMLib.TextMessage.obtain(content); this.useConsole && console.log("sendTextMessage"); this.sendMessage(conversationType, targetId, msgContent, sendMessageCallback); }; VCDataProvider.prototype.getRemoteHistoryMessages = function (conversationType, targetId, timestamp, count, callback, config) { try { var me = this; me.useConsole && console.log("getRemoteHistoryMessages"); me.addon.getRemoteHistoryMessages(conversationType, targetId, timestamp ? timestamp : 0, count, function (ret, hasMore) { var list = ret ? JSON.parse(ret).list : [], msgs = []; list.reverse(); for (var i = 0, len = list.length; i < len; i++) { var message = me.buildMessage(list[i].obj); message.sentStatus = RongIMLib.SentStatus.READ; msgs[i] = message; } callback.onSuccess(msgs, hasMore ? true : false); }, function (errorCode) { callback.onError(errorCode); }); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.getRemoteConversationList = function (callback, conversationTypes, count, isGetHiddenConvers) { try { this.useConsole && console.log("getRemoteConversationList"); var converTypes = conversationTypes || [1, 2, 3, 4, 5, 6, 7, 8]; var result = this.addon.getConversationList(converTypes); var list = JSON.parse(result).list, convers = [], me = this, index = 0; list.reverse(); isGetHiddenConvers = typeof isGetHiddenConvers === 'boolean' ? isGetHiddenConvers : false; for (var i = 0, len_1 = list.length; i < len_1; i++) { var tmpObj = list[i].obj, obj = JSON.parse(tmpObj); if (obj != "") { if (obj.isHidden == 1 && isGetHiddenConvers) { continue; } convers[index] = me.buildConversation(tmpObj); index++; } } convers.reverse(); var len = convers.length; count = count || len; if (len > count) { convers.length = count; } callback.onSuccess(convers); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.removeConversation = function (conversationType, targetId, callback) { try { this.useConsole && console.log("removeConversation"); this.addon.removeConversation(conversationType, targetId); var conversations = RongIMLib.RongIMClient._memoryStore.conversationList; var len = conversations.length; for (var i = 0; i < len; i++) { if (conversations[i].conversationType == conversationType && targetId == conversations[i].targetId) { conversations.splice(i, 1); break; } } callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.joinChatRoom = function (chatRoomId, messageCount, callback) { this.useConsole && console.log("joinChatRoom"); this.addon.joinChatRoom(chatRoomId, messageCount, function () { callback.onSuccess(); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.quitChatRoom = function (chatRoomId, callback) { this.useConsole && console.log("quitChatRoom"); this.addon.quitChatRoom(chatRoomId, function () { callback.onSuccess(); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.setChatroomEntry = function (chatroomId, chatroomEntry, callback) { }; VCDataProvider.prototype.forceSetChatroomEntry = function (chatroomId, chatroomEntry, callback) { }; VCDataProvider.prototype.getChatroomEntry = function (chatroomId, key, callback) { }; VCDataProvider.prototype.getAllChatroomEntries = function (chatroomId, callback) { }; VCDataProvider.prototype.removeChatroomEntry = function (chatroomId, chatroomEntry, callback) { }; VCDataProvider.prototype.forceRemoveChatroomEntry = function (chatroomId, chatroomEntry, callback) { }; VCDataProvider.prototype.pullChatroomEntry = function (chatroomId, time, callback) { }; VCDataProvider.prototype.addToBlacklist = function (userId, callback) { this.useConsole && console.log("addToBlacklist"); this.addon.addToBlacklist(userId, function () { callback.onSuccess(); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.getBlacklist = function (callback) { this.useConsole && console.log("getBlacklist"); this.addon.getBlacklist(function (blacklistors) { callback.onSuccess(blacklistors); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.getBlacklistStatus = function (userId, callback) { this.useConsole && console.log("getBlacklistStatus"); this.addon.getBlacklistStatus(userId, function (result) { callback.onSuccess(result); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.removeFromBlacklist = function (userId, callback) { this.useConsole && console.log("removeFromBlacklist"); this.addon.removeFromBlacklist(userId, function () { callback.onSuccess(); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.sendMessage = function (conversationType, targetId, messageContent, sendCallback, mentiondMsg, pushText, appData, methodType, params) { var me = this, users = []; me.useConsole && console.log("sendMessage"); params = params || {}; var isGroup = (conversationType == RongIMLib.ConversationType.DISCUSSION || conversationType == RongIMLib.ConversationType.GROUP); if (isGroup && messageContent.messageName == RongIMLib.RongIMClient.MessageType["ReadReceiptResponseMessage"]) { users = []; var rspMsg = messageContent; if (rspMsg.receiptMessageDic) { var ids = []; for (var key in rspMsg.receiptMessageDic) { ids.push(key); } users = ids; } } if (isGroup && messageContent.messageName == RongIMLib.RongIMClient.MessageType["SyncReadStatusMessage"]) { users = []; users.push(me.userId); } var userIds = params.userIds; if (isGroup && userIds) { users = userIds; } var msg = me.addon.sendMessage(conversationType, targetId, RongIMLib.RongIMClient.MessageParams[messageContent.messageName].objectName, messageContent.encode(), pushText || "", appData || "", function (progress) { }, function (message, code) { var msg = me.buildMessage(message); var errorCode = RongIMLib.ErrorCode.SENSITIVE_REPLACE; if (code == errorCode) { return sendCallback.onError(errorCode, msg); } sendCallback.onSuccess(msg); }, function (message, code) { sendCallback.onError(code, me.buildMessage(message)); }, users, mentiondMsg); var tempMessage = JSON.parse(msg); sendCallback.onBefore && sendCallback.onBefore(tempMessage.messageId); RongIMLib.MessageIdHandler.messageId = tempMessage.messageId; }; VCDataProvider.prototype.registerMessageType = function (messageType, objectName, messageTag, messageContent, searchProps) { this.useConsole && console.log("registerMessageType"); this.addon.registerMessageType(objectName, messageTag.getMessageTag(), searchProps); var regMsg = RongIMLib.ModelUtil.modleCreate(messageContent, messageType); RongIMLib.RongIMClient.RegisterMessage[messageType] = regMsg; RongIMLib.RongIMClient.RegisterMessage[messageType].messageName = messageType; registerMessageTypeMapping[objectName] = messageType; RongIMLib.RongIMClient.MessageType[messageType] = messageType; RongIMLib.RongIMClient.MessageParams[messageType] = { objectName: objectName, msgTag: messageTag }; typeMapping[objectName] = messageType; }; VCDataProvider.prototype.registerMessageTypes = function (messages) { var types = []; var getProtos = function (proto) { var protos = []; for (var p in proto) { protos.push(p); } return protos; }; //转换消息为自定义消息参数格式 for (var name in messages) { var message = messages[name]; var proto = message.proto; var protos = getProtos(proto); var flag = message.flag || 3; var tag = RongIMLib.MessageTag.getTagByStatus(flag); flag = new RongIMLib.MessageTag(tag.isCounted, tag.isPersited); types.push({ type: name, name: message.name, flag: flag, protos: protos }); } var register = function (message) { var type = message.type; var name = message.name; var flag = message.flag; var protos = message.protos; RongIMLib.RongIMClient.registerMessageType(type, name, flag, protos); }; for (var i = 0, len = types.length; i < len; i++) { var message = types[i]; register(message); } }; VCDataProvider.prototype.addMessage = function (conversationType, targetId, message, callback) { this.useConsole && console.log("addMessage"); var direction = message.direction; var msg = this.addon.insertMessage(conversationType, targetId, message.senderUserId, message.objectName, JSON.stringify(message.content), function () { callback.onSuccess(me.buildMessage(msg)); }, function () { callback.onError(RongIMLib.ErrorCode.MSG_INSERT_ERROR); }, direction), me = this; }; VCDataProvider.prototype.removeMessage = function (conversationType, targetId, messages, callback) { }; VCDataProvider.prototype.deleteRemoteMessages = function (conversationType, targetId, messages, callback) { }; VCDataProvider.prototype.removeLocalMessage = function (conversationType, targetId, timestamps, callback) { try { this.useConsole && console.log("removeLocalMessage"); this.addon.deleteMessages(timestamps); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.getMessage = function (messageId, callback) { try { this.useConsole && console.log("getMessage"); var msg = this.buildMessage(this.addon.getMessage(messageId)); callback.onSuccess(msg); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.clearMessages = function (conversationType, targetId, callback) { try { this.useConsole && console.log("clearMessages"); this.addon.clearMessages(conversationType, targetId); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; // Web 端接口,桌面版无需实现 VCDataProvider.prototype.setUnreadCount = function (conversationType, targetId, count) { }; VCDataProvider.prototype.getConversation = function (conversationType, targetId, callback) { try { this.useConsole && console.log("getConversation"); var ret = this.addon.getConversation(conversationType, targetId); callback.onSuccess(this.buildConversation(ret)); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.getConversationList = function (callback, conversationTypes, count, isGetHiddenConvers) { this.useConsole && console.log("getConversationList"); this.getRemoteConversationList(callback, conversationTypes, count, isGetHiddenConvers); }; VCDataProvider.prototype.clearCache = function () { var memoryStore = RongIMLib.RongIMClient._memoryStore || {}; memoryStore.conversationList = []; memoryStore.isSyncRemoteConverList; }; VCDataProvider.prototype.clearConversations = function (conversationTypes, callback) { try { this.useConsole && console.log("clearConversations"); this.addon.clearConversations(); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.setMessageContent = function (messageId, content, objectName) { content = JSON.stringify(content); this.addon.setMessageContent(messageId, content, objectName); }; VCDataProvider.prototype.setMessageSearchField = function (messageId, content, searchFiles) { this.addon.setMessageSearchField(messageId, content, searchFiles); }; VCDataProvider.prototype.getHistoryMessages = function (conversationType, targetId, timestamp, count, callback, objectname, direction) { this.useConsole && console.log("getHistoryMessages"); if (count <= 0) { callback.onError(RongIMLib.ErrorCode.TIMEOUT); return; } objectname = objectname || ''; direction = typeof direction == 'undefined' || direction; try { var ret = this.addon.getHistoryMessages(conversationType, targetId, timestamp ? timestamp : 0, count, objectname, direction); var list = ret ? JSON.parse(ret).list : [], msgs = [], me = this; list.reverse(); for (var i = 0, len = list.length; i < len; i++) { var message = me.buildMessage(list[i].obj); msgs[i] = message; } callback.onSuccess(msgs, len == count); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.clearRemoteHistoryMessages = function (params, callback) { var conversationType = params.conversationType; var targetId = params.targetId; var timestamp = params.timestamp; var _topic = { 1: true, 2: true, 3: true, 5: true, 6: true }; var topic = _topic[conversationType]; if (!topic) { callback.onError(RongIMLib.ErrorCode.CLEAR_HIS_TYPE_ERROR); return; } if (typeof timestamp != 'number') { callback.onError(RongIMLib.ErrorCode.CLEAR_HIS_TIME_ERROR); return; } this.addon.clearRemoteHistoryMessages(+conversationType, targetId, timestamp, function () { callback.onSuccess(true); }, function (errorCode) { if (errorCode == 1) { // 没有开通历史消息云存储 errorCode = RongIMLib.ErrorCode.CLEAR_HIS_ERROR; } callback.onError(errorCode); }); }; VCDataProvider.prototype.clearHistoryMessages = function (params, callback) { var conversationType = +params.conversationType; var targetId = params.targetId; try { this.addon.clearMessages(conversationType, targetId); var isSuccess = true; callback.onSuccess(isSuccess); } catch (e) { console.log(e); callback.onError(RongIMLib.ErrorCode.CLEAR_HIS_ERROR); } }; VCDataProvider.prototype.getTotalUnreadCount = function (callback, conversationTypes) { var result = 0; try { this.useConsole && console.log("getTotalUnreadCount"); if (conversationTypes) { result = this.addon.getTotalUnreadCount(conversationTypes); } else { result = this.addon.getTotalUnreadCount(); } callback.onSuccess(result); } catch (e) { callback.onError(e); } return result; }; VCDataProvider.prototype.getConversationUnreadCount = function (conversationTypes, callback) { this.useConsole && console.log("getConversationUnreadCount"); this.getTotalUnreadCount(callback, conversationTypes); }; VCDataProvider.prototype.getUnreadCount = function (conversationType, targetId, callback) { try { this.useConsole && console.log("getUnreadCount"); var result = this.addon.getUnreadCount(conversationType, targetId); callback.onSuccess(result); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.clearUnreadCount = function (conversationType, targetId, callback) { try { this.useConsole && console.log("clearUnreadCount"); var result = this.addon.clearUnreadCount(conversationType, targetId); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.clearTotalUnreadCount = function (callback) { this.useConsole && console.log("clearTotalUnreadCount"); }; VCDataProvider.prototype.clearUnreadCountByTimestamp = function (conversationType, targetId, timestamp, callback) { try { this.useConsole && console.log("clearUnreadCountByTimestamp"); var result = this.addon.clearUnreadCountByTimestamp(conversationType, targetId, timestamp); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.setConversationToTop = function (conversationType, targetId, isTop, callback) { try { this.useConsole && console.log("setConversationToTop"); this.addon.setConversationToTop(conversationType, targetId, isTop); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.setConversationHidden = function (conversationType, targetId, isHidden) { this.addon.setConversationHidden(conversationType, targetId, isHidden); }; VCDataProvider.prototype.setMessageReceivedStatus = function (messageId, receivedStatus, callback) { try { this.useConsole && console.log("setMessageReceivedStatus"); this.addon.setMessageReceivedStatus(messageId, receivedStatus); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.setMessageSentStatus = function (messageId, sentStatus, callback) { try { this.useConsole && console.log("setMessageSentStatus"); this.addon.setMessageSentStatus(messageId, sentStatus); callback.onSuccess(true); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.getFileToken = function (fileType, callback) { this.useConsole && console.log("getFileToken"); this.addon.getUploadToken(fileType, function (token) { callback.onSuccess({ token: token }); }, function (errorCode) { callback.onError(errorCode); }); }; VCDataProvider.prototype.getFileUrl = function (fileType, fileName, oriName, callback) { this.useConsole && console.log("getFileUrl"); this.addon.getDownloadUrl(fileType, fileName, oriName, function (url) { callback.onSuccess({ downloadUrl: url }); }, function (errorCode) { callback.onError(errorCode); }); }; VCDataProvider.prototype.getPullSetting = function (callback) { this.useConsole && console.log("getPullSetting"); }; VCDataProvider.prototype.setOfflineMessageDuration = function (duration, callback) { this.useConsole && console.log("setOfflineMessageDuration"); }; VCDataProvider.prototype.searchConversationByContent = function (keyword, callback, conversationTypes) { var converTypes = []; if (typeof conversationTypes == 'undefined') { converTypes = [1, 2, 3, 4, 5, 6, 7]; } else { converTypes = conversationTypes; } try { this.useConsole && console.log("searchConversationByContent"); var result = this.addon.searchConversationByContent(converTypes, keyword); var list = JSON.parse(result).list, convers = [], me = this; list.reverse(); for (var i = 0, len = list.length; i < len; i++) { convers[i] = me.buildConversation(list[i].obj); } callback.onSuccess(convers); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.searchMessageByContent = function (conversationType, targetId, keyword, timestamp, count, total, callback) { var me = this; try { this.useConsole && console.log("searchMessageByContent"); this.addon.searchMessageByContent(conversationType, targetId, keyword, timestamp, count, total, function (ret, matched) { var list = ret ? JSON.parse(ret).list : [], msgs = []; list.reverse(); for (var i = 0, len = list.length; i < len; i++) { msgs[i] = me.buildMessage(list[i].obj); } callback.onSuccess(msgs, matched); }); } catch (e) { callback.onError(e); } }; VCDataProvider.prototype.getChatRoomInfo = function (chatRoomId, count, order, callback) { this.useConsole && console.log("getChatRoomInfo"); this.addon.getChatroomInfo(chatRoomId, count, order, function (ret, count) { var list = ret ? JSON.parse(ret).list : [], chatRoomInfo = { userInfos: [], userTotalNums: count }; if (list.length > 0) { for (var i = 0, len = list.length; i < len; i++) { chatRoomInfo.userInfos.push(JSON.parse(list[i].obj)); } } callback.onSuccess(chatRoomInfo); }, function (errcode) { callback.onError(errcode); }); }; VCDataProvider.prototype.setChatroomHisMessageTimestamp = function (chatRoomId, timestamp) { }; VCDataProvider.prototype.getChatRoomHistoryMessages = function (chatRoomId, count, order, callback) { }; VCDataProvider.prototype.getDelaTime = function () { return this.addon.getDeltaTime(); }; VCDataProvider.prototype.getUserStatus = function (userId, callback) { var me = this; this.addon.getUserStatus(userId, function (status) { var entity = RongIMLib.RongInnerTools.convertUserStatus({ status: status, userId: '' }); callback.onSuccess(entity); }, function (code) { callback.onError(code); }); }; VCDataProvider.prototype.setUserStatus = function (status, callback) { this.addon.setUserStatus(status, function () { callback.onSuccess(true); }, function (code) { callback.onError(code); }); }; VCDataProvider.prototype.subscribeUserStatus = function (userIds, callback) { this.addon.subscribeUserStatus(userIds, function () { callback && callback.onSuccess(true); }, function (code) { callback && callback.onError(code); }); }; VCDataProvider.prototype.setUserStatusListener = function (params, callback) { var me = this; this.addon.setOnReceiveStatusListener(function (userId, status) { var entity = RongIMLib.RongInnerTools.convertUserStatus({ userId: userId, status: status }); RongIMLib.RongIMClient.userStatusObserver.notify({ key: userId, entity: entity }); }); var userIds = params.userIds || []; if (userIds.length) { RongIMLib.RongIMClient._dataAccessProvider.subscribeUserStatus(userIds); } }; VCDataProvider.prototype.getUnreadMentionedMessages = function (conversationType, targetId) { var me = this; var mentions = JSON.parse(me.addon.getUnreadMentionedMessages(conversationType, targetId)).list; for (var i = 0, len = mentions.length; i < len; i++) { var temp = JSON.parse(mentions[i].obj); temp.content = JSON.parse(temp.content); mentions[i] = temp; } return mentions; }; VCDataProvider.prototype.hasRemoteUnreadMessages = function (token, callback) { callback.onSuccess(false); }; VCDataProvider.prototype.sendRecallMessage = function (content, sendMessageCallback) { var me = this; me.addon.recallMessage("RC:RcCmd", JSON.stringify(content), content.push || "", function () { content.objectName = 'RC:RcCmd'; sendMessageCallback.onSuccess(me.buildMessage(JSON.stringify(content))); }, function (errorCode) { sendMessageCallback.onError(errorCode); }); }; VCDataProvider.prototype.updateMessage = function (message, callback) { }; VCDataProvider.prototype.updateMessages = function (conversationType, targetId, key, value, callback) { }; VCDataProvider.prototype.reconnect = function (callback) { var token = RongIMLib.Bridge._client.token; this.disconnect(); this.connect(token, callback); }; VCDataProvider.prototype.sendReceiptResponse = function (conversationType, targetId, sendCallback) { }; VCDataProvider.prototype.setMessageExtra = function (messageId, value, callback) { }; VCDataProvider.prototype.addMemberToDiscussion = function (discussionId, userIdList, callback) { }; VCDataProvider.prototype.createDiscussion = function (name, userIdList, callback) { }; VCDataProvider.prototype.getDiscussion = function (discussionId, callback) { }; VCDataProvider.prototype.quitDiscussion = function (discussionId, callback) { }; VCDataProvider.prototype.removeMemberFromDiscussion = function (discussionId, userId, callback) { }; VCDataProvider.prototype.setDiscussionInviteStatus = function (discussionId, status, callback) { }; VCDataProvider.prototype.setDiscussionName = function (discussionId, name, callback) { }; VCDataProvider.prototype.setEnvironment = function (isPrivate) { this.addon.setEnvironment(isPrivate); }; VCDataProvider.prototype.addConversation = function (conversation, callback) { }; VCDataProvider.prototype.updateConversation = function (conversation) { return null; }; VCDataProvider.prototype.getConversationNotificationStatus = function (params, callback) { var conversationType = params.conversationType; var targetId = params.targetId; var notification = RongIMLib.RongIMClient._memoryStore.notification; var key = conversationType + '_' + targetId; var status = notification[key]; if (typeof status == 'number') { callback.onSuccess(status); return; } this.addon.getConversationNotificationStatus(conversationType, targetId, function (status) { notification[key] = status; callback.onSuccess(status); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.setConversationNotificationStatus = function (params, callback) { var conversationType = params.conversationType; var targetId = params.targetId; var status = params.status; var notification = RongIMLib.RongIMClient._memoryStore.notification; var key = conversationType + '_' + targetId; notification[key] = status; var notify = !!status; this.addon.setConversationNotificationStatus(conversationType, targetId, notify, function () { callback.onSuccess(status); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.getCurrentConnectionStatus = function () { return this.addon.getConnectionStatus(); }; VCDataProvider.prototype.getAgoraDynamicKey = function (engineType, channelName, callback) { var extra = ""; this.addon.getVoIPKey(engineType, channelName, extra, function (token) { callback.onSuccess(token); }, function (errorCode) { callback.onError(errorCode); }); }; VCDataProvider.prototype.getPublicServiceProfile = function (publicServiceType, publicServiceId, callback) { var profile = RongIMLib.RongIMClient._memoryStore.publicServiceMap.get(publicServiceType, publicServiceId); callback.onSuccess(profile); }; VCDataProvider.prototype.setDeviceInfo = function (device) { var id = device.id || ''; this.addon.setDeviceId(id); }; VCDataProvider.prototype.getRemotePublicServiceList = function (callback, pullMessageTime) { var publicList = []; var ret = this.addon.getAccounts(); var transformProto = function (ret) { var result = { hasFollowed: false, isGlobal: false, menu: null }; if (!ret.obj) { var error = { error: ret }; throw new Error('公众账号数据格式错误: ' + JSON.stringify(error)); } var obj = JSON.parse(ret.obj); var protoMap = { aType: 'conversationType', aId: 'publicServiceId', aName: 'introduction', aUri: 'portraitUri', follow: 'hasFollowed', isGlobal: 'isGlobal' }; for (var key in obj) { var val = obj[key]; if (key == 'aExtra') { var extra = JSON.parse(val); result["hasFollowed"] = extra.follow; result["isGlobal"] = extra.isGlobal; result["menu"] = extra.menu; } var uId = protoMap[key]; if (uId) { result[uId] = val; } } return result; }; if (ret) { ret = JSON.parse(ret); var list = ret.list; for (var i = 0, len = list.length; i < len; i++) { var item = list[i]; item = transformProto(item); publicList.push(item); } } if (publicList.length > 0) { RongIMLib.RongIMClient._memoryStore.publicServiceMap.publicServiceList.length = 0; RongIMLib.RongIMClient._memoryStore.publicServiceMap.publicServiceList = publicList; } callback.onSuccess(RongIMLib.RongIMClient._memoryStore.publicServiceMap.publicServiceList); }; VCDataProvider.prototype.buildMessage = function (result) { var message = new RongIMLib.Message(), ret = JSON.parse(result); message.conversationType = ret.conversationType; message.targetId = ret.targetId; message.messageDirection = ret.direction; message.senderUserId = ret.senderUserId; if (ret.direction == RongIMLib.MessageDirection.RECEIVE) { message.receivedStatus = ret.status; } else if (ret.direction == RongIMLib.MessageDirection.SEND) { message.sentStatus = ret.status; } message.sentTime = ret.sentTime; message.objectName = ret.objectName; var content = ret.content ? JSON.parse(ret.content) : ret.content; var messageType = typeMapping[ret.objectName] || registerMessageTypeMapping[ret.objectName]; if (content) { content.messageName = messageType; } message.content = content; message.messageId = ret.messageId; message.messageUId = ret.messageUid; message.messageType = messageType; return message; }; VCDataProvider.prototype.buildConversation = function (val) { if (val === '') { return null; } var conver = new RongIMLib.Conversation(), c = JSON.parse(val), lastestMsg = c.lastestMsg ? this.buildMessage(c.lastestMsg) : {}; conver.conversationTitle = c.title; conver.conversationType = c.conversationType; conver.draft = c.draft; conver.isTop = c.isTop; conver.isHidden = c.isHidden; lastestMsg.conversationType = c.conversationType; lastestMsg.targetId = c.targetId; conver.latestMessage = lastestMsg; conver.latestMessageId = lastestMsg.messageId; conver.latestMessage.messageType = typeMapping[lastestMsg.objectName] || registerMessageTypeMapping[lastestMsg.objectName]; conver.objectName = lastestMsg.objectName; conver.receivedStatus = RongIMLib.ReceivedStatus.READ; conver.sentTime = lastestMsg.sentTime; conver.senderUserId = lastestMsg.senderUserId; conver.sentStatus = lastestMsg.status; conver.targetId = c.targetId; conver.unreadMessageCount = c.unreadCount; conver.hasUnreadMention = c.m_hasUnreadMention; var mentions = this.getUnreadMentionedMessages(c.conversationType, c.targetId); if (mentions.length > 0) { // 取最后一条 @ 消息,原因:和 web 互相兼容 var mention = mentions.pop(); conver.mentionedMsg = { uid: mention.messageUid, time: mention.sentTime, mentionedInfo: mention.content.mentionedInfo, sendUserId: mention.senderUserId }; } return conver; }; VCDataProvider.prototype.getRTCUserInfoList = function (room, callback) { this.addon.getRTCUsers(room.id, 1, function (result) { callback.onSuccess(result); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.getRTCRoomInfo = function (room, callback) { var order = 2; this.addon.getRTCResouce(room.id, order, function (result) { callback.onSuccess(JSON.parse(result)); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.joinRTCRoom = function (room, callback) { var id = room.id; var type = room.type || 0; this.addon.joinRTCRoom(id, type, function (result, token) { var res = JSON.parse(result); var users = {}; var list = res.list; RongIMLib.RongUtil.forEach(list, function (item) { var userId = item.id; var tmpData = {}; RongIMLib.RongUtil.forEach(item.data, function (data) { var key = data.key; var value = data.value; tmpData[key] = value; }); users[userId] = tmpData; }); callback.onSuccess({ users: users, token: token }); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.quitRTCRoom = function (room, callback) { this.addon.exitRTCRoom(room.id, function () { callback.onSuccess(true); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.RTCPing = function (room, callback) { this.addon.sendRTCPing(room.id, function () { callback.onSuccess(true); }, function (error) { callback.onError(error); }); }; VCDataProvider.prototype.setRTCData = function (roomId, key, value, isInner, apiType, callback, message) { var context = this; var hanlders = { room_inner: function (roomId, key, value, name, content, success, error) { context.addon.setRTCInnerData(roomId, RongIMLib.RTCAPIType.ROOM, key, value, name, content, success, error); }, room_outer: function (roomId, key, value, name, content, success, error) { context.addon.setRTCOuterData(roomId, RongIMLib.RTCAPIType.ROOM, key, value, name, content, success, error); }, user_inner: function (roomId, key, value, name, content, success, error) { context.addon.setRTCInnerData(roomId, RongIMLib.RTCAPIType.PERSON, key, value, name, content, success, error); }, user_outer: function (roomId, key, value, name, content, success, error) { context.addon.setRTCOuterData(roomId, RongIMLib.RTCAPIType.PERSON, key, value, name, content, success, error); } }; var type = RongIMLib.RTCAPIType.PERSON == apiType ? 'user' : 'room'; var direction = isInner ? 'inner' : 'outer'; var tpl = '{type}_{direction}'; var name = RongIMLib.RongUtil.tplEngine(tpl, { type: type, direction: direction }); var handler = hanlders[name]; if (handler) { message = message || {}; var name = message.name; var content = message.content; handler(roomId, key, value, name, content, function () { callback.onSuccess(true); }, function (code) { callback.onError(code); }); } }; VCDataProvider.prototype.setRTCRoomData = function (roomId, key, value, isInner, callback, message) { this.setRTCData(roomId, key, value, isInner, RongIMLib.RTCAPIType.ROOM, callback, message); }; VCDataProvider.prototype.getRTCData = function (roomId, keys, isInner, apiType, callback) { var context = this; var hanlders = { room_inner: function (roomId, keys, success, error) { context.addon.getRTCInnerData(roomId, RongIMLib.RTCAPIType.ROOM, keys, success, error); }, room_outer: function (roomId, keys, success, error) { context.addon.getRTCOuterData(roomId, RongIMLib.RTCAPIType.ROOM, keys, success, error); } }; var type = RongIMLib.RTCAPIType.PERSON == apiType ? 'user' : 'room'; var direction = isInner ? 'inner' : 'outer'; var tpl = '{type}_{direction}'; var name = RongIMLib.RongUtil.tplEngine(tpl, { type: type, direction: direction }); var handler = hanlders[name]; if (handler) { handler(roomId, keys, function (result) { var res = JSON.parse(result); var props = {}; var list = res.list; RongIMLib.RongUtil.forEach(list, function (item) { props[item.key] = item.value; }); callback.onSuccess(props); }, function (code) { callback.onError(code); }); } }; VCDataProvider.prototype.getRTCRoomData = function (roomId, keys, isInner, callback, message) { this.getRTCData(roomId, keys, isInner, RongIMLib.RTCAPIType.ROOM, callback); }; VCDataProvider.prototype.removeRTCData = function (roomId, keys, isInner, apiType, callback, message) { var context = this; var hanlders = { room_inner: function (roomId, keys, name, content, success, error) { context.addon.deleteRTCInnerData(roomId, RongIMLib.RTCAPIType.ROOM, keys, name, content, success, error); }, room_outer: function (roomId, keys, name, content, success, error) { context.addon.deleteRTCOuterData(roomId, RongIMLib.RTCAPIType.ROOM, keys, name, content, success, error); }, user_inner: function (roomId, keys, name, content, success, error) { }, user_outer: function (roomId, keys, name, content, success, error) { } }; var type = RongIMLib.RTCAPIType.PERSON == apiType ? 'user' : 'room'; var direction = isInner ? 'inner' : 'outer'; var tpl = '{type}_{direction}'; var name = RongIMLib.RongUtil.tplEngine(tpl, { type: type, direction: direction }); var handler = hanlders[name]; if (handler) { message = message || {}; var name = message.name || ''; var content = message.content || ''; handler(roomId, keys, name, content, function () { callback.onSuccess(true); }, function (code) { callback.onError(code); }); } }; VCDataProvider.prototype.removeRTCRoomData = function (roomId, keys, isInner, callback, message) { this.removeRTCData(roomId, keys, isInner, RongIMLib.RTCAPIType.ROOM, callback); }; VCDataProvider.prototype.getNavi = function () { var nav = this.addon.getNav(); return nav[this.userId]; }; // 信令 SDK 新增 VCDataProvider.prototype.setRTCOutData = function (roomId, data, type, callback, message) { }; // 信令 SDK 新增 VCDataProvider.prototype.getRTCOutData = function (roomId, userId, callback) { }; VCDataProvider.prototype.setRTCUserInfo = function (room, info, callback) { }; VCDataProvider.prototype.removeRTCUserInfo = function (room, info, callback) { }; VCDataProvider.prototype.getRTCUserList = function (room, callback) { }; VCDataProvider.prototype.setRTCRoomInfo = function (room, data, callback) { }; VCDataProvider.prototype.removeRTCRoomInfo = function (room, data, callback) { }; VCDataProvider.prototype.setRTCUserData = function (roomId, key, value, isInner, callback, message) { this.setRTCData(roomId, key, value, isInner, RongIMLib.RTCAPIType.PERSON, callback, message); }; VCDataProvider.prototype.getRTCUserData = function (roomId, key, isInner, callback, message) { }; VCDataProvider.prototype.removeRTCUserData = function (roomId, key, isInner, callback, message) { }; VCDataProvider.prototype.getRTCToken = function (room, callback) { }; VCDataProvider.prototype.setRTCState = function (room, content, callback) { }; return VCDataProvider; })(); RongIMLib.VCDataProvider = VCDataProvider; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { (function (LoggerLevel) { LoggerLevel[LoggerLevel["F"] = 0] = "F"; LoggerLevel[LoggerLevel["E"] = 1] = "E"; LoggerLevel[LoggerLevel["W"] = 2] = "W"; LoggerLevel[LoggerLevel["I"] = 3] = "I"; LoggerLevel[LoggerLevel["D"] = 4] = "D"; //debug })(RongIMLib.LoggerLevel || (RongIMLib.LoggerLevel = {})); var LoggerLevel = RongIMLib.LoggerLevel; (function (LoggerStoreSize) { LoggerStoreSize[LoggerStoreSize["ADVANCED"] = 500] = "ADVANCED"; LoggerStoreSize[LoggerStoreSize["LOW"] = 500] = "LOW"; })(RongIMLib.LoggerStoreSize || (RongIMLib.LoggerStoreSize = {})); var LoggerStoreSize = RongIMLib.LoggerStoreSize; var LoggerType = (function () { function LoggerType() { } LoggerType.IM = 'IM'; LoggerType.RTC = 'RTC'; return LoggerType; })(); RongIMLib.LoggerType = LoggerType; var LoggerTag = (function () { function LoggerTag() { } /** * 三段式关键字: "发起方-任务类型-结果类型" * A: App 层,L: Lib 层,N: 调用 Native 层接口,P: Protocol 层 * O: 操作,S: 状态,T: 任务,R: 结果,E: 错误 */ LoggerTag.IM = { A_INIT_O: 'A-init-O', A_CONN_T: 'A-connect-T', A_CONN_R: 'A-connect-R', L_RECO_T: 'L-reconnect-T', L_RECO_R: 'L-reconnect-R', L_GETN_T: 'L-get_navi-T', L_GETN_R: 'L-get_navi-R', L_PING_WS_T: 'L-ping_ws-T', L_PING_WS_R: 'L-ping_ws-R', L_NETC_S: 'L-network_changed-S', A_DISC_O: 'A-disconnect-O', A_JCTR_T: 'A-join_chatroom-T', A_JCTR_R: 'A-join_chatroom-R', A_QCTR_T: 'A-quit_chatroom-T', A_QCTR_R: 'A-quit_chatroom-R', L_CRAW_F: 'L-crash_web-F', G_CRAW_E: 'G-crash-E', G_UP_LOG_S: 'G-upload_log-S', G_UP_LOG_E: 'G-upload_log-E' }; return LoggerTag; })(); RongIMLib.LoggerTag = LoggerTag; var LoggerReportType = (function () { function LoggerReportType() { } LoggerReportType.REAL_TIME_LOG = 'RealTimeLog'; LoggerReportType.MSG_NOTIF_LOG = 'MessageNotificationLog'; return LoggerReportType; })(); RongIMLib.LoggerReportType = LoggerReportType; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var Logger = (function () { function Logger() { } Logger.writeLog = function (log) { var self = this; if (RongIMLib.RongIMClient._memoryStore.loggerSwitch === "off") { return; } var networkUnavailable = RongIMLib.RongIMClient._memoryStore.networkUnavailable; var isLowLevelBro = RongIMLib.LoggerUtil.isLowLevelBro(); log.time = new Date().getTime(); log.sessionId = RongIMLib.LoggerUtil.getSessionId(); log.content = log.content && JSON.stringify(log.content); if (networkUnavailable) { if (log.level == RongIMLib.LoggerLevel.E || log.level == RongIMLib.LoggerLevel.W) { log.level = RongIMLib.LoggerLevel.I; } } self.logStore.push(log); var _handleOverflowLog = function (size) { if (self.logStore.length > size) { var delLength = self.logStore.length - size; self.logStore.splice(0, delLength); } }; if (isLowLevelBro) { _handleOverflowLog(RongIMLib.LoggerStoreSize.LOW); } else { _handleOverflowLog(RongIMLib.LoggerStoreSize.ADVANCED); } }; Logger.reportRTLog = function () { var self = this; if (self.loggerCache.hasStarted) { return; } self.loggerCache.hasStarted = true; var policy = this.defaultLogPolicy; var isDefaultUpload = true; var currentTime = 1; var _robustUpload = function () { var isOpen = policy.logSwitch; var itv = policy.itv * 1000; var times = policy.times; var url = policy.url; var level = policy.level; var realItv = itv * Math.pow(2, currentTime - 1); if (currentTime < times) { currentTime++; } setTimeout(function () { var csvLog = RongIMLib.LoggerUtil.handleLog({ level: level, type: RongIMLib.LoggerReportType.REAL_TIME_LOG }); var encodeCsvLog = RongIMLib.TextCompressor.compress(csvLog); var entireUrl = RongIMLib.LoggerUtil.getEntireUrl({ url: url, type: RongIMLib.LoggerReportType.REAL_TIME_LOG }); if (self.loggerCache.isNewNavi) { currentTime = 1; policy = RongIMLib.LoggerUtil.getNaviPolicy(); self.loggerCache.isNewNavi = false; } if (isDefaultUpload) { currentTime = 1; isDefaultUpload = false; policy = RongIMLib.LoggerUtil.getNaviPolicy(); // 更新 navi 中配置下次用 } if (csvLog.length == 0) { policy = RongIMLib.LoggerUtil.getNaviPolicy(); _robustUpload(); return; } RongIMLib.RongUtil.request({ url: entireUrl, method: 'POST', body: encodeCsvLog, timeout: policy.timeout * 1000, success: function (data) { Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.G_UP_LOG_S, level: RongIMLib.LoggerLevel.D, type: RongIMLib.LoggerType.IM, content: { desc: 'report real-time log' } }); //第一次成功后,如果导航有数据使用导航数据,导航无数据关闭上传。第二次上传成功后返回数据使用返回数据 if (!isOpen) { return; } if (data) { data = JSON.parse(data); policy.itv = data.nextTime; policy.level = data.level; policy.logSwitch = data.logSwitch; currentTime = 1; } _robustUpload(); }, error: function (status, resText) { _robustUpload(); Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.G_UP_LOG_E, level: RongIMLib.LoggerLevel.D, type: RongIMLib.LoggerType.IM, content: { desc: 'report real-time log', status: status, resText: resText } }); } }); }, realItv); }; _robustUpload(); }; Logger.reportMNLog = function (policy) { var self = this; var currentTime = 1; var connectTime = RongIMLib.RongIMClient._memoryStore.connectAckTime; if (policy.platform !== 'Web' || policy.logId === self.loggerCache.logId) { return; } self.loggerCache.logId = policy.logId; var _robustUpload = function () { var itv = 5000; var times = 3; itv = itv * Math.pow(2, currentTime - 2); if (currentTime === 1) { itv = 0; } if (currentTime <= times) { currentTime++; } else { return; } setTimeout(function () { var csvLog = RongIMLib.LoggerUtil.handleLog({ level: RongIMLib.LoggerLevel.D, startTime: policy.startTime, endTime: policy.endTime, type: RongIMLib.LoggerReportType.MSG_NOTIF_LOG }); if (csvLog.length === 0 && policy.endTime < connectTime) { //没有日志且连接时间大于日志消息结束时间,说明此日志消息过期,无需上传 return; } else if (csvLog.length === 0 && policy.endTime > connectTime) { //没有日志且连接时间小于日志消息结束时间,说明用户连接时间在需要获取的时间内,没有日志上传 nodata csvLog = 'nodata'; } var encodeCsvLog = RongIMLib.TextCompressor.compress(csvLog); var entireUrl = RongIMLib.LoggerUtil.getEntireUrl({ url: policy.uri, logId: policy.logId, type: RongIMLib.LoggerReportType.MSG_NOTIF_LOG }); RongIMLib.RongUtil.request({ url: entireUrl, method: 'POST', body: encodeCsvLog, timeout: self.defaultLogPolicy.timeout * 1000, success: function () { Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.G_UP_LOG_S, level: RongIMLib.LoggerLevel.D, type: RongIMLib.LoggerType.IM, content: { desc: 'report message notification log' } }); }, error: function (status, resText) { _robustUpload(); Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.G_UP_LOG_E, level: RongIMLib.LoggerLevel.D, type: RongIMLib.LoggerType.IM, content: { desc: 'report message notification log', status: status, resText: resText } }); } }); }, itv); }; _robustUpload(); }; Logger.logStore = []; Logger.defaultLogPolicy = { "logSwitch": 1, "url": 'logcollection.ronghub.com/', "level": RongIMLib.LoggerLevel.E, "itv": 20, "times": 5, "timeout": 15 }; Logger.loggerCache = { userId: '', logId: 'none', isNewNavi: false, hasStarted: false }; return Logger; })(); RongIMLib.Logger = Logger; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var LoggerUtil = (function () { function LoggerUtil() { } LoggerUtil.isLowLevelBro = function () { var flag = false; var bro = RongIMLib.RongUtil.getBrower(); if (bro.type == 'IE' && bro.version < 9) { flag = true; } return flag; }; LoggerUtil.isRealTimeLogType = function (type) { return type === RongIMLib.LoggerReportType.REAL_TIME_LOG; }; LoggerUtil.handleLog = function (conf) { var self = this; var csvLog = ''; var logs = RongIMLib.Logger.logStore; var lastIndex = 0; if (self.isRealTimeLogType(conf.type)) { RongIMLib.RongUtil.forEach(logs, function (log, index) { if (log.time > self.lastTime && log.level <= conf.level) { csvLog += self.genCSVLog(log); lastIndex = index; } }); if (csvLog.length !== 0) { self.lastTime = logs[lastIndex].time; } } else { RongIMLib.RongUtil.forEach(logs, function (log) { if (log.level <= conf.level && log.time >= conf.startTime && log.time <= conf.endTime) { csvLog += self.genCSVLog(log); } }); } return csvLog; }; LoggerUtil.getNaviPolicy = function () { var navi = RongIMLib.RongIMClient._storageProvider.getItem("fullnavi") || "{}"; var fullNavi = navi && JSON.parse(navi); var policy = {}; var logPolicy = fullNavi.logPolicy; var logSwitch = fullNavi.logSwitch; policy = logPolicy && JSON.parse(logPolicy); policy.logSwitch = logSwitch; return policy; }; LoggerUtil.genDeviceId = function () { var deviceId = ''; var key = 'deviceId'; var isSupportLS = RongIMLib.RongUtil.supportLocalStorage(); var isSupportSS = RongIMLib.RongUtil.supportSessionStorage(); var loggerStorage; if (isSupportLS) { loggerStorage = new RongIMLib.LocalStorageProvider(); } else if (isSupportSS) { loggerStorage = new RongIMLib.sessionStorageProvider(); } else { loggerStorage = new RongIMLib.MemeoryProvider(); } var hasDeviceId = loggerStorage.getItem(key); if (hasDeviceId) { deviceId = loggerStorage.getItem(key); } else { loggerStorage.removeItem(key); var uuid = RongIMLib.RongUtil.getUUID22(); loggerStorage.setItem(key, uuid); deviceId = uuid; } return deviceId; }; LoggerUtil.getSessionId = function () { var sessionId = ''; var key = 'sessionId'; var sessionStorage; var isSupportSS = RongIMLib.RongUtil.supportSessionStorage(); if (isSupportSS) { sessionStorage = new RongIMLib.sessionStorageProvider(); } else { sessionStorage = new RongIMLib.MemeoryProvider(); } var hasSessionId = sessionStorage.getItem(key); if (hasSessionId) { sessionId = sessionStorage.getItem(key); } else { sessionStorage.removeItem(key); var val = RongIMLib.RongUtil.getUUID22(); sessionStorage.setItem(key, val); sessionId = val; } return sessionId; }; LoggerUtil.getDeviceInfo = function () { var self = this; var browerInfo = RongIMLib.RongUtil.getBrower(); var sessionId = self.getSessionId().slice(0, 10); var infoTpl = '{brower}|{version}|{sessionId}'; return RongIMLib.RongUtil.tplEngine(infoTpl, { brower: browerInfo.type, version: browerInfo.version, sessionId: sessionId }); }; LoggerUtil.getEntireUrl = function (opt) { var self = this; var tLogTpl = '{protocol}{url}?version={version}&appkey={appkey}&userId={userId}&deviceId={deviceId}&deviceInfo={deviceInfo}&platform={platform}'; var mLogTpl = '{protocol}{url}?version={version}&appkey={appkey}&userId={userId}&logId={logId}&deviceId={deviceId}&deviceInfo={deviceInfo}&platform={platform}'; var entireUrl = ''; var protocol = "https://"; if (location.protocol == "http:") { protocol = "http://"; } var paramObj = { protocol: protocol, url: opt.url, version: RongIMLib.RongIMClient.sdkver || 'Unknown version', appkey: RongIMLib.RongIMClient._memoryStore.appKey || 'Unknown appkey', deviceId: self.genDeviceId(), deviceInfo: self.getDeviceInfo(), platform: 'Web', userId: RongIMLib.Logger.loggerCache.userId || '' }; if (self.isRealTimeLogType(opt.type)) { entireUrl = RongIMLib.RongUtil.tplEngine(tLogTpl, paramObj); } else { entireUrl = RongIMLib.RongUtil.tplEngine(mLogTpl, RongIMLib.RongUtil.extend(paramObj, { logId: opt.logId })); } return entireUrl; }; LoggerUtil.genCSVLog = function (log) { var tpl = '{sessionId},{time},{type},{level},{tag},{content}\n'; if (log.content) { var content = '"' + log.content.replace(/\"/g, '""') + '"'; } var csvLog = RongIMLib.RongUtil.tplEngine(tpl, { sessionId: log.sessionId, time: log.time, type: log.type, level: log.level, tag: log.tag, content: content || '""' }); return csvLog; }; LoggerUtil.isLogCmdMsg = function (message) { var flag = false; if (message.messageType === RongIMLib.RongIMClient.MessageType["LogCommandMessage"] && message.senderUserId === 'rongcloudsystem') { flag = true; } return flag; }; LoggerUtil.recordFatalLogOfNavi = function (internalRetry, navigators) { if (internalRetry === 3) { RongIMLib.Logger.writeLog({ tag: RongIMLib.LoggerTag.IM.L_GETN_R, level: RongIMLib.LoggerLevel.F, type: RongIMLib.LoggerType.IM, content: { desc: 'Request navigation failed 3 times', navigators: navigators } }); } }; LoggerUtil.lastTime = 0; return LoggerUtil; })(); RongIMLib.LoggerUtil = LoggerUtil; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var MemeoryProvider = (function () { function MemeoryProvider() { this._memeoryStore = {}; this.prefix = "rong_"; } MemeoryProvider.prototype.setItem = function (composedKey, object) { this._memeoryStore[composedKey] = decodeURIComponent(object); }; MemeoryProvider.prototype.getItem = function (composedKey) { return this._memeoryStore[composedKey]; }; MemeoryProvider.prototype.removeItem = function (composedKey) { if (this.getItem(composedKey)) { delete this._memeoryStore[composedKey]; } }; MemeoryProvider.prototype.getItemKey = function (regStr) { var me = this, item = null, reg = new RegExp(regStr + "\\w+"); for (var key in me._memeoryStore) { var arr = key.match(reg); if (arr) { item = key; } } return item; }; MemeoryProvider.prototype.getItemKeyList = function (regStr) { var prefix = this.prefix; var me = this, itemList = [], reg = new RegExp(regStr + "\\w+"); for (var key in me._memeoryStore) { var arr = key.match(reg); if (arr) { key = key.substring(prefix.length); itemList.push(key); } } return itemList; }; MemeoryProvider.prototype.clearItem = function () { var me = this; for (var key in me._memeoryStore) { delete me._memeoryStore[key]; } }; //单位:字节 MemeoryProvider.prototype.onOutOfQuota = function () { return 4 * 1024; }; return MemeoryProvider; })(); RongIMLib.MemeoryProvider = MemeoryProvider; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var LocalStorageProvider = (function () { // static _instance: LocalStorageProvider = new LocalStorageProvider(); function LocalStorageProvider() { this.prefix = 'rong_'; this._host = ""; var d = new Date(), m = d.getMonth() + 1, date = d.getFullYear() + '/' + (m.toString().length == 1 ? '0' + m : m) + '/' + d.getDate(), nowDate = new Date(date).getTime(); for (var key in localStorage) { if (key.lastIndexOf('RECEIVED') > -1) { var recObj = JSON.parse(localStorage.getItem(key)); for (var key_1 in recObj) { nowDate - recObj[key_1].dealtime > 0 && (delete recObj[key_1]); } if (RongIMLib.RongUtil.isEmpty(recObj)) { localStorage.removeItem(key); } else { localStorage.setItem(key, JSON.stringify(recObj)); } } if (key.lastIndexOf('SENT') > -1) { var sentObj = JSON.parse(localStorage.getItem(key)); nowDate - sentObj.dealtime > 0 && (localStorage.removeItem(key)); } } } LocalStorageProvider.prototype.setItem = function (composedKey, object) { if (composedKey) { composedKey.indexOf(this.prefix) == -1 && (composedKey = this.prefix + composedKey); localStorage.setItem(composedKey, object); } }; LocalStorageProvider.prototype.getItem = function (composedKey) { if (composedKey) { composedKey.indexOf(this.prefix) == -1 && (composedKey = this.prefix + composedKey); return localStorage.getItem(composedKey ? composedKey : ""); } return ""; }; LocalStorageProvider.prototype.getItemKey = function (composedStr) { var item = ""; var _key = this.prefix + composedStr; for (var key in localStorage) { if (key.indexOf(_key) == 0) { item = key; break; } } return item; }; LocalStorageProvider.prototype.getItemKeyList = function (composedStr) { var itemList = []; var prefix = this.prefix; var _key = prefix + composedStr; for (var key in localStorage) { if (key.indexOf(_key) == 0) { key = key.substring(prefix.length); itemList.push(key); } } return itemList; }; LocalStorageProvider.prototype.removeItem = function (composedKey) { if (composedKey) { composedKey.indexOf(this.prefix) == -1 && (composedKey = this.prefix + composedKey); localStorage.removeItem(composedKey.toString()); } }; LocalStorageProvider.prototype.clearItem = function () { var me = this; for (var key in localStorage) { if (key.indexOf(me.prefix) > -1) { me.removeItem(key); } } }; //单位:字节 LocalStorageProvider.prototype.onOutOfQuota = function () { return JSON.stringify(localStorage).length; }; return LocalStorageProvider; })(); RongIMLib.LocalStorageProvider = LocalStorageProvider; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var sessionStorageProvider = (function () { function sessionStorageProvider() { this.prefix = 'rong_'; this._host = ""; } sessionStorageProvider.prototype.setItem = function (composedKey, object) { if (composedKey) { composedKey.indexOf(this.prefix) == -1 && (composedKey = this.prefix + composedKey); sessionStorage.setItem(composedKey, object); } }; sessionStorageProvider.prototype.getItem = function (composedKey) { if (composedKey) { composedKey.indexOf(this.prefix) == -1 && (composedKey = this.prefix + composedKey); return sessionStorage.getItem(composedKey ? composedKey : ""); } return ''; }; sessionStorageProvider.prototype.getItemKey = function (composedStr) { var item = ""; var _key = this.prefix + composedStr; for (var key in sessionStorage) { if (key.indexOf(_key) == 0) { item = key; break; } } return item; }; sessionStorageProvider.prototype.getItemKeyList = function (composedStr) { var itemList = []; var prefix = this.prefix; var _key = prefix + composedStr; for (var key in sessionStorage) { if (key.indexOf(_key) == 0) { key = key.substring(prefix.length); itemList.push(key); } } return itemList; }; sessionStorageProvider.prototype.removeItem = function (composedKey) { if (composedKey) { composedKey.indexOf(this.prefix) == -1 && (composedKey = this.prefix + composedKey); sessionStorage.removeItem(composedKey.toString()); } }; sessionStorageProvider.prototype.clearItem = function () { var me = this; for (var key in sessionStorage) { if (key.indexOf(me.prefix) > -1) { me.removeItem(key); } } }; sessionStorageProvider.prototype.onOutOfQuota = function () { return JSON.stringify(sessionStorage).length; }; return sessionStorageProvider; })(); RongIMLib.sessionStorageProvider = sessionStorageProvider; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var UserDataProvider = (function () { function UserDataProvider() { this.opersistName = 'RongIMLib'; this.keyManager = 'RongUserDataKeyManager'; this._host = ""; this.prefix = "rong_"; this.oPersist = document.createElement("div"); this.oPersist.style.display = "none"; this.oPersist.style.behavior = "url('#default#userData')"; document.body.appendChild(this.oPersist); this.oPersist.load(this.opersistName); } UserDataProvider.prototype.setItem = function (key, value) { key && key.indexOf(this.prefix) == -1 && (key = this.prefix + key); this.oPersist.setAttribute(key, value); var keyNames = this.getItem(this.keyManager); keyNames ? keyNames.indexOf(key) == -1 && (keyNames += ',' + key) : (keyNames = key); this.oPersist.setAttribute(this.prefix + this.keyManager, keyNames); this.oPersist.save(this.opersistName); }; UserDataProvider.prototype.getItem = function (key) { key && key.indexOf(this.prefix) == -1 && (key = this.prefix + key); return key ? this.oPersist.getAttribute(key) : key; }; UserDataProvider.prototype.removeItem = function (key) { key && key.indexOf(this.prefix) == -1 && (key = this.prefix + key); this.oPersist.removeAttribute(key); this.oPersist.save(this.opersistName); var keyNames = this.getItem(this.keyManager), keyNameArray = keyNames && keyNames.split(',') || []; for (var i = 0, len = keyNameArray.length; i < len; i++) { if (keyNameArray[i] == key) { keyNameArray.splice(i, 1); } } this.oPersist.setAttribute(this.prefix + this.keyManager, keyNameArray.join(',')); this.oPersist.save(this.opersistName); }; UserDataProvider.prototype.getItemKey = function (composedStr) { var item = null, keyNames = this.getItem(this.keyManager), keyNameArray = keyNames && keyNames.split(',') || [], me = this; var _key = this.prefix + composedStr; if (keyNameArray.length) { for (var i = 0, len = keyNameArray.length; i < len; i++) { if (keyNameArray[i] && keyNameArray[i].indexOf(_key) == 0) { item = keyNameArray[i]; break; } } } return item; }; UserDataProvider.prototype.getItemKeyList = function (composedStr) { var itemList = [], keyNames = this.getItem(this.keyManager), keyNameArray = keyNames && keyNames.split(',') || []; var prefix = this.prefix; var _key = prefix + composedStr; if (keyNameArray.length) { for (var i = 0, len = keyNameArray.length; i < len; i++) { if (keyNameArray[i] && keyNameArray[i].indexOf(_key) == 0) { var keyName = keyNameArray[i]; keyName = keyName.substring(prefix.length); itemList.push(keyNameArray[i]); } } } return itemList; }; UserDataProvider.prototype.clearItem = function () { var keyNames = this.getItem(this.keyManager), keyNameArray = [], me = this; keyNames && (keyNameArray = keyNames.split(',')); if (keyNameArray.length) { for (var i = 0, len = keyNameArray.length; i < len; i++) { keyNameArray[i] && me.removeItem(keyNameArray[i]); } me.removeItem(me.keyManager); } }; UserDataProvider.prototype.onOutOfQuota = function () { return 10 * 1024 * 1024; }; return UserDataProvider; })(); RongIMLib.UserDataProvider = UserDataProvider; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var FeatureDectector = (function () { function FeatureDectector(callback) { this.script = document.createElement("script"); this.head = document.getElementsByTagName("head")[0]; if ("WebSocket" in window && "ArrayBuffer" in window && WebSocket.prototype.CLOSED === 3 && !RongIMLib.RongIMClient._memoryStore.depend.isPolling) { RongIMLib.Transportations._TransportType = RongIMLib.Socket.WEBSOCKET; if (!RongIMLib.RongIMClient.Protobuf) { var url = RongIMLib.RongIMClient._memoryStore.depend.protobuf; var script = this.script; script.src = url; this.head.appendChild(script); script.onload = script.onreadystatechange = function () { var isLoaded = (!this.readyState || this.readyState == 'loaded' || this.readyState == 'complete'); if (isLoaded) { // 防止 IE6、7 下偶发触发两次 loaded script.onload = script.onreadystatechange = null; if (callback) { callback(); } if (!callback) { var token = RongIMLib.RongIMClient._memoryStore.token; var connectCallback = RongIMLib.RongIMClient._memoryStore.callback; token && RongIMLib.RongIMClient.connect(token, connectCallback, null, { isIgnoreReportStart: true }); } } }; } } else { RongIMLib.Transportations._TransportType = "xhr-polling"; RongIMLib.RongIMClient.Protobuf = Polling; } } return FeatureDectector; })(); RongIMLib.FeatureDectector = FeatureDectector; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var FeaturePatcher = (function () { function FeaturePatcher() { } FeaturePatcher.prototype.patchAll = function () { this.patchJSON(); this.patchForEach(); }; FeaturePatcher.prototype.patchForEach = function () { if (!Array.forEach) { Array.forEach = function (arr, func) { for (var i = 0; i < arr.length; i++) { func.call(arr, arr[i], i, arr); } }; } }; FeaturePatcher.prototype.patchJSON = function () { if (!window["JSON"]) { window["JSON"] = (function () { function JSON() { } JSON.parse = function (sJSON) { return eval('(' + sJSON + ')'); }; JSON.stringify = function (value) { return this.str("", { "": value }); }; JSON.str = function (key, holder) { var i, k, v, length, mind = "", partial, value = holder[key], me = this; if (value && typeof value === "object" && typeof value.toJSON === "function") { value = value.toJSON(key); } switch (typeof value) { case "string": return me.quote(value); case "number": return isFinite(value) ? String(value) : "null"; case "boolean": case "null": return String(value); case "object": if (!value) { return "null"; } partial = []; if (Object.prototype.toString.apply(value) === "[object Array]") { length = value.length; for (i = 0; i < length; i += 1) { partial[i] = me.str(i, value) || "null"; } v = partial.length === 0 ? "[]" : "[" + partial.join(",") + "]"; return v; } for (k in value) { if (Object.prototype.hasOwnProperty.call(value, k)) { v = me.str(k, value); if (v) { partial.push(me.quote(k) + ":" + v); } } } v = partial.length === 0 ? "{}" : "{" + partial.join(",") + "}"; return v; } }; JSON.quote = function (string) { var me = this; me.rx_escapable.lastIndex = 0; return me.rx_escapable.test(string) ? '"' + string.replace(me.rx_escapable, function (a) { var c = me.meta[a]; return typeof c === "string" ? c : "\\u" + ("0000" + a.charCodeAt(0).toString(16)).slice(-4); }) + '"' : '"' + string + '"'; }; JSON.rx_escapable = new RegExp('[\\\"\\\\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]', "g"); JSON.meta = { "\b": "\\b", " ": "\\t", "\n": "\\n", "\f": "\\f", "\r": "\\r", '"': '\\"', "''": "\\''", "\\": "\\\\" }; return JSON; })(); } }; return FeaturePatcher; })(); RongIMLib.FeaturePatcher = FeaturePatcher; })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var ScriptLoader = (function () { function ScriptLoader() { } ScriptLoader.prototype.load = function (src, onLoad, onError) { var script = document.createElement("script"); script.async = true; if (onLoad) { if (script.addEventListener) { script.addEventListener("load", function (event) { var target = event.target || event.srcElement; onLoad(target.src); }, false); } else if (script.readyState) { script.onreadystatechange = function (event) { var target = event.srcElement; onLoad(target.src); }; } } if (onError) { script.onerror = function (event) { var target = event.target || event.srcElement; onError(target.src); }; } (document.head || document.getElementsByTagName("head")[0]).appendChild(script); script.src = src; }; return ScriptLoader; })(); })(RongIMLib || (RongIMLib = {})); var RongIMLib; (function (RongIMLib) { var PublicServiceMap = (function () { function PublicServiceMap() { this.publicServiceList = []; } PublicServiceMap.prototype.get = function (publicServiceType, publicServiceId) { for (var i = 0, len = this.publicServiceList.length; i < len; i++) { if (this.publicServiceList[i].conversationType == publicServiceType && publicServiceId == this.publicServiceList[i].publicServiceId) { return this.publicServiceList[i]; } } }; PublicServiceMap.prototype.add = function (publicServiceProfile) { var isAdd = true, me = this; for (var i = 0, len = this.publicServiceList.length; i < len; i++) { if (me.publicServiceList[i].conversationType == publicServiceProfile.conversationType && publicServiceProfile.publicServiceId == me.publicServiceList[i].publicServiceId) { this.publicServiceList.unshift(this.publicServiceList.splice(i, 1)[0]); isAdd = false; break; } } if (isAdd) { this.publicServiceList.unshift(publicServiceProfile); } }; PublicServiceMap.prototype.replace = function (publicServiceProfile) { var me = this; for (var i = 0, len = this.publicServiceList.length; i < len; i++) { if (me.publicServiceList[i].conversationType == publicServiceProfile.conversationType && publicServiceProfile.publicServiceId == me.publicServiceList[i].publicServiceId) { me.publicServiceList.splice(i, 1, publicServiceProfile); break; } } }; PublicServiceMap.prototype.remove = function (conversationType, publicServiceId) { var me = this; for (var i = 0, len = this.publicServiceList.length; i < len; i++) { if (me.publicServiceList[i].conversationType == conversationType && publicServiceId == me.publicServiceList[i].publicServiceId) { this.publicServiceList.splice(i, 1); break; } } }; return PublicServiceMap; })(); RongIMLib.PublicServiceMap = PublicServiceMap; /** * 会话工具类。 */ var ConversationMap = (function () { function ConversationMap() { this.conversationList = []; } ConversationMap.prototype.get = function (conversavtionType, targetId) { for (var i = 0, len = this.conversationList.length; i < len; i++) { if (this.conversationList[i].conversationType == conversavtionType && this.conversationList[i].targetId == targetId) { return this.conversationList[i]; } } return null; }; ConversationMap.prototype.add = function (conversation) { var isAdd = true; for (var i = 0, len = this.conversationList.length; i < len; i++) { if (this.conversationList[i].conversationType === conversation.conversationType && this.conversationList[i].targetId === conversation.targetId) { this.conversationList.unshift(this.conversationList.splice(i, 1)[0]); isAdd = false; break; } } if (isAdd) { this.conversationList.unshift(conversation); } }; /** * [replace 替换会话] * 会话数组存在的情况下调用add方法会是当前会话被替换且返回到第一个位置,导致用户本地一些设置失效,所以提供replace方法 */ ConversationMap.prototype.replace = function (conversation) { for (var i = 0, len = this.conversationList.length; i < len; i++) { if (this.conversationList[i].conversationType === conversation.conversationType && this.conversationList[i].targetId === conversation.targetId) { this.conversationList.splice(i, 1, conversation); break; } } }; ConversationMap.prototype.remove = function (conversation) { for (var i = 0, len = this.conversationList.length; i < len; i++) { if (this.conversationList[i].conversationType === conversation.conversationType && this.conversationList[i].targetId === conversation.targetId) { this.conversationList.splice(i, 1); break; } } }; return ConversationMap; })(); RongIMLib.ConversationMap = ConversationMap; var CheckParam = (function () { function CheckParam() { } CheckParam.getInstance = function () { if (!CheckParam._instance) { CheckParam._instance = new CheckParam(); } return CheckParam._instance; }; CheckParam.prototype.logger = function (code, funcName, msg) { RongIMLib.RongIMClient.logger({ code: code, funcName: funcName, msg: msg }); }; CheckParam.prototype.check = function (f, position, d, c) { if (RongIMLib.RongIMClient._dataAccessProvider || d) { for (var g = 0, e = c.length; g < e; g++) { if (!new RegExp(this.getType(c[g])).test(f[g])) { // throw new Error("The index of " + g + " parameter was wrong type " + this.getType(c[g]) + " [" + f[g] + "] -> position:" + position); var msg = "第" + (g + 1) + "个参数错误, 错误类型:" + this.getType(c[g]) + " [" + f[g] + "] -> 位置:" + position; this.logger("-3", position, msg); } } } else { var msg = "该参数不正确或尚未实例化RongIMClient -> 位置:" + position; this.logger("-4", position, msg); } }; CheckParam.prototype.getType = function (str) { var temp = Object.prototype.toString.call(str).toLowerCase(); return temp.slice(8, temp.length - 1); }; CheckParam.prototype.checkCookieDisable = function () { document.cookie = "checkCookie=1"; var arr = document.cookie.match(new RegExp("(^| )checkCookie=([^;]*)(;|$)")), isDisable = false; if (!arr) { isDisable = true; } document.cookie = "checkCookie=1;expires=Thu, 01-Jan-1970 00:00:01 GMT"; return isDisable; }; return CheckParam; })(); RongIMLib.CheckParam = CheckParam; var LimitableMap = (function () { function LimitableMap(limit) { this.map = {}; this.keys = []; this.limit = limit || 10; } LimitableMap.prototype.set = function (key, value) { this.map[key] = value; }; LimitableMap.prototype.get = function (key) { return this.map[key] || 0; }; LimitableMap.prototype.remove = function (key) { delete this.map[key]; }; return LimitableMap; })(); RongIMLib.LimitableMap = LimitableMap; var MemoryCache = (function () { function MemoryCache() { this.cache = {}; } MemoryCache.prototype.set = function (key, value) { this.cache[key] = value; }; MemoryCache.prototype.get = function (key) { return this.cache[key]; }; MemoryCache.prototype.remove = function (key) { delete this.cache[key]; }; return MemoryCache; })(); RongIMLib.MemoryCache = MemoryCache; var RongAjax = (function () { function RongAjax(options) { var me = this; me.xmlhttp = null; me.options = options; var hasCORS = typeof XMLHttpRequest !== "undefined" && "withCredentials" in new XMLHttpRequest(); if ("undefined" != typeof XMLHttpRequest && hasCORS) { me.xmlhttp = new XMLHttpRequest(); } else if ("undefined" != typeof XDomainRequest) { me.xmlhttp = new XDomainRequest(); } else { me.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); } } RongAjax.prototype.send = function (callback) { var me = this; me.options.url || (me.options.url = "http://upload.qiniu.com/putb64/-1"); me.xmlhttp.onreadystatechange = function () { if (me.xmlhttp.readyState == 4) { if (me.options.type) { callback(); } else { callback(JSON.parse(me.xmlhttp.responseText.replace(/'/g, '"'))); } } }; me.xmlhttp.open("POST", me.options.url, true); me.xmlhttp.withCredentials = false; if ("setRequestHeader" in me.xmlhttp) { if (me.options.type) { me.xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=utf-8"); } else { me.xmlhttp.setRequestHeader("Content-type", "application/octet-stream"); me.xmlhttp.setRequestHeader('Authorization', "UpToken " + me.options.token); } } me.xmlhttp.send(me.options.type ? "appKey=" + me.options.appKey + "&deviceId=" + me.options.deviceId + "×tamp=" + me.options.timestamp + "&deviceInfo=" + me.options.deviceInfo + "&privateInfo=" + JSON.stringify(me.options.privateInfo) : me.options.base64); }; return RongAjax; })(); RongIMLib.RongAjax = RongAjax; function Prosumer() { var data = [], isConsuming = false; this.produce = function (res) { data.push(res); }; this.consume = function (callback, finished) { if (isConsuming) { return; } isConsuming = true; var next = function () { var res = data.shift(); if (RongUtil.isUndefined(res)) { isConsuming = false; finished && finished(); return; } callback(res, next); }; next(); }; this.isExeuting = function () { return isConsuming; }; } var RongUtil = (function () { function RongUtil() { } RongUtil.noop = function () { }; RongUtil.isEmpty = function (obj) { var result = true; if (RongUtil.isObject(obj)) { RongUtil.forEach(obj, function () { result = false; }); } if (RongUtil.isString(obj) || RongUtil.isArray(obj)) { return obj.length === 0; } if (RongUtil.isNumber(obj)) { return obj === 0; } return result; }; RongUtil.isLengthLimit = function (str, maxLen, minLen) { minLen = minLen || 0; var strLen = str.length; return strLen <= maxLen && strLen >= minLen; }; RongUtil.MD5 = function (str, key, raw) { return md5(str, key, raw); }; RongUtil.isObject = function (obj) { return Object.prototype.toString.call(obj) == '[object Object]'; }; RongUtil.isArray = function (array) { return Object.prototype.toString.call(array) == '[object Array]'; }; RongUtil.isString = function (array) { return Object.prototype.toString.call(array) == '[object String]'; }; RongUtil.isFunction = function (fun) { return Object.prototype.toString.call(fun) == '[object Function]'; }; ; RongUtil.isUndefined = function (str) { return Object.prototype.toString.call(str) == '[object Undefined]'; }; ; RongUtil.isEqual = function (a, b) { return a === b; }; ; RongUtil.indexOf = function (arrs, item) { var index = -1; for (var i = 0; i < arrs.length; i++) { if (item === arrs[i]) { index = i; break; } } return index; }; RongUtil.stringFormat = function (tmpl, vals) { for (var i = 0, len = vals.length; i < len; i++) { var val = vals[i], reg = new RegExp("\\{" + (i) + "\\}", "g"); tmpl = tmpl.replace(reg, val); } return tmpl; }; RongUtil.tplEngine = function (temp, data, regexp) { if (!(Object.prototype.toString.call(data) === "[object Array]")) { data = [data]; } var ret = []; for (var i = 0, j = data.length; i < j; i++) { ret.push(replaceAction(data[i])); } return ret.join(""); function replaceAction(object) { return temp.replace(regexp || (/{([^}]+)}/g), function (match, name) { if (match.charAt(0) == '\\') { return match.slice(1); } return (object[name] != undefined) ? object[name] : '{' + name + '}'; }); } }; ; RongUtil.forEach = function (obj, callback) { callback = callback || RongUtil.noop; var loopObj = function () { for (var key in obj) { if (obj.hasOwnProperty(key)) { callback(obj[key], key, obj); } } }; var loopArr = function () { for (var i = 0, len = obj.length; i < len; i++) { callback(obj[i], i); } }; if (RongUtil.isObject(obj)) { loopObj(); } if (RongUtil.isArray(obj)) { loopArr(); } }; RongUtil.extend = function (source, target, callback, force) { RongUtil.forEach(source, function (val, key) { var hasProto = (key in target); if (force && hasProto) { target[key] = val; } if (!hasProto) { target[key] = val; } }); return target; }; RongUtil.createXHR = function () { var item = { XMLHttpRequest: function () { return new XMLHttpRequest(); }, XDomainRequest: function () { return new XDomainRequest(); }, ActiveXObject: function () { return new ActiveXObject('Microsoft.XMLHTTP'); } }; var isXHR = typeof XMLHttpRequest !== "undefined" && "withCredentials" in new XMLHttpRequest(); var isXDR = typeof XDomainRequest == 'function' || typeof XDomainRequest == 'object'; var key = isXHR ? 'XMLHttpRequest' : isXDR ? 'XDomainRequest' : 'ActiveXObject'; return item[key](); }; RongUtil.request = function (opts) { var url = opts.url; var body = opts.body; var success = opts.success; var error = opts.error || RongUtil.noop; var method = opts.method || 'GET'; var timeout = opts.timeout; var xhr = RongUtil.createXHR(); if ('onload' in xhr) { xhr.onload = function () { xhr.onload = RongUtil.noop; success(xhr.responseText); }; xhr.onerror = function () { error(xhr.status, xhr.responseText); xhr.onerror = RongUtil.noop; }; } else { xhr.onreadystatechange = function () { if (xhr.readyState == 4) { var status = xhr.status; if (status == 200) { success(xhr.responseText); } else { error(status, xhr.responseText); } } }; } xhr.open(method, url, true); if (timeout) { xhr.timeout = timeout; } if (body) { xhr.send(body); return xhr; } xhr.send(null); return xhr; }; RongUtil.getLocalProtocol = function () { var isLocationInvalid = typeof location !== 'object'; // 未找到全局 location 变量, 则协议为 https. 比如小程序 if (isLocationInvalid || location.protocol === 'https:') { return 'https://'; } else { return 'http://'; } }; RongUtil.formatProtoclPath = function (config) { var path = config.path; var protocol = config.protocol; var tmpl = config.tmpl || '{0}{1}'; var sub = config.sub; var flag = '://'; var index = path.indexOf(flag); var hasProtocol = (index > -1); if (hasProtocol) { index += flag.length; path = path.substring(index); } if (sub) { index = path.indexOf('/'); var hasPath = (index > -1); if (hasPath) { path = path.substr(0, index); } } return RongUtil.stringFormat(tmpl, [protocol, path]); }; ; RongUtil.getValidNavi = function (naviHost) { var HttpProtocol = RongIMLib.RongIMClient.HttpProtocol; var flag = '://'; var index = naviHost.indexOf(flag); var hasProtocol = index > -1; var navi = naviHost; if (!hasProtocol) { var protocol = RongIMLib.RongIMClient.getProtocol().protocol; navi = protocol + naviHost; } var naviProtocol = RongUtil.getUrlProtocol(navi), localProtocol = RongUtil.getLocalProtocol(); // 本地为 https, 但却传入 http 时, 强制转化为 https if (naviProtocol === HttpProtocol.http && localProtocol === 'https://') { navi = RongUtil.formatProtoclPath({ path: navi, tmpl: '{0}{1}', protocol: HttpProtocol.https, sub: true }); } return navi; }; RongUtil.getUrlProtocol = function (url) { var flag = '://'; var index = url.indexOf(flag); if (index > -1) { return url.substring(0, index + flag.length); } else { return 'https://'; } ; }; RongUtil.getUrlHost = function (url) { var index = RongUtil.indexOf(url, '/'); return url.substring(0, index); }; RongUtil.supportLocalStorage = function () { var support = false; if (typeof localStorage == 'object') { try { var key = 'RC_TMP_KEY', value = 'RC_TMP_VAL'; localStorage.setItem(key, value); var localVal = localStorage.getItem(key); if (localVal == value) { support = true; } } catch (err) { console.log('localStorage is disabled.'); } } return support; }; RongUtil.supportSessionStorage = function () { var support = false; if (typeof sessionStorage == 'object') { try { var key = 'RC_TMP_KEY', value = 'RC_TMP_VAL'; sessionStorage.setItem(key, value); var localVal = sessionStorage.getItem(key); if (localVal == value) { support = true; } } catch (err) { console.log('sessionStorage is disabled.'); } } return support; }; /* //返回新引用,不破坏原始对象 rename({n: 'martin'}, {n: 'name'}); => {name: 'martin'} rename([{n: 'martin'}, {a: 18}], {n: 'name', a: 'age'}); => [{name: 'martin'}, {age: 18}] */ RongUtil.rename = function (origin, newNames) { var isObject = RongUtil.isObject(origin); if (isObject) { origin = [origin]; } origin = JSON.parse(JSON.stringify(origin)); var updateProperty = function (val, key, obj) { delete obj[key]; key = newNames[key]; obj[key] = val; }; RongUtil.forEach(origin, function (item) { RongUtil.forEach(item, function (val, key, obj) { var isRename = (key in newNames); (isRename ? updateProperty : RongUtil.noop)(val, key, obj); }); }); return isObject ? origin[0] : origin; }; RongUtil.some = function (arrs, callback) { var has = false; for (var i = 0, len = arrs.length; i < len; i++) { if (callback(arrs[i])) { has = true; break; } } return has; }; RongUtil.keys = function (obj) { var props = []; for (var key in obj) { props.push(key); } return props; }; RongUtil.isNumber = function (num) { return Object.prototype.toString.call(num) == '[object Number]'; }; RongUtil.getTimestamp = function () { var date = new Date(); return date.getTime(); }; RongUtil.isSupportRequestHeaders = function () { var userAgent = navigator.userAgent; var isIE = window.ActiveXObject || 'ActiveXObject' in window; if (isIE) { var reIE = new RegExp('MSIE (\\d+\\.\\d+);'); reIE.test(userAgent); var fIEVersion = parseFloat(RegExp['$1']); return fIEVersion > 9; } return true; }; RongUtil.hasValidWsUrl = function (urls) { try { urls = JSON.parse(urls); } catch (e) { return false; } var validUrlList = RongUtil.getValidWsUrlList(urls); return validUrlList.length > 0; }; RongUtil.getValidWsUrlList = function (urls) { var invalidWsUrls = RongIMLib.RongIMClient.invalidWsUrls; var validUrlList = []; RongUtil.forEach(urls, function (url) { if (RongUtil.indexOf(invalidWsUrls, url) === -1) { validUrlList.push(url); } }); return validUrlList; }; RongUtil.getBrower = function () { var userAgent = navigator.userAgent; var version; var type; /* 记录各浏览器名字和匹配条件 */ var condition = { IE: /rv:([\d.]+)\) like Gecko|MSIE ([\d.]+)/, Edge: /Edge\/([\d.]+)/, Firefox: /Firefox\/([\d.]+)/, Opera: /(?:OPERA|OPR).([\d.]+)/, WeChat: /MicroMessenger\/([\d.]+)/, QQBrowser: /QQBrowser\/([\d.]+)/, Chrome: /Chrome\/([\d.]+)/, Safari: /Version\/([\d.]+).*Safari/, iOSChrome: /Mobile\/([\d.]+).*Safari/ }; for (var key in condition) { if (!condition.hasOwnProperty(key)) continue; var browserContent; if (browserContent = userAgent.match(condition[key])) { type = key; version = browserContent[1] || browserContent[2]; break; } } return { type: type || 'UnKonw', version: version || 'UnKonw' }; }; RongUtil.string10to64 = function (number) { var chars = '0123456789abcdefghigklmnopqrstuvwxyzABCDEFGHIGKLMNOPQRSTUVWXYZa0'.split(''), radix = chars.length + 1, qutient = +number, arr = []; do { var mod = qutient % radix; qutient = (qutient - mod) / radix; arr.unshift(chars[mod]); } while (qutient); return arr.join(''); }; RongUtil.getUUID = function () { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8); return v.toString(16); }); }; /* 获取 22 位的 UUID */ RongUtil.getUUID22 = function () { var uuid = this.getUUID(); uuid = uuid.replace(/-/g, '') + 'a'; uuid = parseInt(uuid, 16); uuid = this.string10to64(uuid); if (uuid.length > 22) { uuid = uuid.slice(0, 22); } if (uuid.length < 22) { var len = 22 - uuid.length; for (var i = 0; i < len; i++) { uuid = uuid + '0'; } } return uuid; }; RongUtil.getByteLength = function (str, charset) { charset = charset || 'utf-8'; var total = 0, chatCode; if (charset === 'utf-16') { for (var i = 0, max = str.length; i < max; i++) { chatCode = str.charCodeAt(i); if (chatCode <= 0xffff) { total += 2; } else { total += 4; } } } else { for (var i = 0, max = str.length; i < max; i++) { chatCode = str.charCodeAt(i); if (chatCode < 0x007f) { total += 1; } else if (chatCode <= 0x07ff) { total += 2; } else if (chatCode <= 0xffff) { total += 3; } else { total += 4; } } } return total; }; RongUtil.concat = function (before, after, isDedup) { RongUtil.forEach(after, function (item) { if (!isDedup || RongUtil.indexOf(before, item) === -1) { before.push(item); } }); return before; }; RongUtil.Prosumer = Prosumer; RongUtil.Storage = { set: function (key, value) { try { RongIMLib.RongIMClient._storageProvider.setItem(key, JSON.stringify(value)); } catch (e) { } }, get: function (key) { var value = RongIMLib.RongIMClient._storageProvider.getItem(key); try { return JSON.parse(value); } catch (e) { return {}; } } }; return RongUtil; })(); RongIMLib.RongUtil = RongUtil; /* var observer = new RongObserver(); observer.watch({ key: 'key', func: function(entity){ } }); */ var RongObserver = (function () { function RongObserver() { this.watchers = {}; } RongObserver.prototype.genUId = function (key) { var time = new Date().getTime(); return [key, time].join('_'); }; RongObserver.prototype.watch = function (params) { var me = this; var key = params.key; var multiple = params.multiple; key = RongUtil.isArray(key) ? key : [key]; var func = params.func; RongUtil.forEach(key, function (k) { k = multiple ? me.genUId(k) : k; me.watchers[k] = func; }); }; RongObserver.prototype.notify = function (params) { var me = this; var key = params.key; var entity = params.entity; for (var k in me.watchers) { var isNotify = (k.indexOf(key) == 0); if (isNotify) { me.watchers[k](entity); } } }; RongObserver.prototype.remove = function () { }; return RongObserver; })(); RongIMLib.RongObserver = RongObserver; var Observer = (function () { function Observer() { this.observers = []; } Observer.prototype.add = function (observer, force) { if (force) { this.observers = [observer]; } if (RongUtil.isFunction(observer)) { this.observers.push(observer); } }; Observer.prototype.emit = function (data) { RongUtil.forEach(this.observers, function (observer) { observer(data); }); }; Observer.prototype.clear = function () { this.observers = []; }; Observer.prototype.checkIndexOutBound = function (index, bound) { var isOutBound = (index > -1 && index < bound); return isOutBound; }; Observer.prototype.removeAt = function (index) { var isOutBound = this.checkIndexOutBound(index, this.observers.length); if (isOutBound) { this.observers.splice(index, 1); } }; Observer.prototype.remove = function (observer) { var me = this; if (!observer) { me.clear(); return; } if (!RongUtil.isFunction(observer)) { return; } var observerList = me.observers; for (var i = observerList.length - 1; i >= 0; i--) { if (observer === observerList[i]) { me.removeAt(i); } } }; return Observer; })(); RongIMLib.Observer = Observer; var Timer = (function () { function Timer(config) { this.timeout = 0; this.timers = []; this.timeout = config.timeout; } Timer.prototype.resume = function (callback) { var timer = setTimeout(callback, this.timeout); this.timers.push(timer); }; Timer.prototype.pause = function () { RongUtil.forEach(this.timers, function (timer) { clearTimeout(timer); }); }; return Timer; })(); RongIMLib.Timer = Timer; var IndexTools = (function () { function IndexTools(config) { this.items = []; this.index = 0; this.onwheel = function () { }; this.items = config.items; this.onwheel = config.onwheel; } IndexTools.prototype.get = function () { var context = this; var items = context.items; var index = context.index; var isWheel = index >= items.length; if (isWheel) { context.onwheel(); } return isWheel ? 0 : index; }; IndexTools.prototype.add = function () { this.index += 1; }; return IndexTools; })(); RongIMLib.IndexTools = IndexTools; var InnerUtil = (function () { function InnerUtil() { } InnerUtil.getUId = function (token) { return md5(token).slice(8, 16); }; return InnerUtil; })(); RongIMLib.InnerUtil = InnerUtil; var Base64 = (function () { function Base64() { } Base64.utf8_encode = function (string) { string = string.replace(/\r\n/g, "\n"); var utftext = ""; for (var n = 0; n < string.length; n++) { var c = string.charCodeAt(n); if (c < 128) { utftext += String.fromCharCode(c); } else if ((c > 127) && (c < 2048)) { utftext += String.fromCharCode((c >> 6) | 192); utftext += String.fromCharCode((c & 63) | 128); } else { utftext += String.fromCharCode((c >> 12) | 224); utftext += String.fromCharCode(((c >> 6) & 63) | 128); utftext += String.fromCharCode((c & 63) | 128); } } return utftext; }; Base64.utf8_decode = function (utftext) { var string = ""; var i = 0; var c = 0, c1 = 0, c2 = 0, c3; while (i < utftext.length) { c = utftext.charCodeAt(i); if (c < 128) { string += String.fromCharCode(c); i++; } else if ((c > 191) && (c < 224)) { c2 = utftext.charCodeAt(i + 1); string += String.fromCharCode(((c & 31) << 6) | (c2 & 63)); i += 2; } else { c2 = utftext.charCodeAt(i + 1); c3 = utftext.charCodeAt(i + 2); string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)); i += 3; } } return string; }; Base64.encode = function (input) { var output = ""; var chr1, chr2, chr3, enc1, enc2, enc3, enc4; var i = 0; input = this.utf8_encode(input); while (i < input.length) { chr1 = input.charCodeAt(i++); chr2 = input.charCodeAt(i++); chr3 = input.charCodeAt(i++); enc1 = chr1 >> 2; enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); enc4 = chr3 & 63; if (isNaN(chr2)) { enc3 = enc4 = 64; } else if (isNaN(chr3)) { enc4 = 64; } output = output + this.keyStr.charAt(enc1) + this.keyStr.charAt(enc2) + this.keyStr.charAt(enc3) + this.keyStr.charAt(enc4); } return output; }; Base64.decode = function (input) { var output = ""; var chr1, chr2, chr3; var enc1, enc2, enc3, enc4; var i = 0; input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ""); while (i < input.length) { enc1 = this.keyStr.indexOf(input.charAt(i++)); enc2 = this.keyStr.indexOf(input.charAt(i++)); enc3 = this.keyStr.indexOf(input.charAt(i++)); enc4 = this.keyStr.indexOf(input.charAt(i++)); chr1 = (enc1 << 2) | (enc2 >> 4); chr2 = ((enc2 & 15) << 4) | (enc3 >> 2); chr3 = ((enc3 & 3) << 6) | enc4; output = output + String.fromCharCode(chr1); if (enc3 != 64) { output = output + String.fromCharCode(chr2); } if (enc4 != 64) { output = output + String.fromCharCode(chr3); } } output = this.utf8_decode(output); return output; }; Base64.keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; return Base64; })(); RongIMLib.Base64 = Base64; var TextCompressor = (function () { function TextCompressor() { } TextCompressor.compress = function (data) { var self = this; var map = {}; //构建一个用于反向查询字符位置的 map for (var p = 0; p < data.length - 1; p++) { var c1 = data.charAt(p); var c2 = data.charAt(p + 1); var c = c1 + c2; if (!map.hasOwnProperty(c)) { map[c] = [p]; continue; } map[c].push(p); } var compressedData = [], normalBlockBuffer = []; //编码未压缩数据块 var encodeNormalBlock = function () { if (normalBlockBuffer.length > 0) { var normalBlock = normalBlockBuffer.join(''); normalBlockBuffer = []; if (normalBlock.length > 26) { var normalExtBlockLength = self.numberEncode(normalBlock.length); var normalExtBlockHeader = String.fromCharCode(self.dataType.NormalExt | normalExtBlockLength.length); compressedData.push(normalExtBlockHeader + normalExtBlockLength); } else { var normalBlockHeader = String.fromCharCode(self.dataType.Normal | normalBlock.length); compressedData.push(normalBlockHeader); } compressedData.push(normalBlock); } }; var i = 0; while (i < data.length) { var r = self.indexOf(map, data, i); if (r.length < 2) { normalBlockBuffer.push(data.charAt(i++)); continue; } if (r.length < 4) { normalBlockBuffer.push(data.substr(i, r.length)); i += r.length; continue; } var offset = self.numberEncode(i - r.offset); var length = self.numberEncode(r.length); //欲压缩的数据与数据编码后的长度一致,则不进行压缩 if (offset.length + length.length >= r.length) { normalBlockBuffer.push(data.substr(i, r.length)); i += r.length; continue; } //编码未压缩数据块 encodeNormalBlock(); //编码压缩数据块 var compressedBlockHeader = String.fromCharCode(self.dataType.Compressed | (offset.length << 2) | length.length); compressedData.push(compressedBlockHeader + offset + length); i += r.length; } //编码剩余未压缩数据块 encodeNormalBlock(); //在数据尾部添加校验和 var dataLengthTo62 = self.numberEncode(data.length); var tailBlockHeader = String.fromCharCode(self.dataType.Tail | dataLengthTo62.length); compressedData.push(tailBlockHeader + dataLengthTo62); return compressedData.join(''); }; TextCompressor.uncompress = function (data) { var self = this; var i = 0; var result = ""; label1: do { var header = data.charCodeAt(i++); var headerType = header & self.dataType.Mark; var headerVal = header & 0xF; switch (headerType) { case self.dataType.Compressed: var p1 = headerVal >> 2; var p2 = headerVal & 3; if (p1 == 0 || p2 == 0) { throw new Error("Data parsing error,at " + i); } var offset = self.numberDecode(data.substr(i, p1)); var len = self.numberDecode(data.substr(i += p1, p2)); offset = result.length - offset; if (offset + len > result.length) { throw new Error("Data parsing error,at " + i); } i += p2; result += result.substr(offset, len); break; case self.dataType.Tail: var num = self.numberDecode(data.substr(i, headerVal)); if (num != result.length) { console.log(result.length); console.log(num); throw new Error("Data parsing error,at " + i); } i += headerVal; break label1; case self.dataType.NormalExt: var num = self.numberDecode(data.substr(i, headerVal)); result += data.substr(i += headerVal, num); i += num; break; case self.dataType.Normal: result += data.substr(i, headerVal); i += headerVal; break; case self.dataType.Mark: if (headerVal > 10) { throw new Error("Data parsing error,at " + i); } result += data.substr(i, 16 + headerVal); i += (16 + headerVal); break; default: throw new Error("Data parsing error,at " + i + " header:" + headerType); } } while (i < data.length); return result; }; TextCompressor.indexOf = function (map, source, fromIndex) { var self = this; var result = { length: 0, offset: -1 }; var sourceLength = source.length; if (fromIndex >= source.length - 1) { return result; } var c1 = source.charAt(fromIndex); var c2 = source.charAt(fromIndex + 1); var items = map[c1 + c2]; if (items[0] == fromIndex) { return result; } var space1 = source.length - fromIndex; var lastChar; for (var i = 0, len = items.length; i < len; i++) { var item = items[i]; var space2 = fromIndex - item; if (space2 > self.max) { continue; } var end = Math.min(space1, space2); if (end <= result.length) { break; } if (result.length > 2) { if (source.charAt(item + result.length - 1) != source.charAt(fromIndex + result.length - 1)) { continue; } } var m = 2; for (var j = m; j < end; j++) { if (source.charAt(item + j) == source.charAt(fromIndex + j)) { m++; } else { break; } } if (m >= result.length) { result.length = m; result.offset = item; } } return result; }; /* * 将数字转化为 62 进制字符串。 */ TextCompressor.numberEncode = function (num) { var self = this; var result = [], remainder = 0; do { remainder = num % self.scale; result.push(self.chars.charAt(remainder)); num = (num - remainder) / self.scale; } while (num > 0); return result.join(''); }; /* * 将 62 进制字符串还原为数字。 */ TextCompressor.numberDecode = function (str) { var self = this; var num = 0, index = 0; for (var i = str.length - 1; i >= 0; i--) { index = self.chars.indexOf(str.charAt(i)); if (index == -1) { throw new Error("decode number error, data is \"" + str + "\""); } num = num * self.scale + index; } return num; }; TextCompressor.dataType = { Tail: 0x30, Compressed: 0x40, NormalExt: 0x50, Normal: 0x60, Mark: 0x70 }; TextCompressor.chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; TextCompressor.scale = TextCompressor.chars.length; TextCompressor.max = 238327; return TextCompressor; })(); RongIMLib.TextCompressor = TextCompressor; })(RongIMLib || (RongIMLib = {})); // {WebEnd} WebSDK 内容开始的标识, 方便小程序 SDK 定位 /* 说明: 请勿修改 header.js 和 footer.js 用途: 自动拼接暴露方式 命令: grunt release 中 concat */ return RongIMLib; }); ================================================ FILE: api-test-v2/lib/js/es6-promise.js ================================================ !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):t.ES6Promise=e()}(this,function(){"use strict";function t(t){var e=typeof t;return null!==t&&("object"===e||"function"===e)}function e(t){return"function"==typeof t}function n(t){W=t}function r(t){z=t}function o(){return function(){return process.nextTick(a)}}function i(){return"undefined"!=typeof U?function(){U(a)}:c()}function s(){var t=0,e=new H(a),n=document.createTextNode("");return e.observe(n,{characterData:!0}),function(){n.data=t=++t%2}}function u(){var t=new MessageChannel;return t.port1.onmessage=a,function(){return t.port2.postMessage(0)}}function c(){var t=setTimeout;return function(){return t(a,1)}}function a(){for(var t=0;t=0&&Math.floor(t)===t&&isFinite(e)}function u(e){return n(e)&&"function"==typeof e.then&&"function"==typeof e.catch}function l(e){return null==e?"":Array.isArray(e)||s(e)&&e.toString===a?JSON.stringify(e,null,2):String(e)}function f(e){var t=parseFloat(e);return isNaN(t)?e:t}function p(e,t){for(var n=Object.create(null),r=e.split(","),i=0;i-1)return e.splice(n,1)}}var m=Object.prototype.hasOwnProperty;function y(e,t){return m.call(e,t)}function g(e){var t=Object.create(null);return function(n){return t[n]||(t[n]=e(n))}}var _=/-(\w)/g,b=g(function(e){return e.replace(_,function(e,t){return t?t.toUpperCase():""})}),$=g(function(e){return e.charAt(0).toUpperCase()+e.slice(1)}),w=/\B([A-Z])/g,C=g(function(e){return e.replace(w,"-$1").toLowerCase()});var x=Function.prototype.bind?function(e,t){return e.bind(t)}:function(e,t){function n(n){var r=arguments.length;return r?r>1?e.apply(t,arguments):e.call(t,n):e.call(t)}return n._length=e.length,n};function k(e,t){t=t||0;for(var n=e.length-t,r=new Array(n);n--;)r[n]=e[n+t];return r}function A(e,t){for(var n in t)e[n]=t[n];return e}function O(e){for(var t={},n=0;n0,Z=J&&J.indexOf("edge/")>0,G=(J&&J.indexOf("android"),J&&/iphone|ipad|ipod|ios/.test(J)||"ios"===K),X=(J&&/chrome\/\d+/.test(J),J&&/phantomjs/.test(J),J&&J.match(/firefox\/(\d+)/)),Y={}.watch,Q=!1;if(z)try{var ee={};Object.defineProperty(ee,"passive",{get:function(){Q=!0}}),window.addEventListener("test-passive",null,ee)}catch(e){}var te=function(){return void 0===B&&(B=!z&&!V&&"undefined"!=typeof global&&(global.process&&"server"===global.process.env.VUE_ENV)),B},ne=z&&window.__VUE_DEVTOOLS_GLOBAL_HOOK__;function re(e){return"function"==typeof e&&/native code/.test(e.toString())}var ie,oe="undefined"!=typeof Symbol&&re(Symbol)&&"undefined"!=typeof Reflect&&re(Reflect.ownKeys);ie="undefined"!=typeof Set&&re(Set)?Set:function(){function e(){this.set=Object.create(null)}return e.prototype.has=function(e){return!0===this.set[e]},e.prototype.add=function(e){this.set[e]=!0},e.prototype.clear=function(){this.set=Object.create(null)},e}();var ae=S,se=0,ce=function(){this.id=se++,this.subs=[]};ce.prototype.addSub=function(e){this.subs.push(e)},ce.prototype.removeSub=function(e){h(this.subs,e)},ce.prototype.depend=function(){ce.target&&ce.target.addDep(this)},ce.prototype.notify=function(){for(var e=this.subs.slice(),t=0,n=e.length;t-1)if(o&&!y(i,"default"))a=!1;else if(""===a||a===C(e)){var c=Pe(String,i.type);(c<0||s0&&(st((u=e(u,(a||"")+"_"+c))[0])&&st(f)&&(s[l]=he(f.text+u[0].text),u.shift()),s.push.apply(s,u)):i(u)?st(f)?s[l]=he(f.text+u):""!==u&&s.push(he(u)):st(u)&&st(f)?s[l]=he(f.text+u.text):(r(o._isVList)&&n(u.tag)&&t(u.key)&&n(a)&&(u.key="__vlist"+a+"_"+c+"__"),s.push(u)));return s}(e):void 0}function st(e){return n(e)&&n(e.text)&&!1===e.isComment}function ct(e,t){if(e){for(var n=Object.create(null),r=oe?Reflect.ownKeys(e):Object.keys(e),i=0;i0,a=t?!!t.$stable:!o,s=t&&t.$key;if(t){if(t._normalized)return t._normalized;if(a&&r&&r!==e&&s===r.$key&&!o&&!r.$hasNormal)return r;for(var c in i={},t)t[c]&&"$"!==c[0]&&(i[c]=pt(n,c,t[c]))}else i={};for(var u in n)u in i||(i[u]=dt(n,u));return t&&Object.isExtensible(t)&&(t._normalized=i),R(i,"$stable",a),R(i,"$key",s),R(i,"$hasNormal",o),i}function pt(e,t,n){var r=function(){var e=arguments.length?n.apply(null,arguments):n({});return(e=e&&"object"==typeof e&&!Array.isArray(e)?[e]:at(e))&&(0===e.length||1===e.length&&e[0].isComment)?void 0:e};return n.proxy&&Object.defineProperty(e,t,{get:r,enumerable:!0,configurable:!0}),r}function dt(e,t){return function(){return e[t]}}function vt(e,t){var r,i,a,s,c;if(Array.isArray(e)||"string"==typeof e)for(r=new Array(e.length),i=0,a=e.length;idocument.createEvent("Event").timeStamp&&(sn=function(){return cn.now()})}function un(){var e,t;for(an=sn(),rn=!0,Qt.sort(function(e,t){return e.id-t.id}),on=0;onon&&Qt[n].id>e.id;)n--;Qt.splice(n+1,0,e)}else Qt.push(e);nn||(nn=!0,Ye(un))}}(this)},fn.prototype.run=function(){if(this.active){var e=this.get();if(e!==this.value||o(e)||this.deep){var t=this.value;if(this.value=e,this.user)try{this.cb.call(this.vm,e,t)}catch(e){Re(e,this.vm,'callback for watcher "'+this.expression+'"')}else this.cb.call(this.vm,e,t)}}},fn.prototype.evaluate=function(){this.value=this.get(),this.dirty=!1},fn.prototype.depend=function(){for(var e=this.deps.length;e--;)this.deps[e].depend()},fn.prototype.teardown=function(){if(this.active){this.vm._isBeingDestroyed||h(this.vm._watchers,this);for(var e=this.deps.length;e--;)this.deps[e].removeSub(this);this.active=!1}};var pn={enumerable:!0,configurable:!0,get:S,set:S};function dn(e,t,n){pn.get=function(){return this[t][n]},pn.set=function(e){this[t][n]=e},Object.defineProperty(e,n,pn)}function vn(e){e._watchers=[];var t=e.$options;t.props&&function(e,t){var n=e.$options.propsData||{},r=e._props={},i=e.$options._propKeys=[];e.$parent&&$e(!1);var o=function(o){i.push(o);var a=Me(o,t,n,e);xe(r,o,a),o in e||dn(e,"_props",o)};for(var a in t)o(a);$e(!0)}(e,t.props),t.methods&&function(e,t){e.$options.props;for(var n in t)e[n]="function"!=typeof t[n]?S:x(t[n],e)}(e,t.methods),t.data?function(e){var t=e.$options.data;s(t=e._data="function"==typeof t?function(e,t){le();try{return e.call(t,t)}catch(e){return Re(e,t,"data()"),{}}finally{fe()}}(t,e):t||{})||(t={});var n=Object.keys(t),r=e.$options.props,i=(e.$options.methods,n.length);for(;i--;){var o=n[i];r&&y(r,o)||(a=void 0,36!==(a=(o+"").charCodeAt(0))&&95!==a&&dn(e,"_data",o))}var a;Ce(t,!0)}(e):Ce(e._data={},!0),t.computed&&function(e,t){var n=e._computedWatchers=Object.create(null),r=te();for(var i in t){var o=t[i],a="function"==typeof o?o:o.get;r||(n[i]=new fn(e,a||S,S,hn)),i in e||mn(e,i,o)}}(e,t.computed),t.watch&&t.watch!==Y&&function(e,t){for(var n in t){var r=t[n];if(Array.isArray(r))for(var i=0;i-1:"string"==typeof e?e.split(",").indexOf(t)>-1:(n=e,"[object RegExp]"===a.call(n)&&e.test(t));var n}function An(e,t){var n=e.cache,r=e.keys,i=e._vnode;for(var o in n){var a=n[o];if(a){var s=xn(a.componentOptions);s&&!t(s)&&On(n,o,r,i)}}}function On(e,t,n,r){var i=e[t];!i||r&&i.tag===r.tag||i.componentInstance.$destroy(),e[t]=null,h(n,t)}!function(t){t.prototype._init=function(t){var n=this;n._uid=bn++,n._isVue=!0,t&&t._isComponent?function(e,t){var n=e.$options=Object.create(e.constructor.options),r=t._parentVnode;n.parent=t.parent,n._parentVnode=r;var i=r.componentOptions;n.propsData=i.propsData,n._parentListeners=i.listeners,n._renderChildren=i.children,n._componentTag=i.tag,t.render&&(n.render=t.render,n.staticRenderFns=t.staticRenderFns)}(n,t):n.$options=De($n(n.constructor),t||{},n),n._renderProxy=n,n._self=n,function(e){var t=e.$options,n=t.parent;if(n&&!t.abstract){for(;n.$options.abstract&&n.$parent;)n=n.$parent;n.$children.push(e)}e.$parent=n,e.$root=n?n.$root:e,e.$children=[],e.$refs={},e._watcher=null,e._inactive=null,e._directInactive=!1,e._isMounted=!1,e._isDestroyed=!1,e._isBeingDestroyed=!1}(n),function(e){e._events=Object.create(null),e._hasHookEvent=!1;var t=e.$options._parentListeners;t&&qt(e,t)}(n),function(t){t._vnode=null,t._staticTrees=null;var n=t.$options,r=t.$vnode=n._parentVnode,i=r&&r.context;t.$slots=ut(n._renderChildren,i),t.$scopedSlots=e,t._c=function(e,n,r,i){return Pt(t,e,n,r,i,!1)},t.$createElement=function(e,n,r,i){return Pt(t,e,n,r,i,!0)};var o=r&&r.data;xe(t,"$attrs",o&&o.attrs||e,null,!0),xe(t,"$listeners",n._parentListeners||e,null,!0)}(n),Yt(n,"beforeCreate"),function(e){var t=ct(e.$options.inject,e);t&&($e(!1),Object.keys(t).forEach(function(n){xe(e,n,t[n])}),$e(!0))}(n),vn(n),function(e){var t=e.$options.provide;t&&(e._provided="function"==typeof t?t.call(e):t)}(n),Yt(n,"created"),n.$options.el&&n.$mount(n.$options.el)}}(wn),function(e){var t={get:function(){return this._data}},n={get:function(){return this._props}};Object.defineProperty(e.prototype,"$data",t),Object.defineProperty(e.prototype,"$props",n),e.prototype.$set=ke,e.prototype.$delete=Ae,e.prototype.$watch=function(e,t,n){if(s(t))return _n(this,e,t,n);(n=n||{}).user=!0;var r=new fn(this,e,t,n);if(n.immediate)try{t.call(this,r.value)}catch(e){Re(e,this,'callback for immediate watcher "'+r.expression+'"')}return function(){r.teardown()}}}(wn),function(e){var t=/^hook:/;e.prototype.$on=function(e,n){var r=this;if(Array.isArray(e))for(var i=0,o=e.length;i1?k(t):t;for(var n=k(arguments,1),r='event handler for "'+e+'"',i=0,o=t.length;iparseInt(this.max)&&On(a,s[0],s,this._vnode)),t.data.keepAlive=!0}return t||e&&e[0]}}};!function(e){var t={get:function(){return F}};Object.defineProperty(e,"config",t),e.util={warn:ae,extend:A,mergeOptions:De,defineReactive:xe},e.set=ke,e.delete=Ae,e.nextTick=Ye,e.observable=function(e){return Ce(e),e},e.options=Object.create(null),M.forEach(function(t){e.options[t+"s"]=Object.create(null)}),e.options._base=e,A(e.options.components,Tn),function(e){e.use=function(e){var t=this._installedPlugins||(this._installedPlugins=[]);if(t.indexOf(e)>-1)return this;var n=k(arguments,1);return n.unshift(this),"function"==typeof e.install?e.install.apply(e,n):"function"==typeof e&&e.apply(null,n),t.push(e),this}}(e),function(e){e.mixin=function(e){return this.options=De(this.options,e),this}}(e),Cn(e),function(e){M.forEach(function(t){e[t]=function(e,n){return n?("component"===t&&s(n)&&(n.name=n.name||e,n=this.options._base.extend(n)),"directive"===t&&"function"==typeof n&&(n={bind:n,update:n}),this.options[t+"s"][e]=n,n):this.options[t+"s"][e]}})}(e)}(wn),Object.defineProperty(wn.prototype,"$isServer",{get:te}),Object.defineProperty(wn.prototype,"$ssrContext",{get:function(){return this.$vnode&&this.$vnode.ssrContext}}),Object.defineProperty(wn,"FunctionalRenderContext",{value:Tt}),wn.version="2.6.11";var En=p("style,class"),Nn=p("input,textarea,option,select,progress"),jn=function(e,t,n){return"value"===n&&Nn(e)&&"button"!==t||"selected"===n&&"option"===e||"checked"===n&&"input"===e||"muted"===n&&"video"===e},Dn=p("contenteditable,draggable,spellcheck"),Ln=p("events,caret,typing,plaintext-only"),Mn=function(e,t){return Hn(t)||"false"===t?"false":"contenteditable"===e&&Ln(t)?t:"true"},In=p("allowfullscreen,async,autofocus,autoplay,checked,compact,controls,declare,default,defaultchecked,defaultmuted,defaultselected,defer,disabled,enabled,formnovalidate,hidden,indeterminate,inert,ismap,itemscope,loop,multiple,muted,nohref,noresize,noshade,novalidate,nowrap,open,pauseonexit,readonly,required,reversed,scoped,seamless,selected,sortable,translate,truespeed,typemustmatch,visible"),Fn="http://www.w3.org/1999/xlink",Pn=function(e){return":"===e.charAt(5)&&"xlink"===e.slice(0,5)},Rn=function(e){return Pn(e)?e.slice(6,e.length):""},Hn=function(e){return null==e||!1===e};function Bn(e){for(var t=e.data,r=e,i=e;n(i.componentInstance);)(i=i.componentInstance._vnode)&&i.data&&(t=Un(i.data,t));for(;n(r=r.parent);)r&&r.data&&(t=Un(t,r.data));return function(e,t){if(n(e)||n(t))return zn(e,Vn(t));return""}(t.staticClass,t.class)}function Un(e,t){return{staticClass:zn(e.staticClass,t.staticClass),class:n(e.class)?[e.class,t.class]:t.class}}function zn(e,t){return e?t?e+" "+t:e:t||""}function Vn(e){return Array.isArray(e)?function(e){for(var t,r="",i=0,o=e.length;i-1?hr(e,t,n):In(t)?Hn(n)?e.removeAttribute(t):(n="allowfullscreen"===t&&"EMBED"===e.tagName?"true":t,e.setAttribute(t,n)):Dn(t)?e.setAttribute(t,Mn(t,n)):Pn(t)?Hn(n)?e.removeAttributeNS(Fn,Rn(t)):e.setAttributeNS(Fn,t,n):hr(e,t,n)}function hr(e,t,n){if(Hn(n))e.removeAttribute(t);else{if(q&&!W&&"TEXTAREA"===e.tagName&&"placeholder"===t&&""!==n&&!e.__ieph){var r=function(t){t.stopImmediatePropagation(),e.removeEventListener("input",r)};e.addEventListener("input",r),e.__ieph=!0}e.setAttribute(t,n)}}var mr={create:dr,update:dr};function yr(e,r){var i=r.elm,o=r.data,a=e.data;if(!(t(o.staticClass)&&t(o.class)&&(t(a)||t(a.staticClass)&&t(a.class)))){var s=Bn(r),c=i._transitionClasses;n(c)&&(s=zn(s,Vn(c))),s!==i._prevClass&&(i.setAttribute("class",s),i._prevClass=s)}}var gr,_r,br,$r,wr,Cr,xr={create:yr,update:yr},kr=/[\w).+\-_$\]]/;function Ar(e){var t,n,r,i,o,a=!1,s=!1,c=!1,u=!1,l=0,f=0,p=0,d=0;for(r=0;r=0&&" "===(h=e.charAt(v));v--);h&&kr.test(h)||(u=!0)}}else void 0===i?(d=r+1,i=e.slice(0,r).trim()):m();function m(){(o||(o=[])).push(e.slice(d,r).trim()),d=r+1}if(void 0===i?i=e.slice(0,r).trim():0!==d&&m(),o)for(r=0;r-1?{exp:e.slice(0,$r),key:'"'+e.slice($r+1)+'"'}:{exp:e,key:null};_r=e,$r=wr=Cr=0;for(;!zr();)Vr(br=Ur())?Jr(br):91===br&&Kr(br);return{exp:e.slice(0,wr),key:e.slice(wr+1,Cr)}}(e);return null===n.key?e+"="+t:"$set("+n.exp+", "+n.key+", "+t+")"}function Ur(){return _r.charCodeAt(++$r)}function zr(){return $r>=gr}function Vr(e){return 34===e||39===e}function Kr(e){var t=1;for(wr=$r;!zr();)if(Vr(e=Ur()))Jr(e);else if(91===e&&t++,93===e&&t--,0===t){Cr=$r;break}}function Jr(e){for(var t=e;!zr()&&(e=Ur())!==t;);}var qr,Wr="__r",Zr="__c";function Gr(e,t,n){var r=qr;return function i(){null!==t.apply(null,arguments)&&Qr(e,i,n,r)}}var Xr=Ve&&!(X&&Number(X[1])<=53);function Yr(e,t,n,r){if(Xr){var i=an,o=t;t=o._wrapper=function(e){if(e.target===e.currentTarget||e.timeStamp>=i||e.timeStamp<=0||e.target.ownerDocument!==document)return o.apply(this,arguments)}}qr.addEventListener(e,t,Q?{capture:n,passive:r}:n)}function Qr(e,t,n,r){(r||qr).removeEventListener(e,t._wrapper||t,n)}function ei(e,r){if(!t(e.data.on)||!t(r.data.on)){var i=r.data.on||{},o=e.data.on||{};qr=r.elm,function(e){if(n(e[Wr])){var t=q?"change":"input";e[t]=[].concat(e[Wr],e[t]||[]),delete e[Wr]}n(e[Zr])&&(e.change=[].concat(e[Zr],e.change||[]),delete e[Zr])}(i),rt(i,o,Yr,Qr,Gr,r.context),qr=void 0}}var ti,ni={create:ei,update:ei};function ri(e,r){if(!t(e.data.domProps)||!t(r.data.domProps)){var i,o,a=r.elm,s=e.data.domProps||{},c=r.data.domProps||{};for(i in n(c.__ob__)&&(c=r.data.domProps=A({},c)),s)i in c||(a[i]="");for(i in c){if(o=c[i],"textContent"===i||"innerHTML"===i){if(r.children&&(r.children.length=0),o===s[i])continue;1===a.childNodes.length&&a.removeChild(a.childNodes[0])}if("value"===i&&"PROGRESS"!==a.tagName){a._value=o;var u=t(o)?"":String(o);ii(a,u)&&(a.value=u)}else if("innerHTML"===i&&qn(a.tagName)&&t(a.innerHTML)){(ti=ti||document.createElement("div")).innerHTML=""+o+"";for(var l=ti.firstChild;a.firstChild;)a.removeChild(a.firstChild);for(;l.firstChild;)a.appendChild(l.firstChild)}else if(o!==s[i])try{a[i]=o}catch(e){}}}}function ii(e,t){return!e.composing&&("OPTION"===e.tagName||function(e,t){var n=!0;try{n=document.activeElement!==e}catch(e){}return n&&e.value!==t}(e,t)||function(e,t){var r=e.value,i=e._vModifiers;if(n(i)){if(i.number)return f(r)!==f(t);if(i.trim)return r.trim()!==t.trim()}return r!==t}(e,t))}var oi={create:ri,update:ri},ai=g(function(e){var t={},n=/:(.+)/;return e.split(/;(?![^(]*\))/g).forEach(function(e){if(e){var r=e.split(n);r.length>1&&(t[r[0].trim()]=r[1].trim())}}),t});function si(e){var t=ci(e.style);return e.staticStyle?A(e.staticStyle,t):t}function ci(e){return Array.isArray(e)?O(e):"string"==typeof e?ai(e):e}var ui,li=/^--/,fi=/\s*!important$/,pi=function(e,t,n){if(li.test(t))e.style.setProperty(t,n);else if(fi.test(n))e.style.setProperty(C(t),n.replace(fi,""),"important");else{var r=vi(t);if(Array.isArray(n))for(var i=0,o=n.length;i-1?t.split(yi).forEach(function(t){return e.classList.add(t)}):e.classList.add(t);else{var n=" "+(e.getAttribute("class")||"")+" ";n.indexOf(" "+t+" ")<0&&e.setAttribute("class",(n+t).trim())}}function _i(e,t){if(t&&(t=t.trim()))if(e.classList)t.indexOf(" ")>-1?t.split(yi).forEach(function(t){return e.classList.remove(t)}):e.classList.remove(t),e.classList.length||e.removeAttribute("class");else{for(var n=" "+(e.getAttribute("class")||"")+" ",r=" "+t+" ";n.indexOf(r)>=0;)n=n.replace(r," ");(n=n.trim())?e.setAttribute("class",n):e.removeAttribute("class")}}function bi(e){if(e){if("object"==typeof e){var t={};return!1!==e.css&&A(t,$i(e.name||"v")),A(t,e),t}return"string"==typeof e?$i(e):void 0}}var $i=g(function(e){return{enterClass:e+"-enter",enterToClass:e+"-enter-to",enterActiveClass:e+"-enter-active",leaveClass:e+"-leave",leaveToClass:e+"-leave-to",leaveActiveClass:e+"-leave-active"}}),wi=z&&!W,Ci="transition",xi="animation",ki="transition",Ai="transitionend",Oi="animation",Si="animationend";wi&&(void 0===window.ontransitionend&&void 0!==window.onwebkittransitionend&&(ki="WebkitTransition",Ai="webkitTransitionEnd"),void 0===window.onanimationend&&void 0!==window.onwebkitanimationend&&(Oi="WebkitAnimation",Si="webkitAnimationEnd"));var Ti=z?window.requestAnimationFrame?window.requestAnimationFrame.bind(window):setTimeout:function(e){return e()};function Ei(e){Ti(function(){Ti(e)})}function Ni(e,t){var n=e._transitionClasses||(e._transitionClasses=[]);n.indexOf(t)<0&&(n.push(t),gi(e,t))}function ji(e,t){e._transitionClasses&&h(e._transitionClasses,t),_i(e,t)}function Di(e,t,n){var r=Mi(e,t),i=r.type,o=r.timeout,a=r.propCount;if(!i)return n();var s=i===Ci?Ai:Si,c=0,u=function(){e.removeEventListener(s,l),n()},l=function(t){t.target===e&&++c>=a&&u()};setTimeout(function(){c0&&(n=Ci,l=a,f=o.length):t===xi?u>0&&(n=xi,l=u,f=c.length):f=(n=(l=Math.max(a,u))>0?a>u?Ci:xi:null)?n===Ci?o.length:c.length:0,{type:n,timeout:l,propCount:f,hasTransform:n===Ci&&Li.test(r[ki+"Property"])}}function Ii(e,t){for(;e.length1}function Ui(e,t){!0!==t.data.show&&Pi(t)}var zi=function(e){var o,a,s={},c=e.modules,u=e.nodeOps;for(o=0;ov?_(e,t(i[y+1])?null:i[y+1].elm,i,d,y,o):d>y&&$(r,p,v)}(p,h,y,o,l):n(y)?(n(e.text)&&u.setTextContent(p,""),_(p,null,y,0,y.length-1,o)):n(h)?$(h,0,h.length-1):n(e.text)&&u.setTextContent(p,""):e.text!==i.text&&u.setTextContent(p,i.text),n(v)&&n(d=v.hook)&&n(d=d.postpatch)&&d(e,i)}}}function k(e,t,i){if(r(i)&&n(e.parent))e.parent.data.pendingInsert=t;else for(var o=0;o-1,a.selected!==o&&(a.selected=o);else if(N(Wi(a),r))return void(e.selectedIndex!==s&&(e.selectedIndex=s));i||(e.selectedIndex=-1)}}function qi(e,t){return t.every(function(t){return!N(t,e)})}function Wi(e){return"_value"in e?e._value:e.value}function Zi(e){e.target.composing=!0}function Gi(e){e.target.composing&&(e.target.composing=!1,Xi(e.target,"input"))}function Xi(e,t){var n=document.createEvent("HTMLEvents");n.initEvent(t,!0,!0),e.dispatchEvent(n)}function Yi(e){return!e.componentInstance||e.data&&e.data.transition?e:Yi(e.componentInstance._vnode)}var Qi={model:Vi,show:{bind:function(e,t,n){var r=t.value,i=(n=Yi(n)).data&&n.data.transition,o=e.__vOriginalDisplay="none"===e.style.display?"":e.style.display;r&&i?(n.data.show=!0,Pi(n,function(){e.style.display=o})):e.style.display=r?o:"none"},update:function(e,t,n){var r=t.value;!r!=!t.oldValue&&((n=Yi(n)).data&&n.data.transition?(n.data.show=!0,r?Pi(n,function(){e.style.display=e.__vOriginalDisplay}):Ri(n,function(){e.style.display="none"})):e.style.display=r?e.__vOriginalDisplay:"none")},unbind:function(e,t,n,r,i){i||(e.style.display=e.__vOriginalDisplay)}}},eo={name:String,appear:Boolean,css:Boolean,mode:String,type:String,enterClass:String,leaveClass:String,enterToClass:String,leaveToClass:String,enterActiveClass:String,leaveActiveClass:String,appearClass:String,appearActiveClass:String,appearToClass:String,duration:[Number,String,Object]};function to(e){var t=e&&e.componentOptions;return t&&t.Ctor.options.abstract?to(zt(t.children)):e}function no(e){var t={},n=e.$options;for(var r in n.propsData)t[r]=e[r];var i=n._parentListeners;for(var o in i)t[b(o)]=i[o];return t}function ro(e,t){if(/\d-keep-alive$/.test(t.tag))return e("keep-alive",{props:t.componentOptions.propsData})}var io=function(e){return e.tag||Ut(e)},oo=function(e){return"show"===e.name},ao={name:"transition",props:eo,abstract:!0,render:function(e){var t=this,n=this.$slots.default;if(n&&(n=n.filter(io)).length){var r=this.mode,o=n[0];if(function(e){for(;e=e.parent;)if(e.data.transition)return!0}(this.$vnode))return o;var a=to(o);if(!a)return o;if(this._leaving)return ro(e,o);var s="__transition-"+this._uid+"-";a.key=null==a.key?a.isComment?s+"comment":s+a.tag:i(a.key)?0===String(a.key).indexOf(s)?a.key:s+a.key:a.key;var c=(a.data||(a.data={})).transition=no(this),u=this._vnode,l=to(u);if(a.data.directives&&a.data.directives.some(oo)&&(a.data.show=!0),l&&l.data&&!function(e,t){return t.key===e.key&&t.tag===e.tag}(a,l)&&!Ut(l)&&(!l.componentInstance||!l.componentInstance._vnode.isComment)){var f=l.data.transition=A({},c);if("out-in"===r)return this._leaving=!0,it(f,"afterLeave",function(){t._leaving=!1,t.$forceUpdate()}),ro(e,o);if("in-out"===r){if(Ut(a))return u;var p,d=function(){p()};it(c,"afterEnter",d),it(c,"enterCancelled",d),it(f,"delayLeave",function(e){p=e})}}return o}}},so=A({tag:String,moveClass:String},eo);function co(e){e.elm._moveCb&&e.elm._moveCb(),e.elm._enterCb&&e.elm._enterCb()}function uo(e){e.data.newPos=e.elm.getBoundingClientRect()}function lo(e){var t=e.data.pos,n=e.data.newPos,r=t.left-n.left,i=t.top-n.top;if(r||i){e.data.moved=!0;var o=e.elm.style;o.transform=o.WebkitTransform="translate("+r+"px,"+i+"px)",o.transitionDuration="0s"}}delete so.mode;var fo={Transition:ao,TransitionGroup:{props:so,beforeMount:function(){var e=this,t=this._update;this._update=function(n,r){var i=Zt(e);e.__patch__(e._vnode,e.kept,!1,!0),e._vnode=e.kept,i(),t.call(e,n,r)}},render:function(e){for(var t=this.tag||this.$vnode.data.tag||"span",n=Object.create(null),r=this.prevChildren=this.children,i=this.$slots.default||[],o=this.children=[],a=no(this),s=0;s-1?Gn[e]=t.constructor===window.HTMLUnknownElement||t.constructor===window.HTMLElement:Gn[e]=/HTMLUnknownElement/.test(t.toString())},A(wn.options.directives,Qi),A(wn.options.components,fo),wn.prototype.__patch__=z?zi:S,wn.prototype.$mount=function(e,t){return function(e,t,n){var r;return e.$el=t,e.$options.render||(e.$options.render=ve),Yt(e,"beforeMount"),r=function(){e._update(e._render(),n)},new fn(e,r,S,{before:function(){e._isMounted&&!e._isDestroyed&&Yt(e,"beforeUpdate")}},!0),n=!1,null==e.$vnode&&(e._isMounted=!0,Yt(e,"mounted")),e}(this,e=e&&z?Yn(e):void 0,t)},z&&setTimeout(function(){F.devtools&&ne&&ne.emit("init",wn)},0);var po=/\{\{((?:.|\r?\n)+?)\}\}/g,vo=/[-.*+?^${}()|[\]\/\\]/g,ho=g(function(e){var t=e[0].replace(vo,"\\$&"),n=e[1].replace(vo,"\\$&");return new RegExp(t+"((?:.|\\n)+?)"+n,"g")});var mo={staticKeys:["staticClass"],transformNode:function(e,t){t.warn;var n=Fr(e,"class");n&&(e.staticClass=JSON.stringify(n));var r=Ir(e,"class",!1);r&&(e.classBinding=r)},genData:function(e){var t="";return e.staticClass&&(t+="staticClass:"+e.staticClass+","),e.classBinding&&(t+="class:"+e.classBinding+","),t}};var yo,go={staticKeys:["staticStyle"],transformNode:function(e,t){t.warn;var n=Fr(e,"style");n&&(e.staticStyle=JSON.stringify(ai(n)));var r=Ir(e,"style",!1);r&&(e.styleBinding=r)},genData:function(e){var t="";return e.staticStyle&&(t+="staticStyle:"+e.staticStyle+","),e.styleBinding&&(t+="style:("+e.styleBinding+"),"),t}},_o=function(e){return(yo=yo||document.createElement("div")).innerHTML=e,yo.textContent},bo=p("area,base,br,col,embed,frame,hr,img,input,isindex,keygen,link,meta,param,source,track,wbr"),$o=p("colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr,source"),wo=p("address,article,aside,base,blockquote,body,caption,col,colgroup,dd,details,dialog,div,dl,dt,fieldset,figcaption,figure,footer,form,h1,h2,h3,h4,h5,h6,head,header,hgroup,hr,html,legend,li,menuitem,meta,optgroup,option,param,rp,rt,source,style,summary,tbody,td,tfoot,th,thead,title,tr,track"),Co=/^\s*([^\s"'<>\/=]+)(?:\s*(=)\s*(?:"([^"]*)"+|'([^']*)'+|([^\s"'=<>`]+)))?/,xo=/^\s*((?:v-[\w-]+:|@|:|#)\[[^=]+\][^\s"'<>\/=]*)(?:\s*(=)\s*(?:"([^"]*)"+|'([^']*)'+|([^\s"'=<>`]+)))?/,ko="[a-zA-Z_][\\-\\.0-9_a-zA-Z"+P.source+"]*",Ao="((?:"+ko+"\\:)?"+ko+")",Oo=new RegExp("^<"+Ao),So=/^\s*(\/?)>/,To=new RegExp("^<\\/"+Ao+"[^>]*>"),Eo=/^]+>/i,No=/^",""":'"',"&":"&"," ":"\n"," ":"\t","'":"'"},Io=/&(?:lt|gt|quot|amp|#39);/g,Fo=/&(?:lt|gt|quot|amp|#39|#10|#9);/g,Po=p("pre,textarea",!0),Ro=function(e,t){return e&&Po(e)&&"\n"===t[0]};function Ho(e,t){var n=t?Fo:Io;return e.replace(n,function(e){return Mo[e]})}var Bo,Uo,zo,Vo,Ko,Jo,qo,Wo,Zo=/^@|^v-on:/,Go=/^v-|^@|^:|^#/,Xo=/([\s\S]*?)\s+(?:in|of)\s+([\s\S]*)/,Yo=/,([^,\}\]]*)(?:,([^,\}\]]*))?$/,Qo=/^\(|\)$/g,ea=/^\[.*\]$/,ta=/:(.*)$/,na=/^:|^\.|^v-bind:/,ra=/\.[^.\]]+(?=[^\]]*$)/g,ia=/^v-slot(:|$)|^#/,oa=/[\r\n]/,aa=/\s+/g,sa=g(_o),ca="_empty_";function ua(e,t,n){return{type:1,tag:e,attrsList:t,attrsMap:ma(t),rawAttrsMap:{},parent:n,children:[]}}function la(e,t){Bo=t.warn||Sr,Jo=t.isPreTag||T,qo=t.mustUseProp||T,Wo=t.getTagNamespace||T;t.isReservedTag;zo=Tr(t.modules,"transformNode"),Vo=Tr(t.modules,"preTransformNode"),Ko=Tr(t.modules,"postTransformNode"),Uo=t.delimiters;var n,r,i=[],o=!1!==t.preserveWhitespace,a=t.whitespace,s=!1,c=!1;function u(e){if(l(e),s||e.processed||(e=fa(e,t)),i.length||e===n||n.if&&(e.elseif||e.else)&&da(n,{exp:e.elseif,block:e}),r&&!e.forbidden)if(e.elseif||e.else)a=e,(u=function(e){var t=e.length;for(;t--;){if(1===e[t].type)return e[t];e.pop()}}(r.children))&&u.if&&da(u,{exp:a.elseif,block:a});else{if(e.slotScope){var o=e.slotTarget||'"default"';(r.scopedSlots||(r.scopedSlots={}))[o]=e}r.children.push(e),e.parent=r}var a,u;e.children=e.children.filter(function(e){return!e.slotScope}),l(e),e.pre&&(s=!1),Jo(e.tag)&&(c=!1);for(var f=0;f]*>)","i")),p=e.replace(f,function(e,n,r){return u=r.length,Do(l)||"noscript"===l||(n=n.replace(//g,"$1").replace(//g,"$1")),Ro(l,n)&&(n=n.slice(1)),t.chars&&t.chars(n),""});c+=e.length-p.length,e=p,A(l,c-u,c)}else{var d=e.indexOf("<");if(0===d){if(No.test(e)){var v=e.indexOf("--\x3e");if(v>=0){t.shouldKeepComment&&t.comment(e.substring(4,v),c,c+v+3),C(v+3);continue}}if(jo.test(e)){var h=e.indexOf("]>");if(h>=0){C(h+2);continue}}var m=e.match(Eo);if(m){C(m[0].length);continue}var y=e.match(To);if(y){var g=c;C(y[0].length),A(y[1],g,c);continue}var _=x();if(_){k(_),Ro(_.tagName,e)&&C(1);continue}}var b=void 0,$=void 0,w=void 0;if(d>=0){for($=e.slice(d);!(To.test($)||Oo.test($)||No.test($)||jo.test($)||(w=$.indexOf("<",1))<0);)d+=w,$=e.slice(d);b=e.substring(0,d)}d<0&&(b=e),b&&C(b.length),t.chars&&b&&t.chars(b,c-b.length,c)}if(e===n){t.chars&&t.chars(e);break}}function C(t){c+=t,e=e.substring(t)}function x(){var t=e.match(Oo);if(t){var n,r,i={tagName:t[1],attrs:[],start:c};for(C(t[0].length);!(n=e.match(So))&&(r=e.match(xo)||e.match(Co));)r.start=c,C(r[0].length),r.end=c,i.attrs.push(r);if(n)return i.unarySlash=n[1],C(n[0].length),i.end=c,i}}function k(e){var n=e.tagName,c=e.unarySlash;o&&("p"===r&&wo(n)&&A(r),s(n)&&r===n&&A(n));for(var u=a(n)||!!c,l=e.attrs.length,f=new Array(l),p=0;p=0&&i[a].lowerCasedTag!==s;a--);else a=0;if(a>=0){for(var u=i.length-1;u>=a;u--)t.end&&t.end(i[u].tag,n,o);i.length=a,r=a&&i[a-1].tag}else"br"===s?t.start&&t.start(e,[],!0,n,o):"p"===s&&(t.start&&t.start(e,[],!1,n,o),t.end&&t.end(e,n,o))}A()}(e,{warn:Bo,expectHTML:t.expectHTML,isUnaryTag:t.isUnaryTag,canBeLeftOpenTag:t.canBeLeftOpenTag,shouldDecodeNewlines:t.shouldDecodeNewlines,shouldDecodeNewlinesForHref:t.shouldDecodeNewlinesForHref,shouldKeepComment:t.comments,outputSourceRange:t.outputSourceRange,start:function(e,o,a,l,f){var p=r&&r.ns||Wo(e);q&&"svg"===p&&(o=function(e){for(var t=[],n=0;nc&&(s.push(o=e.slice(c,i)),a.push(JSON.stringify(o)));var u=Ar(r[1].trim());a.push("_s("+u+")"),s.push({"@binding":u}),c=i+r[0].length}return c-1"+("true"===o?":("+t+")":":_q("+t+","+o+")")),Mr(e,"change","var $$a="+t+",$$el=$event.target,$$c=$$el.checked?("+o+"):("+a+");if(Array.isArray($$a)){var $$v="+(r?"_n("+i+")":i)+",$$i=_i($$a,$$v);if($$el.checked){$$i<0&&("+Br(t,"$$a.concat([$$v])")+")}else{$$i>-1&&("+Br(t,"$$a.slice(0,$$i).concat($$a.slice($$i+1))")+")}}else{"+Br(t,"$$c")+"}",null,!0)}(e,r,i);else if("input"===o&&"radio"===a)!function(e,t,n){var r=n&&n.number,i=Ir(e,"value")||"null";Er(e,"checked","_q("+t+","+(i=r?"_n("+i+")":i)+")"),Mr(e,"change",Br(t,i),null,!0)}(e,r,i);else if("input"===o||"textarea"===o)!function(e,t,n){var r=e.attrsMap.type,i=n||{},o=i.lazy,a=i.number,s=i.trim,c=!o&&"range"!==r,u=o?"change":"range"===r?Wr:"input",l="$event.target.value";s&&(l="$event.target.value.trim()"),a&&(l="_n("+l+")");var f=Br(t,l);c&&(f="if($event.target.composing)return;"+f),Er(e,"value","("+t+")"),Mr(e,u,f,null,!0),(s||a)&&Mr(e,"blur","$forceUpdate()")}(e,r,i);else if(!F.isReservedTag(o))return Hr(e,r,i),!1;return!0},text:function(e,t){t.value&&Er(e,"textContent","_s("+t.value+")",t)},html:function(e,t){t.value&&Er(e,"innerHTML","_s("+t.value+")",t)}},isPreTag:function(e){return"pre"===e},isUnaryTag:bo,mustUseProp:jn,canBeLeftOpenTag:$o,isReservedTag:Wn,getTagNamespace:Zn,staticKeys:function(e){return e.reduce(function(e,t){return e.concat(t.staticKeys||[])},[]).join(",")}(ba)},xa=g(function(e){return p("type,tag,attrsList,attrsMap,plain,parent,children,attrs,start,end,rawAttrsMap"+(e?","+e:""))});function ka(e,t){e&&($a=xa(t.staticKeys||""),wa=t.isReservedTag||T,function e(t){t.static=function(e){if(2===e.type)return!1;if(3===e.type)return!0;return!(!e.pre&&(e.hasBindings||e.if||e.for||d(e.tag)||!wa(e.tag)||function(e){for(;e.parent;){if("template"!==(e=e.parent).tag)return!1;if(e.for)return!0}return!1}(e)||!Object.keys(e).every($a)))}(t);if(1===t.type){if(!wa(t.tag)&&"slot"!==t.tag&&null==t.attrsMap["inline-template"])return;for(var n=0,r=t.children.length;n|^function(?:\s+[\w$]+)?\s*\(/,Oa=/\([^)]*?\);*$/,Sa=/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*|\['[^']*?']|\["[^"]*?"]|\[\d+]|\[[A-Za-z_$][\w$]*])*$/,Ta={esc:27,tab:9,enter:13,space:32,up:38,left:37,right:39,down:40,delete:[8,46]},Ea={esc:["Esc","Escape"],tab:"Tab",enter:"Enter",space:[" ","Spacebar"],up:["Up","ArrowUp"],left:["Left","ArrowLeft"],right:["Right","ArrowRight"],down:["Down","ArrowDown"],delete:["Backspace","Delete","Del"]},Na=function(e){return"if("+e+")return null;"},ja={stop:"$event.stopPropagation();",prevent:"$event.preventDefault();",self:Na("$event.target !== $event.currentTarget"),ctrl:Na("!$event.ctrlKey"),shift:Na("!$event.shiftKey"),alt:Na("!$event.altKey"),meta:Na("!$event.metaKey"),left:Na("'button' in $event && $event.button !== 0"),middle:Na("'button' in $event && $event.button !== 1"),right:Na("'button' in $event && $event.button !== 2")};function Da(e,t){var n=t?"nativeOn:":"on:",r="",i="";for(var o in e){var a=La(e[o]);e[o]&&e[o].dynamic?i+=o+","+a+",":r+='"'+o+'":'+a+","}return r="{"+r.slice(0,-1)+"}",i?n+"_d("+r+",["+i.slice(0,-1)+"])":n+r}function La(e){if(!e)return"function(){}";if(Array.isArray(e))return"["+e.map(function(e){return La(e)}).join(",")+"]";var t=Sa.test(e.value),n=Aa.test(e.value),r=Sa.test(e.value.replace(Oa,""));if(e.modifiers){var i="",o="",a=[];for(var s in e.modifiers)if(ja[s])o+=ja[s],Ta[s]&&a.push(s);else if("exact"===s){var c=e.modifiers;o+=Na(["ctrl","shift","alt","meta"].filter(function(e){return!c[e]}).map(function(e){return"$event."+e+"Key"}).join("||"))}else a.push(s);return a.length&&(i+=function(e){return"if(!$event.type.indexOf('key')&&"+e.map(Ma).join("&&")+")return null;"}(a)),o&&(i+=o),"function($event){"+i+(t?"return "+e.value+"($event)":n?"return ("+e.value+")($event)":r?"return "+e.value:e.value)+"}"}return t||n?e.value:"function($event){"+(r?"return "+e.value:e.value)+"}"}function Ma(e){var t=parseInt(e,10);if(t)return"$event.keyCode!=="+t;var n=Ta[e],r=Ea[e];return"_k($event.keyCode,"+JSON.stringify(e)+","+JSON.stringify(n)+",$event.key,"+JSON.stringify(r)+")"}var Ia={on:function(e,t){e.wrapListeners=function(e){return"_g("+e+","+t.value+")"}},bind:function(e,t){e.wrapData=function(n){return"_b("+n+",'"+e.tag+"',"+t.value+","+(t.modifiers&&t.modifiers.prop?"true":"false")+(t.modifiers&&t.modifiers.sync?",true":"")+")"}},cloak:S},Fa=function(e){this.options=e,this.warn=e.warn||Sr,this.transforms=Tr(e.modules,"transformCode"),this.dataGenFns=Tr(e.modules,"genData"),this.directives=A(A({},Ia),e.directives);var t=e.isReservedTag||T;this.maybeComponent=function(e){return!!e.component||!t(e.tag)},this.onceId=0,this.staticRenderFns=[],this.pre=!1};function Pa(e,t){var n=new Fa(t);return{render:"with(this){return "+(e?Ra(e,n):'_c("div")')+"}",staticRenderFns:n.staticRenderFns}}function Ra(e,t){if(e.parent&&(e.pre=e.pre||e.parent.pre),e.staticRoot&&!e.staticProcessed)return Ha(e,t);if(e.once&&!e.onceProcessed)return Ba(e,t);if(e.for&&!e.forProcessed)return za(e,t);if(e.if&&!e.ifProcessed)return Ua(e,t);if("template"!==e.tag||e.slotTarget||t.pre){if("slot"===e.tag)return function(e,t){var n=e.slotName||'"default"',r=qa(e,t),i="_t("+n+(r?","+r:""),o=e.attrs||e.dynamicAttrs?Ga((e.attrs||[]).concat(e.dynamicAttrs||[]).map(function(e){return{name:b(e.name),value:e.value,dynamic:e.dynamic}})):null,a=e.attrsMap["v-bind"];!o&&!a||r||(i+=",null");o&&(i+=","+o);a&&(i+=(o?"":",null")+","+a);return i+")"}(e,t);var n;if(e.component)n=function(e,t,n){var r=t.inlineTemplate?null:qa(t,n,!0);return"_c("+e+","+Va(t,n)+(r?","+r:"")+")"}(e.component,e,t);else{var r;(!e.plain||e.pre&&t.maybeComponent(e))&&(r=Va(e,t));var i=e.inlineTemplate?null:qa(e,t,!0);n="_c('"+e.tag+"'"+(r?","+r:"")+(i?","+i:"")+")"}for(var o=0;o>>0}(a):"")+")"}(e,e.scopedSlots,t)+","),e.model&&(n+="model:{value:"+e.model.value+",callback:"+e.model.callback+",expression:"+e.model.expression+"},"),e.inlineTemplate){var o=function(e,t){var n=e.children[0];if(n&&1===n.type){var r=Pa(n,t.options);return"inlineTemplate:{render:function(){"+r.render+"},staticRenderFns:["+r.staticRenderFns.map(function(e){return"function(){"+e+"}"}).join(",")+"]}"}}(e,t);o&&(n+=o+",")}return n=n.replace(/,$/,"")+"}",e.dynamicAttrs&&(n="_b("+n+',"'+e.tag+'",'+Ga(e.dynamicAttrs)+")"),e.wrapData&&(n=e.wrapData(n)),e.wrapListeners&&(n=e.wrapListeners(n)),n}function Ka(e){return 1===e.type&&("slot"===e.tag||e.children.some(Ka))}function Ja(e,t){var n=e.attrsMap["slot-scope"];if(e.if&&!e.ifProcessed&&!n)return Ua(e,t,Ja,"null");if(e.for&&!e.forProcessed)return za(e,t,Ja);var r=e.slotScope===ca?"":String(e.slotScope),i="function("+r+"){return "+("template"===e.tag?e.if&&n?"("+e.if+")?"+(qa(e,t)||"undefined")+":undefined":qa(e,t)||"undefined":Ra(e,t))+"}",o=r?"":",proxy:true";return"{key:"+(e.slotTarget||'"default"')+",fn:"+i+o+"}"}function qa(e,t,n,r,i){var o=e.children;if(o.length){var a=o[0];if(1===o.length&&a.for&&"template"!==a.tag&&"slot"!==a.tag){var s=n?t.maybeComponent(a)?",1":",0":"";return""+(r||Ra)(a,t)+s}var c=n?function(e,t){for(var n=0,r=0;r':'
',ts.innerHTML.indexOf(" ")>0}var os=!!z&&is(!1),as=!!z&&is(!0),ss=g(function(e){var t=Yn(e);return t&&t.innerHTML}),cs=wn.prototype.$mount;return wn.prototype.$mount=function(e,t){if((e=e&&Yn(e))===document.body||e===document.documentElement)return this;var n=this.$options;if(!n.render){var r=n.template;if(r)if("string"==typeof r)"#"===r.charAt(0)&&(r=ss(r));else{if(!r.nodeType)return this;r=r.innerHTML}else e&&(r=function(e){if(e.outerHTML)return e.outerHTML;var t=document.createElement("div");return t.appendChild(e.cloneNode(!0)),t.innerHTML}(e));if(r){var i=rs(r,{outputSourceRange:!1,shouldDecodeNewlines:os,shouldDecodeNewlinesForHref:as,delimiters:n.delimiters,comments:n.comments},this),o=i.render,a=i.staticRenderFns;n.render=o,n.staticRenderFns=a}}return cs.call(this,e,t)},wn.compile=rs,wn}); ================================================ FILE: api-test-v2/lib/js/vue-json-pretty.js ================================================ !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.VueJsonPretty=t():e.VueJsonPretty=t()}("undefined"!=typeof self?self:this,function(){return function(e){function t(r){if(n[r])return n[r].exports;var o=n[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,t),o.l=!0,o.exports}var n={};return t.m=e,t.c=n,t.d=function(e,n,r){t.o(e,n)||Object.defineProperty(e,n,{configurable:!1,enumerable:!0,get:r})},t.n=function(e){var n=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(n,"a",n),n},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p="",t(t.s=39)}([function(e,t){var n=e.exports={version:"2.6.9"};"number"==typeof __e&&(__e=n)},function(e,t,n){var r=n(25)("wks"),o=n(27),i=n(3).Symbol,s="function"==typeof i;(e.exports=function(e){return r[e]||(r[e]=s&&i[e]||(s?i:o)("Symbol."+e))}).store=r},function(e,t){e.exports=function(e,t,n,r,o,i){var s,a=e=e||{},c=typeof e.default;"object"!==c&&"function"!==c||(s=e,a=e.default);var u="function"==typeof a?a.options:a;t&&(u.render=t.render,u.staticRenderFns=t.staticRenderFns,u._compiled=!0),n&&(u.functional=!0),o&&(u._scopeId=o);var l;if(i?(l=function(e){e=e||this.$vnode&&this.$vnode.ssrContext||this.parent&&this.parent.$vnode&&this.parent.$vnode.ssrContext,e||"undefined"==typeof __VUE_SSR_CONTEXT__||(e=__VUE_SSR_CONTEXT__),r&&r.call(this,e),e&&e._registeredComponents&&e._registeredComponents.add(i)},u._ssrRegister=l):r&&(l=r),l){var f=u.functional,d=f?u.render:u.beforeCreate;f?(u._injectStyles=l,u.render=function(e,t){return l.call(t),d(e,t)}):u.beforeCreate=d?[].concat(d,l):[l]}return{esModule:s,exports:a,options:u}}},function(e,t){var n=e.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=n)},function(e,t,n){e.exports=!n(9)(function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a})},function(e,t,n){var r=n(3),o=n(0),i=n(19),s=n(6),a=n(10),c=function(e,t,n){var u,l,f,d=e&c.F,p=e&c.G,h=e&c.S,v=e&c.P,b=e&c.B,m=e&c.W,y=p?o:o[t]||(o[t]={}),g=y.prototype,_=p?r:h?r[t]:(r[t]||{}).prototype;p&&(n=t);for(u in n)(l=!d&&_&&void 0!==_[u])&&a(y,u)||(f=l?_[u]:n[u],y[u]=p&&"function"!=typeof _[u]?n[u]:b&&l?i(f,r):m&&_[u]==f?function(e){var t=function(t,n,r){if(this instanceof e){switch(arguments.length){case 0:return new e;case 1:return new e(t);case 2:return new e(t,n)}return new e(t,n,r)}return e.apply(this,arguments)};return t.prototype=e.prototype,t}(f):v&&"function"==typeof f?i(Function.call,f):f,v&&((y.virtual||(y.virtual={}))[u]=f,e&c.R&&g&&!g[u]&&s(g,u,f)))};c.F=1,c.G=2,c.S=4,c.P=8,c.B=16,c.W=32,c.U=64,c.R=128,e.exports=c},function(e,t,n){var r=n(7),o=n(13);e.exports=n(4)?function(e,t,n){return r.f(e,t,o(1,n))}:function(e,t,n){return e[t]=n,e}},function(e,t,n){var r=n(8),o=n(44),i=n(45),s=Object.defineProperty;t.f=n(4)?Object.defineProperty:function(e,t,n){if(r(e),t=i(t,!0),r(n),o)try{return s(e,t,n)}catch(e){}if("get"in n||"set"in n)throw TypeError("Accessors not supported!");return"value"in n&&(e[t]=n.value),e}},function(e,t,n){var r=n(12);e.exports=function(e){if(!r(e))throw TypeError(e+" is not an object!");return e}},function(e,t){e.exports=function(e){try{return!!e()}catch(e){return!0}}},function(e,t){var n={}.hasOwnProperty;e.exports=function(e,t){return n.call(e,t)}},function(e,t,n){var r=n(15);e.exports=function(e){return Object(r(e))}},function(e,t){e.exports=function(e){return"object"==typeof e?null!==e:"function"==typeof e}},function(e,t){e.exports=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}}},function(e,t,n){var r=n(47),o=n(28);e.exports=Object.keys||function(e){return r(e,o)}},function(e,t){e.exports=function(e){if(void 0==e)throw TypeError("Can't call method on "+e);return e}},function(e,t){var n=Math.ceil,r=Math.floor;e.exports=function(e){return isNaN(e=+e)?0:(e>0?r:n)(e)}},function(e,t,n){var r=n(25)("keys"),o=n(27);e.exports=function(e){return r[e]||(r[e]=o(e))}},function(e,t){e.exports={}},function(e,t,n){var r=n(43);e.exports=function(e,t,n){if(r(e),void 0===t)return e;switch(n){case 1:return function(n){return e.call(t,n)};case 2:return function(n,r){return e.call(t,n,r)};case 3:return function(n,r,o){return e.call(t,n,r,o)}}return function(){return e.apply(t,arguments)}}},function(e,t,n){var r=n(12),o=n(3).document,i=r(o)&&r(o.createElement);e.exports=function(e){return i?o.createElement(e):{}}},function(e,t,n){var r=n(22),o=n(15);e.exports=function(e){return r(o(e))}},function(e,t,n){var r=n(23);e.exports=Object("z").propertyIsEnumerable(0)?Object:function(e){return"String"==r(e)?e.split(""):Object(e)}},function(e,t){var n={}.toString;e.exports=function(e){return n.call(e).slice(8,-1)}},function(e,t,n){var r=n(16),o=Math.min;e.exports=function(e){return e>0?o(r(e),9007199254740991):0}},function(e,t,n){var r=n(0),o=n(3),i=o["__core-js_shared__"]||(o["__core-js_shared__"]={});(e.exports=function(e,t){return i[e]||(i[e]=void 0!==t?t:{})})("versions",[]).push({version:r.version,mode:n(26)?"pure":"global",copyright:"© 2019 Denis Pushkarev (zloirock.ru)"})},function(e,t){e.exports=!0},function(e,t){var n=0,r=Math.random();e.exports=function(e){return"Symbol(".concat(void 0===e?"":e,")_",(++n+r).toString(36))}},function(e,t){e.exports="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(",")},function(e,t,n){"use strict";var r=n(53),o=n.n(r),i=n(31),s=n.n(i),a=n(75),c=n(77),u=n(79),l=n(81),f=n(83),d=n(33);t.a={name:"vue-json-pretty",components:{SimpleText:a.a,VueCheckbox:c.a,VueRadio:u.a,BracketsLeft:l.a,BracketsRight:f.a},props:{data:{},deep:{type:Number,default:1/0},showLength:{type:Boolean,default:!1},showDoubleQuotes:{type:Boolean,default:!0},path:{type:String,default:"root"},selectableType:{type:String,default:""},showSelectController:{type:Boolean,default:!1},showLine:{type:Boolean,default:!0},selectOnClickNode:{type:Boolean,default:!0},value:{type:[Array,String],default:function(){return""}},pathSelectable:{type:Function,default:function(){return!0}},highlightMouseoverNode:{type:Boolean,default:!1},highlightSelectedNode:{type:Boolean,default:!0},collapsedOnClickBrackets:{type:Boolean,default:!0},parentData:{},currentDeep:{type:Number,default:1},currentKey:[Number,String]},data:function(){return{visible:this.currentDeep<=this.deep,isMouseover:!1,currentCheckboxVal:!!Array.isArray(this.value)&&this.value.includes(this.path)}},computed:{model:{get:function(){var e="multiple"===this.selectableType?[]:"single"===this.selectableType?"":null;return this.value||e},set:function(e){this.$emit("input",e)}},lastKey:function(){if(Array.isArray(this.parentData))return this.parentData.length-1;if(this.isObject(this.parentData)){var e=s()(this.parentData);return e[e.length-1]}},notLastKey:function(){return this.currentKey!==this.lastKey},selectable:function(){return this.pathSelectable(this.path,this.data)&&(this.isMultiple||this.isSingle)},isMultiple:function(){return"multiple"===this.selectableType},isSingle:function(){return"single"===this.selectableType},isSelected:function(){return this.isMultiple?this.model.includes(this.path):!!this.isSingle&&this.model===this.path},propsError:function(){return!this.selectableType||this.selectOnClickNode||this.showSelectController?"":"When selectableType is not null, selectOnClickNode and showSelectController cannot be false at the same time, because this will cause the selection to fail."}},methods:{handleValueChange:function(e){var t=this;if(!this.isMultiple||"checkbox"!==e&&"tree"!==e){if(this.isSingle&&("radio"===e||"tree"===e)&&this.model!==this.path){var n=this.model,r=this.path;this.model=r,this.$emit("change",r,n)}}else{var i=this.model.findIndex(function(e){return e===t.path}),s=[].concat(o()(this.model));-1!==i?this.model.splice(i,1):this.model.push(this.path),"checkbox"!==e&&(this.currentCheckboxVal=!this.currentCheckboxVal),this.$emit("change",this.model,s)}},handleClick:function(e){e._uid&&e._uid!==this._uid||(e._uid=this._uid,this.$emit("click",this.path,this.data),this.selectable&&this.selectOnClickNode&&this.handleValueChange("tree"))},handleItemClick:function(e,t){this.$emit("click",e,t)},handleItemChange:function(e,t){this.selectable&&this.$emit("change",e,t)},handleMouseover:function(){this.highlightMouseoverNode&&(this.selectable||""===this.selectableType)&&(this.isMouseover=!0)},handleMouseout:function(){this.highlightMouseoverNode&&(this.selectable||""===this.selectableType)&&(this.isMouseover=!1)},isObject:function(e){return"object"===Object(d.a)(e)},keyFormatter:function(e){return this.showDoubleQuotes?'"'+e+'"':e}},errorCaptured:function(){return!1},watch:{deep:function(e){this.visible=this.currentDeep<=e},propsError:{handler:function(e){if(e)throw new Error("[vue-json-pretty] "+e)},immediate:!0}}}},function(e,t,n){var r=n(7).f,o=n(10),i=n(1)("toStringTag");e.exports=function(e,t,n){e&&!o(e=n?e:e.prototype,i)&&r(e,i,{configurable:!0,value:t})}},function(e,t,n){e.exports={default:n(72),__esModule:!0}},function(e,t,n){"use strict";var r=n(33);t.a={props:{showDoubleQuotes:Boolean,parentData:{},data:{},showComma:Boolean,currentKey:[Number,String]},computed:{dataType:function(){return Object(r.a)(this.data)},parentDataType:function(){return Object(r.a)(this.parentData)}},methods:{textFormatter:function(e){var t=e+"";return"string"===this.dataType&&(t='"'+t+'"'),this.showComma&&(t+=","),t}}}},function(e,t,n){"use strict";function r(e){return Object.prototype.toString.call(e).slice(8,-1).toLowerCase()}t.a=r},function(e,t,n){"use strict";t.a={props:{value:{type:Boolean,default:!1}},data:function(){return{focus:!1}},computed:{model:{get:function(){return this.value},set:function(e){this.$emit("input",e)}}}}},function(e,t,n){"use strict";t.a={props:{path:String,value:{type:String,default:""}},data:function(){return{focus:!1}},computed:{currentPath:function(){return this.path},model:{get:function(){return this.value},set:function(e){this.$emit("input",e)}}},methods:{change:function(){this.$emit("change",this.model)}}}},function(e,t,n){"use strict";var r=n(31),o=n.n(r),i=n(37);t.a={mixins:[i.a],props:{showLength:Boolean},methods:{closedBracketsGenerator:function(e){var t=Array.isArray(e)?"[...]":"{...}";return this.bracketsFormatter(t)},lengthGenerator:function(e){return" // "+(Array.isArray(e)?e.length+" items":o()(e).length+" keys")}}}},function(e,t,n){"use strict";t.a={props:{visible:{required:!0,type:Boolean},data:{required:!0},showComma:Boolean,collapsedOnClickBrackets:Boolean},computed:{dataVisible:{get:function(){return this.visible},set:function(e){this.collapsedOnClickBrackets&&this.$emit("update:visible",e)}}},methods:{toggleBrackets:function(){this.dataVisible=!this.dataVisible},bracketsFormatter:function(e){return this.showComma?e+",":e}}}},function(e,t,n){"use strict";var r=n(37);t.a={mixins:[r.a]}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(40),o=n.n(r),i=n(52),s=n(86);n.n(s);t.default=o()({},i.a,{version:"1.6.2"})},function(e,t,n){e.exports={default:n(41),__esModule:!0}},function(e,t,n){n(42),e.exports=n(0).Object.assign},function(e,t,n){var r=n(5);r(r.S+r.F,"Object",{assign:n(46)})},function(e,t){e.exports=function(e){if("function"!=typeof e)throw TypeError(e+" is not a function!");return e}},function(e,t,n){e.exports=!n(4)&&!n(9)(function(){return 7!=Object.defineProperty(n(20)("div"),"a",{get:function(){return 7}}).a})},function(e,t,n){var r=n(12);e.exports=function(e,t){if(!r(e))return e;var n,o;if(t&&"function"==typeof(n=e.toString)&&!r(o=n.call(e)))return o;if("function"==typeof(n=e.valueOf)&&!r(o=n.call(e)))return o;if(!t&&"function"==typeof(n=e.toString)&&!r(o=n.call(e)))return o;throw TypeError("Can't convert object to primitive value")}},function(e,t,n){"use strict";var r=n(4),o=n(14),i=n(50),s=n(51),a=n(11),c=n(22),u=Object.assign;e.exports=!u||n(9)(function(){var e={},t={},n=Symbol(),r="abcdefghijklmnopqrst";return e[n]=7,r.split("").forEach(function(e){t[e]=e}),7!=u({},e)[n]||Object.keys(u({},t)).join("")!=r})?function(e,t){for(var n=a(e),u=arguments.length,l=1,f=i.f,d=s.f;u>l;)for(var p,h=c(arguments[l++]),v=f?o(h).concat(f(h)):o(h),b=v.length,m=0;b>m;)p=v[m++],r&&!d.call(h,p)||(n[p]=h[p]);return n}:u},function(e,t,n){var r=n(10),o=n(21),i=n(48)(!1),s=n(17)("IE_PROTO");e.exports=function(e,t){var n,a=o(e),c=0,u=[];for(n in a)n!=s&&r(a,n)&&u.push(n);for(;t.length>c;)r(a,n=t[c++])&&(~i(u,n)||u.push(n));return u}},function(e,t,n){var r=n(21),o=n(24),i=n(49);e.exports=function(e){return function(t,n,s){var a,c=r(t),u=o(c.length),l=i(s,u);if(e&&n!=n){for(;u>l;)if((a=c[l++])!=a)return!0}else for(;u>l;l++)if((e||l in c)&&c[l]===n)return e||l||0;return!e&&-1}}},function(e,t,n){var r=n(16),o=Math.max,i=Math.min;e.exports=function(e,t){return e=r(e),e<0?o(e+t,0):i(e,t)}},function(e,t){t.f=Object.getOwnPropertySymbols},function(e,t){t.f={}.propertyIsEnumerable},function(e,t,n){"use strict";var r=n(29),o=n(85),i=n(2),s=i(r.a,o.a,!1,null,null,null);t.a=s.exports},function(e,t,n){"use strict";t.__esModule=!0;var r=n(54),o=function(e){return e&&e.__esModule?e:{default:e}}(r);t.default=function(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t=t.length?{value:void 0,done:!0}:(e=r(t,n),this._i+=e.length,{value:e,done:!1})})},function(e,t,n){var r=n(16),o=n(15);e.exports=function(e){return function(t,n){var i,s,a=String(o(t)),c=r(n),u=a.length;return c<0||c>=u?e?"":void 0:(i=a.charCodeAt(c),i<55296||i>56319||c+1===u||(s=a.charCodeAt(c+1))<56320||s>57343?e?a.charAt(c):i:e?a.slice(c,c+2):s-56320+(i-55296<<10)+65536)}}},function(e,t,n){"use strict";var r=n(26),o=n(5),i=n(59),s=n(6),a=n(18),c=n(60),u=n(30),l=n(64),f=n(1)("iterator"),d=!([].keys&&"next"in[].keys()),p=function(){return this};e.exports=function(e,t,n,h,v,b,m){c(n,t,h);var y,g,_,x=function(e){if(!d&&e in C)return C[e];switch(e){case"keys":case"values":return function(){return new n(this,e)}}return function(){return new n(this,e)}},k=t+" Iterator",j="values"==v,w=!1,C=e.prototype,O=C[f]||C["@@iterator"]||v&&C[v],S=O||x(v),A=v?j?x("entries"):S:void 0,M="Array"==t?C.entries||O:O;if(M&&(_=l(M.call(new e)))!==Object.prototype&&_.next&&(u(_,k,!0),r||"function"==typeof _[f]||s(_,f,p)),j&&O&&"values"!==O.name&&(w=!0,S=function(){return O.call(this)}),r&&!m||!d&&!w&&C[f]||s(C,f,S),a[t]=S,a[k]=p,v)if(y={values:j?S:x("values"),keys:b?S:x("keys"),entries:A},m)for(g in y)g in C||i(C,g,y[g]);else o(o.P+o.F*(d||w),t,y);return y}},function(e,t,n){e.exports=n(6)},function(e,t,n){"use strict";var r=n(61),o=n(13),i=n(30),s={};n(6)(s,n(1)("iterator"),function(){return this}),e.exports=function(e,t,n){e.prototype=r(s,{next:o(1,n)}),i(e,t+" Iterator")}},function(e,t,n){var r=n(8),o=n(62),i=n(28),s=n(17)("IE_PROTO"),a=function(){},c=function(){var e,t=n(20)("iframe"),r=i.length;for(t.style.display="none",n(63).appendChild(t),t.src="javascript:",e=t.contentWindow.document,e.open(),e.write("

Web SDK Demo 示例源码

{{opt.name}}

提示: {{RunType[runType].prompt}}

运行
================================================ FILE: api-test-v4/js/common/api-list.js ================================================ (function (win, dependencies) { var RongIMLib = win.RongIMLib, RongIMClient = RongIMLib.RongIMClient; var RongIM = dependencies.RongIM, utils = RongIM.Utils, Service = RongIM.Service, config = RongIM.config.im, urlQueryConfig = utils.getUrlQuery(); var MiniUnSupportEventList = [ 'sendRecallMessage', 'deleteRemoteMessages', 'clearRemoteHistoryMessages' ]; var getConnectedTime = { name: '连接时间', event: Service.getConnectedTime, eventName: 'getConnectedTime', desc: '断开链接', doc: 'https://docs.rongcloud.cn/v4/views/im/noui/guide/private/connection/connect/web.html', params: [] } var disconnect = { name: '断开链接', event: Service.disconnect, eventName: 'disconnect', desc: '断开链接', doc: 'https://docs.rongcloud.cn/v4/views/im/noui/guide/private/connection/disconnect/web.html', params: [] }; var reconnect = { name: '重新链接', event: Service.reconnect, eventName: 'reconnect', desc: '重新链接', doc: 'https://docs.rongcloud.cn/v3/views/im/noui/guide/private/connection/reconnect/web3.html', params: [ // { name: '是否嗅探', type: 'boolean', value: true }, // { name: '嗅探 url', type: 'string', value: 'https://cdn.ronghub.com/RongIMLib-2.2.6.min.js?d=' + Date.now() }, // { name: '嗅探频率', type: 'string', value: '100,1000,3000,3000,3000' } ] }; var changeUser = { name: '切换用户', evnet: utils.noop, eventName: 'logout', desc: '切换用户', doc: 'https://docs.rongcloud.cn/v4/views/im/noui/guide/private/connection/disconnect/web.html#logout', params: [ { name: 'Token', type: 'string', value: '5JQlp5czM31GNl99DOZyI3xpRjANxKgfakOnYLFljI+TMvOF0hGaVtR1n9Qp4baLgKBGsyl3w5j4gAWBbNZ3nOKrvnVo8Ldl' } ] }; var registerMessage = { name: '注册自定义消息', event: Service.registerMessage, eventName: 'registerMessageType', desc: '注册自定义消息', doc: 'https://docs.rongcloud.cn/v4/views/im/noui/guide/private/msgmanage/msgsend/web.html#createcustom', params: [ { name: 'messageType', type: 'string', value: 's:person' }, { name: '是否存储', type: 'boolean', value: true }, { name: '是否计数', type: 'boolean', value: true }, { name: '属性', type: 'string', value: 'name,age' }, ] }; var sendRegisterMessage = { name: '发送自定义消息', event: Service.sendRegisterMessage, eventName: 'conversation.send', desc: '发送自定义消息(RegisterMessage)', doc: 'https://docs.rongcloud.cn/v4/views/im/noui/guide/private/msgmanage/msgsend/web.html#createcustom', params: [ { name: '消息类型', type: 'string', value: 's:person' }, { name: '属性值', type: 'string', value: 'name,age' }, { name: '会话类型', type: 'number', value: 1 }, { name: '对方 id', type: 'string', value: config.targetId }, { name: '静默消息', type: 'boolean', value: false }, ] }; var getConversationList = { name: '获取会话列表', event: Service.getConversationList, eventName: 'im.Conversation.getList', desc: '获取会话列表', doc: 'https://docs.rongcloud.cn/v4/views/im/noui/guide/private/conversation/getall/web.html', params: [ { name: '数量', type: 'number', value: 1000 }, { name: '时间戳', type: 'number', value: 0 }, { name: '时间戳前/后', type: 'number', value: 0 } ] }; var removeConversation = { name: '删除会话列表', event: Service.removeConversation, eventName: 'conversation.destory', desc: '删除会话列表', doc: 'https://docs.rongcloud.cn/v4/views/im/noui/guide/private/conversation/clear/web.html', params: [ { name: '会话类型', type: 'number', value: 1 }, { name: '对方 id', type: 'string', value: config.targetId } ] }; var getHistoryMessages = { name: '获取历史消息', event: Service.getHistoryMessages, eventName: 'conversation.getMessages', desc: '获取历史消息', doc: 'https://docs.rongcloud.cn/v4/views/im/noui/guide/private/msgmanage/storage/web.html', params: [ { name: '时间戳', type: 'number', value: 0 }, { name: '数量', type: 'number', value: 20 }, { name: '会话类型', type: 'number', value: 1 }, { name: '对方 id', type: 'string', value: config.targetId } ] }; var setConversationStatus = { name: '设置会话状态', event: Service.setConversationStatus, eventName: 'conversation.setStatus', desc: '设置会话状态', doc: 'https://docs.rongcloud.cn/v4/views/im/noui/guide/private/conversation/top/web.html', params: [ { name: '免打扰', type: 'number', value: 1 }, { name: '置顶', type: 'boolean', value: true }, { name: '会话类型', type: 'number', value: 1 }, { name: '对方 id', type: 'string', value: config.targetId } ] }; var deleteRemoteMessages = { name: '删除历史消息(按消息)', event: Service.deleteRemoteMessages, eventName: 'conversation.deleteMessages', desc: '按消息删除指定历史消息', doc: 'https://docs.rongcloud.cn/v4/views/im/noui/guide/private/msgmanage/delete/web.html#deletebyid', params: [ { name: '消息 Uid', type: 'string', value: '', event: Service.getLastCacheMsgUId }, { name: '发送时间', type: 'number', value: 0, event: Service.getLastCacheMsgSentTime }, { name: '消息方向', type: 'number', value: 1, event: Service.getLastCacheMsgDirection }, { name: '会话类型', type: 'number', value: 1 }, { name: '对方 id', type: 'string', value: config.targetId } ] }; var clearHistoryMessages = { name: '删除历史消息(按时间)', event: Service.clearHistoryMessages, eventName: 'conversation.clearMessages', desc: '按时间删除历史消息', doc: 'https://docs.rongcloud.cn/v4/views/im/noui/guide/private/msgmanage/delete/web.html#delete', params: [ { name: '删除时间戳', type: 'number', value: Date.now() }, { name: '会话类型', type: 'number', value: 1 }, { name: '对方 id', type: 'string', value: config.targetId } ] }; var sendTextMessage = { name: '发送文字消息', event: Service.sendTextMessage, eventName: 'conversation.send', desc: '发送文字消息(TextMessage)', doc: 'https://docs.rongcloud.cn/v4/views/im/noui/guide/private/msgmanage/msgsend/web.html#TxtMsg', params: [ { name: '文字内容', type: 'string', value: '我是一条文字消息' }, { name: '会话类型', type: 'number', value: 1 }, { name: '对方 id', type: 'string', value: config.targetId }, { name: '状态消息', type: 'boolean', value: false }, { name: '静默消息', type: 'boolean', value: false }, { name: '支持扩展', type: 'boolean', value: false }, { name: '扩展Key', type: 'string', value: 'key1' }, { name: '扩展Value', type: 'string', value: 'val1' } ] }; var sendImageMessage = { name: '发送图片消息', event: Service.sendImageMessage, eventName: 'conversation.send', desc: '发送图片消息(ImageMessage)', doc: 'https://docs.rongcloud.cn/v4/views/im/noui/guide/private/msgmanage/msgsend/web.html#ImgTextMsg', params: [ { name: '缩略图', type: 'string', value: '/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDABALDA4MChAODQ4SERATGCgaGBYWGDEjJR0oOjM9PDkzODdASFxOQERXRTc4UG1RV19iZ2hnPk1xeXBkeFxlZ2P/2wBDARESEhgVGC8aGi9jQjhCY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2P/wAARCABkAPADASIAAhEBAxEB/8QAGwABAAIDAQEAAAAAAAAAAAAAAAECAwQGBwX/xAA7EAABAwEHAQYDBQcFAQAAAAABAAIDEQQFEiExUZETFiJBVGHRI3GTBhSBobEVM1Ji4fDxJEJDU3LB/8QAFwEBAQEBAAAAAAAAAAAAAAAAAAEDAv/EABwRAQEBAQACAwAAAAAAAAAAAAABEwIRMQNRYf/aAAwDAQACEQMRAD8ArBct7wBwbZWkOoc5G5EaHVSLnvoRCIQgNAoO+2ozrrVdY9tpNoqx7BDQZeNc/TTMceqwMivFrm4p43NqcVRmR4Uy11/Jb638ZZxzxu6/nPL3QtJJqQSyhOeo08StR/2dvV7sX3YVJqfiN912NLYZ8TSwREjuu1A/DxOfj4D1Wdgko3GW1/3UGvyU2s+jOVxTbivhgAbCQ2tadVtP1UTXBe81S6zguIp+8b7rsZ22rrNdA+PAKVa/x1r/APFEf3t9mlEmCObMRluY0yPj4qb9efRnHIw3HfEDsUdnaDUGpcw0/NQ+4b2eBis4y0+I33XUGG8uqCLVH0w5hphzIqMQ02r/AEWeZlqM7XQyNEWGjmkamvyXW3X4Zxhu2yPjueGy2hpa4No4A6Z7hbENlihdiZUHxO6iyNtLICLU8PlrkQcv0H6LXskF4iOMWq1MxtcC4xtBxCmmYyWNnm+Xb4l+XNb7Xess8EAdG4NocbRoBuVrfsi++/8ACpjbhdSRoqKU3XaItJ8tk8Ob8ct8uD7OXriB+7DT/sb7rajuu/Y8GGIdymGr2GlPmf7ouyRXbr6Mo4R32dvUkH7tXOp+I33WWO5b5iaAyGgDsQ+I3I8+i7ZE26Mo4WX7P3tIHE2epIP/ACN91qdl748qPqM916KibdGceddl748qPqM907L3x5UfUZ7r0VFNujOPOuy98eVH1Ge6dl748qPqM916KibdGceddl748qPqM907L3x5UfUZ7r0VE26M4867L3x5UfUZ7p2Xvjyo+oz3XoqJt0Zx512Xvjyo+oz3TsvfHlR9RnuvRUTbozjzrsvfHlR9RnunZe+PKj6jPdeiom3RnGV0UTRV2Q3Liqn7sK1ezLXv/P19DwrytbKzCXkA/wAJodKLAbFCS49SSrjUnH8+NSs2jJMLPBC+aU4Y4wXOcScgNVVr7I5xa2VhcDhID866U1V5YYp7NJZ5u/HI0tcCaVB10Wsy6bAy0/eBH8Tu5l5NS2tCc8zmcz7oMjJ7C9mNs8Zbv1P6qRLYnFwE0dWOLXfE0I1Gqwtue7mTGZkDWyurV7XkE1BGtdiomua7Z3h8sAe5shkDi91Q4nEaZ6Vzpog2OpZC9jBI0uecLQHE1NCf0B4UdSx4XO6rMLa4j1NKGh8d8lSz3XYbNKJIYg1weZK4ye8QRXX+Z3KC67CBJSL96AH/ABHZ0pTx9Px8UGQyWNpAMrAXEAfE1rSnj6hYHXhdjBMXWqL4BAk75OAkkUPrUFP2NdvUhk6Axw06Zxu7tKU8fQfnuU/Y120nHQAFofjlAe4YzUnPPcnJBW0Xnddm6vWtLWdJwa+pd3Sa0H5HhTJeF3RMe983djNHuAcQ3XWn/k8KZbnu+ZsrXxEiZ2N9JXCpz9ch3nZaZlXddtifHJGY+5IHB4xuzxYq+P8AO7n0CDHaLwu6yyOZPKWOa0OILX6EgA8kBS233a6EzC0MwBodUuIyJoMvmNFe13bY7aXG0Nc7FStJXN0II0O4Cwm4rrNKwVoMNeq7eu+Z9UFo7wuyQAstLHVoBRx8cgrMtl3vja8TDA4E4iSAKEg1rpmDqsYuK6w0tFnGEginUdTP8dchn4UCvFc9ggjayJj2taSRSd9RWtc6+p5QXbarC9jnslxsa0vLm4iKfMf3rskNpsU72sic9znad14/XRY3XNd7nRudG9zowQwumeSAdfFZIrssUNrbamNf1m1o4zPOuuRNP8DZBs9GPY8lOjHseSr4huExDcIKdGPY8lOjHseSr4huExDcIKdGPY8lOjHseSr4huExDcIKdGPY8lOjHseSr4huExDcIKdGPY8lOjHseSr4huExDcIKdGPY8lOjHseSr4huExDcIMi15rbZoOp1ZWt6YxOr4DdZzqFozXfd8tqklmaHTSt6bwZD3hTSlaaBQXlvOxQsc+S0Na1oBcTXKulVtNcHtDmmoIqCtEXZdtphdSJsrH4QTjLqhtKCtdMhkt5rQxoa3QCgQWREQEREBERAREQEREBERAREQEREBERAREQEREBERAREQQdQtK0ywtklbJG5+VXVc0DT1K3TqFpTtvA2z4Do2WfDSrhU13UqVe7HQvsgfA1zWOOKjnYjnnrUrbWGzdbpf6jDjrXu6D0/DT8FmSeiehERVRERAREQEREBERAREQEREBERAREQEREBERAREQEREEEE6GiijtxwpPgtG02W2yzSGK2GONwoG0zbpmDz+SDdo7ccJR244URtc2Noe7E4DN1KVVkEUduOEo7ccKUQRR244SjtxwpRBFHbjhKO3HClEEUduOEo7ccKUQRR244SjtxwpRBFHbjhKO3HClEEUduOEo7ccKUQRR244SjtxwpRBFHbjhKO3HClEEUduOEo7ccKUQRR244SjtxwpRBFHbjhKO3HClEEUduOEo7ccKUQD4Ii07VLbmOlFngY8BowEnU8oNxF8ya0XuC8RWSI4Wijia4jlWgqNM9f87mKfrMBADKd70OWn5oM6LFG6Qvo4CnzWVAREQEREBERAREQEREBERAREQEREBERAREQEREBERAOoUoiAiIgIiIC+VaLymiksrWtjImjxuqDkaeGaIgXfeU1qbZS9sY6wcXYQcqGmWazR22R0sTS1lHuAOR/gr+qIg30REBERAREQEREBERAREQEREBERAREQEREH//Z' }, { name: '原图 url', type: 'string', value: 'https://nfsprodrcx.cn.ronghub.com/v3/BGSPKH501EG0K6MI/base64.png?token=Um9uZ2Nsb3VkMTQyMDIwMDMxNzAzMzk1OTM2MDBtZXNzYWdlOzs7MjczMTk5NDg4OA==' }, { name: '会话类型', type: 'number', value: 1 }, { name: '对方 id', type: 'string', value: config.targetId }, { name: '静默消息', type: 'boolean', value: false }, ] }; var sendFileMessage = { name: '发送文件消息', event: Service.sendFileMessage, eventName: 'conversation.send', desc: '发送文件消息(FileMessage)', doc: 'https://docs.rongcloud.cn/v4/views/im/noui/guide/private/msgmanage/msgsend/web.html#FileMsg', params: [ { name: '文件名', type: 'string', value: 'logo_wx' }, { name: '文件大小', type: 'number', value: 20000 }, { name: '文件类型', type: 'string', value: 'png' }, { name: '文件 url', type: 'string', value: 'http://rongcloud.cn/images/newVersion/log_wx.png' }, { name: '会话类型', type: 'number', value: 1 }, { name: '对方 id', type: 'string', value: config.targetId }, { name: '静默消息', type: 'boolean', value: false }, ] }; var sendVoiceMessage = { name: '发送语音消息', event: Service.sendVoiceMessage, eventName: 'conversation.send', desc: '发送语音消息(HQVoiceMessage)', doc: 'https://docs.rongcloud.cn/v4/views/im/noui/guide/private/msgmanage/msgsend/web.html#HQVCMsg', params: [ { name: '语音 url', type: 'string', value: 'https://rongcloud-audio.cn.ronghub.com/audio_amr__RC-2020-03-17_42_1584413950049.aac?e=1599965952&token=CddrKW5AbOMQaDRwc3ReDNvo3-sL_SO1fSUBKV3H:CDngyWj7ZApNmAfoecng7L_3SaU=' }, { name: '语音类型', type: 'string', value: 'aac' }, { name: '语音时长', type: 'number', value: 6 }, { name: '会话类型', type: 'number', value: 1 }, { name: '对方 id', type: 'string', value: config.targetId }, { name: '静默消息', type: 'boolean', value: false }, ] }; var sendRecallMessage = { name: '发送撤回消息', event: Service.sendRecallMessage, eventName: 'conversation.recall', desc: '发送撤回消息', doc: 'https://docs.rongcloud.cn/v4/views/im/noui/guide/private/msgmanage/msgrecall/web.html', params: [ { name: '消息 Uid', type: 'string', value: '', event: Service.getLastCacheMsgUId }, { name: '发送时间', type: 'number', value: 0, event: Service.getLastCacheMsgSentTime }, { name: '会话类型', type: 'number', value: 1 }, { name: '对方 id', type: 'string', value: config.targetId }, { name: '静默消息', type: 'boolean', value: false }, ] }; var sendAtMessage = { name: '发送 @ 消息', event: Service.sendAtMessage, eventName: 'conversation.send', desc: '发送 @ 消息', doc: 'https://docs.rongcloud.cn/v4/views/im/noui/guide/group/msgmanage/msgsend/web.html#at', params: [ { name: '文字内容', type: 'string', value: '我是一条文本消息, 我 @ 了其他人' }, { name: '@ 对象 id', type: 'string', value: config.targetId }, { name: '会话类型', type: 'number', value: 3 }, { name: '群组 id', type: 'string', value: config.targetId }, { name: '静默消息', type: 'boolean', value: false }, ] }; var sendAtMessageByErrorParamField = { name: '发送 @ 消息 ErrorParams', event: Service.sendAtMessageByErrorParamField, eventName: 'sendMessage', desc: '发送 @ 消息', doc: 'https://docs.rongcloud.cn/v3/views/im/noui/guide/group/msgmanage/msgsend/web3.html#at', params: [ { name: '文字内容', type: 'string', value: '我是一条文本消息, 我 @ 了其他人' }, { name: '@ 对象 id', type: 'string', value: config.targetId }, { name: '会话类型', type: 'number', value: 3 }, { name: '群组 id', type: 'string', value: config.targetId }, { name: '静默消息', type: 'boolean', value: false }, ] }; var sendLocationMessage = { name: '发送位置消息', event: Service.sendLocationMessage, eventName: 'conversation.send', desc: '发送位置消息(sendLocationMessage)', doc: 'https://docs.rongcloud.cn/v4/views/im/noui/guide/private/msgmanage/msgsend/web.html#LBSMsg', params: [ { name: '位置缩略图', type: 'string', value: '/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDABsSFBcUERsXFhceHBsgKEIrKCUlKFE6PTBCYFVlZF9VXVtqeJmBanGQc1tdhbWGkJ6jq62rZ4C8ybqmx5moq6T/2wBDARweHigjKE4rK06kbl1upKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKSkpKT/wAARCADwAZgDASIAAhEBAxEB/8QAGQAAAwEBAQAAAAAAAAAAAAAAAAIDAQQF/8QAQRAAAgIBAwEFBQQIBAUFAQAAAQIAAxEEEiExEzJBUXEUImGBkQVSobEVIzNCU2LB0TRykuEkVXOi8ENjZJOkZf/EABgBAQEBAQEAAAAAAAAAAAAAAAABAgME/8QAHxEBAQEBAQACAwEBAAAAAAAAAAERAjEhQQMTcRIy/9oADAMBAAIRAxEAPwD3YQhKohCEAhCEAhCEAhCbtbyP0gZCNtb7phsbygLCaVI6iZAIQm9TiBkYIx8MesYKEG5jFZyenAgN2YHVofqx8ZOECm5B0X8IdqPBZOEYKdr/AC/jN9x/gZKEYGZCvxEWOLCOvIjYVxxwYCMLRUDTs3k/v5xj5TnX7RCUhr1O7cVIQeI9Z2rwoE8rU0sbLqzXdtNm9WRNw5HM3xJfii/6W0/3LPoP7zpWxb6FtUEA8jPWeR7J/Lqf/o/3nsVKE0iKAQAgHIwZe+eZ4EhCE5ghCEAl5CWHSSjG7p9I8WancHpIjB4j4xLn7Opn8QOPWMSAxyfjAtwdpBOOBmFjmyXoZAVKL7u9j1OOfzhTZvVHLuzYHCr/AF/3hWMUEMVJCn3scA+vnEV2XvBxXncCAeT5emZt0d0IiPlFLYDEcjym7l85hzavfPpNfoD8YoILjHlGfuH6wghCEKJJuplZJu8ZYzWQhCVGQhNAJ6CG2Qj9m3wikEdRAyEJoGTgdYGR1rJ68RjtrHTJiF2br0gPlE4HJi9o3wiQgP2jfCBsbziQgUVw3usIrLtOIucc+UpaMlQPGAnU4lABWMnkwwKxnqZMkk5MALFjkzIQgEIQgEIQgEIQgEIDkkAgkdQDyJu0+R+kBkswcN084g02dZ7SLD0xt8JuDnGJinoyMCPgeDHngbV0e0U7C5TnOZhPuqgJIUYyepjNsfOGG4DJGecRI34wEIEgYyQMnAycZMIBCEIBLDoJGWXuj0ko2CdPmYRGfs0dsZxziRFIYBGCBFY52kHAMMH7xlGlVOMgcdOJz6E4WxCclXIl8H7xnHV7v2jauTgjP5GWNT5ld0IuPifrDb8T9TMsmgRkYiEYBIJ4+MeUKvKibMXxHkZsiiSbvGVkm78sSjb8YRoRphAMkCJrdWNJUAmDYegP5mVq7/ynN9pLVX2eosrNhB27c4B6nmb5y9fKuX9Laj7lf0P953aLVDV1EOALB1A/MTy/1XZ9p7Hbszndv49M4nofZq1WdpqK6zWSdu3OQOh4nXvnnPCrkYJEk2rSm0p2V1jYz7i5wJ0ON1uPhzODUEj7QfbqVo9xe8Ac/WcEbXq7CpN2m1BYsT7tXQeAlqLlvDbVdSpwQ4wZDc//ADOr/Qn94aRTYupXttxZ8dooHl4QA6u3fcyUiylOh3hcY6nzMd9Um+gLbWm/O8Eg7fd8fnItStlwpGw1Vd6wcYH3T5xrKl1FnbVVIVTke6B2pzz8pBZdQi0dpdbXwdpKHcCflJJ9o0G20PcNmRs90+XPh5yo1GlpqDqyVox6KuOfiAJCrXaddTexuwHK4O084HPhKGT7Ro7ewPcOzG3Z7p8ufCX1erupXtKqA9e3dvLY/DrOenX6ZNVqHNvusE2kqecA58In2iy2U9pXdad4yFDYXA6nEg6TqLK69+pQZLBVWrk8zF1al0Vqb03ttBdMDP1kMYFQL3FxegZbWzjr0nVrOun/AOuv5GBJ77u1sCtpkRG2g2kgniZ7Rf8Ax9B/rM0VvY2oCV0uwt/9UZGMTm7O2u+7NGlOCoI2EgZHhA7NPbbZc1dvZHChg1WcHM6Cp8JCldmtZSFUilchRgA5PSdMCcJRuknLFEPA4xnwzGUeM1uhOMkeHnJo8+ntrNZdXZ2BBCiwAtyMeH1kex0q6O6w1hmR2Ue8eOePGX09IW657uHXbYWB6Hkn+0VHOipS8g4sHvrnBzyR+eIRfT21JpVNO+5a8KdiknPoZypqwmhRf1lbAjBIxuG7nHnO3TL2NQaxhljvds8ZM4ltrs0SIASyMOdvAy3nKKJqbG1lj6ekvlAPf93HXmWFtr6NLUVd+AxXHUeImWpqDqrDSFG5ANzg48emPGU0hzp1VR+zJTPnjxkErrFtTSuhyrXKR+MobWOpFVeMLzYT4eQ9Zz2INQ+3TYVKSW3Dozzp07V2Vl61CknLr4hvHMopCEIUSq90SUqndElDSdoYq4UZJWUmfvj0MiJ0lmoQnHBwPylYP3D8OYQCcbjb9p1n7y/3nZOXVLi6iz+cLLG+fXVCEJGWTU5UQgnQjyMIz98/WbMbvD0mwCTbvykm3flhWwhCQIDggjwktdRdq1VazWKxzznOeZSAJByDibly7Fc3smr9k9mzRs88nPXMroaLtIrLYazWeeM5zxLdo/w+kFBdveOcS3u2YHHClz1M8+5LDrGf2QXgoOWIAH1nc5LNgcgQFbHrxMI4dr/8rq/1p/aPpEZRfvoNYZs7B5Y8MTs2IveMO0Ud0QORUur0aYqGcgtWF/dJ6To2WC7Bx2RXg9NpjGxj8InXrzKJpbbXSc6ffdu2kqAA383pNp7YFnts3M37q91fSPCMVKw6ity9ZNqE5NZ6j0P9Jmqq36e51RjY6AEdT6S0deklRHWVWW11rUcMtitnj3fjzJPp9SbKS2o7VVsDEbAuPjOyEg862l3uuDaI3LvyCbNngPrF9kH/ACv/APRPTPSEo49HW6ah92nNKhAFG7cOp8Z2QhIAjMUqY0IAvSbMHQQgQfTCyx2LnbZt3KB1AzxmaNMpsNlp7RugBHCjyAloQOYaOtFZDl6ichG5CmPZUllRqYYQ+A4xLNyDJzUVD2TjHtOq/wDt/wBo1mjU6eutXdah3lB72fMysoTmmESRVRQqAKo6ASVmnD2dojtVZ4svj6jxloQrZkIQCVTuiSla+7FDTD3l9ZsxunzEyGYZUj4RQcgGNEXuj4cQhpza/wDYBvusDOmQ1ozpbB8P6yz1rn2LwiVndWjeagx5EExe8Zsz98fSED+B8jNg/dMyBsm/eEpJv3hEK2EIQJwHPTmV2IvX8YGwAe6JrVKKyevEf3a1k9zMQCesa09BIgNvkIuXbxMEHOY0BCuJkpFYY9IlUsIQlBCEIBKDgRB1EeSghCEiA+EIeMIBCEIBA9DCB6QCE0AmNt+MBITSCJkAiHgx4rdZYFlFwaj8JOUq7pEtVOEIQCEIQCUr7snKV9DFDxW7p9I0yZDRR4j4zU7g9Jn7zfWEbJ3jNFg/lP5SkwjIwfGFS0rbtNWf5cS05tAc6VR5Ej8Z0y31evRMPgfIzZjcqZENEXuiODkZijqR8YRsR+8I8R+CDEKITN3whKEhCEqnqGWz5THOWJjJ7qFvOTA6CBRRgQhCZQQhCArDHpFlIjDEsqshCaAScASgXvCPBa2BzxNII6yVGQhCQHiYQEIBCEIBNAycTJq96Bz/AGk5TTqA+xXbaxxngg5nn6RhVepquyWsCY29Vz1nf9p5NVQVQx7UYB6HrPOzZV+salAEvySOCCP3fSd+P+WL692IRg4nBd9pXCxqFoCWjBJZshR8pzLq9SbmUaoPYg95GrAH4c/jPP1ZLldueLZsevMfwkdJqRqaydux1OHU+Blm6SxkkpV1MnHq7/ymqFIwSJk1uHPrMgEIQgEpX4ycevxiikIQmQJ3fmZh7/qIJ+96wbvD6QjYQhCubR4AuT7thnTObTjbqtQvxBnTLfV69EIQkQJ3R8OJh75+Ignj6wbvD0MI2JZ4R4lnhEKSEZekJdTCQhNUZOOflK0569WzO6Gu5k34RlT3cDjr6xa9Wz7LA+mVCOUa7nP04kNO4S9wfbFrTopHCjH7wlFsNI09deouKHgnsfDHh7v95EdCarfp7rAFzXuHDbgcDPXictX2ja9la7tO25gCqhs8n48SjJWdPentDYLh7CyEEA446fCciXICgbWMQCNw7RyCPLG3+sDrbWaoMzey4ROHXtBnPhL2vY1VaBTVbacYByVHic+n5zxm7HeuPZ8c5x2mPn4/SdlyaZdFQGCBnyFYFsKM8nnmBbWazFdbUvtHaEbmzg49Ooi6bW2X6hay1LqQSdgYEcfGZcKzUG0916pjC4Yqg/DJPpJ0otrVg36o3YIb38bPPw/CB6XXiLZqk077GrsxkDft93n4x074/rF+0U36KweIGfpNTNyqo2opUkNdWCOoLCA1FDEKLqyT0AYTxdRWbbmsRq8Phv2ijkjnxj6HTt7XWWNeAc8OpP4GdP1zN0x7BGDiZGfqIp6TggHSEIQCEAwJIDAkdQD0grBlDKQwPQg5EAgenHWbiGD5QJajTpq1UOzrt5wp6yP6Jo+/Z9R/adW3I5EMHzM1OrEyPGetdLqtRWAxxh1zyWGP7gzlprvreu8ovvE7wM5w3n6cT1/tKkGg3A7bK+6fP4fOcD35pRq+9ZwvwPx9Jx6l3+vTxZef46/s3B1OoZemFUn4jP8AcTvPIM4NOyU1itOg6nxJ8zOiu0HksAPMnE3Jkcert1SNWffERXRyQjoxHUBgYy94es2jbO+Yse3vD0iQCEIQCPX1MSPX1MUUhCZMgXvH5Qf931gO/wDKa/T5iEEIQhXMox9oP/MgP9J0zms419R+8hH9Z0y1b9CEISIxe80G6r6wHfPpNfoPWEESzoI8SzpEKxYTF6wloWPV3/lElKuplVx2U3tqNQQ1a12DHPJPu4+Ua2uweyisAsmRnBwDt8fhLk5JMcdJEcqJqK1usZVstswNtbbQAOOpnI+n1jIV2ajkY51KkflPVhA8ldPrlCgLeFAwQNQB9PKdrLqbUrO2uphkHf77D0M6YQOG6vUJljl8DmxFy5+Cjwi00v2TNUhrcWbq1fr0AOfWehJxAdOR1lWPaVMFAJIIw3TPxkoDIOQcGVSaTTfqf+Joq358EHSC0PXrty1VLSB1CgHp9ZXtH+H0mglu8Zb1RucnMD0hA9DMIJK+/scfqrbM/wANc4lYlt1dK7rXCj4+MDn0T9pfqX2MmWXhxgjiS0Wpc6Wqqio2Mo94nhV585XRWC2/UuAwBZcBhg9IaWwU/ZaWEZCoTj5yjNVSl+srV03gVsQucZMh7J//AC//ANErqK69VqQHXIWndjPQk8Tm9m06abT3umQf2g3HJHn8oHVpdIq27m0PYlRkN2u7n0lPtFqhpttpXk+7v3Yz8uZHR6RDcNQtIrrAygLEk/HrLmqyioppiPeYlmsbO3MDxn7IsoHs4Gclh2mPQ5nLcRuevNbKp9wDdjnnjx4wevnPXewaenUVrcr2MNwsU+8eehlhut1Vl+mepXHu7DyXx4nyg1B9Kg+zTZntCQuMcDqI3YbAT+i1wPO4GW1NXbNSLWtQ2HBRLPdBAz5RbdMVvpq9q1JWzduzZ5CA2lZiVZdEtSOO+HXp9MzpnKNOKrq6lv1OMEj9ZwMY4xidR5zKqlvhJyl3UScQEIQgEevvRI9Xf+UBrLEprL2NhR4yH6R0n8X/ALT/AGkftOmy2ysGxUp8SxAwf6zz/ZW/i09cftB9Z1445s+aPdqdLlFlbZU9DGfuGcH2ZTZVZYBYr0+BUg5P9J3tyCPhOfUkuRBCYORmbMK5tSduo07fzEfWdM5tcdqVv92wGdMt8W+QQhCRGDvj0M1+6frM/eX1mtyp9IQRLOkYciY/diFIvWEwdYS1IyUr4UmTlF/Yn5y1pOUk5SSghCEiCEIQCIepjxG6mWKyEISgmg4MyECkIqnwjEgTKAdBFaqtnV2QFl6EjpGXkQgJXVsuts3Z7Qg4x0wMTn/R1WNvaXdnnPZ7/d+k64QJLQqtawY7rep8hjHEXT6OqgDguwGNzc8fDyl4QIV6YU2BqrHSvxr6j/aVsRLUKOoZT1EaGIHLboQ/upYK6jjci1jn5yl2lpvO50w33l4Mt6wgT1FC3hcu6FTkFDgyJ0Clgx1OpJXoe06fhOqB4EDlr0wruFnbWvgEYsO7rLryw9ZkavviaVtp94D4RIznLmLAIQhAIyHDiLGXvCByfbNidktWff3BsY8OZx/8J7B/8j5+f06T2wSOvIm7x/4Jvn8mTB5/2NYnZNVn39xbGPDiegOcxWYkccCPM9df6uoRe6PSNFXp8zGmFc+uGdK/wwfxl1O5Qw8RmT1K7tPYP5TDTNu09Z/lEv0v0rCEJEYfA/GNEbp8xHhCKw2jkdJjkbeojbl8j9IblHgfpAlkecJTen/ghNamJSg/Yycov7I/OK0nKScoOgkoIQhIghCEAiv4RpjdICQhCaUQhCAQhA8AnygMp5xGkkYOodc4PPMqORJQQkjqqFJBs5HHQzPbNP8AxPwMZTFoQhIghCEAik4PEaIeplgYMPHiYzZ4EWEuKJSrxMnKLxUT5xQh5OfOZCEAi2OK13MGPBPCk/kOI0jqveCJsVy5IANYY5x4ZIxA1dTWaRa25QVBwVP0BxzGovV3RSGSwjJRlPH4TnoU1g1Csq1YXJStA3wOSxEmtlqO9w7Ut2orOQmMZHHr6cSI7L/tDT1F0Ng7RfDaesj+lKPZt29e22Z27TjdjpOjV3CunG3L2e6qE9SZlpWqqqg15Wz9WQD0GICV/aGmtVV7Ub2HI2nrMs+1tKqgo+85HGCP6S9V9TOaaiTsHJHIHwzOW46i9rNnZGmrAPaZ7w5J4gM32ppVI2vuy3PBGB59J0UaqjUEil9xHJ4InH2up1TVhUpyqrb7+4YPPkZ16S2y1H7UIGRyp2Zxx6wLMNylT4jEhoTnSp8Mj8Z0Tm0Q2pYv3bCI+mp46YQhIhW6fOPEbpNssWpNzZx8BCMXp8zB+6YtNi2oSucAkciYXdndFQELjJLY/pAyEViyldyDDMF4b/aE0mNjK+MJjvk8+XEWI7FXTC554itHjr0iDpzNBxFDwmbhNyD4zKCEIQCB6QhAnCaepmTSiEIQCY3db0M2DA7W9DA56XtFKAU5GODvAzOip2K++mw56ZzE04/UJ6QvJWlyMggdZb8qSm7YHXs7G988quR1hqL91Dr2VoyOpXiDI1YRhbafeHBbiMENt1v62xQCMBWx4R8ejoXoIhci9UwMFSYmnG+llclhuK8nwkzpKu3UCs7NpzyesmRHXMmIi1qFQYAmzKA9JOVAyYwUDwlghCdBAPUSTpt5HSVSSjjFYEQDJAj2n3gIE4QhAJDVJvs064U5c99cjofCXmgkdCYHJpxWH1B31iv3PerOxfHyP9YaeiuwO2XK9sWU7zggY5+M68nzMM88wjn1lIF1VxYsxuQDP7o8hJayuwtS2rtXszZgqowBx5z0HrSzbvGdrBh6ia6K67XUMPIjImRyG+tbKKNK9eGY7gmDgYkGrS6xaNIzAAbbXB4I8j5meglNVZzXUiHzVQI9YABwAOT0Eo4LsV610F66f9Uu1jjHBPnH0DAPbWri1R7zWDxYzqtqrscdpWj4HG5QZqIlYwiKo8lGIDTn0nW//qtOic2k79//AFDH01PK6YQhIhW7seI3dM2xO0TbuZfipwYRHTdLcfxGk3U9s29EbIB3dkW/rKU6cVtuFlh5OQW4Ms2dpxjPxGYHLtQMvCKdwwewYc/WEcqWK7mGAc4C45+sJRsesAk5AOOREj1H3vWVSnqfWNtHlMfhjGXoJKM2iGwec2EiF2kdDN94fGbCBm7zE0EHxh1mFfKUY/WLNIImSxRCEIAyhlKsMg9ZL2Wj+H+JlYS6Jey0fw/xM0UVBWVV27hg4MpCNpqQ01IIIUgg5zma2nqdyzLkn4yuD5GZG00Uota7FyBnPMpJzQSJmwPCYG85oOZEDVpbUUcZVuonm2M+j9probaFZWHGeD6/Keoh8Jw6xV9tVRbsa1QpBrDA8+OZ1/HfpY4v0jq/4v8A2j+09PQWWX6Tfa24knBxjic92jNNTWPdXtXy06zq0rj2NGDbhg4O0L4+Qmu7zefiBq++IWHLmbV3vlMfvH1nILCEIBCEIBCEIFpswdBNmQQTofWExOresIG749DNmN3h85sAnNpP2moH/uGdM5tJ+11H+eWeNTyumEISIV+6fSPEbun0jwhV6H1P5wgvj6mbCowgesJazGTQcEHymQlaUtHQzE6TQN1WPKKvWRDTnv1qUuyGu1tgBYquQM/OdE8/U/tdSD3Cat58l5zIOhtYAcDTalh5ivI/OZXrVe5auwvVj95MYHn16RLm1DW6g13italBC7Ac8Z6zamZtYrcFjpgefPMotXqEc2Bv1bVn3gx6Dz9IrayhbUQWVkMDlt4wuJz22WPptWty1h0UDKA8gjPjJO9HtFJGhsAw2V7Ee908PGB6JtU1M9WLceCsDk+UKrEvrFicg/hOXSFzRcdOio3bHC2AjAwPAR6qzq6KrTZZSSORU20dYFK37Q2AKRscr1zmJqNVVptgsPeP0Hiek5tHQlpu26q8EWHhbMEjzMrrx2OmpHbMNto/WN7xHXn4wNTXaey4Vq+crndg9fLGJg1qPxTVbb8QMD6yent7XUWt7R2+KT72zbjnpCnU3pTQnspO5QFPagZ4/CUehtEA9KPtaxA/kSMzE7y5GPMZkftKpfZ3tVALFIO4DmJNuVXZMZQ3UTw9XqLl1L7brApOQAxHB5jaG6+3V1qbrCM5ILE8Tp+q5umPWKYMUjHWVfqIs5aicI+0E8cTjXWo4ylGpYea15H5y6rq3Ecxt6MwZ0G4dCR0kmtVXqVgwNvQY6cZ5jQKsysCCNwPhiTbwAAAA4A8JJtTXXelJLb36YHEa61aq2tfO1RzgcwiiHDibYMN6yVVi3VLZWcqenwjC5LrHRQQayAc/GFEJzLrkZdy06gr94V8fnLVW13JurYMPygPCEIBCEIFl7omzF7omzIJi9WmzF7x9BCBuq+s2Y/7vrNgE5tL+21H+edM5tL+31H+eWeNTyumEISIVu6fSb2i9p2fjjMxu6fST2L7X0/d3dfHMIqPH1mzB1PrNhUm7xhB+8YS1ksIQlaPUfeI85hG1vSYDtIMe0cgwM3CcNxta/VJVUH3oqklsbeDOuGBknAyepxyYwcz6W0do3tS1Vsqq2VBzgY8ek2hqzrcJYrqmnClgeOs6CAQQQCD1BGQZtSVoCERUz12qBmRHn2Xo66rqouA7MsMBsDHWabbmsrsOo0OUBAG8+M9EorLtZQV8iOIns2n/gVf6BA5tJetddzW2VljYWxWc5zjGJOm4pp00pdaXUYdnIGPTznelVdedlaLnyUCD1V2ftK0fH3lBgclo03Zp2GoqrsrHuMHH0MXUtZetHZ2jtMg7a1DDI6nPwzOr2XT/wACr/QJRFVF2ooVfIDAgebqK9WlljNa1hKbFIrGGB8PhyZ02J2dmkTwUkfRZ1wgTBwQfKPeFfTuCCVKnu9flFZfETFYr05HlKrm0dAvoDi7U1gHAHaflxNq/V/aAp36h8DOWfKnjynX2w+6Yby3HSavfo1jlvSZCE5o0dZ5mgt1C6ULXpe0XJ97tAM8+U9MdZ5+l9r09Iq9k3YJOe1USimqH/F6TjHvN+U6PXic+pS9n01qU7mTJZN4GMgeMy5tXbTYg0uxiuAe1U/+cQOYtVdRfcbUWxm3ICwBAXp/WX1dgt+zHsHRlB/ESy6ahFC9jWdoxkoOZznTWjR6ihVBBbNfvDkZBxKNUeyagDpRd/2t/vLaIZ1WrH86/lGtqW2o1P0Ix6RPsym6pru3xuYjByDnHjIE+zf8GnqfzgRs+0ht47Sslh8QesTTjV6ekVeygkE+8bQPwlqKXWxrrmDWsMe70UeQlFoQhCiEIQKp3RGip3RGmQTB3z6TZg749IRr9B6wg/dhAJzaX/Ean/MP6zpnNpv8Tqf8w/rLPGp5XTCEJEY3dPpNCjdvx72MZ+Exu6fSMOkIUdT6zZg6t6zYVN+9CFnWEqEhKnbYgdCDkZBHjJSqJTvVfEScpUeSPOKJwmsMMRMgEdRgQUeJmyVBCEJAQhCAQhCAQhCARWXxEaECc0HBzNYYOYs0qkJiHwmzKCEIQCEIQMYZ5ESUisMGWKWMhwwiwlD2DD+sSWZd4BziL2X834QJwlOy/m/CHZfzfhGicJTsv5vwh2X834QNr7saYqFfHPym4Oeox6TKCZ+8JpB8CPpDb056QB+4fSE08gxR0EDZzaf/ABOp9VnTOej/ABWo9V/KWNTyuiEISIxu6fSMOkVu6fSMOkIUdW9ZswdW9ZsKSzwhCzpCVH//2Q==' }, { name: '维度', type: 'number', value: 40.03190424323978 }, { name: '经度', type: 'number', value: 116.41731465378871 }, { name: '位置信息', type: 'string', value: '奥运村街道麦当劳(上品奥运村店)上品+(奥运村店)' }, { name: '会话类型', type: 'number', value: 1 }, { name: '对方 id', type: 'string', value: config.targetId }, { name: '静默消息', type: 'boolean', value: false }, ] }; var sendRichContentMessage = { name: '发送富文本消息', event: Service.sendRichContentMessage, eventName: 'conversation.send', desc: '发送富文本(图文)消息(sendRichContentMessage)', doc: 'https://docs.rongcloud.cn/v4/views/im/noui/guide/private/msgmanage/msgsend/web.html#ImgTextMsg', params: [ { name: '图文标题', type: 'string', value: '标题: 融云' }, { name: '图文内容', type: 'string', value: '为用户提供 IM 即时通讯和音视频通讯云服务' }, { name: '图片信息', type: 'string', value: 'https://www.rongcloud.cn/images/newVersion/log_wx.png' }, { name: '图文链接', type: 'string', value: 'https://developer.rongcloud.cn' }, { name: '会话类型', type: 'number', value: 1 }, { name: '对方 id', type: 'string', value: config.targetId }, { name: '静默消息', type: 'boolean', value: false }, ] }; var sendReferenceMessage = { name: '发送引用消息', event: Service.sendReferenceMessage, eventName: 'conversation.send', desc: '发送引用消息(sendReferenceMessage)', doc: 'https://docs.rongcloud.cn/im/imlib/web/message-send/#rich-content', params: [ { name: '引用消息内容', type: 'string', value: '' }, { name: '引用消息用户 ID', type: 'string', value: '' }, { name: '引用消息类型', type: 'string', value: 'RC:TxtMsg' }, { name: '消息内容', type: 'string', value: '为用户提供 IM 即时通讯和音视频通讯云服务' }, { name: '会话类型', type: 'number', value: 1 }, { name: '对方 id', type: 'string', value: config.targetId }, { name: '静默消息', type: 'boolean', value: false }, ] }; var sendSightMessage = { name: '发送小视频消息', event: Service.sendSightMessage, eventName: 'conversation.send', desc: '发送小视频消息(sendSightMessage)', doc: 'https://docs.rongcloud.cn/v4/views/im/noui/guide/group/msgmanage/msgsend/web.html#SightMsg', params: [ { name: '会话类型', type: 'number', value: 1 }, { name: '对方 id', type: 'string', value: config.targetId }, { name: 'sightUrl', type: 'string', value: '123' }, { name: 'content', type: 'string', value: '123' }, { name: 'duration', type: 'number', value: 100 }, { name: 'size', type: 'number', value: '为用户提供 IM 即时通讯和音视频通讯云服务' }, { name: 'name', type: 'string', value: '123' } ] }; var getUnreadCount = { name: '获取会话未读数', event: Service.getUnreadCount, eventName: 'conversation.getUnreadCount', desc: '获取指定会话未读数', doc: 'https://docs.rongcloud.cn/v4/views/im/noui/guide/private/conversation/unreadcount/web.html#get', params: [ { name: '会话类型', type: 'number', value: 1 }, { name: '对方 id', type: 'string', value: config.targetId } ] }; var getTotalUnreadCount = { name: '获取会话未读数总数', event: Service.getTotalUnreadCount, eventName: 'im.Conversation.getTotalUnreadCount', desc: '获取会话未读总数', doc: 'https://docs.rongcloud.cn/v4/views/im/noui/guide/private/conversation/unreadcount/web.html#total', params: [ ] }; var clearUnreadCount = { name: '清除会话未读数', event: Service.clearUnreadCount, eventName: 'conversation.read', desc: '清除指定会话未读数', doc: 'https://docs.rongcloud.cn/v4/views/im/noui/guide/private/conversation/unreadcount/web.html#clear', params: [ { name: '会话类型', type: 'number', value: 1 }, { name: '对方 id', type: 'string', value: config.targetId } ] }; var setDraft = { name: '设置会话草稿', event: Service.setDraft, eventName: 'conversation.setDraft', desc: '设置会话草稿', doc: 'https://docs.rongcloud.cn/v4/views/im/noui/guide/private/conversation/draft/web.html#save', params: [ { name: '会话类型', type: 'number', value: 1 }, { name: '对方 id', type: 'string', value: config.targetId }, { name: '草稿内容', type: 'string', value: '这是会话草稿' } ] }; var getDraft = { name: '获取会话草稿', event: Service.getDraft, eventName: 'conversation.getDraft', desc: '获取会话草稿', doc: 'https://docs.rongcloud.cn/v4/views/im/noui/guide/private/conversation/draft/web.html#get', params: [ { name: '会话类型', type: 'number', value: 1 }, { name: '对方 id', type: 'string', value: config.targetId } ] }; var deleteDraft = { name: '清除会话草稿', event: Service.deleteDraft, eventName: 'conversation.deleteDraft', desc: '清除会话草稿', doc: 'https://docs.rongcloud.cn/v4/views/im/noui/guide/private/conversation/draft/web.html#remove', params: [ { name: '会话类型', type: 'number', value: 1 }, { name: '对方 id', type: 'string', value: config.targetId } ] }; var joinChatRoom = { name: '加入聊天室', event: Service.joinChatRoom, eventName: 'chatRoom.join', desc: '加入指定聊天室, 并拉取消息', doc: 'https://docs.rongcloud.cn/v4/views/im/noui/guide/chatroom/manage/basic/join/web.html', params: [ { name: '聊天室 id', type: 'string', value: config.targetId }, { name: '拉取消息数', type: 'number', value: 2 } ] }; var joinExistChatRoom = { name: '加入已存在的聊天室', event: Service.joinExistChatRoom, eventName: 'chatRoom.joinExist', desc: '加入已存在的聊天室,若聊天室不存在,则加入失败', doc: 'https://docs.rongcloud.cn/v4/views/im/noui/guide/chatroom/manage/basic/join/web.html#jion-exist', params: [ { name: '聊天室 id', type: 'string', value: config.targetId }, { name: '拉取消息数', type: 'number', value: 2 } ] }; var quitChatRoom = { name: '退出聊天室', event: Service.quitChatRoom, eventName: 'chatRoom.quit', desc: '退出聊天室', doc: 'https://docs.rongcloud.cn/v4/views/im/noui/guide/chatroom/manage/basic/quit/web.html', params: [ { name: '聊天室 id', type: 'string', value: config.targetId } ] }; var getChatRoomInfo = { name: '获取聊天室信息', event: Service.getChatRoomInfo, eventName: 'chatRoom.getInfo', desc: '获取聊天室信息', doc: 'https://docs.rongcloud.cn/v4/views/im/noui/guide/chatroom/manage/basic/info/web.html', params: [ { name: '聊天室 id', type: 'string', value: config.targetId }, { name: '获取人数', type: 'number', value: 20 }, { name: '排序方式', type: 'number', value: 1 } ] }; var getChatRoomHistoryMessages = { name: '获取聊天室历史消息', event: Service.getChatRoomHistoryMessages, eventName: 'chatRoom.getMessages', desc: '获取聊天室历史消息', doc: 'https://docs.rongcloud.cn/v4/views/im/noui/guide/chatroom/msgmanage/storage/web.html', params: [ { name: '聊天室 id', type: 'string', value: config.targetId }, { name: '获取时间', type: 'number', value: 0 }, { name: '获取个数', type: 'number', value: 20 }, { name: '排序方式', type: 'number', value: 0 } ] }; var setChatRoomEntry = { name: '设置聊天室属性', event: Service.setChatRoomEntry, eventName: 'chatRoom.setEntry', desc: '设置聊天室自定义属性', doc: 'https://docs.rongcloud.cn/v4/views/im/noui/guide/chatroom/manage/key/set/web.html#set', params: [ { name: '属性 key', type: 'string', value: 'chrmKey1' }, { name: '属性 value', type: 'string', value: '我是一个聊天室 value' }, { name: '是否退出清除', type: 'boolean', value: true }, { name: '是否发送消息', type: 'boolean', value: true }, { name: '附加信息', type: 'string', value: '我是消息中的附加信息' }, { name: '聊天室 id', type: 'string', value: config.targetId } ] }; var forceSetChatRoomEntry = { name: '设置聊天室属性(强制)', event: Service.forceSetChatRoomEntry, eventName: 'chatRoom.forceSetEntry', desc: '强制设置聊天室自定义属性', doc: 'https://docs.rongcloud.cn/v4/views/im/noui/guide/chatroom/manage/key/set/web.html#force', params: [ { name: '属性 key', type: 'string', value: 'chrmKey2' }, { name: '属性 value', type: 'string', value: '我是一个聊天室 value' }, { name: '是否退出清除', type: 'boolean', value: true }, { name: '是否发送消息', type: 'boolean', value: true }, { name: '附加信息', type: 'string', value: '我是消息中的附加信息' }, { name: '聊天室 id', type: 'string', value: config.targetId } ] }; var removeChatRoomEntry = { name: '删除聊天室属性', event: Service.removeChatRoomEntry, eventName: 'chatRoom.removeEntry', desc: '删除聊天室自定义属性', doc: 'https://docs.rongcloud.cn/v4/views/im/noui/guide/chatroom/manage/key/remove/web.html', params: [ { name: '属性 key', type: 'string', value: 'chrmKey1' }, { name: '是否发送消息', type: 'boolean', value: true }, { name: '附加信息', type: 'string', value: '我是消息中的附加信息' }, { name: '聊天室 id', type: 'string', value: config.targetId } ] }; var forceRemoveChatRoomEntry = { name: '删除聊天室属性(强制)', event: Service.forceRemoveChatRoomEntry, eventName: 'chatRoom.forceRemoveEntry', desc: '强制删除聊天室自定义属性', doc: 'https://docs.rongcloud.cn/v4/views/im/noui/guide/chatroom/manage/key/remove/web.html#forcedel', params: [ { name: '属性 key', type: 'string', value: 'chrmKey2' }, { name: '是否发送消息', type: 'boolean', value: true }, { name: '附加信息', type: 'string', value: '我是消息中的附加信息' }, { name: '聊天室 id', type: 'string', value: config.targetId } ] }; var getChatRoomEntry = { name: '获取聊天室属性', event: Service.getChatRoomEntry, eventName: 'chatRoom.getEntry', desc: '获取指定聊天室自定义属性', doc: 'https://docs.rongcloud.cn/v4/views/im/noui/guide/chatroom/manage/key/query/web.html', params: [ { name: '属性 key', type: 'string', value: 'chrmKey1' }, { name: '聊天室 id', type: 'string', value: config.targetId } ] }; var getAllChatRoomEntries = { name: '获取聊天室属性(所有)', event: Service.getAllChatRoomEntries, eventName: 'chatRoom.getAllEntries', desc: '获取所有聊天室自定义属性', doc: 'https://docs.rongcloud.cn/v4/views/im/noui/guide/chatroom/manage/key/query/web.html#getall', params: [ { name: '聊天室 id', type: 'string', value: config.targetId } ] }; var sendChatRoomMessage = { name: '发送聊天室消息', event: Service.sendChatRoomMessage, eventName: 'chatRoom.send', desc: '发送聊天室消息, 以文本消息为例(TextMessage)', doc: 'https://docs.rongcloud.cn/v4/views/im/noui/guide/chatroom/msgmanage/msgsend/web.html', params: [ { name: '文字内容', type: 'string', value: '我是一条聊天室的文字消息' }, { name: '聊天室 id', type: 'string', value: config.targetId } ] }; var recallChatRoomMessage = { name: '撤回聊天室消息', event: Service.recallChatroomMessage, eventName: 'chatRoom.recall', desc: '撤回聊天室消息, 以文本消息为例(TextMessage)', doc: 'https://docs.rongcloud.cn/v4/views/im/noui/guide/chatroom/msgmanage/msgrecall/web.html', params: [ { name: '消息 Uid', type: 'string', value: '', event: Service.getLastCacheMsgUId }, { name: '发送时间', type: 'number', value: 0, event: Service.getLastCacheMsgSentTime }, { name: '对方 id', type: 'string', value: config.targetId } ] }; var joinRTCRoom = { name: '加入 RTC 房间', event: Service.joinRTCRoom, eventName: 'rtc.join', desc: '', params: [ { name: '房间 id', type: 'string', value: config.targetId }, { name: '模式', type: 'number', value: 0 } ] }; var pingRTCRoom = { name: 'Ping RTC', event: Service.pingRTCRoom, eventName: 'rtc.ping', desc: '', params: [ { name: '房间 id', type: 'string', value: config.targetId } ] }; var setRTCData = { name: '设置 RTC 数据', event: Service.setRTCData, eventName: '', desc: '', params: [ { name: '房间 id', type: 'string', value: config.targetId }, { name: 'key', type: 'string', value: 'key' }, { name: 'value', type: 'string', value: 'value' }, { name: 'isInner', type: 'boolean', value: false }, { name: 'apiType', type: 'number', value: 1 } ] }; var getRTCData = { name: '获取 RTC 数据', event: Service.getRTCData, eventName: '', desc: '', params: [ { name: '房间 id', type: 'string', value: config.targetId }, { name: 'key', type: 'string', value: 'key' }, { name: 'isInner', type: 'boolean', value: false }, { name: 'apiType', type: 'number', value: 1 } ] }; var removeRTCData = { name: '删除 RTC 数据', event: Service.removeRTCData, eventName: '', desc: '', params: [ { name: '房间 id', type: 'string', value: config.targetId }, { name: 'key', type: 'string', value: 'key' }, { name: 'isInner', type: 'boolean', value: false }, { name: 'apiType', type: 'number', value: 1 } ] }; var getRTCToken = { name: '获取 RTC Token', event: Service.getRTCToken, eventName: '', desc: '', params: [ { name: '房间 id', type: 'string', value: config.targetId } ] }; var getRTCRoomInfo = { name: '获取 RTC 房间信息', event: Service.getRTCRoomInfo, eventName: '', desc: '', params: [ { name: '房间 id', type: 'string', value: config.targetId } ] }; var setRTCUserInfo = { name: '设置 RTC 人员信息', event: Service.setRTCUserInfo, eventName: 'rtc.getRTCUserInfoList', desc: '', params: [ { name: '房间 id', type: 'string', value: config.targetId } ] }; var getRTCUserInfoList = { name: '获取 RTC 人员列表', event: Service.getRTCUserInfoList, eventName: '', desc: '', params: [ { name: '房间 id', type: 'string', value: config.targetId } ] }; var removeRTCUserInfo = { name: '删除 RTC 人员信息', event: Service.removeRTCUserInfo, eventName: '', desc: '', params: [ { name: '房间 id', type: 'string', value: config.targetId } ] }; var quitRTCRoom = { name: '退出 RTC 房间', event: Service.quitRTCRoom, eventName: 'rtc.quit', desc: '', params: [ { name: '房间 id', type: 'string', value: config.targetId } ] }; var updateMessageExpansion = { name: '设置消息扩展存储', event: Service.updateMessageExpansion, eventName: 'updateMessageExpansion', desc: '', params: [ { name: '会话类型', type: 'number', value: 1 }, { name: '对方 id', type: 'string', value: config.targetId }, { name: '消息 Uid', type: 'string', value: '', event: Service.getLastCacheMsgUId }, { name: 'key', type: 'string', value: '多个以逗号区分', event: Service.getLastCacheMsgUId }, { name: 'value', type: 'string', value: '多个以逗号区分', event: Service.getLastCacheMsgUId }, ] } var removeMessageExpansion = { name: '删除消息扩展存储', event: Service.removeMessageExpansion, eventName: 'removeMessageExpansion', desc: '', params: [ { name: '会话类型', type: 'number', value: 1 }, { name: '对方 id', type: 'string', value: config.targetId }, { name: '要移除的 keys', type: 'string', value: '', value: '' }, { name: '消息 Uid', type: 'string', value: '', event: Service.getLastCacheMsgUId }, ] } win.RongIM = win.RongIM || {}; var DefailtReadyApiQueue = [ [disconnect, reconnect, getConnectedTime], [getConversationList, removeConversation, setConversationStatus, getUnreadCount, getTotalUnreadCount, clearUnreadCount, setDraft, getDraft, deleteDraft], [sendTextMessage, sendImageMessage, sendRecallMessage, sendFileMessage, sendVoiceMessage, sendAtMessage, sendLocationMessage, sendRichContentMessage, sendReferenceMessage, sendSightMessage], [registerMessage, sendRegisterMessage], [getHistoryMessages, deleteRemoteMessages, clearHistoryMessages], [joinChatRoom, joinExistChatRoom, getChatRoomInfo, sendChatRoomMessage, getChatRoomHistoryMessages, recallChatRoomMessage], [setChatRoomEntry, getChatRoomEntry, forceSetChatRoomEntry, getAllChatRoomEntries, removeChatRoomEntry, forceRemoveChatRoomEntry], [quitChatRoom], [updateMessageExpansion, removeMessageExpansion], [joinRTCRoom, pingRTCRoom, setRTCData, getRTCData, removeRTCData, getRTCToken, getRTCRoomInfo, getRTCUserInfoList, setRTCUserInfo, removeRTCUserInfo], [quitRTCRoom], ]; urlQueryConfig.isMini && utils.forEach(DefailtReadyApiQueue, function (list, i) { utils.forEach(list, function (item, j) { if (MiniUnSupportEventList.indexOf(item.eventName) !== -1) { list.splice(j, 1); } }, { isReverse: true }) }); win.RongIM.DefailtReadyApiQueue = DefailtReadyApiQueue; win.RongIM.ApiList = [ getConversationList ]; window.RongIM.Api = { changeUser: changeUser } })(window, { RongIM: RongIM }); ================================================ FILE: api-test-v4/js/common/service.js ================================================ (function(win) { var RongIMLib = win.RongIMLib, RongIM = win.RongIM, RongIMClient = RongIMLib.RongIMClient, utils = RongIM.Utils; var im; // var sendMsgTimeout = RongIM.config.isDebug ? 300 : 0; var selfUserId; // 缓存消息, 用作撤回、删除等操作的参数 var CacheMsg = { eventEmitter: new utils.EventEmitter(), _list: [], set: function (msg) { this._list.push(msg); this.eventEmitter.emit('msgChanged'); }, remove: function (msg) { var list = this._list; utils.forEach(list, function(child, index) { if (child.messageUId === msg.messageUId) { list.splice(index, 1); } }, { isReverse: true }); this.eventEmitter.emit('msgChanged'); }, getLast: function () { var list = this._list, length = list.length; var msg = {}; if (length) { msg = list[length - 1]; } return msg; } }; /** * 初始化以及链接 * @param {object} config * @param {string} config.appkey 融云颁发的 appkey * @param {string} config.token 融云颁发的 token(代表某一个用户) * @param {Object} watcher * @param {Object} watcher.status 监听链接状态的变化 * @param {Object} watcher.message 监听消息的接收 */ function init(config, watcher) { watcher = watcher || {}; config = utils.clearUndefKey(config); config = utils.copy(config); var navi = config.navi; if (config.isPolling) { config.connectType = 'comet'; } if (navi) { var navigators; navi = navi.replace(/\s/g, ''); if (navi.indexOf(',') !== -1) { navigators = navi.split(','); } else { navigators = [navi]; } config.navigators = navigators; } // config.customCMP = ['120.92.13.84:80'] // config.isDebug = true; im = RongIMLib.init(config); RongIM.Service.im = im; im.watch({ conversation: function (event) { console.log('watch conversation', event); }, message: function (event) { var message = event.message; var hasMore = event.hasMore; watcher.message(message); console.warn('received messages', event); // message.xxx.xxx; }, status: function (event) { var status = event.status; console.log('status changed', event); // 不处理的状态码 var unHandleStatus = []; if (unHandleStatus.indexOf(status) === -1) { watcher.status(status); } }, chatroom: function (event) { console.warn('chatroom', event); var updatedEntries = event.updatedEntries; watcher.chatroom(updatedEntries); console.log('rejoin chatroom', event); }, expansion: function(event) { console.warn('----msg expansion----', event); watcher.expansion(event); } }); if(!config.customCMP){ delete config.customCMP; } return im.connect(config); } /** * 断开链接 * 文档: https://docs.rongcloud.cn/im/imlib/web/connect/#disconnect */ function disconnect() { return im.disconnect(); } function changeUser(config) { return im.changeUser(config); } function getConnectedTime() { return Promise.resolve(im.getConnectedTime()) } /** * 重新链接 * 文档: https://docs.rongcloud.cn/im/imlib/web/connect/#reconnect */ function reconnect() { return im.reconnect(); } /** * 获取会话列表 * 文档: https://docs.rongcloud.cn/im/imlib/web/conversation/get-list/ * * @param {number} count 获取会话的数量 * @param {number} startTime 获取起始时间 * @param {number} order 获取顺序 */ function getConversationList(count, startTime, order) { return im.Conversation.getList({ count: count, startTime: startTime, order: order }); } /** * 删除会话列表 * 文档: https://docs.rongcloud.cn/im/imlib/web/conversation/remove/ */ function removeConversation(conversationType, targetId) { conversationType = Number(conversationType); return im.Conversation.remove({ type: conversationType, targetId: targetId }); } /** * 获取历史消息 * 文档: https://docs.rongcloud.cn/im/imlib/web/message-list/get-list/ * * @param {number} timestrap 时间戳 * @param {number} count 数量 */ function getHistoryMessages(timestrap, count, conversationType, targetId) { conversationType = Number(conversationType); count = Number(count); timestrap = Number(timestrap); var conversation = im.Conversation.get({ type: conversationType, targetId: targetId }); return conversation.getMessages({ timestrap: timestrap, count: count }); } /** * 按时间删除历史消息 * 文档: https://docs.rongcloud.cn/im/imlib/web/message-list/remove-list/#_1 * * @param {number} timestrap 时间戳 */ function clearHistoryMessages(timestamp, conversationType, targetId) { conversationType = Number(conversationType); timestamp = Number(timestamp); var conversation = im.Conversation.get({ type: conversationType, targetId: targetId }); return conversation.clearMessages({ timestamp, }); } /** * 按消息删除历史消息 * @param {string} messageUId 消息在 server 的唯一标识 * @param {number} sentTime 消息发送时间 * @param {number} messageDirection 消息方向 */ function deleteRemoteMessages(messageUId, sentTime, messageDirection, conversationType, targetId) { var lastMsg = CacheMsg.getLast() || {}; conversationType = Number(conversationType) || lastMsg.type; sentTime = Number(sentTime) || lastMsg.sentTime; messageDirection = Number(messageDirection) || lastMsg.direction; var deleteMsg = { messageUId: messageUId, sentTime: sentTime, messageDirection: messageDirection }; var messages = [ deleteMsg ]; var conversation = im.Conversation.get({ type: conversationType, targetId: targetId }); return conversation.deleteMessages(messages); } /** * 获取指定会话未读数 * 文档: https://docs.rongcloud.cn/im/imlib/web/conversation/unreadcount/#get-one * * @param {number} conversationType 会话类型 * @param {string} targetId 目标 id (对方 id、群组 id、聊天室 id 等) */ function getUnreadCount(conversationType, targetId) { conversationType = Number(conversationType); var conversation = im.Conversation.get({ type: conversationType, targetId: targetId }); return conversation.getUnreadCount() } /** * 获取所有会话未读数 * 文档: https://docs.rongcloud.cn/im/imlib/web/conversation/unreadcount/#get-all */ async function getTotalUnreadCount() { return im.Conversation.getTotalUnreadCount(); } /** * 清除指定会话未读数 * 文档: https://docs.rongcloud.cn/im/imlib/web/conversation/unreadcount/#clear */ function clearUnreadCount(conversationType, targetId) { conversationType = Number(conversationType); var conversation = im.Conversation.get({ type: conversationType, targetId: targetId }); return conversation.read(); } /** * 设置会话草稿 */ function setDraft(conversationType, targetId, draft) { conversationType = Number(conversationType); return im.Conversation.get({ type: conversationType, targetId: targetId }).setDraft(draft) } /** * 获取会话草稿 */ function getDraft(conversationType, targetId) { conversationType = Number(conversationType); return im.Conversation.get({ type: conversationType, targetId: targetId }).getDraft() } /** * 删除会话草稿 */ function deleteDraft(conversationType, targetId) { conversationType = Number(conversationType); return im.Conversation.get({ type: conversationType, targetId: targetId }).deleteDraft() } function sendMessage(conversationType, targetId, msg) { conversationType = Number(conversationType); var conversation = im.Conversation.get({ type: conversationType, targetId: targetId }); return conversation.send(msg).then(function (msg) { CacheMsg.set(msg); return msg; }); } /** * 发送文本消息 * 文档: https://docs.rongcloud.cn/im/imlib/web/message-send/#text * 注意事项: * 1: 单条消息整体不得大于128K * 2: conversationType 类型是 number,targetId 类型是 string * * @param {string} text 文字内容 * @param {number} conversationType 会话类型 * @param {string} targetId 目标 id (对方 id、群组 id、聊天室 id 等) * @param {booleam} disableNotification 是否推送消息 */ function sendTextMessage(text, conversationType, targetId, isStatusMessage, disableNotification, canIncludeExpansion, exKeys, exVals) { var content = { content: text, // 文本内容 user: { "id" : "user1", "name" : "张三", "portrait" : "https://cdn.ronghub.com/thinking-face.png" } }; var expansion = {}; var exKeysArr = exKeys.split(','), exValsArr = exVals.split(','); exKeysArr.forEach((item, idx) =>{ expansion[item] = exValsArr[idx]; }) expansion = expansion || {key: 'value'} return sendMessage(conversationType, targetId, { content: content, messageType: 'RC:TxtMsg', isStatusMessage: isStatusMessage, disableNotification: disableNotification, canIncludeExpansion, expansion }); } /** * 发送图片消息 * 文档: https://docs.rongcloud.cn/im/imlib/web/message-send/#image * 注意事项: * 1. 略缩图(content 字段)必须是 base64 字符串, 类型必须为 jpg * 2. base64 略缩图必须不带前缀 * 3. base64 字符串大小不可超过 100 k * 4. 可通过 FileReader 或者 canvas 对图片进行压缩, 生成压缩后的 base64 字符串 * imageUri 为上传至服务器的原图 url, 用来展示高清图片 * 上传图片需开发者实现. 可参考上传插件: https://docs.rongcloud.cn/im/imlib/web/plugin/upload * * @param {string} base64 图片 base64 缩略图 * @param {string} imageUri 图片上传后的 url */ function sendImageMessage(base64, imageUri, conversationType, targetId, disableNotification) { var content = { content: base64, // 压缩后的 base64 略缩图, 用来快速展示图片 imageUri: imageUri // 上传到服务器的 url. 用来展示高清图片 }; return sendMessage(conversationType, targetId, { content: content, messageType: 'RC:ImgMsg', disableNotification }); } /** * 发送文件消息 * 文档:https://docs.rongcloud.cn/im/imlib/web/message-send/#file * * @param {string} fileName 文件名 * @param {string} fileSize 文件大小 * @param {string} fileType 文件类型 * @param {string} fileUrl 文件上传后的 url */ function sendFileMessage(fileName, fileSize, fileType, fileUrl, conversationType, targetId, disableNotification) { var content = { name: fileName, // 文件名 size: fileSize, // 文件大小 type: fileType, // 文件类型 fileUrl: fileUrl // 文件地址 }; return sendMessage(conversationType, targetId, { content: content, messageType: 'RC:FileMsg', disableNotification }); } /** * 高质量语音消息: https://docs.rongcloud.cn/im/introduction/message_structure/#hqvoice_message * 注意事项: * 融云不提供声音录制的方法. remoteUrl 的生成需开发者实现 * * @param {string} remoteUrl 语音上传后的 url * @param {number} duration 语音时长 */ function sendVoiceMessage(remoteUrl, type, duration, conversationType, targetId, disableNotification) { var content = { remoteUrl: remoteUrl, // 音频 url, 建议格式: aac duration: duration, // 音频时长 type: type }; return sendMessage(conversationType, targetId, { content: content, messageType: 'RC:HQVCMsg', disableNotification }); } /** * 撤回消息: https://docs.rongcloud.cn/im/imlib/web/message-send/#recall * 注意事项: * 消息撤回操作服务器端没有撤回时间范围的限制,由客户端决定 * * @param {string} messageUId 撤回的消息 Uid * @param {number} sentTime 撤回的消息 sentTime */ // BKE3-39Q0-4ME7-QRCS // 1599619898624 function sendRecallMessage(messageUId, sentTime, conversationType, targetId, disableNotification) { var recallMsg; if (messageUId && sentTime && conversationType && targetId) { recallMsg = { messageUId: messageUId, sentTime: sentTime, disableNotification: disableNotification }; } else { var lastMsg = CacheMsg.getLast() || {}; recallMsg = lastMsg; recallMsg.disableNotification = disableNotification; } recallMsg.user = { // 携带用户信息 "id" : "user1", "name" : "张三", "portrait" : "https://cdn.ronghub.com/thinking-face.png" } return im.Conversation.get({ type: conversationType, targetId: targetId, }).recall(recallMsg); } function recallChatroomMessage(messageUId, sentTime, targetId, disableNotification) { var recallMsg; if (messageUId && sentTime && targetId) { recallMsg = { messageUId: messageUId, sentTime: sentTime, disableNotification: disableNotification }; } else { var lastMsg = CacheMsg.getLast() || {}; recallMsg = lastMsg; recallMsg.disableNotification = disableNotification; } recallMsg.user = { "id" : "user1", "name" : "张三", "portrait" : "https://cdn.ronghub.com/thinking-face.png" } return im.ChatRoom.get({ id: targetId, }).recall(recallMsg); } /** * 发送 @ 消息(此处以文本消息举例) * 文档: https://docs.rongcloud.cn/im/imlib/web/message-send/#example * * @param {string} text 文字内容 * @param {string} methiondId @ 对象的 id */ function sendAtMessage(text, methiondId, conversationType, targetId, disableNotification) { conversationType = Number(conversationType); var isMentioned = true; var content = { content: text }; return im.Conversation.get({ type: conversationType, targetId: targetId }).send({ content: content, messageType: 'RC:TxtMsg', isMentioned: isMentioned, mentionedUserIdList: [methiondId], // @ 人 id 列表 mentionedType: 2, disableNotification }); } //测试错误参数下发送 @ 消息 function sendAtMessageByErrorParamField(text, methiondId, conversationType, targetId, disableNotification) { conversationType = Number(conversationType); var isMentioned = true; var content = { content: text }; return im.Conversation.get({ type: conversationType, targetId: targetId }).send({ content: content, messageType: 'RC:TxtMsg', isMentiond: isMentioned, mentiondUserIdList: [methiondId], // @ 人 id 列表 mentiondType: 1, disableNotification }); } /** * 注册自定义消息 * 文档: https://docs.rongcloud.cn/im/imlib/web/message-send/#custom * * @param {string} messageName 注册消息的 Web 端类型名 * @param {string} messageType 注册消息的唯一名称. 注: 此名称需多端一致 * @param {boolean} isCounted 是否计数 * @param {boolean} isPersited 是否存储 * @param {Array} props 消息包含的字段集合 */ function registerMessage(messageType, isPersited, isCounted, props) { // var mesasgeTag = new RongIMLib.MessageTag(isCounted, isPersited); //true true 保存且计数,false false 不保存不计数。 // props = props.split(','); // 将字符串截取为数组. 此处为 Demo 逻辑, 与融云无关 // RongIMClient.registerMessageType(messageName, messageType, mesasgeTag, props); // 废弃此概念 im.registerMessageType(messageType, isPersited, isCounted, props) return utils.Defer.resolve(); } /** * 发送自定义消息 * 文档: https://docs.rongcloud.cn/im/imlib/web/message-send/#custom * * @param {string} messageType 注册消息的 Web 端类型名 * @param {*} props 消息包含的字段集合 */ function sendRegisterMessage(messageType, props, conversationType, targetId, disableNotification) { var content = {} props && (props = props.split(',')) props.forEach(item => { content[item] = item }) return im.Conversation.get({ type: conversationType, targetId: targetId }).send({ messageType: messageType, content: { content: content }, disableNotification }); } /** * 发送位置消息 * 文档: https://docs.rongcloud.cn/im/imlib/web/message-send/#location * 注意事项: * 1. 缩略图必须是base64码的jpg图, 而且不带前缀"data:image/jpeg;base64,", 不得超过100K * 2. 需要开发者做显示效果, 一般显示逻辑: 图片加链接, 传入经纬度并跳转进入地图网站 * * @param {string} base64 位置缩略图 * @param {number} latitude 维度 * @param {number} longitude 经度 * @param {string} poi 位置信息 */ function sendLocationMessage(base64, latitude, longitude, poi, conversationType, targetId, disableNotification) { var content = { latitude: latitude, longitude: longitude, poi: poi, content: base64 }; return im.Conversation.get({ type: conversationType, targetId: targetId }).send({ messageType: 'RC:LBSMsg', content: content, disableNotification }); } /** * 发送引用消息 * 文档: https://docs.rongcloud.cn/im/imlib/web/message-send/#location * 注意事项: * * @param {string} referContent 引用消息内容 * @param {number} referMsgUserId 引用消息用户 ID * @param {number} objName 引用消息类型 * @param {string} content 消息内容 */ function sendReferenceMessage(referContent, referMsgUserId, objName, content, conversationType, targetId, disableNotification) { var content = { referMsg: { content: referContent }, referMsgUserId: referMsgUserId, objName: objName, content: content, }; return im.Conversation.get({ type: conversationType, targetId: targetId }).send({ messageType: RongIMLib.MESSAGE_TYPE.REFERENCE, content: content, disableNotification }); } /** * 发送富文本(图文)消息 * 文档: https://docs.rongcloud.cn/im/imlib/web/message-send/#rich-content * * @param {string} title 图文标题 * @param {number} content 图文内容 * @param {number} imageUri 显示图片的 url(图片信息) * @param {string} url 点击图文后打开的 url */ function sendRichContentMessage(title, content, imageUri, url, conversationType, targetId, disableNotification) { content = { title: title, content: content, imageUri: imageUri, url: url }; return im.Conversation.get({ type: conversationType, targetId: targetId }).send({ messageType: 'RC:ImgTextMsg', content: content, disableNotification }); } /** * 发送小视频消息 */ function sendSightMessage(conversationType, targetId, sightUrl, content, duration, size, name) { content = { sightUrl: sightUrl, content: content, duration: duration, size: size, name: name }; return im.Conversation.get({ type: conversationType, targetId: targetId }).send({ messageType: 'RC:SightMsg', content: content }); } /** * 加入聊天室 * 文档: https://docs.rongcloud.cn/im/imlib/web/chatroom/#join * * @param {string} chatRoomId 聊天室 id * @param {number} count 拉取消息数量 */ function joinChatRoom(chatRoomId, count) { return im.ChatRoom.get({ id: chatRoomId }).join({ count: count }); } /** * 加入已存在的聊天室 * 文档: https://docs.rongcloud.cn/im/imlib/web/chatroom/#join * * @param {string} chatRoomId 聊天室 id * @param {number} count 拉取消息数量 */ function joinExistChatRoom(chatRoomId, count) { return im.ChatRoom.get({ id: chatRoomId }).joinExist({ count: count }); } /** * 退出聊天室 * 文档: https://docs.rongcloud.cn/im/imlib/web/chatroom/#quit * * @param {string} chatRoomId 聊天室 id */ function quitChatRoom(chatRoomId) { return im.ChatRoom.get({ id: chatRoomId }).quit(); } /** * 获取聊天室信息 * 文档: https://docs.rongcloud.cn/im/imlib/web/chatroom/#get * * @param {string} chatRoomId 聊天室 id * @param {string} count 获取人数 * @param {string} order 排序方式 */ function getChatRoomInfo(chatRoomId, count, order) { return im.ChatRoom.get({ id: chatRoomId }).getInfo({ count: count, order: order }); } function getChatRoomHistoryMessages(chatRoomId, timestrap, count, order) { return im.ChatRoom.get({ id: chatRoomId }).getMessages({ timestrap: timestrap, timestamp: timestrap, count: count, order: order }); } function getFileToken(fileType, fileName) { return im.getFileToken(fileType, fileName) } function getFileUrl(fileType, fileName, originName) { return im.getFileUrl(fileType, fileName, originName) } /** * 发送聊天室消息(以文本消息为例) * 文档: https://docs.rongcloud.cn/im/imlib/web/message-send/#text * * @param {string} text 文字内容 */ function sendChatRoomMessage(text, targetId) { var content = { content: text // 文本内容 }; return im.ChatRoom.get({ id: targetId }).send({ messageType: 'RC:TxtMsg', content: content }) } function setChatRoomEntry(key, value, isAutoDelete, isSendNotification, extra, chatRoomId) { var entry = { key: key, value: value, notificationExtra: extra, isAutoDelete: isAutoDelete, isSendNotification: isSendNotification }; return im.ChatRoom.get({ id: chatRoomId }).setEntry(entry); } function forceSetChatRoomEntry(key, value, isAutoDelete, isSendNotification, extra, chatRoomId) { var entry = { key: key, value: value, notificationExtra: extra, isAutoDelete: isAutoDelete, isSendNotification: isSendNotification }; return im.ChatRoom.get({ id: chatRoomId }).forceSetEntry(entry); } function removeChatRoomEntry(key, isSendNotification, extra, chatRoomId) { var entry = { key: key, notificationExtra: extra, isSendNotification: isSendNotification }; return im.ChatRoom.get({ id: chatRoomId }).removeEntry(entry); } function forceRemoveChatRoomEntry(key, isSendNotification, extra, chatRoomId) { var entry = { key: key, notificationExtra: extra, isSendNotification: isSendNotification }; return im.ChatRoom.get({ id: chatRoomId }).forceRemoveEntry(entry); } function getChatRoomEntry(key, chatRoomId) { return im.ChatRoom.get({ id: chatRoomId }).getEntry(key); } function getAllChatRoomEntries(chatRoomId) { return im.ChatRoom.get({ id: chatRoomId }).getAllEntries(); } function joinRTCRoom(roomId, mode) { return im.RTC.get({ roomId: roomId, mode: mode }).join(); } function pingRTCRoom(roomId, mode) { return im.RTC.get({ roomId: roomId }).ping(); } function setRTCData(roomId, key, value, isInner, apiType, message) { return im.RTC.get({ roomId: roomId }).setData(key, value, isInner, apiType, message); } function getRTCData(roomId, key, isInner, apiType) { return im.RTC.get({ roomId: roomId }).getData([key], isInner, apiType); } function removeRTCData(roomId, key, isInner, apiType) { return im.RTC.get({ roomId: roomId }).removeData([key], isInner, apiType); } function getRTCToken(roomId) { return im.RTC.get({ roomId: roomId }).getToken(); } function getRTCRoomInfo(roomId) { return im.RTC.get({ roomId: roomId }).getRoomInfo(); } function getRTCUserInfoList(roomId) { return im.RTC.get({ roomId: roomId }).getUserInfoList(); } function setRTCUserInfo(roomId) { return im.RTC.get({ roomId: roomId }).setUserInfo({ key: 'test', value: 'test hahahah' }); } function removeRTCUserInfo(roomId) { return im.RTC.get({ roomId: roomId }).removeUserInfo({ key: 'test' }); } function quitRTCRoom(roomId, mode) { return im.RTC.get({ roomId: roomId, mode: mode }).quit(); } function setConversationStatus(isNotification, isTop, conversationType, targetId) { return im.Conversation.get({ type: conversationType, targetId: targetId }).setStatus({ notificationStatus: isNotification, isTop: isTop }); } function setMessageKV(){ console.log('setMessageKV'); return Promise.resolve('set message kv') } function updateMessageExpansion(conversationType, targetId, messageUId, key, value, canIncludeExpansion, isTest) { key && (key = key.split(',')); value && (value = value.split(',')); var expansion = {}; key.forEach((item,idx) => { expansion[item] = value[idx]; }) let message; if (isTest) { message = { canIncludeExpansion, messageUId, type: conversationType, targetId } }else { message = CacheMsg.getLast(); if(utils.isEmpty(message)) { return utils.Defer.reject('请先发送一条消息') } } return im.Conversation.get({ type: conversationType, targetId: targetId }).updateMessageExpansion(expansion, message); } function removeMessageExpansion(conversationType, targetId, keys, messageUId, canIncludeExpansion, isTest) { keys.length > 0 && (keys = keys.split(',')); let message; if (isTest) { message = { canIncludeExpansion: canIncludeExpansion == undefined ? true : canIncludeExpansion, messageUId, type: conversationType, targetId } }else { message = CacheMsg.getLast(); if(utils.isEmpty(message)) { return utils.Defer.reject('请先发送一条消息') } } return im.Conversation.get({ type: conversationType, targetId: targetId }).removeMessageExpansion(keys, message); } function removeMessageAllExpansion(conversationType, targetId, messageUId) { return im.Conversation.get({ type: conversationType, targetId: targetId }).removeMessageAllExpansion(messageUId); } function getLastCacheMsgUId() { return CacheMsg.getLast().messageUId; } function getLastCacheMsgSentTime() { return CacheMsg.getLast().sentTime; } function getLastCacheMsgDirection() { return CacheMsg.getLast().direction; } win.RongIM = win.RongIM || {}; win.RongIM.Service = { init: init, disconnect: disconnect, reconnect: reconnect, getConnectedTime: getConnectedTime, registerMessage: registerMessage, sendRegisterMessage: sendRegisterMessage, getConversationList: getConversationList, removeConversation: removeConversation, getHistoryMessages: getHistoryMessages, clearHistoryMessages: clearHistoryMessages, deleteRemoteMessages: deleteRemoteMessages, sendTextMessage: sendTextMessage, sendImageMessage: sendImageMessage, sendFileMessage: sendFileMessage, sendVoiceMessage: sendVoiceMessage, sendAtMessage: sendAtMessage, sendAtMessageByErrorParamField: sendAtMessageByErrorParamField, sendLocationMessage: sendLocationMessage, sendRichContentMessage: sendRichContentMessage, sendRecallMessage: sendRecallMessage, sendReferenceMessage: sendReferenceMessage, sendSightMessage: sendSightMessage, getUnreadCount: getUnreadCount, getTotalUnreadCount: getTotalUnreadCount, clearUnreadCount: clearUnreadCount, setDraft: setDraft, getDraft: getDraft, deleteDraft: deleteDraft, joinChatRoom: joinChatRoom, joinExistChatRoom: joinExistChatRoom, quitChatRoom: quitChatRoom, getChatRoomInfo: getChatRoomInfo, getChatRoomHistoryMessages: getChatRoomHistoryMessages, sendChatRoomMessage: sendChatRoomMessage, recallChatroomMessage: recallChatroomMessage, setChatRoomEntry: setChatRoomEntry, forceSetChatRoomEntry: forceSetChatRoomEntry, removeChatRoomEntry: removeChatRoomEntry, forceRemoveChatRoomEntry: forceRemoveChatRoomEntry, getChatRoomEntry: getChatRoomEntry, getAllChatRoomEntries: getAllChatRoomEntries, getLastCacheMsgSentTime: getLastCacheMsgSentTime, getLastCacheMsgUId: getLastCacheMsgUId, getLastCacheMsgDirection: getLastCacheMsgDirection, msgEmitter: CacheMsg.eventEmitter, changeUser: changeUser, joinRTCRoom: joinRTCRoom, quitRTCRoom: quitRTCRoom, pingRTCRoom: pingRTCRoom, setRTCData: setRTCData, getRTCData: getRTCData, removeRTCData: removeRTCData, getRTCToken: getRTCToken, getRTCRoomInfo: getRTCRoomInfo, getRTCUserInfoList: getRTCUserInfoList, setRTCUserInfo: setRTCUserInfo, removeRTCUserInfo: removeRTCUserInfo, setConversationStatus: setConversationStatus, setMessageKV, updateMessageExpansion, removeMessageExpansion, removeMessageAllExpansion, im }; })(window); ================================================ FILE: api-test-v4/js/common/utils.js ================================================ (function (win) { var Defer = win.Promise || ES6Promise; var Vue = win.Vue; var TypeColor = { FAILED: '#ed4014', MSG: '#2db7f5', STATUS: '#ff9900' }; var ConversationName = { 1: '单聊', 3: '群聊', 4: '聊天室', 5: '客服', 6: '系统', 7: '公众号', 8: '公众号' }; var StatusName = { 0: '已连接', 1: '正在链接', 2: '主动断开链接', 3: '网络不可用', 4: '链接关闭', 5: 'Socket Error', 6: '其他设备登录, 被踢', 12: '被封禁', 20: 'AppKey 错误', 201: '正在请求 Navi', 202: '请求 Navi 成功', 203: '请求 Navi 错误', 204: '请求 Navi 超时' }; var SuccessStatus = [0, 1, 2, 4, 201, 202, 203, 204]; var noop = function () {}; function isObject(obj) { return Object.prototype.toString.call(obj) === '[object Object]'; } function isArray(arr) { return Object.prototype.toString.call(arr) === '[object Array]'; } function isNodeList(arr) { return Object.prototype.toString.call(arr) === '[object NodeList]' || Object.prototype.toString.call(arr) === '[object HTMLCollection]'; } function isFunction(arr) { return Object.prototype.toString.call(arr) === '[object Function]'; } function isString(str) { return Object.prototype.toString.call(str) === '[object String]'; } function isBoolean(str) { return Object.prototype.toString.call(str) === '[object Boolean]'; } function isUndefined(str) { return Object.prototype.toString.call(str) === '[object Undefined]'; } function isNull(str) { return Object.prototype.toString.call(str) === '[object Null]'; } function isNumber(str) { return Object.prototype.toString.call(str) === '[object Number]'; } function defered(callback) { return new Defer(callback); } function isEmpty(val) { let result = true; if (isObject(val)) { forEach(val, () => { result = false; }); } if (isString(val) || isArray(val)) { result = val.length === 0; } if (isNumber(val)) { result = val === 0; } return result; } function tplEngine(temp, data, regexp) { var replaceAction = function (object) { return temp.replace(regexp || (/{([^}]+)}/g), function (match, name) { if (match.charAt(0) === '\\') return match.slice(1); return (object[name] !== undefined) ? object[name] : '{' + name + '}'; }); }; if (!(Object.prototype.toString.call(data) === '[object Array]')) data = [data]; var ret = []; for (var i = 0, j = data.length; i < j; i++) { ret.push(replaceAction(data[i])); } return ret.join(''); } function forEach(obj, callback, options) { options = options || {}; callback = callback || noop; var isReverse = options.isReverse; var loopObj = function() { for (var key in obj) { callback(obj[key], key, obj); } }; var loopArr = function() { if (isReverse) { for (var i = obj.length - 1; i >= 0; i--) { callback(obj[i], i); } } else { for (var j = 0, len = obj.length; j < len; j++) { callback(obj[j], j); } } }; if (isObject(obj)) { loopObj(); } if (isArray(obj) || isNodeList(obj)) { loopArr(); } }; function clearUndefKey(obj) { forEach(obj, function (key, val) { if (isUndefined(val)) { delete obj[key]; } }); return obj; } function map(arr, event) { forEach(arr, function(item, index) { arr[index] = event(item, index); }); return arr; } function deepMap(arr, event) { forEach(arr, function (item, index) { if (isArray(item) || isObject(item)) { arr[index] = deepMap(item, event); } else { arr[index] = event(item, index); } }); return arr; } function isEqual(obj1, obj2) { if (isObject(obj1) && isObject(obj2)) { var isEq = true; forEach(obj1, function (val, key) { if (obj2[key] !== val) { isEq = false; } }); return isEq; } else { return obj1 == obj2; } } function getDom(id) { return document.getElementById(id); } function queryAllDom(sel) { return document.querySelectorAll(sel); } function queryDom(sel) { return document.querySelector(sel); } function removeDom(dom) { var parent = dom.parentNode || dom.parentElement; parent.removeChild(dom); } function getParent(dom) { return dom.parentNode || dom.parentElement; } function getChildren(dom) { return dom.children; } function getTemp(id) { var dom = getDom(id); return dom.innerHTML; } function getDomIndex(dom) { var parent = getParent(dom); var children = parent.children; for (var i = 0, max = children.length; i < max; i++) { var child = children[i]; if (dom === child) { return i; } } return -1; } function toJSON(obj) { return JSON.stringify(obj); } function parseJSON(str) { var val; try { val = JSON.parse(str); } catch(e) {} return val; } function copy(obj) { var copyObj = parseJSON(toJSON(obj)); return copyObj; } function hasClass(el, className) { if (!el) { return false; } var classList = el.classList; for (var i = 0, max = classList.length; i < max; i++) { if (classList[i] === className) { return true; } } return false; } function timestampToString(timestamp) { var date = timestamp ? new Date(timestamp) : new Date(); Y = date.getFullYear() + '-'; M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'; D = date.getDate() + ' '; h = date.getHours() + ':'; m = date.getMinutes() + ':'; s = date.getSeconds(); return Y + M + D + h + m + s; } function extend(destination, sources) { for (var key in sources) { var value = sources[key]; if (!isUndefined(value)) { destination[key] = value; } } return destination; }; /** * 封装弹框组件 * @param {object} options */ function mountDialog(options, instance) { options.parent = instance; var Dialog = Vue.extend(options); var instance = new Dialog({ el: document.createElement('div') }); var wrap = document.getElementsByTagName('body')[0]; wrap.appendChild(instance.$el); return instance; } function reverse(obj) { var newObj = copy(obj); return newObj.reverse(); } function openUrl(url) { window.open(url); } function getBase64Image() { var canvas = document.createElement('canvas'); canvas.width = 100; canvas.height = 100; var context = canvas.getContext('2d'); context.font = '20pt Arial'; context.fillStyle = 'blue'; context.fillText('RongCloud.cn', 10, 20); var content = canvas.toDataURL('image/jpeg'); content = content.replace('data:image/jpeg;base64,', ''); return content; } var increaseNumber = 0; function getIncreasNumber() { return ++increaseNumber; } var EventEmitter = function () { this._events = {}; this.on = function (name, event) { var _events = this._events[name] || []; _events.push(event); this._events[name] = _events; }; this.emit = function (name, data) { var _events = this._events[name]; forEach(_events, function(event) { event(data); }); }; }; var Storage = { ConfigKey: 'config', get: function (key) { var str = localStorage.getItem(key); return parseJSON(str); }, set: function (key, val) { var str = toJSON(val); localStorage.setItem(key, str); } }; function getUrlQuery() { var url = location.search; //获取url中"?"符后的字串 var theRequest = new Object(); if (url.indexOf('?') != -1) { var str = url.substr(1); strs = str.split('&'); for (var i = 0; i < strs.length; i++) { theRequest[strs[i].split('=')[0]] = unescape(strs[i].split('=')[1]); } } return theRequest; } function getRCUrlQuery() { var theRequest = getUrlQuery(); var transMap = { 'true': true, 'false': false }; map(theRequest, function (val, key) { var transVal = transMap[val]; if (!isUndefined(transVal)) { val = transVal; } return val; }); forEach(theRequest, function (val, key) { if (key === 'encodeToken') { theRequest.token = decodeURIComponent(val); delete theRequest.encodeToken; } if (key === 'isMini') { delete theRequest.isMini; } }); return theRequest; } function deferNoop() { return Defer.resolve(); } win.RongIM = win.RongIM || {}; win.RongIM.Utils = { Storage: Storage, TypeColor: TypeColor, ConversationName: ConversationName, StatusName: StatusName, SuccessStatus: SuccessStatus, EventEmitter: EventEmitter, noop: noop, isNumber: isNumber, isFunction: isFunction, map: map, deepMap: deepMap, isEqual: isEqual, clearUndefKey: clearUndefKey, Defer: Defer, defered: defered, tplEngine: tplEngine, forEach: forEach, toJSON: toJSON, parseJSON: parseJSON, copy: copy, removeDom: removeDom, getParent: getParent, getChildren: getChildren, hasClass: hasClass, getDomIndex: getDomIndex, timestampToString: timestampToString, extend: extend, reverse: reverse, openUrl: openUrl, getBase64Image: getBase64Image, getIncreasNumber: getIncreasNumber, getDom: getDom, queryDom: queryDom, queryAllDom: queryAllDom, getTemp: getTemp, mountDialog: mountDialog, getUrlQuery: getUrlQuery, getRCUrlQuery: getRCUrlQuery, deferNoop: deferNoop, isEmpty: isEmpty, }; })(window); ================================================ FILE: api-test-v4/js/components/button.js ================================================ (function (win, dependencies, components) { var Vue = dependencies.Vue, RongIM = dependencies.RongIM, utils = RongIM.Utils, Service = RongIM.Service; var OutputMark = { SUCCESS: '成功', FAILED: '失败' }; var copyApi = function (api) { var params = api.params || []; var copyParams = utils.copy(params); utils.forEach(params, function (item, index) { utils.forEach(item, function (val, key) { if (utils.isFunction(val)) { copyParams[index][key] = val; } }); }); api.params = copyParams; return api; }; components.apiBtn = Vue.component('api-btn', { template: utils.getTemp('rong-tpl-apibtn'), props: ['api', 'isdragging'], data: function() { return { isShowEditDialog: false, selfApi: copyApi(this.api), isOpen: false } }, watch: { markMessage: function (newMsg) { console.log(newMsg); } }, computed: { tip: function() { var api = this.selfApi; return utils.tplEngine(TipTpl, api); }, apiValue: function() { var api = this.selfApi; return utils.toJSON(api); }, paramList: function () { var paramList = this.selfApi.params; return paramList; }, hasParams: function () { var params = this.selfApi.params; return params && params.length; } }, methods: { openUrl: utils.openUrl, showEditDialog: function() { this.isShowEditDialog = true; }, hideEditDialog: function() { this.isShowEditDialog = false; }, change: function() { }, run: function() { var self = this; var params = []; var startTime = +new Date(); if(self.api.eventName === "setMessageKV") { console.warn('send msg kv'); this.isOpen = true; return; } utils.forEach(self.selfApi.params, function(item) { if (item.type === 'number') { item.value = Number(item.value); } params.push(item.value); }); var imInstance = RongIM.vueInstance; var addOutput = function(data, isSuccess) { var currentTime = +new Date(); var consumedTime = currentTime - startTime; var title = self.api.name + (isSuccess ? OutputMark.SUCCESS : OutputMark.FAILED); var config = {}; if (!isSuccess) { config.color = utils.TypeColor.FAILED; } self.hideEditDialog(); return imInstance.addOutput(title, data, consumedTime, params, config); }; return self.api.event.apply(void 0, params).then(function(data) { data = addOutput(data, true); return { isSuccess: true, data: data }; }).catch(function(errorInfo) { // TODO 报警 // error = utils.isNumber(error) ? error : error.toString(); var data = addOutput(errorInfo, false); return { isSuccess: false, data: data }; }); } }, mounted: function() { var self = this; var setParams = function () { var paramList = self.selfApi.params; utils.forEach(paramList, function (item) { if (item.event) { item.value = item.value || item.event(); } }); }; setParams(); Service.msgEmitter.on('msgChanged', setParams); } }); })(window, { Vue: Vue, iview: iview, RongIM: RongIM }, window.RongIM.components); ================================================ FILE: api-test-v4/js/components/json-alert.js ================================================ (function (win, dependencies) { var RongIM = dependencies.RongIM; var utils = RongIM.Utils; RongIM.dialog = RongIM.dialog || {}; RongIM.dialog.jsonAlert = function(options) { var vueInstance = RongIM.vueInstance; options = options || {}; utils.mountDialog({ name: 'json-alert', template: '#rong-json-alert', data: function () { return { isShow: true, data: options.data }; }, watch: { isShow: function(isShow) { if (!isShow) { utils.removeDom(this.$el); } } }, methods: { hide: function() { this.isShow = false; } } }, vueInstance); }; })(window, { RongIM: RongIM }); ================================================ FILE: api-test-v4/js/components/msg-expansion.js ================================================ (function (win, dependencies, components) { var Vue = dependencies.Vue, RongIM = dependencies.RongIM, utils = RongIM.Utils, Service = RongIM.Service; components.apiExpansion = Vue.component('api-expansion', { template: utils.getTemp('rong-tpl-expansion'), props: ['isOpen'], data: function() { return { isOpen: true, } }, watch: { isOpen: function (val, newval) { console.warn(val, newval); } }, computed: { }, methods: { }, mounted: function() { console.warn('msg-expansion'); } }); })(window, { Vue: Vue, iview: iview, RongIM: RongIM }, window.RongIM.components); ================================================ FILE: api-test-v4/js/login.js ================================================ (function (win, dependencies, components) { var Vue = dependencies.Vue, RongIM = dependencies.RongIM, utils = RongIM.Utils, isDebug = RongIM.config.isDebug, debugConf = RongIM.config.debugConf; var ConfigPlacehoder = { appkey: '开发者的融云 AppKey', token: '开发者的用户 Token', targetId: '对方 id. 发消息、获取历史消息等都默认对此用户操作. 默认聊天室、群组、个人 id 都为此 id', navi: '导航地址. 注: 国内数据中心可不填', customCMP: '链接地址(开发者忽略此项)', isPolling: '若使用长轮训链接方式, 可选择此项(开发者可忽略)' }; components.login = Vue.component('login', { template: utils.getTemp('rong-global-config'), props: ['config', 'login'], computed: { configList: function() { var items = []; utils.forEach(this.config, function(val, key) { items.push({ type: typeof val, name: key }); }); return items; }, prompt: function() { return ConfigPlacehoder; } }, methods: { clearStorage: function () { window.localStorage.clear(); this.$Message.success({ background: true, content: '清空本地缓存成功' }); } }, mounted: function () { if (isDebug && debugConf.autoRun) { var self = this; Vue.nextTick(function () { self.login(self.config); }); } } }); })(window, { Vue: Vue, iview: iview, RongIM: RongIM }, window.RongIM.components); ================================================ FILE: api-test-v4/js/main.js ================================================ (function (win, dependencies, components) { var Vue = dependencies.Vue, iview = dependencies.iview, VueJsonPretty = dependencies.VueJsonPretty, RongIM = dependencies.RongIM, Service = RongIM.Service, utils = RongIM.Utils, ApiList = RongIM.ApiList, DefailtReadyApiQueue = RongIM.DefailtReadyApiQueue, DefaultConfig = RongIM.config.im, Config = utils.copy(DefaultConfig), Storage = utils.Storage, StorageConfig = Storage.get(Storage.ConfigKey), DefaultTargetId = Config.targetId, isDebug = RongIM.config.isDebug, debugConf = RongIM.config.debugConf; DefailtReadyApiQueue.push([]); var ValidStatus = [0, 1, 2, 6, 201, 202]; var ValidErrorCode = [23424, 23427, 23426, 23423]; var isStop = false; var isStorageConfig = false; if (StorageConfig && !isDebug) { isStorageConfig = true; Config = utils.copy(StorageConfig); } var urlQueryConfig = utils.getRCUrlQuery(); Config = utils.extend(Config, urlQueryConfig); var ReceiveMsgTextTpl = '监听到{typeName} ({conversationType})消息. 发送者: {senderUserId}'; var StatusTextTpl = '链接状态: {statusName} ({status})'; var OptBoxClass = 'rong-ready-box'; var ApiBoxClass = 'rong-api-list'; var ApiSourceClass = 'rong-api-source'; var RunType = { OneByOne: { name: '逐个运行', prompt: 'Api 逐个执行' }, LineByLine: { name: '逐行运行', prompt: '每行 Api 并行. 执行完一行后执行下一行' } }; var vueInstance; function runAllApi(allRefs, currentIndex, finishCallback) { var total = allRefs.length; var isFinished = total === currentIndex || isStop; if (isFinished) { return finishCallback && finishCallback(); } var refList = allRefs[currentIndex]; var deferArr = []; utils.forEach(refList, function (instance) { deferArr.push(instance.run()); }); return utils.Defer.all(deferArr).then(function (result) { result = result[0]; var isSuccess = result.isSuccess || ValidErrorCode.indexOf(result.data.result) !== -1; if (isSuccess) { vueInstance.runInfo.successApiCount++; } else { vueInstance.runInfo.failApiList.push(result.data); } currentIndex++; runAllApi(allRefs, currentIndex, finishCallback); }); } function runOneByOne(finishCallback) { var refs = vueInstance.$refs; var allRefs = []; utils.forEach(refs, function (subRefList) { utils.forEach(subRefList, function (ref) { allRefs.push([ ref ]); }); }); runAllApi(allRefs, 0, finishCallback); } function runLineByLine(finishCallback) { var refs = vueInstance.$refs; var allRefs = []; utils.forEach(refs, function (ins) { allRefs.push(ins); }); runAllApi(allRefs, 0, finishCallback); } function setConfig(config) { var currentTargetId = config.targetId; vueInstance.globalConfig = config; vueInstance.readyApiQueue = utils.deepMap(vueInstance.readyApiQueue, function (item) { if (item === DefaultTargetId) { item = currentTargetId; } return item; }); } function watchStatus(status) { var title = utils.tplEngine(StatusTextTpl, { status: status, statusName: utils.StatusName[status] }); var output = vueInstance.addOutput(title, status, 0, [], { color: utils.TypeColor.STATUS }); if (ValidStatus.indexOf(status) === -1) { vueInstance.runInfo.failApiList.push(output); } var isSuccess = utils.SuccessStatus.indexOf(status) !== -1; var event = isSuccess ? vueInstance.$Message.success : vueInstance.$Message.error; event.call(vueInstance.$Message, { background: true, content: title }); } function watchMessage(message) { if (RongIM.config.isDebug && !RongIM.config.debugConf.isShowMsg) { return; } var title = utils.tplEngine(ReceiveMsgTextTpl, { typeName: utils.ConversationName[message.type], conversationType: message.type, senderUserId: message.senderUserId }); vueInstance.addOutput(title, message, 0, [], { color: utils.TypeColor.MSG }); console.log('Reveice Msg', utils.toJSON(message)); } function watchChatroom(entries) { vueInstance.addOutput('监听到聊天室 KV 更新', entries, 0, [], { color: utils.TypeColor.MSG }); } function innerEl(text) { var newEl = document.createElement('p'); newEl.innerText = text; newEl.style = "border-bottom: 1px sloid #333"; var exEl = document.getElementById('rong-ex-content'); if(exEl) { var exElLen = exEl.childNodes.length; if(exElLen == 0) { exEl.appendChild(newEl); }else { exEl.insertBefore(newEl, exEl.childNodes[exElLen-1].nextSibling); } } } function watchExpansion(event) { console.warn(event); var updatedExpansion = event.updatedExpansion; var deletedExpansion = event.deletedExpansion; vueInstance.addOutput('监听到消息 KV 变更', event, 0, [], { color: utils.TypeColor.MSG }); if(updatedExpansion){ var time = utils.timestampToString(updatedExpansion.updatedTime), expansion = updatedExpansion.expansion, msgUId = updatedExpansion.messageUId; innerEl(`${time}: 监听更新, msgUId: ${msgUId}, expansion: ${JSON.stringify(expansion)}`) } if(deletedExpansion){ var time = utils.timestampToString(deletedExpansion.updatedTime), keys = deletedExpansion.deletedKeys, msgUId = deletedExpansion.messageUId; innerEl(`${time}: 监听删除, keys: ${keys} | msgUId: ${msgUId}`) } } function autoRun() { Vue.nextTick(function () { runOneByOne(function () { vueInstance.runInfo.runCount++; localStorage.removeItem('rong_servers'); localStorage.removeItem('rong_fullnavi'); vueInstance.outputList = []; vueInstance.allOutputList = []; !isStop && autoRun(); }); }); } function loginSuccessEvent(userId, config) { vueInstance.$Message.success({ background: true, content: '链接成功 ' + userId }); vueInstance.currentUserId = userId; vueInstance.isLogged = true; if (isDebug && debugConf.autoRun) { Vue.nextTick(autoRun); } } function login(config) { setConfig(config); return Service.init(config, { status: watchStatus, message: watchMessage, chatroom: watchChatroom, expansion: watchExpansion }).then(function (userId) { Storage.set(Storage.ConfigKey, config); loginSuccessEvent(userId.id, config); }).catch(function (error) { console.log(error); vueInstance.$Message.error({ background: true, content: '链接失败 ' + JSON.stringify(error) }); return utils.Defer.reject(); }); } function getApiListMethods() { return { addOutput: function (title, result, consumedTime, params, config) { config = config || {}; var output = { id: utils.getIncreasNumber(), title: title, result: result, consumedTime: consumedTime, params: params, config: config }; output.time = utils.timestampToString(); vueInstance.allOutputList.push(output); vueInstance.outputList.push(output); return output; }, clearOutput: function () { vueInstance.outputList = []; }, showAllOutput: function () { vueInstance.outputList = vueInstance.allOutputList; }, toJSON: function (data) { return utils.toJSON(data); }, showJSONAlert: function(data) { RongIM.dialog.jsonAlert({ data: data }); }, runAllApi: function() { if (vueInstance.runType === 'OneByOne') { runOneByOne(); } else { runLineByLine(); } }, startDragging: function () { setTimeout(function() { vueInstance.isDragging = true; }, 100); } }; } function getServiceMethods() { return { openUrl: utils.openUrl, reverse: utils.reverse, login: function(config) { var isEqualStorage = utils.isEqual(config, StorageConfig); var isEqualDefault = utils.isEqual(config, DefaultConfig); if (isStorageConfig && isEqualStorage && !isEqualDefault && !isDebug) { vueInstance.$Modal.confirm({ title: '注意', content: '您目前使用的为上一次链接配置, 请确定配置是否可用 ?', onOk: function () { login(config); } }); } else { return login(config); } }, alarm: function () { if (!this.isAlarmMuted) { vueInstance.$refs.alarm.play(); } }, mute: function () { vueInstance.$refs.alarm.pause(); }, showMsgExpansion: function() { if(vueInstance.openMsgEx) { vueInstance.openMsgEx = false; }else { vueInstance.openMsgEx = true; } var data = vueInstance.exData; data.joinBtn = true; data.setBtn = data.showInputBtn = data.showId = data.showUId = data.showKey = data.showVal = data.showMsg = false; }, exJoin(type) { var data = vueInstance.exData; data.type = type; data.showInputBtn = data.showId = data.setBtn = true; data.joinBtn = false; data.exeEvent = () => { var type = data.type === 1 ? '单聊' : '群聊'; var time = utils.timestampToString(new Date().getTime()); innerEl(`时间:${time}加入${type}${data.targetId}成功`) } }, setKey() { var data = vueInstance.exData; data.showId = data.showMsg = false; data.showUId = data.showKey = data.showVal = true; var time = utils.timestampToString(new Date().getTime()); data.exeEvent = () => { var type = data.type; var targetId = data.targetId; var msgUId = data.msgUId; Service.updateMessageExpansion(type, targetId, msgUId, data.msgKeys, data.msgValues, data.canIncludeExpansion, true).then(()=> { innerEl(`时间:${time}设置成功`) },(rea) => { innerEl(`时间:${time}设置失败, ${JSON.stringify(rea)}`); }); } }, delKey() { var data = vueInstance.exData; data.showId = data.showVal = data.showMsg = false; data.showUId = data.showKey = true; data.exeEvent = () => { var type = data.type; var targetId = data.targetId; var msgUId = data.msgUId; var keys = data.msgKeys; var time = utils.timestampToString(new Date().getTime()); Service.removeMessageExpansion(type, targetId, keys, msgUId, data.canIncludeExpansion, true).then(()=> { innerEl(`时间:${time}删除成功`) },(rea) => { innerEl(`时间:${time}删除失败, ${JSON.stringify(rea)}`); }); } }, delAllKey() { var data = vueInstance.exData; data.showId = data.showVal = data.showMsg = false; data.showUId = data.showKey = true; data.exeEvent = () => { var type = data.type; var targetId = data.targetId; var msgUId = data.msgUId; var time = utils.timestampToString(new Date().getTime()); Service.removeMessageAllExpansion(type, targetId, msgUId).then(()=> { innerEl(`时间:${time}删除成功`) },(rea) => { innerEl(`时间:${time}删除失败, ${JSON.stringify(rea)}`); }); } }, getList() { var data = vueInstance.exData; data.exeEvent = () => { var type = data.type; var targetId = data.targetId; Service.getHistoryMessages(0, 20, type, targetId).then((list) => { RongIM.dialog.jsonAlert({ data: list }); },rea => { }) } }, sendMsg() { var data = vueInstance.exData; data.showId = data.showUId = data.showKey = data.showVal = false; data.showMsg = true; var data = vueInstance.exData; data.exeEvent = () => { console.log('发送消息成功', data.msgContent); } }, exConfirm() { var data = vueInstance.exData; data.exeEvent(); }, exCancel() { //置空 console.log('取消成功'); }, }; } Vue.use(iview); vueInstance = new Vue({ el: '#app', data: function() { return { currentUserId: '', isLogged: false, readyApiQueue: DefailtReadyApiQueue, allOutputList: [], outputList: [], globalConfig: Config, RunType: RunType, runType: 'OneByOne', alertJSON: null, isDragging: false, isShowRunType: false, isShowOutList: false, isDebug: RongIM.config.isDebug, runInfo: { runCount: 0, successApiCount: 0, failApiList: [] }, isAlarmMuted: false, openMsgEx: false, exData: { title: 'sdfsdf', exeEvent: null, type: null, targetId: null, joinBtn: true, showInputBtn: false, setBtn: false, showId: false, showUId: false, showKey: false, showVal: false, showMsg: false, targetId: null, msgUId: null, msgKeys: null, msgValues: null, msgContent: null, canIncludeExpansion: true, } }; }, computed: { apiList: function() { return ApiList; }, changeUserApi: function () { var self = this; var changeUserApi = RongIM.Api.changeUser; var changeUserEvent = changeUserApi.event; changeUserApi.event = function (token) { var globalConfig = self.globalConfig globalConfig.token = token; return Service.changeUser(globalConfig, { status: watchStatus, message: watchMessage, expansion: watchExpansion }).then(function (userId) { loginSuccessEvent(userId, globalConfig); }).catch(function () { vueInstance.$Message.error({ background: true, content: '切换用户失败 ' + error }); }); }; return changeUserApi; }, currentOutput: function() { var outputList = this.outputList; if (outputList.length) { return outputList[outputList.length - 1]; } }, displayedOutputList: function () { if (isDebug) { return this.runInfo.failApiList; } else { return this.outputList; } } }, watch: { 'runInfo.failApiList': function (newList) { if (newList.length > 20) { this.alarm(); } }, isAlarmMuted: function (isMuted) { if (isMuted) { this.mute(); } } }, components: { apiBtn: components.apiBtn, login: components.login, apiExpansion: components.apiExpansion, prettyjson: Vue.component('prettyjson', VueJsonPretty.default) }, mounted: function() { this.isPageLoaded = true; }, methods: utils.extend(getApiListMethods(), getServiceMethods()) }); RongIM.vueInstance = vueInstance; (function () { function start() { isStop = false; if (vueInstance.isLogged) { autoRun(); } else { vueInstance.login(vueInstance.globalConfig).then(autoRun); } } window.addEventListener("message", function (event) { var type = event.data; if (type === 'start') { start(); } else if (type === 'pause') { isStop = true; } }, false); })(); })(window, { Vue: Vue, iview: iview, VueJsonPretty: VueJsonPretty, RongIM: RongIM }, window.RongIM.components); ================================================ FILE: api-test-v4/lib/js/RongIMLib-4.1.0.js ================================================ /** * @rongcloud/imlib-v4 * Version: v4.1.0 * CommitId: 0012eb74bbf7318ea4a4e2ee3e3e858d6849090c * Date: Mon Dec 28 2020 11:08:22 GMT+0800 (China Standard Time) * ©2020 RongCloud, Inc. All rights reserved. */ var RongIMLib = (function (exports) { 'use strict'; /*! ***************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */ function __awaiter(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); } function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function (obj) { return typeof obj; }; } else { _typeof = function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } function _construct(Parent, args, Class) { if (_isNativeReflectConstruct()) { _construct = Reflect.construct; } else { _construct = function _construct(Parent, args, Class) { var a = [null]; a.push.apply(a, args); var Constructor = Function.bind.apply(Parent, a); var instance = new Constructor(); if (Class) _setPrototypeOf(instance, Class.prototype); return instance; }; } return _construct.apply(null, arguments); } function _isNativeFunction(fn) { return Function.toString.call(fn).indexOf("[native code]") !== -1; } function _wrapNativeSuper(Class) { var _cache = typeof Map === "function" ? new Map() : undefined; _wrapNativeSuper = function _wrapNativeSuper(Class) { if (Class === null || !_isNativeFunction(Class)) return Class; if (typeof Class !== "function") { throw new TypeError("Super expression must either be null or a function"); } if (typeof _cache !== "undefined") { if (_cache.has(Class)) return _cache.get(Class); _cache.set(Class, Wrapper); } function Wrapper() { return _construct(Class, arguments, _getPrototypeOf(this).constructor); } Wrapper.prototype = Object.create(Class.prototype, { constructor: { value: Wrapper, enumerable: false, writable: true, configurable: true } }); return _setPrototypeOf(Wrapper, Class); }; return _wrapNativeSuper(Class); } function _newArrowCheck(innerThis, boundThis) { if (innerThis !== boundThis) { throw new TypeError("Cannot instantiate an arrow function"); } } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _possibleConstructorReturn(self, call) { if (call && (typeof call === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; } function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); } function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var runtime = function (exports) { var Op = Object.prototype; var hasOwn = Op.hasOwnProperty; var undefined$1; var $Symbol = typeof Symbol === "function" ? Symbol : {}; var iteratorSymbol = $Symbol.iterator || "@@iterator"; var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator"; var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; function define(obj, key, value) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); return obj[key]; } try { define({}, ""); } catch (err) { define = function define(obj, key, value) { return obj[key] = value; }; } function wrap(innerFn, outerFn, self, tryLocsList) { var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator; var generator = Object.create(protoGenerator.prototype); var context = new Context(tryLocsList || []); generator._invoke = makeInvokeMethod(innerFn, self, context); return generator; } exports.wrap = wrap; function tryCatch(fn, obj, arg) { try { return { type: "normal", arg: fn.call(obj, arg) }; } catch (err) { return { type: "throw", arg: err }; } } var GenStateSuspendedStart = "suspendedStart"; var GenStateSuspendedYield = "suspendedYield"; var GenStateExecuting = "executing"; var GenStateCompleted = "completed"; var ContinueSentinel = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var IteratorPrototype = {}; IteratorPrototype[iteratorSymbol] = function () { return this; }; var getProto = Object.getPrototypeOf; var NativeIteratorPrototype = getProto && getProto(getProto(values([]))); if (NativeIteratorPrototype && NativeIteratorPrototype !== Op && hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) { IteratorPrototype = NativeIteratorPrototype; } var Gp = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(IteratorPrototype); GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype; GeneratorFunctionPrototype.constructor = GeneratorFunction; GeneratorFunction.displayName = define(GeneratorFunctionPrototype, toStringTagSymbol, "GeneratorFunction"); function defineIteratorMethods(prototype) { ["next", "throw", "return"].forEach(function (method) { define(prototype, method, function (arg) { return this._invoke(method, arg); }); }); } exports.isGeneratorFunction = function (genFun) { var ctor = typeof genFun === "function" && genFun.constructor; return ctor ? ctor === GeneratorFunction || (ctor.displayName || ctor.name) === "GeneratorFunction" : false; }; exports.mark = function (genFun) { if (Object.setPrototypeOf) { Object.setPrototypeOf(genFun, GeneratorFunctionPrototype); } else { genFun.__proto__ = GeneratorFunctionPrototype; define(genFun, toStringTagSymbol, "GeneratorFunction"); } genFun.prototype = Object.create(Gp); return genFun; }; exports.awrap = function (arg) { return { __await: arg }; }; function AsyncIterator(generator, PromiseImpl) { function invoke(method, arg, resolve, reject) { var record = tryCatch(generator[method], generator, arg); if (record.type === "throw") { reject(record.arg); } else { var result = record.arg; var value = result.value; if (value && _typeof(value) === "object" && hasOwn.call(value, "__await")) { return PromiseImpl.resolve(value.__await).then(function (value) { invoke("next", value, resolve, reject); }, function (err) { invoke("throw", err, resolve, reject); }); } return PromiseImpl.resolve(value).then(function (unwrapped) { result.value = unwrapped; resolve(result); }, function (error) { return invoke("throw", error, resolve, reject); }); } } var previousPromise; function enqueue(method, arg) { function callInvokeWithMethodAndArg() { return new PromiseImpl(function (resolve, reject) { invoke(method, arg, resolve, reject); }); } return previousPromise = previousPromise ? previousPromise.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } this._invoke = enqueue; } defineIteratorMethods(AsyncIterator.prototype); AsyncIterator.prototype[asyncIteratorSymbol] = function () { return this; }; exports.AsyncIterator = AsyncIterator; exports.async = function (innerFn, outerFn, self, tryLocsList, PromiseImpl) { if (PromiseImpl === void 0) PromiseImpl = Promise; var iter = new AsyncIterator(wrap(innerFn, outerFn, self, tryLocsList), PromiseImpl); return exports.isGeneratorFunction(outerFn) ? iter : iter.next().then(function (result) { return result.done ? result.value : iter.next(); }); }; function makeInvokeMethod(innerFn, self, context) { var state = GenStateSuspendedStart; return function invoke(method, arg) { if (state === GenStateExecuting) { throw new Error("Generator is already running"); } if (state === GenStateCompleted) { if (method === "throw") { throw arg; } return doneResult(); } context.method = method; context.arg = arg; while (true) { var delegate = context.delegate; if (delegate) { var delegateResult = maybeInvokeDelegate(delegate, context); if (delegateResult) { if (delegateResult === ContinueSentinel) continue; return delegateResult; } } if (context.method === "next") { context.sent = context._sent = context.arg; } else if (context.method === "throw") { if (state === GenStateSuspendedStart) { state = GenStateCompleted; throw context.arg; } context.dispatchException(context.arg); } else if (context.method === "return") { context.abrupt("return", context.arg); } state = GenStateExecuting; var record = tryCatch(innerFn, self, context); if (record.type === "normal") { state = context.done ? GenStateCompleted : GenStateSuspendedYield; if (record.arg === ContinueSentinel) { continue; } return { value: record.arg, done: context.done }; } else if (record.type === "throw") { state = GenStateCompleted; context.method = "throw"; context.arg = record.arg; } } }; } function maybeInvokeDelegate(delegate, context) { var method = delegate.iterator[context.method]; if (method === undefined$1) { context.delegate = null; if (context.method === "throw") { if (delegate.iterator["return"]) { context.method = "return"; context.arg = undefined$1; maybeInvokeDelegate(delegate, context); if (context.method === "throw") { return ContinueSentinel; } } context.method = "throw"; context.arg = new TypeError("The iterator does not provide a 'throw' method"); } return ContinueSentinel; } var record = tryCatch(method, delegate.iterator, context.arg); if (record.type === "throw") { context.method = "throw"; context.arg = record.arg; context.delegate = null; return ContinueSentinel; } var info = record.arg; if (!info) { context.method = "throw"; context.arg = new TypeError("iterator result is not an object"); context.delegate = null; return ContinueSentinel; } if (info.done) { context[delegate.resultName] = info.value; context.next = delegate.nextLoc; if (context.method !== "return") { context.method = "next"; context.arg = undefined$1; } } else { return info; } context.delegate = null; return ContinueSentinel; } defineIteratorMethods(Gp); define(Gp, toStringTagSymbol, "Generator"); Gp[iteratorSymbol] = function () { return this; }; Gp.toString = function () { return "[object Generator]"; }; function pushTryEntry(locs) { var entry = { tryLoc: locs[0] }; if (1 in locs) { entry.catchLoc = locs[1]; } if (2 in locs) { entry.finallyLoc = locs[2]; entry.afterLoc = locs[3]; } this.tryEntries.push(entry); } function resetTryEntry(entry) { var record = entry.completion || {}; record.type = "normal"; delete record.arg; entry.completion = record; } function Context(tryLocsList) { this.tryEntries = [{ tryLoc: "root" }]; tryLocsList.forEach(pushTryEntry, this); this.reset(true); } exports.keys = function (object) { var keys = []; for (var key in object) { keys.push(key); } keys.reverse(); return function next() { while (keys.length) { var key = keys.pop(); if (key in object) { next.value = key; next.done = false; return next; } } next.done = true; return next; }; }; function values(iterable) { if (iterable) { var iteratorMethod = iterable[iteratorSymbol]; if (iteratorMethod) { return iteratorMethod.call(iterable); } if (typeof iterable.next === "function") { return iterable; } if (!isNaN(iterable.length)) { var i = -1, next = function next() { while (++i < iterable.length) { if (hasOwn.call(iterable, i)) { next.value = iterable[i]; next.done = false; return next; } } next.value = undefined$1; next.done = true; return next; }; return next.next = next; } } return { next: doneResult }; } exports.values = values; function doneResult() { return { value: undefined$1, done: true }; } Context.prototype = { constructor: Context, reset: function reset(skipTempReset) { this.prev = 0; this.next = 0; this.sent = this._sent = undefined$1; this.done = false; this.delegate = null; this.method = "next"; this.arg = undefined$1; this.tryEntries.forEach(resetTryEntry); if (!skipTempReset) { for (var name in this) { if (name.charAt(0) === "t" && hasOwn.call(this, name) && !isNaN(+name.slice(1))) { this[name] = undefined$1; } } } }, stop: function stop() { this.done = true; var rootEntry = this.tryEntries[0]; var rootRecord = rootEntry.completion; if (rootRecord.type === "throw") { throw rootRecord.arg; } return this.rval; }, dispatchException: function dispatchException(exception) { if (this.done) { throw exception; } var context = this; function handle(loc, caught) { record.type = "throw"; record.arg = exception; context.next = loc; if (caught) { context.method = "next"; context.arg = undefined$1; } return !!caught; } for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; var record = entry.completion; if (entry.tryLoc === "root") { return handle("end"); } if (entry.tryLoc <= this.prev) { var hasCatch = hasOwn.call(entry, "catchLoc"); var hasFinally = hasOwn.call(entry, "finallyLoc"); if (hasCatch && hasFinally) { if (this.prev < entry.catchLoc) { return handle(entry.catchLoc, true); } else if (this.prev < entry.finallyLoc) { return handle(entry.finallyLoc); } } else if (hasCatch) { if (this.prev < entry.catchLoc) { return handle(entry.catchLoc, true); } } else if (hasFinally) { if (this.prev < entry.finallyLoc) { return handle(entry.finallyLoc); } } else { throw new Error("try statement without catch or finally"); } } } }, abrupt: function abrupt(type, arg) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc <= this.prev && hasOwn.call(entry, "finallyLoc") && this.prev < entry.finallyLoc) { var finallyEntry = entry; break; } } if (finallyEntry && (type === "break" || type === "continue") && finallyEntry.tryLoc <= arg && arg <= finallyEntry.finallyLoc) { finallyEntry = null; } var record = finallyEntry ? finallyEntry.completion : {}; record.type = type; record.arg = arg; if (finallyEntry) { this.method = "next"; this.next = finallyEntry.finallyLoc; return ContinueSentinel; } return this.complete(record); }, complete: function complete(record, afterLoc) { if (record.type === "throw") { throw record.arg; } if (record.type === "break" || record.type === "continue") { this.next = record.arg; } else if (record.type === "return") { this.rval = this.arg = record.arg; this.method = "return"; this.next = "end"; } else if (record.type === "normal" && afterLoc) { this.next = afterLoc; } return ContinueSentinel; }, finish: function finish(finallyLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.finallyLoc === finallyLoc) { this.complete(entry.completion, entry.afterLoc); resetTryEntry(entry); return ContinueSentinel; } } }, "catch": function _catch(tryLoc) { for (var i = this.tryEntries.length - 1; i >= 0; --i) { var entry = this.tryEntries[i]; if (entry.tryLoc === tryLoc) { var record = entry.completion; if (record.type === "throw") { var thrown = record.arg; resetTryEntry(entry); } return thrown; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(iterable, resultName, nextLoc) { this.delegate = { iterator: values(iterable), resultName: resultName, nextLoc: nextLoc }; if (this.method === "next") { this.arg = undefined$1; } return ContinueSentinel; } }; return exports; }((typeof module === "undefined" ? "undefined" : _typeof(module)) === "object" ? module.exports : {}); try { regeneratorRuntime = runtime; } catch (accidentalStrictMode) { Function("r", "regeneratorRuntime = r")(runtime); } var _this = undefined, _methods, _validators, _SSMsg, _PublishTopicToConver, _ConversationTypeToQu, _ConversationTypeToCl; var ReceivedStatus; (function (ReceivedStatus) { ReceivedStatus[ReceivedStatus["READ"] = 1] = "READ"; ReceivedStatus[ReceivedStatus["LISTENED"] = 2] = "LISTENED"; ReceivedStatus[ReceivedStatus["DOWNLOADED"] = 4] = "DOWNLOADED"; ReceivedStatus[ReceivedStatus["RETRIEVED"] = 8] = "RETRIEVED"; ReceivedStatus[ReceivedStatus["UNREAD"] = 0] = "UNREAD"; })(ReceivedStatus || (ReceivedStatus = {})); var ReceivedStatus$1 = ReceivedStatus; var NAVI_CACHE_DURATION = 2 * 60 * 60 * 1000; var NAVI_REQ_TIMEOUT = 10 * 1000; var PING_REQ_TIMEOUT = 5 * 1000; var WEB_SOCKET_TIMEOUT = 5 * 1000; var PUBLIC_CLOUD_NAVI_URIS = ['https://nav.cn.ronghub.com', 'https://nav2-cn.ronghub.com']; var MINI_SOCKET_CONNECT_URIS = ['wsproxy.cn.ronghub.com', 'wsap-cn.ronghub.com']; var MINI_COMET_CONNECT_URIS = ['cometproxy-cn.ronghub.com', 'mini-cn.ronghub.com']; var IM_SIGNAL_TIMEOUT = 30 * 1000; var IM_PING_INTERVAL_TIME = 30 * 1000; var MAX_MESSAGE_CONTENT_BYTES = 128 * 1024; var IM_COMET_PULLMSG_TIMEOUT = 45000; var STORAGE_ROOT_KEY = 'RCV4-'; var SEND_MESSAGE_TYPE_OPTION = { 'RC:TxtMsg': { isCounted: true, isPersited: true }, 'RC:ImgMsg': { isCounted: true, isPersited: true }, 'RC:VcMsg': { isCounted: true, isPersited: true }, 'RC:ImgTextMsg': { isCounted: true, isPersited: true }, 'RC:FileMsg': { isCounted: true, isPersited: true }, 'RC:HQVCMsg': { isCounted: true, isPersited: true }, 'RC:LBSMsg': { isCounted: true, isPersited: true }, 'RC:PSImgTxtMsg': { isCounted: true, isPersited: true }, 'RC:PSMultiImgTxtMsg': { isCounted: true, isPersited: true }, 'RCJrmf:RpMsg': { isCounted: true, isPersited: true }, 'RCJrmf:RpOpendMsg': { isCounted: true, isPersited: true }, 'RC:CombineMsg': { isCounted: true, isPersited: true }, 'RC:ReferenceMsg': { isCounted: true, isPersited: true }, 'RC:SightMsg': { isCounted: true, isPersited: true }, 'RC:InfoNtf': { isCounted: false, isPersited: true }, 'RC:ContactNtf': { isCounted: false, isPersited: true }, 'RC:ProfileNtf': { isCounted: false, isPersited: true }, 'RC:CmdNtf': { isCounted: false, isPersited: true }, 'RC:GrpNtf': { isCounted: false, isPersited: true }, 'RC:RcCmd': { isCounted: false, isPersited: true }, 'RC:CmdMsg': { isCounted: false, isPersited: false }, 'RC:TypSts': { isCounted: false, isPersited: false }, 'RC:PSCmd': { isCounted: false, isPersited: false }, 'RC:SRSMsg': { isCounted: false, isPersited: false }, 'RC:RRReqMsg': { isCounted: false, isPersited: false }, 'RC:RRRspMsg': { isCounted: false, isPersited: false }, 'RC:CsChaR': { isCounted: false, isPersited: false }, 'RC:CSCha': { isCounted: false, isPersited: false }, 'RC:CsEva': { isCounted: false, isPersited: false }, 'RC:CsContact': { isCounted: false, isPersited: false }, 'RC:CsHs': { isCounted: false, isPersited: false }, 'RC:CsHsR': { isCounted: false, isPersited: false }, 'RC:CsSp': { isCounted: false, isPersited: false }, 'RC:CsEnd': { isCounted: false, isPersited: false }, 'RC:CsUpdate': { isCounted: false, isPersited: false }, 'RC:ReadNtf': { isCounted: false, isPersited: false }, 'RC:chrmKVNotiMsg': { isCounted: false, isPersited: false }, 'RC:VCAccept': { isCounted: false, isPersited: false }, 'RC:VCRinging': { isCounted: false, isPersited: false }, 'RC:VCSummary': { isCounted: false, isPersited: false }, 'RC:VCHangup': { isCounted: false, isPersited: false }, 'RC:VCInvite': { isCounted: false, isPersited: false }, 'RC:VCModifyMedia': { isCounted: false, isPersited: false }, 'RC:VCModifyMem': { isCounted: false, isPersited: false }, 'RC:MsgExMsg': { isCounted: false, isPersited: false } }; var rootStorage; var createRootStorage = function createRootStorage(runtime) { var _this2 = this; _newArrowCheck(this, _this); if (!rootStorage) { rootStorage = { set: function set(key, val) { _newArrowCheck(this, _this2); runtime.localStorage.setItem(key, JSON.stringify(val)); }.bind(this), get: function get(key) { _newArrowCheck(this, _this2); var val; try { val = JSON.parse(runtime.localStorage.getItem(key)); } catch (e) { val = null; } return val; }.bind(this), remove: function remove(key) { _newArrowCheck(this, _this2); return runtime.localStorage.removeItem(key); }.bind(this), getKeys: function getKeys() { _newArrowCheck(this, _this2); var keys = []; for (var _key in runtime.localStorage) { keys.push(_key); } return keys; }.bind(this) }; } return rootStorage; }.bind(undefined); var AppCache = function () { function AppCache(value) { _classCallCheck(this, AppCache); this._caches = {}; if (value) { this._caches = value; } } _createClass(AppCache, [{ key: "set", value: function set(key, value) { this._caches[key] = value; } }, { key: "remove", value: function remove(key) { var val = this.get(key); delete this._caches[key]; return val; } }, { key: "get", value: function get(key) { return this._caches[key]; } }, { key: "getKeys", value: function getKeys() { var keys = []; for (var _key2 in this._caches) { keys.push(_key2); } return keys; } }]); return AppCache; }(); var AppStorage = function () { function AppStorage(runtime, suffix) { _classCallCheck(this, AppStorage); var key = suffix ? "".concat(STORAGE_ROOT_KEY).concat(suffix) : STORAGE_ROOT_KEY; this._rootStorage = createRootStorage(runtime); var localCache = this._rootStorage.get(key) || {}; this._cache = new AppCache(_defineProperty({}, key, localCache)); this._storageKey = key; } _createClass(AppStorage, [{ key: "_get", value: function _get() { var key = this._storageKey; return this._cache.get(key) || {}; } }, { key: "_set", value: function _set(cache) { var key = this._storageKey; cache = cache || {}; this._cache.set(key, cache); this._rootStorage.set(key, cache); } }, { key: "set", value: function set(key, value) { var localValue = this._get(); localValue[key] = value; this._set(localValue); } }, { key: "remove", value: function remove(key) { var localValue = this._get(); delete localValue[key]; this._set(localValue); } }, { key: "clear", value: function clear() { var key = this._storageKey; this._rootStorage.remove(key); this._cache.remove(key); } }, { key: "get", value: function get(key) { var localValue = this._get(); return localValue[key]; } }, { key: "getKeys", value: function getKeys() { var localValue = this._get(); var keyList = []; for (var _key3 in localValue) { keyList.push(_key3); } return keyList; } }, { key: "getValues", value: function getValues() { return this._get() || {}; } }]); return AppStorage; }(); var Todo = function (_Error) { _inherits(Todo, _Error); var _super = _createSuper(Todo); function Todo(message) { _classCallCheck(this, Todo); return _super.call(this, "TODO => ".concat(message)); } return Todo; }(_wrapNativeSuper(Error)); var todo = function todo(message) { _newArrowCheck(this, _this); return new Todo(message); }.bind(undefined); var toUpperCase = function toUpperCase(str, startIndex, endIndex) { var _this3 = this; _newArrowCheck(this, _this); if (startIndex === undefined || endIndex === undefined) { return str.toUpperCase(); } var sliceStr = str.slice(startIndex, endIndex); str = str.replace(sliceStr, function (text) { _newArrowCheck(this, _this3); return text.toUpperCase(); }.bind(this)); return str; }.bind(undefined); var getByteLength = function getByteLength(str) { var charset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'utf-8'; var total = 0; var chatCode; if (charset === 'utf-16') { for (var i = 0, max = str.length; i < max; i++) { chatCode = str.charCodeAt(i); if (chatCode <= 0xffff) { total += 2; } else { total += 4; } } } else { for (var _i = 0, _max = str.length; _i < _max; _i++) { chatCode = str.charCodeAt(_i); if (chatCode < 0x007f) { total += 1; } else if (chatCode <= 0x07ff) { total += 2; } else if (chatCode <= 0xffff) { total += 3; } else { total += 4; } } } return total; }; var appendUrl = function appendUrl(url, query) { var _this4 = this; _newArrowCheck(this, _this); url = url.replace(/\?$/, ''); if (!query) { return url; } var searchArr = Object.keys(query).map(function (key) { _newArrowCheck(this, _this4); return "".concat(key, "=").concat(query[key]); }.bind(this)).filter(function (item) { _newArrowCheck(this, _this4); return !!item; }.bind(this)); if (searchArr.length) { return [url, searchArr.join('&')].join('?'); } return url; }.bind(undefined); var matchVersion = function matchVersion(apiVersion) { _newArrowCheck(this, _this); var matches = apiVersion.match(/\d+(\.\d+){2}/); return matches[0]; }.bind(undefined); (function (LogLevel) { LogLevel[LogLevel["LOG"] = 0] = "LOG"; LogLevel[LogLevel["DEBUG"] = 0] = "DEBUG"; LogLevel[LogLevel["INFO"] = 1] = "INFO"; LogLevel[LogLevel["WARN"] = 2] = "WARN"; LogLevel[LogLevel["ERROR"] = 3] = "ERROR"; LogLevel[LogLevel["NONE"] = 1000] = "NONE"; })(exports.LogLevel || (exports.LogLevel = {})); var methods = (_methods = {}, _defineProperty(_methods, exports.LogLevel.DEBUG, console.debug.bind(console)), _defineProperty(_methods, exports.LogLevel.INFO, console.info.bind(console)), _defineProperty(_methods, exports.LogLevel.WARN, console.warn.bind(console)), _defineProperty(_methods, exports.LogLevel.ERROR, console.error.bind(console)), _methods); var Logger = function () { function Logger(_tag) { _classCallCheck(this, Logger); this._tag = _tag; this._outLevel = exports.LogLevel.WARN; this._stdout = this._defaultStdout; this.log = this._out; this.debug = this._out.bind(this, exports.LogLevel.DEBUG); this.info = this._out.bind(this, exports.LogLevel.INFO); this.warn = this._out.bind(this, exports.LogLevel.WARN); this.error = this._out.bind(this, exports.LogLevel.ERROR); } _createClass(Logger, [{ key: "_defaultStdout", value: function _defaultStdout(level) { for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key4 = 1; _key4 < _len; _key4++) { args[_key4 - 1] = arguments[_key4]; } methods[level].apply(methods, ["[".concat(this._tag, "](").concat(new Date().toUTCString(), "):")].concat(args)); } }, { key: "_out", value: function _out(level) { for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key5 = 1; _key5 < _len2; _key5++) { args[_key5 - 1] = arguments[_key5]; } level >= this._outLevel && this._stdout.apply(this, [level].concat(args)); } }, { key: "set", value: function set(outLevel, stdout) { this._outLevel = outLevel; this._stdout = stdout || this._defaultStdout; } }]); return Logger; }(); var logger = new Logger('RCLog'); var ConversationType; (function (ConversationType) { ConversationType[ConversationType["NONE"] = 0] = "NONE"; ConversationType[ConversationType["PRIVATE"] = 1] = "PRIVATE"; ConversationType[ConversationType["DISCUSSION"] = 2] = "DISCUSSION"; ConversationType[ConversationType["GROUP"] = 3] = "GROUP"; ConversationType[ConversationType["CHATROOM"] = 4] = "CHATROOM"; ConversationType[ConversationType["CUSTOMER_SERVICE"] = 5] = "CUSTOMER_SERVICE"; ConversationType[ConversationType["SYSTEM"] = 6] = "SYSTEM"; ConversationType[ConversationType["APP_PUBLIC_SERVICE"] = 7] = "APP_PUBLIC_SERVICE"; ConversationType[ConversationType["PUBLIC_SERVICE"] = 8] = "PUBLIC_SERVICE"; ConversationType[ConversationType["RTC_ROOM"] = 12] = "RTC_ROOM"; })(ConversationType || (ConversationType = {})); var ConversationType$1 = ConversationType; var FileType; (function (FileType) { FileType[FileType["IMAGE"] = 1] = "IMAGE"; FileType[FileType["AUDIO"] = 2] = "AUDIO"; FileType[FileType["VIDEO"] = 3] = "VIDEO"; FileType[FileType["FILE"] = 4] = "FILE"; FileType[FileType["SIGHT"] = 5] = "SIGHT"; FileType[FileType["COMBINE_HTML"] = 6] = "COMBINE_HTML"; })(FileType || (FileType = {})); var FileType$1 = FileType; var isString = function isString(value) { _newArrowCheck(this, _this); return typeof value === 'string'; }.bind(undefined); var isNumber = function isNumber(value) { _newArrowCheck(this, _this); return typeof value === 'number' && !isNaN(value); }.bind(undefined); var isArray = function isArray(arr) { _newArrowCheck(this, _this); return Object.prototype.toString.call(arr).indexOf('Array') !== -1; }.bind(undefined); var isArrayBuffer = function isArrayBuffer(arr) { _newArrowCheck(this, _this); return Object.prototype.toString.call(arr) === '[object ArrayBuffer]'; }.bind(undefined); var notEmptyString = function notEmptyString(str) { _newArrowCheck(this, _this); return isString(str) && str.length > 0; }.bind(undefined); var notEmptyArray = function notEmptyArray(arr) { _newArrowCheck(this, _this); return isArray(arr) && arr.length > 0; }.bind(undefined); var isObject = function isObject(val) { _newArrowCheck(this, _this); return Object.prototype.toString.call(val) === '[object Object]'; }.bind(undefined); var isFunction = function isFunction(val) { _newArrowCheck(this, _this); return Object.prototype.toString.call(val) === '[object Function]'; }.bind(undefined); var isUndefined = function isUndefined(val) { _newArrowCheck(this, _this); return val === undefined || Object.prototype.toString.call(val) === '[object Undefined]'; }.bind(undefined); var isNull = function isNull(val) { _newArrowCheck(this, _this); return Object.prototype.toString.call(val) === '[object Null]'; }.bind(undefined); var isHttpUrl = function isHttpUrl(value) { _newArrowCheck(this, _this); return isString(value) && /https?:\/\//.test(value); }.bind(undefined); var notEmptyObject = function notEmptyObject(val) { _newArrowCheck(this, _this); for (var _key6 in val) { return true; } return false; }.bind(undefined); var isValidConversationType = function isValidConversationType(conversation) { _newArrowCheck(this, _this); return isNumber(conversation) && Object.prototype.hasOwnProperty.call(ConversationType$1, conversation); }.bind(undefined); var isValidFileType = function isValidFileType(fileType) { _newArrowCheck(this, _this); return isNumber(fileType) && Object.prototype.hasOwnProperty.call(FileType$1, fileType); }.bind(undefined); var AssertRules; (function (AssertRules) { AssertRules[AssertRules["STRING"] = 0] = "STRING"; AssertRules[AssertRules["ONLY_STRING"] = 1] = "ONLY_STRING"; AssertRules[AssertRules["NUMBER"] = 2] = "NUMBER"; AssertRules[AssertRules["BOOLEAN"] = 3] = "BOOLEAN"; AssertRules[AssertRules["OBJECT"] = 4] = "OBJECT"; AssertRules[AssertRules["ARRAY"] = 5] = "ARRAY"; AssertRules[AssertRules["CALLBACK"] = 6] = "CALLBACK"; })(AssertRules || (AssertRules = {})); var validators = (_validators = {}, _defineProperty(_validators, AssertRules.STRING, notEmptyString), _defineProperty(_validators, AssertRules.ONLY_STRING, isString), _defineProperty(_validators, AssertRules.NUMBER, isNumber), _defineProperty(_validators, AssertRules.BOOLEAN, function (value) { _newArrowCheck(this, _this); return typeof value === 'boolean'; }.bind(undefined)), _defineProperty(_validators, AssertRules.OBJECT, isObject), _defineProperty(_validators, AssertRules.ARRAY, isArray), _defineProperty(_validators, AssertRules.CALLBACK, function (callback) { _newArrowCheck(this, _this); var flag = true; if (!isObject(callback)) { flag = false; } callback = callback || {}; if (callback.onSuccess && !isFunction(callback.onSuccess)) { flag = false; } if (callback.onError && !isFunction(callback.onError)) { flag = false; } return flag; }.bind(undefined)), _validators); var RCAssertError = function (_Error2) { _inherits(RCAssertError, _Error2); var _super2 = _createSuper(RCAssertError); function RCAssertError(message) { var _this5; _classCallCheck(this, RCAssertError); _this5 = _super2.call(this, message); _this5.name = 'RCAssertError'; return _this5; } return RCAssertError; }(_wrapNativeSuper(Error)); var assert = function assert(key, value, validator) { var required = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; if (!validate(key, value, validator, required)) { throw new RCAssertError("".concat(key, " is invalid.")); } }; var validate = function validate(key, value, validator) { var required = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; validator = validators[validator] || validator; var invalid = required && !validator(value) || !required && !(isUndefined(value) || value === null || validator(value)); if (invalid) { var msg = "".concat(key, " is invalid."); logger.error(msg); } return !invalid; }; var assertCPPMode = function assertCPPMode(isCPPMode, errorMsg) { _newArrowCheck(this, _this); errorMsg = errorMsg || 'Method is only available in cppProtocol mode'; if (!isCPPMode) { throw new RCAssertError(errorMsg); } }.bind(undefined); var forEach = function forEach(source, event, options) { var _this6 = this; _newArrowCheck(this, _this); options = options || {}; event = event || function () {}; var _options2 = options, isReverse = _options2.isReverse; var loopObj = function loopObj() { _newArrowCheck(this, _this6); for (var _key7 in source) { event(source[_key7], _key7, source); } }.bind(this); var loopArr = function loopArr() { _newArrowCheck(this, _this6); if (isReverse) { for (var i = source.length - 1; i >= 0; i--) { event(source[i], i); } } else { for (var j = 0, len = source.length; j < len; j++) { event(source[j], j); } } }.bind(this); if (isObject(source)) { loopObj(); } if (isArray(source) || isString(source)) { loopArr(); } }.bind(undefined); var map = function map(source, event) { var _this7 = this; _newArrowCheck(this, _this); forEach(source, function (item, index) { _newArrowCheck(this, _this7); source[index] = event(item, index); }.bind(this)); return source; }.bind(undefined); var indexOf = function indexOf(source, searchVal) { var _this8 = this; _newArrowCheck(this, _this); if (source.indexOf) { return source.indexOf(searchVal); } var index = -1; forEach(source, function (sub, i) { _newArrowCheck(this, _this8); if (searchVal === sub) { index = i; } }.bind(this)); return index; }.bind(undefined); var isInclude = function isInclude(source, searchVal) { _newArrowCheck(this, _this); var index = indexOf(source, searchVal); return index !== -1; }.bind(undefined); var isInObject = function isInObject(source, searchVal) { var _this9 = this; _newArrowCheck(this, _this); var arr = []; forEach(source, function (val) { _newArrowCheck(this, _this9); arr.push(val); }.bind(this)); var index = indexOf(arr, searchVal); return index !== -1; }.bind(undefined); var cloneByJSON = function cloneByJSON(sourceObj) { _newArrowCheck(this, _this); return JSON.parse(JSON.stringify(sourceObj)); }.bind(undefined); var ChatroomEntryType; (function (ChatroomEntryType) { ChatroomEntryType[ChatroomEntryType["UPDATE"] = 1] = "UPDATE"; ChatroomEntryType[ChatroomEntryType["DELETE"] = 2] = "DELETE"; })(ChatroomEntryType || (ChatroomEntryType = {})); var ChatroomEntryType$1 = ChatroomEntryType; var getMessageOptionByStatus = function getMessageOptionByStatus(status) { _newArrowCheck(this, _this); var isPersited = true; var isCounted = true; var isMentioned = false; var disableNotification = false; var receivedStatus = ReceivedStatus$1.READ; var isReceivedByOtherClient = false; var canIncludeExpansion = false; isPersited = !!(status & 0x10); isCounted = !!(status & 0x20); isMentioned = !!(status & 0x40); disableNotification = !!(status & 0x100); isReceivedByOtherClient = !!(status & 0x02); receivedStatus = isReceivedByOtherClient ? ReceivedStatus$1.RETRIEVED : receivedStatus; canIncludeExpansion = !!(status & 0x400); return { isPersited: isPersited, isCounted: isCounted, isMentioned: isMentioned, disableNotification: disableNotification, receivedStatus: receivedStatus, canIncludeExpansion: canIncludeExpansion }; }.bind(undefined); var getUpMessageOptionBySessionId = function getUpMessageOptionBySessionId(sessionId) { _newArrowCheck(this, _this); var isPersited = false; var isCounted = false; var disableNotification = false; var canIncludeExpansion = false; isPersited = !!(sessionId & 0x01); isCounted = !!(sessionId & 0x02); disableNotification = !!(sessionId & 0x10); canIncludeExpansion = !!(sessionId & 0x40); return { isPersited: isPersited, isCounted: isCounted, disableNotification: disableNotification, canIncludeExpansion: canIncludeExpansion }; }.bind(undefined); var formatExtraContent = function formatExtraContent(extraContent) { var _this10 = this; _newArrowCheck(this, _this); var expansion = {}; var parseExtraContent = JSON.parse(extraContent); forEach(parseExtraContent, function (value, key) { _newArrowCheck(this, _this10); expansion[key] = value.v; }.bind(this)); return expansion; }.bind(undefined); var DelayTimer = { _delayTime: 0, setTime: function setTime(time) { _newArrowCheck(this, _this); var currentTime = new Date().getTime(); DelayTimer._delayTime = currentTime - time; }.bind(undefined), getTime: function getTime() { _newArrowCheck(this, _this); var delayTime = DelayTimer._delayTime; var currentTime = new Date().getTime(); return currentTime - delayTime; }.bind(undefined) }; var getChatRoomKVByStatus = function getChatRoomKVByStatus(status) { _newArrowCheck(this, _this); var isDeleteOpt = !!(status & 0x0004); return { isAutoDelete: !!(status & 0x0001), isOverwrite: !!(status & 0x0002), type: isDeleteOpt ? ChatroomEntryType$1.DELETE : ChatroomEntryType$1.UPDATE }; }.bind(undefined); var getChatRoomKVOptStatus = function getChatRoomKVOptStatus(entity, action) { _newArrowCheck(this, _this); var status = 0; if (entity.isAutoDelete) { status = status | 0x0001; } if (entity.isOverwrite) { status = status | 0x0002; } if (action === 2) { status = status | 0x0004; } return status; }.bind(undefined); var getSessionId = function getSessionId(option) { _newArrowCheck(this, _this); var isStatusMessage = option.isStatusMessage; var isPersited = option.isPersited, isCounted = option.isCounted, isMentioned = option.isMentioned, disableNotification = option.disableNotification, canIncludeExpansion = option.canIncludeExpansion; if (isStatusMessage) { isPersited = isCounted = false; } var sessionId = 0; if (isPersited) { sessionId = sessionId | 0x01; } if (isCounted) { sessionId = sessionId | 0x02; } if (isMentioned) { sessionId = sessionId | 0x04; } if (disableNotification) { sessionId = sessionId | 0x20; } if (canIncludeExpansion) { sessionId = sessionId | 0x40; } return sessionId; }.bind(undefined); function __awaiter$1(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); } var QOS; (function (QOS) { QOS[QOS["AT_MOST_ONCE"] = 0] = "AT_MOST_ONCE"; QOS[QOS["AT_LEAST_ONCE"] = 1] = "AT_LEAST_ONCE"; QOS[QOS["EXACTLY_ONCE"] = 2] = "EXACTLY_ONCE"; QOS[QOS["DEFAULT"] = 3] = "DEFAULT"; })(QOS || (QOS = {})); var OperationType; (function (OperationType) { OperationType[OperationType["SYMMETRIC"] = 0] = "SYMMETRIC"; OperationType[OperationType["CONNECT"] = 1] = "CONNECT"; OperationType[OperationType["CONN_ACK"] = 2] = "CONN_ACK"; OperationType[OperationType["PUBLISH"] = 3] = "PUBLISH"; OperationType[OperationType["PUB_ACK"] = 4] = "PUB_ACK"; OperationType[OperationType["QUERY"] = 5] = "QUERY"; OperationType[OperationType["QUERY_ACK"] = 6] = "QUERY_ACK"; OperationType[OperationType["QUERY_CONFIRM"] = 7] = "QUERY_CONFIRM"; OperationType[OperationType["SUBSCRIBE"] = 8] = "SUBSCRIBE"; OperationType[OperationType["SUB_ACK"] = 9] = "SUB_ACK"; OperationType[OperationType["UNSUBSCRIBE"] = 10] = "UNSUBSCRIBE"; OperationType[OperationType["UNSUB_ACK"] = 11] = "UNSUB_ACK"; OperationType[OperationType["PING_REQ"] = 12] = "PING_REQ"; OperationType[OperationType["PING_RESP"] = 13] = "PING_RESP"; OperationType[OperationType["DISCONNECT"] = 14] = "DISCONNECT"; OperationType[OperationType["RESERVER2"] = 15] = "RESERVER2"; })(OperationType || (OperationType = {})); var MessageName; (function (MessageName) { MessageName["CONN_ACK"] = "ConnAckMessage"; MessageName["DISCONNECT"] = "DisconnectMessage"; MessageName["PING_REQ"] = "PingReqMessage"; MessageName["PING_RESP"] = "PingRespMessage"; MessageName["PUBLISH"] = "PublishMessage"; MessageName["PUB_ACK"] = "PubAckMessage"; MessageName["QUERY"] = "QueryMessage"; MessageName["QUERY_CON"] = "QueryConMessage"; MessageName["QUERY_ACK"] = "QueryAckMessage"; })(MessageName || (MessageName = {})); var IDENTIFIER; (function (IDENTIFIER) { IDENTIFIER["PUB"] = "pub"; IDENTIFIER["QUERY"] = "qry"; })(IDENTIFIER || (IDENTIFIER = {})); var Header = function () { function Header(type) { var retain = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; var qos = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : QOS.AT_LEAST_ONCE; var dup = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; _classCallCheck(this, Header); this._retain = false; this.qos = QOS.AT_LEAST_ONCE; this._dup = false; this.syncMsg = false; var isPlusType = type > 0; if (type && isPlusType && arguments.length === 1) { this._retain = (type & 1) > 0; this.qos = (type & 6) >> 1; this._dup = (type & 8) > 0; this.type = type >> 4 & 15; this.syncMsg = (type & 8) === 8; } else { this.type = type; this._retain = retain; this.qos = qos; this._dup = dup; } } _createClass(Header, [{ key: "encode", value: function encode() { var byte = this.type << 4; byte |= this._retain ? 1 : 0; byte |= this.qos << 1; byte |= this._dup ? 8 : 0; return byte; } }]); return Header; }(); var BinaryHelper = function () { function BinaryHelper() { _classCallCheck(this, BinaryHelper); } _createClass(BinaryHelper, null, [{ key: "writeUTF", value: function writeUTF(str, isGetBytes) { var back = []; var byteSize = 0; if (isString(str)) { for (var i = 0, len = str.length; i < len; i++) { var code = str.charCodeAt(i); if (code >= 0 && code <= 127) { byteSize += 1; back.push(code); } else if (code >= 128 && code <= 2047) { byteSize += 2; back.push(192 | 31 & code >> 6); back.push(128 | 63 & code); } else if (code >= 2048 && code <= 65535) { byteSize += 3; back.push(224 | 15 & code >> 12); back.push(128 | 63 & code >> 6); back.push(128 | 63 & code); } } } for (var _i2 = 0, _len3 = back.length; _i2 < _len3; _i2++) { if (back[_i2] > 255) { back[_i2] &= 255; } } if (isGetBytes) { return back; } if (byteSize <= 255) { return [0, byteSize].concat(back); } else { return [byteSize >> 8, byteSize & 255].concat(back); } } }, { key: "readUTF", value: function readUTF(arr) { var MAX_SIZE = 0x4000; var codeUnits = []; var highSurrogate; var lowSurrogate; var index = -1; var strBytes = arr; var result = ''; while (++index < strBytes.length) { var codePoint = Number(strBytes[index]); if (codePoint === (codePoint & 0x7F)) ;else if ((codePoint & 0xF0) === 0xF0) { codePoint ^= 0xF0; codePoint = codePoint << 6 | strBytes[++index] ^ 0x80; codePoint = codePoint << 6 | strBytes[++index] ^ 0x80; codePoint = codePoint << 6 | strBytes[++index] ^ 0x80; } else if ((codePoint & 0xE0) === 0xE0) { codePoint ^= 0xE0; codePoint = codePoint << 6 | strBytes[++index] ^ 0x80; codePoint = codePoint << 6 | strBytes[++index] ^ 0x80; } else if ((codePoint & 0xC0) === 0xC0) { codePoint ^= 0xC0; codePoint = codePoint << 6 | strBytes[++index] ^ 0x80; } if (!isFinite(codePoint) || codePoint < 0 || codePoint > 0x10FFFF || Math.floor(codePoint) !== codePoint) { throw RangeError('Invalid code point: ' + codePoint); } if (codePoint <= 0xFFFF) { codeUnits.push(codePoint); } else { codePoint -= 0x10000; highSurrogate = codePoint >> 10 | 0xD800; lowSurrogate = codePoint % 0x400 | 0xDC00; codeUnits.push(highSurrogate, lowSurrogate); } if (index + 1 === strBytes.length || codeUnits.length > MAX_SIZE) { result += String.fromCharCode.apply(null, codeUnits); codeUnits.length = 0; } } return result; } }]); return BinaryHelper; }(); var RongStreamReader = function () { function RongStreamReader(arr) { _classCallCheck(this, RongStreamReader); this._position = 0; this._poolLen = 0; this._pool = arr; this._poolLen = arr.length; } _createClass(RongStreamReader, [{ key: "check", value: function check() { return this._position >= this._pool.length; } }, { key: "readInt", value: function readInt() { var self = this; if (self.check()) { return -1; } var end = ''; for (var i = 0; i < 4; i++) { var t = self._pool[self._position++].toString(16); if (t.length === 1) { t = '0' + t; } end += t.toString(); } return parseInt(end, 16); } }, { key: "readLong", value: function readLong() { var self = this; if (self.check()) { return -1; } var end = ''; for (var i = 0; i < 8; i++) { var t = self._pool[self._position++].toString(16); if (t.length === 1) { t = '0' + t; } end += t; } return parseInt(end, 16); } }, { key: "readByte", value: function readByte() { if (this.check()) { return -1; } var val = this._pool[this._position++]; if (val > 255) { val &= 255; } return val; } }, { key: "readUTF", value: function readUTF() { if (this.check()) { return ''; } var big = this.readByte() << 8 | this.readByte(); var pool = this._pool.subarray(this._position, this._position += big); return BinaryHelper.readUTF(pool); } }, { key: "readAll", value: function readAll() { return this._pool.subarray(this._position, this._poolLen); } }]); return RongStreamReader; }(); var RongStreamWriter = function () { function RongStreamWriter() { _classCallCheck(this, RongStreamWriter); this._pool = []; this._position = 0; this._writen = 0; } _createClass(RongStreamWriter, [{ key: "write", value: function write(byte) { if (Object.prototype.toString.call(byte).indexOf('Array') !== -1) { this._pool = this._pool.concat(byte); } else if (byte >= 0) { if (byte > 255) { byte &= 255; } this._pool.push(byte); this._writen++; } return byte; } }, { key: "writeArr", value: function writeArr(byte) { this._pool = this._pool.concat(byte); return byte; } }, { key: "writeUTF", value: function writeUTF(str) { var val = BinaryHelper.writeUTF(str); this._pool = this._pool.concat(val); this._writen += val.length; } }, { key: "getBytesArray", value: function getBytesArray() { return this._pool; } }]); return RongStreamWriter; }(); var PBName = { UpStreamMessage: 'UpStreamMessage', DownStreamMessage: 'DownStreamMessage', DownStreamMessages: 'DownStreamMessages', SessionsAttQryInput: 'SessionsAttQryInput', SessionsAttOutput: 'SessionsAttOutput', SyncRequestMsg: 'SyncRequestMsg', ChrmPullMsg: 'ChrmPullMsg', NotifyMsg: 'NotifyMsg', HistoryMsgInput: 'HistoryMsgInput', HistoryMsgOuput: 'HistoryMsgOuput', RelationQryInput: 'RelationQryInput', RelationsOutput: 'RelationsOutput', DeleteSessionsInput: 'DeleteSessionsInput', SessionInfo: 'SessionInfo', DeleteSessionsOutput: 'DeleteSessionsOutput', RelationsInput: 'RelationsInput', DeleteMsgInput: 'DeleteMsgInput', CleanHisMsgInput: 'CleanHisMsgInput', SessionMsgReadInput: 'SessionMsgReadInput', ChrmInput: 'ChrmInput', QueryChatRoomInfoInput: 'QueryChatRoomInfoInput', QueryChatRoomInfoOutput: 'QueryChatRoomInfoOutput', RtcInput: 'RtcInput', RtcUserListOutput: 'RtcUserListOutput', SetUserStatusInput: 'SetUserStatusInput', RtcSetDataInput: 'RtcSetDataInput', RtcUserSetDataInput: 'RtcUserSetDataInput', RtcDataInput: 'RtcDataInput', RtcSetOutDataInput: 'RtcSetOutDataInput', MCFollowInput: 'MCFollowInput', RtcTokenOutput: 'RtcTokenOutput', RtcQryOutput: 'RtcQryOutput', RtcQryUserOutDataInput: 'RtcQryUserOutDataInput', RtcUserOutDataOutput: 'RtcUserOutDataOutput', RtcQueryListInput: 'RtcQueryListInput', RtcRoomInfoOutput: 'RtcRoomInfoOutput', RtcValueInfo: 'RtcValueInfo', RtcKeyDeleteInput: 'RtcKeyDeleteInput', GetQNupTokenInput: 'GetQNupTokenInput', GetQNupTokenOutput: 'GetQNupTokenOutput', GetQNdownloadUrlInput: 'GetQNdownloadUrlInput', GetDownloadUrlInput: 'GetDownloadUrlInput', GetQNdownloadUrlOutput: 'GetQNdownloadUrlOutput', GetDownloadUrlOutput: 'GetDownloadUrlOutput', SetChrmKV: 'SetChrmKV', ChrmKVOutput: 'ChrmKVOutput', QueryChrmKV: 'QueryChrmKV', SetUserSettingInput: 'SetUserSettingInput', SetUserSettingOutput: 'SetUserSettingOutput', PullUserSettingInput: 'PullUserSettingInput', PullUserSettingOutput: 'PullUserSettingOutput', UserSettingNotification: 'UserSettingNotification', SessionReq: 'SessionReq', SessionStates: 'SessionStates', SessionState: 'SessionState', SessionStateItem: 'SessionStateItem', SessionStateModifyReq: 'SessionStateModifyReq', SessionStateModifyResp: 'SessionStateModifyResp' }; var SSMsg = (_SSMsg = {}, _defineProperty(_SSMsg, PBName.UpStreamMessage, ['sessionId', 'classname', 'content', 'pushText', 'userId', 'configFlag', 'appData', 'extraContent']), _defineProperty(_SSMsg, PBName.DownStreamMessages, ['list', 'syncTime', 'finished']), _defineProperty(_SSMsg, PBName.DownStreamMessage, ['fromUserId', 'type', 'groupId', 'classname', 'content', 'dataTime', 'status', 'msgId', 'extraContent']), _defineProperty(_SSMsg, PBName.SessionsAttQryInput, ['nothing']), _defineProperty(_SSMsg, PBName.SessionsAttOutput, ['inboxTime', 'sendboxTime', 'totalUnreadCount']), _defineProperty(_SSMsg, PBName.SyncRequestMsg, ['syncTime', 'ispolling', 'isweb', 'isPullSend', 'isKeeping', 'sendBoxSyncTime']), _defineProperty(_SSMsg, PBName.ChrmPullMsg, ['syncTime', 'count']), _defineProperty(_SSMsg, PBName.NotifyMsg, ['type', 'time', 'chrmId']), _defineProperty(_SSMsg, PBName.HistoryMsgInput, ['targetId', 'time', 'count', 'order']), _defineProperty(_SSMsg, PBName.HistoryMsgOuput, ['list', 'syncTime', 'hasMsg']), _defineProperty(_SSMsg, PBName.RelationQryInput, ['type', 'count', 'startTime', 'order']), _defineProperty(_SSMsg, PBName.RelationsOutput, ['info']), _defineProperty(_SSMsg, PBName.DeleteSessionsInput, ['sessions']), _defineProperty(_SSMsg, PBName.SessionInfo, ['type', 'channelId']), _defineProperty(_SSMsg, PBName.DeleteSessionsOutput, ['nothing']), _defineProperty(_SSMsg, PBName.RelationsInput, ['type', 'msg', 'count', 'offset', 'startTime', 'endTime']), _defineProperty(_SSMsg, PBName.DeleteMsgInput, ['type', 'conversationId', 'msgs']), _defineProperty(_SSMsg, PBName.CleanHisMsgInput, ['targetId', 'dataTime', 'conversationType']), _defineProperty(_SSMsg, PBName.SessionMsgReadInput, ['type', 'msgTime', 'channelId']), _defineProperty(_SSMsg, PBName.ChrmInput, ['nothing']), _defineProperty(_SSMsg, PBName.QueryChatRoomInfoInput, ['count', 'order']), _defineProperty(_SSMsg, PBName.QueryChatRoomInfoOutput, ['userTotalNums', 'userInfos']), _defineProperty(_SSMsg, PBName.GetQNupTokenInput, ['type', 'key']), _defineProperty(_SSMsg, PBName.GetQNdownloadUrlInput, ['type', 'key', 'fileName']), _defineProperty(_SSMsg, PBName.GetDownloadUrlInput, ['type', 'key', 'fileName']), _defineProperty(_SSMsg, PBName.GetQNupTokenOutput, ['deadline', 'token', 'bosToken', 'bosDate', 'path', 'osskeyId', 'ossPolicy', 'ossSign', 'ossBucketName']), _defineProperty(_SSMsg, PBName.GetQNdownloadUrlOutput, ['downloadUrl']), _defineProperty(_SSMsg, PBName.GetDownloadUrlOutput, ['downloadUrl']), _defineProperty(_SSMsg, PBName.SetChrmKV, ['entry', 'bNotify', 'notification', 'type']), _defineProperty(_SSMsg, PBName.ChrmKVOutput, ['entries', 'bFullUpdate', 'syncTime']), _defineProperty(_SSMsg, PBName.QueryChrmKV, ['timestamp']), _defineProperty(_SSMsg, PBName.SetUserSettingInput, ['version', 'value']), _defineProperty(_SSMsg, PBName.SetUserSettingOutput, ['version', 'reserve']), _defineProperty(_SSMsg, PBName.PullUserSettingInput, ['version', 'reserve']), _defineProperty(_SSMsg, PBName.PullUserSettingOutput, ['items', 'version']), _defineProperty(_SSMsg, PBName.SessionReq, ['time']), _defineProperty(_SSMsg, PBName.SessionStates, ['version', 'state']), _defineProperty(_SSMsg, PBName.SessionState, ['type', 'channelId', 'time', 'stateItem']), _defineProperty(_SSMsg, PBName.SessionStateItem, ['sessionStateType', 'value']), _defineProperty(_SSMsg, PBName.SessionStateModifyReq, ['version', 'state']), _defineProperty(_SSMsg, PBName.SessionStateModifyResp, ['version']), _SSMsg); var Codec = {}; var _loop = function _loop() { var _this165 = this; var paramsList = SSMsg[key]; Codec[key] = function () { _newArrowCheck(this, _this165); var data = {}; var ins = { getArrayData: function getArrayData() { return data; } }; var _loop3 = function _loop3(i) { var _this166 = this; var param = paramsList[i]; var setEventName = "set".concat(toUpperCase(param, 0, 1)); ins[setEventName] = function (item) { _newArrowCheck(this, _this166); data[param] = item; }.bind(this); }; for (var i = 0; i < paramsList.length; i++) { _loop3(i); } return ins; }.bind(this); Codec[key].decode = function (data) { var decodeResult = {}; if (isString(data)) { data = JSON.parse(data); } var _loop4 = function _loop4(_key21) { var _this167 = this; var getEventName = "get".concat(toUpperCase(_key21, 0, 1)); decodeResult[_key21] = data[_key21]; decodeResult[getEventName] = function () { _newArrowCheck(this, _this167); return data[_key21]; }.bind(this); }; for (var _key21 in data) { _loop4(_key21); } return decodeResult; }; }; for (var key in SSMsg) { _loop(); } Codec.getModule = function (pbName) { _newArrowCheck(this, _this); return Codec[pbName](); }.bind(undefined); var SSMsg$1 = "\npackage Modules;\nmessage probuf {\n message ".concat(PBName.SetUserStatusInput, "\n {\n optional int32 status=1;\n }\n\n message SetUserStatusOutput\n {\n optional int32 nothing=1;\n }\n\n message GetUserStatusInput\n {\n optional int32 nothing=1;\n }\n\n message GetUserStatusOutput\n {\n optional string status=1;\n optional string subUserId=2;\n }\n\n message SubUserStatusInput\n {\n repeated string userid =1;\n }\n\n message SubUserStatusOutput\n {\n optional int32 nothing=1; \n }\n message VoipDynamicInput\n {\n required int32 engineType = 1;\n required string channelName = 2;\n optional string channelExtra = 3;\n }\n\n message VoipDynamicOutput\n {\n required string dynamicKey=1;\n }\n message ").concat(PBName.NotifyMsg, " {\n required int32 type = 1;\n optional int64 time = 2;\n optional string chrmId=3;\n }\n message ").concat(PBName.SyncRequestMsg, " {\n required int64 syncTime = 1;\n required bool ispolling = 2;\n optional bool isweb=3;\n optional bool isPullSend=4;\n optional bool isKeeping=5;\n optional int64 sendBoxSyncTime=6;\n }\n message ").concat(PBName.UpStreamMessage, " {\n required int32 sessionId = 1;\n required string classname = 2;\n required bytes content = 3;\n optional string pushText = 4;\n optional string appData = 5;\n repeated string userId = 6;\n optional int64 delMsgTime = 7;\n optional string delMsgId = 8;\n optional int32 configFlag = 9;\n optional int64 clientUniqueId = 10;\n optional string extraContent = 11;\n }\n message ").concat(PBName.DownStreamMessages, " {\n repeated DownStreamMessage list = 1;\n required int64 syncTime = 2;\n optional bool finished = 3;\n }\n message ").concat(PBName.DownStreamMessage, " {\n required string fromUserId = 1;\n required ChannelType type = 2;\n optional string groupId = 3;\n required string classname = 4;\n required bytes content = 5;\n required int64 dataTime = 6;\n required int64 status = 7;\n optional int64 extra = 8;\n optional string msgId = 9;\n optional int32 direction = 10;\n optional int32 plantform =11;\n optional int32 isRemoved = 12; \n optional string source = 13; \n optional int64 clientUniqueId = 14; \n optional string extraContent = 15; \n\n }\n enum ChannelType {\n PERSON = 1;\n PERSONS = 2;\n GROUP = 3;\n TEMPGROUP = 4;\n CUSTOMERSERVICE = 5;\n NOTIFY = 6;\n MC=7;\n MP=8;\n }\n message CreateDiscussionInput {\n optional string name = 1;\n }\n message CreateDiscussionOutput {\n required string id = 1;\n }\n message ChannelInvitationInput {\n repeated string users = 1;\n }\n message LeaveChannelInput {\n required int32 nothing = 1;\n }\n message ChannelEvictionInput {\n required string user = 1;\n }\n message RenameChannelInput {\n required string name = 1;\n }\n message ChannelInfoInput {\n required int32 nothing = 1;\n }\n message ChannelInfoOutput {\n required ChannelType type = 1;\n required string channelId = 2;\n required string channelName = 3;\n required string adminUserId = 4;\n repeated string firstTenUserIds = 5;\n required int32 openStatus = 6;\n }\n message ChannelInfosInput {\n required int32 page = 1;\n optional int32 number = 2;\n }\n message ChannelInfosOutput {\n repeated ChannelInfoOutput channels = 1;\n required int32 total = 2;\n }\n message MemberInfo {\n required string userId = 1;\n required string userName = 2;\n required string userPortrait = 3;\n required string extension = 4;\n }\n message GroupMembersInput {\n required int32 page = 1;\n optional int32 number = 2;\n }\n message GroupMembersOutput {\n repeated MemberInfo members = 1;\n required int32 total = 2;\n }\n message GetUserInfoInput {\n required int32 nothing = 1;\n }\n message GetUserInfoOutput {\n required string userId = 1;\n required string userName = 2;\n required string userPortrait = 3;\n }\n message GetSessionIdInput {\n required int32 nothing = 1;\n }\n message GetSessionIdOutput {\n required int32 sessionId = 1;\n }\n enum FileType {\n image = ").concat(FileType$1.IMAGE, ";\n audio = ").concat(FileType$1.AUDIO, ";\n video = ").concat(FileType$1.VIDEO, ";\n file = ").concat(FileType$1.FILE, ";\n }\n message ").concat(PBName.GetQNupTokenInput, " {\n required FileType type = 1;\n optional string key = 2;\n }\n message ").concat(PBName.GetQNdownloadUrlInput, " {\n required FileType type = 1;\n required string key = 2;\n optional string fileName = 3;\n }\n message ").concat(PBName.GetDownloadUrlInput, " {\n required FileType type = 1; // \u4E0B\u8F7D\u7684\u6587\u4EF6\u7C7B\u578B\n required string key = 2; // \u8BF7\u6C42\u4E0B\u8F7D\u7684\u6587\u4EF6\u540D\n optional string fileName = 3; // \u4E0B\u8F7D\u751F\u6210\u7684\u6587\u4EF6\u540D\u5B57\n }\n message ").concat(PBName.GetQNupTokenOutput, " {\n required int64 deadline = 1;\n required string token = 2;\n optional string bosToken = 3;\n optional string bosDate = 4;\n optional string path = 5;\n optional string osskeyId = 6;\n optional string ossPolicy = 7;\n optional string ossSign = 8;\n optional string ossBucketName = 9;\n }\n message ").concat(PBName.GetQNdownloadUrlOutput, " {\n required string downloadUrl = 1;\n }\n message ").concat(PBName.GetDownloadUrlOutput, " {\n required string downloadUrl = 1;\n }\n message Add2BlackListInput {\n required string userId = 1;\n }\n message RemoveFromBlackListInput {\n required string userId = 1;\n }\n message QueryBlackListInput {\n required int32 nothing = 1;\n }\n message QueryBlackListOutput {\n repeated string userIds = 1;\n }\n message BlackListStatusInput {\n required string userId = 1;\n }\n message BlockPushInput {\n required string blockeeId = 1;\n }\n message ModifyPermissionInput {\n required int32 openStatus = 1;\n }\n message GroupInput {\n repeated GroupInfo groupInfo = 1;\n }\n message GroupOutput {\n required int32 nothing = 1;\n }\n message GroupInfo {\n required string id = 1;\n required string name = 2;\n }\n message GroupHashInput {\n required string userId = 1;\n required string groupHashCode = 2;\n }\n message GroupHashOutput {\n required GroupHashType result = 1;\n }\n enum GroupHashType {\n group_success = 0x00;\n group_failure = 0x01;\n }\n message ").concat(PBName.ChrmInput, " {\n required int32 nothing = 1;\n }\n message ChrmOutput {\n required int32 nothing = 1;\n }\n message ").concat(PBName.ChrmPullMsg, " {\n required int64 syncTime = 1;\n required int32 count = 2;\n }\n \n message ChrmPullMsgNew \n {\n required int32 count = 1;\n required int64 syncTime = 2;\n optional string chrmId=3;\n }\n message ").concat(PBName.RelationQryInput, "\n {\n optional ChannelType type = 1;\n optional int32 count = 2;\n optional int64 startTime = 3;\n optional int32 order = 4;\n }\n message ").concat(PBName.RelationsInput, "\n {\n required ChannelType type = 1;\n optional DownStreamMessage msg =2;\n optional int32 count = 3;\n optional int32 offset = 4;\n optional int64 startTime = 5;\n optional int64 endTime = 6;\n }\n message ").concat(PBName.RelationsOutput, "\n {\n repeated RelationInfo info = 1;\n }\n message RelationInfo\n {\n required ChannelType type = 1;\n required string userId = 2;\n optional DownStreamMessage msg =3;\n optional int64 readMsgTime= 4;\n optional int64 unreadCount= 5;\n }\n message RelationInfoReadTime\n {\n required ChannelType type = 1;\n required int64 readMsgTime= 2;\n required string targetId = 3;\n }\n message ").concat(PBName.CleanHisMsgInput, "\n {\n required string targetId = 1;\n required int64 dataTime = 2;\n optional int32 conversationType= 3;\n }\n message HistoryMessageInput\n {\n required string targetId = 1;\n required int64 dataTime =2;\n required int32 size = 3;\n }\n\n message HistoryMessagesOuput\n {\n repeated DownStreamMessage list = 1;\n required int64 syncTime = 2;\n required int32 hasMsg = 3;\n }\n message ").concat(PBName.QueryChatRoomInfoInput, "\n {\n required int32 count= 1;\n optional int32 order= 2;\n }\n\n message ").concat(PBName.QueryChatRoomInfoOutput, "\n {\n optional int32 userTotalNums = 1;\n repeated ChrmMember userInfos = 2;\n }\n message ChrmMember\n {\n required int64 time = 1;\n required string id = 2;\n }\n message MPFollowInput\n {\n required string id = 1;\n }\n\n message MPFollowOutput\n {\n required int32 nothing = 1;\n optional MpInfo info =2;\n }\n\n message ").concat(PBName.MCFollowInput, "\n {\n required string id = 1;\n }\n\n message MCFollowOutput\n {\n required int32 nothing = 1;\n optional MpInfo info =2;\n }\n\n message MpInfo \n {\n required string mpid=1;\n required string name = 2;\n required string type = 3;\n required int64 time=4;\n optional string portraitUrl=5;\n optional string extra =6;\n }\n\n message SearchMpInput\n {\n required int32 type=1;\n required string id=2;\n }\n\n message SearchMpOutput\n {\n required int32 nothing=1;\n repeated MpInfo info = 2;\n }\n\n message PullMpInput\n {\n required int64 time=1;\n required string mpid=2;\n }\n\n message PullMpOutput\n {\n required int32 status=1;\n repeated MpInfo info = 2;\n }\n message ").concat(PBName.HistoryMsgInput, "\n {\n optional string targetId = 1;\n optional int64 time = 2;\n optional int32 count = 3;\n optional int32 order = 4;\n }\n\n message ").concat(PBName.HistoryMsgOuput, "\n {\n repeated DownStreamMessage list=1;\n required int64 syncTime=2;\n required int32 hasMsg=3;\n }\n message ").concat(PBName.RtcQueryListInput, "{\n optional int32 order=1;\n }\n\n message ").concat(PBName.RtcKeyDeleteInput, "{\n repeated string key=1;\n }\n\n message ").concat(PBName.RtcValueInfo, "{\n required string key=1;\n required string value=2;\n }\n\n message RtcUserInfo{\n required string userId=1;\n repeated ").concat(PBName.RtcValueInfo, " userData=2;\n }\n\n message ").concat(PBName.RtcUserListOutput, "{\n repeated RtcUserInfo list=1;\n optional string token=2;\n optional string sessionId=3;\n }\n message RtcRoomInfoOutput{\n optional string roomId = 1;\n repeated ").concat(PBName.RtcValueInfo, " roomData = 2;\n optional int32 userCount = 3;\n repeated RtcUserInfo list=4;\n }\n message ").concat(PBName.RtcInput, "{\n required int32 roomType=1;\n optional int32 broadcastType=2;\n }\n message RtcQryInput{ \n required bool isInterior=1;\n required targetType target=2;\n repeated string key=3;\n }\n message ").concat(PBName.RtcQryOutput, "{\n repeated ").concat(PBName.RtcValueInfo, " outInfo=1;\n }\n message RtcDelDataInput{\n repeated string key=1;\n required bool isInterior=2;\n required targetType target=3;\n }\n message ").concat(PBName.RtcDataInput, "{ \n required bool interior=1;\n required targetType target=2;\n repeated string key=3;\n optional string objectName=4;\n optional string content=5;\n }\n message ").concat(PBName.RtcSetDataInput, "{\n required bool interior=1;\n required targetType target=2;\n required string key=3;\n required string value=4;\n optional string objectName=5;\n optional string content=6;\n }\n message ").concat(PBName.RtcUserSetDataInput, " {\n repeated ").concat(PBName.RtcValueInfo, " valueInfo = 1;\n required string objectName = 2;\n repeated ").concat(PBName.RtcValueInfo, " content = 3;\n }\n message RtcOutput\n {\n optional int32 nothing=1; \n }\n message ").concat(PBName.RtcTokenOutput, "{\n required string rtcToken=1;\n }\n enum targetType {\n ROOM =1 ;\n PERSON = 2;\n }\n message ").concat(PBName.RtcSetOutDataInput, "{\n required targetType target=1;\n repeated ").concat(PBName.RtcValueInfo, " valueInfo=2;\n optional string objectName=3;\n optional string content=4;\n }\n message ").concat(PBName.RtcQryUserOutDataInput, "{\n repeated string userId = 1;\n }\n message ").concat(PBName.RtcUserOutDataOutput, "{\n repeated RtcUserInfo user = 1;\n }\n message ").concat(PBName.SessionsAttQryInput, "{\n required int32 nothing = 1;\n }\n message ").concat(PBName.SessionsAttOutput, "{\n required int64 inboxTime = 1;\n required int64 sendboxTime = 2;\n required int64 totalUnreadCount = 3;\n }\n message ").concat(PBName.SessionMsgReadInput, "\n {\n required ChannelType type = 1;\n required int64 msgTime = 2;\n required string channelId = 3;\n }\n message SessionMsgReadOutput\n {\n optional int32 nothing=1; \n }\n message ").concat(PBName.DeleteSessionsInput, "\n {\n repeated SessionInfo sessions = 1;\n }\n message ").concat(PBName.SessionInfo, "\n {\n required ChannelType type = 1;\n required string channelId = 2;\n }\n message ").concat(PBName.DeleteSessionsOutput, "\n {\n optional int32 nothing=1; \n }\n message ").concat(PBName.DeleteMsgInput, "\n {\n optional ChannelType type = 1;\n optional string conversationId = 2;\n repeated DeleteMsg msgs = 3;\n }\n message DeleteMsg\n {\n optional string msgId = 1;\n optional int64 msgDataTime = 2;\n optional int32 direct = 3;\n }\n message ChrmKVEntity {\n required string key = 1;\n required string value = 2;\n optional int32 status = 3;\n optional int64 timestamp = 4;\n optional string uid = 5;\n }\n message ").concat(PBName.SetChrmKV, " {\n required ChrmKVEntity entry = 1;\n optional bool bNotify = 2;\n optional UpStreamMessage notification = 3;\n optional ChannelType type = 4;\n }\n message ").concat(PBName.ChrmKVOutput, " {\n repeated ChrmKVEntity entries = 1;\n optional bool bFullUpdate = 2;\n optional int64 syncTime = 3;\n }\n message ").concat(PBName.QueryChrmKV, " {\n required int64 timestamp = 1;\n }\n message ").concat(PBName.SetUserSettingInput, " {\n required int64 version=1;\n required string value=2;\n }\n message ").concat(PBName.SetUserSettingOutput, " {\n required int64 version=1;\n required bool reserve=2;\n }\n message ").concat(PBName.PullUserSettingInput, " {\n required int64 version=1;//\u5F53\u524D\u5BA2\u6237\u7AEF\u7684\u6700\u5927\u7248\u672C\u53F7\n optional bool reserve=2;\n }\n message ").concat(PBName.PullUserSettingOutput, " {\n repeated UserSettingItem items = 1;\n required int64 version=2;\n }\n message UserSettingItem {\n required string targetId= 1;\n required ChannelType type = 2;\n required string key = 4;\n required bytes value = 5;\n required int64 version=6;\n required int32 status=7;\n }\n message ").concat(PBName.SessionReq, " {\n required int64 time = 1;\n }\n message ").concat(PBName.SessionStates, " {\n required int64 version=1;\n repeated SessionState state= 2;\n }\n message ").concat(PBName.SessionState, " {\n required ChannelType type = 1;\n required string channelId = 2; \n optional int64 time = 3;\n repeated SessionStateItem stateItem = 4;\n }\n message ").concat(PBName.SessionStateItem, " {\n required SessionStateType sessionStateType = 1;\n required string value = 2;\n }\n enum SessionStateType {\n IsSilent = 1;\n IsTop = 2;\n }\n message ").concat(PBName.SessionStateModifyReq, " {\n required int64 version=1;\n repeated SessionState state= 2;\n }\n message ").concat(PBName.SessionStateModifyResp, " {\n required int64 version=1;\n }\n}\n"); function protobuf(a) { var c = function () { function a(a, b, c) { this.low = 0 | a, this.high = 0 | b, this.unsigned = !!c; } function b(a) { return (a && a.__isLong__) === !0; } function e(a, b) { var e, f, h; return b ? (a >>>= 0, (h = a >= 0 && a < 256) && (f = d[a]) ? f : (e = g(a, (0 | a) < 0 ? -1 : 0, !0), h && (d[a] = e), e)) : (a |= 0, (h = a >= -128 && a < 128) && (f = c[a]) ? f : (e = g(a, a < 0 ? -1 : 0, !1), h && (c[a] = e), e)); } function f(a, b) { if (isNaN(a) || !isFinite(a)) return b ? r : q; if (b) { if (a < 0) return r; if (a >= n) return w; } else { if (-o >= a) return x; if (a + 1 >= o) return v; } return a < 0 ? f(-a, b).neg() : g(0 | a % m, 0 | a / m, b); } function g(b, c, d) { return new a(b, c, d); } function i(a, b, c) { var d, e, g, j, k, l, m; if (a.length === 0) throw Error('empty string'); if (a === 'NaN' || a === 'Infinity' || a === '+Infinity' || a === '-Infinity') return q; if (typeof b === 'number' ? (c = b, b = !1) : b = !!b, c = c || 10, c < 2 || c > 36) throw RangeError('radix'); if ((d = a.indexOf('-')) > 0) throw Error('interior hyphen'); if (d === 0) return i(a.substring(1), b, c).neg(); for (e = f(h(c, 8)), g = q, j = 0; j < a.length; j += 8) { k = Math.min(8, a.length - j), l = parseInt(a.substring(j, j + k), c), k < 8 ? (m = f(h(c, k)), g = g.mul(m).add(f(l))) : (g = g.mul(e), g = g.add(f(l))); } return g.unsigned = b, g; } function j(b) { return b instanceof a ? b : typeof b === 'number' ? f(b) : typeof b === 'string' ? i(b) : g(b.low, b.high, b.unsigned); } var c, d, h, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y; return a.prototype.__isLong__, Object.defineProperty(a.prototype, '__isLong__', { value: !0, enumerable: !1, configurable: !1 }), a.isLong = b, c = {}, d = {}, a.fromInt = e, a.fromNumber = f, a.fromBits = g, h = Math.pow, a.fromString = i, a.fromValue = j, k = 65536, l = 1 << 24, m = k * k, n = m * m, o = n / 2, p = e(l), q = e(0), a.ZERO = q, r = e(0, !0), a.UZERO = r, s = e(1), a.ONE = s, t = e(1, !0), a.UONE = t, u = e(-1), a.NEG_ONE = u, v = g(-1, 2147483647, !1), a.MAX_VALUE = v, w = g(-1, -1, !0), a.MAX_UNSIGNED_VALUE = w, x = g(0, -2147483648, !1), a.MIN_VALUE = x, y = a.prototype, y.toInt = function () { return this.unsigned ? this.low >>> 0 : this.low; }, y.toNumber = function () { return this.unsigned ? (this.high >>> 0) * m + (this.low >>> 0) : this.high * m + (this.low >>> 0); }, y.toString = function (a) { var b, c, d, e, g, i, j, k, l; if (a = a || 10, a < 2 || a > 36) throw RangeError('radix'); if (this.isZero()) return '0'; if (this.isNegative()) return this.eq(x) ? (b = f(a), c = this.div(b), d = c.mul(b).sub(this), c.toString(a) + d.toInt().toString(a)) : '-' + this.neg().toString(a); for (e = f(h(a, 6), this.unsigned), g = this, i = '';;) { if (j = g.div(e), k = g.sub(j.mul(e)).toInt() >>> 0, l = k.toString(a), g = j, g.isZero()) return l + i; for (; l.length < 6;) { l = '0' + l; } i = '' + l + i; } }, y.getHighBits = function () { return this.high; }, y.getHighBitsUnsigned = function () { return this.high >>> 0; }, y.getLowBits = function () { return this.low; }, y.getLowBitsUnsigned = function () { return this.low >>> 0; }, y.getNumBitsAbs = function () { var a, b; if (this.isNegative()) return this.eq(x) ? 64 : this.neg().getNumBitsAbs(); for (a = this.high != 0 ? this.high : this.low, b = 31; b > 0 && (a & 1 << b) == 0; b--) { } return this.high != 0 ? b + 33 : b + 1; }, y.isZero = function () { return this.high === 0 && this.low === 0; }, y.isNegative = function () { return !this.unsigned && this.high < 0; }, y.isPositive = function () { return this.unsigned || this.high >= 0; }, y.isOdd = function () { return (1 & this.low) === 1; }, y.isEven = function () { return (1 & this.low) === 0; }, y.equals = function (a) { return b(a) || (a = j(a)), this.unsigned !== a.unsigned && this.high >>> 31 === 1 && a.high >>> 31 === 1 ? !1 : this.high === a.high && this.low === a.low; }, y.eq = y.equals, y.notEquals = function (a) { return !this.eq(a); }, y.neq = y.notEquals, y.lessThan = function (a) { return this.comp(a) < 0; }, y.lt = y.lessThan, y.lessThanOrEqual = function (a) { return this.comp(a) <= 0; }, y.lte = y.lessThanOrEqual, y.greaterThan = function (a) { return this.comp(a) > 0; }, y.gt = y.greaterThan, y.greaterThanOrEqual = function (a) { return this.comp(a) >= 0; }, y.gte = y.greaterThanOrEqual, y.compare = function (a) { if (b(a) || (a = j(a)), this.eq(a)) return 0; var c = this.isNegative(); var d = a.isNegative(); return c && !d ? -1 : !c && d ? 1 : this.unsigned ? a.high >>> 0 > this.high >>> 0 || a.high === this.high && a.low >>> 0 > this.low >>> 0 ? -1 : 1 : this.sub(a).isNegative() ? -1 : 1; }, y.comp = y.compare, y.negate = function () { return !this.unsigned && this.eq(x) ? x : this.not().add(s); }, y.neg = y.negate, y.add = function (a) { var c, d, e, f, h, i, k, l, m, n, o, p; return b(a) || (a = j(a)), c = this.high >>> 16, d = 65535 & this.high, e = this.low >>> 16, f = 65535 & this.low, h = a.high >>> 16, i = 65535 & a.high, k = a.low >>> 16, l = 65535 & a.low, m = 0, n = 0, o = 0, p = 0, p += f + l, o += p >>> 16, p &= 65535, o += e + k, n += o >>> 16, o &= 65535, n += d + i, m += n >>> 16, n &= 65535, m += c + h, m &= 65535, g(o << 16 | p, m << 16 | n, this.unsigned); }, y.subtract = function (a) { return b(a) || (a = j(a)), this.add(a.neg()); }, y.sub = y.subtract, y.multiply = function (a) { var c, d, e, h, i, k, l, m, n, o, r, s; return this.isZero() ? q : (b(a) || (a = j(a)), a.isZero() ? q : this.eq(x) ? a.isOdd() ? x : q : a.eq(x) ? this.isOdd() ? x : q : this.isNegative() ? a.isNegative() ? this.neg().mul(a.neg()) : this.neg().mul(a).neg() : a.isNegative() ? this.mul(a.neg()).neg() : this.lt(p) && a.lt(p) ? f(this.toNumber() * a.toNumber(), this.unsigned) : (c = this.high >>> 16, d = 65535 & this.high, e = this.low >>> 16, h = 65535 & this.low, i = a.high >>> 16, k = 65535 & a.high, l = a.low >>> 16, m = 65535 & a.low, n = 0, o = 0, r = 0, s = 0, s += h * m, r += s >>> 16, s &= 65535, r += e * m, o += r >>> 16, r &= 65535, r += h * l, o += r >>> 16, r &= 65535, o += d * m, n += o >>> 16, o &= 65535, o += e * l, n += o >>> 16, o &= 65535, o += h * k, n += o >>> 16, o &= 65535, n += c * m + d * l + e * k + h * i, n &= 65535, g(r << 16 | s, n << 16 | o, this.unsigned))); }, y.mul = y.multiply, y.divide = function (a) { var c, d, e, g, i, k, l, m; if (b(a) || (a = j(a)), a.isZero()) throw Error('division by zero'); if (this.isZero()) return this.unsigned ? r : q; if (this.unsigned) { if (a.unsigned || (a = a.toUnsigned()), a.gt(this)) return r; if (a.gt(this.shru(1))) return t; e = r; } else { if (this.eq(x)) return a.eq(s) || a.eq(u) ? x : a.eq(x) ? s : (g = this.shr(1), c = g.div(a).shl(1), c.eq(q) ? a.isNegative() ? s : u : (d = this.sub(a.mul(c)), e = c.add(d.div(a)))); if (a.eq(x)) return this.unsigned ? r : q; if (this.isNegative()) return a.isNegative() ? this.neg().div(a.neg()) : this.neg().div(a).neg(); if (a.isNegative()) return this.div(a.neg()).neg(); e = q; } for (d = this; d.gte(a);) { for (c = Math.max(1, Math.floor(d.toNumber() / a.toNumber())), i = Math.ceil(Math.log(c) / Math.LN2), k = i <= 48 ? 1 : h(2, i - 48), l = f(c), m = l.mul(a); m.isNegative() || m.gt(d);) { c -= k, l = f(c, this.unsigned), m = l.mul(a); } l.isZero() && (l = s), e = e.add(l), d = d.sub(m); } return e; }, y.div = y.divide, y.modulo = function (a) { return b(a) || (a = j(a)), this.sub(this.div(a).mul(a)); }, y.mod = y.modulo, y.not = function () { return g(~this.low, ~this.high, this.unsigned); }, y.and = function (a) { return b(a) || (a = j(a)), g(this.low & a.low, this.high & a.high, this.unsigned); }, y.or = function (a) { return b(a) || (a = j(a)), g(this.low | a.low, this.high | a.high, this.unsigned); }, y.xor = function (a) { return b(a) || (a = j(a)), g(this.low ^ a.low, this.high ^ a.high, this.unsigned); }, y.shiftLeft = function (a) { return b(a) && (a = a.toInt()), (a &= 63) === 0 ? this : a < 32 ? g(this.low << a, this.high << a | this.low >>> 32 - a, this.unsigned) : g(0, this.low << a - 32, this.unsigned); }, y.shl = y.shiftLeft, y.shiftRight = function (a) { return b(a) && (a = a.toInt()), (a &= 63) === 0 ? this : a < 32 ? g(this.low >>> a | this.high << 32 - a, this.high >> a, this.unsigned) : g(this.high >> a - 32, this.high >= 0 ? 0 : -1, this.unsigned); }, y.shr = y.shiftRight, y.shiftRightUnsigned = function (a) { var c, d; return b(a) && (a = a.toInt()), a &= 63, a === 0 ? this : (c = this.high, a < 32 ? (d = this.low, g(d >>> a | c << 32 - a, c >>> a, this.unsigned)) : a === 32 ? g(c, 0, this.unsigned) : g(c >>> a - 32, 0, this.unsigned)); }, y.shru = y.shiftRightUnsigned, y.toSigned = function () { return this.unsigned ? g(this.low, this.high, !1) : this; }, y.toUnsigned = function () { return this.unsigned ? this : g(this.low, this.high, !0); }, y.toBytes = function (a) { return a ? this.toBytesLE() : this.toBytesBE(); }, y.toBytesLE = function () { var a = this.high; var b = this.low; return [255 & b, 255 & b >>> 8, 255 & b >>> 16, 255 & b >>> 24, 255 & a, 255 & a >>> 8, 255 & a >>> 16, 255 & a >>> 24]; }, y.toBytesBE = function () { var a = this.high; var b = this.low; return [255 & a >>> 24, 255 & a >>> 16, 255 & a >>> 8, 255 & a, 255 & b >>> 24, 255 & b >>> 16, 255 & b >>> 8, 255 & b]; }, a; }(); var d = function (a) { function f(a) { var b = 0; return function () { return b < a.length ? a.charCodeAt(b++) : null; }; } function g() { var a = []; var b = []; return function () { return arguments.length === 0 ? b.join('') + e.apply(String, a) : (a.length + arguments.length > 1024 && (b.push(e.apply(String, a)), a.length = 0), Array.prototype.push.apply(a, arguments), void 0); }; } function h(a, b, c, d, e) { var f; var g; var h = 8 * e - d - 1; var i = (1 << h) - 1; var j = i >> 1; var k = -7; var l = c ? e - 1 : 0; var m = c ? -1 : 1; var n = a[b + l]; for (l += m, f = n & (1 << -k) - 1, n >>= -k, k += h; k > 0; f = 256 * f + a[b + l], l += m, k -= 8) { } for (g = f & (1 << -k) - 1, f >>= -k, k += d; k > 0; g = 256 * g + a[b + l], l += m, k -= 8) { } if (f === 0) f = 1 - j;else { if (f === i) return g ? 0 / 0 : 1 / 0 * (n ? -1 : 1); g += Math.pow(2, d), f -= j; } return (n ? -1 : 1) * g * Math.pow(2, f - d); } function i(a, b, c, d, e, f) { var g; var h; var i; var j = 8 * f - e - 1; var k = (1 << j) - 1; var l = k >> 1; var m = e === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0; var n = d ? 0 : f - 1; var o = d ? 1 : -1; var p = b < 0 || b === 0 && 1 / b < 0 ? 1 : 0; for (b = Math.abs(b), isNaN(b) || 1 / 0 === b ? (h = isNaN(b) ? 1 : 0, g = k) : (g = Math.floor(Math.log(b) / Math.LN2), b * (i = Math.pow(2, -g)) < 1 && (g--, i *= 2), b += g + l >= 1 ? m / i : m * Math.pow(2, 1 - l), b * i >= 2 && (g++, i /= 2), g + l >= k ? (h = 0, g = k) : g + l >= 1 ? (h = (b * i - 1) * Math.pow(2, e), g += l) : (h = b * Math.pow(2, l - 1) * Math.pow(2, e), g = 0)); e >= 8; a[c + n] = 255 & h, n += o, h /= 256, e -= 8) { } for (g = g << e | h, j += e; j > 0; a[c + n] = 255 & g, n += o, g /= 256, j -= 8) { } a[c + n - o] |= 128 * p; } var c; var d; var e; var j; var k; var b = function b(a, c, e) { if (typeof a === 'undefined' && (a = b.DEFAULT_CAPACITY), typeof c === 'undefined' && (c = b.DEFAULT_ENDIAN), typeof e === 'undefined' && (e = b.DEFAULT_NOASSERT), !e) { if (a = 0 | a, a < 0) throw RangeError('Illegal capacity'); c = !!c, e = !!e; } this.buffer = a === 0 ? d : new ArrayBuffer(a), this.view = a === 0 ? null : new Uint8Array(this.buffer), this.offset = 0, this.markedOffset = -1, this.limit = a, this.littleEndian = c, this.noAssert = e; }; return b.VERSION = '5.0.1', b.LITTLE_ENDIAN = !0, b.BIG_ENDIAN = !1, b.DEFAULT_CAPACITY = 16, b.DEFAULT_ENDIAN = b.BIG_ENDIAN, b.DEFAULT_NOASSERT = !1, b.Long = a || null, c = b.prototype, c.__isByteBuffer__, Object.defineProperty(c, '__isByteBuffer__', { value: !0, enumerable: !1, configurable: !1 }), d = new ArrayBuffer(0), e = String.fromCharCode, b.accessor = function () { return Uint8Array; }, b.allocate = function (a, c, d) { return new b(a, c, d); }, b.concat = function (a, c, d, e) { var f, i, g, h, k, j; for ((typeof c === 'boolean' || typeof c !== 'string') && (e = d, d = c, c = void 0), f = 0, g = 0, h = a.length; h > g; ++g) { b.isByteBuffer(a[g]) || (a[g] = b.wrap(a[g], c)), i = a[g].limit - a[g].offset, i > 0 && (f += i); } if (f === 0) return new b(0, d, e); for (j = new b(f, d, e), g = 0; h > g;) { k = a[g++], i = k.limit - k.offset, i <= 0 || (j.view.set(k.view.subarray(k.offset, k.limit), j.offset), j.offset += i); } return j.limit = j.offset, j.offset = 0, j; }, b.isByteBuffer = function (a) { return (a && a.__isByteBuffer__) === !0; }, b.type = function () { return ArrayBuffer; }, b.wrap = function (a, d, e, f) { var g, h; if (typeof d !== 'string' && (f = e, e = d, d = void 0), typeof a === 'string') switch (typeof d === 'undefined' && (d = 'utf8'), d) { case 'base64': return b.fromBase64(a, e); case 'hex': return b.fromHex(a, e); case 'binary': return b.fromBinary(a, e); case 'utf8': return b.fromUTF8(a, e); case 'debug': return b.fromDebug(a, e); default: throw Error('Unsupported encoding: ' + d); } if (a === null || _typeof(a) !== 'object') throw TypeError('Illegal buffer'); if (b.isByteBuffer(a)) return g = c.clone.call(a), g.markedOffset = -1, g; if (a instanceof Uint8Array) g = new b(0, e, f), a.length > 0 && (g.buffer = a.buffer, g.offset = a.byteOffset, g.limit = a.byteOffset + a.byteLength, g.view = new Uint8Array(a.buffer));else if (a instanceof ArrayBuffer) g = new b(0, e, f), a.byteLength > 0 && (g.buffer = a, g.offset = 0, g.limit = a.byteLength, g.view = a.byteLength > 0 ? new Uint8Array(a) : null);else { if (Object.prototype.toString.call(a) !== '[object Array]') throw TypeError('Illegal buffer'); for (g = new b(a.length, e, f), g.limit = a.length, h = 0; h < a.length; ++h) { g.view[h] = a[h]; } } return g; }, c.writeBitSet = function (a, b) { var h; var d; var e; var f; var g; var i; var c = typeof b === 'undefined'; if (c && (b = this.offset), !this.noAssert) { if (!(a instanceof Array)) throw TypeError('Illegal BitSet: Not an array'); if (typeof b !== 'number' || b % 1 !== 0) throw TypeError('Illegal offset: ' + b + ' (not an integer)'); if (b >>>= 0, b < 0 || b + 0 > this.buffer.byteLength) throw RangeError('Illegal offset: 0 <= ' + b + ' (+' + 0 + ') <= ' + this.buffer.byteLength); } for (d = b, e = a.length, f = e >> 3, g = 0, b += this.writeVarint32(e, b); f--;) { h = 1 & !!a[g++] | (1 & !!a[g++]) << 1 | (1 & !!a[g++]) << 2 | (1 & !!a[g++]) << 3 | (1 & !!a[g++]) << 4 | (1 & !!a[g++]) << 5 | (1 & !!a[g++]) << 6 | (1 & !!a[g++]) << 7, this.writeByte(h, b++); } if (e > g) { for (i = 0, h = 0; e > g;) { h |= (1 & !!a[g++]) << i++; } this.writeByte(h, b++); } return c ? (this.offset = b, this) : b - d; }, c.readBitSet = function (a) { var h; var c; var d; var e; var f; var g; var i; var b = typeof a === 'undefined'; for (b && (a = this.offset), c = this.readVarint32(a), d = c.value, e = d >> 3, f = 0, g = [], a += c.length; e--;) { h = this.readByte(a++), g[f++] = !!(1 & h), g[f++] = !!(2 & h), g[f++] = !!(4 & h), g[f++] = !!(8 & h), g[f++] = !!(16 & h), g[f++] = !!(32 & h), g[f++] = !!(64 & h), g[f++] = !!(128 & h); } if (d > f) for (i = 0, h = this.readByte(a++); d > f;) { g[f++] = !!(1 & h >> i++); } return b && (this.offset = a), g; }, c.readBytes = function (a, b) { var d; var c = typeof b === 'undefined'; if (c && (b = this.offset), !this.noAssert) { if (typeof b !== 'number' || b % 1 !== 0) throw TypeError('Illegal offset: ' + b + ' (not an integer)'); if (b >>>= 0, b < 0 || b + a > this.buffer.byteLength) throw RangeError('Illegal offset: 0 <= ' + b + ' (+' + a + ') <= ' + this.buffer.byteLength); } return d = this.slice(b, b + a), c && (this.offset += a), d; }, c.writeBytes = c.append, c.writeInt8 = function (a, b) { var d; var c = typeof b === 'undefined'; if (c && (b = this.offset), !this.noAssert) { if (typeof a !== 'number' || a % 1 !== 0) throw TypeError('Illegal value: ' + a + ' (not an integer)'); if (a |= 0, typeof b !== 'number' || b % 1 !== 0) throw TypeError('Illegal offset: ' + b + ' (not an integer)'); if (b >>>= 0, b < 0 || b + 0 > this.buffer.byteLength) throw RangeError('Illegal offset: 0 <= ' + b + ' (+' + 0 + ') <= ' + this.buffer.byteLength); } return b += 1, d = this.buffer.byteLength, b > d && this.resize((d *= 2) > b ? d : b), b -= 1, this.view[b] = a, c && (this.offset += 1), this; }, c.writeByte = c.writeInt8, c.readInt8 = function (a) { var c; var b = typeof a === 'undefined'; if (b && (a = this.offset), !this.noAssert) { if (typeof a !== 'number' || a % 1 !== 0) throw TypeError('Illegal offset: ' + a + ' (not an integer)'); if (a >>>= 0, a < 0 || a + 1 > this.buffer.byteLength) throw RangeError('Illegal offset: 0 <= ' + a + ' (+' + 1 + ') <= ' + this.buffer.byteLength); } return c = this.view[a], (128 & c) === 128 && (c = -(255 - c + 1)), b && (this.offset += 1), c; }, c.readByte = c.readInt8, c.writeUint8 = function (a, b) { var d; var c = typeof b === 'undefined'; if (c && (b = this.offset), !this.noAssert) { if (typeof a !== 'number' || a % 1 !== 0) throw TypeError('Illegal value: ' + a + ' (not an integer)'); if (a >>>= 0, typeof b !== 'number' || b % 1 !== 0) throw TypeError('Illegal offset: ' + b + ' (not an integer)'); if (b >>>= 0, b < 0 || b + 0 > this.buffer.byteLength) throw RangeError('Illegal offset: 0 <= ' + b + ' (+' + 0 + ') <= ' + this.buffer.byteLength); } return b += 1, d = this.buffer.byteLength, b > d && this.resize((d *= 2) > b ? d : b), b -= 1, this.view[b] = a, c && (this.offset += 1), this; }, c.writeUInt8 = c.writeUint8, c.readUint8 = function (a) { var c; var b = typeof a === 'undefined'; if (b && (a = this.offset), !this.noAssert) { if (typeof a !== 'number' || a % 1 !== 0) throw TypeError('Illegal offset: ' + a + ' (not an integer)'); if (a >>>= 0, a < 0 || a + 1 > this.buffer.byteLength) throw RangeError('Illegal offset: 0 <= ' + a + ' (+' + 1 + ') <= ' + this.buffer.byteLength); } return c = this.view[a], b && (this.offset += 1), c; }, c.readUInt8 = c.readUint8, c.writeInt16 = function (a, b) { var d; var c = typeof b === 'undefined'; if (c && (b = this.offset), !this.noAssert) { if (typeof a !== 'number' || a % 1 !== 0) throw TypeError('Illegal value: ' + a + ' (not an integer)'); if (a |= 0, typeof b !== 'number' || b % 1 !== 0) throw TypeError('Illegal offset: ' + b + ' (not an integer)'); if (b >>>= 0, b < 0 || b + 0 > this.buffer.byteLength) throw RangeError('Illegal offset: 0 <= ' + b + ' (+' + 0 + ') <= ' + this.buffer.byteLength); } return b += 2, d = this.buffer.byteLength, b > d && this.resize((d *= 2) > b ? d : b), b -= 2, this.littleEndian ? (this.view[b + 1] = (65280 & a) >>> 8, this.view[b] = 255 & a) : (this.view[b] = (65280 & a) >>> 8, this.view[b + 1] = 255 & a), c && (this.offset += 2), this; }, c.writeShort = c.writeInt16, c.readInt16 = function (a) { var c; var b = typeof a === 'undefined'; if (b && (a = this.offset), !this.noAssert) { if (typeof a !== 'number' || a % 1 !== 0) throw TypeError('Illegal offset: ' + a + ' (not an integer)'); if (a >>>= 0, a < 0 || a + 2 > this.buffer.byteLength) throw RangeError('Illegal offset: 0 <= ' + a + ' (+' + 2 + ') <= ' + this.buffer.byteLength); } return c = 0, this.littleEndian ? (c = this.view[a], c |= this.view[a + 1] << 8) : (c = this.view[a] << 8, c |= this.view[a + 1]), (32768 & c) === 32768 && (c = -(65535 - c + 1)), b && (this.offset += 2), c; }, c.readShort = c.readInt16, c.writeUint16 = function (a, b) { var d; var c = typeof b === 'undefined'; if (c && (b = this.offset), !this.noAssert) { if (typeof a !== 'number' || a % 1 !== 0) throw TypeError('Illegal value: ' + a + ' (not an integer)'); if (a >>>= 0, typeof b !== 'number' || b % 1 !== 0) throw TypeError('Illegal offset: ' + b + ' (not an integer)'); if (b >>>= 0, b < 0 || b + 0 > this.buffer.byteLength) throw RangeError('Illegal offset: 0 <= ' + b + ' (+' + 0 + ') <= ' + this.buffer.byteLength); } return b += 2, d = this.buffer.byteLength, b > d && this.resize((d *= 2) > b ? d : b), b -= 2, this.littleEndian ? (this.view[b + 1] = (65280 & a) >>> 8, this.view[b] = 255 & a) : (this.view[b] = (65280 & a) >>> 8, this.view[b + 1] = 255 & a), c && (this.offset += 2), this; }, c.writeUInt16 = c.writeUint16, c.readUint16 = function (a) { var c; var b = typeof a === 'undefined'; if (b && (a = this.offset), !this.noAssert) { if (typeof a !== 'number' || a % 1 !== 0) throw TypeError('Illegal offset: ' + a + ' (not an integer)'); if (a >>>= 0, a < 0 || a + 2 > this.buffer.byteLength) throw RangeError('Illegal offset: 0 <= ' + a + ' (+' + 2 + ') <= ' + this.buffer.byteLength); } return c = 0, this.littleEndian ? (c = this.view[a], c |= this.view[a + 1] << 8) : (c = this.view[a] << 8, c |= this.view[a + 1]), b && (this.offset += 2), c; }, c.readUInt16 = c.readUint16, c.writeInt32 = function (a, b) { var d; var c = typeof b === 'undefined'; if (c && (b = this.offset), !this.noAssert) { if (typeof a !== 'number' || a % 1 !== 0) throw TypeError('Illegal value: ' + a + ' (not an integer)'); if (a |= 0, typeof b !== 'number' || b % 1 !== 0) throw TypeError('Illegal offset: ' + b + ' (not an integer)'); if (b >>>= 0, b < 0 || b + 0 > this.buffer.byteLength) throw RangeError('Illegal offset: 0 <= ' + b + ' (+' + 0 + ') <= ' + this.buffer.byteLength); } return b += 4, d = this.buffer.byteLength, b > d && this.resize((d *= 2) > b ? d : b), b -= 4, this.littleEndian ? (this.view[b + 3] = 255 & a >>> 24, this.view[b + 2] = 255 & a >>> 16, this.view[b + 1] = 255 & a >>> 8, this.view[b] = 255 & a) : (this.view[b] = 255 & a >>> 24, this.view[b + 1] = 255 & a >>> 16, this.view[b + 2] = 255 & a >>> 8, this.view[b + 3] = 255 & a), c && (this.offset += 4), this; }, c.writeInt = c.writeInt32, c.readInt32 = function (a) { var c; var b = typeof a === 'undefined'; if (b && (a = this.offset), !this.noAssert) { if (typeof a !== 'number' || a % 1 !== 0) throw TypeError('Illegal offset: ' + a + ' (not an integer)'); if (a >>>= 0, a < 0 || a + 4 > this.buffer.byteLength) throw RangeError('Illegal offset: 0 <= ' + a + ' (+' + 4 + ') <= ' + this.buffer.byteLength); } return c = 0, this.littleEndian ? (c = this.view[a + 2] << 16, c |= this.view[a + 1] << 8, c |= this.view[a], c += this.view[a + 3] << 24 >>> 0) : (c = this.view[a + 1] << 16, c |= this.view[a + 2] << 8, c |= this.view[a + 3], c += this.view[a] << 24 >>> 0), c |= 0, b && (this.offset += 4), c; }, c.readInt = c.readInt32, c.writeUint32 = function (a, b) { var d; var c = typeof b === 'undefined'; if (c && (b = this.offset), !this.noAssert) { if (typeof a !== 'number' || a % 1 !== 0) throw TypeError('Illegal value: ' + a + ' (not an integer)'); if (a >>>= 0, typeof b !== 'number' || b % 1 !== 0) throw TypeError('Illegal offset: ' + b + ' (not an integer)'); if (b >>>= 0, b < 0 || b + 0 > this.buffer.byteLength) throw RangeError('Illegal offset: 0 <= ' + b + ' (+' + 0 + ') <= ' + this.buffer.byteLength); } return b += 4, d = this.buffer.byteLength, b > d && this.resize((d *= 2) > b ? d : b), b -= 4, this.littleEndian ? (this.view[b + 3] = 255 & a >>> 24, this.view[b + 2] = 255 & a >>> 16, this.view[b + 1] = 255 & a >>> 8, this.view[b] = 255 & a) : (this.view[b] = 255 & a >>> 24, this.view[b + 1] = 255 & a >>> 16, this.view[b + 2] = 255 & a >>> 8, this.view[b + 3] = 255 & a), c && (this.offset += 4), this; }, c.writeUInt32 = c.writeUint32, c.readUint32 = function (a) { var c; var b = typeof a === 'undefined'; if (b && (a = this.offset), !this.noAssert) { if (typeof a !== 'number' || a % 1 !== 0) throw TypeError('Illegal offset: ' + a + ' (not an integer)'); if (a >>>= 0, a < 0 || a + 4 > this.buffer.byteLength) throw RangeError('Illegal offset: 0 <= ' + a + ' (+' + 4 + ') <= ' + this.buffer.byteLength); } return c = 0, this.littleEndian ? (c = this.view[a + 2] << 16, c |= this.view[a + 1] << 8, c |= this.view[a], c += this.view[a + 3] << 24 >>> 0) : (c = this.view[a + 1] << 16, c |= this.view[a + 2] << 8, c |= this.view[a + 3], c += this.view[a] << 24 >>> 0), b && (this.offset += 4), c; }, c.readUInt32 = c.readUint32, a && (c.writeInt64 = function (b, c) { var e; var f; var g; var d = typeof c === 'undefined'; if (d && (c = this.offset), !this.noAssert) { if (typeof b === 'number') b = a.fromNumber(b);else if (typeof b === 'string') b = a.fromString(b);else if (!(b && b instanceof a)) throw TypeError('Illegal value: ' + b + ' (not an integer or Long)'); if (typeof c !== 'number' || c % 1 !== 0) throw TypeError('Illegal offset: ' + c + ' (not an integer)'); if (c >>>= 0, c < 0 || c + 0 > this.buffer.byteLength) throw RangeError('Illegal offset: 0 <= ' + c + ' (+' + 0 + ') <= ' + this.buffer.byteLength); } return typeof b === 'number' ? b = a.fromNumber(b) : typeof b === 'string' && (b = a.fromString(b)), c += 8, e = this.buffer.byteLength, c > e && this.resize((e *= 2) > c ? e : c), c -= 8, f = b.low, g = b.high, this.littleEndian ? (this.view[c + 3] = 255 & f >>> 24, this.view[c + 2] = 255 & f >>> 16, this.view[c + 1] = 255 & f >>> 8, this.view[c] = 255 & f, c += 4, this.view[c + 3] = 255 & g >>> 24, this.view[c + 2] = 255 & g >>> 16, this.view[c + 1] = 255 & g >>> 8, this.view[c] = 255 & g) : (this.view[c] = 255 & g >>> 24, this.view[c + 1] = 255 & g >>> 16, this.view[c + 2] = 255 & g >>> 8, this.view[c + 3] = 255 & g, c += 4, this.view[c] = 255 & f >>> 24, this.view[c + 1] = 255 & f >>> 16, this.view[c + 2] = 255 & f >>> 8, this.view[c + 3] = 255 & f), d && (this.offset += 8), this; }, c.writeLong = c.writeInt64, c.readInt64 = function (b) { var d; var e; var f; var c = typeof b === 'undefined'; if (c && (b = this.offset), !this.noAssert) { if (typeof b !== 'number' || b % 1 !== 0) throw TypeError('Illegal offset: ' + b + ' (not an integer)'); if (b >>>= 0, b < 0 || b + 8 > this.buffer.byteLength) throw RangeError('Illegal offset: 0 <= ' + b + ' (+' + 8 + ') <= ' + this.buffer.byteLength); } return d = 0, e = 0, this.littleEndian ? (d = this.view[b + 2] << 16, d |= this.view[b + 1] << 8, d |= this.view[b], d += this.view[b + 3] << 24 >>> 0, b += 4, e = this.view[b + 2] << 16, e |= this.view[b + 1] << 8, e |= this.view[b], e += this.view[b + 3] << 24 >>> 0) : (e = this.view[b + 1] << 16, e |= this.view[b + 2] << 8, e |= this.view[b + 3], e += this.view[b] << 24 >>> 0, b += 4, d = this.view[b + 1] << 16, d |= this.view[b + 2] << 8, d |= this.view[b + 3], d += this.view[b] << 24 >>> 0), f = new a(d, e, !1), c && (this.offset += 8), f; }, c.readLong = c.readInt64, c.writeUint64 = function (b, c) { var e; var f; var g; var d = typeof c === 'undefined'; if (d && (c = this.offset), !this.noAssert) { if (typeof b === 'number') b = a.fromNumber(b);else if (typeof b === 'string') b = a.fromString(b);else if (!(b && b instanceof a)) throw TypeError('Illegal value: ' + b + ' (not an integer or Long)'); if (typeof c !== 'number' || c % 1 !== 0) throw TypeError('Illegal offset: ' + c + ' (not an integer)'); if (c >>>= 0, c < 0 || c + 0 > this.buffer.byteLength) throw RangeError('Illegal offset: 0 <= ' + c + ' (+' + 0 + ') <= ' + this.buffer.byteLength); } return typeof b === 'number' ? b = a.fromNumber(b) : typeof b === 'string' && (b = a.fromString(b)), c += 8, e = this.buffer.byteLength, c > e && this.resize((e *= 2) > c ? e : c), c -= 8, f = b.low, g = b.high, this.littleEndian ? (this.view[c + 3] = 255 & f >>> 24, this.view[c + 2] = 255 & f >>> 16, this.view[c + 1] = 255 & f >>> 8, this.view[c] = 255 & f, c += 4, this.view[c + 3] = 255 & g >>> 24, this.view[c + 2] = 255 & g >>> 16, this.view[c + 1] = 255 & g >>> 8, this.view[c] = 255 & g) : (this.view[c] = 255 & g >>> 24, this.view[c + 1] = 255 & g >>> 16, this.view[c + 2] = 255 & g >>> 8, this.view[c + 3] = 255 & g, c += 4, this.view[c] = 255 & f >>> 24, this.view[c + 1] = 255 & f >>> 16, this.view[c + 2] = 255 & f >>> 8, this.view[c + 3] = 255 & f), d && (this.offset += 8), this; }, c.writeUInt64 = c.writeUint64, c.readUint64 = function (b) { var d; var e; var f; var c = typeof b === 'undefined'; if (c && (b = this.offset), !this.noAssert) { if (typeof b !== 'number' || b % 1 !== 0) throw TypeError('Illegal offset: ' + b + ' (not an integer)'); if (b >>>= 0, b < 0 || b + 8 > this.buffer.byteLength) throw RangeError('Illegal offset: 0 <= ' + b + ' (+' + 8 + ') <= ' + this.buffer.byteLength); } return d = 0, e = 0, this.littleEndian ? (d = this.view[b + 2] << 16, d |= this.view[b + 1] << 8, d |= this.view[b], d += this.view[b + 3] << 24 >>> 0, b += 4, e = this.view[b + 2] << 16, e |= this.view[b + 1] << 8, e |= this.view[b], e += this.view[b + 3] << 24 >>> 0) : (e = this.view[b + 1] << 16, e |= this.view[b + 2] << 8, e |= this.view[b + 3], e += this.view[b] << 24 >>> 0, b += 4, d = this.view[b + 1] << 16, d |= this.view[b + 2] << 8, d |= this.view[b + 3], d += this.view[b] << 24 >>> 0), f = new a(d, e, !0), c && (this.offset += 8), f; }, c.readUInt64 = c.readUint64), c.writeFloat32 = function (a, b) { var d; var c = typeof b === 'undefined'; if (c && (b = this.offset), !this.noAssert) { if (typeof a !== 'number') throw TypeError('Illegal value: ' + a + ' (not a number)'); if (typeof b !== 'number' || b % 1 !== 0) throw TypeError('Illegal offset: ' + b + ' (not an integer)'); if (b >>>= 0, b < 0 || b + 0 > this.buffer.byteLength) throw RangeError('Illegal offset: 0 <= ' + b + ' (+' + 0 + ') <= ' + this.buffer.byteLength); } return b += 4, d = this.buffer.byteLength, b > d && this.resize((d *= 2) > b ? d : b), b -= 4, i(this.view, a, b, this.littleEndian, 23, 4), c && (this.offset += 4), this; }, c.writeFloat = c.writeFloat32, c.readFloat32 = function (a) { var c; var b = typeof a === 'undefined'; if (b && (a = this.offset), !this.noAssert) { if (typeof a !== 'number' || a % 1 !== 0) throw TypeError('Illegal offset: ' + a + ' (not an integer)'); if (a >>>= 0, a < 0 || a + 4 > this.buffer.byteLength) throw RangeError('Illegal offset: 0 <= ' + a + ' (+' + 4 + ') <= ' + this.buffer.byteLength); } return c = h(this.view, a, this.littleEndian, 23, 4), b && (this.offset += 4), c; }, c.readFloat = c.readFloat32, c.writeFloat64 = function (a, b) { var d; var c = typeof b === 'undefined'; if (c && (b = this.offset), !this.noAssert) { if (typeof a !== 'number') throw TypeError('Illegal value: ' + a + ' (not a number)'); if (typeof b !== 'number' || b % 1 !== 0) throw TypeError('Illegal offset: ' + b + ' (not an integer)'); if (b >>>= 0, b < 0 || b + 0 > this.buffer.byteLength) throw RangeError('Illegal offset: 0 <= ' + b + ' (+' + 0 + ') <= ' + this.buffer.byteLength); } return b += 8, d = this.buffer.byteLength, b > d && this.resize((d *= 2) > b ? d : b), b -= 8, i(this.view, a, b, this.littleEndian, 52, 8), c && (this.offset += 8), this; }, c.writeDouble = c.writeFloat64, c.readFloat64 = function (a) { var c; var b = typeof a === 'undefined'; if (b && (a = this.offset), !this.noAssert) { if (typeof a !== 'number' || a % 1 !== 0) throw TypeError('Illegal offset: ' + a + ' (not an integer)'); if (a >>>= 0, a < 0 || a + 8 > this.buffer.byteLength) throw RangeError('Illegal offset: 0 <= ' + a + ' (+' + 8 + ') <= ' + this.buffer.byteLength); } return c = h(this.view, a, this.littleEndian, 52, 8), b && (this.offset += 8), c; }, c.readDouble = c.readFloat64, b.MAX_VARINT32_BYTES = 5, b.calculateVarint32 = function (a) { return a >>>= 0, a < 128 ? 1 : a < 16384 ? 2 : 1 << 21 > a ? 3 : 1 << 28 > a ? 4 : 5; }, b.zigZagEncode32 = function (a) { return ((a |= 0) << 1 ^ a >> 31) >>> 0; }, b.zigZagDecode32 = function (a) { return 0 | a >>> 1 ^ -(1 & a); }, c.writeVarint32 = function (a, c) { var f; var e; var g; var d = typeof c === 'undefined'; if (d && (c = this.offset), !this.noAssert) { if (typeof a !== 'number' || a % 1 !== 0) throw TypeError('Illegal value: ' + a + ' (not an integer)'); if (a |= 0, typeof c !== 'number' || c % 1 !== 0) throw TypeError('Illegal offset: ' + c + ' (not an integer)'); if (c >>>= 0, c < 0 || c + 0 > this.buffer.byteLength) throw RangeError('Illegal offset: 0 <= ' + c + ' (+' + 0 + ') <= ' + this.buffer.byteLength); } for (e = b.calculateVarint32(a), c += e, g = this.buffer.byteLength, c > g && this.resize((g *= 2) > c ? g : c), c -= e, a >>>= 0; a >= 128;) { f = 128 | 127 & a, this.view[c++] = f, a >>>= 7; } return this.view[c++] = a, d ? (this.offset = c, this) : e; }, c.writeVarint32ZigZag = function (a, c) { return this.writeVarint32(b.zigZagEncode32(a), c); }, c.readVarint32 = function (a) { var e; var c; var d; var f; var b = typeof a === 'undefined'; if (b && (a = this.offset), !this.noAssert) { if (typeof a !== 'number' || a % 1 !== 0) throw TypeError('Illegal offset: ' + a + ' (not an integer)'); if (a >>>= 0, a < 0 || a + 1 > this.buffer.byteLength) throw RangeError('Illegal offset: 0 <= ' + a + ' (+' + 1 + ') <= ' + this.buffer.byteLength); } c = 0, d = 0; do { if (!this.noAssert && a > this.limit) throw f = Error('Truncated'), f.truncated = !0, f; e = this.view[a++], c < 5 && (d |= (127 & e) << 7 * c), ++c; } while ((128 & e) !== 0); return d |= 0, b ? (this.offset = a, d) : { value: d, length: c }; }, c.readVarint32ZigZag = function (a) { var c = this.readVarint32(a); return _typeof(c) === 'object' ? c.value = b.zigZagDecode32(c.value) : c = b.zigZagDecode32(c), c; }, a && (b.MAX_VARINT64_BYTES = 10, b.calculateVarint64 = function (b) { typeof b === 'number' ? b = a.fromNumber(b) : typeof b === 'string' && (b = a.fromString(b)); var c = b.toInt() >>> 0; var d = b.shiftRightUnsigned(28).toInt() >>> 0; var e = b.shiftRightUnsigned(56).toInt() >>> 0; return e == 0 ? d == 0 ? c < 16384 ? c < 128 ? 1 : 2 : 1 << 21 > c ? 3 : 4 : d < 16384 ? d < 128 ? 5 : 6 : 1 << 21 > d ? 7 : 8 : e < 128 ? 9 : 10; }, b.zigZagEncode64 = function (b) { return typeof b === 'number' ? b = a.fromNumber(b, !1) : typeof b === 'string' ? b = a.fromString(b, !1) : b.unsigned !== !1 && (b = b.toSigned()), b.shiftLeft(1).xor(b.shiftRight(63)).toUnsigned(); }, b.zigZagDecode64 = function (b) { return typeof b === 'number' ? b = a.fromNumber(b, !1) : typeof b === 'string' ? b = a.fromString(b, !1) : b.unsigned !== !1 && (b = b.toSigned()), b.shiftRightUnsigned(1).xor(b.and(a.ONE).toSigned().negate()).toSigned(); }, c.writeVarint64 = function (c, d) { var f; var g; var h; var i; var j; var e = typeof d === 'undefined'; if (e && (d = this.offset), !this.noAssert) { if (typeof c === 'number') c = a.fromNumber(c);else if (typeof c === 'string') c = a.fromString(c);else if (!(c && c instanceof a)) throw TypeError('Illegal value: ' + c + ' (not an integer or Long)'); if (typeof d !== 'number' || d % 1 !== 0) throw TypeError('Illegal offset: ' + d + ' (not an integer)'); if (d >>>= 0, d < 0 || d + 0 > this.buffer.byteLength) throw RangeError('Illegal offset: 0 <= ' + d + ' (+' + 0 + ') <= ' + this.buffer.byteLength); } switch (typeof c === 'number' ? c = a.fromNumber(c, !1) : typeof c === 'string' ? c = a.fromString(c, !1) : c.unsigned !== !1 && (c = c.toSigned()), f = b.calculateVarint64(c), g = c.toInt() >>> 0, h = c.shiftRightUnsigned(28).toInt() >>> 0, i = c.shiftRightUnsigned(56).toInt() >>> 0, d += f, j = this.buffer.byteLength, d > j && this.resize((j *= 2) > d ? j : d), d -= f, f) { case 10: this.view[d + 9] = 1 & i >>> 7; case 9: this.view[d + 8] = f !== 9 ? 128 | i : 127 & i; case 8: this.view[d + 7] = f !== 8 ? 128 | h >>> 21 : 127 & h >>> 21; case 7: this.view[d + 6] = f !== 7 ? 128 | h >>> 14 : 127 & h >>> 14; case 6: this.view[d + 5] = f !== 6 ? 128 | h >>> 7 : 127 & h >>> 7; case 5: this.view[d + 4] = f !== 5 ? 128 | h : 127 & h; case 4: this.view[d + 3] = f !== 4 ? 128 | g >>> 21 : 127 & g >>> 21; case 3: this.view[d + 2] = f !== 3 ? 128 | g >>> 14 : 127 & g >>> 14; case 2: this.view[d + 1] = f !== 2 ? 128 | g >>> 7 : 127 & g >>> 7; case 1: this.view[d] = f !== 1 ? 128 | g : 127 & g; } return e ? (this.offset += f, this) : f; }, c.writeVarint64ZigZag = function (a, c) { return this.writeVarint64(b.zigZagEncode64(a), c); }, c.readVarint64 = function (b) { var d; var e; var f; var g; var h; var i; var c = typeof b === 'undefined'; if (c && (b = this.offset), !this.noAssert) { if (typeof b !== 'number' || b % 1 !== 0) throw TypeError('Illegal offset: ' + b + ' (not an integer)'); if (b >>>= 0, b < 0 || b + 1 > this.buffer.byteLength) throw RangeError('Illegal offset: 0 <= ' + b + ' (+' + 1 + ') <= ' + this.buffer.byteLength); } if (d = b, e = 0, f = 0, g = 0, h = 0, h = this.view[b++], e = 127 & h, 128 & h && (h = this.view[b++], e |= (127 & h) << 7, (128 & h || this.noAssert && typeof h === 'undefined') && (h = this.view[b++], e |= (127 & h) << 14, (128 & h || this.noAssert && typeof h === 'undefined') && (h = this.view[b++], e |= (127 & h) << 21, (128 & h || this.noAssert && typeof h === 'undefined') && (h = this.view[b++], f = 127 & h, (128 & h || this.noAssert && typeof h === 'undefined') && (h = this.view[b++], f |= (127 & h) << 7, (128 & h || this.noAssert && typeof h === 'undefined') && (h = this.view[b++], f |= (127 & h) << 14, (128 & h || this.noAssert && typeof h === 'undefined') && (h = this.view[b++], f |= (127 & h) << 21, (128 & h || this.noAssert && typeof h === 'undefined') && (h = this.view[b++], g = 127 & h, (128 & h || this.noAssert && typeof h === 'undefined') && (h = this.view[b++], g |= (127 & h) << 7, 128 & h || this.noAssert && typeof h === 'undefined')))))))))) throw Error('Buffer overrun'); return i = a.fromBits(e | f << 28, f >>> 4 | g << 24, !1), c ? (this.offset = b, i) : { value: i, length: b - d }; }, c.readVarint64ZigZag = function (c) { var d = this.readVarint64(c); return d && d.value instanceof a ? d.value = b.zigZagDecode64(d.value) : d = b.zigZagDecode64(d), d; }), c.writeCString = function (a, b) { var d; var e; var g; var c = typeof b === 'undefined'; if (c && (b = this.offset), e = a.length, !this.noAssert) { if (typeof a !== 'string') throw TypeError('Illegal str: Not a string'); for (d = 0; e > d; ++d) { if (a.charCodeAt(d) === 0) throw RangeError('Illegal str: Contains NULL-characters'); } if (typeof b !== 'number' || b % 1 !== 0) throw TypeError('Illegal offset: ' + b + ' (not an integer)'); if (b >>>= 0, b < 0 || b + 0 > this.buffer.byteLength) throw RangeError('Illegal offset: 0 <= ' + b + ' (+' + 0 + ') <= ' + this.buffer.byteLength); } return e = k.calculateUTF16asUTF8(f(a))[1], b += e + 1, g = this.buffer.byteLength, b > g && this.resize((g *= 2) > b ? g : b), b -= e + 1, k.encodeUTF16toUTF8(f(a), function (a) { this.view[b++] = a; }.bind(this)), this.view[b++] = 0, c ? (this.offset = b, this) : e; }, c.readCString = function (a) { var c; var e; var f; var b = typeof a === 'undefined'; if (b && (a = this.offset), !this.noAssert) { if (typeof a !== 'number' || a % 1 !== 0) throw TypeError('Illegal offset: ' + a + ' (not an integer)'); if (a >>>= 0, a < 0 || a + 1 > this.buffer.byteLength) throw RangeError('Illegal offset: 0 <= ' + a + ' (+' + 1 + ') <= ' + this.buffer.byteLength); } return c = a, f = -1, k.decodeUTF8toUTF16(function () { if (f === 0) return null; if (a >= this.limit) throw RangeError('Illegal range: Truncated data, ' + a + ' < ' + this.limit); return f = this.view[a++], f === 0 ? null : f; }.bind(this), e = g(), !0), b ? (this.offset = a, e()) : { string: e(), length: a - c }; }, c.writeIString = function (a, b) { var e; var d; var g; var c = typeof b === 'undefined'; if (c && (b = this.offset), !this.noAssert) { if (typeof a !== 'string') throw TypeError('Illegal str: Not a string'); if (typeof b !== 'number' || b % 1 !== 0) throw TypeError('Illegal offset: ' + b + ' (not an integer)'); if (b >>>= 0, b < 0 || b + 0 > this.buffer.byteLength) throw RangeError('Illegal offset: 0 <= ' + b + ' (+' + 0 + ') <= ' + this.buffer.byteLength); } if (d = b, e = k.calculateUTF16asUTF8(f(a), this.noAssert)[1], b += 4 + e, g = this.buffer.byteLength, b > g && this.resize((g *= 2) > b ? g : b), b -= 4 + e, this.littleEndian ? (this.view[b + 3] = 255 & e >>> 24, this.view[b + 2] = 255 & e >>> 16, this.view[b + 1] = 255 & e >>> 8, this.view[b] = 255 & e) : (this.view[b] = 255 & e >>> 24, this.view[b + 1] = 255 & e >>> 16, this.view[b + 2] = 255 & e >>> 8, this.view[b + 3] = 255 & e), b += 4, k.encodeUTF16toUTF8(f(a), function (a) { this.view[b++] = a; }.bind(this)), b !== d + 4 + e) throw RangeError('Illegal range: Truncated data, ' + b + ' == ' + (b + 4 + e)); return c ? (this.offset = b, this) : b - d; }, c.readIString = function (a) { var d; var e; var f; var c = typeof a === 'undefined'; if (c && (a = this.offset), !this.noAssert) { if (typeof a !== 'number' || a % 1 !== 0) throw TypeError('Illegal offset: ' + a + ' (not an integer)'); if (a >>>= 0, a < 0 || a + 4 > this.buffer.byteLength) throw RangeError('Illegal offset: 0 <= ' + a + ' (+' + 4 + ') <= ' + this.buffer.byteLength); } return d = a, e = this.readUint32(a), f = this.readUTF8String(e, b.METRICS_BYTES, a += 4), a += f.length, c ? (this.offset = a, f.string) : { string: f.string, length: a - d }; }, b.METRICS_CHARS = 'c', b.METRICS_BYTES = 'b', c.writeUTF8String = function (a, b) { var d; var e; var g; var c = typeof b === 'undefined'; if (c && (b = this.offset), !this.noAssert) { if (typeof b !== 'number' || b % 1 !== 0) throw TypeError('Illegal offset: ' + b + ' (not an integer)'); if (b >>>= 0, b < 0 || b + 0 > this.buffer.byteLength) throw RangeError('Illegal offset: 0 <= ' + b + ' (+' + 0 + ') <= ' + this.buffer.byteLength); } return e = b, d = k.calculateUTF16asUTF8(f(a))[1], b += d, g = this.buffer.byteLength, b > g && this.resize((g *= 2) > b ? g : b), b -= d, k.encodeUTF16toUTF8(f(a), function (a) { this.view[b++] = a; }.bind(this)), c ? (this.offset = b, this) : b - e; }, c.writeString = c.writeUTF8String, b.calculateUTF8Chars = function (a) { return k.calculateUTF16asUTF8(f(a))[0]; }, b.calculateUTF8Bytes = function (a) { return k.calculateUTF16asUTF8(f(a))[1]; }, b.calculateString = b.calculateUTF8Bytes, c.readUTF8String = function (a, c, d) { var e, i, f, h, j; if (typeof c === 'number' && (d = c, c = void 0), e = typeof d === 'undefined', e && (d = this.offset), typeof c === 'undefined' && (c = b.METRICS_CHARS), !this.noAssert) { if (typeof a !== 'number' || a % 1 !== 0) throw TypeError('Illegal length: ' + a + ' (not an integer)'); if (a |= 0, typeof d !== 'number' || d % 1 !== 0) throw TypeError('Illegal offset: ' + d + ' (not an integer)'); if (d >>>= 0, d < 0 || d + 0 > this.buffer.byteLength) throw RangeError('Illegal offset: 0 <= ' + d + ' (+' + 0 + ') <= ' + this.buffer.byteLength); } if (f = 0, h = d, c === b.METRICS_CHARS) { if (i = g(), k.decodeUTF8(function () { return a > f && d < this.limit ? this.view[d++] : null; }.bind(this), function (a) { ++f, k.UTF8toUTF16(a, i); }), f !== a) throw RangeError('Illegal range: Truncated data, ' + f + ' == ' + a); return e ? (this.offset = d, i()) : { string: i(), length: d - h }; } if (c === b.METRICS_BYTES) { if (!this.noAssert) { if (typeof d !== 'number' || d % 1 !== 0) throw TypeError('Illegal offset: ' + d + ' (not an integer)'); if (d >>>= 0, d < 0 || d + a > this.buffer.byteLength) throw RangeError('Illegal offset: 0 <= ' + d + ' (+' + a + ') <= ' + this.buffer.byteLength); } if (j = d + a, k.decodeUTF8toUTF16(function () { return j > d ? this.view[d++] : null; }.bind(this), i = g(), this.noAssert), d !== j) throw RangeError('Illegal range: Truncated data, ' + d + ' == ' + j); return e ? (this.offset = d, i()) : { string: i(), length: d - h }; } throw TypeError('Unsupported metrics: ' + c); }, c.readString = c.readUTF8String, c.writeVString = function (a, c) { var g; var h; var e; var i; var d = typeof c === 'undefined'; if (d && (c = this.offset), !this.noAssert) { if (typeof a !== 'string') throw TypeError('Illegal str: Not a string'); if (typeof c !== 'number' || c % 1 !== 0) throw TypeError('Illegal offset: ' + c + ' (not an integer)'); if (c >>>= 0, c < 0 || c + 0 > this.buffer.byteLength) throw RangeError('Illegal offset: 0 <= ' + c + ' (+' + 0 + ') <= ' + this.buffer.byteLength); } if (e = c, g = k.calculateUTF16asUTF8(f(a), this.noAssert)[1], h = b.calculateVarint32(g), c += h + g, i = this.buffer.byteLength, c > i && this.resize((i *= 2) > c ? i : c), c -= h + g, c += this.writeVarint32(g, c), k.encodeUTF16toUTF8(f(a), function (a) { this.view[c++] = a; }.bind(this)), c !== e + g + h) throw RangeError('Illegal range: Truncated data, ' + c + ' == ' + (c + g + h)); return d ? (this.offset = c, this) : c - e; }, c.readVString = function (a) { var d; var e; var f; var c = typeof a === 'undefined'; if (c && (a = this.offset), !this.noAssert) { if (typeof a !== 'number' || a % 1 !== 0) throw TypeError('Illegal offset: ' + a + ' (not an integer)'); if (a >>>= 0, a < 0 || a + 1 > this.buffer.byteLength) throw RangeError('Illegal offset: 0 <= ' + a + ' (+' + 1 + ') <= ' + this.buffer.byteLength); } return d = a, e = this.readVarint32(a), f = this.readUTF8String(e.value, b.METRICS_BYTES, a += e.length), a += f.length, c ? (this.offset = a, f.string) : { string: f.string, length: a - d }; }, c.append = function (a, c, d) { var e, f, g; if ((typeof c === 'number' || typeof c !== 'string') && (d = c, c = void 0), e = typeof d === 'undefined', e && (d = this.offset), !this.noAssert) { if (typeof d !== 'number' || d % 1 !== 0) throw TypeError('Illegal offset: ' + d + ' (not an integer)'); if (d >>>= 0, d < 0 || d + 0 > this.buffer.byteLength) throw RangeError('Illegal offset: 0 <= ' + d + ' (+' + 0 + ') <= ' + this.buffer.byteLength); } return a instanceof b || (a = b.wrap(a, c)), f = a.limit - a.offset, f <= 0 ? this : (d += f, g = this.buffer.byteLength, d > g && this.resize((g *= 2) > d ? g : d), d -= f, this.view.set(a.view.subarray(a.offset, a.limit), d), a.offset += f, e && (this.offset += f), this); }, c.appendTo = function (a, b) { return a.append(this, b), this; }, c.assert = function (a) { return this.noAssert = !a, this; }, c.capacity = function () { return this.buffer.byteLength; }, c.clear = function () { return this.offset = 0, this.limit = this.buffer.byteLength, this.markedOffset = -1, this; }, c.clone = function (a) { var c = new b(0, this.littleEndian, this.noAssert); return a ? (c.buffer = new ArrayBuffer(this.buffer.byteLength), c.view = new Uint8Array(c.buffer)) : (c.buffer = this.buffer, c.view = this.view), c.offset = this.offset, c.markedOffset = this.markedOffset, c.limit = this.limit, c; }, c.compact = function (a, b) { var c, e, f; if (typeof a === 'undefined' && (a = this.offset), typeof b === 'undefined' && (b = this.limit), !this.noAssert) { if (typeof a !== 'number' || a % 1 !== 0) throw TypeError('Illegal begin: Not an integer'); if (a >>>= 0, typeof b !== 'number' || b % 1 !== 0) throw TypeError('Illegal end: Not an integer'); if (b >>>= 0, a < 0 || a > b || b > this.buffer.byteLength) throw RangeError('Illegal range: 0 <= ' + a + ' <= ' + b + ' <= ' + this.buffer.byteLength); } return a === 0 && b === this.buffer.byteLength ? this : (c = b - a, c === 0 ? (this.buffer = d, this.view = null, this.markedOffset >= 0 && (this.markedOffset -= a), this.offset = 0, this.limit = 0, this) : (e = new ArrayBuffer(c), f = new Uint8Array(e), f.set(this.view.subarray(a, b)), this.buffer = e, this.view = f, this.markedOffset >= 0 && (this.markedOffset -= a), this.offset = 0, this.limit = c, this)); }, c.copy = function (a, c) { if (typeof a === 'undefined' && (a = this.offset), typeof c === 'undefined' && (c = this.limit), !this.noAssert) { if (typeof a !== 'number' || a % 1 !== 0) throw TypeError('Illegal begin: Not an integer'); if (a >>>= 0, typeof c !== 'number' || c % 1 !== 0) throw TypeError('Illegal end: Not an integer'); if (c >>>= 0, a < 0 || a > c || c > this.buffer.byteLength) throw RangeError('Illegal range: 0 <= ' + a + ' <= ' + c + ' <= ' + this.buffer.byteLength); } if (a === c) return new b(0, this.littleEndian, this.noAssert); var d = c - a; var e = new b(d, this.littleEndian, this.noAssert); return e.offset = 0, e.limit = d, e.markedOffset >= 0 && (e.markedOffset -= a), this.copyTo(e, 0, a, c), e; }, c.copyTo = function (a, c, d, e) { var f, g, h; if (!this.noAssert && !b.isByteBuffer(a)) throw TypeError('Illegal target: Not a ByteBuffer'); if (c = (g = typeof c === 'undefined') ? a.offset : 0 | c, d = (f = typeof d === 'undefined') ? this.offset : 0 | d, e = typeof e === 'undefined' ? this.limit : 0 | e, c < 0 || c > a.buffer.byteLength) throw RangeError('Illegal target range: 0 <= ' + c + ' <= ' + a.buffer.byteLength); if (d < 0 || e > this.buffer.byteLength) throw RangeError('Illegal source range: 0 <= ' + d + ' <= ' + this.buffer.byteLength); return h = e - d, h === 0 ? a : (a.ensureCapacity(c + h), a.view.set(this.view.subarray(d, e), c), f && (this.offset += h), g && (a.offset += h), this); }, c.ensureCapacity = function (a) { var b = this.buffer.byteLength; return a > b ? this.resize((b *= 2) > a ? b : a) : this; }, c.fill = function (a, b, c) { var d = typeof b === 'undefined'; if (d && (b = this.offset), typeof a === 'string' && a.length > 0 && (a = a.charCodeAt(0)), typeof b === 'undefined' && (b = this.offset), typeof c === 'undefined' && (c = this.limit), !this.noAssert) { if (typeof a !== 'number' || a % 1 !== 0) throw TypeError('Illegal value: ' + a + ' (not an integer)'); if (a |= 0, typeof b !== 'number' || b % 1 !== 0) throw TypeError('Illegal begin: Not an integer'); if (b >>>= 0, typeof c !== 'number' || c % 1 !== 0) throw TypeError('Illegal end: Not an integer'); if (c >>>= 0, b < 0 || b > c || c > this.buffer.byteLength) throw RangeError('Illegal range: 0 <= ' + b + ' <= ' + c + ' <= ' + this.buffer.byteLength); } if (b >= c) return this; for (; c > b;) { this.view[b++] = a; } return d && (this.offset = b), this; }, c.flip = function () { return this.limit = this.offset, this.offset = 0, this; }, c.mark = function (a) { if (a = typeof a === 'undefined' ? this.offset : a, !this.noAssert) { if (typeof a !== 'number' || a % 1 !== 0) throw TypeError('Illegal offset: ' + a + ' (not an integer)'); if (a >>>= 0, a < 0 || a + 0 > this.buffer.byteLength) throw RangeError('Illegal offset: 0 <= ' + a + ' (+' + 0 + ') <= ' + this.buffer.byteLength); } return this.markedOffset = a, this; }, c.order = function (a) { if (!this.noAssert && typeof a !== 'boolean') throw TypeError('Illegal littleEndian: Not a boolean'); return this.littleEndian = !!a, this; }, c.LE = function (a) { return this.littleEndian = typeof a !== 'undefined' ? !!a : !0, this; }, c.BE = function (a) { return this.littleEndian = typeof a !== 'undefined' ? !a : !1, this; }, c.prepend = function (a, c, d) { var e, f, g, h, i; if ((typeof c === 'number' || typeof c !== 'string') && (d = c, c = void 0), e = typeof d === 'undefined', e && (d = this.offset), !this.noAssert) { if (typeof d !== 'number' || d % 1 !== 0) throw TypeError('Illegal offset: ' + d + ' (not an integer)'); if (d >>>= 0, d < 0 || d + 0 > this.buffer.byteLength) throw RangeError('Illegal offset: 0 <= ' + d + ' (+' + 0 + ') <= ' + this.buffer.byteLength); } return a instanceof b || (a = b.wrap(a, c)), f = a.limit - a.offset, f <= 0 ? this : (g = f - d, g > 0 ? (h = new ArrayBuffer(this.buffer.byteLength + g), i = new Uint8Array(h), i.set(this.view.subarray(d, this.buffer.byteLength), f), this.buffer = h, this.view = i, this.offset += g, this.markedOffset >= 0 && (this.markedOffset += g), this.limit += g, d += g) : new Uint8Array(this.buffer), this.view.set(a.view.subarray(a.offset, a.limit), d - f), a.offset = a.limit, e && (this.offset -= f), this); }, c.prependTo = function (a, b) { return a.prepend(this, b), this; }, c.printDebug = function (a) { typeof a !== 'function' && (a = console.log.bind(console)), a(this.toString() + '\n-------------------------------------------------------------------\n' + this.toDebug(!0)); }, c.remaining = function () { return this.limit - this.offset; }, c.reset = function () { return this.markedOffset >= 0 ? (this.offset = this.markedOffset, this.markedOffset = -1) : this.offset = 0, this; }, c.resize = function (a) { var b, c; if (!this.noAssert) { if (typeof a !== 'number' || a % 1 !== 0) throw TypeError('Illegal capacity: ' + a + ' (not an integer)'); if (a |= 0, a < 0) throw RangeError('Illegal capacity: 0 <= ' + a); } return this.buffer.byteLength < a && (b = new ArrayBuffer(a), c = new Uint8Array(b), c.set(this.view), this.buffer = b, this.view = c), this; }, c.reverse = function (a, b) { if (typeof a === 'undefined' && (a = this.offset), typeof b === 'undefined' && (b = this.limit), !this.noAssert) { if (typeof a !== 'number' || a % 1 !== 0) throw TypeError('Illegal begin: Not an integer'); if (a >>>= 0, typeof b !== 'number' || b % 1 !== 0) throw TypeError('Illegal end: Not an integer'); if (b >>>= 0, a < 0 || a > b || b > this.buffer.byteLength) throw RangeError('Illegal range: 0 <= ' + a + ' <= ' + b + ' <= ' + this.buffer.byteLength); } return a === b ? this : (Array.prototype.reverse.call(this.view.subarray(a, b)), this); }, c.skip = function (a) { if (!this.noAssert) { if (typeof a !== 'number' || a % 1 !== 0) throw TypeError('Illegal length: ' + a + ' (not an integer)'); a |= 0; } var b = this.offset + a; if (!this.noAssert && (b < 0 || b > this.buffer.byteLength)) throw RangeError('Illegal length: 0 <= ' + this.offset + ' + ' + a + ' <= ' + this.buffer.byteLength); return this.offset = b, this; }, c.slice = function (a, b) { if (typeof a === 'undefined' && (a = this.offset), typeof b === 'undefined' && (b = this.limit), !this.noAssert) { if (typeof a !== 'number' || a % 1 !== 0) throw TypeError('Illegal begin: Not an integer'); if (a >>>= 0, typeof b !== 'number' || b % 1 !== 0) throw TypeError('Illegal end: Not an integer'); if (b >>>= 0, a < 0 || a > b || b > this.buffer.byteLength) throw RangeError('Illegal range: 0 <= ' + a + ' <= ' + b + ' <= ' + this.buffer.byteLength); } var c = this.clone(); return c.offset = a, c.limit = b, c; }, c.toBuffer = function (a) { var e; var b = this.offset; var c = this.limit; if (!this.noAssert) { if (typeof b !== 'number' || b % 1 !== 0) throw TypeError('Illegal offset: Not an integer'); if (b >>>= 0, typeof c !== 'number' || c % 1 !== 0) throw TypeError('Illegal limit: Not an integer'); if (c >>>= 0, b < 0 || b > c || c > this.buffer.byteLength) throw RangeError('Illegal range: 0 <= ' + b + ' <= ' + c + ' <= ' + this.buffer.byteLength); } return a || b !== 0 || c !== this.buffer.byteLength ? b === c ? d : (e = new ArrayBuffer(c - b), new Uint8Array(e).set(new Uint8Array(this.buffer).subarray(b, c), 0), e) : this.buffer; }, c.toArrayBuffer = c.toBuffer, c.toString = function (a, b, c) { if (typeof a === 'undefined') return 'ByteBufferAB(offset=' + this.offset + ',markedOffset=' + this.markedOffset + ',limit=' + this.limit + ',capacity=' + this.capacity() + ')'; switch (typeof a === 'number' && (a = 'utf8', b = a, c = b), a) { case 'utf8': return this.toUTF8(b, c); case 'base64': return this.toBase64(b, c); case 'hex': return this.toHex(b, c); case 'binary': return this.toBinary(b, c); case 'debug': return this.toDebug(); case 'columns': return this.toColumns(); default: throw Error('Unsupported encoding: ' + a); } }, j = function () { var d; var e; var a = {}; var b = [65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 43, 47]; var c = []; for (d = 0, e = b.length; e > d; ++d) { c[b[d]] = d; } return a.encode = function (a, c) { for (var d, e; (d = a()) !== null;) { c(b[63 & d >> 2]), e = (3 & d) << 4, (d = a()) !== null ? (e |= 15 & d >> 4, c(b[63 & (e | 15 & d >> 4)]), e = (15 & d) << 2, (d = a()) !== null ? (c(b[63 & (e | 3 & d >> 6)]), c(b[63 & d])) : (c(b[63 & e]), c(61))) : (c(b[63 & e]), c(61), c(61)); } }, a.decode = function (a, b) { function g(a) { throw Error('Illegal character code: ' + a); } for (var d, e, f; (d = a()) !== null;) { if (e = c[d], typeof e === 'undefined' && g(d), (d = a()) !== null && (f = c[d], typeof f === 'undefined' && g(d), b(e << 2 >>> 0 | (48 & f) >> 4), (d = a()) !== null)) { if (e = c[d], typeof e === 'undefined') { if (d === 61) break; g(d); } if (b((15 & f) << 4 >>> 0 | (60 & e) >> 2), (d = a()) !== null) { if (f = c[d], typeof f === 'undefined') { if (d === 61) break; g(d); } b((3 & e) << 6 >>> 0 | f); } } } }, a.test = function (a) { return /^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/.test(a); }, a; }(), c.toBase64 = function (a, b) { if (typeof a === 'undefined' && (a = this.offset), typeof b === 'undefined' && (b = this.limit), a = 0 | a, b = 0 | b, a < 0 || b > this.capacity || a > b) throw RangeError('begin, end'); var c; return j.encode(function () { return b > a ? this.view[a++] : null; }.bind(this), c = g()), c(); }, b.fromBase64 = function (a, c) { if (typeof a !== 'string') throw TypeError('str'); var d = new b(3 * (a.length / 4), c); var e = 0; return j.decode(f(a), function (a) { d.view[e++] = a; }), d.limit = e, d; }, b.btoa = function (a) { return b.fromBinary(a).toBase64(); }, b.atob = function (a) { return b.fromBase64(a).toBinary(); }, c.toBinary = function (a, b) { if (typeof a === 'undefined' && (a = this.offset), typeof b === 'undefined' && (b = this.limit), a |= 0, b |= 0, a < 0 || b > this.capacity() || a > b) throw RangeError('begin, end'); if (a === b) return ''; for (var c = [], d = []; b > a;) { c.push(this.view[a++]), c.length >= 1024 && (d.push(String.fromCharCode.apply(String, c)), c = []); } return d.join('') + String.fromCharCode.apply(String, c); }, b.fromBinary = function (a, c) { if (typeof a !== 'string') throw TypeError('str'); for (var f, d = 0, e = a.length, g = new b(e, c); e > d;) { if (f = a.charCodeAt(d), f > 255) throw RangeError('illegal char code: ' + f); g.view[d++] = f; } return g.limit = e, g; }, c.toDebug = function (a) { for (var d, b = -1, c = this.buffer.byteLength, e = '', f = '', g = ''; c > b;) { if (b !== -1 && (d = this.view[b], e += d < 16 ? '0' + d.toString(16).toUpperCase() : d.toString(16).toUpperCase(), a && (f += d > 32 && d < 127 ? String.fromCharCode(d) : '.')), ++b, a && b > 0 && b % 16 === 0 && b !== c) { for (; e.length < 51;) { e += ' '; } g += e + f + '\n', e = f = ''; } e += b === this.offset && b === this.limit ? b === this.markedOffset ? '!' : '|' : b === this.offset ? b === this.markedOffset ? '[' : '<' : b === this.limit ? b === this.markedOffset ? ']' : '>' : b === this.markedOffset ? "'" : a || b !== 0 && b !== c ? ' ' : ''; } if (a && e !== ' ') { for (; e.length < 51;) { e += ' '; } g += e + f + '\n'; } return a ? g : e; }, b.fromDebug = function (a, c, d) { for (var i, j, e = a.length, f = new b(0 | (e + 1) / 3, c, d), g = 0, h = 0, k = !1, l = !1, m = !1, n = !1, o = !1; e > g;) { switch (i = a.charAt(g++)) { case '!': if (!d) { if (l || m || n) { o = !0; break; } l = m = n = !0; } f.offset = f.markedOffset = f.limit = h, k = !1; break; case '|': if (!d) { if (l || n) { o = !0; break; } l = n = !0; } f.offset = f.limit = h, k = !1; break; case '[': if (!d) { if (l || m) { o = !0; break; } l = m = !0; } f.offset = f.markedOffset = h, k = !1; break; case '<': if (!d) { if (l) { o = !0; break; } l = !0; } f.offset = h, k = !1; break; case ']': if (!d) { if (n || m) { o = !0; break; } n = m = !0; } f.limit = f.markedOffset = h, k = !1; break; case '>': if (!d) { if (n) { o = !0; break; } n = !0; } f.limit = h, k = !1; break; case "'": if (!d) { if (m) { o = !0; break; } m = !0; } f.markedOffset = h, k = !1; break; case ' ': k = !1; break; default: if (!d && k) { o = !0; break; } if (j = parseInt(i + a.charAt(g++), 16), !d && (isNaN(j) || j < 0 || j > 255)) throw TypeError('Illegal str: Not a debug encoded string'); f.view[h++] = j, k = !0; } if (o) throw TypeError('Illegal str: Invalid symbol at ' + g); } if (!d) { if (!l || !n) throw TypeError('Illegal str: Missing offset or limit'); if (h < f.buffer.byteLength) throw TypeError('Illegal str: Not a debug encoded string (is it hex?) ' + h + ' < ' + e); } return f; }, c.toHex = function (a, b) { if (a = typeof a === 'undefined' ? this.offset : a, b = typeof b === 'undefined' ? this.limit : b, !this.noAssert) { if (typeof a !== 'number' || a % 1 !== 0) throw TypeError('Illegal begin: Not an integer'); if (a >>>= 0, typeof b !== 'number' || b % 1 !== 0) throw TypeError('Illegal end: Not an integer'); if (b >>>= 0, a < 0 || a > b || b > this.buffer.byteLength) throw RangeError('Illegal range: 0 <= ' + a + ' <= ' + b + ' <= ' + this.buffer.byteLength); } for (var d, c = new Array(b - a); b > a;) { d = this.view[a++], d < 16 ? c.push('0', d.toString(16)) : c.push(d.toString(16)); } return c.join(''); }, b.fromHex = function (a, c, d) { var g, e, f, h, i; if (!d) { if (typeof a !== 'string') throw TypeError('Illegal str: Not a string'); if (a.length % 2 !== 0) throw TypeError('Illegal str: Length not a multiple of 2'); } for (e = a.length, f = new b(0 | e / 2, c), h = 0, i = 0; e > h; h += 2) { if (g = parseInt(a.substring(h, h + 2), 16), !d && (!isFinite(g) || g < 0 || g > 255)) throw TypeError('Illegal str: Contains non-hex characters'); f.view[i++] = g; } return f.limit = i, f; }, k = function () { var a = {}; return a.MAX_CODEPOINT = 1114111, a.encodeUTF8 = function (a, b) { var c = null; for (typeof a === 'number' && (c = a, a = function a() { return null; }); c !== null || (c = a()) !== null;) { c < 128 ? b(127 & c) : c < 2048 ? (b(192 | 31 & c >> 6), b(128 | 63 & c)) : c < 65536 ? (b(224 | 15 & c >> 12), b(128 | 63 & c >> 6), b(128 | 63 & c)) : (b(240 | 7 & c >> 18), b(128 | 63 & c >> 12), b(128 | 63 & c >> 6), b(128 | 63 & c)), c = null; } }, a.decodeUTF8 = function (a, b) { for (var c, d, e, f, g = function g(a) { a = a.slice(0, a.indexOf(null)); var b = Error(a.toString()); throw b.name = 'TruncatedError', b.bytes = a, b; }; (c = a()) !== null;) { if ((128 & c) === 0) b(c);else if ((224 & c) === 192) (d = a()) === null && g([c, d]), b((31 & c) << 6 | 63 & d);else if ((240 & c) === 224) ((d = a()) === null || (e = a()) === null) && g([c, d, e]), b((15 & c) << 12 | (63 & d) << 6 | 63 & e);else { if ((248 & c) !== 240) throw RangeError('Illegal starting byte: ' + c); ((d = a()) === null || (e = a()) === null || (f = a()) === null) && g([c, d, e, f]), b((7 & c) << 18 | (63 & d) << 12 | (63 & e) << 6 | 63 & f); } } }, a.UTF16toUTF8 = function (a, b) { for (var c, d = null;;) { if ((c = d !== null ? d : a()) === null) break; c >= 55296 && c <= 57343 && (d = a()) !== null && d >= 56320 && d <= 57343 ? (b(1024 * (c - 55296) + d - 56320 + 65536), d = null) : b(c); } d !== null && b(d); }, a.UTF8toUTF16 = function (a, b) { var c = null; for (typeof a === 'number' && (c = a, a = function a() { return null; }); c !== null || (c = a()) !== null;) { c <= 65535 ? b(c) : (c -= 65536, b((c >> 10) + 55296), b(c % 1024 + 56320)), c = null; } }, a.encodeUTF16toUTF8 = function (b, c) { a.UTF16toUTF8(b, function (b) { a.encodeUTF8(b, c); }); }, a.decodeUTF8toUTF16 = function (b, c) { a.decodeUTF8(b, function (b) { a.UTF8toUTF16(b, c); }); }, a.calculateCodePoint = function (a) { return a < 128 ? 1 : a < 2048 ? 2 : a < 65536 ? 3 : 4; }, a.calculateUTF8 = function (a) { for (var b, c = 0; (b = a()) !== null;) { c += b < 128 ? 1 : b < 2048 ? 2 : b < 65536 ? 3 : 4; } return c; }, a.calculateUTF16asUTF8 = function (b) { var c = 0; var d = 0; return a.UTF16toUTF8(b, function (a) { ++c, d += a < 128 ? 1 : a < 2048 ? 2 : a < 65536 ? 3 : 4; }), [c, d]; }, a; }(), c.toUTF8 = function (a, b) { if (typeof a === 'undefined' && (a = this.offset), typeof b === 'undefined' && (b = this.limit), !this.noAssert) { if (typeof a !== 'number' || a % 1 !== 0) throw TypeError('Illegal begin: Not an integer'); if (a >>>= 0, typeof b !== 'number' || b % 1 !== 0) throw TypeError('Illegal end: Not an integer'); if (b >>>= 0, a < 0 || a > b || b > this.buffer.byteLength) throw RangeError('Illegal range: 0 <= ' + a + ' <= ' + b + ' <= ' + this.buffer.byteLength); } var c; try { k.decodeUTF8toUTF16(function () { return b > a ? this.view[a++] : null; }.bind(this), c = g()); } catch (d) { if (a !== b) throw RangeError('Illegal range: Truncated data, ' + a + ' != ' + b); } return c(); }, b.fromUTF8 = function (a, c, d) { if (!d && typeof a !== 'string') throw TypeError('Illegal str: Not a string'); var e = new b(k.calculateUTF16asUTF8(f(a), !0)[1], c, d); var g = 0; return k.encodeUTF16toUTF8(f(a), function (a) { e.view[g++] = a; }), e.limit = g, e; }, b; }(c); var e = function (b, c) { var f; var h; var i; var e = {}; return e.ByteBuffer = b, e.c = b, f = b, e.Long = c || null, e.VERSION = '5.0.1', e.WIRE_TYPES = {}, e.WIRE_TYPES.VARINT = 0, e.WIRE_TYPES.BITS64 = 1, e.WIRE_TYPES.LDELIM = 2, e.WIRE_TYPES.STARTGROUP = 3, e.WIRE_TYPES.ENDGROUP = 4, e.WIRE_TYPES.BITS32 = 5, e.PACKABLE_WIRE_TYPES = [e.WIRE_TYPES.VARINT, e.WIRE_TYPES.BITS64, e.WIRE_TYPES.BITS32], e.TYPES = { int32: { name: 'int32', wireType: e.WIRE_TYPES.VARINT, defaultValue: 0 }, uint32: { name: 'uint32', wireType: e.WIRE_TYPES.VARINT, defaultValue: 0 }, sint32: { name: 'sint32', wireType: e.WIRE_TYPES.VARINT, defaultValue: 0 }, int64: { name: 'int64', wireType: e.WIRE_TYPES.VARINT, defaultValue: e.Long ? e.Long.ZERO : void 0 }, uint64: { name: 'uint64', wireType: e.WIRE_TYPES.VARINT, defaultValue: e.Long ? e.Long.UZERO : void 0 }, sint64: { name: 'sint64', wireType: e.WIRE_TYPES.VARINT, defaultValue: e.Long ? e.Long.ZERO : void 0 }, bool: { name: 'bool', wireType: e.WIRE_TYPES.VARINT, defaultValue: !1 }, double: { name: 'double', wireType: e.WIRE_TYPES.BITS64, defaultValue: 0 }, string: { name: 'string', wireType: e.WIRE_TYPES.LDELIM, defaultValue: '' }, bytes: { name: 'bytes', wireType: e.WIRE_TYPES.LDELIM, defaultValue: null }, fixed32: { name: 'fixed32', wireType: e.WIRE_TYPES.BITS32, defaultValue: 0 }, sfixed32: { name: 'sfixed32', wireType: e.WIRE_TYPES.BITS32, defaultValue: 0 }, fixed64: { name: 'fixed64', wireType: e.WIRE_TYPES.BITS64, defaultValue: e.Long ? e.Long.UZERO : void 0 }, sfixed64: { name: 'sfixed64', wireType: e.WIRE_TYPES.BITS64, defaultValue: e.Long ? e.Long.ZERO : void 0 }, float: { name: 'float', wireType: e.WIRE_TYPES.BITS32, defaultValue: 0 }, enum: { name: 'enum', wireType: e.WIRE_TYPES.VARINT, defaultValue: 0 }, message: { name: 'message', wireType: e.WIRE_TYPES.LDELIM, defaultValue: null }, group: { name: 'group', wireType: e.WIRE_TYPES.STARTGROUP, defaultValue: null } }, e.MAP_KEY_TYPES = [e.TYPES.int32, e.TYPES.sint32, e.TYPES.sfixed32, e.TYPES.uint32, e.TYPES.fixed32, e.TYPES.int64, e.TYPES.sint64, e.TYPES.sfixed64, e.TYPES.uint64, e.TYPES.fixed64, e.TYPES.bool, e.TYPES.string, e.TYPES.bytes], e.ID_MIN = 1, e.ID_MAX = 536870911, e.convertFieldsToCamelCase = !1, e.populateAccessors = !0, e.populateDefaults = !0, e.Util = function () { var a = {}; return a.IS_NODE = !((typeof process === "undefined" ? "undefined" : _typeof(process)) !== 'object' || process + '' != '[object process]' || process.browser), a.XHR = function () { var c; var a = [function () { return new XMLHttpRequest(); }, function () { return new ActiveXObject('Msxml2.XMLHTTP'); }, function () { return new ActiveXObject('Msxml3.XMLHTTP'); }, function () { return new ActiveXObject('Microsoft.XMLHTTP'); }]; var b = null; for (c = 0; c < a.length; c++) { try { b = a[c](); } catch (d) { continue; } break; } if (!b) throw Error('XMLHttpRequest is not supported'); return b; }, a.fetch = function (b, c) { if (c && typeof c !== 'function' && (c = null), a.IS_NODE) { if (c) g.readFile(b, function (a, b) { a ? c(null) : c('' + b); });else try { return g.readFileSync(b); } catch (d) { return null; } } else { var e = a.XHR(); if (e.open('GET', b, c ? !0 : !1), e.setRequestHeader('Accept', 'text/plain'), typeof e.overrideMimeType === 'function' && e.overrideMimeType('text/plain'), !c) return e.send(null), e.status == 200 || e.status == 0 && typeof e.responseText === 'string' ? e.responseText : null; if (e.onreadystatechange = function () { e.readyState == 4 && (e.status == 200 || e.status == 0 && typeof e.responseText === 'string' ? c(e.responseText) : c(null)); }, e.readyState == 4) return; e.send(null); } }, a.toCamelCase = function (a) { return a.replace(/_([a-zA-Z])/g, function (a, b) { return b.toUpperCase(); }); }, a; }(), e.Lang = { DELIM: /[\s\{\}=;:\[\],'"\(\)<>]/g, RULE: /^(?:required|optional|repeated|map)$/, TYPE: /^(?:double|float|int32|uint32|sint32|int64|uint64|sint64|fixed32|sfixed32|fixed64|sfixed64|bool|string|bytes)$/, NAME: /^[a-zA-Z_][a-zA-Z_0-9]*$/, TYPEDEF: /^[a-zA-Z][a-zA-Z_0-9]*$/, TYPEREF: /^(?:\.?[a-zA-Z_][a-zA-Z_0-9]*)+$/, FQTYPEREF: /^(?:\.[a-zA-Z][a-zA-Z_0-9]*)+$/, NUMBER: /^-?(?:[1-9][0-9]*|0|0[xX][0-9a-fA-F]+|0[0-7]+|([0-9]*(\.[0-9]*)?([Ee][+-]?[0-9]+)?)|inf|nan)$/, NUMBER_DEC: /^(?:[1-9][0-9]*|0)$/, NUMBER_HEX: /^0[xX][0-9a-fA-F]+$/, NUMBER_OCT: /^0[0-7]+$/, NUMBER_FLT: /^([0-9]*(\.[0-9]*)?([Ee][+-]?[0-9]+)?|inf|nan)$/, BOOL: /^(?:true|false)$/i, ID: /^(?:[1-9][0-9]*|0|0[xX][0-9a-fA-F]+|0[0-7]+)$/, NEGID: /^\-?(?:[1-9][0-9]*|0|0[xX][0-9a-fA-F]+|0[0-7]+)$/, WHITESPACE: /\s/, STRING: /(?:"([^"\\]*(?:\\.[^"\\]*)*)")|(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g, STRING_DQ: /(?:"([^"\\]*(?:\\.[^"\\]*)*)")/g, STRING_SQ: /(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g }, e.DotProto = function (a, b) { function h(a, c) { var d = -1; var e = 1; if (a.charAt(0) == '-' && (e = -1, a = a.substring(1)), b.NUMBER_DEC.test(a)) d = parseInt(a);else if (b.NUMBER_HEX.test(a)) d = parseInt(a.substring(2), 16);else { if (!b.NUMBER_OCT.test(a)) throw Error('illegal id value: ' + (e < 0 ? '-' : '') + a); d = parseInt(a.substring(1), 8); } if (d = 0 | e * d, !c && d < 0) throw Error('illegal id value: ' + (e < 0 ? '-' : '') + a); return d; } function i(a) { var c = 1; if (a.charAt(0) == '-' && (c = -1, a = a.substring(1)), b.NUMBER_DEC.test(a)) return c * parseInt(a, 10); if (b.NUMBER_HEX.test(a)) return c * parseInt(a.substring(2), 16); if (b.NUMBER_OCT.test(a)) return c * parseInt(a.substring(1), 8); if (a === 'inf') return 1 / 0 * c; if (a === 'nan') return 0 / 0; if (b.NUMBER_FLT.test(a)) return c * parseFloat(a); throw Error('illegal number value: ' + (c < 0 ? '-' : '') + a); } function j(a, b, c) { typeof a[b] === 'undefined' ? a[b] = c : (Array.isArray(a[b]) || (a[b] = [a[b]]), a[b].push(c)); } var f; var g; var c = {}; var d = function d(a) { this.source = a + '', this.index = 0, this.line = 1, this.stack = [], this._stringOpen = null; }; var e = d.prototype; return e._readString = function () { var c; var a = this._stringOpen === '"' ? b.STRING_DQ : b.STRING_SQ; if (a.lastIndex = this.index - 1, c = a.exec(this.source), !c) throw Error('unterminated string'); return this.index = a.lastIndex, this.stack.push(this._stringOpen), this._stringOpen = null, c[1]; }, e.next = function () { var a, c, d, e, f, g; if (this.stack.length > 0) return this.stack.shift(); if (this.index >= this.source.length) return null; if (this._stringOpen !== null) return this._readString(); do { for (a = !1; b.WHITESPACE.test(d = this.source.charAt(this.index));) { if (d === '\n' && ++this.line, ++this.index === this.source.length) return null; } if (this.source.charAt(this.index) === '/') if (++this.index, this.source.charAt(this.index) === '/') { for (; this.source.charAt(++this.index) !== '\n';) { if (this.index == this.source.length) return null; } ++this.index, ++this.line, a = !0; } else { if ((d = this.source.charAt(this.index)) !== '*') return '/'; do { if (d === '\n' && ++this.line, ++this.index === this.source.length) return null; c = d, d = this.source.charAt(this.index); } while (c !== '*' || d !== '/'); ++this.index, a = !0; } } while (a); if (this.index === this.source.length) return null; if (e = this.index, b.DELIM.lastIndex = 0, f = b.DELIM.test(this.source.charAt(e++)), !f) for (; e < this.source.length && !b.DELIM.test(this.source.charAt(e));) { ++e; } return g = this.source.substring(this.index, this.index = e), (g === '"' || g === "'") && (this._stringOpen = g), g; }, e.peek = function () { if (this.stack.length === 0) { var a = this.next(); if (a === null) return null; this.stack.push(a); } return this.stack[0]; }, e.skip = function (a) { var b = this.next(); if (b !== a) throw Error("illegal '" + b + "', '" + a + "' expected"); }, e.omit = function (a) { return this.peek() === a ? (this.next(), !0) : !1; }, e.toString = function () { return 'Tokenizer (' + this.index + '/' + this.source.length + ' at line ' + this.line + ')'; }, c.Tokenizer = d, f = function f(a) { this.tn = new d(a), this.proto3 = !1; }, g = f.prototype, g.parse = function () { var c; var a = { name: '[ROOT]', package: null, messages: [], enums: [], imports: [], options: {}, services: [] }; var d = !0; try { for (; c = this.tn.next();) { switch (c) { case 'package': if (!d || a.package !== null) throw Error("unexpected 'package'"); if (c = this.tn.next(), !b.TYPEREF.test(c)) throw Error('illegal package name: ' + c); this.tn.skip(';'), a.package = c; break; case 'import': if (!d) throw Error("unexpected 'import'"); c = this.tn.peek(), c === 'public' && this.tn.next(), c = this._readString(), this.tn.skip(';'), a.imports.push(c); break; case 'syntax': if (!d) throw Error("unexpected 'syntax'"); this.tn.skip('='), (a.syntax = this._readString()) === 'proto3' && (this.proto3 = !0), this.tn.skip(';'); break; case 'message': this._parseMessage(a, null), d = !1; break; case 'enum': this._parseEnum(a), d = !1; break; case 'option': this._parseOption(a); break; case 'service': this._parseService(a); break; case 'extend': this._parseExtend(a); break; default: throw Error("unexpected '" + c + "'"); } } } catch (e) { throw e.message = 'Parse error at line ' + this.tn.line + ': ' + e.message, e; } return delete a.name, a; }, f.parse = function (a) { return new f(a).parse(); }, g._readString = function () { var b; var c; var a = ''; do { if (c = this.tn.next(), c !== "'" && c !== '"') throw Error('illegal string delimiter: ' + c); a += this.tn.next(), this.tn.skip(c), b = this.tn.peek(); } while (b === '"' || b === '"'); return a; }, g._readValue = function (a) { var c = this.tn.peek(); if (c === '"' || c === "'") return this._readString(); if (this.tn.next(), b.NUMBER.test(c)) return i(c); if (b.BOOL.test(c)) return c.toLowerCase() === 'true'; if (a && b.TYPEREF.test(c)) return c; throw Error('illegal value: ' + c); }, g._parseOption = function (a, c) { var f; var d = this.tn.next(); var e = !1; if (d === '(' && (e = !0, d = this.tn.next()), !b.TYPEREF.test(d)) throw Error('illegal option name: ' + d); f = d, e && (this.tn.skip(')'), f = '(' + f + ')', d = this.tn.peek(), b.FQTYPEREF.test(d) && (f += d, this.tn.next())), this.tn.skip('='), this._parseOptionValue(a, f), c || this.tn.skip(';'); }, g._parseOptionValue = function (a, c) { var d = this.tn.peek(); if (d !== '{') j(a.options, c, this._readValue(!0));else for (this.tn.skip('{'); (d = this.tn.next()) !== '}';) { if (!b.NAME.test(d)) throw Error('illegal option name: ' + c + '.' + d); this.tn.omit(':') ? j(a.options, c + '.' + d, this._readValue(!0)) : this._parseOptionValue(a, c + '.' + d); } }, g._parseService = function (a) { var d; var e; var c = this.tn.next(); if (!b.NAME.test(c)) throw Error('illegal service name at line ' + this.tn.line + ': ' + c); for (d = c, e = { name: d, rpc: {}, options: {} }, this.tn.skip('{'); (c = this.tn.next()) !== '}';) { if (c === 'option') this._parseOption(e);else { if (c !== 'rpc') throw Error('illegal service token: ' + c); this._parseServiceRPC(e); } } this.tn.omit(';'), a.services.push(e); }, g._parseServiceRPC = function (a) { var e; var f; var c = 'rpc'; var d = this.tn.next(); if (!b.NAME.test(d)) throw Error('illegal rpc service method name: ' + d); if (e = d, f = { request: null, response: null, request_stream: !1, response_stream: !1, options: {} }, this.tn.skip('('), d = this.tn.next(), d.toLowerCase() === 'stream' && (f.request_stream = !0, d = this.tn.next()), !b.TYPEREF.test(d)) throw Error('illegal rpc service request type: ' + d); if (f.request = d, this.tn.skip(')'), d = this.tn.next(), d.toLowerCase() !== 'returns') throw Error('illegal rpc service request type delimiter: ' + d); if (this.tn.skip('('), d = this.tn.next(), d.toLowerCase() === 'stream' && (f.response_stream = !0, d = this.tn.next()), f.response = d, this.tn.skip(')'), d = this.tn.peek(), d === '{') { for (this.tn.next(); (d = this.tn.next()) !== '}';) { if (d !== 'option') throw Error('illegal rpc service token: ' + d); this._parseOption(f); } this.tn.omit(';'); } else this.tn.skip(';'); typeof a[c] === 'undefined' && (a[c] = {}), a[c][e] = f; }, g._parseMessage = function (a, c) { var d = !!c; var e = this.tn.next(); var f = { name: '', fields: [], enums: [], messages: [], options: {}, services: [], oneofs: {} }; if (!b.NAME.test(e)) throw Error('illegal ' + (d ? 'group' : 'message') + ' name: ' + e); for (f.name = e, d && (this.tn.skip('='), c.id = h(this.tn.next()), f.isGroup = !0), e = this.tn.peek(), e === '[' && c && this._parseFieldOptions(c), this.tn.skip('{'); (e = this.tn.next()) !== '}';) { if (b.RULE.test(e)) this._parseMessageField(f, e);else if (e === 'oneof') this._parseMessageOneOf(f);else if (e === 'enum') this._parseEnum(f);else if (e === 'message') this._parseMessage(f);else if (e === 'option') this._parseOption(f);else if (e === 'service') this._parseService(f);else if (e === 'extensions') f.extensions = this._parseExtensionRanges();else if (e === 'reserved') this._parseIgnored();else if (e === 'extend') this._parseExtend(f);else { if (!b.TYPEREF.test(e)) throw Error('illegal message token: ' + e); if (!this.proto3) throw Error('illegal field rule: ' + e); this._parseMessageField(f, 'optional', e); } } return this.tn.omit(';'), a.messages.push(f), f; }, g._parseIgnored = function () { for (; this.tn.peek() !== ';';) { this.tn.next(); } this.tn.skip(';'); }, g._parseMessageField = function (a, c, d) { var e, f, g; if (!b.RULE.test(c)) throw Error('illegal message field rule: ' + c); if (e = { rule: c, type: '', name: '', options: {}, id: 0 }, c === 'map') { if (d) throw Error('illegal type: ' + d); if (this.tn.skip('<'), f = this.tn.next(), !b.TYPE.test(f) && !b.TYPEREF.test(f)) throw Error('illegal message field type: ' + f); if (e.keytype = f, this.tn.skip(','), f = this.tn.next(), !b.TYPE.test(f) && !b.TYPEREF.test(f)) throw Error('illegal message field: ' + f); if (e.type = f, this.tn.skip('>'), f = this.tn.next(), !b.NAME.test(f)) throw Error('illegal message field name: ' + f); e.name = f, this.tn.skip('='), e.id = h(this.tn.next()), f = this.tn.peek(), f === '[' && this._parseFieldOptions(e), this.tn.skip(';'); } else if (d = typeof d !== 'undefined' ? d : this.tn.next(), d === 'group') { if (g = this._parseMessage(a, e), !/^[A-Z]/.test(g.name)) throw Error('illegal group name: ' + g.name); e.type = g.name, e.name = g.name.toLowerCase(), this.tn.omit(';'); } else { if (!b.TYPE.test(d) && !b.TYPEREF.test(d)) throw Error('illegal message field type: ' + d); if (e.type = d, f = this.tn.next(), !b.NAME.test(f)) throw Error('illegal message field name: ' + f); e.name = f, this.tn.skip('='), e.id = h(this.tn.next()), f = this.tn.peek(), f === '[' && this._parseFieldOptions(e), this.tn.skip(';'); } return a.fields.push(e), e; }, g._parseMessageOneOf = function (a) { var e; var d; var f; var c = this.tn.next(); if (!b.NAME.test(c)) throw Error('illegal oneof name: ' + c); for (d = c, f = [], this.tn.skip('{'); (c = this.tn.next()) !== '}';) { e = this._parseMessageField(a, 'optional', c), e.oneof = d, f.push(e.id); } this.tn.omit(';'), a.oneofs[d] = f; }, g._parseFieldOptions = function (a) { this.tn.skip('['); for (var b, c = !0; (b = this.tn.peek()) !== ']';) { c || this.tn.skip(','), this._parseOption(a, !0), c = !1; } this.tn.next(); }, g._parseEnum = function (a) { var e; var c = { name: '', values: [], options: {} }; var d = this.tn.next(); if (!b.NAME.test(d)) throw Error('illegal name: ' + d); for (c.name = d, this.tn.skip('{'); (d = this.tn.next()) !== '}';) { if (d === 'option') this._parseOption(c);else { if (!b.NAME.test(d)) throw Error('illegal name: ' + d); this.tn.skip('='), e = { name: d, id: h(this.tn.next(), !0) }, d = this.tn.peek(), d === '[' && this._parseFieldOptions({ options: {} }), this.tn.skip(';'), c.values.push(e); } } this.tn.omit(';'), a.enums.push(c); }, g._parseExtensionRanges = function () { var c; var d; var e; var b = []; do { for (d = [];;) { switch (c = this.tn.next()) { case 'min': e = a.ID_MIN; break; case 'max': e = a.ID_MAX; break; default: e = i(c); } if (d.push(e), d.length === 2) break; if (this.tn.peek() !== 'to') { d.push(e); break; } this.tn.next(); } b.push(d); } while (this.tn.omit(',')); return this.tn.skip(';'), b; }, g._parseExtend = function (a) { var d; var c = this.tn.next(); if (!b.TYPEREF.test(c)) throw Error('illegal extend reference: ' + c); for (d = { ref: c, fields: [] }, this.tn.skip('{'); (c = this.tn.next()) !== '}';) { if (b.RULE.test(c)) this._parseMessageField(d, c);else { if (!b.TYPEREF.test(c)) throw Error('illegal extend token: ' + c); if (!this.proto3) throw Error('illegal field rule: ' + c); this._parseMessageField(d, 'optional', c); } } return this.tn.omit(';'), a.messages.push(d), d; }, g.toString = function () { return 'Parser at line ' + this.tn.line; }, c.Parser = f, c; }(e, e.Lang), e.Reflect = function (a) { function k(b) { if (typeof b === 'string' && (b = a.TYPES[b]), typeof b.defaultValue === 'undefined') throw Error('default value for type ' + b.name + ' is not supported'); return b == a.TYPES.bytes ? new f(0) : b.defaultValue; } function l(b, c) { if (b && typeof b.low === 'number' && typeof b.high === 'number' && typeof b.unsigned === 'boolean' && b.low === b.low && b.high === b.high) return new a.Long(b.low, b.high, typeof c === 'undefined' ? b.unsigned : c); if (typeof b === 'string') return a.Long.fromString(b, c || !1, 10); if (typeof b === 'number') return a.Long.fromNumber(b, c || !1); throw Error('not convertible to Long'); } function o(b, c) { var d = c.readVarint32(); var e = 7 & d; var f = d >>> 3; switch (e) { case a.WIRE_TYPES.VARINT: do { d = c.readUint8(); } while ((128 & d) === 128); break; case a.WIRE_TYPES.BITS64: c.offset += 8; break; case a.WIRE_TYPES.LDELIM: d = c.readVarint32(), c.offset += d; break; case a.WIRE_TYPES.STARTGROUP: o(f, c); break; case a.WIRE_TYPES.ENDGROUP: if (f === b) return !1; throw Error('Illegal GROUPEND after unknown group: ' + f + ' (' + b + ' expected)'); case a.WIRE_TYPES.BITS32: c.offset += 4; break; default: throw Error('Illegal wire type in unknown group ' + b + ': ' + e); } return !0; } var g; var h; var i; var j; var m; var n; var p; var q; var r; var s; var t; var u; var v; var w; var x; var y; var z; var A; var B; var c = {}; var d = function d(a, b, c) { this.builder = a, this.parent = b, this.name = c, this.className; }; var e = d.prototype; return e.fqn = function () { for (var a = this.name, b = this;;) { if (b = b.parent, b == null) break; a = b.name + '.' + a; } return a; }, e.toString = function (a) { return (a ? this.className + ' ' : '') + this.fqn(); }, e.build = function () { throw Error(this.toString(!0) + ' cannot be built directly'); }, c.T = d, g = function g(a, b, c, e, f) { d.call(this, a, b, c), this.className = 'Namespace', this.children = [], this.options = e || {}, this.syntax = f || 'proto2'; }, h = g.prototype = Object.create(d.prototype), h.getChildren = function (a) { var b, c, d; if (a = a || null, a == null) return this.children.slice(); for (b = [], c = 0, d = this.children.length; d > c; ++c) { this.children[c] instanceof a && b.push(this.children[c]); } return b; }, h.addChild = function (a) { var b; if (b = this.getChild(a.name)) if (b instanceof m.Field && b.name !== b.originalName && this.getChild(b.originalName) === null) b.name = b.originalName;else { if (!(a instanceof m.Field && a.name !== a.originalName && this.getChild(a.originalName) === null)) throw Error('Duplicate name in namespace ' + this.toString(!0) + ': ' + a.name); a.name = a.originalName; } this.children.push(a); }, h.getChild = function (a) { var c; var d; var b = typeof a === 'number' ? 'id' : 'name'; for (c = 0, d = this.children.length; d > c; ++c) { if (this.children[c][b] === a) return this.children[c]; } return null; }, h.resolve = function (a, b) { var g; var d = typeof a === 'string' ? a.split('.') : a; var e = this; var f = 0; if (d[f] === '') { for (; e.parent !== null;) { e = e.parent; } f++; } do { do { if (!(e instanceof c.Namespace)) { e = null; break; } if (g = e.getChild(d[f]), !(g && g instanceof c.T && (!b || g instanceof c.Namespace))) { e = null; break; } e = g, f++; } while (f < d.length); if (e != null) break; if (this.parent !== null) return this.parent.resolve(a, b); } while (e != null); return e; }, h.qn = function (a) { var e; var f; var b = []; var d = a; do { b.unshift(d.name), d = d.parent; } while (d !== null); for (e = 1; e <= b.length; e++) { if (f = b.slice(b.length - e), a === this.resolve(f, a instanceof c.Namespace)) return f.join('.'); } return a.fqn(); }, h.build = function () { var e; var c; var d; var a = {}; var b = this.children; for (c = 0, d = b.length; d > c; ++c) { e = b[c], e instanceof g && (a[e.name] = e.build()); } return Object.defineProperty && Object.defineProperty(a, '$options', { value: this.buildOpt() }), a; }, h.buildOpt = function () { var c; var d; var e; var f; var a = {}; var b = Object.keys(this.options); for (c = 0, d = b.length; d > c; ++c) { e = b[c], f = this.options[b[c]], a[e] = f; } return a; }, h.getOption = function (a) { return typeof a === 'undefined' ? this.options : typeof this.options[a] !== 'undefined' ? this.options[a] : null; }, c.Namespace = g, i = function i(b, c, d, e) { if (this.type = b, this.resolvedType = c, this.isMapKey = d, this.syntax = e, d && a.MAP_KEY_TYPES.indexOf(b) < 0) throw Error('Invalid map key type: ' + b.name); }, j = i.prototype, i.defaultFieldValue = k, j.verifyValue = function (c) { var f; var g; var h; var d = function (a, b) { throw Error('Illegal value for ' + this.toString(!0) + ' of type ' + this.type.name + ': ' + a + ' (' + b + ')'); }.bind(this); switch (this.type) { case a.TYPES.int32: case a.TYPES.sint32: case a.TYPES.sfixed32: return (typeof c !== 'number' || c === c && c % 1 !== 0) && d(_typeof(c), 'not an integer'), c > 4294967295 ? 0 | c : c; case a.TYPES.uint32: case a.TYPES.fixed32: return (typeof c !== 'number' || c === c && c % 1 !== 0) && d(_typeof(c), 'not an integer'), c < 0 ? c >>> 0 : c; case a.TYPES.int64: case a.TYPES.sint64: case a.TYPES.sfixed64: if (a.Long) try { return l(c, !1); } catch (e) { d(_typeof(c), e.message); } else d(_typeof(c), 'requires Long.js'); case a.TYPES.uint64: case a.TYPES.fixed64: if (a.Long) try { return l(c, !0); } catch (e) { d(_typeof(c), e.message); } else d(_typeof(c), 'requires Long.js'); case a.TYPES.bool: return typeof c !== 'boolean' && d(_typeof(c), 'not a boolean'), c; case a.TYPES.float: case a.TYPES.double: return typeof c !== 'number' && d(_typeof(c), 'not a number'), c; case a.TYPES.string: return typeof c === 'string' || c && c instanceof String || d(_typeof(c), 'not a string'), '' + c; case a.TYPES.bytes: return b.isByteBuffer(c) ? c : b.wrap(c); case a.TYPES.enum: for (f = this.resolvedType.getChildren(a.Reflect.Enum.Value), h = 0; h < f.length; h++) { if (f[h].name == c) return f[h].id; if (f[h].id == c) return f[h].id; } if (this.syntax === 'proto3') return (typeof c !== 'number' || c === c && c % 1 !== 0) && d(_typeof(c), 'not an integer'), (c > 4294967295 || c < 0) && d(_typeof(c), 'not in range for uint32'), c; d(c, 'not a valid enum value'); case a.TYPES.group: case a.TYPES.message: if (c && _typeof(c) === 'object' || d(_typeof(c), 'object expected'), c instanceof this.resolvedType.clazz) return c; if (c instanceof a.Builder.Message) { g = {}; for (h in c) { c.hasOwnProperty(h) && (g[h] = c[h]); } c = g; } return new this.resolvedType.clazz(c); } throw Error('[INTERNAL] Illegal value for ' + this.toString(!0) + ': ' + c + ' (undefined type ' + this.type + ')'); }, j.calculateLength = function (b, c) { if (c === null) return 0; var d; switch (this.type) { case a.TYPES.int32: return c < 0 ? f.calculateVarint64(c) : f.calculateVarint32(c); case a.TYPES.uint32: return f.calculateVarint32(c); case a.TYPES.sint32: return f.calculateVarint32(f.zigZagEncode32(c)); case a.TYPES.fixed32: case a.TYPES.sfixed32: case a.TYPES.float: return 4; case a.TYPES.int64: case a.TYPES.uint64: return f.calculateVarint64(c); case a.TYPES.sint64: return f.calculateVarint64(f.zigZagEncode64(c)); case a.TYPES.fixed64: case a.TYPES.sfixed64: return 8; case a.TYPES.bool: return 1; case a.TYPES.enum: return f.calculateVarint32(c); case a.TYPES.double: return 8; case a.TYPES.string: return d = f.calculateUTF8Bytes(c), f.calculateVarint32(d) + d; case a.TYPES.bytes: if (c.remaining() < 0) throw Error('Illegal value for ' + this.toString(!0) + ': ' + c.remaining() + ' bytes remaining'); return f.calculateVarint32(c.remaining()) + c.remaining(); case a.TYPES.message: return d = this.resolvedType.calculate(c), f.calculateVarint32(d) + d; case a.TYPES.group: return d = this.resolvedType.calculate(c), d + f.calculateVarint32(b << 3 | a.WIRE_TYPES.ENDGROUP); } throw Error('[INTERNAL] Illegal value to encode in ' + this.toString(!0) + ': ' + c + ' (unknown type)'); }, j.encodeValue = function (b, c, d) { var e, g; if (c === null) return d; switch (this.type) { case a.TYPES.int32: c < 0 ? d.writeVarint64(c) : d.writeVarint32(c); break; case a.TYPES.uint32: d.writeVarint32(c); break; case a.TYPES.sint32: d.writeVarint32ZigZag(c); break; case a.TYPES.fixed32: d.writeUint32(c); break; case a.TYPES.sfixed32: d.writeInt32(c); break; case a.TYPES.int64: case a.TYPES.uint64: d.writeVarint64(c); break; case a.TYPES.sint64: d.writeVarint64ZigZag(c); break; case a.TYPES.fixed64: d.writeUint64(c); break; case a.TYPES.sfixed64: d.writeInt64(c); break; case a.TYPES.bool: typeof c === 'string' ? d.writeVarint32(c.toLowerCase() === 'false' ? 0 : !!c) : d.writeVarint32(c ? 1 : 0); break; case a.TYPES.enum: d.writeVarint32(c); break; case a.TYPES.float: d.writeFloat32(c); break; case a.TYPES.double: d.writeFloat64(c); break; case a.TYPES.string: d.writeVString(c); break; case a.TYPES.bytes: if (c.remaining() < 0) throw Error('Illegal value for ' + this.toString(!0) + ': ' + c.remaining() + ' bytes remaining'); e = c.offset, d.writeVarint32(c.remaining()), d.append(c), c.offset = e; break; case a.TYPES.message: g = new f().LE(), this.resolvedType.encode(c, g), d.writeVarint32(g.offset), d.append(g.flip()); break; case a.TYPES.group: this.resolvedType.encode(c, d), d.writeVarint32(b << 3 | a.WIRE_TYPES.ENDGROUP); break; default: throw Error('[INTERNAL] Illegal value to encode in ' + this.toString(!0) + ': ' + c + ' (unknown type)'); } return d; }, j.decode = function (b, c, d) { if (c != this.type.wireType) throw Error('Unexpected wire type for element'); var e, f; switch (this.type) { case a.TYPES.int32: return 0 | b.readVarint32(); case a.TYPES.uint32: return b.readVarint32() >>> 0; case a.TYPES.sint32: return 0 | b.readVarint32ZigZag(); case a.TYPES.fixed32: return b.readUint32() >>> 0; case a.TYPES.sfixed32: return 0 | b.readInt32(); case a.TYPES.int64: return b.readVarint64(); case a.TYPES.uint64: return b.readVarint64().toUnsigned(); case a.TYPES.sint64: return b.readVarint64ZigZag(); case a.TYPES.fixed64: return b.readUint64(); case a.TYPES.sfixed64: return b.readInt64(); case a.TYPES.bool: return !!b.readVarint32(); case a.TYPES.enum: return b.readVarint32(); case a.TYPES.float: return b.readFloat(); case a.TYPES.double: return b.readDouble(); case a.TYPES.string: return b.readVString(); case a.TYPES.bytes: if (f = b.readVarint32(), b.remaining() < f) throw Error('Illegal number of bytes for ' + this.toString(!0) + ': ' + f + ' required but got only ' + b.remaining()); return e = b.clone(), e.limit = e.offset + f, b.offset += f, e; case a.TYPES.message: return f = b.readVarint32(), this.resolvedType.decode(b, f); case a.TYPES.group: return this.resolvedType.decode(b, -1, d); } throw Error('[INTERNAL] Illegal decode type'); }, j.valueFromString = function (b) { if (!this.isMapKey) throw Error('valueFromString() called on non-map-key element'); switch (this.type) { case a.TYPES.int32: case a.TYPES.sint32: case a.TYPES.sfixed32: case a.TYPES.uint32: case a.TYPES.fixed32: return this.verifyValue(parseInt(b)); case a.TYPES.int64: case a.TYPES.sint64: case a.TYPES.sfixed64: case a.TYPES.uint64: case a.TYPES.fixed64: return this.verifyValue(b); case a.TYPES.bool: return b === 'true'; case a.TYPES.string: return this.verifyValue(b); case a.TYPES.bytes: return f.fromBinary(b); } }, j.valueToString = function (b) { if (!this.isMapKey) throw Error('valueToString() called on non-map-key element'); return this.type === a.TYPES.bytes ? b.toString('binary') : b.toString(); }, c.Element = i, m = function m(a, b, c, d, e, f) { g.call(this, a, b, c, d, f), this.className = 'Message', this.extensions = void 0, this.clazz = null, this.isGroup = !!e, this._fields = null, this._fieldsById = null, this._fieldsByName = null; }, n = m.prototype = Object.create(g.prototype), n.build = function (c) { var d, h, e, g; if (this.clazz && !c) return this.clazz; for (d = function (a, c) { function k(b, c, d, e) { var g, h, i, j, l, m, n; if (b === null || _typeof(b) !== 'object') return e && e instanceof a.Reflect.Enum && (g = a.Reflect.Enum.getName(e.object, b), g !== null) ? g : b; if (f.isByteBuffer(b)) return c ? b.toBase64() : b.toBuffer(); if (a.Long.isLong(b)) return d ? b.toString() : a.Long.fromValue(b); if (Array.isArray(b)) return h = [], b.forEach(function (a, b) { h[b] = k(a, c, d, e); }), h; if (h = {}, b instanceof a.Map) { for (i = b.entries(), j = i.next(); !j.done; j = i.next()) { h[b.keyElem.valueToString(j.value[0])] = k(j.value[1], c, d, b.valueElem.resolvedType); } return h; } l = b.$type, m = void 0; for (n in b) { b.hasOwnProperty(n) && (h[n] = l && (m = l.getChild(n)) ? k(b[n], c, d, m.resolvedType) : k(b[n], c, d)); } return h; } var i; var j; var d = c.getChildren(a.Reflect.Message.Field); var e = c.getChildren(a.Reflect.Message.OneOf); var g = function g(b) { var i, j, k, l; for (a.Builder.Message.call(this), i = 0, j = e.length; j > i; ++i) { this[e[i].name] = null; } for (i = 0, j = d.length; j > i; ++i) { k = d[i], this[k.name] = k.repeated ? [] : k.map ? new a.Map(k) : null, !k.required && c.syntax !== 'proto3' || k.defaultValue === null || (this[k.name] = k.defaultValue); } if (arguments.length > 0) if (arguments.length !== 1 || b === null || _typeof(b) !== 'object' || !(typeof b.encode !== 'function' || b instanceof g) || Array.isArray(b) || b instanceof a.Map || f.isByteBuffer(b) || b instanceof ArrayBuffer || a.Long && b instanceof a.Long) for (i = 0, j = arguments.length; j > i; ++i) { typeof (l = arguments[i]) !== 'undefined' && this.$set(d[i].name, l); } else this.$set(b); }; var h = g.prototype = Object.create(a.Builder.Message.prototype); for (h.add = function (b, d, e) { var f = c._fieldsByName[b]; if (!e) { if (!f) throw Error(this + '#' + b + ' is undefined'); if (!(f instanceof a.Reflect.Message.Field)) throw Error(this + '#' + b + ' is not a field: ' + f.toString(!0)); if (!f.repeated) throw Error(this + '#' + b + ' is not a repeated field'); d = f.verifyValue(d, !0); } return this[b] === null && (this[b] = []), this[b].push(d), this; }, h.$add = h.add, h.set = function (b, d, e) { var f, g, h; if (b && _typeof(b) === 'object') { e = d; for (f in b) { b.hasOwnProperty(f) && typeof (d = b[f]) !== 'undefined' && this.$set(f, d, e); } return this; } if (g = c._fieldsByName[b], e) this[b] = d;else { if (!g) throw Error(this + '#' + b + ' is not a field: undefined'); if (!(g instanceof a.Reflect.Message.Field)) throw Error(this + '#' + b + ' is not a field: ' + g.toString(!0)); this[g.name] = d = g.verifyValue(d); } return g && g.oneof && (h = this[g.oneof.name], d !== null ? (h !== null && h !== g.name && (this[h] = null), this[g.oneof.name] = g.name) : h === b && (this[g.oneof.name] = null)), this; }, h.$set = h.set, h.get = function (b, d) { if (d) return this[b]; var e = c._fieldsByName[b]; if (!(e && e instanceof a.Reflect.Message.Field)) throw Error(this + '#' + b + ' is not a field: undefined'); if (!(e instanceof a.Reflect.Message.Field)) throw Error(this + '#' + b + ' is not a field: ' + e.toString(!0)); return this[e.name]; }, h.$get = h.get, i = 0; i < d.length; i++) { j = d[i], j instanceof a.Reflect.Message.ExtensionField || c.builder.options.populateAccessors && function (a) { var d; var e; var f; var b = a.originalName.replace(/(_[a-zA-Z])/g, function (a) { return a.toUpperCase().replace('_', ''); }); b = b.substring(0, 1).toUpperCase() + b.substring(1), d = a.originalName.replace(/([A-Z])/g, function (a) { return '_' + a; }), e = function e(b, c) { return this[a.name] = c ? b : a.verifyValue(b), this; }, f = function f() { return this[a.name]; }, c.getChild('set' + b) === null && (h['set' + b] = e), c.getChild('set_' + d) === null && (h['set_' + d] = e), c.getChild('get' + b) === null && (h['get' + b] = f), c.getChild('get_' + d) === null && (h['get_' + d] = f); }(j); } return h.encode = function (a, d) { var e, f; typeof a === 'boolean' && (d = a, a = void 0), e = !1, a || (a = new b(), e = !0), f = a.littleEndian; try { return c.encode(this, a.LE(), d), (e ? a.flip() : a).LE(f); } catch (g) { throw a.LE(f), g; } }, g.encode = function (a, b, c) { return new g(a).encode(b, c); }, h.calculate = function () { return c.calculate(this); }, h.encodeDelimited = function (a) { var d; var b = !1; return a || (a = new f(), b = !0), d = new f().LE(), c.encode(this, d).flip(), a.writeVarint32(d.remaining()), a.append(d), b ? a.flip() : a; }, h.encodeAB = function () { try { return this.encode().toArrayBuffer(); } catch (a) { throw a.encoded && (a.encoded = a.encoded.toArrayBuffer()), a; } }, h.toArrayBuffer = h.encodeAB, h.encodeNB = function () { try { return this.encode().toBuffer(); } catch (a) { throw a.encoded && (a.encoded = a.encoded.toBuffer()), a; } }, h.toBuffer = h.encodeNB, h.encode64 = function () { try { return this.encode().toBase64(); } catch (a) { throw a.encoded && (a.encoded = a.encoded.toBase64()), a; } }, h.toBase64 = h.encode64, h.encodeHex = function () { try { return this.encode().toHex(); } catch (a) { throw a.encoded && (a.encoded = a.encoded.toHex()), a; } }, h.toHex = h.encodeHex, h.toRaw = function (a, b) { return k(this, !!a, !!b, this.$type); }, h.encodeJSON = function () { return JSON.stringify(k(this, !0, !0, this.$type)); }, g.decode = function (a, b) { var d, e; typeof a === 'string' && (a = f.wrap(a, b || 'base64')), a = f.isByteBuffer(a) ? a : f.wrap(a), d = a.littleEndian; try { return e = c.decode(a.LE()), a.LE(d), e; } catch (g) { throw a.LE(d), g; } }, g.decodeDelimited = function (a, b) { var d, e, g; if (typeof a === 'string' && (a = f.wrap(a, b || 'base64')), a = f.isByteBuffer(a) ? a : f.wrap(a), a.remaining() < 1) return null; if (d = a.offset, e = a.readVarint32(), a.remaining() < e) return a.offset = d, null; try { return g = c.decode(a.slice(a.offset, a.offset + e).LE()), a.offset += e, g; } catch (h) { throw a.offset += e, h; } }, g.decode64 = function (a) { return g.decode(a, 'base64'); }, g.decodeHex = function (a) { return g.decode(a, 'hex'); }, g.decodeJSON = function (a) { return new g(JSON.parse(a)); }, h.toString = function () { return c.toString(); }, Object.defineProperty && (Object.defineProperty(g, '$options', { value: c.buildOpt() }), Object.defineProperty(h, '$options', { value: g.$options }), Object.defineProperty(g, '$type', { value: c }), Object.defineProperty(h, '$type', { value: c })), g; }(a, this), this._fields = [], this._fieldsById = {}, this._fieldsByName = {}, e = 0, g = this.children.length; g > e; e++) { if (h = this.children[e], h instanceof t || h instanceof m || h instanceof x) { if (d.hasOwnProperty(h.name)) throw Error('Illegal reflect child of ' + this.toString(!0) + ': ' + h.toString(!0) + " cannot override static property '" + h.name + "'"); d[h.name] = h.build(); } else if (h instanceof m.Field) h.build(), this._fields.push(h), this._fieldsById[h.id] = h, this._fieldsByName[h.name] = h;else if (!(h instanceof m.OneOf || h instanceof w)) throw Error('Illegal reflect child of ' + this.toString(!0) + ': ' + this.children[e].toString(!0)); } return this.clazz = d; }, n.encode = function (a, b, c) { var e; var h; var f; var g; var i; var d = null; for (f = 0, g = this._fields.length; g > f; ++f) { e = this._fields[f], h = a[e.name], e.required && h === null ? d === null && (d = e) : e.encode(c ? h : e.verifyValue(h), b, a); } if (d !== null) throw i = Error('Missing at least one required field for ' + this.toString(!0) + ': ' + d), i.encoded = b, i; return b; }, n.calculate = function (a) { for (var e, f, b = 0, c = 0, d = this._fields.length; d > c; ++c) { if (e = this._fields[c], f = a[e.name], e.required && f === null) throw Error('Missing at least one required field for ' + this.toString(!0) + ': ' + e); b += e.calculate(f, a); } return b; }, n.decode = function (b, c, d) { var g, h, i, j, e, f, k, l, m, n, p, q; for (c = typeof c === 'number' ? c : -1, e = b.offset, f = new this.clazz(); b.offset < e + c || c === -1 && b.remaining() > 0;) { if (g = b.readVarint32(), h = 7 & g, i = g >>> 3, h === a.WIRE_TYPES.ENDGROUP) { if (i !== d) throw Error('Illegal group end indicator for ' + this.toString(!0) + ': ' + i + ' (' + (d ? d + ' expected' : 'not a group') + ')'); break; } if (j = this._fieldsById[i]) j.repeated && !j.options.packed ? f[j.name].push(j.decode(h, b)) : j.map ? (l = j.decode(h, b), f[j.name].set(l[0], l[1])) : (f[j.name] = j.decode(h, b), j.oneof && (m = f[j.oneof.name], m !== null && m !== j.name && (f[m] = null), f[j.oneof.name] = j.name));else switch (h) { case a.WIRE_TYPES.VARINT: b.readVarint32(); break; case a.WIRE_TYPES.BITS32: b.offset += 4; break; case a.WIRE_TYPES.BITS64: b.offset += 8; break; case a.WIRE_TYPES.LDELIM: k = b.readVarint32(), b.offset += k; break; case a.WIRE_TYPES.STARTGROUP: for (; o(i, b);) { } break; default: throw Error('Illegal wire type for unknown field ' + i + ' in ' + this.toString(!0) + '#decode: ' + h); } } for (n = 0, p = this._fields.length; p > n; ++n) { if (j = this._fields[n], f[j.name] === null) if (this.syntax === 'proto3') f[j.name] = j.defaultValue;else { if (j.required) throw q = Error('Missing at least one required field for ' + this.toString(!0) + ': ' + j.name), q.decoded = f, q; a.populateDefaults && j.defaultValue !== null && (f[j.name] = j.defaultValue); } } return f; }, c.Message = m, p = function p(b, c, e, f, g, h, i, j, k, l) { d.call(this, b, c, h), this.className = 'Message.Field', this.required = e === 'required', this.repeated = e === 'repeated', this.map = e === 'map', this.keyType = f || null, this.type = g, this.resolvedType = null, this.id = i, this.options = j || {}, this.defaultValue = null, this.oneof = k || null, this.syntax = l || 'proto2', this.originalName = this.name, this.element = null, this.keyElement = null, !this.builder.options.convertFieldsToCamelCase || this instanceof m.ExtensionField || (this.name = a.Util.toCamelCase(this.name)); }, q = p.prototype = Object.create(d.prototype), q.build = function () { this.element = new i(this.type, this.resolvedType, !1, this.syntax), this.map && (this.keyElement = new i(this.keyType, void 0, !0, this.syntax)), this.syntax !== 'proto3' || this.repeated || this.map ? typeof this.options.default !== 'undefined' && (this.defaultValue = this.verifyValue(this.options.default)) : this.defaultValue = i.defaultFieldValue(this.type); }, q.verifyValue = function (b, c) { var d, e, f; if (c = c || !1, d = function (a, b) { throw Error('Illegal value for ' + this.toString(!0) + ' of type ' + this.type.name + ': ' + a + ' (' + b + ')'); }.bind(this), b === null) return this.required && d(_typeof(b), 'required'), this.syntax === 'proto3' && this.type !== a.TYPES.message && d(_typeof(b), 'proto3 field without field presence cannot be null'), null; if (this.repeated && !c) { for (Array.isArray(b) || (b = [b]), f = [], e = 0; e < b.length; e++) { f.push(this.element.verifyValue(b[e])); } return f; } return this.map && !c ? b instanceof a.Map ? b : (b instanceof Object || d(_typeof(b), 'expected ProtoBuf.Map or raw object for map field'), new a.Map(this, b)) : (!this.repeated && Array.isArray(b) && d(_typeof(b), 'no array expected'), this.element.verifyValue(b)); }, q.hasWirePresence = function (b, c) { if (this.syntax !== 'proto3') return b !== null; if (this.oneof && c[this.oneof.name] === this.name) return !0; switch (this.type) { case a.TYPES.int32: case a.TYPES.sint32: case a.TYPES.sfixed32: case a.TYPES.uint32: case a.TYPES.fixed32: return b !== 0; case a.TYPES.int64: case a.TYPES.sint64: case a.TYPES.sfixed64: case a.TYPES.uint64: case a.TYPES.fixed64: return b.low !== 0 || b.high !== 0; case a.TYPES.bool: return b; case a.TYPES.float: case a.TYPES.double: return b !== 0; case a.TYPES.string: return b.length > 0; case a.TYPES.bytes: return b.remaining() > 0; case a.TYPES.enum: return b !== 0; case a.TYPES.message: return b !== null; default: return !0; } }, q.encode = function (b, c, d) { var e, g, h, i, j; if (this.type === null || _typeof(this.type) !== 'object') throw Error('[INTERNAL] Unresolved type in ' + this.toString(!0) + ': ' + this.type); if (b === null || this.repeated && b.length == 0) return c; try { if (this.repeated) { if (this.options.packed && a.PACKABLE_WIRE_TYPES.indexOf(this.type.wireType) >= 0) { for (c.writeVarint32(this.id << 3 | a.WIRE_TYPES.LDELIM), c.ensureCapacity(c.offset += 1), g = c.offset, e = 0; e < b.length; e++) { this.element.encodeValue(this.id, b[e], c); } h = c.offset - g, i = f.calculateVarint32(h), i > 1 && (j = c.slice(g, c.offset), g += i - 1, c.offset = g, c.append(j)), c.writeVarint32(h, g - i); } else for (e = 0; e < b.length; e++) { c.writeVarint32(this.id << 3 | this.type.wireType), this.element.encodeValue(this.id, b[e], c); } } else this.map ? b.forEach(function (b, d) { var g = f.calculateVarint32(8 | this.keyType.wireType) + this.keyElement.calculateLength(1, d) + f.calculateVarint32(16 | this.type.wireType) + this.element.calculateLength(2, b); c.writeVarint32(this.id << 3 | a.WIRE_TYPES.LDELIM), c.writeVarint32(g), c.writeVarint32(8 | this.keyType.wireType), this.keyElement.encodeValue(1, d, c), c.writeVarint32(16 | this.type.wireType), this.element.encodeValue(2, b, c); }, this) : this.hasWirePresence(b, d) && (c.writeVarint32(this.id << 3 | this.type.wireType), this.element.encodeValue(this.id, b, c)); } catch (k) { throw Error('Illegal value for ' + this.toString(!0) + ': ' + b + ' (' + k + ')'); } return c; }, q.calculate = function (b, c) { var d, e, g; if (b = this.verifyValue(b), this.type === null || _typeof(this.type) !== 'object') throw Error('[INTERNAL] Unresolved type in ' + this.toString(!0) + ': ' + this.type); if (b === null || this.repeated && b.length == 0) return 0; d = 0; try { if (this.repeated) { if (this.options.packed && a.PACKABLE_WIRE_TYPES.indexOf(this.type.wireType) >= 0) { for (d += f.calculateVarint32(this.id << 3 | a.WIRE_TYPES.LDELIM), g = 0, e = 0; e < b.length; e++) { g += this.element.calculateLength(this.id, b[e]); } d += f.calculateVarint32(g), d += g; } else for (e = 0; e < b.length; e++) { d += f.calculateVarint32(this.id << 3 | this.type.wireType), d += this.element.calculateLength(this.id, b[e]); } } else this.map ? b.forEach(function (b, c) { var g = f.calculateVarint32(8 | this.keyType.wireType) + this.keyElement.calculateLength(1, c) + f.calculateVarint32(16 | this.type.wireType) + this.element.calculateLength(2, b); d += f.calculateVarint32(this.id << 3 | a.WIRE_TYPES.LDELIM), d += f.calculateVarint32(g), d += g; }, this) : this.hasWirePresence(b, c) && (d += f.calculateVarint32(this.id << 3 | this.type.wireType), d += this.element.calculateLength(this.id, b)); } catch (h) { throw Error('Illegal value for ' + this.toString(!0) + ': ' + b + ' (' + h + ')'); } return d; }, q.decode = function (b, c, d) { var e; var f; var h; var j; var k; var l; var m; var g = !this.map && b == this.type.wireType || !d && this.repeated && this.options.packed && b == a.WIRE_TYPES.LDELIM || this.map && b == a.WIRE_TYPES.LDELIM; if (!g) throw Error('Illegal wire type for field ' + this.toString(!0) + ': ' + b + ' (' + this.type.wireType + ' expected)'); if (b == a.WIRE_TYPES.LDELIM && this.repeated && this.options.packed && a.PACKABLE_WIRE_TYPES.indexOf(this.type.wireType) >= 0 && !d) { for (f = c.readVarint32(), f = c.offset + f, h = []; c.offset < f;) { h.push(this.decode(this.type.wireType, c, !0)); } return h; } if (this.map) { if (j = i.defaultFieldValue(this.keyType), e = i.defaultFieldValue(this.type), f = c.readVarint32(), c.remaining() < f) throw Error('Illegal number of bytes for ' + this.toString(!0) + ': ' + f + ' required but got only ' + c.remaining()); for (k = c.clone(), k.limit = k.offset + f, c.offset += f; k.remaining() > 0;) { if (l = k.readVarint32(), b = 7 & l, m = l >>> 3, m === 1) j = this.keyElement.decode(k, b, m);else { if (m !== 2) throw Error('Unexpected tag in map field key/value submessage'); e = this.element.decode(k, b, m); } } return [j, e]; } return this.element.decode(c, b, this.id); }, c.Message.Field = p, r = function r(a, b, c, d, e, f, g) { p.call(this, a, b, c, null, d, e, f, g), this.extension; }, r.prototype = Object.create(p.prototype), c.Message.ExtensionField = r, s = function s(a, b, c) { d.call(this, a, b, c), this.fields = []; }, c.Message.OneOf = s, t = function t(a, b, c, d, e) { g.call(this, a, b, c, d, e), this.className = 'Enum', this.object = null; }, t.getName = function (a, b) { var e; var d; var c = Object.keys(a); for (d = 0; d < c.length; ++d) { if (a[e = c[d]] === b) return e; } return null; }, u = t.prototype = Object.create(g.prototype), u.build = function (b) { var c, d, e, f; if (this.object && !b) return this.object; for (c = new a.Builder.Enum(), d = this.getChildren(t.Value), e = 0, f = d.length; f > e; ++e) { c[d[e].name] = d[e].id; } return Object.defineProperty && Object.defineProperty(c, '$options', { value: this.buildOpt(), enumerable: !1 }), this.object = c; }, c.Enum = t, v = function v(a, b, c, e) { d.call(this, a, b, c), this.className = 'Enum.Value', this.id = e; }, v.prototype = Object.create(d.prototype), c.Enum.Value = v, w = function w(a, b, c, e) { d.call(this, a, b, c), this.field = e; }, w.prototype = Object.create(d.prototype), c.Extension = w, x = function x(a, b, c, d) { g.call(this, a, b, c, d), this.className = 'Service', this.clazz = null; }, y = x.prototype = Object.create(g.prototype), y.build = function (b) { return this.clazz && !b ? this.clazz : this.clazz = function (a, b) { var g; var c = function c(b) { a.Builder.Service.call(this), this.rpcImpl = b || function (a, b, c) { setTimeout(c.bind(this, Error('Not implemented, see: https://github.com/dcodeIO/ProtoBuf.js/wiki/Services')), 0); }; }; var d = c.prototype = Object.create(a.Builder.Service.prototype); var e = b.getChildren(a.Reflect.Service.RPCMethod); for (g = 0; g < e.length; g++) { !function (a) { d[a.name] = function (c, d) { try { try { c = a.resolvedRequestType.clazz.decode(f.wrap(c)); } catch (e) { if (!(e instanceof TypeError)) throw e; } if (c === null || _typeof(c) !== 'object') throw Error('Illegal arguments'); c instanceof a.resolvedRequestType.clazz || (c = new a.resolvedRequestType.clazz(c)), this.rpcImpl(a.fqn(), c, function (c, e) { if (c) return d(c), void 0; try { e = a.resolvedResponseType.clazz.decode(e); } catch (f) {} return e && e instanceof a.resolvedResponseType.clazz ? (d(null, e), void 0) : (d(Error('Illegal response type received in service method ' + b.name + '#' + a.name)), void 0); }); } catch (e) { setTimeout(d.bind(this, e), 0); } }, c[a.name] = function (b, d, e) { new c(b)[a.name](d, e); }, Object.defineProperty && (Object.defineProperty(c[a.name], '$options', { value: a.buildOpt() }), Object.defineProperty(d[a.name], '$options', { value: c[a.name].$options })); }(e[g]); } return Object.defineProperty && (Object.defineProperty(c, '$options', { value: b.buildOpt() }), Object.defineProperty(d, '$options', { value: c.$options }), Object.defineProperty(c, '$type', { value: b }), Object.defineProperty(d, '$type', { value: b })), c; }(a, this); }, c.Service = x, z = function z(a, b, c, e) { d.call(this, a, b, c), this.className = 'Service.Method', this.options = e || {}; }, A = z.prototype = Object.create(d.prototype), A.buildOpt = h.buildOpt, c.Service.Method = z, B = function B(a, b, c, d, e, f, g, h) { z.call(this, a, b, c, h), this.className = 'Service.RPCMethod', this.requestName = d, this.responseName = e, this.requestStream = f, this.responseStream = g, this.resolvedRequestType = null, this.resolvedResponseType = null; }, B.prototype = Object.create(z.prototype), c.Service.RPCMethod = B, c; }(e), e.Builder = function (a, b, c) { function f(a) { a.messages && a.messages.forEach(function (b) { b.syntax = a.syntax, f(b); }), a.enums && a.enums.forEach(function (b) { b.syntax = a.syntax; }); } var d = function d(a) { this.ns = new c.Namespace(this, null, ''), this.ptr = this.ns, this.resolved = !1, this.result = null, this.files = {}, this.importRoot = null, this.options = a || {}; }; var e = d.prototype; return d.isMessage = function (a) { return typeof a.name !== 'string' ? !1 : typeof a.values !== 'undefined' || typeof a.rpc !== 'undefined' ? !1 : !0; }, d.isMessageField = function (a) { return typeof a.rule !== 'string' || typeof a.name !== 'string' || typeof a.type !== 'string' || typeof a.id === 'undefined' ? !1 : !0; }, d.isEnum = function (a) { return typeof a.name !== 'string' ? !1 : typeof a.values !== 'undefined' && Array.isArray(a.values) && a.values.length !== 0 ? !0 : !1; }, d.isService = function (a) { return typeof a.name === 'string' && _typeof(a.rpc) === 'object' && a.rpc ? !0 : !1; }, d.isExtend = function (a) { return typeof a.ref !== 'string' ? !1 : !0; }, e.reset = function () { return this.ptr = this.ns, this; }, e.define = function (a) { if (typeof a !== 'string' || !b.TYPEREF.test(a)) throw Error('illegal namespace: ' + a); return a.split('.').forEach(function (a) { var b = this.ptr.getChild(a); b === null && this.ptr.addChild(b = new c.Namespace(this, this.ptr, a)), this.ptr = b; }, this), this; }, e.create = function (b) { var e, f, g, h, i; if (!b) return this; if (Array.isArray(b)) { if (b.length === 0) return this; b = b.slice(); } else b = [b]; for (e = [b]; e.length > 0;) { if (b = e.pop(), !Array.isArray(b)) throw Error('not a valid namespace: ' + JSON.stringify(b)); for (; b.length > 0;) { if (f = b.shift(), d.isMessage(f)) { if (g = new c.Message(this, this.ptr, f.name, f.options, f.isGroup, f.syntax), h = {}, f.oneofs && Object.keys(f.oneofs).forEach(function (a) { g.addChild(h[a] = new c.Message.OneOf(this, g, a)); }, this), f.fields && f.fields.forEach(function (a) { if (g.getChild(0 | a.id) !== null) throw Error('duplicate or invalid field id in ' + g.name + ': ' + a.id); if (a.options && _typeof(a.options) !== 'object') throw Error('illegal field options in ' + g.name + '#' + a.name); var b = null; if (typeof a.oneof === 'string' && !(b = h[a.oneof])) throw Error('illegal oneof in ' + g.name + '#' + a.name + ': ' + a.oneof); a = new c.Message.Field(this, g, a.rule, a.keytype, a.type, a.name, a.id, a.options, b, f.syntax), b && b.fields.push(a), g.addChild(a); }, this), i = [], f.enums && f.enums.forEach(function (a) { i.push(a); }), f.messages && f.messages.forEach(function (a) { i.push(a); }), f.services && f.services.forEach(function (a) { i.push(a); }), f.extensions && (g.extensions = typeof f.extensions[0] === 'number' ? [f.extensions] : f.extensions), this.ptr.addChild(g), i.length > 0) { e.push(b), b = i, i = null, this.ptr = g, g = null; continue; } i = null; } else if (d.isEnum(f)) g = new c.Enum(this, this.ptr, f.name, f.options, f.syntax), f.values.forEach(function (a) { g.addChild(new c.Enum.Value(this, g, a.name, a.id)); }, this), this.ptr.addChild(g);else if (d.isService(f)) g = new c.Service(this, this.ptr, f.name, f.options), Object.keys(f.rpc).forEach(function (a) { var b = f.rpc[a]; g.addChild(new c.Service.RPCMethod(this, g, a, b.request, b.response, !!b.request_stream, !!b.response_stream, b.options)); }, this), this.ptr.addChild(g);else { if (!d.isExtend(f)) throw Error('not a valid definition: ' + JSON.stringify(f)); if (g = this.ptr.resolve(f.ref, !0)) { f.fields.forEach(function (b) { var d, e, f, h; if (g.getChild(0 | b.id) !== null) throw Error('duplicate extended field id in ' + g.name + ': ' + b.id); if (g.extensions && (d = !1, g.extensions.forEach(function (a) { b.id >= a[0] && b.id <= a[1] && (d = !0); }), !d)) throw Error('illegal extended field id in ' + g.name + ': ' + b.id + ' (not within valid ranges)'); e = b.name, this.options.convertFieldsToCamelCase && (e = a.Util.toCamelCase(e)), f = new c.Message.ExtensionField(this, g, b.rule, b.type, this.ptr.fqn() + '.' + e, b.id, b.options), h = new c.Extension(this, this.ptr, b.name, f), f.extension = h, this.ptr.addChild(h), g.addChild(f); }, this); } else if (!/\.?google\.protobuf\./.test(f.ref)) throw Error('extended message ' + f.ref + ' is not defined'); } f = null, g = null; } b = null, this.ptr = this.ptr.parent; } return this.resolved = !1, this.result = null, this; }, e.import = function (b, c) { var e; var g; var h; var i; var j; var k; var l; var m; var d = '/'; if (typeof c === 'string') { if (a.Util.IS_NODE, this.files[c] === !0) return this.reset(); this.files[c] = !0; } else if (_typeof(c) === 'object') { if (e = c.root, a.Util.IS_NODE, (e.indexOf('\\') >= 0 || c.file.indexOf('\\') >= 0) && (d = '\\'), g = e + d + c.file, this.files[g] === !0) return this.reset(); this.files[g] = !0; } if (b.imports && b.imports.length > 0) { for (i = !1, _typeof(c) === 'object' ? (this.importRoot = c.root, i = !0, h = this.importRoot, c = c.file, (h.indexOf('\\') >= 0 || c.indexOf('\\') >= 0) && (d = '\\')) : typeof c === 'string' ? this.importRoot ? h = this.importRoot : c.indexOf('/') >= 0 ? (h = c.replace(/\/[^\/]*$/, ''), h === '' && (h = '/')) : c.indexOf('\\') >= 0 ? (h = c.replace(/\\[^\\]*$/, ''), d = '\\') : h = '.' : h = null, j = 0; j < b.imports.length; j++) { if (typeof b.imports[j] === 'string') { if (!h) throw Error('cannot determine import root'); if (k = b.imports[j], k === 'google/protobuf/descriptor.proto') continue; if (k = h + d + k, this.files[k] === !0) continue; if (/\.proto$/i.test(k) && !a.DotProto && (k = k.replace(/\.proto$/, '.json')), l = a.Util.fetch(k), l === null) throw Error("failed to import '" + k + "' in '" + c + "': file not found"); /\.json$/i.test(k) ? this.import(JSON.parse(l + ''), k) : this.import(a.DotProto.Parser.parse(l), k); } else c ? /\.(\w+)$/.test(c) ? this.import(b.imports[j], c.replace(/^(.+)\.(\w+)$/, function (a, b, c) { return b + '_import' + j + '.' + c; })) : this.import(b.imports[j], c + '_import' + j) : this.import(b.imports[j]); } i && (this.importRoot = null); } return b.package && this.define(b.package), b.syntax && f(b), m = this.ptr, b.options && Object.keys(b.options).forEach(function (a) { m.options[a] = b.options[a]; }), b.messages && (this.create(b.messages), this.ptr = m), b.enums && (this.create(b.enums), this.ptr = m), b.services && (this.create(b.services), this.ptr = m), b.extends && this.create(b.extends), this.reset(); }, e.resolveAll = function () { var d; if (this.ptr == null || _typeof(this.ptr.type) === 'object') return this; if (this.ptr instanceof c.Namespace) this.ptr.children.forEach(function (a) { this.ptr = a, this.resolveAll(); }, this);else if (this.ptr instanceof c.Message.Field) { if (b.TYPE.test(this.ptr.type)) this.ptr.type = a.TYPES[this.ptr.type];else { if (!b.TYPEREF.test(this.ptr.type)) throw Error('illegal type reference in ' + this.ptr.toString(!0) + ': ' + this.ptr.type); if (d = (this.ptr instanceof c.Message.ExtensionField ? this.ptr.extension.parent : this.ptr.parent).resolve(this.ptr.type, !0), !d) throw Error('unresolvable type reference in ' + this.ptr.toString(!0) + ': ' + this.ptr.type); if (this.ptr.resolvedType = d, d instanceof c.Enum) { if (this.ptr.type = a.TYPES.enum, this.ptr.syntax === 'proto3' && d.syntax !== 'proto3') throw Error('proto3 message cannot reference proto2 enum'); } else { if (!(d instanceof c.Message)) throw Error('illegal type reference in ' + this.ptr.toString(!0) + ': ' + this.ptr.type); this.ptr.type = d.isGroup ? a.TYPES.group : a.TYPES.message; } } if (this.ptr.map) { if (!b.TYPE.test(this.ptr.keyType)) throw Error('illegal key type for map field in ' + this.ptr.toString(!0) + ': ' + this.ptr.keyType); this.ptr.keyType = a.TYPES[this.ptr.keyType]; } } else if (this.ptr instanceof a.Reflect.Service.Method) { if (!(this.ptr instanceof a.Reflect.Service.RPCMethod)) throw Error('illegal service type in ' + this.ptr.toString(!0)); if (d = this.ptr.parent.resolve(this.ptr.requestName, !0), !(d && d instanceof a.Reflect.Message)) throw Error('Illegal type reference in ' + this.ptr.toString(!0) + ': ' + this.ptr.requestName); if (this.ptr.resolvedRequestType = d, d = this.ptr.parent.resolve(this.ptr.responseName, !0), !(d && d instanceof a.Reflect.Message)) throw Error('Illegal type reference in ' + this.ptr.toString(!0) + ': ' + this.ptr.responseName); this.ptr.resolvedResponseType = d; } else if (!(this.ptr instanceof a.Reflect.Message.OneOf || this.ptr instanceof a.Reflect.Extension || this.ptr instanceof a.Reflect.Enum.Value)) throw Error('illegal object in namespace: ' + _typeof(this.ptr) + ': ' + this.ptr); return this.reset(); }, e.build = function (a) { var b, c, d; if (this.reset(), this.resolved || (this.resolveAll(), this.resolved = !0, this.result = null), this.result === null && (this.result = this.ns.build()), !a) return this.result; for (b = typeof a === 'string' ? a.split('.') : a, c = this.result, d = 0; d < b.length; d++) { if (!c[b[d]]) { c = null; break; } c = c[b[d]]; } return c; }, e.lookup = function (a, b) { return a ? this.ns.resolve(a, b) : this.ns; }, e.toString = function () { return 'Builder'; }, d.Message = function () {}, d.Enum = function () {}, d.Service = function () {}, d; }(e, e.Lang, e.Reflect), e.Map = function (a, b) { function e(a) { var b = 0; return { next: function next() { return b < a.length ? { done: !1, value: a[b++] } : { done: !0 }; } }; } var c = function c(a, _c) { var d, e, f, g; if (!a.map) throw Error('field is not a map'); if (this.field = a, this.keyElem = new b.Element(a.keyType, null, !0, a.syntax), this.valueElem = new b.Element(a.type, a.resolvedType, !1, a.syntax), this.map = {}, Object.defineProperty(this, 'size', { get: function get() { return Object.keys(this.map).length; } }), _c) for (d = Object.keys(_c), e = 0; e < d.length; e++) { f = this.keyElem.valueFromString(d[e]), g = this.valueElem.verifyValue(_c[d[e]]), this.map[this.keyElem.valueToString(f)] = { key: f, value: g }; } }; var d = c.prototype; return d.clear = function () { this.map = {}; }, d.delete = function (a) { var b = this.keyElem.valueToString(this.keyElem.verifyValue(a)); var c = (b in this.map); return delete this.map[b], c; }, d.entries = function () { var d; var c; var a = []; var b = Object.keys(this.map); for (c = 0; c < b.length; c++) { a.push([(d = this.map[b[c]]).key, d.value]); } return e(a); }, d.keys = function () { var c; var a = []; var b = Object.keys(this.map); for (c = 0; c < b.length; c++) { a.push(this.map[b[c]].key); } return e(a); }, d.values = function () { var c; var a = []; var b = Object.keys(this.map); for (c = 0; c < b.length; c++) { a.push(this.map[b[c]].value); } return e(a); }, d.forEach = function (a, b) { var e; var d; var c = Object.keys(this.map); for (d = 0; d < c.length; d++) { a.call(b, (e = this.map[c[d]]).value, e.key, this); } }, d.set = function (a, b) { var c = this.keyElem.verifyValue(a); var d = this.valueElem.verifyValue(b); return this.map[this.keyElem.valueToString(c)] = { key: c, value: d }, this; }, d.get = function (a) { var b = this.keyElem.valueToString(this.keyElem.verifyValue(a)); return b in this.map ? this.map[b].value : void 0; }, d.has = function (a) { var b = this.keyElem.valueToString(this.keyElem.verifyValue(a)); return b in this.map; }, c; }(e, e.Reflect), e.loadProto = function (a, b, c) { return (typeof b === 'string' || b && typeof b.file === 'string' && typeof b.root === 'string') && (c = b, b = void 0), e.loadJson(e.DotProto.Parser.parse(a), b, c); }, e.protoFromString = e.loadProto, e.loadProtoFile = function (a, b, c) { if (b && _typeof(b) === 'object' ? (c = b, b = null) : b && typeof b === 'function' || (b = null), b) return e.Util.fetch(typeof a === 'string' ? a : a.root + '/' + a.file, function (d) { if (d === null) return b(Error('Failed to fetch file')), void 0; try { b(null, e.loadProto(d, c, a)); } catch (f) { b(f); } }); var d = e.Util.fetch(_typeof(a) === 'object' ? a.root + '/' + a.file : a); return d === null ? null : e.loadProto(d, c, a); }, e.protoFromFile = e.loadProtoFile, e.newBuilder = function (a) { return a = a || {}, typeof a.convertFieldsToCamelCase === 'undefined' && (a.convertFieldsToCamelCase = e.convertFieldsToCamelCase), typeof a.populateAccessors === 'undefined' && (a.populateAccessors = e.populateAccessors), new e.Builder(a); }, e.loadJson = function (a, b, c) { return (typeof b === 'string' || b && typeof b.file === 'string' && typeof b.root === 'string') && (c = b, b = null), b && _typeof(b) === 'object' || (b = e.newBuilder()), typeof a === 'string' && (a = JSON.parse(a)), b.import(a, c), b.resolveAll(), b; }, e.loadJsonFile = function (a, b, c) { if (b && _typeof(b) === 'object' ? (c = b, b = null) : b && typeof b === 'function' || (b = null), b) return e.Util.fetch(typeof a === 'string' ? a : a.root + '/' + a.file, function (d) { if (d === null) return b(Error('Failed to fetch file')), void 0; try { b(null, e.loadJson(JSON.parse(d), c, a)); } catch (f) { b(f); } }); var d = e.Util.fetch(_typeof(a) === 'object' ? a.root + '/' + a.file : a); return d === null ? null : e.loadJson(JSON.parse(d), c, a); }, h = a, i = e.loadProto(h, void 0, '').build('Modules').probuf; }(d, c); return e; } var Codec$1 = protobuf(SSMsg$1); Codec$1.getModule = function (pbName) { var _this11 = this; _newArrowCheck(this, _this); var modules = new Codec$1[pbName](); modules.getArrayData = function () { _newArrowCheck(this, _this11); var data = modules.toArrayBuffer(); data = isArrayBuffer(data) ? [].slice.call(new Int8Array(data)) : data; return data; }.bind(this); return modules; }.bind(undefined); var ErrorCode; (function (ErrorCode) { ErrorCode[ErrorCode["TIMEOUT"] = -1] = "TIMEOUT"; ErrorCode[ErrorCode["UNKNOWN"] = -2] = "UNKNOWN"; ErrorCode[ErrorCode["PARAMETER_ERROR"] = -3] = "PARAMETER_ERROR"; ErrorCode[ErrorCode["SUCCESS"] = 0] = "SUCCESS"; ErrorCode[ErrorCode["RC_MSG_UNAUTHORIZED"] = 20406] = "RC_MSG_UNAUTHORIZED"; ErrorCode[ErrorCode["RC_DISCUSSION_GROUP_ID_INVALID"] = 20407] = "RC_DISCUSSION_GROUP_ID_INVALID"; ErrorCode[ErrorCode["SEND_FREQUENCY_TOO_FAST"] = 20604] = "SEND_FREQUENCY_TOO_FAST"; ErrorCode[ErrorCode["NOT_IN_DISCUSSION"] = 21406] = "NOT_IN_DISCUSSION"; ErrorCode[ErrorCode["FORBIDDEN_IN_GROUP"] = 22408] = "FORBIDDEN_IN_GROUP"; ErrorCode[ErrorCode["RECALL_MESSAGE"] = 25101] = "RECALL_MESSAGE"; ErrorCode[ErrorCode["NOT_IN_GROUP"] = 22406] = "NOT_IN_GROUP"; ErrorCode[ErrorCode["NOT_IN_CHATROOM"] = 23406] = "NOT_IN_CHATROOM"; ErrorCode[ErrorCode["FORBIDDEN_IN_CHATROOM"] = 23408] = "FORBIDDEN_IN_CHATROOM"; ErrorCode[ErrorCode["RC_CHATROOM_USER_KICKED"] = 23409] = "RC_CHATROOM_USER_KICKED"; ErrorCode[ErrorCode["RC_CHATROOM_NOT_EXIST"] = 23410] = "RC_CHATROOM_NOT_EXIST"; ErrorCode[ErrorCode["RC_CHATROOM_IS_FULL"] = 23411] = "RC_CHATROOM_IS_FULL"; ErrorCode[ErrorCode["RC_CHATROOM_PATAMETER_INVALID"] = 23412] = "RC_CHATROOM_PATAMETER_INVALID"; ErrorCode[ErrorCode["CHATROOM_GET_HISTORYMSG_ERROR"] = 23413] = "CHATROOM_GET_HISTORYMSG_ERROR"; ErrorCode[ErrorCode["CHATROOM_NOT_OPEN_HISTORYMSG_STORE"] = 23414] = "CHATROOM_NOT_OPEN_HISTORYMSG_STORE"; ErrorCode[ErrorCode["CHATROOM_KV_EXCEED"] = 23423] = "CHATROOM_KV_EXCEED"; ErrorCode[ErrorCode["CHATROOM_KV_OVERWRITE_INVALID"] = 23424] = "CHATROOM_KV_OVERWRITE_INVALID"; ErrorCode[ErrorCode["CHATROOM_KV_STORE_NOT_OPEN"] = 23426] = "CHATROOM_KV_STORE_NOT_OPEN"; ErrorCode[ErrorCode["CHATROOM_KEY_NOT_EXIST"] = 23427] = "CHATROOM_KEY_NOT_EXIST"; ErrorCode[ErrorCode["SENSITIVE_SHIELD"] = 21501] = "SENSITIVE_SHIELD"; ErrorCode[ErrorCode["SENSITIVE_REPLACE"] = 21502] = "SENSITIVE_REPLACE"; ErrorCode[ErrorCode["JOIN_IN_DISCUSSION"] = 21407] = "JOIN_IN_DISCUSSION"; ErrorCode[ErrorCode["CREATE_DISCUSSION"] = 21408] = "CREATE_DISCUSSION"; ErrorCode[ErrorCode["INVITE_DICUSSION"] = 21409] = "INVITE_DICUSSION"; ErrorCode[ErrorCode["GET_USERINFO_ERROR"] = 23407] = "GET_USERINFO_ERROR"; ErrorCode[ErrorCode["REJECTED_BY_BLACKLIST"] = 405] = "REJECTED_BY_BLACKLIST"; ErrorCode[ErrorCode["RC_NET_CHANNEL_INVALID"] = 30001] = "RC_NET_CHANNEL_INVALID"; ErrorCode[ErrorCode["RC_NET_UNAVAILABLE"] = 30002] = "RC_NET_UNAVAILABLE"; ErrorCode[ErrorCode["RC_MSG_RESP_TIMEOUT"] = 30003] = "RC_MSG_RESP_TIMEOUT"; ErrorCode[ErrorCode["RC_HTTP_SEND_FAIL"] = 30004] = "RC_HTTP_SEND_FAIL"; ErrorCode[ErrorCode["RC_HTTP_REQ_TIMEOUT"] = 30005] = "RC_HTTP_REQ_TIMEOUT"; ErrorCode[ErrorCode["RC_HTTP_RECV_FAIL"] = 30006] = "RC_HTTP_RECV_FAIL"; ErrorCode[ErrorCode["RC_NAVI_RESOURCE_ERROR"] = 30007] = "RC_NAVI_RESOURCE_ERROR"; ErrorCode[ErrorCode["RC_NODE_NOT_FOUND"] = 30008] = "RC_NODE_NOT_FOUND"; ErrorCode[ErrorCode["RC_DOMAIN_NOT_RESOLVE"] = 30009] = "RC_DOMAIN_NOT_RESOLVE"; ErrorCode[ErrorCode["RC_SOCKET_NOT_CREATED"] = 30010] = "RC_SOCKET_NOT_CREATED"; ErrorCode[ErrorCode["RC_SOCKET_DISCONNECTED"] = 30011] = "RC_SOCKET_DISCONNECTED"; ErrorCode[ErrorCode["RC_PING_SEND_FAIL"] = 30012] = "RC_PING_SEND_FAIL"; ErrorCode[ErrorCode["RC_PONG_RECV_FAIL"] = 30013] = "RC_PONG_RECV_FAIL"; ErrorCode[ErrorCode["RC_MSG_SEND_FAIL"] = 30014] = "RC_MSG_SEND_FAIL"; ErrorCode[ErrorCode["RC_MSG_CONTENT_EXCEED_LIMIT"] = 30016] = "RC_MSG_CONTENT_EXCEED_LIMIT"; ErrorCode[ErrorCode["RC_CONN_ACK_TIMEOUT"] = 31000] = "RC_CONN_ACK_TIMEOUT"; ErrorCode[ErrorCode["RC_CONN_PROTO_VERSION_ERROR"] = 31001] = "RC_CONN_PROTO_VERSION_ERROR"; ErrorCode[ErrorCode["RC_CONN_ID_REJECT"] = 31002] = "RC_CONN_ID_REJECT"; ErrorCode[ErrorCode["RC_CONN_SERVER_UNAVAILABLE"] = 31003] = "RC_CONN_SERVER_UNAVAILABLE"; ErrorCode[ErrorCode["RC_CONN_USER_OR_PASSWD_ERROR"] = 31004] = "RC_CONN_USER_OR_PASSWD_ERROR"; ErrorCode[ErrorCode["RC_CONN_NOT_AUTHRORIZED"] = 31005] = "RC_CONN_NOT_AUTHRORIZED"; ErrorCode[ErrorCode["RC_CONN_REDIRECTED"] = 31006] = "RC_CONN_REDIRECTED"; ErrorCode[ErrorCode["RC_CONN_PACKAGE_NAME_INVALID"] = 31007] = "RC_CONN_PACKAGE_NAME_INVALID"; ErrorCode[ErrorCode["RC_CONN_APP_BLOCKED_OR_DELETED"] = 31008] = "RC_CONN_APP_BLOCKED_OR_DELETED"; ErrorCode[ErrorCode["RC_CONN_USER_BLOCKED"] = 31009] = "RC_CONN_USER_BLOCKED"; ErrorCode[ErrorCode["RC_DISCONN_KICK"] = 31010] = "RC_DISCONN_KICK"; ErrorCode[ErrorCode["RC_DISCONN_EXCEPTION"] = 31011] = "RC_DISCONN_EXCEPTION"; ErrorCode[ErrorCode["RC_QUERY_ACK_NO_DATA"] = 32001] = "RC_QUERY_ACK_NO_DATA"; ErrorCode[ErrorCode["RC_MSG_DATA_INCOMPLETE"] = 32002] = "RC_MSG_DATA_INCOMPLETE"; ErrorCode[ErrorCode["BIZ_ERROR_CLIENT_NOT_INIT"] = 33001] = "BIZ_ERROR_CLIENT_NOT_INIT"; ErrorCode[ErrorCode["BIZ_ERROR_DATABASE_ERROR"] = 33002] = "BIZ_ERROR_DATABASE_ERROR"; ErrorCode[ErrorCode["BIZ_ERROR_INVALID_PARAMETER"] = 33003] = "BIZ_ERROR_INVALID_PARAMETER"; ErrorCode[ErrorCode["BIZ_ERROR_NO_CHANNEL"] = 33004] = "BIZ_ERROR_NO_CHANNEL"; ErrorCode[ErrorCode["BIZ_ERROR_RECONNECT_SUCCESS"] = 33005] = "BIZ_ERROR_RECONNECT_SUCCESS"; ErrorCode[ErrorCode["BIZ_ERROR_CONNECTING"] = 33006] = "BIZ_ERROR_CONNECTING"; ErrorCode[ErrorCode["MSG_ROAMING_SERVICE_UNAVAILABLE"] = 33007] = "MSG_ROAMING_SERVICE_UNAVAILABLE"; ErrorCode[ErrorCode["MSG_INSERT_ERROR"] = 33008] = "MSG_INSERT_ERROR"; ErrorCode[ErrorCode["MSG_DEL_ERROR"] = 33009] = "MSG_DEL_ERROR"; ErrorCode[ErrorCode["CONVER_REMOVE_ERROR"] = 34001] = "CONVER_REMOVE_ERROR"; ErrorCode[ErrorCode["CONVER_GETLIST_ERROR"] = 34002] = "CONVER_GETLIST_ERROR"; ErrorCode[ErrorCode["CONVER_SETOP_ERROR"] = 34003] = "CONVER_SETOP_ERROR"; ErrorCode[ErrorCode["CONVER_TOTAL_UNREAD_ERROR"] = 34004] = "CONVER_TOTAL_UNREAD_ERROR"; ErrorCode[ErrorCode["CONVER_TYPE_UNREAD_ERROR"] = 34005] = "CONVER_TYPE_UNREAD_ERROR"; ErrorCode[ErrorCode["CONVER_ID_TYPE_UNREAD_ERROR"] = 34006] = "CONVER_ID_TYPE_UNREAD_ERROR"; ErrorCode[ErrorCode["CONVER_CLEAR_ERROR"] = 34007] = "CONVER_CLEAR_ERROR"; ErrorCode[ErrorCode["EXPANSION_LIMIT_EXCEET"] = 34010] = "EXPANSION_LIMIT_EXCEET"; ErrorCode[ErrorCode["MESSAGE_KV_NOT_SUPPORT"] = 34008] = "MESSAGE_KV_NOT_SUPPORT"; ErrorCode[ErrorCode["CLEAR_HIS_TIME_ERROR"] = 34011] = "CLEAR_HIS_TIME_ERROR"; ErrorCode[ErrorCode["CONVER_GET_ERROR"] = 34009] = "CONVER_GET_ERROR"; ErrorCode[ErrorCode["GROUP_SYNC_ERROR"] = 35001] = "GROUP_SYNC_ERROR"; ErrorCode[ErrorCode["GROUP_MATCH_ERROR"] = 35002] = "GROUP_MATCH_ERROR"; ErrorCode[ErrorCode["CHATROOM_ID_ISNULL"] = 36001] = "CHATROOM_ID_ISNULL"; ErrorCode[ErrorCode["CHARTOOM_JOIN_ERROR"] = 36002] = "CHARTOOM_JOIN_ERROR"; ErrorCode[ErrorCode["CHATROOM_HISMESSAGE_ERROR"] = 36003] = "CHATROOM_HISMESSAGE_ERROR"; ErrorCode[ErrorCode["CHATROOM_KV_NOT_FOUND"] = 36004] = "CHATROOM_KV_NOT_FOUND"; ErrorCode[ErrorCode["BLACK_ADD_ERROR"] = 37001] = "BLACK_ADD_ERROR"; ErrorCode[ErrorCode["BLACK_GETSTATUS_ERROR"] = 37002] = "BLACK_GETSTATUS_ERROR"; ErrorCode[ErrorCode["BLACK_REMOVE_ERROR"] = 37003] = "BLACK_REMOVE_ERROR"; ErrorCode[ErrorCode["DRAF_GET_ERROR"] = 38001] = "DRAF_GET_ERROR"; ErrorCode[ErrorCode["DRAF_SAVE_ERROR"] = 38002] = "DRAF_SAVE_ERROR"; ErrorCode[ErrorCode["DRAF_REMOVE_ERROR"] = 38003] = "DRAF_REMOVE_ERROR"; ErrorCode[ErrorCode["SUBSCRIBE_ERROR"] = 39001] = "SUBSCRIBE_ERROR"; ErrorCode[ErrorCode["QNTKN_FILETYPE_ERROR"] = 41001] = "QNTKN_FILETYPE_ERROR"; ErrorCode[ErrorCode["QNTKN_GET_ERROR"] = 41002] = "QNTKN_GET_ERROR"; ErrorCode[ErrorCode["COOKIE_ENABLE"] = 51001] = "COOKIE_ENABLE"; ErrorCode[ErrorCode["GET_MESSAGE_BY_ID_ERROR"] = 61001] = "GET_MESSAGE_BY_ID_ERROR"; ErrorCode[ErrorCode["HAVNODEVICEID"] = 24001] = "HAVNODEVICEID"; ErrorCode[ErrorCode["DEVICEIDISHAVE"] = 24002] = "DEVICEIDISHAVE"; ErrorCode[ErrorCode["FEILD"] = 24009] = "FEILD"; ErrorCode[ErrorCode["VOIPISNULL"] = 24013] = "VOIPISNULL"; ErrorCode[ErrorCode["NOENGINETYPE"] = 24010] = "NOENGINETYPE"; ErrorCode[ErrorCode["NULLCHANNELNAME"] = 24011] = "NULLCHANNELNAME"; ErrorCode[ErrorCode["VOIPDYANMICERROR"] = 24012] = "VOIPDYANMICERROR"; ErrorCode[ErrorCode["NOVOIP"] = 24014] = "NOVOIP"; ErrorCode[ErrorCode["INTERNALERRROR"] = 24015] = "INTERNALERRROR"; ErrorCode[ErrorCode["VOIPCLOSE"] = 24016] = "VOIPCLOSE"; ErrorCode[ErrorCode["CLOSE_BEFORE_OPEN"] = 51001] = "CLOSE_BEFORE_OPEN"; ErrorCode[ErrorCode["ALREADY_IN_USE"] = 51002] = "ALREADY_IN_USE"; ErrorCode[ErrorCode["INVALID_CHANNEL_NAME"] = 51003] = "INVALID_CHANNEL_NAME"; ErrorCode[ErrorCode["VIDEO_CONTAINER_IS_NULL"] = 51004] = "VIDEO_CONTAINER_IS_NULL"; ErrorCode[ErrorCode["DELETE_MESSAGE_ID_IS_NULL"] = 61001] = "DELETE_MESSAGE_ID_IS_NULL"; ErrorCode[ErrorCode["CANCEL"] = 1] = "CANCEL"; ErrorCode[ErrorCode["REJECT"] = 2] = "REJECT"; ErrorCode[ErrorCode["HANGUP"] = 3] = "HANGUP"; ErrorCode[ErrorCode["BUSYLINE"] = 4] = "BUSYLINE"; ErrorCode[ErrorCode["NO_RESPONSE"] = 5] = "NO_RESPONSE"; ErrorCode[ErrorCode["ENGINE_UN_SUPPORTED"] = 6] = "ENGINE_UN_SUPPORTED"; ErrorCode[ErrorCode["NETWORK_ERROR"] = 7] = "NETWORK_ERROR"; ErrorCode[ErrorCode["REMOTE_CANCEL"] = 11] = "REMOTE_CANCEL"; ErrorCode[ErrorCode["REMOTE_REJECT"] = 12] = "REMOTE_REJECT"; ErrorCode[ErrorCode["REMOTE_HANGUP"] = 13] = "REMOTE_HANGUP"; ErrorCode[ErrorCode["REMOTE_BUSYLINE"] = 14] = "REMOTE_BUSYLINE"; ErrorCode[ErrorCode["REMOTE_NO_RESPONSE"] = 15] = "REMOTE_NO_RESPONSE"; ErrorCode[ErrorCode["REMOTE_ENGINE_UN_SUPPORTED"] = 16] = "REMOTE_ENGINE_UN_SUPPORTED"; ErrorCode[ErrorCode["REMOTE_NETWORK_ERROR"] = 17] = "REMOTE_NETWORK_ERROR"; ErrorCode[ErrorCode["VOIP_NOT_AVALIABLE"] = 18] = "VOIP_NOT_AVALIABLE"; })(ErrorCode || (ErrorCode = {})); var ErrorCode$1 = ErrorCode; var timerSetTimeout = function timerSetTimeout(fun, itv) { _newArrowCheck(this, _this); return setTimeout(fun, itv); }.bind(undefined); var int64ToTimestamp = function int64ToTimestamp(obj) { _newArrowCheck(this, _this); if (!isObject(obj) || obj.low === undefined || obj.high === undefined) { return obj; } var low = obj.low; if (low < 0) { low += 0xffffffff + 1; } low = low.toString(16); var timestamp = parseInt(obj.high.toString(16) + '00000000'.replace(new RegExp('0{' + low.length + '}$'), low), 16); return timestamp; }.bind(undefined); var batchInt64ToTimestamp = function batchInt64ToTimestamp(data) { _newArrowCheck(this, _this); for (var _key8 in data) { if (isObject(data[_key8])) { data[_key8] = int64ToTimestamp(data[_key8]); } } return data; }.bind(undefined); var formatDate = function formatDate(seperator) { _newArrowCheck(this, _this); seperator = seperator || '-'; var date = new Date(); var year = date.getFullYear(); var month = date.getMonth() + 1; var day = date.getDate(); return "".concat(year).concat(seperator).concat(month).concat(seperator).concat(day); }.bind(undefined); var MentionedType; (function (MentionedType) { MentionedType[MentionedType["ALL"] = 1] = "ALL"; MentionedType[MentionedType["SINGAL"] = 2] = "SINGAL"; })(MentionedType || (MentionedType = {})); var MentionedType$1 = MentionedType; var MessageType; (function (MessageType) { MessageType["TextMessage"] = "RC:TxtMsg"; MessageType["VOICE"] = "RC:VcMsg"; MessageType["HQ_VOICE"] = "RC:HQVCMsg"; MessageType["IMAGE"] = "RC:ImgMsg"; MessageType["GIF"] = "RC:GIFMsg"; MessageType["RICH_CONTENT"] = "RC:ImgTextMsg"; MessageType["LOCATION"] = "RC:LBSMsg"; MessageType["FILE"] = "RC:FileMsg"; MessageType["SIGHT"] = "RC:SightMsg"; MessageType["COMBINE"] = "RC:CombineMsg"; MessageType["CHRM_KV_NOTIFY"] = "RC:chrmKVNotiMsg"; MessageType["LOG_COMMAND"] = "RC:LogCmdMsg"; MessageType["EXPANSION_NOTIFY"] = "RC:MsgExMsg"; MessageType["REFERENCE"] = "RC:ReferenceMsg"; MessageType["RECALL"] = "RC:RcCmd"; MessageType["READ_RECEIPT"] = "RC:ReadNtf"; MessageType["READ_RECEIPT_REQUEST"] = "RC:RRReqMsg"; MessageType["READ_RECEIPT_RESPONSE"] = "RC:RRRspMsg"; MessageType["SYNC_READ_STATUS"] = "RC:SRSMsg"; })(MessageType || (MessageType = {})); var MessageType$1 = MessageType; var NotificationStatus; (function (NotificationStatus) { NotificationStatus[NotificationStatus["OPEN"] = 1] = "OPEN"; NotificationStatus[NotificationStatus["CLOSE"] = 2] = "CLOSE"; })(NotificationStatus || (NotificationStatus = {})); var NotificationStatus$1 = NotificationStatus; var PublishTopic = { PRIVATE: 'ppMsgP', GROUP: 'pgMsgP', CHATROOM: 'chatMsg', CUSTOMER_SERVICE: 'pcMsgP', RECALL: 'recallMsg', RTC_MSG: 'prMsgS', NOTIFY_PULL_MSG: 's_ntf', RECEIVE_MSG: 's_msg', SYNC_STATUS: 's_stat', SERVER_NOTIFY: 's_cmd', SETTING_NOTIFY: 's_us' }; var PublishStatusTopic = { PRIVATE: 'ppMsgS', GROUP: 'pgMsgS', CHATROOM: 'chatMsgS' }; var QueryTopic = { GET_SYNC_TIME: 'qrySessionsAtt', PULL_MSG: 'pullMsg', GET_CONVERSATION_LIST: 'qrySessions', REMOVE_CONVERSATION_LIST: 'delSessions', DELETE_MESSAGES: 'delMsg', CLEAR_UNREAD_COUNT: 'updRRTime', PULL_USER_SETTING: 'pullUS', PULL_CHRM_MSG: 'chrmPull', JOIN_CHATROOM: 'joinChrm', JOIN_EXIST_CHATROOM: 'joinChrmR', QUIT_CHATROOM: 'exitChrm', GET_CHATROOM_INFO: 'queryChrmI', UPDATE_CHATROOM_KV: 'setKV', DELETE_CHATROOM_KV: 'delKV', PULL_CHATROOM_KV: 'pullKV', GET_OLD_CONVERSATION_LIST: 'qryRelationR', REMOVE_OLD_CONVERSATION: 'delRelation', GET_CONVERSATION_STATUS: 'pullSeAtts', SET_CONVERSATION_STATUS: 'setSeAtt', GET_UPLOAD_FILE_TOKEN: 'qnTkn', GET_UPLOAD_FILE_URL: 'qnUrl', CLEAR_MESSAGES: { PRIVATE: 'cleanPMsg', GROUP: 'cleanGMsg', CUSTOMER_SERVICE: 'cleanCMsg', SYSTEM: 'cleanSMsg' }, JOIN_RTC_ROOM: 'rtcRJoin_data', QUIT_RTC_ROOM: 'rtcRExit', PING_RTC: 'rtcPing', SET_RTC_DATA: 'rtcSetData', USER_SET_RTC_DATA: 'userSetData', GET_RTC_DATA: 'rtcQryData', DEL_RTC_DATA: 'rtcDelData', SET_RTC_OUT_DATA: 'rtcSetOutData', GET_RTC_OUT_DATA: 'rtcQryUserOutData', GET_RTC_TOKEN: 'rtcToken', SET_RTC_STATE: 'rtcUserState', GET_RTC_ROOM_INFO: 'rtcRInfo', GET_RTC_USER_INFO_LIST: 'rtcUData', SET_RTC_USER_INFO: 'rtcUPut', DEL_RTC_USER_INFO: 'rtcUDel', GET_RTC_USER_LIST: 'rtcUList' }; var QueryHistoryTopic = { PRIVATE: 'qryPMsg', GROUP: 'qryGMsg', CHATROOM: 'qryCHMsg', CUSTOMER_SERVICE: 'qryCMsg', SYSTEM: 'qrySMsg' }; var PublishTopicToConversationType = (_PublishTopicToConver = {}, _defineProperty(_PublishTopicToConver, PublishTopic.PRIVATE, ConversationType$1.PRIVATE), _defineProperty(_PublishTopicToConver, PublishTopic.GROUP, ConversationType$1.GROUP), _defineProperty(_PublishTopicToConver, PublishTopic.CHATROOM, ConversationType$1.CHATROOM), _defineProperty(_PublishTopicToConver, PublishTopic.CUSTOMER_SERVICE, ConversationType$1.CUSTOMER_SERVICE), _PublishTopicToConver); var ConversationTypeToQueryHistoryTopic = (_ConversationTypeToQu = {}, _defineProperty(_ConversationTypeToQu, ConversationType$1.PRIVATE, QueryHistoryTopic.PRIVATE), _defineProperty(_ConversationTypeToQu, ConversationType$1.GROUP, QueryHistoryTopic.GROUP), _defineProperty(_ConversationTypeToQu, ConversationType$1.CHATROOM, QueryHistoryTopic.CHATROOM), _defineProperty(_ConversationTypeToQu, ConversationType$1.CUSTOMER_SERVICE, QueryHistoryTopic.CUSTOMER_SERVICE), _defineProperty(_ConversationTypeToQu, ConversationType$1.SYSTEM, QueryHistoryTopic.SYSTEM), _ConversationTypeToQu); var ConversationTypeToClearMessageTopic = (_ConversationTypeToCl = {}, _defineProperty(_ConversationTypeToCl, ConversationType$1.PRIVATE, QueryTopic.CLEAR_MESSAGES.PRIVATE), _defineProperty(_ConversationTypeToCl, ConversationType$1.GROUP, QueryTopic.CLEAR_MESSAGES.GROUP), _defineProperty(_ConversationTypeToCl, ConversationType$1.CUSTOMER_SERVICE, QueryTopic.CLEAR_MESSAGES.CUSTOMER_SERVICE), _defineProperty(_ConversationTypeToCl, ConversationType$1.SYSTEM, QueryTopic.CLEAR_MESSAGES.SYSTEM), _ConversationTypeToCl); var ConversationStatusConfig = { ENABLED: '1', DISABLED: '0' }; var ConversationStatusType = { DO_NOT_DISTURB: 1, TOP: 2 }; var MessageDirection; (function (MessageDirection) { MessageDirection[MessageDirection["SEND"] = 1] = "SEND"; MessageDirection[MessageDirection["RECEIVE"] = 2] = "RECEIVE"; })(MessageDirection || (MessageDirection = {})); var MessageDirection$1 = MessageDirection; var DataCodec = function () { function DataCodec(connectType) { _classCallCheck(this, DataCodec); this._codec = connectType === 'websocket' ? Codec$1 : Codec; this._connectType = connectType; } _createClass(DataCodec, [{ key: "decodeByPBName", value: function decodeByPBName(data, pbName, option) { var _formatEventMap; var self = this; var formatEventMap = (_formatEventMap = {}, _defineProperty(_formatEventMap, PBName.DownStreamMessages, self._formatSyncMessages), _defineProperty(_formatEventMap, PBName.DownStreamMessage, self._formatReceivedMessage), _defineProperty(_formatEventMap, PBName.UpStreamMessage, self._formatSentMessage), _defineProperty(_formatEventMap, PBName.HistoryMsgOuput, self._formatHistoryMessages), _defineProperty(_formatEventMap, PBName.RelationsOutput, self._formatConversationList), _defineProperty(_formatEventMap, PBName.QueryChatRoomInfoOutput, self._formatChatRoomInfos), _defineProperty(_formatEventMap, PBName.RtcUserListOutput, self._formatRTCUserList), _defineProperty(_formatEventMap, PBName.RtcQryOutput, self._formatRTCData), _defineProperty(_formatEventMap, PBName.ChrmKVOutput, self._formatChatRoomKVList), _defineProperty(_formatEventMap, PBName.PullUserSettingOutput, self._formatUserSetting), _defineProperty(_formatEventMap, PBName.SessionStates, self._formatConversationStatus), _formatEventMap); var decodedData = data; var formatEvent = formatEventMap[pbName]; try { var hasData = data.length > 0; decodedData = hasData && self._codec[pbName].decode(data); if (isObject(decodedData)) { decodedData = batchInt64ToTimestamp(decodedData); } if (isFunction(formatEvent)) { decodedData = formatEvent.call(this, decodedData, option); } } catch (e) { logger.error('PB parse error\n', e); } return decodedData; } }, { key: "_readBytes", value: function _readBytes(content) { var offset = content.offset, buffer = content.buffer, limit = content.limit; if (offset) { try { var _content = isArrayBuffer(buffer) ? new Uint8Array(buffer) : buffer; return BinaryHelper.readUTF(_content.subarray(offset, limit)); } catch (e) { logger.info('readBytes error\n', e); } } return content; } }, { key: "_formatBytes", value: function _formatBytes(content) { var formatRes = this._readBytes(content); try { formatRes = JSON.parse(formatRes); } catch (e) { logger.info('formatBytes error\n', e); } return formatRes || content; } }, { key: "_formatSyncMessages", value: function _formatSyncMessages(data, option) { var _this12 = this; option = option || {}; var self = this; var list = data.list, syncTime = data.syncTime, finished = data.finished; if (isUndefined(finished) || finished === null) { data.finished = true; } data.syncTime = int64ToTimestamp(syncTime); data.list = map(list, function (msgData) { _newArrowCheck(this, _this12); var message = self._formatReceivedMessage(msgData, option); return message; }.bind(this)); return data; } }, { key: "_formatReceivedMessage", value: function _formatReceivedMessage(data, option) { option = option || {}; var self = this; var _option = option, currentUserId = _option.currentUserId, connectedTime = _option.connectedTime; var content = data.content, fromUserId = data.fromUserId, type = data.type, groupId = data.groupId, status = data.status, dataTime = data.dataTime, messageType = data.classname, messageUId = data.msgId, extraContent = data.extraContent; var direction = data.direction || MessageDirection$1.RECEIVE; var isSelfSend = direction === MessageDirection$1.SEND; var _getMessageOptionBySt = getMessageOptionByStatus(status), isPersited = _getMessageOptionBySt.isPersited, isCounted = _getMessageOptionBySt.isCounted, isMentioned = _getMessageOptionBySt.isMentioned, disableNotification = _getMessageOptionBySt.disableNotification, receivedStatus = _getMessageOptionBySt.receivedStatus, canIncludeExpansion = _getMessageOptionBySt.canIncludeExpansion; var targetId = type === ConversationType$1.GROUP || type === ConversationType$1.CHATROOM ? groupId : fromUserId; var senderUserId = isSelfSend ? currentUserId : fromUserId; var sentTime = int64ToTimestamp(dataTime); var isOffLineMessage = sentTime < connectedTime; var isChatRoomMsg = type === ConversationType$1.CHATROOM; var utfContent = self._formatBytes(content); var messageDirection = isSelfSend ? MessageDirection$1.SEND : MessageDirection$1.RECEIVE; if (isChatRoomMsg && fromUserId === currentUserId) { messageDirection = MessageDirection$1.SEND; } var expansion; if (extraContent) { expansion = {}; expansion = formatExtraContent(extraContent); } return { conversationType: type, targetId: targetId, senderUserId: senderUserId, messageType: messageType, messageUId: messageUId, isPersited: isPersited, isCounted: isCounted, isMentioned: isMentioned, sentTime: sentTime, isOffLineMessage: isOffLineMessage, messageDirection: messageDirection, receivedTime: DelayTimer.getTime(), disableNotification: disableNotification, receivedStatus: receivedStatus, canIncludeExpansion: canIncludeExpansion, content: utfContent, expansion: expansion }; } }, { key: "_formatSentMessage", value: function _formatSentMessage(data, option) { var self = this; var content = data.content, messageType = data.classname, sessionId = data.sessionId, messageUId = data.msgId, extraContent = data.extraContent; var signal = option.signal, currentUserId = option.currentUserId; var date = signal.date, topic = signal.topic, targetId = signal.targetId; var _getUpMessageOptionBy = getUpMessageOptionBySessionId(sessionId), isPersited = _getUpMessageOptionBy.isPersited, isCounted = _getUpMessageOptionBy.isCounted, disableNotification = _getUpMessageOptionBy.disableNotification, canIncludeExpansion = _getUpMessageOptionBy.canIncludeExpansion; var type = PublishTopicToConversationType[topic] || ConversationType$1.PRIVATE; var isStatusMessage = isInObject(PublishStatusTopic, topic); var expansion; if (extraContent) { expansion = {}; expansion = formatExtraContent(extraContent); } return { conversationType: type, targetId: targetId, messageType: messageType, messageUId: messageUId, isPersited: isPersited, isCounted: isCounted, isStatusMessage: isStatusMessage, senderUserId: currentUserId, content: self._formatBytes(content), sentTime: date * 1000, receivedTime: DelayTimer.getTime(), messageDirection: MessageDirection$1.SEND, isOffLineMessage: false, disableNotification: disableNotification, canIncludeExpansion: canIncludeExpansion, expansion: expansion }; } }, { key: "_formatHistoryMessages", value: function _formatHistoryMessages(data, option) { var _this13 = this; var conversation = option.conversation || {}; var msgList = data.list, hasMsg = data.hasMsg; var targetId = conversation.targetId; var syncTime = int64ToTimestamp(data.syncTime); var list = []; forEach(msgList, function (msgData) { _newArrowCheck(this, _this13); var msg = this._formatReceivedMessage(msgData, option); msg.targetId = targetId; list.push(msg); }.bind(this), { isReverse: true }); return { syncTime: syncTime, list: list, hasMore: !!hasMsg }; } }, { key: "_formatConversationList", value: function _formatConversationList(serverData, option) { var _this14 = this; var self = this; var conversationList = serverData.info; var afterDecode = option.afterDecode || function () {}; conversationList = map(conversationList, function (serverConversation) { _newArrowCheck(this, _this14); var msg = serverConversation.msg, userId = serverConversation.userId, type = serverConversation.type, unreadCount = serverConversation.unreadCount; var latestMessage = self._formatReceivedMessage(msg, option); latestMessage.targetId = userId; var conversation = { targetId: userId, conversationType: type, unreadMessageCount: unreadCount, latestMessage: latestMessage }; return afterDecode(conversation) || conversation; }.bind(this)); return conversationList || []; } }, { key: "_formatChatRoomInfos", value: function _formatChatRoomInfos(data) { var _this15 = this; var userTotalNums = data.userTotalNums, userInfos = data.userInfos; var chrmInfos = map(userInfos, function (user) { _newArrowCheck(this, _this15); var id = user.id, time = user.time; var timestamp = int64ToTimestamp(time); return { id: id, time: timestamp }; }.bind(this)); return { userCount: userTotalNums, userInfos: chrmInfos }; } }, { key: "_formatChatRoomKVList", value: function _formatChatRoomKVList(data) { var _this16 = this; var kvEntries = data.entries, isFullUpdate = data.bFullUpdate, syncTime = data.syncTime; kvEntries = kvEntries || []; kvEntries = map(kvEntries, function (kv) { _newArrowCheck(this, _this16); var key = kv.key, value = kv.value, status = kv.status, timestamp = kv.timestamp, uid = kv.uid; var _getChatRoomKVByStatu = getChatRoomKVByStatus(status), isAutoDelete = _getChatRoomKVByStatu.isAutoDelete, isOverwrite = _getChatRoomKVByStatu.isOverwrite, type = _getChatRoomKVByStatu.type; return { key: key, value: value, isAutoDelete: isAutoDelete, isOverwrite: isOverwrite, type: type, userId: uid, timestamp: int64ToTimestamp(timestamp) }; }.bind(this)); return { kvEntries: kvEntries, isFullUpdate: isFullUpdate, syncTime: syncTime }; } }, { key: "_formatUserSetting", value: function _formatUserSetting(data) { var _this17 = this; var items = data.items, version = data.version; var settings = {}; forEach(items || [], function (setting) { _newArrowCheck(this, _this17); var key = setting.key, version = setting.version, value = setting.value; setting.version = int64ToTimestamp(version); setting.value = this._readBytes(value); settings[key] = setting; }.bind(this)); return { settings: settings, version: version }; } }, { key: "_formatConversationStatus", value: function _formatConversationStatus(data) { var _this18 = this; var stateList = data.state; var statusList = []; forEach(stateList, function (session) { var _this19 = this; _newArrowCheck(this, _this18); var type = session.type, targetId = session.channelId, updatedTime = session.time, stateItem = session.stateItem; var notificationStatus = NotificationStatus$1.CLOSE; var isTop = false; forEach(stateItem, function (item) { _newArrowCheck(this, _this19); var sessionStateType = item.sessionStateType, value = item.value; switch (sessionStateType) { case ConversationStatusType.DO_NOT_DISTURB: notificationStatus = value === ConversationStatusConfig.ENABLED ? NotificationStatus$1.OPEN : NotificationStatus$1.CLOSE; break; case ConversationStatusType.TOP: isTop = value === ConversationStatusConfig.ENABLED; break; } }.bind(this)); statusList.push({ type: type, targetId: targetId, notificationStatus: notificationStatus, isTop: isTop, updatedTime: int64ToTimestamp(updatedTime) }); }.bind(this)); return statusList; } }, { key: "_formatRTCUserList", value: function _formatRTCUserList(rtcInfos) { var _this20 = this; var list = rtcInfos.list, token = rtcInfos.token, sessionId = rtcInfos.sessionId; var users = {}; forEach(list, function (item) { var _this21 = this; _newArrowCheck(this, _this20); var userId = item.userId, userData = item.userData; var tmpData = {}; forEach(userData, function (data) { _newArrowCheck(this, _this21); var key = data.key, value = data.value; tmpData[key] = value; }.bind(this)); users[userId] = tmpData; }.bind(this)); return { users: users, token: token, sessionId: sessionId }; } }, { key: "_formatRTCData", value: function _formatRTCData(data) { var _this22 = this; var list = data.outInfo; var props = {}; forEach(list, function (item) { _newArrowCheck(this, _this22); props[item.key] = item.value; }.bind(this)); return props; } }, { key: "_formatRTCRoomInfo", value: function _formatRTCRoomInfo(data) { var _this23 = this; var id = data.roomId, total = data.userCount, roomData = data.roomData; var room = { id: id, total: total }; forEach(roomData, function (data) { _newArrowCheck(this, _this23); room[data.key] = data.value; }.bind(this)); return room; } }, { key: "encodeServerConfParams", value: function encodeServerConfParams() { var modules = this._codec.getModule(PBName.SessionsAttQryInput); modules.setNothing(1); return modules.getArrayData(); } }, { key: "_getUpMsgModule", value: function _getUpMsgModule(conversation, option) { var _this24 = this; var type = conversation.type; var messageType = option.messageType, isMentioned = option.isMentioned, mentionedType = option.mentionedType, mentionedUserIdList = option.mentionedUserIdList, content = option.content, pushContent = option.pushContent, pushData = option.pushData, directionalUserIdList = option.directionalUserIdList, isFilerWhiteBlacklist = option.isFilerWhiteBlacklist, isVoipPush = option.isVoipPush, canIncludeExpansion = option.canIncludeExpansion, expansion = option.expansion; var isGroupType = type === ConversationType$1.GROUP; var modules = this._codec.getModule(PBName.UpStreamMessage); var sessionId = getSessionId(option); var flag = 0; modules.setSessionId(sessionId); if (isGroupType && isMentioned && content) { content.mentionedInfo = { userIdList: mentionedUserIdList, type: mentionedType || MentionedType$1.ALL }; } pushContent && modules.setPushText(pushContent); pushData && modules.setAppData(pushData); directionalUserIdList && modules.setUserId(directionalUserIdList); flag |= isVoipPush ? 0x01 : 0; flag |= isFilerWhiteBlacklist ? 0x02 : 0; modules.setConfigFlag(flag); modules.setClassname(messageType); modules.setContent(JSON.stringify(content)); if (canIncludeExpansion && expansion) { var extraContent = {}; forEach(expansion, function (val, key) { _newArrowCheck(this, _this24); extraContent[key] = { v: val }; }.bind(this)); modules.setExtraContent(JSON.stringify(extraContent)); } return modules; } }, { key: "encodeUpMsg", value: function encodeUpMsg(conversation, option) { var modules = this._getUpMsgModule(conversation, option); return modules.getArrayData(); } }, { key: "encodeSyncMsg", value: function encodeSyncMsg(syncMsgArgs) { var sendboxTime = syncMsgArgs.sendboxTime, inboxTime = syncMsgArgs.inboxTime; var modules = this._codec.getModule(PBName.SyncRequestMsg); modules.setIspolling(false); modules.setIsPullSend(true); modules.setSendBoxSyncTime(sendboxTime); modules.setSyncTime(inboxTime); return modules.getArrayData(); } }, { key: "encodeChrmSyncMsg", value: function encodeChrmSyncMsg(time, count) { time = time || 0; count = count || 0; var modules = this._codec.getModule(PBName.ChrmPullMsg); modules.setCount(count); modules.setSyncTime(time); return modules.getArrayData(); } }, { key: "encodeGetHistoryMsg", value: function encodeGetHistoryMsg(targetId, option) { var count = option.count, order = option.order, timestamp = option.timestamp; var modules = this._codec.getModule(PBName.HistoryMsgInput); modules.setTargetId(targetId); modules.setTime(timestamp); modules.setCount(count); modules.setOrder(order); return modules.getArrayData(); } }, { key: "encodeGetConversationList", value: function encodeGetConversationList(option) { option = option || {}; var _option2 = option, count = _option2.count, startTime = _option2.startTime; var modules = this._codec.getModule(PBName.RelationQryInput); modules.setType(1); modules.setCount(count); modules.setStartTime(startTime); return modules.getArrayData(); } }, { key: "encodeOldConversationList", value: function encodeOldConversationList(option) { option = option || {}; var _option3 = option, count = _option3.count, type = _option3.type, startTime = _option3.startTime, order = _option3.order; count = count || 0; startTime = startTime || 0; order = order || 0; var modules = this._codec.getModule(PBName.RelationQryInput); modules.setType(type); modules.setCount(count); modules.setStartTime(startTime); modules.setOrder(order); return modules.getArrayData(); } }, { key: "encodeRemoveConversationList", value: function encodeRemoveConversationList(conversationList) { var _this25 = this; var modules = this._codec.getModule(PBName.DeleteSessionsInput); var sessions = []; forEach(conversationList, function (conversation) { _newArrowCheck(this, _this25); var type = conversation.type, targetId = conversation.targetId; var session = this._codec.getModule(PBName.SessionInfo); session.setType(type); session.setChannelId(targetId); sessions.push(session); }.bind(this)); modules.setSessions(sessions); return modules.getArrayData(); } }, { key: "encodeDeleteMessages", value: function encodeDeleteMessages(conversationType, targetId, list) { var _this26 = this; var modules = this._codec.getModule(PBName.DeleteMsgInput); var encodeMsgs = []; forEach(list, function (message) { _newArrowCheck(this, _this26); encodeMsgs.push({ msgId: message.messageUId, msgDataTime: message.sentTime, direct: message.messageDirection }); }.bind(this)); modules.setType(conversationType); modules.setConversationId(targetId); modules.setMsgs(encodeMsgs); return modules.getArrayData(); } }, { key: "encodeClearMessages", value: function encodeClearMessages(targetId, timestamp) { var modules = this._codec.getModule(PBName.CleanHisMsgInput); timestamp = timestamp || new Date().getTime(); modules.setDataTime(timestamp); modules.setTargetId(targetId); return modules.getArrayData(); } }, { key: "encodeClearUnreadCount", value: function encodeClearUnreadCount(conversation, option) { var type = conversation.type, targetId = conversation.targetId; var timestamp = option.timestamp; var modules = this._codec.getModule(PBName.SessionMsgReadInput); timestamp = timestamp || +new Date(); modules.setType(type); modules.setChannelId(targetId); modules.setMsgTime(timestamp); return modules.getArrayData(); } }, { key: "encodeJoinOrQuitChatRoom", value: function encodeJoinOrQuitChatRoom() { var modules = this._codec.getModule(PBName.ChrmInput); modules.setNothing(1); return modules.getArrayData(); } }, { key: "encodeGetChatRoomInfo", value: function encodeGetChatRoomInfo(count, order) { var modules = this._codec.getModule(PBName.QueryChatRoomInfoInput); modules.setCount(count); modules.setOrder(order); return modules.getArrayData(); } }, { key: "encodeGetFileToken", value: function encodeGetFileToken(fileType, fileName) { var modules = this._codec.getModule(PBName.GetQNupTokenInput); modules.setType(fileType); modules.setKey(fileName); return modules.getArrayData(); } }, { key: "encodeGetFileUrl", value: function encodeGetFileUrl(inputPBName, fileType, fileName, originName) { var modules = this._codec.getModule(inputPBName); modules.setType(fileType); modules.setKey(fileName); if (originName) { modules.setFileName(originName); } return modules.getArrayData(); } }, { key: "encodeModifyChatRoomKV", value: function encodeModifyChatRoomKV(chrmId, entry, currentUserId) { var isComet = this._connectType === 'comet'; var modules = this._codec.getModule(PBName.SetChrmKV); var key = entry.key, value = entry.value, extra = entry.notificationExtra, isSendNotification = entry.isSendNotification, type = entry.type; var action = type || ChatroomEntryType$1.UPDATE; var status = getChatRoomKVOptStatus(entry, action); var serverEntry = { key: key, value: value || '', uid: currentUserId }; if (!isUndefined(status)) { serverEntry.status = status; } modules.setEntry(serverEntry); if (isSendNotification) { var conversation = { type: ConversationType$1.CHATROOM, targetId: chrmId }; var msgContent = { key: key, value: value, extra: extra, type: action }; var msgModule = this._getUpMsgModule(conversation, { messageType: MessageType$1.CHRM_KV_NOTIFY, content: msgContent, isPersited: false, isCounted: false }); isComet ? modules.setNotification(msgModule.getArrayData()) : modules.setNotification(msgModule); modules.setBNotify(true); modules.setType(ConversationType$1.CHATROOM); } return modules.getArrayData(); } }, { key: "encodePullChatRoomKV", value: function encodePullChatRoomKV(time) { var modules = this._codec.getModule(PBName.QueryChrmKV); modules.setTimestamp(time); return modules.getArrayData(); } }, { key: "encodePullUserSetting", value: function encodePullUserSetting(version) { var modules = this._codec.getModule(PBName.PullUserSettingInput); modules.setVersion(version); return modules.getArrayData(); } }, { key: "encodeGetConversationStatus", value: function encodeGetConversationStatus(time) { var modules = this._codec.getModule(PBName.SessionReq); modules.setTime(time); return modules.getArrayData(); } }, { key: "encodeSetConversationStatus", value: function encodeSetConversationStatus(statusList) { var _this27 = this; var isComet = this._connectType === 'comet'; var modules = this._codec.getModule(PBName.SessionStateModifyReq); var currentTime = DelayTimer.getTime(); var stateModuleList = []; forEach(statusList, function (status) { var _this28 = this; _newArrowCheck(this, _this27); var stateModules = this._codec.getModule(PBName.SessionState); var type = status.conversationType, targetId = status.targetId, notificationStatus = status.notificationStatus, isTop = status.isTop; var stateItemModuleList = []; stateModules.setType(type); stateModules.setChannelId(targetId); stateModules.setTime(currentTime); var isNotDisturb = notificationStatus === NotificationStatus$1.OPEN; var TypeToVal = {}; if (!isUndefined(notificationStatus)) { TypeToVal[ConversationStatusType.DO_NOT_DISTURB] = isNotDisturb; } if (!isUndefined(isTop)) { TypeToVal[ConversationStatusType.TOP] = isTop; } forEach(TypeToVal, function (val, type) { _newArrowCheck(this, _this28); if (!isUndefined(val)) { var stateItemModules = this._codec.getModule(PBName.SessionStateItem); val = val ? ConversationStatusConfig.ENABLED : ConversationStatusConfig.DISABLED; stateItemModules.setSessionStateType(Number(type)); stateItemModules.setValue(val); var stateItemModulesData = isComet ? stateItemModules.getArrayData() : stateItemModules; stateItemModuleList.push(stateItemModulesData); } }.bind(this)); stateModules.setStateItem(stateItemModuleList); var stateModulesData = isComet ? stateModules.getArrayData() : stateModules; stateModuleList.push(stateModulesData); }.bind(this)); modules.setVersion(currentTime); modules.setState(stateModuleList); return modules.getArrayData(); } }, { key: "encodeJoinRTCRoom", value: function encodeJoinRTCRoom(mode, broadcastType) { var modules = this._codec.getModule(PBName.RtcInput); mode = mode || 0; modules.setRoomType(mode); isUndefined(broadcastType) || modules.setBroadcastType(broadcastType); return modules.getArrayData(); } }, { key: "encodeQuitRTCRoom", value: function encodeQuitRTCRoom() { return this._codec.getModule(PBName.SetUserStatusInput).getArrayData(); } }, { key: "encodeSetRTCData", value: function encodeSetRTCData(key, value, isInner, apiType, message) { var modules = this._codec.getModule(PBName.RtcSetDataInput); modules.setInterior(isInner); modules.setTarget(apiType); modules.setKey(key); modules.setValue(value); message = message || {}; var _message = message, name = _message.name, content = _message.content; !isUndefined(name) && modules.setObjectName(name); if (!isUndefined(content)) { if (isObject(content)) { content = JSON.stringify(content); } modules.setContent(content); } return modules.getArrayData(); } }, { key: "encodeUserSetRTCData", value: function encodeUserSetRTCData(message, valueInfo, objectName) { var modules = this._codec.getModule(PBName.RtcUserSetDataInput); modules.setObjectName(objectName); var val = this._codec.getModule(PBName.RtcValueInfo); val.setKey(message.name); val.setValue(message.content); modules.setContent(val); val = this._codec.getModule(PBName.RtcValueInfo); val.setKey('uris'); val.setValue(valueInfo); modules.setValueInfo(val); return modules.getArrayData(); } }, { key: "encodeGetRTCData", value: function encodeGetRTCData(keys, isInner, apiType) { var modules = this._codec.getModule(PBName.RtcDataInput); modules.setInterior(isInner); modules.setTarget(apiType); modules.setKey(keys); return modules.getArrayData(); } }, { key: "encodeRemoveRTCData", value: function encodeRemoveRTCData(keys, isInner, apiType, message) { var modules = this._codec.getModule(PBName.RtcDataInput); modules.setInterior(isInner); modules.setTarget(apiType); modules.setKey(keys); message = message || {}; var _message2 = message, name = _message2.name, content = _message2.content; !isUndefined(name) && modules.setObjectName(name); if (!isUndefined(content)) { if (isObject(content)) { content = JSON.stringify(content); } modules.setContent(content); } return modules.getArrayData(); } }, { key: "encodeSetRTCOutData", value: function encodeSetRTCOutData(data, type, message) { var _this29 = this; var modules = this._codec.getModule(PBName.RtcSetOutDataInput); modules.setTarget(type); if (!isArray(data)) { data = [data]; } forEach(data, function (item, index) { _newArrowCheck(this, _this29); item.key = item.key ? item.key.toString() : item.key; item.value = item.value ? item.value.toString() : item.value; data[index] = item; }.bind(this)); modules.setValueInfo(data); message = message || {}; var _message3 = message, name = _message3.name, content = _message3.content; !isUndefined(name) && modules.setObjectName(name); if (!isUndefined(content)) { if (isObject(content)) { content = JSON.stringify(content); } modules.setContent(content); } return modules.getArrayData(); } }, { key: "ecnodeGetRTCOutData", value: function ecnodeGetRTCOutData(userIds) { var modules = this._codec.getModule(PBName.RtcQryUserOutDataInput); modules.setUserId(userIds); return modules.getArrayData(); } }, { key: "encodeSetRTCState", value: function encodeSetRTCState(report) { var modules = this._codec.getModule(PBName.MCFollowInput); modules.setId(report); return modules.getArrayData(); } }, { key: "encodeGetRTCRoomInfo", value: function encodeGetRTCRoomInfo() { var modules = this._codec.getModule(PBName.RtcQueryListInput); modules.setOrder(2); return modules.getArrayData(); } }, { key: "encodeSetRTCUserInfo", value: function encodeSetRTCUserInfo(key, value) { var modules = this._codec.getModule(PBName.RtcValueInfo); modules.setKey(key); modules.setValue(value); return modules.getArrayData(); } }, { key: "encodeRemoveRTCUserInfo", value: function encodeRemoveRTCUserInfo(keys) { var modules = this._codec.getModule(PBName.RtcKeyDeleteInput); modules.setKey(keys); return modules.getArrayData(); } }]); return DataCodec; }(); var ADataChannel = function ADataChannel(type, _watcher) { _classCallCheck(this, ADataChannel); this._watcher = _watcher; this.codec = new DataCodec(type); }; var _getIdentifier = function getIdentifier(messageId, identifier) { _newArrowCheck(this, _this); if (messageId && identifier) { return identifier + '_' + messageId; } else if (messageId) { return messageId; } else { return Date.now(); } }.bind(undefined); var BaseReader = function () { function BaseReader(header) { _classCallCheck(this, BaseReader); this.header = header; this._name = null; this.lengthSize = 0; this.messageId = 0; this.timestamp = 0; this.syncMsg = false; this.identifier = ''; } _createClass(BaseReader, [{ key: "getIdentifier", value: function getIdentifier() { var messageId = this.messageId, identifier = this.identifier; return _getIdentifier(messageId, identifier); } }, { key: "read", value: function read(stream, length) { this.readMessage(stream, length); } }, { key: "readMessage", value: function readMessage(stream, length) { return { stream: stream, length: length }; } }]); return BaseReader; }(); var BaseWriter = function () { function BaseWriter(headerType) { _classCallCheck(this, BaseWriter); this.lengthSize = 0; this.messageId = 0; this.topic = ''; this.targetId = ''; this.identifier = ''; this._header = new Header(headerType, false, QOS.AT_MOST_ONCE, false); } _createClass(BaseWriter, [{ key: "getIdentifier", value: function getIdentifier() { var messageId = this.messageId, identifier = this.identifier; return _getIdentifier(messageId, identifier); } }, { key: "write", value: function write(stream) { var headerCode = this.getHeaderFlag(); stream.write(headerCode); this.writeMessage(stream); } }, { key: "setHeaderQos", value: function setHeaderQos(qos) { this._header.qos = qos; } }, { key: "getHeaderFlag", value: function getHeaderFlag() { return this._header.encode(); } }, { key: "getLengthSize", value: function getLengthSize() { return this.lengthSize; } }, { key: "getBufferData", value: function getBufferData() { var stream = new RongStreamWriter(); this.write(stream); var val = stream.getBytesArray(); var binary = new Int8Array(val); return binary; } }, { key: "getCometData", value: function getCometData() { var data = this.data || {}; return JSON.stringify(data); } }]); return BaseWriter; }(); var ConnAckReader = function (_BaseReader) { _inherits(ConnAckReader, _BaseReader); var _super3 = _createSuper(ConnAckReader); function ConnAckReader() { var _this30; _classCallCheck(this, ConnAckReader); _this30 = _super3.apply(this, arguments); _this30._name = MessageName.CONN_ACK; _this30.status = null; _this30.userId = null; _this30.timestamp = 0; return _this30; } _createClass(ConnAckReader, [{ key: "readMessage", value: function readMessage(stream, length) { stream.readByte(); this.status = +stream.readByte(); if (length > ConnAckReader.MESSAGE_LENGTH) { this.userId = stream.readUTF(); stream.readUTF(); this.timestamp = stream.readLong(); } return { stream: stream, length: length }; } }]); return ConnAckReader; }(BaseReader); ConnAckReader.MESSAGE_LENGTH = 2; var DisconnectReader = function (_BaseReader2) { _inherits(DisconnectReader, _BaseReader2); var _super4 = _createSuper(DisconnectReader); function DisconnectReader() { var _this31; _classCallCheck(this, DisconnectReader); _this31 = _super4.apply(this, arguments); _this31._name = MessageName.DISCONNECT; _this31.status = 0; return _this31; } _createClass(DisconnectReader, [{ key: "readMessage", value: function readMessage(stream, length) { stream.readByte(); this.status = +stream.readByte(); return { stream: stream, length: length }; } }]); return DisconnectReader; }(BaseReader); DisconnectReader.MESSAGE_LENGTH = 2; var PingReqWriter = function (_BaseWriter) { _inherits(PingReqWriter, _BaseWriter); var _super5 = _createSuper(PingReqWriter); function PingReqWriter() { var _this32; _classCallCheck(this, PingReqWriter); _this32 = _super5.call(this, OperationType.PING_REQ); _this32._name = MessageName.PING_REQ; return _this32; } _createClass(PingReqWriter, [{ key: "writeMessage", value: function writeMessage(stream) {} }]); return PingReqWriter; }(BaseWriter); var PingRespReader = function (_BaseReader3) { _inherits(PingRespReader, _BaseReader3); var _super6 = _createSuper(PingRespReader); function PingRespReader(header) { var _this33; _classCallCheck(this, PingRespReader); _this33 = _super6.call(this, header); _this33._name = MessageName.PING_RESP; return _this33; } return PingRespReader; }(BaseReader); var RetryableReader = function (_BaseReader4) { _inherits(RetryableReader, _BaseReader4); var _super7 = _createSuper(RetryableReader); function RetryableReader() { var _this34; _classCallCheck(this, RetryableReader); _this34 = _super7.apply(this, arguments); _this34.messageId = 0; return _this34; } _createClass(RetryableReader, [{ key: "readMessage", value: function readMessage(stream, length) { var msgId = stream.readByte() * 256 + stream.readByte(); this.messageId = parseInt(msgId.toString(), 10); return { stream: stream, length: length }; } }]); return RetryableReader; }(BaseReader); var RetryableWriter = function (_BaseWriter2) { _inherits(RetryableWriter, _BaseWriter2); var _super8 = _createSuper(RetryableWriter); function RetryableWriter() { var _this35; _classCallCheck(this, RetryableWriter); _this35 = _super8.apply(this, arguments); _this35.messageId = 0; return _this35; } _createClass(RetryableWriter, [{ key: "writeMessage", value: function writeMessage(stream) { var id = this.messageId; var lsb = id & 255; var msb = (id & 65280) >> 8; stream.write(msb); stream.write(lsb); } }]); return RetryableWriter; }(BaseWriter); var PublishReader = function (_RetryableReader) { _inherits(PublishReader, _RetryableReader); var _super9 = _createSuper(PublishReader); function PublishReader() { var _this36; _classCallCheck(this, PublishReader); _this36 = _super9.apply(this, arguments); _this36._name = MessageName.PUBLISH; _this36.topic = ''; _this36.targetId = ''; _this36.syncMsg = false; _this36.identifier = IDENTIFIER.PUB; return _this36; } _createClass(PublishReader, [{ key: "readMessage", value: function readMessage(stream, length) { this.date = stream.readInt(); this.topic = stream.readUTF(); this.targetId = stream.readUTF(); _get(_getPrototypeOf(PublishReader.prototype), "readMessage", this).call(this, stream, length); this.data = stream.readAll(); return { stream: stream, length: length }; } }]); return PublishReader; }(RetryableReader); var PublishWriter = function (_RetryableWriter) { _inherits(PublishWriter, _RetryableWriter); var _super10 = _createSuper(PublishWriter); function PublishWriter(topic, data, targetId) { var _this37; _classCallCheck(this, PublishWriter); _this37 = _super10.call(this, OperationType.PUBLISH); _this37._name = MessageName.PUBLISH; _this37.syncMsg = false; _this37.identifier = IDENTIFIER.PUB; _this37.topic = topic; _this37.data = isString(data) ? BinaryHelper.writeUTF(data) : data; _this37.targetId = targetId; return _this37; } _createClass(PublishWriter, [{ key: "writeMessage", value: function writeMessage(stream) { stream.writeUTF(this.topic); stream.writeUTF(this.targetId); _get(_getPrototypeOf(PublishWriter.prototype), "writeMessage", this).call(this, stream); stream.write(this.data); } }]); return PublishWriter; }(RetryableWriter); var PubAckReader = function (_RetryableReader2) { _inherits(PubAckReader, _RetryableReader2); var _super11 = _createSuper(PubAckReader); function PubAckReader() { var _this38; _classCallCheck(this, PubAckReader); _this38 = _super11.apply(this, arguments); _this38._name = MessageName.PUB_ACK; _this38.status = 0; _this38.date = 0; _this38.millisecond = 0; _this38.messageUId = ''; _this38.timestamp = 0; _this38.identifier = IDENTIFIER.PUB; _this38.topic = ''; _this38.targetId = ''; return _this38; } _createClass(PubAckReader, [{ key: "readMessage", value: function readMessage(stream, length) { _get(_getPrototypeOf(PubAckReader.prototype), "readMessage", this).call(this, stream, length); this.date = stream.readInt(); this.status = stream.readByte() * 256 + stream.readByte(); this.millisecond = stream.readByte() * 256 + stream.readByte(); this.timestamp = this.date * 1000 + this.millisecond; this.messageUId = stream.readUTF(); return { stream: stream, length: length }; } }]); return PubAckReader; }(RetryableReader); var PubAckWriter = function (_RetryableWriter2) { _inherits(PubAckWriter, _RetryableWriter2); var _super12 = _createSuper(PubAckWriter); function PubAckWriter(messageId) { var _this39; _classCallCheck(this, PubAckWriter); _this39 = _super12.call(this, OperationType.PUB_ACK); _this39._name = MessageName.PUB_ACK; _this39.status = 0; _this39.date = 0; _this39.millisecond = 0; _this39.messageUId = ''; _this39.timestamp = 0; _this39.messageId = messageId; return _this39; } _createClass(PubAckWriter, [{ key: "writeMessage", value: function writeMessage(stream) { _get(_getPrototypeOf(PubAckWriter.prototype), "writeMessage", this).call(this, stream); } }]); return PubAckWriter; }(RetryableWriter); var QueryWriter = function (_RetryableWriter3) { _inherits(QueryWriter, _RetryableWriter3); var _super13 = _createSuper(QueryWriter); function QueryWriter(topic, data, targetId) { var _this40; _classCallCheck(this, QueryWriter); _this40 = _super13.call(this, OperationType.QUERY); _this40.name = MessageName.QUERY; _this40.identifier = IDENTIFIER.QUERY; _this40.topic = topic; _this40.data = isString(data) ? BinaryHelper.writeUTF(data) : data; _this40.targetId = targetId; return _this40; } _createClass(QueryWriter, [{ key: "writeMessage", value: function writeMessage(stream) { stream.writeUTF(this.topic); stream.writeUTF(this.targetId); _get(_getPrototypeOf(QueryWriter.prototype), "writeMessage", this).call(this, stream); stream.write(this.data); } }]); return QueryWriter; }(RetryableWriter); var QueryConWriter = function (_RetryableWriter4) { _inherits(QueryConWriter, _RetryableWriter4); var _super14 = _createSuper(QueryConWriter); function QueryConWriter(messageId) { var _this41; _classCallCheck(this, QueryConWriter); _this41 = _super14.call(this, OperationType.QUERY_CONFIRM); _this41._name = MessageName.QUERY_CON; _this41.messageId = messageId; return _this41; } return QueryConWriter; }(RetryableWriter); var QueryAckReader = function (_RetryableReader3) { _inherits(QueryAckReader, _RetryableReader3); var _super15 = _createSuper(QueryAckReader); function QueryAckReader() { var _this42; _classCallCheck(this, QueryAckReader); _this42 = _super15.apply(this, arguments); _this42._name = MessageName.QUERY_ACK; _this42.status = 0; _this42.identifier = IDENTIFIER.QUERY; _this42.topic = ''; _this42.targetId = ''; return _this42; } _createClass(QueryAckReader, [{ key: "readMessage", value: function readMessage(stream, length) { _get(_getPrototypeOf(QueryAckReader.prototype), "readMessage", this).call(this, stream, length); this.date = stream.readInt(); this.status = stream.readByte() * 256 + stream.readByte(); this.data = stream.readAll(); return { stream: stream, length: length }; } }]); return QueryAckReader; }(RetryableReader); var getReaderByHeader = function getReaderByHeader(header) { _newArrowCheck(this, _this); var type = header.type; var msg; switch (type) { case OperationType.CONN_ACK: msg = new ConnAckReader(header); break; case OperationType.PUBLISH: msg = new PublishReader(header); msg.syncMsg = header.syncMsg; break; case OperationType.PUB_ACK: msg = new PubAckReader(header); break; case OperationType.QUERY_ACK: msg = new QueryAckReader(header); break; case OperationType.SUB_ACK: case OperationType.UNSUB_ACK: case OperationType.PING_RESP: msg = new PingRespReader(header); break; case OperationType.DISCONNECT: msg = new DisconnectReader(header); break; default: msg = new BaseReader(header); logger.error('No support for deserializing ' + type + ' messages'); } return msg; }.bind(undefined); var readWSBuffer = function readWSBuffer(data) { _newArrowCheck(this, _this); var arr = new Uint8Array(data); var stream = new RongStreamReader(arr); var flags = stream.readByte(); var header = new Header(flags); var msg = getReaderByHeader(header); msg.read(stream, arr.length - 1); return msg; }.bind(undefined); var readCometData = function readCometData(data) { _newArrowCheck(this, _this); var flags = data.headerCode; var header = new Header(flags); var msg = getReaderByHeader(header); for (var _key9 in data) { msg[_key9] = data[_key9]; } return msg; }.bind(undefined); var ConnectResultCode = { ACCEPTED: 0, UNACCEPTABLE_PROTOCOL_VERSION: 1, IDENTIFIER_REJECTED: 2, SERVER_UNAVAILABLE: 3, TOKEN_INCORRECT: 4, NOT_AUTHORIZED: 5, REDIRECT: 6, PACKAGE_ERROR: 7, APP_BLOCK_OR_DELETE: 8, BLOCK: 9, TOKEN_EXPIRE: 10, DEVICE_ERROR: 11, HOSTNAME_ERROR: 12, HASOHTERSAMECLIENTONLINE: 13 }; var ConnectionStatus; (function (ConnectionStatus) { ConnectionStatus[ConnectionStatus["CONNECTED"] = 0] = "CONNECTED"; ConnectionStatus[ConnectionStatus["CONNECTING"] = 1] = "CONNECTING"; ConnectionStatus[ConnectionStatus["DISCONNECTED"] = 2] = "DISCONNECTED"; ConnectionStatus[ConnectionStatus["NETWORK_UNAVAILABLE"] = 3] = "NETWORK_UNAVAILABLE"; ConnectionStatus[ConnectionStatus["CONNECTION_CLOSED"] = 4] = "CONNECTION_CLOSED"; ConnectionStatus[ConnectionStatus["KICKED_OFFLINE_BY_OTHER_CLIENT"] = 6] = "KICKED_OFFLINE_BY_OTHER_CLIENT"; ConnectionStatus[ConnectionStatus["WEBSOCKET_UNAVAILABLE"] = 7] = "WEBSOCKET_UNAVAILABLE"; ConnectionStatus[ConnectionStatus["WEBSOCKET_ERROR"] = 8] = "WEBSOCKET_ERROR"; ConnectionStatus[ConnectionStatus["BLOCKED"] = 9] = "BLOCKED"; ConnectionStatus[ConnectionStatus["DOMAIN_INCORRECT"] = 12] = "DOMAIN_INCORRECT"; ConnectionStatus[ConnectionStatus["APPKEY_IS_FAKE"] = 20] = "APPKEY_IS_FAKE"; ConnectionStatus[ConnectionStatus["ULTRALIMIT"] = 1101] = "ULTRALIMIT"; ConnectionStatus[ConnectionStatus["REQUEST_NAVI"] = 201] = "REQUEST_NAVI"; ConnectionStatus[ConnectionStatus["RESPONSE_NAVI"] = 202] = "RESPONSE_NAVI"; ConnectionStatus[ConnectionStatus["RESPONSE_NAVI_ERROR"] = 203] = "RESPONSE_NAVI_ERROR"; ConnectionStatus[ConnectionStatus["RESPONSE_NAVI_TIMEOUT"] = 204] = "RESPONSE_NAVI_TIMEOUT"; })(ConnectionStatus || (ConnectionStatus = {})); var ConnectionStatus$1 = ConnectionStatus; var randomNum = function randomNum(min, max) { _newArrowCheck(this, _this); return min + Math.floor(Math.random() * (max - min)); }.bind(undefined); var getUUID = function getUUID() { var _this43 = this; _newArrowCheck(this, _this); return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { _newArrowCheck(this, _this43); var r = Math.random() * 16 | 0; var v = c === 'x' ? r : r & 0x3 | 0x8; return v.toString(16); }.bind(this)); }.bind(undefined); var Topic; (function (Topic) { Topic[Topic["ppMsgP"] = 1] = "ppMsgP"; Topic[Topic["ppMsgN"] = 2] = "ppMsgN"; Topic[Topic["ppMsgS"] = 3] = "ppMsgS"; Topic[Topic["pgMsgP"] = 4] = "pgMsgP"; Topic[Topic["chatMsg"] = 5] = "chatMsg"; Topic[Topic["pcMsgP"] = 6] = "pcMsgP"; Topic[Topic["qryPMsg"] = 7] = "qryPMsg"; Topic[Topic["qryGMsg"] = 8] = "qryGMsg"; Topic[Topic["qryCHMsg"] = 9] = "qryCHMsg"; Topic[Topic["qryCMsg"] = 10] = "qryCMsg"; Topic[Topic["qrySMsg"] = 11] = "qrySMsg"; Topic[Topic["recallMsg"] = 12] = "recallMsg"; Topic[Topic["prMsgS"] = 13] = "prMsgS"; Topic[Topic["s_ntf"] = 14] = "s_ntf"; Topic[Topic["s_msg"] = 15] = "s_msg"; Topic[Topic["s_stat"] = 16] = "s_stat"; Topic[Topic["s_cmd"] = 17] = "s_cmd"; Topic[Topic["s_us"] = 18] = "s_us"; Topic[Topic["pullUS"] = 19] = "pullUS"; Topic[Topic["pgMsgS"] = 20] = "pgMsgS"; Topic[Topic["chatMsgS"] = 21] = "chatMsgS"; Topic[Topic["qrySessionsAtt"] = 22] = "qrySessionsAtt"; Topic[Topic["pullMsg"] = 23] = "pullMsg"; Topic[Topic["qrySessions"] = 24] = "qrySessions"; Topic[Topic["delSessions"] = 25] = "delSessions"; Topic[Topic["delMsg"] = 26] = "delMsg"; Topic[Topic["updRRTime"] = 27] = "updRRTime"; Topic[Topic["chrmPull"] = 28] = "chrmPull"; Topic[Topic["joinChrm"] = 29] = "joinChrm"; Topic[Topic["joinChrmR"] = 30] = "joinChrmR"; Topic[Topic["exitChrm"] = 31] = "exitChrm"; Topic[Topic["queryChrmI"] = 32] = "queryChrmI"; Topic[Topic["setKV"] = 33] = "setKV"; Topic[Topic["delKV"] = 34] = "delKV"; Topic[Topic["pullKV"] = 35] = "pullKV"; Topic[Topic["qryRelation"] = 36] = "qryRelation"; Topic[Topic["delRelation"] = 37] = "delRelation"; Topic[Topic["pullSeAtts"] = 38] = "pullSeAtts"; Topic[Topic["setSeAtt"] = 39] = "setSeAtt"; Topic[Topic["qnTkn"] = 40] = "qnTkn"; Topic[Topic["qnUrl"] = 41] = "qnUrl"; Topic[Topic["aliUrl"] = 42] = "aliUrl"; Topic[Topic["cleanPMsg"] = 43] = "cleanPMsg"; Topic[Topic["cleanGMsg"] = 44] = "cleanGMsg"; Topic[Topic["cleanCMsg"] = 45] = "cleanCMsg"; Topic[Topic["cleanSMsg"] = 46] = "cleanSMsg"; Topic[Topic["rtcRJoin_data"] = 47] = "rtcRJoin_data"; Topic[Topic["rtcRExit"] = 48] = "rtcRExit"; Topic[Topic["rtcPing"] = 49] = "rtcPing"; Topic[Topic["rtcSetData"] = 50] = "rtcSetData"; Topic[Topic["userSetData"] = 51] = "userSetData"; Topic[Topic["rtcQryData"] = 52] = "rtcQryData"; Topic[Topic["rtcDelData"] = 53] = "rtcDelData"; Topic[Topic["rtcSetOutData"] = 54] = "rtcSetOutData"; Topic[Topic["rtcQryUserOutData"] = 55] = "rtcQryUserOutData"; Topic[Topic["rtcToken"] = 56] = "rtcToken"; Topic[Topic["rtcUserState"] = 57] = "rtcUserState"; Topic[Topic["rtcRInfo"] = 58] = "rtcRInfo"; Topic[Topic["rtcUData"] = 59] = "rtcUData"; Topic[Topic["rtcUPut"] = 60] = "rtcUPut"; Topic[Topic["rtcUDel"] = 61] = "rtcUDel"; Topic[Topic["rtcUList"] = 62] = "rtcUList"; })(Topic || (Topic = {})); var Topic$1 = Topic; var getValidHosts = function getValidHosts(hosts, protocol, runtime) { _newArrowCheck(this, _this); return __awaiter$1(void 0, void 0, void 0, regeneratorRuntime.mark(function _callee2() { var _this44 = this; var pingRes; return regeneratorRuntime.wrap(function _callee2$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: _context3.next = 2; return Promise.all(hosts.map(function (host) { _newArrowCheck(this, _this44); return __awaiter$1(void 0, void 0, void 0, regeneratorRuntime.mark(function _callee() { var now, url, res; return regeneratorRuntime.wrap(function _callee$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: now = Date.now(); url = "".concat(protocol, "://").concat(host, "/ping?r=").concat(randomNum(1000, 9999)); _context2.next = 4; return runtime.httpReq({ url: url, timeout: PING_REQ_TIMEOUT }); case 4: res = _context2.sent; return _context2.abrupt("return", { status: res.status, host: host, cost: Date.now() - now }); case 6: case "end": return _context2.stop(); } } }, _callee); })); }.bind(this))); case 2: pingRes = _context3.sent; pingRes = pingRes.filter(function (item) { _newArrowCheck(this, _this44); return item.status === 200; }.bind(this)); if (pingRes.length > 1) { pingRes = pingRes.sort(function (a, b) { _newArrowCheck(this, _this44); return a.cost - b.cost; }.bind(this)); } return _context3.abrupt("return", pingRes.map(function (item) { _newArrowCheck(this, _this44); return item.host; }.bind(this))); case 6: case "end": return _context3.stop(); } } }, _callee2, this); })); }.bind(undefined); var formatWSUrl = function formatWSUrl(protocol, host, appkey, token, runtime, apiVersion, pid) { _newArrowCheck(this, _this); return "".concat(protocol, "://").concat(host, "/websocket?appId=").concat(appkey, "&token=").concat(encodeURIComponent(token), "&sdkVer=").concat(apiVersion, "&pid=").concat(pid, "&apiVer=").concat(runtime.isFromUniapp ? 'uniapp' : 'normal').concat(runtime.connectPlatform ? '&platform=' + runtime.connectPlatform : ''); }.bind(undefined); var formatResolveKey = function formatResolveKey(messageId, identifier) { _newArrowCheck(this, _this); return [messageId, identifier].join('-'); }.bind(undefined); var isStatusMessage = function isStatusMessage(topic) { var _this45 = this; _newArrowCheck(this, _this); return [Topic$1.ppMsgS, Topic$1.pgMsgS, Topic$1.chatMsgS].map(function (item) { _newArrowCheck(this, _this45); return Topic$1[item]; }.bind(this)).indexOf(topic) >= 0; }.bind(undefined); var sendWSData = function sendWSData(writer, socket) { _newArrowCheck(this, _this); if (!(writer instanceof PingReqWriter)) { logger.debug('Websocket ==>', writer); } var binary = writer.getBufferData(); socket.send(binary.buffer); }.bind(undefined); var WebSocketChannel = function (_ADataChannel) { _inherits(WebSocketChannel, _ADataChannel); var _super16 = _createSuper(WebSocketChannel); function WebSocketChannel(_runtime, watcher) { var _this47 = this; var _this46; _classCallCheck(this, WebSocketChannel); _this46 = _super16.call(this, 'websocket', watcher); _this46._runtime = _runtime; _this46._socket = null; _this46._messageIds = {}; _this46._syncMessageIds = {}; _this46._failedCount = 0; _this46.ALLOW_FAILED_TIMES = 4; _this46._idCount = 0; _this46._generateMessageId = function () { _newArrowCheck(this, _this47); if (_this46._idCount >= 65535) { _this46._idCount = 0; } return ++_this46._idCount; }.bind(this); return _this46; } _createClass(WebSocketChannel, [{ key: "connect", value: function connect(appkey, token, hosts, protocol, apiVersion) { return __awaiter$1(this, void 0, void 0, regeneratorRuntime.mark(function _callee3() { var _this48 = this; var validHosts, wsProtocol, _loop2, i, len, _ret; return regeneratorRuntime.wrap(function _callee3$(_context5) { while (1) { switch (_context5.prev = _context5.next) { case 0: apiVersion = matchVersion(apiVersion); this._watcher.status(ConnectionStatus$1.CONNECTING); _context5.next = 4; return getValidHosts(hosts, protocol, this._runtime); case 4: validHosts = _context5.sent; if (!(validHosts.length === 0)) { _context5.next = 8; break; } logger.error('No valid websocket server hosts!'); return _context5.abrupt("return", ErrorCode$1.RC_SOCKET_NOT_CREATED); case 8: wsProtocol = protocol.replace('http', 'ws'); _loop2 = regeneratorRuntime.mark(function _loop2(i, len) { var _this49 = this; var url, socket, disconnected, code; return regeneratorRuntime.wrap(function _loop2$(_context4) { while (1) { switch (_context4.prev = _context4.next) { case 0: url = formatWSUrl(wsProtocol, validHosts[i], appkey, token, _this48._runtime, apiVersion); socket = _this48._runtime.createWebSocket(url); disconnected = function disconnected(code) { _newArrowCheck(this, _this49); if (_this48._socket === socket) { _this48._socket = null; _this48._watcher.status(code); } }.bind(this); _context4.next = 5; return new Promise(function (resolve) { var _this50 = this; _newArrowCheck(this, _this49); socket.onMessage(function (data) { _newArrowCheck(this, _this50); if (Object.prototype.toString.call(data) !== '[object ArrayBuffer]') { logger.warn('Socket received invalid data:', data); return; } var signal = readWSBuffer(data); if (signal instanceof PingRespReader && _this48._pingResolve) { _this48._pingResolve(ErrorCode$1.SUCCESS); _this48._pingResolve = undefined; return; } logger.debug('Websocket <==', signal); if (signal instanceof ConnAckReader) { if (signal.status !== ConnectResultCode.ACCEPTED) { logger.error('Websocket connAck status:', signal.status); resolve(signal.status); return; } _this48.connectedTime = signal.timestamp; _this48.userId = signal.userId || ''; resolve(ErrorCode$1.SUCCESS); return; } if (signal instanceof DisconnectReader) { var status = signal.status; var connStatus = status === 1 ? ConnectionStatus$1.KICKED_OFFLINE_BY_OTHER_CLIENT : status === 2 ? ConnectionStatus$1.BLOCKED : status; _this48._watcher.status(connStatus); return; } _this48._onReceiveSignal(signal); }.bind(this)); socket.onClose(function (code, reason) { _newArrowCheck(this, _this50); logger.warn('websocket closed! code:', code, 'reason:', reason); disconnected(ConnectionStatus$1.CONNECTION_CLOSED); resolve(code); }.bind(this)); socket.onError(function (error) { _newArrowCheck(this, _this50); logger.error('websocket error!', error); disconnected(ConnectionStatus$1.WEBSOCKET_ERROR); resolve(ErrorCode$1.NETWORK_ERROR); }.bind(this)); socket.onOpen(function () { _newArrowCheck(this, _this50); return logger.debug('websocket open =>', url); }.bind(this)); timerSetTimeout(function () { _newArrowCheck(this, _this50); resolve(ErrorCode$1.TIMEOUT); }.bind(this), WEB_SOCKET_TIMEOUT); }.bind(this)); case 5: code = _context4.sent; if (!(code === ErrorCode$1.SUCCESS)) { _context4.next = 11; break; } _this48._socket = socket; _this48._checkAlive(); _this48._watcher.status(ConnectionStatus$1.CONNECTED); return _context4.abrupt("return", { v: code }); case 11: socket.close(); case 12: case "end": return _context4.stop(); } } }, _loop2, this); }); i = 0, len = validHosts.length; case 11: if (!(i < len)) { _context5.next = 19; break; } return _context5.delegateYield(_loop2(i, len), "t0", 13); case 13: _ret = _context5.t0; if (!(_typeof(_ret) === "object")) { _context5.next = 16; break; } return _context5.abrupt("return", _ret.v); case 16: i += 1; _context5.next = 11; break; case 19: return _context5.abrupt("return", ErrorCode$1.RC_NET_UNAVAILABLE); case 20: case "end": return _context5.stop(); } } }, _callee3, this); })); } }, { key: "_checkAlive", value: function _checkAlive() { var _a; return __awaiter$1(this, void 0, void 0, regeneratorRuntime.mark(function _callee4() { var _this51 = this; var code; return regeneratorRuntime.wrap(function _callee4$(_context6) { while (1) { switch (_context6.prev = _context6.next) { case 0: if (this._socket) { _context6.next = 2; break; } return _context6.abrupt("return"); case 2: this.sendOnly(new PingReqWriter()); _context6.next = 5; return new Promise(function (resolve) { var _this52 = this; _newArrowCheck(this, _this51); this._pingResolve = resolve; setTimeout(function () { _newArrowCheck(this, _this52); this._pingResolve = undefined; resolve(ErrorCode$1.TIMEOUT); }.bind(this), IM_SIGNAL_TIMEOUT); }.bind(this)); case 5: code = _context6.sent; if (!(code !== ErrorCode$1.SUCCESS && ++this._failedCount >= this.ALLOW_FAILED_TIMES)) { _context6.next = 9; break; } (_a = this._socket) === null || _a === void 0 ? void 0 : _a.close(); return _context6.abrupt("return"); case 9: this._failedCount = 0; setTimeout(function () { _newArrowCheck(this, _this51); return this._checkAlive(); }.bind(this), IM_PING_INTERVAL_TIME); case 11: case "end": return _context6.stop(); } } }, _callee4, this); })); } }, { key: "_onReceiveSignal", value: function _onReceiveSignal(signal) { return __awaiter$1(this, void 0, void 0, regeneratorRuntime.mark(function _callee5() { var _this53 = this; var messageId, identifier, isQosNeedAck, key, resolve, syncMsg, topic, ack; return regeneratorRuntime.wrap(function _callee5$(_context7) { while (1) { switch (_context7.prev = _context7.next) { case 0: messageId = signal.messageId, identifier = signal.identifier; isQosNeedAck = signal.header && signal.header.qos !== QOS.AT_MOST_ONCE; if (isQosNeedAck) { if (signal instanceof PublishReader && !signal.syncMsg) { this.sendOnly(new PubAckWriter(messageId)); } if (signal instanceof QueryAckReader) { this.sendOnly(new QueryConWriter(messageId)); } } key = formatResolveKey(messageId, identifier); if (messageId > 0) { resolve = this._messageIds[key]; resolve && resolve(signal); this._syncMessageIds[key] && this._syncMessageIds[key](signal); } if (!(signal instanceof PublishReader)) { _context7.next = 15; break; } syncMsg = signal.syncMsg, topic = signal.topic; if (!(!syncMsg || isStatusMessage(topic))) { _context7.next = 10; break; } this._watcher.signal(signal); return _context7.abrupt("return"); case 10: _context7.next = 12; return new Promise(function (resolve) { _newArrowCheck(this, _this53); this._syncMessageIds[key] = resolve; }.bind(this)); case 12: ack = _context7.sent; delete this._syncMessageIds[key]; this._watcher.signal(signal, ack); case 15: case "end": return _context7.stop(); } } }, _callee5, this); })); } }, { key: "sendOnly", value: function sendOnly(writer) { if (this._socket) { sendWSData(writer, this._socket); } } }, { key: "send", value: function send(writer, respPBName, option) { var timeout = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : IM_SIGNAL_TIMEOUT; return __awaiter$1(this, void 0, void 0, regeneratorRuntime.mark(function _callee6() { var _this54 = this; var messageId, identifier, respSignal, data; return regeneratorRuntime.wrap(function _callee6$(_context8) { while (1) { switch (_context8.prev = _context8.next) { case 0: if (!this._socket) { _context8.next = 14; break; } messageId = this._generateMessageId(); writer.messageId = messageId; identifier = writer.identifier; sendWSData(writer, this._socket); _context8.next = 7; return new Promise(function (resolve) { var _this55 = this; _newArrowCheck(this, _this54); var key = formatResolveKey(messageId, identifier); this._messageIds[key] = resolve; setTimeout(function () { _newArrowCheck(this, _this55); delete this._messageIds[key]; resolve(); }.bind(this), timeout); }.bind(this)); case 7: respSignal = _context8.sent; if (respSignal) { _context8.next = 10; break; } return _context8.abrupt("return", { code: ErrorCode$1.TIMEOUT }); case 10: if (!(respSignal.status !== 0)) { _context8.next = 12; break; } return _context8.abrupt("return", { code: respSignal.status }); case 12: data = respPBName ? this.codec.decodeByPBName(respSignal.data, respPBName, option) : respSignal; return _context8.abrupt("return", { code: ErrorCode$1.SUCCESS, data: data }); case 14: return _context8.abrupt("return", { code: ErrorCode$1.RC_NET_CHANNEL_INVALID }); case 15: case "end": return _context8.stop(); } } }, _callee6, this); })); } }, { key: "close", value: function close() { if (this._socket) { this._socket.close(); this._socket = null; this._watcher.status(ConnectionStatus$1.DISCONNECTED); } } }]); return WebSocketChannel; }(ADataChannel); var HttpMethod; (function (HttpMethod) { HttpMethod["GET"] = "GET"; HttpMethod["POST"] = "POST"; })(HttpMethod || (HttpMethod = {})); var isValidJSON = function isValidJSON(jsonStr) { _newArrowCheck(this, _this); if (isObject(jsonStr)) { return true; } var isValid = false; try { var obj = JSON.parse(jsonStr); var str = JSON.stringify(obj); isValid = str === jsonStr; } catch (e) { isValid = false; } return isValid; }.bind(undefined); var CometChannel = function (_ADataChannel2) { _inherits(CometChannel, _ADataChannel2); var _super17 = _createSuper(CometChannel); function CometChannel(_runtime, watcher) { var _this57 = this; var _this56; _classCallCheck(this, CometChannel); _this56 = _super17.call(this, 'comet', watcher); _this56._runtime = _runtime; _this56._messageIds = {}; _this56._syncMessageIds = {}; _this56._idCount = 0; _this56._generateMessageId = function () { _newArrowCheck(this, _this57); return ++_this56._idCount; }.bind(this); _this56._pid = encodeURIComponent(new Date().getTime() + Math.random() + ''); return _this56; } _createClass(CometChannel, [{ key: "handleCometRes", value: function handleCometRes(res) { var _this58 = this; if (res.status !== 200 && res.status !== 202) { return false; } var data = isString(res.data) ? JSON.parse(res.data) : res.data; if (!data) { logger.warn('received data is not a validJson', data); return false; } if (!isArray(data)) { return true; } forEach(data, function (item) { _newArrowCheck(this, _this58); return __awaiter$1(this, void 0, void 0, regeneratorRuntime.mark(function _callee7() { var _this59 = this; var sessionid, signal, messageId, _header, status, identifier, isQosNeedAck, key, resolve, writer, _writer, connStatus, syncMsg, topic, ack; return regeneratorRuntime.wrap(function _callee7$(_context9) { while (1) { switch (_context9.prev = _context9.next) { case 0: sessionid = item.sessionid; if (sessionid) { this._sessionid = sessionid; } signal = readCometData(item); messageId = signal.messageId, _header = signal._header, status = signal.status, identifier = signal.identifier; isQosNeedAck = _header && _header.qos !== QOS.AT_MOST_ONCE; key = formatResolveKey(messageId, identifier); if (messageId && signal.getIdentifier) { resolve = this._messageIds[key]; resolve && resolve(signal); this._syncMessageIds[key] && this._syncMessageIds[key](signal); } if (isQosNeedAck) { if (signal instanceof PublishReader && !signal.syncMsg) { writer = new PubAckWriter(messageId); this.sendOnly(writer); } if (signal instanceof QueryAckReader) { _writer = new QueryConWriter(messageId); this.sendOnly(_writer); } } if (signal instanceof DisconnectReader) { connStatus = status === 1 ? ConnectionStatus$1.KICKED_OFFLINE_BY_OTHER_CLIENT : status === 2 ? ConnectionStatus$1.BLOCKED : status; this._watcher.status(connStatus); } if (!(signal instanceof PublishReader)) { _context9.next = 19; break; } syncMsg = signal.syncMsg, topic = signal.topic; if (!(!syncMsg || isStatusMessage(topic))) { _context9.next = 14; break; } this._watcher.signal(signal); return _context9.abrupt("return", false); case 14: _context9.next = 16; return new Promise(function (resolve) { _newArrowCheck(this, _this59); this._syncMessageIds[key] = resolve; }.bind(this)); case 16: ack = _context9.sent; delete this._syncMessageIds[key]; this._watcher.signal(signal, ack); case 19: case "end": return _context9.stop(); } } }, _callee7, this); })); }.bind(this)); return true; } }, { key: "_startPullSignal", value: function _startPullSignal(protocol) { return __awaiter$1(this, void 0, void 0, regeneratorRuntime.mark(function _callee8() { var timestamp, url, res, isSuccess; return regeneratorRuntime.wrap(function _callee8$(_context10) { while (1) { switch (_context10.prev = _context10.next) { case 0: timestamp = new Date().getTime(); url = "".concat(protocol, "://").concat(this._domain, "/pullmsg.js?sessionid=").concat(this._sessionid, "×trap=").concat(timestamp, "&pid=").concat(this._pid); _context10.next = 4; return this._runtime.httpReq({ url: url, body: { pid: this._pid }, timeout: IM_COMET_PULLMSG_TIMEOUT }); case 4: res = _context10.sent; isSuccess = this.handleCometRes(res); if (!this._isDisconnected) { if (isSuccess) { this._startPullSignal(protocol); } else { this._watcher.status(ConnectionStatus$1.NETWORK_UNAVAILABLE); this.close(); } } case 7: case "end": return _context10.stop(); } } }, _callee8, this); })); } }, { key: "connect", value: function connect(appkey, token, hosts, protocol, apiVersion) { return __awaiter$1(this, void 0, void 0, regeneratorRuntime.mark(function _callee9() { var _this60 = this; var validHosts, handleConnectRes, i, len, url, res, response; return regeneratorRuntime.wrap(function _callee9$(_context11) { while (1) { switch (_context11.prev = _context11.next) { case 0: apiVersion = matchVersion(apiVersion); this._protocol = protocol; this._isDisconnected = false; this._watcher.status(ConnectionStatus$1.CONNECTING); _context11.next = 6; return getValidHosts(hosts, protocol, this._runtime); case 6: validHosts = _context11.sent; if (!(validHosts.length === 0)) { _context11.next = 10; break; } logger.error('No valid websocket server hosts!'); return _context11.abrupt("return", ErrorCode$1.RC_SOCKET_NOT_CREATED); case 10: handleConnectRes = function handleConnectRes(res) { _newArrowCheck(this, _this60); if (res.status !== 200 && res.status !== 202) { return false; } if (res.data) { if (!isValidJSON(res.data)) { logger.warn('received data is not a validJson', res.data); return false; } return isObject(res.data) ? res.data : JSON.parse(res.data); } return false; }.bind(this); i = 0, len = validHosts.length; case 12: if (!(i < len)) { _context11.next = 29; break; } url = formatWSUrl(protocol, validHosts[i], appkey, token, this._runtime, apiVersion, this._pid); _context11.next = 16; return this._runtime.httpReq({ url: url, body: { pid: this._pid }, timeout: WEB_SOCKET_TIMEOUT }); case 16: res = _context11.sent; response = handleConnectRes(res); this._domain = validHosts[i]; if (!(response && response.status === 0)) { _context11.next = 26; break; } this._watcher.status(ConnectionStatus$1.CONNECTED); this._sessionid = response.sessionid; this._startPullSignal(protocol); this.userId = response.userId; this.connectedTime = response.timestamp; return _context11.abrupt("return", response.status); case 26: i += 1; _context11.next = 12; break; case 29: return _context11.abrupt("return", ErrorCode$1.RC_NET_UNAVAILABLE); case 30: case "end": return _context11.stop(); } } }, _callee9, this); })); } }, { key: "sendCometData", value: function sendCometData(writer) { return __awaiter$1(this, void 0, void 0, regeneratorRuntime.mark(function _callee10() { var _domain, _sessionid, _pid, messageId, topic, targetId, identifier, headerCode, url, res; return regeneratorRuntime.wrap(function _callee10$(_context12) { while (1) { switch (_context12.prev = _context12.next) { case 0: _domain = this._domain, _sessionid = this._sessionid, _pid = this._pid; messageId = writer.messageId, topic = writer.topic, targetId = writer.targetId, identifier = writer.identifier; headerCode = writer.getHeaderFlag(); if (topic) { url = "".concat(this._protocol, "://").concat(_domain, "/websocket?messageid=").concat(messageId, "&header=").concat(headerCode, "&sessionid=").concat(_sessionid, "&topic=").concat(topic, "&targetid=").concat(targetId, "&pid=").concat(_pid); } else { url = "".concat(this._protocol, "://").concat(_domain, "/websocket?messageid=").concat(messageId, "&header=").concat(headerCode, "&sessionid=").concat(_sessionid, "&pid=").concat(_pid); } _context12.next = 6; return this._runtime.httpReq({ url: url, method: HttpMethod.POST, body: writer.getCometData() }); case 6: res = _context12.sent; this.handleCometRes(res); case 8: case "end": return _context12.stop(); } } }, _callee10, this); })); } }, { key: "sendOnly", value: function sendOnly(writer) { this.sendCometData(writer); } }, { key: "send", value: function send(writer, respPBName, option) { var timeout = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : IM_SIGNAL_TIMEOUT; return __awaiter$1(this, void 0, void 0, regeneratorRuntime.mark(function _callee11() { var _this61 = this; var messageId, identifier, respSignal, data; return regeneratorRuntime.wrap(function _callee11$(_context13) { while (1) { switch (_context13.prev = _context13.next) { case 0: messageId = this._generateMessageId(); writer.messageId = messageId; this.sendCometData(writer); identifier = writer.identifier; _context13.next = 6; return new Promise(function (resolve) { var _this62 = this; _newArrowCheck(this, _this61); var key = formatResolveKey(messageId, identifier); this._messageIds[key] = resolve; setTimeout(function () { _newArrowCheck(this, _this62); delete this._messageIds[key]; resolve(); }.bind(this), timeout); }.bind(this)); case 6: respSignal = _context13.sent; if (respSignal) { _context13.next = 9; break; } return _context13.abrupt("return", { code: ErrorCode$1.TIMEOUT }); case 9: if (!(respSignal.status !== 0)) { _context13.next = 11; break; } return _context13.abrupt("return", { code: respSignal.status }); case 11: data = respPBName ? this.codec.decodeByPBName(respSignal.data, respPBName, option) : respSignal; return _context13.abrupt("return", { code: ErrorCode$1.SUCCESS, data: data }); case 13: case "end": return _context13.stop(); } } }, _callee11, this); })); } }, { key: "close", value: function close() { this._isDisconnected = true; this._watcher.status(ConnectionStatus$1.DISCONNECTED); } }]); return CometChannel; }(ADataChannel); var getKey = function getKey(appkey, token) { _newArrowCheck(this, _this); return ['navi', appkey, token].join('_'); }.bind(undefined); var getNaviInfoFromCache = function getNaviInfoFromCache(appkey, token, storage) { _newArrowCheck(this, _this); var key = getKey(appkey, token); var jsonStr = storage.getItem(key); if (!jsonStr) { return null; } var data; try { data = JSON.parse(jsonStr); } catch (err) { storage.removeItem(key); return null; } if (Date.now() - data.timestamp >= NAVI_CACHE_DURATION) { storage.removeItem(key); return null; } return data.naviInfo; }.bind(undefined); var setNaviInfo2Cache = function setNaviInfo2Cache(appkey, token, naviInfo, storage) { _newArrowCheck(this, _this); var key = getKey(appkey, token); var data = { naviInfo: naviInfo, timestamp: Date.now() }; storage.setItem(key, JSON.stringify(data)); }.bind(undefined); var clearCache = function clearCache(appkey, token, storage) { _newArrowCheck(this, _this); storage.removeItem(getKey(appkey, token)); }.bind(undefined); var Navi = function () { function Navi(_runtime, _appkey, _navigators) { var _customCMP = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : []; var _apiVersion = arguments.length > 4 ? arguments[4] : undefined; var _connectType = arguments.length > 5 ? arguments[5] : undefined; _classCallCheck(this, Navi); this._runtime = _runtime; this._appkey = _appkey; this._navigators = _navigators; this._customCMP = _customCMP; this._apiVersion = _apiVersion; this._connectType = _connectType; this._apiVersion = matchVersion(this._apiVersion); } _createClass(Navi, [{ key: "_formatNaviUrl", value: function _formatNaviUrl(url, token, appkey, jsonpFunc, connectType) { var path = this._runtime.isSupportSocket() && connectType === 'websocket' ? 'navi' : 'cometnavi'; var tmpUrl = "".concat(url, "/").concat(path, ".js?appId=").concat(appkey, "&token=").concat(encodeURIComponent(token), "&callBack=").concat(jsonpFunc, "&v=").concat(this._apiVersion, "&r=").concat(Date.now()); return tmpUrl; } }, { key: "_reqNavi", value: function _reqNavi(uris, appkey, token, connectType) { return __awaiter$1(this, void 0, void 0, regeneratorRuntime.mark(function _callee12() { var jsonpFunc, i, len, url, res, jsonStr, naviInfo, protocol; return regeneratorRuntime.wrap(function _callee12$(_context14) { while (1) { switch (_context14.prev = _context14.next) { case 0: jsonpFunc = 'getServerEndpoint'; i = 0, len = uris.length; case 2: if (!(i < len)) { _context14.next = 24; break; } url = this._formatNaviUrl(uris[i], token, appkey, jsonpFunc, connectType); logger.debug("req navi => ".concat(url)); _context14.next = 7; return this._runtime.httpReq({ url: url, timeout: NAVI_REQ_TIMEOUT }); case 7: res = _context14.sent; if (!(res.status !== 200)) { _context14.next = 10; break; } return _context14.abrupt("continue", 21); case 10: _context14.prev = 10; jsonStr = res.data.replace("".concat(jsonpFunc, "("), '').replace(/\);?$/, ''); naviInfo = JSON.parse(jsonStr); protocol = /^https/.test(url) ? 'https' : 'http'; naviInfo.protocol = protocol; return _context14.abrupt("return", naviInfo); case 18: _context14.prev = 18; _context14.t0 = _context14["catch"](10); logger.error('parse navi err =>', _context14.t0); case 21: i += 1; _context14.next = 2; break; case 24: return _context14.abrupt("return", null); case 25: case "end": return _context14.stop(); } } }, _callee12, this, [[10, 18]]); })); } }, { key: "getInfo", value: function getInfo(token, dynamicUris, force, isCppMode) { var _a; return __awaiter$1(this, void 0, void 0, regeneratorRuntime.mark(function _callee13() { var _this63 = this; var connectUrl, _naviInfo, naviInfo, uris; return regeneratorRuntime.wrap(function _callee13$(_context15) { while (1) { switch (_context15.prev = _context15.next) { case 0: if (!isCppMode) { _context15.next = 2; break; } return _context15.abrupt("return", null); case 2: if (this._runtime.useNavi) { _context15.next = 7; break; } if (this._runtime.isSupportSocket()) { connectUrl = MINI_SOCKET_CONNECT_URIS.join(','); } else { connectUrl = MINI_COMET_CONNECT_URIS.join(','); } _naviInfo = { code: 200, protocol: 'https', server: '', voipCallInfo: '', kvStorage: 0, openHttpDNS: false, historyMsg: false, chatroomMsg: false, uploadServer: 'https://upload.qiniup.com', bosAddr: 'https://gz.bcebos.com', location: '', monitor: 0, joinMChrm: false, openMp: 0, openUS: 0, grpMsgLimit: 0, isFormatted: 0, gifSize: 2048, logSwitch: 0, logPolicy: '', compDays: 0, msgAck: '', activeServer: '', qnAddr: '', extkitSwitch: 0, alone: false, voipServer: '', offlinelogserver: '', backupServer: ((_a = this._customCMP) === null || _a === void 0 ? void 0 : _a.length) ? this._customCMP.join(',') : connectUrl }; setNaviInfo2Cache(this._appkey, token, _naviInfo, this._runtime.localStorage); return _context15.abrupt("return", _naviInfo); case 7: if (force) { this._clear(token); } naviInfo = getNaviInfoFromCache(this._appkey, token, this._runtime.localStorage); if (!naviInfo) { _context15.next = 11; break; } return _context15.abrupt("return", naviInfo); case 11: uris = this._navigators.slice(); dynamicUris.length && dynamicUris.forEach(function (uri) { _newArrowCheck(this, _this63); uris.indexOf(uri) < 0 && uris.push(uri); }.bind(this)); _context15.next = 15; return this._reqNavi(uris, this._appkey, token, this._connectType); case 15: naviInfo = _context15.sent; if (!naviInfo) { _context15.next = 19; break; } setNaviInfo2Cache(this._appkey, token, naviInfo, this._runtime.localStorage); return _context15.abrupt("return", naviInfo); case 19: return _context15.abrupt("return", naviInfo); case 20: case "end": return _context15.stop(); } } }, _callee13, this); })); } }, { key: "getInfoFromCache", value: function getInfoFromCache(token) { return getNaviInfoFromCache(this._appkey, token, this._runtime.localStorage); } }, { key: "_clear", value: function _clear(token) { clearCache(this._appkey, token, this._runtime.localStorage); } }]); return Navi; }(); var AEngine = function AEngine(runtime, _appkey, _watcher, _apiVersion, _options) { _classCallCheck(this, AEngine); this.runtime = runtime; this._appkey = _appkey; this._watcher = _watcher; this._apiVersion = _apiVersion; this._options = _options; this.currentUserId = ''; this.connectedTime = 0; }; var OUTBOX_KEY = 'outbox'; var INBOX_KEY = 'inbox'; var generateKey = function generateKey(prefix, appkey, userId) { _newArrowCheck(this, _this); return [prefix, appkey, userId].join('_'); }.bind(undefined); var Letterbox = function () { function Letterbox(_runtime, _appkey) { _classCallCheck(this, Letterbox); this._runtime = _runtime; this._appkey = _appkey; this._inboxTime = 0; this._outboxTime = 0; } _createClass(Letterbox, [{ key: "setInboxTime", value: function setInboxTime(timestamp, userId) { if (this._inboxTime > timestamp) { return; } this._inboxTime = timestamp; var key = generateKey(INBOX_KEY, this._appkey, userId); this._runtime.localStorage.setItem(key, timestamp.toString()); } }, { key: "getInboxTime", value: function getInboxTime(userId) { if (this._inboxTime === 0) { var _key10 = generateKey(INBOX_KEY, this._appkey, userId); this._inboxTime = parseInt(this._runtime.localStorage.getItem(_key10)) || 0; } return this._inboxTime; } }, { key: "setOutboxTime", value: function setOutboxTime(timestamp, userId) { if (this._outboxTime > timestamp) { return; } this._outboxTime = timestamp; var key = generateKey(OUTBOX_KEY, this._appkey, userId); this._runtime.localStorage.setItem(key, timestamp.toString()); } }, { key: "getOutboxTime", value: function getOutboxTime(userId) { if (this._outboxTime === 0) { var _key11 = generateKey(OUTBOX_KEY, this._appkey, userId); this._outboxTime = parseInt(this._runtime.localStorage.getItem(_key11)) || 0; } return this._outboxTime; } }]); return Letterbox; }(); var PullTimeCache = { _caches: {}, set: function set(chrmId, time) { this._caches[chrmId] = time; }, get: function get(chrmId) { return this._caches[chrmId] || 0; }, clear: function clear(chrmId) { this._caches[chrmId] = 0; } }; var KVStore = function () { function KVStore(chatroomId, currentUserId) { _classCallCheck(this, KVStore); this._kvCaches = {}; this._chatroomId = chatroomId; this._currentUserId = currentUserId; } _createClass(KVStore, [{ key: "_add", value: function _add(kv) { var key = kv.key; kv.isDeleted = false; this._kvCaches[key] = kv; } }, { key: "_remove", value: function _remove(kv) { var key = kv.key; var cacheKV = this._kvCaches[key]; cacheKV.isDeleted = true; this._kvCaches[key] = cacheKV; } }, { key: "_setEntry", value: function _setEntry(data, isFullUpdate) { var key = data.key, type = data.type, isOverwrite = data.isOverwrite, userId = data.userId; var latestUserId = this._getSetUserId(key); var isDeleteOpt = type === ChatroomEntryType$1.DELETE; var isSameAtLastSetUser = latestUserId === userId; var isKeyNotExist = !this._isExisted(key); var event = isDeleteOpt ? this._remove : this._add; if (isFullUpdate) { event.call(this, data); } else if (isOverwrite || isSameAtLastSetUser || isKeyNotExist) { event.call(this, data); } else ; } }, { key: "getValue", value: function getValue(key) { var kv = this._kvCaches[key] || {}; var isDeleted = kv.isDeleted; return isDeleted ? null : kv.value; } }, { key: "getAllValue", value: function getAllValue() { var entries = {}; for (var _key12 in this._kvCaches) { if (!this._kvCaches[_key12].isDeleted) { entries[_key12] = this._kvCaches[_key12].value; } } return entries; } }, { key: "_getSetUserId", value: function _getSetUserId(key) { var cache = this._kvCaches[key] || {}; return cache.userId; } }, { key: "_isExisted", value: function _isExisted(key) { var cache = this._kvCaches[key] || {}; var value = cache.value, isDeleted = cache.isDeleted; return value && !isDeleted; } }, { key: "setEntries", value: function setEntries(data) { var _this64 = this; var kvEntries = data.kvEntries, isFullUpdate = data.isFullUpdate; kvEntries = kvEntries || []; isFullUpdate = isFullUpdate || false; isFullUpdate && this.clear(); kvEntries.forEach(function (kv) { _newArrowCheck(this, _this64); this._setEntry(kv, isFullUpdate); }.bind(this)); } }, { key: "clear", value: function clear() { this._kvCaches = {}; } }]); return KVStore; }(); var ChrmEntryHandler = function () { function ChrmEntryHandler(engine) { _classCallCheck(this, ChrmEntryHandler); this._pullQueue = []; this._isPulling = false; this._storeCaches = {}; this._engine = engine; } _createClass(ChrmEntryHandler, [{ key: "_startPull", value: function _startPull() { return __awaiter$1(this, void 0, void 0, regeneratorRuntime.mark(function _callee14() { var _this$_pullQueue$spli, chrmId, timestamp, pulledUpTime, _yield$this$_engine$p, code, data; return regeneratorRuntime.wrap(function _callee14$(_context16) { while (1) { switch (_context16.prev = _context16.next) { case 0: if (!(this._isPulling || this._pullQueue.length === 0)) { _context16.next = 2; break; } return _context16.abrupt("return"); case 2: this._isPulling = true; _this$_pullQueue$spli = this._pullQueue.splice(0, 1)[0], chrmId = _this$_pullQueue$spli.chrmId, timestamp = _this$_pullQueue$spli.timestamp; pulledUpTime = PullTimeCache.get(chrmId); if (!(pulledUpTime > timestamp)) { _context16.next = 8; break; } this._isPulling = false; return _context16.abrupt("return"); case 8: _context16.next = 10; return this._engine.pullChatroomEntry(chrmId, timestamp); case 10: _yield$this$_engine$p = _context16.sent; code = _yield$this$_engine$p.code; data = _yield$this$_engine$p.data; if (code === ErrorCode$1.SUCCESS) { this._isPulling = false; PullTimeCache.set(chrmId, data.syncTime || 0); this._startPull(); } else { this._startPull(); } case 14: case "end": return _context16.stop(); } } }, _callee14, this); })); } }, { key: "reset", value: function reset(chrmId) { PullTimeCache.clear(chrmId); var kvStore = this._storeCaches[chrmId]; kvStore.clear(); } }, { key: "pullEntry", value: function pullEntry(chrmId, timestamp) { this._pullQueue.push({ chrmId: chrmId, timestamp: timestamp }); this._startPull(); } }, { key: "setLocal", value: function setLocal(chrmId, data, userId) { var kvStore = this._storeCaches[chrmId]; if (!notEmptyObject(kvStore)) { kvStore = new KVStore(chrmId, userId); } kvStore.setEntries(data); this._storeCaches[chrmId] = kvStore; } }, { key: "getValue", value: function getValue(chrmId, key) { var kvStore = this._storeCaches[chrmId]; return kvStore ? kvStore.getValue(key) : null; } }, { key: "getAll", value: function getAll(chrmId) { var kvStore = this._storeCaches[chrmId]; var entries = {}; if (kvStore) { entries = kvStore.getAllValue(); } return entries; } }]); return ChrmEntryHandler; }(); var JoinedChrmManager = function () { function JoinedChrmManager(_runtime, _appkey, _userId, _canJoinMulipleChrm) { _classCallCheck(this, JoinedChrmManager); this._runtime = _runtime; this._appkey = _appkey; this._userId = _userId; this._canJoinMulipleChrm = _canJoinMulipleChrm; this._sessionKey = ''; this._joinedChrmsInfo = {}; this._sessionKey = "sync-chrm-".concat(this._appkey, "-").concat(this._userId); } _createClass(JoinedChrmManager, [{ key: "set", value: function set(chrmId) { var count = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 10; !this._canJoinMulipleChrm && (this._joinedChrmsInfo = {}); this._joinedChrmsInfo[chrmId] = count; this._runtime.sessionStorage.setItem(this._sessionKey, JSON.stringify(this._joinedChrmsInfo)); } }, { key: "get", value: function get() { var infos; try { infos = this._runtime.sessionStorage.getItem(this._sessionKey); } catch (err) { logger.error('parse rejoined chrm infos error', err); infos = {}; } return infos; } }, { key: "remove", value: function remove(chrmId) { delete this._joinedChrmsInfo[chrmId]; if (notEmptyObject(this._joinedChrmsInfo)) { this._runtime.sessionStorage.setItem(this._sessionKey, JSON.stringify(this._joinedChrmsInfo)); } else { this.clear(); } } }, { key: "clear", value: function clear() { this._joinedChrmsInfo = {}; this._runtime.sessionStorage.removeItem(this._sessionKey); } }]); return JoinedChrmManager; }(); var EventDispatcher = function () { function EventDispatcher() { _classCallCheck(this, EventDispatcher); this._map = {}; } _createClass(EventDispatcher, [{ key: "on", value: function on(eventType, listener) { var arr = this._map[eventType] || (this._map[eventType] = []); if (arr.includes(listener)) { return; } arr.push(listener); } }, { key: "off", value: function off(eventType, listener) { var arr = this._map[eventType]; if (!arr) { return; } var len = arr.length; for (var i = len - 1; i >= 0; i -= 1) { if (arr[i] === listener) { arr.splice(i, 1); if (len === 1) { delete this._map[eventType]; } break; } } } }, { key: "emit", value: function emit(eventType, data) { var _this65 = this; var arr = this._map[eventType]; if (!arr) { return; } arr.forEach(function (item) { _newArrowCheck(this, _this65); return item(data); }.bind(this)); } }, { key: "removeAll", value: function removeAll(eventType) { delete this._map[eventType]; } }, { key: "clear", value: function clear() { Object.keys(this._map).forEach(this.removeAll, this); } }]); return EventDispatcher; }(); var EventName = { STATUS_CHANGED: 'converStatusChanged' }; var ConversationStatus = function () { function ConversationStatus(engine, appkey, currentUserId) { _classCallCheck(this, ConversationStatus); this._eventEmitter = new EventDispatcher(); this._pullQueue = []; this._isPulling = false; this._storage = createRootStorage(engine.runtime); this._appkey = appkey; this._currentUserId = currentUserId; this._engine = engine; this._storagePullTimeKey = "con-s-".concat(appkey, "-").concat(currentUserId); } _createClass(ConversationStatus, [{ key: "_set", value: function _set(list) { var _this66 = this; if (isUndefined(list)) { return; } var localTime = this._storage.get(this._storagePullTimeKey) || 0; var listCount = list.length; list.forEach(function (statusItem, index) { _newArrowCheck(this, _this66); var updatedTime = statusItem.updatedTime || 0; localTime = updatedTime > localTime ? updatedTime : localTime; statusItem.conversationType = statusItem.type; this._eventEmitter.emit(EventName.STATUS_CHANGED, { statusItem: statusItem, isLastPull: index === listCount - 1 }); }.bind(this)); this._storage.set(this._storagePullTimeKey, localTime); } }, { key: "_startPull", value: function _startPull() { return __awaiter$1(this, void 0, void 0, regeneratorRuntime.mark(function _callee15() { var time, _yield$this$_engine$p2, code, data; return regeneratorRuntime.wrap(function _callee15$(_context17) { while (1) { switch (_context17.prev = _context17.next) { case 0: if (!(this._isPulling || this._pullQueue.length === 0)) { _context17.next = 2; break; } return _context17.abrupt("return"); case 2: this._isPulling = true; time = this._pullQueue.splice(0, 1)[0]; _context17.next = 6; return this._engine.pullConversationStatus(time); case 6: _yield$this$_engine$p2 = _context17.sent; code = _yield$this$_engine$p2.code; data = _yield$this$_engine$p2.data; if (code === ErrorCode$1.SUCCESS) { this._isPulling = false; this._set(data); this._startPull(); } else { this._startPull(); } case 10: case "end": return _context17.stop(); } } }, _callee15, this); })); } }, { key: "pull", value: function pull(newPullTime) { var time = this._storage.get(this._storagePullTimeKey) || 0; if (newPullTime > time || newPullTime === 0) { this._pullQueue.push(time); this._startPull(); } } }, { key: "watch", value: function watch(event) { var _this67 = this; this._eventEmitter.on(EventName.STATUS_CHANGED, function (data) { _newArrowCheck(this, _this67); event(data); }.bind(this)); } }, { key: "unwatch", value: function unwatch() { var _this68 = this; this._eventEmitter.off(EventName.STATUS_CHANGED, function (data) { _newArrowCheck(this, _this68); }.bind(this)); } }]); return ConversationStatus; }(); var StorageKey2ConversationKey = { c: { keyName: 'unreadMessageCount', defaultVal: 0 }, hm: { keyName: 'hasMentioned', defaultVal: false }, m: { keyName: 'mentionedInfo', defaultVal: null }, t: { keyName: 'lastUnreadTime', defaultVal: 0 }, nc: { keyName: 'notificationStatus', defaultVal: 2 }, to: { keyName: 'isTop', defaultVal: false } }; var ConversationKey2StorageKey = {}; for (var _key13 in StorageKey2ConversationKey) { var keyName = StorageKey2ConversationKey[_key13].keyName; ConversationKey2StorageKey[keyName] = _key13; } var ConversationStore = function () { function ConversationStore(runtime, _appkey, _currentUserId) { _classCallCheck(this, ConversationStore); this._appkey = _appkey; this._currentUserId = _currentUserId; var suffix = "con-".concat(_appkey, "-").concat(_currentUserId); this.storage = new AppStorage(runtime, suffix); } _createClass(ConversationStore, [{ key: "_getStoreKey", value: function _getStoreKey(type, targetId) { return "".concat(type, "_").concat(targetId); } }, { key: "_getConOptionByKey", value: function _getConOptionByKey(key) { key = key || ''; var arr = key.split('_'); if (arr.length === 2) { return { conversationType: arr[0], targetId: arr[1] }; } else { return { conversationType: ConversationType$1.PRIVATE, targetId: '' }; } } }, { key: "updateMentionedData", value: function updateMentionedData(message) { var _this69 = this; var conversationType = message.conversationType, targetId = message.targetId, messageType = message.messageType, isMentioned = message.isMentioned, content = message.content, senderUserId = message.senderUserId; var key = this._getStoreKey(conversationType, targetId); var local = this.storage.get(key) || {}; var storageMetionedInfoKey = ConversationKey2StorageKey.mentionedInfo; var storageHasMentionedKey = ConversationKey2StorageKey.hasMentioned; var updatedUserIdList = []; var localMentionedInfo = local[storageMetionedInfoKey] || {}; var localUserIdList = localMentionedInfo.userIdList || []; var mentionedInfo = content.mentionedInfo; if (isMentioned && conversationType === ConversationType$1.GROUP && mentionedInfo.userIdList) { var receiveUserIdList = mentionedInfo.userIdList; var isNotIncludeSender = localUserIdList.indexOf(senderUserId) < 0; receiveUserIdList.forEach(function (userId) { _newArrowCheck(this, _this69); if (userId === this._currentUserId && isNotIncludeSender) { localUserIdList.push(senderUserId); } }.bind(this)); if (mentionedInfo.type === MentionedType$1.ALL && localUserIdList.indexOf(senderUserId) < 0) { localUserIdList.push(senderUserId); } updatedUserIdList = localUserIdList; } if (messageType === MessageType$1.RECALL && conversationType === ConversationType$1.GROUP) { var list = localUserIdList; localUserIdList.forEach(function (userId, index) { _newArrowCheck(this, _this69); if (userId === senderUserId) { list.splice(index, 1); } }.bind(this)); updatedUserIdList = list; } mentionedInfo = { userIdList: updatedUserIdList, type: mentionedInfo === null || mentionedInfo === void 0 ? void 0 : mentionedInfo.type }; if (updatedUserIdList.length !== 0) { local[storageMetionedInfoKey] = mentionedInfo; local[storageHasMentionedKey] = true; } else { delete local[storageMetionedInfoKey]; delete local[storageHasMentionedKey]; } if (notEmptyObject(local)) { this.storage.set(key, local); } else { this.storage.remove(key); } } }, { key: "set", value: function set(type, targetId, conversation) { var key = this._getStoreKey(type, targetId); var local = this.storage.get(key) || {}; for (var _key14 in conversation) { var storageKey = ConversationKey2StorageKey[_key14]; var val = conversation[_key14]; if (isUndefined(storageKey) || isUndefined(val) || _key14 === 'hasMentioned' || _key14 === 'MentionedInfo') { continue; } var defaultVal = StorageKey2ConversationKey[storageKey].defaultVal; if (val === defaultVal) { delete local[storageKey]; } else { local[storageKey] = val; } if (!local.c) { delete local.t; } } if (notEmptyObject(local)) { this.storage.set(key, local); } else { this.storage.remove(key); } } }, { key: "get", value: function get(type, targetId) { var key = this._getStoreKey(type, targetId); var local = this.storage.get(key) || {}; var conversation = {}; for (var _key15 in StorageKey2ConversationKey) { var _StorageKey2Conversat = StorageKey2ConversationKey[_key15], _keyName = _StorageKey2Conversat.keyName, defaultVal = _StorageKey2Conversat.defaultVal; conversation[_keyName] = local[_key15] || defaultVal; } return conversation; } }, { key: "getValue", value: function getValue(func) { var values = this.storage.getValues() || {}; var storageConversationList = []; for (var _key16 in values) { var _this$_getConOptionBy = this._getConOptionByKey(_key16), conversationType = _this$_getConOptionBy.conversationType, targetId = _this$_getConOptionBy.targetId; var conversation = {}; var store = values[_key16]; for (var storeKey in store) { var _StorageKey2Conversat2 = StorageKey2ConversationKey[storeKey], _keyName2 = _StorageKey2Conversat2.keyName, defaultVal = _StorageKey2Conversat2.defaultVal; conversation[_keyName2] = store[storeKey] || defaultVal; } conversation = Object.assign(conversation, { conversationType: conversationType, targetId: targetId }); conversation = func ? func(conversation) : conversation; storageConversationList.push(conversation); } return storageConversationList; } }]); return ConversationStore; }(); var saveConversationType = [ConversationType$1.PRIVATE, ConversationType$1.GROUP, ConversationType$1.SYSTEM]; var EventName$1 = { CHANGED: 'conversationChanged' }; var ConversationManager = function () { function ConversationManager(engine, appkey, userId, updatedConversationFunc) { var _this70 = this; _classCallCheck(this, ConversationManager); this._updatedConversations = {}; this._eventEmitter = new EventDispatcher(); this._draftMap = {}; this._appkey = appkey; this._loginUserId = userId; this._store = new ConversationStore(engine.runtime, appkey, userId); this._statusManager = new ConversationStatus(engine, appkey, userId); this._statusManager.watch(function (data) { _newArrowCheck(this, _this70); var statusItem = data.statusItem, isLastPull = data.isLastPull; this.addStatus(statusItem, isLastPull); }.bind(this)); this._eventEmitter.on(EventName$1.CHANGED, function (data) { _newArrowCheck(this, _this70); updatedConversationFunc(data); }.bind(this)); } _createClass(ConversationManager, [{ key: "_calcUnreadCount", value: function _calcUnreadCount(message, localConversation) { var content = message.content, messageType = message.messageType, sentTime = message.sentTime, isCounted = message.isCounted, messageDirection = message.messageDirection, senderUserId = message.senderUserId; var isSelfSend = messageDirection === MessageDirection$1.SEND && senderUserId === this._loginUserId; var isRecall = messageType === MessageType$1.RECALL; var hasContent = isObject(content); var hasChanged = false; var lastUnreadTime = localConversation.lastUnreadTime || 0; var unreadMessageCount = localConversation.unreadMessageCount || 0; var hasBeenAdded = lastUnreadTime > sentTime; if (hasBeenAdded || isSelfSend) { return { hasChanged: hasChanged, localConversation: localConversation }; } if (isCounted) { localConversation.unreadMessageCount = unreadMessageCount + 1; localConversation.lastUnreadTime = sentTime; hasChanged = true; } if (isRecall && hasContent) { var isNotRead = lastUnreadTime >= content.sentTime; if (isNotRead && unreadMessageCount) { localConversation.unreadMessageCount = unreadMessageCount - 1; hasChanged = true; } } return { hasChanged: hasChanged, localConversation: localConversation }; } }, { key: "_calcMentionedInfo", value: function _calcMentionedInfo(message, localConversation) { var content = message.content, messageDirection = message.messageDirection, isMentioned = message.isMentioned; var isSelfSend = messageDirection === MessageDirection$1.SEND; var hasContent = isObject(content); var hasChanged = false; if (isMentioned && hasContent && content.mentionedInfo) { localConversation.hasMentioned = true; // localConversation.mentionedInfo = content.mentionedInfo; hasChanged = true; } return { hasChanged: hasChanged, localConversation: localConversation }; } }, { key: "_setUpdatedConversation", value: function _setUpdatedConversation(updatedConOptions) { if (isObject(updatedConOptions)) { var conversationType = updatedConOptions.conversationType, targetId = updatedConOptions.targetId; var _key17 = "".concat(conversationType, "_").concat(targetId); var cacheConversation = this._store.get(conversationType, targetId) || {}; this._updatedConversations[_key17] = Object.assign(cacheConversation, updatedConOptions); } } }, { key: "addStatus", value: function addStatus(statusItem, isLastPull) { var conversationType = statusItem.conversationType, targetId = statusItem.targetId, updatedTime = statusItem.updatedTime, notificationStatus = statusItem.notificationStatus, isTop = statusItem.isTop; var updatedItems = {}; if (!isUndefined(notificationStatus)) { updatedItems.notificationStatus = { time: updatedTime, val: notificationStatus }; } if (!isUndefined(isTop)) { updatedItems.isTop = { time: updatedTime, val: isTop }; } this._store.set(conversationType, targetId, { notificationStatus: notificationStatus, isTop: isTop }); this._setUpdatedConversation({ conversationType: conversationType, targetId: targetId, updatedItems: updatedItems }); if (isLastPull) { this._notifyConversationChanged(); } } }, { key: "_notifyConversationChanged", value: function _notifyConversationChanged() { var list = []; for (var _key18 in this._updatedConversations) { list.push(this._updatedConversations[_key18]); } this._eventEmitter.emit(EventName$1.CHANGED, list); this._updatedConversations = {}; } }, { key: "setConversationCacheByMessage", value: function setConversationCacheByMessage(message, isPullMessageFinished) { var _this71 = this; var conversationType = message.conversationType, isPersited = message.isPersited, targetId = message.targetId; var isSaveConversationType = saveConversationType.indexOf(conversationType) >= 0; if (!isSaveConversationType) { return; } var hasChanged = false; var storageConversation = this._store.get(conversationType, targetId); var CalcEvents = [this._calcUnreadCount, this._calcMentionedInfo]; CalcEvents.forEach(function (func) { _newArrowCheck(this, _this71); var _func$call = func.call(this, message, storageConversation), hasCaclChanged = _func$call.hasChanged, localConversation = _func$call.localConversation; hasChanged = hasChanged || hasCaclChanged; storageConversation = cloneByJSON(localConversation); }.bind(this)); if (hasChanged) { this._store.set(conversationType, targetId, storageConversation); } this._store.updateMentionedData(message); if (isPersited) { var conversation = this._store.get(conversationType, targetId); conversation.updatedItems = { latestMessage: { time: message.sentTime, val: message } }; conversation.latestMessage = message; var updateConOptions = Object.assign(conversation, { conversationType: conversationType, targetId: targetId }); this._setUpdatedConversation(updateConOptions); } if (isPullMessageFinished) { this._notifyConversationChanged(); } } }, { key: "get", value: function get(conversationType, targetId) { return this._store.get(conversationType, targetId); } }, { key: "getAllUnreadCount", value: function getAllUnreadCount() { var _this72 = this; var conversationList = this._store.getValue(); var totalCount = 0; conversationList.forEach(function (_ref) { _newArrowCheck(this, _this72); var unreadMessageCount = _ref.unreadMessageCount; unreadMessageCount = unreadMessageCount || 0; totalCount += Number(unreadMessageCount); }.bind(this)); return totalCount; } }, { key: "getUnreadCount", value: function getUnreadCount(conversationType, targetId) { var conversation = this._store.get(conversationType, targetId); return conversation.unreadMessageCount || 0; } }, { key: "clearUnreadCount", value: function clearUnreadCount(conversationType, targetId) { var conversation = this._store.get(conversationType, targetId); var unreadMessageCount = conversation.unreadMessageCount, hasMentioned = conversation.hasMentioned; if (unreadMessageCount || hasMentioned) { conversation.unreadMessageCount = 0; conversation.hasMentioned = false; } this._store.set(conversationType, targetId, conversation); var updateConOptions = Object.assign(conversation, { conversationType: conversationType, targetId: targetId }); this._setUpdatedConversation(updateConOptions); this._notifyConversationChanged(); } }, { key: "startPullConversationStatus", value: function startPullConversationStatus(time) { this._statusManager.pull(time); } }, { key: "setDraft", value: function setDraft(conversationType, targetId, draft) { var key = "".concat(conversationType, "_").concat(targetId); this._draftMap[key] = draft; } }, { key: "getDraft", value: function getDraft(conversationType, targetId) { var key = "".concat(conversationType, "_").concat(targetId); return this._draftMap[key]; } }, { key: "clearDraft", value: function clearDraft(conversationType, targetId) { var key = "".concat(conversationType, "_").concat(targetId); delete this._draftMap[key]; } }]); return ConversationManager; }(); var UploadMethod; (function (UploadMethod) { UploadMethod[UploadMethod["QINIU"] = 1] = "QINIU"; UploadMethod[UploadMethod["ALI"] = 2] = "ALI"; })(UploadMethod || (UploadMethod = {})); var UploadMethod$1 = UploadMethod; var getUploadFileName = function getUploadFileName(type, fileName) { _newArrowCheck(this, _this); var random = Math.floor(Math.random() * 1000 % 10000); var uuid = getUUID(); var date = formatDate(); var timestamp = new Date().getTime(); var extension = ''; if (fileName) { var fileNameArr = fileName.split('.'); extension = '.' + fileNameArr[fileNameArr.length - 1]; } return "".concat(type, "__RC-").concat(date, "_").concat(random, "_").concat(timestamp).concat(uuid).concat(extension); }.bind(undefined); var getMimeKey = function getMimeKey(fileType) { _newArrowCheck(this, _this); var mimeKey = 'application/octet-stream'; switch (fileType) { case FileType$1.IMAGE: mimeKey = 'image/jpeg'; break; case FileType$1.AUDIO: mimeKey = 'audio/amr'; break; case FileType$1.VIDEO: mimeKey = 'video/3gpp'; break; case FileType$1.SIGHT: mimeKey = 'video/mpeg4'; break; case FileType$1.COMBINE_HTML: mimeKey = 'text/html'; break; } return mimeKey; }.bind(undefined); var pushConfigsToJSON = function pushConfigsToJSON() { var iOSConfig = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var androidConfig = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var threadId = iOSConfig.threadId, apnsCollapseId = iOSConfig.apnsCollapseId; var channelIdMi = androidConfig.channelIdMi, channelIdHW = androidConfig.channelIdHW, channelIdOPPO = androidConfig.channelIdOPPO, typeVivo = androidConfig.typeVivo; var APNS = {}; APNS['thread-id'] = threadId || ''; APNS['apns-collapse-id'] = apnsCollapseId || ''; var pushCongfigs = [{ HW: { channelId: channelIdHW || '' } }, { MI: { channelId: channelIdMi || '' } }, { OPPO: { channelId: channelIdOPPO || '' } }, { VIVO: { classification: typeVivo || '' } }, { APNS: APNS }]; return JSON.stringify(pushCongfigs); }; var getPubTopic = function getPubTopic(type) { var _ConversationType$1$P; _newArrowCheck(this, _this); return (_ConversationType$1$P = {}, _defineProperty(_ConversationType$1$P, ConversationType$1.PRIVATE, Topic$1.ppMsgP), _defineProperty(_ConversationType$1$P, ConversationType$1.GROUP, Topic$1.pgMsgP), _defineProperty(_ConversationType$1$P, ConversationType$1.CHATROOM, Topic$1.chatMsg), _defineProperty(_ConversationType$1$P, ConversationType$1.CUSTOMER_SERVICE, Topic$1.pcMsgP), _defineProperty(_ConversationType$1$P, ConversationType$1.RTC_ROOM, Topic$1.prMsgS), _ConversationType$1$P)[type]; }.bind(undefined); var getStatPubTopic = function getStatPubTopic(type) { var _ConversationType$1$P2; _newArrowCheck(this, _this); return (_ConversationType$1$P2 = {}, _defineProperty(_ConversationType$1$P2, ConversationType$1.PRIVATE, Topic$1.ppMsgS), _defineProperty(_ConversationType$1$P2, ConversationType$1.GROUP, Topic$1.pgMsgS), _ConversationType$1$P2)[type]; }.bind(undefined); var transSentAttrs2IReceivedMessage = function transSentAttrs2IReceivedMessage(conversationType, targetId, options, messageUId, sentTime, senderUserId) { _newArrowCheck(this, _this); return { conversationType: conversationType, targetId: targetId, senderUserId: senderUserId, messageDirection: MessageDirection$1.SEND, isCounted: !!options.isCounted, isMentioned: !!options.isMentioned, content: options.content, messageType: options.messageType, isOffLineMessage: false, isPersited: !!options.isPersited, messageUId: messageUId, sentTime: sentTime, receivedTime: 0, disableNotification: !!options.disableNotification, isStatusMessage: !!options.isStatusMessage, canIncludeExpansion: !!options.canIncludeExpansion, expansion: options.canIncludeExpansion ? options.expansion : null, receivedStatus: ReceivedStatus$1.UNREAD }; }.bind(undefined); var JSEngine = function (_AEngine) { _inherits(JSEngine, _AEngine); var _super18 = _createSuper(JSEngine); function JSEngine(runtime, appkey, watcher, apiVersion) { var _this73; _classCallCheck(this, JSEngine); _this73 = _super18.call(this, runtime, appkey, watcher, apiVersion, {}); _this73._customMessageType = {}; _this73._pullingMsg = false; _this73._pullQueue = []; _this73._chrmsQueue = {}; _this73._letterbox = new Letterbox(runtime, appkey); _this73._chrmEntryHandler = new ChrmEntryHandler(_assertThisInitialized(_this73)); return _this73; } _createClass(JSEngine, [{ key: "connect", value: function connect(token, naviInfo, connectType) { return __awaiter$1(this, void 0, void 0, regeneratorRuntime.mark(function _callee16() { var _this74 = this; var hosts, backupServer, channel, code; return regeneratorRuntime.wrap(function _callee16$(_context18) { while (1) { switch (_context18.prev = _context18.next) { case 0: hosts = []; this._naviInfo = naviInfo; if (naviInfo.server) { hosts.push(naviInfo.server); } else { logger.warn('navi.server is invalid'); } backupServer = naviInfo.backupServer; backupServer && backupServer.split(',').forEach(function (host) { _newArrowCheck(this, _this74); if (hosts.indexOf(host) < 0) { hosts.push(host); } }.bind(this)); if (!(hosts.length === 0)) { _context18.next = 8; break; } logger.error('navi invaild.', hosts); return _context18.abrupt("return", ErrorCode$1.UNKNOWN); case 8: channel = this.runtime.createDataChannel({ status: function status(_status) { _newArrowCheck(this, _this74); this._connectionStatusHandler(_status, token, hosts, naviInfo.protocol); }.bind(this), signal: this._signalHandler.bind(this) }, connectType); _context18.next = 11; return channel.connect(this._appkey, token, hosts, naviInfo.protocol, this._apiVersion); case 11: code = _context18.sent; if (code === ErrorCode$1.SUCCESS) { this._channel = channel; this.currentUserId = channel.userId; this.connectedTime = channel.connectedTime; this._conversationManager = new ConversationManager(this, this._appkey, this.currentUserId, this._watcher.conversation); this._conversationManager.startPullConversationStatus(0); this._joinedChrmManager = new JoinedChrmManager(this.runtime, this._appkey, this.currentUserId, naviInfo.joinMChrm); this._syncMsg(); } else { channel.close(); } return _context18.abrupt("return", code); case 14: case "end": return _context18.stop(); } } }, _callee16, this); })); } }, { key: "_connectionStatusHandler", value: function _connectionStatusHandler(status, token, hosts, protocol) { logger.warn('connection status changed:', status); if (status === ConnectionStatus$1.CONNECTING || status === ConnectionStatus$1.CONNECTED) { this._watcher.status(status); return; } if (!this._channel || status === ConnectionStatus$1.DISCONNECTED) { this._watcher.status(status); return; } if (status === ConnectionStatus$1.BLOCKED || status === ConnectionStatus$1.KICKED_OFFLINE_BY_OTHER_CLIENT) { this.disconnect(); this._watcher.status(status); return; } this._try2Reconnect(token, hosts, protocol); } }, { key: "_try2Reconnect", value: function _try2Reconnect(token, hosts, protocol) { return __awaiter$1(this, void 0, void 0, regeneratorRuntime.mark(function _callee17() { var _this75 = this; var code; return regeneratorRuntime.wrap(function _callee17$(_context19) { while (1) { switch (_context19.prev = _context19.next) { case 0: if (this._channel) { _context19.next = 2; break; } return _context19.abrupt("return"); case 2: _context19.next = 4; return this._channel.connect(this._appkey, token, hosts, protocol, this._apiVersion); case 4: code = _context19.sent; if (!(code === ErrorCode$1.SUCCESS)) { _context19.next = 8; break; } this._rejoinChrm(); return _context19.abrupt("return"); case 8: this._watcher.status(ConnectionStatus$1.WEBSOCKET_UNAVAILABLE); setTimeout(function () { _newArrowCheck(this, _this75); this._try2Reconnect(token, hosts, protocol); }.bind(this), 5000); case 10: case "end": return _context19.stop(); } } }, _callee17, this); })); } }, { key: "_signalHandler", value: function _signalHandler(signal, ack) { var syncMsg = signal.syncMsg, topic = signal.topic; if (syncMsg) { this._receiveSyncMsg(signal, ack); return; } var tmpTopic = Topic$1[topic]; if (!tmpTopic) { logger.error('unknown topic:', topic); return; } switch (tmpTopic) { case Topic$1.s_ntf: this._pullMsg(signal); break; case Topic$1.s_msg: this._receiveMsg(signal); break; case Topic$1.s_cmd: this._receiveStateNotify(signal); break; case Topic$1.s_us: this._receiveSettingNotify(signal); break; } } }, { key: "_receiveStateNotify", value: function _receiveStateNotify(signal) { var _a; var _ref2 = (_a = this._channel) === null || _a === void 0 ? void 0 : _a.codec.decodeByPBName(signal.data, PBName.NotifyMsg), time = _ref2.time, type = _ref2.type, chrmId = _ref2.chrmId; switch (type) { case 2: logger.warn('server notify chrm:', chrmId, time); this._chrmEntryHandler.pullEntry(chrmId, time); break; case 3: this._conversationManager.startPullConversationStatus(time); break; } } }, { key: "_receiveSettingNotify", value: function _receiveSettingNotify(signal) {} }, { key: "_receiveMessageExpansion", value: function _receiveMessageExpansion(message) { var content = message.content; var put = content.put, del = content.del, mid = content.mid; if (put) { this._watcher.expansion({ updatedExpansion: { messageUId: mid, expansion: put } }); } if (del) { this._watcher.expansion({ deletedExpansion: { messageUId: mid, deletedKeys: del } }); } } }, { key: "_receiveSyncMsg", value: function _receiveSyncMsg(signal, ack) { var _a; var msg = (_a = this._channel) === null || _a === void 0 ? void 0 : _a.codec.decodeByPBName(signal.data, PBName.UpStreamMessage, { currentUserId: this.currentUserId, signal: signal }); msg = this._handleMsgProperties(msg); msg.sentTime = ack.timestamp; msg.messageUId = ack.messageUId; if (this._pullingMsg) { this._pullQueue.push(ack.timestamp); return; } this._letterbox.setOutboxTime(ack.timestamp, this.currentUserId); if (msg.messageType === MessageType$1.EXPANSION_NOTIFY) { this._receiveMessageExpansion(msg); return; } this._watcher.message(msg); this._conversationManager.setConversationCacheByMessage(msg, true); } }, { key: "_pullMsg", value: function _pullMsg(signal) { if (!this._channel) { return; } var _this$_channel$codec$ = this._channel.codec.decodeByPBName(signal.data, PBName.NotifyMsg), type = _this$_channel$codec$.type, chrmId = _this$_channel$codec$.chrmId, time = _this$_channel$codec$.time; if (type === 2) { var info = this._chrmsQueue[chrmId]; info.queue.push(time); this._pullChrmMsg(chrmId); } else { this._pullQueue.push(time); this._syncMsg(); } } }, { key: "_syncMsg", value: function _syncMsg() { return __awaiter$1(this, void 0, void 0, regeneratorRuntime.mark(function _callee18() { var _this76 = this, _this$_pullQueue; var outboxTime, inboxTime, reqBody, writer, _yield$this$_channel$, code, data, list, finished, syncTime, newOutboxTime, tmpPullQueue; return regeneratorRuntime.wrap(function _callee18$(_context20) { while (1) { switch (_context20.prev = _context20.next) { case 0: if (!this._pullingMsg) { _context20.next = 2; break; } return _context20.abrupt("return"); case 2: if (this._channel) { _context20.next = 5; break; } this._pullingMsg = false; return _context20.abrupt("return"); case 5: this._pullingMsg = true; outboxTime = this._letterbox.getOutboxTime(this.currentUserId); inboxTime = this._letterbox.getInboxTime(this.currentUserId); logger.warn('outboxTime', outboxTime); logger.warn('inboxTime', inboxTime); reqBody = this._channel.codec.encodeSyncMsg({ sendboxTime: outboxTime, inboxTime: inboxTime }); writer = new QueryWriter(Topic$1[Topic$1.pullMsg], reqBody, this.currentUserId); _context20.next = 14; return this._channel.send(writer, PBName.DownStreamMessages, { connectedTime: this._channel.connectedTime, currentUserId: this.currentUserId }); case 14: _yield$this$_channel$ = _context20.sent; code = _yield$this$_channel$.code; data = _yield$this$_channel$.data; if (!(code !== ErrorCode$1.SUCCESS || !data)) { _context20.next = 21; break; } logger.warn('Pull msg failed, code:', code, ', data: ', data); this._pullingMsg = false; return _context20.abrupt("return"); case 21: list = data.list, finished = data.finished, syncTime = data.syncTime; newOutboxTime = 0; list.forEach(function (item) { _newArrowCheck(this, _this76); if (item.messageDirection === MessageDirection$1.SEND) { newOutboxTime = Math.max(item.sentTime, newOutboxTime); } if (item.messageType === MessageType$1.EXPANSION_NOTIFY) { this._receiveMessageExpansion(item); return; } this._watcher.message(item); this._conversationManager.setConversationCacheByMessage(item, true); }.bind(this)); this._letterbox.setInboxTime(syncTime, this.currentUserId); this._letterbox.setOutboxTime(newOutboxTime, this.currentUserId); this._pullingMsg = false; tmpPullQueue = this._pullQueue.filter(function (timestamp) { _newArrowCheck(this, _this76); return timestamp > syncTime; }.bind(this)); this._pullQueue.length = 0; (_this$_pullQueue = this._pullQueue).push.apply(_this$_pullQueue, _toConsumableArray(tmpPullQueue)); if (!finished || tmpPullQueue.length > 0) { this._syncMsg(); } case 31: case "end": return _context20.stop(); } } }, _callee18, this); })); } }, { key: "_receiveMsg", value: function _receiveMsg(signal) { if (!this._channel) { return; } var msg = this._channel.codec.decodeByPBName(signal.data, PBName.DownStreamMessage, { currentUserId: this.currentUserId, connectedTime: this._channel.connectedTime }); msg = this._handleMsgProperties(msg); if (this._pullingMsg) { return; } this._letterbox.setInboxTime(msg.sentTime, this.currentUserId); if (msg.messageType === MessageType$1.EXPANSION_NOTIFY) { this._receiveMessageExpansion(msg); return; } this._watcher.message(msg); this._conversationManager.setConversationCacheByMessage(msg, true); } }, { key: "_handleMsgProperties", value: function _handleMsgProperties(msgOptions) { var isSendMsg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; var messageType = msgOptions.messageType, isCounted = msgOptions.isCounted, isPersited = msgOptions.isPersited, isStatusMessage = msgOptions.isStatusMessage; var options; var inRCMessageType = (messageType in SEND_MESSAGE_TYPE_OPTION); var inCustomMessageType = (messageType in this._customMessageType); if (inRCMessageType) { options = SEND_MESSAGE_TYPE_OPTION[messageType]; } else if (inCustomMessageType) { options = this._customMessageType[messageType]; } else { options = { isCounted: isNull(isCounted) ? false : isCounted, isPersited: isNull(isPersited) ? false : isPersited }; } Object.assign(msgOptions, { isCounted: options.isCounted, isPersited: options.isPersited, isStatusMessage: !(msgOptions.isCounted && msgOptions.isPersited) }); isSendMsg && (msgOptions.isStatusMessage = isStatusMessage); return msgOptions; } }, { key: "getConnectTime", value: function getConnectTime() { if (this._channel) { return Promise.resolve({ code: ErrorCode$1.SUCCESS, data: this._channel.connectedTime }); } return Promise.resolve({ code: ErrorCode$1.RC_NET_CHANNEL_INVALID }); } }, { key: "getHistoryMessage", value: function getHistoryMessage(conversationType, targetId, timestamp, count, order) { return __awaiter$1(this, void 0, void 0, regeneratorRuntime.mark(function _callee19() { var currentUserId, channel, hisTopic, data, resp, code, downstreamData; return regeneratorRuntime.wrap(function _callee19$(_context21) { while (1) { switch (_context21.prev = _context21.next) { case 0: currentUserId = this.currentUserId, channel = this._channel; hisTopic = ConversationTypeToQueryHistoryTopic[conversationType] || QueryHistoryTopic.PRIVATE; if (!channel) { _context21.next = 12; break; } data = channel.codec.encodeGetHistoryMsg(targetId, { timestamp: timestamp, count: count, order: order }); _context21.next = 6; return channel.send(new QueryWriter(hisTopic, data, currentUserId), PBName.HistoryMsgOuput, { currentUserId: currentUserId, connectedTime: channel.connectedTime, conversation: { targetId: targetId } }); case 6: resp = _context21.sent; code = resp.code; if (!(code !== ErrorCode$1.SUCCESS)) { _context21.next = 10; break; } return _context21.abrupt("return", { code: code }); case 10: downstreamData = resp.data; return _context21.abrupt("return", { code: code, data: { list: downstreamData.list, hasMore: downstreamData.hasMore } }); case 12: return _context21.abrupt("return", { code: ErrorCode$1.RC_NET_CHANNEL_INVALID }); case 13: case "end": return _context21.stop(); } } }, _callee19, this); })); } }, { key: "deleteRemoteMessage", value: function deleteRemoteMessage(conversationType, targetId, list) { return __awaiter$1(this, void 0, void 0, regeneratorRuntime.mark(function _callee20() { var currentUserId, channel, data, writer, resp, code; return regeneratorRuntime.wrap(function _callee20$(_context22) { while (1) { switch (_context22.prev = _context22.next) { case 0: currentUserId = this.currentUserId, channel = this._channel; if (!channel) { _context22.next = 11; break; } data = channel.codec.encodeDeleteMessages(conversationType, targetId, list); writer = new QueryWriter(QueryTopic.DELETE_MESSAGES, data, currentUserId); _context22.next = 6; return channel.send(writer); case 6: resp = _context22.sent; code = resp.code; if (!(code !== ErrorCode$1.SUCCESS)) { _context22.next = 10; break; } return _context22.abrupt("return", code); case 10: return _context22.abrupt("return", code); case 11: return _context22.abrupt("return", ErrorCode$1.RC_NET_CHANNEL_INVALID); case 12: case "end": return _context22.stop(); } } }, _callee20, this); })); } }, { key: "deleteRemoteMessageByTimestamp", value: function deleteRemoteMessageByTimestamp(conversationType, targetId, timestamp) { return __awaiter$1(this, void 0, void 0, regeneratorRuntime.mark(function _callee21() { var currentUserId, channel, data, topic, writer, resp, code; return regeneratorRuntime.wrap(function _callee21$(_context23) { while (1) { switch (_context23.prev = _context23.next) { case 0: currentUserId = this.currentUserId, channel = this._channel; if (!channel) { _context23.next = 12; break; } data = channel.codec.encodeClearMessages(targetId, timestamp); topic = ConversationTypeToClearMessageTopic[conversationType]; writer = new QueryWriter(topic, data, currentUserId); _context23.next = 7; return channel.send(writer); case 7: resp = _context23.sent; code = resp.code; if (!(code !== ErrorCode$1.SUCCESS)) { _context23.next = 11; break; } return _context23.abrupt("return", code); case 11: return _context23.abrupt("return", code); case 12: return _context23.abrupt("return", ErrorCode$1.RC_NET_CHANNEL_INVALID); case 13: case "end": return _context23.stop(); } } }, _callee21, this); })); } }, { key: "getConversationList", value: function getConversationList() { var count = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 300; var conversationType = arguments.length > 1 ? arguments[1] : undefined; var startTime = arguments.length > 2 ? arguments[2] : undefined; var order = arguments.length > 3 ? arguments[3] : undefined; return __awaiter$1(this, void 0, void 0, regeneratorRuntime.mark(function _callee22() { var _this77 = this; var currentUserId, channel, buff, writer, resp, code, data; return regeneratorRuntime.wrap(function _callee22$(_context24) { while (1) { switch (_context24.prev = _context24.next) { case 0: currentUserId = this.currentUserId, channel = this._channel; conversationType = conversationType || ConversationType$1.PRIVATE; if (!channel) { _context24.next = 13; break; } buff = channel.codec.encodeOldConversationList({ count: count, type: conversationType, startTime: startTime, order: order }); writer = new QueryWriter(QueryTopic.GET_OLD_CONVERSATION_LIST, buff, currentUserId); _context24.next = 7; return channel.send(writer, PBName.RelationsOutput, { currentUserId: currentUserId, connectedTime: channel.connectedTime, afterDecode: function afterDecode(conversation) { _newArrowCheck(this, _this77); var conversationType = conversation.conversationType, targetId = conversation.targetId; var localConversation = this._conversationManager.get(conversationType, targetId); Object.assign(conversation, localConversation); return conversation; }.bind(this) }); case 7: resp = _context24.sent; logger.info('GetConversationList =>', resp); code = resp.code, data = resp.data; if (!(code !== ErrorCode$1.SUCCESS)) { _context24.next = 12; break; } return _context24.abrupt("return", { code: code }); case 12: return _context24.abrupt("return", { code: code, data: data }); case 13: return _context24.abrupt("return", { code: ErrorCode$1.RC_NET_CHANNEL_INVALID }); case 14: case "end": return _context24.stop(); } } }, _callee22, this); })); } }, { key: "removeConversation", value: function removeConversation(conversationType, targetId) { return __awaiter$1(this, void 0, void 0, regeneratorRuntime.mark(function _callee23() { var channel, data, writer, resp, code; return regeneratorRuntime.wrap(function _callee23$(_context25) { while (1) { switch (_context25.prev = _context25.next) { case 0: channel = this._channel; if (!channel) { _context25.next = 12; break; } data = channel.codec.encodeOldConversationList({ type: conversationType }); writer = new QueryWriter(QueryTopic.REMOVE_OLD_CONVERSATION, data, targetId); _context25.next = 6; return channel.send(writer); case 6: resp = _context25.sent; logger.info('RemoveConversation =>', resp); code = resp.code; if (!(code !== ErrorCode$1.SUCCESS)) { _context25.next = 11; break; } return _context25.abrupt("return", code); case 11: return _context25.abrupt("return", code); case 12: return _context25.abrupt("return", ErrorCode$1.RC_NET_CHANNEL_INVALID); case 13: case "end": return _context25.stop(); } } }, _callee23, this); })); } }, { key: "getConversation", value: function getConversation(conversationType, targetId) { throw new Error('Method not implemented.'); } }, { key: "getAllConversationUnreadCount", value: function getAllConversationUnreadCount() { var allUnreadCount = this._conversationManager.getAllUnreadCount(); return Promise.resolve({ code: ErrorCode$1.SUCCESS, data: allUnreadCount }); } }, { key: "getConversationUnreadCount", value: function getConversationUnreadCount(conversationType, targetId) { var unreadCount = this._conversationManager.getUnreadCount(conversationType, targetId); return Promise.resolve({ code: ErrorCode$1.SUCCESS, data: unreadCount }); } }, { key: "clearConversationUnreadCount", value: function clearConversationUnreadCount(conversationType, targetId) { this._conversationManager.clearUnreadCount(conversationType, targetId); return Promise.resolve(ErrorCode$1.SUCCESS); } }, { key: "saveConversationMessageDraft", value: function saveConversationMessageDraft(conversationType, targetId, draft) { this._conversationManager.setDraft(conversationType, targetId, draft); return Promise.resolve(ErrorCode$1.SUCCESS); } }, { key: "getConversationMessageDraft", value: function getConversationMessageDraft(conversationType, targetId) { var draft = this._conversationManager.getDraft(conversationType, targetId); return Promise.resolve({ code: ErrorCode$1.SUCCESS, data: draft }); } }, { key: "clearConversationMessageDraft", value: function clearConversationMessageDraft(conversationType, targetId) { this._conversationManager.clearDraft(conversationType, targetId); return Promise.resolve(ErrorCode$1.SUCCESS); } }, { key: "pullConversationStatus", value: function pullConversationStatus(timestamp) { return __awaiter$1(this, void 0, void 0, regeneratorRuntime.mark(function _callee24() { var channel, currentUserId, buff, writer, resp, code, data; return regeneratorRuntime.wrap(function _callee24$(_context26) { while (1) { switch (_context26.prev = _context26.next) { case 0: channel = this._channel, currentUserId = this.currentUserId; if (!channel) { _context26.next = 11; break; } buff = channel.codec.encodeGetConversationStatus(timestamp); writer = new QueryWriter(Topic$1[Topic$1.pullSeAtts], buff, currentUserId); _context26.next = 6; return channel.send(writer, PBName.SessionStates); case 6: resp = _context26.sent; code = resp.code, data = resp.data; if (!(code !== ErrorCode$1.SUCCESS)) { _context26.next = 10; break; } return _context26.abrupt("return", { code: code }); case 10: return _context26.abrupt("return", { code: code, data: data }); case 11: return _context26.abrupt("return", { code: ErrorCode$1.RC_NET_CHANNEL_INVALID }); case 12: case "end": return _context26.stop(); } } }, _callee24, this); })); } }, { key: "batchSetConversationStatus", value: function batchSetConversationStatus(statusList) { return __awaiter$1(this, void 0, void 0, regeneratorRuntime.mark(function _callee25() { var _this78 = this; var currentUserId, channel, buff, writer, resp, code, data, versionData; return regeneratorRuntime.wrap(function _callee25$(_context27) { while (1) { switch (_context27.prev = _context27.next) { case 0: currentUserId = this.currentUserId, channel = this._channel; if (!channel) { _context27.next = 13; break; } buff = channel.codec.encodeSetConversationStatus(statusList); writer = new QueryWriter(QueryTopic.SET_CONVERSATION_STATUS, buff, currentUserId); _context27.next = 6; return channel.send(writer, PBName.SessionStateModifyResp); case 6: resp = _context27.sent; code = resp.code, data = resp.data; if (!(code === ErrorCode$1.SUCCESS)) { _context27.next = 12; break; } versionData = data; statusList.forEach(function (item) { _newArrowCheck(this, _this78); this._conversationManager.addStatus(Object.assign(Object.assign({}, item), { updatedTime: versionData.version }), true); }.bind(this)); return _context27.abrupt("return", code); case 12: return _context27.abrupt("return", code); case 13: return _context27.abrupt("return", ErrorCode$1.RC_NET_CHANNEL_INVALID); case 14: case "end": return _context27.stop(); } } }, _callee25, this); })); } }, { key: "_joinChrm", value: function _joinChrm(chrmId, count, isJoinExist) { return __awaiter$1(this, void 0, void 0, regeneratorRuntime.mark(function _callee26() { var channel, buff, topic, writer, _yield$channel$send, code, data, info, isOpenKVService; return regeneratorRuntime.wrap(function _callee26$(_context28) { while (1) { switch (_context28.prev = _context28.next) { case 0: channel = this._channel; if (channel) { _context28.next = 3; break; } return _context28.abrupt("return", ErrorCode$1.RC_NET_CHANNEL_INVALID); case 3: buff = channel.codec.encodeJoinOrQuitChatRoom(); topic = isJoinExist ? QueryTopic.JOIN_EXIST_CHATROOM : QueryTopic.JOIN_CHATROOM; writer = new QueryWriter(topic, buff, chrmId); _context28.next = 8; return channel.send(writer); case 8: _yield$channel$send = _context28.sent; code = _yield$channel$send.code; data = _yield$channel$send.data; if (code === ErrorCode$1.SUCCESS) { info = this._chrmsQueue[chrmId]; if (!info) { this._chrmsQueue[chrmId] = { pulling: false, queue: [], timestamp: 0 }; } this._pullChrmMsg(chrmId, count); isOpenKVService = this._naviInfo.kvStorage; if (isOpenKVService) { this._chrmEntryHandler.pullEntry(chrmId, 0); } this._joinedChrmManager.set(chrmId, count); } return _context28.abrupt("return", code); case 13: case "end": return _context28.stop(); } } }, _callee26, this); })); } }, { key: "_rejoinChrm", value: function _rejoinChrm() { return __awaiter$1(this, void 0, void 0, regeneratorRuntime.mark(function _callee27() { var joinedChrms, chrmId, code; return regeneratorRuntime.wrap(function _callee27$(_context29) { while (1) { switch (_context29.prev = _context29.next) { case 0: joinedChrms = this._joinedChrmManager.get(); _context29.t0 = regeneratorRuntime.keys(joinedChrms); case 2: if ((_context29.t1 = _context29.t0()).done) { _context29.next = 10; break; } chrmId = _context29.t1.value; _context29.next = 6; return this._joinChrm(chrmId, joinedChrms[chrmId], true); case 6: code = _context29.sent; if (code === ErrorCode$1.SUCCESS) { this._watcher.chatroom({ rejoinedRoom: { chatroomId: chrmId, count: joinedChrms[chrmId] } }); } else { this._watcher.chatroom({ rejoinedRoom: { chatroomId: chrmId, errorCode: code } }); } _context29.next = 2; break; case 10: case "end": return _context29.stop(); } } }, _callee27, this); })); } }, { key: "_pullChrmMsg", value: function _pullChrmMsg(chrmId) { var count = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 10; return __awaiter$1(this, void 0, void 0, regeneratorRuntime.mark(function _callee28() { var _this79 = this; var chrmInfo, pulling, timestamp, reqBody, signal, _yield$this$_channel$2, code, data, list, syncTime, finished; return regeneratorRuntime.wrap(function _callee28$(_context30) { while (1) { switch (_context30.prev = _context30.next) { case 0: if (this._channel) { _context30.next = 2; break; } return _context30.abrupt("return"); case 2: chrmInfo = this._chrmsQueue[chrmId]; pulling = chrmInfo.pulling, timestamp = chrmInfo.timestamp; if (!pulling) { _context30.next = 6; break; } return _context30.abrupt("return"); case 6: reqBody = this._channel.codec.encodeChrmSyncMsg(timestamp, count); signal = new QueryWriter(Topic$1[Topic$1.chrmPull], reqBody, chrmId); _context30.next = 10; return this._channel.send(signal, PBName.DownStreamMessages, { connectedTime: this._channel.connectedTime, currentUserId: this.currentUserId }); case 10: _yield$this$_channel$2 = _context30.sent; code = _yield$this$_channel$2.code; data = _yield$this$_channel$2.data; if (!(code !== ErrorCode$1.SUCCESS || !data)) { _context30.next = 16; break; } logger.warn('pull chatroom msg failed, code:', code, ', data:', data); return _context30.abrupt("return"); case 16: list = data.list, syncTime = data.syncTime, finished = data.finished; chrmInfo.timestamp = syncTime; chrmInfo.pulling = false; chrmInfo.queue = chrmInfo.queue.filter(function (item) { _newArrowCheck(this, _this79); return item > timestamp; }.bind(this)); list.forEach(function (item) { _newArrowCheck(this, _this79); if (item.sentTime < timestamp) { return; } this._watcher.message(item); }.bind(this)); if (!finished || chrmInfo.queue.length > 0) { this._pullChrmMsg(chrmId); } case 22: case "end": return _context30.stop(); } } }, _callee28, this); })); } }, { key: "joinChatroom", value: function joinChatroom(chatroomId, count) { return __awaiter$1(this, void 0, void 0, regeneratorRuntime.mark(function _callee29() { return regeneratorRuntime.wrap(function _callee29$(_context31) { while (1) { switch (_context31.prev = _context31.next) { case 0: return _context31.abrupt("return", this._joinChrm(chatroomId, count, false)); case 1: case "end": return _context31.stop(); } } }, _callee29, this); })); } }, { key: "joinExistChatroom", value: function joinExistChatroom(chatroomId, count) { return __awaiter$1(this, void 0, void 0, regeneratorRuntime.mark(function _callee30() { return regeneratorRuntime.wrap(function _callee30$(_context32) { while (1) { switch (_context32.prev = _context32.next) { case 0: return _context32.abrupt("return", this._joinChrm(chatroomId, count, true)); case 1: case "end": return _context32.stop(); } } }, _callee30, this); })); } }, { key: "quitChatroom", value: function quitChatroom(chrmId) { return __awaiter$1(this, void 0, void 0, regeneratorRuntime.mark(function _callee31() { var channel, buff, writer, resp, code; return regeneratorRuntime.wrap(function _callee31$(_context33) { while (1) { switch (_context33.prev = _context33.next) { case 0: channel = this._channel; if (channel) { _context33.next = 3; break; } return _context33.abrupt("return", ErrorCode$1.RC_NET_CHANNEL_INVALID); case 3: buff = channel.codec.encodeJoinOrQuitChatRoom(); writer = new QueryWriter(QueryTopic.QUIT_CHATROOM, buff, chrmId); _context33.next = 7; return channel.send(writer); case 7: resp = _context33.sent; code = resp.code; if (code === ErrorCode$1.SUCCESS) { delete this._chrmsQueue[chrmId]; this._chrmEntryHandler.reset(chrmId); this._joinedChrmManager.remove(chrmId); } return _context33.abrupt("return", code); case 11: case "end": return _context33.stop(); } } }, _callee31, this); })); } }, { key: "getChatroomInfo", value: function getChatroomInfo(chatroomId, count, order) { return __awaiter$1(this, void 0, void 0, regeneratorRuntime.mark(function _callee32() { var channel, buff, writer, resp, code, data; return regeneratorRuntime.wrap(function _callee32$(_context34) { while (1) { switch (_context34.prev = _context34.next) { case 0: channel = this._channel; if (channel) { _context34.next = 3; break; } return _context34.abrupt("return", { code: ErrorCode$1.RC_NET_CHANNEL_INVALID }); case 3: buff = channel.codec.encodeGetChatRoomInfo(count, order); writer = new QueryWriter(Topic$1[Topic$1.queryChrmI], buff, chatroomId); _context34.next = 7; return channel.send(writer, PBName.QueryChatRoomInfoOutput); case 7: resp = _context34.sent; code = resp.code, data = resp.data; if (!(code !== ErrorCode$1.SUCCESS)) { _context34.next = 11; break; } return _context34.abrupt("return", { code: code }); case 11: return _context34.abrupt("return", { code: code, data: data }); case 12: case "end": return _context34.stop(); } } }, _callee32, this); })); } }, { key: "getChatroomHistoryMessages", value: function getChatroomHistoryMessages(chatroomId, timestamp, count, order) { return __awaiter$1(this, void 0, void 0, regeneratorRuntime.mark(function _callee33() { var channel, buff, writer, resp, code, data; return regeneratorRuntime.wrap(function _callee33$(_context35) { while (1) { switch (_context35.prev = _context35.next) { case 0: channel = this._channel; if (channel) { _context35.next = 3; break; } return _context35.abrupt("return", { code: ErrorCode$1.RC_NET_CHANNEL_INVALID }); case 3: buff = channel.codec.encodeGetHistoryMsg(chatroomId, { timestamp: timestamp, count: count, order: order }); writer = new QueryWriter(QueryHistoryTopic.CHATROOM, buff, chatroomId); _context35.next = 7; return channel.send(writer, PBName.HistoryMsgOuput, { conversation: { targetId: chatroomId } }); case 7: resp = _context35.sent; code = resp.code; data = resp.data; if (!(code !== ErrorCode$1.SUCCESS)) { _context35.next = 12; break; } return _context35.abrupt("return", { code: code }); case 12: return _context35.abrupt("return", { code: code, data: { list: data.list, hasMore: data.hasMore } }); case 13: case "end": return _context35.stop(); } } }, _callee33, this); })); } }, { key: "_modifyChatroomKV", value: function _modifyChatroomKV(chatroomId, entry) { return __awaiter$1(this, void 0, void 0, regeneratorRuntime.mark(function _callee34() { var channel, currentUserId, buff, topic, writer, resp, code; return regeneratorRuntime.wrap(function _callee34$(_context36) { while (1) { switch (_context36.prev = _context36.next) { case 0: channel = this._channel, currentUserId = this.currentUserId; if (channel) { _context36.next = 3; break; } return _context36.abrupt("return", ErrorCode$1.RC_NET_CHANNEL_INVALID); case 3: buff = channel.codec.encodeModifyChatRoomKV(chatroomId, entry, currentUserId); topic = entry.type === ChatroomEntryType$1.UPDATE ? QueryTopic.UPDATE_CHATROOM_KV : QueryTopic.DELETE_CHATROOM_KV; writer = new QueryWriter(topic, buff, chatroomId); _context36.next = 8; return channel.send(writer); case 8: resp = _context36.sent; code = resp.code; if (!(code === ErrorCode$1.SUCCESS)) { _context36.next = 13; break; } this._chrmEntryHandler.setLocal(chatroomId, { kvEntries: [entry], syncTime: new Date().getTime() }, currentUserId); return _context36.abrupt("return", code); case 13: return _context36.abrupt("return", code); case 14: case "end": return _context36.stop(); } } }, _callee34, this); })); } }, { key: "setChatroomEntry", value: function setChatroomEntry(chatroomId, entry) { return __awaiter$1(this, void 0, void 0, regeneratorRuntime.mark(function _callee35() { return regeneratorRuntime.wrap(function _callee35$(_context37) { while (1) { switch (_context37.prev = _context37.next) { case 0: entry.type = ChatroomEntryType$1.UPDATE; return _context37.abrupt("return", this._modifyChatroomKV(chatroomId, entry)); case 2: case "end": return _context37.stop(); } } }, _callee35, this); })); } }, { key: "forceSetChatroomEntry", value: function forceSetChatroomEntry(chatroomId, entry) { return __awaiter$1(this, void 0, void 0, regeneratorRuntime.mark(function _callee36() { return regeneratorRuntime.wrap(function _callee36$(_context38) { while (1) { switch (_context38.prev = _context38.next) { case 0: entry.type = ChatroomEntryType$1.UPDATE; entry.isOverwrite = true; return _context38.abrupt("return", this._modifyChatroomKV(chatroomId, entry)); case 3: case "end": return _context38.stop(); } } }, _callee36, this); })); } }, { key: "removeChatroomEntry", value: function removeChatroomEntry(chatroomId, entry) { return __awaiter$1(this, void 0, void 0, regeneratorRuntime.mark(function _callee37() { return regeneratorRuntime.wrap(function _callee37$(_context39) { while (1) { switch (_context39.prev = _context39.next) { case 0: entry.type = ChatroomEntryType$1.DELETE; return _context39.abrupt("return", this._modifyChatroomKV(chatroomId, entry)); case 2: case "end": return _context39.stop(); } } }, _callee37, this); })); } }, { key: "forceRemoveChatroomEntry", value: function forceRemoveChatroomEntry(chatroomId, entry) { return __awaiter$1(this, void 0, void 0, regeneratorRuntime.mark(function _callee38() { return regeneratorRuntime.wrap(function _callee38$(_context40) { while (1) { switch (_context40.prev = _context40.next) { case 0: entry.type = ChatroomEntryType$1.DELETE; entry.isOverwrite = true; return _context40.abrupt("return", this._modifyChatroomKV(chatroomId, entry)); case 3: case "end": return _context40.stop(); } } }, _callee38, this); })); } }, { key: "getChatroomEntry", value: function getChatroomEntry(chatroomId, key) { var entry = this._chrmEntryHandler.getValue(chatroomId, key); if (entry) { return Promise.resolve({ code: ErrorCode$1.SUCCESS, data: entry }); } else { return Promise.resolve({ code: ErrorCode$1.CHATROOM_KEY_NOT_EXIST }); } } }, { key: "getAllChatroomEntry", value: function getAllChatroomEntry(chatroomId) { var entries = this._chrmEntryHandler.getAll(chatroomId); return Promise.resolve({ code: ErrorCode$1.SUCCESS, data: entries }); } }, { key: "pullChatroomEntry", value: function pullChatroomEntry(chatroomId, timestamp) { return __awaiter$1(this, void 0, void 0, regeneratorRuntime.mark(function _callee39() { var _this80 = this; var channel, currentUserId, buff, writer, resp, code, data, kvEntries, updatedEntries; return regeneratorRuntime.wrap(function _callee39$(_context41) { while (1) { switch (_context41.prev = _context41.next) { case 0: channel = this._channel, currentUserId = this.currentUserId; if (channel) { _context41.next = 3; break; } return _context41.abrupt("return", { code: ErrorCode$1.RC_NET_CHANNEL_INVALID }); case 3: buff = channel.codec.encodePullChatRoomKV(timestamp); writer = new QueryWriter(Topic$1[Topic$1.pullKV], buff, chatroomId); _context41.next = 7; return channel.send(writer, PBName.ChrmKVOutput); case 7: resp = _context41.sent; code = resp.code, data = resp.data; if (!(code === ErrorCode$1.SUCCESS)) { _context41.next = 15; break; } this._chrmEntryHandler.setLocal(chatroomId, data, currentUserId); kvEntries = data.kvEntries; updatedEntries = []; if (kvEntries.length > 0) { kvEntries.forEach(function (entry) { _newArrowCheck(this, _this80); var key = entry.key, value = entry.value, type = entry.type, timestamp = entry.timestamp; updatedEntries.push({ key: key, value: value, type: type, timestamp: timestamp, chatroomId: chatroomId }); }.bind(this)); this._watcher.chatroom({ updatedEntries: updatedEntries }); } return _context41.abrupt("return", { code: code, data: data }); case 15: return _context41.abrupt("return", { code: code }); case 16: case "end": return _context41.stop(); } } }, _callee39, this); })); } }, { key: "sendMessage", value: function sendMessage(conversationType, targetId, options) { return __awaiter$1(this, void 0, void 0, regeneratorRuntime.mark(function _callee40() { var isStatusMessage, topic, data, signal, _yield$this$_channel$3, code, resp, pubAck, receivedMessage; return regeneratorRuntime.wrap(function _callee40$(_context42) { while (1) { switch (_context42.prev = _context42.next) { case 0: if (this._channel) { _context42.next = 2; break; } return _context42.abrupt("return", { code: ErrorCode$1.RC_NET_CHANNEL_INVALID }); case 2: options = this._handleMsgProperties(options, true); isStatusMessage = [ConversationType$1.PRIVATE, ConversationType$1.GROUP].includes(conversationType) ? options.isStatusMessage : false; topic = isStatusMessage ? getStatPubTopic(conversationType) : getPubTopic(conversationType) || Topic$1.ppMsgP; if (isStatusMessage) { options.isPersited = false; options.isCounted = false; } data = this._channel.codec.encodeUpMsg({ type: conversationType, targetId: targetId }, options); signal = new PublishWriter(Topic$1[topic], data, targetId); signal.setHeaderQos(QOS.AT_LEAST_ONCE); if (!isStatusMessage) { _context42.next = 12; break; } this._channel.sendOnly(signal); return _context42.abrupt("return", { code: ErrorCode$1.SUCCESS, data: transSentAttrs2IReceivedMessage(conversationType, targetId, Object.assign({}, options), '', 0, this.currentUserId) }); case 12: _context42.next = 14; return this._channel.send(signal); case 14: _yield$this$_channel$3 = _context42.sent; code = _yield$this$_channel$3.code; resp = _yield$this$_channel$3.data; if (!(code !== ErrorCode$1.SUCCESS)) { _context42.next = 19; break; } return _context42.abrupt("return", { code: code }); case 19: pubAck = resp; this._letterbox.setOutboxTime(pubAck.timestamp, this.currentUserId); receivedMessage = transSentAttrs2IReceivedMessage(conversationType, targetId, Object.assign({}, options), pubAck.messageUId, pubAck.timestamp, this.currentUserId); this._conversationManager.setConversationCacheByMessage(receivedMessage, true); return _context42.abrupt("return", { code: ErrorCode$1.SUCCESS, data: receivedMessage }); case 24: case "end": return _context42.stop(); } } }, _callee40, this); })); } }, { key: "recallMsg", value: function recallMsg(conversationType, targetId, messageUId, sentTime, user) { return __awaiter$1(this, void 0, void 0, regeneratorRuntime.mark(function _callee41() { var msg, topic, data, signal, _yield$this$_channel$4, code, resp, pubAck; return regeneratorRuntime.wrap(function _callee41$(_context43) { while (1) { switch (_context43.prev = _context43.next) { case 0: if (this._channel) { _context43.next = 2; break; } return _context43.abrupt("return", { code: ErrorCode$1.RC_NET_CHANNEL_INVALID }); case 2: msg = { content: { conversationType: conversationType, targetId: targetId, messageUId: messageUId, sentTime: sentTime, user: user }, messageType: 'RC:RcCmd' }; topic = Topic$1[Topic$1.recallMsg]; data = this._channel.codec.encodeUpMsg({ type: conversationType, targetId: targetId }, msg); signal = new PublishWriter(topic, data, this.currentUserId); signal.setHeaderQos(QOS.AT_LEAST_ONCE); _context43.next = 9; return this._channel.send(signal); case 9: _yield$this$_channel$4 = _context43.sent; code = _yield$this$_channel$4.code; resp = _yield$this$_channel$4.data; if (!(code !== ErrorCode$1.SUCCESS)) { _context43.next = 14; break; } return _context43.abrupt("return", { code: code }); case 14: pubAck = resp; return _context43.abrupt("return", { code: ErrorCode$1.SUCCESS, data: transSentAttrs2IReceivedMessage(conversationType, targetId, Object.assign({}, msg), pubAck.messageUId, pubAck.timestamp, this.currentUserId) }); case 16: case "end": return _context43.stop(); } } }, _callee41, this); })); } }, { key: "pullUserSettings", value: function pullUserSettings(version) { return __awaiter$1(this, void 0, void 0, regeneratorRuntime.mark(function _callee42() { var buff, writer; return regeneratorRuntime.wrap(function _callee42$(_context44) { while (1) { switch (_context44.prev = _context44.next) { case 0: if (this._channel) { _context44.next = 2; break; } return _context44.abrupt("return", { code: ErrorCode$1.RC_NET_CHANNEL_INVALID }); case 2: buff = this._channel.codec.encodePullUserSetting(version); writer = new QueryWriter(Topic$1[Topic$1.pullUS], buff, this.currentUserId); return _context44.abrupt("return", this._channel.send(writer, PBName.PullUserSettingOutput)); case 5: case "end": return _context44.stop(); } } }, _callee42, this); })); } }, { key: "getFileToken", value: function getFileToken(fileType, fileName) { return __awaiter$1(this, void 0, void 0, regeneratorRuntime.mark(function _callee43() { var uploadFileName, buff, writer, _yield$this$_channel$5, code, data; return regeneratorRuntime.wrap(function _callee43$(_context45) { while (1) { switch (_context45.prev = _context45.next) { case 0: if (this._channel) { _context45.next = 2; break; } return _context45.abrupt("return", { code: ErrorCode$1.RC_NET_CHANNEL_INVALID }); case 2: uploadFileName = getUploadFileName(fileType, fileName); buff = this._channel.codec.encodeGetFileToken(fileType, uploadFileName); writer = new QueryWriter(Topic$1[Topic$1.qnTkn], buff, this.currentUserId); _context45.next = 7; return this._channel.send(writer, PBName.GetQNupTokenOutput); case 7: _yield$this$_channel$5 = _context45.sent; code = _yield$this$_channel$5.code; data = _yield$this$_channel$5.data; data = Object.assign(data, { fileName: uploadFileName }); if (!(code === ErrorCode$1.SUCCESS)) { _context45.next = 13; break; } return _context45.abrupt("return", { code: code, data: data }); case 13: return _context45.abrupt("return", { code: code }); case 14: case "end": return _context45.stop(); } } }, _callee43, this); })); } }, { key: "getFileUrl", value: function getFileUrl(fileType, uploadMethod, fileName, originName) { return __awaiter$1(this, void 0, void 0, regeneratorRuntime.mark(function _callee44() { var topic, inputPBName, outputPBName, buff, writer, _yield$this$_channel$6, code, data, resp; return regeneratorRuntime.wrap(function _callee44$(_context46) { while (1) { switch (_context46.prev = _context46.next) { case 0: if (this._channel) { _context46.next = 2; break; } return _context46.abrupt("return", { code: ErrorCode$1.RC_NET_CHANNEL_INVALID }); case 2: topic = ''; inputPBName = ''; outputPBName = ''; if (uploadMethod === UploadMethod$1.QINIU) { topic = Topic$1[Topic$1.qnUrl]; inputPBName = PBName.GetQNdownloadUrlInput; outputPBName = PBName.GetQNdownloadUrlOutput; } else { topic = Topic$1[Topic$1.aliUrl]; inputPBName = PBName.GetDownloadUrlInput; outputPBName = PBName.GetDownloadUrlOutput; } buff = this._channel.codec.encodeGetFileUrl(inputPBName, fileType, fileName, originName); writer = new QueryWriter(topic, buff, this.currentUserId); _context46.next = 10; return this._channel.send(writer, outputPBName); case 10: _yield$this$_channel$6 = _context46.sent; code = _yield$this$_channel$6.code; data = _yield$this$_channel$6.data; resp = data; if (!(code === ErrorCode$1.SUCCESS)) { _context46.next = 16; break; } return _context46.abrupt("return", { code: code, data: resp }); case 16: return _context46.abrupt("return", { code: code }); case 17: case "end": return _context46.stop(); } } }, _callee44, this); })); } }, { key: "disconnect", value: function disconnect() { if (this._channel) { this._channel.close(); this._channel = undefined; } } }, { key: "destroy", value: function destroy() { throw new Error('JSEngine\'s method not implemented.'); } }, { key: "registerMessageType", value: function registerMessageType(objectName, isPersited, isCounted, searchProps) { this._customMessageType[objectName] = { isPersited: isPersited, isCounted: isCounted }; } }, { key: "joinRTCRoom", value: function joinRTCRoom(roomId, mode, broadcastType) { return __awaiter$1(this, void 0, void 0, regeneratorRuntime.mark(function _callee45() { var reqBody, writer; return regeneratorRuntime.wrap(function _callee45$(_context47) { while (1) { switch (_context47.prev = _context47.next) { case 0: if (this._channel) { _context47.next = 2; break; } return _context47.abrupt("return", { code: ErrorCode$1.RC_NET_CHANNEL_INVALID }); case 2: reqBody = this._channel.codec.encodeJoinRTCRoom(mode, broadcastType); writer = new QueryWriter(Topic$1[Topic$1.rtcRJoin_data], reqBody, roomId); return _context47.abrupt("return", this._channel.send(writer, PBName.RtcUserListOutput)); case 5: case "end": return _context47.stop(); } } }, _callee45, this); })); } }, { key: "quitRTCRoom", value: function quitRTCRoom(roomId) { return __awaiter$1(this, void 0, void 0, regeneratorRuntime.mark(function _callee46() { var reqBody, writer, _yield$this$_channel$7, code; return regeneratorRuntime.wrap(function _callee46$(_context48) { while (1) { switch (_context48.prev = _context48.next) { case 0: if (this._channel) { _context48.next = 2; break; } return _context48.abrupt("return", ErrorCode$1.RC_NET_CHANNEL_INVALID); case 2: reqBody = this._channel.codec.encodeQuitRTCRoom(); writer = new QueryWriter(Topic$1[Topic$1.rtcRExit], reqBody, roomId); _context48.next = 6; return this._channel.send(writer); case 6: _yield$this$_channel$7 = _context48.sent; code = _yield$this$_channel$7.code; return _context48.abrupt("return", code); case 9: case "end": return _context48.stop(); } } }, _callee46, this); })); } }, { key: "rtcPing", value: function rtcPing(roomId, mode, broadcastType) { return __awaiter$1(this, void 0, void 0, regeneratorRuntime.mark(function _callee47() { var reqBody, writer, _yield$this$_channel$8, code; return regeneratorRuntime.wrap(function _callee47$(_context49) { while (1) { switch (_context49.prev = _context49.next) { case 0: if (this._channel) { _context49.next = 2; break; } return _context49.abrupt("return", ErrorCode$1.RC_NET_CHANNEL_INVALID); case 2: reqBody = this._channel.codec.encodeJoinRTCRoom(mode, broadcastType); writer = new QueryWriter(Topic$1[Topic$1.rtcPing], reqBody, roomId); _context49.next = 6; return this._channel.send(writer); case 6: _yield$this$_channel$8 = _context49.sent; code = _yield$this$_channel$8.code; return _context49.abrupt("return", code); case 9: case "end": return _context49.stop(); } } }, _callee47, this); })); } }, { key: "getRTCRoomInfo", value: function getRTCRoomInfo(roomId) { return __awaiter$1(this, void 0, void 0, regeneratorRuntime.mark(function _callee48() { var reqBody, writer; return regeneratorRuntime.wrap(function _callee48$(_context50) { while (1) { switch (_context50.prev = _context50.next) { case 0: if (this._channel) { _context50.next = 2; break; } return _context50.abrupt("return", { code: ErrorCode$1.RC_NET_CHANNEL_INVALID }); case 2: reqBody = this._channel.codec.encodeGetRTCRoomInfo(); writer = new QueryWriter(Topic$1[Topic$1.rtcRInfo], reqBody, roomId); return _context50.abrupt("return", this._channel.send(writer, PBName.RtcRoomInfoOutput)); case 5: case "end": return _context50.stop(); } } }, _callee48, this); })); } }, { key: "getRTCUserInfoList", value: function getRTCUserInfoList(roomId) { return __awaiter$1(this, void 0, void 0, regeneratorRuntime.mark(function _callee49() { var reqBody, writer, _yield$this$_channel$9, code, data; return regeneratorRuntime.wrap(function _callee49$(_context51) { while (1) { switch (_context51.prev = _context51.next) { case 0: if (this._channel) { _context51.next = 2; break; } return _context51.abrupt("return", { code: ErrorCode$1.RC_NET_CHANNEL_INVALID }); case 2: reqBody = this._channel.codec.encodeGetRTCRoomInfo(); writer = new QueryWriter(Topic$1[Topic$1.rtcUData], reqBody, roomId); _context51.next = 6; return this._channel.send(writer, PBName.RtcUserListOutput); case 6: _yield$this$_channel$9 = _context51.sent; code = _yield$this$_channel$9.code; data = _yield$this$_channel$9.data; return _context51.abrupt("return", { code: code, data: data ? { users: data.users } : data }); case 10: case "end": return _context51.stop(); } } }, _callee49, this); })); } }, { key: "setRTCUserInfo", value: function setRTCUserInfo(roomId, key, value) { return __awaiter$1(this, void 0, void 0, regeneratorRuntime.mark(function _callee50() { var reqBody, writer, _yield$this$_channel$10, code; return regeneratorRuntime.wrap(function _callee50$(_context52) { while (1) { switch (_context52.prev = _context52.next) { case 0: if (this._channel) { _context52.next = 2; break; } return _context52.abrupt("return", ErrorCode$1.RC_NET_CHANNEL_INVALID); case 2: reqBody = this._channel.codec.encodeSetRTCUserInfo(key, value); writer = new QueryWriter(Topic$1[Topic$1.rtcUPut], reqBody, roomId); _context52.next = 6; return this._channel.send(writer); case 6: _yield$this$_channel$10 = _context52.sent; code = _yield$this$_channel$10.code; return _context52.abrupt("return", code); case 9: case "end": return _context52.stop(); } } }, _callee50, this); })); } }, { key: "removeRTCUserInfo", value: function removeRTCUserInfo(roomId, keys) { return __awaiter$1(this, void 0, void 0, regeneratorRuntime.mark(function _callee51() { var reqBody, writer, _yield$this$_channel$11, code; return regeneratorRuntime.wrap(function _callee51$(_context53) { while (1) { switch (_context53.prev = _context53.next) { case 0: if (this._channel) { _context53.next = 2; break; } return _context53.abrupt("return", ErrorCode$1.RC_NET_CHANNEL_INVALID); case 2: reqBody = this._channel.codec.encodeRemoveRTCUserInfo(keys); writer = new PublishWriter(Topic$1[Topic$1.rtcUDel], reqBody, roomId); _context53.next = 6; return this._channel.send(writer); case 6: _yield$this$_channel$11 = _context53.sent; code = _yield$this$_channel$11.code; return _context53.abrupt("return", code); case 9: case "end": return _context53.stop(); } } }, _callee51, this); })); } }, { key: "setRTCData", value: function setRTCData(roomId, key, value, isInner, apiType, message) { return __awaiter$1(this, void 0, void 0, regeneratorRuntime.mark(function _callee52() { var reqBody, writer, _yield$this$_channel$12, code; return regeneratorRuntime.wrap(function _callee52$(_context54) { while (1) { switch (_context54.prev = _context54.next) { case 0: if (this._channel) { _context54.next = 2; break; } return _context54.abrupt("return", ErrorCode$1.RC_NET_CHANNEL_INVALID); case 2: reqBody = this._channel.codec.encodeSetRTCData(key, value, isInner, apiType, message); writer = new PublishWriter(Topic$1[Topic$1.rtcSetData], reqBody, roomId); _context54.next = 6; return this._channel.send(writer); case 6: _yield$this$_channel$12 = _context54.sent; code = _yield$this$_channel$12.code; return _context54.abrupt("return", code); case 9: case "end": return _context54.stop(); } } }, _callee52, this); })); } }, { key: "setRTCTotalRes", value: function setRTCTotalRes(roomId, message, valueInfo, objectName) { return __awaiter$1(this, void 0, void 0, regeneratorRuntime.mark(function _callee53() { var reqBody, writer, _yield$this$_channel$13, code; return regeneratorRuntime.wrap(function _callee53$(_context55) { while (1) { switch (_context55.prev = _context55.next) { case 0: if (this._channel) { _context55.next = 2; break; } return _context55.abrupt("return", ErrorCode$1.RC_NET_CHANNEL_INVALID); case 2: reqBody = this._channel.codec.encodeUserSetRTCData(message, valueInfo, objectName); writer = new PublishWriter(Topic$1[Topic$1.userSetData], reqBody, roomId); _context55.next = 6; return this._channel.send(writer); case 6: _yield$this$_channel$13 = _context55.sent; code = _yield$this$_channel$13.code; return _context55.abrupt("return", code); case 9: case "end": return _context55.stop(); } } }, _callee53, this); })); } }, { key: "getRTCData", value: function getRTCData(roomId, keys, isInner, apiType) { if (!this._channel) { return Promise.resolve({ code: ErrorCode$1.RC_NET_CHANNEL_INVALID }); } var reqBody = this._channel.codec.encodeGetRTCData(keys, isInner, apiType); var writer = new QueryWriter(Topic$1[Topic$1.rtcQryData], reqBody, roomId); return this._channel.send(writer, PBName.RtcQryOutput); } }, { key: "removeRTCData", value: function removeRTCData(roomId, keys, isInner, apiType, message) { return __awaiter$1(this, void 0, void 0, regeneratorRuntime.mark(function _callee54() { var reqBody, writer, _yield$this$_channel$14, code; return regeneratorRuntime.wrap(function _callee54$(_context56) { while (1) { switch (_context56.prev = _context56.next) { case 0: if (this._channel) { _context56.next = 2; break; } return _context56.abrupt("return", ErrorCode$1.RC_NET_CHANNEL_INVALID); case 2: reqBody = this._channel.codec.encodeRemoveRTCData(keys, isInner, apiType, message); writer = new PublishWriter(Topic$1[Topic$1.rtcDelData], reqBody, roomId); _context56.next = 6; return this._channel.send(writer); case 6: _yield$this$_channel$14 = _context56.sent; code = _yield$this$_channel$14.code; return _context56.abrupt("return", code); case 9: case "end": return _context56.stop(); } } }, _callee54, this); })); } }, { key: "setRTCOutData", value: function setRTCOutData(roomId, rtcData, type, message) { throw new Error('JSEngine\'s method not implemented.'); } }, { key: "getRTCOutData", value: function getRTCOutData(roomId, userIds) { throw new Error('JSEngine\'s method not implemented.'); } }, { key: "getRTCToken", value: function getRTCToken(roomId, mode, broadcastType) { return __awaiter$1(this, void 0, void 0, regeneratorRuntime.mark(function _callee55() { var reqBody, writer; return regeneratorRuntime.wrap(function _callee55$(_context57) { while (1) { switch (_context57.prev = _context57.next) { case 0: if (this._channel) { _context57.next = 2; break; } return _context57.abrupt("return", { code: ErrorCode$1.RC_NET_CHANNEL_INVALID }); case 2: reqBody = this._channel.codec.encodeJoinRTCRoom(mode, broadcastType); writer = new QueryWriter(Topic$1[Topic$1.rtcToken], reqBody, roomId); return _context57.abrupt("return", this._channel.send(writer, PBName.RtcTokenOutput)); case 5: case "end": return _context57.stop(); } } }, _callee55, this); })); } }, { key: "setRTCState", value: function setRTCState(roomId, report) { return __awaiter$1(this, void 0, void 0, regeneratorRuntime.mark(function _callee56() { var reqBody, writer, _yield$this$_channel$15, code; return regeneratorRuntime.wrap(function _callee56$(_context58) { while (1) { switch (_context58.prev = _context58.next) { case 0: if (this._channel) { _context58.next = 2; break; } return _context58.abrupt("return", ErrorCode$1.RC_NET_CHANNEL_INVALID); case 2: reqBody = this._channel.codec.encodeSetRTCState(report); writer = new QueryWriter(Topic$1[Topic$1.rtcUserState], reqBody, roomId); _context58.next = 6; return this._channel.send(writer); case 6: _yield$this$_channel$15 = _context58.sent; code = _yield$this$_channel$15.code; return _context58.abrupt("return", code); case 9: case "end": return _context58.stop(); } } }, _callee56, this); })); } }, { key: "getRTCUserInfo", value: function getRTCUserInfo(roomId) { return __awaiter$1(this, void 0, void 0, regeneratorRuntime.mark(function _callee57() { return regeneratorRuntime.wrap(function _callee57$(_context59) { while (1) { switch (_context59.prev = _context59.next) { case 0: throw new Error('Method not implemented.'); case 1: case "end": return _context59.stop(); } } }, _callee57); })); } }, { key: "getRTCUserList", value: function getRTCUserList(roomId) { if (!this._channel) { return Promise.resolve({ code: ErrorCode$1.RC_NET_CHANNEL_INVALID }); } var data = this._channel.codec.encodeGetRTCRoomInfo(); var writer = new QueryWriter(Topic$1[Topic$1.rtcUList], data, roomId); return this._channel.send(writer, PBName.RtcUserListOutput); } }, { key: "clearConversations", value: function clearConversations() { throw new Error('Method not implemented.'); } }, { key: "setUserStatusListener", value: function setUserStatusListener(config, listener) { throw new Error('Method not implemented.'); } }, { key: "setUserStatus", value: function setUserStatus(status) { throw new Error('Method not implemented.'); } }, { key: "subscribeUserStatus", value: function subscribeUserStatus(userIds) { throw new Error('Method not implemented.'); } }, { key: "getUserStatus", value: function getUserStatus(userId) { throw new Error('Method not implemented.'); } }, { key: "addToBlacklist", value: function addToBlacklist(userId) { throw new Error('Method not implemented.'); } }, { key: "removeFromBlacklist", value: function removeFromBlacklist(userId) { throw new Error('Method not implemented.'); } }, { key: "getBlacklist", value: function getBlacklist() { throw new Error('Method not implemented.'); } }, { key: "getBlacklistStatus", value: function getBlacklistStatus(userId) { throw new Error('Method not implemented.'); } }, { key: "insertMessage", value: function insertMessage(conversationType, targetId, senderUserId, objectName, msgContent, direction) { throw new Error('Method not implemented.'); } }, { key: "deleteMessages", value: function deleteMessages(timestamps) { throw new Error('Method not implemented.'); } }, { key: "deleteMessagesByTimestamp", value: function deleteMessagesByTimestamp(conversationType, targetId, timestamp, cleanSpace) { throw new Error('Method not implemented.'); } }, { key: "getMessage", value: function getMessage(messageId) { throw new Error('Method not implemented.'); } }, { key: "setMessageContent", value: function setMessageContent(messageId, content, objectName) { throw new Error('Method not implemented.'); } }, { key: "setMessageSearchField", value: function setMessageSearchField(messageId, content, searchFiles) { throw new Error('Method not implemented.'); } }, { key: "searchConversationByContent", value: function searchConversationByContent(keyword, conversationTypes) { throw new Error('Method not implemented.'); } }, { key: "searchMessageByContent", value: function searchMessageByContent(conversationType, targetId, keyword, timestamp, count, total) { throw new Error('Method not implemented.'); } }, { key: "getUnreadMentionedMessages", value: function getUnreadMentionedMessages(conversationType, targetId) { throw new Error('Method not implemented.'); } }, { key: "setMessageSentStatus", value: function setMessageSentStatus(messageId, sentStatus) { throw new Error('Method not implemented.'); } }, { key: "setMessageReceivedStatus", value: function setMessageReceivedStatus(messageId, receivedStatus) { throw new Error('Method not implemented.'); } }]); return JSEngine; }(AEngine); var RTCMode; (function (RTCMode) { RTCMode[RTCMode["RTC"] = 0] = "RTC"; RTCMode[RTCMode["LIVE"] = 2] = "LIVE"; })(RTCMode || (RTCMode = {})); var LiveType; (function (LiveType) { LiveType[LiveType["AUDIO_AND_VIDEO"] = 0] = "AUDIO_AND_VIDEO"; LiveType[LiveType["AUDIO"] = 1] = "AUDIO"; })(LiveType || (LiveType = {})); var LiveRole; (function (LiveRole) { LiveRole[LiveRole["ANCHOR"] = 1] = "ANCHOR"; LiveRole[LiveRole["AUDIENCE"] = 2] = "AUDIENCE"; })(LiveRole || (LiveRole = {})); var CallLibMsgType = { 'RC:VCAccept': 'RC:VCAccept', 'RC:VCRinging': 'RC:VCRinging', 'RC:VCSummary': 'RC:VCSummary', 'RC:VCHangup': 'RC:VCHangup', 'RC:VCInvite': 'RC:VCInvite', 'RC:VCModifyMedia': 'RC:VCModifyMedia', 'RC:VCModifyMem': 'RC:VCModifyMem' }; var RTCApiType; (function (RTCApiType) { RTCApiType[RTCApiType["ROOM"] = 1] = "ROOM"; RTCApiType[RTCApiType["PERSON"] = 2] = "PERSON"; })(RTCApiType || (RTCApiType = {})); var Heartbeat = function () { function Heartbeat(pongRes, connectionListener) { _classCallCheck(this, Heartbeat); this._timerId = 0; this._heartbeatTimeoutId = 0; this._isFirstPing = true; this._hasPingRes = pongRes; this._connectionListener = connectionListener; } _createClass(Heartbeat, [{ key: "start", value: function start(cppHeartbeatFunc, cppEngine) { var _this81 = this; var self = this; var _startHeartbeat = function startHeartbeat() { var _this82 = this; _newArrowCheck(this, _this81); var time = this._isFirstPing ? 0 : 15 * 1000; self._timerId = setTimeout(function () { var _this83 = this; _newArrowCheck(this, _this82); self._isFirstPing = false; if (self._hasPingRes) { cppHeartbeatFunc.call(cppEngine); self._hasPingRes = false; _startHeartbeat(); } else { self._heartbeatTimeoutId = setTimeout(function () { _newArrowCheck(this, _this83); }.bind(this), 90 * 1000); } }.bind(this), time); }.bind(this); _startHeartbeat(); } }, { key: "stop", value: function stop() { clearTimeout(this._timerId); } }, { key: "setHeartbeatRes", value: function setHeartbeatRes(hasRes) { this._hasPingRes = hasRes; if (this._hasPingRes) { clearTimeout(this._heartbeatTimeoutId); } } }]); return Heartbeat; }(); var CPPEngine = function (_AEngine2) { _inherits(CPPEngine, _AEngine2); var _super19 = _createSuper(CPPEngine); function CPPEngine(_runtime, _appkey, _watcher, _apiVersion, _cppProtocol, _options) { var _this85 = this; var _this84; _classCallCheck(this, CPPEngine); _this84 = _super19.call(this, _runtime, _appkey, _watcher, _apiVersion, _options); _this84._cppProtocol = _cppProtocol; _this84._currentToken = ''; _this84._connectionStatus = ConnectionStatus$1.DISCONNECTED; _this84._promiseHandler = {}; _this84._customMessageType = {}; _this84._heartbeat = {}; _this84._connectionListener = function (status) { _newArrowCheck(this, _this85); }.bind(this); _this84._cppConnectionStatus = ConnectionStatus$1.DISCONNECTED; _this84.init(_appkey, { version: _apiVersion, dbPath: _options.dbPath || '', navi: _options.navigators[0] || '' }); _this84._setConnectionStatusListener(_watcher.status); _this84._setOnReceiveMessageListener(_watcher.message); _this84._setConversationStatusListener(_watcher.conversation); return _this84; } _createClass(CPPEngine, [{ key: "_registerMsgTypes", value: function _registerMsgTypes() { SEND_MESSAGE_TYPE_OPTION['RC:RcCmd'] = { isCounted: false, isPersited: false }; for (var messageType in SEND_MESSAGE_TYPE_OPTION) { var _SEND_MESSAGE_TYPE_OP = SEND_MESSAGE_TYPE_OPTION[messageType], isCounted = _SEND_MESSAGE_TYPE_OP.isCounted, isPersited = _SEND_MESSAGE_TYPE_OP.isPersited; var msgOptions = 0; if (isPersited) { msgOptions = msgOptions | 0x01; } if (isCounted) { msgOptions = msgOptions | 0x02; } this._cppProtocol.registerMessageType(messageType, msgOptions); } } }, { key: "_buildMessage", value: function _buildMessage(result, isOffLineMessage) { var receivedCppMessage = JSON.parse(result); var conversationType = receivedCppMessage.conversationType, targetId = receivedCppMessage.targetId, senderUserId = receivedCppMessage.senderUserId, content = receivedCppMessage.content, objectName = receivedCppMessage.objectName, messageUid = receivedCppMessage.messageUid, direction = receivedCppMessage.direction, status = receivedCppMessage.status, source = receivedCppMessage.source, messageId = receivedCppMessage.messageId, sentTime = receivedCppMessage.sentTime; var msgContent; if (isObject(content)) { msgContent = content; } else { msgContent = content ? JSON.parse(content) : content; } var msgOptions = { isCounted: false, isPersited: false }; if (objectName in SEND_MESSAGE_TYPE_OPTION) { msgOptions = SEND_MESSAGE_TYPE_OPTION[objectName]; } else if (objectName in this._customMessageType) { msgOptions = this._customMessageType[objectName]; } var isOffline = isUndefined(isOffLineMessage) ? sentTime < this.connectedTime : isOffLineMessage; var msg = { conversationType: conversationType, targetId: targetId, senderUserId: senderUserId, content: msgContent || {}, messageType: objectName, messageUId: messageUid, messageDirection: direction, isOffLineMessage: isOffline, sentTime: sentTime, receivedTime: 0, isPersited: msgOptions.isPersited, isCounted: msgOptions.isCounted, isMentioned: false, disableNotification: false, isStatusMessage: false, canIncludeExpansion: false, expansion: null, receivedStatus: status, messageId: messageId }; if (direction === MessageDirection$1.RECEIVE) { msg.receivedStatus = status; } else if (direction === MessageDirection$1.SEND) { msg.sentStatus = status; } return msg; } }, { key: "_buildConversation", value: function _buildConversation(result) { var conver = JSON.parse(result); var conversationType = conver.conversationType, targetId = conver.targetId, unreadMessageCount = conver.unreadCount, lastestMsg = conver.lastestMsg, isTop = conver.isTop, isBlocked = conver.isBlocked; var isTopToBool = isTop === 1; var isNotify = isBlocked === 1 ? NotificationStatus$1.OPEN : NotificationStatus$1.CLOSE; return { conversationType: conversationType, targetId: targetId, unreadMessageCount: unreadMessageCount, latestMessage: this._buildMessage(lastestMsg), hasMentioned: false, mentionedInfo: null, notificationStatus: isNotify, isTop: isTopToBool, lastUnreadTime: 0 }; } }, { key: "_setConnectionStatusListener", value: function _setConnectionStatusListener(listener) { var _this86 = this; this._connectionListener = listener; this._cppProtocol.setConnectionStatusListener(function (status) { var _this87 = this; _newArrowCheck(this, _this86); logger.warn('protocol connection status changed:', status); this._cppConnectionStatus = status; var connectionStatus; switch (status) { case 10: connectionStatus = ConnectionStatus$1.CONNECTING; break; case 31004: setTimeout(function () { _newArrowCheck(this, _this87); this._promiseHandler.connect && this._promiseHandler.connect.resolve(ErrorCode$1.RC_CONN_USER_OR_PASSWD_ERROR); }.bind(this)); return; case 12: connectionStatus = ConnectionStatus$1.DISCONNECTED; break; case 13: connectionStatus = ConnectionStatus$1.BLOCKED; break; case 1: case 8: case 9: case 11: case 31011: case 30000: case 30002: connectionStatus = ConnectionStatus$1.NETWORK_UNAVAILABLE; break; case 30010: this._try2Reconnect(); connectionStatus = ConnectionStatus$1.NETWORK_UNAVAILABLE; break; case 0: case 33005: connectionStatus = ConnectionStatus$1.CONNECTED; this.connectedTime = new Date().getTime() - this._cppProtocol.getDeltaTime(); setTimeout(function () { _newArrowCheck(this, _this87); this._promiseHandler.connect && this._promiseHandler.connect.resolve(ErrorCode$1.SUCCESS); this._heartbeat = new Heartbeat(true, listener); this._heartbeat.start(this._sendHeartbeat, this); }.bind(this)); break; case ConnectionStatus$1.KICKED_OFFLINE_BY_OTHER_CLIENT: connectionStatus = ConnectionStatus$1.KICKED_OFFLINE_BY_OTHER_CLIENT; break; case 30004: return; default: connectionStatus = status; break; } this._connectionStatus = connectionStatus; setTimeout(function () { _newArrowCheck(this, _this87); listener(connectionStatus); }.bind(this)); }.bind(this), this._dbInitCallback, function () { _newArrowCheck(this, _this86); this._heartbeat.setHeartbeatRes(true); }.bind(this)); } }, { key: "_dbInitCallback", value: function _dbInitCallback(code) {} }, { key: "_sendHeartbeat", value: function _sendHeartbeat() { this._cppProtocol.sendHeartbeat(); } }, { key: "_try2Reconnect", value: function _try2Reconnect() { var _this88 = this; if (this._cppConnectionStatus !== 30010 && this._cppConnectionStatus !== 30004) { return; } logger.warn('protocol reconnecting'); this._cppProtocol.connectWithToken(this._currentToken, '', function () { _newArrowCheck(this, _this88); }.bind(this)); setTimeout(function () { _newArrowCheck(this, _this88); this._try2Reconnect(); }.bind(this), 5000); } }, { key: "_setOnReceiveMessageListener", value: function _setOnReceiveMessageListener(listener) { var _this89 = this; this._cppProtocol.setOnReceiveMessageListener(function (result, leftCount, offline, hasMore) { _newArrowCheck(this, _this89); var message = this._buildMessage(result, offline); listener(message); }.bind(this)); } }, { key: "_setConversationStatusListener", value: function _setConversationStatusListener(listener) { var _this90 = this; this._cppProtocol.setConversationStatusListener(function (result) { var _this91 = this; _newArrowCheck(this, _this90); var list = JSON.parse(result).list; var updatedConvers = []; list.forEach(function (conver) { var _this92 = this; _newArrowCheck(this, _this91); var converData = JSON.parse(conver.obj); var conversationType = converData.conversationType, targetId = converData.targetId, status = converData.status; var statusObj = { notificationStatus: 2, isTop: false }; status.forEach(function (status) { _newArrowCheck(this, _this92); var itemObj = JSON.parse(status.item); if (itemObj.type === 1) { statusObj.notificationStatus = Number(itemObj.value) === 1 ? NotificationStatus$1.OPEN : NotificationStatus$1.CLOSE; } else { statusObj.isTop = Number(itemObj.value) === 1; } }.bind(this)); updatedConvers.push({ conversationType: conversationType, targetId: targetId, updatedItems: { notificationStatus: { val: statusObj.notificationStatus, time: 0 }, isTop: { val: statusObj.isTop, time: 0 } } }); }.bind(this)); listener(updatedConvers); }.bind(this)); } }, { key: "_clearListener", value: function _clearListener() { this._cppProtocol.setOnReceiveMessageListener(); this._cppProtocol.setConnectionStatusListener(); this._cppProtocol.setOnReceiveStatusListener(); } }, { key: "init", value: function init(appkey, config) { var sdkInfo = this._cppProtocol.initWithAppkey(appkey, config === null || config === void 0 ? void 0 : config.dbPath, config); if (sdkInfo) { sdkInfo = JSON.parse(sdkInfo); } this._registerMsgTypes(); return sdkInfo; } }, { key: "registerMessageType", value: function registerMessageType(messageType, isPersited, isCounted, searchProps) { var msgOptions = 0; if (isPersited) { msgOptions = msgOptions | 0x01; } if (isCounted) { msgOptions = msgOptions | 0x02; } this._customMessageType[messageType] = { isCounted: isCounted, isPersited: isPersited }; this._cppProtocol.registerMessageType(messageType, msgOptions, searchProps); } }, { key: "connect", value: function connect(token, naviInfo, connectType, userId) { var _this93 = this; var options = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {}; this._currentToken = token; if (options.type) { this._cppProtocol.setEnvironment(true); } this._cppProtocol.connectWithToken(token, userId, function (userId) { _newArrowCheck(this, _this93); this.currentUserId = userId; }.bind(this)); return new Promise(function (resolve, reject) { _newArrowCheck(this, _this93); this._promiseHandler.connect = { resolve: resolve, reject: reject }; }.bind(this)); } }, { key: "disconnect", value: function disconnect() { this._cppProtocol.disconnect(true); this._heartbeat.stop(); this._connectionListener(ConnectionStatus$1.DISCONNECTED); } }, { key: "logout", value: function logout() { this.disconnect(); } }, { key: "getConnectTime", value: function getConnectTime() { var _this94 = this; return new Promise(function (resolve, reject) { _newArrowCheck(this, _this94); resolve({ code: ErrorCode$1.SUCCESS, data: this.connectedTime }); }.bind(this)); } }, { key: "setUserStatusListener", value: function setUserStatusListener(config, listener) { var _this95 = this; this._cppProtocol.setOnReceiveStatusListener(function (userId, status) { _newArrowCheck(this, _this95); listener({ userId: userId, status: status }); }.bind(this)); var userIds = config.userIds || []; if (userIds.length) { this.subscribeUserStatus(userIds); } } }, { key: "subscribeUserStatus", value: function subscribeUserStatus(userIds) { var _this96 = this; return new Promise(function (resolve, reject) { var _this97 = this; _newArrowCheck(this, _this96); this._cppProtocol.subscribeUserStatus(userIds, function () { _newArrowCheck(this, _this97); resolve(ErrorCode$1.SUCCESS); }.bind(this), resolve); }.bind(this)); } }, { key: "setUserStatus", value: function setUserStatus(status) { var _this98 = this; return new Promise(function (resolve, reject) { var _this99 = this; _newArrowCheck(this, _this98); this._cppProtocol.setUserStatus(status, function () { _newArrowCheck(this, _this99); resolve(ErrorCode$1.SUCCESS); }.bind(this), resolve); }.bind(this)); } }, { key: "getUserStatus", value: function getUserStatus(userId) { var _this100 = this; return new Promise(function (resolve, reject) { var _this101 = this; _newArrowCheck(this, _this100); this._cppProtocol.getUserStatus(userId, function (status) { _newArrowCheck(this, _this101); resolve({ code: ErrorCode$1.SUCCESS, data: { status: status } }); }.bind(this), function (code) { _newArrowCheck(this, _this101); resolve({ code: code }); }.bind(this)); }.bind(this)); } }, { key: "sendMessage", value: function sendMessage(conversationType, targetId, options) { var _this102 = this; var messageType = options.messageType, content = options.content, pushContent = options.pushContent, pushData = options.pushData, directionalUserIdList = options.directionalUserIdList, disableNotification = options.disableNotification, canIncludeExpansion = options.canIncludeExpansion, expansion = options.expansion, isVoipPush = options.isVoipPush, pushConfig = options.pushConfig; var _ref3 = pushConfig || {}, iOSConfig = _ref3.iOSConfig, androidConfig = _ref3.androidConfig, pushTitle = _ref3.pushTitle, newPushContent = _ref3.pushContent, newPushData = _ref3.pushData, disablePushTitle = _ref3.disablePushTitle, forceShowDetailContent = _ref3.forceShowDetailContent; var serverPushConfigStr = pushConfigsToJSON(iOSConfig, androidConfig); return new Promise(function (resolve, reject) { var _this103 = this; _newArrowCheck(this, _this102); pushContent = pushContent || ''; pushData = pushData || ''; disableNotification = disableNotification || false; expansion = expansion || ''; isVoipPush = isVoipPush || false; pushTitle = pushTitle || ''; newPushContent = newPushContent || ''; newPushData = newPushData || ''; disablePushTitle = disablePushTitle || false; forceShowDetailContent = forceShowDetailContent || false; canIncludeExpansion = canIncludeExpansion || false; var notificationId = (androidConfig === null || androidConfig === void 0 ? void 0 : androidConfig.notificationId) || ''; var isGroup = conversationType === ConversationType$1.GROUP; directionalUserIdList = []; if (isGroup && messageType === MessageType$1.READ_RECEIPT_RESPONSE) { if (content.receiptMessageDic) { for (var _key19 in content.receiptMessageDic) { directionalUserIdList === null || directionalUserIdList === void 0 ? void 0 : directionalUserIdList.push(_key19); } } } if (isGroup && messageType === MessageType$1.READ_RECEIPT_REQUEST) { directionalUserIdList === null || directionalUserIdList === void 0 ? void 0 : directionalUserIdList.push(this.currentUserId); } var onSuccess = function onSuccess(message, code) { _newArrowCheck(this, _this103); var msg = this._buildMessage(message, false); if (code === ErrorCode$1.SENSITIVE_REPLACE) { return resolve({ code: code }); } return resolve({ code: ErrorCode$1.SUCCESS, data: msg }); }.bind(this); var onError = function onError(message, code) { _newArrowCheck(this, _this103); var msg = this._buildMessage(message, false); return resolve({ code: code, data: msg }); }.bind(this); var pushTplId = ''; this._cppProtocol.sendMessage(onSuccess, onError, conversationType, targetId, messageType, JSON.stringify(content), directionalUserIdList, disableNotification, disablePushTitle, forceShowDetailContent, pushContent, pushData, notificationId, pushTitle, serverPushConfigStr, pushTplId, canIncludeExpansion, JSON.stringify(expansion), isVoipPush); }.bind(this)); } }, { key: "recallMsg", value: function recallMsg(conversationType, targetId, messageUId, sentTime, user, pushContent) { var _this104 = this; return new Promise(function (resolve, reject) { var _this105 = this; _newArrowCheck(this, _this104); pushContent = pushContent || ''; var message = { conversationType: conversationType, targetId: targetId, senderUserId: this.currentUserId, content: null, objectName: MessageType$1.RECALL, messageUid: messageUId, messageDirection: MessageDirection$1.SEND, status: ReceivedStatus$1.UNREAD, sentTime: sentTime }; var returnMsg = this._buildMessage(JSON.stringify(message), false); var disableNotification = false; var disablePushTitle = false; var forceShowDetailContent = false; var pushData = ''; var notificationId = ''; var pushTitle = ''; var pushConfig = ''; var pushTemplateId = ''; var onSuccess = function onSuccess() { _newArrowCheck(this, _this105); resolve({ code: ErrorCode$1.SUCCESS, data: returnMsg }); }.bind(this); var onError = function onError(code) { _newArrowCheck(this, _this105); resolve({ code: code }); }.bind(this); this._cppProtocol.recallMessage(onSuccess, onError, MessageType$1.RECALL, JSON.stringify(returnMsg), disableNotification, disablePushTitle, forceShowDetailContent, pushContent, pushData, notificationId, pushTitle, pushConfig, pushTemplateId); }.bind(this)); } }, { key: "getHistoryMessage", value: function getHistoryMessage(conversationType, targetId, timestamp, count, order, messageType) { var _this106 = this; return new Promise(function (resolve, reject) { _newArrowCheck(this, _this106); timestamp = timestamp || 0; messageType = messageType || ''; var desc = order === 0; var cppMessagaes = this._cppProtocol.getHistoryMessages(conversationType, targetId, timestamp, count, messageType, desc); var messages = JSON.parse(cppMessagaes).list; var hisMessages = []; messages.reverse(); for (var i = 0; i < messages.length; i++) { var buildMsg = this._buildMessage(messages[i].obj); hisMessages[i] = buildMsg; } resolve({ code: ErrorCode$1.SUCCESS, data: { list: hisMessages, hasMore: messages.length === count } }); }.bind(this)); } }, { key: "deleteRemoteMessage", value: function deleteRemoteMessage(conversationType, targetId, messages) { var _this107 = this; return new Promise(function (resolve, reject) { _newArrowCheck(this, _this107); this._cppProtocol.clearMessages(conversationType, targetId); resolve(ErrorCode$1.SUCCESS); }.bind(this)); } }, { key: "deleteRemoteMessageByTimestamp", value: function deleteRemoteMessageByTimestamp(conversationType, targetId, timestamp) { var _this108 = this; return new Promise(function (resolve, reject) { var _this109 = this; _newArrowCheck(this, _this108); var onSuccess = function onSuccess() { _newArrowCheck(this, _this109); resolve(ErrorCode$1.SUCCESS); }.bind(this); var onError = function onError(code) { _newArrowCheck(this, _this109); resolve(code); }.bind(this); this._cppProtocol.clearRemoteHistoryMessages(conversationType, targetId, timestamp, onSuccess, onError); }.bind(this)); } }, { key: "getConversationList", value: function getConversationList(count, conversationType, startTime, order) { var _this110 = this; return new Promise(function (resolve, reject) { _newArrowCheck(this, _this110); var converTypes = [1, 3, 6, 7]; var result = this._cppProtocol.getConversationList(converTypes); var resultList = JSON.parse(result); var converList = resultList.list; var convers = []; for (var i = 0; i < converList.length; i++) { convers.push(this._buildConversation(converList[i].obj)); } resolve({ code: ErrorCode$1.SUCCESS, data: convers }); }.bind(this)); } }, { key: "getConversation", value: function getConversation(conversationType, targetId) { var _this111 = this; return new Promise(function (resolve, reject) { _newArrowCheck(this, _this111); var result = this._cppProtocol.getConversation(conversationType, targetId); resolve({ code: ErrorCode$1.SUCCESS, data: this._buildConversation(result) }); }.bind(this)); } }, { key: "removeConversation", value: function removeConversation(conversationType, targetId) { var _this112 = this; return new Promise(function (resolve, reject) { _newArrowCheck(this, _this112); this._cppProtocol.removeConversation(conversationType, targetId); resolve(ErrorCode$1.SUCCESS); }.bind(this)); } }, { key: "clearConversations", value: function clearConversations() { var _this113 = this; return new Promise(function (resolve, reject) { _newArrowCheck(this, _this113); this._cppProtocol.clearConversations(); resolve(ErrorCode$1.SUCCESS); }.bind(this)); } }, { key: "getAllConversationUnreadCount", value: function getAllConversationUnreadCount() { var _this114 = this; return new Promise(function (resolve, reject) { _newArrowCheck(this, _this114); var count = this._cppProtocol.getTotalUnreadCount(); resolve({ code: ErrorCode$1.SUCCESS, data: count }); }.bind(this)); } }, { key: "getConversationUnreadCount", value: function getConversationUnreadCount(conversationType, targetId) { var _this115 = this; return new Promise(function (resolve, reject) { _newArrowCheck(this, _this115); var count = this._cppProtocol.getUnreadCount(conversationType, targetId); resolve({ code: ErrorCode$1.SUCCESS, data: count }); }.bind(this)); } }, { key: "clearConversationUnreadCount", value: function clearConversationUnreadCount(conversationType, targetId) { var _this116 = this; return new Promise(function (resolve, reject) { _newArrowCheck(this, _this116); this._cppProtocol.clearUnreadCount(conversationType, targetId); resolve(ErrorCode$1.SUCCESS); }.bind(this)); } }, { key: "clearUnreadCountByTimestamp", value: function clearUnreadCountByTimestamp(conversationType, targetId) { var _this117 = this; return new Promise(function (resolve, reject) { _newArrowCheck(this, _this117); this._cppProtocol.clearUnreadCountByTimestamp(conversationType, targetId); resolve(ErrorCode$1.SUCCESS); }.bind(this)); } }, { key: "setConversationToTop", value: function setConversationToTop(conversationType, targetId, isTop) { var _this118 = this; return new Promise(function (resolve, reject) { _newArrowCheck(this, _this118); this._cppProtocol.setConversationToTop(conversationType, targetId, isTop); resolve(ErrorCode$1.SUCCESS); }.bind(this)); } }, { key: "setConversationHidden", value: function setConversationHidden(conversationType, targetId, isHidden) { var _this119 = this; return new Promise(function (resolve, reject) { _newArrowCheck(this, _this119); this._cppProtocol.setConversationHidden(conversationType, targetId, isHidden); resolve(ErrorCode$1.SUCCESS); }.bind(this)); } }, { key: "setConversationNotificationStatus", value: function setConversationNotificationStatus(conversationType, targetId, isNotify) { var _this120 = this; return new Promise(function (resolve, reject) { var _this121 = this; _newArrowCheck(this, _this120); this._cppProtocol.setConversationNotificationStatus(conversationType, targetId, isNotify, function () { _newArrowCheck(this, _this121); resolve(ErrorCode$1.SUCCESS); }.bind(this), resolve); }.bind(this)); } }, { key: "getConversationNotificationStatus", value: function getConversationNotificationStatus(conversationType, targetId) { var _this122 = this; return new Promise(function (resolve, reject) { _newArrowCheck(this, _this122); var notify = this._cppProtocol.getConversationNotificationStatus(conversationType, targetId); resolve({ code: ErrorCode$1.SUCCESS, data: notify }); }.bind(this)); } }, { key: "searchConversationByContent", value: function searchConversationByContent(keyword, conversationTypes) { var _this123 = this; return new Promise(function (resolve, reject) { _newArrowCheck(this, _this123); conversationTypes = conversationTypes || [1, 3, 6, 7]; var data = this._cppProtocol.searchConversationByContent(conversationTypes, keyword); var list = JSON.parse(data).list; var convers = []; for (var i = 0; i < list.length; i++) { convers[i] = this._buildConversation(list[i].obj); } resolve({ code: ErrorCode$1.SUCCESS, data: convers }); }.bind(this)); } }, { key: "searchMessageByContent", value: function searchMessageByContent(conversationType, targetId, keyword, timestamp, count, total) { var _this124 = this; return new Promise(function (resolve, reject) { var _this125 = this; _newArrowCheck(this, _this124); this._cppProtocol.searchMessageByContent(conversationType, targetId, keyword, timestamp, count, total, function (result, matched) { _newArrowCheck(this, _this125); var list = result ? JSON.parse(result).list : []; var msgs = []; for (var i = 0; i < list.length; i++) { msgs[i] = this._buildMessage(list[i].obj); } resolve({ code: ErrorCode$1.SUCCESS, data: msgs }); }.bind(this), function (code) { _newArrowCheck(this, _this125); resolve({ code: code }); }.bind(this)); }.bind(this)); } }, { key: "getUnreadMentionedMessages", value: function getUnreadMentionedMessages(conversationType, targetId) { var mentions = JSON.parse(this._cppProtocol.getUnreadMentionedMessages(conversationType, targetId)).list; for (var i = 0; i < mentions.length; i++) { mentions[i] = this._buildMessage(mentions[i].obj); } return mentions; } }, { key: "addToBlacklist", value: function addToBlacklist(userId) { var _this126 = this; return new Promise(function (resolve, reject) { var _this127 = this; _newArrowCheck(this, _this126); this._cppProtocol.addToBlacklist(userId, function () { _newArrowCheck(this, _this127); resolve(ErrorCode$1.SUCCESS); }.bind(this), resolve); }.bind(this)); } }, { key: "removeFromBlacklist", value: function removeFromBlacklist(userId) { var _this128 = this; return new Promise(function (resolve, reject) { var _this129 = this; _newArrowCheck(this, _this128); this._cppProtocol.removeFromBlacklist(userId, function () { _newArrowCheck(this, _this129); resolve(ErrorCode$1.SUCCESS); }.bind(this), resolve); }.bind(this)); } }, { key: "getBlacklist", value: function getBlacklist() { var _this130 = this; return new Promise(function (resolve, reject) { var _this131 = this; _newArrowCheck(this, _this130); this._cppProtocol.getBlacklist(function (userIds) { _newArrowCheck(this, _this131); resolve({ code: ErrorCode$1.SUCCESS, data: userIds }); }.bind(this), function (code) { _newArrowCheck(this, _this131); resolve({ code: code }); }.bind(this)); }.bind(this)); } }, { key: "getBlacklistStatus", value: function getBlacklistStatus(userId) { var _this132 = this; return new Promise(function (resolve, reject) { var _this133 = this; _newArrowCheck(this, _this132); this._cppProtocol.getBlacklistStatus(userId, function (result) { _newArrowCheck(this, _this133); resolve({ code: ErrorCode$1.SUCCESS, data: result }); }.bind(this), function (code) { _newArrowCheck(this, _this133); resolve({ code: code }); }.bind(this)); }.bind(this)); } }, { key: "insertMessage", value: function insertMessage(conversationType, targetId, senderUserId, messageType, msgContent, direction) { var _this134 = this; msgContent = JSON.stringify(msgContent); return new Promise(function (resolve, reject) { var _this135 = this; _newArrowCheck(this, _this134); var msg = this._cppProtocol.insertMessage(conversationType, targetId, senderUserId, messageType, msgContent, function () { _newArrowCheck(this, _this135); }.bind(this), function (error) { _newArrowCheck(this, _this135); resolve({ code: error }); }.bind(this), direction); var receivedMessage = this._buildMessage(msg, false); resolve({ code: ErrorCode$1.SUCCESS, data: receivedMessage }); }.bind(this)); } }, { key: "deleteMessages", value: function deleteMessages(timestamps) { var _this136 = this; return new Promise(function (resolve, reject) { _newArrowCheck(this, _this136); this._cppProtocol.deleteMessages(timestamps); resolve(ErrorCode$1.SUCCESS); }.bind(this)); } }, { key: "deleteMessagesByTimestamp", value: function deleteMessagesByTimestamp(conversationType, targetId, timestamp, cleanSpace) { var _this137 = this; return new Promise(function (resolve, reject) { _newArrowCheck(this, _this137); this._cppProtocol.deleteMessagesByTimestamp(conversationType, targetId, timestamp, cleanSpace); resolve(ErrorCode$1.SUCCESS); }.bind(this)); } }, { key: "getMessage", value: function getMessage(messageId) { var _this138 = this; return new Promise(function (resolve, reject) { _newArrowCheck(this, _this138); var result = this._cppProtocol.getMessage(messageId); var message = this._buildMessage(result, false); resolve({ code: ErrorCode$1.SUCCESS, data: message }); }.bind(this)); } }, { key: "setMessageContent", value: function setMessageContent(messageId, content, messageType) { var _this139 = this; return new Promise(function (resolve, reject) { _newArrowCheck(this, _this139); content = JSON.stringify(content); this._cppProtocol.setMessageContent(messageId, content, messageType); resolve(ErrorCode$1.SUCCESS); }.bind(this)); } }, { key: "setMessageSearchField", value: function setMessageSearchField(messageId, content, searchFiles) { var _this140 = this; return new Promise(function (resolve, reject) { _newArrowCheck(this, _this140); this._cppProtocol.setMessageSearchField(messageId, content, searchFiles); resolve(ErrorCode$1.SUCCESS); }.bind(this)); } }, { key: "setMessageSentStatus", value: function setMessageSentStatus(messageId, sentStatus) { var _this141 = this; return new Promise(function (resolve, reject) { _newArrowCheck(this, _this141); this._cppProtocol.setMessageSentStatus(messageId, sentStatus); resolve(ErrorCode$1.SUCCESS); }.bind(this)); } }, { key: "setMessageReceivedStatus", value: function setMessageReceivedStatus(messageId, receivedStatus) { var _this142 = this; return new Promise(function (resolve, reject) { _newArrowCheck(this, _this142); this._cppProtocol.setMessageReceivedStatus(messageId, receivedStatus); resolve(ErrorCode$1.SUCCESS); }.bind(this)); } }, { key: "saveConversationMessageDraft", value: function saveConversationMessageDraft(conversationType, targetId, draft) { throw new Error('Method not implemented.'); } }, { key: "getConversationMessageDraft", value: function getConversationMessageDraft(conversationType, targetId) { throw new Error('Method not implemented.'); } }, { key: "clearConversationMessageDraft", value: function clearConversationMessageDraft(conversationType, targetId) { throw new Error('Method not implemented.'); } }, { key: "pullConversationStatus", value: function pullConversationStatus(timestamp) { throw new Error('Method not implemented.'); } }, { key: "batchSetConversationStatus", value: function batchSetConversationStatus(statusList) { var _statusList$ = statusList[0], conversationType = _statusList$.conversationType, targetId = _statusList$.targetId, isTop = _statusList$.isTop, notificationStatus = _statusList$.notificationStatus; if (isTop !== undefined) { return this.setConversationToTop(conversationType, targetId, isTop); } else if (notificationStatus !== undefined) { var isBlocked = notificationStatus === NotificationStatus$1.OPEN; return this.setConversationNotificationStatus(conversationType, targetId, isBlocked); } else { this.setConversationToTop(conversationType, targetId, isTop); var _isBlocked = notificationStatus === NotificationStatus$1.OPEN; return this.setConversationNotificationStatus(conversationType, targetId, _isBlocked); } } }, { key: "pullUserSettings", value: function pullUserSettings(version) { throw new Error('Method not implemented.'); } }, { key: "joinChatroom", value: function joinChatroom(chatroomId, count) { var _this143 = this; return new Promise(function (resolve, reject) { var _this144 = this; _newArrowCheck(this, _this143); this._cppProtocol.joinChatRoom(chatroomId, count, function () { _newArrowCheck(this, _this144); resolve(ErrorCode$1.SUCCESS); }.bind(this), resolve); }.bind(this)); } }, { key: "joinExistChatroom", value: function joinExistChatroom(chatroomId, count) { throw new Error('Method not implemented.'); } }, { key: "quitChatroom", value: function quitChatroom(chatroomId) { var _this145 = this; return new Promise(function (resolve, reject) { var _this146 = this; _newArrowCheck(this, _this145); this._cppProtocol.quitChatRoom(chatroomId, function () { _newArrowCheck(this, _this146); resolve(ErrorCode$1.SUCCESS); }.bind(this), resolve); }.bind(this)); } }, { key: "getChatroomInfo", value: function getChatroomInfo(chatroomId, count, order) { var _this147 = this; return new Promise(function (resolve, reject) { var _this148 = this; _newArrowCheck(this, _this147); this._cppProtocol.getChatroomInfo(chatroomId, count, order, function (result, count) { _newArrowCheck(this, _this148); var list = result ? JSON.parse(result).list : []; var userInfos = []; if (list.length > 0) { for (var i = 0; i < list.length; i++) { userInfos.push(JSON.parse(list[i].obj)); } } resolve({ code: ErrorCode$1.SUCCESS, data: { userInfos: userInfos, userCount: count } }); }.bind(this), function (code) { _newArrowCheck(this, _this148); resolve({ code: code }); }.bind(this)); }.bind(this)); } }, { key: "getChatroomHistoryMessages", value: function getChatroomHistoryMessages(chatroomId, timestamp, count, order) { throw new Error('Method not implemented.'); } }, { key: "setChatroomEntry", value: function setChatroomEntry(chatroomId, entry) { throw new Error('Method not implemented.'); } }, { key: "forceSetChatroomEntry", value: function forceSetChatroomEntry(chatroomId, entry) { throw new Error('Method not implemented.'); } }, { key: "removeChatroomEntry", value: function removeChatroomEntry(chatroomId, entry) { throw new Error('Method not implemented.'); } }, { key: "forceRemoveChatroomEntry", value: function forceRemoveChatroomEntry(chatroomId, entry) { throw new Error('Method not implemented.'); } }, { key: "getChatroomEntry", value: function getChatroomEntry(chatroomId, key) { throw new Error('Method not implemented.'); } }, { key: "getAllChatroomEntry", value: function getAllChatroomEntry(chatroomId) { throw new Error('Method not implemented.'); } }, { key: "getFileToken", value: function getFileToken(fileType, fileName) { var _this149 = this; return new Promise(function (resolve, reject) { var _this150 = this; _newArrowCheck(this, _this149); var uploadFileName = getUploadFileName(fileType, fileName); this._cppProtocol.getUploadToken(fileType, uploadFileName, function (token, bosToken, bosDate, bosPath, ossToken, ossPolicy, ossSignature, ossBucketName) { _newArrowCheck(this, _this150); resolve({ code: ErrorCode$1.SUCCESS, data: { token: token, deadline: 0, bosToken: bosToken, bosDate: bosDate, path: bosPath, osskeyId: ossToken, ossPolicy: ossPolicy, ossSign: ossSignature, ossBucketName: ossBucketName, fileName: uploadFileName } }); }.bind(this), function (code) { _newArrowCheck(this, _this150); resolve({ code: code }); }.bind(this)); }.bind(this)); } }, { key: "getFileUrl", value: function getFileUrl(fileType, uploadMethod, fileName, originName) { var _this151 = this; return new Promise(function (resolve, reject) { var _this152 = this; _newArrowCheck(this, _this151); var onSuccess = function onSuccess(url) { _newArrowCheck(this, _this152); resolve({ code: ErrorCode$1.SUCCESS, data: { downloadUrl: url } }); }.bind(this); var onError = function onError(code) { _newArrowCheck(this, _this152); resolve({ code: code }); }.bind(this); var isOss = uploadMethod === UploadMethod$1.ALI; var mimeKey = getMimeKey(fileType); this._cppProtocol.getDownloadUrl(fileType, mimeKey, originName, isOss, onSuccess, onError); }.bind(this)); } }, { key: "clearData", value: function clearData() { var _this153 = this; return new Promise(function (resolve, reject) { _newArrowCheck(this, _this153); var result = this._cppProtocol.clearData(); resolve({ code: ErrorCode$1.SUCCESS, data: result }); }.bind(this)); } }, { key: "setDeviceInfo", value: function setDeviceInfo(device) { var _this154 = this; return new Promise(function (resolve, reject) { _newArrowCheck(this, _this154); var id = device.id || ''; this._cppProtocol.setDeviceInfo({ id: id }); }.bind(this)); } }, { key: "getVoIPKey", value: function getVoIPKey(engineType, channelName) { var _this155 = this; return new Promise(function (resolve, reject) { var _this156 = this; _newArrowCheck(this, _this155); var extra = ''; var onSuccess = function onSuccess(token) { _newArrowCheck(this, _this156); resolve({ code: ErrorCode$1.SUCCESS, data: token }); }.bind(this); var onError = function onError(code) { _newArrowCheck(this, _this156); resolve({ code: code }); }.bind(this); this._cppProtocol.getVoIPKey(engineType, channelName, extra, onSuccess, onError); }.bind(this)); } }, { key: "joinRTCRoom", value: function joinRTCRoom(roomId, mode, broadcastType) { throw new Error('Method not implemented.'); } }, { key: "quitRTCRoom", value: function quitRTCRoom(roomId) { throw new Error('Method not implemented.'); } }, { key: "rtcPing", value: function rtcPing(roomId, mode, broadcastType) { throw new Error('Method not implemented.'); } }, { key: "getRTCRoomInfo", value: function getRTCRoomInfo(roomId) { throw new Error('Method not implemented.'); } }, { key: "getRTCUserInfoList", value: function getRTCUserInfoList(roomId) { throw new Error('Method not implemented.'); } }, { key: "getRTCUserInfo", value: function getRTCUserInfo(roomId) { throw new Error('Method not implemented.'); } }, { key: "setRTCUserInfo", value: function setRTCUserInfo(roomId, key, value) { throw new Error('Method not implemented.'); } }, { key: "removeRTCUserInfo", value: function removeRTCUserInfo(roomId, keys) { throw new Error('Method not implemented.'); } }, { key: "setRTCData", value: function setRTCData(roomId, key, value, isInner, apiType, message) { throw new Error('Method not implemented.'); } }, { key: "setRTCTotalRes", value: function setRTCTotalRes(roomId, message, valueInfo, messageType) { throw new Error('Method not implemented.'); } }, { key: "getRTCData", value: function getRTCData(roomId, keys, isInner, apiType) { throw new Error('Method not implemented.'); } }, { key: "removeRTCData", value: function removeRTCData(roomId, keys, isInner, apiType, message) { throw new Error('Method not implemented.'); } }, { key: "setRTCOutData", value: function setRTCOutData(roomId, rtcData, type, message) { throw new Error('Method not implemented.'); } }, { key: "getRTCOutData", value: function getRTCOutData(roomId, userIds) { throw new Error('Method not implemented.'); } }, { key: "getRTCToken", value: function getRTCToken(roomId, mode, broadcastType) { throw new Error('Method not implemented.'); } }, { key: "setRTCState", value: function setRTCState(roomId, reportId) { throw new Error('Method not implemented.'); } }, { key: "getRTCUserList", value: function getRTCUserList(roomId) { throw new Error('Method not implemented.'); } }]); return CPPEngine; }(AEngine); var PluginContext = function () { function PluginContext(_context) { _classCallCheck(this, PluginContext); this._context = _context; } _createClass(PluginContext, [{ key: "getCoreVersion", value: function getCoreVersion() { return this._context.coreVersion; } }, { key: "getAPIVersion", value: function getAPIVersion() { return this._context.apiVersion; } }, { key: "getAppkey", value: function getAppkey() { return this._context.appkey; } }, { key: "getCurrentId", value: function getCurrentId() { return this._context.getCurrentUserId(); } }, { key: "getConnectionStatus", value: function getConnectionStatus() { return this._context.getConnectionStatus(); } }, { key: "sendMessage", value: function sendMessage(conversationType, targetId, options) { return this._context.sendMessage(conversationType, targetId, options); } }, { key: "registerMessageType", value: function registerMessageType(objectName, isPersited, isCounted) { var searchProps = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : []; this._context.registerMessageType(objectName, isPersited, isCounted, searchProps); } }]); return PluginContext; }(); var RTCPluginContext = function (_PluginContext) { _inherits(RTCPluginContext, _PluginContext); var _super20 = _createSuper(RTCPluginContext); function RTCPluginContext() { _classCallCheck(this, RTCPluginContext); return _super20.apply(this, arguments); } _createClass(RTCPluginContext, [{ key: "getNaviInfo", value: function getNaviInfo() { return this._context.getInfoFromCache(); } }, { key: "joinRTCRoom", value: function joinRTCRoom(roomId, mode, broadcastType) { return this._context.joinRTCRoom(roomId, mode, broadcastType); } }, { key: "quitRTCRoom", value: function quitRTCRoom(roomId) { return this._context.quitRTCRoom(roomId); } }, { key: "rtcPing", value: function rtcPing(roomId, mode, broadcastType) { return this._context.rtcPing(roomId, mode, broadcastType); } }, { key: "getRTCRoomInfo", value: function getRTCRoomInfo(roomId) { return this._context.getRTCRoomInfo(roomId); } }, { key: "getRTCUserInfoList", value: function getRTCUserInfoList(roomId) { return this._context.getRTCUserInfoList(roomId); } }, { key: "getRTCUserInfo", value: function getRTCUserInfo(roomId) { return this._context.getRTCUserInfo(roomId); } }, { key: "setRTCUserInfo", value: function setRTCUserInfo(roomId, key, value) { return this._context.setRTCUserInfo(roomId, key, value); } }, { key: "removeRTCUserInfo", value: function removeRTCUserInfo(roomId, keys) { return this._context.removeRTCUserInfo(roomId, keys); } }, { key: "setRTCData", value: function setRTCData(roomId, key, value, isInner, apiType, message) { return this._context.setRTCData(roomId, key, value, isInner, apiType, message); } }, { key: "setRTCTotalRes", value: function setRTCTotalRes(roomId, message, valueInfo, objectName) { return this._context.setRTCTotalRes(roomId, message, valueInfo, objectName); } }, { key: "getRTCData", value: function getRTCData(roomId, keys, isInner, apiType) { return this._context.getRTCData(roomId, keys, isInner, apiType); } }, { key: "removeRTCData", value: function removeRTCData(roomId, keys, isInner, apiType, message) { return this._context.removeRTCData(roomId, keys, isInner, apiType, message); } }, { key: "setRTCOutData", value: function setRTCOutData(roomId, rtcData, type, message) { return this._context.setRTCOutData(roomId, rtcData, type, message); } }, { key: "getRTCOutData", value: function getRTCOutData(roomId, userIds) { return this._context.getRTCOutData(roomId, userIds); } }, { key: "getRTCToken", value: function getRTCToken(roomId, mode, broadcastType) { return this._context.getRTCToken(roomId, mode, broadcastType); } }, { key: "setRTCState", value: function setRTCState(roomId, report) { return this._context.setRTCState(roomId, report); } }, { key: "getRTCUserList", value: function getRTCUserList(roomId) { return this._context.getRTCUserList(roomId); } }]); return RTCPluginContext; }(PluginContext); function cloneMessage(message) { return Object.assign({}, message); } var APIContext = function () { function APIContext(_runtime, options) { var _this157 = this; _classCallCheck(this, APIContext); this._runtime = _runtime; this._token = ''; this._pluginContextQueue = []; this.coreVersion = "4.1.0"; this._connectionStatus = ConnectionStatus$1.DISCONNECTED; this._watcher = { message: undefined, conversationState: undefined, chatroomState: undefined, connectionState: undefined, rtcInnerWatcher: undefined, expansion: undefined }; this._options = Object.assign({}, options); this.appkey = this._options.appkey; this.apiVersion = this._options.apiVersion; var _this$_options = this._options, isEnterPrise = _this$_options.isEnterPrise, appkey = _this$_options.appkey, miniCMPProxy = _this$_options.miniCMPProxy, apiVersion = _this$_options.apiVersion, connectionType = _this$_options.connectionType; if (_runtime.tag === "electron" && !this._options.cppProtocol) { var msg = 'cppProtocol is required'; logger.error(msg); throw new Error(msg); } if (isEnterPrise && this._options.navigators.length === 0) { var _msg = 'private navigators is required'; logger.error(_msg); throw new Error(_msg); } this._options.navigators = this._options.navigators.filter(function (item) { _newArrowCheck(this, _this157); return /^https?:\/\//.test(item); }.bind(this)); if (this._options.navigators.length === 0) { var _this$_options$naviga; if (isEnterPrise) { var _msg2 = 'navi urls is invalid'; logger.error(_msg2); throw new Error(_msg2); } (_this$_options$naviga = this._options.navigators).push.apply(_this$_options$naviga, PUBLIC_CLOUD_NAVI_URIS); } this._navi = new Navi(_runtime, appkey, this._options.navigators, miniCMPProxy, apiVersion, connectionType); var engineWatcher = { status: this._connectionStatusListener.bind(this), message: this._messageReceiver.bind(this), chatroom: this._chatroomInfoListener.bind(this), conversation: this._conversationInfoListener.bind(this), expansion: this._expansionInfoListener.bind(this) }; this._engine = this._options.cppProtocol ? new CPPEngine(_runtime, appkey, engineWatcher, apiVersion, this._options.cppProtocol, this._options) : new JSEngine(_runtime, appkey, engineWatcher, apiVersion); } _createClass(APIContext, [{ key: "install", value: function install(plugin, options) { var context = plugin.tag === 'RCRTC' ? new RTCPluginContext(this) : new PluginContext(this); var pluginClient = null; try { if (!plugin.verify(this._runtime)) { return null; } pluginClient = plugin.setup(context, this._runtime, options); } catch (error) { logger.error('install plugin error!\n', error); } pluginClient && this._pluginContextQueue.push(context); return pluginClient; } }, { key: "_connectionStatusListener", value: function _connectionStatusListener(status) { var _this158 = this; var _a; this._connectionStatus = status; ((_a = this._watcher.rtcInnerWatcher) === null || _a === void 0 ? void 0 : _a.status) && this._watcher.rtcInnerWatcher.status(status); this._pluginContextQueue.forEach(function (item) { _newArrowCheck(this, _this158); item.onconnectionstatechange && item.onconnectionstatechange(status); }.bind(this)); this._watcher.connectionState && this._watcher.connectionState(status); } }, { key: "_messageReceiver", value: function _messageReceiver(message) { var _this159 = this; if (message.conversationType === ConversationType$1.RTC_ROOM || Object.prototype.hasOwnProperty.call(CallLibMsgType, message.messageType)) { if (this._watcher.rtcInnerWatcher && this._watcher.rtcInnerWatcher.message) { this._watcher.rtcInnerWatcher.message(cloneMessage(message)); return; } } if (this._pluginContextQueue.some(function (item) { _newArrowCheck(this, _this159); if (!item.onmessage) { return false; } try { return item.onmessage(cloneMessage(message)); } catch (err) { logger.error('plugin error =>', err); return false; } }.bind(this))) { return; } this._watcher.message && this._watcher.message(cloneMessage(message)); } }, { key: "_chatroomInfoListener", value: function _chatroomInfoListener(info) { this._watcher.chatroomState && this._watcher.chatroomState(info); } }, { key: "_conversationInfoListener", value: function _conversationInfoListener(info) { this._watcher.conversationState && this._watcher.conversationState(info); } }, { key: "_expansionInfoListener", value: function _expansionInfoListener(info) { this._watcher.expansion && this._watcher.expansion(info); } }, { key: "assignWatcher", value: function assignWatcher(watcher) { var _this160 = this; Object.keys(this._watcher).forEach(function (key) { _newArrowCheck(this, _this160); if (Object.prototype.hasOwnProperty.call(watcher, key)) { var value = watcher[key]; this._watcher[key] = isFunction(value) || isObject(value) ? value : undefined; } }.bind(this)); } }, { key: "getConnectedTime", value: function getConnectedTime() { return this._engine.connectedTime; } }, { key: "getCurrentUserId", value: function getCurrentUserId() { return this._engine.currentUserId; } }, { key: "getConnectionStatus", value: function getConnectionStatus() { return this._connectionStatus; } }, { key: "connect", value: function connect(token) { var refreshNavi = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; return __awaiter$1(this, void 0, void 0, regeneratorRuntime.mark(function _callee58() { var _this161 = this; var tmpArr, dynamicUris, isCppMode, naviInfo, code; return regeneratorRuntime.wrap(function _callee58$(_context60) { while (1) { switch (_context60.prev = _context60.next) { case 0: if (!(this._connectionStatus === ConnectionStatus$1.CONNECTED)) { _context60.next = 2; break; } return _context60.abrupt("return", { code: ErrorCode$1.SUCCESS, userId: this._engine.currentUserId }); case 2: if (!(this._connectionStatus === ConnectionStatus$1.CONNECTING)) { _context60.next = 4; break; } return _context60.abrupt("return", { code: ErrorCode$1.BIZ_ERROR_CONNECTING }); case 4: if (!(typeof token !== 'string' || token.length === 0)) { _context60.next = 6; break; } return _context60.abrupt("return", { code: ErrorCode$1.RC_CONN_USER_OR_PASSWD_ERROR }); case 6: this._token = token; tmpArr = token.split('@'); dynamicUris = tmpArr[1] ? tmpArr[1].split(';').map(function (item) { _newArrowCheck(this, _this161); return /^https?:/.test(item) ? item : "https://".concat(item); }.bind(this)) : []; isCppMode = !!this._options.cppProtocol; _context60.next = 12; return this._navi.getInfo(this._getTokenWithoutNavi(), dynamicUris, refreshNavi, isCppMode); case 12: naviInfo = _context60.sent; if (!(!naviInfo && !isCppMode)) { _context60.next = 15; break; } return _context60.abrupt("return", { code: ErrorCode$1.RC_NAVI_RESOURCE_ERROR }); case 15: _context60.next = 17; return this._engine.connect(this._getTokenWithoutNavi(), naviInfo, this._options.connectionType); case 17: code = _context60.sent; if (code === ErrorCode$1.SUCCESS && !isCppMode) { naviInfo.openUS === 1 && this._pullUserSettings(); } return _context60.abrupt("return", { code: code, userId: this._engine.currentUserId }); case 20: case "end": return _context60.stop(); } } }, _callee58, this); })); } }, { key: "getConnectTime", value: function getConnectTime() { return this._engine.getConnectTime(); } }, { key: "_pullUserSettings", value: function _pullUserSettings() { return __awaiter$1(this, void 0, void 0, regeneratorRuntime.mark(function _callee59() { return regeneratorRuntime.wrap(function _callee59$(_context61) { while (1) { switch (_context61.prev = _context61.next) { case 0: case "end": return _context61.stop(); } } }, _callee59); })); } }, { key: "disconnect", value: function disconnect() { var _this162 = this; this._engine.disconnect(); this._pluginContextQueue.forEach(function (item) { _newArrowCheck(this, _this162); if (!item.ondisconnect) { return; } try { item.ondisconnect(); } catch (err) { logger.error('plugin error =>', err); } }.bind(this)); return Promise.resolve(); } }, { key: "reconnect", value: function reconnect() { return this.connect(this._getTokenWithoutNavi()); } }, { key: "_getTokenWithoutNavi", value: function _getTokenWithoutNavi() { return this._token.replace(/@.+$/, '@'); } }, { key: "getInfoFromCache", value: function getInfoFromCache() { return this._navi.getInfoFromCache(this._getTokenWithoutNavi()); } }, { key: "registerMessageType", value: function registerMessageType(objectName, isPersited, isCounted) { var searchProps = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : []; this._engine.registerMessageType(objectName, isPersited, isCounted, searchProps); } }, { key: "sendMessage", value: function sendMessage(conversationType, targetId, options) { var contentJson = JSON.stringify(options.content); if (getByteLength(contentJson) > MAX_MESSAGE_CONTENT_BYTES) { return Promise.resolve({ code: ErrorCode$1.RC_MSG_CONTENT_EXCEED_LIMIT }); } return this._engine.sendMessage(conversationType, targetId, options); } }, { key: "sendExpansionMessage", value: function sendExpansionMessage(options) { return __awaiter$1(this, void 0, void 0, regeneratorRuntime.mark(function _callee60() { var conversationType, targetId, messageUId, keys, expansion, originExpansion, removeAll, canIncludeExpansion, isExceedLimit, isIllgalEx, exKeysLength, totalExpansion, totalExKeysLength, _key20, val, content, _yield$this$_engine$s, code; return regeneratorRuntime.wrap(function _callee60$(_context62) { while (1) { switch (_context62.prev = _context62.next) { case 0: conversationType = options.conversationType, targetId = options.targetId, messageUId = options.messageUId, keys = options.keys, expansion = options.expansion, originExpansion = options.originExpansion, removeAll = options.removeAll, canIncludeExpansion = options.canIncludeExpansion; if (canIncludeExpansion) { _context62.next = 3; break; } return _context62.abrupt("return", { code: ErrorCode$1.MESSAGE_KV_NOT_SUPPORT }); case 3: isExceedLimit = false; isIllgalEx = false; if (isObject(expansion)) { originExpansion = originExpansion || {}; exKeysLength = Object.keys(expansion).length; totalExpansion = Object.assign(originExpansion, expansion); totalExKeysLength = Object.keys(totalExpansion).length; isExceedLimit = totalExKeysLength > 300 || exKeysLength > 20; for (_key20 in expansion) { val = expansion[_key20]; isExceedLimit = _key20.length > 32 || val.length > 64; isIllgalEx = !/^[A-Za-z0-9_=+-]+$/.test(_key20); } } if (!isExceedLimit) { _context62.next = 8; break; } return _context62.abrupt("return", { code: ErrorCode$1.EXPANSION_LIMIT_EXCEET }); case 8: if (!isIllgalEx) { _context62.next = 10; break; } return _context62.abrupt("return", { code: ErrorCode$1.BIZ_ERROR_INVALID_PARAMETER }); case 10: content = { mid: messageUId }; expansion && (content.put = expansion); keys && (content.del = keys); removeAll && (content.removeAll = 1); _context62.next = 16; return this._engine.sendMessage(conversationType, targetId, { content: content, messageType: MessageType$1.EXPANSION_NOTIFY }); case 16: _yield$this$_engine$s = _context62.sent; code = _yield$this$_engine$s.code; return _context62.abrupt("return", { code: code }); case 19: case "end": return _context62.stop(); } } }, _callee60, this); })); } }, { key: "_destroy", value: function _destroy() { var _this163 = this; this._watcher = {}; this._engine.disconnect(); this._pluginContextQueue.forEach(function (item) { _newArrowCheck(this, _this163); if (!item.ondestroy) { return; } try { item.ondestroy(); } catch (err) { logger.error('plugin error =>', err); } }.bind(this)); this._pluginContextQueue.length = 0; } }, { key: "getHistoryMessage", value: function getHistoryMessage(conversationType, targetId) { var timestamp = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; var count = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 20; var order = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 0; return this._engine.getHistoryMessage(conversationType, targetId, timestamp, count, order); } }, { key: "getConversationList", value: function getConversationList() { var count = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 300; var conversationType = arguments.length > 1 ? arguments[1] : undefined; var startTime = arguments.length > 2 ? arguments[2] : undefined; var order = arguments.length > 3 ? arguments[3] : undefined; return this._engine.getConversationList(count, conversationType, startTime, order); } }, { key: "removeConversation", value: function removeConversation(conversationType, targetId) { return this._engine.removeConversation(conversationType, targetId); } }, { key: "clearUnreadCount", value: function clearUnreadCount(conversationType, targetId) { return this._engine.clearConversationUnreadCount(conversationType, targetId); } }, { key: "getUnreadCount", value: function getUnreadCount(conversationType, targetId) { return this._engine.getConversationUnreadCount(conversationType, targetId); } }, { key: "getTotalUnreadCount", value: function getTotalUnreadCount() { return this._engine.getAllConversationUnreadCount(); } }, { key: "setConversationStatus", value: function setConversationStatus(conversationType, targetId, isTop, notificationStatus) { var statusList = [{ conversationType: conversationType, targetId: targetId, isTop: isTop, notificationStatus: notificationStatus }]; return this._engine.batchSetConversationStatus(statusList); } }, { key: "saveConversationMessageDraft", value: function saveConversationMessageDraft(conversationType, targetId, draft) { return this._engine.saveConversationMessageDraft(conversationType, targetId, draft); } }, { key: "getConversationMessageDraft", value: function getConversationMessageDraft(conversationType, targetId) { return this._engine.getConversationMessageDraft(conversationType, targetId); } }, { key: "clearConversationMessageDraft", value: function clearConversationMessageDraft(conversationType, targetId) { return this._engine.clearConversationMessageDraft(conversationType, targetId); } }, { key: "recallMessage", value: function recallMessage(conversationType, targetId, messageUId, sentTime, user) { return this._engine.recallMsg(conversationType, targetId, messageUId, sentTime, user); } }, { key: "deleteRemoteMessage", value: function deleteRemoteMessage(conversationType, targetId, list) { return this._engine.deleteRemoteMessage(conversationType, targetId, list); } }, { key: "deleteRemoteMessageByTimestamp", value: function deleteRemoteMessageByTimestamp(conversationType, targetId, timestamp) { return this._engine.deleteRemoteMessageByTimestamp(conversationType, targetId, timestamp); } }, { key: "joinChatroom", value: function joinChatroom(roomId) { var count = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 10; return this._engine.joinChatroom(roomId, count); } }, { key: "joinExistChatroom", value: function joinExistChatroom(roomId) { var count = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 10; return this._engine.joinExistChatroom(roomId, count); } }, { key: "quitChatroom", value: function quitChatroom(roomId) { return this._engine.quitChatroom(roomId); } }, { key: "getChatroomInfo", value: function getChatroomInfo(roomId) { var count = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; var order = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; return this._engine.getChatroomInfo(roomId, count, order); } }, { key: "setChatroomEntry", value: function setChatroomEntry(roomId, entry) { return this._engine.setChatroomEntry(roomId, entry); } }, { key: "forceSetChatroomEntry", value: function forceSetChatroomEntry(roomId, entry) { return this._engine.forceSetChatroomEntry(roomId, entry); } }, { key: "removeChatroomEntry", value: function removeChatroomEntry(roomId, entry) { return this._engine.removeChatroomEntry(roomId, entry); } }, { key: "forceRemoveChatroomEntry", value: function forceRemoveChatroomEntry(roomId, entry) { return this._engine.forceRemoveChatroomEntry(roomId, entry); } }, { key: "getChatroomEntry", value: function getChatroomEntry(roomId, key) { return this._engine.getChatroomEntry(roomId, key); } }, { key: "getAllChatroomEntries", value: function getAllChatroomEntries(roomId) { return this._engine.getAllChatroomEntry(roomId); } }, { key: "getChatRoomHistoryMessages", value: function getChatRoomHistoryMessages(roomId) { var count = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 20; var order = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; var timestamp = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; return this._engine.getChatroomHistoryMessages(roomId, timestamp, count, order); } }, { key: "getFileToken", value: function getFileToken(fileType, fileName) { return __awaiter$1(this, void 0, void 0, regeneratorRuntime.mark(function _callee61() { var naviInfo, bos, qiniu, ossConfig, _yield$this$_engine$g, code, data; return regeneratorRuntime.wrap(function _callee61$(_context63) { while (1) { switch (_context63.prev = _context63.next) { case 0: naviInfo = this.getInfoFromCache(); bos = (naviInfo === null || naviInfo === void 0 ? void 0 : naviInfo.bosAddr) || ''; qiniu = (naviInfo === null || naviInfo === void 0 ? void 0 : naviInfo.uploadServer) || ''; ossConfig = (naviInfo === null || naviInfo === void 0 ? void 0 : naviInfo.ossConfig) || ''; _context63.next = 6; return this._engine.getFileToken(fileType, fileName); case 6: _yield$this$_engine$g = _context63.sent; code = _yield$this$_engine$g.code; data = _yield$this$_engine$g.data; if (!(code === ErrorCode$1.SUCCESS)) { _context63.next = 11; break; } return _context63.abrupt("return", Promise.resolve(Object.assign(data, { bos: bos, qiniu: qiniu, ossConfig: ossConfig }))); case 11: return _context63.abrupt("return", Promise.reject(code)); case 12: case "end": return _context63.stop(); } } }, _callee61, this); })); } }, { key: "getFileUrl", value: function getFileUrl(fileType, fileName, originName, uploadRes) { var uploadMethod = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : UploadMethod$1.QINIU; return __awaiter$1(this, void 0, void 0, regeneratorRuntime.mark(function _callee62() { var _yield$this$_engine$g2, code, data; return regeneratorRuntime.wrap(function _callee62$(_context64) { while (1) { switch (_context64.prev = _context64.next) { case 0: if (!(uploadRes === null || uploadRes === void 0 ? void 0 : uploadRes.isBosRes)) { _context64.next = 2; break; } return _context64.abrupt("return", Promise.resolve(uploadRes)); case 2: _context64.next = 4; return this._engine.getFileUrl(fileType, uploadMethod, fileName, originName); case 4: _yield$this$_engine$g2 = _context64.sent; code = _yield$this$_engine$g2.code; data = _yield$this$_engine$g2.data; if (!(code === ErrorCode$1.SUCCESS)) { _context64.next = 9; break; } return _context64.abrupt("return", Promise.resolve(data)); case 9: return _context64.abrupt("return", Promise.reject(code)); case 10: case "end": return _context64.stop(); } } }, _callee62, this); })); } }, { key: "clearConversations", value: function clearConversations() { return __awaiter$1(this, void 0, void 0, regeneratorRuntime.mark(function _callee63() { return regeneratorRuntime.wrap(function _callee63$(_context65) { while (1) { switch (_context65.prev = _context65.next) { case 0: _context65.next = 2; return this._engine.clearConversations(); case 2: return _context65.abrupt("return", _context65.sent); case 3: case "end": return _context65.stop(); } } }, _callee63, this); })); } }, { key: "setUserStatusListener", value: function setUserStatusListener(config, listener) { var _this164 = this; return this._engine.setUserStatusListener(config, function (data) { _newArrowCheck(this, _this164); try { listener(data); } catch (error) { logger.error(error); } }.bind(this)); } }, { key: "addToBlacklist", value: function addToBlacklist(userId) { return __awaiter$1(this, void 0, void 0, regeneratorRuntime.mark(function _callee64() { return regeneratorRuntime.wrap(function _callee64$(_context66) { while (1) { switch (_context66.prev = _context66.next) { case 0: return _context66.abrupt("return", this._engine.addToBlacklist(userId)); case 1: case "end": return _context66.stop(); } } }, _callee64, this); })); } }, { key: "removeFromBlacklist", value: function removeFromBlacklist(userId) { return __awaiter$1(this, void 0, void 0, regeneratorRuntime.mark(function _callee65() { return regeneratorRuntime.wrap(function _callee65$(_context67) { while (1) { switch (_context67.prev = _context67.next) { case 0: return _context67.abrupt("return", this._engine.removeFromBlacklist(userId)); case 1: case "end": return _context67.stop(); } } }, _callee65, this); })); } }, { key: "getBlacklist", value: function getBlacklist() { return __awaiter$1(this, void 0, void 0, regeneratorRuntime.mark(function _callee66() { return regeneratorRuntime.wrap(function _callee66$(_context68) { while (1) { switch (_context68.prev = _context68.next) { case 0: return _context68.abrupt("return", this._engine.getBlacklist()); case 1: case "end": return _context68.stop(); } } }, _callee66, this); })); } }, { key: "getBlacklistStatus", value: function getBlacklistStatus(userId) { return __awaiter$1(this, void 0, void 0, regeneratorRuntime.mark(function _callee67() { return regeneratorRuntime.wrap(function _callee67$(_context69) { while (1) { switch (_context69.prev = _context69.next) { case 0: return _context69.abrupt("return", this._engine.getBlacklistStatus(userId)); case 1: case "end": return _context69.stop(); } } }, _callee67, this); })); } }, { key: "insertMessage", value: function insertMessage(conversationType, targetId, senderUserId, messageType, msgContent, direction) { return __awaiter$1(this, void 0, void 0, regeneratorRuntime.mark(function _callee68() { return regeneratorRuntime.wrap(function _callee68$(_context70) { while (1) { switch (_context70.prev = _context70.next) { case 0: return _context70.abrupt("return", this._engine.insertMessage(conversationType, targetId, senderUserId, messageType, msgContent, direction)); case 1: case "end": return _context70.stop(); } } }, _callee68, this); })); } }, { key: "deleteMessages", value: function deleteMessages(timestamp) { return __awaiter$1(this, void 0, void 0, regeneratorRuntime.mark(function _callee69() { return regeneratorRuntime.wrap(function _callee69$(_context71) { while (1) { switch (_context71.prev = _context71.next) { case 0: return _context71.abrupt("return", this._engine.deleteMessages(timestamp)); case 1: case "end": return _context71.stop(); } } }, _callee69, this); })); } }, { key: "deleteMessagesByTimestamp", value: function deleteMessagesByTimestamp(conversationType, targetId, timestamp, cleanSpace) { return __awaiter$1(this, void 0, void 0, regeneratorRuntime.mark(function _callee70() { return regeneratorRuntime.wrap(function _callee70$(_context72) { while (1) { switch (_context72.prev = _context72.next) { case 0: return _context72.abrupt("return", this._engine.deleteMessagesByTimestamp(conversationType, targetId, timestamp, cleanSpace)); case 1: case "end": return _context72.stop(); } } }, _callee70, this); })); } }, { key: "getMessage", value: function getMessage(messageId) { return __awaiter$1(this, void 0, void 0, regeneratorRuntime.mark(function _callee71() { return regeneratorRuntime.wrap(function _callee71$(_context73) { while (1) { switch (_context73.prev = _context73.next) { case 0: return _context73.abrupt("return", this._engine.getMessage(messageId)); case 1: case "end": return _context73.stop(); } } }, _callee71, this); })); } }, { key: "setMessageContent", value: function setMessageContent(messageId, content, messageType) { return __awaiter$1(this, void 0, void 0, regeneratorRuntime.mark(function _callee72() { return regeneratorRuntime.wrap(function _callee72$(_context74) { while (1) { switch (_context74.prev = _context74.next) { case 0: return _context74.abrupt("return", this._engine.setMessageContent(messageId, content, messageType)); case 1: case "end": return _context74.stop(); } } }, _callee72, this); })); } }, { key: "setMessageSearchField", value: function setMessageSearchField(messageId, content, searchFiles) { return __awaiter$1(this, void 0, void 0, regeneratorRuntime.mark(function _callee73() { return regeneratorRuntime.wrap(function _callee73$(_context75) { while (1) { switch (_context75.prev = _context75.next) { case 0: return _context75.abrupt("return", this._engine.setMessageSearchField(messageId, content, searchFiles)); case 1: case "end": return _context75.stop(); } } }, _callee73, this); })); } }, { key: "setMessageSentStatus", value: function setMessageSentStatus(messageId, sentStatus) { return __awaiter$1(this, void 0, void 0, regeneratorRuntime.mark(function _callee74() { return regeneratorRuntime.wrap(function _callee74$(_context76) { while (1) { switch (_context76.prev = _context76.next) { case 0: return _context76.abrupt("return", this._engine.setMessageSentStatus(messageId, sentStatus)); case 1: case "end": return _context76.stop(); } } }, _callee74, this); })); } }, { key: "setMessageReceivedStatus", value: function setMessageReceivedStatus(messageId, receivedStatus) { return __awaiter$1(this, void 0, void 0, regeneratorRuntime.mark(function _callee75() { return regeneratorRuntime.wrap(function _callee75$(_context77) { while (1) { switch (_context77.prev = _context77.next) { case 0: return _context77.abrupt("return", this._engine.setMessageReceivedStatus(messageId, receivedStatus)); case 1: case "end": return _context77.stop(); } } }, _callee75, this); })); } }, { key: "setUserStatus", value: function setUserStatus(status) { return __awaiter$1(this, void 0, void 0, regeneratorRuntime.mark(function _callee76() { return regeneratorRuntime.wrap(function _callee76$(_context78) { while (1) { switch (_context78.prev = _context78.next) { case 0: return _context78.abrupt("return", this._engine.setUserStatus(status)); case 1: case "end": return _context78.stop(); } } }, _callee76, this); })); } }, { key: "subscribeUserStatus", value: function subscribeUserStatus(userIds) { return __awaiter$1(this, void 0, void 0, regeneratorRuntime.mark(function _callee77() { return regeneratorRuntime.wrap(function _callee77$(_context79) { while (1) { switch (_context79.prev = _context79.next) { case 0: return _context79.abrupt("return", this._engine.subscribeUserStatus(userIds)); case 1: case "end": return _context79.stop(); } } }, _callee77, this); })); } }, { key: "getUserStatus", value: function getUserStatus(userId) { return __awaiter$1(this, void 0, void 0, regeneratorRuntime.mark(function _callee78() { return regeneratorRuntime.wrap(function _callee78$(_context80) { while (1) { switch (_context80.prev = _context80.next) { case 0: return _context80.abrupt("return", this._engine.getUserStatus(userId)); case 1: case "end": return _context80.stop(); } } }, _callee78, this); })); } }, { key: "searchConversationByContent", value: function searchConversationByContent(keyword, conversationTypes) { return __awaiter$1(this, void 0, void 0, regeneratorRuntime.mark(function _callee79() { return regeneratorRuntime.wrap(function _callee79$(_context81) { while (1) { switch (_context81.prev = _context81.next) { case 0: return _context81.abrupt("return", this._engine.searchConversationByContent(keyword, conversationTypes)); case 1: case "end": return _context81.stop(); } } }, _callee79, this); })); } }, { key: "searchMessageByContent", value: function searchMessageByContent(conversationType, targetId, keyword, timestamp, count, total) { return __awaiter$1(this, void 0, void 0, regeneratorRuntime.mark(function _callee80() { return regeneratorRuntime.wrap(function _callee80$(_context82) { while (1) { switch (_context82.prev = _context82.next) { case 0: return _context82.abrupt("return", this._engine.searchMessageByContent(conversationType, targetId, keyword, timestamp, count, total)); case 1: case "end": return _context82.stop(); } } }, _callee80, this); })); } }, { key: "getUnreadMentionedMessages", value: function getUnreadMentionedMessages(conversationType, targetId) { return this._engine.getUnreadMentionedMessages(conversationType, targetId); } }, { key: "joinRTCRoom", value: function joinRTCRoom(roomId, mode, mediaType) { return this._engine.joinRTCRoom(roomId, mode, mediaType); } }, { key: "quitRTCRoom", value: function quitRTCRoom(roomId) { return this._engine.quitRTCRoom(roomId); } }, { key: "rtcPing", value: function rtcPing(roomId, mode, mediaType) { return this._engine.rtcPing(roomId, mode, mediaType); } }, { key: "getRTCRoomInfo", value: function getRTCRoomInfo(roomId) { return this._engine.getRTCRoomInfo(roomId); } }, { key: "getRTCUserInfoList", value: function getRTCUserInfoList(roomId) { return this._engine.getRTCUserInfoList(roomId); } }, { key: "getRTCUserInfo", value: function getRTCUserInfo(roomId) { return this._engine.getRTCUserInfo(roomId); } }, { key: "setRTCUserInfo", value: function setRTCUserInfo(roomId, key, value) { return this._engine.setRTCUserInfo(roomId, key, value); } }, { key: "removeRTCUserInfo", value: function removeRTCUserInfo(roomId, keys) { return this._engine.removeRTCUserInfo(roomId, keys); } }, { key: "setRTCData", value: function setRTCData(roomId, key, value, isInner, apiType, message) { return this._engine.setRTCData(roomId, key, value, isInner, apiType, message); } }, { key: "setRTCTotalRes", value: function setRTCTotalRes(roomId, message, valueInfo, objectName) { return this._engine.setRTCTotalRes(roomId, message, valueInfo, objectName); } }, { key: "getRTCData", value: function getRTCData(roomId, keys, isInner, apiType) { return this._engine.getRTCData(roomId, keys, isInner, apiType); } }, { key: "removeRTCData", value: function removeRTCData(roomId, keys, isInner, apiType, message) { return this._engine.removeRTCData(roomId, keys, isInner, apiType, message); } }, { key: "setRTCOutData", value: function setRTCOutData(roomId, rtcData, type, message) { return this._engine.setRTCOutData(roomId, rtcData, type, message); } }, { key: "getRTCOutData", value: function getRTCOutData(roomId, userIds) { return this._engine.getRTCOutData(roomId, userIds); } }, { key: "getRTCToken", value: function getRTCToken(roomId, mode, broadcastType) { return this._engine.getRTCToken(roomId, mode, broadcastType); } }, { key: "setRTCState", value: function setRTCState(roomId, report) { return !this._options.isEnterPrise ? this._engine.setRTCState(roomId, report) : Promise.resolve(ErrorCode$1.SUCCESS); } }, { key: "getRTCUserList", value: function getRTCUserList(roomId) { return this._engine.getRTCUserList(roomId); } }], [{ key: "init", value: function init(runtime, options) { logger.debug('APIContext.init =>', options.appkey, options.navigators); if (this._context) { logger.error('Repeat initialize!'); return this._context; } this._context = new APIContext(runtime, options); return this._context; } }, { key: "destroy", value: function destroy() { if (this._context) { this._context._destroy(); this._context = undefined; } } }]); return APIContext; }(); { logger.warn('RCEngineVersion:', "4.1.0"); logger.warn('VersionCode:', "0012eb74bbf7318ea4a4e2ee3e3e858d6849090c"); } const logger$1 = new Logger('RCIM'); logger$1.set( exports.LogLevel.DEBUG ); const ERROR_INFO = { // 超时 TIMEOUT: { code: -1, msg: 'Network timeout' }, // SDK 内部错误 SDK_INTERNAL_ERROR: { code: -2, msg: 'SDK internal error' }, // 开发者参数传入错误 PARAMETER_ERROR: { code: -3, msg: 'Please check the parameters, the {param} expected a value of {expect} but received {current}' }, REJECTED_BY_BLACKLIST: { code: 405, msg: 'Blacklisted by the other party' }, // 发送频率过快 SEND_TOO_FAST: { code: 20604, msg: 'Sending messages too quickly' }, // 不在群组中 NOT_IN_GROUP: { code: 22406, msg: 'Not in group' }, // 在群组中被禁言 FORBIDDEN_IN_GROUP: { code: 22408, msg: 'Forbbiden from speaking in the group' }, // 不在聊天室中 NOT_IN_CHATROOM: { code: 23406, msg: 'Not in chatRoom' }, // 在聊天室中被禁言 FORBIDDEN_IN_CHATROOM: { code: 23408, msg: 'Forbbiden from speaking in the chatRoom' }, // 已被踢出并禁止加入聊天室 KICKED_FROM_CHATROOM: { code: 23409, msg: 'Kicked out and forbbiden from joining the chatRoom' }, // 聊天室不存在 CHATROOM_NOT_EXIST: { code: 23410, msg: 'ChatRoom does not exist' }, // 聊天室成员超限 CHATROOM_IS_FULL: { code: 23411, msg: 'ChatRoom members exceeded' }, // 聊天室参数无效 PARAMETER_INVALID_CHATROOM: { code: 23412, msg: 'Invalid chatRoom parameters' }, // 聊天室云存储业务未开通 ROAMING_SERVICE_UNAVAILABLE_CHATROOM: { code: 23414, msg: 'ChatRoom message roaming service is not open, Please go to the developer to open this service' }, // 撤回消息失败 RECALLMESSAGE_PARAMETER_INVALID: { code: 25101, msg: 'Invalid recall message parameter' }, // 未开通单群聊消息云存储服务 ROAMING_SERVICE_UNAVAILABLE_MESSAGE: { code: 25102, msg: 'Single group chat roaming service is not open, Please go to the developer to open this service' }, // push 设置参数无效 PUSHSETTING_PARAMETER_INVALID: { code: 26001, msg: 'Invalid push parameter' }, // 操作被禁止 OPERATION_BLOCKED: { code: 20605, msg: 'Operation is blocked' }, // 操作不支持 OPERATION_NOT_SUPPORT: { code: 20606, msg: 'Operation is not supported' }, // 发送的消息中包含敏感词 (发送方发送失败,接收方不会收到消息) MSG_BLOCKED_SENSITIVE_WORD: { code: 21501, msg: 'The sent message contains sensitive words' }, // 消息中敏感词已经被替换 (接收方可以收到被替换之后的消息) REPLACED_SENSITIVE_WORD: { code: 21502, msg: 'Sensitive words in the message have been replaced' }, // 用户未连接成功 NOT_CONNECTED: { code: 30001, msg: 'Please connect successfully first' }, // 导航 http 请求失败 NAVI_REQUEST_ERROR: { code: 30007, msg: 'Navigation http request failed' }, // CMP 嗅探 http 请求失败 CMP_REQUEST_ERROR: { code: 30010, msg: 'CMP sniff http request failed' }, CONN_APPKEY_FAKE: { code: 31002, msg: 'Your appkey is fake' }, CONN_MINI_SERVICE_NOT_OPEN: { code: 31003, msg: 'Mini program service is not open, Please go to the developer to open this service' }, CONN_ACK_TIMEOUT: { code: 31000, msg: 'Connection ACK timeout' }, CONN_TOKEN_INCORRECT: { code: 31004, msg: 'Your token is not valid or expired' }, CONN_NOT_AUTHRORIZED: { code: 31005, msg: 'AppKey and Token do not match' }, CONN_REDIRECTED: { code: 31006, msg: 'Connection redirection' }, CONN_APP_BLOCKED_OR_DELETED: { code: 31008, msg: 'AppKey is banned or deleted' }, CONN_USER_BLOCKED: { code: 31009, msg: 'User blocked' }, // 域名无效 CONN_DOMAIN_INCORRECT: { code: 31012, msg: 'Connect domain error, Please check the set security domain' }, // 未开通单群聊历史消息云存储 ROAMING_SERVICE_UNAVAILABLE: { code: 33007, msg: 'Roaming service cloud is not open, Please go to the developer to open this service' }, // 已连接, 不可再次调用链接(错误码与移动端对齐) RC_CONNECTION_EXIST: { code: 34001, msg: 'Connection already exists' }, // 聊天室 KV 设置超出最大值(已满, 默认最多设置 100 个) CHATROOM_KV_EXCEED: { code: 23423, msg: 'ChatRoom KV setting exceeds maximum' }, // 聊天室 KV 已存在 CHATROOM_KV_OVERWRITE_INVALID: { code: 23424, msg: 'ChatRoom KV already exists' }, // 聊天室 KV 存储功能没有开通 CHATROOM_KV_STORE_NOT_OPEN: { code: 23426, msg: 'ChatRoom KV storage service is not open, Please go to the developer to open this service' }, // 聊天室Key不存在 CHATROOM_KEY_NOT_EXIST: { code: 23427, msg: 'ChatRoom key does not exist' }, // 消息不支持扩展存储(错误码与移动端对齐) MSG_KV_NOT_SUPPORT: { code: 34008, msg: 'The message cannot be extended' }, // 发送扩展存储消息失败(错误码与移动端对齐) SEND_MESSAGE_KV_FAIL: { code: 34009, msg: 'Sending RC expansion message fail' }, // 扩展存储 key value 超出限制(错误码与移动端对齐) EXPANSION_LIMIT_EXCEET: { code: 34010, msg: 'The message expansion size is beyond the limit' }, // 调用接口时传入的参数不正确(错误码与移动端对齐) ILLGAL_PARAMS: { code: 33003, msg: 'Incorrect parameters passed in while calling the interface' } }; const ERROR_CODE = {}; for (const name in ERROR_INFO) { const info = ERROR_INFO[name]; const { code } = info; // ERROR_CODE[name] = code ERROR_CODE[code] = name; } // 服务返回的错误码, 转化为 SDK 的 ErrorCode const SERVER_ERROR_TO_CODE = { // 未开通单群聊历史消息云存储 1: ERROR_INFO.ROAMING_SERVICE_UNAVAILABLE.code }; const CONNECTION_STATUS = { CONNECTED: 0, CONNECTING: 1, DISCONNECTED: 2, NETWORK_UNAVAILABLE: 3, SOCKET_ERROR: 4, KICKED_OFFLINE_BY_OTHER_CLIENT: 6, BLOCKED: 12 // 用户被封禁(服务值为 2, 转为状态码后 + 10) }; /** * 业务层枚举, 此处枚举会暴露给开发者 */ const CONNECT_TYPE = { COMET: 'comet', WEBSOCKET: 'websocket' }; const CONVERSATION_TYPE = ConversationType$1; const MESSAGE_DIRECTION = MessageDirection$1; const MESSAGS_TIME_ORDER = { DESC: 0, ASC: 1 // 正序 }; // 聊天室历史消息、聊天室用户信息排序 const CHATROOM_ORDER = { ASC: 1, DESC: 2 }; const RECALL_MESSAGE_TYPE = 'RC:RcCmd'; const MENTIONED_TYPE = { ALL: 1, SINGAL: 2 }; const MESSAGE_TYPE = { TEXT: 'RC:TxtMsg', VOICE: 'RC:VcMsg', HQ_VOICE: 'RC:HQVCMsg', IMAGE: 'RC:ImgMsg', GIF: 'RC:GIFMsg', RICH_CONTENT: 'RC:ImgTextMsg', LOCATION: 'RC:LBSMsg', FILE: 'RC:FileMsg', SIGHT: 'RC:SightMsg', COMBINE: 'RC:CombineMsg', CHRM_KV_NOTIFY: 'RC:chrmKVNotiMsg', LOG_COMMAND: 'RC:LogCmdMsg', EXPANSION_NOTIFY: 'RC:MsgExMsg', REFERENCE: 'RC:ReferenceMsg' }; const FILE_TYPE = FileType$1; // 聊天室 kv 存储操作类型. 对方操作, 己方收到消息(RC:chrmKVNotiMsg)中会带入此值. 根据此值判断是删除还是更新 const CHATROOM_ENTRY_TYPE = { UPDATE: 1, DELETE: 2 }; const NOTIFICATION_STATUS = { DO_NOT_DISTURB: 1, NOTIFY: 2 // 提醒(非免打扰) }; const RECEIVED_STATUS = { READ: 0x1, LISTENED: 0x2, DOWNLOADED: 0x4, RETRIEVED: 0x8, UNREAD: 0 // 未读 }; const SDK_VERSION = "4.1.0"; /** * 转化 APIContext 传过来的消息数据 * @param msg APIContext 消息 * @returns V3 需要的消息数据 */ function tranReceivedMessage(msg) { let { conversationType: type, messageType, content, senderUserId, targetId, sentTime, receivedTime, messageUId, messageDirection, isPersited, isCounted, isOffLineMessage, canIncludeExpansion, expansion, receivedStatus, disableNotification, isMentioned, isStatusMessage } = msg; if (!receivedStatus) { receivedStatus = ReceivedStatus$1.UNREAD; } return { messageType, content, senderUserId, targetId, type, sentTime, receivedTime, messageUId, messageDirection, isPersited, isCounted, isOffLineMessage, isMentioned, disableNotification, isStatusMessage, canIncludeExpansion, expansion, receivedStatus }; } /** * 转化 APIContext 传过来的会话数据 * @param conversation APIContext 会话 * @returns V3 需要的会话数据 */ function tranReceiveConversation(conversation) { const { conversationType: type, targetId, latestMessage, unreadMessageCount, hasMentioned, mentionedInfo, lastUnreadTime, notificationStatus, isTop } = conversation; const latestMessageV3 = latestMessage && tranReceivedMessage(latestMessage); const mentionedInfoV3 = { type: mentionedInfo === null || mentionedInfo === void 0 ? void 0 : mentionedInfo.type, userIdList: mentionedInfo === null || mentionedInfo === void 0 ? void 0 : mentionedInfo.userIdList }; return { type, targetId, latestMessage: latestMessageV3, unreadMessageCount, hasMentioned, mentionedInfo: mentionedInfoV3, lastUnreadTime, notificationStatus, isTop }; } function tranReceiveUpdateConversation(conversation) { const { updatedItems, conversationType: type, targetId, latestMessage, unreadMessageCount, lastUnreadTime, notificationStatus, isTop, mentionedInfo, hasMentioned } = conversation; const latestMessageV3 = latestMessage && tranReceivedMessage(latestMessage); if (updatedItems && updatedItems.latestMessage) { updatedItems.latestMessage.val = latestMessageV3; } return { updatedItems, type, targetId, latestMessage: latestMessageV3, unreadMessageCount, lastUnreadTime, notificationStatus, isTop, mentionedInfo, hasMentioned }; } /** * 校验发消息的参数 */ function assertSendMsgOption(options) { assert('options.messageType', options.messageType, AssertRules.STRING, true); assert('options.content', options.content, (value) => { return isObject(value); }, true); assert('options.isPersited', options.isPersited, AssertRules.BOOLEAN); assert('options.isCounted', options.isCounted, AssertRules.BOOLEAN); assert('options.pushContent', options.pushContent, AssertRules.STRING); assert('options.pushData', options.pushData, AssertRules.STRING); assert('options.isVoipPush', options.isVoipPush, AssertRules.BOOLEAN); assert('options.isStatusMessage', options.isStatusMessage, AssertRules.BOOLEAN); assert('options.isMentioned', options.isMentioned, AssertRules.BOOLEAN); assert('options.mentionedType', options.mentionedType, AssertRules.NUMBER); assert('options.mentionedUserIdList', options.mentionedUserIdList, (value) => { return isArray(value) && (value.length === 0 || value.every(isString)); }); assert('options.directionalUserIdList', options.directionalUserIdList, (value) => { return isArray(value) && (value.length === 0 || value.every(isString)); }); if (!isUndefined(options.isPersited) || !isUndefined(options.isCounted) || !isUndefined(options.isStatusMessage)) { logger$1.warn('注意: 由于参数 isPersited、isCounted、isStatusMessage 的传入在接收消息时会导致移动端与 Web 端的 isPersited、isCounted、isStatusMessage 这三个参数值不一致。\n故 isPersited、isCounted、isStatusMessage 即将废弃,非内置消息请使用 registerMessageType 方法注册自定义消息.'); } } // import { isObject, isUndefined } from '../../utils/validator' /** * 会话排序(拆分-排序-合并) * 将会话列表拆分为置顶和非置顶的两个数组 * 再对两个数组按时间进行排序,时间戳大的说明是最近的消息排最上 */ const sortConList = (conversationList, order) => { if (!conversationList) { return []; } const splitConversationList = splitConversationListByIsTop(conversationList); const topConversationList = _sortListBySentTime(splitConversationList.topConversationList, order); const unToppedConversationList = _sortListBySentTime(splitConversationList.unToppedConversationList, order); topConversationList.push.apply(topConversationList, unToppedConversationList); return topConversationList; }; const mergeConversationList = (option) => { option = option || {}; let { conversationList, updatedConversationList } = option; conversationList = conversationList || []; updatedConversationList = updatedConversationList || []; const allConversationList = [...updatedConversationList, ...conversationList]; // 按顺序合并相同会话的数值(顺序依然为上一步的排序, 只是数值合并, 顺序靠后的数值合并到顺序靠前数值中) const hashTable = {}; let newList = []; const invalidDataIndexList = []; forEach(allConversationList, (conversation) => { if (!isObject(conversation)) { // 会话格式错误, 不添加至新列表 return; } const { type, targetId } = conversation; const key = getConversationKey({ type, targetId }); const hashItem = hashTable[key] || {}; const hashIndex = isUndefined(hashItem.index) ? newList.length : hashItem.index; const hashVal = hashItem.val || {}; const cacheUpdatedItems = hashVal.updatedItems || {}; const updatedItems = conversation.updatedItems; conversation = extend(conversation, hashVal); forEach(cacheUpdatedItems, (item, key) => { conversation[key] = item.val; }); forEach(updatedItems, (item, key) => { const cacheItem = cacheUpdatedItems[key] || {}; const cacheItemUpdatedTime = cacheItem.time || 0; if (item.time > cacheItemUpdatedTime) { conversation[key] = item.val; } }); hashTable[key] = { index: hashIndex, val: conversation }; newList[hashIndex] = conversation; isInValidConversationData(conversation) && invalidDataIndexList.push(hashIndex); }); forEach(invalidDataIndexList, (invalidIndex) => { const conversation = newList[invalidIndex]; newList[invalidIndex] = fixConversationData(conversation); }); newList = sortConList(newList); return map(newList, (item) => { delete item.updatedItems; return item; }); }; const splitConversationListByIsTop = (conversationList) => { const topConversationList = []; const unToppedConversationList = []; forEach(conversationList, (conversation) => { // 兼容会话中单词拼写错误字段 hasMentiond、mentiondInfo const { hasMentioned, mentionedInfo } = conversation; conversation.hasMentioned = hasMentioned; conversation.mentionedInfo = mentionedInfo; // 兼容接收 const isTop = conversation.isTop || false; if (isTop) { topConversationList.push(conversation); } else { unToppedConversationList.push(conversation); } }); return { topConversationList: topConversationList || [], unToppedConversationList: unToppedConversationList || [] }; }; const getConversationKey = (option) => { const { type, targetId } = option; return type + '_' + targetId; }; const _sortListBySentTime = (convers, order = 0) => { return quickSort(convers, (before, after) => { before = before || {}; after = after || {}; const beforeLatestMessage = before.latestMessage || {}; const afterLatestMessage = after.latestMessage || {}; const beforeLatestSentTime = beforeLatestMessage.sentTime || 0; const afterLatestSentTime = afterLatestMessage.sentTime || 0; if (!order) { return afterLatestSentTime <= beforeLatestSentTime; } return afterLatestSentTime >= beforeLatestSentTime; }); }; const fixConversationData = (conversation) => { conversation = conversation || {}; const { targetId, type } = conversation; const defaultType = ConversationType$1.PRIVATE; const defaultMsg = { messageType: MessageType$1.TextMessage, sentTime: DelayTimer.getTime(), content: { content: '' }, senderUserId: targetId, targetId, type }; conversation.type = type || defaultType; conversation.targetId = targetId || ''; conversation.latestMessage = conversation.latestMessage || defaultMsg; return conversation; }; const quickSort = (arr, event) => { const sort = (array, left, right, event) => { event = event || ((a, b) => { return a <= b; }); if (left < right) { const x = array[right]; let i = left - 1; let temp; for (let j = left; j <= right; j++) { if (event(array[j], x)) { i++; temp = array[i]; array[i] = array[j]; array[j] = temp; } } sort(array, left, i - 1, event); sort(array, i + 1, right, event); } return array; }; return sort(arr, 0, arr.length - 1, event); }; const isInValidConversationData = (conversation) => { return !conversation.type || !conversation.targetId || !isObject(conversation.latestMessage) || isUndefined(conversation.unreadMessageCount); }; const extend = (destination, sources, option) => { option = option || {}; const { isAllowNull } = option; destination = destination || {}; sources = sources || {}; for (const key in sources) { const value = sources[key]; if (!isUndefined(value) || isAllowNull) { destination[key] = value; } } return destination; }; class Conversation { constructor(_context, option) { this._context = _context; this.targetId = option.targetId; this.type = option.type; } /** * 删除指定会话 */ destory() { return __awaiter(this, void 0, void 0, function* () { const code = yield this._context.removeConversation(this.type, this.targetId); if (code !== ErrorCode$1.SUCCESS) { return Promise.reject({ code, msg: ERROR_CODE[code] }); } }); } /** * 清除会话未读数 */ read() { return __awaiter(this, void 0, void 0, function* () { const code = yield this._context.clearUnreadCount(this.type, this.targetId); if (code !== ErrorCode$1.SUCCESS) { return Promise.reject({ code, msg: ERROR_CODE[code] }); } }); } /** * 获取指定会话未读数 */ getUnreadCount() { return __awaiter(this, void 0, void 0, function* () { const { code, data } = yield this._context.getUnreadCount(this.type, this.targetId); // 当未读数为空时,返回 0 故不校验 data 值 if (code === ErrorCode$1.SUCCESS) { return data; } return Promise.reject({ code, msg: ERROR_CODE[code] }); }); } /** * 发送消息 * @param options * @deprecated options.isPersited * @deprecated options.isCounted * @deprecated options.isStatusMessage */ send(options) { return __awaiter(this, void 0, void 0, function* () { assertSendMsgOption(options); if (!Object.prototype.hasOwnProperty.call(options, 'isPersited')) { options.isPersited = true; } if (!Object.prototype.hasOwnProperty.call(options, 'isCounted')) { options.isCounted = true; } const { code, data } = yield this._context.sendMessage(this.type, this.targetId, options); if (code === ErrorCode$1.SUCCESS) { return tranReceivedMessage(data); } return Promise.reject({ code, msg: ERROR_CODE[code] }); }); } /** * 设置会话状态 */ setStatus(status) { return __awaiter(this, void 0, void 0, function* () { assert('options.notificationStatus', status.notificationStatus, (value) => { return (value === 1 || value === 2); }); assert('options.isTop', status.isTop, AssertRules.BOOLEAN); const code = yield this._context.setConversationStatus(this.type, this.targetId, status.isTop, status.notificationStatus); if (code !== ErrorCode$1.SUCCESS) { return Promise.reject({ code, msg: ERROR_CODE[code] }); } }); } /** * 获取历史消息 */ getMessages(options) { return __awaiter(this, void 0, void 0, function* () { assert('options.timestamp', options.timestamp, AssertRules.NUMBER); assert('options.count', options.count, AssertRules.NUMBER); assert('options.order', options.order, (value) => { return (value === 0 || value === 1); }); const { code, data } = yield this._context.getHistoryMessage(this.type, this.targetId, options === null || options === void 0 ? void 0 : options.timestamp, options === null || options === void 0 ? void 0 : options.count, options === null || options === void 0 ? void 0 : options.order); if (code === ErrorCode$1.SUCCESS && data) { const list = data.list.map(item => tranReceivedMessage(item)); return Promise.resolve({ list, hasMore: data.hasMore }); } return Promise.reject({ code, msg: ERROR_CODE[code] }); }); } /** * 撤回消息 * @param options */ recall(options) { return __awaiter(this, void 0, void 0, function* () { assert('options.messageUId', options.messageUId, AssertRules.STRING, true); assert('options.sentTime', options.sentTime, AssertRules.NUMBER, true); const { code, data } = yield this._context.recallMessage(this.type, this.targetId, options.messageUId, options.sentTime, options.user); if (code === ErrorCode$1.SUCCESS && data) { return tranReceivedMessage(data); } return Promise.reject({ code, msg: ERROR_CODE[code] }); }); } /** * 按消息 id 删除消息 */ deleteMessages(messages) { return __awaiter(this, void 0, void 0, function* () { assert('options', messages, (value) => { return isArray(value) && value.length; }, true); messages.forEach((item) => { assert('options.messageUId', item.messageUId, AssertRules.STRING, true); assert('options.sentTime', item.sentTime, AssertRules.NUMBER, true); assert('options.messageDirection', item.messageDirection, (value) => { return (value === 1 || value === 2); }, true); }); const code = yield this._context.deleteRemoteMessage(this.type, this.targetId, messages); if (code !== ErrorCode$1.SUCCESS) { return Promise.reject({ code, msg: ERROR_CODE[code] }); } }); } /** * 按时间戳删除消息 */ clearMessages(options) { return __awaiter(this, void 0, void 0, function* () { assert('options.timestamp', options.timestamp, AssertRules.NUMBER, true); const code = yield this._context.deleteRemoteMessageByTimestamp(this.type, this.targetId, options.timestamp); if (code !== ErrorCode$1.SUCCESS) { return Promise.reject({ code, msg: ERROR_CODE[code] }); } }); } /** * 更新(添加、替换)消息扩展属性 * @param expansion 要更新的消息扩展信息键值对 * @param message 要更新的原始消息体 */ updateMessageExpansion(expansion, message) { return __awaiter(this, void 0, void 0, function* () { assert('expansion', expansion, AssertRules.OBJECT, true); assert('message', message, AssertRules.OBJECT, true); const { type: conversationType, targetId, messageUId, canIncludeExpansion, expansion: originExpansion } = message; const { code } = yield this._context.sendExpansionMessage({ conversationType, targetId, messageUId, expansion, canIncludeExpansion, originExpansion }); if (code !== ErrorCode$1.SUCCESS) { return Promise.reject({ code, msg: ERROR_CODE[code] }); } }); } /** * 删除扩展存储 * @params keys 需删除消息扩展的 keys * @params message 原始消息体 */ removeMessageExpansion(keys, message) { return __awaiter(this, void 0, void 0, function* () { assert('keys', keys, AssertRules.ARRAY, true); assert('message', message, AssertRules.OBJECT, true); const { conversationType, targetId, messageUId, canIncludeExpansion } = message; const { code } = yield this._context.sendExpansionMessage({ conversationType, targetId, messageUId, canIncludeExpansion, keys }); if (code !== ErrorCode$1.SUCCESS) { return Promise.reject({ code, msg: ERROR_CODE[code] }); } }); } /** * 设置会话文本草稿 * @params conversationType 会话乐行 * @params targetId 目标 ID * @params draft 草稿内容 */ setDraft(draft) { return __awaiter(this, void 0, void 0, function* () { assert('draft', draft, AssertRules.STRING, true); const code = yield this._context.saveConversationMessageDraft(this.type, this.targetId, draft); if (code === ErrorCode$1.SUCCESS) { return Promise.resolve(); } }); } /** * 获取会话文本草稿 * @params conversationType 会话乐行 * @params targetId 目标 ID */ getDraft() { return __awaiter(this, void 0, void 0, function* () { const { code, data } = yield this._context.getConversationMessageDraft(this.type, this.targetId); if (code === ErrorCode$1.SUCCESS) { return Promise.resolve(data); } return Promise.reject({ code, msg: ERROR_CODE[code] }); }); } /** * 删除会话文本草稿 * @params conversationType 会话乐行 * @params targetId 目标 ID */ deleteDraft() { return __awaiter(this, void 0, void 0, function* () { const code = yield this._context.clearConversationMessageDraft(this.type, this.targetId); if (code === ErrorCode$1.SUCCESS) { return Promise.resolve(); } }); } } class ConversationModule { constructor(apiContext) { this._context = apiContext; } /** * 获取会话列表 * @param options */ getList(options) { return __awaiter(this, void 0, void 0, function* () { const { code, data } = yield this._context.getConversationList(options === null || options === void 0 ? void 0 : options.count, undefined, options === null || options === void 0 ? void 0 : options.startTime, options === null || options === void 0 ? void 0 : options.order); if (code === ErrorCode$1.SUCCESS && data) { const list = data.map(item => tranReceiveConversation(item)); return sortConList(list); } return Promise.reject({ code, msg: ERROR_CODE[code] }); }); } /** * 获取指定会话实例,通过实例可实现向指定会话收发消息等功能 * @description 通过该方法获取的会话可能并不存在于当前的会话列表中,此处只作为功能性封装语法糖 * @param options */ get(options) { assert('options.type', options.type, isValidConversationType, true); return new Conversation(this._context, options); } remove(options) { assert('options.type', options.type, isValidConversationType, true); return new Conversation(this._context, options).destory(); } /** * 获取当前所有会话的消息未读数 */ getTotalUnreadCount() { return __awaiter(this, void 0, void 0, function* () { const { code, data } = yield this._context.getTotalUnreadCount(); // 当未读数为空时,返回 0 故不校验 data 值 if (code === ErrorCode$1.SUCCESS) { return data; } return Promise.reject({ code, msg: ERROR_CODE[code] }); }); } /** * 合并会话 * @param option */ merge(option) { !option.conversationList && logger$1.warn('Parameter option.conversationList are required!'); return mergeConversationList(option); } } /** * 校验设置聊天室属性的参数 * @param options */ const assertSetChatRoomEntryOption = (options) => { assert('options.key', options.key, AssertRules.STRING, true); assert('options.value', options.value, AssertRules.STRING, true); assert('options.isAutoDelete', options.isAutoDelete, AssertRules.BOOLEAN); assert('options.isSendNotification', options.isSendNotification, AssertRules.BOOLEAN); assert('options.notificationExtra', options.notificationExtra, AssertRules.STRING); }; /** * 校验删除聊天室属性的参数 * @param options */ const assertRemoveChatRoomEntryOption = (options) => { assert('options.key', options.key, AssertRules.STRING, true); assert('options.isSendNotification', options.isSendNotification, AssertRules.BOOLEAN); assert('options.notificationExtra', options.notificationExtra, AssertRules.STRING); }; class Chatroom { constructor(context, id) { this._context = context; this._id = id; } /** * 加入聊天室 */ join(options) { return __awaiter(this, void 0, void 0, function* () { assert('options.count', options.count, AssertRules.NUMBER, true); const code = yield this._context.joinChatroom(this._id, options.count); if (code !== ErrorCode$1.SUCCESS) { return Promise.reject({ code, msg: ERROR_CODE[code] }); } }); } /** * 加入已存在的聊天室 */ joinExist(options) { return __awaiter(this, void 0, void 0, function* () { assert('options.count', options.count, AssertRules.NUMBER, true); const code = yield this._context.joinExistChatroom(this._id, options.count); if (code !== ErrorCode$1.SUCCESS) { return Promise.reject({ code, msg: ERROR_CODE[code] }); } }); } /** * 退出聊天室 */ quit() { return __awaiter(this, void 0, void 0, function* () { const code = yield this._context.quitChatroom(this._id); if (code !== ErrorCode$1.SUCCESS) { return Promise.reject({ code, msg: ERROR_CODE[code] }); } }); } /** * 获取聊天室房间数据 * @description count 或 order 有一个为 0 时,只返回成员总数,不返回成员列表信息 */ getInfo(options = {}) { return __awaiter(this, void 0, void 0, function* () { assert('options.count', options.count, AssertRules.NUMBER); assert('options.order', options.order, (value) => { return [0, 1, 2].includes(value); }); const { code, data: chatroomInfo } = yield this._context.getChatroomInfo(this._id, options.count, options.order); if (code === ErrorCode$1.SUCCESS && chatroomInfo) { return chatroomInfo; } return Promise.reject({ code, msg: ERROR_CODE[code] }); }); } /** * 设置聊天室自定义属性 * @description 仅聊天室中不存在此属性或属性设置者为己方时可设置成功 */ setEntry(options) { return __awaiter(this, void 0, void 0, function* () { assertSetChatRoomEntryOption(options); const code = yield this._context.setChatroomEntry(this._id, options); if (code !== ErrorCode$1.SUCCESS) { return Promise.reject({ code, msg: ERROR_CODE[code] }); } }); } /** * 强制 增加/修改 任意聊天室属性 * @description 仅聊天室中不存在此属性或属性设置者为己方时可设置成功 */ forceSetEntry(options) { return __awaiter(this, void 0, void 0, function* () { assertSetChatRoomEntryOption(options); const code = yield this._context.forceSetChatroomEntry(this._id, options); if (code !== ErrorCode$1.SUCCESS) { return Promise.reject({ code, msg: ERROR_CODE[code] }); } }); } /** * 删除聊天室属性 * @description 仅限于删除自己设置的聊天室属性 * @param key 属性名称, 支持英文字母、数字、+、=、-、_ 的组合方式, 最大长度 128 字符 * @param isSendNotification? 删除成功后是否发送通知消息 * @param notificationExtra? RC:chrmKVNotiMsg 通知消息中携带的附加信息 */ removeEntry(options) { return __awaiter(this, void 0, void 0, function* () { assertRemoveChatRoomEntryOption(options); const code = yield this._context.removeChatroomEntry(this._id, options); if (code !== ErrorCode$1.SUCCESS) { return Promise.reject({ code, msg: ERROR_CODE[code] }); } }); } /** * 强制删除聊天室内的任意属性 * @description */ forceRemoveEntry(options) { return __awaiter(this, void 0, void 0, function* () { assertRemoveChatRoomEntryOption(options); const code = yield this._context.forceRemoveChatroomEntry(this._id, options); if (code !== ErrorCode$1.SUCCESS) { return Promise.reject({ code, msg: ERROR_CODE[code] }); } }); } /** * 获取聊天室的指定属性 */ getEntry(key /** * 属性名称, 支持英文字母、数字、+、=、-、_ 的组合方式, 最大长度 128 字符 */ ) { return __awaiter(this, void 0, void 0, function* () { assert('key', key, (value) => { return isString(value) && /[\w+=-]+/.test(value) && value.length <= 128; }, true); const { code, data } = yield this._context.getChatroomEntry(this._id, key); if (code === ErrorCode$1.SUCCESS && data) { return data; } return Promise.reject({ code, msg: ERROR_CODE[code] }); }); } /** * 获取聊天室的所有属性 */ getAllEntries() { return __awaiter(this, void 0, void 0, function* () { const { code, data } = yield this._context.getAllChatroomEntries(this._id); if (code === ErrorCode$1.SUCCESS && data) { return data; } return Promise.reject({ code, msg: ERROR_CODE[code] }); }); } /** * 发送消息 */ send(options) { return __awaiter(this, void 0, void 0, function* () { assertSendMsgOption(options); if (!Object.prototype.hasOwnProperty.call(options, 'isPersited')) { options.isPersited = true; } if (!Object.prototype.hasOwnProperty.call(options, 'isCounted')) { options.isCounted = true; } const { code, data } = yield this._context.sendMessage(ConversationType$1.CHATROOM, this._id, options); if (code === ErrorCode$1.SUCCESS) { return tranReceivedMessage(data); } return Promise.reject({ code, msg: ERROR_CODE[code] }); }); } /** * 获取聊天室的历史消息 */ getMessages(options) { return __awaiter(this, void 0, void 0, function* () { assert('options.timestamp', options.timestamp, AssertRules.NUMBER); assert('options.count', options.count, AssertRules.NUMBER); assert('options.order', options.order, (value) => { return (value === 0 || value === 1); }); const { code, data } = yield this._context.getChatRoomHistoryMessages(this._id, options.count, options.order, options.timestamp); if (code === ErrorCode$1.SUCCESS && data) { const list = data.list.map(item => tranReceivedMessage(item)); return { list, hasMore: data.hasMore }; } return Promise.reject({ code, msg: ERROR_CODE[code] }); }); } /** * 撤回聊天室消息 */ recall(options) { return __awaiter(this, void 0, void 0, function* () { assert('options.messageUId', options.messageUId, AssertRules.STRING, true); assert('options.sentTime', options.sentTime, AssertRules.NUMBER, true); const conversationType = ConversationType$1.CHATROOM; const { code, data } = yield this._context.recallMessage(conversationType, this._id, options.messageUId, options.sentTime, options.user); if (code === ErrorCode$1.SUCCESS && data) { return tranReceivedMessage(data); } return Promise.reject({ code, msg: ERROR_CODE[code] }); }); } } class ChatroomModule { constructor(apiContext) { this._context = apiContext; } /** * 根据聊天室 id 初始化一个聊天室功能实例,以实现收发消息等聊天室相关功能 * @param option */ get(option) { assert('option.id', option.id, notEmptyString, true); return new Chatroom(this._context, option.id); } } class RTCClient { constructor(_options, _context) { this._options = _options; this._context = _context; this._roomId = _options.id; } join() { return __awaiter(this, void 0, void 0, function* () { const { code, data } = yield this._context.joinRTCRoom(this._roomId, this._options.mode, this._options.broadcastType); if (code === ErrorCode$1.SUCCESS) { return data; } return Promise.reject(code); }); } quit() { return __awaiter(this, void 0, void 0, function* () { const code = yield this._context.quitRTCRoom(this._roomId); return code === ErrorCode$1.SUCCESS ? code : Promise.reject(code); }); } getRoomInfo() { return __awaiter(this, void 0, void 0, function* () { const { code, data } = yield this._context.getRTCRoomInfo(this._roomId); if (code === ErrorCode$1.SUCCESS) { return data; } return Promise.reject(code); }); } setUserInfo(info) { return __awaiter(this, void 0, void 0, function* () { const code = yield this._context.setRTCUserInfo(this._roomId, info.key, info.value); return code === ErrorCode$1.SUCCESS ? code : Promise.reject(code); }); } removeUserInfo(info) { return __awaiter(this, void 0, void 0, function* () { const code = yield this._context.removeRTCUserInfo(this._roomId, info.keys); return code === ErrorCode$1.SUCCESS ? code : Promise.reject(code); }); } setData(key, value, isInner, apiType, message) { return __awaiter(this, void 0, void 0, function* () { const code = yield this._context.setRTCData(this._roomId, key, value, isInner, apiType, message); return code === ErrorCode$1.SUCCESS ? code : Promise.reject(code); }); } setUserData(key, value, isInner, message) { return this.setData(key, value, isInner, RTCApiType.PERSON, message); } /** * 全量 URI 资源发布 * @param message 旧版本消息,含消息名及消息内容 * @param valueInfo 全量消息数据 * @param objectName 全量 URI 消息名 */ setRTCUserData(message, valueInfo, objectName) { return __awaiter(this, void 0, void 0, function* () { const code = yield this._context.setRTCTotalRes(this._roomId, message, valueInfo, objectName); return code === ErrorCode$1.SUCCESS ? code : Promise.reject(code); }); } getData(keys, isInner, apiType) { return __awaiter(this, void 0, void 0, function* () { const { code, data } = yield this._context.getRTCData(this._roomId, keys, isInner, apiType); return code === ErrorCode$1.SUCCESS ? data : Promise.reject(code); }); } getUserData(keys, isInner) { return this.getData(keys, isInner, RTCApiType.PERSON); } removeData(keys, isInner, apiType, message) { return __awaiter(this, void 0, void 0, function* () { const code = yield this._context.removeRTCData(this._roomId, keys, isInner, apiType, message); return code === ErrorCode$1.SUCCESS ? code : Promise.reject(code); }); } removeUserData(keys, isInner, message) { return this.removeData(keys, isInner, RTCApiType.PERSON, message); } setRoomData(key, value, isInner, message) { return this.setData(key, value, isInner, RTCApiType.ROOM, message); } getRoomData(keys, isInner) { return this.getData(keys, isInner, RTCApiType.ROOM); } removeRoomData(keys, isInner, message) { return this.removeData(keys, isInner, RTCApiType.ROOM, message); } setState(content) { return __awaiter(this, void 0, void 0, function* () { const code = yield this._context.setRTCState(this._roomId, content.report); return code === ErrorCode$1.SUCCESS ? code : Promise.reject(code); }); } getUserList() { return __awaiter(this, void 0, void 0, function* () { const { code, data } = yield this._context.getRTCUserInfoList(this._roomId); if (code === ErrorCode$1.SUCCESS) { return data; } return Promise.reject(code); }); } getUserInfoList() { return __awaiter(this, void 0, void 0, function* () { const { code, data } = yield this._context.getRTCUserInfoList(this._roomId); if (code === ErrorCode$1.SUCCESS) { return data; } return Promise.reject(code); }); } getToken() { return __awaiter(this, void 0, void 0, function* () { const { data, code } = yield this._context.getRTCToken(this._roomId, this._options.mode, this._options.broadcastType); if (code === ErrorCode$1.SUCCESS) { return data; } return Promise.reject(code); }); } ping() { return __awaiter(this, void 0, void 0, function* () { const code = yield this._context.rtcPing(this._roomId, this._options.mode, this._options.broadcastType); return code === ErrorCode$1.SUCCESS ? code : Promise.reject(code); }); } send(options) { return __awaiter(this, void 0, void 0, function* () { const { code, data } = yield this._context.sendMessage(ConversationType$1.RTC_ROOM, this._roomId, { content: Object.assign({}, options.content), messageType: options.messageType }); if (code === ErrorCode$1.SUCCESS) { return data; } return Promise.reject(code); }); } } // export class RTCModule { // private _context: APIContext // constructor (apiContext: APIContext) { // this._context = apiContext // } // /** // * 为 RTCLib 提供的 API 接口,业务层不可使用 // * @private // * @param options // */ // get (options: RTCRoomOption) { // assert('options.id', options.id, notEmptyString, true) // return new RTCClient(options, this._context) // } // } const hasMiniBaseEvent = (miniGlobal) => { const baseMiniEventNames = ['canIUse', 'getSystemInfo']; for (let i = 0, max = baseMiniEventNames.length; i < max; i++) { const baseEventName = baseMiniEventNames[i]; if (!miniGlobal[baseEventName]) { return false; } } return true; }; const isFromUniappEnv = () => { if (typeof uni !== 'undefined' && hasMiniBaseEvent(uni)) { return true; } return false; }; const isFromUniapp = isFromUniappEnv(); const isValidRequest = (obj) => { return typeof obj === 'function' || typeof obj === 'object'; }; const createXHR = () => { if (isValidRequest(XMLHttpRequest) && 'withCredentials' in new XMLHttpRequest()) { return new XMLHttpRequest(); } // IE 7-9 中的跨域请求方案 if (isValidRequest(XDomainRequest)) { return new XDomainRequest(); } // 更低版本 IE 使用 ActiveXObject 插件实现跨域请求 return new ActiveXObject('Microsoft.XMLHTTP'); }; function httpReq(options) { const method = options.method || HttpMethod.GET; const timeout = options.timeout || 60 * 1000; const { headers, query, body } = options; const url = appendUrl(options.url, query); return new Promise((resolve) => { const xhr = createXHR(); xhr.timeout = timeout; xhr.open(method, url); if (headers && xhr.setRequestHeader) { for (const key in headers) { xhr.setRequestHeader(key, headers[key]); } } if ('onload' in xhr) { xhr.onload = function () { resolve({ data: xhr.responseText, status: xhr.status }); }; xhr.onerror = function () { resolve({ status: xhr.status }); }; xhr.ontimeout = function () { resolve({ status: xhr.status }); }; } else { xhr.onreadystatechange = () => { if (xhr.readyState === 4) { const { result, status } = xhr.responseText; resolve({ data: result, status }); } }; setTimeout(() => resolve({ status: xhr.responseText.status }), timeout); } const isXDomainRequest = Object.prototype.toString.call(xhr) === '[object XDomainRequest]'; const reqBody = isXDomainRequest && typeof body === 'object' ? JSON.stringify(body) : body; xhr.send(reqBody); }); } function createWebSocket(url, protocols) { const ws = new WebSocket(url, protocols); ws.binaryType = 'arraybuffer'; return { onClose(callback) { ws.onclose = (evt) => { const { code, reason } = evt; callback(code, reason); }; }, onError(callback) { ws.onerror = callback; }, onMessage(callback) { ws.onmessage = (evt) => { callback(evt.data); }; }, onOpen(callback) { ws.onopen = callback; }, send(data) { ws.send(data); }, close(code, reason) { ws.close(code, reason); } }; } const browser = { tag: "browser", httpReq, localStorage: window === null || window === void 0 ? void 0 : window.localStorage, sessionStorage: window === null || window === void 0 ? void 0 : window.sessionStorage, isSupportSocket() { const bool = typeof WebSocket !== 'undefined'; bool || logger$1.warn('websocket not support'); return bool; }, useNavi: true, connectPlatform: '', isFromUniapp, createWebSocket, createDataChannel(watcher, connectType) { if (this.isSupportSocket() && connectType === 'websocket') { return new WebSocketChannel(this, watcher); } else { return new CometChannel(this, watcher); } } }; const isFromUniapp$1 = isFromUniappEnv(); const isFromUniapp$2 = isFromUniappEnv(); let runtime$1; { runtime$1 = browser; } var runtime$2 = runtime$1; // RTCLib、CallLib 相关监听存储 const rtcInnerMsgWatcher = []; const rtcInnerStatusWatcher = []; const rtcInnerWatcher = { message(message) { rtcInnerMsgWatcher.forEach(item => item(message)); }, status(status) { rtcInnerStatusWatcher.forEach(item => item(status)); } }; class IMClient { constructor(apiContext) { this._token = ''; this._context = apiContext; this.Conversation = new ConversationModule(apiContext); this.ChatRoom = new ChatroomModule(apiContext); this.RTC = function (options) { assert('options.id', options.id, notEmptyString, true); return new RTCClient(options, apiContext); }; } /** * 装载 plugin 插件,并返回相应的插件实例,需在调用 `connect` 方法之前使用 * @param plugins */ install(plugin, options) { return this._context.install(plugin, options); } /** * 添加全局事件监听,同一类型事件会覆盖添加,以避免多次监听引起的复杂问题 * @param options */ watch(options) { const { status: statusListener, conversation: conversationListener, message: messageListener, chatroom: chatroomListener, expansion: expansionListener } = options; const watcher = {}; if (statusListener) { watcher.connectionState = (status) => { // 对业务层的方法要增加 catch 捕获,避免影响内部调用栈的继续进行 try { statusListener({ status }); } catch (err) { logger$1.error(err); } }; } if (conversationListener) { watcher.conversationState = (conversations) => { try { const list = conversations.map((item) => tranReceiveUpdateConversation(item)); conversationListener({ updatedConversationList: list }); } catch (err) { logger$1.error(err); } }; } if (messageListener) { watcher.message = (message) => { try { messageListener({ message: tranReceivedMessage(message) }); } catch (err) { logger$1.error(err); } }; } if (chatroomListener) { watcher.chatroomState = (event) => { try { chatroomListener(event); } catch (err) { logger$1.error(err); } }; } if (expansionListener) { watcher.expansion = (event) => { try { expansionListener(event); } catch (err) { logger$1.error(err); } }; } this._context.assignWatcher(watcher); } unwatch() { this._context.assignWatcher({ message: undefined, connectionState: undefined, conversationState: undefined, chatroomState: undefined, expansion: undefined }); } rtcInnerWatch(attrs) { const { message: messageListener, status: statusListener } = attrs; if (messageListener) { rtcInnerMsgWatcher.push((message) => { try { messageListener({ message: tranReceivedMessage(message) }); } catch (err) { logger$1.error(err); } }); } if (statusListener) { rtcInnerStatusWatcher.push((status) => { try { statusListener({ status }); } catch (err) { logger$1.error(err); } }); } this._context.assignWatcher({ rtcInnerWatcher }); } rtcInnerUnwatch() { rtcInnerStatusWatcher.length = rtcInnerStatusWatcher.length = 0; this._context.assignWatcher({ rtcInnerWatcher: undefined }); } /** * 建立 IM 连接 * @param options */ connect(options) { return __awaiter(this, void 0, void 0, function* () { assert('options.token', options.token, AssertRules.STRING, true); const token = options.token; this._token = token; const res = yield this._context.connect(token, true); if (res.code === ErrorCode$1.SUCCESS) { return { id: res.userId }; } return Promise.reject({ code: res.code, msg: ERROR_CODE[res.code] }); }); } /** * 使用上一次的链接 token 重新建立连接,该方法只需在主动调用 `disconnect` 方法之后有重连需求时调用 */ reconnect() { return __awaiter(this, void 0, void 0, function* () { const res = yield this._context.reconnect(); if (res.code === ErrorCode$1.SUCCESS) { return { id: res.userId }; } return Promise.reject({ code: res.code, msg: ERROR_CODE[res.code] }); }); } /** * 断开当前用户的连接 * @description 调用后将不再接收消息,不可发送消息,不可获取历史消息,不可获取会话列表 */ disconnect() { return this._context.disconnect(); } /** * 获取当前 IM 环境信息 */ getAppInfo() { return { appkey: this._context.appkey, token: this._token, navi: this._context.getInfoFromCache() }; } /** * 获取 IM 连接时间 */ getConnectedTime() { return this._context.getConnectedTime(); } /** * 获取 IM 连接状态 */ getConnectionStatus() { return this._context.getConnectionStatus(); } /** * 获取 IM 连接用户的 id */ getConnectionUserId() { return this._context.getCurrentUserId(); } /** * 获取文件 token * @description 上传文件时,获取文件 token * @param fileType 上传类型, 通过 RongIMLib.FILE_TYPE 获取 * @param fileName 上传文件名,Server 通过文件名生成百度上传认证, 若不传 engine 自动生成 */ getFileToken(fileType, fileName) { assert('fileType', fileType, isValidFileType, true); return this._context.getFileToken(fileType, fileName); } /** * 获取文件上传后的下载地址 */ getFileUrl( /** * 上传类型, 通过 RongIMLib.FILE_TYPE 获取 */ fileType, /** * 上传后的文件名 */ filename, /** * 原始文件名 */ oriname, /** * 上传成功返回数据 * 百度 bos 上传地址即为下载地址,IM Server 不会返回百度 bos 下载地址,通过用户层传入再返回 */ uploadRes, /** * 上传方式,阿里或七牛,RongIMLib.UploadMethod 获取 */ uploadMethod) { assert('fileType', fileType, isValidFileType, true); assert('filename', filename, AssertRules.STRING); assert('oriname', oriname, AssertRules.STRING); assert('uploadMethod', uploadMethod, AssertRules.NUMBER); return this._context.getFileUrl(fileType, filename, oriname, uploadRes, uploadMethod); } /** * 切换用户,作用等同于断开当前用户连接,以新的 token 重新建立连接 * @param option */ changeUser(options) { return __awaiter(this, void 0, void 0, function* () { assert('options.token', options.token, AssertRules.STRING, true); yield this.disconnect(); return this.connect(options); }); } /** * 注册自定义消息 * @param messageType 消息类型 * @param isPersited 是否存储 * @param isCounted 是否计数 * @param prototypes 消息属性名称 */ registerMessageType(messageType, isPersited, isCounted, prototypes) { this._context.registerMessageType(messageType, isPersited, isCounted, prototypes); } } let imInstance; /** * 初始化 * @param {IInitOption} options */ const init = (options) => { if (imInstance) { logger$1.error('The instance already exists. Do not repeatedly call the init method'); return imInstance; } assert('options.appkey', options.appkey, AssertRules.STRING, true); assert('options.debug', options.debug, AssertRules.BOOLEAN); assert('options.navigators', options.navigators, (value) => { return isArray(value) && (value.length === 0 || value.every(isHttpUrl)); }); const context = APIContext.init(runtime$2, { appkey: options.appkey, apiVersion: "4.1.0", navigators: options.navigators || [], miniCMPProxy: options.customCMP || [], isEnterPrise: !true, connectionType: options.connectType || 'websocket', cppProtocol: options.cppProtocol }); imInstance = new IMClient(context); return imInstance; }; const getInstance = () => { if (!imInstance) { logger$1.error('Please call the init method first'); } return imInstance; }; exports.CHATROOM_ENTRY_TYPE = CHATROOM_ENTRY_TYPE; exports.CHATROOM_ORDER = CHATROOM_ORDER; exports.CONNECTION_STATUS = CONNECTION_STATUS; exports.CONNECT_TYPE = CONNECT_TYPE; exports.CONVERSATION_TYPE = CONVERSATION_TYPE; exports.ConnectionStatus = ConnectionStatus$1; exports.ERROR_CODE = ERROR_CODE; exports.FILE_TYPE = FILE_TYPE; exports.IMClient = IMClient; exports.MENTIONED_TYPE = MENTIONED_TYPE; exports.MESSAGE_DIRECTION = MESSAGE_DIRECTION; exports.MESSAGE_TYPE = MESSAGE_TYPE; exports.MESSAGS_TIME_ORDER = MESSAGS_TIME_ORDER; exports.NOTIFICATION_STATUS = NOTIFICATION_STATUS; exports.RECALL_MESSAGE_TYPE = RECALL_MESSAGE_TYPE; exports.RECEIVED_STATUS = RECEIVED_STATUS; exports.SDK_VERSION = SDK_VERSION; exports.UploadMethod = UploadMethod$1; exports.getInstance = getInstance; exports.init = init; return exports; }({})); ================================================ FILE: api-test-v4/lib/js/RongIMLib-4.2.0.js ================================================ /* * RCEngine - v4.2.0 * CommitId - 1838ab715d966e65fa509d4d5e4ffd76827367a7 * Tue Jan 12 2021 20:56:53 GMT+0800 (China Standard Time) * ©2020 RongCloud, Inc. All rights reserved. */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.RCEngine = {})); }(this, (function (exports) { 'use strict'; var ReceivedStatus; (function (ReceivedStatus) { /** * 已读 */ ReceivedStatus[ReceivedStatus["READ"] = 1] = "READ"; /** * 已听 */ ReceivedStatus[ReceivedStatus["LISTENED"] = 2] = "LISTENED"; /** * 已下载 */ ReceivedStatus[ReceivedStatus["DOWNLOADED"] = 4] = "DOWNLOADED"; /** * 该消息已经被其他登录的多端收取过。( 即该消息已经被其他端收取过后。当前端才登录,并重新拉取了这条消息。客户可以通过这个状态更新 UI,比如不再提示 ) */ ReceivedStatus[ReceivedStatus["RETRIEVED"] = 8] = "RETRIEVED"; /** * 未读 */ ReceivedStatus[ReceivedStatus["UNREAD"] = 0] = "UNREAD"; })(ReceivedStatus || (ReceivedStatus = {})); var ReceivedStatus$1 = ReceivedStatus; /** * Navi 缓存数据有效时长,单位毫秒 */ const NAVI_CACHE_DURATION = 2 * 60 * 60 * 1000; /** * 单个 Navi 请求的超时时间,单位毫秒 */ const NAVI_REQ_TIMEOUT = 10 * 1000; /** * /ping?r= 请求的超时时间,单位毫秒 */ const PING_REQ_TIMEOUT = 5 * 1000; /** * WebSocket 建立连接超时时间,单位毫秒 */ const WEB_SOCKET_TIMEOUT = 5 * 1000; /** * 公有云 Navi 请求地址 */ const PUBLIC_CLOUD_NAVI_URIS = ['https://nav.cn.ronghub.com', 'https://nav2-cn.ronghub.com']; /** * 小程序 websocket 连接地址 */ const MINI_SOCKET_CONNECT_URIS = ['wsproxy.cn.ronghub.com', 'wsap-cn.ronghub.com']; /** * 小程序 长轮询 连接地址 */ const MINI_COMET_CONNECT_URIS = ['cometproxy-cn.ronghub.com', 'mini-cn.ronghub.com']; /** * IM 接口超时时间,单位毫秒 */ const IM_SIGNAL_TIMEOUT = 30 * 1000; /** * IM Ping 间隔时间,单位毫秒 */ const IM_PING_INTERVAL_TIME = 30 * 1000; /** * 消息 content 内容尺寸限制:128 KB */ const MAX_MESSAGE_CONTENT_BYTES = 128 * 1024; /** * IM Comet 发送 pullmsg(嗅探 + 等待信令) 超时时间 45s */ const IM_COMET_PULLMSG_TIMEOUT = 45000; /** * storage key 使用的前缀 */ const STORAGE_ROOT_KEY = 'RCV4-'; /* * 内置消息的配置项. 发消息时, objectName 匹配到以下项时, 将覆盖用户传入值 * 内置消息文档: https://docs.rongcloud.cn/im/introduction/message_structure/#inherent * 'RC:DizNtf' 为讨论组消息通知类型,讨论组已废弃 */ const SEND_MESSAGE_TYPE_OPTION = { // 存储且计数 'RC:TxtMsg': { isCounted: true, isPersited: true }, 'RC:ImgMsg': { isCounted: true, isPersited: true }, 'RC:VcMsg': { isCounted: true, isPersited: true }, 'RC:ImgTextMsg': { isCounted: true, isPersited: true }, 'RC:FileMsg': { isCounted: true, isPersited: true }, 'RC:HQVCMsg': { isCounted: true, isPersited: true }, 'RC:LBSMsg': { isCounted: true, isPersited: true }, 'RC:PSImgTxtMsg': { isCounted: true, isPersited: true }, 'RC:PSMultiImgTxtMsg': { isCounted: true, isPersited: true }, 'RCJrmf:RpMsg': { isCounted: true, isPersited: true }, 'RCJrmf:RpOpendMsg': { isCounted: true, isPersited: true }, 'RC:CombineMsg': { isCounted: true, isPersited: true }, 'RC:ReferenceMsg': { isCounted: true, isPersited: true }, 'RC:SightMsg': { isCounted: true, isPersited: true }, // 只存储 不计数 'RC:InfoNtf': { isCounted: false, isPersited: true }, 'RC:ContactNtf': { isCounted: false, isPersited: true }, 'RC:ProfileNtf': { isCounted: false, isPersited: true }, 'RC:CmdNtf': { isCounted: false, isPersited: true }, 'RC:GrpNtf': { isCounted: false, isPersited: true }, 'RC:RcCmd': { isCounted: false, isPersited: true }, // 不存储 只计数 - 目前无 // 不存储 不计数 'RC:CmdMsg': { isCounted: false, isPersited: false }, 'RC:TypSts': { isCounted: false, isPersited: false }, 'RC:PSCmd': { isCounted: false, isPersited: false }, 'RC:SRSMsg': { isCounted: false, isPersited: false }, 'RC:RRReqMsg': { isCounted: false, isPersited: false }, 'RC:RRRspMsg': { isCounted: false, isPersited: false }, 'RC:CsChaR': { isCounted: false, isPersited: false }, 'RC:CSCha': { isCounted: false, isPersited: false }, 'RC:CsEva': { isCounted: false, isPersited: false }, 'RC:CsContact': { isCounted: false, isPersited: false }, 'RC:CsHs': { isCounted: false, isPersited: false }, 'RC:CsHsR': { isCounted: false, isPersited: false }, 'RC:CsSp': { isCounted: false, isPersited: false }, 'RC:CsEnd': { isCounted: false, isPersited: false }, 'RC:CsUpdate': { isCounted: false, isPersited: false }, 'RC:ReadNtf': { isCounted: false, isPersited: false }, 'RC:chrmKVNotiMsg': { isCounted: false, isPersited: false }, 'RC:VCAccept': { isCounted: false, isPersited: false }, 'RC:VCRinging': { isCounted: false, isPersited: false }, 'RC:VCSummary': { isCounted: false, isPersited: false }, 'RC:VCHangup': { isCounted: false, isPersited: false }, 'RC:VCInvite': { isCounted: false, isPersited: false }, 'RC:VCModifyMedia': { isCounted: false, isPersited: false }, 'RC:VCModifyMem': { isCounted: false, isPersited: false }, 'RC:MsgExMsg': { isCounted: false, isPersited: false } }; let rootStorage; const createRootStorage = (runtime) => { if (!rootStorage) { rootStorage = { set: (key, val) => { runtime.localStorage.setItem(key, JSON.stringify(val)); }, get: (key) => { let val; try { val = JSON.parse(runtime.localStorage.getItem(key)); } catch (e) { val = null; } return val; }, remove: (key) => { return runtime.localStorage.removeItem(key); }, getKeys: () => { const keys = []; for (const key in runtime.localStorage) { keys.push(key); } return keys; } }; } return rootStorage; }; class AppCache { constructor(value) { this._caches = {}; if (value) { this._caches = value; } } set(key, value) { this._caches[key] = value; } remove(key) { const val = this.get(key); delete this._caches[key]; return val; } get(key) { return this._caches[key]; } getKeys() { const keys = []; for (const key in this._caches) { keys.push(key); } return keys; } } class AppStorage { constructor(runtime, suffix) { const key = suffix ? `${STORAGE_ROOT_KEY}${suffix}` : STORAGE_ROOT_KEY; this._rootStorage = createRootStorage(runtime); const localCache = this._rootStorage.get(key) || {}; this._cache = new AppCache({ [key]: localCache }); this._storageKey = key; } _get() { const key = this._storageKey; return this._cache.get(key) || {}; } _set(cache) { const key = this._storageKey; cache = cache || {}; this._cache.set(key, cache); this._rootStorage.set(key, cache); } set(key, value) { const localValue = this._get(); localValue[key] = value; this._set(localValue); } remove(key) { const localValue = this._get(); delete localValue[key]; this._set(localValue); } clear() { const key = this._storageKey; this._rootStorage.remove(key); this._cache.remove(key); } get(key) { const localValue = this._get(); return localValue[key]; } getKeys() { const localValue = this._get(); const keyList = []; for (const key in localValue) { keyList.push(key); } return keyList; } getValues() { return this._get() || {}; } } class Todo extends Error { constructor(message) { super(`TODO => ${message}`); } } const todo = (message) => new Todo(message); /** * 字符串转为大写形式并返回 * @todo 违反单一性原则,后续需分拆,以及需要评估是否过渡封装 * @param str * @param startIndex 开始位置 * @param endIndex 结束位置 */ const toUpperCase = (str, startIndex, endIndex) => { if (startIndex === undefined || endIndex === undefined) { return str.toUpperCase(); } const sliceStr = str.slice(startIndex, endIndex); str = str.replace(sliceStr, (text) => { return text.toUpperCase(); }); return str; }; const getByteLength = (str, charset = 'utf-8') => { let total = 0; let chatCode; if (charset === 'utf-16') { for (let i = 0, max = str.length; i < max; i++) { chatCode = str.charCodeAt(i); if (chatCode <= 0xffff) { total += 2; } else { total += 4; } } } else { for (let i = 0, max = str.length; i < max; i++) { chatCode = str.charCodeAt(i); if (chatCode < 0x007f) { total += 1; } else if (chatCode <= 0x07ff) { total += 2; } else if (chatCode <= 0xffff) { total += 3; } else { total += 4; } } } return total; }; const appendUrl = (url, query) => { url = url.replace(/\?$/, ''); if (!query) { return url; } const searchArr = Object.keys(query).map(key => `${key}=${query[key]}`).filter(item => !!item); if (searchArr.length) { return [url, searchArr.join('&')].join('?'); } return url; }; /** * 建立连接时,apiVersion 需符合 `/\d+(\.\d+){2}/` 规则,对于预发布版本号如 `3.1.0-alpha.1`,需解析定为 `3.1.0` * @param apiVersion */ const matchVersion = (apiVersion) => { const matches = apiVersion.match(/\d+(\.\d+){2}/); return matches[0]; }; (function (LogLevel) { /** * 等同于 `LogLevel.DEBUG` */ LogLevel[LogLevel["LOG"] = 0] = "LOG"; LogLevel[LogLevel["DEBUG"] = 0] = "DEBUG"; LogLevel[LogLevel["INFO"] = 1] = "INFO"; LogLevel[LogLevel["WARN"] = 2] = "WARN"; LogLevel[LogLevel["ERROR"] = 3] = "ERROR"; LogLevel[LogLevel["NONE"] = 1000] = "NONE"; })(exports.LogLevel || (exports.LogLevel = {})); const methods = { [exports.LogLevel.DEBUG]: console.debug.bind(console), [exports.LogLevel.INFO]: console.info.bind(console), [exports.LogLevel.WARN]: console.warn.bind(console), [exports.LogLevel.ERROR]: console.error.bind(console) }; class Logger { constructor(_tag) { this._tag = _tag; /** * 输出等级 */ this._outLevel = exports.LogLevel.WARN; /** * 输出函数 */ this._stdout = this._defaultStdout; this.log = this._out; this.debug = this._out.bind(this, exports.LogLevel.DEBUG); this.info = this._out.bind(this, exports.LogLevel.INFO); this.warn = this._out.bind(this, exports.LogLevel.WARN); this.error = this._out.bind(this, exports.LogLevel.ERROR); } /** * 默认输出函数 * @param level * @param args */ _defaultStdout(level, ...args) { methods[level](`[${this._tag}](${new Date().toUTCString()}):`, ...args); } _out(level, ...args) { level >= this._outLevel && this._stdout(level, ...args); } /** * 设置默认输出等级及输出函数 * @param outLevel * @param stdout */ set(outLevel, stdout) { this._outLevel = outLevel; this._stdout = stdout || this._defaultStdout; } } const logger = new Logger('RCLog'); /** * 会话类型 */ var ConversationType; (function (ConversationType) { /** * 无类型 */ ConversationType[ConversationType["NONE"] = 0] = "NONE"; /** * 单聊 */ ConversationType[ConversationType["PRIVATE"] = 1] = "PRIVATE"; /** * 讨论组 */ ConversationType[ConversationType["DISCUSSION"] = 2] = "DISCUSSION"; /** * 群组聊天 */ ConversationType[ConversationType["GROUP"] = 3] = "GROUP"; /** * 聊天室会话 */ ConversationType[ConversationType["CHATROOM"] = 4] = "CHATROOM"; /** * 客服会话 */ ConversationType[ConversationType["CUSTOMER_SERVICE"] = 5] = "CUSTOMER_SERVICE"; /** * 系统消息 */ ConversationType[ConversationType["SYSTEM"] = 6] = "SYSTEM"; /** * 默认关注的公众号会话类型(MC) */ ConversationType[ConversationType["APP_PUBLIC_SERVICE"] = 7] = "APP_PUBLIC_SERVICE"; /** * 需手动关注的公众号会话类型(MP) */ ConversationType[ConversationType["PUBLIC_SERVICE"] = 8] = "PUBLIC_SERVICE"; /** * RTCLib 特有的会话类型 */ ConversationType[ConversationType["RTC_ROOM"] = 12] = "RTC_ROOM"; })(ConversationType || (ConversationType = {})); var ConversationType$1 = ConversationType; /** * 文件类型 */ var FileType; (function (FileType) { /** * 图片文件 */ FileType[FileType["IMAGE"] = 1] = "IMAGE"; /** * 声音文件 */ FileType[FileType["AUDIO"] = 2] = "AUDIO"; /** * 视频文件 */ FileType[FileType["VIDEO"] = 3] = "VIDEO"; /** * 非媒体文件 */ FileType[FileType["FILE"] = 4] = "FILE"; /** * 小视频类型 */ FileType[FileType["SIGHT"] = 5] = "SIGHT"; /** * 合并转发 */ FileType[FileType["COMBINE_HTML"] = 6] = "COMBINE_HTML"; })(FileType || (FileType = {})); var FileType$1 = FileType; /** * 检查参数是否为字符串 * 只做类型检查,不做长度检查,故当字符串长度为 0,结果依然为 true * @param str */ const isString = (value) => typeof value === 'string'; /** * 检查参数是否为 number 数据 * @param value */ const isNumber = (value) => typeof value === 'number' && !isNaN(value); /** * 检查参数是否为数组 * 只做类型检查,不做长度检查 * 如 UnitArray、BufferArray 等也属于数组 * @param arr */ const isArray = (arr) => Object.prototype.toString.call(arr).indexOf('Array') !== -1; /** * 检查参数是否为 ArrayBuffer * @param arr */ const isArrayBuffer = (arr) => Object.prototype.toString.call(arr) === '[object ArrayBuffer]'; /** * 检查参数是否为长度非 0 的字符串 * @param str */ const notEmptyString = (str) => isString(str) && str.length > 0; /** * 检查参数是否为长度非 0 的数组 * @param str */ const notEmptyArray = (arr) => isArray(arr) && arr.length > 0; /** * 检查参数是否为对象 * @param val */ const isObject = (val) => { return Object.prototype.toString.call(val) === '[object Object]'; }; /** * 检查参数是否为函数 * @param val */ const isFunction = (val) => { return Object.prototype.toString.call(val) === '[object Function]'; }; /** * 检查参数是否为undefined * @param val */ const isUndefined = (val) => { // IE 下 undefined 为 Object return val === undefined || Object.prototype.toString.call(val) === '[object Undefined]'; }; /** * 检查参数是否为 null */ const isNull = (val) => { return Object.prototype.toString.call(val) === '[object Null]'; }; /** * 检查参数是否为有效 http(s) 协议 url * @param value */ const isHttpUrl = (value) => isString(value) && /https?:\/\//.test(value); /** * 检查对象不为空 * @param val */ const notEmptyObject = (val) => { // eslint-disable-next-line no-unreachable-loop for (const key in val) { return true; } return false; }; const isValidConversationType = (conversation) => { return isNumber(conversation) && Object.prototype.hasOwnProperty.call(ConversationType$1, conversation); }; /** * 判断是否是一个有效的文件类型 */ const isValidFileType = (fileType) => { return isNumber(fileType) && Object.prototype.hasOwnProperty.call(FileType$1, fileType); }; class EventEmitter { constructor() { this._map = {}; } /** * 添加事件监听器 * @param eventType * @param listener */ on(eventType, listener) { const arr = this._map[eventType] || (this._map[eventType] = []); if (arr.includes(listener)) { return; } arr.push(listener); } /** * 移除事件监听器 * @param eventType * @param listener */ off(eventType, listener) { const arr = this._map[eventType]; if (!arr) { return; } const len = arr.length; for (let i = len - 1; i >= 0; i -= 1) { if (arr[i] === listener) { arr.splice(i, 1); if (len === 1) { delete this._map[eventType]; } break; } } } /** * 事件派发 * @param eventType * @param data */ emit(eventType, data) { const arr = this._map[eventType]; if (!arr) { return; } arr.forEach(item => item(data)); } /** * 清空所有指定类型的事件监听器 * @param eventType */ removeAll(eventType) { delete this._map[eventType]; } /** * 无差别清空所有事件监听器 */ clear() { Object.keys(this._map).forEach(this.removeAll, this); } } (function (AssertRules) { /** * 类型为字符串,且长度大于 0 */ AssertRules[AssertRules["STRING"] = 0] = "STRING"; /** * 类型仅为 String */ AssertRules[AssertRules["ONLY_STRING"] = 1] = "ONLY_STRING"; /** * 类型为数字 */ AssertRules[AssertRules["NUMBER"] = 2] = "NUMBER"; /** * 类型为布尔值 */ AssertRules[AssertRules["BOOLEAN"] = 3] = "BOOLEAN"; /** * 类型为对象 */ AssertRules[AssertRules["OBJECT"] = 4] = "OBJECT"; /** * 类型为数组 */ AssertRules[AssertRules["ARRAY"] = 5] = "ARRAY"; /** * 类型为 callback 回调对象,包含 callback.onSuccess、callback.onError */ AssertRules[AssertRules["CALLBACK"] = 6] = "CALLBACK"; })(exports.AssertRules || (exports.AssertRules = {})); const validators = { [exports.AssertRules.STRING]: notEmptyString, [exports.AssertRules.ONLY_STRING]: isString, [exports.AssertRules.NUMBER]: isNumber, [exports.AssertRules.BOOLEAN]: (value) => typeof value === 'boolean', [exports.AssertRules.OBJECT]: isObject, [exports.AssertRules.ARRAY]: isArray, [exports.AssertRules.CALLBACK]: (callback) => { let flag = true; if (!isObject(callback)) { flag = false; } callback = callback || {}; if (callback.onSuccess && !isFunction(callback.onSuccess)) { flag = false; } if (callback.onError && !isFunction(callback.onError)) { flag = false; } return flag; } }; class RCAssertError extends Error { constructor(message) { super(message); this.name = 'RCAssertError'; } } /** * 参数校验,该方法用于对业务层入参数据检查,及时抛出异常通知业务层进行修改 * @description * 1. 必填参数,value 需符合 validator 验证规,否则抛出异常 * 2. 非必填参数,value 可为 undefined | null 或符合 validator 规则 * @param key 字段名,仅用于验证失败时给出提示信息 * @param value 待验证的值 * @param validator 期望类型或校验规则函数,若使用规则函数 * @param required 是否为必填参数,默认为 `false` */ const assert = (key, value, validator, required = false) => { if (!validate(key, value, validator, required)) { throw new RCAssertError(`'${key}' is invalid: ${JSON.stringify(value)}`); } }; /** * 参数校验,该方法用于对业务层入参数据检查,与 `assert` 函数不同的是其返回 boolean 值而非直接抛出异常 * @description * 1. 必填参数,value 需符合 validator 验证规,否则抛出异常 * 2. 非必填参数,value 可为 undefined | null 或符合 validator 规则 * @param key 字段名,仅用于验证失败时给出提示信息 * @param value 待验证的值 * @param validator 期望类型或校验规则函数,若使用规则函数 * @param required 是否为必填参数,默认为 `false` */ const validate = (key, value, validator, required = false) => { validator = validators[validator] || validator; const invalid = // 必填参数校验 (required && !validator(value)) || // 非必填参数校验 (!required && !(isUndefined(value) || value === null || validator(value))); if (invalid) { // 打印无效参数到控制台便于定位问题 logger.error(`'${key}' is invalid: ${JSON.stringify(value)}`); } return !invalid; }; /** * @todo 后期禁用此方法,容易滥用,且会丢失上下文的数据类型跟踪 * @deprecated * @param source * @param event * @param options */ const forEach = (source, event, options) => { options = options || {}; event = event || function () { }; const { isReverse } = options; const loopObj = () => { for (const key in source) { event(source[key], key, source); } }; const loopArr = () => { if (isReverse) { for (let i = source.length - 1; i >= 0; i--) { event(source[i], i); } } else { for (let j = 0, len = source.length; j < len; j++) { event(source[j], j); } } }; if (isObject(source)) { loopObj(); } if (isArray(source) || isString(source)) { loopArr(); } }; /** * @deprecated * @param source * @param event */ const map = (source, event) => { forEach(source, (item, index) => { source[index] = event(item, index); }); return source; }; const indexOf = (source, searchVal) => { // 注: 字符串的 indexof 兼容至 IE3 if (source.indexOf) { return source.indexOf(searchVal); } let index = -1; forEach(source, (sub, i) => { if (searchVal === sub) { index = i; } }); return index; }; const isInclude = (source, searchVal) => { const index = indexOf(source, searchVal); return index !== -1; }; /** * 判断对象里是否有某个值 */ const isInObject = (source, searchVal) => { const arr = []; forEach(source, (val) => { arr.push(val); }); const index = indexOf(arr, searchVal); return index !== -1; }; /** * 通过 JSON 拷贝 */ const cloneByJSON = (sourceObj) => { return JSON.parse(JSON.stringify(sourceObj)); }; /** * 聊天室 kv 存储操作类型. 对方操作, 己方收到消息(RC:chrmKVNotiMsg)中会带入此值. 根据此值判断是删除还是更新 */ var ChatroomEntryType; (function (ChatroomEntryType) { ChatroomEntryType[ChatroomEntryType["UPDATE"] = 1] = "UPDATE"; ChatroomEntryType[ChatroomEntryType["DELETE"] = 2] = "DELETE"; })(ChatroomEntryType || (ChatroomEntryType = {})); var ChatroomEntryType$1 = ChatroomEntryType; /** * 通过 status 计算接收到的消息的部分属性值 * @description * status 转为二进制, 二进制的比特位存储消息的部分属性值 * 属性所占比特位: * 0000-0010 该消息是否曾被该用户拉取过(其他端) * 0001-0000 isPersited * 0010-0000 isCounted * 0100-0000 isMentioned * 0010-0000-0000 disableNotification * 0100-0000-0000 canIncludeExpansion */ const getMessageOptionByStatus = (status) => { let isPersited = true; let isCounted = true; let isMentioned = false; let disableNotification = false; let receivedStatus = ReceivedStatus$1.READ; let isReceivedByOtherClient = false; let canIncludeExpansion = false; isPersited = !!(status & 0x10); isCounted = !!(status & 0x20); isMentioned = !!(status & 0x40); disableNotification = !!(status & 0x200); isReceivedByOtherClient = !!(status & 0x02); receivedStatus = isReceivedByOtherClient ? ReceivedStatus$1.RETRIEVED : receivedStatus; canIncludeExpansion = !!(status & 0x400); return { isPersited, isCounted, isMentioned, disableNotification, receivedStatus, canIncludeExpansion }; }; /** * 通过 sessionId 计算发送消息成功后,发送消息的部分属性 * @description * sessionId 转为二进制, 二进制的比特位存储消息的部分属性值 * 属性所占比特位: * 0000-0001 isPersited * 0000-0010 isCounted * 0000-0100 isMentioned * 0010-0000 disableNotification * 0100-0000 canIncludeExpansion */ const getUpMessageOptionBySessionId = (sessionId) => { let isPersited = false; let isCounted = false; let disableNotification = false; let canIncludeExpansion = false; isPersited = !!(sessionId & 0x01); isCounted = !!(sessionId & 0x02); disableNotification = !!(sessionId & 0x10); canIncludeExpansion = !!(sessionId & 0x40); return { isPersited, isCounted, disableNotification, canIncludeExpansion }; }; const formatExtraContent = (extraContent) => { const expansion = {}; // 扩展为用户任意设置的键值对 const parseExtraContent = JSON.parse(extraContent); forEach(parseExtraContent, (value, key) => { expansion[key] = value.v; }); return expansion; }; /** * TODO: 确定对外暴露的必要性 * @deprecated */ const DelayTimer = { _delayTime: 0, /** * 方法并未引用,getTimer 实际返回值始终为 Date.now() * @deprecated */ setTime: (time) => { const currentTime = new Date().getTime(); DelayTimer._delayTime = currentTime - time; }, getTime: () => { const delayTime = DelayTimer._delayTime; const currentTime = new Date().getTime(); return currentTime - delayTime; } }; const getChatRoomKVByStatus = (status) => { const isDeleteOpt = !!(status & 0x0004); return { isAutoDelete: !!(status & 0x0001), isOverwrite: !!(status & 0x0002), type: isDeleteOpt ? ChatroomEntryType$1.DELETE : ChatroomEntryType$1.UPDATE }; }; const getChatRoomKVOptStatus = (entity, action) => { let status = 0; // 是否自动清理 if (entity.isAutoDelete) { status = status | 0x0001; } // 是否覆盖 if (entity.isOverwrite) { status = status | 0x0002; } // 操作类型 if (action === 2) { status = status | 0x0004; } return status; }; const getSessionId = (option) => { const { isStatusMessage } = option; let { isPersited, isCounted, isMentioned, disableNotification, canIncludeExpansion } = option; if (isStatusMessage) { isPersited = isCounted = false; } let sessionId = 0; if (isPersited) { sessionId = sessionId | 0x01; } if (isCounted) { sessionId = sessionId | 0x02; } if (isMentioned) { sessionId = sessionId | 0x04; } if (disableNotification) { sessionId = sessionId | 0x20; } if (canIncludeExpansion) { sessionId = sessionId | 0x40; } return sessionId; }; /*! ***************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */ function __awaiter(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); } /** * 通信协议中 fixHeader 第一个字节中的 Qos 数据标识 * ``` * fixHeader:command(4 bit) | dup(1 bit) | Qos(2 bit) | retain(1 bit) * ``` */ var QOS; (function (QOS) { QOS[QOS["AT_MOST_ONCE"] = 0] = "AT_MOST_ONCE"; QOS[QOS["AT_LEAST_ONCE"] = 1] = "AT_LEAST_ONCE"; QOS[QOS["EXACTLY_ONCE"] = 2] = "EXACTLY_ONCE"; QOS[QOS["DEFAULT"] = 3] = "DEFAULT"; })(QOS || (QOS = {})); /** * 通信协议中 fixHeader 第一个字节中的 command 数据标识,用于判断操作类型 * ``` * fixHeader:command(4 bit) | dup(1 bit) | Qos(2 bit) | retain(1 bit) * ``` */ var OperationType; (function (OperationType) { /** 私有云专用,解密协商指令 */ OperationType[OperationType["SYMMETRIC"] = 0] = "SYMMETRIC"; /** 连接请求 */ OperationType[OperationType["CONNECT"] = 1] = "CONNECT"; /** 连接应答 */ OperationType[OperationType["CONN_ACK"] = 2] = "CONN_ACK"; /** 上行发送消息 */ OperationType[OperationType["PUBLISH"] = 3] = "PUBLISH"; /** 上行发送消息的应答 */ OperationType[OperationType["PUB_ACK"] = 4] = "PUB_ACK"; /** 上行拉消息 */ OperationType[OperationType["QUERY"] = 5] = "QUERY"; /** 上行拉消息的应答 */ OperationType[OperationType["QUERY_ACK"] = 6] = "QUERY_ACK"; /** QueryConfirm */ OperationType[OperationType["QUERY_CONFIRM"] = 7] = "QUERY_CONFIRM"; OperationType[OperationType["SUBSCRIBE"] = 8] = "SUBSCRIBE"; OperationType[OperationType["SUB_ACK"] = 9] = "SUB_ACK"; OperationType[OperationType["UNSUBSCRIBE"] = 10] = "UNSUBSCRIBE"; OperationType[OperationType["UNSUB_ACK"] = 11] = "UNSUB_ACK"; OperationType[OperationType["PING_REQ"] = 12] = "PING_REQ"; OperationType[OperationType["PING_RESP"] = 13] = "PING_RESP"; /** 连接挂断 */ OperationType[OperationType["DISCONNECT"] = 14] = "DISCONNECT"; OperationType[OperationType["RESERVER2"] = 15] = "RESERVER2"; })(OperationType || (OperationType = {})); var MessageName; (function (MessageName) { MessageName["CONN_ACK"] = "ConnAckMessage"; MessageName["DISCONNECT"] = "DisconnectMessage"; MessageName["PING_REQ"] = "PingReqMessage"; MessageName["PING_RESP"] = "PingRespMessage"; MessageName["PUBLISH"] = "PublishMessage"; MessageName["PUB_ACK"] = "PubAckMessage"; MessageName["QUERY"] = "QueryMessage"; MessageName["QUERY_CON"] = "QueryConMessage"; MessageName["QUERY_ACK"] = "QueryAckMessage"; })(MessageName || (MessageName = {})); var IDENTIFIER; (function (IDENTIFIER) { IDENTIFIER["PUB"] = "pub"; IDENTIFIER["QUERY"] = "qry"; })(IDENTIFIER || (IDENTIFIER = {})); /** * @todo 注释补全 * @description * Header 处理 */ class Header { constructor(type, retain = false, qos = QOS.AT_LEAST_ONCE, dup = false) { this._retain = false; this.qos = QOS.AT_LEAST_ONCE; this._dup = false; this.syncMsg = false; const isPlusType = type > 0; // 是否为正数 if (type && isPlusType && arguments.length === 1) { this._retain = (type & 1) > 0; this.qos = (type & 6) >> 1; // (_type & 0b110) >> 1 this._dup = (type & 8) > 0; // (_type & 0b1000) > 0 this.type = (type >> 4) & 15; // (_type >> 0b100) & 0b1111 this.syncMsg = (type & 8) === 8; // (_type & 0b1000) === 0b1000; } else { this.type = type; this._retain = retain; this.qos = qos; this._dup = dup; } } encode() { // const validQosList = [QOS.AT_MOST_ONCE, QOS.AT_LEAST_ONCE, QOS.EXACTLY_ONCE, QOS.DEFAULT] // // 如果 qos 为字符串, 此处转为数字 // for (let i = 0; i < validQosList.length; i++) { // if (this.qos === validQosList[i]) { // this.qos = validQosList[i] // } // } let byte = (this.type << 4); // 4 -> 100 byte |= this._retain ? 1 : 0; byte |= this.qos << 1; byte |= this._dup ? 8 : 0; // 8 -> 1000 return byte; } } /** * @description * 二进制处理 */ class BinaryHelper { /** * @description * 将字符串转化为 utf8 编码组成的数组 * @param {string} str 待转化的字符串 * @param {boolean} isGetBytes 是否向前插入字符长度 */ static writeUTF(str, isGetBytes) { const back = []; let byteSize = 0; if (isString(str)) { for (let i = 0, len = str.length; i < len; i++) { const code = str.charCodeAt(i); if (code >= 0 && code <= 127) { byteSize += 1; back.push(code); } else if (code >= 128 && code <= 2047) { byteSize += 2; back.push((192 | (31 & (code >> 6)))); back.push((128 | (63 & code))); } else if (code >= 2048 && code <= 65535) { byteSize += 3; back.push((224 | (15 & (code >> 12)))); back.push((128 | (63 & (code >> 6)))); back.push((128 | (63 & code))); } } } for (let i = 0, len = back.length; i < len; i++) { if (back[i] > 255) { back[i] &= 255; } } if (isGetBytes) { return back; } if (byteSize <= 255) { return [0, byteSize].concat(back); } else { return [byteSize >> 8, byteSize & 255].concat(back); } } /** * @description * 获取二进制字节流的 utf8 编码结果 * @param {Array} arr 二进制数据 */ static readUTF(arr) { const MAX_SIZE = 0x4000; const codeUnits = []; let highSurrogate; let lowSurrogate; let index = -1; const strBytes = arr; let result = ''; while (++index < strBytes.length) { let codePoint = Number(strBytes[index]); if (codePoint === (codePoint & 0x7F)) ; else if ((codePoint & 0xF0) === 0xF0) { codePoint ^= 0xF0; codePoint = (codePoint << 6) | (strBytes[++index] ^ 0x80); codePoint = (codePoint << 6) | (strBytes[++index] ^ 0x80); codePoint = (codePoint << 6) | (strBytes[++index] ^ 0x80); } else if ((codePoint & 0xE0) === 0xE0) { codePoint ^= 0xE0; codePoint = (codePoint << 6) | (strBytes[++index] ^ 0x80); codePoint = (codePoint << 6) | (strBytes[++index] ^ 0x80); } else if ((codePoint & 0xC0) === 0xC0) { codePoint ^= 0xC0; codePoint = (codePoint << 6) | (strBytes[++index] ^ 0x80); } if (!isFinite(codePoint) || codePoint < 0 || codePoint > 0x10FFFF || Math.floor(codePoint) !== codePoint) { throw RangeError('Invalid code point: ' + codePoint); } if (codePoint <= 0xFFFF) { codeUnits.push(codePoint); } else { codePoint -= 0x10000; highSurrogate = (codePoint >> 10) | 0xD800; lowSurrogate = (codePoint % 0x400) | 0xDC00; codeUnits.push(highSurrogate, lowSurrogate); } if (index + 1 === strBytes.length || codeUnits.length > MAX_SIZE) { result += String.fromCharCode.apply(null, codeUnits); codeUnits.length = 0; } } return result; } } /** * @description * 融云读取二进制数据 */ class RongStreamReader { constructor(arr) { // 当前流已截取到的位置 this._position = 0; // 待处理数据的总长度 this._poolLen = 0; this._pool = arr; this._poolLen = arr.length; } check() { return this._position >= this._pool.length; } /** * 读 4 位 */ readInt() { const self = this; if (self.check()) { return -1; } let end = ''; for (let i = 0; i < 4; i++) { let t = self._pool[self._position++].toString(16); if (t.length === 1) { t = '0' + t; } end += t.toString(); } return parseInt(end, 16); } /** * 读 8 位 */ readLong() { const self = this; if (self.check()) { return -1; } let end = ''; for (let i = 0; i < 8; i++) { let t = self._pool[self._position++].toString(16); if (t.length === 1) { t = '0' + t; } end += t; } return parseInt(end, 16); } /** * 读 1 位 */ readByte() { if (this.check()) { return -1; } let val = this._pool[this._position++]; if (val > 255) { val &= 255; } return val; } /** * 获取数据 */ readUTF() { if (this.check()) { return ''; } const big = (this.readByte() << 8) | this.readByte(); const pool = this._pool.subarray(this._position, this._position += big); return BinaryHelper.readUTF(pool); } /** * 读剩余的所有值 */ readAll() { return this._pool.subarray(this._position, this._poolLen); } } /** * @description * 融云写入二进制数据 */ class RongStreamWriter { constructor() { // 待处理的数据, 由 server 直接抛出的数据 this._pool = []; // 当前流已截取到的位置 this._position = 0; // 当前流写入的多少字节 this._writen = 0; } /** * 写入缓存区, writen 值往后移 */ write(byte) { // todo if (Object.prototype.toString.call(byte).indexOf('Array') !== -1) { this._pool = this._pool.concat(byte); } else if (byte >= 0) { if (byte > 255) { byte &= 255; } this._pool.push(byte); this._writen++; } return byte; } writeArr(byte) { this._pool = this._pool.concat(byte); return byte; } // PENDING. 用于 ConnectMessage, 暂未知此消息用途 // writeChat(v: number) { // if (+v != v) { // throw new Error("writeChar:arguments type is error"); // } // this.write(v >> 8 & 255); // this.write(v & 255); // this.writen += 2; // } writeUTF(str) { const val = BinaryHelper.writeUTF(str); this._pool = this._pool.concat(val); this._writen += val.length; } // PENDING. 暂仅知道 write 时使用, 此时 this.poolLen 为 0, 调用无意义 // toComplements(): any { // var _tPool = this.pool; // for (var i = 0; i < this.poolLen; i++) { // if (_tPool[i] > 128) { // _tPool[i] -= 256; // } // } // return _tPool; // } getBytesArray() { return this._pool; } } var PBName = { UpStreamMessage: 'UpStreamMessage', DownStreamMessage: 'DownStreamMessage', DownStreamMessages: 'DownStreamMessages', SessionsAttQryInput: 'SessionsAttQryInput', SessionsAttOutput: 'SessionsAttOutput', SyncRequestMsg: 'SyncRequestMsg', ChrmPullMsg: 'ChrmPullMsg', NotifyMsg: 'NotifyMsg', HistoryMsgInput: 'HistoryMsgInput', HistoryMsgOuput: 'HistoryMsgOuput', RelationQryInput: 'RelationQryInput', RelationsOutput: 'RelationsOutput', DeleteSessionsInput: 'DeleteSessionsInput', SessionInfo: 'SessionInfo', DeleteSessionsOutput: 'DeleteSessionsOutput', RelationsInput: 'RelationsInput', DeleteMsgInput: 'DeleteMsgInput', CleanHisMsgInput: 'CleanHisMsgInput', SessionMsgReadInput: 'SessionMsgReadInput', ChrmInput: 'ChrmInput', QueryChatRoomInfoInput: 'QueryChatRoomInfoInput', QueryChatRoomInfoOutput: 'QueryChatRoomInfoOutput', RtcInput: 'RtcInput', RtcUserListOutput: 'RtcUserListOutput', SetUserStatusInput: 'SetUserStatusInput', RtcSetDataInput: 'RtcSetDataInput', RtcUserSetDataInput: 'RtcUserSetDataInput', RtcDataInput: 'RtcDataInput', RtcSetOutDataInput: 'RtcSetOutDataInput', MCFollowInput: 'MCFollowInput', RtcTokenOutput: 'RtcTokenOutput', RtcQryOutput: 'RtcQryOutput', RtcQryUserOutDataInput: 'RtcQryUserOutDataInput', RtcUserOutDataOutput: 'RtcUserOutDataOutput', RtcQueryListInput: 'RtcQueryListInput', RtcRoomInfoOutput: 'RtcRoomInfoOutput', RtcValueInfo: 'RtcValueInfo', RtcKeyDeleteInput: 'RtcKeyDeleteInput', GetQNupTokenInput: 'GetQNupTokenInput', GetQNupTokenOutput: 'GetQNupTokenOutput', GetQNdownloadUrlInput: 'GetQNdownloadUrlInput', GetDownloadUrlInput: 'GetDownloadUrlInput', GetQNdownloadUrlOutput: 'GetQNdownloadUrlOutput', GetDownloadUrlOutput: 'GetDownloadUrlOutput', SetChrmKV: 'SetChrmKV', ChrmKVOutput: 'ChrmKVOutput', QueryChrmKV: 'QueryChrmKV', SetUserSettingInput: 'SetUserSettingInput', SetUserSettingOutput: 'SetUserSettingOutput', PullUserSettingInput: 'PullUserSettingInput', PullUserSettingOutput: 'PullUserSettingOutput', UserSettingNotification: 'UserSettingNotification', SessionReq: 'SessionReq', SessionStates: 'SessionStates', SessionState: 'SessionState', SessionStateItem: 'SessionStateItem', SessionStateModifyReq: 'SessionStateModifyReq', SessionStateModifyResp: 'SessionStateModifyResp' // 修改会话状态回执 }; const SSMsg = { [PBName.UpStreamMessage]: ['sessionId', 'classname', 'content', 'pushText', 'userId', 'configFlag', 'appData', 'extraContent'], [PBName.DownStreamMessages]: ['list', 'syncTime', 'finished'], [PBName.DownStreamMessage]: ['fromUserId', 'type', 'groupId', 'classname', 'content', 'dataTime', 'status', 'msgId', 'extraContent'], [PBName.SessionsAttQryInput]: ['nothing'], [PBName.SessionsAttOutput]: ['inboxTime', 'sendboxTime', 'totalUnreadCount'], [PBName.SyncRequestMsg]: ['syncTime', 'ispolling', 'isweb', 'isPullSend', 'isKeeping', 'sendBoxSyncTime'], [PBName.ChrmPullMsg]: ['syncTime', 'count'], [PBName.NotifyMsg]: ['type', 'time', 'chrmId'], [PBName.HistoryMsgInput]: ['targetId', 'time', 'count', 'order'], [PBName.HistoryMsgOuput]: ['list', 'syncTime', 'hasMsg'], [PBName.RelationQryInput]: ['type', 'count', 'startTime', 'order'], [PBName.RelationsOutput]: ['info'], [PBName.DeleteSessionsInput]: ['sessions'], [PBName.SessionInfo]: ['type', 'channelId'], [PBName.DeleteSessionsOutput]: ['nothing'], [PBName.RelationsInput]: ['type', 'msg', 'count', 'offset', 'startTime', 'endTime'], [PBName.DeleteMsgInput]: ['type', 'conversationId', 'msgs'], [PBName.CleanHisMsgInput]: ['targetId', 'dataTime', 'conversationType'], [PBName.SessionMsgReadInput]: ['type', 'msgTime', 'channelId'], [PBName.ChrmInput]: ['nothing'], [PBName.QueryChatRoomInfoInput]: ['count', 'order'], [PBName.QueryChatRoomInfoOutput]: ['userTotalNums', 'userInfos'], [PBName.GetQNupTokenInput]: ['type', 'key'], [PBName.GetQNdownloadUrlInput]: ['type', 'key', 'fileName'], [PBName.GetDownloadUrlInput]: ['type', 'key', 'fileName'], [PBName.GetQNupTokenOutput]: ['deadline', 'token', 'bosToken', 'bosDate', 'path', 'osskeyId', 'ossPolicy', 'ossSign', 'ossBucketName'], [PBName.GetQNdownloadUrlOutput]: ['downloadUrl'], [PBName.GetDownloadUrlOutput]: ['downloadUrl'], [PBName.SetChrmKV]: ['entry', 'bNotify', 'notification', 'type'], [PBName.ChrmKVOutput]: ['entries', 'bFullUpdate', 'syncTime'], [PBName.QueryChrmKV]: ['timestamp'], [PBName.SetUserSettingInput]: ['version', 'value'], [PBName.SetUserSettingOutput]: ['version', 'reserve'], [PBName.PullUserSettingInput]: ['version', 'reserve'], [PBName.PullUserSettingOutput]: ['items', 'version'], [PBName.SessionReq]: ['time'], [PBName.SessionStates]: ['version', 'state'], [PBName.SessionState]: ['type', 'channelId', 'time', 'stateItem'], [PBName.SessionStateItem]: ['sessionStateType', 'value'], [PBName.SessionStateModifyReq]: ['version', 'state'], [PBName.SessionStateModifyResp]: ['version'] }; const Codec = {}; for (const key in SSMsg) { const paramsList = SSMsg[key]; Codec[key] = () => { const data = {}; const ins = { getArrayData() { return data; } }; for (let i = 0; i < paramsList.length; i++) { const param = paramsList[i]; const setEventName = `set${toUpperCase(param, 0, 1)}`; ins[setEventName] = (item) => { data[param] = item; }; } return ins; }; Codec[key].decode = function (data) { const decodeResult = {}; if (isString(data)) { data = JSON.parse(data); } for (const key in data) { const getEventName = `get${toUpperCase(key, 0, 1)}`; decodeResult[key] = data[key]; decodeResult[getEventName] = () => { return data[key]; }; } return decodeResult; }; } Codec.getModule = (pbName) => { return Codec[pbName](); }; const SSMsg$1 = ` package Modules; message probuf { message ${PBName.SetUserStatusInput} { optional int32 status=1; } message SetUserStatusOutput { optional int32 nothing=1; } message GetUserStatusInput { optional int32 nothing=1; } message GetUserStatusOutput { optional string status=1; optional string subUserId=2; } message SubUserStatusInput { repeated string userid =1; } message SubUserStatusOutput { optional int32 nothing=1; } message VoipDynamicInput { required int32 engineType = 1; required string channelName = 2; optional string channelExtra = 3; } message VoipDynamicOutput { required string dynamicKey=1; } message ${PBName.NotifyMsg} { required int32 type = 1; optional int64 time = 2; optional string chrmId=3; } message ${PBName.SyncRequestMsg} { required int64 syncTime = 1; required bool ispolling = 2; optional bool isweb=3; optional bool isPullSend=4; optional bool isKeeping=5; optional int64 sendBoxSyncTime=6; } message ${PBName.UpStreamMessage} { required int32 sessionId = 1; required string classname = 2; required bytes content = 3; optional string pushText = 4; optional string appData = 5; repeated string userId = 6; optional int64 delMsgTime = 7; optional string delMsgId = 8; optional int32 configFlag = 9; optional int64 clientUniqueId = 10; optional string extraContent = 11; } message ${PBName.DownStreamMessages} { repeated DownStreamMessage list = 1; required int64 syncTime = 2; optional bool finished = 3; } message ${PBName.DownStreamMessage} { required string fromUserId = 1; required ChannelType type = 2; optional string groupId = 3; required string classname = 4; required bytes content = 5; required int64 dataTime = 6; required int64 status = 7; optional int64 extra = 8; optional string msgId = 9; optional int32 direction = 10; optional int32 plantform =11; optional int32 isRemoved = 12; optional string source = 13; optional int64 clientUniqueId = 14; optional string extraContent = 15; } enum ChannelType { PERSON = 1; PERSONS = 2; GROUP = 3; TEMPGROUP = 4; CUSTOMERSERVICE = 5; NOTIFY = 6; MC=7; MP=8; } message CreateDiscussionInput { optional string name = 1; } message CreateDiscussionOutput { required string id = 1; } message ChannelInvitationInput { repeated string users = 1; } message LeaveChannelInput { required int32 nothing = 1; } message ChannelEvictionInput { required string user = 1; } message RenameChannelInput { required string name = 1; } message ChannelInfoInput { required int32 nothing = 1; } message ChannelInfoOutput { required ChannelType type = 1; required string channelId = 2; required string channelName = 3; required string adminUserId = 4; repeated string firstTenUserIds = 5; required int32 openStatus = 6; } message ChannelInfosInput { required int32 page = 1; optional int32 number = 2; } message ChannelInfosOutput { repeated ChannelInfoOutput channels = 1; required int32 total = 2; } message MemberInfo { required string userId = 1; required string userName = 2; required string userPortrait = 3; required string extension = 4; } message GroupMembersInput { required int32 page = 1; optional int32 number = 2; } message GroupMembersOutput { repeated MemberInfo members = 1; required int32 total = 2; } message GetUserInfoInput { required int32 nothing = 1; } message GetUserInfoOutput { required string userId = 1; required string userName = 2; required string userPortrait = 3; } message GetSessionIdInput { required int32 nothing = 1; } message GetSessionIdOutput { required int32 sessionId = 1; } enum FileType { image = ${FileType$1.IMAGE}; audio = ${FileType$1.AUDIO}; video = ${FileType$1.VIDEO}; file = ${FileType$1.FILE}; } message ${PBName.GetQNupTokenInput} { required FileType type = 1; optional string key = 2; } message ${PBName.GetQNdownloadUrlInput} { required FileType type = 1; required string key = 2; optional string fileName = 3; } message ${PBName.GetDownloadUrlInput} { required FileType type = 1; // 下载的文件类型 required string key = 2; // 请求下载的文件名 optional string fileName = 3; // 下载生成的文件名字 } message ${PBName.GetQNupTokenOutput} { required int64 deadline = 1; required string token = 2; optional string bosToken = 3; optional string bosDate = 4; optional string path = 5; optional string osskeyId = 6; optional string ossPolicy = 7; optional string ossSign = 8; optional string ossBucketName = 9; } message ${PBName.GetQNdownloadUrlOutput} { required string downloadUrl = 1; } message ${PBName.GetDownloadUrlOutput} { required string downloadUrl = 1; } message Add2BlackListInput { required string userId = 1; } message RemoveFromBlackListInput { required string userId = 1; } message QueryBlackListInput { required int32 nothing = 1; } message QueryBlackListOutput { repeated string userIds = 1; } message BlackListStatusInput { required string userId = 1; } message BlockPushInput { required string blockeeId = 1; } message ModifyPermissionInput { required int32 openStatus = 1; } message GroupInput { repeated GroupInfo groupInfo = 1; } message GroupOutput { required int32 nothing = 1; } message GroupInfo { required string id = 1; required string name = 2; } message GroupHashInput { required string userId = 1; required string groupHashCode = 2; } message GroupHashOutput { required GroupHashType result = 1; } enum GroupHashType { group_success = 0x00; group_failure = 0x01; } message ${PBName.ChrmInput} { required int32 nothing = 1; } message ChrmOutput { required int32 nothing = 1; } message ${PBName.ChrmPullMsg} { required int64 syncTime = 1; required int32 count = 2; } message ChrmPullMsgNew { required int32 count = 1; required int64 syncTime = 2; optional string chrmId=3; } message ${PBName.RelationQryInput} { optional ChannelType type = 1; optional int32 count = 2; optional int64 startTime = 3; optional int32 order = 4; } message ${PBName.RelationsInput} { required ChannelType type = 1; optional DownStreamMessage msg =2; optional int32 count = 3; optional int32 offset = 4; optional int64 startTime = 5; optional int64 endTime = 6; } message ${PBName.RelationsOutput} { repeated RelationInfo info = 1; } message RelationInfo { required ChannelType type = 1; required string userId = 2; optional DownStreamMessage msg =3; optional int64 readMsgTime= 4; optional int64 unreadCount= 5; } message RelationInfoReadTime { required ChannelType type = 1; required int64 readMsgTime= 2; required string targetId = 3; } message ${PBName.CleanHisMsgInput} { required string targetId = 1; required int64 dataTime = 2; optional int32 conversationType= 3; } message HistoryMessageInput { required string targetId = 1; required int64 dataTime =2; required int32 size = 3; } message HistoryMessagesOuput { repeated DownStreamMessage list = 1; required int64 syncTime = 2; required int32 hasMsg = 3; } message ${PBName.QueryChatRoomInfoInput} { required int32 count= 1; optional int32 order= 2; } message ${PBName.QueryChatRoomInfoOutput} { optional int32 userTotalNums = 1; repeated ChrmMember userInfos = 2; } message ChrmMember { required int64 time = 1; required string id = 2; } message MPFollowInput { required string id = 1; } message MPFollowOutput { required int32 nothing = 1; optional MpInfo info =2; } message ${PBName.MCFollowInput} { required string id = 1; } message MCFollowOutput { required int32 nothing = 1; optional MpInfo info =2; } message MpInfo { required string mpid=1; required string name = 2; required string type = 3; required int64 time=4; optional string portraitUrl=5; optional string extra =6; } message SearchMpInput { required int32 type=1; required string id=2; } message SearchMpOutput { required int32 nothing=1; repeated MpInfo info = 2; } message PullMpInput { required int64 time=1; required string mpid=2; } message PullMpOutput { required int32 status=1; repeated MpInfo info = 2; } message ${PBName.HistoryMsgInput} { optional string targetId = 1; optional int64 time = 2; optional int32 count = 3; optional int32 order = 4; } message ${PBName.HistoryMsgOuput} { repeated DownStreamMessage list=1; required int64 syncTime=2; required int32 hasMsg=3; } message ${PBName.RtcQueryListInput}{ optional int32 order=1; } message ${PBName.RtcKeyDeleteInput}{ repeated string key=1; } message ${PBName.RtcValueInfo}{ required string key=1; required string value=2; } message RtcUserInfo{ required string userId=1; repeated ${PBName.RtcValueInfo} userData=2; } message ${PBName.RtcUserListOutput}{ repeated RtcUserInfo list=1; optional string token=2; optional string sessionId=3; } message RtcRoomInfoOutput{ optional string roomId = 1; repeated ${PBName.RtcValueInfo} roomData = 2; optional int32 userCount = 3; repeated RtcUserInfo list=4; } message ${PBName.RtcInput}{ required int32 roomType=1; optional int32 broadcastType=2; } message RtcQryInput{ required bool isInterior=1; required targetType target=2; repeated string key=3; } message ${PBName.RtcQryOutput}{ repeated ${PBName.RtcValueInfo} outInfo=1; } message RtcDelDataInput{ repeated string key=1; required bool isInterior=2; required targetType target=3; } message ${PBName.RtcDataInput}{ required bool interior=1; required targetType target=2; repeated string key=3; optional string objectName=4; optional string content=5; } message ${PBName.RtcSetDataInput}{ required bool interior=1; required targetType target=2; required string key=3; required string value=4; optional string objectName=5; optional string content=6; } message ${PBName.RtcUserSetDataInput} { repeated ${PBName.RtcValueInfo} valueInfo = 1; required string objectName = 2; repeated ${PBName.RtcValueInfo} content = 3; } message RtcOutput { optional int32 nothing=1; } message ${PBName.RtcTokenOutput}{ required string rtcToken=1; } enum targetType { ROOM =1 ; PERSON = 2; } message ${PBName.RtcSetOutDataInput}{ required targetType target=1; repeated ${PBName.RtcValueInfo} valueInfo=2; optional string objectName=3; optional string content=4; } message ${PBName.RtcQryUserOutDataInput}{ repeated string userId = 1; } message ${PBName.RtcUserOutDataOutput}{ repeated RtcUserInfo user = 1; } message ${PBName.SessionsAttQryInput}{ required int32 nothing = 1; } message ${PBName.SessionsAttOutput}{ required int64 inboxTime = 1; required int64 sendboxTime = 2; required int64 totalUnreadCount = 3; } message ${PBName.SessionMsgReadInput} { required ChannelType type = 1; required int64 msgTime = 2; required string channelId = 3; } message SessionMsgReadOutput { optional int32 nothing=1; } message ${PBName.DeleteSessionsInput} { repeated SessionInfo sessions = 1; } message ${PBName.SessionInfo} { required ChannelType type = 1; required string channelId = 2; } message ${PBName.DeleteSessionsOutput} { optional int32 nothing=1; } message ${PBName.DeleteMsgInput} { optional ChannelType type = 1; optional string conversationId = 2; repeated DeleteMsg msgs = 3; } message DeleteMsg { optional string msgId = 1; optional int64 msgDataTime = 2; optional int32 direct = 3; } message ChrmKVEntity { required string key = 1; required string value = 2; optional int32 status = 3; optional int64 timestamp = 4; optional string uid = 5; } message ${PBName.SetChrmKV} { required ChrmKVEntity entry = 1; optional bool bNotify = 2; optional UpStreamMessage notification = 3; optional ChannelType type = 4; } message ${PBName.ChrmKVOutput} { repeated ChrmKVEntity entries = 1; optional bool bFullUpdate = 2; optional int64 syncTime = 3; } message ${PBName.QueryChrmKV} { required int64 timestamp = 1; } message ${PBName.SetUserSettingInput} { required int64 version=1; required string value=2; } message ${PBName.SetUserSettingOutput} { required int64 version=1; required bool reserve=2; } message ${PBName.PullUserSettingInput} { required int64 version=1;//当前客户端的最大版本号 optional bool reserve=2; } message ${PBName.PullUserSettingOutput} { repeated UserSettingItem items = 1; required int64 version=2; } message UserSettingItem { required string targetId= 1; required ChannelType type = 2; required string key = 4; required bytes value = 5; required int64 version=6; required int32 status=7; } message ${PBName.SessionReq} { required int64 time = 1; } message ${PBName.SessionStates} { required int64 version=1; repeated SessionState state= 2; } message ${PBName.SessionState} { required ChannelType type = 1; required string channelId = 2; optional int64 time = 3; repeated SessionStateItem stateItem = 4; } message ${PBName.SessionStateItem} { required SessionStateType sessionStateType = 1; required string value = 2; } enum SessionStateType { IsSilent = 1; IsTop = 2; } message ${PBName.SessionStateModifyReq} { required int64 version=1; repeated SessionState state= 2; } message ${PBName.SessionStateModifyResp} { required int64 version=1; } } `; function protobuf (a) { var c = (function () { function a (a, b, c) { this.low = 0 | a, this.high = 0 | b, this.unsigned = !!c; } function b (a) { return (a && a.__isLong__) === !0 } function e (a, b) { var e, f, h; return b ? (a >>>= 0, (h = a >= 0 && a < 256) && (f = d[a]) ? f : (e = g(a, (0 | a) < 0 ? -1 : 0, !0), h && (d[a] = e), e)) : (a |= 0, (h = a >= -128 && a < 128) && (f = c[a]) ? f : (e = g(a, a < 0 ? -1 : 0, !1), h && (c[a] = e), e)) } function f (a, b) { if (isNaN(a) || !isFinite(a)) return b ? r : q; if (b) { if (a < 0) return r; if (a >= n) return w } else { if (-o >= a) return x; if (a + 1 >= o) return v } return a < 0 ? f(-a, b).neg() : g(0 | a % m, 0 | a / m, b) } function g (b, c, d) { return new a(b, c, d) } function i (a, b, c) { var d, e, g, j, k, l, m; if (a.length === 0) throw Error('empty string'); if (a === 'NaN' || a === 'Infinity' || a === '+Infinity' || a === '-Infinity') return q; if (typeof b === 'number' ? (c = b, b = !1) : b = !!b, c = c || 10, c < 2 || c > 36) throw RangeError('radix'); if ((d = a.indexOf('-')) > 0) throw Error('interior hyphen'); if (d === 0) return i(a.substring(1), b, c).neg(); for (e = f(h(c, 8)), g = q, j = 0; j < a.length; j += 8)k = Math.min(8, a.length - j), l = parseInt(a.substring(j, j + k), c), k < 8 ? (m = f(h(c, k)), g = g.mul(m).add(f(l))) : (g = g.mul(e), g = g.add(f(l))); return g.unsigned = b, g } function j (b) { return b instanceof a ? b : typeof b === 'number' ? f(b) : typeof b === 'string' ? i(b) : g(b.low, b.high, b.unsigned) } var c, d, h, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y; return a.prototype.__isLong__, Object.defineProperty(a.prototype, '__isLong__', { value: !0, enumerable: !1, configurable: !1 }), a.isLong = b, c = {}, d = {}, a.fromInt = e, a.fromNumber = f, a.fromBits = g, h = Math.pow, a.fromString = i, a.fromValue = j, k = 65536, l = 1 << 24, m = k * k, n = m * m, o = n / 2, p = e(l), q = e(0), a.ZERO = q, r = e(0, !0), a.UZERO = r, s = e(1), a.ONE = s, t = e(1, !0), a.UONE = t, u = e(-1), a.NEG_ONE = u, v = g(-1, 2147483647, !1), a.MAX_VALUE = v, w = g(-1, -1, !0), a.MAX_UNSIGNED_VALUE = w, x = g(0, -2147483648, !1), a.MIN_VALUE = x, y = a.prototype, y.toInt = function () { return this.unsigned ? this.low >>> 0 : this.low }, y.toNumber = function () { return this.unsigned ? (this.high >>> 0) * m + (this.low >>> 0) : this.high * m + (this.low >>> 0) }, y.toString = function (a) { var b, c, d, e, g, i, j, k, l; if (a = a || 10, a < 2 || a > 36) throw RangeError('radix'); if (this.isZero()) return '0'; if (this.isNegative()) return this.eq(x) ? (b = f(a), c = this.div(b), d = c.mul(b).sub(this), c.toString(a) + d.toInt().toString(a)) : '-' + this.neg().toString(a); for (e = f(h(a, 6), this.unsigned), g = this, i = ''; ;) { if (j = g.div(e), k = g.sub(j.mul(e)).toInt() >>> 0, l = k.toString(a), g = j, g.isZero()) return l + i; for (;l.length < 6;)l = '0' + l; i = '' + l + i; } }, y.getHighBits = function () { return this.high }, y.getHighBitsUnsigned = function () { return this.high >>> 0 }, y.getLowBits = function () { return this.low }, y.getLowBitsUnsigned = function () { return this.low >>> 0 }, y.getNumBitsAbs = function () { var a, b; if (this.isNegative()) return this.eq(x) ? 64 : this.neg().getNumBitsAbs(); for (a = this.high != 0 ? this.high : this.low, b = 31; b > 0 && (a & 1 << b) == 0; b--);return this.high != 0 ? b + 33 : b + 1 }, y.isZero = function () { return this.high === 0 && this.low === 0 }, y.isNegative = function () { return !this.unsigned && this.high < 0 }, y.isPositive = function () { return this.unsigned || this.high >= 0 }, y.isOdd = function () { return (1 & this.low) === 1 }, y.isEven = function () { return (1 & this.low) === 0 }, y.equals = function (a) { return b(a) || (a = j(a)), this.unsigned !== a.unsigned && this.high >>> 31 === 1 && a.high >>> 31 === 1 ? !1 : this.high === a.high && this.low === a.low }, y.eq = y.equals, y.notEquals = function (a) { return !this.eq(a) }, y.neq = y.notEquals, y.lessThan = function (a) { return this.comp(a) < 0 }, y.lt = y.lessThan, y.lessThanOrEqual = function (a) { return this.comp(a) <= 0 }, y.lte = y.lessThanOrEqual, y.greaterThan = function (a) { return this.comp(a) > 0 }, y.gt = y.greaterThan, y.greaterThanOrEqual = function (a) { return this.comp(a) >= 0 }, y.gte = y.greaterThanOrEqual, y.compare = function (a) { if (b(a) || (a = j(a)), this.eq(a)) return 0; var c = this.isNegative(); var d = a.isNegative(); return c && !d ? -1 : !c && d ? 1 : this.unsigned ? a.high >>> 0 > this.high >>> 0 || a.high === this.high && a.low >>> 0 > this.low >>> 0 ? -1 : 1 : this.sub(a).isNegative() ? -1 : 1 }, y.comp = y.compare, y.negate = function () { return !this.unsigned && this.eq(x) ? x : this.not().add(s) }, y.neg = y.negate, y.add = function (a) { var c, d, e, f, h, i, k, l, m, n, o, p; return b(a) || (a = j(a)), c = this.high >>> 16, d = 65535 & this.high, e = this.low >>> 16, f = 65535 & this.low, h = a.high >>> 16, i = 65535 & a.high, k = a.low >>> 16, l = 65535 & a.low, m = 0, n = 0, o = 0, p = 0, p += f + l, o += p >>> 16, p &= 65535, o += e + k, n += o >>> 16, o &= 65535, n += d + i, m += n >>> 16, n &= 65535, m += c + h, m &= 65535, g(o << 16 | p, m << 16 | n, this.unsigned) }, y.subtract = function (a) { return b(a) || (a = j(a)), this.add(a.neg()) }, y.sub = y.subtract, y.multiply = function (a) { var c, d, e, h, i, k, l, m, n, o, r, s; return this.isZero() ? q : (b(a) || (a = j(a)), a.isZero() ? q : this.eq(x) ? a.isOdd() ? x : q : a.eq(x) ? this.isOdd() ? x : q : this.isNegative() ? a.isNegative() ? this.neg().mul(a.neg()) : this.neg().mul(a).neg() : a.isNegative() ? this.mul(a.neg()).neg() : this.lt(p) && a.lt(p) ? f(this.toNumber() * a.toNumber(), this.unsigned) : (c = this.high >>> 16, d = 65535 & this.high, e = this.low >>> 16, h = 65535 & this.low, i = a.high >>> 16, k = 65535 & a.high, l = a.low >>> 16, m = 65535 & a.low, n = 0, o = 0, r = 0, s = 0, s += h * m, r += s >>> 16, s &= 65535, r += e * m, o += r >>> 16, r &= 65535, r += h * l, o += r >>> 16, r &= 65535, o += d * m, n += o >>> 16, o &= 65535, o += e * l, n += o >>> 16, o &= 65535, o += h * k, n += o >>> 16, o &= 65535, n += c * m + d * l + e * k + h * i, n &= 65535, g(r << 16 | s, n << 16 | o, this.unsigned))) }, y.mul = y.multiply, y.divide = function (a) { var c, d, e, g, i, k, l, m; if (b(a) || (a = j(a)), a.isZero()) throw Error('division by zero'); if (this.isZero()) return this.unsigned ? r : q; if (this.unsigned) { if (a.unsigned || (a = a.toUnsigned()), a.gt(this)) return r; if (a.gt(this.shru(1))) return t; e = r; } else { if (this.eq(x)) return a.eq(s) || a.eq(u) ? x : a.eq(x) ? s : (g = this.shr(1), c = g.div(a).shl(1), c.eq(q) ? a.isNegative() ? s : u : (d = this.sub(a.mul(c)), e = c.add(d.div(a)))); if (a.eq(x)) return this.unsigned ? r : q; if (this.isNegative()) return a.isNegative() ? this.neg().div(a.neg()) : this.neg().div(a).neg(); if (a.isNegative()) return this.div(a.neg()).neg(); e = q; } for (d = this; d.gte(a);) { for (c = Math.max(1, Math.floor(d.toNumber() / a.toNumber())), i = Math.ceil(Math.log(c) / Math.LN2), k = i <= 48 ? 1 : h(2, i - 48), l = f(c), m = l.mul(a); m.isNegative() || m.gt(d);)c -= k, l = f(c, this.unsigned), m = l.mul(a); l.isZero() && (l = s), e = e.add(l), d = d.sub(m); } return e }, y.div = y.divide, y.modulo = function (a) { return b(a) || (a = j(a)), this.sub(this.div(a).mul(a)) }, y.mod = y.modulo, y.not = function () { return g(~this.low, ~this.high, this.unsigned) }, y.and = function (a) { return b(a) || (a = j(a)), g(this.low & a.low, this.high & a.high, this.unsigned) }, y.or = function (a) { return b(a) || (a = j(a)), g(this.low | a.low, this.high | a.high, this.unsigned) }, y.xor = function (a) { return b(a) || (a = j(a)), g(this.low ^ a.low, this.high ^ a.high, this.unsigned) }, y.shiftLeft = function (a) { return b(a) && (a = a.toInt()), (a &= 63) === 0 ? this : a < 32 ? g(this.low << a, this.high << a | this.low >>> 32 - a, this.unsigned) : g(0, this.low << a - 32, this.unsigned) }, y.shl = y.shiftLeft, y.shiftRight = function (a) { return b(a) && (a = a.toInt()), (a &= 63) === 0 ? this : a < 32 ? g(this.low >>> a | this.high << 32 - a, this.high >> a, this.unsigned) : g(this.high >> a - 32, this.high >= 0 ? 0 : -1, this.unsigned) }, y.shr = y.shiftRight, y.shiftRightUnsigned = function (a) { var c, d; return b(a) && (a = a.toInt()), a &= 63, a === 0 ? this : (c = this.high, a < 32 ? (d = this.low, g(d >>> a | c << 32 - a, c >>> a, this.unsigned)) : a === 32 ? g(c, 0, this.unsigned) : g(c >>> a - 32, 0, this.unsigned)) }, y.shru = y.shiftRightUnsigned, y.toSigned = function () { return this.unsigned ? g(this.low, this.high, !1) : this }, y.toUnsigned = function () { return this.unsigned ? this : g(this.low, this.high, !0) }, y.toBytes = function (a) { return a ? this.toBytesLE() : this.toBytesBE() }, y.toBytesLE = function () { var a = this.high; var b = this.low; return [255 & b, 255 & b >>> 8, 255 & b >>> 16, 255 & b >>> 24, 255 & a, 255 & a >>> 8, 255 & a >>> 16, 255 & a >>> 24] }, y.toBytesBE = function () { var a = this.high; var b = this.low; return [255 & a >>> 24, 255 & a >>> 16, 255 & a >>> 8, 255 & a, 255 & b >>> 24, 255 & b >>> 16, 255 & b >>> 8, 255 & b] }, a }()); var d = (function (a) { function f (a) { var b = 0; return function () { return b < a.length ? a.charCodeAt(b++) : null } } function g () { var a = []; var b = []; return function () { return arguments.length === 0 ? b.join('') + e.apply(String, a) : (a.length + arguments.length > 1024 && (b.push(e.apply(String, a)), a.length = 0), Array.prototype.push.apply(a, arguments), void 0) } } function h (a, b, c, d, e) { var f; var g; var h = 8 * e - d - 1; var i = (1 << h) - 1; var j = i >> 1; var k = -7; var l = c ? e - 1 : 0; var m = c ? -1 : 1; var n = a[b + l]; for (l += m, f = n & (1 << -k) - 1, n >>= -k, k += h; k > 0; f = 256 * f + a[b + l], l += m, k -= 8);for (g = f & (1 << -k) - 1, f >>= -k, k += d; k > 0; g = 256 * g + a[b + l], l += m, k -= 8);if (f === 0)f = 1 - j; else { if (f === i) return g ? 0 / 0 : 1 / 0 * (n ? -1 : 1); g += Math.pow(2, d), f -= j; } return (n ? -1 : 1) * g * Math.pow(2, f - d) } function i (a, b, c, d, e, f) { var g; var h; var i; var j = 8 * f - e - 1; var k = (1 << j) - 1; var l = k >> 1; var m = e === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0; var n = d ? 0 : f - 1; var o = d ? 1 : -1; var p = b < 0 || b === 0 && 1 / b < 0 ? 1 : 0; for (b = Math.abs(b), isNaN(b) || 1 / 0 === b ? (h = isNaN(b) ? 1 : 0, g = k) : (g = Math.floor(Math.log(b) / Math.LN2), b * (i = Math.pow(2, -g)) < 1 && (g--, i *= 2), b += g + l >= 1 ? m / i : m * Math.pow(2, 1 - l), b * i >= 2 && (g++, i /= 2), g + l >= k ? (h = 0, g = k) : g + l >= 1 ? (h = (b * i - 1) * Math.pow(2, e), g += l) : (h = b * Math.pow(2, l - 1) * Math.pow(2, e), g = 0)); e >= 8; a[c + n] = 255 & h, n += o, h /= 256, e -= 8);for (g = g << e | h, j += e; j > 0; a[c + n] = 255 & g, n += o, g /= 256, j -= 8);a[c + n - o] |= 128 * p; } var c; var d; var e; var j; var k; var b = function (a, c, e) { if (typeof a === 'undefined' && (a = b.DEFAULT_CAPACITY), typeof c === 'undefined' && (c = b.DEFAULT_ENDIAN), typeof e === 'undefined' && (e = b.DEFAULT_NOASSERT), !e) { if (a = 0 | a, a < 0) throw RangeError('Illegal capacity'); c = !!c, e = !!e; } this.buffer = a === 0 ? d : new ArrayBuffer(a), this.view = a === 0 ? null : new Uint8Array(this.buffer), this.offset = 0, this.markedOffset = -1, this.limit = a, this.littleEndian = c, this.noAssert = e; }; return b.VERSION = '5.0.1', b.LITTLE_ENDIAN = !0, b.BIG_ENDIAN = !1, b.DEFAULT_CAPACITY = 16, b.DEFAULT_ENDIAN = b.BIG_ENDIAN, b.DEFAULT_NOASSERT = !1, b.Long = a || null, c = b.prototype, c.__isByteBuffer__, Object.defineProperty(c, '__isByteBuffer__', { value: !0, enumerable: !1, configurable: !1 }), d = new ArrayBuffer(0), e = String.fromCharCode, b.accessor = function () { return Uint8Array }, b.allocate = function (a, c, d) { return new b(a, c, d) }, b.concat = function (a, c, d, e) { var f, i, g, h, k, j; for ((typeof c === 'boolean' || typeof c !== 'string') && (e = d, d = c, c = void 0), f = 0, g = 0, h = a.length; h > g; ++g)b.isByteBuffer(a[g]) || (a[g] = b.wrap(a[g], c)), i = a[g].limit - a[g].offset, i > 0 && (f += i); if (f === 0) return new b(0, d, e); for (j = new b(f, d, e), g = 0; h > g;)k = a[g++], i = k.limit - k.offset, i <= 0 || (j.view.set(k.view.subarray(k.offset, k.limit), j.offset), j.offset += i); return j.limit = j.offset, j.offset = 0, j }, b.isByteBuffer = function (a) { return (a && a.__isByteBuffer__) === !0 }, b.type = function () { return ArrayBuffer }, b.wrap = function (a, d, e, f) { var g, h; if (typeof d !== 'string' && (f = e, e = d, d = void 0), typeof a === 'string') switch (typeof d === 'undefined' && (d = 'utf8'), d) { case 'base64':return b.fromBase64(a, e); case 'hex':return b.fromHex(a, e); case 'binary':return b.fromBinary(a, e); case 'utf8':return b.fromUTF8(a, e); case 'debug':return b.fromDebug(a, e); default:throw Error('Unsupported encoding: ' + d) } if (a === null || typeof a !== 'object') throw TypeError('Illegal buffer'); if (b.isByteBuffer(a)) return g = c.clone.call(a), g.markedOffset = -1, g; if (a instanceof Uint8Array)g = new b(0, e, f), a.length > 0 && (g.buffer = a.buffer, g.offset = a.byteOffset, g.limit = a.byteOffset + a.byteLength, g.view = new Uint8Array(a.buffer)); else if (a instanceof ArrayBuffer)g = new b(0, e, f), a.byteLength > 0 && (g.buffer = a, g.offset = 0, g.limit = a.byteLength, g.view = a.byteLength > 0 ? new Uint8Array(a) : null); else { if (Object.prototype.toString.call(a) !== '[object Array]') throw TypeError('Illegal buffer'); for (g = new b(a.length, e, f), g.limit = a.length, h = 0; h < a.length; ++h)g.view[h] = a[h]; } return g }, c.writeBitSet = function (a, b) { var h; var d; var e; var f; var g; var i; var c = typeof b === 'undefined'; if (c && (b = this.offset), !this.noAssert) { if (!(a instanceof Array)) throw TypeError('Illegal BitSet: Not an array'); if (typeof b !== 'number' || b % 1 !== 0) throw TypeError('Illegal offset: ' + b + ' (not an integer)'); if (b >>>= 0, b < 0 || b + 0 > this.buffer.byteLength) throw RangeError('Illegal offset: 0 <= ' + b + ' (+' + 0 + ') <= ' + this.buffer.byteLength) } for (d = b, e = a.length, f = e >> 3, g = 0, b += this.writeVarint32(e, b); f--;)h = 1 & !!a[g++] | (1 & !!a[g++]) << 1 | (1 & !!a[g++]) << 2 | (1 & !!a[g++]) << 3 | (1 & !!a[g++]) << 4 | (1 & !!a[g++]) << 5 | (1 & !!a[g++]) << 6 | (1 & !!a[g++]) << 7, this.writeByte(h, b++); if (e > g) { for (i = 0, h = 0; e > g;)h |= (1 & !!a[g++]) << i++; this.writeByte(h, b++); } return c ? (this.offset = b, this) : b - d }, c.readBitSet = function (a) { var h; var c; var d; var e; var f; var g; var i; var b = typeof a === 'undefined'; for (b && (a = this.offset), c = this.readVarint32(a), d = c.value, e = d >> 3, f = 0, g = [], a += c.length; e--;)h = this.readByte(a++), g[f++] = !!(1 & h), g[f++] = !!(2 & h), g[f++] = !!(4 & h), g[f++] = !!(8 & h), g[f++] = !!(16 & h), g[f++] = !!(32 & h), g[f++] = !!(64 & h), g[f++] = !!(128 & h); if (d > f) for (i = 0, h = this.readByte(a++); d > f;)g[f++] = !!(1 & h >> i++); return b && (this.offset = a), g }, c.readBytes = function (a, b) { var d; var c = typeof b === 'undefined'; if (c && (b = this.offset), !this.noAssert) { if (typeof b !== 'number' || b % 1 !== 0) throw TypeError('Illegal offset: ' + b + ' (not an integer)'); if (b >>>= 0, b < 0 || b + a > this.buffer.byteLength) throw RangeError('Illegal offset: 0 <= ' + b + ' (+' + a + ') <= ' + this.buffer.byteLength) } return d = this.slice(b, b + a), c && (this.offset += a), d }, c.writeBytes = c.append, c.writeInt8 = function (a, b) { var d; var c = typeof b === 'undefined'; if (c && (b = this.offset), !this.noAssert) { if (typeof a !== 'number' || a % 1 !== 0) throw TypeError('Illegal value: ' + a + ' (not an integer)'); if (a |= 0, typeof b !== 'number' || b % 1 !== 0) throw TypeError('Illegal offset: ' + b + ' (not an integer)'); if (b >>>= 0, b < 0 || b + 0 > this.buffer.byteLength) throw RangeError('Illegal offset: 0 <= ' + b + ' (+' + 0 + ') <= ' + this.buffer.byteLength) } return b += 1, d = this.buffer.byteLength, b > d && this.resize((d *= 2) > b ? d : b), b -= 1, this.view[b] = a, c && (this.offset += 1), this }, c.writeByte = c.writeInt8, c.readInt8 = function (a) { var c; var b = typeof a === 'undefined'; if (b && (a = this.offset), !this.noAssert) { if (typeof a !== 'number' || a % 1 !== 0) throw TypeError('Illegal offset: ' + a + ' (not an integer)'); if (a >>>= 0, a < 0 || a + 1 > this.buffer.byteLength) throw RangeError('Illegal offset: 0 <= ' + a + ' (+' + 1 + ') <= ' + this.buffer.byteLength) } return c = this.view[a], (128 & c) === 128 && (c = -(255 - c + 1)), b && (this.offset += 1), c }, c.readByte = c.readInt8, c.writeUint8 = function (a, b) { var d; var c = typeof b === 'undefined'; if (c && (b = this.offset), !this.noAssert) { if (typeof a !== 'number' || a % 1 !== 0) throw TypeError('Illegal value: ' + a + ' (not an integer)'); if (a >>>= 0, typeof b !== 'number' || b % 1 !== 0) throw TypeError('Illegal offset: ' + b + ' (not an integer)'); if (b >>>= 0, b < 0 || b + 0 > this.buffer.byteLength) throw RangeError('Illegal offset: 0 <= ' + b + ' (+' + 0 + ') <= ' + this.buffer.byteLength) } return b += 1, d = this.buffer.byteLength, b > d && this.resize((d *= 2) > b ? d : b), b -= 1, this.view[b] = a, c && (this.offset += 1), this }, c.writeUInt8 = c.writeUint8, c.readUint8 = function (a) { var c; var b = typeof a === 'undefined'; if (b && (a = this.offset), !this.noAssert) { if (typeof a !== 'number' || a % 1 !== 0) throw TypeError('Illegal offset: ' + a + ' (not an integer)'); if (a >>>= 0, a < 0 || a + 1 > this.buffer.byteLength) throw RangeError('Illegal offset: 0 <= ' + a + ' (+' + 1 + ') <= ' + this.buffer.byteLength) } return c = this.view[a], b && (this.offset += 1), c }, c.readUInt8 = c.readUint8, c.writeInt16 = function (a, b) { var d; var c = typeof b === 'undefined'; if (c && (b = this.offset), !this.noAssert) { if (typeof a !== 'number' || a % 1 !== 0) throw TypeError('Illegal value: ' + a + ' (not an integer)'); if (a |= 0, typeof b !== 'number' || b % 1 !== 0) throw TypeError('Illegal offset: ' + b + ' (not an integer)'); if (b >>>= 0, b < 0 || b + 0 > this.buffer.byteLength) throw RangeError('Illegal offset: 0 <= ' + b + ' (+' + 0 + ') <= ' + this.buffer.byteLength) } return b += 2, d = this.buffer.byteLength, b > d && this.resize((d *= 2) > b ? d : b), b -= 2, this.littleEndian ? (this.view[b + 1] = (65280 & a) >>> 8, this.view[b] = 255 & a) : (this.view[b] = (65280 & a) >>> 8, this.view[b + 1] = 255 & a), c && (this.offset += 2), this }, c.writeShort = c.writeInt16, c.readInt16 = function (a) { var c; var b = typeof a === 'undefined'; if (b && (a = this.offset), !this.noAssert) { if (typeof a !== 'number' || a % 1 !== 0) throw TypeError('Illegal offset: ' + a + ' (not an integer)'); if (a >>>= 0, a < 0 || a + 2 > this.buffer.byteLength) throw RangeError('Illegal offset: 0 <= ' + a + ' (+' + 2 + ') <= ' + this.buffer.byteLength) } return c = 0, this.littleEndian ? (c = this.view[a], c |= this.view[a + 1] << 8) : (c = this.view[a] << 8, c |= this.view[a + 1]), (32768 & c) === 32768 && (c = -(65535 - c + 1)), b && (this.offset += 2), c }, c.readShort = c.readInt16, c.writeUint16 = function (a, b) { var d; var c = typeof b === 'undefined'; if (c && (b = this.offset), !this.noAssert) { if (typeof a !== 'number' || a % 1 !== 0) throw TypeError('Illegal value: ' + a + ' (not an integer)'); if (a >>>= 0, typeof b !== 'number' || b % 1 !== 0) throw TypeError('Illegal offset: ' + b + ' (not an integer)'); if (b >>>= 0, b < 0 || b + 0 > this.buffer.byteLength) throw RangeError('Illegal offset: 0 <= ' + b + ' (+' + 0 + ') <= ' + this.buffer.byteLength) } return b += 2, d = this.buffer.byteLength, b > d && this.resize((d *= 2) > b ? d : b), b -= 2, this.littleEndian ? (this.view[b + 1] = (65280 & a) >>> 8, this.view[b] = 255 & a) : (this.view[b] = (65280 & a) >>> 8, this.view[b + 1] = 255 & a), c && (this.offset += 2), this }, c.writeUInt16 = c.writeUint16, c.readUint16 = function (a) { var c; var b = typeof a === 'undefined'; if (b && (a = this.offset), !this.noAssert) { if (typeof a !== 'number' || a % 1 !== 0) throw TypeError('Illegal offset: ' + a + ' (not an integer)'); if (a >>>= 0, a < 0 || a + 2 > this.buffer.byteLength) throw RangeError('Illegal offset: 0 <= ' + a + ' (+' + 2 + ') <= ' + this.buffer.byteLength) } return c = 0, this.littleEndian ? (c = this.view[a], c |= this.view[a + 1] << 8) : (c = this.view[a] << 8, c |= this.view[a + 1]), b && (this.offset += 2), c }, c.readUInt16 = c.readUint16, c.writeInt32 = function (a, b) { var d; var c = typeof b === 'undefined'; if (c && (b = this.offset), !this.noAssert) { if (typeof a !== 'number' || a % 1 !== 0) throw TypeError('Illegal value: ' + a + ' (not an integer)'); if (a |= 0, typeof b !== 'number' || b % 1 !== 0) throw TypeError('Illegal offset: ' + b + ' (not an integer)'); if (b >>>= 0, b < 0 || b + 0 > this.buffer.byteLength) throw RangeError('Illegal offset: 0 <= ' + b + ' (+' + 0 + ') <= ' + this.buffer.byteLength) } return b += 4, d = this.buffer.byteLength, b > d && this.resize((d *= 2) > b ? d : b), b -= 4, this.littleEndian ? (this.view[b + 3] = 255 & a >>> 24, this.view[b + 2] = 255 & a >>> 16, this.view[b + 1] = 255 & a >>> 8, this.view[b] = 255 & a) : (this.view[b] = 255 & a >>> 24, this.view[b + 1] = 255 & a >>> 16, this.view[b + 2] = 255 & a >>> 8, this.view[b + 3] = 255 & a), c && (this.offset += 4), this }, c.writeInt = c.writeInt32, c.readInt32 = function (a) { var c; var b = typeof a === 'undefined'; if (b && (a = this.offset), !this.noAssert) { if (typeof a !== 'number' || a % 1 !== 0) throw TypeError('Illegal offset: ' + a + ' (not an integer)'); if (a >>>= 0, a < 0 || a + 4 > this.buffer.byteLength) throw RangeError('Illegal offset: 0 <= ' + a + ' (+' + 4 + ') <= ' + this.buffer.byteLength) } return c = 0, this.littleEndian ? (c = this.view[a + 2] << 16, c |= this.view[a + 1] << 8, c |= this.view[a], c += this.view[a + 3] << 24 >>> 0) : (c = this.view[a + 1] << 16, c |= this.view[a + 2] << 8, c |= this.view[a + 3], c += this.view[a] << 24 >>> 0), c |= 0, b && (this.offset += 4), c }, c.readInt = c.readInt32, c.writeUint32 = function (a, b) { var d; var c = typeof b === 'undefined'; if (c && (b = this.offset), !this.noAssert) { if (typeof a !== 'number' || a % 1 !== 0) throw TypeError('Illegal value: ' + a + ' (not an integer)'); if (a >>>= 0, typeof b !== 'number' || b % 1 !== 0) throw TypeError('Illegal offset: ' + b + ' (not an integer)'); if (b >>>= 0, b < 0 || b + 0 > this.buffer.byteLength) throw RangeError('Illegal offset: 0 <= ' + b + ' (+' + 0 + ') <= ' + this.buffer.byteLength) } return b += 4, d = this.buffer.byteLength, b > d && this.resize((d *= 2) > b ? d : b), b -= 4, this.littleEndian ? (this.view[b + 3] = 255 & a >>> 24, this.view[b + 2] = 255 & a >>> 16, this.view[b + 1] = 255 & a >>> 8, this.view[b] = 255 & a) : (this.view[b] = 255 & a >>> 24, this.view[b + 1] = 255 & a >>> 16, this.view[b + 2] = 255 & a >>> 8, this.view[b + 3] = 255 & a), c && (this.offset += 4), this }, c.writeUInt32 = c.writeUint32, c.readUint32 = function (a) { var c; var b = typeof a === 'undefined'; if (b && (a = this.offset), !this.noAssert) { if (typeof a !== 'number' || a % 1 !== 0) throw TypeError('Illegal offset: ' + a + ' (not an integer)'); if (a >>>= 0, a < 0 || a + 4 > this.buffer.byteLength) throw RangeError('Illegal offset: 0 <= ' + a + ' (+' + 4 + ') <= ' + this.buffer.byteLength) } return c = 0, this.littleEndian ? (c = this.view[a + 2] << 16, c |= this.view[a + 1] << 8, c |= this.view[a], c += this.view[a + 3] << 24 >>> 0) : (c = this.view[a + 1] << 16, c |= this.view[a + 2] << 8, c |= this.view[a + 3], c += this.view[a] << 24 >>> 0), b && (this.offset += 4), c }, c.readUInt32 = c.readUint32, a && (c.writeInt64 = function (b, c) { var e; var f; var g; var d = typeof c === 'undefined'; if (d && (c = this.offset), !this.noAssert) { if (typeof b === 'number')b = a.fromNumber(b); else if (typeof b === 'string')b = a.fromString(b); else if (!(b && b instanceof a)) throw TypeError('Illegal value: ' + b + ' (not an integer or Long)'); if (typeof c !== 'number' || c % 1 !== 0) throw TypeError('Illegal offset: ' + c + ' (not an integer)'); if (c >>>= 0, c < 0 || c + 0 > this.buffer.byteLength) throw RangeError('Illegal offset: 0 <= ' + c + ' (+' + 0 + ') <= ' + this.buffer.byteLength) } return typeof b === 'number' ? b = a.fromNumber(b) : typeof b === 'string' && (b = a.fromString(b)), c += 8, e = this.buffer.byteLength, c > e && this.resize((e *= 2) > c ? e : c), c -= 8, f = b.low, g = b.high, this.littleEndian ? (this.view[c + 3] = 255 & f >>> 24, this.view[c + 2] = 255 & f >>> 16, this.view[c + 1] = 255 & f >>> 8, this.view[c] = 255 & f, c += 4, this.view[c + 3] = 255 & g >>> 24, this.view[c + 2] = 255 & g >>> 16, this.view[c + 1] = 255 & g >>> 8, this.view[c] = 255 & g) : (this.view[c] = 255 & g >>> 24, this.view[c + 1] = 255 & g >>> 16, this.view[c + 2] = 255 & g >>> 8, this.view[c + 3] = 255 & g, c += 4, this.view[c] = 255 & f >>> 24, this.view[c + 1] = 255 & f >>> 16, this.view[c + 2] = 255 & f >>> 8, this.view[c + 3] = 255 & f), d && (this.offset += 8), this }, c.writeLong = c.writeInt64, c.readInt64 = function (b) { var d; var e; var f; var c = typeof b === 'undefined'; if (c && (b = this.offset), !this.noAssert) { if (typeof b !== 'number' || b % 1 !== 0) throw TypeError('Illegal offset: ' + b + ' (not an integer)'); if (b >>>= 0, b < 0 || b + 8 > this.buffer.byteLength) throw RangeError('Illegal offset: 0 <= ' + b + ' (+' + 8 + ') <= ' + this.buffer.byteLength) } return d = 0, e = 0, this.littleEndian ? (d = this.view[b + 2] << 16, d |= this.view[b + 1] << 8, d |= this.view[b], d += this.view[b + 3] << 24 >>> 0, b += 4, e = this.view[b + 2] << 16, e |= this.view[b + 1] << 8, e |= this.view[b], e += this.view[b + 3] << 24 >>> 0) : (e = this.view[b + 1] << 16, e |= this.view[b + 2] << 8, e |= this.view[b + 3], e += this.view[b] << 24 >>> 0, b += 4, d = this.view[b + 1] << 16, d |= this.view[b + 2] << 8, d |= this.view[b + 3], d += this.view[b] << 24 >>> 0), f = new a(d, e, !1), c && (this.offset += 8), f }, c.readLong = c.readInt64, c.writeUint64 = function (b, c) { var e; var f; var g; var d = typeof c === 'undefined'; if (d && (c = this.offset), !this.noAssert) { if (typeof b === 'number')b = a.fromNumber(b); else if (typeof b === 'string')b = a.fromString(b); else if (!(b && b instanceof a)) throw TypeError('Illegal value: ' + b + ' (not an integer or Long)'); if (typeof c !== 'number' || c % 1 !== 0) throw TypeError('Illegal offset: ' + c + ' (not an integer)'); if (c >>>= 0, c < 0 || c + 0 > this.buffer.byteLength) throw RangeError('Illegal offset: 0 <= ' + c + ' (+' + 0 + ') <= ' + this.buffer.byteLength) } return typeof b === 'number' ? b = a.fromNumber(b) : typeof b === 'string' && (b = a.fromString(b)), c += 8, e = this.buffer.byteLength, c > e && this.resize((e *= 2) > c ? e : c), c -= 8, f = b.low, g = b.high, this.littleEndian ? (this.view[c + 3] = 255 & f >>> 24, this.view[c + 2] = 255 & f >>> 16, this.view[c + 1] = 255 & f >>> 8, this.view[c] = 255 & f, c += 4, this.view[c + 3] = 255 & g >>> 24, this.view[c + 2] = 255 & g >>> 16, this.view[c + 1] = 255 & g >>> 8, this.view[c] = 255 & g) : (this.view[c] = 255 & g >>> 24, this.view[c + 1] = 255 & g >>> 16, this.view[c + 2] = 255 & g >>> 8, this.view[c + 3] = 255 & g, c += 4, this.view[c] = 255 & f >>> 24, this.view[c + 1] = 255 & f >>> 16, this.view[c + 2] = 255 & f >>> 8, this.view[c + 3] = 255 & f), d && (this.offset += 8), this }, c.writeUInt64 = c.writeUint64, c.readUint64 = function (b) { var d; var e; var f; var c = typeof b === 'undefined'; if (c && (b = this.offset), !this.noAssert) { if (typeof b !== 'number' || b % 1 !== 0) throw TypeError('Illegal offset: ' + b + ' (not an integer)'); if (b >>>= 0, b < 0 || b + 8 > this.buffer.byteLength) throw RangeError('Illegal offset: 0 <= ' + b + ' (+' + 8 + ') <= ' + this.buffer.byteLength) } return d = 0, e = 0, this.littleEndian ? (d = this.view[b + 2] << 16, d |= this.view[b + 1] << 8, d |= this.view[b], d += this.view[b + 3] << 24 >>> 0, b += 4, e = this.view[b + 2] << 16, e |= this.view[b + 1] << 8, e |= this.view[b], e += this.view[b + 3] << 24 >>> 0) : (e = this.view[b + 1] << 16, e |= this.view[b + 2] << 8, e |= this.view[b + 3], e += this.view[b] << 24 >>> 0, b += 4, d = this.view[b + 1] << 16, d |= this.view[b + 2] << 8, d |= this.view[b + 3], d += this.view[b] << 24 >>> 0), f = new a(d, e, !0), c && (this.offset += 8), f }, c.readUInt64 = c.readUint64), c.writeFloat32 = function (a, b) { var d; var c = typeof b === 'undefined'; if (c && (b = this.offset), !this.noAssert) { if (typeof a !== 'number') throw TypeError('Illegal value: ' + a + ' (not a number)'); if (typeof b !== 'number' || b % 1 !== 0) throw TypeError('Illegal offset: ' + b + ' (not an integer)'); if (b >>>= 0, b < 0 || b + 0 > this.buffer.byteLength) throw RangeError('Illegal offset: 0 <= ' + b + ' (+' + 0 + ') <= ' + this.buffer.byteLength) } return b += 4, d = this.buffer.byteLength, b > d && this.resize((d *= 2) > b ? d : b), b -= 4, i(this.view, a, b, this.littleEndian, 23, 4), c && (this.offset += 4), this }, c.writeFloat = c.writeFloat32, c.readFloat32 = function (a) { var c; var b = typeof a === 'undefined'; if (b && (a = this.offset), !this.noAssert) { if (typeof a !== 'number' || a % 1 !== 0) throw TypeError('Illegal offset: ' + a + ' (not an integer)'); if (a >>>= 0, a < 0 || a + 4 > this.buffer.byteLength) throw RangeError('Illegal offset: 0 <= ' + a + ' (+' + 4 + ') <= ' + this.buffer.byteLength) } return c = h(this.view, a, this.littleEndian, 23, 4), b && (this.offset += 4), c }, c.readFloat = c.readFloat32, c.writeFloat64 = function (a, b) { var d; var c = typeof b === 'undefined'; if (c && (b = this.offset), !this.noAssert) { if (typeof a !== 'number') throw TypeError('Illegal value: ' + a + ' (not a number)'); if (typeof b !== 'number' || b % 1 !== 0) throw TypeError('Illegal offset: ' + b + ' (not an integer)'); if (b >>>= 0, b < 0 || b + 0 > this.buffer.byteLength) throw RangeError('Illegal offset: 0 <= ' + b + ' (+' + 0 + ') <= ' + this.buffer.byteLength) } return b += 8, d = this.buffer.byteLength, b > d && this.resize((d *= 2) > b ? d : b), b -= 8, i(this.view, a, b, this.littleEndian, 52, 8), c && (this.offset += 8), this }, c.writeDouble = c.writeFloat64, c.readFloat64 = function (a) { var c; var b = typeof a === 'undefined'; if (b && (a = this.offset), !this.noAssert) { if (typeof a !== 'number' || a % 1 !== 0) throw TypeError('Illegal offset: ' + a + ' (not an integer)'); if (a >>>= 0, a < 0 || a + 8 > this.buffer.byteLength) throw RangeError('Illegal offset: 0 <= ' + a + ' (+' + 8 + ') <= ' + this.buffer.byteLength) } return c = h(this.view, a, this.littleEndian, 52, 8), b && (this.offset += 8), c }, c.readDouble = c.readFloat64, b.MAX_VARINT32_BYTES = 5, b.calculateVarint32 = function (a) { return a >>>= 0, a < 128 ? 1 : a < 16384 ? 2 : 1 << 21 > a ? 3 : 1 << 28 > a ? 4 : 5 }, b.zigZagEncode32 = function (a) { return ((a |= 0) << 1 ^ a >> 31) >>> 0 }, b.zigZagDecode32 = function (a) { return 0 | a >>> 1 ^ -(1 & a) }, c.writeVarint32 = function (a, c) { var f; var e; var g; var d = typeof c === 'undefined'; if (d && (c = this.offset), !this.noAssert) { if (typeof a !== 'number' || a % 1 !== 0) throw TypeError('Illegal value: ' + a + ' (not an integer)'); if (a |= 0, typeof c !== 'number' || c % 1 !== 0) throw TypeError('Illegal offset: ' + c + ' (not an integer)'); if (c >>>= 0, c < 0 || c + 0 > this.buffer.byteLength) throw RangeError('Illegal offset: 0 <= ' + c + ' (+' + 0 + ') <= ' + this.buffer.byteLength) } for (e = b.calculateVarint32(a), c += e, g = this.buffer.byteLength, c > g && this.resize((g *= 2) > c ? g : c), c -= e, a >>>= 0; a >= 128;)f = 128 | 127 & a, this.view[c++] = f, a >>>= 7; return this.view[c++] = a, d ? (this.offset = c, this) : e }, c.writeVarint32ZigZag = function (a, c) { return this.writeVarint32(b.zigZagEncode32(a), c) }, c.readVarint32 = function (a) { var e; var c; var d; var f; var b = typeof a === 'undefined'; if (b && (a = this.offset), !this.noAssert) { if (typeof a !== 'number' || a % 1 !== 0) throw TypeError('Illegal offset: ' + a + ' (not an integer)'); if (a >>>= 0, a < 0 || a + 1 > this.buffer.byteLength) throw RangeError('Illegal offset: 0 <= ' + a + ' (+' + 1 + ') <= ' + this.buffer.byteLength) }c = 0, d = 0; do { if (!this.noAssert && a > this.limit) throw f = Error('Truncated'), f.truncated = !0, f; e = this.view[a++], c < 5 && (d |= (127 & e) << 7 * c), ++c; } while ((128 & e) !== 0); return d |= 0, b ? (this.offset = a, d) : { value: d, length: c } }, c.readVarint32ZigZag = function (a) { var c = this.readVarint32(a); return typeof c === 'object' ? c.value = b.zigZagDecode32(c.value) : c = b.zigZagDecode32(c), c }, a && (b.MAX_VARINT64_BYTES = 10, b.calculateVarint64 = function (b) { typeof b === 'number' ? b = a.fromNumber(b) : typeof b === 'string' && (b = a.fromString(b)); var c = b.toInt() >>> 0; var d = b.shiftRightUnsigned(28).toInt() >>> 0; var e = b.shiftRightUnsigned(56).toInt() >>> 0; return e == 0 ? d == 0 ? c < 16384 ? c < 128 ? 1 : 2 : 1 << 21 > c ? 3 : 4 : d < 16384 ? d < 128 ? 5 : 6 : 1 << 21 > d ? 7 : 8 : e < 128 ? 9 : 10 }, b.zigZagEncode64 = function (b) { return typeof b === 'number' ? b = a.fromNumber(b, !1) : typeof b === 'string' ? b = a.fromString(b, !1) : b.unsigned !== !1 && (b = b.toSigned()), b.shiftLeft(1).xor(b.shiftRight(63)).toUnsigned() }, b.zigZagDecode64 = function (b) { return typeof b === 'number' ? b = a.fromNumber(b, !1) : typeof b === 'string' ? b = a.fromString(b, !1) : b.unsigned !== !1 && (b = b.toSigned()), b.shiftRightUnsigned(1).xor(b.and(a.ONE).toSigned().negate()).toSigned() }, c.writeVarint64 = function (c, d) { var f; var g; var h; var i; var j; var e = typeof d === 'undefined'; if (e && (d = this.offset), !this.noAssert) { if (typeof c === 'number')c = a.fromNumber(c); else if (typeof c === 'string')c = a.fromString(c); else if (!(c && c instanceof a)) throw TypeError('Illegal value: ' + c + ' (not an integer or Long)'); if (typeof d !== 'number' || d % 1 !== 0) throw TypeError('Illegal offset: ' + d + ' (not an integer)'); if (d >>>= 0, d < 0 || d + 0 > this.buffer.byteLength) throw RangeError('Illegal offset: 0 <= ' + d + ' (+' + 0 + ') <= ' + this.buffer.byteLength) } switch (typeof c === 'number' ? c = a.fromNumber(c, !1) : typeof c === 'string' ? c = a.fromString(c, !1) : c.unsigned !== !1 && (c = c.toSigned()), f = b.calculateVarint64(c), g = c.toInt() >>> 0, h = c.shiftRightUnsigned(28).toInt() >>> 0, i = c.shiftRightUnsigned(56).toInt() >>> 0, d += f, j = this.buffer.byteLength, d > j && this.resize((j *= 2) > d ? j : d), d -= f, f) { case 10:this.view[d + 9] = 1 & i >>> 7; case 9:this.view[d + 8] = f !== 9 ? 128 | i : 127 & i; case 8:this.view[d + 7] = f !== 8 ? 128 | h >>> 21 : 127 & h >>> 21; case 7:this.view[d + 6] = f !== 7 ? 128 | h >>> 14 : 127 & h >>> 14; case 6:this.view[d + 5] = f !== 6 ? 128 | h >>> 7 : 127 & h >>> 7; case 5:this.view[d + 4] = f !== 5 ? 128 | h : 127 & h; case 4:this.view[d + 3] = f !== 4 ? 128 | g >>> 21 : 127 & g >>> 21; case 3:this.view[d + 2] = f !== 3 ? 128 | g >>> 14 : 127 & g >>> 14; case 2:this.view[d + 1] = f !== 2 ? 128 | g >>> 7 : 127 & g >>> 7; case 1:this.view[d] = f !== 1 ? 128 | g : 127 & g; } return e ? (this.offset += f, this) : f }, c.writeVarint64ZigZag = function (a, c) { return this.writeVarint64(b.zigZagEncode64(a), c) }, c.readVarint64 = function (b) { var d; var e; var f; var g; var h; var i; var c = typeof b === 'undefined'; if (c && (b = this.offset), !this.noAssert) { if (typeof b !== 'number' || b % 1 !== 0) throw TypeError('Illegal offset: ' + b + ' (not an integer)'); if (b >>>= 0, b < 0 || b + 1 > this.buffer.byteLength) throw RangeError('Illegal offset: 0 <= ' + b + ' (+' + 1 + ') <= ' + this.buffer.byteLength) } if (d = b, e = 0, f = 0, g = 0, h = 0, h = this.view[b++], e = 127 & h, 128 & h && (h = this.view[b++], e |= (127 & h) << 7, (128 & h || this.noAssert && typeof h === 'undefined') && (h = this.view[b++], e |= (127 & h) << 14, (128 & h || this.noAssert && typeof h === 'undefined') && (h = this.view[b++], e |= (127 & h) << 21, (128 & h || this.noAssert && typeof h === 'undefined') && (h = this.view[b++], f = 127 & h, (128 & h || this.noAssert && typeof h === 'undefined') && (h = this.view[b++], f |= (127 & h) << 7, (128 & h || this.noAssert && typeof h === 'undefined') && (h = this.view[b++], f |= (127 & h) << 14, (128 & h || this.noAssert && typeof h === 'undefined') && (h = this.view[b++], f |= (127 & h) << 21, (128 & h || this.noAssert && typeof h === 'undefined') && (h = this.view[b++], g = 127 & h, (128 & h || this.noAssert && typeof h === 'undefined') && (h = this.view[b++], g |= (127 & h) << 7, 128 & h || this.noAssert && typeof h === 'undefined')))))))))) throw Error('Buffer overrun'); return i = a.fromBits(e | f << 28, f >>> 4 | g << 24, !1), c ? (this.offset = b, i) : { value: i, length: b - d } }, c.readVarint64ZigZag = function (c) { var d = this.readVarint64(c); return d && d.value instanceof a ? d.value = b.zigZagDecode64(d.value) : d = b.zigZagDecode64(d), d }), c.writeCString = function (a, b) { var d; var e; var g; var c = typeof b === 'undefined'; if (c && (b = this.offset), e = a.length, !this.noAssert) { if (typeof a !== 'string') throw TypeError('Illegal str: Not a string'); for (d = 0; e > d; ++d) if (a.charCodeAt(d) === 0) throw RangeError('Illegal str: Contains NULL-characters'); if (typeof b !== 'number' || b % 1 !== 0) throw TypeError('Illegal offset: ' + b + ' (not an integer)'); if (b >>>= 0, b < 0 || b + 0 > this.buffer.byteLength) throw RangeError('Illegal offset: 0 <= ' + b + ' (+' + 0 + ') <= ' + this.buffer.byteLength) } return e = k.calculateUTF16asUTF8(f(a))[1], b += e + 1, g = this.buffer.byteLength, b > g && this.resize((g *= 2) > b ? g : b), b -= e + 1, k.encodeUTF16toUTF8(f(a), function (a) { this.view[b++] = a; }.bind(this)), this.view[b++] = 0, c ? (this.offset = b, this) : e }, c.readCString = function (a) { var c; var e; var f; var b = typeof a === 'undefined'; if (b && (a = this.offset), !this.noAssert) { if (typeof a !== 'number' || a % 1 !== 0) throw TypeError('Illegal offset: ' + a + ' (not an integer)'); if (a >>>= 0, a < 0 || a + 1 > this.buffer.byteLength) throw RangeError('Illegal offset: 0 <= ' + a + ' (+' + 1 + ') <= ' + this.buffer.byteLength) } return c = a, f = -1, k.decodeUTF8toUTF16(function () { if (f === 0) return null; if (a >= this.limit) throw RangeError('Illegal range: Truncated data, ' + a + ' < ' + this.limit); return f = this.view[a++], f === 0 ? null : f }.bind(this), e = g(), !0), b ? (this.offset = a, e()) : { string: e(), length: a - c } }, c.writeIString = function (a, b) { var e; var d; var g; var c = typeof b === 'undefined'; if (c && (b = this.offset), !this.noAssert) { if (typeof a !== 'string') throw TypeError('Illegal str: Not a string'); if (typeof b !== 'number' || b % 1 !== 0) throw TypeError('Illegal offset: ' + b + ' (not an integer)'); if (b >>>= 0, b < 0 || b + 0 > this.buffer.byteLength) throw RangeError('Illegal offset: 0 <= ' + b + ' (+' + 0 + ') <= ' + this.buffer.byteLength) } if (d = b, e = k.calculateUTF16asUTF8(f(a), this.noAssert)[1], b += 4 + e, g = this.buffer.byteLength, b > g && this.resize((g *= 2) > b ? g : b), b -= 4 + e, this.littleEndian ? (this.view[b + 3] = 255 & e >>> 24, this.view[b + 2] = 255 & e >>> 16, this.view[b + 1] = 255 & e >>> 8, this.view[b] = 255 & e) : (this.view[b] = 255 & e >>> 24, this.view[b + 1] = 255 & e >>> 16, this.view[b + 2] = 255 & e >>> 8, this.view[b + 3] = 255 & e), b += 4, k.encodeUTF16toUTF8(f(a), function (a) { this.view[b++] = a; }.bind(this)), b !== d + 4 + e) throw RangeError('Illegal range: Truncated data, ' + b + ' == ' + (b + 4 + e)); return c ? (this.offset = b, this) : b - d }, c.readIString = function (a) { var d; var e; var f; var c = typeof a === 'undefined'; if (c && (a = this.offset), !this.noAssert) { if (typeof a !== 'number' || a % 1 !== 0) throw TypeError('Illegal offset: ' + a + ' (not an integer)'); if (a >>>= 0, a < 0 || a + 4 > this.buffer.byteLength) throw RangeError('Illegal offset: 0 <= ' + a + ' (+' + 4 + ') <= ' + this.buffer.byteLength) } return d = a, e = this.readUint32(a), f = this.readUTF8String(e, b.METRICS_BYTES, a += 4), a += f.length, c ? (this.offset = a, f.string) : { string: f.string, length: a - d } }, b.METRICS_CHARS = 'c', b.METRICS_BYTES = 'b', c.writeUTF8String = function (a, b) { var d; var e; var g; var c = typeof b === 'undefined'; if (c && (b = this.offset), !this.noAssert) { if (typeof b !== 'number' || b % 1 !== 0) throw TypeError('Illegal offset: ' + b + ' (not an integer)'); if (b >>>= 0, b < 0 || b + 0 > this.buffer.byteLength) throw RangeError('Illegal offset: 0 <= ' + b + ' (+' + 0 + ') <= ' + this.buffer.byteLength) } return e = b, d = k.calculateUTF16asUTF8(f(a))[1], b += d, g = this.buffer.byteLength, b > g && this.resize((g *= 2) > b ? g : b), b -= d, k.encodeUTF16toUTF8(f(a), function (a) { this.view[b++] = a; }.bind(this)), c ? (this.offset = b, this) : b - e }, c.writeString = c.writeUTF8String, b.calculateUTF8Chars = function (a) { return k.calculateUTF16asUTF8(f(a))[0] }, b.calculateUTF8Bytes = function (a) { return k.calculateUTF16asUTF8(f(a))[1] }, b.calculateString = b.calculateUTF8Bytes, c.readUTF8String = function (a, c, d) { var e, i, f, h, j; if (typeof c === 'number' && (d = c, c = void 0), e = typeof d === 'undefined', e && (d = this.offset), typeof c === 'undefined' && (c = b.METRICS_CHARS), !this.noAssert) { if (typeof a !== 'number' || a % 1 !== 0) throw TypeError('Illegal length: ' + a + ' (not an integer)'); if (a |= 0, typeof d !== 'number' || d % 1 !== 0) throw TypeError('Illegal offset: ' + d + ' (not an integer)'); if (d >>>= 0, d < 0 || d + 0 > this.buffer.byteLength) throw RangeError('Illegal offset: 0 <= ' + d + ' (+' + 0 + ') <= ' + this.buffer.byteLength) } if (f = 0, h = d, c === b.METRICS_CHARS) { if (i = g(), k.decodeUTF8(function () { return a > f && d < this.limit ? this.view[d++] : null }.bind(this), function (a) { ++f, k.UTF8toUTF16(a, i); }), f !== a) throw RangeError('Illegal range: Truncated data, ' + f + ' == ' + a); return e ? (this.offset = d, i()) : { string: i(), length: d - h } } if (c === b.METRICS_BYTES) { if (!this.noAssert) { if (typeof d !== 'number' || d % 1 !== 0) throw TypeError('Illegal offset: ' + d + ' (not an integer)'); if (d >>>= 0, d < 0 || d + a > this.buffer.byteLength) throw RangeError('Illegal offset: 0 <= ' + d + ' (+' + a + ') <= ' + this.buffer.byteLength) } if (j = d + a, k.decodeUTF8toUTF16(function () { return j > d ? this.view[d++] : null }.bind(this), i = g(), this.noAssert), d !== j) throw RangeError('Illegal range: Truncated data, ' + d + ' == ' + j); return e ? (this.offset = d, i()) : { string: i(), length: d - h } } throw TypeError('Unsupported metrics: ' + c) }, c.readString = c.readUTF8String, c.writeVString = function (a, c) { var g; var h; var e; var i; var d = typeof c === 'undefined'; if (d && (c = this.offset), !this.noAssert) { if (typeof a !== 'string') throw TypeError('Illegal str: Not a string'); if (typeof c !== 'number' || c % 1 !== 0) throw TypeError('Illegal offset: ' + c + ' (not an integer)'); if (c >>>= 0, c < 0 || c + 0 > this.buffer.byteLength) throw RangeError('Illegal offset: 0 <= ' + c + ' (+' + 0 + ') <= ' + this.buffer.byteLength) } if (e = c, g = k.calculateUTF16asUTF8(f(a), this.noAssert)[1], h = b.calculateVarint32(g), c += h + g, i = this.buffer.byteLength, c > i && this.resize((i *= 2) > c ? i : c), c -= h + g, c += this.writeVarint32(g, c), k.encodeUTF16toUTF8(f(a), function (a) { this.view[c++] = a; }.bind(this)), c !== e + g + h) throw RangeError('Illegal range: Truncated data, ' + c + ' == ' + (c + g + h)); return d ? (this.offset = c, this) : c - e }, c.readVString = function (a) { var d; var e; var f; var c = typeof a === 'undefined'; if (c && (a = this.offset), !this.noAssert) { if (typeof a !== 'number' || a % 1 !== 0) throw TypeError('Illegal offset: ' + a + ' (not an integer)'); if (a >>>= 0, a < 0 || a + 1 > this.buffer.byteLength) throw RangeError('Illegal offset: 0 <= ' + a + ' (+' + 1 + ') <= ' + this.buffer.byteLength) } return d = a, e = this.readVarint32(a), f = this.readUTF8String(e.value, b.METRICS_BYTES, a += e.length), a += f.length, c ? (this.offset = a, f.string) : { string: f.string, length: a - d } }, c.append = function (a, c, d) { var e, f, g; if ((typeof c === 'number' || typeof c !== 'string') && (d = c, c = void 0), e = typeof d === 'undefined', e && (d = this.offset), !this.noAssert) { if (typeof d !== 'number' || d % 1 !== 0) throw TypeError('Illegal offset: ' + d + ' (not an integer)'); if (d >>>= 0, d < 0 || d + 0 > this.buffer.byteLength) throw RangeError('Illegal offset: 0 <= ' + d + ' (+' + 0 + ') <= ' + this.buffer.byteLength) } return a instanceof b || (a = b.wrap(a, c)), f = a.limit - a.offset, f <= 0 ? this : (d += f, g = this.buffer.byteLength, d > g && this.resize((g *= 2) > d ? g : d), d -= f, this.view.set(a.view.subarray(a.offset, a.limit), d), a.offset += f, e && (this.offset += f), this) }, c.appendTo = function (a, b) { return a.append(this, b), this }, c.assert = function (a) { return this.noAssert = !a, this }, c.capacity = function () { return this.buffer.byteLength }, c.clear = function () { return this.offset = 0, this.limit = this.buffer.byteLength, this.markedOffset = -1, this }, c.clone = function (a) { var c = new b(0, this.littleEndian, this.noAssert); return a ? (c.buffer = new ArrayBuffer(this.buffer.byteLength), c.view = new Uint8Array(c.buffer)) : (c.buffer = this.buffer, c.view = this.view), c.offset = this.offset, c.markedOffset = this.markedOffset, c.limit = this.limit, c }, c.compact = function (a, b) { var c, e, f; if (typeof a === 'undefined' && (a = this.offset), typeof b === 'undefined' && (b = this.limit), !this.noAssert) { if (typeof a !== 'number' || a % 1 !== 0) throw TypeError('Illegal begin: Not an integer'); if (a >>>= 0, typeof b !== 'number' || b % 1 !== 0) throw TypeError('Illegal end: Not an integer'); if (b >>>= 0, a < 0 || a > b || b > this.buffer.byteLength) throw RangeError('Illegal range: 0 <= ' + a + ' <= ' + b + ' <= ' + this.buffer.byteLength) } return a === 0 && b === this.buffer.byteLength ? this : (c = b - a, c === 0 ? (this.buffer = d, this.view = null, this.markedOffset >= 0 && (this.markedOffset -= a), this.offset = 0, this.limit = 0, this) : (e = new ArrayBuffer(c), f = new Uint8Array(e), f.set(this.view.subarray(a, b)), this.buffer = e, this.view = f, this.markedOffset >= 0 && (this.markedOffset -= a), this.offset = 0, this.limit = c, this)) }, c.copy = function (a, c) { if (typeof a === 'undefined' && (a = this.offset), typeof c === 'undefined' && (c = this.limit), !this.noAssert) { if (typeof a !== 'number' || a % 1 !== 0) throw TypeError('Illegal begin: Not an integer'); if (a >>>= 0, typeof c !== 'number' || c % 1 !== 0) throw TypeError('Illegal end: Not an integer'); if (c >>>= 0, a < 0 || a > c || c > this.buffer.byteLength) throw RangeError('Illegal range: 0 <= ' + a + ' <= ' + c + ' <= ' + this.buffer.byteLength) } if (a === c) return new b(0, this.littleEndian, this.noAssert); var d = c - a; var e = new b(d, this.littleEndian, this.noAssert); return e.offset = 0, e.limit = d, e.markedOffset >= 0 && (e.markedOffset -= a), this.copyTo(e, 0, a, c), e }, c.copyTo = function (a, c, d, e) { var f, g, h; if (!this.noAssert && !b.isByteBuffer(a)) throw TypeError('Illegal target: Not a ByteBuffer'); if (c = (g = typeof c === 'undefined') ? a.offset : 0 | c, d = (f = typeof d === 'undefined') ? this.offset : 0 | d, e = typeof e === 'undefined' ? this.limit : 0 | e, c < 0 || c > a.buffer.byteLength) throw RangeError('Illegal target range: 0 <= ' + c + ' <= ' + a.buffer.byteLength); if (d < 0 || e > this.buffer.byteLength) throw RangeError('Illegal source range: 0 <= ' + d + ' <= ' + this.buffer.byteLength); return h = e - d, h === 0 ? a : (a.ensureCapacity(c + h), a.view.set(this.view.subarray(d, e), c), f && (this.offset += h), g && (a.offset += h), this) }, c.ensureCapacity = function (a) { var b = this.buffer.byteLength; return a > b ? this.resize((b *= 2) > a ? b : a) : this }, c.fill = function (a, b, c) { var d = typeof b === 'undefined'; if (d && (b = this.offset), typeof a === 'string' && a.length > 0 && (a = a.charCodeAt(0)), typeof b === 'undefined' && (b = this.offset), typeof c === 'undefined' && (c = this.limit), !this.noAssert) { if (typeof a !== 'number' || a % 1 !== 0) throw TypeError('Illegal value: ' + a + ' (not an integer)'); if (a |= 0, typeof b !== 'number' || b % 1 !== 0) throw TypeError('Illegal begin: Not an integer'); if (b >>>= 0, typeof c !== 'number' || c % 1 !== 0) throw TypeError('Illegal end: Not an integer'); if (c >>>= 0, b < 0 || b > c || c > this.buffer.byteLength) throw RangeError('Illegal range: 0 <= ' + b + ' <= ' + c + ' <= ' + this.buffer.byteLength) } if (b >= c) return this; for (;c > b;) this.view[b++] = a; return d && (this.offset = b), this }, c.flip = function () { return this.limit = this.offset, this.offset = 0, this }, c.mark = function (a) { if (a = typeof a === 'undefined' ? this.offset : a, !this.noAssert) { if (typeof a !== 'number' || a % 1 !== 0) throw TypeError('Illegal offset: ' + a + ' (not an integer)'); if (a >>>= 0, a < 0 || a + 0 > this.buffer.byteLength) throw RangeError('Illegal offset: 0 <= ' + a + ' (+' + 0 + ') <= ' + this.buffer.byteLength) } return this.markedOffset = a, this }, c.order = function (a) { if (!this.noAssert && typeof a !== 'boolean') throw TypeError('Illegal littleEndian: Not a boolean'); return this.littleEndian = !!a, this }, c.LE = function (a) { return this.littleEndian = typeof a !== 'undefined' ? !!a : !0, this }, c.BE = function (a) { return this.littleEndian = typeof a !== 'undefined' ? !a : !1, this }, c.prepend = function (a, c, d) { var e, f, g, h, i; if ((typeof c === 'number' || typeof c !== 'string') && (d = c, c = void 0), e = typeof d === 'undefined', e && (d = this.offset), !this.noAssert) { if (typeof d !== 'number' || d % 1 !== 0) throw TypeError('Illegal offset: ' + d + ' (not an integer)'); if (d >>>= 0, d < 0 || d + 0 > this.buffer.byteLength) throw RangeError('Illegal offset: 0 <= ' + d + ' (+' + 0 + ') <= ' + this.buffer.byteLength) } return a instanceof b || (a = b.wrap(a, c)), f = a.limit - a.offset, f <= 0 ? this : (g = f - d, g > 0 ? (h = new ArrayBuffer(this.buffer.byteLength + g), i = new Uint8Array(h), i.set(this.view.subarray(d, this.buffer.byteLength), f), this.buffer = h, this.view = i, this.offset += g, this.markedOffset >= 0 && (this.markedOffset += g), this.limit += g, d += g) : new Uint8Array(this.buffer), this.view.set(a.view.subarray(a.offset, a.limit), d - f), a.offset = a.limit, e && (this.offset -= f), this) }, c.prependTo = function (a, b) { return a.prepend(this, b), this }, c.printDebug = function (a) { typeof a !== 'function' && (a = console.log.bind(console)), a(this.toString() + '\n-------------------------------------------------------------------\n' + this.toDebug(!0)); }, c.remaining = function () { return this.limit - this.offset }, c.reset = function () { return this.markedOffset >= 0 ? (this.offset = this.markedOffset, this.markedOffset = -1) : this.offset = 0, this }, c.resize = function (a) { var b, c; if (!this.noAssert) { if (typeof a !== 'number' || a % 1 !== 0) throw TypeError('Illegal capacity: ' + a + ' (not an integer)'); if (a |= 0, a < 0) throw RangeError('Illegal capacity: 0 <= ' + a) } return this.buffer.byteLength < a && (b = new ArrayBuffer(a), c = new Uint8Array(b), c.set(this.view), this.buffer = b, this.view = c), this }, c.reverse = function (a, b) { if (typeof a === 'undefined' && (a = this.offset), typeof b === 'undefined' && (b = this.limit), !this.noAssert) { if (typeof a !== 'number' || a % 1 !== 0) throw TypeError('Illegal begin: Not an integer'); if (a >>>= 0, typeof b !== 'number' || b % 1 !== 0) throw TypeError('Illegal end: Not an integer'); if (b >>>= 0, a < 0 || a > b || b > this.buffer.byteLength) throw RangeError('Illegal range: 0 <= ' + a + ' <= ' + b + ' <= ' + this.buffer.byteLength) } return a === b ? this : (Array.prototype.reverse.call(this.view.subarray(a, b)), this) }, c.skip = function (a) { if (!this.noAssert) { if (typeof a !== 'number' || a % 1 !== 0) throw TypeError('Illegal length: ' + a + ' (not an integer)'); a |= 0; } var b = this.offset + a; if (!this.noAssert && (b < 0 || b > this.buffer.byteLength)) throw RangeError('Illegal length: 0 <= ' + this.offset + ' + ' + a + ' <= ' + this.buffer.byteLength); return this.offset = b, this }, c.slice = function (a, b) { if (typeof a === 'undefined' && (a = this.offset), typeof b === 'undefined' && (b = this.limit), !this.noAssert) { if (typeof a !== 'number' || a % 1 !== 0) throw TypeError('Illegal begin: Not an integer'); if (a >>>= 0, typeof b !== 'number' || b % 1 !== 0) throw TypeError('Illegal end: Not an integer'); if (b >>>= 0, a < 0 || a > b || b > this.buffer.byteLength) throw RangeError('Illegal range: 0 <= ' + a + ' <= ' + b + ' <= ' + this.buffer.byteLength) } var c = this.clone(); return c.offset = a, c.limit = b, c }, c.toBuffer = function (a) { var e; var b = this.offset; var c = this.limit; if (!this.noAssert) { if (typeof b !== 'number' || b % 1 !== 0) throw TypeError('Illegal offset: Not an integer'); if (b >>>= 0, typeof c !== 'number' || c % 1 !== 0) throw TypeError('Illegal limit: Not an integer'); if (c >>>= 0, b < 0 || b > c || c > this.buffer.byteLength) throw RangeError('Illegal range: 0 <= ' + b + ' <= ' + c + ' <= ' + this.buffer.byteLength) } return a || b !== 0 || c !== this.buffer.byteLength ? b === c ? d : (e = new ArrayBuffer(c - b), new Uint8Array(e).set(new Uint8Array(this.buffer).subarray(b, c), 0), e) : this.buffer }, c.toArrayBuffer = c.toBuffer, c.toString = function (a, b, c) { if (typeof a === 'undefined') return 'ByteBufferAB(offset=' + this.offset + ',markedOffset=' + this.markedOffset + ',limit=' + this.limit + ',capacity=' + this.capacity() + ')'; switch (typeof a === 'number' && (a = 'utf8', b = a, c = b), a) { case 'utf8':return this.toUTF8(b, c); case 'base64':return this.toBase64(b, c); case 'hex':return this.toHex(b, c); case 'binary':return this.toBinary(b, c); case 'debug':return this.toDebug(); case 'columns':return this.toColumns(); default:throw Error('Unsupported encoding: ' + a) } }, j = (function () { var d; var e; var a = {}; var b = [65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 43, 47]; var c = []; for (d = 0, e = b.length; e > d; ++d)c[b[d]] = d; return a.encode = function (a, c) { for (var d, e; (d = a()) !== null;)c(b[63 & d >> 2]), e = (3 & d) << 4, (d = a()) !== null ? (e |= 15 & d >> 4, c(b[63 & (e | 15 & d >> 4)]), e = (15 & d) << 2, (d = a()) !== null ? (c(b[63 & (e | 3 & d >> 6)]), c(b[63 & d])) : (c(b[63 & e]), c(61))) : (c(b[63 & e]), c(61), c(61)); }, a.decode = function (a, b) { function g (a) { throw Error('Illegal character code: ' + a) } for (var d, e, f; (d = a()) !== null;) if (e = c[d], typeof e === 'undefined' && g(d), (d = a()) !== null && (f = c[d], typeof f === 'undefined' && g(d), b(e << 2 >>> 0 | (48 & f) >> 4), (d = a()) !== null)) { if (e = c[d], typeof e === 'undefined') { if (d === 61) break; g(d); } if (b((15 & f) << 4 >>> 0 | (60 & e) >> 2), (d = a()) !== null) { if (f = c[d], typeof f === 'undefined') { if (d === 61) break; g(d); }b((3 & e) << 6 >>> 0 | f); } } }, a.test = function (a) { return /^(?:[A-Za-z0-9+\/]{4})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/.test(a) }, a }()), c.toBase64 = function (a, b) { if (typeof a === 'undefined' && (a = this.offset), typeof b === 'undefined' && (b = this.limit), a = 0 | a, b = 0 | b, a < 0 || b > this.capacity || a > b) throw RangeError('begin, end'); var c; return j.encode(function () { return b > a ? this.view[a++] : null }.bind(this), c = g()), c() }, b.fromBase64 = function (a, c) { if (typeof a !== 'string') throw TypeError('str'); var d = new b(3 * (a.length / 4), c); var e = 0; return j.decode(f(a), function (a) { d.view[e++] = a; }), d.limit = e, d }, b.btoa = function (a) { return b.fromBinary(a).toBase64() }, b.atob = function (a) { return b.fromBase64(a).toBinary() }, c.toBinary = function (a, b) { if (typeof a === 'undefined' && (a = this.offset), typeof b === 'undefined' && (b = this.limit), a |= 0, b |= 0, a < 0 || b > this.capacity() || a > b) throw RangeError('begin, end'); if (a === b) return ''; for (var c = [], d = []; b > a;)c.push(this.view[a++]), c.length >= 1024 && (d.push(String.fromCharCode.apply(String, c)), c = []); return d.join('') + String.fromCharCode.apply(String, c) }, b.fromBinary = function (a, c) { if (typeof a !== 'string') throw TypeError('str'); for (var f, d = 0, e = a.length, g = new b(e, c); e > d;) { if (f = a.charCodeAt(d), f > 255) throw RangeError('illegal char code: ' + f); g.view[d++] = f; } return g.limit = e, g }, c.toDebug = function (a) { for (var d, b = -1, c = this.buffer.byteLength, e = '', f = '', g = ''; c > b;) { if (b !== -1 && (d = this.view[b], e += d < 16 ? '0' + d.toString(16).toUpperCase() : d.toString(16).toUpperCase(), a && (f += d > 32 && d < 127 ? String.fromCharCode(d) : '.')), ++b, a && b > 0 && b % 16 === 0 && b !== c) { for (;e.length < 51;)e += ' '; g += e + f + '\n', e = f = ''; }e += b === this.offset && b === this.limit ? b === this.markedOffset ? '!' : '|' : b === this.offset ? b === this.markedOffset ? '[' : '<' : b === this.limit ? b === this.markedOffset ? ']' : '>' : b === this.markedOffset ? "'" : a || b !== 0 && b !== c ? ' ' : ''; } if (a && e !== ' ') { for (;e.length < 51;)e += ' '; g += e + f + '\n'; } return a ? g : e }, b.fromDebug = function (a, c, d) { for (var i, j, e = a.length, f = new b(0 | (e + 1) / 3, c, d), g = 0, h = 0, k = !1, l = !1, m = !1, n = !1, o = !1; e > g;) { switch (i = a.charAt(g++)) { case '!':if (!d) { if (l || m || n) { o = !0; break }l = m = n = !0; }f.offset = f.markedOffset = f.limit = h, k = !1; break; case '|':if (!d) { if (l || n) { o = !0; break }l = n = !0; }f.offset = f.limit = h, k = !1; break; case '[':if (!d) { if (l || m) { o = !0; break }l = m = !0; }f.offset = f.markedOffset = h, k = !1; break; case '<':if (!d) { if (l) { o = !0; break }l = !0; }f.offset = h, k = !1; break; case ']':if (!d) { if (n || m) { o = !0; break }n = m = !0; }f.limit = f.markedOffset = h, k = !1; break; case '>':if (!d) { if (n) { o = !0; break }n = !0; }f.limit = h, k = !1; break; case "'":if (!d) { if (m) { o = !0; break }m = !0; }f.markedOffset = h, k = !1; break; case ' ':k = !1; break; default:if (!d && k) { o = !0; break } if (j = parseInt(i + a.charAt(g++), 16), !d && (isNaN(j) || j < 0 || j > 255)) throw TypeError('Illegal str: Not a debug encoded string'); f.view[h++] = j, k = !0; } if (o) throw TypeError('Illegal str: Invalid symbol at ' + g) } if (!d) { if (!l || !n) throw TypeError('Illegal str: Missing offset or limit'); if (h < f.buffer.byteLength) throw TypeError('Illegal str: Not a debug encoded string (is it hex?) ' + h + ' < ' + e) } return f }, c.toHex = function (a, b) { if (a = typeof a === 'undefined' ? this.offset : a, b = typeof b === 'undefined' ? this.limit : b, !this.noAssert) { if (typeof a !== 'number' || a % 1 !== 0) throw TypeError('Illegal begin: Not an integer'); if (a >>>= 0, typeof b !== 'number' || b % 1 !== 0) throw TypeError('Illegal end: Not an integer'); if (b >>>= 0, a < 0 || a > b || b > this.buffer.byteLength) throw RangeError('Illegal range: 0 <= ' + a + ' <= ' + b + ' <= ' + this.buffer.byteLength) } for (var d, c = new Array(b - a); b > a;)d = this.view[a++], d < 16 ? c.push('0', d.toString(16)) : c.push(d.toString(16)); return c.join('') }, b.fromHex = function (a, c, d) { var g, e, f, h, i; if (!d) { if (typeof a !== 'string') throw TypeError('Illegal str: Not a string'); if (a.length % 2 !== 0) throw TypeError('Illegal str: Length not a multiple of 2') } for (e = a.length, f = new b(0 | e / 2, c), h = 0, i = 0; e > h; h += 2) { if (g = parseInt(a.substring(h, h + 2), 16), !d && (!isFinite(g) || g < 0 || g > 255)) throw TypeError('Illegal str: Contains non-hex characters'); f.view[i++] = g; } return f.limit = i, f }, k = (function () { var a = {}; return a.MAX_CODEPOINT = 1114111, a.encodeUTF8 = function (a, b) { var c = null; for (typeof a === 'number' && (c = a, a = function () { return null }); c !== null || (c = a()) !== null;)c < 128 ? b(127 & c) : c < 2048 ? (b(192 | 31 & c >> 6), b(128 | 63 & c)) : c < 65536 ? (b(224 | 15 & c >> 12), b(128 | 63 & c >> 6), b(128 | 63 & c)) : (b(240 | 7 & c >> 18), b(128 | 63 & c >> 12), b(128 | 63 & c >> 6), b(128 | 63 & c)), c = null; }, a.decodeUTF8 = function (a, b) { for (var c, d, e, f, g = function (a) { a = a.slice(0, a.indexOf(null)); var b = Error(a.toString()); throw b.name = 'TruncatedError', b.bytes = a, b }; (c = a()) !== null;) if ((128 & c) === 0)b(c); else if ((224 & c) === 192)(d = a()) === null && g([c, d]), b((31 & c) << 6 | 63 & d); else if ((240 & c) === 224)((d = a()) === null || (e = a()) === null) && g([c, d, e]), b((15 & c) << 12 | (63 & d) << 6 | 63 & e); else { if ((248 & c) !== 240) throw RangeError('Illegal starting byte: ' + c); ((d = a()) === null || (e = a()) === null || (f = a()) === null) && g([c, d, e, f]), b((7 & c) << 18 | (63 & d) << 12 | (63 & e) << 6 | 63 & f); } }, a.UTF16toUTF8 = function (a, b) { for (var c, d = null; ;) { if ((c = d !== null ? d : a()) === null) break; c >= 55296 && c <= 57343 && (d = a()) !== null && d >= 56320 && d <= 57343 ? (b(1024 * (c - 55296) + d - 56320 + 65536), d = null) : b(c); }d !== null && b(d); }, a.UTF8toUTF16 = function (a, b) { var c = null; for (typeof a === 'number' && (c = a, a = function () { return null }); c !== null || (c = a()) !== null;)c <= 65535 ? b(c) : (c -= 65536, b((c >> 10) + 55296), b(c % 1024 + 56320)), c = null; }, a.encodeUTF16toUTF8 = function (b, c) { a.UTF16toUTF8(b, function (b) { a.encodeUTF8(b, c); }); }, a.decodeUTF8toUTF16 = function (b, c) { a.decodeUTF8(b, function (b) { a.UTF8toUTF16(b, c); }); }, a.calculateCodePoint = function (a) { return a < 128 ? 1 : a < 2048 ? 2 : a < 65536 ? 3 : 4 }, a.calculateUTF8 = function (a) { for (var b, c = 0; (b = a()) !== null;)c += b < 128 ? 1 : b < 2048 ? 2 : b < 65536 ? 3 : 4; return c }, a.calculateUTF16asUTF8 = function (b) { var c = 0; var d = 0; return a.UTF16toUTF8(b, function (a) { ++c, d += a < 128 ? 1 : a < 2048 ? 2 : a < 65536 ? 3 : 4; }), [c, d] }, a }()), c.toUTF8 = function (a, b) { if (typeof a === 'undefined' && (a = this.offset), typeof b === 'undefined' && (b = this.limit), !this.noAssert) { if (typeof a !== 'number' || a % 1 !== 0) throw TypeError('Illegal begin: Not an integer'); if (a >>>= 0, typeof b !== 'number' || b % 1 !== 0) throw TypeError('Illegal end: Not an integer'); if (b >>>= 0, a < 0 || a > b || b > this.buffer.byteLength) throw RangeError('Illegal range: 0 <= ' + a + ' <= ' + b + ' <= ' + this.buffer.byteLength) } var c; try { k.decodeUTF8toUTF16(function () { return b > a ? this.view[a++] : null }.bind(this), c = g()); } catch (d) { if (a !== b) throw RangeError('Illegal range: Truncated data, ' + a + ' != ' + b) } return c() }, b.fromUTF8 = function (a, c, d) { if (!d && typeof a !== 'string') throw TypeError('Illegal str: Not a string'); var e = new b(k.calculateUTF16asUTF8(f(a), !0)[1], c, d); var g = 0; return k.encodeUTF16toUTF8(f(a), function (a) { e.view[g++] = a; }), e.limit = g, e }, b }(c)); var e = (function (b, c) { var f; var h; var e = {}; return e.ByteBuffer = b, e.c = b, f = b, e.Long = c || null, e.VERSION = '5.0.1', e.WIRE_TYPES = {}, e.WIRE_TYPES.VARINT = 0, e.WIRE_TYPES.BITS64 = 1, e.WIRE_TYPES.LDELIM = 2, e.WIRE_TYPES.STARTGROUP = 3, e.WIRE_TYPES.ENDGROUP = 4, e.WIRE_TYPES.BITS32 = 5, e.PACKABLE_WIRE_TYPES = [e.WIRE_TYPES.VARINT, e.WIRE_TYPES.BITS64, e.WIRE_TYPES.BITS32], e.TYPES = { int32: { name: 'int32', wireType: e.WIRE_TYPES.VARINT, defaultValue: 0 }, uint32: { name: 'uint32', wireType: e.WIRE_TYPES.VARINT, defaultValue: 0 }, sint32: { name: 'sint32', wireType: e.WIRE_TYPES.VARINT, defaultValue: 0 }, int64: { name: 'int64', wireType: e.WIRE_TYPES.VARINT, defaultValue: e.Long ? e.Long.ZERO : void 0 }, uint64: { name: 'uint64', wireType: e.WIRE_TYPES.VARINT, defaultValue: e.Long ? e.Long.UZERO : void 0 }, sint64: { name: 'sint64', wireType: e.WIRE_TYPES.VARINT, defaultValue: e.Long ? e.Long.ZERO : void 0 }, bool: { name: 'bool', wireType: e.WIRE_TYPES.VARINT, defaultValue: !1 }, double: { name: 'double', wireType: e.WIRE_TYPES.BITS64, defaultValue: 0 }, string: { name: 'string', wireType: e.WIRE_TYPES.LDELIM, defaultValue: '' }, bytes: { name: 'bytes', wireType: e.WIRE_TYPES.LDELIM, defaultValue: null }, fixed32: { name: 'fixed32', wireType: e.WIRE_TYPES.BITS32, defaultValue: 0 }, sfixed32: { name: 'sfixed32', wireType: e.WIRE_TYPES.BITS32, defaultValue: 0 }, fixed64: { name: 'fixed64', wireType: e.WIRE_TYPES.BITS64, defaultValue: e.Long ? e.Long.UZERO : void 0 }, sfixed64: { name: 'sfixed64', wireType: e.WIRE_TYPES.BITS64, defaultValue: e.Long ? e.Long.ZERO : void 0 }, float: { name: 'float', wireType: e.WIRE_TYPES.BITS32, defaultValue: 0 }, enum: { name: 'enum', wireType: e.WIRE_TYPES.VARINT, defaultValue: 0 }, message: { name: 'message', wireType: e.WIRE_TYPES.LDELIM, defaultValue: null }, group: { name: 'group', wireType: e.WIRE_TYPES.STARTGROUP, defaultValue: null } }, e.MAP_KEY_TYPES = [e.TYPES.int32, e.TYPES.sint32, e.TYPES.sfixed32, e.TYPES.uint32, e.TYPES.fixed32, e.TYPES.int64, e.TYPES.sint64, e.TYPES.sfixed64, e.TYPES.uint64, e.TYPES.fixed64, e.TYPES.bool, e.TYPES.string, e.TYPES.bytes], e.ID_MIN = 1, e.ID_MAX = 536870911, e.convertFieldsToCamelCase = !1, e.populateAccessors = !0, e.populateDefaults = !0, e.Util = (function () { var a = {}; return a.IS_NODE = !(typeof process !== 'object' || process + '' != '[object process]' || process.browser), a.XHR = function () { var c; var a = [function () { return new XMLHttpRequest() }, function () { return new ActiveXObject('Msxml2.XMLHTTP') }, function () { return new ActiveXObject('Msxml3.XMLHTTP') }, function () { return new ActiveXObject('Microsoft.XMLHTTP') }]; var b = null; for (c = 0; c < a.length; c++) { try { b = a[c](); } catch (d) { continue } break } if (!b) throw Error('XMLHttpRequest is not supported'); return b }, a.fetch = function (b, c) { if (c && typeof c !== 'function' && (c = null), a.IS_NODE) if (c)g.readFile(b, function (a, b) { a ? c(null) : c('' + b); }); else try { return g.readFileSync(b) } catch (d) { return null } else { var e = a.XHR(); if (e.open('GET', b, c ? !0 : !1), e.setRequestHeader('Accept', 'text/plain'), typeof e.overrideMimeType === 'function' && e.overrideMimeType('text/plain'), !c) return e.send(null), e.status == 200 || e.status == 0 && typeof e.responseText === 'string' ? e.responseText : null; if (e.onreadystatechange = function () { e.readyState == 4 && (e.status == 200 || e.status == 0 && typeof e.responseText === 'string' ? c(e.responseText) : c(null)); }, e.readyState == 4) return; e.send(null); } }, a.toCamelCase = function (a) { return a.replace(/_([a-zA-Z])/g, function (a, b) { return b.toUpperCase() }) }, a }()), e.Lang = { DELIM: /[\s\{\}=;:\[\],'"\(\)<>]/g, RULE: /^(?:required|optional|repeated|map)$/, TYPE: /^(?:double|float|int32|uint32|sint32|int64|uint64|sint64|fixed32|sfixed32|fixed64|sfixed64|bool|string|bytes)$/, NAME: /^[a-zA-Z_][a-zA-Z_0-9]*$/, TYPEDEF: /^[a-zA-Z][a-zA-Z_0-9]*$/, TYPEREF: /^(?:\.?[a-zA-Z_][a-zA-Z_0-9]*)+$/, FQTYPEREF: /^(?:\.[a-zA-Z][a-zA-Z_0-9]*)+$/, NUMBER: /^-?(?:[1-9][0-9]*|0|0[xX][0-9a-fA-F]+|0[0-7]+|([0-9]*(\.[0-9]*)?([Ee][+-]?[0-9]+)?)|inf|nan)$/, NUMBER_DEC: /^(?:[1-9][0-9]*|0)$/, NUMBER_HEX: /^0[xX][0-9a-fA-F]+$/, NUMBER_OCT: /^0[0-7]+$/, NUMBER_FLT: /^([0-9]*(\.[0-9]*)?([Ee][+-]?[0-9]+)?|inf|nan)$/, BOOL: /^(?:true|false)$/i, ID: /^(?:[1-9][0-9]*|0|0[xX][0-9a-fA-F]+|0[0-7]+)$/, NEGID: /^\-?(?:[1-9][0-9]*|0|0[xX][0-9a-fA-F]+|0[0-7]+)$/, WHITESPACE: /\s/, STRING: /(?:"([^"\\]*(?:\\.[^"\\]*)*)")|(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g, STRING_DQ: /(?:"([^"\\]*(?:\\.[^"\\]*)*)")/g, STRING_SQ: /(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g }, e.DotProto = (function (a, b) { function h (a, c) { var d = -1; var e = 1; if (a.charAt(0) == '-' && (e = -1, a = a.substring(1)), b.NUMBER_DEC.test(a))d = parseInt(a); else if (b.NUMBER_HEX.test(a))d = parseInt(a.substring(2), 16); else { if (!b.NUMBER_OCT.test(a)) throw Error('illegal id value: ' + (e < 0 ? '-' : '') + a); d = parseInt(a.substring(1), 8); } if (d = 0 | e * d, !c && d < 0) throw Error('illegal id value: ' + (e < 0 ? '-' : '') + a); return d } function i (a) { var c = 1; if (a.charAt(0) == '-' && (c = -1, a = a.substring(1)), b.NUMBER_DEC.test(a)) return c * parseInt(a, 10); if (b.NUMBER_HEX.test(a)) return c * parseInt(a.substring(2), 16); if (b.NUMBER_OCT.test(a)) return c * parseInt(a.substring(1), 8); if (a === 'inf') return 1 / 0 * c; if (a === 'nan') return 0 / 0; if (b.NUMBER_FLT.test(a)) return c * parseFloat(a); throw Error('illegal number value: ' + (c < 0 ? '-' : '') + a) } function j (a, b, c) { typeof a[b] === 'undefined' ? a[b] = c : (Array.isArray(a[b]) || (a[b] = [a[b]]), a[b].push(c)); } var f; var g; var c = {}; var d = function (a) { this.source = a + '', this.index = 0, this.line = 1, this.stack = [], this._stringOpen = null; }; var e = d.prototype; return e._readString = function () { var c; var a = this._stringOpen === '"' ? b.STRING_DQ : b.STRING_SQ; if (a.lastIndex = this.index - 1, c = a.exec(this.source), !c) throw Error('unterminated string'); return this.index = a.lastIndex, this.stack.push(this._stringOpen), this._stringOpen = null, c[1] }, e.next = function () { var a, c, d, e, f, g; if (this.stack.length > 0) return this.stack.shift(); if (this.index >= this.source.length) return null; if (this._stringOpen !== null) return this._readString(); do { for (a = !1; b.WHITESPACE.test(d = this.source.charAt(this.index));) if (d === '\n' && ++this.line, ++this.index === this.source.length) return null; if (this.source.charAt(this.index) === '/') if (++this.index, this.source.charAt(this.index) === '/') { for (;this.source.charAt(++this.index) !== '\n';) if (this.index == this.source.length) return null; ++this.index, ++this.line, a = !0; } else { if ((d = this.source.charAt(this.index)) !== '*') return '/'; do { if (d === '\n' && ++this.line, ++this.index === this.source.length) return null; c = d, d = this.source.charAt(this.index); } while (c !== '*' || d !== '/'); ++this.index, a = !0; } } while (a); if (this.index === this.source.length) return null; if (e = this.index, b.DELIM.lastIndex = 0, f = b.DELIM.test(this.source.charAt(e++)), !f) for (;e < this.source.length && !b.DELIM.test(this.source.charAt(e));)++e; return g = this.source.substring(this.index, this.index = e), (g === '"' || g === "'") && (this._stringOpen = g), g }, e.peek = function () { if (this.stack.length === 0) { var a = this.next(); if (a === null) return null; this.stack.push(a); } return this.stack[0] }, e.skip = function (a) { var b = this.next(); if (b !== a) throw Error("illegal '" + b + "', '" + a + "' expected") }, e.omit = function (a) { return this.peek() === a ? (this.next(), !0) : !1 }, e.toString = function () { return 'Tokenizer (' + this.index + '/' + this.source.length + ' at line ' + this.line + ')' }, c.Tokenizer = d, f = function (a) { this.tn = new d(a), this.proto3 = !1; }, g = f.prototype, g.parse = function () { var c; var a = { name: '[ROOT]', package: null, messages: [], enums: [], imports: [], options: {}, services: [] }; var d = !0; try { for (;c = this.tn.next();) switch (c) { case 'package':if (!d || a.package !== null) throw Error("unexpected 'package'"); if (c = this.tn.next(), !b.TYPEREF.test(c)) throw Error('illegal package name: ' + c); this.tn.skip(';'), a.package = c; break; case 'import':if (!d) throw Error("unexpected 'import'"); c = this.tn.peek(), c === 'public' && this.tn.next(), c = this._readString(), this.tn.skip(';'), a.imports.push(c); break; case 'syntax':if (!d) throw Error("unexpected 'syntax'"); this.tn.skip('='), (a.syntax = this._readString()) === 'proto3' && (this.proto3 = !0), this.tn.skip(';'); break; case 'message':this._parseMessage(a, null), d = !1; break; case 'enum':this._parseEnum(a), d = !1; break; case 'option':this._parseOption(a); break; case 'service':this._parseService(a); break; case 'extend':this._parseExtend(a); break; default:throw Error("unexpected '" + c + "'") } } catch (e) { throw e.message = 'Parse error at line ' + this.tn.line + ': ' + e.message, e } return delete a.name, a }, f.parse = function (a) { return new f(a).parse() }, g._readString = function () { var b; var c; var a = ''; do { if (c = this.tn.next(), c !== "'" && c !== '"') throw Error('illegal string delimiter: ' + c); a += this.tn.next(), this.tn.skip(c), b = this.tn.peek(); } while (b === '"' || b === '"'); return a }, g._readValue = function (a) { var c = this.tn.peek(); if (c === '"' || c === "'") return this._readString(); if (this.tn.next(), b.NUMBER.test(c)) return i(c); if (b.BOOL.test(c)) return c.toLowerCase() === 'true'; if (a && b.TYPEREF.test(c)) return c; throw Error('illegal value: ' + c) }, g._parseOption = function (a, c) { var f; var d = this.tn.next(); var e = !1; if (d === '(' && (e = !0, d = this.tn.next()), !b.TYPEREF.test(d)) throw Error('illegal option name: ' + d); f = d, e && (this.tn.skip(')'), f = '(' + f + ')', d = this.tn.peek(), b.FQTYPEREF.test(d) && (f += d, this.tn.next())), this.tn.skip('='), this._parseOptionValue(a, f), c || this.tn.skip(';'); }, g._parseOptionValue = function (a, c) { var d = this.tn.peek(); if (d !== '{')j(a.options, c, this._readValue(!0)); else for (this.tn.skip('{'); (d = this.tn.next()) !== '}';) { if (!b.NAME.test(d)) throw Error('illegal option name: ' + c + '.' + d); this.tn.omit(':') ? j(a.options, c + '.' + d, this._readValue(!0)) : this._parseOptionValue(a, c + '.' + d); } }, g._parseService = function (a) { var d; var e; var c = this.tn.next(); if (!b.NAME.test(c)) throw Error('illegal service name at line ' + this.tn.line + ': ' + c); for (d = c, e = { name: d, rpc: {}, options: {} }, this.tn.skip('{'); (c = this.tn.next()) !== '}';) if (c === 'option') this._parseOption(e); else { if (c !== 'rpc') throw Error('illegal service token: ' + c); this._parseServiceRPC(e); } this.tn.omit(';'), a.services.push(e); }, g._parseServiceRPC = function (a) { var e; var f; var c = 'rpc'; var d = this.tn.next(); if (!b.NAME.test(d)) throw Error('illegal rpc service method name: ' + d); if (e = d, f = { request: null, response: null, request_stream: !1, response_stream: !1, options: {} }, this.tn.skip('('), d = this.tn.next(), d.toLowerCase() === 'stream' && (f.request_stream = !0, d = this.tn.next()), !b.TYPEREF.test(d)) throw Error('illegal rpc service request type: ' + d); if (f.request = d, this.tn.skip(')'), d = this.tn.next(), d.toLowerCase() !== 'returns') throw Error('illegal rpc service request type delimiter: ' + d); if (this.tn.skip('('), d = this.tn.next(), d.toLowerCase() === 'stream' && (f.response_stream = !0, d = this.tn.next()), f.response = d, this.tn.skip(')'), d = this.tn.peek(), d === '{') { for (this.tn.next(); (d = this.tn.next()) !== '}';) { if (d !== 'option') throw Error('illegal rpc service token: ' + d); this._parseOption(f); } this.tn.omit(';'); } else this.tn.skip(';'); typeof a[c] === 'undefined' && (a[c] = {}), a[c][e] = f; }, g._parseMessage = function (a, c) { var d = !!c; var e = this.tn.next(); var f = { name: '', fields: [], enums: [], messages: [], options: {}, services: [], oneofs: {} }; if (!b.NAME.test(e)) throw Error('illegal ' + (d ? 'group' : 'message') + ' name: ' + e); for (f.name = e, d && (this.tn.skip('='), c.id = h(this.tn.next()), f.isGroup = !0), e = this.tn.peek(), e === '[' && c && this._parseFieldOptions(c), this.tn.skip('{'); (e = this.tn.next()) !== '}';) if (b.RULE.test(e)) this._parseMessageField(f, e); else if (e === 'oneof') this._parseMessageOneOf(f); else if (e === 'enum') this._parseEnum(f); else if (e === 'message') this._parseMessage(f); else if (e === 'option') this._parseOption(f); else if (e === 'service') this._parseService(f); else if (e === 'extensions')f.extensions = this._parseExtensionRanges(); else if (e === 'reserved') this._parseIgnored(); else if (e === 'extend') this._parseExtend(f); else { if (!b.TYPEREF.test(e)) throw Error('illegal message token: ' + e); if (!this.proto3) throw Error('illegal field rule: ' + e); this._parseMessageField(f, 'optional', e); } return this.tn.omit(';'), a.messages.push(f), f }, g._parseIgnored = function () { for (;this.tn.peek() !== ';';) this.tn.next(); this.tn.skip(';'); }, g._parseMessageField = function (a, c, d) { var e, f, g; if (!b.RULE.test(c)) throw Error('illegal message field rule: ' + c); if (e = { rule: c, type: '', name: '', options: {}, id: 0 }, c === 'map') { if (d) throw Error('illegal type: ' + d); if (this.tn.skip('<'), f = this.tn.next(), !b.TYPE.test(f) && !b.TYPEREF.test(f)) throw Error('illegal message field type: ' + f); if (e.keytype = f, this.tn.skip(','), f = this.tn.next(), !b.TYPE.test(f) && !b.TYPEREF.test(f)) throw Error('illegal message field: ' + f); if (e.type = f, this.tn.skip('>'), f = this.tn.next(), !b.NAME.test(f)) throw Error('illegal message field name: ' + f); e.name = f, this.tn.skip('='), e.id = h(this.tn.next()), f = this.tn.peek(), f === '[' && this._parseFieldOptions(e), this.tn.skip(';'); } else if (d = typeof d !== 'undefined' ? d : this.tn.next(), d === 'group') { if (g = this._parseMessage(a, e), !/^[A-Z]/.test(g.name)) throw Error('illegal group name: ' + g.name); e.type = g.name, e.name = g.name.toLowerCase(), this.tn.omit(';'); } else { if (!b.TYPE.test(d) && !b.TYPEREF.test(d)) throw Error('illegal message field type: ' + d); if (e.type = d, f = this.tn.next(), !b.NAME.test(f)) throw Error('illegal message field name: ' + f) e.name = f, this.tn.skip('='), e.id = h(this.tn.next()), f = this.tn.peek(), f === '[' && this._parseFieldOptions(e), this.tn.skip(';'); } return a.fields.push(e), e }, g._parseMessageOneOf = function (a) { var e; var d; var f; var c = this.tn.next(); if (!b.NAME.test(c)) throw Error('illegal oneof name: ' + c); for (d = c, f = [], this.tn.skip('{'); (c = this.tn.next()) !== '}';)e = this._parseMessageField(a, 'optional', c), e.oneof = d, f.push(e.id); this.tn.omit(';'), a.oneofs[d] = f; }, g._parseFieldOptions = function (a) { this.tn.skip('['); for (var c = !0; (this.tn.peek()) !== ']';)c || this.tn.skip(','), this._parseOption(a, !0), c = !1; this.tn.next(); }, g._parseEnum = function (a) { var e; var c = { name: '', values: [], options: {} }; var d = this.tn.next(); if (!b.NAME.test(d)) throw Error('illegal name: ' + d); for (c.name = d, this.tn.skip('{'); (d = this.tn.next()) !== '}';) if (d === 'option') this._parseOption(c); else { if (!b.NAME.test(d)) throw Error('illegal name: ' + d); this.tn.skip('='), e = { name: d, id: h(this.tn.next(), !0) }, d = this.tn.peek(), d === '[' && this._parseFieldOptions({ options: {} }), this.tn.skip(';'), c.values.push(e); } this.tn.omit(';'), a.enums.push(c); }, g._parseExtensionRanges = function () { var c; var d; var e; var b = []; do { for (d = []; ;) { switch (c = this.tn.next()) { case 'min':e = a.ID_MIN; break; case 'max':e = a.ID_MAX; break; default:e = i(c); } if (d.push(e), d.length === 2) break; if (this.tn.peek() !== 'to') { d.push(e); break } this.tn.next(); }b.push(d); } while (this.tn.omit(',')); return this.tn.skip(';'), b }, g._parseExtend = function (a) { var d; var c = this.tn.next(); if (!b.TYPEREF.test(c)) throw Error('illegal extend reference: ' + c); for (d = { ref: c, fields: [] }, this.tn.skip('{'); (c = this.tn.next()) !== '}';) if (b.RULE.test(c)) this._parseMessageField(d, c); else { if (!b.TYPEREF.test(c)) throw Error('illegal extend token: ' + c); if (!this.proto3) throw Error('illegal field rule: ' + c); this._parseMessageField(d, 'optional', c); } return this.tn.omit(';'), a.messages.push(d), d }, g.toString = function () { return 'Parser at line ' + this.tn.line }, c.Parser = f, c }(e, e.Lang)), e.Reflect = (function (a) { function k (b) { if (typeof b === 'string' && (b = a.TYPES[b]), typeof b.defaultValue === 'undefined') throw Error('default value for type ' + b.name + ' is not supported'); return b == a.TYPES.bytes ? new f(0) : b.defaultValue } function l (b, c) { if (b && typeof b.low === 'number' && typeof b.high === 'number' && typeof b.unsigned === 'boolean' && b.low === b.low && b.high === b.high) return new a.Long(b.low, b.high, typeof c === 'undefined' ? b.unsigned : c); if (typeof b === 'string') return a.Long.fromString(b, c || !1, 10); if (typeof b === 'number') return a.Long.fromNumber(b, c || !1); throw Error('not convertible to Long') } function o (b, c) { var d = c.readVarint32(); var e = 7 & d; var f = d >>> 3; switch (e) { case a.WIRE_TYPES.VARINT:do d = c.readUint8(); while ((128 & d) === 128); break; case a.WIRE_TYPES.BITS64:c.offset += 8; break; case a.WIRE_TYPES.LDELIM:d = c.readVarint32(), c.offset += d; break; case a.WIRE_TYPES.STARTGROUP:o(f, c); break; case a.WIRE_TYPES.ENDGROUP:if (f === b) return !1; throw Error('Illegal GROUPEND after unknown group: ' + f + ' (' + b + ' expected)'); case a.WIRE_TYPES.BITS32:c.offset += 4; break; default:throw Error('Illegal wire type in unknown group ' + b + ': ' + e) } return !0 } var g; var h; var i; var j; var m; var n; var p; var q; var r; var s; var t; var u; var v; var w; var x; var y; var z; var A; var B; var c = {}; var d = function (a, b, c) { this.builder = a, this.parent = b, this.name = c, this.className; }; var e = d.prototype; return e.fqn = function () { for (var a = this.name, b = this; ;) { if (b = b.parent, b == null) break; a = b.name + '.' + a; } return a }, e.toString = function (a) { return (a ? this.className + ' ' : '') + this.fqn() }, e.build = function () { throw Error(this.toString(!0) + ' cannot be built directly') }, c.T = d, g = function (a, b, c, e, f) { d.call(this, a, b, c), this.className = 'Namespace', this.children = [], this.options = e || {}, this.syntax = f || 'proto2'; }, h = g.prototype = Object.create(d.prototype), h.getChildren = function (a) { var b, c, d; if (a = a || null, a == null) return this.children.slice(); for (b = [], c = 0, d = this.children.length; d > c; ++c) this.children[c] instanceof a && b.push(this.children[c]); return b }, h.addChild = function (a) { var b; if (b = this.getChild(a.name)) if (b instanceof m.Field && b.name !== b.originalName && this.getChild(b.originalName) === null)b.name = b.originalName; else { if (!(a instanceof m.Field && a.name !== a.originalName && this.getChild(a.originalName) === null)) throw Error('Duplicate name in namespace ' + this.toString(!0) + ': ' + a.name); a.name = a.originalName; } this.children.push(a); }, h.getChild = function (a) { var c; var d; var b = typeof a === 'number' ? 'id' : 'name'; for (c = 0, d = this.children.length; d > c; ++c) if (this.children[c][b] === a) return this.children[c]; return null }, h.resolve = function (a, b) { var g; var d = typeof a === 'string' ? a.split('.') : a; var e = this; var f = 0; if (d[f] === '') { for (;e.parent !== null;)e = e.parent; f++; } do { do { if (!(e instanceof c.Namespace)) { e = null; break } if (g = e.getChild(d[f]), !(g && g instanceof c.T && (!b || g instanceof c.Namespace))) { e = null; break }e = g, f++; } while (f < d.length); if (e != null) break; if (this.parent !== null) return this.parent.resolve(a, b) } while (e != null); return e }, h.qn = function (a) { var e; var f; var b = []; var d = a; do b.unshift(d.name), d = d.parent; while (d !== null); for (e = 1; e <= b.length; e++) if (f = b.slice(b.length - e), a === this.resolve(f, a instanceof c.Namespace)) return f.join('.'); return a.fqn() }, h.build = function () { var e; var c; var d; var a = {}; var b = this.children; for (c = 0, d = b.length; d > c; ++c)e = b[c], e instanceof g && (a[e.name] = e.build()); return Object.defineProperty && Object.defineProperty(a, '$options', { value: this.buildOpt() }), a }, h.buildOpt = function () { var c; var d; var e; var f; var a = {}; var b = Object.keys(this.options); for (c = 0, d = b.length; d > c; ++c)e = b[c], f = this.options[b[c]], a[e] = f; return a }, h.getOption = function (a) { return typeof a === 'undefined' ? this.options : typeof this.options[a] !== 'undefined' ? this.options[a] : null }, c.Namespace = g, i = function (b, c, d, e) { if (this.type = b, this.resolvedType = c, this.isMapKey = d, this.syntax = e, d && a.MAP_KEY_TYPES.indexOf(b) < 0) throw Error('Invalid map key type: ' + b.name) }, j = i.prototype, i.defaultFieldValue = k, j.verifyValue = function (c) { var f; var g; var h; var d = function (a, b) { throw Error('Illegal value for ' + this.toString(!0) + ' of type ' + this.type.name + ': ' + a + ' (' + b + ')') }.bind(this); switch (this.type) { case a.TYPES.int32:case a.TYPES.sint32:case a.TYPES.sfixed32:return (typeof c !== 'number' || c === c && c % 1 !== 0) && d(typeof c, 'not an integer'), c > 4294967295 ? 0 | c : c; case a.TYPES.uint32:case a.TYPES.fixed32:return (typeof c !== 'number' || c === c && c % 1 !== 0) && d(typeof c, 'not an integer'), c < 0 ? c >>> 0 : c; case a.TYPES.int64:case a.TYPES.sint64:case a.TYPES.sfixed64:if (a.Long) try { return l(c, !1) } catch (e) { d(typeof c, e.message); } else d(typeof c, 'requires Long.js'); case a.TYPES.uint64:case a.TYPES.fixed64:if (a.Long) try { return l(c, !0) } catch (e) { d(typeof c, e.message); } else d(typeof c, 'requires Long.js'); case a.TYPES.bool:return typeof c !== 'boolean' && d(typeof c, 'not a boolean'), c; case a.TYPES.float:case a.TYPES.double:return typeof c !== 'number' && d(typeof c, 'not a number'), c; case a.TYPES.string:return typeof c === 'string' || c && c instanceof String || d(typeof c, 'not a string'), '' + c; case a.TYPES.bytes:return b.isByteBuffer(c) ? c : b.wrap(c); case a.TYPES.enum:for (f = this.resolvedType.getChildren(a.Reflect.Enum.Value), h = 0; h < f.length; h++) { if (f[h].name == c) return f[h].id; if (f[h].id == c) return f[h].id } if (this.syntax === 'proto3') return (typeof c !== 'number' || c === c && c % 1 !== 0) && d(typeof c, 'not an integer'), (c > 4294967295 || c < 0) && d(typeof c, 'not in range for uint32'), c; d(c, 'not a valid enum value'); case a.TYPES.group:case a.TYPES.message:if (c && typeof c === 'object' || d(typeof c, 'object expected'), c instanceof this.resolvedType.clazz) return c; if (c instanceof a.Builder.Message) { g = {}; for (h in c)c.hasOwnProperty(h) && (g[h] = c[h]); c = g; } return new this.resolvedType.clazz(c) } throw Error('[INTERNAL] Illegal value for ' + this.toString(!0) + ': ' + c + ' (undefined type ' + this.type + ')') }, j.calculateLength = function (b, c) { if (c === null) return 0; var d; switch (this.type) { case a.TYPES.int32:return c < 0 ? f.calculateVarint64(c) : f.calculateVarint32(c); case a.TYPES.uint32:return f.calculateVarint32(c); case a.TYPES.sint32:return f.calculateVarint32(f.zigZagEncode32(c)); case a.TYPES.fixed32:case a.TYPES.sfixed32:case a.TYPES.float:return 4; case a.TYPES.int64:case a.TYPES.uint64:return f.calculateVarint64(c); case a.TYPES.sint64:return f.calculateVarint64(f.zigZagEncode64(c)); case a.TYPES.fixed64:case a.TYPES.sfixed64:return 8; case a.TYPES.bool:return 1; case a.TYPES.enum:return f.calculateVarint32(c); case a.TYPES.double:return 8; case a.TYPES.string:return d = f.calculateUTF8Bytes(c), f.calculateVarint32(d) + d; case a.TYPES.bytes:if (c.remaining() < 0) throw Error('Illegal value for ' + this.toString(!0) + ': ' + c.remaining() + ' bytes remaining'); return f.calculateVarint32(c.remaining()) + c.remaining(); case a.TYPES.message:return d = this.resolvedType.calculate(c), f.calculateVarint32(d) + d; case a.TYPES.group:return d = this.resolvedType.calculate(c), d + f.calculateVarint32(b << 3 | a.WIRE_TYPES.ENDGROUP) } throw Error('[INTERNAL] Illegal value to encode in ' + this.toString(!0) + ': ' + c + ' (unknown type)') }, j.encodeValue = function (b, c, d) { var e, g; if (c === null) return d; switch (this.type) { case a.TYPES.int32:c < 0 ? d.writeVarint64(c) : d.writeVarint32(c); break; case a.TYPES.uint32:d.writeVarint32(c); break; case a.TYPES.sint32:d.writeVarint32ZigZag(c); break; case a.TYPES.fixed32:d.writeUint32(c); break; case a.TYPES.sfixed32:d.writeInt32(c); break; case a.TYPES.int64:case a.TYPES.uint64:d.writeVarint64(c); break; case a.TYPES.sint64:d.writeVarint64ZigZag(c); break; case a.TYPES.fixed64:d.writeUint64(c); break; case a.TYPES.sfixed64:d.writeInt64(c); break; case a.TYPES.bool:typeof c === 'string' ? d.writeVarint32(c.toLowerCase() === 'false' ? 0 : !!c) : d.writeVarint32(c ? 1 : 0); break; case a.TYPES.enum:d.writeVarint32(c); break; case a.TYPES.float:d.writeFloat32(c); break; case a.TYPES.double:d.writeFloat64(c); break; case a.TYPES.string:d.writeVString(c); break; case a.TYPES.bytes:if (c.remaining() < 0) throw Error('Illegal value for ' + this.toString(!0) + ': ' + c.remaining() + ' bytes remaining'); e = c.offset, d.writeVarint32(c.remaining()), d.append(c), c.offset = e; break; case a.TYPES.message:g = (new f()).LE(), this.resolvedType.encode(c, g), d.writeVarint32(g.offset), d.append(g.flip()); break; case a.TYPES.group:this.resolvedType.encode(c, d), d.writeVarint32(b << 3 | a.WIRE_TYPES.ENDGROUP); break; default:throw Error('[INTERNAL] Illegal value to encode in ' + this.toString(!0) + ': ' + c + ' (unknown type)') } return d }, j.decode = function (b, c, d) { if (c != this.type.wireType) throw Error('Unexpected wire type for element'); var e, f; switch (this.type) { case a.TYPES.int32:return 0 | b.readVarint32(); case a.TYPES.uint32:return b.readVarint32() >>> 0; case a.TYPES.sint32:return 0 | b.readVarint32ZigZag(); case a.TYPES.fixed32:return b.readUint32() >>> 0; case a.TYPES.sfixed32:return 0 | b.readInt32(); case a.TYPES.int64:return b.readVarint64(); case a.TYPES.uint64:return b.readVarint64().toUnsigned(); case a.TYPES.sint64:return b.readVarint64ZigZag(); case a.TYPES.fixed64:return b.readUint64(); case a.TYPES.sfixed64:return b.readInt64(); case a.TYPES.bool:return !!b.readVarint32(); case a.TYPES.enum:return b.readVarint32(); case a.TYPES.float:return b.readFloat(); case a.TYPES.double:return b.readDouble(); case a.TYPES.string:return b.readVString(); case a.TYPES.bytes:if (f = b.readVarint32(), b.remaining() < f) throw Error('Illegal number of bytes for ' + this.toString(!0) + ': ' + f + ' required but got only ' + b.remaining()); return e = b.clone(), e.limit = e.offset + f, b.offset += f, e; case a.TYPES.message:return f = b.readVarint32(), this.resolvedType.decode(b, f); case a.TYPES.group:return this.resolvedType.decode(b, -1, d) } throw Error('[INTERNAL] Illegal decode type') }, j.valueFromString = function (b) { if (!this.isMapKey) throw Error('valueFromString() called on non-map-key element'); switch (this.type) { case a.TYPES.int32:case a.TYPES.sint32:case a.TYPES.sfixed32:case a.TYPES.uint32:case a.TYPES.fixed32:return this.verifyValue(parseInt(b)); case a.TYPES.int64:case a.TYPES.sint64:case a.TYPES.sfixed64:case a.TYPES.uint64:case a.TYPES.fixed64:return this.verifyValue(b); case a.TYPES.bool:return b === 'true'; case a.TYPES.string:return this.verifyValue(b); case a.TYPES.bytes:return f.fromBinary(b) } }, j.valueToString = function (b) { if (!this.isMapKey) throw Error('valueToString() called on non-map-key element'); return this.type === a.TYPES.bytes ? b.toString('binary') : b.toString() }, c.Element = i, m = function (a, b, c, d, e, f) { g.call(this, a, b, c, d, f), this.className = 'Message', this.extensions = void 0, this.clazz = null, this.isGroup = !!e, this._fields = null, this._fieldsById = null, this._fieldsByName = null; }, n = m.prototype = Object.create(g.prototype), n.build = function (c) { var d, h, e, g; if (this.clazz && !c) return this.clazz; for (d = (function (a, c) { function k (b, c, d, e) { var g, h, i, j, l, m, n; if (b === null || typeof b !== 'object') return e && e instanceof a.Reflect.Enum && (g = a.Reflect.Enum.getName(e.object, b), g !== null) ? g : b; if (f.isByteBuffer(b)) return c ? b.toBase64() : b.toBuffer(); if (a.Long.isLong(b)) return d ? b.toString() : a.Long.fromValue(b); if (Array.isArray(b)) return h = [], b.forEach(function (a, b) { h[b] = k(a, c, d, e); }), h; if (h = {}, b instanceof a.Map) { for (i = b.entries(), j = i.next(); !j.done; j = i.next())h[b.keyElem.valueToString(j.value[0])] = k(j.value[1], c, d, b.valueElem.resolvedType); return h }l = b.$type, m = void 0; for (n in b)b.hasOwnProperty(n) && (h[n] = l && (m = l.getChild(n)) ? k(b[n], c, d, m.resolvedType) : k(b[n], c, d)); return h } var i; var j; var d = c.getChildren(a.Reflect.Message.Field); var e = c.getChildren(a.Reflect.Message.OneOf); var g = function (b) { var i, j, k, l; for (a.Builder.Message.call(this), i = 0, j = e.length; j > i; ++i) this[e[i].name] = null; for (i = 0, j = d.length; j > i; ++i)k = d[i], this[k.name] = k.repeated ? [] : k.map ? new a.Map(k) : null, !k.required && c.syntax !== 'proto3' || k.defaultValue === null || (this[k.name] = k.defaultValue); if (arguments.length > 0) if (arguments.length !== 1 || b === null || typeof b !== 'object' || !(typeof b.encode !== 'function' || b instanceof g) || Array.isArray(b) || b instanceof a.Map || f.isByteBuffer(b) || b instanceof ArrayBuffer || a.Long && b instanceof a.Long) for (i = 0, j = arguments.length; j > i; ++i) typeof (l = arguments[i]) !== 'undefined' && this.$set(d[i].name, l); else this.$set(b); }; var h = g.prototype = Object.create(a.Builder.Message.prototype); for (h.add = function (b, d, e) { var f = c._fieldsByName[b]; if (!e) { if (!f) throw Error(this + '#' + b + ' is undefined'); if (!(f instanceof a.Reflect.Message.Field)) throw Error(this + '#' + b + ' is not a field: ' + f.toString(!0)); if (!f.repeated) throw Error(this + '#' + b + ' is not a repeated field'); d = f.verifyValue(d, !0); } return this[b] === null && (this[b] = []), this[b].push(d), this }, h.$add = h.add, h.set = function (b, d, e) { var f, g, h; if (b && typeof b === 'object') { e = d; for (f in b)b.hasOwnProperty(f) && typeof (d = b[f]) !== 'undefined' && this.$set(f, d, e); return this } if (g = c._fieldsByName[b], e) this[b] = d; else { if (!g) throw Error(this + '#' + b + ' is not a field: undefined'); if (!(g instanceof a.Reflect.Message.Field)) throw Error(this + '#' + b + ' is not a field: ' + g.toString(!0)); this[g.name] = d = g.verifyValue(d); } return g && g.oneof && (h = this[g.oneof.name], d !== null ? (h !== null && h !== g.name && (this[h] = null), this[g.oneof.name] = g.name) : h === b && (this[g.oneof.name] = null)), this }, h.$set = h.set, h.get = function (b, d) { if (d) return this[b]; var e = c._fieldsByName[b]; if (!(e && e instanceof a.Reflect.Message.Field)) throw Error(this + '#' + b + ' is not a field: undefined'); if (!(e instanceof a.Reflect.Message.Field)) throw Error(this + '#' + b + ' is not a field: ' + e.toString(!0)); return this[e.name] }, h.$get = h.get, i = 0; i < d.length; i++)j = d[i], j instanceof a.Reflect.Message.ExtensionField || c.builder.options.populateAccessors && (function (a) { var d; var e; var f; var b = a.originalName.replace(/(_[a-zA-Z])/g, function (a) { return a.toUpperCase().replace('_', '') }); b = b.substring(0, 1).toUpperCase() + b.substring(1), d = a.originalName.replace(/([A-Z])/g, function (a) { return '_' + a }), e = function (b, c) { return this[a.name] = c ? b : a.verifyValue(b), this }, f = function () { return this[a.name] }, c.getChild('set' + b) === null && (h['set' + b] = e), c.getChild('set_' + d) === null && (h['set_' + d] = e), c.getChild('get' + b) === null && (h['get' + b] = f), c.getChild('get_' + d) === null && (h['get_' + d] = f); }(j)); return h.encode = function (a, d) { var e, f; typeof a === 'boolean' && (d = a, a = void 0), e = !1, a || (a = new b(), e = !0), f = a.littleEndian; try { return c.encode(this, a.LE(), d), (e ? a.flip() : a).LE(f) } catch (g) { throw a.LE(f), g } }, g.encode = function (a, b, c) { return new g(a).encode(b, c) }, h.calculate = function () { return c.calculate(this) }, h.encodeDelimited = function (a) { var d; var b = !1; return a || (a = new f(), b = !0), d = (new f()).LE(), c.encode(this, d).flip(), a.writeVarint32(d.remaining()), a.append(d), b ? a.flip() : a }, h.encodeAB = function () { try { return this.encode().toArrayBuffer() } catch (a) { throw a.encoded && (a.encoded = a.encoded.toArrayBuffer()), a } }, h.toArrayBuffer = h.encodeAB, h.encodeNB = function () { try { return this.encode().toBuffer() } catch (a) { throw a.encoded && (a.encoded = a.encoded.toBuffer()), a } }, h.toBuffer = h.encodeNB, h.encode64 = function () { try { return this.encode().toBase64() } catch (a) { throw a.encoded && (a.encoded = a.encoded.toBase64()), a } }, h.toBase64 = h.encode64, h.encodeHex = function () { try { return this.encode().toHex() } catch (a) { throw a.encoded && (a.encoded = a.encoded.toHex()), a } }, h.toHex = h.encodeHex, h.toRaw = function (a, b) { return k(this, !!a, !!b, this.$type) }, h.encodeJSON = function () { return JSON.stringify(k(this, !0, !0, this.$type)) }, g.decode = function (a, b) { var d, e; typeof a === 'string' && (a = f.wrap(a, b || 'base64')), a = f.isByteBuffer(a) ? a : f.wrap(a), d = a.littleEndian; try { return e = c.decode(a.LE()), a.LE(d), e } catch (g) { throw a.LE(d), g } }, g.decodeDelimited = function (a, b) { var d, e, g; if (typeof a === 'string' && (a = f.wrap(a, b || 'base64')), a = f.isByteBuffer(a) ? a : f.wrap(a), a.remaining() < 1) return null; if (d = a.offset, e = a.readVarint32(), a.remaining() < e) return a.offset = d, null; try { return g = c.decode(a.slice(a.offset, a.offset + e).LE()), a.offset += e, g } catch (h) { throw a.offset += e, h } }, g.decode64 = function (a) { return g.decode(a, 'base64') }, g.decodeHex = function (a) { return g.decode(a, 'hex') }, g.decodeJSON = function (a) { return new g(JSON.parse(a)) }, h.toString = function () { return c.toString() }, Object.defineProperty && (Object.defineProperty(g, '$options', { value: c.buildOpt() }), Object.defineProperty(h, '$options', { value: g.$options }), Object.defineProperty(g, '$type', { value: c }), Object.defineProperty(h, '$type', { value: c })), g }(a, this)), this._fields = [], this._fieldsById = {}, this._fieldsByName = {}, e = 0, g = this.children.length; g > e; e++) if (h = this.children[e], h instanceof t || h instanceof m || h instanceof x) { if (d.hasOwnProperty(h.name)) throw Error('Illegal reflect child of ' + this.toString(!0) + ': ' + h.toString(!0) + " cannot override static property '" + h.name + "'"); d[h.name] = h.build(); } else if (h instanceof m.Field)h.build(), this._fields.push(h), this._fieldsById[h.id] = h, this._fieldsByName[h.name] = h; else if (!(h instanceof m.OneOf || h instanceof w)) throw Error('Illegal reflect child of ' + this.toString(!0) + ': ' + this.children[e].toString(!0)); return this.clazz = d }, n.encode = function (a, b, c) { var e; var h; var f; var g; var i; var d = null; for (f = 0, g = this._fields.length; g > f; ++f)e = this._fields[f], h = a[e.name], e.required && h === null ? d === null && (d = e) : e.encode(c ? h : e.verifyValue(h), b, a); if (d !== null) throw i = Error('Missing at least one required field for ' + this.toString(!0) + ': ' + d), i.encoded = b, i; return b }, n.calculate = function (a) { for (var e, f, b = 0, c = 0, d = this._fields.length; d > c; ++c) { if (e = this._fields[c], f = a[e.name], e.required && f === null) throw Error('Missing at least one required field for ' + this.toString(!0) + ': ' + e); b += e.calculate(f, a); } return b }, n.decode = function (b, c, d) { var g, h, i, j, e, f, k, l, m, n, p, q; for (c = typeof c === 'number' ? c : -1, e = b.offset, f = new this.clazz(); b.offset < e + c || c === -1 && b.remaining() > 0;) { if (g = b.readVarint32(), h = 7 & g, i = g >>> 3, h === a.WIRE_TYPES.ENDGROUP) { if (i !== d) throw Error('Illegal group end indicator for ' + this.toString(!0) + ': ' + i + ' (' + (d ? d + ' expected' : 'not a group') + ')'); break } if (j = this._fieldsById[i])j.repeated && !j.options.packed ? f[j.name].push(j.decode(h, b)) : j.map ? (l = j.decode(h, b), f[j.name].set(l[0], l[1])) : (f[j.name] = j.decode(h, b), j.oneof && (m = f[j.oneof.name], m !== null && m !== j.name && (f[m] = null), f[j.oneof.name] = j.name)); else switch (h) { case a.WIRE_TYPES.VARINT:b.readVarint32(); break; case a.WIRE_TYPES.BITS32:b.offset += 4; break; case a.WIRE_TYPES.BITS64:b.offset += 8; break; case a.WIRE_TYPES.LDELIM:k = b.readVarint32(), b.offset += k; break; case a.WIRE_TYPES.STARTGROUP:for (;o(i, b););break; default:throw Error('Illegal wire type for unknown field ' + i + ' in ' + this.toString(!0) + '#decode: ' + h) } } for (n = 0, p = this._fields.length; p > n; ++n) if (j = this._fields[n], f[j.name] === null) if (this.syntax === 'proto3')f[j.name] = j.defaultValue; else { if (j.required) throw q = Error('Missing at least one required field for ' + this.toString(!0) + ': ' + j.name), q.decoded = f, q; a.populateDefaults && j.defaultValue !== null && (f[j.name] = j.defaultValue); } return f }, c.Message = m, p = function (b, c, e, f, g, h, i, j, k, l) { d.call(this, b, c, h), this.className = 'Message.Field', this.required = e === 'required', this.repeated = e === 'repeated', this.map = e === 'map', this.keyType = f || null, this.type = g, this.resolvedType = null, this.id = i, this.options = j || {}, this.defaultValue = null, this.oneof = k || null, this.syntax = l || 'proto2', this.originalName = this.name, this.element = null, this.keyElement = null, !this.builder.options.convertFieldsToCamelCase || this instanceof m.ExtensionField || (this.name = a.Util.toCamelCase(this.name)); }, q = p.prototype = Object.create(d.prototype), q.build = function () { this.element = new i(this.type, this.resolvedType, !1, this.syntax), this.map && (this.keyElement = new i(this.keyType, void 0, !0, this.syntax)), this.syntax !== 'proto3' || this.repeated || this.map ? typeof this.options.default !== 'undefined' && (this.defaultValue = this.verifyValue(this.options.default)) : this.defaultValue = i.defaultFieldValue(this.type); }, q.verifyValue = function (b, c) { var d, e, f; if (c = c || !1, d = function (a, b) { throw Error('Illegal value for ' + this.toString(!0) + ' of type ' + this.type.name + ': ' + a + ' (' + b + ')') }.bind(this), b === null) return this.required && d(typeof b, 'required'), this.syntax === 'proto3' && this.type !== a.TYPES.message && d(typeof b, 'proto3 field without field presence cannot be null'), null; if (this.repeated && !c) { for (Array.isArray(b) || (b = [b]), f = [], e = 0; e < b.length; e++)f.push(this.element.verifyValue(b[e])); return f } return this.map && !c ? b instanceof a.Map ? b : (b instanceof Object || d(typeof b, 'expected ProtoBuf.Map or raw object for map field'), new a.Map(this, b)) : (!this.repeated && Array.isArray(b) && d(typeof b, 'no array expected'), this.element.verifyValue(b)) }, q.hasWirePresence = function (b, c) { if (this.syntax !== 'proto3') return b !== null; if (this.oneof && c[this.oneof.name] === this.name) return !0; switch (this.type) { case a.TYPES.int32:case a.TYPES.sint32:case a.TYPES.sfixed32:case a.TYPES.uint32:case a.TYPES.fixed32:return b !== 0; case a.TYPES.int64:case a.TYPES.sint64:case a.TYPES.sfixed64:case a.TYPES.uint64:case a.TYPES.fixed64:return b.low !== 0 || b.high !== 0; case a.TYPES.bool:return b; case a.TYPES.float:case a.TYPES.double:return b !== 0; case a.TYPES.string:return b.length > 0; case a.TYPES.bytes:return b.remaining() > 0; case a.TYPES.enum:return b !== 0; case a.TYPES.message:return b !== null; default:return !0 } }, q.encode = function (b, c, d) { var e, g, h, i, j; if (this.type === null || typeof this.type !== 'object') throw Error('[INTERNAL] Unresolved type in ' + this.toString(!0) + ': ' + this.type); if (b === null || this.repeated && b.length == 0) return c; try { if (this.repeated) if (this.options.packed && a.PACKABLE_WIRE_TYPES.indexOf(this.type.wireType) >= 0) { for (c.writeVarint32(this.id << 3 | a.WIRE_TYPES.LDELIM), c.ensureCapacity(c.offset += 1), g = c.offset, e = 0; e < b.length; e++) this.element.encodeValue(this.id, b[e], c); h = c.offset - g, i = f.calculateVarint32(h), i > 1 && (j = c.slice(g, c.offset), g += i - 1, c.offset = g, c.append(j)), c.writeVarint32(h, g - i); } else for (e = 0; e < b.length; e++)c.writeVarint32(this.id << 3 | this.type.wireType), this.element.encodeValue(this.id, b[e], c); else this.map ? b.forEach(function (b, d) { var g = f.calculateVarint32(8 | this.keyType.wireType) + this.keyElement.calculateLength(1, d) + f.calculateVarint32(16 | this.type.wireType) + this.element.calculateLength(2, b); c.writeVarint32(this.id << 3 | a.WIRE_TYPES.LDELIM), c.writeVarint32(g), c.writeVarint32(8 | this.keyType.wireType), this.keyElement.encodeValue(1, d, c), c.writeVarint32(16 | this.type.wireType), this.element.encodeValue(2, b, c); }, this) : this.hasWirePresence(b, d) && (c.writeVarint32(this.id << 3 | this.type.wireType), this.element.encodeValue(this.id, b, c)); } catch (k) { throw Error('Illegal value for ' + this.toString(!0) + ': ' + b + ' (' + k + ')') } return c }, q.calculate = function (b, c) { var d, e, g; if (b = this.verifyValue(b), this.type === null || typeof this.type !== 'object') throw Error('[INTERNAL] Unresolved type in ' + this.toString(!0) + ': ' + this.type); if (b === null || this.repeated && b.length == 0) return 0; d = 0; try { if (this.repeated) if (this.options.packed && a.PACKABLE_WIRE_TYPES.indexOf(this.type.wireType) >= 0) { for (d += f.calculateVarint32(this.id << 3 | a.WIRE_TYPES.LDELIM), g = 0, e = 0; e < b.length; e++)g += this.element.calculateLength(this.id, b[e]); d += f.calculateVarint32(g), d += g; } else for (e = 0; e < b.length; e++)d += f.calculateVarint32(this.id << 3 | this.type.wireType), d += this.element.calculateLength(this.id, b[e]); else this.map ? b.forEach(function (b, c) { var g = f.calculateVarint32(8 | this.keyType.wireType) + this.keyElement.calculateLength(1, c) + f.calculateVarint32(16 | this.type.wireType) + this.element.calculateLength(2, b); d += f.calculateVarint32(this.id << 3 | a.WIRE_TYPES.LDELIM), d += f.calculateVarint32(g), d += g; }, this) : this.hasWirePresence(b, c) && (d += f.calculateVarint32(this.id << 3 | this.type.wireType), d += this.element.calculateLength(this.id, b)); } catch (h) { throw Error('Illegal value for ' + this.toString(!0) + ': ' + b + ' (' + h + ')') } return d }, q.decode = function (b, c, d) { var e; var f; var h; var j; var k; var l; var m; var g = !this.map && b == this.type.wireType || !d && this.repeated && this.options.packed && b == a.WIRE_TYPES.LDELIM || this.map && b == a.WIRE_TYPES.LDELIM; if (!g) throw Error('Illegal wire type for field ' + this.toString(!0) + ': ' + b + ' (' + this.type.wireType + ' expected)'); if (b == a.WIRE_TYPES.LDELIM && this.repeated && this.options.packed && a.PACKABLE_WIRE_TYPES.indexOf(this.type.wireType) >= 0 && !d) { for (f = c.readVarint32(), f = c.offset + f, h = []; c.offset < f;)h.push(this.decode(this.type.wireType, c, !0)); return h } if (this.map) { if (j = i.defaultFieldValue(this.keyType), e = i.defaultFieldValue(this.type), f = c.readVarint32(), c.remaining() < f) throw Error('Illegal number of bytes for ' + this.toString(!0) + ': ' + f + ' required but got only ' + c.remaining()); for (k = c.clone(), k.limit = k.offset + f, c.offset += f; k.remaining() > 0;) if (l = k.readVarint32(), b = 7 & l, m = l >>> 3, m === 1)j = this.keyElement.decode(k, b, m); else { if (m !== 2) throw Error('Unexpected tag in map field key/value submessage'); e = this.element.decode(k, b, m); } return [j, e] } return this.element.decode(c, b, this.id) }, c.Message.Field = p, r = function (a, b, c, d, e, f, g) { p.call(this, a, b, c, null, d, e, f, g), this.extension; }, r.prototype = Object.create(p.prototype), c.Message.ExtensionField = r, s = function (a, b, c) { d.call(this, a, b, c), this.fields = []; }, c.Message.OneOf = s, t = function (a, b, c, d, e) { g.call(this, a, b, c, d, e), this.className = 'Enum', this.object = null; }, t.getName = function (a, b) { var e; var d; var c = Object.keys(a); for (d = 0; d < c.length; ++d) if (a[e = c[d]] === b) return e; return null }, u = t.prototype = Object.create(g.prototype), u.build = function (b) { var c, d, e, f; if (this.object && !b) return this.object; for (c = new a.Builder.Enum(), d = this.getChildren(t.Value), e = 0, f = d.length; f > e; ++e)c[d[e].name] = d[e].id; return Object.defineProperty && Object.defineProperty(c, '$options', { value: this.buildOpt(), enumerable: !1 }), this.object = c }, c.Enum = t, v = function (a, b, c, e) { d.call(this, a, b, c), this.className = 'Enum.Value', this.id = e; }, v.prototype = Object.create(d.prototype), c.Enum.Value = v, w = function (a, b, c, e) { d.call(this, a, b, c), this.field = e; }, w.prototype = Object.create(d.prototype), c.Extension = w, x = function (a, b, c, d) { g.call(this, a, b, c, d), this.className = 'Service', this.clazz = null; }, y = x.prototype = Object.create(g.prototype), y.build = function (b) { return this.clazz && !b ? this.clazz : this.clazz = (function (a, b) { var g; var c = function (b) { a.Builder.Service.call(this), this.rpcImpl = b || function (a, b, c) { setTimeout(c.bind(this, Error('Not implemented, see: https://github.com/dcodeIO/ProtoBuf.js/wiki/Services')), 0); }; }; var d = c.prototype = Object.create(a.Builder.Service.prototype); var e = b.getChildren(a.Reflect.Service.RPCMethod); for (g = 0; g < e.length; g++)!(function (a) { d[a.name] = function (c, d) { try { try { c = a.resolvedRequestType.clazz.decode(f.wrap(c)); } catch (e) { if (!(e instanceof TypeError)) throw e } if (c === null || typeof c !== 'object') throw Error('Illegal arguments'); c instanceof a.resolvedRequestType.clazz || (c = new a.resolvedRequestType.clazz(c)), this.rpcImpl(a.fqn(), c, function (c, e) { if (c) return d(c), void 0; try { e = a.resolvedResponseType.clazz.decode(e); } catch (f) {} return e && e instanceof a.resolvedResponseType.clazz ? (d(null, e), void 0) : (d(Error('Illegal response type received in service method ' + b.name + '#' + a.name)), void 0) }); } catch (e) { setTimeout(d.bind(this, e), 0); } }, c[a.name] = function (b, d, e) { new c(b)[a.name](d, e); }, Object.defineProperty && (Object.defineProperty(c[a.name], '$options', { value: a.buildOpt() }), Object.defineProperty(d[a.name], '$options', { value: c[a.name].$options })); }(e[g])); return Object.defineProperty && (Object.defineProperty(c, '$options', { value: b.buildOpt() }), Object.defineProperty(d, '$options', { value: c.$options }), Object.defineProperty(c, '$type', { value: b }), Object.defineProperty(d, '$type', { value: b })), c }(a, this)) }, c.Service = x, z = function (a, b, c, e) { d.call(this, a, b, c), this.className = 'Service.Method', this.options = e || {}; }, A = z.prototype = Object.create(d.prototype), A.buildOpt = h.buildOpt, c.Service.Method = z, B = function (a, b, c, d, e, f, g, h) { z.call(this, a, b, c, h), this.className = 'Service.RPCMethod', this.requestName = d, this.responseName = e, this.requestStream = f, this.responseStream = g, this.resolvedRequestType = null, this.resolvedResponseType = null; }, B.prototype = Object.create(z.prototype), c.Service.RPCMethod = B, c }(e)), e.Builder = (function (a, b, c) { function f (a) { a.messages && a.messages.forEach(function (b) { b.syntax = a.syntax, f(b); }), a.enums && a.enums.forEach(function (b) { b.syntax = a.syntax; }); } var d = function (a) { this.ns = new c.Namespace(this, null, ''), this.ptr = this.ns, this.resolved = !1, this.result = null, this.files = {}, this.importRoot = null, this.options = a || {}; }; var e = d.prototype; return d.isMessage = function (a) { return typeof a.name !== 'string' ? !1 : typeof a.values !== 'undefined' || typeof a.rpc !== 'undefined' ? !1 : !0 }, d.isMessageField = function (a) { return typeof a.rule !== 'string' || typeof a.name !== 'string' || typeof a.type !== 'string' || typeof a.id === 'undefined' ? !1 : !0 }, d.isEnum = function (a) { return typeof a.name !== 'string' ? !1 : typeof a.values !== 'undefined' && Array.isArray(a.values) && a.values.length !== 0 ? !0 : !1 }, d.isService = function (a) { return typeof a.name === 'string' && typeof a.rpc === 'object' && a.rpc ? !0 : !1 }, d.isExtend = function (a) { return typeof a.ref !== 'string' ? !1 : !0 }, e.reset = function () { return this.ptr = this.ns, this }, e.define = function (a) { if (typeof a !== 'string' || !b.TYPEREF.test(a)) throw Error('illegal namespace: ' + a); return a.split('.').forEach(function (a) { var b = this.ptr.getChild(a); b === null && this.ptr.addChild(b = new c.Namespace(this, this.ptr, a)), this.ptr = b; }, this), this }, e.create = function (b) { var e, f, g, h, i; if (!b) return this; if (Array.isArray(b)) { if (b.length === 0) return this; b = b.slice(); } else b = [b]; for (e = [b]; e.length > 0;) { if (b = e.pop(), !Array.isArray(b)) throw Error('not a valid namespace: ' + JSON.stringify(b)); for (;b.length > 0;) { if (f = b.shift(), d.isMessage(f)) { if (g = new c.Message(this, this.ptr, f.name, f.options, f.isGroup, f.syntax), h = {}, f.oneofs && Object.keys(f.oneofs).forEach(function (a) { g.addChild(h[a] = new c.Message.OneOf(this, g, a)); }, this), f.fields && f.fields.forEach(function (a) { if (g.getChild(0 | a.id) !== null) throw Error('duplicate or invalid field id in ' + g.name + ': ' + a.id); if (a.options && typeof a.options !== 'object') throw Error('illegal field options in ' + g.name + '#' + a.name); var b = null; if (typeof a.oneof === 'string' && !(b = h[a.oneof])) throw Error('illegal oneof in ' + g.name + '#' + a.name + ': ' + a.oneof); a = new c.Message.Field(this, g, a.rule, a.keytype, a.type, a.name, a.id, a.options, b, f.syntax), b && b.fields.push(a), g.addChild(a); }, this), i = [], f.enums && f.enums.forEach(function (a) { i.push(a); }), f.messages && f.messages.forEach(function (a) { i.push(a); }), f.services && f.services.forEach(function (a) { i.push(a); }), f.extensions && (g.extensions = typeof f.extensions[0] === 'number' ? [f.extensions] : f.extensions), this.ptr.addChild(g), i.length > 0) { e.push(b), b = i, i = null, this.ptr = g, g = null; continue }i = null; } else if (d.isEnum(f))g = new c.Enum(this, this.ptr, f.name, f.options, f.syntax), f.values.forEach(function (a) { g.addChild(new c.Enum.Value(this, g, a.name, a.id)); }, this), this.ptr.addChild(g); else if (d.isService(f))g = new c.Service(this, this.ptr, f.name, f.options), Object.keys(f.rpc).forEach(function (a) { var b = f.rpc[a]; g.addChild(new c.Service.RPCMethod(this, g, a, b.request, b.response, !!b.request_stream, !!b.response_stream, b.options)); }, this), this.ptr.addChild(g); else { if (!d.isExtend(f)) throw Error('not a valid definition: ' + JSON.stringify(f)); if (g = this.ptr.resolve(f.ref, !0)) { f.fields.forEach(function (b) { var d, e, f, h; if (g.getChild(0 | b.id) !== null) throw Error('duplicate extended field id in ' + g.name + ': ' + b.id) if (g.extensions && (d = !1, g.extensions.forEach(function (a) { b.id >= a[0] && b.id <= a[1] && (d = !0); }), !d)) throw Error('illegal extended field id in ' + g.name + ': ' + b.id + ' (not within valid ranges)'); e = b.name, this.options.convertFieldsToCamelCase && (e = a.Util.toCamelCase(e)), f = new c.Message.ExtensionField(this, g, b.rule, b.type, this.ptr.fqn() + '.' + e, b.id, b.options), h = new c.Extension(this, this.ptr, b.name, f), f.extension = h, this.ptr.addChild(h), g.addChild(f); }, this); } else if (!/\.?google\.protobuf\./.test(f.ref)) throw Error('extended message ' + f.ref + ' is not defined') }f = null, g = null; }b = null, this.ptr = this.ptr.parent; } return this.resolved = !1, this.result = null, this }, e.import = function (b, c) { var e; var g; var h; var i; var j; var k; var l; var m; var d = '/'; if (typeof c === 'string') { if (a.Util.IS_NODE, this.files[c] === !0) return this.reset(); this.files[c] = !0; } else if (typeof c === 'object') { if (e = c.root, a.Util.IS_NODE, (e.indexOf('\\') >= 0 || c.file.indexOf('\\') >= 0) && (d = '\\'), g = e + d + c.file, this.files[g] === !0) return this.reset(); this.files[g] = !0; } if (b.imports && b.imports.length > 0) { for (i = !1, typeof c === 'object' ? (this.importRoot = c.root, i = !0, h = this.importRoot, c = c.file, (h.indexOf('\\') >= 0 || c.indexOf('\\') >= 0) && (d = '\\')) : typeof c === 'string' ? this.importRoot ? h = this.importRoot : c.indexOf('/') >= 0 ? (h = c.replace(/\/[^\/]*$/, ''), h === '' && (h = '/')) : c.indexOf('\\') >= 0 ? (h = c.replace(/\\[^\\]*$/, ''), d = '\\') : h = '.' : h = null, j = 0; j < b.imports.length; j++) if (typeof b.imports[j] === 'string') { if (!h) throw Error('cannot determine import root'); if (k = b.imports[j], k === 'google/protobuf/descriptor.proto') continue; if (k = h + d + k, this.files[k] === !0) continue; if (/\.proto$/i.test(k) && !a.DotProto && (k = k.replace(/\.proto$/, '.json')), l = a.Util.fetch(k), l === null) throw Error("failed to import '" + k + "' in '" + c + "': file not found"); /\.json$/i.test(k) ? this.import(JSON.parse(l + ''), k) : this.import(a.DotProto.Parser.parse(l), k); } else c ? /\.(\w+)$/.test(c) ? this.import(b.imports[j], c.replace(/^(.+)\.(\w+)$/, function (a, b, c) { return b + '_import' + j + '.' + c })) : this.import(b.imports[j], c + '_import' + j) : this.import(b.imports[j]); i && (this.importRoot = null); } return b.package && this.define(b.package), b.syntax && f(b), m = this.ptr, b.options && Object.keys(b.options).forEach(function (a) { m.options[a] = b.options[a]; }), b.messages && (this.create(b.messages), this.ptr = m), b.enums && (this.create(b.enums), this.ptr = m), b.services && (this.create(b.services), this.ptr = m), b.extends && this.create(b.extends), this.reset() }, e.resolveAll = function () { var d; if (this.ptr == null || typeof this.ptr.type === 'object') return this; if (this.ptr instanceof c.Namespace) this.ptr.children.forEach(function (a) { this.ptr = a, this.resolveAll(); }, this); else if (this.ptr instanceof c.Message.Field) { if (b.TYPE.test(this.ptr.type)) this.ptr.type = a.TYPES[this.ptr.type]; else { if (!b.TYPEREF.test(this.ptr.type)) throw Error('illegal type reference in ' + this.ptr.toString(!0) + ': ' + this.ptr.type); if (d = (this.ptr instanceof c.Message.ExtensionField ? this.ptr.extension.parent : this.ptr.parent).resolve(this.ptr.type, !0), !d) throw Error('unresolvable type reference in ' + this.ptr.toString(!0) + ': ' + this.ptr.type); if (this.ptr.resolvedType = d, d instanceof c.Enum) { if (this.ptr.type = a.TYPES.enum, this.ptr.syntax === 'proto3' && d.syntax !== 'proto3') throw Error('proto3 message cannot reference proto2 enum') } else { if (!(d instanceof c.Message)) throw Error('illegal type reference in ' + this.ptr.toString(!0) + ': ' + this.ptr.type); this.ptr.type = d.isGroup ? a.TYPES.group : a.TYPES.message; } } if (this.ptr.map) { if (!b.TYPE.test(this.ptr.keyType)) throw Error('illegal key type for map field in ' + this.ptr.toString(!0) + ': ' + this.ptr.keyType); this.ptr.keyType = a.TYPES[this.ptr.keyType]; } } else if (this.ptr instanceof a.Reflect.Service.Method) { if (!(this.ptr instanceof a.Reflect.Service.RPCMethod)) throw Error('illegal service type in ' + this.ptr.toString(!0)); if (d = this.ptr.parent.resolve(this.ptr.requestName, !0), !(d && d instanceof a.Reflect.Message)) throw Error('Illegal type reference in ' + this.ptr.toString(!0) + ': ' + this.ptr.requestName); if (this.ptr.resolvedRequestType = d, d = this.ptr.parent.resolve(this.ptr.responseName, !0), !(d && d instanceof a.Reflect.Message)) throw Error('Illegal type reference in ' + this.ptr.toString(!0) + ': ' + this.ptr.responseName); this.ptr.resolvedResponseType = d; } else if (!(this.ptr instanceof a.Reflect.Message.OneOf || this.ptr instanceof a.Reflect.Extension || this.ptr instanceof a.Reflect.Enum.Value)) throw Error('illegal object in namespace: ' + typeof this.ptr + ': ' + this.ptr); return this.reset() }, e.build = function (a) { var b, c, d; if (this.reset(), this.resolved || (this.resolveAll(), this.resolved = !0, this.result = null), this.result === null && (this.result = this.ns.build()), !a) return this.result; for (b = typeof a === 'string' ? a.split('.') : a, c = this.result, d = 0; d < b.length; d++) { if (!c[b[d]]) { c = null; break }c = c[b[d]]; } return c }, e.lookup = function (a, b) { return a ? this.ns.resolve(a, b) : this.ns }, e.toString = function () { return 'Builder' }, d.Message = function () {}, d.Enum = function () {}, d.Service = function () {}, d }(e, e.Lang, e.Reflect)), e.Map = (function (a, b) { function e (a) { var b = 0; return { next: function () { return b < a.length ? { done: !1, value: a[b++] } : { done: !0 } } } } var c = function (a, c) { var d, e, f, g; if (!a.map) throw Error('field is not a map'); if (this.field = a, this.keyElem = new b.Element(a.keyType, null, !0, a.syntax), this.valueElem = new b.Element(a.type, a.resolvedType, !1, a.syntax), this.map = {}, Object.defineProperty(this, 'size', { get: function () { return Object.keys(this.map).length } }), c) for (d = Object.keys(c), e = 0; e < d.length; e++)f = this.keyElem.valueFromString(d[e]), g = this.valueElem.verifyValue(c[d[e]]), this.map[this.keyElem.valueToString(f)] = { key: f, value: g }; }; var d = c.prototype; return d.clear = function () { this.map = {}; }, d.delete = function (a) { var b = this.keyElem.valueToString(this.keyElem.verifyValue(a)); var c = b in this.map; return delete this.map[b], c }, d.entries = function () { var d; var c; var a = []; var b = Object.keys(this.map); for (c = 0; c < b.length; c++)a.push([(d = this.map[b[c]]).key, d.value]); return e(a) }, d.keys = function () { var c; var a = []; var b = Object.keys(this.map); for (c = 0; c < b.length; c++)a.push(this.map[b[c]].key); return e(a) }, d.values = function () { var c; var a = []; var b = Object.keys(this.map); for (c = 0; c < b.length; c++)a.push(this.map[b[c]].value); return e(a) }, d.forEach = function (a, b) { var e; var d; var c = Object.keys(this.map); for (d = 0; d < c.length; d++)a.call(b, (e = this.map[c[d]]).value, e.key, this); }, d.set = function (a, b) { var c = this.keyElem.verifyValue(a); var d = this.valueElem.verifyValue(b); return this.map[this.keyElem.valueToString(c)] = { key: c, value: d }, this }, d.get = function (a) { var b = this.keyElem.valueToString(this.keyElem.verifyValue(a)); return b in this.map ? this.map[b].value : void 0 }, d.has = function (a) { var b = this.keyElem.valueToString(this.keyElem.verifyValue(a)); return b in this.map }, c }(e, e.Reflect)), e.loadProto = function (a, b, c) { return (typeof b === 'string' || b && typeof b.file === 'string' && typeof b.root === 'string') && (c = b, b = void 0), e.loadJson(e.DotProto.Parser.parse(a), b, c) }, e.protoFromString = e.loadProto, e.loadProtoFile = function (a, b, c) { if (b && typeof b === 'object' ? (c = b, b = null) : b && typeof b === 'function' || (b = null), b) return e.Util.fetch(typeof a === 'string' ? a : a.root + '/' + a.file, function (d) { if (d === null) return b(Error('Failed to fetch file')), void 0; try { b(null, e.loadProto(d, c, a)); } catch (f) { b(f); } }); var d = e.Util.fetch(typeof a === 'object' ? a.root + '/' + a.file : a); return d === null ? null : e.loadProto(d, c, a) }, e.protoFromFile = e.loadProtoFile, e.newBuilder = function (a) { return a = a || {}, typeof a.convertFieldsToCamelCase === 'undefined' && (a.convertFieldsToCamelCase = e.convertFieldsToCamelCase), typeof a.populateAccessors === 'undefined' && (a.populateAccessors = e.populateAccessors), new e.Builder(a) }, e.loadJson = function (a, b, c) { return (typeof b === 'string' || b && typeof b.file === 'string' && typeof b.root === 'string') && (c = b, b = null), b && typeof b === 'object' || (b = e.newBuilder()), typeof a === 'string' && (a = JSON.parse(a)), b.import(a, c), b.resolveAll(), b }, e.loadJsonFile = function (a, b, c) { if (b && typeof b === 'object' ? (c = b, b = null) : b && typeof b === 'function' || (b = null), b) return e.Util.fetch(typeof a === 'string' ? a : a.root + '/' + a.file, function (d) { if (d === null) return b(Error('Failed to fetch file')), void 0; try { b(null, e.loadJson(JSON.parse(d), c, a)); } catch (f) { b(f); } }); var d = e.Util.fetch(typeof a === 'object' ? a.root + '/' + a.file : a); return d === null ? null : e.loadJson(JSON.parse(d), c, a) }, h = a, e.loadProto(h, void 0, '').build('Modules').probuf }(d, c)); return e } const Codec$1 = protobuf(SSMsg$1); Codec$1.getModule = (pbName) => { const modules = new Codec$1[pbName](); modules.getArrayData = () => { let data = modules.toArrayBuffer(); data = isArrayBuffer(data) ? [].slice.call(new Int8Array(data)) : data; return data; }; return modules; }; var ErrorCode; (function (ErrorCode) { /** 超时 */ ErrorCode[ErrorCode["TIMEOUT"] = -1] = "TIMEOUT"; /** * 未知原因失败。 */ ErrorCode[ErrorCode["UNKNOWN"] = -2] = "UNKNOWN"; /** 参数错误 */ ErrorCode[ErrorCode["PARAMETER_ERROR"] = -3] = "PARAMETER_ERROR"; /** * 成功 */ ErrorCode[ErrorCode["SUCCESS"] = 0] = "SUCCESS"; ErrorCode[ErrorCode["RC_MSG_UNAUTHORIZED"] = 20406] = "RC_MSG_UNAUTHORIZED"; /** * 群组 Id 无效 */ ErrorCode[ErrorCode["RC_DISCUSSION_GROUP_ID_INVALID"] = 20407] = "RC_DISCUSSION_GROUP_ID_INVALID"; /** * 发送频率过快 */ ErrorCode[ErrorCode["SEND_FREQUENCY_TOO_FAST"] = 20604] = "SEND_FREQUENCY_TOO_FAST"; /** * 不在讨论组。 */ ErrorCode[ErrorCode["NOT_IN_DISCUSSION"] = 21406] = "NOT_IN_DISCUSSION"; /** * 群组被禁言 */ ErrorCode[ErrorCode["FORBIDDEN_IN_GROUP"] = 22408] = "FORBIDDEN_IN_GROUP"; ErrorCode[ErrorCode["RECALL_MESSAGE"] = 25101] = "RECALL_MESSAGE"; /** * 不在群组。 */ ErrorCode[ErrorCode["NOT_IN_GROUP"] = 22406] = "NOT_IN_GROUP"; /** * 不在聊天室。 */ ErrorCode[ErrorCode["NOT_IN_CHATROOM"] = 23406] = "NOT_IN_CHATROOM"; /** *聊天室被禁言 */ ErrorCode[ErrorCode["FORBIDDEN_IN_CHATROOM"] = 23408] = "FORBIDDEN_IN_CHATROOM"; /** * 聊天室中成员被踢出 */ ErrorCode[ErrorCode["RC_CHATROOM_USER_KICKED"] = 23409] = "RC_CHATROOM_USER_KICKED"; /** * 聊天室不存在 */ ErrorCode[ErrorCode["RC_CHATROOM_NOT_EXIST"] = 23410] = "RC_CHATROOM_NOT_EXIST"; /** * 聊天室成员已满 */ ErrorCode[ErrorCode["RC_CHATROOM_IS_FULL"] = 23411] = "RC_CHATROOM_IS_FULL"; /** * 获取聊天室信息参数无效 */ ErrorCode[ErrorCode["RC_CHATROOM_PATAMETER_INVALID"] = 23412] = "RC_CHATROOM_PATAMETER_INVALID"; /** * 聊天室异常 */ ErrorCode[ErrorCode["CHATROOM_GET_HISTORYMSG_ERROR"] = 23413] = "CHATROOM_GET_HISTORYMSG_ERROR"; /** * 没有打开聊天室消息存储 */ ErrorCode[ErrorCode["CHATROOM_NOT_OPEN_HISTORYMSG_STORE"] = 23414] = "CHATROOM_NOT_OPEN_HISTORYMSG_STORE"; /** * 聊天室 KV 设置超出最大值(已满, 默认最多设置 100 个) */ ErrorCode[ErrorCode["CHATROOM_KV_EXCEED"] = 23423] = "CHATROOM_KV_EXCEED"; /** * 聊天室 KV 设置失败(kv 已存在, 需覆盖设置) */ ErrorCode[ErrorCode["CHATROOM_KV_OVERWRITE_INVALID"] = 23424] = "CHATROOM_KV_OVERWRITE_INVALID"; /** * 聊天室 KV 存储功能没有开通 */ ErrorCode[ErrorCode["CHATROOM_KV_STORE_NOT_OPEN"] = 23426] = "CHATROOM_KV_STORE_NOT_OPEN"; /** * 聊天室Key不存在 */ ErrorCode[ErrorCode["CHATROOM_KEY_NOT_EXIST"] = 23427] = "CHATROOM_KEY_NOT_EXIST"; /** * 敏感词屏蔽 */ ErrorCode[ErrorCode["SENSITIVE_SHIELD"] = 21501] = "SENSITIVE_SHIELD"; ErrorCode[ErrorCode["SENSITIVE_REPLACE"] = 21502] = "SENSITIVE_REPLACE"; /** * 加入讨论失败 */ ErrorCode[ErrorCode["JOIN_IN_DISCUSSION"] = 21407] = "JOIN_IN_DISCUSSION"; /** * 创建讨论组失败 */ ErrorCode[ErrorCode["CREATE_DISCUSSION"] = 21408] = "CREATE_DISCUSSION"; /** * 设置讨论组邀请状态失败 */ ErrorCode[ErrorCode["INVITE_DICUSSION"] = 21409] = "INVITE_DICUSSION"; /** *获取用户失败 */ ErrorCode[ErrorCode["GET_USERINFO_ERROR"] = 23407] = "GET_USERINFO_ERROR"; /** * 在黑名单中。 */ ErrorCode[ErrorCode["REJECTED_BY_BLACKLIST"] = 405] = "REJECTED_BY_BLACKLIST"; /** * 通信过程中,当前 Socket 不存在。 */ ErrorCode[ErrorCode["RC_NET_CHANNEL_INVALID"] = 30001] = "RC_NET_CHANNEL_INVALID"; /** * Socket 连接不可用。 */ ErrorCode[ErrorCode["RC_NET_UNAVAILABLE"] = 30002] = "RC_NET_UNAVAILABLE"; /** * 通信超时。 */ ErrorCode[ErrorCode["RC_MSG_RESP_TIMEOUT"] = 30003] = "RC_MSG_RESP_TIMEOUT"; /** * 导航操作时,Http 请求失败。 */ ErrorCode[ErrorCode["RC_HTTP_SEND_FAIL"] = 30004] = "RC_HTTP_SEND_FAIL"; /** * HTTP 请求失败。 */ ErrorCode[ErrorCode["RC_HTTP_REQ_TIMEOUT"] = 30005] = "RC_HTTP_REQ_TIMEOUT"; /** * HTTP 接收失败。 */ ErrorCode[ErrorCode["RC_HTTP_RECV_FAIL"] = 30006] = "RC_HTTP_RECV_FAIL"; /** * 导航操作的 HTTP 请求,返回不是200。 */ ErrorCode[ErrorCode["RC_NAVI_RESOURCE_ERROR"] = 30007] = "RC_NAVI_RESOURCE_ERROR"; /** * 导航数据解析后,其中不存在有效数据。 */ ErrorCode[ErrorCode["RC_NODE_NOT_FOUND"] = 30008] = "RC_NODE_NOT_FOUND"; /** * 导航数据解析后,其中不存在有效 IP 地址。 */ ErrorCode[ErrorCode["RC_DOMAIN_NOT_RESOLVE"] = 30009] = "RC_DOMAIN_NOT_RESOLVE"; /** * 创建 Socket 失败。 */ ErrorCode[ErrorCode["RC_SOCKET_NOT_CREATED"] = 30010] = "RC_SOCKET_NOT_CREATED"; /** * Socket 被断开。 */ ErrorCode[ErrorCode["RC_SOCKET_DISCONNECTED"] = 30011] = "RC_SOCKET_DISCONNECTED"; /** * PING 操作失败。 */ ErrorCode[ErrorCode["RC_PING_SEND_FAIL"] = 30012] = "RC_PING_SEND_FAIL"; /** * PING 超时。 */ ErrorCode[ErrorCode["RC_PONG_RECV_FAIL"] = 30013] = "RC_PONG_RECV_FAIL"; /** * 消息发送失败。 */ ErrorCode[ErrorCode["RC_MSG_SEND_FAIL"] = 30014] = "RC_MSG_SEND_FAIL"; /** * JSON 后的消息体超限, 目前最大 128kb */ ErrorCode[ErrorCode["RC_MSG_CONTENT_EXCEED_LIMIT"] = 30016] = "RC_MSG_CONTENT_EXCEED_LIMIT"; /** * 做 connect 连接时,收到的 ACK 超时。 */ ErrorCode[ErrorCode["RC_CONN_ACK_TIMEOUT"] = 31000] = "RC_CONN_ACK_TIMEOUT"; /** * 参数错误。 */ ErrorCode[ErrorCode["RC_CONN_PROTO_VERSION_ERROR"] = 31001] = "RC_CONN_PROTO_VERSION_ERROR"; /** * 参数错误,App Id 错误。 */ ErrorCode[ErrorCode["RC_CONN_ID_REJECT"] = 31002] = "RC_CONN_ID_REJECT"; /** * 服务器不可用。 */ ErrorCode[ErrorCode["RC_CONN_SERVER_UNAVAILABLE"] = 31003] = "RC_CONN_SERVER_UNAVAILABLE"; /** * Token 错误。 */ ErrorCode[ErrorCode["RC_CONN_USER_OR_PASSWD_ERROR"] = 31004] = "RC_CONN_USER_OR_PASSWD_ERROR"; /** * websocket 鉴权失败,通常为连接后未及时发送 Ping 或接收到 Pong */ ErrorCode[ErrorCode["RC_CONN_NOT_AUTHRORIZED"] = 31005] = "RC_CONN_NOT_AUTHRORIZED"; /** * 重定向,地址错误。 */ ErrorCode[ErrorCode["RC_CONN_REDIRECTED"] = 31006] = "RC_CONN_REDIRECTED"; /** * NAME 与后台注册信息不一致。 */ ErrorCode[ErrorCode["RC_CONN_PACKAGE_NAME_INVALID"] = 31007] = "RC_CONN_PACKAGE_NAME_INVALID"; /** * APP 被屏蔽、删除或不存在。 */ ErrorCode[ErrorCode["RC_CONN_APP_BLOCKED_OR_DELETED"] = 31008] = "RC_CONN_APP_BLOCKED_OR_DELETED"; /** * 用户被屏蔽。 */ ErrorCode[ErrorCode["RC_CONN_USER_BLOCKED"] = 31009] = "RC_CONN_USER_BLOCKED"; /** * Disconnect,由服务器返回,比如用户互踢。 */ ErrorCode[ErrorCode["RC_DISCONN_KICK"] = 31010] = "RC_DISCONN_KICK"; /** * Disconnect,由服务器返回,比如用户互踢。 */ ErrorCode[ErrorCode["RC_DISCONN_EXCEPTION"] = 31011] = "RC_DISCONN_EXCEPTION"; /** * 协议层内部错误。query,上传下载过程中数据错误。 */ ErrorCode[ErrorCode["RC_QUERY_ACK_NO_DATA"] = 32001] = "RC_QUERY_ACK_NO_DATA"; /** * 协议层内部错误。 */ ErrorCode[ErrorCode["RC_MSG_DATA_INCOMPLETE"] = 32002] = "RC_MSG_DATA_INCOMPLETE"; /** * 未调用 init 初始化函数。 */ ErrorCode[ErrorCode["BIZ_ERROR_CLIENT_NOT_INIT"] = 33001] = "BIZ_ERROR_CLIENT_NOT_INIT"; /** * 数据库初始化失败。 */ ErrorCode[ErrorCode["BIZ_ERROR_DATABASE_ERROR"] = 33002] = "BIZ_ERROR_DATABASE_ERROR"; /** * 传入参数无效。 */ ErrorCode[ErrorCode["BIZ_ERROR_INVALID_PARAMETER"] = 33003] = "BIZ_ERROR_INVALID_PARAMETER"; /** * 通道无效。 */ ErrorCode[ErrorCode["BIZ_ERROR_NO_CHANNEL"] = 33004] = "BIZ_ERROR_NO_CHANNEL"; /** * 重新连接成功。 */ ErrorCode[ErrorCode["BIZ_ERROR_RECONNECT_SUCCESS"] = 33005] = "BIZ_ERROR_RECONNECT_SUCCESS"; /** * 连接中,再调用 connect 被拒绝。 */ ErrorCode[ErrorCode["BIZ_ERROR_CONNECTING"] = 33006] = "BIZ_ERROR_CONNECTING"; /** * 消息漫游服务未开通 */ ErrorCode[ErrorCode["MSG_ROAMING_SERVICE_UNAVAILABLE"] = 33007] = "MSG_ROAMING_SERVICE_UNAVAILABLE"; ErrorCode[ErrorCode["MSG_INSERT_ERROR"] = 33008] = "MSG_INSERT_ERROR"; ErrorCode[ErrorCode["MSG_DEL_ERROR"] = 33009] = "MSG_DEL_ERROR"; /** * 删除会话失败 */ ErrorCode[ErrorCode["CONVER_REMOVE_ERROR"] = 34001] = "CONVER_REMOVE_ERROR"; /** *拉取历史消息 */ ErrorCode[ErrorCode["CONVER_GETLIST_ERROR"] = 34002] = "CONVER_GETLIST_ERROR"; /** * 会话指定异常 */ ErrorCode[ErrorCode["CONVER_SETOP_ERROR"] = 34003] = "CONVER_SETOP_ERROR"; /** * 获取会话未读消息总数失败 */ ErrorCode[ErrorCode["CONVER_TOTAL_UNREAD_ERROR"] = 34004] = "CONVER_TOTAL_UNREAD_ERROR"; /** * 获取指定会话类型未读消息数异常 */ ErrorCode[ErrorCode["CONVER_TYPE_UNREAD_ERROR"] = 34005] = "CONVER_TYPE_UNREAD_ERROR"; /** * 获取指定用户ID&会话类型未读消息数异常 */ ErrorCode[ErrorCode["CONVER_ID_TYPE_UNREAD_ERROR"] = 34006] = "CONVER_ID_TYPE_UNREAD_ERROR"; ErrorCode[ErrorCode["CONVER_CLEAR_ERROR"] = 34007] = "CONVER_CLEAR_ERROR"; /** * 扩展存储 key value 超出限制 (错误码与移动端对齐) */ ErrorCode[ErrorCode["EXPANSION_LIMIT_EXCEET"] = 34010] = "EXPANSION_LIMIT_EXCEET"; /** * 消息不支持扩展 (错误码与移动端对齐) */ ErrorCode[ErrorCode["MESSAGE_KV_NOT_SUPPORT"] = 34008] = "MESSAGE_KV_NOT_SUPPORT"; ErrorCode[ErrorCode["CLEAR_HIS_TIME_ERROR"] = 34011] = "CLEAR_HIS_TIME_ERROR"; ErrorCode[ErrorCode["CONVER_GET_ERROR"] = 34009] = "CONVER_GET_ERROR"; /** * 群组信息异常 */ ErrorCode[ErrorCode["GROUP_SYNC_ERROR"] = 35001] = "GROUP_SYNC_ERROR"; /** * 匹配群信息异常 */ ErrorCode[ErrorCode["GROUP_MATCH_ERROR"] = 35002] = "GROUP_MATCH_ERROR"; // 聊天室异常 /** * 加入聊天室Id为空 */ ErrorCode[ErrorCode["CHATROOM_ID_ISNULL"] = 36001] = "CHATROOM_ID_ISNULL"; /** * 加入聊天室失败 */ ErrorCode[ErrorCode["CHARTOOM_JOIN_ERROR"] = 36002] = "CHARTOOM_JOIN_ERROR"; /** * 拉取聊天室历史消息失败 */ ErrorCode[ErrorCode["CHATROOM_HISMESSAGE_ERROR"] = 36003] = "CHATROOM_HISMESSAGE_ERROR"; /** * 聊天室 kv 未找到 */ ErrorCode[ErrorCode["CHATROOM_KV_NOT_FOUND"] = 36004] = "CHATROOM_KV_NOT_FOUND"; // 黑名单异常 /** * 加入黑名单异常 */ ErrorCode[ErrorCode["BLACK_ADD_ERROR"] = 37001] = "BLACK_ADD_ERROR"; /** * 获得指定人员再黑名单中的状态异常 */ ErrorCode[ErrorCode["BLACK_GETSTATUS_ERROR"] = 37002] = "BLACK_GETSTATUS_ERROR"; /** * 移除黑名单异常 */ ErrorCode[ErrorCode["BLACK_REMOVE_ERROR"] = 37003] = "BLACK_REMOVE_ERROR"; /** * 获取草稿失败 */ ErrorCode[ErrorCode["DRAF_GET_ERROR"] = 38001] = "DRAF_GET_ERROR"; /** * 保存草稿失败 */ ErrorCode[ErrorCode["DRAF_SAVE_ERROR"] = 38002] = "DRAF_SAVE_ERROR"; /** * 删除草稿失败 */ ErrorCode[ErrorCode["DRAF_REMOVE_ERROR"] = 38003] = "DRAF_REMOVE_ERROR"; /** * 关注公众号失败 */ ErrorCode[ErrorCode["SUBSCRIBE_ERROR"] = 39001] = "SUBSCRIBE_ERROR"; /** * 方法未支持 */ ErrorCode[ErrorCode["NOT_SUPPORT"] = 39002] = "NOT_SUPPORT"; /** * 关注公众号失败 */ ErrorCode[ErrorCode["QNTKN_FILETYPE_ERROR"] = 41001] = "QNTKN_FILETYPE_ERROR"; /** * 获取七牛token失败 */ ErrorCode[ErrorCode["QNTKN_GET_ERROR"] = 41002] = "QNTKN_GET_ERROR"; /** * cookie被禁用 */ ErrorCode[ErrorCode["COOKIE_ENABLE"] = 51001] = "COOKIE_ENABLE"; ErrorCode[ErrorCode["GET_MESSAGE_BY_ID_ERROR"] = 61001] = "GET_MESSAGE_BY_ID_ERROR"; // 没有注册DeviveId 也就是用户没有登陆 ErrorCode[ErrorCode["HAVNODEVICEID"] = 24001] = "HAVNODEVICEID"; // 已经存在 ErrorCode[ErrorCode["DEVICEIDISHAVE"] = 24002] = "DEVICEIDISHAVE"; // 没有对应的用户或token ErrorCode[ErrorCode["FEILD"] = 24009] = "FEILD"; // voip为空 ErrorCode[ErrorCode["VOIPISNULL"] = 24013] = "VOIPISNULL"; // 不支持的Voip引擎 ErrorCode[ErrorCode["NOENGINETYPE"] = 24010] = "NOENGINETYPE"; // channleName 是空 ErrorCode[ErrorCode["NULLCHANNELNAME"] = 24011] = "NULLCHANNELNAME"; // 生成Voipkey失败 ErrorCode[ErrorCode["VOIPDYANMICERROR"] = 24012] = "VOIPDYANMICERROR"; // 没有配置voip ErrorCode[ErrorCode["NOVOIP"] = 24014] = "NOVOIP"; // 服务器内部错误 ErrorCode[ErrorCode["INTERNALERRROR"] = 24015] = "INTERNALERRROR"; // VOIP close ErrorCode[ErrorCode["VOIPCLOSE"] = 24016] = "VOIPCLOSE"; ErrorCode[ErrorCode["CLOSE_BEFORE_OPEN"] = 51001] = "CLOSE_BEFORE_OPEN"; ErrorCode[ErrorCode["ALREADY_IN_USE"] = 51002] = "ALREADY_IN_USE"; ErrorCode[ErrorCode["INVALID_CHANNEL_NAME"] = 51003] = "INVALID_CHANNEL_NAME"; ErrorCode[ErrorCode["VIDEO_CONTAINER_IS_NULL"] = 51004] = "VIDEO_CONTAINER_IS_NULL"; /** * 删除消息数组长度为 0 . */ ErrorCode[ErrorCode["DELETE_MESSAGE_ID_IS_NULL"] = 61001] = "DELETE_MESSAGE_ID_IS_NULL"; /** * 己方取消已发出的通话请求 */ ErrorCode[ErrorCode["CANCEL"] = 1] = "CANCEL"; /** * 己方拒绝收到的通话请求 */ ErrorCode[ErrorCode["REJECT"] = 2] = "REJECT"; /** * 己方挂断 */ ErrorCode[ErrorCode["HANGUP"] = 3] = "HANGUP"; /** * 己方忙碌 */ ErrorCode[ErrorCode["BUSYLINE"] = 4] = "BUSYLINE"; /** * 己方未接听 */ ErrorCode[ErrorCode["NO_RESPONSE"] = 5] = "NO_RESPONSE"; /** * 己方不支持当前引擎 */ ErrorCode[ErrorCode["ENGINE_UN_SUPPORTED"] = 6] = "ENGINE_UN_SUPPORTED"; /** * 己方网络出错 */ ErrorCode[ErrorCode["NETWORK_ERROR"] = 7] = "NETWORK_ERROR"; /** * 对方取消已发出的通话请求 */ ErrorCode[ErrorCode["REMOTE_CANCEL"] = 11] = "REMOTE_CANCEL"; /** * 对方拒绝收到的通话请求 */ ErrorCode[ErrorCode["REMOTE_REJECT"] = 12] = "REMOTE_REJECT"; /** * 通话过程对方挂断 */ ErrorCode[ErrorCode["REMOTE_HANGUP"] = 13] = "REMOTE_HANGUP"; /** * 对方忙碌 */ ErrorCode[ErrorCode["REMOTE_BUSYLINE"] = 14] = "REMOTE_BUSYLINE"; /** * 对方未接听 */ ErrorCode[ErrorCode["REMOTE_NO_RESPONSE"] = 15] = "REMOTE_NO_RESPONSE"; /** * 对方网络错误 */ ErrorCode[ErrorCode["REMOTE_ENGINE_UN_SUPPORTED"] = 16] = "REMOTE_ENGINE_UN_SUPPORTED"; /** * 对方网络错误 */ ErrorCode[ErrorCode["REMOTE_NETWORK_ERROR"] = 17] = "REMOTE_NETWORK_ERROR"; /** * VoIP 不可用 */ ErrorCode[ErrorCode["VOIP_NOT_AVALIABLE"] = 18] = "VOIP_NOT_AVALIABLE"; })(ErrorCode || (ErrorCode = {})); var ErrorCode$1 = ErrorCode; const timerSetTimeout = (fun, itv) => { return setTimeout(fun, itv); }; const int64ToTimestamp = (obj) => { if (!isObject(obj) || obj.low === undefined || obj.high === undefined) { return obj; } let low = obj.low; if (low < 0) { low += 0xffffffff + 1; } low = low.toString(16); const timestamp = parseInt(obj.high.toString(16) + '00000000'.replace(new RegExp('0{' + low.length + '}$'), low), 16); return timestamp; }; const batchInt64ToTimestamp = (data) => { for (const key in data) { if (isObject(data[key])) { data[key] = int64ToTimestamp(data[key]); } } return data; }; const formatDate = (seperator) => { seperator = seperator || '-'; const date = new Date(); const year = date.getFullYear(); const month = date.getMonth() + 1; const day = date.getDate(); return `${year}${seperator}${month}${seperator}${day}`; }; /** * 群组 @ 类型 */ var MentionedType; (function (MentionedType) { /** * 所有人 */ MentionedType[MentionedType["ALL"] = 1] = "ALL"; /** * 部分人 */ MentionedType[MentionedType["SINGAL"] = 2] = "SINGAL"; })(MentionedType || (MentionedType = {})); var MentionedType$1 = MentionedType; /** * 内置消息类型 */ var MessageType; (function (MessageType) { /** * 文字消息 */ MessageType["TextMessage"] = "RC:TxtMsg"; /** * 语音消息 */ MessageType["VOICE"] = "RC:VcMsg"; /** * 高质量消息 */ MessageType["HQ_VOICE"] = "RC:HQVCMsg"; /** * 图片消息 */ MessageType["IMAGE"] = "RC:ImgMsg"; /** * GIF 消息 */ MessageType["GIF"] = "RC:GIFMsg"; /** * 图文消息 */ MessageType["RICH_CONTENT"] = "RC:ImgTextMsg"; /** * 位置消息 */ MessageType["LOCATION"] = "RC:LBSMsg"; /** * 文件消息 */ MessageType["FILE"] = "RC:FileMsg"; /** * 小视频消息 */ MessageType["SIGHT"] = "RC:SightMsg"; /** * 合并转发消息 */ MessageType["COMBINE"] = "RC:CombineMsg"; /** * 聊天室 KV 通知消息 */ MessageType["CHRM_KV_NOTIFY"] = "RC:chrmKVNotiMsg"; /** * 日志通知消息 */ MessageType["LOG_COMMAND"] = "RC:LogCmdMsg"; /** * 消息扩展 */ MessageType["EXPANSION_NOTIFY"] = "RC:MsgExMsg"; /** * 引用消息 */ MessageType["REFERENCE"] = "RC:ReferenceMsg"; /** * 撤回消息 */ MessageType["RECALL"] = "RC:RcCmd"; /** * 已读同步状态消息 */ MessageType["READ_RECEIPT"] = "RC:ReadNtf"; /** * 群已读请求回执消息 */ MessageType["READ_RECEIPT_REQUEST"] = "RC:RRReqMsg"; /** * 群已读响应回执消息 */ MessageType["READ_RECEIPT_RESPONSE"] = "RC:RRRspMsg"; /** * TODO */ MessageType["SYNC_READ_STATUS"] = "RC:SRSMsg"; })(MessageType || (MessageType = {})); var MessageType$1 = MessageType; var NotificationStatus; (function (NotificationStatus) { /** * 免打扰已开启 */ NotificationStatus[NotificationStatus["OPEN"] = 1] = "OPEN"; /** * 免打扰已关闭 */ NotificationStatus[NotificationStatus["CLOSE"] = 2] = "CLOSE"; })(NotificationStatus || (NotificationStatus = {})); var NotificationStatus$1 = NotificationStatus; const PublishTopic = { // 以下为发送消息操作, 本端发送、其他端同步都为以下值 PRIVATE: 'ppMsgP', GROUP: 'pgMsgP', CHATROOM: 'chatMsg', CUSTOMER_SERVICE: 'pcMsgP', RECALL: 'recallMsg', // RTC 消息 RTC_MSG: 'prMsgS', // 以下为服务端通知操作 NOTIFY_PULL_MSG: 's_ntf', RECEIVE_MSG: 's_msg', SYNC_STATUS: 's_stat', SERVER_NOTIFY: 's_cmd', SETTING_NOTIFY: 's_us' // 服务端配置变更通知 }; // 状态消息 const PublishStatusTopic = { PRIVATE: 'ppMsgS', GROUP: 'pgMsgS', CHATROOM: 'chatMsgS' }; const QueryTopic = { GET_SYNC_TIME: 'qrySessionsAtt', PULL_MSG: 'pullMsg', GET_CONVERSATION_LIST: 'qrySessions', REMOVE_CONVERSATION_LIST: 'delSessions', DELETE_MESSAGES: 'delMsg', CLEAR_UNREAD_COUNT: 'updRRTime', PULL_USER_SETTING: 'pullUS', PULL_CHRM_MSG: 'chrmPull', JOIN_CHATROOM: 'joinChrm', JOIN_EXIST_CHATROOM: 'joinChrmR', QUIT_CHATROOM: 'exitChrm', GET_CHATROOM_INFO: 'queryChrmI', UPDATE_CHATROOM_KV: 'setKV', DELETE_CHATROOM_KV: 'delKV', PULL_CHATROOM_KV: 'pullKV', GET_OLD_CONVERSATION_LIST: 'qryRelationR', REMOVE_OLD_CONVERSATION: 'delRelation', GET_CONVERSATION_STATUS: 'pullSeAtts', SET_CONVERSATION_STATUS: 'setSeAtt', GET_UPLOAD_FILE_TOKEN: 'qnTkn', GET_UPLOAD_FILE_URL: 'qnUrl', CLEAR_MESSAGES: { PRIVATE: 'cleanPMsg', GROUP: 'cleanGMsg', CUSTOMER_SERVICE: 'cleanCMsg', SYSTEM: 'cleanSMsg' }, // 以下为 RTC 操作 JOIN_RTC_ROOM: 'rtcRJoin_data', QUIT_RTC_ROOM: 'rtcRExit', PING_RTC: 'rtcPing', SET_RTC_DATA: 'rtcSetData', USER_SET_RTC_DATA: 'userSetData', GET_RTC_DATA: 'rtcQryData', DEL_RTC_DATA: 'rtcDelData', SET_RTC_OUT_DATA: 'rtcSetOutData', GET_RTC_OUT_DATA: 'rtcQryUserOutData', GET_RTC_TOKEN: 'rtcToken', SET_RTC_STATE: 'rtcUserState', GET_RTC_ROOM_INFO: 'rtcRInfo', GET_RTC_USER_INFO_LIST: 'rtcUData', SET_RTC_USER_INFO: 'rtcUPut', DEL_RTC_USER_INFO: 'rtcUDel', GET_RTC_USER_LIST: 'rtcUList' }; const QueryHistoryTopic = { PRIVATE: 'qryPMsg', GROUP: 'qryGMsg', CHATROOM: 'qryCHMsg', CUSTOMER_SERVICE: 'qryCMsg', SYSTEM: 'qrySMsg' }; const PublishTopicToConversationType = { [PublishTopic.PRIVATE]: ConversationType$1.PRIVATE, [PublishTopic.GROUP]: ConversationType$1.GROUP, [PublishTopic.CHATROOM]: ConversationType$1.CHATROOM, [PublishTopic.CUSTOMER_SERVICE]: ConversationType$1.CUSTOMER_SERVICE }; const ConversationTypeToQueryHistoryTopic = { [ConversationType$1.PRIVATE]: QueryHistoryTopic.PRIVATE, [ConversationType$1.GROUP]: QueryHistoryTopic.GROUP, [ConversationType$1.CHATROOM]: QueryHistoryTopic.CHATROOM, [ConversationType$1.CUSTOMER_SERVICE]: QueryHistoryTopic.CUSTOMER_SERVICE, [ConversationType$1.SYSTEM]: QueryHistoryTopic.SYSTEM }; const ConversationTypeToClearMessageTopic = { [ConversationType$1.PRIVATE]: QueryTopic.CLEAR_MESSAGES.PRIVATE, [ConversationType$1.GROUP]: QueryTopic.CLEAR_MESSAGES.GROUP, [ConversationType$1.CUSTOMER_SERVICE]: QueryTopic.CLEAR_MESSAGES.CUSTOMER_SERVICE, [ConversationType$1.SYSTEM]: QueryTopic.CLEAR_MESSAGES.SYSTEM }; const ConversationStatusConfig = { ENABLED: '1', DISABLED: '0' }; const ConversationStatusType = { DO_NOT_DISTURB: 1, TOP: 2 }; var MessageDirection; (function (MessageDirection) { /** * 己方发送消息 */ MessageDirection[MessageDirection["SEND"] = 1] = "SEND"; /** * 己方接收消息 */ MessageDirection[MessageDirection["RECEIVE"] = 2] = "RECEIVE"; })(MessageDirection || (MessageDirection = {})); var MessageDirection$1 = MessageDirection; /** * 序列化、反序列化数据通道 */ class DataCodec { constructor(connectType) { this._codec = connectType === 'websocket' ? Codec$1 : Codec; this._connectType = connectType; } /** * PB 数据 转为 rmtp 数据 反序列化 通用数据 * 根据解析的 PBName 分配解码方法. 如果没有单独的解码方法定义. 直接返回 pb 解析后的结果 */ decodeByPBName(data, pbName, option) { const self = this; const formatEventMap = { [PBName.DownStreamMessages]: self._formatSyncMessages, [PBName.DownStreamMessage]: self._formatReceivedMessage, [PBName.UpStreamMessage]: self._formatSentMessage, [PBName.HistoryMsgOuput]: self._formatHistoryMessages, [PBName.RelationsOutput]: self._formatConversationList, [PBName.QueryChatRoomInfoOutput]: self._formatChatRoomInfos, [PBName.RtcUserListOutput]: self._formatRTCUserList, [PBName.RtcQryOutput]: self._formatRTCData, [PBName.ChrmKVOutput]: self._formatChatRoomKVList, [PBName.PullUserSettingOutput]: self._formatUserSetting, [PBName.SessionStates]: self._formatConversationStatus }; let decodedData = data; const formatEvent = formatEventMap[pbName]; try { const hasData = data.length > 0; // 判断是否有数据, 防止无数据 pb 解析报错 decodedData = hasData && self._codec[pbName].decode(data); // pb 解析 if (isObject(decodedData)) { decodedData = batchInt64ToTimestamp(decodedData); // 时间转化 } if (isFunction(formatEvent)) { decodedData = formatEvent.call(this, decodedData, option); // 数据格式化 } } catch (e) { logger.error('PB parse error\n', e); } return decodedData; } _readBytes(content) { const { offset, buffer, limit } = content; if (offset) { try { const content = isArrayBuffer(buffer) ? new Uint8Array(buffer) : buffer; // content = utils.ArrayBufferToUint8Array(buffer).subarray(offset, limit) return BinaryHelper.readUTF(content.subarray(offset, limit)); } catch (e) { logger.info('readBytes error\n', e); } } return content; } /** * ====== 以下为 rmtp 数据 反序列化为 可用数据 ====== */ _formatBytes(content) { // 1. socket 下, content.buffer 为二进制 ArrayBuffer, 需调用 ArrayBufferToUint8Array 转换 // 2. comet 下, content 为 JSON 字符串. socket、comet 解析后都需要 JSON to Object let formatRes = this._readBytes(content); try { formatRes = JSON.parse(formatRes); } catch (e) { logger.info('formatBytes error\n', e); } return formatRes || content; } /** * 格式化多端同步消息 */ _formatSyncMessages(data, option) { option = option || {}; const self = this; const { list, syncTime, finished } = data; // Comet 与 聊天室没有 finished 字段定义,默认为 true if (isUndefined(finished) || finished === null) { data.finished = true; } data.syncTime = int64ToTimestamp(syncTime); data.list = map(list, (msgData) => { const message = self._formatReceivedMessage(msgData, option); return message; }); return data; } /** * 格式化接收消息 */ _formatReceivedMessage(data, option) { // TODO: 需杜绝此类传参,参数在进入方法前进行类型值确认 option = option || {}; const self = this; const { currentUserId, connectedTime } = option; const { content, fromUserId, type, groupId, status, dataTime, classname: messageType, msgId: messageUId, extraContent } = data; const direction = data.direction || MessageDirection$1.RECEIVE; // null || 0 都为收件箱 const isSelfSend = direction === MessageDirection$1.SEND; const { isPersited, isCounted, isMentioned, disableNotification, receivedStatus, canIncludeExpansion } = getMessageOptionByStatus(status); const targetId = type === ConversationType$1.GROUP || type === ConversationType$1.CHATROOM ? groupId : fromUserId; const senderUserId = isSelfSend ? currentUserId : fromUserId; const sentTime = int64ToTimestamp(dataTime); const isOffLineMessage = sentTime < connectedTime; const isChatRoomMsg = type === ConversationType$1.CHATROOM; const utfContent = self._formatBytes(content); let messageDirection = isSelfSend ? MessageDirection$1.SEND : MessageDirection$1.RECEIVE; // 聊天室拉消息时, 自己发送的消息, direction 也为 null if (isChatRoomMsg && (fromUserId === currentUserId)) { messageDirection = MessageDirection$1.SEND; } let expansion; if (extraContent) { expansion = {}; expansion = formatExtraContent(extraContent); } return { conversationType: type, targetId, senderUserId, messageType, messageUId, isPersited, isCounted, isMentioned, sentTime, isOffLineMessage, messageDirection, receivedTime: DelayTimer.getTime(), disableNotification, receivedStatus, canIncludeExpansion, content: utfContent, expansion }; } /** * 格式化发送消息 */ _formatSentMessage(data, option) { const self = this; const { content, classname: messageType, sessionId, msgId: messageUId, extraContent } = data; const { signal, currentUserId } = option; const { date, topic, targetId } = signal; const { isPersited, isCounted, disableNotification, canIncludeExpansion } = getUpMessageOptionBySessionId(sessionId); const type = PublishTopicToConversationType[topic] || ConversationType$1.PRIVATE; const isStatusMessage = isInObject(PublishStatusTopic, topic); let expansion; if (extraContent) { expansion = {}; expansion = formatExtraContent(extraContent); } return { conversationType: type, targetId, messageType, messageUId, isPersited, isCounted, isStatusMessage, senderUserId: currentUserId, content: self._formatBytes(content), sentTime: date * 1000, receivedTime: DelayTimer.getTime(), messageDirection: MessageDirection$1.SEND, isOffLineMessage: false, disableNotification, canIncludeExpansion, expansion // 消息携带的 KV 字段 }; } /** * 格式化历史消息 */ _formatHistoryMessages(data, option) { const conversation = option.conversation || {}; const { list: msgList, hasMsg } = data; const targetId = conversation.targetId; const syncTime = int64ToTimestamp(data.syncTime); const list = []; forEach(msgList, (msgData) => { const msg = this._formatReceivedMessage(msgData, option); msg.targetId = targetId; list.push(msg); }, { isReverse: true }); return { syncTime, list, hasMore: !!hasMsg }; } /** * 格式化会话列表 */ _formatConversationList(serverData, option) { const self = this; let { info: conversationList } = serverData; const afterDecode = option.afterDecode || function () { }; conversationList = map(conversationList, (serverConversation) => { const { msg, userId, type, unreadCount } = serverConversation; const latestMessage = self._formatReceivedMessage(msg, option); latestMessage.targetId = userId; const conversation = { targetId: userId, conversationType: type, unreadMessageCount: unreadCount, latestMessage }; return afterDecode(conversation) || conversation; }); return conversationList || []; } /** * 格式化聊天室信息 */ _formatChatRoomInfos(data) { const { userTotalNums, userInfos } = data; const chrmInfos = map(userInfos, (user) => { const { id, time } = user; const timestamp = int64ToTimestamp(time); return { id, time: timestamp }; }); return { userCount: userTotalNums, userInfos: chrmInfos }; } /** * 格式化 聊天室 KV 列表 */ _formatChatRoomKVList(data) { let { entries: kvEntries, bFullUpdate: isFullUpdate, syncTime } = data; kvEntries = kvEntries || []; kvEntries = map(kvEntries, (kv) => { const { key, value, status, timestamp, uid } = kv; const { isAutoDelete, isOverwrite, type } = getChatRoomKVByStatus(status); return { key, value, isAutoDelete, isOverwrite, type, userId: uid, timestamp: int64ToTimestamp(timestamp) }; }); return { kvEntries, isFullUpdate, syncTime }; } /** * 格式化 用户设置 */ _formatUserSetting(data) { const { items, version } = data; const settings = {}; forEach(items || [], (setting) => { const { key, version, value } = setting; setting.version = int64ToTimestamp(version); setting.value = this._readBytes(value); settings[key] = setting; }); return { settings, version }; } /** * 格式化 会话状态 置顶、免打扰) */ _formatConversationStatus(data) { const { state: stateList } = data; const statusList = []; forEach(stateList, (session) => { const { type, channelId: targetId, time: updatedTime, stateItem } = session; let notificationStatus = NotificationStatus$1.CLOSE; let isTop = false; forEach(stateItem, (item) => { const { sessionStateType, value } = item; switch (sessionStateType) { case ConversationStatusType.DO_NOT_DISTURB: notificationStatus = value === ConversationStatusConfig.ENABLED ? NotificationStatus$1.OPEN : NotificationStatus$1.CLOSE; break; case ConversationStatusType.TOP: isTop = value === ConversationStatusConfig.ENABLED; break; } }); statusList.push({ type, targetId, notificationStatus, isTop, updatedTime: int64ToTimestamp(updatedTime) }); }); return statusList; } /** * 格式化 RTC 用户列表 */ _formatRTCUserList(rtcInfos) { const { list, token, sessionId } = rtcInfos; const users = {}; forEach(list, (item) => { const { userId, userData } = item; const tmpData = {}; forEach(userData, (data) => { const { key, value } = data; tmpData[key] = value; }); users[userId] = tmpData; }); return { users, token, sessionId }; } /** * 格式化 RTC 数据 */ _formatRTCData(data) { const { outInfo: list } = data; const props = {}; forEach(list, (item) => { props[item.key] = item.value; }); return props; } /** * 格式化 RTC 房间信息 */ _formatRTCRoomInfo(data) { const { roomId: id, userCount: total, roomData } = data; const room = { id, total }; forEach(roomData, (data) => { room[data.key] = data.value; }); return room; } /** * ===== 以下为通用数据 序列化为 PB 数据 ===== * Engine Index 调用处理数据 */ /** * ? 待补全注释 */ encodeServerConfParams() { const modules = this._codec.getModule(PBName.SessionsAttQryInput); modules.setNothing(1); return modules.getArrayData(); } /** * 上行消息基础配置 */ _getUpMsgModule(conversation, option) { const { type } = conversation; const { messageType, isMentioned, mentionedType, mentionedUserIdList, content, pushContent, pushData, directionalUserIdList, isFilerWhiteBlacklist, isVoipPush, canIncludeExpansion, expansion } = option; const isGroupType = type === ConversationType$1.GROUP; const modules = this._codec.getModule(PBName.UpStreamMessage); const sessionId = getSessionId(option); let flag = 0; modules.setSessionId(sessionId); if (isGroupType && isMentioned && content) { content.mentionedInfo = { userIdList: mentionedUserIdList, type: mentionedType || MentionedType$1.ALL }; } pushContent && modules.setPushText(pushContent); // 设置 pushContent pushData && modules.setAppData(pushData); // 设置 pushData directionalUserIdList && modules.setUserId(directionalUserIdList); // 设置群定向消息人员 // 设置 flag. 涉及业务: 1、iOS VoipPush 2、过滤黑/白名单 flag |= (isVoipPush ? 0x01 : 0); flag |= (isFilerWhiteBlacklist ? 0x02 : 0); modules.setConfigFlag(flag); modules.setClassname(messageType); // 设置 objectName modules.setContent(JSON.stringify(content)); if (canIncludeExpansion && expansion) { const extraContent = {}; forEach(expansion, (val, key) => { extraContent[key] = { v: val }; }); modules.setExtraContent(JSON.stringify(extraContent)); // 设置消息扩展内容 } return modules; } /** * 序列化上行消息 */ encodeUpMsg(conversation, option) { const modules = this._getUpMsgModule(conversation, option); return modules.getArrayData(); } /** * 序列化拉取多端消息 */ encodeSyncMsg(syncMsgArgs) { const { sendboxTime, inboxTime } = syncMsgArgs; const modules = this._codec.getModule(PBName.SyncRequestMsg); modules.setIspolling(false); modules.setIsPullSend(true); modules.setSendBoxSyncTime(sendboxTime); modules.setSyncTime(inboxTime); return modules.getArrayData(); } /** * 序列化拉取聊天室消息 */ encodeChrmSyncMsg(time, count) { time = time || 0; count = count || 0; const modules = this._codec.getModule(PBName.ChrmPullMsg); modules.setCount(count); modules.setSyncTime(time); return modules.getArrayData(); } /** * 序列化历史消息 */ encodeGetHistoryMsg(targetId, option) { const { count, order, timestamp } = option; const modules = this._codec.getModule(PBName.HistoryMsgInput); modules.setTargetId(targetId); modules.setTime(timestamp); modules.setCount(count); modules.setOrder(order); return modules.getArrayData(); } /** * 序列化会话列表 */ encodeGetConversationList(option) { option = option || {}; const { count, startTime } = option; const modules = this._codec.getModule(PBName.RelationQryInput); // 默认值已在 modules 暴露层赋值. 传入此处, 必有值 modules.setType(1); // type 可传任意值 modules.setCount(count); modules.setStartTime(startTime); return modules.getArrayData(); } /** * 旧会话列表. 获取、删除都调用此方法 */ encodeOldConversationList(option) { option = option || {}; let { count, type, startTime, order } = option; count = count || 0; // 删除会话列表 count 传 0 , setCount 形参 count 为必填参数 startTime = startTime || 0; order = order || 0; const modules = this._codec.getModule(PBName.RelationQryInput); modules.setType(type); modules.setCount(count); modules.setStartTime(startTime); modules.setOrder(order); return modules.getArrayData(); } /** * 旧会话列表删除 */ encodeRemoveConversationList(conversationList) { const modules = this._codec.getModule(PBName.DeleteSessionsInput); const sessions = []; forEach(conversationList, (conversation) => { const { type, targetId } = conversation; const session = this._codec.getModule(PBName.SessionInfo); session.setType(type); session.setChannelId(targetId); sessions.push(session); }); modules.setSessions(sessions); return modules.getArrayData(); } /** * 批量删除消息通过消息 ID */ encodeDeleteMessages(conversationType, targetId, list) { const modules = this._codec.getModule(PBName.DeleteMsgInput); const encodeMsgs = []; forEach(list, (message) => { encodeMsgs.push({ msgId: message.messageUId, msgDataTime: message.sentTime, direct: message.messageDirection }); }); modules.setType(conversationType); modules.setConversationId(targetId); modules.setMsgs(encodeMsgs); return modules.getArrayData(); } /** * 批量删除消息通过时间 */ encodeClearMessages(targetId, timestamp) { const modules = this._codec.getModule(PBName.CleanHisMsgInput); timestamp = timestamp || new Date().getTime(); // 默认当前时间 modules.setDataTime(timestamp); modules.setTargetId(targetId); return modules.getArrayData(); } /** * 未读数清除 */ encodeClearUnreadCount(conversation, option) { const { type, targetId } = conversation; let { timestamp } = option; const modules = this._codec.getModule(PBName.SessionMsgReadInput); timestamp = timestamp || +new Date(); modules.setType(type); modules.setChannelId(targetId); modules.setMsgTime(timestamp); return modules.getArrayData(); } /** * 加入退出聊天室 */ encodeJoinOrQuitChatRoom() { const modules = this._codec.getModule(PBName.ChrmInput); modules.setNothing(1); return modules.getArrayData(); } /** * 获取聊天室信息 * @param count 获取人数 * @param order 排序方式 */ encodeGetChatRoomInfo(count, order) { const modules = this._codec.getModule(PBName.QueryChatRoomInfoInput); modules.setCount(count); modules.setOrder(order); return modules.getArrayData(); } /** * 上传文件认证信息获取 */ encodeGetFileToken(fileType, fileName) { const modules = this._codec.getModule(PBName.GetQNupTokenInput); modules.setType(fileType); modules.setKey(fileName); return modules.getArrayData(); } /** * 获取七牛上传url */ encodeGetFileUrl(inputPBName, fileType, fileName, originName) { const modules = this._codec.getModule(inputPBName); modules.setType(fileType); modules.setKey(fileName); if (originName) { modules.setFileName(originName); } return modules.getArrayData(); } /** * 聊天室 KV 存储 */ encodeModifyChatRoomKV(chrmId, entry, currentUserId) { const isComet = this._connectType === 'comet'; const modules = this._codec.getModule(PBName.SetChrmKV); const { key, value, notificationExtra: extra, isSendNotification, type } = entry; const action = type || ChatroomEntryType$1.UPDATE; const status = getChatRoomKVOptStatus(entry, action); const serverEntry = { key, value: value || '', uid: currentUserId }; // 若 status 传空, server 会出问题 if (!isUndefined(status)) { serverEntry.status = status; } modules.setEntry(serverEntry); if (isSendNotification) { // 如果需要发送通知, 设置通知消息 const conversation = { type: ConversationType$1.CHATROOM, targetId: chrmId }; const msgContent = { key, value, extra, type: action }; // 通知消息内置, 由 Server 自动发送 const msgModule = this._getUpMsgModule(conversation, { messageType: MessageType$1.CHRM_KV_NOTIFY, content: msgContent, isPersited: false, isCounted: false }); isComet ? modules.setNotification(msgModule.getArrayData()) : modules.setNotification(msgModule); modules.setBNotify(true); modules.setType(ConversationType$1.CHATROOM); } return modules.getArrayData(); } /** * KV 存储拉取 */ encodePullChatRoomKV(time) { const modules = this._codec.getModule(PBName.QueryChrmKV); modules.setTimestamp(time); return modules.getArrayData(); } /** * 用户实时配置更新 */ encodePullUserSetting(version) { const modules = this._codec.getModule(PBName.PullUserSettingInput); modules.setVersion(version); return modules.getArrayData(); } /** * 获取会话状态 (置顶、免打扰) */ encodeGetConversationStatus(time) { const modules = this._codec.getModule(PBName.SessionReq); modules.setTime(time); return modules.getArrayData(); } /** * 设置会话状态 (置顶、免打扰) */ encodeSetConversationStatus(statusList) { const isComet = this._connectType === 'comet'; const modules = this._codec.getModule(PBName.SessionStateModifyReq); const currentTime = DelayTimer.getTime(); const stateModuleList = []; forEach(statusList, (status) => { const stateModules = this._codec.getModule(PBName.SessionState); const { conversationType: type, targetId, notificationStatus, isTop } = status; const stateItemModuleList = []; stateModules.setType(type); stateModules.setChannelId(targetId); stateModules.setTime(currentTime); const isNotDisturb = notificationStatus === NotificationStatus$1.OPEN; const TypeToVal = {}; if (!isUndefined(notificationStatus)) { TypeToVal[ConversationStatusType.DO_NOT_DISTURB] = isNotDisturb; } if (!isUndefined(isTop)) { TypeToVal[ConversationStatusType.TOP] = isTop; } forEach(TypeToVal, (val, type) => { if (!isUndefined(val)) { const stateItemModules = this._codec.getModule(PBName.SessionStateItem); val = val ? ConversationStatusConfig.ENABLED : ConversationStatusConfig.DISABLED; stateItemModules.setSessionStateType(Number(type)); // TODO 暂时写死 stateItemModules.setValue(val); const stateItemModulesData = isComet ? stateItemModules.getArrayData() : stateItemModules; stateItemModuleList.push(stateItemModulesData); } }); stateModules.setStateItem(stateItemModuleList); const stateModulesData = isComet ? stateModules.getArrayData() : stateModules; stateModuleList.push(stateModulesData); }); modules.setVersion(currentTime); modules.setState(stateModuleList); return modules.getArrayData(); } /** * ============ 以下为 RTC 相关 ============ */ /** * 加入 RTC 房间 */ encodeJoinRTCRoom(mode, broadcastType) { const modules = this._codec.getModule(PBName.RtcInput); mode = mode || 0; modules.setRoomType(mode); isUndefined(broadcastType) || modules.setBroadcastType(broadcastType); return modules.getArrayData(); } /** * 退出 RTC 房间 */ encodeQuitRTCRoom() { return this._codec.getModule(PBName.SetUserStatusInput).getArrayData(); } /** * 房间数据 */ encodeSetRTCData(key, value, isInner, apiType, message) { const modules = this._codec.getModule(PBName.RtcSetDataInput); modules.setInterior(isInner); modules.setTarget(apiType); modules.setKey(key); modules.setValue(value); if (message) { message.name && modules.setObjectName(message.name); let content = message.content; if (content) { if (isObject(content)) { content = JSON.stringify(content); } modules.setContent(content); } } return modules.getArrayData(); } /** * 全量 URI */ encodeUserSetRTCData(message, valueInfo, objectName) { const modules = this._codec.getModule(PBName.RtcUserSetDataInput); // 全量 URI 新增 // 全量发布中 // valueInfo: key 为 uris,值为 全量的订阅信息 // content: key 为增量数据消息 RCRTC:ModifyResource,value 为增量订阅信息 modules.setObjectName(objectName); // content let val = this._codec.getModule(PBName.RtcValueInfo); val.setKey(message.name); val.setValue(message.content); modules.setContent(val); // valueInfo val = this._codec.getModule(PBName.RtcValueInfo); val.setKey('uris'); val.setValue(valueInfo); modules.setValueInfo(val); return modules.getArrayData(); } /** * 待完善注释 */ encodeGetRTCData(keys, isInner, apiType) { const modules = this._codec.getModule(PBName.RtcDataInput); modules.setInterior(isInner); modules.setTarget(apiType); modules.setKey(keys); return modules.getArrayData(); } /** * 待完善注释 */ encodeRemoveRTCData(keys, isInner, apiType, message) { const modules = this._codec.getModule(PBName.RtcDataInput); modules.setInterior(isInner); modules.setTarget(apiType); modules.setKey(keys); message = message || {}; let { name, content } = message; !isUndefined(name) && modules.setObjectName(name); if (!isUndefined(content)) { if (isObject(content)) { content = JSON.stringify(content); } modules.setContent(content); } return modules.getArrayData(); } /** * 待完善注释 */ encodeSetRTCOutData(data, type, message) { const modules = this._codec.getModule(PBName.RtcSetOutDataInput); modules.setTarget(type); if (!isArray(data)) { data = [data]; } forEach(data, (item, index) => { item.key = item.key ? item.key.toString() : item.key; item.value = item.value ? item.value.toString() : item.value; data[index] = item; }); modules.setValueInfo(data); message = message || {}; let { name, content } = message; !isUndefined(name) && modules.setObjectName(name); if (!isUndefined(content)) { if (isObject(content)) { content = JSON.stringify(content); } modules.setContent(content); } return modules.getArrayData(); } /** * 待完善注释 */ ecnodeGetRTCOutData(userIds) { const modules = this._codec.getModule(PBName.RtcQryUserOutDataInput); modules.setUserId(userIds); return modules.getArrayData(); } encodeSetRTCState(report) { const modules = this._codec.getModule(PBName.MCFollowInput); modules.setId(report); return modules.getArrayData(); } /** * 待完善注释 */ encodeGetRTCRoomInfo() { const modules = this._codec.getModule(PBName.RtcQueryListInput); modules.setOrder(2); return modules.getArrayData(); } /** * 待完善注释 */ encodeSetRTCUserInfo(key, value) { const modules = this._codec.getModule(PBName.RtcValueInfo); modules.setKey(key); modules.setValue(value); return modules.getArrayData(); } /** * 待完善注释 */ encodeRemoveRTCUserInfo(keys) { const modules = this._codec.getModule(PBName.RtcKeyDeleteInput); modules.setKey(keys); return modules.getArrayData(); } } /** * 数据通道接口,为 long-polling 与 websocket 提供公共抽象 */ class ADataChannel { constructor(type, _watcher) { this._watcher = _watcher; this.codec = new DataCodec(type); } } const getIdentifier = (messageId, identifier) => { if (messageId && identifier) { return identifier + '_' + messageId; } else if (messageId) { return messageId; } else { return Date.now(); // 若无 messageId、identifer, 直接返回时间戳, 避免返回空造成唯一标识重复 } }; /** * @description * 与 Server 交互的信令封装 */ /** * @description * 读数据处理基类 */ class BaseReader { constructor(header) { this.header = header; this._name = null; this.lengthSize = 0; this.messageId = 0; this.timestamp = 0; this.syncMsg = false; this.identifier = ''; // string + messageId 作为唯一标识, 目前用处: 方便 Pub、Query 回执定位对应 Promise, 且增加前缀避免 Pub、Query 回执错乱 } getIdentifier() { const { messageId, identifier } = this; return getIdentifier(messageId, identifier); } read(stream, length) { this.readMessage(stream, length); // return { stream, length } } readMessage(stream, length) { return { stream, length }; } } /** * @description * 写数据处理基类 */ class BaseWriter { constructor(headerType) { this.lengthSize = 0; this.messageId = 0; this.topic = ''; this.targetId = ''; this.identifier = ''; this._header = new Header(headerType, false, QOS.AT_MOST_ONCE, false); } getIdentifier() { const { messageId, identifier } = this; return getIdentifier(messageId, identifier); } write(stream) { const headerCode = this.getHeaderFlag(); stream.write(headerCode); // 写入 Header this.writeMessage(stream); } setHeaderQos(qos) { this._header.qos = qos; } getHeaderFlag() { return this._header.encode(); } getLengthSize() { return this.lengthSize; } getBufferData() { const stream = new RongStreamWriter(); this.write(stream); const val = stream.getBytesArray(); const binary = new Int8Array(val); return binary; } getCometData() { const data = this.data || {}; return JSON.stringify(data); } } /** * @description * 连接成功后服务端的回执 */ class ConnAckReader extends BaseReader { constructor() { super(...arguments); this._name = MessageName.CONN_ACK; this.status = null; // 链接状态 this.userId = null; // 用户 id // sessionId: string; this.timestamp = 0; } readMessage(stream, length) { stream.readByte(); // 去除 Header this.status = +stream.readByte(); if (length > ConnAckReader.MESSAGE_LENGTH) { this.userId = stream.readUTF(); stream.readUTF(); // 此处为取 sessionId, ws 未用到此值, 但也需执行, 否则读取后面数值时会不准 this.timestamp = stream.readLong(); } return { stream, length }; } } ConnAckReader.MESSAGE_LENGTH = 2; /** * @description * 服务端断开链接. 比如: 被踢 */ class DisconnectReader extends BaseReader { constructor() { super(...arguments); this._name = MessageName.DISCONNECT; this.status = 0; } readMessage(stream, length) { stream.readByte(); // (1)、此处未转换为链接状态码 (2)、2.0 代码限制了 status 为 0 - 5, 不在范围内则报错. 此处去掉此判断 this.status = +stream.readByte(); return { stream, length }; } } DisconnectReader.MESSAGE_LENGTH = 2; /** * @description * ping 请求 */ class PingReqWriter extends BaseWriter { constructor() { super(OperationType.PING_REQ); this._name = MessageName.PING_REQ; } writeMessage(stream) { } } /** * @description * ping 响应 */ class PingRespReader extends BaseReader { constructor(header) { super(header); this._name = MessageName.PING_RESP; } } class RetryableReader extends BaseReader { constructor() { super(...arguments); this.messageId = 0; } readMessage(stream, length) { const msgId = stream.readByte() * 256 + stream.readByte(); this.messageId = parseInt(msgId.toString(), 10); return { stream, length }; } } class RetryableWriter extends BaseWriter { constructor() { super(...arguments); this.messageId = 0; } writeMessage(stream) { const id = this.messageId; const lsb = id & 255; const msb = (id & 65280) >> 8; // 65280 -> 1111111100000000 stream.write(msb); stream.write(lsb); } } class PublishReader extends RetryableReader { constructor() { super(...arguments); this._name = MessageName.PUBLISH; this.topic = ''; this.targetId = ''; this.syncMsg = false; this.identifier = IDENTIFIER.PUB; } readMessage(stream, length) { // let pos = 6; this.date = stream.readInt(); this.topic = stream.readUTF(); // pos += BinaryHelper.writeUTF(this.topic).length; this.targetId = stream.readUTF(); // pos += BinaryHelper.writeUTF(this.targetId).length; // RetryableReader.prototype.readMessage.apply(this, arguments) super.readMessage(stream, length); // this.data = new Array(msgLength - pos); this.data = stream.readAll(); return { stream, length }; } } /** * @description * 发消息使用 */ class PublishWriter extends RetryableWriter { constructor(topic, data, targetId) { super(OperationType.PUBLISH); this._name = MessageName.PUBLISH; this.syncMsg = false; this.identifier = IDENTIFIER.PUB; this.topic = topic; this.data = isString(data) ? BinaryHelper.writeUTF(data) : data; this.targetId = targetId; } writeMessage(stream) { stream.writeUTF(this.topic); stream.writeUTF(this.targetId); super.writeMessage(stream); stream.write(this.data); } } /** * @description * 发消息, Server 给的 Ack 回执 */ class PubAckReader extends RetryableReader { constructor() { super(...arguments); this._name = MessageName.PUB_ACK; this.status = 0; this.date = 0; this.millisecond = 0; this.messageUId = ''; this.timestamp = 0; this.identifier = IDENTIFIER.PUB; this.topic = ''; this.targetId = ''; } readMessage(stream, length) { super.readMessage(stream, length); this.date = stream.readInt(); this.status = stream.readByte() * 256 + stream.readByte(); this.millisecond = stream.readByte() * 256 + stream.readByte(); this.timestamp = this.date * 1000 + this.millisecond; this.messageUId = stream.readUTF(); return { stream, length }; } } /** * @description * Server 下发 Pub, Web 给 Server 发送回执 */ class PubAckWriter extends RetryableWriter { constructor(messageId) { super(OperationType.PUB_ACK); this._name = MessageName.PUB_ACK; this.status = 0; this.date = 0; this.millisecond = 0; this.messageUId = ''; this.timestamp = 0; this.messageId = messageId; } writeMessage(stream) { super.writeMessage(stream); } } /** * @description * Web 主动查询 */ class QueryWriter extends RetryableWriter { constructor(topic, data, targetId) { super(OperationType.QUERY); this.name = MessageName.QUERY; this.identifier = IDENTIFIER.QUERY; this.topic = topic; this.data = isString(data) ? BinaryHelper.writeUTF(data) : data; this.targetId = targetId; } writeMessage(stream) { stream.writeUTF(this.topic); stream.writeUTF(this.targetId); // RetryableWriter.prototype.writeMessage.call(this, stream) super.writeMessage(stream); stream.write(this.data); } } /** * @description * Server 发送 Query, Web 给 Server 的回执 */ class QueryConWriter extends RetryableWriter { constructor(messageId) { super(OperationType.QUERY_CONFIRM); this._name = MessageName.QUERY_CON; this.messageId = messageId; } } /** * @description * Server 对 Web 查询操作的回执 */ class QueryAckReader extends RetryableReader { constructor() { super(...arguments); this._name = MessageName.QUERY_ACK; this.status = 0; this.identifier = IDENTIFIER.QUERY; this.topic = ''; this.targetId = ''; } readMessage(stream, length) { // RetryableReader.prototype.readMessage.call(this, stream) super.readMessage(stream, length); this.date = stream.readInt(); this.status = stream.readByte() * 256 + stream.readByte(); this.data = stream.readAll(); // if (msgLength > 0) { // this.data = new Array(msgLength - 8); // this.data = stream.readAll(); // } return { stream, length }; } } const getReaderByHeader = (header) => { const type = header.type; let msg; switch (type) { case OperationType.CONN_ACK: msg = new ConnAckReader(header); break; case OperationType.PUBLISH: msg = new PublishReader(header); msg.syncMsg = header.syncMsg; break; case OperationType.PUB_ACK: msg = new PubAckReader(header); break; case OperationType.QUERY_ACK: msg = new QueryAckReader(header); break; case OperationType.SUB_ACK: case OperationType.UNSUB_ACK: case OperationType.PING_RESP: msg = new PingRespReader(header); break; case OperationType.DISCONNECT: msg = new DisconnectReader(header); break; default: msg = new BaseReader(header); logger.error('No support for deserializing ' + type + ' messages'); } return msg; }; /** * 解析 websocket 收到的数据 ArrayBuffer 数据 * @param {ArrayBuffer} data server 通过 webscoekt 传送的所有数据 */ const readWSBuffer = (data) => { const arr = new Uint8Array(data); const stream = new RongStreamReader(arr); const flags = stream.readByte(); const header = new Header(flags); const msg = getReaderByHeader(header); msg.read(stream, arr.length - 1); return msg; }; const readCometData = (data) => { const flags = data.headerCode; const header = new Header(flags); const msg = getReaderByHeader(header); // utils.forEach(data, (item: any, key: string) => { // if (key in msg) { // msg[key] = item; // } // }); for (const key in data) { // if (key in msg) { msg[key] = data[key]; // } } return msg; }; /** * CMP/Comet 服务连接应答码 */ const ConnectResultCode = { /** * 连接成功 */ ACCEPTED: 0, /** * 协议版本不匹配 * @description 暂未使用 */ UNACCEPTABLE_PROTOCOL_VERSION: 1, /** * 客户端(移动端 TCP 连接建立时)`info` 字段格式错误 * @description 格式:`{平台类型}-{设备信息}-{sdk版本}`。 * 其中设备信息为:{手机类型}{手机型号}{网络类型,4G/WIFI}{运营商标识, 移动/电信/联通} */ IDENTIFIER_REJECTED: 2, /** * 不支持的平台类型,一般小程序或 PC 未开通 */ SERVER_UNAVAILABLE: 3, /** * Token无法解析,或Token已过期 */ TOKEN_INCORRECT: 4, /** * 防黑产规则相关应答 */ NOT_AUTHORIZED: 5, /** * 服务重定向,一般服务扩缩容时,落点已经改变,此时 userId 链接到旧的节点时,会触发该错误。 * 客户端收到该应答后须重新访问导航,重新获取 CMP 地址 */ REDIRECT: 6, /** * 暂未使用 */ PACKAGE_ERROR: 7, /** * 该 AppKey 已经封禁或删除 */ APP_BLOCK_OR_DELETE: 8, /** * 该用户 ID 已经被封禁 */ BLOCK: 9, /** * Token 已过期,暂未使用 */ TOKEN_EXPIRE: 10, /** * Token 中携带 deviceId 时,检测 Token 中 deviceId 与链接设备 deviceId 不一致 */ DEVICE_ERROR: 11, /** * Web 端设置安全域名后,连接端域名不在安全域名范围内 */ HOSTNAME_ERROR: 12, /** * 开启`禁止把已在线客户端踢下线`开关后,该错误码标识已有同类型端在线,禁止链接 */ HASOHTERSAMECLIENTONLINE: 13 }; /** * 连接状态 */ var ConnectionStatus; (function (ConnectionStatus) { /** * 连接成功。 */ ConnectionStatus[ConnectionStatus["CONNECTED"] = 0] = "CONNECTED"; /** * 连接中。 */ ConnectionStatus[ConnectionStatus["CONNECTING"] = 1] = "CONNECTING"; /** * 正常断开连接。 */ ConnectionStatus[ConnectionStatus["DISCONNECTED"] = 2] = "DISCONNECTED"; /** * 网络不可用。 */ ConnectionStatus[ConnectionStatus["NETWORK_UNAVAILABLE"] = 3] = "NETWORK_UNAVAILABLE"; /** * 连接关闭。 */ ConnectionStatus[ConnectionStatus["CONNECTION_CLOSED"] = 4] = "CONNECTION_CLOSED"; /** * 用户账户在其他设备登录,本机会被踢掉线。 */ ConnectionStatus[ConnectionStatus["KICKED_OFFLINE_BY_OTHER_CLIENT"] = 6] = "KICKED_OFFLINE_BY_OTHER_CLIENT"; /** * websocket 连接失败 */ ConnectionStatus[ConnectionStatus["WEBSOCKET_UNAVAILABLE"] = 7] = "WEBSOCKET_UNAVAILABLE"; /** * websocket 报错 */ ConnectionStatus[ConnectionStatus["WEBSOCKET_ERROR"] = 8] = "WEBSOCKET_ERROR"; /** * 用户被封禁 */ ConnectionStatus[ConnectionStatus["BLOCKED"] = 9] = "BLOCKED"; /** * 域名错误 */ ConnectionStatus[ConnectionStatus["DOMAIN_INCORRECT"] = 12] = "DOMAIN_INCORRECT"; /** * appkey 不正确 */ ConnectionStatus[ConnectionStatus["APPKEY_IS_FAKE"] = 20] = "APPKEY_IS_FAKE"; /** * 互踢次数过多(`count > 5`),此时可能出现:在其它他设备登陆有 reconnect 逻辑 */ ConnectionStatus[ConnectionStatus["ULTRALIMIT"] = 1101] = "ULTRALIMIT"; /** * 开始请求导航 */ ConnectionStatus[ConnectionStatus["REQUEST_NAVI"] = 201] = "REQUEST_NAVI"; /** * 请求导航结束 */ ConnectionStatus[ConnectionStatus["RESPONSE_NAVI"] = 202] = "RESPONSE_NAVI"; /** * 请求导航失败 */ ConnectionStatus[ConnectionStatus["RESPONSE_NAVI_ERROR"] = 203] = "RESPONSE_NAVI_ERROR"; /** * 请求导航超时 */ ConnectionStatus[ConnectionStatus["RESPONSE_NAVI_TIMEOUT"] = 204] = "RESPONSE_NAVI_TIMEOUT"; })(ConnectionStatus || (ConnectionStatus = {})); var ConnectionStatus$1 = ConnectionStatus; const randomNum = (min, max) => { return min + Math.floor(Math.random() * (max - min)); }; const getUUID = () => { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => { const r = Math.random() * 16 | 0; const v = c === 'x' ? r : (r & 0x3 | 0x8); return v.toString(16); }); }; /* eslint-disable camelcase */ /** * 信令名 */ var Topic; (function (Topic) { /** 发送消息进入离线消息存储,接收者不在线时,可转推送 */ Topic[Topic["ppMsgP"] = 1] = "ppMsgP"; /** 发送消息进入离线消息存储,接收者不在线时,不转推送 */ Topic[Topic["ppMsgN"] = 2] = "ppMsgN"; /** 发送消息不进入离线存储,用户在线时直发到接收者,不在线时消息丢弃,不转推送 */ Topic[Topic["ppMsgS"] = 3] = "ppMsgS"; Topic[Topic["pgMsgP"] = 4] = "pgMsgP"; Topic[Topic["chatMsg"] = 5] = "chatMsg"; Topic[Topic["pcMsgP"] = 6] = "pcMsgP"; Topic[Topic["qryPMsg"] = 7] = "qryPMsg"; Topic[Topic["qryGMsg"] = 8] = "qryGMsg"; Topic[Topic["qryCHMsg"] = 9] = "qryCHMsg"; Topic[Topic["qryCMsg"] = 10] = "qryCMsg"; Topic[Topic["qrySMsg"] = 11] = "qrySMsg"; Topic[Topic["recallMsg"] = 12] = "recallMsg"; Topic[Topic["prMsgS"] = 13] = "prMsgS"; /** 消息通知拉取 */ Topic[Topic["s_ntf"] = 14] = "s_ntf"; /** 服务直发消息 */ Topic[Topic["s_msg"] = 15] = "s_msg"; /** * 状态同步 * @todo 需确定同步哪些状态 */ Topic[Topic["s_stat"] = 16] = "s_stat"; /** 服务端通知:聊天室 kv 、会话状态 */ Topic[Topic["s_cmd"] = 17] = "s_cmd"; /** 实时配置变更通知 */ Topic[Topic["s_us"] = 18] = "s_us"; /** 拉取实时配置 */ Topic[Topic["pullUS"] = 19] = "pullUS"; Topic[Topic["pgMsgS"] = 20] = "pgMsgS"; Topic[Topic["chatMsgS"] = 21] = "chatMsgS"; Topic[Topic["qrySessionsAtt"] = 22] = "qrySessionsAtt"; Topic[Topic["pullMsg"] = 23] = "pullMsg"; Topic[Topic["qrySessions"] = 24] = "qrySessions"; Topic[Topic["delSessions"] = 25] = "delSessions"; Topic[Topic["delMsg"] = 26] = "delMsg"; Topic[Topic["updRRTime"] = 27] = "updRRTime"; /** 拉取聊天室消息 */ Topic[Topic["chrmPull"] = 28] = "chrmPull"; Topic[Topic["joinChrm"] = 29] = "joinChrm"; Topic[Topic["joinChrmR"] = 30] = "joinChrmR"; Topic[Topic["exitChrm"] = 31] = "exitChrm"; Topic[Topic["queryChrmI"] = 32] = "queryChrmI"; Topic[Topic["setKV"] = 33] = "setKV"; Topic[Topic["delKV"] = 34] = "delKV"; /** 拉取聊天室 KV 存储 */ Topic[Topic["pullKV"] = 35] = "pullKV"; Topic[Topic["qryRelation"] = 36] = "qryRelation"; Topic[Topic["delRelation"] = 37] = "delRelation"; Topic[Topic["pullSeAtts"] = 38] = "pullSeAtts"; Topic[Topic["setSeAtt"] = 39] = "setSeAtt"; Topic[Topic["qnTkn"] = 40] = "qnTkn"; Topic[Topic["qnUrl"] = 41] = "qnUrl"; Topic[Topic["aliUrl"] = 42] = "aliUrl"; Topic[Topic["cleanPMsg"] = 43] = "cleanPMsg"; Topic[Topic["cleanGMsg"] = 44] = "cleanGMsg"; Topic[Topic["cleanCMsg"] = 45] = "cleanCMsg"; Topic[Topic["cleanSMsg"] = 46] = "cleanSMsg"; Topic[Topic["rtcRJoin_data"] = 47] = "rtcRJoin_data"; Topic[Topic["rtcRExit"] = 48] = "rtcRExit"; Topic[Topic["rtcPing"] = 49] = "rtcPing"; Topic[Topic["rtcSetData"] = 50] = "rtcSetData"; /** 全量 URI 资源变更 */ Topic[Topic["userSetData"] = 51] = "userSetData"; Topic[Topic["rtcQryData"] = 52] = "rtcQryData"; Topic[Topic["rtcDelData"] = 53] = "rtcDelData"; Topic[Topic["rtcSetOutData"] = 54] = "rtcSetOutData"; Topic[Topic["rtcQryUserOutData"] = 55] = "rtcQryUserOutData"; Topic[Topic["rtcToken"] = 56] = "rtcToken"; Topic[Topic["rtcUserState"] = 57] = "rtcUserState"; Topic[Topic["rtcRInfo"] = 58] = "rtcRInfo"; Topic[Topic["rtcUData"] = 59] = "rtcUData"; Topic[Topic["rtcUPut"] = 60] = "rtcUPut"; Topic[Topic["rtcUDel"] = 61] = "rtcUDel"; Topic[Topic["rtcUList"] = 62] = "rtcUList"; })(Topic || (Topic = {})); var Topic$1 = Topic; /** * 通过 /ping 接口确定目标导航是否可用,并根据响应速度排序 * @todo 需确认该嗅探的必要性,并确定是否需要删除 * @param hosts * @param protocol * @param runtime */ const getValidHosts = (hosts, protocol, runtime) => __awaiter(void 0, void 0, void 0, function* () { // 根据 /ping?r= 的响应速度对 hosts 进行排序响应速度排序 let pingRes = yield Promise.all(hosts.map((host) => __awaiter(void 0, void 0, void 0, function* () { const now = Date.now(); const url = `${protocol}://${host}/ping?r=${randomNum(1000, 9999)}`; const res = yield runtime.httpReq({ url, timeout: PING_REQ_TIMEOUT }); return { status: res.status, host, cost: Date.now() - now }; }))); // 清理无效地址 pingRes = pingRes.filter(item => item.status === 200); // 按响应时间排序 if (pingRes.length > 1) { pingRes = pingRes.sort((a, b) => a.cost - b.cost); } return pingRes.map(item => item.host); }); const formatWSUrl = (protocol, host, appkey, token, runtime, apiVersion, pid) => { return `${protocol}://${host}/websocket?appId=${appkey}&token=${encodeURIComponent(token)}&sdkVer=${apiVersion}&pid=${pid}&apiVer=${runtime.isFromUniapp ? 'uniapp' : 'normal'}${runtime.connectPlatform ? '&platform=' + runtime.connectPlatform : ''}`; }; const formatResolveKey = (messageId, identifier) => [messageId, identifier].join('-'); const isStatusMessage = (topic) => { return [Topic$1.ppMsgS, Topic$1.pgMsgS, Topic$1.chatMsgS].map(item => Topic$1[item]).indexOf(topic) >= 0; }; const sendWSData = (writer, socket) => { if (!(writer instanceof PingReqWriter)) { logger.debug('Websocket ==>', writer); } const binary = writer.getBufferData(); socket.send(binary.buffer); }; /** * @todo 迁移中的 DataCodec 模块导致数据通道不够独立,与 xhr-polling 通信可能会有耦合,后续需解耦 * @description * 1. 基于 WebSocket 协议建立数据通道,实现数据收发 * 2. 基于 Protobuf 进行数据编解码 */ class WebSocketChannel extends ADataChannel { // 为避免 Circular dependency,此处 runtime 通过参数传入而非全局获取 constructor(_runtime, watcher) { super('websocket', watcher); this._runtime = _runtime; this._socket = null; /** * 本端发送消息时等待接收 PubAck 的 Promise.resolve 函数 */ this._messageIds = {}; /** * 接收多端同步消息时,等待 PubAck 的 Promise.resolve 函数 */ this._syncMessageIds = {}; /** * 当前累计心跳超时次数 */ this._failedCount = 0; /** * 允许连续 PING 超时次数,次数内不主动关闭连接 */ this.ALLOW_FAILED_TIMES = 4; /** * 有效值 0 - 65535,超出 65535 位数超长溢出 */ this._idCount = 0; this._generateMessageId = () => { if (this._idCount >= 65535) { this._idCount = 0; } return ++this._idCount; }; } /** * 建立 websocket 连接 * @param appkey * @param token * @param hosts * @param protocol * @param apiVersion - apiVersion 需符合 `/\d+(\.\d+){2}/` 规则 */ connect(appkey, token, hosts, protocol, apiVersion) { return __awaiter(this, void 0, void 0, function* () { // 祛除预发布包中的预发布标签,取真实版本号 apiVersion = matchVersion(apiVersion); // 通知连接中 this._watcher.status(ConnectionStatus$1.CONNECTING); // 检索有效地址 const validHosts = yield getValidHosts(hosts, protocol, this._runtime); if (validHosts.length === 0) { logger.error('No valid websocket server hosts!'); return ErrorCode$1.RC_SOCKET_NOT_CREATED; } // 确定连接协议:http -> ws, https -> wss const wsProtocol = protocol.replace('http', 'ws'); // 逐个尝试建立 websocket 连接 for (let i = 0, len = validHosts.length; i < len; i += 1) { const url = formatWSUrl(wsProtocol, validHosts[i], appkey, token, this._runtime, apiVersion); // 创建 socket,若超时一定时间未收到 ConnAck 确认,则视为连接超时 const socket = this._runtime.createWebSocket(url); // 服务连接非主动断开,尝试重连 const disconnected = (code) => { if (this._socket === socket) { this._socket = null; this._watcher.status(code); } }; // 等待连接结果 const code = yield new Promise((resolve) => { socket.onMessage((data) => { if (Object.prototype.toString.call(data) !== '[object ArrayBuffer]') { logger.error('Socket received invalid data:', data); return; } const signal = readWSBuffer(data); // Ping 响应 if (signal instanceof PingRespReader && this._pingResolve) { this._pingResolve(ErrorCode$1.SUCCESS); this._pingResolve = undefined; return; } logger.debug('Websocket <==', signal); // 连接回执 if (signal instanceof ConnAckReader) { if (signal.status !== ConnectResultCode.ACCEPTED) { logger.error('Websocket connAck status:', signal.status); resolve(signal.status); return; } this.connectedTime = signal.timestamp; this.userId = signal.userId || ''; resolve(ErrorCode$1.SUCCESS); return; } // 连接状态断开 if (signal instanceof DisconnectReader) { // 收到 Server 通知己方被踢, 抛出至状态监听 // 1 为被其他端挤下线 // 2 为用户封禁,其他正常向上抛出给业务层 const { status } = signal; const connStatus = status === 1 ? ConnectionStatus$1.KICKED_OFFLINE_BY_OTHER_CLIENT : (status === 2 ? ConnectionStatus$1.BLOCKED : status); this._watcher.status(connStatus); return; } // 非连接信令处理 this._onReceiveSignal(signal); }); socket.onClose((code, reason) => { logger.warn('websocket closed! code:', code, 'reason:', reason); disconnected(ConnectionStatus$1.CONNECTION_CLOSED); resolve(code); }); socket.onError((error) => { logger.error('websocket error!', error); disconnected(ConnectionStatus$1.WEBSOCKET_ERROR); resolve(ErrorCode$1.NETWORK_ERROR); }); socket.onOpen(() => logger.debug('websocket open =>', url)); // ConnAck 超时 timerSetTimeout(() => { resolve(ErrorCode$1.TIMEOUT); }, WEB_SOCKET_TIMEOUT); }); if (code === ErrorCode$1.SUCCESS) { this._socket = socket; // 启动定时心跳 this._checkAlive(); // 通知上层连接成功 this._watcher.status(ConnectionStatus$1.CONNECTED); return code; } socket.close(); } return ErrorCode$1.RC_NET_UNAVAILABLE; }); } _checkAlive() { var _a; return __awaiter(this, void 0, void 0, function* () { if (!this._socket) { // 连接已中断,停止发 Ping return; } this.sendOnly(new PingReqWriter()); // 等待响应 const code = yield new Promise((resolve) => { this._pingResolve = resolve; setTimeout(() => { this._pingResolve = undefined; resolve(ErrorCode$1.TIMEOUT); }, IM_SIGNAL_TIMEOUT); }); // 响应超时,尝试关闭连接 if (code !== ErrorCode$1.SUCCESS && ++this._failedCount >= this.ALLOW_FAILED_TIMES) { (_a = this._socket) === null || _a === void 0 ? void 0 : _a.close(); return; } this._failedCount = 0; // 重新定时任务 setTimeout(() => this._checkAlive(), IM_PING_INTERVAL_TIME); }); } _onReceiveSignal(signal) { return __awaiter(this, void 0, void 0, function* () { const { messageId, identifier } = signal; // 检查是否为 Ack, 如果是, 则处理回执 const isQosNeedAck = signal.header && signal.header.qos !== QOS.AT_MOST_ONCE; if (isQosNeedAck) { // Pub 回执 if (signal instanceof PublishReader && !signal.syncMsg) { this.sendOnly(new PubAckWriter(messageId)); } // qry 回执 if (signal instanceof QueryAckReader) { this.sendOnly(new QueryConWriter(messageId)); } } const key = formatResolveKey(messageId, identifier); // 处理 pubAck、queryAck 回执 if (messageId > 0) { const resolve = this._messageIds[key]; resolve && resolve(signal); // 多端同步消息的 pubAck this._syncMessageIds[key] && this._syncMessageIds[key](signal); } // PublishReader 处理 if (signal instanceof PublishReader) { const { syncMsg, topic } = signal; // 非同步消息或者是状态消息(ppMsgS,pgMsgS,chatMsgS),则直接抛出到上层 if (!syncMsg || isStatusMessage(topic)) { this._watcher.signal(signal); return; } // 多端同步消息息需等待 CMP 发送的 PubAck(Comet 不发) const ack = yield new Promise(resolve => { this._syncMessageIds[key] = resolve; }); delete this._syncMessageIds[key]; this._watcher.signal(signal, ack); } }); } sendOnly(writer) { if (this._socket) { sendWSData(writer, this._socket); } } send(writer, respPBName, option, timeout = IM_SIGNAL_TIMEOUT) { return __awaiter(this, void 0, void 0, function* () { if (this._socket) { const messageId = this._generateMessageId(); writer.messageId = messageId; const identifier = writer.identifier; sendWSData(writer, this._socket); // 等待响应结果 const respSignal = yield new Promise((resolve) => { const key = formatResolveKey(messageId, identifier); this._messageIds[key] = resolve; setTimeout(() => { delete this._messageIds[key]; resolve(); // 无值认为 timeout 超时 }, timeout); }); if (!respSignal) { return { code: ErrorCode$1.TIMEOUT }; } if (respSignal.status !== 0) { return { code: respSignal.status }; } const data = respPBName ? this.codec.decodeByPBName(respSignal.data, respPBName, option) : respSignal; return { code: ErrorCode$1.SUCCESS, data }; } return { code: ErrorCode$1.RC_NET_CHANNEL_INVALID }; }); } close() { if (this._socket) { this._socket.close(); this._socket = null; this._watcher.status(ConnectionStatus$1.DISCONNECTED); } } } (function (HttpMethod) { HttpMethod["GET"] = "GET"; HttpMethod["POST"] = "POST"; })(exports.HttpMethod || (exports.HttpMethod = {})); const isValidJSON = (jsonStr) => { if (isObject(jsonStr)) { return true; } let isValid = false; try { const obj = JSON.parse(jsonStr); const str = JSON.stringify(obj); isValid = str === jsonStr; } catch (e) { isValid = false; } return isValid; }; class CometChannel extends ADataChannel { constructor(_runtime, watcher) { super('comet', watcher); this._runtime = _runtime; this._messageIds = {}; this._syncMessageIds = {}; this._idCount = 0; this._generateMessageId = () => { return ++this._idCount; }; this._pid = encodeURIComponent(new Date().getTime() + Math.random() + ''); } /** * 长轮询结果处理 * @param data */ handleCometRes(res) { if (res.status !== 200 && res.status !== 202) { return false; } const data = isString(res.data) ? JSON.parse(res.data) : res.data; if (!data) { logger.error('received data is not a validJson', data); return false; } if (!isArray(data)) { return true; } forEach(data, (item) => __awaiter(this, void 0, void 0, function* () { const { sessionid } = item; if (sessionid) { this._sessionid = sessionid; } const signal = readCometData(item); const { messageId, _header, status, identifier } = signal; const isQosNeedAck = _header && _header.qos !== QOS.AT_MOST_ONCE; const key = formatResolveKey(messageId, identifier); // 处理 pubAck、queryAck 回执 if (messageId && signal.getIdentifier) { const resolve = this._messageIds[key]; resolve && resolve(signal); // 多端同步消息的 pubAck this._syncMessageIds[key] && this._syncMessageIds[key](signal); } // 是否需要发回执 if (isQosNeedAck) { if (signal instanceof PublishReader && !signal.syncMsg) { const writer = new PubAckWriter(messageId); this.sendOnly(writer); } if (signal instanceof QueryAckReader) { const writer = new QueryConWriter(messageId); this.sendOnly(writer); } } // 连接状态断开 if (signal instanceof DisconnectReader) { const connStatus = status === 1 ? ConnectionStatus$1.KICKED_OFFLINE_BY_OTHER_CLIENT : (status === 2 ? ConnectionStatus$1.BLOCKED : status); this._watcher.status(connStatus); } // 处理 publish if (signal instanceof PublishReader) { const { syncMsg, topic } = signal; // 非同步消息或者是状态消息(ppMsgS,pgMsgS,chatMsgS),则直接抛出到上层 if (!syncMsg || isStatusMessage(topic)) { this._watcher.signal(signal); return false; } // 多端同步消息需等待 CMP 发送的 PubAck const ack = yield new Promise(resolve => { this._syncMessageIds[key] = resolve; }); delete this._syncMessageIds[key]; this._watcher.signal(signal, ack); } })); return true; } /** * 长轮询心跳 */ _startPullSignal(protocol) { return __awaiter(this, void 0, void 0, function* () { const timestamp = new Date().getTime(); const url = `${protocol}://${this._domain}/pullmsg.js?sessionid=${this._sessionid}×trap=${timestamp}&pid=${this._pid}`; const res = yield this._runtime.httpReq({ url, body: { pid: this._pid }, timeout: IM_COMET_PULLMSG_TIMEOUT }); const isSuccess = this.handleCometRes(res); if (!this._isDisconnected) { if (isSuccess) { this._startPullSignal(protocol); } else { this._watcher.status(ConnectionStatus$1.NETWORK_UNAVAILABLE); this.close(); } } }); } connect(appkey, token, hosts, protocol, apiVersion) { return __awaiter(this, void 0, void 0, function* () { // 祛除预发布包中的预发布标签,取真实版本号 apiVersion = matchVersion(apiVersion); this._protocol = protocol; this._isDisconnected = false; this._watcher.status(ConnectionStatus$1.CONNECTING); const validHosts = yield getValidHosts(hosts, protocol, this._runtime); if (validHosts.length === 0) { logger.error('No valid comet server hosts!'); return ErrorCode$1.RC_SOCKET_NOT_CREATED; } /** * 连接结果处理 */ const handleConnectRes = (res) => { if (res.status !== 200 && res.status !== 202) { return false; } if (res.data) { if (!isValidJSON(res.data)) { logger.error('received data is not a validJson', res.data); return false; } return isObject(res.data) ? res.data : JSON.parse(res.data); } return false; }; for (let i = 0, len = validHosts.length; i < len; i += 1) { const url = formatWSUrl(protocol, validHosts[i], appkey, token, this._runtime, apiVersion, this._pid); const res = yield this._runtime.httpReq({ url, body: { pid: this._pid }, timeout: WEB_SOCKET_TIMEOUT }); const response = handleConnectRes(res); this._domain = validHosts[i]; if (response && response.status === 0) { this._watcher.status(ConnectionStatus$1.CONNECTED); this._sessionid = response.sessionid; this._startPullSignal(protocol); this.userId = response.userId; this.connectedTime = response.timestamp; return response.status; } } return ErrorCode$1.RC_NET_UNAVAILABLE; }); } sendCometData(writer, timeout = IM_SIGNAL_TIMEOUT) { return __awaiter(this, void 0, void 0, function* () { const { _domain, _sessionid, _pid } = this; const { messageId, topic, targetId, identifier } = writer; const headerCode = writer.getHeaderFlag(); let url; if (topic) { url = `${this._protocol}://${_domain}/websocket?messageid=${messageId}&header=${headerCode}&sessionid=${_sessionid}&topic=${topic}&targetid=${targetId}&pid=${_pid}`; } else { url = `${this._protocol}://${_domain}/websocket?messageid=${messageId}&header=${headerCode}&sessionid=${_sessionid}&pid=${_pid}`; } const res = yield this._runtime.httpReq({ url, method: exports.HttpMethod.POST, body: writer.getCometData() }); this.handleCometRes(res); }); } sendOnly(writer) { this.sendCometData(writer); } send(writer, respPBName, option, timeout = IM_SIGNAL_TIMEOUT) { return __awaiter(this, void 0, void 0, function* () { const messageId = this._generateMessageId(); writer.messageId = messageId; this.sendCometData(writer); const { identifier } = writer; const respSignal = yield new Promise((resolve) => { const key = formatResolveKey(messageId, identifier); this._messageIds[key] = resolve; setTimeout(() => { delete this._messageIds[key]; resolve(); // 无值认为 timeout 超时 }, timeout); }); if (!respSignal) { return { code: ErrorCode$1.TIMEOUT }; } if (respSignal.status !== 0) { return { code: respSignal.status }; } const data = respPBName ? this.codec.decodeByPBName(respSignal.data, respPBName, option) : respSignal; return { code: ErrorCode$1.SUCCESS, data }; }); } close() { this._isDisconnected = true; this._watcher.status(ConnectionStatus$1.DISCONNECTED); } } const getKey = (appkey, token) => { return ['navi', appkey, token].join('_'); }; const getNaviInfoFromCache = (appkey, token, storage) => { const key = getKey(appkey, token); const jsonStr = storage.getItem(key); if (!jsonStr) { return null; } let data; try { data = JSON.parse(jsonStr); } catch (err) { // 缓存数据被篡改,清空缓存 storage.removeItem(key); return null; } // 缓存超时 if (Date.now() - data.timestamp >= NAVI_CACHE_DURATION) { storage.removeItem(key); return null; } return data.naviInfo; }; const setNaviInfo2Cache = (appkey, token, naviInfo, storage) => { const key = getKey(appkey, token); const data = { naviInfo, timestamp: Date.now() }; storage.setItem(key, JSON.stringify(data)); }; const clearCache = (appkey, token, storage) => { storage.removeItem(getKey(appkey, token)); }; class Navi { constructor(_runtime, _appkey, /** * 导航地址,该数据中不包含 token 中的动态导航 */ _navigators, _customCMP = [], _apiVersion, _connectType) { this._runtime = _runtime; this._appkey = _appkey; this._navigators = _navigators; this._customCMP = _customCMP; this._apiVersion = _apiVersion; this._connectType = _connectType; this._apiVersion = matchVersion(this._apiVersion); } _formatNaviUrl(url, token, appkey, jsonpFunc, connectType) { const path = this._runtime.isSupportSocket() && (connectType === 'websocket') ? 'navi' : 'cometnavi'; const tmpUrl = `${url}/${path}.js?appId=${appkey}&token=${encodeURIComponent(token)}&callBack=${jsonpFunc}&v=${this._apiVersion}&r=${Date.now()}`; return tmpUrl; } _reqNavi(uris, appkey, token, connectType) { return __awaiter(this, void 0, void 0, function* () { const jsonpFunc = 'getServerEndpoint'; for (let i = 0, len = uris.length; i < len; i += 1) { const url = this._formatNaviUrl(uris[i], token, appkey, jsonpFunc, connectType); logger.debug(`req navi => ${url}`); const res = yield this._runtime.httpReq({ url, timeout: NAVI_REQ_TIMEOUT }); if (res.status !== 200) { continue; } try { // 返回结果中,私有云无 ; 号,公有云有分号 // 解析 res 数据,解析成功则返回 naviInfo 数据 const jsonStr = res.data.replace(`${jsonpFunc}(`, '').replace(/\);?$/, ''); const naviInfo = JSON.parse(jsonStr); // 补充导航数据请求使用的协议 const protocol = /^https/.test(url) ? 'https' : 'http'; naviInfo.protocol = protocol; return naviInfo; } catch (err) { logger.error('parse navi err =>', err); } } return null; }); } /** * 获取导航数据 * @param force 是否强制重新获取并清空缓存数据 */ getInfo(token, dynamicUris, force, isCppMode) { var _a; return __awaiter(this, void 0, void 0, function* () { // C++ 协议栈不请求导航 if (isCppMode) { return null; } // TODO: 微信小程序直接返值,不需请求导航 if (!this._runtime.useNavi) { let connectUrl; if (this._runtime.isSupportSocket()) { connectUrl = MINI_SOCKET_CONNECT_URIS.join(','); } else { connectUrl = MINI_COMET_CONNECT_URIS.join(','); } const naviInfo = { code: 200, protocol: 'https', server: '', voipCallInfo: '', kvStorage: 0, openHttpDNS: false, historyMsg: false, chatroomMsg: false, uploadServer: 'https://upload.qiniup.com', bosAddr: 'https://gz.bcebos.com', location: '', monitor: 0, joinMChrm: false, openMp: 0, openUS: 0, grpMsgLimit: 0, isFormatted: 0, gifSize: 2048, logSwitch: 0, logPolicy: '', compDays: 0, msgAck: '', activeServer: '', qnAddr: '', extkitSwitch: 0, alone: false, voipServer: '', offlinelogserver: '', backupServer: ((_a = this._customCMP) === null || _a === void 0 ? void 0 : _a.length) ? this._customCMP.join(',') : connectUrl }; setNaviInfo2Cache(this._appkey, token, naviInfo, this._runtime.localStorage); return naviInfo; } // 判断是否需要重新获取导航数据,是则清空缓存数据 if (force) { this._clear(token); } // 判断是否有有效缓存数据 let naviInfo = getNaviInfoFromCache(this._appkey, token, this._runtime.localStorage); if (naviInfo) { return naviInfo; } const uris = this._navigators.slice(); dynamicUris.length && dynamicUris.forEach(uri => { uris.indexOf(uri) < 0 && uris.unshift(uri); }); // 串行请求,直到获取到导航数据或所有请求结束 // TODO: 考虑是否可改为并行请求,串行请求时间过长 naviInfo = yield this._reqNavi(uris, this._appkey, token, this._connectType); if (naviInfo) { setNaviInfo2Cache(this._appkey, token, naviInfo, this._runtime.localStorage); return naviInfo; } // TODO: 所有请求已失败,公有云需要内置导航数据 return naviInfo; }); } getInfoFromCache(token) { return getNaviInfoFromCache(this._appkey, token, this._runtime.localStorage); } /** * 清空导航数据:内存数据、缓存数据 */ _clear(token) { clearCache(this._appkey, token, this._runtime.localStorage); } } /** * 引擎定义 */ class AEngine { /** * 引擎初始化 * @param _appkey */ constructor(runtime, _appkey, _watcher, _apiVersion, _options) { this.runtime = runtime; this._appkey = _appkey; this._watcher = _watcher; this._apiVersion = _apiVersion; this._options = _options; /** * 当前用户 Id */ this.currentUserId = ''; /** * 连接时间 */ this.connectedTime = 0; } } const OUTBOX_KEY = 'outbox'; const INBOX_KEY = 'inbox'; const generateKey = (prefix, appkey, userId) => { return [prefix, appkey, userId].join('_'); }; /** * 用于维护用户的收件箱、发件箱时间 */ class Letterbox { constructor(_runtime, _appkey) { this._runtime = _runtime; this._appkey = _appkey; // 需要在内存维护一份时间戳数据,以避免同浏览器多标签页下多端拉取消息时共享时间戳 this._inboxTime = 0; this._outboxTime = 0; } /** * 更新收件箱时间 * @param timestamp * @param userId */ setInboxTime(timestamp, userId) { if (this._inboxTime > timestamp) { return; } this._inboxTime = timestamp; const key = generateKey(INBOX_KEY, this._appkey, userId); this._runtime.localStorage.setItem(key, timestamp.toString()); } /** * 获取收件箱时间 * @param userId */ getInboxTime(userId) { if (this._inboxTime === 0) { const key = generateKey(INBOX_KEY, this._appkey, userId); this._inboxTime = parseInt(this._runtime.localStorage.getItem(key)) || 0; } return this._inboxTime; } /** * 更新发件箱时间 * @param timestamp * @param userId */ setOutboxTime(timestamp, userId) { if (this._outboxTime > timestamp) { return; } this._outboxTime = timestamp; const key = generateKey(OUTBOX_KEY, this._appkey, userId); this._runtime.localStorage.setItem(key, timestamp.toString()); } /** * 获取发件箱时间 * @param userId */ getOutboxTime(userId) { if (this._outboxTime === 0) { const key = generateKey(OUTBOX_KEY, this._appkey, userId); this._outboxTime = parseInt(this._runtime.localStorage.getItem(key)) || 0; } return this._outboxTime; } } const PullTimeCache = { _caches: {}, set(chrmId, time) { this._caches[chrmId] = time; }, get(chrmId) { return this._caches[chrmId] || 0; }, clear(chrmId) { this._caches[chrmId] = 0; } }; class KVStore { constructor(chatroomId, currentUserId) { this._kvCaches = {}; this._chatroomId = chatroomId; this._currentUserId = currentUserId; } _add(kv) { const { key } = kv; kv.isDeleted = false; this._kvCaches[key] = kv; } _remove(kv) { const { key } = kv; const cacheKV = this._kvCaches[key]; cacheKV.isDeleted = true; this._kvCaches[key] = cacheKV; } _setEntry(data, isFullUpdate) { const { key, type, isOverwrite, userId } = data; const latestUserId = this._getSetUserId(key); const isDeleteOpt = type === ChatroomEntryType$1.DELETE; const isSameAtLastSetUser = latestUserId === userId; const isKeyNotExist = !this._isExisted(key); const event = isDeleteOpt ? this._remove : this._add; if (isFullUpdate) { event.call(this, data); } else if (isOverwrite || isSameAtLastSetUser || isKeyNotExist) { event.call(this, data); } else ; } getValue(key) { const kv = this._kvCaches[key] || {}; const { isDeleted } = kv; return isDeleted ? null : kv.value; } getAllValue() { const entries = {}; for (const key in this._kvCaches) { if (!this._kvCaches[key].isDeleted) { entries[key] = this._kvCaches[key].value; } } return entries; } _getSetUserId(key) { const cache = this._kvCaches[key] || {}; return cache.userId; } _isExisted(key) { const cache = this._kvCaches[key] || {}; const { value, isDeleted } = cache; return (value && !isDeleted); } setEntries(data) { let { kvEntries, isFullUpdate } = data; kvEntries = kvEntries || []; isFullUpdate = isFullUpdate || false; isFullUpdate && this.clear(); kvEntries.forEach((kv) => { this._setEntry(kv, isFullUpdate); }); } clear() { this._kvCaches = {}; } } class ChrmEntryHandler { constructor(engine) { this._pullQueue = []; this._isPulling = false; this._storeCaches = {}; // 所有聊天室的 Store 缓存 this._engine = engine; } _startPull() { return __awaiter(this, void 0, void 0, function* () { if (this._isPulling || this._pullQueue.length === 0) { return; } this._isPulling = true; const { chrmId, timestamp } = this._pullQueue.splice(0, 1)[0]; const pulledUpTime = PullTimeCache.get(chrmId); if (pulledUpTime > timestamp) { // 已经拉取过,不再拉取 this._isPulling = false; this._startPull(); return; } const { code, data } = yield this._engine.pullChatroomEntry(chrmId, pulledUpTime); if (code === ErrorCode$1.SUCCESS) { this._isPulling = false; PullTimeCache.set(chrmId, data.syncTime || 0); this._startPull(); } else { this._startPull(); } }); } /** * 退出聊天室前清空 kv 缓存 和 拉取时间缓存,再次加入聊天室后重新拉取 kv 并更新本地 */ reset(chrmId) { // throw new Error('Method not implemented.') PullTimeCache.clear(chrmId); const kvStore = this._storeCaches[chrmId]; kvStore && kvStore.clear(); } /** * 向服务端拉取 kv * @description * 拉取时机: 1、加入聊天室成功后 2、收到 Server 拉取通知后 */ pullEntry(chrmId, timestamp) { this._pullQueue.push({ chrmId, timestamp }); this._startPull(); } /** * 向本地缓存己方设置或拉取到的 kv */ setLocal(chrmId, data, userId) { // throw new Error('Method not implemented.') let kvStore = this._storeCaches[chrmId]; if (!notEmptyObject(kvStore)) { kvStore = new KVStore(chrmId, userId); } kvStore.setEntries(data); this._storeCaches[chrmId] = kvStore; } /** * 获取聊天室 key 对应的 value * @param chrmId * @param key */ getValue(chrmId, key) { // throw new Error('Method not implemented.') const kvStore = this._storeCaches[chrmId]; return kvStore ? kvStore.getValue(key) : null; } /** * 获取聊天室所有 key value * @param chrmId */ getAll(chrmId) { // throw new Error('Method not implemented.') const kvStore = this._storeCaches[chrmId]; let entries = {}; if (kvStore) { entries = kvStore.getAllValue(); } return entries; } } class JoinedChrmManager { constructor(_runtime, _appkey, _userId, _canJoinMulipleChrm) { this._runtime = _runtime; this._appkey = _appkey; this._userId = _userId; this._canJoinMulipleChrm = _canJoinMulipleChrm; this._sessionKey = ''; this._joinedChrmsInfo = {}; this._sessionKey = `sync-chrm-${this._appkey}-${this._userId}`; } set(chrmId, count = 10) { !this._canJoinMulipleChrm && (this._joinedChrmsInfo = {}); this._joinedChrmsInfo[chrmId] = count; this._runtime.sessionStorage.setItem(this._sessionKey, JSON.stringify(this._joinedChrmsInfo)); } get() { let infos; try { const data = this._runtime.sessionStorage.getItem(this._sessionKey); infos = JSON.parse(data || ''); } catch (err) { logger.error('parse rejoined chrm infos error', err); infos = {}; } return infos; } remove(chrmId) { delete this._joinedChrmsInfo[chrmId]; if (notEmptyObject(this._joinedChrmsInfo)) { this._runtime.sessionStorage.setItem(this._sessionKey, JSON.stringify(this._joinedChrmsInfo)); } else { this.clear(); } } clear() { this._joinedChrmsInfo = {}; this._runtime.sessionStorage.removeItem(this._sessionKey); } } const EventName = { STATUS_CHANGED: 'converStatusChanged' }; class ConversationStatus { constructor(engine, appkey, currentUserId) { this._eventEmitter = new EventEmitter(); this._pullQueue = []; this._isPulling = false; this._storage = createRootStorage(engine.runtime); this._appkey = appkey; this._currentUserId = currentUserId; this._engine = engine; this._storagePullTimeKey = `con-s-${appkey}-${currentUserId}`; } /** * 向本地设置拉取的时间, 并通知上层会话状态的变更 */ _set(list) { // todo('ConversationStatus set') if (isUndefined(list)) { return; } let localTime = this._storage.get(this._storagePullTimeKey) || 0; const listCount = list.length; list.forEach((statusItem, index) => { const updatedTime = statusItem.updatedTime || 0; localTime = updatedTime > localTime ? updatedTime : localTime; statusItem.conversationType = statusItem.type; this._eventEmitter.emit(EventName.STATUS_CHANGED, { statusItem, isLastPull: index === listCount - 1 }); }); this._storage.set(this._storagePullTimeKey, localTime); } /** * 拉取队列 */ _startPull() { return __awaiter(this, void 0, void 0, function* () { if (this._isPulling || this._pullQueue.length === 0) { return; } this._isPulling = true; const time = this._pullQueue.splice(0, 1)[0]; const { code, data } = yield this._engine.pullConversationStatus(time); if (code === ErrorCode$1.SUCCESS) { this._isPulling = false; this._set(data); this._startPull(); } else { this._startPull(); } }); } /** * 从服务端拉取变更 */ pull(newPullTime) { const time = this._storage.get(this._storagePullTimeKey) || 0; if (newPullTime > time || newPullTime === 0) { // 拉取,并通知上层拉取到的数据 this._pullQueue.push(time); this._startPull(); } } /** * 注册会话状态变更事件 */ watch(event) { this._eventEmitter.on(EventName.STATUS_CHANGED, (data) => { event(data); }); } /** * 断开连接的后,取消注册的会话状态变更时间,防止再次连接重复注册 */ unwatch() { this._eventEmitter.off(EventName.STATUS_CHANGED, (data) => { }); } } const StorageKey2ConversationKey = { c: { keyName: 'unreadMessageCount', defaultVal: 0 }, hm: { keyName: 'hasMentioned', defaultVal: false }, m: { keyName: 'mentionedInfo', defaultVal: null }, t: { keyName: 'lastUnreadTime', defaultVal: 0 }, nc: { keyName: 'notificationStatus', defaultVal: 2 }, to: { keyName: 'isTop', defaultVal: false } }; const ConversationKey2StorageKey = {}; for (const key in StorageKey2ConversationKey) { const keyName = StorageKey2ConversationKey[key].keyName; ConversationKey2StorageKey[keyName] = key; } /** * 存储再本地的 conversation 信息 * 目前字段: * 未读数 * 是否有 @ 消息 * @ 内容 * 免打扰状态 * 置顶状态 * 对应开发者字段 * unreadMessageCount * hasMentioned * mentionedInfo * notificationStatus * isTop */ class ConversationStore { constructor(runtime, _appkey, _currentUserId) { this._appkey = _appkey; this._currentUserId = _currentUserId; const suffix = `con-${_appkey}-${_currentUserId}`; this.storage = new AppStorage(runtime, suffix); } _getStoreKey(type, targetId) { return `${type}_${targetId}`; } _getConOptionByKey(key) { key = key || ''; const arr = key.split('_'); if (arr.length === 2) { return { conversationType: arr[0], targetId: arr[1] }; } else { return { conversationType: ConversationType$1.PRIVATE, targetId: '' }; } } /** * 更新 hasMentioned mentionedInfo 信息 */ updateMentionedData(message) { const { conversationType, targetId, messageType, isMentioned, content, senderUserId } = message; const key = this._getStoreKey(conversationType, targetId); const local = this.storage.get(key) || {}; const storageMetionedInfoKey = ConversationKey2StorageKey.mentionedInfo; const storageHasMentionedKey = ConversationKey2StorageKey.hasMentioned; let updatedUserIdList = []; // let mentionedInfo = {} const localMentionedInfo = local[storageMetionedInfoKey] || {}; const localUserIdList = localMentionedInfo.userIdList || []; let mentionedInfo = content.mentionedInfo; // 如果是 @ 消息, 且 @ 列表里有自己, 更新本地的 MentionInfo.userIdList if (isMentioned && conversationType === ConversationType$1.GROUP) { const receiveUserIdList = mentionedInfo.userIdList || []; receiveUserIdList.forEach(userId => { if (userId === this._currentUserId && localUserIdList.indexOf(senderUserId) < 0) { localUserIdList.push(senderUserId); } }); if (mentionedInfo.type === MentionedType$1.ALL && localUserIdList.indexOf(senderUserId) < 0) { localUserIdList.push(senderUserId); } updatedUserIdList = localUserIdList; } // 如果是撤回 @ 消息, 更新本地 userIdList, userIdList 为空时更新 hasMentioned 为 false if (messageType === MessageType$1.RECALL && conversationType === ConversationType$1.GROUP) { const list = localUserIdList; localUserIdList.forEach((userId, index) => { if (userId === senderUserId) { list.splice(index, 1); } }); updatedUserIdList = list; } mentionedInfo = { userIdList: updatedUserIdList, type: mentionedInfo === null || mentionedInfo === void 0 ? void 0 : mentionedInfo.type }; if (updatedUserIdList.length !== 0) { local[storageMetionedInfoKey] = mentionedInfo; local[storageHasMentionedKey] = true; } else { delete local[storageMetionedInfoKey]; delete local[storageHasMentionedKey]; } if (notEmptyObject(local)) { this.storage.set(key, local); } else { this.storage.remove(key); } } /** * 设置会话信息 */ set(type, targetId, conversation) { const key = this._getStoreKey(type, targetId); const local = this.storage.get(key) || {}; for (const key in conversation) { const storageKey = ConversationKey2StorageKey[key]; const val = conversation[key]; if (isUndefined(storageKey) || isUndefined(val) || key === 'hasMentioned' || key === 'MentionedInfo') { continue; } const defaultVal = StorageKey2ConversationKey[storageKey].defaultVal; if (val === defaultVal) { // 默认值不存储,避免占用存储空间。获取时未获取到的返回默认值 delete local[storageKey]; } else { local[storageKey] = val; } if (!local.c) { // 清空未读数则清空最后操作未读时间,避免占用空间 delete local.t; } } if (notEmptyObject(local)) { this.storage.set(key, local); } else { this.storage.remove(key); } } /** * 获取单个会话本地存储信息 */ get(type, targetId) { const key = this._getStoreKey(type, targetId); const local = this.storage.get(key) || {}; const conversation = {}; for (const key in StorageKey2ConversationKey) { const { keyName, defaultVal } = StorageKey2ConversationKey[key]; conversation[keyName] = local[key] || defaultVal; } return conversation; } /** * 获取所有会话信息 */ getValue(func) { const values = this.storage.getValues() || {}; const storageConversationList = []; for (const key in values) { const { conversationType, targetId } = this._getConOptionByKey(key); let conversation = {}; const store = values[key]; for (const storeKey in store) { const { keyName, defaultVal } = StorageKey2ConversationKey[storeKey]; conversation[keyName] = store[storeKey] || defaultVal; } conversation = Object.assign(conversation, { conversationType, targetId }); conversation = func ? func(conversation) : conversation; storageConversationList.push(conversation); } return storageConversationList; } } const saveConversationType = [ConversationType$1.PRIVATE, ConversationType$1.GROUP, ConversationType$1.SYSTEM]; const EventName$1 = { CHANGED: 'conversationChanged' }; class ConversationManager { constructor(engine, appkey, userId, updatedConversationFunc) { this._updatedConversations = {}; this._eventEmitter = new EventEmitter(); this._draftMap = {}; this._appkey = appkey; this._loginUserId = userId; this._store = new ConversationStore(engine.runtime, appkey, userId); this._statusManager = new ConversationStatus(engine, appkey, userId); this._statusManager.watch((data) => { const { statusItem, isLastPull } = data; this.addStatus(statusItem, isLastPull); }); this._eventEmitter.on(EventName$1.CHANGED, (data) => { updatedConversationFunc(data); }); } /** * 根据消息计算本地 localConversation 是否需要更新 和 更新的未读数 */ _calcUnreadCount(message, localConversation) { const { content, messageType, sentTime, isCounted, messageDirection, senderUserId } = message; const isSelfSend = messageDirection === MessageDirection$1.SEND && senderUserId === this._loginUserId; const isRecall = messageType === MessageType$1.RECALL; const hasContent = isObject(content); let hasChanged = false; const lastUnreadTime = localConversation.lastUnreadTime || 0; const unreadMessageCount = localConversation.unreadMessageCount || 0; const hasBeenAdded = lastUnreadTime > sentTime; // 自己发送的消息、已经计算过的消息 不更新本地存储 if (hasBeenAdded || isSelfSend) { return { hasChanged, localConversation }; } // 计数的消息,未读数 + 1 if (isCounted) { localConversation.unreadMessageCount = unreadMessageCount + 1; localConversation.lastUnreadTime = sentTime; hasChanged = true; } // 测回的消息 且 符合撤回消息内容格式( 撤回消息 content: {conversationType, targetId, messageUId, sentTime} ) if (isRecall && hasContent) { const isNotRead = lastUnreadTime >= content.sentTime; if (isNotRead && unreadMessageCount) { localConversation.unreadMessageCount = unreadMessageCount - 1; hasChanged = true; } } return { hasChanged, localConversation }; } /** * 根据消息计算本地 localConversation 是否需要更新 和 更新的 mentionedInfo */ _calcMentionedInfo(message, localConversation) { const { content, messageDirection, isMentioned } = message; const isSelfSend = messageDirection === MessageDirection$1.SEND; const hasContent = isObject(content); let hasChanged = false; if (isMentioned && hasContent && content.mentionedInfo) { localConversation.hasMentioned = true; // localConversation.mentionedInfo = (content.mentionedInfo as unknown as IMentionInfo) hasChanged = true; } return { hasChanged, localConversation }; } /** * 更新内存中 updatedConversation 字段 */ _setUpdatedConversation(updatedConOptions) { if (isObject(updatedConOptions)) { const { conversationType, targetId } = updatedConOptions; const key = `${conversationType}_${targetId}`; const cacheConversation = this._store.get(conversationType, targetId) || {}; this._updatedConversations[key] = Object.assign(cacheConversation, updatedConOptions); } } addStatus(statusItem, isLastPull) { const { conversationType, targetId, updatedTime, notificationStatus, isTop } = statusItem; const updatedItems = {}; if (!isUndefined(notificationStatus)) { updatedItems.notificationStatus = { time: updatedTime, val: notificationStatus }; } if (!isUndefined(isTop)) { updatedItems.isTop = { time: updatedTime, val: isTop }; } this._store.set(conversationType, targetId, { notificationStatus, isTop }); this._setUpdatedConversation({ conversationType, targetId, updatedItems }); if (isLastPull) { this._notifyConversationChanged(); } } /** * 通知会话更新 * @description * 通知的条件: 会话状态变化、会话未读数变化(未读数增加、未读数清空)、会话 @ 信息(hasMentioned、mentionedInfo)、?会话最后一条消息 */ _notifyConversationChanged() { const list = []; for (const key in this._updatedConversations) { list.push(this._updatedConversations[key]); } this._eventEmitter.emit(EventName$1.CHANGED, list); this._updatedConversations = {}; } /** * 根据消息向 localstorage 设置会话未读数、会话 @ 信息( hasMentioned、MentionedInfo )、会话状态( 置顶、免打扰 ) * @description * 调用时机:1、收到消息后 2、发消息成功后 3、发送撤回消息成功后 */ setConversationCacheByMessage(message, isPullMessageFinished) { // 若不是存储会话的类型(比如: 聊天室类型), 则不作处理 const { conversationType, isPersited, targetId } = message; const isSaveConversationType = saveConversationType.indexOf(conversationType) >= 0; if (!isSaveConversationType) { return; } let hasChanged = false; let storageConversation = this._store.get(conversationType, targetId); // 计算本地存储 const CalcEvents = [this._calcUnreadCount, this._calcMentionedInfo]; CalcEvents.forEach((func) => { const { hasChanged: hasCaclChanged, localConversation } = func.call(this, message, storageConversation); hasChanged = hasChanged || hasCaclChanged; storageConversation = cloneByJSON(localConversation); }); if (hasChanged) { this._store.set(conversationType, targetId, storageConversation); } this._store.updateMentionedData(message); // 写入会话缓存中 if (isPersited) { const conversation = this._store.get(conversationType, targetId); conversation.updatedItems = { latestMessage: { time: message.sentTime, val: message } }; conversation.latestMessage = message; const updateConOptions = Object.assign(conversation, { conversationType, targetId }); this._setUpdatedConversation(updateConOptions); } // 是否需要通知, 通知 API Context 本地会话变更 if (isPullMessageFinished) { this._notifyConversationChanged(); } } /** * 获取会话本地存储信息 */ get(conversationType, targetId) { return this._store.get(conversationType, targetId); } /** * 获取本地会话所有未读数 */ getAllUnreadCount() { const conversationList = this._store.getValue(); let totalCount = 0; conversationList.forEach(({ unreadMessageCount }) => { unreadMessageCount = unreadMessageCount || 0; totalCount += Number(unreadMessageCount); }); return totalCount; } /** * 获取本地指定会话未读数 */ getUnreadCount(conversationType, targetId) { const conversation = this._store.get(conversationType, targetId); return conversation.unreadMessageCount || 0; } /** * 清除本地指定会话未读数 */ clearUnreadCount(conversationType, targetId) { const conversation = this._store.get(conversationType, targetId); const { unreadMessageCount, hasMentioned } = conversation; if (unreadMessageCount || hasMentioned) { conversation.unreadMessageCount = 0; conversation.hasMentioned = false; // conversation.mentionedInfo = null } this._store.set(conversationType, targetId, conversation); const updateConOptions = Object.assign(conversation, { conversationType, targetId }); this._setUpdatedConversation(updateConOptions); this._notifyConversationChanged(); } startPullConversationStatus(time) { this._statusManager.pull(time); } /** * 设置会话消息草稿 */ setDraft(conversationType, targetId, draft) { const key = `${conversationType}_${targetId}`; this._draftMap[key] = draft; } /** * 获取会话消息草稿 */ getDraft(conversationType, targetId) { const key = `${conversationType}_${targetId}`; return this._draftMap[key]; } /** * 删除会话消息草稿 */ clearDraft(conversationType, targetId) { const key = `${conversationType}_${targetId}`; delete this._draftMap[key]; } } var UploadMethod; (function (UploadMethod) { /** * 七牛上传 */ UploadMethod[UploadMethod["QINIU"] = 1] = "QINIU"; /** * 阿里云上传 */ UploadMethod[UploadMethod["ALI"] = 2] = "ALI"; })(UploadMethod || (UploadMethod = {})); var UploadMethod$1 = UploadMethod; /** * engine 层业务相关工具方法 */ /** * 通过文件类型生成上传唯一文件名 */ const getUploadFileName = (type, fileName) => { const random = Math.floor((Math.random() * 1000) % 10000); const uuid = getUUID(); const date = formatDate(); const timestamp = new Date().getTime(); let extension = ''; if (fileName) { const fileNameArr = fileName.split('.'); extension = '.' + fileNameArr[fileNameArr.length - 1]; } return `${type}__RC-${date}_${random}_${timestamp}${uuid}${extension}`; }; /** * 通过 fileType 获取 MIME */ const getMimeKey = (fileType) => { let mimeKey = 'application/octet-stream'; switch (fileType) { case FileType$1.IMAGE: mimeKey = 'image/jpeg'; break; case FileType$1.AUDIO: mimeKey = 'audio/amr'; break; case FileType$1.VIDEO: mimeKey = 'video/3gpp'; break; case FileType$1.SIGHT: mimeKey = 'video/mpeg4'; break; case FileType$1.COMBINE_HTML: mimeKey = 'text/html'; break; } return mimeKey; }; /** * 生成 pushConfigs JSON * @description * 与 Server 约定一致, threadId、apnsCollapseId、channelIdMi、channelIdHW、channelIdOPPO、typeVivo 无值时可传空字符串 */ const pushConfigsToJSON = (iOSConfig = {}, androidConfig = {}) => { const { threadId, apnsCollapseId } = iOSConfig; const { channelIdMi, channelIdHW, channelIdOPPO, typeVivo } = androidConfig; const APNS = {}; APNS['thread-id'] = threadId || ''; APNS['apns-collapse-id'] = apnsCollapseId || ''; const pushCongfigs = [ { HW: { channelId: channelIdHW || '' } }, { MI: { channelId: channelIdMi || '' } }, { OPPO: { channelId: channelIdOPPO || '' } }, { VIVO: { classification: typeVivo || '' } }, { APNS: APNS } ]; return JSON.stringify(pushCongfigs); }; const getPubTopic = (type) => { return { [ConversationType$1.PRIVATE]: Topic$1.ppMsgP, [ConversationType$1.GROUP]: Topic$1.pgMsgP, [ConversationType$1.CHATROOM]: Topic$1.chatMsg, [ConversationType$1.CUSTOMER_SERVICE]: Topic$1.pcMsgP, [ConversationType$1.RTC_ROOM]: Topic$1.prMsgS }[type]; }; const getStatPubTopic = (type) => { return { [ConversationType$1.PRIVATE]: Topic$1.ppMsgS, [ConversationType$1.GROUP]: Topic$1.pgMsgS }[type]; }; const transSentAttrs2IReceivedMessage = (conversationType, targetId, options, messageUId, sentTime, senderUserId) => { return { conversationType, targetId, senderUserId, messageDirection: MessageDirection$1.SEND, isCounted: !!options.isCounted, isMentioned: !!options.isMentioned, content: options.content, messageType: options.messageType, isOffLineMessage: false, isPersited: !!options.isPersited, messageUId, sentTime, receivedTime: 0, disableNotification: !!options.disableNotification, isStatusMessage: !!options.isStatusMessage, canIncludeExpansion: !!options.canIncludeExpansion, expansion: options.canIncludeExpansion ? options.expansion : null, receivedStatus: ReceivedStatus$1.UNREAD // 发送消息成功返回的 接收状态默认为 未读 }; }; /** * @description * 处理群已读同步消息逻辑:即时用户传 directionalUserIdList 也强制修改为当前登录用户。群内其他人接收无意义 */ const handleInnerMsgOptions = (options, currentUserId) => { const { messageType } = options; if (messageType === 'RC:SRSMsg') { Object.assign(options, { directionalUserIdList: [currentUserId] }); } return options; }; class JSEngine extends AEngine { constructor(runtime, appkey, watcher, apiVersion) { super(runtime, appkey, watcher, apiVersion, {}); this._customMessageType = {}; /** * 拉取离线消息标记 */ this._pullingMsg = false; /** * 收到的所有消息拉取通知事件戳队列 */ this._pullQueue = []; /** * 聊天室消息拉取通知队列 */ this._chrmsQueue = {}; // 初始化信箱 this._letterbox = new Letterbox(runtime, appkey); // 初始化 Chrm KV 处理 this._chrmEntryHandler = new ChrmEntryHandler(this); } connect(token, naviInfo, connectType) { return __awaiter(this, void 0, void 0, function* () { const hosts = []; this._naviInfo = naviInfo; if (naviInfo.server) { hosts.push(naviInfo.server); } else { // 私有云无法保证客户环境 Navi 配置有效性 logger.warn('navi.server is invalid'); } const backupServer = naviInfo.backupServer; // 备用服务有效性验证与排重 backupServer && backupServer.split(',').forEach(host => { if (hosts.indexOf(host) < 0) { hosts.push(host); } }); if (hosts.length === 0) { logger.error('navi invaild.', hosts); return ErrorCode$1.UNKNOWN; } // 创建数据通道 const channel = this.runtime.createDataChannel({ status: (status) => { this._connectionStatusHandler(status, token, hosts, naviInfo.protocol); }, signal: this._signalHandler.bind(this) }, connectType); // 建立连接 const code = yield channel.connect(this._appkey, token, hosts, naviInfo.protocol, this._apiVersion); if (code === ErrorCode$1.SUCCESS) { this._channel = channel; this.currentUserId = channel.userId; this.connectedTime = channel.connectedTime; this._conversationManager = new ConversationManager(this, this._appkey, this.currentUserId, this._watcher.conversation); this._conversationManager.startPullConversationStatus(0); // 初始化加入 chrm 的信息 this._joinedChrmManager = new JoinedChrmManager(this.runtime, this._appkey, this.currentUserId, naviInfo.joinMChrm); // 拉取离线消息 this._syncMsg(); } else { channel.close(); } return code; }); } _connectionStatusHandler(status, token, hosts, protocol) { logger.warn('connection status changed:', status); if (status === ConnectionStatus$1.CONNECTING || status === ConnectionStatus$1.CONNECTED) { this._watcher.status(status); return; } if (!this._channel || status === ConnectionStatus$1.DISCONNECTED) { // 用户主动断开连接,直接抛出连接状态 this._watcher.status(status); return; } if (status === ConnectionStatus$1.BLOCKED || status === ConnectionStatus$1.KICKED_OFFLINE_BY_OTHER_CLIENT) { // 用户被封禁,或多端被踢下线,需主动断开 websocket 连接 this.disconnect(); this._watcher.status(status); return; } // 异常断开,尝试重连 this._try2Reconnect(token, hosts, protocol); } _try2Reconnect(token, hosts, protocol) { return __awaiter(this, void 0, void 0, function* () { if (!this._channel) { return; } const code = yield this._channel.connect(this._appkey, token, hosts, protocol, this._apiVersion); if (code === ErrorCode$1.SUCCESS) { this._rejoinChrm(); return; } this._watcher.status(ConnectionStatus$1.WEBSOCKET_UNAVAILABLE); // 等待 5s 后重新尝试 setTimeout(() => { this._try2Reconnect(token, hosts, protocol); }, 5000); }); } _signalHandler(signal, ack) { const { syncMsg, topic } = signal; if (syncMsg) { // 此消息为本人其他端发出的消息,此处为多端消息同步 this._receiveSyncMsg(signal, ack); return; } const tmpTopic = Topic$1[topic]; if (!tmpTopic) { logger.error('unknown topic:', topic); return; } switch (tmpTopic) { case Topic$1.s_ntf: this._pullMsg(signal); // 通知拉取 break; case Topic$1.s_msg: this._receiveMsg(signal); // 接收直发消息 break; case Topic$1.s_cmd: this._receiveStateNotify(signal); break; case Topic$1.s_us: this._receiveSettingNotify(signal); break; } } /** * 接收聊天室 kv 通知与会话状态变更通知 * @param signal */ _receiveStateNotify(signal) { var _a; const { time, type, chrmId } = (_a = this._channel) === null || _a === void 0 ? void 0 : _a.codec.decodeByPBName(signal.data, PBName.NotifyMsg); switch (type) { case 2: this._chrmEntryHandler.pullEntry(chrmId, time); break; case 3: this._conversationManager.startPullConversationStatus(time); break; } } /** * 接收实时配置变更通知 * @param signal */ _receiveSettingNotify(signal) { // 持续迭代中,注释防止 comet 报错 // const notice = this._channel?.codec.decodeByPBName(signal.data, PBName.UserSettingNotification) // logger.error('TODO: 接收用户级配置变更通知', notice) } /** * 通知 API Content 扩展变更 */ _receiveMessageExpansion(message) { const { content } = message; const { put, del, mid } = content; if (put) { this._watcher.expansion({ updatedExpansion: { messageUId: mid, expansion: put } }); } if (del) { this._watcher.expansion({ deletedExpansion: { messageUId: mid, deletedKeys: del } }); } } /** * 接收多端同步消息 * @param signal * @param ack 同步消息的 ack 信令数据,comet 连接无此数据 */ _receiveSyncMsg(signal, ack) { var _a; let msg = (_a = this._channel) === null || _a === void 0 ? void 0 : _a.codec.decodeByPBName(signal.data, PBName.UpStreamMessage, { currentUserId: this.currentUserId, signal }); msg = this._handleMsgProperties(msg); // 更新消息并通知业务层 msg.sentTime = ack.timestamp; msg.messageUId = ack.messageUId; // 当前正在拉取消息过程中,不需要同步直发消息到业务层,向拉取队列中重新添加一个时间戳等待当前拉取动作完成后递归拉取 if (this._pullingMsg) { this._pullQueue.push(ack.timestamp); return; } // 更新发件箱时间 this._letterbox.setOutboxTime(ack.timestamp, this.currentUserId); if (msg.messageType === MessageType$1.EXPANSION_NOTIFY) { this._receiveMessageExpansion(msg); return; } this._watcher.message(msg); this._conversationManager.setConversationCacheByMessage(msg, true); } /** * 拉取消息 * @description 聊天室消息与普通消息都是通知拉取 * @param signal */ _pullMsg(signal) { if (!this._channel) { return; } const { type, chrmId, time } = this._channel.codec.decodeByPBName(signal.data, PBName.NotifyMsg); if (type === 2) { const info = this._chrmsQueue[chrmId]; info.queue.push(time); this._pullChrmMsg(chrmId); } else { // 记录消息拉取通知的时间戳 this._pullQueue.push(time); this._syncMsg(); } } /** * 拉取消息:离线 Or 通知拉取 */ _syncMsg() { return __awaiter(this, void 0, void 0, function* () { // 拉取中,队列等待 if (this._pullingMsg) { return; } if (!this._channel) { // 连接中断,无需拉取离线消息 this._pullingMsg = false; return; } this._pullingMsg = true; // 获取消息时间戳 const outboxTime = this._letterbox.getOutboxTime(this.currentUserId); const inboxTime = this._letterbox.getInboxTime(this.currentUserId); logger.debug('outboxTime', outboxTime); logger.debug('inboxTime', inboxTime); const reqBody = this._channel.codec.encodeSyncMsg({ sendboxTime: outboxTime, inboxTime }); const writer = new QueryWriter(Topic$1[Topic$1.pullMsg], reqBody, this.currentUserId); const { code, data } = yield this._channel.send(writer, PBName.DownStreamMessages, { connectedTime: this._channel.connectedTime, currentUserId: this.currentUserId }); if (code !== ErrorCode$1.SUCCESS || !data) { logger.warn('Pull msg failed, code:', code, ', data: ', data); this._pullingMsg = false; return; } const { list, finished, syncTime } = data; let newOutboxTime = 0; // let newInboxTime = 0 // 派发消息 list.forEach(item => { if (item.messageDirection === MessageDirection$1.SEND) { newOutboxTime = Math.max(item.sentTime, newOutboxTime); } // else { // newInboxTime = Math.max(item.sentTime, newInboxTime) // } if (item.messageType === MessageType$1.EXPANSION_NOTIFY) { this._receiveMessageExpansion(item); return; } this._watcher.message(item); this._conversationManager.setConversationCacheByMessage(item, true); }); // 更新收件箱时间 // this.letterbox.setInboxTime(newInboxTime, this.currentUserId) this._letterbox.setInboxTime(syncTime, this.currentUserId); // 更新发件箱时间 this._letterbox.setOutboxTime(newOutboxTime, this.currentUserId); this._pullingMsg = false; // 清除较 syncTime 更早的拉取通知时间戳 const tmpPullQueue = this._pullQueue.filter(timestamp => timestamp > syncTime); this._pullQueue.length = 0; this._pullQueue.push(...tmpPullQueue); if (!finished || tmpPullQueue.length > 0) { // 继续拉取 this._syncMsg(); } }); } /** * 接收直发消息 * @description 直发消息只有单聊、群聊存在,其他会话类型均为通知拉取 * @param signal */ _receiveMsg(signal) { if (!this._channel) { return; } let msg = this._channel.codec.decodeByPBName(signal.data, PBName.DownStreamMessage, { currentUserId: this.currentUserId, connectedTime: this._channel.connectedTime }); msg = this._handleMsgProperties(msg); // 当在拉取单群聊离线过程中,直发消息可直接抛弃 if (this._pullingMsg) { return; } // 更新收件箱时间 this._letterbox.setInboxTime(msg.sentTime, this.currentUserId); if (msg.messageType === MessageType$1.EXPANSION_NOTIFY) { this._receiveMessageExpansion(msg); return; } this._watcher.message(msg); this._conversationManager.setConversationCacheByMessage(msg, true); } /** * 向 API Context 抛出消息时,处理消息的部分属性值 * @description * 当前仅根据内置消息或自定义类型的消息处理消息的存储、计数属性 */ _handleMsgProperties(msgOptions, isSendMsg = false) { const { messageType, isCounted, isPersited, isStatusMessage } = msgOptions; let options; const inRCMessageType = messageType in SEND_MESSAGE_TYPE_OPTION; const inCustomMessageType = messageType in this._customMessageType; if (inRCMessageType) { // 内置消息 options = SEND_MESSAGE_TYPE_OPTION[messageType]; } else if (inCustomMessageType) { // 自定义消息 options = this._customMessageType[messageType]; } else { // 其他消息, 发消息已传参为准, 无参数默认 false. 收消息已服务端微赚 options = { isCounted: isNull(isCounted) ? false : isCounted, isPersited: isNull(isPersited) ? false : isPersited }; } Object.assign(msgOptions, { isCounted: options.isCounted, isPersited: options.isPersited, isStatusMessage: !(msgOptions.isCounted && msgOptions.isPersited) }); isSendMsg && (msgOptions.isStatusMessage = isStatusMessage); return msgOptions; } getConnectTime() { if (this._channel) { return Promise.resolve({ code: ErrorCode$1.SUCCESS, data: this._channel.connectedTime }); } return Promise.resolve({ code: ErrorCode$1.RC_NET_CHANNEL_INVALID }); } getHistoryMessage(conversationType, targetId, timestamp, count, order) { return __awaiter(this, void 0, void 0, function* () { const { currentUserId, _channel: channel } = this; const hisTopic = ConversationTypeToQueryHistoryTopic[conversationType] || QueryHistoryTopic.PRIVATE; if (channel) { const data = channel.codec.encodeGetHistoryMsg(targetId, { timestamp, count, order }); const resp = yield channel.send(new QueryWriter(hisTopic, data, currentUserId), PBName.HistoryMsgOuput, { currentUserId, connectedTime: channel.connectedTime, conversation: { targetId } }); const { code } = resp; if (code !== ErrorCode$1.SUCCESS) { return { code }; } // 解析数据转换为业务层数据结构 const downstreamData = resp.data; return { code, data: { list: downstreamData.list, hasMore: downstreamData.hasMore } }; } return { code: ErrorCode$1.RC_NET_CHANNEL_INVALID }; }); } deleteRemoteMessage(conversationType, targetId, list) { return __awaiter(this, void 0, void 0, function* () { const { currentUserId, _channel: channel } = this; if (channel) { const data = channel.codec.encodeDeleteMessages(conversationType, targetId, list); const writer = new QueryWriter(QueryTopic.DELETE_MESSAGES, data, currentUserId); const resp = yield channel.send(writer); const { code } = resp; if (code !== ErrorCode$1.SUCCESS) { return code; } return code; } return ErrorCode$1.RC_NET_CHANNEL_INVALID; }); } deleteRemoteMessageByTimestamp(conversationType, targetId, timestamp) { return __awaiter(this, void 0, void 0, function* () { const { currentUserId, _channel: channel } = this; if (channel) { const data = channel.codec.encodeClearMessages(targetId, timestamp); const topic = ConversationTypeToClearMessageTopic[conversationType]; const writer = new QueryWriter(topic, data, currentUserId); const resp = yield channel.send(writer); const { code } = resp; if (code !== ErrorCode$1.SUCCESS) { return code; } return code; } return ErrorCode$1.RC_NET_CHANNEL_INVALID; }); } getConversationList(count = 300, conversationType, startTime, order) { return __awaiter(this, void 0, void 0, function* () { const { currentUserId, _channel: channel } = this; conversationType = conversationType || ConversationType$1.PRIVATE; if (channel) { const buff = channel.codec.encodeOldConversationList({ count, type: conversationType, startTime, order }); const writer = new QueryWriter(QueryTopic.GET_OLD_CONVERSATION_LIST, buff, currentUserId); const resp = yield channel.send(writer, PBName.RelationsOutput, { currentUserId, connectedTime: channel.connectedTime, afterDecode: (conversation) => { const { conversationType, targetId } = conversation; const localConversation = this._conversationManager.get(conversationType, targetId); // 将本地存储的会话属性和从 Server 获取到的会话属性进行合并 Object.assign(conversation, localConversation); return conversation; } }); logger.info('GetConversationList =>', resp); const { code, data } = resp; if (code !== ErrorCode$1.SUCCESS) { return { code }; } return { code, data: data }; } return { code: ErrorCode$1.RC_NET_CHANNEL_INVALID }; }); } removeConversation(conversationType, targetId) { return __awaiter(this, void 0, void 0, function* () { const { _channel: channel } = this; if (channel) { const data = channel.codec.encodeOldConversationList({ type: conversationType }); const writer = new QueryWriter(QueryTopic.REMOVE_OLD_CONVERSATION, data, targetId); const resp = yield channel.send(writer); logger.info('RemoveConversation =>', resp); const { code } = resp; if (code !== ErrorCode$1.SUCCESS) { return code; } return code; } return ErrorCode$1.RC_NET_CHANNEL_INVALID; }); } getConversation(conversationType, targetId, tag) { throw new Error('Method not implemented.'); } getAllConversationUnreadCount() { const allUnreadCount = this._conversationManager.getAllUnreadCount(); return Promise.resolve({ code: ErrorCode$1.SUCCESS, data: allUnreadCount }); } getConversationUnreadCount(conversationType, targetId) { const unreadCount = this._conversationManager.getUnreadCount(conversationType, targetId); return Promise.resolve({ code: ErrorCode$1.SUCCESS, data: unreadCount }); } clearConversationUnreadCount(conversationType, targetId) { this._conversationManager.clearUnreadCount(conversationType, targetId); return Promise.resolve(ErrorCode$1.SUCCESS); } saveConversationMessageDraft(conversationType, targetId, draft) { this._conversationManager.setDraft(conversationType, targetId, draft); return Promise.resolve(ErrorCode$1.SUCCESS); } getConversationMessageDraft(conversationType, targetId) { const draft = this._conversationManager.getDraft(conversationType, targetId); return Promise.resolve({ code: ErrorCode$1.SUCCESS, data: draft }); } clearConversationMessageDraft(conversationType, targetId) { this._conversationManager.clearDraft(conversationType, targetId); return Promise.resolve(ErrorCode$1.SUCCESS); } pullConversationStatus(timestamp) { return __awaiter(this, void 0, void 0, function* () { const { _channel: channel, currentUserId } = this; if (channel) { const buff = channel.codec.encodeGetConversationStatus(timestamp); const writer = new QueryWriter(Topic$1[Topic$1.pullSeAtts], buff, currentUserId); const resp = yield channel.send(writer, PBName.SessionStates); const { code, data } = resp; if (code !== ErrorCode$1.SUCCESS) { return { code }; } return { code, data: data }; } return { code: ErrorCode$1.RC_NET_CHANNEL_INVALID }; }); } batchSetConversationStatus(statusList) { return __awaiter(this, void 0, void 0, function* () { const { currentUserId, _channel: channel } = this; if (channel) { const buff = channel.codec.encodeSetConversationStatus(statusList); const writer = new QueryWriter(QueryTopic.SET_CONVERSATION_STATUS, buff, currentUserId); const resp = yield channel.send(writer, PBName.SessionStateModifyResp); const { code, data } = resp; if (code === ErrorCode$1.SUCCESS) { const versionData = data; statusList.forEach((item) => { this._conversationManager.addStatus(Object.assign(Object.assign({}, item), { updatedTime: versionData.version }), true); }); return code; } return code; } return ErrorCode$1.RC_NET_CHANNEL_INVALID; }); } _joinChrm(chrmId, count, isJoinExist) { return __awaiter(this, void 0, void 0, function* () { const { _channel: channel } = this; if (!channel) return ErrorCode$1.RC_NET_CHANNEL_INVALID; const buff = channel.codec.encodeJoinOrQuitChatRoom(); const topic = isJoinExist ? QueryTopic.JOIN_EXIST_CHATROOM : QueryTopic.JOIN_CHATROOM; const writer = new QueryWriter(topic, buff, chrmId); const { code, data } = yield channel.send(writer); // 加入聊天室成功后,需要拉取聊天室最近消息, 并抛给消息监听器 if (code === ErrorCode$1.SUCCESS) { const info = this._chrmsQueue[chrmId]; // 断线重连情况下,重复加房间不能重置消息拉取信息 if (!info) { this._chrmsQueue[chrmId] = { pulling: false, queue: [], timestamp: 0 }; } this._pullChrmMsg(chrmId, count); // 如果开通聊天室 KV 存储服务, 加入成功后拉取聊天室 KV 存储 const { kvStorage: isOpenKVService } = this._naviInfo; if (isOpenKVService) { this._chrmEntryHandler.pullEntry(chrmId, 0); } // sessionStorage 存储加入房间的信息 this._joinedChrmManager.set(chrmId, count); } return code; }); } /** * 断网重连成功后,从 sessionStorage 缓存中获取用户已加入的聊天室,然后重新加入已存在的聊天室,并拉取消息 */ _rejoinChrm() { return __awaiter(this, void 0, void 0, function* () { const joinedChrms = this._joinedChrmManager.get(); for (const chrmId in joinedChrms) { const code = yield this._joinChrm(chrmId, joinedChrms[chrmId], true); if (code === ErrorCode$1.SUCCESS) { this._watcher.chatroom({ rejoinedRoom: { chatroomId: chrmId, count: joinedChrms[chrmId] } }); } else { this._watcher.chatroom({ rejoinedRoom: { chatroomId: chrmId, errorCode: code } }); } } }); } /** * 拉取聊天室消息 * @param chrmId * @param count 默认拉取 10 条,最大一次拉取 50 条,只在加入房间时第一次拉取时有效 */ _pullChrmMsg(chrmId, count = 10) { return __awaiter(this, void 0, void 0, function* () { if (!this._channel) { return; } const chrmInfo = this._chrmsQueue[chrmId]; const { pulling, timestamp } = chrmInfo; if (pulling) { return; } const reqBody = this._channel.codec.encodeChrmSyncMsg(timestamp, count); const signal = new QueryWriter(Topic$1[Topic$1.chrmPull], reqBody, chrmId); const { code, data } = yield this._channel.send(signal, PBName.DownStreamMessages, { connectedTime: this._channel.connectedTime, currentUserId: this.currentUserId }); if (code !== ErrorCode$1.SUCCESS || !data) { logger.warn('pull chatroom msg failed, code:', code, ', data:', data); return; } const { list, syncTime, finished } = data; chrmInfo.timestamp = syncTime; chrmInfo.pulling = false; // 清除无效时间戳 chrmInfo.queue = chrmInfo.queue.filter(item => item > timestamp); // 派发消息 list.forEach(item => { if (item.sentTime < timestamp) { return; } this._watcher.message(item); }); if (!finished || chrmInfo.queue.length > 0) { this._pullChrmMsg(chrmId); } }); } joinChatroom(chatroomId, count) { return __awaiter(this, void 0, void 0, function* () { return this._joinChrm(chatroomId, count, false); }); } joinExistChatroom(chatroomId, count) { return __awaiter(this, void 0, void 0, function* () { return this._joinChrm(chatroomId, count, true); }); } quitChatroom(chrmId) { return __awaiter(this, void 0, void 0, function* () { const { _channel: channel } = this; if (!channel) { return ErrorCode$1.RC_NET_CHANNEL_INVALID; } const buff = channel.codec.encodeJoinOrQuitChatRoom(); const writer = new QueryWriter(QueryTopic.QUIT_CHATROOM, buff, chrmId); const resp = yield channel.send(writer); const { code } = resp; if (code === ErrorCode$1.SUCCESS) { delete this._chrmsQueue[chrmId]; this._chrmEntryHandler.reset(chrmId); // 移除加入聊天室存储信息 this._joinedChrmManager.remove(chrmId); } return code; }); } getChatroomInfo(chatroomId, count, order) { return __awaiter(this, void 0, void 0, function* () { const { _channel: channel } = this; if (!channel) return { code: ErrorCode$1.RC_NET_CHANNEL_INVALID }; const buff = channel.codec.encodeGetChatRoomInfo(count, order); const writer = new QueryWriter(Topic$1[Topic$1.queryChrmI], buff, chatroomId); const resp = yield channel.send(writer, PBName.QueryChatRoomInfoOutput); const { code, data } = resp; if (code !== ErrorCode$1.SUCCESS) return { code }; return { code, data: data }; }); } getChatroomHistoryMessages(chatroomId, timestamp, count, order) { return __awaiter(this, void 0, void 0, function* () { const { _channel: channel } = this; if (!channel) { return { code: ErrorCode$1.RC_NET_CHANNEL_INVALID }; } const buff = channel.codec.encodeGetHistoryMsg(chatroomId, { timestamp, count, order }); const writer = new QueryWriter(QueryHistoryTopic.CHATROOM, buff, chatroomId); const resp = yield channel.send(writer, PBName.HistoryMsgOuput, { conversation: { targetId: chatroomId } }); const { code } = resp; const data = resp.data; if (code !== ErrorCode$1.SUCCESS) return { code }; return { code, data: { list: data.list, hasMore: data.hasMore } }; }); } _modifyChatroomKV(chatroomId, entry) { return __awaiter(this, void 0, void 0, function* () { const { _channel: channel, currentUserId } = this; if (!channel) return ErrorCode$1.RC_NET_CHANNEL_INVALID; const buff = channel.codec.encodeModifyChatRoomKV(chatroomId, entry, currentUserId); const topic = entry.type === ChatroomEntryType$1.UPDATE ? QueryTopic.UPDATE_CHATROOM_KV : QueryTopic.DELETE_CHATROOM_KV; const writer = new QueryWriter(topic, buff, chatroomId); const resp = yield channel.send(writer); const { code } = resp; if (code === ErrorCode$1.SUCCESS) { this._chrmEntryHandler.setLocal(chatroomId, { kvEntries: [entry], syncTime: new Date().getTime() }, currentUserId); return code; } return code; }); } setChatroomEntry(chatroomId, entry) { return __awaiter(this, void 0, void 0, function* () { entry.type = ChatroomEntryType$1.UPDATE; return this._modifyChatroomKV(chatroomId, entry); }); } forceSetChatroomEntry(chatroomId, entry) { return __awaiter(this, void 0, void 0, function* () { entry.type = ChatroomEntryType$1.UPDATE; entry.isOverwrite = true; return this._modifyChatroomKV(chatroomId, entry); }); } removeChatroomEntry(chatroomId, entry) { return __awaiter(this, void 0, void 0, function* () { entry.type = ChatroomEntryType$1.DELETE; return this._modifyChatroomKV(chatroomId, entry); }); } forceRemoveChatroomEntry(chatroomId, entry) { return __awaiter(this, void 0, void 0, function* () { entry.type = ChatroomEntryType$1.DELETE; entry.isOverwrite = true; return this._modifyChatroomKV(chatroomId, entry); }); } getChatroomEntry(chatroomId, key) { // 1、判断用户是否在聊天室,不在抛出 不在聊天室 错误码 2、从本地获取 key value 属性 const entry = this._chrmEntryHandler.getValue(chatroomId, key); if (entry) { return Promise.resolve({ code: ErrorCode$1.SUCCESS, data: entry }); } else { return Promise.resolve({ code: ErrorCode$1.CHATROOM_KEY_NOT_EXIST }); } } getAllChatroomEntry(chatroomId) { // 1、判断用户是否在聊天室,不在抛出 不在聊天室 错误码 2、从本地获取 key value 属性 const entries = this._chrmEntryHandler.getAll(chatroomId); return Promise.resolve({ code: ErrorCode$1.SUCCESS, data: entries }); } /** * 拉取聊天室 KV 存储 * @param chatroomId * @param timestamp */ pullChatroomEntry(chatroomId, timestamp) { return __awaiter(this, void 0, void 0, function* () { const { _channel: channel, currentUserId } = this; if (!channel) { return { code: ErrorCode$1.RC_NET_CHANNEL_INVALID }; } const buff = channel.codec.encodePullChatRoomKV(timestamp); const writer = new QueryWriter(Topic$1[Topic$1.pullKV], buff, chatroomId); const resp = yield channel.send(writer, PBName.ChrmKVOutput); const { code, data } = resp; if (code === ErrorCode$1.SUCCESS) { // 拉取完成后,向本地缓存 kv this._chrmEntryHandler.setLocal(chatroomId, data, currentUserId); // 拉取完成后, 如果有拉取到更新的 entry 通知聊天室 KV 监听器 const { kvEntries } = data; const updatedEntries = []; if (kvEntries.length > 0) { kvEntries.forEach(entry => { const { key, value, type, timestamp } = entry; updatedEntries.push({ key, value: value, type: type, timestamp: timestamp, chatroomId }); }); this._watcher.chatroom({ updatedEntries }); } return { code, data: data }; } return { code }; }); } /** * 消息发送 * @param conversationType * @param targetId * @param options */ sendMessage(conversationType, targetId, options) { return __awaiter(this, void 0, void 0, function* () { if (!this._channel) { return { code: ErrorCode$1.RC_NET_CHANNEL_INVALID }; } options = handleInnerMsgOptions(options, this.currentUserId); options = this._handleMsgProperties(options, true); // 检查是否为状态消息,状态消息只在单聊、群聊类型会话中有效 const isStatusMessage = [ConversationType$1.PRIVATE, ConversationType$1.GROUP].includes(conversationType) ? options.isStatusMessage : false; const topic = isStatusMessage ? getStatPubTopic(conversationType) : (getPubTopic(conversationType) || Topic$1.ppMsgP); if (isStatusMessage) { options.isPersited = false; options.isCounted = false; } const data = this._channel.codec.encodeUpMsg({ type: conversationType, targetId }, options); const signal = new PublishWriter(Topic$1[topic], data, targetId); signal.setHeaderQos(QOS.AT_LEAST_ONCE); // 状态消息无 Ack 应答 if (isStatusMessage) { this._channel.sendOnly(signal); return { code: ErrorCode$1.SUCCESS, data: transSentAttrs2IReceivedMessage(conversationType, targetId, Object.assign({}, options), '', 0, this.currentUserId) }; } const { code, data: resp } = yield this._channel.send(signal); if (code !== ErrorCode$1.SUCCESS) { return { code }; } const pubAck = resp; // 更新发件箱时间 this._letterbox.setOutboxTime(pubAck.timestamp, this.currentUserId); // 更新会话监听 const receivedMessage = transSentAttrs2IReceivedMessage(conversationType, targetId, Object.assign({}, options), pubAck.messageUId, pubAck.timestamp, this.currentUserId); this._conversationManager.setConversationCacheByMessage(receivedMessage, true); return { code: ErrorCode$1.SUCCESS, data: receivedMessage }; }); } recallMsg(conversationType, targetId, messageUId, sentTime, recallMsgOptions) { return __awaiter(this, void 0, void 0, function* () { if (!this._channel) { return { code: ErrorCode$1.RC_NET_CHANNEL_INVALID }; } const { user } = recallMsgOptions; // user 为发送撤回消息携带的用户信息 const msg = { content: { conversationType, targetId, messageUId, sentTime, user }, messageType: 'RC:RcCmd' }; const topic = Topic$1[Topic$1.recallMsg]; const data = this._channel.codec.encodeUpMsg({ type: conversationType, targetId }, msg); const signal = new PublishWriter(topic, data, this.currentUserId); signal.setHeaderQos(QOS.AT_LEAST_ONCE); const { code, data: resp } = yield this._channel.send(signal); if (code !== ErrorCode$1.SUCCESS) { return { code }; } const pubAck = resp; return { code: ErrorCode$1.SUCCESS, data: transSentAttrs2IReceivedMessage(conversationType, targetId, Object.assign({}, msg), pubAck.messageUId, pubAck.timestamp, this.currentUserId) }; }); } /** * 拉取用户配置 * @todo 需要确定 version 的作用是什么 * @param version */ pullUserSettings(version) { return __awaiter(this, void 0, void 0, function* () { if (!this._channel) { return { code: ErrorCode$1.RC_NET_CHANNEL_INVALID }; } const buff = this._channel.codec.encodePullUserSetting(version); const writer = new QueryWriter(Topic$1[Topic$1.pullUS], buff, this.currentUserId); return this._channel.send(writer, PBName.PullUserSettingOutput); }); } getFileToken(fileType, fileName) { return __awaiter(this, void 0, void 0, function* () { if (!this._channel) { return { code: ErrorCode$1.RC_NET_CHANNEL_INVALID }; } // 若不设置 fileName 百度上传的认证数据均返回 null const uploadFileName = getUploadFileName(fileType, fileName); const buff = this._channel.codec.encodeGetFileToken(fileType, uploadFileName); const writer = new QueryWriter(Topic$1[Topic$1.qnTkn], buff, this.currentUserId); let { code, data } = yield this._channel.send(writer, PBName.GetQNupTokenOutput); data = Object.assign(data, { fileName: uploadFileName }); if (code === ErrorCode$1.SUCCESS) { return { code, data: data }; } return { code }; }); } getFileUrl(fileType, uploadMethod, fileName, originName) { return __awaiter(this, void 0, void 0, function* () { if (!this._channel) { return { code: ErrorCode$1.RC_NET_CHANNEL_INVALID }; } let topic = ''; let inputPBName = ''; let outputPBName = ''; if (uploadMethod === UploadMethod$1.QINIU) { topic = Topic$1[Topic$1.qnUrl]; inputPBName = PBName.GetQNdownloadUrlInput; outputPBName = PBName.GetQNdownloadUrlOutput; } else { topic = Topic$1[Topic$1.aliUrl]; inputPBName = PBName.GetDownloadUrlInput; outputPBName = PBName.GetDownloadUrlOutput; } const buff = this._channel.codec.encodeGetFileUrl(inputPBName, fileType, fileName, originName); const writer = new QueryWriter(topic, buff, this.currentUserId); const { code, data } = yield this._channel.send(writer, outputPBName); const resp = data; if (code === ErrorCode$1.SUCCESS) { return { code, data: resp }; } return { code }; }); } disconnect() { if (this._channel) { this._channel.close(); this._channel = undefined; } } destroy() { throw new Error('JSEngine\'s method not implemented.'); } registerMessageType(objectName, isPersited, isCounted, searchProps) { // ✔️ 根据 objectName 将自定义消息属性内存态存储 [objectName]: {isPersited, isCounted} this._customMessageType[objectName] = { isPersited, isCounted }; // 根据 messageName searchProps 生成构造消息( V3 不实现 V2 API 层实现) // ✔️ SDK 发消息时,根据内置消息类型或自定义消息类型去处理 存储、计数属性 // ✔️ SDK 收到消息后,内置消息类型的属性(存储、计数)去处理收到的消息、本地会话未读数存储 } // ===================== RTC 相关接口 ===================== joinRTCRoom(roomId, mode, broadcastType) { return __awaiter(this, void 0, void 0, function* () { if (!this._channel) { return { code: ErrorCode$1.RC_NET_CHANNEL_INVALID }; } const reqBody = this._channel.codec.encodeJoinRTCRoom(mode, broadcastType); const writer = new QueryWriter(Topic$1[Topic$1.rtcRJoin_data], reqBody, roomId); return this._channel.send(writer, PBName.RtcUserListOutput); }); } quitRTCRoom(roomId) { return __awaiter(this, void 0, void 0, function* () { if (!this._channel) { return ErrorCode$1.RC_NET_CHANNEL_INVALID; } const reqBody = this._channel.codec.encodeQuitRTCRoom(); const writer = new QueryWriter(Topic$1[Topic$1.rtcRExit], reqBody, roomId); const { code } = yield this._channel.send(writer); return code; }); } rtcPing(roomId, mode, broadcastType) { return __awaiter(this, void 0, void 0, function* () { if (!this._channel) { return ErrorCode$1.RC_NET_CHANNEL_INVALID; } const reqBody = this._channel.codec.encodeJoinRTCRoom(mode, broadcastType); const writer = new QueryWriter(Topic$1[Topic$1.rtcPing], reqBody, roomId); const { code } = yield this._channel.send(writer); return code; }); } getRTCRoomInfo(roomId) { return __awaiter(this, void 0, void 0, function* () { if (!this._channel) { return { code: ErrorCode$1.RC_NET_CHANNEL_INVALID }; } const reqBody = this._channel.codec.encodeGetRTCRoomInfo(); const writer = new QueryWriter(Topic$1[Topic$1.rtcRInfo], reqBody, roomId); return this._channel.send(writer, PBName.RtcRoomInfoOutput); }); } getRTCUserInfoList(roomId) { return __awaiter(this, void 0, void 0, function* () { if (!this._channel) { return { code: ErrorCode$1.RC_NET_CHANNEL_INVALID }; } const reqBody = this._channel.codec.encodeGetRTCRoomInfo(); const writer = new QueryWriter(Topic$1[Topic$1.rtcUData], reqBody, roomId); const { code, data } = yield this._channel.send(writer, PBName.RtcUserListOutput); return { code, data: data ? { users: data.users } : data }; }); } // TODO: 排查 rtcUPut 超时无响应问题 setRTCUserInfo(roomId, key, value) { return __awaiter(this, void 0, void 0, function* () { if (!this._channel) { return ErrorCode$1.RC_NET_CHANNEL_INVALID; } const reqBody = this._channel.codec.encodeSetRTCUserInfo(key, value); const writer = new QueryWriter(Topic$1[Topic$1.rtcUPut], reqBody, roomId); const { code } = yield this._channel.send(writer); return code; }); } removeRTCUserInfo(roomId, keys) { return __awaiter(this, void 0, void 0, function* () { if (!this._channel) { return ErrorCode$1.RC_NET_CHANNEL_INVALID; } const reqBody = this._channel.codec.encodeRemoveRTCUserInfo(keys); const writer = new PublishWriter(Topic$1[Topic$1.rtcUDel], reqBody, roomId); const { code } = yield this._channel.send(writer); return code; }); } setRTCData(roomId, key, value, isInner, apiType, message) { return __awaiter(this, void 0, void 0, function* () { if (!this._channel) { return ErrorCode$1.RC_NET_CHANNEL_INVALID; } const reqBody = this._channel.codec.encodeSetRTCData(key, value, isInner, apiType, message); const writer = new PublishWriter(Topic$1[Topic$1.rtcSetData], reqBody, roomId); const { code } = yield this._channel.send(writer); return code; }); } setRTCTotalRes(roomId, message, valueInfo, objectName) { return __awaiter(this, void 0, void 0, function* () { if (!this._channel) { return ErrorCode$1.RC_NET_CHANNEL_INVALID; } const reqBody = this._channel.codec.encodeUserSetRTCData(message, valueInfo, objectName); const writer = new PublishWriter(Topic$1[Topic$1.userSetData], reqBody, roomId); const { code } = yield this._channel.send(writer); return code; }); } getRTCData(roomId, keys, isInner, apiType) { if (!this._channel) { return Promise.resolve({ code: ErrorCode$1.RC_NET_CHANNEL_INVALID }); } const reqBody = this._channel.codec.encodeGetRTCData(keys, isInner, apiType); const writer = new QueryWriter(Topic$1[Topic$1.rtcQryData], reqBody, roomId); return this._channel.send(writer, PBName.RtcQryOutput); } removeRTCData(roomId, keys, isInner, apiType, message) { return __awaiter(this, void 0, void 0, function* () { if (!this._channel) { return ErrorCode$1.RC_NET_CHANNEL_INVALID; } const reqBody = this._channel.codec.encodeRemoveRTCData(keys, isInner, apiType, message); const writer = new PublishWriter(Topic$1[Topic$1.rtcDelData], reqBody, roomId); const { code } = yield this._channel.send(writer); return code; }); } setRTCOutData(roomId, rtcData, type, message) { // const data = this._serverDataCodec.encodeSetRTCOutData(rtcData, type, message); // let writer = new PublishWriter(QUERY_TOPIC.SET_RTC_OUT_DATA, data, roomId); // return this._sendSignalForData(writer); throw new Error('JSEngine\'s method not implemented.'); } getRTCOutData(roomId, userIds) { // const data = this._serverDataCodec.ecnodeGetRTCOutData(userIds); // let writer = new QueryWriter(QUERY_TOPIC.GET_RTC_OUT_DATA, data, roomId); // return this._sendSignalForData(writer, PBName.RtcUserOutDataOutput); throw new Error('JSEngine\'s method not implemented.'); } getRTCToken(roomId, mode, broadcastType) { return __awaiter(this, void 0, void 0, function* () { if (!this._channel) { return { code: ErrorCode$1.RC_NET_CHANNEL_INVALID }; } const reqBody = this._channel.codec.encodeJoinRTCRoom(mode, broadcastType); const writer = new QueryWriter(Topic$1[Topic$1.rtcToken], reqBody, roomId); return this._channel.send(writer, PBName.RtcTokenOutput); }); } setRTCState(roomId, report) { return __awaiter(this, void 0, void 0, function* () { if (!this._channel) { return ErrorCode$1.RC_NET_CHANNEL_INVALID; } const reqBody = this._channel.codec.encodeSetRTCState(report); const writer = new QueryWriter(Topic$1[Topic$1.rtcUserState], reqBody, roomId); const { code } = yield this._channel.send(writer); return code; }); } getRTCUserInfo(roomId) { return __awaiter(this, void 0, void 0, function* () { throw new Error('Method not implemented.'); }); } getRTCUserList(roomId) { if (!this._channel) { return Promise.resolve({ code: ErrorCode$1.RC_NET_CHANNEL_INVALID }); } const data = this._channel.codec.encodeGetRTCRoomInfo(); const writer = new QueryWriter(Topic$1[Topic$1.rtcUList], data, roomId); return this._channel.send(writer, PBName.RtcUserListOutput); } /* ================ 以下为 CPP 特有接口,JSEngine 无需实现 ================== */ clearConversations() { throw new Error('Method not implemented.'); } setUserStatusListener(config, listener) { throw new Error('Method not implemented.'); } setUserStatus(status) { throw new Error('Method not implemented.'); } subscribeUserStatus(userIds) { throw new Error('Method not implemented.'); } getUserStatus(userId) { throw new Error('Method not implemented.'); } addToBlacklist(userId) { throw new Error('Method not implemented.'); } removeFromBlacklist(userId) { throw new Error('Method not implemented.'); } getBlacklist() { throw new Error('Method not implemented.'); } getBlacklistStatus(userId) { throw new Error('Method not implemented.'); } insertMessage(conversationType, targetId, insertOptions) { throw new Error('Method not implemented.'); } deleteMessages(timestamps) { throw new Error('Method not implemented.'); } deleteMessagesByTimestamp(conversationType, targetId, timestamp, cleanSpace, channelId) { throw new Error('Method not implemented.'); } clearMessages(conversationType, targetId, channelId) { throw new Error('Method not implemented.'); } getMessage(messageId) { throw new Error('Method not implemented.'); } setMessageContent(messageId, content, objectName) { throw new Error('Method not implemented.'); } setMessageSearchField(messageId, content, searchFiles) { throw new Error('Method not implemented.'); } searchConversationByContent(keyword, messageTypes, channelId, conversationTypes) { throw new Error('Method not implemented.'); } searchMessageByContent(conversationType, targetId, keyword, timestamp, count, total) { throw new Error('Method not implemented.'); } getUnreadMentionedMessages(conversationType, targetId) { throw new Error('Method not implemented.'); } setMessageSentStatus(messageId, sentStatus) { throw new Error('Method not implemented.'); } setMessageReceivedStatus(messageId, receivedStatus) { throw new Error('Method not implemented.'); } clearUnreadCountByTimestamp(conversationType, targetId, timestamp, channelId) { throw new Error('Method not implemented.'); } getConversationNotificationStatus(conversationType, targetId, channelId) { throw new Error('Method not implemented.'); } getRemoteHistoryMessages(conversationType, targetId, timestamp, count, order, channelId) { throw new Error('Method not implemented.'); } } /** * 音视频模式 */ (function (RTCMode) { /** * 普通音视频模式 */ RTCMode[RTCMode["RTC"] = 0] = "RTC"; /** * 直播模式 */ RTCMode[RTCMode["LIVE"] = 2] = "LIVE"; })(exports.RTCMode || (exports.RTCMode = {})); (function (LiveType) { /** * 音视频直播 */ LiveType[LiveType["AUDIO_AND_VIDEO"] = 0] = "AUDIO_AND_VIDEO"; /** * 音频直播 */ LiveType[LiveType["AUDIO"] = 1] = "AUDIO"; })(exports.LiveType || (exports.LiveType = {})); (function (LiveRole) { /** * 主播身份 */ LiveRole[LiveRole["ANCHOR"] = 1] = "ANCHOR"; /** * 观众身份 */ LiveRole[LiveRole["AUDIENCE"] = 2] = "AUDIENCE"; })(exports.LiveRole || (exports.LiveRole = {})); /** * CallLib 流程消息 */ const CallLibMsgType = { 'RC:VCAccept': 'RC:VCAccept', 'RC:VCRinging': 'RC:VCRinging', 'RC:VCSummary': 'RC:VCSummary', 'RC:VCHangup': 'RC:VCHangup', 'RC:VCInvite': 'RC:VCInvite', 'RC:VCModifyMedia': 'RC:VCModifyMedia', 'RC:VCModifyMem': 'RC:VCModifyMem' }; (function (RTCApiType) { RTCApiType[RTCApiType["ROOM"] = 1] = "ROOM"; RTCApiType[RTCApiType["PERSON"] = 2] = "PERSON"; })(exports.RTCApiType || (exports.RTCApiType = {})); const string10to64 = (number) => { const chars = '0123456789abcdefghigklmnopqrstuvwxyzABCDEFGHIGKLMNOPQRSTUVWXYZa0'.split(''); const radix = chars.length + 1; let qutient = +number; const arr = []; do { const mod = qutient % radix; qutient = (qutient - mod) / radix; arr.unshift(chars[mod]); } while (qutient); return arr.join(''); }; const getUUID22 = () => { let uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { const r = Math.random() * 16 | 0; const v = c === 'x' ? r : (r & 0x3 | 0x8); return v.toString(16); }); uuid = uuid.replace(/-/g, '') + 'a'; const uuidNum = parseInt(uuid, 16); uuid = string10to64(uuidNum); if (uuid.length > 22) { uuid = uuid.slice(0, 22); } if (uuid.length < 22) { const len = 22 - uuid.length; for (let i = 0; i < len; i++) { uuid = uuid + '0'; } } return uuid; }; class Heartbeat { constructor(pongRes, connectionListener) { this._timerId = 0; this._heartbeatTimeoutId = 0; this._isFirstPing = true; this._hasPingRes = pongRes; this._connectionListener = connectionListener; } start(cppHeartbeatFunc, cppEngine) { const self = this; const startHeartbeat = () => { const time = this._isFirstPing ? 0 : 15 * 1000; self._timerId = setTimeout(() => { self._isFirstPing = false; if (self._hasPingRes) { cppHeartbeatFunc.call(cppEngine); self._hasPingRes = false; startHeartbeat(); } else { self._heartbeatTimeoutId = setTimeout(() => { // 网络不可用后,ping 超时暂不抛出,状态监听器会抛出网络不可用 // self._connectionListener.call(cppEngine, ErrorCode.NETWORK_ERROR) }, 90 * 1000); } }, time); }; startHeartbeat(); } stop() { clearTimeout(this._timerId); } setHeartbeatRes(hasRes) { this._hasPingRes = hasRes; if (this._hasPingRes) { clearTimeout(this._heartbeatTimeoutId); } } } /** * 用于对接协议栈的基础引擎桥接类 */ class CPPEngine extends AEngine { constructor(_runtime, _appkey, _watcher, _apiVersion, _cppProtocol, _options) { super(_runtime, _appkey, _watcher, _apiVersion, _options); this._cppProtocol = _cppProtocol; this._currentToken = ''; this._connectionStatus = ConnectionStatus$1.DISCONNECTED; this._promiseHandler = {}; this._customMessageType = {}; this._heartbeat = {}; this._connectionListener = (status) => { }; this._cppConnectionStatus = ConnectionStatus$1.DISCONNECTED; this.init(_appkey, { version: _apiVersion, dbPath: _options.dbPath || '', navi: _options.navigators[0] || '' }); this._setConnectionStatusListener(_watcher.status); this._setOnReceiveMessageListener(_watcher.message); this._setConversationStatusListener(_watcher.conversation); } /** * 批量注册内置消息 */ _registerMsgTypes() { SEND_MESSAGE_TYPE_OPTION['RC:RcCmd'] = { isCounted: false, isPersited: false }; for (const messageType in SEND_MESSAGE_TYPE_OPTION) { const { isCounted, isPersited } = SEND_MESSAGE_TYPE_OPTION[messageType]; let msgOptions = 0; if (isPersited) { msgOptions = msgOptions | 0x01; } if (isCounted) { msgOptions = msgOptions | 0x02; } this._cppProtocol.registerMessageType(messageType, msgOptions); } } /** * 消息构建 */ _buildMessage(result, isOffLineMessage) { const receivedCppMessage = JSON.parse(result); const { channelId, conversationType, targetId, senderUserId, content, objectName, messageUid, direction, status, source, messageId, sentTime } = receivedCppMessage; let msgContent; // try { // msgContent = content ? JSON.parse(content) : content // } catch (error) { // logger.error('cpp engine build messaga error:', error) // msgContent = content // } if (isObject(content)) { msgContent = content; } else { msgContent = content ? JSON.parse(content) : content; } let msgOptions = { isCounted: false, isPersited: false }; if (objectName in SEND_MESSAGE_TYPE_OPTION) { msgOptions = SEND_MESSAGE_TYPE_OPTION[objectName]; } else if (objectName in this._customMessageType) { msgOptions = this._customMessageType[objectName]; } const isOffline = isUndefined(isOffLineMessage) ? (sentTime < this.connectedTime) : isOffLineMessage; const msg = { channelId, conversationType, targetId, senderUserId, content: msgContent || {}, messageType: objectName, messageUId: messageUid, messageDirection: direction, isOffLineMessage: isOffline, sentTime, receivedTime: 0, isPersited: msgOptions.isPersited, isCounted: msgOptions.isCounted, isMentioned: false, disableNotification: false, isStatusMessage: false, canIncludeExpansion: false, expansion: null, receivedStatus: status, messageId }; if (direction === MessageDirection$1.RECEIVE) { msg.receivedStatus = status; } else if (direction === MessageDirection$1.SEND) { msg.sentStatus = status; } return msg; } /** * 会话构建 */ _buildConversation(result) { const conver = JSON.parse(result); const { channelId, conversationType, targetId, unreadCount: unreadMessageCount, lastestMsg, isTop, isBlocked } = conver; const isTopToBool = isTop === 1; const isNotify = isBlocked === 1 ? NotificationStatus$1.OPEN : NotificationStatus$1.CLOSE; return { channelId, conversationType, targetId, unreadMessageCount, latestMessage: this._buildMessage(lastestMsg), hasMentioned: false, mentionedInfo: null, notificationStatus: isNotify, isTop: isTopToBool, lastUnreadTime: 0 }; } /** * 设置连接状态监听器 * ConnectionStatus_TokenIncorrect = 31004, * ConnectionStatus_Connected = 0, * ConnectionStatus_KickedOff = 6,// 其他设备登录 * ConnectionStatus_Connecting = 10,// 连接中 * ConnectionStatus_SignUp = 12, // 未登录 * ConnectionStatus_NetworkUnavailable = 1, // 连接断开 * ConnectionStatus_ServerInvalid = 8, // 断开 * ConnectionStatus_ValidateFailure = 9,//断开 * ConnectionStatus_Unconnected = 11,//断开 * ConnectionStatus_DisconnExecption = 31011 //断开 * RC_NAVI_MALLOC_ERROR = 30000,//断开 * RC_NAVI_NET_UNAVAILABLE= 30002,//断开 * RC_NAVI_SEND_FAIL = 30004,//断开 * RC_NAVI_REQ_TIMEOUT = 30005,//断开 * RC_NAVI_RECV_FAIL = 30006,//断开 * RC_NAVI_RESOURCE_ERROR = 30007,//断开 * RC_NAVI_NODE_NOT_FOUND = 30008,//断开 * RC_NAVI_DNS_ERROR = 30009,//断开 */ _setConnectionStatusListener(listener) { this._connectionListener = listener; this._cppProtocol.setConnectionStatusListener((status) => { logger.warn('protocol connection status changed:', status); this._cppConnectionStatus = status; let connectionStatus; switch (status) { case 10: connectionStatus = ConnectionStatus$1.CONNECTING; break; case 31004: setTimeout(() => { this._promiseHandler.connect && this._promiseHandler.connect.resolve(ErrorCode$1.RC_CONN_USER_OR_PASSWD_ERROR); }); return; case 12: connectionStatus = ConnectionStatus$1.DISCONNECTED; break; case 13: connectionStatus = ConnectionStatus$1.BLOCKED; break; case 1: case 8: case 9: case 11: case 31011: case 30000: case 30002: connectionStatus = ConnectionStatus$1.NETWORK_UNAVAILABLE; break; case 30010: // 收到 30010 说明协议栈已重连失败,SDK 内部开始尝试定时重连 this._try2Reconnect(); connectionStatus = ConnectionStatus$1.NETWORK_UNAVAILABLE; break; case 0: case 33005: connectionStatus = ConnectionStatus$1.CONNECTED; this.connectedTime = new Date().getTime() - this._cppProtocol.getDeltaTime(); setTimeout(() => { this._promiseHandler.connect && this._promiseHandler.connect.resolve(ErrorCode$1.SUCCESS); this._heartbeat = new Heartbeat(true, listener); this._heartbeat.start(this._sendHeartbeat, this); }); break; case ConnectionStatus$1.KICKED_OFFLINE_BY_OTHER_CLIENT: connectionStatus = ConnectionStatus$1.KICKED_OFFLINE_BY_OTHER_CLIENT; break; case 30004: // 断网内部重连失败状态码,不向上层抛出 return; default: connectionStatus = status; break; } this._connectionStatus = connectionStatus; setTimeout(() => { listener(connectionStatus); }); }, this._dbInitCallback, () => { this._heartbeat.setHeartbeatRes(true); }); } /** * 数据库初始化回调 */ _dbInitCallback(code) { } /** * 发送心跳 */ _sendHeartbeat() { this._cppProtocol.sendHeartbeat(); } /** * 重连 */ _try2Reconnect() { if (this._cppConnectionStatus !== 30010 && this._cppConnectionStatus !== 30004) { return; } this._cppProtocol.connectWithToken(this._currentToken, '', () => { }); // 等待 5s 后重新尝试 setTimeout(() => { this._try2Reconnect(); }, 5000); } /** * 设置消息监听器 */ _setOnReceiveMessageListener(listener) { this._cppProtocol.setOnReceiveMessageListener((result, leftCount, offline, hasMore) => { // 构建消息 const message = this._buildMessage(result, offline); // 触发 API Context 消息监听 listener(message); }); } /** * 设置会话状态监听器 */ _setConversationStatusListener(listener) { this._cppProtocol.setConversationStatusListener((result) => { const list = JSON.parse(result).list; const updatedConvers = []; list.forEach(conver => { const converData = JSON.parse(conver.obj); const { conversationType, targetId, status, channelId } = converData; const statusObj = { notificationStatus: 2, isTop: false }; status.forEach(status => { const itemObj = JSON.parse(status.item); if (itemObj.type === 1) { statusObj.notificationStatus = Number(itemObj.value) === 1 ? NotificationStatus$1.OPEN : NotificationStatus$1.CLOSE; } else { statusObj.isTop = Number(itemObj.value) === 1; } }); updatedConvers.push({ channelId, conversationType, targetId, updatedItems: { notificationStatus: { val: statusObj.notificationStatus, time: 0 }, isTop: { val: statusObj.isTop, time: 0 } } }); }); listener(updatedConvers); }); } /** * 清空监听器 */ _clearListener() { this._cppProtocol.setOnReceiveMessageListener(); this._cppProtocol.setConnectionStatusListener(); this._cppProtocol.setOnReceiveStatusListener(); } /** * 初始化 */ init(appkey, config) { // 1、获取 SDK 信息 let sdkInfo = this._cppProtocol.initWithAppkey(appkey, config === null || config === void 0 ? void 0 : config.dbPath, config); if (sdkInfo) { sdkInfo = JSON.parse(sdkInfo); } // 2、调用 c++ 接口注册内置消息 this._registerMsgTypes(); // 3、设置 DeviceId const deviceIdKey = `${appkey}_device_id`; let deviceId = this.runtime.localStorage.getItem(deviceIdKey); if (!deviceId) { deviceId = getUUID22(); this.runtime.localStorage.setItem(deviceIdKey, deviceId); } this._cppProtocol.setDeviceId(deviceId); return sdkInfo; } /** * 注册自定义消息 */ registerMessageType(messageType, isPersited, isCounted, searchProps) { let msgOptions = 0; if (isPersited) { msgOptions = msgOptions | 0x01; } if (isCounted) { msgOptions = msgOptions | 0x02; } this._customMessageType[messageType] = { isCounted, isPersited }; this._cppProtocol.registerMessageType(messageType, msgOptions, searchProps); } /** * 连接 */ connect(token, naviInfo, connectType, userId, options = {}) { this._currentToken = token; // 设置环境信息 if (options.type) { this._cppProtocol.setEnvironment(true); } // 通过 token 连接 this._cppProtocol.connectWithToken(token, userId, (userId) => { this.currentUserId = userId; }); return new Promise((resolve, reject) => { this._promiseHandler.connect = { resolve, reject }; }); } /** * 断开链接 */ disconnect() { // this._clearListener() this._cppProtocol.disconnect(true); this._heartbeat.stop(); this._connectionListener(ConnectionStatus$1.DISCONNECTED); } /** * 注销登录 */ logout() { this.disconnect(); } getConnectTime() { return new Promise((resolve, reject) => { resolve({ code: ErrorCode$1.SUCCESS, data: this.connectedTime }); }); } /** * 设置用户在线状态监听器 */ setUserStatusListener(config, listener) { this._cppProtocol.setOnReceiveStatusListener((userId, status) => { listener({ userId: userId, status: status }); }); const userIds = config.userIds || []; if (userIds.length) { this.subscribeUserStatus(userIds); } } /** * 订阅用户在线状态 */ subscribeUserStatus(userIds) { return new Promise((resolve, reject) => { this._cppProtocol.subscribeUserStatus(userIds, () => { resolve(ErrorCode$1.SUCCESS); }, resolve); }); } /** * 设置当前用户在线状态 */ setUserStatus(status) { return new Promise((resolve, reject) => { this._cppProtocol.setUserStatus(status, () => { resolve(ErrorCode$1.SUCCESS); }, resolve); }); } /** * 获取用户状态 */ getUserStatus(userId) { return new Promise((resolve, reject) => { this._cppProtocol.getUserStatus(userId, (status) => { resolve({ code: ErrorCode$1.SUCCESS, data: { status } }); }, (code) => { resolve({ code }); }); }); } /** * 发送消息 */ sendMessage(conversationType, targetId, options) { let { messageType, content, pushContent, pushData, directionalUserIdList, disableNotification, canIncludeExpansion, expansion, isVoipPush, pushConfig, channelId } = options; let { iOSConfig, androidConfig, pushTitle, pushContent: newPushContent, pushData: newPushData, disablePushTitle, forceShowDetailContent } = pushConfig || {}; const serverPushConfigStr = pushConfigsToJSON(iOSConfig, androidConfig); return new Promise((resolve, reject) => { // pushContent、pushData 优先使用 pushConfig.pushContent pushConfig.pushData pushContent = newPushContent || pushContent || ''; pushData = newPushData || pushData || ''; disableNotification = disableNotification || false; expansion = expansion || ''; isVoipPush = isVoipPush || false; pushTitle = pushTitle || ''; newPushContent = newPushContent || ''; newPushData = newPushData || ''; disablePushTitle = disablePushTitle || false; forceShowDetailContent = forceShowDetailContent || false; canIncludeExpansion = canIncludeExpansion || false; const notificationId = (androidConfig === null || androidConfig === void 0 ? void 0 : androidConfig.notificationId) || ''; // TODO 待确认逻辑 start const isGroup = conversationType === ConversationType$1.GROUP; directionalUserIdList = []; if (isGroup && messageType === MessageType$1.READ_RECEIPT_RESPONSE) { if (content.receiptMessageDic) { for (const key in content.receiptMessageDic) { directionalUserIdList === null || directionalUserIdList === void 0 ? void 0 : directionalUserIdList.push(key); } } } if (isGroup && messageType === MessageType$1.READ_RECEIPT_REQUEST) { directionalUserIdList === null || directionalUserIdList === void 0 ? void 0 : directionalUserIdList.push(this.currentUserId); } // TODO 待确认逻辑 end const onSuccess = (message, code) => { const msg = this._buildMessage(message, false); if (code === ErrorCode$1.SENSITIVE_REPLACE) { return resolve({ code }); } return resolve({ code: ErrorCode$1.SUCCESS, data: msg }); }; const onError = (message, code) => { const msg = this._buildMessage(message, false); return resolve({ code, data: msg }); }; const pushTplId = ''; // PUSH 模板 ID,PUSH 二期功能 this._cppProtocol.sendMessage(onSuccess, onError, conversationType, targetId, messageType, JSON.stringify(content), directionalUserIdList, disableNotification, disablePushTitle, forceShowDetailContent, pushContent, pushData, notificationId, pushTitle, serverPushConfigStr, pushTplId, canIncludeExpansion, JSON.stringify(expansion), isVoipPush, channelId); }); } /** * 撤回消息 */ recallMsg(conversationType, targetId, messageUId, sentTime, recallMsgOptions) { return new Promise((resolve, reject) => { let { user, pushContent, channelId, oriContent } = recallMsgOptions; pushContent = pushContent || ''; const message = { conversationType, targetId, senderUserId: this.currentUserId, content: oriContent, objectName: MessageType$1.RECALL, messageUid: messageUId, messageDirection: MessageDirection$1.SEND, status: ReceivedStatus$1.UNREAD, sentTime }; const returnMsg = this._buildMessage(JSON.stringify(message), false); const disableNotification = false; const disablePushTitle = false; const forceShowDetailContent = false; const pushData = ''; const notificationId = ''; const pushTitle = ''; const pushConfig = ''; const pushTemplateId = ''; const onSuccess = () => { resolve({ code: ErrorCode$1.SUCCESS, data: returnMsg }); }; const onError = (code) => { resolve({ code }); }; this._cppProtocol.recallMessage(onSuccess, onError, MessageType$1.RECALL, JSON.stringify(returnMsg), disableNotification, disablePushTitle, forceShowDetailContent, pushContent, pushData, notificationId, pushTitle, pushConfig, pushTemplateId, channelId); }); } getHistoryMessage(conversationType, targetId, timestamp, count, order, channelId) { return new Promise((resolve, reject) => { timestamp = timestamp || 0; const desc = order === 0; const searchCount = count + 1; const cppMessagaes = this._cppProtocol.getHistoryMessages(conversationType, targetId, timestamp, searchCount, '', desc, channelId); const messages = JSON.parse(cppMessagaes).list; const hisMessages = []; messages.reverse(); for (let i = 0; i < messages.length; i++) { const buildMsg = this._buildMessage(messages[i].obj); hisMessages[i] = buildMsg; } resolve({ code: ErrorCode$1.SUCCESS, data: { list: searchCount === hisMessages.length ? hisMessages.slice(1, searchCount) : hisMessages, hasMore: count < hisMessages.length // 如果查到历史消息的长度大于用户实际传入的长度,说明还有更多消息 } }); }); } getRemoteHistoryMessages(conversationType, targetId, timestamp, count, order, channelId) { return new Promise((resolve, reject) => { timestamp = timestamp || 0; const desc = 0; const needRepeatMsg = true; const onSuccess = (result, hasMore) => { const messages = JSON.parse(result).list; const hisMessages = []; messages.reverse(); for (let i = 0; i < messages.length; i++) { const buildMsg = this._buildMessage(messages[i].obj); hisMessages[i] = buildMsg; } resolve({ code: ErrorCode$1.SUCCESS, data: { list: hisMessages, hasMore: !!hasMore } }); }; const onError = (code) => { resolve({ code }); }; this._cppProtocol.getRemoteHistoryMessages(conversationType, targetId, timestamp, count, onSuccess, onError, desc, needRepeatMsg, channelId); }); } deleteRemoteMessage(conversationType, targetId, messages, channelId) { return new Promise((resolve, reject) => { const msgsStr = JSON.stringify(messages); const onSuccess = () => { resolve(ErrorCode$1.SUCCESS); }; // 保持功能单一性,仅删除远端,不删除本地 const isDelLocal = false; this._cppProtocol.deleteRemoteHistoryMessages(conversationType, targetId, msgsStr, isDelLocal, channelId, onSuccess, resolve); }); } deleteRemoteMessageByTimestamp(conversationType, targetId, timestamp, channelId) { return new Promise((resolve, reject) => { const onSuccess = () => { resolve(ErrorCode$1.SUCCESS); }; const onError = (code) => { resolve(code); }; this._cppProtocol.clearRemoteHistoryMessages(conversationType, targetId, timestamp, onSuccess, onError, channelId); }); } clearMessages(conversationType, targetId, channelId) { return new Promise((resolve, reject) => { this._cppProtocol.clearMessages(conversationType, targetId, channelId); resolve(ErrorCode$1.SUCCESS); }); } /** * 获取全部会话列表 */ getConversationList(count, conversationType, startTime, order, channelId = '') { return new Promise((resolve, reject) => { const converTypes = [1, 3, 6, 7]; const result = this._cppProtocol.getConversationList(converTypes, channelId); const resultList = JSON.parse(result); const converList = resultList.list; const convers = []; for (let i = 0; i < converList.length; i++) { convers.push(this._buildConversation(converList[i].obj)); } resolve({ code: ErrorCode$1.SUCCESS, data: convers }); }); } /** * 获取指定会话 */ getConversation(conversationType, targetId, channelId) { return new Promise((resolve, reject) => { const result = this._cppProtocol.getConversation(conversationType, targetId, channelId); resolve({ code: ErrorCode$1.SUCCESS, data: this._buildConversation(result) }); }); } /** * 删除指定会话 */ removeConversation(conversationType, targetId, channelId) { return new Promise((resolve, reject) => { this._cppProtocol.removeConversation(conversationType, targetId, channelId); resolve(ErrorCode$1.SUCCESS); }); } /** * 删除所有会话 */ clearConversations(conversationTypes, channelId) { return new Promise((resolve, reject) => { let types = []; if (isArray(conversationTypes)) { types = conversationTypes; } else { types = [ConversationType$1.PRIVATE, ConversationType$1.GROUP, ConversationType$1.SYSTEM, ConversationType$1.PUBLIC_SERVICE]; } this._cppProtocol.clearConversations(types, channelId); resolve(ErrorCode$1.SUCCESS); }); } /** * 获取所有会话未读数 */ getAllConversationUnreadCount(channelId) { return new Promise((resolve, reject) => { // getTotalUnreadCount 如果传入 conversationTyps 可按类型, TODO ? 是否分开写? const types = [ConversationType$1.PRIVATE, ConversationType$1.GROUP, ConversationType$1.SYSTEM, ConversationType$1.PUBLIC_SERVICE]; const isIncludeNotDisturb = true; const count = this._cppProtocol.getTotalUnreadCount(types, isIncludeNotDisturb, channelId); resolve({ code: ErrorCode$1.SUCCESS, data: count }); }); } /** * 获取指定会话未读数 */ getConversationUnreadCount(conversationType, targetId, channelId = '') { return new Promise((resolve, reject) => { const count = this._cppProtocol.getUnreadCount(conversationType, targetId, channelId); resolve({ code: ErrorCode$1.SUCCESS, data: count }); }); } /** * 清除指定会话未读数 */ clearConversationUnreadCount(conversationType, targetId, channelId = '') { return new Promise((resolve, reject) => { this._cppProtocol.clearUnreadCount(conversationType, targetId, channelId); resolve(ErrorCode$1.SUCCESS); }); } /** * 清除时间戳之前的未读数 */ clearUnreadCountByTimestamp(conversationType, targetId, timestamp, channelId) { return new Promise((resolve, reject) => { this._cppProtocol.clearUnreadCountByTimestamp(conversationType, targetId, timestamp, channelId); resolve(ErrorCode$1.SUCCESS); }); } /** * 设置会话置顶 */ setConversationToTop(conversationType, targetId, isTop, channelId = '') { return new Promise((resolve, reject) => { const isCreateConversation = true; this._cppProtocol.setConversationToTop(conversationType, targetId, isTop, channelId, isCreateConversation); resolve(ErrorCode$1.SUCCESS); }); } /** * 设置会话隐藏 */ setConversationHidden(conversationType, targetId, isHidden, channelId) { return new Promise((resolve, reject) => { this._cppProtocol.setConversationHidden(conversationType, targetId, isHidden, channelId); resolve(ErrorCode$1.SUCCESS); }); } /** * 设置会话置顶 */ setConversationNotificationStatus(conversationType, targetId, isNotify, channelId) { return new Promise((resolve, reject) => { this._cppProtocol.setConversationNotificationStatus(conversationType, targetId, isNotify, () => { resolve(ErrorCode$1.SUCCESS); }, resolve, channelId); }); } /** * 设置会话置顶、免打扰 */ setConversationStatus(conversationType, targetId, isBlocked, isTop, channelId) { return new Promise((resolve, reject) => { const isCreateConversation = true; this._cppProtocol.setConversationStatus(conversationType, targetId, isBlocked, isTop, () => { resolve(ErrorCode$1.SUCCESS); }, resolve, channelId, isCreateConversation); }); } /** * 获取会话置顶状态 */ getConversationNotificationStatus(conversationType, targetId, channelId) { return new Promise((resolve, reject) => { const notify = this._cppProtocol.getConversationNotificationStatus(conversationType, targetId, channelId); resolve({ code: ErrorCode$1.SUCCESS, data: notify ? NotificationStatus$1.OPEN : NotificationStatus$1.CLOSE }); }); } /** * 通过关键字搜索会话 * @description * 不传 messageTypes 默认仅支持 文本消息、文件消息, 自定义消息类型需传 */ searchConversationByContent(keyword, customMessageTypes, channelId, conversationTypes) { return new Promise((resolve, reject) => { conversationTypes = conversationTypes || [1, 3, 6, 7]; const data = this._cppProtocol.searchConversationByContent(conversationTypes, keyword, customMessageTypes, channelId); const list = JSON.parse(data).list; const convers = []; for (let i = 0; i < list.length; i++) { convers[i] = this._buildConversation(list[i].obj); } resolve({ code: ErrorCode$1.SUCCESS, data: convers }); }); } /** * 按内容搜索会话内的消息 */ searchMessageByContent(conversationType, targetId, keyword, timestamp, count, total, channelId) { return new Promise((resolve, reject) => { const isReturnMatchedNum = 1; this._cppProtocol.searchMessageByContent(conversationType, targetId, keyword, timestamp, count, isReturnMatchedNum, (result, matched) => { const list = result ? JSON.parse(result).list : []; const msgs = []; for (let i = 0; i < list.length; i++) { msgs[i] = this._buildMessage(list[i].obj); } resolve({ code: ErrorCode$1.SUCCESS, data: { messages: msgs, count: matched } }); }, channelId); }); } /** * 获取会话下所有未读的 @ 消息 */ getUnreadMentionedMessages(conversationType, targetId, channelId) { const mentions = JSON.parse(this._cppProtocol.getUnreadMentionedMessages(conversationType, targetId, channelId)).list; for (let i = 0; i < mentions.length; i++) { // var temp = JSON.parse(mentions[i].obj) // temp.content = JSON.parse(temp.content) mentions[i] = this._buildMessage(mentions[i].obj); } return mentions; } addToBlacklist(userId) { return new Promise((resolve, reject) => { this._cppProtocol.addToBlacklist(userId, () => { resolve(ErrorCode$1.SUCCESS); }, resolve); }); } removeFromBlacklist(userId) { return new Promise((resolve, reject) => { this._cppProtocol.removeFromBlacklist(userId, () => { resolve(ErrorCode$1.SUCCESS); }, resolve); }); } getBlacklist() { return new Promise((resolve, reject) => { this._cppProtocol.getBlacklist((userIds) => { resolve({ code: ErrorCode$1.SUCCESS, data: userIds }); }, (code) => { resolve({ code }); }); }); } getBlacklistStatus(userId) { return new Promise((resolve, reject) => { this._cppProtocol.getBlacklistStatus(userId, (result) => { resolve({ code: ErrorCode$1.SUCCESS, data: result }); }, (code) => { resolve({ code }); }); }); } insertMessage(conversationType, targetId, insertOptions) { let { content: msgContent, senderUserId, messageType, messageDirection, readStatus, sendStatus, sentTime, searchContent, isUnread, messageUId, disableNotification, canIncludeExpansion, expansionMsg, channelId } = insertOptions; msgContent = JSON.stringify(msgContent); return new Promise((resolve, reject) => { const onSuccess = () => { }; const onError = (error) => { resolve({ code: error }); }; const msg = this._cppProtocol.insertMessage(conversationType, targetId, senderUserId, messageType, msgContent, onSuccess, onError, messageDirection, readStatus, sendStatus, sentTime, searchContent, isUnread, messageUId, disableNotification, canIncludeExpansion, expansionMsg, channelId); const receivedMessage = this._buildMessage(msg, false); resolve({ code: ErrorCode$1.SUCCESS, data: receivedMessage }); }); } deleteMessages(timestamps) { return new Promise((resolve, reject) => { this._cppProtocol.deleteMessages(timestamps); resolve(ErrorCode$1.SUCCESS); }); } deleteMessagesByTimestamp(conversationType, targetId, timestamp, cleanSpace, channelId) { return new Promise((resolve, reject) => { this._cppProtocol.deleteMessagesByTimestamp(conversationType, targetId, timestamp, cleanSpace, channelId); resolve(ErrorCode$1.SUCCESS); }); } getMessage(messageId) { return new Promise((resolve, reject) => { const result = this._cppProtocol.getMessage(messageId); const message = this._buildMessage(result, false); resolve({ code: ErrorCode$1.SUCCESS, data: message }); }); } setMessageContent(messageId, content, messageType) { return new Promise((resolve, reject) => { content = JSON.stringify(content); this._cppProtocol.setMessageContent(messageId, content, messageType); resolve(ErrorCode$1.SUCCESS); }); } setMessageSearchField(messageId, content, searchFiles) { return new Promise((resolve, reject) => { this._cppProtocol.setMessageSearchField(messageId, content, searchFiles); resolve(ErrorCode$1.SUCCESS); }); } setMessageSentStatus(messageId, sentStatus) { return new Promise((resolve, reject) => { this._cppProtocol.setMessageSentStatus(messageId, sentStatus); resolve(ErrorCode$1.SUCCESS); }); } setMessageReceivedStatus(messageId, receivedStatus) { return new Promise((resolve, reject) => { this._cppProtocol.setMessageReceivedStatus(messageId, receivedStatus); resolve(ErrorCode$1.SUCCESS); }); } saveConversationMessageDraft(conversationType, targetId, draft) { throw new Error('Method not implemented.'); } getConversationMessageDraft(conversationType, targetId) { throw new Error('Method not implemented.'); } clearConversationMessageDraft(conversationType, targetId) { throw new Error('Method not implemented.'); } pullConversationStatus(timestamp) { throw new Error('Method not implemented.'); } /** * 协议栈暂时仅支持单独设置免打扰和置顶 */ batchSetConversationStatus(statusList) { const { conversationType, targetId, isTop, notificationStatus, channelId } = statusList[0]; if (isTop !== undefined && notificationStatus === undefined) { return this.setConversationToTop(conversationType, targetId, isTop, channelId); } else if (notificationStatus !== undefined && isTop === undefined) { const isBlocked = notificationStatus === NotificationStatus$1.OPEN; return this.setConversationNotificationStatus(conversationType, targetId, isBlocked, channelId); } else { const isBlocked = notificationStatus === NotificationStatus$1.OPEN; return this.setConversationStatus(conversationType, targetId, isBlocked, isTop, channelId); } } pullUserSettings(version) { throw new Error('Method not implemented.'); } joinChatroom(chatroomId, count) { return new Promise((resolve, reject) => { this._cppProtocol.joinChatRoom(chatroomId, count, () => { resolve(ErrorCode$1.SUCCESS); }, resolve); }); } joinExistChatroom(chatroomId, count) { throw new Error('Method not implemented.'); } quitChatroom(chatroomId) { return new Promise((resolve, reject) => { this._cppProtocol.quitChatRoom(chatroomId, () => { resolve(ErrorCode$1.SUCCESS); }, resolve); }); } /** * 获取聊天室信息 * @description * 协议栈返回数据里不带用户加入时间 */ getChatroomInfo(chatroomId, count, order) { return new Promise((resolve, reject) => { this._cppProtocol.getChatroomInfo(chatroomId, count, order, (result, count) => { const list = result ? JSON.parse(result).list : []; const userInfos = []; if (list.length > 0) { for (let i = 0; i < list.length; i++) { userInfos.push(JSON.parse(list[i].obj)); } } resolve({ code: ErrorCode$1.SUCCESS, data: { userInfos, userCount: count } }); }, (code) => { resolve({ code }); }); }); } getChatroomHistoryMessages(chatroomId, timestamp, count, order) { throw new Error('Method not implemented.'); } setChatroomEntry(chatroomId, entry) { throw new Error('Method not implemented.'); } forceSetChatroomEntry(chatroomId, entry) { throw new Error('Method not implemented.'); } removeChatroomEntry(chatroomId, entry) { throw new Error('Method not implemented.'); } forceRemoveChatroomEntry(chatroomId, entry) { throw new Error('Method not implemented.'); } getChatroomEntry(chatroomId, key) { throw new Error('Method not implemented.'); } getAllChatroomEntry(chatroomId) { throw new Error('Method not implemented.'); } getFileToken(fileType, fileName) { return new Promise((resolve, reject) => { const uploadFileName = getUploadFileName(fileType, fileName); this._cppProtocol.getUploadToken(fileType, uploadFileName, (token, bosToken, bosDate, bosPath, ossToken, ossPolicy, ossSignature, ossBucketName) => { resolve({ code: ErrorCode$1.SUCCESS, data: { token, deadline: 0, bosToken, bosDate, path: bosPath, osskeyId: ossToken, ossPolicy, ossSign: ossSignature, ossBucketName, fileName: uploadFileName } }); }, (code) => { resolve({ code }); }); }); } getFileUrl(fileType, uploadMethod, fileName, originName) { return new Promise((resolve, reject) => { const onSuccess = (url) => { resolve({ code: ErrorCode$1.SUCCESS, data: { downloadUrl: url } }); }; const onError = (code) => { resolve({ code }); }; const isOss = uploadMethod === UploadMethod$1.ALI; const mimeKey = getMimeKey(fileType); this._cppProtocol.getDownloadUrl(fileType, mimeKey, originName, isOss, onSuccess, onError); }); } clearData() { return new Promise((resolve, reject) => { const result = this._cppProtocol.clearData(); resolve({ code: ErrorCode$1.SUCCESS, data: result }); }); } setDeviceInfo(device) { return new Promise((resolve, reject) => { const id = device.id || ''; this._cppProtocol.setDeviceId(id); }); } getVoIPKey(engineType, channelName) { return new Promise((resolve, reject) => { const extra = ''; const onSuccess = (token) => { resolve({ code: ErrorCode$1.SUCCESS, data: token }); }; const onError = (code) => { resolve({ code }); }; this._cppProtocol.getVoIPKey(engineType, channelName, extra, onSuccess, onError); }); } /** * 以下为 RTC 方法 */ joinRTCRoom(roomId, mode, broadcastType) { throw new Error('Method not implemented.'); } quitRTCRoom(roomId) { throw new Error('Method not implemented.'); } rtcPing(roomId, mode, broadcastType) { throw new Error('Method not implemented.'); } getRTCRoomInfo(roomId) { throw new Error('Method not implemented.'); } getRTCUserInfoList(roomId) { throw new Error('Method not implemented.'); } getRTCUserInfo(roomId) { throw new Error('Method not implemented.'); } setRTCUserInfo(roomId, key, value) { throw new Error('Method not implemented.'); } removeRTCUserInfo(roomId, keys) { throw new Error('Method not implemented.'); } setRTCData(roomId, key, value, isInner, apiType, message) { throw new Error('Method not implemented.'); } setRTCTotalRes(roomId, message, valueInfo, messageType) { throw new Error('Method not implemented.'); } getRTCData(roomId, keys, isInner, apiType) { throw new Error('Method not implemented.'); } removeRTCData(roomId, keys, isInner, apiType, message) { throw new Error('Method not implemented.'); } setRTCOutData(roomId, rtcData, type, message) { throw new Error('Method not implemented.'); } getRTCOutData(roomId, userIds) { throw new Error('Method not implemented.'); } getRTCToken(roomId, mode, broadcastType) { throw new Error('Method not implemented.'); } setRTCState(roomId, reportId) { throw new Error('Method not implemented.'); } getRTCUserList(roomId) { throw new Error('Method not implemented.'); } } class PluginContext { constructor(_context) { this._context = _context; } /** * 获取 `@rongcloud/engine` 包版本 */ getCoreVersion() { return this._context.coreVersion; } /** * 获取当前运行中的 IMLib 版本号 */ getAPIVersion() { return this._context.apiVersion; } /** * 获取当前应用的 appkey */ getAppkey() { return this._context.appkey; } /** * 获取当前已连接用户的 userId * 用户连接建立之前及 disconnect 之后,该方法返回 '' 值 */ getCurrentId() { return this._context.getCurrentUserId(); } /** * 获取当前连接状态 */ getConnectionStatus() { return this._context.getConnectionStatus(); } /** * 发送消息 */ sendMessage(conversationType, targetId, options) { return this._context.sendMessage(conversationType, targetId, options); } /** * 消息注册 * @description 消息注册需在应用初始化完成前进行 * @param objectName 消息类型,如:RC:TxtMsg * @param isPersited 是否存储 * @param isCounted 是否技术 * @param searchProps 搜索字段,只在搭配协议栈使用时有效 */ registerMessageType(objectName, isPersited, isCounted, searchProps = []) { this._context.registerMessageType(objectName, isPersited, isCounted, searchProps); } } class RTCPluginContext extends PluginContext { /** * 获取当前的导航数据 */ getNaviInfo() { return this._context.getInfoFromCache(); } /** * 加入 RTC 房间 * @todo 需确认 `broadcastType` 参数的作用与有效值 * @param roomId * @param mode 房间模式:直播 or 会议 * @param broadcastType */ joinRTCRoom(roomId, mode, broadcastType) { return this._context.joinRTCRoom(roomId, mode, broadcastType); } quitRTCRoom(roomId) { return this._context.quitRTCRoom(roomId); } rtcPing(roomId, mode, broadcastType) { return this._context.rtcPing(roomId, mode, broadcastType); } getRTCRoomInfo(roomId) { return this._context.getRTCRoomInfo(roomId); } getRTCUserInfoList(roomId) { return this._context.getRTCUserInfoList(roomId); } getRTCUserInfo(roomId) { return this._context.getRTCUserInfo(roomId); } setRTCUserInfo(roomId, key, value) { return this._context.setRTCUserInfo(roomId, key, value); } removeRTCUserInfo(roomId, keys) { return this._context.removeRTCUserInfo(roomId, keys); } setRTCData(roomId, key, value, isInner, apiType, message) { return this._context.setRTCData(roomId, key, value, isInner, apiType, message); } /** * @param - roomId * @param - message 向前兼容的消息数据,以兼容旧版本 SDK,即增量数据,如: * ``` * JSON.stringify({ * name: 'RCRTC:PublishResource', * content: { * } * }) * ``` * @param - valueInfo 全量资源数据 * @param - 全量 URI 消息名,即 `RCRTC:TotalContentResources` */ setRTCTotalRes(roomId, /** * 向旧版本 RTCLib 兼容的消息数据 */ message, valueInfo, objectName) { return this._context.setRTCTotalRes(roomId, message, valueInfo, objectName); } getRTCData(roomId, keys, isInner, apiType) { return this._context.getRTCData(roomId, keys, isInner, apiType); } removeRTCData(roomId, keys, isInner, apiType, message) { return this._context.removeRTCData(roomId, keys, isInner, apiType, message); } setRTCOutData(roomId, rtcData, type, message) { return this._context.setRTCOutData(roomId, rtcData, type, message); } getRTCOutData(roomId, userIds) { return this._context.getRTCOutData(roomId, userIds); } getRTCToken(roomId, mode, broadcastType) { return this._context.getRTCToken(roomId, mode, broadcastType); } setRTCState(roomId, report) { return this._context.setRTCState(roomId, report); } getRTCUserList(roomId) { return this._context.getRTCUserList(roomId); } } function cloneMessage(message) { return Object.assign({}, message); } class APIContext { constructor(_runtime, options) { this._runtime = _runtime; this._token = ''; /** * 插件队列,用于逐一派发消息与信令 */ this._pluginContextQueue = []; /** * 核心库版本号,后期与 4.0 IM SDK 版本号保持一致 */ this.coreVersion = "4.2.0"; this._connectionStatus = ConnectionStatus$1.DISCONNECTED; /** * 业务层事件监听器挂载点 */ this._watcher = { message: undefined, conversationState: undefined, chatroomState: undefined, connectionState: undefined, rtcInnerWatcher: undefined, expansion: undefined }; this._options = Object.assign({}, options); this.appkey = this._options.appkey; this.apiVersion = this._options.apiVersion; const { appkey, miniCMPProxy, apiVersion, connectionType } = this._options; // electron 运行时下, cppProtocol 为必填项 if (_runtime.tag === "electron" && !this._options.cppProtocol) { const msg = 'cppProtocol is required'; logger.error(msg); throw new Error(msg); } // 过滤无效地址 this._options.navigators = this._options.navigators.filter(item => /^https?:\/\//.test(item)); // 有自定义导航的状态下,不再使用内置导航地址 if (this._options.navigators.length === 0) { this._options.navigators.push(...PUBLIC_CLOUD_NAVI_URIS); } // 初始化 Navi 模块 this._navi = new Navi(_runtime, appkey, this._options.navigators, miniCMPProxy, apiVersion, connectionType); // 初始化引擎监听器,监听连接状态变化、消息变化以及聊天室状态变化 const engineWatcher = { status: this._connectionStatusListener.bind(this), message: this._messageReceiver.bind(this), chatroom: this._chatroomInfoListener.bind(this), conversation: this._conversationInfoListener.bind(this), expansion: this._expansionInfoListener.bind(this) }; // 初始化引擎 this._engine = this._options.cppProtocol ? new CPPEngine(_runtime, appkey, engineWatcher, apiVersion, this._options.cppProtocol, this._options) : new JSEngine(_runtime, appkey, engineWatcher, apiVersion); } static init(runtime, options) { logger.debug('APIContext.init =>', options.appkey, options.navigators); if (this._context) { logger.error('Repeat initialize!'); return this._context; } { logger.warn('VersionCode:', "1838ab715d966e65fa509d4d5e4ffd76827367a7"); } this._context = new APIContext(runtime, options); return this._context; } static destroy() { if (this._context) { this._context._destroy(); this._context = undefined; } } /** * 安装使用插件,并初始化插件实例 * @param plugin * @param options */ install(plugin, options) { const context = plugin.tag === 'RCRTC' ? new RTCPluginContext(this) : new PluginContext(this); let pluginClient = null; try { if (!plugin.verify(this._runtime)) { return null; } pluginClient = plugin.setup(context, this._runtime, options); } catch (error) { logger.error('install plugin error!\n', error); } pluginClient && this._pluginContextQueue.push(context); return pluginClient; } /** * 连接状态变更回调 * @param message */ _connectionStatusListener(status) { var _a; this._connectionStatus = status; // 通知旧版本 RTCLib、CallLib ((_a = this._watcher.rtcInnerWatcher) === null || _a === void 0 ? void 0 : _a.status) && this._watcher.rtcInnerWatcher.status(status); // 通知插件连接状态变更 this._pluginContextQueue.forEach(item => { item.onconnectionstatechange && item.onconnectionstatechange(status); }); // 通知应用层连接状态变更 this._watcher.connectionState && this._watcher.connectionState(status); } _messageReceiver(message) { /** * 为兼容非插件化的 RTCLib、CallLib,需预先将 * conversationType === 12 * 或 * RCRTC:AcceptMsg... 等消息分别分发给 RTCLib\CallLib */ if (message.conversationType === ConversationType$1.RTC_ROOM || Object.prototype.hasOwnProperty.call(CallLibMsgType, message.messageType)) { /** * 分发 RTCLib 或 CallLib 消息,如果未找到 RTCLib 或 CallLib 注册的消息监听, * 说明未使用旧版本 RTCLib 或 CallLib,消息要分发到插件钩子 */ if (this._watcher.rtcInnerWatcher && this._watcher.rtcInnerWatcher.message) { this._watcher.rtcInnerWatcher.message(cloneMessage(message)); return; } } // 消息分发至插件,并根据插件响应结果确定是否继续向业务层派发 if (this._pluginContextQueue.some((item) => { // 插件不接收消息 if (!item.onmessage) { return false; } try { return item.onmessage(cloneMessage(message)); } catch (err) { logger.error('plugin error =>', err); return false; } })) { return; } // 最终未被过滤的消息派发给应用层 this._watcher.message && this._watcher.message(cloneMessage(message)); } /** * 聊天室相关信息监听 */ _chatroomInfoListener(info) { this._watcher.chatroomState && this._watcher.chatroomState(info); } /** * 会话监听相关 */ _conversationInfoListener(info) { this._watcher.conversationState && this._watcher.conversationState(info); } /** * 消息扩展监听相关 */ _expansionInfoListener(info) { this._watcher.expansion && this._watcher.expansion(info); } /** * 添加事件监听 * @param options */ assignWatcher(watcher) { // 只取有效的四个 key,避免引用透传造成内存泄露 Object.keys(this._watcher).forEach((key) => { if (Object.prototype.hasOwnProperty.call(watcher, key)) { const value = watcher[key]; this._watcher[key] = isFunction(value) || isObject(value) ? value : undefined; } }); } getConnectedTime() { return this._engine.connectedTime; } getCurrentUserId() { return this._engine.currentUserId; } getConnectionStatus() { return this._connectionStatus; } /** * 建立连接,连接失败则抛出异常,连接成功后返回用户 userId,否则返回相应的错误码 * @param token * @param refreshNavi 是否需要重新请求导航,当值为 `false` 时,优先使用有效缓存导航,若缓存失效则重新获取导航 */ connect(token, refreshNavi = false) { return __awaiter(this, void 0, void 0, function* () { if (this._connectionStatus === ConnectionStatus$1.CONNECTED) { return { code: ErrorCode$1.SUCCESS, userId: this._engine.currentUserId }; } if (this._connectionStatus === ConnectionStatus$1.CONNECTING) { return { code: ErrorCode$1.BIZ_ERROR_CONNECTING }; } if (typeof token !== 'string' || token.length === 0) { return { code: ErrorCode$1.RC_CONN_USER_OR_PASSWD_ERROR }; } this._token = token; // 根据 token 解析动态导航,优先从动态导航获取数据 const [, tmpArr] = token.split('@'); const dynamicUris = tmpArr ? tmpArr.split(';').map(item => /^https?:/.test(item) ? item : `https://${item}`) : []; const isCppMode = !!this._options.cppProtocol; // 获取导航数据 const naviInfo = yield this._navi.getInfo(this._getTokenWithoutNavi(), dynamicUris, refreshNavi, isCppMode); if (!naviInfo && !isCppMode) { return { code: ErrorCode$1.RC_NAVI_RESOURCE_ERROR }; } // 开始连接,并监听链接状态变化,状态为 0 则连接成功 const code = yield this._engine.connect(this._getTokenWithoutNavi(), naviInfo, this._options.connectionType); if (code === ErrorCode$1.SUCCESS && !isCppMode) { // TODO 限制 !isCppMode 防止报错,临时解决方案 // 拉取用户级配置 naviInfo.openUS === 1 && this._pullUserSettings(); } return { code, userId: this._engine.currentUserId }; }); } getConnectTime() { return this._engine.getConnectTime(); } /** * 拉取实时配置 web 端需更新 voipCall 字段 */ _pullUserSettings() { return __awaiter(this, void 0, void 0, function* () { // TODO: 持续迭代中,防止 comet 报错 // const res = await this._engine.pullUserSettings(version) // logger.error('TODO:存储配置,需要使用时获取', res) }); } disconnect() { this._engine.disconnect(); this._pluginContextQueue.forEach(item => { if (!item.ondisconnect) { return; } try { item.ondisconnect(); } catch (err) { logger.error('plugin error =>', err); } }); // 为照顾 API 层的 Promise 链式调用,故增加返回 Promise return Promise.resolve(); } reconnect() { return this.connect(this._getTokenWithoutNavi()); } // 获取 token 动态导航前的部分 _getTokenWithoutNavi() { return this._token.replace(/@.+$/, '@'); } /** * 获取当前缓存的导航数据 */ getInfoFromCache() { return this._navi.getInfoFromCache(this._getTokenWithoutNavi()); } /** * 消息注册 * @description 消息注册需在应用初始化完成前进行 * @param objectName 消息类型,如:RC:TxtMsg * @param isPersited 是否存储 * @param isCounted 是否技术 * @param searchProps 搜索字段,只在搭配协议栈使用时有效 */ registerMessageType(objectName, isPersited, isCounted, searchProps = []) { this._engine.registerMessageType(objectName, isPersited, isCounted, searchProps); } /** * 发送消息 * @param conversationType * @param targetId * @param objectName * @param content * @param options */ sendMessage(conversationType, targetId, options) { // 端上不能发送系统消息,若会话类型传入 6 ,抛出参数错误,与移动端一致 if (conversationType === ConversationType$1.SYSTEM) { return Promise.resolve({ code: ErrorCode$1.BIZ_ERROR_INVALID_PARAMETER }); } // 消息 content 需小于 128 KB const contentJson = JSON.stringify(options.content); if (getByteLength(contentJson) > MAX_MESSAGE_CONTENT_BYTES) { return Promise.resolve({ code: ErrorCode$1.RC_MSG_CONTENT_EXCEED_LIMIT }); } return this._engine.sendMessage(conversationType, targetId, options); } /** * 发送扩展消息 * @param messageUId 消息 Id * @param keys 需要删除的 key * @param expansion 设置的扩展 */ sendExpansionMessage(options) { return __awaiter(this, void 0, void 0, function* () { let { conversationType, targetId, messageUId, keys, expansion, originExpansion, removeAll, canIncludeExpansion } = options; // 校验消息是否支持扩展 if (!canIncludeExpansion) { return { code: ErrorCode$1.MESSAGE_KV_NOT_SUPPORT }; } let isExceedLimit = false; let isIllgalEx = false; if (isObject(expansion)) { // 验证扩展总数是否 大于 300 originExpansion = originExpansion || {}; const exKeysLength = Object.keys(expansion).length; const totalExpansion = Object.assign(originExpansion, expansion); const totalExKeysLength = Object.keys(totalExpansion).length; isExceedLimit = totalExKeysLength > 300 || exKeysLength > 20; // 验证 expansion key value 是否合法 for (const key in expansion) { const val = expansion[key]; isExceedLimit = key.length > 32 || val.length > 64; isIllgalEx = !/^[A-Za-z0-9_=+-]+$/.test(key); } } if (isExceedLimit) { return { code: ErrorCode$1.EXPANSION_LIMIT_EXCEET }; } if (isIllgalEx) { return { code: ErrorCode$1.BIZ_ERROR_INVALID_PARAMETER }; } const content = { mid: messageUId }; expansion && (content.put = expansion); keys && (content.del = keys); removeAll && (content.removeAll = 1); // RC:MsgExMsg 类型消息需使用单群聊消息信令:ppMsgP、pgMsgP( Server 端处理不存到历史消息云存储) const { code } = yield this._engine.sendMessage(conversationType, targetId, { content, messageType: MessageType$1.EXPANSION_NOTIFY }); return { code }; }); } /** * 反初始化,清空所有监听及计时器 */ _destroy() { this._watcher = {}; this._engine.disconnect(); this._pluginContextQueue.forEach(item => { if (!item.ondestroy) { return; } try { item.ondestroy(); } catch (err) { logger.error('plugin error =>', err); } }); this._pluginContextQueue.length = 0; } /** * @param conversationType * @param targetId 会话 Id * @param timestamp 拉取时间戳 * @param count 拉取条数 * @param order 1 正序拉取,0 为倒序拉取 */ getHistoryMessage(conversationType, targetId, timestamp = 0, count = 20, order = 0, channelId = '') { return this._engine.getHistoryMessage(conversationType, targetId, timestamp, count, order, channelId); } /** * 获取会话列表 * @param count 指定获取数量, 不传则获取全部会话列表,默认 `300` */ getConversationList(count = 300, conversationType, startTime, order, channelId = '') { return this._engine.getConversationList(count, conversationType, startTime, order, channelId); } /** * 删除会话 */ removeConversation(conversationType, targetId, channelId = '') { return this._engine.removeConversation(conversationType, targetId, channelId); } /** * 清除会话消息未读数 */ clearUnreadCount(conversationType, targetId, channelId = '') { return this._engine.clearConversationUnreadCount(conversationType, targetId, channelId); } /** * 获取指定会话消息未读数 */ getUnreadCount(conversationType, targetId, channelId = '') { return this._engine.getConversationUnreadCount(conversationType, targetId, channelId); } getTotalUnreadCount(channelId = '') { return this._engine.getAllConversationUnreadCount(channelId); } setConversationStatus(conversationType, targetId, isTop, notificationStatus, channelId = '') { const statusList = [{ conversationType, targetId, isTop, notificationStatus, channelId }]; return this._engine.batchSetConversationStatus(statusList); } saveConversationMessageDraft(conversationType, targetId, draft) { return this._engine.saveConversationMessageDraft(conversationType, targetId, draft); } getConversationMessageDraft(conversationType, targetId) { return this._engine.getConversationMessageDraft(conversationType, targetId); } clearConversationMessageDraft(conversationType, targetId) { return this._engine.clearConversationMessageDraft(conversationType, targetId); } recallMessage(conversationType, targetId, messageUId, sentTime, recallMsgOptions) { return this._engine.recallMsg(conversationType, targetId, messageUId, sentTime, recallMsgOptions); } /** * 删除远端消息 * @param conversationType * @param targetId * @param list */ deleteRemoteMessage(conversationType, targetId, list, channelId = '') { return this._engine.deleteRemoteMessage(conversationType, targetId, list, channelId); } /** * 根据时间戳删除指定时间之前的 * @param conversationType * @param targetId * @param timestamp */ deleteRemoteMessageByTimestamp(conversationType, targetId, timestamp, channelId = '') { return this._engine.deleteRemoteMessageByTimestamp(conversationType, targetId, timestamp, channelId); } /** * 加入聊天室,若聊天室不存在则创建聊天室 * @param roomId 聊天室房间 Id * @param count 进入聊天室成功后,自动拉取的历史消息数量,默认值为 `10`,最大有效值为 `50`,`-1` 为不拉取 */ joinChatroom(roomId, count = 10) { return this._engine.joinChatroom(roomId, count); } /** * 加入聊天室,若聊天室不存在则抛出异常 * @param roomId 聊天室房间 Id * @param count 进入聊天室成功后,自动拉取的历史消息数量,默认值为 `10`,最大有效值为 `50`,`-1` 为不拉取 */ joinExistChatroom(roomId, count = 10) { return this._engine.joinExistChatroom(roomId, count); } /** * 退出聊天室 * @param roomId */ quitChatroom(roomId) { return this._engine.quitChatroom(roomId); } /** * 获取聊天室房间数据 * @description count 或 order 有一个为 0 时,只返回成员总数,不返回成员列表信息 * @param roomId 聊天室 Id * @param count 获取房间人员列表数量,最大有效值 `20`,最小值未 `0`,默认为 0 * @param order 人员排序方式,`1` 为正序,`2` 为倒序,默认为 0 */ getChatroomInfo(roomId, count = 0, order = 0) { return this._engine.getChatroomInfo(roomId, count, order); } /** * 在指定聊天室中设置自定义属性 * @description 仅聊天室中不存在此属性或属性设置者为己方时可设置成功 * @param roomId 聊天室房间 id * @param entry 属性信息 */ setChatroomEntry(roomId, entry) { return this._engine.setChatroomEntry(roomId, entry); } /** * 在指定聊天室中强制增加 / 修改任意聊天室属性 * @description 仅聊天室中不存在此属性或属性设置者为己方时可设置成功 * @param roomId 聊天室房间 id * @param entry 属性信息 */ forceSetChatroomEntry(roomId, entry) { return this._engine.forceSetChatroomEntry(roomId, entry); } /** * 删除聊天室属性 * @description 该方法仅限于删除自己设置的聊天室属性 * @param roomId 聊天室房间 id * @param entry 要移除的属性信息 */ removeChatroomEntry(roomId, entry) { return this._engine.removeChatroomEntry(roomId, entry); } /** * 强制删除任意聊天室属性 * @description 该方法仅限于删除自己设置的聊天室属性 * @param roomId 聊天室房间 id * @param entry 要移除的属性信息 */ forceRemoveChatroomEntry(roomId, entry) { return this._engine.forceRemoveChatroomEntry(roomId, entry); } /** * 获取聊天室中的指定属性 * @param roomId 聊天室房间 id * @param key 属性键名 */ getChatroomEntry(roomId, key) { return this._engine.getChatroomEntry(roomId, key); } /** * 获取聊天室内的所有属性 * @param roomId 聊天室房间 id */ getAllChatroomEntries(roomId) { return this._engine.getAllChatroomEntry(roomId); } /** * 拉取聊天室内的历史消息 * @param roomId * @param count 拉取消息条数, 有效值范围 `1 - 20` * @param order 获取顺序,默认值为 0。 * * 0:降序,用于获取早于指定时间戳发送的消息 * * 1:升序,用于获取晚于指定时间戳发送的消息 * @param timestamp 指定拉取消息用到的时间戳。默认值为 `0`,表示按当前时间拉取 */ getChatRoomHistoryMessages(roomId, count = 20, order = 0, timestamp = 0) { return this._engine.getChatroomHistoryMessages(roomId, timestamp, count, order); } /** * 获取 七牛、百度上传认证信息 * @param fileType 文件类型 * @param fileName 文件名 */ getFileToken(fileType, fileName) { return __awaiter(this, void 0, void 0, function* () { const naviInfo = this.getInfoFromCache(); const bos = (naviInfo === null || naviInfo === void 0 ? void 0 : naviInfo.bosAddr) || ''; const qiniu = (naviInfo === null || naviInfo === void 0 ? void 0 : naviInfo.uploadServer) || ''; const ossConfig = (naviInfo === null || naviInfo === void 0 ? void 0 : naviInfo.ossConfig) || ''; const { code, data } = yield this._engine.getFileToken(fileType, fileName); if (code === ErrorCode$1.SUCCESS) { return Promise.resolve(Object.assign(data, { bos, qiniu, ossConfig })); } return Promise.reject(code); }); } /** * 获取 七牛、百度、阿里云 上传成功可下载的 URL * @param fileType 文件类型 * @param uploadMethod 上传方式 * @param fileName 文件名 * @param originName 文件源名 * @param uploadRes 插件上传返回的结果。降级百度上传后,用户传入返回结果,再把结果里的下载地址返回给用户,保证兼容之前结果获取 */ getFileUrl(fileType, fileName, originName, uploadRes, uploadMethod = UploadMethod$1.QINIU) { return __awaiter(this, void 0, void 0, function* () { if (uploadRes === null || uploadRes === void 0 ? void 0 : uploadRes.isBosRes) { return Promise.resolve(uploadRes); } const { code, data } = yield this._engine.getFileUrl(fileType, uploadMethod, fileName, originName); if (code === ErrorCode$1.SUCCESS) { return Promise.resolve(data); } return Promise.reject(code); }); } /* ============================= 以下为 CPP 接口 ================================== */ /** * 删除所有会话 */ clearConversations(conversationTypes, tag) { return __awaiter(this, void 0, void 0, function* () { return yield this._engine.clearConversations(conversationTypes, tag); }); } /** * 设置用户连接状态监听器 */ setUserStatusListener(config, listener) { return this._engine.setUserStatusListener(config, (data) => { try { listener(data); } catch (error) { logger.error(error); } }); } /** * 添加用户黑名单 */ addToBlacklist(userId) { return __awaiter(this, void 0, void 0, function* () { return this._engine.addToBlacklist(userId); }); } /** * 将指定用户移除黑名单 */ removeFromBlacklist(userId) { return __awaiter(this, void 0, void 0, function* () { return this._engine.removeFromBlacklist(userId); }); } /** * 获取黑名单列表 */ getBlacklist() { return __awaiter(this, void 0, void 0, function* () { return this._engine.getBlacklist(); }); } /** * 获取指定人员在黑名单中的状态 */ getBlacklistStatus(userId) { return __awaiter(this, void 0, void 0, function* () { return this._engine.getBlacklistStatus(userId); }); } /** * 向本地插入一条消息,不发送到服务器 */ insertMessage(conversationType, targetId, insertOptions) { return __awaiter(this, void 0, void 0, function* () { return this._engine.insertMessage(conversationType, targetId, insertOptions); }); } /** * 删除本地消息 */ deleteMessages(timestamp) { return __awaiter(this, void 0, void 0, function* () { return this._engine.deleteMessages(timestamp); }); } /** * 从本地消息数据库中删除某一会话指定时间之前的消息数据 */ deleteMessagesByTimestamp(conversationType, targetId, timestamp, cleanSpace, channelId = '') { return __awaiter(this, void 0, void 0, function* () { return this._engine.deleteMessagesByTimestamp(conversationType, targetId, timestamp, cleanSpace, channelId); }); } /** * 清空会话下历史消息 */ clearMessages(conversationType, targetId, channelId = '') { return __awaiter(this, void 0, void 0, function* () { return this._engine.clearMessages(conversationType, targetId, channelId); }); } /** * 获取本地消息 */ getMessage(messageId) { return __awaiter(this, void 0, void 0, function* () { return this._engine.getMessage(messageId); }); } /** * 设置消息内容 */ setMessageContent(messageId, content, messageType) { return __awaiter(this, void 0, void 0, function* () { return this._engine.setMessageContent(messageId, content, messageType); }); } /** * 设置消息搜索字段 */ setMessageSearchField(messageId, content, searchFiles) { return __awaiter(this, void 0, void 0, function* () { return this._engine.setMessageSearchField(messageId, content, searchFiles); }); } /** * 设置消息发送状态 */ setMessageSentStatus(messageId, sentStatus) { return __awaiter(this, void 0, void 0, function* () { return this._engine.setMessageSentStatus(messageId, sentStatus); }); } /** * 设置消息接收状态 */ setMessageReceivedStatus(messageId, receivedStatus) { return __awaiter(this, void 0, void 0, function* () { return this._engine.setMessageReceivedStatus(messageId, receivedStatus); }); } /** * 设置当前用户在线状态 */ setUserStatus(status) { return __awaiter(this, void 0, void 0, function* () { return this._engine.setUserStatus(status); }); } /** * 订阅用户在线状态 */ subscribeUserStatus(userIds) { return __awaiter(this, void 0, void 0, function* () { return this._engine.subscribeUserStatus(userIds); }); } /** * 获取用户在线状态 */ getUserStatus(userId) { return __awaiter(this, void 0, void 0, function* () { return this._engine.getUserStatus(userId); }); } searchConversationByContent(keyword, customMessageTypes = [], channelId = '', conversationTypes) { return __awaiter(this, void 0, void 0, function* () { return this._engine.searchConversationByContent(keyword, customMessageTypes, channelId, conversationTypes); }); } searchMessageByContent(conversationType, targetId, keyword, timestamp, count, total, channelId = '') { return __awaiter(this, void 0, void 0, function* () { return this._engine.searchMessageByContent(conversationType, targetId, keyword, timestamp, count, total, channelId); }); } getUnreadMentionedMessages(conversationType, targetId, channelId = '') { return this._engine.getUnreadMentionedMessages(conversationType, targetId, channelId); } clearUnreadCountByTimestamp(conversationType, targetId, timestamp, channelId = '') { return this._engine.clearUnreadCountByTimestamp(conversationType, targetId, timestamp, channelId); } /** * 获取会话免打扰状态 */ getConversationNotificationStatus(conversationType, targetId, channelId = '') { return this._engine.getConversationNotificationStatus(conversationType, targetId, channelId); } getRemoteHistoryMessages(conversationType, targetId, timestamp, count, order, channelId) { return this._engine.getRemoteHistoryMessages(conversationType, targetId, timestamp, count, order, channelId); } /* ============================= CPP 接口 END =================================== */ /* ============================= 以下为 RTC 相关接口 ============================== */ /** * 加入房间 * @param roomId * @param mode 房间模式:直播 or 会议 * @param mediaType 直播房间模式下的媒体资源类型 */ joinRTCRoom(roomId, mode, mediaType) { return this._engine.joinRTCRoom(roomId, mode, mediaType); } quitRTCRoom(roomId) { return this._engine.quitRTCRoom(roomId); } rtcPing(roomId, mode, mediaType) { return this._engine.rtcPing(roomId, mode, mediaType); } getRTCRoomInfo(roomId) { return this._engine.getRTCRoomInfo(roomId); } getRTCUserInfoList(roomId) { return this._engine.getRTCUserInfoList(roomId); } getRTCUserInfo(roomId) { return this._engine.getRTCUserInfo(roomId); } setRTCUserInfo(roomId, key, value) { return this._engine.setRTCUserInfo(roomId, key, value); } removeRTCUserInfo(roomId, keys) { return this._engine.removeRTCUserInfo(roomId, keys); } setRTCData(roomId, key, value, isInner, apiType, message) { return this._engine.setRTCData(roomId, key, value, isInner, apiType, message); } setRTCTotalRes(roomId, message, valueInfo, objectName) { return this._engine.setRTCTotalRes(roomId, message, valueInfo, objectName); } getRTCData(roomId, keys, isInner, apiType) { return this._engine.getRTCData(roomId, keys, isInner, apiType); } removeRTCData(roomId, keys, isInner, apiType, message) { return this._engine.removeRTCData(roomId, keys, isInner, apiType, message); } setRTCOutData(roomId, rtcData, type, message) { return this._engine.setRTCOutData(roomId, rtcData, type, message); } getRTCOutData(roomId, userIds) { return this._engine.getRTCOutData(roomId, userIds); } getRTCToken(roomId, mode, broadcastType) { return this._engine.getRTCToken(roomId, mode, broadcastType); } // RTC 北极星数据上报 setRTCState(roomId, report) { return this._engine.setRTCState(roomId, report); } getRTCUserList(roomId) { return this._engine.getRTCUserList(roomId); } } /** * engine 版本号 */ const version = "4.2.0"; exports.APIContext = APIContext; exports.AppStorage = AppStorage; exports.CallLibMsgType = CallLibMsgType; exports.CometChannel = CometChannel; exports.ConnectResultCode = ConnectResultCode; exports.ConnectionStatus = ConnectionStatus$1; exports.ConversationType = ConversationType$1; exports.DelayTimer = DelayTimer; exports.ErrorCode = ErrorCode$1; exports.EventEmitter = EventEmitter; exports.FileType = FileType$1; exports.Logger = Logger; exports.MentionedType = MentionedType$1; exports.MessageDirection = MessageDirection$1; exports.MessageType = MessageType$1; exports.NotificationStatus = NotificationStatus$1; exports.PluginContext = PluginContext; exports.RCAssertError = RCAssertError; exports.RTCPluginContext = RTCPluginContext; exports.ReceivedStatus = ReceivedStatus$1; exports.UploadMethod = UploadMethod$1; exports.WebSocketChannel = WebSocketChannel; exports.appendUrl = appendUrl; exports.assert = assert; exports.cloneByJSON = cloneByJSON; exports.forEach = forEach; exports.indexOf = indexOf; exports.isArray = isArray; exports.isArrayBuffer = isArrayBuffer; exports.isFunction = isFunction; exports.isHttpUrl = isHttpUrl; exports.isInObject = isInObject; exports.isInclude = isInclude; exports.isNull = isNull; exports.isNumber = isNumber; exports.isObject = isObject; exports.isString = isString; exports.isUndefined = isUndefined; exports.isValidConversationType = isValidConversationType; exports.isValidFileType = isValidFileType; exports.map = map; exports.notEmptyArray = notEmptyArray; exports.notEmptyObject = notEmptyObject; exports.notEmptyString = notEmptyString; exports.todo = todo; exports.validate = validate; exports.version = version; Object.defineProperty(exports, '__esModule', { value: true }); }))); /* * RongIMLib - v4.2.0 * CommitId - a00ad544f0c1624334ccf8ba7cca39a77640f5e4 * Tue Jan 12 2021 20:58:11 GMT+0800 (China Standard Time) * ©2020 RongCloud, Inc. All rights reserved. */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@rongcloud/engine')) : typeof define === 'function' && define.amd ? define(['exports', '@rongcloud/engine'], factory) : (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.RongIMLib = {}, global.RCEngine)); }(this, (function (exports, engine) { 'use strict'; /*! ***************************************************************************** Copyright (c) Microsoft Corporation. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ***************************************************************************** */ function __awaiter(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); } const logger = new engine.Logger('RCIM'); logger.set( engine.LogLevel.DEBUG ); const ERROR_INFO = { // 超时 TIMEOUT: { code: -1, msg: 'Network timeout' }, // SDK 内部错误 SDK_INTERNAL_ERROR: { code: -2, msg: 'SDK internal error' }, // 开发者参数传入错误 PARAMETER_ERROR: { code: -3, msg: 'Please check the parameters, the {param} expected a value of {expect} but received {current}' }, REJECTED_BY_BLACKLIST: { code: 405, msg: 'Blacklisted by the other party' }, // 发送频率过快 SEND_TOO_FAST: { code: 20604, msg: 'Sending messages too quickly' }, // 不在群组中 NOT_IN_GROUP: { code: 22406, msg: 'Not in group' }, // 在群组中被禁言 FORBIDDEN_IN_GROUP: { code: 22408, msg: 'Forbbiden from speaking in the group' }, // 不在聊天室中 NOT_IN_CHATROOM: { code: 23406, msg: 'Not in chatRoom' }, // 在聊天室中被禁言 FORBIDDEN_IN_CHATROOM: { code: 23408, msg: 'Forbbiden from speaking in the chatRoom' }, // 已被踢出并禁止加入聊天室 KICKED_FROM_CHATROOM: { code: 23409, msg: 'Kicked out and forbbiden from joining the chatRoom' }, // 聊天室不存在 CHATROOM_NOT_EXIST: { code: 23410, msg: 'ChatRoom does not exist' }, // 聊天室成员超限 CHATROOM_IS_FULL: { code: 23411, msg: 'ChatRoom members exceeded' }, // 聊天室参数无效 PARAMETER_INVALID_CHATROOM: { code: 23412, msg: 'Invalid chatRoom parameters' }, // 聊天室云存储业务未开通 ROAMING_SERVICE_UNAVAILABLE_CHATROOM: { code: 23414, msg: 'ChatRoom message roaming service is not open, Please go to the developer to open this service' }, // 撤回消息失败 RECALLMESSAGE_PARAMETER_INVALID: { code: 25101, msg: 'Invalid recall message parameter' }, // 未开通单群聊消息云存储服务 ROAMING_SERVICE_UNAVAILABLE_MESSAGE: { code: 25102, msg: 'Single group chat roaming service is not open, Please go to the developer to open this service' }, // push 设置参数无效 PUSHSETTING_PARAMETER_INVALID: { code: 26001, msg: 'Invalid push parameter' }, // 操作被禁止 OPERATION_BLOCKED: { code: 20605, msg: 'Operation is blocked' }, // 操作不支持 OPERATION_NOT_SUPPORT: { code: 20606, msg: 'Operation is not supported' }, // 发送的消息中包含敏感词 (发送方发送失败,接收方不会收到消息) MSG_BLOCKED_SENSITIVE_WORD: { code: 21501, msg: 'The sent message contains sensitive words' }, // 消息中敏感词已经被替换 (接收方可以收到被替换之后的消息) REPLACED_SENSITIVE_WORD: { code: 21502, msg: 'Sensitive words in the message have been replaced' }, // 用户未连接成功 NOT_CONNECTED: { code: 30001, msg: 'Please connect successfully first' }, // 导航 http 请求失败 NAVI_REQUEST_ERROR: { code: 30007, msg: 'Navigation http request failed' }, // CMP 嗅探 http 请求失败 CMP_REQUEST_ERROR: { code: 30010, msg: 'CMP sniff http request failed' }, CONN_APPKEY_FAKE: { code: 31002, msg: 'Your appkey is fake' }, CONN_MINI_SERVICE_NOT_OPEN: { code: 31003, msg: 'Mini program service is not open, Please go to the developer to open this service' }, CONN_ACK_TIMEOUT: { code: 31000, msg: 'Connection ACK timeout' }, CONN_TOKEN_INCORRECT: { code: 31004, msg: 'Your token is not valid or expired' }, CONN_NOT_AUTHRORIZED: { code: 31005, msg: 'AppKey and Token do not match' }, CONN_REDIRECTED: { code: 31006, msg: 'Connection redirection' }, CONN_APP_BLOCKED_OR_DELETED: { code: 31008, msg: 'AppKey is banned or deleted' }, CONN_USER_BLOCKED: { code: 31009, msg: 'User blocked' }, // 域名无效 CONN_DOMAIN_INCORRECT: { code: 31012, msg: 'Connect domain error, Please check the set security domain' }, // 未开通单群聊历史消息云存储 ROAMING_SERVICE_UNAVAILABLE: { code: 33007, msg: 'Roaming service cloud is not open, Please go to the developer to open this service' }, // 已连接, 不可再次调用链接(错误码与移动端对齐) RC_CONNECTION_EXIST: { code: 34001, msg: 'Connection already exists' }, // 聊天室 KV 设置超出最大值(已满, 默认最多设置 100 个) CHATROOM_KV_EXCEED: { code: 23423, msg: 'ChatRoom KV setting exceeds maximum' }, // 聊天室 KV 已存在 CHATROOM_KV_OVERWRITE_INVALID: { code: 23424, msg: 'ChatRoom KV already exists' }, // 聊天室 KV 存储功能没有开通 CHATROOM_KV_STORE_NOT_OPEN: { code: 23426, msg: 'ChatRoom KV storage service is not open, Please go to the developer to open this service' }, // 聊天室Key不存在 CHATROOM_KEY_NOT_EXIST: { code: 23427, msg: 'ChatRoom key does not exist' }, // 消息不支持扩展存储(错误码与移动端对齐) MSG_KV_NOT_SUPPORT: { code: 34008, msg: 'The message cannot be extended' }, // 发送扩展存储消息失败(错误码与移动端对齐) SEND_MESSAGE_KV_FAIL: { code: 34009, msg: 'Sending RC expansion message fail' }, // 扩展存储 key value 超出限制(错误码与移动端对齐) EXPANSION_LIMIT_EXCEET: { code: 34010, msg: 'The message expansion size is beyond the limit' }, // 调用接口时传入的参数不正确(错误码与移动端对齐) ILLGAL_PARAMS: { code: 33003, msg: 'Incorrect parameters passed in while calling the interface' } }; const ERROR_CODE = {}; for (const name in ERROR_INFO) { const info = ERROR_INFO[name]; const { code } = info; // ERROR_CODE[name] = code ERROR_CODE[code] = name; } // 服务返回的错误码, 转化为 SDK 的 ErrorCode const SERVER_ERROR_TO_CODE = { // 未开通单群聊历史消息云存储 1: ERROR_INFO.ROAMING_SERVICE_UNAVAILABLE.code }; const CONNECTION_STATUS = { CONNECTED: 0, CONNECTING: 1, DISCONNECTED: 2, NETWORK_UNAVAILABLE: 3, SOCKET_ERROR: 4, KICKED_OFFLINE_BY_OTHER_CLIENT: 6, BLOCKED: 12 // 用户被封禁(服务值为 2, 转为状态码后 + 10) }; /** * 业务层枚举, 此处枚举会暴露给开发者 */ const CONNECT_TYPE = { COMET: 'comet', WEBSOCKET: 'websocket' }; const CONVERSATION_TYPE = engine.ConversationType; const MESSAGE_DIRECTION = engine.MessageDirection; const MESSAGS_TIME_ORDER = { DESC: 0, ASC: 1 // 正序 }; // 聊天室历史消息、聊天室用户信息排序 const CHATROOM_ORDER = { ASC: 1, DESC: 2 }; const RECALL_MESSAGE_TYPE = 'RC:RcCmd'; const MENTIONED_TYPE = { ALL: 1, SINGAL: 2 }; const MESSAGE_TYPE = { TEXT: 'RC:TxtMsg', VOICE: 'RC:VcMsg', HQ_VOICE: 'RC:HQVCMsg', IMAGE: 'RC:ImgMsg', GIF: 'RC:GIFMsg', RICH_CONTENT: 'RC:ImgTextMsg', LOCATION: 'RC:LBSMsg', FILE: 'RC:FileMsg', SIGHT: 'RC:SightMsg', COMBINE: 'RC:CombineMsg', CHRM_KV_NOTIFY: 'RC:chrmKVNotiMsg', LOG_COMMAND: 'RC:LogCmdMsg', EXPANSION_NOTIFY: 'RC:MsgExMsg', REFERENCE: 'RC:ReferenceMsg' }; const FILE_TYPE = engine.FileType; // 聊天室 kv 存储操作类型. 对方操作, 己方收到消息(RC:chrmKVNotiMsg)中会带入此值. 根据此值判断是删除还是更新 const CHATROOM_ENTRY_TYPE = { UPDATE: 1, DELETE: 2 }; const NOTIFICATION_STATUS = { DO_NOT_DISTURB: 1, NOTIFY: 2 // 提醒(非免打扰) }; const RECEIVED_STATUS = { READ: 0x1, LISTENED: 0x2, DOWNLOADED: 0x4, RETRIEVED: 0x8, UNREAD: 0 // 未读 }; const SDK_VERSION = "4.2.0"; /** * 转化 APIContext 传过来的消息数据 * @param msg APIContext 消息 * @returns V3 需要的消息数据 */ function tranReceivedMessage(msg) { let { conversationType: type, messageType, content, senderUserId, targetId, sentTime, receivedTime, messageUId, messageDirection, isPersited, isCounted, isOffLineMessage, canIncludeExpansion, expansion, receivedStatus, disableNotification, isMentioned, isStatusMessage } = msg; if (!receivedStatus) { receivedStatus = engine.ReceivedStatus.UNREAD; } return { messageType, content, senderUserId, targetId, type, sentTime, receivedTime, messageUId, messageDirection, isPersited, isCounted, isOffLineMessage, isMentioned, disableNotification, isStatusMessage, canIncludeExpansion, expansion, receivedStatus }; } /** * 转化 APIContext 传过来的会话数据 * @param conversation APIContext 会话 * @returns V3 需要的会话数据 */ function tranReceiveConversation(conversation) { const { conversationType: type, targetId, latestMessage, unreadMessageCount, hasMentioned, mentionedInfo, lastUnreadTime, notificationStatus, isTop } = conversation; const latestMessageV3 = latestMessage && tranReceivedMessage(latestMessage); let mentionedInfoV3; if (hasMentioned) { mentionedInfoV3 = { type: mentionedInfo === null || mentionedInfo === void 0 ? void 0 : mentionedInfo.type, userIdList: mentionedInfo === null || mentionedInfo === void 0 ? void 0 : mentionedInfo.userIdList }; } else { mentionedInfoV3 = undefined; } return { type, targetId, latestMessage: latestMessageV3, unreadMessageCount, hasMentioned, mentionedInfo: mentionedInfoV3, lastUnreadTime, notificationStatus, isTop }; } function tranReceiveUpdateConversation(conversation) { const { updatedItems, conversationType: type, targetId, latestMessage, unreadMessageCount, lastUnreadTime, notificationStatus, isTop, mentionedInfo, hasMentioned } = conversation; const latestMessageV3 = latestMessage && tranReceivedMessage(latestMessage); if (updatedItems && updatedItems.latestMessage) { updatedItems.latestMessage.val = latestMessageV3; } return { updatedItems, type, targetId, latestMessage: latestMessageV3, unreadMessageCount, lastUnreadTime, notificationStatus, isTop, mentionedInfo, hasMentioned }; } /** * 校验发消息的参数 */ function assertSendMsgOption(options) { engine.assert('options.messageType', options.messageType, engine.AssertRules.STRING, true); engine.assert('options.content', options.content, (value) => { return engine.isObject(value); }, true); engine.assert('options.isPersited', options.isPersited, engine.AssertRules.BOOLEAN); engine.assert('options.isCounted', options.isCounted, engine.AssertRules.BOOLEAN); engine.assert('options.pushContent', options.pushContent, engine.AssertRules.STRING); engine.assert('options.pushData', options.pushData, engine.AssertRules.STRING); engine.assert('options.isVoipPush', options.isVoipPush, engine.AssertRules.BOOLEAN); engine.assert('options.isStatusMessage', options.isStatusMessage, engine.AssertRules.BOOLEAN); engine.assert('options.isMentioned', options.isMentioned, engine.AssertRules.BOOLEAN); engine.assert('options.mentionedType', options.mentionedType, engine.AssertRules.NUMBER); engine.assert('options.mentionedUserIdList', options.mentionedUserIdList, (value) => { return engine.isArray(value) && (value.length === 0 || value.every(engine.isString)); }); engine.assert('options.directionalUserIdList', options.directionalUserIdList, (value) => { return engine.isArray(value) && (value.length === 0 || value.every(engine.isString)); }); if (!engine.isUndefined(options.isPersited) || !engine.isUndefined(options.isCounted) || !engine.isUndefined(options.isStatusMessage)) { logger.warn('The parameters `isPersited`, `isCounted`, `isStatusMessage` will be deprecated in future releases due to inconsistance of the values on mobile side and web side. Please use `registerMessageType` instead for non-integrated message type.'); } } // import { isObject, isUndefined } from '../../utils/validator' /** * 会话排序(拆分-排序-合并) * 将会话列表拆分为置顶和非置顶的两个数组 * 再对两个数组按时间进行排序,时间戳大的说明是最近的消息排最上 */ const sortConList = (conversationList, order) => { if (!conversationList) { return []; } const splitConversationList = splitConversationListByIsTop(conversationList); const topConversationList = _sortListBySentTime(splitConversationList.topConversationList, order); const unToppedConversationList = _sortListBySentTime(splitConversationList.unToppedConversationList, order); topConversationList.push.apply(topConversationList, unToppedConversationList); return topConversationList; }; const mergeConversationList = (option) => { option = option || {}; let { conversationList, updatedConversationList } = option; conversationList = conversationList || []; updatedConversationList = updatedConversationList || []; const allConversationList = [...updatedConversationList, ...conversationList]; // 按顺序合并相同会话的数值(顺序依然为上一步的排序, 只是数值合并, 顺序靠后的数值合并到顺序靠前数值中) const hashTable = {}; let newList = []; const invalidDataIndexList = []; engine.forEach(allConversationList, (conversation) => { if (!engine.isObject(conversation)) { // 会话格式错误, 不添加至新列表 return; } const { type, targetId } = conversation; const key = getConversationKey({ type, targetId }); const hashItem = hashTable[key] || {}; const hashIndex = engine.isUndefined(hashItem.index) ? newList.length : hashItem.index; const hashVal = hashItem.val || {}; const cacheUpdatedItems = hashVal.updatedItems || {}; const updatedItems = conversation.updatedItems; conversation = extend(conversation, hashVal); engine.forEach(cacheUpdatedItems, (item, key) => { conversation[key] = item.val; }); engine.forEach(updatedItems, (item, key) => { const cacheItem = cacheUpdatedItems[key] || {}; const cacheItemUpdatedTime = cacheItem.time || 0; if (item.time > cacheItemUpdatedTime) { conversation[key] = item.val; } }); hashTable[key] = { index: hashIndex, val: conversation }; newList[hashIndex] = conversation; isInValidConversationData(conversation) && invalidDataIndexList.push(hashIndex); }); engine.forEach(invalidDataIndexList, (invalidIndex) => { const conversation = newList[invalidIndex]; newList[invalidIndex] = fixConversationData(conversation); }); newList = sortConList(newList); return engine.map(newList, (item) => { delete item.updatedItems; return item; }); }; const splitConversationListByIsTop = (conversationList) => { const topConversationList = []; const unToppedConversationList = []; engine.forEach(conversationList, (conversation) => { // 兼容会话中单词拼写错误字段 hasMentiond、mentiondInfo const { hasMentioned, mentionedInfo } = conversation; conversation.hasMentioned = hasMentioned; conversation.mentionedInfo = mentionedInfo; // 兼容接收 const isTop = conversation.isTop || false; if (isTop) { topConversationList.push(conversation); } else { unToppedConversationList.push(conversation); } }); return { topConversationList: topConversationList || [], unToppedConversationList: unToppedConversationList || [] }; }; const getConversationKey = (option) => { const { type, targetId } = option; return type + '_' + targetId; }; const _sortListBySentTime = (convers, order = 0) => { return quickSort(convers, (before, after) => { before = before || {}; after = after || {}; const beforeLatestMessage = before.latestMessage || {}; const afterLatestMessage = after.latestMessage || {}; const beforeLatestSentTime = beforeLatestMessage.sentTime || 0; const afterLatestSentTime = afterLatestMessage.sentTime || 0; if (!order) { return afterLatestSentTime <= beforeLatestSentTime; } return afterLatestSentTime >= beforeLatestSentTime; }); }; const fixConversationData = (conversation) => { conversation = conversation || {}; const { targetId, type } = conversation; const defaultType = engine.ConversationType.PRIVATE; const defaultMsg = { messageType: engine.MessageType.TextMessage, sentTime: engine.DelayTimer.getTime(), content: { content: '' }, senderUserId: targetId, targetId, type }; conversation.type = type || defaultType; conversation.targetId = targetId || ''; conversation.latestMessage = conversation.latestMessage || defaultMsg; return conversation; }; const quickSort = (arr, event) => { const sort = (array, left, right, event) => { event = event || ((a, b) => { return a <= b; }); if (left < right) { const x = array[right]; let i = left - 1; let temp; for (let j = left; j <= right; j++) { if (event(array[j], x)) { i++; temp = array[i]; array[i] = array[j]; array[j] = temp; } } sort(array, left, i - 1, event); sort(array, i + 1, right, event); } return array; }; return sort(arr, 0, arr.length - 1, event); }; const isInValidConversationData = (conversation) => { return !conversation.type || !conversation.targetId || !engine.isObject(conversation.latestMessage) || engine.isUndefined(conversation.unreadMessageCount); }; const extend = (destination, sources, option) => { option = option || {}; const { isAllowNull } = option; destination = destination || {}; sources = sources || {}; for (const key in sources) { const value = sources[key]; if (!engine.isUndefined(value) || isAllowNull) { destination[key] = value; } } return destination; }; class Conversation { constructor(_context, option) { this._context = _context; this.targetId = option.targetId; this.type = option.type; } /** * 删除指定会话 */ destory() { return __awaiter(this, void 0, void 0, function* () { const code = yield this._context.removeConversation(this.type, this.targetId); if (code !== engine.ErrorCode.SUCCESS) { return Promise.reject({ code, msg: ERROR_CODE[code] }); } }); } /** * 清除会话未读数 */ read() { return __awaiter(this, void 0, void 0, function* () { const code = yield this._context.clearUnreadCount(this.type, this.targetId); if (code !== engine.ErrorCode.SUCCESS) { return Promise.reject({ code, msg: ERROR_CODE[code] }); } }); } /** * 获取指定会话未读数 */ getUnreadCount() { return __awaiter(this, void 0, void 0, function* () { const { code, data } = yield this._context.getUnreadCount(this.type, this.targetId); // 当未读数为空时,返回 0 故不校验 data 值 if (code === engine.ErrorCode.SUCCESS) { return data; } return Promise.reject({ code, msg: ERROR_CODE[code] }); }); } /** * 发送消息 * @param options * @deprecated options.isPersited * @deprecated options.isCounted * @deprecated options.isStatusMessage */ send(options) { return __awaiter(this, void 0, void 0, function* () { assertSendMsgOption(options); if (!Object.prototype.hasOwnProperty.call(options, 'isPersited')) { options.isPersited = true; } if (!Object.prototype.hasOwnProperty.call(options, 'isCounted')) { options.isCounted = true; } const { code, data } = yield this._context.sendMessage(this.type, this.targetId, options); if (code === engine.ErrorCode.SUCCESS) { return tranReceivedMessage(data); } return Promise.reject({ code, msg: ERROR_CODE[code] }); }); } /** * 设置会话状态 */ setStatus(status) { return __awaiter(this, void 0, void 0, function* () { engine.assert('options.notificationStatus', status.notificationStatus, (value) => { return (value === 1 || value === 2); }); engine.assert('options.isTop', status.isTop, engine.AssertRules.BOOLEAN); const code = yield this._context.setConversationStatus(this.type, this.targetId, status.isTop, status.notificationStatus); if (code !== engine.ErrorCode.SUCCESS) { return Promise.reject({ code, msg: ERROR_CODE[code] }); } }); } /** * 获取历史消息 */ getMessages(options) { return __awaiter(this, void 0, void 0, function* () { engine.assert('options.timestamp', options.timestamp, engine.AssertRules.NUMBER); engine.assert('options.count', options.count, engine.AssertRules.NUMBER); engine.assert('options.order', options.order, (value) => { return (value === 0 || value === 1); }); const { code, data } = yield this._context.getHistoryMessage(this.type, this.targetId, options === null || options === void 0 ? void 0 : options.timestamp, options === null || options === void 0 ? void 0 : options.count, options === null || options === void 0 ? void 0 : options.order); if (code === engine.ErrorCode.SUCCESS && data) { const list = data.list.map(item => tranReceivedMessage(item)); return Promise.resolve({ list, hasMore: data.hasMore }); } return Promise.reject({ code, msg: ERROR_CODE[code] }); }); } /** * 撤回消息 * @param options */ recall(options) { return __awaiter(this, void 0, void 0, function* () { engine.assert('options.messageUId', options.messageUId, engine.AssertRules.STRING, true); engine.assert('options.sentTime', options.sentTime, engine.AssertRules.NUMBER, true); const recallOptions = { user: options.user, channelId: '' }; const { code, data } = yield this._context.recallMessage(this.type, this.targetId, options.messageUId, options.sentTime, recallOptions); if (code === engine.ErrorCode.SUCCESS && data) { return tranReceivedMessage(data); } return Promise.reject({ code, msg: ERROR_CODE[code] }); }); } /** * 按消息 id 删除消息 */ deleteMessages(messages) { return __awaiter(this, void 0, void 0, function* () { engine.assert('options', messages, (value) => { return engine.isArray(value) && value.length; }, true); messages.forEach((item) => { engine.assert('options.messageUId', item.messageUId, engine.AssertRules.STRING, true); engine.assert('options.sentTime', item.sentTime, engine.AssertRules.NUMBER, true); engine.assert('options.messageDirection', item.messageDirection, (value) => { return (value === 1 || value === 2); }, true); }); const code = yield this._context.deleteRemoteMessage(this.type, this.targetId, messages); if (code !== engine.ErrorCode.SUCCESS) { return Promise.reject({ code, msg: ERROR_CODE[code] }); } }); } /** * 按时间戳删除消息 */ clearMessages(options) { return __awaiter(this, void 0, void 0, function* () { engine.assert('options.timestamp', options.timestamp, engine.AssertRules.NUMBER, true); const code = yield this._context.deleteRemoteMessageByTimestamp(this.type, this.targetId, options.timestamp); if (code !== engine.ErrorCode.SUCCESS) { return Promise.reject({ code, msg: ERROR_CODE[code] }); } }); } /** * 更新(添加、替换)消息扩展属性 * @param expansion 要更新的消息扩展信息键值对 * @param message 要更新的原始消息体 */ updateMessageExpansion(expansion, message) { return __awaiter(this, void 0, void 0, function* () { engine.assert('expansion', expansion, engine.AssertRules.OBJECT, true); engine.assert('message', message, engine.AssertRules.OBJECT, true); const { type: conversationType, targetId, messageUId, canIncludeExpansion, expansion: originExpansion } = message; const { code } = yield this._context.sendExpansionMessage({ conversationType, targetId, messageUId, expansion, canIncludeExpansion, originExpansion }); if (code !== engine.ErrorCode.SUCCESS) { return Promise.reject({ code, msg: ERROR_CODE[code] }); } }); } /** * 删除扩展存储 * @params keys 需删除消息扩展的 keys * @params message 原始消息体 */ removeMessageExpansion(keys, message) { return __awaiter(this, void 0, void 0, function* () { engine.assert('keys', keys, engine.AssertRules.ARRAY, true); engine.assert('message', message, engine.AssertRules.OBJECT, true); const { conversationType, targetId, messageUId, canIncludeExpansion } = message; const { code } = yield this._context.sendExpansionMessage({ conversationType, targetId, messageUId, canIncludeExpansion, keys }); if (code !== engine.ErrorCode.SUCCESS) { return Promise.reject({ code, msg: ERROR_CODE[code] }); } }); } /** * 设置会话文本草稿 * @params conversationType 会话乐行 * @params targetId 目标 ID * @params draft 草稿内容 */ setDraft(draft) { return __awaiter(this, void 0, void 0, function* () { engine.assert('draft', draft, engine.AssertRules.STRING, true); const code = yield this._context.saveConversationMessageDraft(this.type, this.targetId, draft); if (code === engine.ErrorCode.SUCCESS) { return Promise.resolve(); } }); } /** * 获取会话文本草稿 * @params conversationType 会话乐行 * @params targetId 目标 ID */ getDraft() { return __awaiter(this, void 0, void 0, function* () { const { code, data } = yield this._context.getConversationMessageDraft(this.type, this.targetId); if (code === engine.ErrorCode.SUCCESS) { return Promise.resolve(data); } return Promise.reject({ code, msg: ERROR_CODE[code] }); }); } /** * 删除会话文本草稿 * @params conversationType 会话乐行 * @params targetId 目标 ID */ deleteDraft() { return __awaiter(this, void 0, void 0, function* () { const code = yield this._context.clearConversationMessageDraft(this.type, this.targetId); if (code === engine.ErrorCode.SUCCESS) { return Promise.resolve(); } }); } } class ConversationModule { constructor(apiContext) { this._context = apiContext; } /** * 获取会话列表 * @param options */ getList(options) { return __awaiter(this, void 0, void 0, function* () { const { code, data } = yield this._context.getConversationList(options === null || options === void 0 ? void 0 : options.count, undefined, options === null || options === void 0 ? void 0 : options.startTime, options === null || options === void 0 ? void 0 : options.order); if (code === engine.ErrorCode.SUCCESS && data) { const list = data.map(item => tranReceiveConversation(item)); return sortConList(list); } return Promise.reject({ code, msg: ERROR_CODE[code] }); }); } /** * 获取指定会话实例,通过实例可实现向指定会话收发消息等功能 * @description 通过该方法获取的会话可能并不存在于当前的会话列表中,此处只作为功能性封装语法糖 * @param options */ get(options) { engine.assert('options.type', options.type, engine.isValidConversationType, true); return new Conversation(this._context, options); } remove(options) { engine.assert('options.type', options.type, engine.isValidConversationType, true); return new Conversation(this._context, options).destory(); } /** * 获取当前所有会话的消息未读数 */ getTotalUnreadCount() { return __awaiter(this, void 0, void 0, function* () { const { code, data } = yield this._context.getTotalUnreadCount(); // 当未读数为空时,返回 0 故不校验 data 值 if (code === engine.ErrorCode.SUCCESS) { return data; } return Promise.reject({ code, msg: ERROR_CODE[code] }); }); } /** * 合并会话 * @param option */ merge(option) { !option.conversationList && logger.warn('Parameter option.conversationList are required!'); return mergeConversationList(option); } } /** * 校验设置聊天室属性的参数 * @param options */ const assertSetChatRoomEntryOption = (options) => { engine.assert('options.key', options.key, engine.AssertRules.STRING, true); engine.assert('options.value', options.value, engine.AssertRules.STRING, true); engine.assert('options.isAutoDelete', options.isAutoDelete, engine.AssertRules.BOOLEAN); engine.assert('options.isSendNotification', options.isSendNotification, engine.AssertRules.BOOLEAN); engine.assert('options.notificationExtra', options.notificationExtra, engine.AssertRules.STRING); }; /** * 校验删除聊天室属性的参数 * @param options */ const assertRemoveChatRoomEntryOption = (options) => { engine.assert('options.key', options.key, engine.AssertRules.STRING, true); engine.assert('options.isSendNotification', options.isSendNotification, engine.AssertRules.BOOLEAN); engine.assert('options.notificationExtra', options.notificationExtra, engine.AssertRules.STRING); }; class Chatroom { constructor(context, id) { this._context = context; this._id = id; } /** * 加入聊天室 */ join(options) { return __awaiter(this, void 0, void 0, function* () { engine.assert('options.count', options.count, engine.AssertRules.NUMBER, true); const code = yield this._context.joinChatroom(this._id, options.count); if (code !== engine.ErrorCode.SUCCESS) { return Promise.reject({ code, msg: ERROR_CODE[code] }); } }); } /** * 加入已存在的聊天室 */ joinExist(options) { return __awaiter(this, void 0, void 0, function* () { engine.assert('options.count', options.count, engine.AssertRules.NUMBER, true); const code = yield this._context.joinExistChatroom(this._id, options.count); if (code !== engine.ErrorCode.SUCCESS) { return Promise.reject({ code, msg: ERROR_CODE[code] }); } }); } /** * 退出聊天室 */ quit() { return __awaiter(this, void 0, void 0, function* () { const code = yield this._context.quitChatroom(this._id); if (code !== engine.ErrorCode.SUCCESS) { return Promise.reject({ code, msg: ERROR_CODE[code] }); } }); } /** * 获取聊天室房间数据 * @description count 或 order 有一个为 0 时,只返回成员总数,不返回成员列表信息 */ getInfo(options = {}) { return __awaiter(this, void 0, void 0, function* () { engine.assert('options.count', options.count, engine.AssertRules.NUMBER); engine.assert('options.order', options.order, (value) => { return [0, 1, 2].includes(value); }); const { code, data: chatroomInfo } = yield this._context.getChatroomInfo(this._id, options.count, options.order); if (code === engine.ErrorCode.SUCCESS && chatroomInfo) { return chatroomInfo; } return Promise.reject({ code, msg: ERROR_CODE[code] }); }); } /** * 设置聊天室自定义属性 * @description 仅聊天室中不存在此属性或属性设置者为己方时可设置成功 */ setEntry(options) { return __awaiter(this, void 0, void 0, function* () { assertSetChatRoomEntryOption(options); const code = yield this._context.setChatroomEntry(this._id, options); if (code !== engine.ErrorCode.SUCCESS) { return Promise.reject({ code, msg: ERROR_CODE[code] }); } }); } /** * 强制 增加/修改 任意聊天室属性 * @description 仅聊天室中不存在此属性或属性设置者为己方时可设置成功 */ forceSetEntry(options) { return __awaiter(this, void 0, void 0, function* () { assertSetChatRoomEntryOption(options); const code = yield this._context.forceSetChatroomEntry(this._id, options); if (code !== engine.ErrorCode.SUCCESS) { return Promise.reject({ code, msg: ERROR_CODE[code] }); } }); } /** * 删除聊天室属性 * @description 仅限于删除自己设置的聊天室属性 * @param key 属性名称, 支持英文字母、数字、+、=、-、_ 的组合方式, 最大长度 128 字符 * @param isSendNotification? 删除成功后是否发送通知消息 * @param notificationExtra? RC:chrmKVNotiMsg 通知消息中携带的附加信息 */ removeEntry(options) { return __awaiter(this, void 0, void 0, function* () { assertRemoveChatRoomEntryOption(options); const code = yield this._context.removeChatroomEntry(this._id, options); if (code !== engine.ErrorCode.SUCCESS) { return Promise.reject({ code, msg: ERROR_CODE[code] }); } }); } /** * 强制删除聊天室内的任意属性 * @description */ forceRemoveEntry(options) { return __awaiter(this, void 0, void 0, function* () { assertRemoveChatRoomEntryOption(options); const code = yield this._context.forceRemoveChatroomEntry(this._id, options); if (code !== engine.ErrorCode.SUCCESS) { return Promise.reject({ code, msg: ERROR_CODE[code] }); } }); } /** * 获取聊天室的指定属性 */ getEntry(key /** * 属性名称, 支持英文字母、数字、+、=、-、_ 的组合方式, 最大长度 128 字符 */ ) { return __awaiter(this, void 0, void 0, function* () { engine.assert('key', key, (value) => { return engine.isString(value) && /[\w+=-]+/.test(value) && value.length <= 128; }, true); const { code, data } = yield this._context.getChatroomEntry(this._id, key); if (code === engine.ErrorCode.SUCCESS && data) { return data; } return Promise.reject({ code, msg: ERROR_CODE[code] }); }); } /** * 获取聊天室的所有属性 */ getAllEntries() { return __awaiter(this, void 0, void 0, function* () { const { code, data } = yield this._context.getAllChatroomEntries(this._id); if (code === engine.ErrorCode.SUCCESS && data) { return data; } return Promise.reject({ code, msg: ERROR_CODE[code] }); }); } /** * 发送消息 */ send(options) { return __awaiter(this, void 0, void 0, function* () { assertSendMsgOption(options); if (!Object.prototype.hasOwnProperty.call(options, 'isPersited')) { options.isPersited = true; } if (!Object.prototype.hasOwnProperty.call(options, 'isCounted')) { options.isCounted = true; } const { code, data } = yield this._context.sendMessage(engine.ConversationType.CHATROOM, this._id, options); if (code === engine.ErrorCode.SUCCESS) { return tranReceivedMessage(data); } return Promise.reject({ code, msg: ERROR_CODE[code] }); }); } /** * 获取聊天室的历史消息 */ getMessages(options) { return __awaiter(this, void 0, void 0, function* () { engine.assert('options.timestamp', options.timestamp, engine.AssertRules.NUMBER); engine.assert('options.count', options.count, engine.AssertRules.NUMBER); engine.assert('options.order', options.order, (value) => { return (value === 0 || value === 1); }); const { code, data } = yield this._context.getChatRoomHistoryMessages(this._id, options.count, options.order, options.timestamp); if (code === engine.ErrorCode.SUCCESS && data) { const list = data.list.map(item => tranReceivedMessage(item)); return { list, hasMore: data.hasMore }; } return Promise.reject({ code, msg: ERROR_CODE[code] }); }); } /** * 撤回聊天室消息 */ recall(options) { return __awaiter(this, void 0, void 0, function* () { engine.assert('options.messageUId', options.messageUId, engine.AssertRules.STRING, true); engine.assert('options.sentTime', options.sentTime, engine.AssertRules.NUMBER, true); const conversationType = engine.ConversationType.CHATROOM; const { code, data } = yield this._context.recallMessage(conversationType, this._id, options.messageUId, options.sentTime, { channelId: '', user: options.user }); if (code === engine.ErrorCode.SUCCESS && data) { return tranReceivedMessage(data); } return Promise.reject({ code, msg: ERROR_CODE[code] }); }); } } class ChatroomModule { constructor(apiContext) { this._context = apiContext; } /** * 根据聊天室 id 初始化一个聊天室功能实例,以实现收发消息等聊天室相关功能 * @param option */ get(option) { engine.assert('option.id', option.id, engine.notEmptyString, true); return new Chatroom(this._context, option.id); } } class RTCClient { constructor(_options, _context) { this._options = _options; this._context = _context; this._roomId = _options.id; } join() { return __awaiter(this, void 0, void 0, function* () { const { code, data } = yield this._context.joinRTCRoom(this._roomId, this._options.mode, this._options.broadcastType); if (code === engine.ErrorCode.SUCCESS) { return data; } return Promise.reject(code); }); } quit() { return __awaiter(this, void 0, void 0, function* () { const code = yield this._context.quitRTCRoom(this._roomId); return code === engine.ErrorCode.SUCCESS ? code : Promise.reject(code); }); } getRoomInfo() { return __awaiter(this, void 0, void 0, function* () { const { code, data } = yield this._context.getRTCRoomInfo(this._roomId); if (code === engine.ErrorCode.SUCCESS) { return data; } return Promise.reject(code); }); } setUserInfo(info) { return __awaiter(this, void 0, void 0, function* () { const code = yield this._context.setRTCUserInfo(this._roomId, info.key, info.value); return code === engine.ErrorCode.SUCCESS ? code : Promise.reject(code); }); } removeUserInfo(info) { return __awaiter(this, void 0, void 0, function* () { const code = yield this._context.removeRTCUserInfo(this._roomId, info.keys); return code === engine.ErrorCode.SUCCESS ? code : Promise.reject(code); }); } setData(key, value, isInner, apiType, message) { return __awaiter(this, void 0, void 0, function* () { const code = yield this._context.setRTCData(this._roomId, key, value, isInner, apiType, message); return code === engine.ErrorCode.SUCCESS ? code : Promise.reject(code); }); } setUserData(key, value, isInner, message) { return this.setData(key, value, isInner, engine.RTCApiType.PERSON, message); } /** * 全量 URI 资源发布 * @param message 旧版本消息,含消息名及消息内容 * @param valueInfo 全量消息数据 * @param objectName 全量 URI 消息名 */ setRTCUserData(message, valueInfo, objectName) { return __awaiter(this, void 0, void 0, function* () { const code = yield this._context.setRTCTotalRes(this._roomId, message, valueInfo, objectName); return code === engine.ErrorCode.SUCCESS ? code : Promise.reject(code); }); } getData(keys, isInner, apiType) { return __awaiter(this, void 0, void 0, function* () { const { code, data } = yield this._context.getRTCData(this._roomId, keys, isInner, apiType); return code === engine.ErrorCode.SUCCESS ? data : Promise.reject(code); }); } getUserData(keys, isInner) { return this.getData(keys, isInner, engine.RTCApiType.PERSON); } removeData(keys, isInner, apiType, message) { return __awaiter(this, void 0, void 0, function* () { const code = yield this._context.removeRTCData(this._roomId, keys, isInner, apiType, message); return code === engine.ErrorCode.SUCCESS ? code : Promise.reject(code); }); } removeUserData(keys, isInner, message) { return this.removeData(keys, isInner, engine.RTCApiType.PERSON, message); } setRoomData(key, value, isInner, message) { return this.setData(key, value, isInner, engine.RTCApiType.ROOM, message); } getRoomData(keys, isInner) { return this.getData(keys, isInner, engine.RTCApiType.ROOM); } removeRoomData(keys, isInner, message) { return this.removeData(keys, isInner, engine.RTCApiType.ROOM, message); } setState(content) { return __awaiter(this, void 0, void 0, function* () { const code = yield this._context.setRTCState(this._roomId, content.report); return code === engine.ErrorCode.SUCCESS ? code : Promise.reject(code); }); } getUserList() { return __awaiter(this, void 0, void 0, function* () { const { code, data } = yield this._context.getRTCUserInfoList(this._roomId); if (code === engine.ErrorCode.SUCCESS) { return data; } return Promise.reject(code); }); } getUserInfoList() { return __awaiter(this, void 0, void 0, function* () { const { code, data } = yield this._context.getRTCUserInfoList(this._roomId); if (code === engine.ErrorCode.SUCCESS) { return data; } return Promise.reject(code); }); } getToken() { return __awaiter(this, void 0, void 0, function* () { const { data, code } = yield this._context.getRTCToken(this._roomId, this._options.mode, this._options.broadcastType); if (code === engine.ErrorCode.SUCCESS) { return data; } return Promise.reject(code); }); } ping() { return __awaiter(this, void 0, void 0, function* () { const code = yield this._context.rtcPing(this._roomId, this._options.mode, this._options.broadcastType); return code === engine.ErrorCode.SUCCESS ? code : Promise.reject(code); }); } send(options) { return __awaiter(this, void 0, void 0, function* () { const { code, data } = yield this._context.sendMessage(engine.ConversationType.RTC_ROOM, this._roomId, { content: Object.assign({}, options.content), messageType: options.messageType }); if (code === engine.ErrorCode.SUCCESS) { return data; } return Promise.reject(code); }); } } // export class RTCModule { // private _context: APIContext // constructor (apiContext: APIContext) { // this._context = apiContext // } // /** // * 为 RTCLib 提供的 API 接口,业务层不可使用 // * @private // * @param options // */ // get (options: RTCRoomOption) { // assert('options.id', options.id, notEmptyString, true) // return new RTCClient(options, this._context) // } // } const hasMiniBaseEvent = (miniGlobal) => { const baseMiniEventNames = ['canIUse', 'getSystemInfo']; for (let i = 0, max = baseMiniEventNames.length; i < max; i++) { const baseEventName = baseMiniEventNames[i]; if (!miniGlobal[baseEventName]) { return false; } } return true; }; const isFromUniappEnv = () => { if (typeof uni !== 'undefined' && hasMiniBaseEvent(uni)) { return true; } return false; }; const isFromUniapp = isFromUniappEnv(); const createXHR = () => { const hasCORS = typeof XMLHttpRequest !== 'undefined' && 'withCredentials' in new XMLHttpRequest(); if (typeof XMLHttpRequest !== 'undefined' && hasCORS) { return new XMLHttpRequest(); } else if (typeof XDomainRequest !== 'undefined') { return new XDomainRequest(); } else { return new ActiveXObject('Microsoft.XMLHTTP'); } }; function httpReq(options) { const method = options.method || engine.HttpMethod.GET; const timeout = options.timeout || 60 * 1000; const { headers, query, body } = options; const url = engine.appendUrl(options.url, query); return new Promise((resolve) => { const xhr = createXHR(); const isXDomainRequest = Object.prototype.toString.call(xhr) === '[object XDomainRequest]'; xhr.open(method, url); if (headers && xhr.setRequestHeader) { for (const key in headers) { xhr.setRequestHeader(key, headers[key]); } } if (isXDomainRequest) { xhr.timeout = timeout; xhr.onload = function () { resolve({ data: xhr.responseText, status: xhr.status || 200 }); }; xhr.onerror = function () { resolve({ status: xhr.status || 0 }); }; xhr.ontimeout = () => { resolve({ status: xhr.status || 0 }); }; const reqBody = typeof body === 'object' ? JSON.stringify(body) : body; xhr.send(reqBody); } else { xhr.onreadystatechange = () => { if (xhr.readyState === 4) { resolve({ data: xhr.responseText, status: xhr.status }); } }; xhr.onerror = function () { resolve({ status: xhr.status || 0 }); }; setTimeout(() => resolve({ status: xhr.status || 0 }), timeout); xhr.send(body); } }); } function createWebSocket(url, protocols) { const ws = new WebSocket(url, protocols); ws.binaryType = 'arraybuffer'; return { onClose(callback) { ws.onclose = (evt) => { const { code, reason } = evt; callback(code, reason); }; }, onError(callback) { ws.onerror = callback; }, onMessage(callback) { ws.onmessage = (evt) => { callback(evt.data); }; }, onOpen(callback) { ws.onopen = callback; }, send(data) { ws.send(data); }, close(code, reason) { ws.close(code, reason); } }; } const browser = { tag: "browser", httpReq, localStorage: window === null || window === void 0 ? void 0 : window.localStorage, sessionStorage: window === null || window === void 0 ? void 0 : window.sessionStorage, isSupportSocket() { const bool = typeof WebSocket !== 'undefined'; bool || logger.warn('websocket not support'); return bool; }, useNavi: true, connectPlatform: '', isFromUniapp, createWebSocket, createDataChannel(watcher, connectType) { if (this.isSupportSocket() && connectType === 'websocket') { return new engine.WebSocketChannel(this, watcher); } else { return new engine.CometChannel(this, watcher); } } }; const isFromUniapp$1 = isFromUniappEnv(); const createFunc = (method) => (...args) => { try { return wx[method](...args); } catch (err) { // 此 Bug 是由于微信小程序数据库文件可能会意外损坏导致,目前无解 logger.error(err); } }; const storage = { setItem: createFunc('setStorageSync'), getItem: createFunc('getStorageSync'), removeItem: createFunc('removeStorageSync'), clear: createFunc('clearStorageSync') }; /** * @todo */ const wechat = { tag: "wechat", httpReq(options) { const method = options.method || engine.HttpMethod.GET; const timeout = options.timeout || 60 * 1000; const { headers, query, body } = options; const url = engine.appendUrl(options.url, query); return new Promise((resolve) => { wx.request({ url, method, headers, timeout, data: body, success: (res) => { resolve({ data: res.data, status: res.statusCode }); }, fail: () => { resolve({ status: engine.ErrorCode.RC_HTTP_REQ_TIMEOUT }); } }); }); }, localStorage: storage, sessionStorage: storage, isSupportSocket() { return true; }, useNavi: false, connectPlatform: 'MiniProgram', isFromUniapp: isFromUniapp$1, createWebSocket(url, protocols) { const socketTask = wx.connectSocket({ url, protocols }); return { onClose(callback) { socketTask.onClose((res) => { callback(res.code, res.reason); }); }, onError(callback) { socketTask.onError((res) => { callback(res.errMsg); }); }, onMessage(callback) { socketTask.onMessage((res) => { callback(res.data); }); }, onOpen(callback) { socketTask.onOpen(callback); }, send(data) { socketTask.send({ data }); }, close(code, reason) { socketTask.close({ code, reason }); } }; }, createDataChannel(watcher) { return new engine.WebSocketChannel(this, watcher); } }; const isFromUniapp$2 = isFromUniappEnv(); const createFunc$1 = (method) => (...args) => { try { return my[method](...args); } catch (err) { logger.error(err); } }; const storage$1 = { setItem: createFunc$1('setStorageSync'), getItem: createFunc$1('getStorageSync'), removeItem: createFunc$1('removeStorageSync'), clear: createFunc$1('clearStorageSync') }; const alipay = { tag: "alipay", httpReq(options) { const method = options.method || engine.HttpMethod.GET; const timeout = options.timeout || 60 * 1000; const { headers, query, body } = options; const url = engine.appendUrl(options.url, query); return new Promise((resolve) => { my.request({ url, method, headers, timeout, data: body, success: (res) => { resolve({ data: res.data, status: res.status }); }, fail: () => { resolve({ status: engine.ErrorCode.RC_HTTP_REQ_TIMEOUT }); } }); }); }, localStorage: storage$1, sessionStorage: storage$1, isSupportSocket() { return false; }, useNavi: false, connectPlatform: 'MiniProgram', isFromUniapp: isFromUniapp$2, createDataChannel(watcher) { return new engine.CometChannel(this, watcher); } }; // TODO const createFunc$2 = (method) => (...args) => { try { return uni[method](...args); } catch (err) { logger.error(err); } }; const storage$2 = { setItem: createFunc$2('setStorageSync'), getItem: createFunc$2('getStorageSync'), removeItem: createFunc$2('removeStorageSync'), clear: createFunc$2('clearStorageSync') }; /** * @todo */ const appPlus = { tag: "uniapp", httpReq(options) { const method = options.method || engine.HttpMethod.GET; const timeout = options.timeout || 60 * 1000; const { headers, query, body } = options; const url = engine.appendUrl(options.url, query); return new Promise((resolve) => { uni.request({ url, method, headers, timeout, data: body, success: (res) => { resolve({ data: res.data, status: res.statusCode }); }, fail: () => { resolve({ status: engine.ErrorCode.RC_HTTP_REQ_TIMEOUT }); } }); }); }, localStorage: storage$2, sessionStorage: storage$2, isSupportSocket() { return true; }, useNavi: true, connectPlatform: '', isFromUniapp: true, createWebSocket(url, protocols) { const options = { complete: () => { }, url, protocols }; const socketTask = uni.connectSocket(options); return { onClose(callback) { socketTask.onClose((res) => { callback(res.code, res.reason); }); }, onError(callback) { socketTask.onError((res) => { callback(res.errMsg); }); }, onMessage(callback) { socketTask.onMessage((res) => { callback(res.data); }); }, onOpen(callback) { socketTask.onOpen(callback); }, send(data) { socketTask.send({ data }); }, close(code, reason) { socketTask.close({ code, reason }); } }; }, createDataChannel(watcher) { return new engine.WebSocketChannel(this, watcher); } }; const uniapp = () => { const uniPlatform = process.env.VUE_APP_PLATFORM; switch (uniPlatform) { case 'app-plus': return appPlus; // case 'mp-baidu': // return {} // case 'mp-toutiao': // return {} case 'mp-alipay': return alipay; case 'mp-weixin': return wechat; case 'h5': default: return browser; } }; const isMiniPrograme = (miniGlobal) => { return miniGlobal && miniGlobal.canIUse && miniGlobal.getSystemInfo; }; const runtime = (() => { if (typeof uni !== 'undefined' && isMiniPrograme(uni)) { return uniapp(); } if (typeof wx !== 'undefined' && isMiniPrograme(wx)) { return wechat; } if (typeof my !== 'undefined' && isMiniPrograme(my)) { return alipay; } return browser; })(); // RTCLib、CallLib 相关监听存储 const rtcInnerMsgWatcher = []; const rtcInnerStatusWatcher = []; const rtcInnerWatcher = { message(message) { rtcInnerMsgWatcher.forEach(item => item(message)); }, status(status) { rtcInnerStatusWatcher.forEach(item => item(status)); } }; class IMClient { constructor(apiContext) { this._token = ''; this._context = apiContext; this.Conversation = new ConversationModule(apiContext); this.ChatRoom = new ChatroomModule(apiContext); this.RTC = function (options) { engine.assert('options.id', options.id, engine.notEmptyString, true); return new RTCClient(options, apiContext); }; } /** * 装载 plugin 插件,并返回相应的插件实例,需在调用 `connect` 方法之前使用 * @param plugins */ install(plugin, options) { return this._context.install(plugin, options); } /** * 添加全局事件监听,同一类型事件会覆盖添加,以避免多次监听引起的复杂问题 * @param options */ watch(options) { const { status: statusListener, conversation: conversationListener, message: messageListener, chatroom: chatroomListener, expansion: expansionListener } = options; const watcher = {}; if (statusListener) { watcher.connectionState = (status) => { // 对业务层的方法要增加 catch 捕获,避免影响内部调用栈的继续进行 try { statusListener({ status }); } catch (err) { logger.error(err); } }; } if (conversationListener) { watcher.conversationState = (conversations) => { try { const list = conversations.map((item) => tranReceiveUpdateConversation(item)); conversationListener({ updatedConversationList: list }); } catch (err) { logger.error(err); } }; } if (messageListener) { watcher.message = (message) => { try { messageListener({ message: tranReceivedMessage(message) }); } catch (err) { logger.error(err); } }; } if (chatroomListener) { watcher.chatroomState = (event) => { try { chatroomListener(event); } catch (err) { logger.error(err); } }; } if (expansionListener) { watcher.expansion = (event) => { try { expansionListener(event); } catch (err) { logger.error(err); } }; } this._context.assignWatcher(watcher); } unwatch() { this._context.assignWatcher({ message: undefined, connectionState: undefined, conversationState: undefined, chatroomState: undefined, expansion: undefined }); } rtcInnerWatch(attrs) { const { message: messageListener, status: statusListener } = attrs; if (messageListener) { rtcInnerMsgWatcher.push((message) => { try { messageListener({ message: tranReceivedMessage(message) }); } catch (err) { logger.error(err); } }); } if (statusListener) { rtcInnerStatusWatcher.push((status) => { try { statusListener({ status }); } catch (err) { logger.error(err); } }); } this._context.assignWatcher({ rtcInnerWatcher }); } rtcInnerUnwatch() { rtcInnerStatusWatcher.length = rtcInnerStatusWatcher.length = 0; this._context.assignWatcher({ rtcInnerWatcher: undefined }); } /** * 建立 IM 连接 * @param options */ connect(options) { return __awaiter(this, void 0, void 0, function* () { engine.assert('options.token', options.token, engine.AssertRules.STRING, true); const token = options.token; this._token = token; const res = yield this._context.connect(token, true); if (res.code === engine.ErrorCode.SUCCESS) { return { id: res.userId }; } return Promise.reject({ code: res.code, msg: ERROR_CODE[res.code] }); }); } /** * 使用上一次的链接 token 重新建立连接,该方法只需在主动调用 `disconnect` 方法之后有重连需求时调用 */ reconnect() { return __awaiter(this, void 0, void 0, function* () { const res = yield this._context.reconnect(); if (res.code === engine.ErrorCode.SUCCESS) { return { id: res.userId }; } return Promise.reject({ code: res.code, msg: ERROR_CODE[res.code] }); }); } /** * 断开当前用户的连接 * @description 调用后将不再接收消息,不可发送消息,不可获取历史消息,不可获取会话列表 */ disconnect() { return this._context.disconnect(); } /** * 获取当前 IM 环境信息 */ getAppInfo() { return { appkey: this._context.appkey, token: this._token, navi: this._context.getInfoFromCache() }; } /** * 获取 IM 连接时间 */ getConnectedTime() { return this._context.getConnectedTime(); } /** * 获取 IM 连接状态 */ getConnectionStatus() { return this._context.getConnectionStatus(); } /** * 获取 IM 连接用户的 id */ getConnectionUserId() { return this._context.getCurrentUserId(); } /** * 获取文件 token * @description 上传文件时,获取文件 token * @param fileType 上传类型, 通过 RongIMLib.FILE_TYPE 获取 * @param fileName 上传文件名,Server 通过文件名生成百度上传认证, 若不传 engine 自动生成 */ getFileToken(fileType, fileName) { engine.assert('fileType', fileType, engine.isValidFileType, true); return this._context.getFileToken(fileType, fileName); } /** * 获取文件上传后的下载地址 */ getFileUrl( /** * 上传类型, 通过 RongIMLib.FILE_TYPE 获取 */ fileType, /** * 上传后的文件名 */ filename, /** * 原始文件名 */ oriname, /** * 上传成功返回数据 * 百度 bos 上传地址即为下载地址,IM Server 不会返回百度 bos 下载地址,通过用户层传入再返回 */ uploadRes, /** * 上传方式,阿里或七牛,RongIMLib.UploadMethod 获取 */ uploadMethod) { engine.assert('fileType', fileType, engine.isValidFileType, true); engine.assert('filename', filename, engine.AssertRules.STRING); engine.assert('oriname', oriname, engine.AssertRules.STRING); engine.assert('uploadMethod', uploadMethod, engine.AssertRules.NUMBER); return this._context.getFileUrl(fileType, filename, oriname, uploadRes, uploadMethod); } /** * 切换用户,作用等同于断开当前用户连接,以新的 token 重新建立连接 * @deprecated * @param option */ changeUser(options) { return __awaiter(this, void 0, void 0, function* () { logger.warn('Method is deprecated'); engine.assert('options.token', options.token, engine.AssertRules.STRING, true); yield this.disconnect(); return this.connect(options); }); } /** * 注册自定义消息 * @param messageType 消息类型 * @param isPersited 是否存储 * @param isCounted 是否计数 * @param prototypes 消息属性名称 */ registerMessageType(messageType, isPersited, isCounted, prototypes) { this._context.registerMessageType(messageType, isPersited, isCounted, prototypes); } } let imInstance; /** * 初始化 * @param {IInitOption} options */ const init = (options) => { if (imInstance) { logger.error('The instance already exists. Do not repeatedly call the init method'); return imInstance; } engine.assert('options.appkey', options.appkey, engine.AssertRules.STRING, true); engine.assert('options.debug', options.debug, engine.AssertRules.BOOLEAN); engine.assert('options.navigators', options.navigators, (value) => { return engine.isArray(value) && (value.length === 0 || value.every(engine.isHttpUrl)); }); const context = engine.APIContext.init(runtime, { appkey: options.appkey, apiVersion: "4.2.0", navigators: options.navigators || [], miniCMPProxy: options.customCMP || [], connectionType: options.connectType || 'websocket', cppProtocol: options.cppProtocol }); imInstance = new IMClient(context); return imInstance; }; const getInstance = () => { if (!imInstance) { logger.error('Please call the init method first'); } return imInstance; }; Object.defineProperty(exports, 'ConnectionStatus', { enumerable: true, get: function () { return engine.ConnectionStatus; } }); Object.defineProperty(exports, 'LogLevel', { enumerable: true, get: function () { return engine.LogLevel; } }); Object.defineProperty(exports, 'UploadMethod', { enumerable: true, get: function () { return engine.UploadMethod; } }); exports.CHATROOM_ENTRY_TYPE = CHATROOM_ENTRY_TYPE; exports.CHATROOM_ORDER = CHATROOM_ORDER; exports.CONNECTION_STATUS = CONNECTION_STATUS; exports.CONNECT_TYPE = CONNECT_TYPE; exports.CONVERSATION_TYPE = CONVERSATION_TYPE; exports.ERROR_CODE = ERROR_CODE; exports.FILE_TYPE = FILE_TYPE; exports.IMClient = IMClient; exports.MENTIONED_TYPE = MENTIONED_TYPE; exports.MESSAGE_DIRECTION = MESSAGE_DIRECTION; exports.MESSAGE_TYPE = MESSAGE_TYPE; exports.MESSAGS_TIME_ORDER = MESSAGS_TIME_ORDER; exports.NOTIFICATION_STATUS = NOTIFICATION_STATUS; exports.RECALL_MESSAGE_TYPE = RECALL_MESSAGE_TYPE; exports.RECEIVED_STATUS = RECEIVED_STATUS; exports.SDK_VERSION = SDK_VERSION; exports.getInstance = getInstance; exports.init = init; Object.defineProperty(exports, '__esModule', { value: true }); }))); ================================================ FILE: api-test-v4/lib/js/es6-promise.js ================================================ !function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):t.ES6Promise=e()}(this,function(){"use strict";function t(t){var e=typeof t;return null!==t&&("object"===e||"function"===e)}function e(t){return"function"==typeof t}function n(t){W=t}function r(t){z=t}function o(){return function(){return process.nextTick(a)}}function i(){return"undefined"!=typeof U?function(){U(a)}:c()}function s(){var t=0,e=new H(a),n=document.createTextNode("");return e.observe(n,{characterData:!0}),function(){n.data=t=++t%2}}function u(){var t=new MessageChannel;return t.port1.onmessage=a,function(){return t.port2.postMessage(0)}}function c(){var t=setTimeout;return function(){return t(a,1)}}function a(){for(var t=0;t=0&&Math.floor(t)===t&&isFinite(e)}function u(e){return n(e)&&"function"==typeof e.then&&"function"==typeof e.catch}function l(e){return null==e?"":Array.isArray(e)||s(e)&&e.toString===a?JSON.stringify(e,null,2):String(e)}function f(e){var t=parseFloat(e);return isNaN(t)?e:t}function p(e,t){for(var n=Object.create(null),r=e.split(","),i=0;i-1)return e.splice(n,1)}}var m=Object.prototype.hasOwnProperty;function y(e,t){return m.call(e,t)}function g(e){var t=Object.create(null);return function(n){return t[n]||(t[n]=e(n))}}var _=/-(\w)/g,b=g(function(e){return e.replace(_,function(e,t){return t?t.toUpperCase():""})}),$=g(function(e){return e.charAt(0).toUpperCase()+e.slice(1)}),w=/\B([A-Z])/g,C=g(function(e){return e.replace(w,"-$1").toLowerCase()});var x=Function.prototype.bind?function(e,t){return e.bind(t)}:function(e,t){function n(n){var r=arguments.length;return r?r>1?e.apply(t,arguments):e.call(t,n):e.call(t)}return n._length=e.length,n};function k(e,t){t=t||0;for(var n=e.length-t,r=new Array(n);n--;)r[n]=e[n+t];return r}function A(e,t){for(var n in t)e[n]=t[n];return e}function O(e){for(var t={},n=0;n0,Z=J&&J.indexOf("edge/")>0,G=(J&&J.indexOf("android"),J&&/iphone|ipad|ipod|ios/.test(J)||"ios"===K),X=(J&&/chrome\/\d+/.test(J),J&&/phantomjs/.test(J),J&&J.match(/firefox\/(\d+)/)),Y={}.watch,Q=!1;if(z)try{var ee={};Object.defineProperty(ee,"passive",{get:function(){Q=!0}}),window.addEventListener("test-passive",null,ee)}catch(e){}var te=function(){return void 0===B&&(B=!z&&!V&&"undefined"!=typeof global&&(global.process&&"server"===global.process.env.VUE_ENV)),B},ne=z&&window.__VUE_DEVTOOLS_GLOBAL_HOOK__;function re(e){return"function"==typeof e&&/native code/.test(e.toString())}var ie,oe="undefined"!=typeof Symbol&&re(Symbol)&&"undefined"!=typeof Reflect&&re(Reflect.ownKeys);ie="undefined"!=typeof Set&&re(Set)?Set:function(){function e(){this.set=Object.create(null)}return e.prototype.has=function(e){return!0===this.set[e]},e.prototype.add=function(e){this.set[e]=!0},e.prototype.clear=function(){this.set=Object.create(null)},e}();var ae=S,se=0,ce=function(){this.id=se++,this.subs=[]};ce.prototype.addSub=function(e){this.subs.push(e)},ce.prototype.removeSub=function(e){h(this.subs,e)},ce.prototype.depend=function(){ce.target&&ce.target.addDep(this)},ce.prototype.notify=function(){for(var e=this.subs.slice(),t=0,n=e.length;t-1)if(o&&!y(i,"default"))a=!1;else if(""===a||a===C(e)){var c=Pe(String,i.type);(c<0||s0&&(st((u=e(u,(a||"")+"_"+c))[0])&&st(f)&&(s[l]=he(f.text+u[0].text),u.shift()),s.push.apply(s,u)):i(u)?st(f)?s[l]=he(f.text+u):""!==u&&s.push(he(u)):st(u)&&st(f)?s[l]=he(f.text+u.text):(r(o._isVList)&&n(u.tag)&&t(u.key)&&n(a)&&(u.key="__vlist"+a+"_"+c+"__"),s.push(u)));return s}(e):void 0}function st(e){return n(e)&&n(e.text)&&!1===e.isComment}function ct(e,t){if(e){for(var n=Object.create(null),r=oe?Reflect.ownKeys(e):Object.keys(e),i=0;i0,a=t?!!t.$stable:!o,s=t&&t.$key;if(t){if(t._normalized)return t._normalized;if(a&&r&&r!==e&&s===r.$key&&!o&&!r.$hasNormal)return r;for(var c in i={},t)t[c]&&"$"!==c[0]&&(i[c]=pt(n,c,t[c]))}else i={};for(var u in n)u in i||(i[u]=dt(n,u));return t&&Object.isExtensible(t)&&(t._normalized=i),R(i,"$stable",a),R(i,"$key",s),R(i,"$hasNormal",o),i}function pt(e,t,n){var r=function(){var e=arguments.length?n.apply(null,arguments):n({});return(e=e&&"object"==typeof e&&!Array.isArray(e)?[e]:at(e))&&(0===e.length||1===e.length&&e[0].isComment)?void 0:e};return n.proxy&&Object.defineProperty(e,t,{get:r,enumerable:!0,configurable:!0}),r}function dt(e,t){return function(){return e[t]}}function vt(e,t){var r,i,a,s,c;if(Array.isArray(e)||"string"==typeof e)for(r=new Array(e.length),i=0,a=e.length;idocument.createEvent("Event").timeStamp&&(sn=function(){return cn.now()})}function un(){var e,t;for(an=sn(),rn=!0,Qt.sort(function(e,t){return e.id-t.id}),on=0;onon&&Qt[n].id>e.id;)n--;Qt.splice(n+1,0,e)}else Qt.push(e);nn||(nn=!0,Ye(un))}}(this)},fn.prototype.run=function(){if(this.active){var e=this.get();if(e!==this.value||o(e)||this.deep){var t=this.value;if(this.value=e,this.user)try{this.cb.call(this.vm,e,t)}catch(e){Re(e,this.vm,'callback for watcher "'+this.expression+'"')}else this.cb.call(this.vm,e,t)}}},fn.prototype.evaluate=function(){this.value=this.get(),this.dirty=!1},fn.prototype.depend=function(){for(var e=this.deps.length;e--;)this.deps[e].depend()},fn.prototype.teardown=function(){if(this.active){this.vm._isBeingDestroyed||h(this.vm._watchers,this);for(var e=this.deps.length;e--;)this.deps[e].removeSub(this);this.active=!1}};var pn={enumerable:!0,configurable:!0,get:S,set:S};function dn(e,t,n){pn.get=function(){return this[t][n]},pn.set=function(e){this[t][n]=e},Object.defineProperty(e,n,pn)}function vn(e){e._watchers=[];var t=e.$options;t.props&&function(e,t){var n=e.$options.propsData||{},r=e._props={},i=e.$options._propKeys=[];e.$parent&&$e(!1);var o=function(o){i.push(o);var a=Me(o,t,n,e);xe(r,o,a),o in e||dn(e,"_props",o)};for(var a in t)o(a);$e(!0)}(e,t.props),t.methods&&function(e,t){e.$options.props;for(var n in t)e[n]="function"!=typeof t[n]?S:x(t[n],e)}(e,t.methods),t.data?function(e){var t=e.$options.data;s(t=e._data="function"==typeof t?function(e,t){le();try{return e.call(t,t)}catch(e){return Re(e,t,"data()"),{}}finally{fe()}}(t,e):t||{})||(t={});var n=Object.keys(t),r=e.$options.props,i=(e.$options.methods,n.length);for(;i--;){var o=n[i];r&&y(r,o)||(a=void 0,36!==(a=(o+"").charCodeAt(0))&&95!==a&&dn(e,"_data",o))}var a;Ce(t,!0)}(e):Ce(e._data={},!0),t.computed&&function(e,t){var n=e._computedWatchers=Object.create(null),r=te();for(var i in t){var o=t[i],a="function"==typeof o?o:o.get;r||(n[i]=new fn(e,a||S,S,hn)),i in e||mn(e,i,o)}}(e,t.computed),t.watch&&t.watch!==Y&&function(e,t){for(var n in t){var r=t[n];if(Array.isArray(r))for(var i=0;i-1:"string"==typeof e?e.split(",").indexOf(t)>-1:(n=e,"[object RegExp]"===a.call(n)&&e.test(t));var n}function An(e,t){var n=e.cache,r=e.keys,i=e._vnode;for(var o in n){var a=n[o];if(a){var s=xn(a.componentOptions);s&&!t(s)&&On(n,o,r,i)}}}function On(e,t,n,r){var i=e[t];!i||r&&i.tag===r.tag||i.componentInstance.$destroy(),e[t]=null,h(n,t)}!function(t){t.prototype._init=function(t){var n=this;n._uid=bn++,n._isVue=!0,t&&t._isComponent?function(e,t){var n=e.$options=Object.create(e.constructor.options),r=t._parentVnode;n.parent=t.parent,n._parentVnode=r;var i=r.componentOptions;n.propsData=i.propsData,n._parentListeners=i.listeners,n._renderChildren=i.children,n._componentTag=i.tag,t.render&&(n.render=t.render,n.staticRenderFns=t.staticRenderFns)}(n,t):n.$options=De($n(n.constructor),t||{},n),n._renderProxy=n,n._self=n,function(e){var t=e.$options,n=t.parent;if(n&&!t.abstract){for(;n.$options.abstract&&n.$parent;)n=n.$parent;n.$children.push(e)}e.$parent=n,e.$root=n?n.$root:e,e.$children=[],e.$refs={},e._watcher=null,e._inactive=null,e._directInactive=!1,e._isMounted=!1,e._isDestroyed=!1,e._isBeingDestroyed=!1}(n),function(e){e._events=Object.create(null),e._hasHookEvent=!1;var t=e.$options._parentListeners;t&&qt(e,t)}(n),function(t){t._vnode=null,t._staticTrees=null;var n=t.$options,r=t.$vnode=n._parentVnode,i=r&&r.context;t.$slots=ut(n._renderChildren,i),t.$scopedSlots=e,t._c=function(e,n,r,i){return Pt(t,e,n,r,i,!1)},t.$createElement=function(e,n,r,i){return Pt(t,e,n,r,i,!0)};var o=r&&r.data;xe(t,"$attrs",o&&o.attrs||e,null,!0),xe(t,"$listeners",n._parentListeners||e,null,!0)}(n),Yt(n,"beforeCreate"),function(e){var t=ct(e.$options.inject,e);t&&($e(!1),Object.keys(t).forEach(function(n){xe(e,n,t[n])}),$e(!0))}(n),vn(n),function(e){var t=e.$options.provide;t&&(e._provided="function"==typeof t?t.call(e):t)}(n),Yt(n,"created"),n.$options.el&&n.$mount(n.$options.el)}}(wn),function(e){var t={get:function(){return this._data}},n={get:function(){return this._props}};Object.defineProperty(e.prototype,"$data",t),Object.defineProperty(e.prototype,"$props",n),e.prototype.$set=ke,e.prototype.$delete=Ae,e.prototype.$watch=function(e,t,n){if(s(t))return _n(this,e,t,n);(n=n||{}).user=!0;var r=new fn(this,e,t,n);if(n.immediate)try{t.call(this,r.value)}catch(e){Re(e,this,'callback for immediate watcher "'+r.expression+'"')}return function(){r.teardown()}}}(wn),function(e){var t=/^hook:/;e.prototype.$on=function(e,n){var r=this;if(Array.isArray(e))for(var i=0,o=e.length;i1?k(t):t;for(var n=k(arguments,1),r='event handler for "'+e+'"',i=0,o=t.length;iparseInt(this.max)&&On(a,s[0],s,this._vnode)),t.data.keepAlive=!0}return t||e&&e[0]}}};!function(e){var t={get:function(){return F}};Object.defineProperty(e,"config",t),e.util={warn:ae,extend:A,mergeOptions:De,defineReactive:xe},e.set=ke,e.delete=Ae,e.nextTick=Ye,e.observable=function(e){return Ce(e),e},e.options=Object.create(null),M.forEach(function(t){e.options[t+"s"]=Object.create(null)}),e.options._base=e,A(e.options.components,Tn),function(e){e.use=function(e){var t=this._installedPlugins||(this._installedPlugins=[]);if(t.indexOf(e)>-1)return this;var n=k(arguments,1);return n.unshift(this),"function"==typeof e.install?e.install.apply(e,n):"function"==typeof e&&e.apply(null,n),t.push(e),this}}(e),function(e){e.mixin=function(e){return this.options=De(this.options,e),this}}(e),Cn(e),function(e){M.forEach(function(t){e[t]=function(e,n){return n?("component"===t&&s(n)&&(n.name=n.name||e,n=this.options._base.extend(n)),"directive"===t&&"function"==typeof n&&(n={bind:n,update:n}),this.options[t+"s"][e]=n,n):this.options[t+"s"][e]}})}(e)}(wn),Object.defineProperty(wn.prototype,"$isServer",{get:te}),Object.defineProperty(wn.prototype,"$ssrContext",{get:function(){return this.$vnode&&this.$vnode.ssrContext}}),Object.defineProperty(wn,"FunctionalRenderContext",{value:Tt}),wn.version="2.6.11";var En=p("style,class"),Nn=p("input,textarea,option,select,progress"),jn=function(e,t,n){return"value"===n&&Nn(e)&&"button"!==t||"selected"===n&&"option"===e||"checked"===n&&"input"===e||"muted"===n&&"video"===e},Dn=p("contenteditable,draggable,spellcheck"),Ln=p("events,caret,typing,plaintext-only"),Mn=function(e,t){return Hn(t)||"false"===t?"false":"contenteditable"===e&&Ln(t)?t:"true"},In=p("allowfullscreen,async,autofocus,autoplay,checked,compact,controls,declare,default,defaultchecked,defaultmuted,defaultselected,defer,disabled,enabled,formnovalidate,hidden,indeterminate,inert,ismap,itemscope,loop,multiple,muted,nohref,noresize,noshade,novalidate,nowrap,open,pauseonexit,readonly,required,reversed,scoped,seamless,selected,sortable,translate,truespeed,typemustmatch,visible"),Fn="http://www.w3.org/1999/xlink",Pn=function(e){return":"===e.charAt(5)&&"xlink"===e.slice(0,5)},Rn=function(e){return Pn(e)?e.slice(6,e.length):""},Hn=function(e){return null==e||!1===e};function Bn(e){for(var t=e.data,r=e,i=e;n(i.componentInstance);)(i=i.componentInstance._vnode)&&i.data&&(t=Un(i.data,t));for(;n(r=r.parent);)r&&r.data&&(t=Un(t,r.data));return function(e,t){if(n(e)||n(t))return zn(e,Vn(t));return""}(t.staticClass,t.class)}function Un(e,t){return{staticClass:zn(e.staticClass,t.staticClass),class:n(e.class)?[e.class,t.class]:t.class}}function zn(e,t){return e?t?e+" "+t:e:t||""}function Vn(e){return Array.isArray(e)?function(e){for(var t,r="",i=0,o=e.length;i-1?hr(e,t,n):In(t)?Hn(n)?e.removeAttribute(t):(n="allowfullscreen"===t&&"EMBED"===e.tagName?"true":t,e.setAttribute(t,n)):Dn(t)?e.setAttribute(t,Mn(t,n)):Pn(t)?Hn(n)?e.removeAttributeNS(Fn,Rn(t)):e.setAttributeNS(Fn,t,n):hr(e,t,n)}function hr(e,t,n){if(Hn(n))e.removeAttribute(t);else{if(q&&!W&&"TEXTAREA"===e.tagName&&"placeholder"===t&&""!==n&&!e.__ieph){var r=function(t){t.stopImmediatePropagation(),e.removeEventListener("input",r)};e.addEventListener("input",r),e.__ieph=!0}e.setAttribute(t,n)}}var mr={create:dr,update:dr};function yr(e,r){var i=r.elm,o=r.data,a=e.data;if(!(t(o.staticClass)&&t(o.class)&&(t(a)||t(a.staticClass)&&t(a.class)))){var s=Bn(r),c=i._transitionClasses;n(c)&&(s=zn(s,Vn(c))),s!==i._prevClass&&(i.setAttribute("class",s),i._prevClass=s)}}var gr,_r,br,$r,wr,Cr,xr={create:yr,update:yr},kr=/[\w).+\-_$\]]/;function Ar(e){var t,n,r,i,o,a=!1,s=!1,c=!1,u=!1,l=0,f=0,p=0,d=0;for(r=0;r=0&&" "===(h=e.charAt(v));v--);h&&kr.test(h)||(u=!0)}}else void 0===i?(d=r+1,i=e.slice(0,r).trim()):m();function m(){(o||(o=[])).push(e.slice(d,r).trim()),d=r+1}if(void 0===i?i=e.slice(0,r).trim():0!==d&&m(),o)for(r=0;r-1?{exp:e.slice(0,$r),key:'"'+e.slice($r+1)+'"'}:{exp:e,key:null};_r=e,$r=wr=Cr=0;for(;!zr();)Vr(br=Ur())?Jr(br):91===br&&Kr(br);return{exp:e.slice(0,wr),key:e.slice(wr+1,Cr)}}(e);return null===n.key?e+"="+t:"$set("+n.exp+", "+n.key+", "+t+")"}function Ur(){return _r.charCodeAt(++$r)}function zr(){return $r>=gr}function Vr(e){return 34===e||39===e}function Kr(e){var t=1;for(wr=$r;!zr();)if(Vr(e=Ur()))Jr(e);else if(91===e&&t++,93===e&&t--,0===t){Cr=$r;break}}function Jr(e){for(var t=e;!zr()&&(e=Ur())!==t;);}var qr,Wr="__r",Zr="__c";function Gr(e,t,n){var r=qr;return function i(){null!==t.apply(null,arguments)&&Qr(e,i,n,r)}}var Xr=Ve&&!(X&&Number(X[1])<=53);function Yr(e,t,n,r){if(Xr){var i=an,o=t;t=o._wrapper=function(e){if(e.target===e.currentTarget||e.timeStamp>=i||e.timeStamp<=0||e.target.ownerDocument!==document)return o.apply(this,arguments)}}qr.addEventListener(e,t,Q?{capture:n,passive:r}:n)}function Qr(e,t,n,r){(r||qr).removeEventListener(e,t._wrapper||t,n)}function ei(e,r){if(!t(e.data.on)||!t(r.data.on)){var i=r.data.on||{},o=e.data.on||{};qr=r.elm,function(e){if(n(e[Wr])){var t=q?"change":"input";e[t]=[].concat(e[Wr],e[t]||[]),delete e[Wr]}n(e[Zr])&&(e.change=[].concat(e[Zr],e.change||[]),delete e[Zr])}(i),rt(i,o,Yr,Qr,Gr,r.context),qr=void 0}}var ti,ni={create:ei,update:ei};function ri(e,r){if(!t(e.data.domProps)||!t(r.data.domProps)){var i,o,a=r.elm,s=e.data.domProps||{},c=r.data.domProps||{};for(i in n(c.__ob__)&&(c=r.data.domProps=A({},c)),s)i in c||(a[i]="");for(i in c){if(o=c[i],"textContent"===i||"innerHTML"===i){if(r.children&&(r.children.length=0),o===s[i])continue;1===a.childNodes.length&&a.removeChild(a.childNodes[0])}if("value"===i&&"PROGRESS"!==a.tagName){a._value=o;var u=t(o)?"":String(o);ii(a,u)&&(a.value=u)}else if("innerHTML"===i&&qn(a.tagName)&&t(a.innerHTML)){(ti=ti||document.createElement("div")).innerHTML=""+o+"";for(var l=ti.firstChild;a.firstChild;)a.removeChild(a.firstChild);for(;l.firstChild;)a.appendChild(l.firstChild)}else if(o!==s[i])try{a[i]=o}catch(e){}}}}function ii(e,t){return!e.composing&&("OPTION"===e.tagName||function(e,t){var n=!0;try{n=document.activeElement!==e}catch(e){}return n&&e.value!==t}(e,t)||function(e,t){var r=e.value,i=e._vModifiers;if(n(i)){if(i.number)return f(r)!==f(t);if(i.trim)return r.trim()!==t.trim()}return r!==t}(e,t))}var oi={create:ri,update:ri},ai=g(function(e){var t={},n=/:(.+)/;return e.split(/;(?![^(]*\))/g).forEach(function(e){if(e){var r=e.split(n);r.length>1&&(t[r[0].trim()]=r[1].trim())}}),t});function si(e){var t=ci(e.style);return e.staticStyle?A(e.staticStyle,t):t}function ci(e){return Array.isArray(e)?O(e):"string"==typeof e?ai(e):e}var ui,li=/^--/,fi=/\s*!important$/,pi=function(e,t,n){if(li.test(t))e.style.setProperty(t,n);else if(fi.test(n))e.style.setProperty(C(t),n.replace(fi,""),"important");else{var r=vi(t);if(Array.isArray(n))for(var i=0,o=n.length;i-1?t.split(yi).forEach(function(t){return e.classList.add(t)}):e.classList.add(t);else{var n=" "+(e.getAttribute("class")||"")+" ";n.indexOf(" "+t+" ")<0&&e.setAttribute("class",(n+t).trim())}}function _i(e,t){if(t&&(t=t.trim()))if(e.classList)t.indexOf(" ")>-1?t.split(yi).forEach(function(t){return e.classList.remove(t)}):e.classList.remove(t),e.classList.length||e.removeAttribute("class");else{for(var n=" "+(e.getAttribute("class")||"")+" ",r=" "+t+" ";n.indexOf(r)>=0;)n=n.replace(r," ");(n=n.trim())?e.setAttribute("class",n):e.removeAttribute("class")}}function bi(e){if(e){if("object"==typeof e){var t={};return!1!==e.css&&A(t,$i(e.name||"v")),A(t,e),t}return"string"==typeof e?$i(e):void 0}}var $i=g(function(e){return{enterClass:e+"-enter",enterToClass:e+"-enter-to",enterActiveClass:e+"-enter-active",leaveClass:e+"-leave",leaveToClass:e+"-leave-to",leaveActiveClass:e+"-leave-active"}}),wi=z&&!W,Ci="transition",xi="animation",ki="transition",Ai="transitionend",Oi="animation",Si="animationend";wi&&(void 0===window.ontransitionend&&void 0!==window.onwebkittransitionend&&(ki="WebkitTransition",Ai="webkitTransitionEnd"),void 0===window.onanimationend&&void 0!==window.onwebkitanimationend&&(Oi="WebkitAnimation",Si="webkitAnimationEnd"));var Ti=z?window.requestAnimationFrame?window.requestAnimationFrame.bind(window):setTimeout:function(e){return e()};function Ei(e){Ti(function(){Ti(e)})}function Ni(e,t){var n=e._transitionClasses||(e._transitionClasses=[]);n.indexOf(t)<0&&(n.push(t),gi(e,t))}function ji(e,t){e._transitionClasses&&h(e._transitionClasses,t),_i(e,t)}function Di(e,t,n){var r=Mi(e,t),i=r.type,o=r.timeout,a=r.propCount;if(!i)return n();var s=i===Ci?Ai:Si,c=0,u=function(){e.removeEventListener(s,l),n()},l=function(t){t.target===e&&++c>=a&&u()};setTimeout(function(){c0&&(n=Ci,l=a,f=o.length):t===xi?u>0&&(n=xi,l=u,f=c.length):f=(n=(l=Math.max(a,u))>0?a>u?Ci:xi:null)?n===Ci?o.length:c.length:0,{type:n,timeout:l,propCount:f,hasTransform:n===Ci&&Li.test(r[ki+"Property"])}}function Ii(e,t){for(;e.length1}function Ui(e,t){!0!==t.data.show&&Pi(t)}var zi=function(e){var o,a,s={},c=e.modules,u=e.nodeOps;for(o=0;ov?_(e,t(i[y+1])?null:i[y+1].elm,i,d,y,o):d>y&&$(r,p,v)}(p,h,y,o,l):n(y)?(n(e.text)&&u.setTextContent(p,""),_(p,null,y,0,y.length-1,o)):n(h)?$(h,0,h.length-1):n(e.text)&&u.setTextContent(p,""):e.text!==i.text&&u.setTextContent(p,i.text),n(v)&&n(d=v.hook)&&n(d=d.postpatch)&&d(e,i)}}}function k(e,t,i){if(r(i)&&n(e.parent))e.parent.data.pendingInsert=t;else for(var o=0;o-1,a.selected!==o&&(a.selected=o);else if(N(Wi(a),r))return void(e.selectedIndex!==s&&(e.selectedIndex=s));i||(e.selectedIndex=-1)}}function qi(e,t){return t.every(function(t){return!N(t,e)})}function Wi(e){return"_value"in e?e._value:e.value}function Zi(e){e.target.composing=!0}function Gi(e){e.target.composing&&(e.target.composing=!1,Xi(e.target,"input"))}function Xi(e,t){var n=document.createEvent("HTMLEvents");n.initEvent(t,!0,!0),e.dispatchEvent(n)}function Yi(e){return!e.componentInstance||e.data&&e.data.transition?e:Yi(e.componentInstance._vnode)}var Qi={model:Vi,show:{bind:function(e,t,n){var r=t.value,i=(n=Yi(n)).data&&n.data.transition,o=e.__vOriginalDisplay="none"===e.style.display?"":e.style.display;r&&i?(n.data.show=!0,Pi(n,function(){e.style.display=o})):e.style.display=r?o:"none"},update:function(e,t,n){var r=t.value;!r!=!t.oldValue&&((n=Yi(n)).data&&n.data.transition?(n.data.show=!0,r?Pi(n,function(){e.style.display=e.__vOriginalDisplay}):Ri(n,function(){e.style.display="none"})):e.style.display=r?e.__vOriginalDisplay:"none")},unbind:function(e,t,n,r,i){i||(e.style.display=e.__vOriginalDisplay)}}},eo={name:String,appear:Boolean,css:Boolean,mode:String,type:String,enterClass:String,leaveClass:String,enterToClass:String,leaveToClass:String,enterActiveClass:String,leaveActiveClass:String,appearClass:String,appearActiveClass:String,appearToClass:String,duration:[Number,String,Object]};function to(e){var t=e&&e.componentOptions;return t&&t.Ctor.options.abstract?to(zt(t.children)):e}function no(e){var t={},n=e.$options;for(var r in n.propsData)t[r]=e[r];var i=n._parentListeners;for(var o in i)t[b(o)]=i[o];return t}function ro(e,t){if(/\d-keep-alive$/.test(t.tag))return e("keep-alive",{props:t.componentOptions.propsData})}var io=function(e){return e.tag||Ut(e)},oo=function(e){return"show"===e.name},ao={name:"transition",props:eo,abstract:!0,render:function(e){var t=this,n=this.$slots.default;if(n&&(n=n.filter(io)).length){var r=this.mode,o=n[0];if(function(e){for(;e=e.parent;)if(e.data.transition)return!0}(this.$vnode))return o;var a=to(o);if(!a)return o;if(this._leaving)return ro(e,o);var s="__transition-"+this._uid+"-";a.key=null==a.key?a.isComment?s+"comment":s+a.tag:i(a.key)?0===String(a.key).indexOf(s)?a.key:s+a.key:a.key;var c=(a.data||(a.data={})).transition=no(this),u=this._vnode,l=to(u);if(a.data.directives&&a.data.directives.some(oo)&&(a.data.show=!0),l&&l.data&&!function(e,t){return t.key===e.key&&t.tag===e.tag}(a,l)&&!Ut(l)&&(!l.componentInstance||!l.componentInstance._vnode.isComment)){var f=l.data.transition=A({},c);if("out-in"===r)return this._leaving=!0,it(f,"afterLeave",function(){t._leaving=!1,t.$forceUpdate()}),ro(e,o);if("in-out"===r){if(Ut(a))return u;var p,d=function(){p()};it(c,"afterEnter",d),it(c,"enterCancelled",d),it(f,"delayLeave",function(e){p=e})}}return o}}},so=A({tag:String,moveClass:String},eo);function co(e){e.elm._moveCb&&e.elm._moveCb(),e.elm._enterCb&&e.elm._enterCb()}function uo(e){e.data.newPos=e.elm.getBoundingClientRect()}function lo(e){var t=e.data.pos,n=e.data.newPos,r=t.left-n.left,i=t.top-n.top;if(r||i){e.data.moved=!0;var o=e.elm.style;o.transform=o.WebkitTransform="translate("+r+"px,"+i+"px)",o.transitionDuration="0s"}}delete so.mode;var fo={Transition:ao,TransitionGroup:{props:so,beforeMount:function(){var e=this,t=this._update;this._update=function(n,r){var i=Zt(e);e.__patch__(e._vnode,e.kept,!1,!0),e._vnode=e.kept,i(),t.call(e,n,r)}},render:function(e){for(var t=this.tag||this.$vnode.data.tag||"span",n=Object.create(null),r=this.prevChildren=this.children,i=this.$slots.default||[],o=this.children=[],a=no(this),s=0;s-1?Gn[e]=t.constructor===window.HTMLUnknownElement||t.constructor===window.HTMLElement:Gn[e]=/HTMLUnknownElement/.test(t.toString())},A(wn.options.directives,Qi),A(wn.options.components,fo),wn.prototype.__patch__=z?zi:S,wn.prototype.$mount=function(e,t){return function(e,t,n){var r;return e.$el=t,e.$options.render||(e.$options.render=ve),Yt(e,"beforeMount"),r=function(){e._update(e._render(),n)},new fn(e,r,S,{before:function(){e._isMounted&&!e._isDestroyed&&Yt(e,"beforeUpdate")}},!0),n=!1,null==e.$vnode&&(e._isMounted=!0,Yt(e,"mounted")),e}(this,e=e&&z?Yn(e):void 0,t)},z&&setTimeout(function(){F.devtools&&ne&&ne.emit("init",wn)},0);var po=/\{\{((?:.|\r?\n)+?)\}\}/g,vo=/[-.*+?^${}()|[\]\/\\]/g,ho=g(function(e){var t=e[0].replace(vo,"\\$&"),n=e[1].replace(vo,"\\$&");return new RegExp(t+"((?:.|\\n)+?)"+n,"g")});var mo={staticKeys:["staticClass"],transformNode:function(e,t){t.warn;var n=Fr(e,"class");n&&(e.staticClass=JSON.stringify(n));var r=Ir(e,"class",!1);r&&(e.classBinding=r)},genData:function(e){var t="";return e.staticClass&&(t+="staticClass:"+e.staticClass+","),e.classBinding&&(t+="class:"+e.classBinding+","),t}};var yo,go={staticKeys:["staticStyle"],transformNode:function(e,t){t.warn;var n=Fr(e,"style");n&&(e.staticStyle=JSON.stringify(ai(n)));var r=Ir(e,"style",!1);r&&(e.styleBinding=r)},genData:function(e){var t="";return e.staticStyle&&(t+="staticStyle:"+e.staticStyle+","),e.styleBinding&&(t+="style:("+e.styleBinding+"),"),t}},_o=function(e){return(yo=yo||document.createElement("div")).innerHTML=e,yo.textContent},bo=p("area,base,br,col,embed,frame,hr,img,input,isindex,keygen,link,meta,param,source,track,wbr"),$o=p("colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr,source"),wo=p("address,article,aside,base,blockquote,body,caption,col,colgroup,dd,details,dialog,div,dl,dt,fieldset,figcaption,figure,footer,form,h1,h2,h3,h4,h5,h6,head,header,hgroup,hr,html,legend,li,menuitem,meta,optgroup,option,param,rp,rt,source,style,summary,tbody,td,tfoot,th,thead,title,tr,track"),Co=/^\s*([^\s"'<>\/=]+)(?:\s*(=)\s*(?:"([^"]*)"+|'([^']*)'+|([^\s"'=<>`]+)))?/,xo=/^\s*((?:v-[\w-]+:|@|:|#)\[[^=]+\][^\s"'<>\/=]*)(?:\s*(=)\s*(?:"([^"]*)"+|'([^']*)'+|([^\s"'=<>`]+)))?/,ko="[a-zA-Z_][\\-\\.0-9_a-zA-Z"+P.source+"]*",Ao="((?:"+ko+"\\:)?"+ko+")",Oo=new RegExp("^<"+Ao),So=/^\s*(\/?)>/,To=new RegExp("^<\\/"+Ao+"[^>]*>"),Eo=/^]+>/i,No=/^",""":'"',"&":"&"," ":"\n"," ":"\t","'":"'"},Io=/&(?:lt|gt|quot|amp|#39);/g,Fo=/&(?:lt|gt|quot|amp|#39|#10|#9);/g,Po=p("pre,textarea",!0),Ro=function(e,t){return e&&Po(e)&&"\n"===t[0]};function Ho(e,t){var n=t?Fo:Io;return e.replace(n,function(e){return Mo[e]})}var Bo,Uo,zo,Vo,Ko,Jo,qo,Wo,Zo=/^@|^v-on:/,Go=/^v-|^@|^:|^#/,Xo=/([\s\S]*?)\s+(?:in|of)\s+([\s\S]*)/,Yo=/,([^,\}\]]*)(?:,([^,\}\]]*))?$/,Qo=/^\(|\)$/g,ea=/^\[.*\]$/,ta=/:(.*)$/,na=/^:|^\.|^v-bind:/,ra=/\.[^.\]]+(?=[^\]]*$)/g,ia=/^v-slot(:|$)|^#/,oa=/[\r\n]/,aa=/\s+/g,sa=g(_o),ca="_empty_";function ua(e,t,n){return{type:1,tag:e,attrsList:t,attrsMap:ma(t),rawAttrsMap:{},parent:n,children:[]}}function la(e,t){Bo=t.warn||Sr,Jo=t.isPreTag||T,qo=t.mustUseProp||T,Wo=t.getTagNamespace||T;t.isReservedTag;zo=Tr(t.modules,"transformNode"),Vo=Tr(t.modules,"preTransformNode"),Ko=Tr(t.modules,"postTransformNode"),Uo=t.delimiters;var n,r,i=[],o=!1!==t.preserveWhitespace,a=t.whitespace,s=!1,c=!1;function u(e){if(l(e),s||e.processed||(e=fa(e,t)),i.length||e===n||n.if&&(e.elseif||e.else)&&da(n,{exp:e.elseif,block:e}),r&&!e.forbidden)if(e.elseif||e.else)a=e,(u=function(e){var t=e.length;for(;t--;){if(1===e[t].type)return e[t];e.pop()}}(r.children))&&u.if&&da(u,{exp:a.elseif,block:a});else{if(e.slotScope){var o=e.slotTarget||'"default"';(r.scopedSlots||(r.scopedSlots={}))[o]=e}r.children.push(e),e.parent=r}var a,u;e.children=e.children.filter(function(e){return!e.slotScope}),l(e),e.pre&&(s=!1),Jo(e.tag)&&(c=!1);for(var f=0;f]*>)","i")),p=e.replace(f,function(e,n,r){return u=r.length,Do(l)||"noscript"===l||(n=n.replace(//g,"$1").replace(//g,"$1")),Ro(l,n)&&(n=n.slice(1)),t.chars&&t.chars(n),""});c+=e.length-p.length,e=p,A(l,c-u,c)}else{var d=e.indexOf("<");if(0===d){if(No.test(e)){var v=e.indexOf("--\x3e");if(v>=0){t.shouldKeepComment&&t.comment(e.substring(4,v),c,c+v+3),C(v+3);continue}}if(jo.test(e)){var h=e.indexOf("]>");if(h>=0){C(h+2);continue}}var m=e.match(Eo);if(m){C(m[0].length);continue}var y=e.match(To);if(y){var g=c;C(y[0].length),A(y[1],g,c);continue}var _=x();if(_){k(_),Ro(_.tagName,e)&&C(1);continue}}var b=void 0,$=void 0,w=void 0;if(d>=0){for($=e.slice(d);!(To.test($)||Oo.test($)||No.test($)||jo.test($)||(w=$.indexOf("<",1))<0);)d+=w,$=e.slice(d);b=e.substring(0,d)}d<0&&(b=e),b&&C(b.length),t.chars&&b&&t.chars(b,c-b.length,c)}if(e===n){t.chars&&t.chars(e);break}}function C(t){c+=t,e=e.substring(t)}function x(){var t=e.match(Oo);if(t){var n,r,i={tagName:t[1],attrs:[],start:c};for(C(t[0].length);!(n=e.match(So))&&(r=e.match(xo)||e.match(Co));)r.start=c,C(r[0].length),r.end=c,i.attrs.push(r);if(n)return i.unarySlash=n[1],C(n[0].length),i.end=c,i}}function k(e){var n=e.tagName,c=e.unarySlash;o&&("p"===r&&wo(n)&&A(r),s(n)&&r===n&&A(n));for(var u=a(n)||!!c,l=e.attrs.length,f=new Array(l),p=0;p=0&&i[a].lowerCasedTag!==s;a--);else a=0;if(a>=0){for(var u=i.length-1;u>=a;u--)t.end&&t.end(i[u].tag,n,o);i.length=a,r=a&&i[a-1].tag}else"br"===s?t.start&&t.start(e,[],!0,n,o):"p"===s&&(t.start&&t.start(e,[],!1,n,o),t.end&&t.end(e,n,o))}A()}(e,{warn:Bo,expectHTML:t.expectHTML,isUnaryTag:t.isUnaryTag,canBeLeftOpenTag:t.canBeLeftOpenTag,shouldDecodeNewlines:t.shouldDecodeNewlines,shouldDecodeNewlinesForHref:t.shouldDecodeNewlinesForHref,shouldKeepComment:t.comments,outputSourceRange:t.outputSourceRange,start:function(e,o,a,l,f){var p=r&&r.ns||Wo(e);q&&"svg"===p&&(o=function(e){for(var t=[],n=0;nc&&(s.push(o=e.slice(c,i)),a.push(JSON.stringify(o)));var u=Ar(r[1].trim());a.push("_s("+u+")"),s.push({"@binding":u}),c=i+r[0].length}return c-1"+("true"===o?":("+t+")":":_q("+t+","+o+")")),Mr(e,"change","var $$a="+t+",$$el=$event.target,$$c=$$el.checked?("+o+"):("+a+");if(Array.isArray($$a)){var $$v="+(r?"_n("+i+")":i)+",$$i=_i($$a,$$v);if($$el.checked){$$i<0&&("+Br(t,"$$a.concat([$$v])")+")}else{$$i>-1&&("+Br(t,"$$a.slice(0,$$i).concat($$a.slice($$i+1))")+")}}else{"+Br(t,"$$c")+"}",null,!0)}(e,r,i);else if("input"===o&&"radio"===a)!function(e,t,n){var r=n&&n.number,i=Ir(e,"value")||"null";Er(e,"checked","_q("+t+","+(i=r?"_n("+i+")":i)+")"),Mr(e,"change",Br(t,i),null,!0)}(e,r,i);else if("input"===o||"textarea"===o)!function(e,t,n){var r=e.attrsMap.type,i=n||{},o=i.lazy,a=i.number,s=i.trim,c=!o&&"range"!==r,u=o?"change":"range"===r?Wr:"input",l="$event.target.value";s&&(l="$event.target.value.trim()"),a&&(l="_n("+l+")");var f=Br(t,l);c&&(f="if($event.target.composing)return;"+f),Er(e,"value","("+t+")"),Mr(e,u,f,null,!0),(s||a)&&Mr(e,"blur","$forceUpdate()")}(e,r,i);else if(!F.isReservedTag(o))return Hr(e,r,i),!1;return!0},text:function(e,t){t.value&&Er(e,"textContent","_s("+t.value+")",t)},html:function(e,t){t.value&&Er(e,"innerHTML","_s("+t.value+")",t)}},isPreTag:function(e){return"pre"===e},isUnaryTag:bo,mustUseProp:jn,canBeLeftOpenTag:$o,isReservedTag:Wn,getTagNamespace:Zn,staticKeys:function(e){return e.reduce(function(e,t){return e.concat(t.staticKeys||[])},[]).join(",")}(ba)},xa=g(function(e){return p("type,tag,attrsList,attrsMap,plain,parent,children,attrs,start,end,rawAttrsMap"+(e?","+e:""))});function ka(e,t){e&&($a=xa(t.staticKeys||""),wa=t.isReservedTag||T,function e(t){t.static=function(e){if(2===e.type)return!1;if(3===e.type)return!0;return!(!e.pre&&(e.hasBindings||e.if||e.for||d(e.tag)||!wa(e.tag)||function(e){for(;e.parent;){if("template"!==(e=e.parent).tag)return!1;if(e.for)return!0}return!1}(e)||!Object.keys(e).every($a)))}(t);if(1===t.type){if(!wa(t.tag)&&"slot"!==t.tag&&null==t.attrsMap["inline-template"])return;for(var n=0,r=t.children.length;n|^function(?:\s+[\w$]+)?\s*\(/,Oa=/\([^)]*?\);*$/,Sa=/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*|\['[^']*?']|\["[^"]*?"]|\[\d+]|\[[A-Za-z_$][\w$]*])*$/,Ta={esc:27,tab:9,enter:13,space:32,up:38,left:37,right:39,down:40,delete:[8,46]},Ea={esc:["Esc","Escape"],tab:"Tab",enter:"Enter",space:[" ","Spacebar"],up:["Up","ArrowUp"],left:["Left","ArrowLeft"],right:["Right","ArrowRight"],down:["Down","ArrowDown"],delete:["Backspace","Delete","Del"]},Na=function(e){return"if("+e+")return null;"},ja={stop:"$event.stopPropagation();",prevent:"$event.preventDefault();",self:Na("$event.target !== $event.currentTarget"),ctrl:Na("!$event.ctrlKey"),shift:Na("!$event.shiftKey"),alt:Na("!$event.altKey"),meta:Na("!$event.metaKey"),left:Na("'button' in $event && $event.button !== 0"),middle:Na("'button' in $event && $event.button !== 1"),right:Na("'button' in $event && $event.button !== 2")};function Da(e,t){var n=t?"nativeOn:":"on:",r="",i="";for(var o in e){var a=La(e[o]);e[o]&&e[o].dynamic?i+=o+","+a+",":r+='"'+o+'":'+a+","}return r="{"+r.slice(0,-1)+"}",i?n+"_d("+r+",["+i.slice(0,-1)+"])":n+r}function La(e){if(!e)return"function(){}";if(Array.isArray(e))return"["+e.map(function(e){return La(e)}).join(",")+"]";var t=Sa.test(e.value),n=Aa.test(e.value),r=Sa.test(e.value.replace(Oa,""));if(e.modifiers){var i="",o="",a=[];for(var s in e.modifiers)if(ja[s])o+=ja[s],Ta[s]&&a.push(s);else if("exact"===s){var c=e.modifiers;o+=Na(["ctrl","shift","alt","meta"].filter(function(e){return!c[e]}).map(function(e){return"$event."+e+"Key"}).join("||"))}else a.push(s);return a.length&&(i+=function(e){return"if(!$event.type.indexOf('key')&&"+e.map(Ma).join("&&")+")return null;"}(a)),o&&(i+=o),"function($event){"+i+(t?"return "+e.value+"($event)":n?"return ("+e.value+")($event)":r?"return "+e.value:e.value)+"}"}return t||n?e.value:"function($event){"+(r?"return "+e.value:e.value)+"}"}function Ma(e){var t=parseInt(e,10);if(t)return"$event.keyCode!=="+t;var n=Ta[e],r=Ea[e];return"_k($event.keyCode,"+JSON.stringify(e)+","+JSON.stringify(n)+",$event.key,"+JSON.stringify(r)+")"}var Ia={on:function(e,t){e.wrapListeners=function(e){return"_g("+e+","+t.value+")"}},bind:function(e,t){e.wrapData=function(n){return"_b("+n+",'"+e.tag+"',"+t.value+","+(t.modifiers&&t.modifiers.prop?"true":"false")+(t.modifiers&&t.modifiers.sync?",true":"")+")"}},cloak:S},Fa=function(e){this.options=e,this.warn=e.warn||Sr,this.transforms=Tr(e.modules,"transformCode"),this.dataGenFns=Tr(e.modules,"genData"),this.directives=A(A({},Ia),e.directives);var t=e.isReservedTag||T;this.maybeComponent=function(e){return!!e.component||!t(e.tag)},this.onceId=0,this.staticRenderFns=[],this.pre=!1};function Pa(e,t){var n=new Fa(t);return{render:"with(this){return "+(e?Ra(e,n):'_c("div")')+"}",staticRenderFns:n.staticRenderFns}}function Ra(e,t){if(e.parent&&(e.pre=e.pre||e.parent.pre),e.staticRoot&&!e.staticProcessed)return Ha(e,t);if(e.once&&!e.onceProcessed)return Ba(e,t);if(e.for&&!e.forProcessed)return za(e,t);if(e.if&&!e.ifProcessed)return Ua(e,t);if("template"!==e.tag||e.slotTarget||t.pre){if("slot"===e.tag)return function(e,t){var n=e.slotName||'"default"',r=qa(e,t),i="_t("+n+(r?","+r:""),o=e.attrs||e.dynamicAttrs?Ga((e.attrs||[]).concat(e.dynamicAttrs||[]).map(function(e){return{name:b(e.name),value:e.value,dynamic:e.dynamic}})):null,a=e.attrsMap["v-bind"];!o&&!a||r||(i+=",null");o&&(i+=","+o);a&&(i+=(o?"":",null")+","+a);return i+")"}(e,t);var n;if(e.component)n=function(e,t,n){var r=t.inlineTemplate?null:qa(t,n,!0);return"_c("+e+","+Va(t,n)+(r?","+r:"")+")"}(e.component,e,t);else{var r;(!e.plain||e.pre&&t.maybeComponent(e))&&(r=Va(e,t));var i=e.inlineTemplate?null:qa(e,t,!0);n="_c('"+e.tag+"'"+(r?","+r:"")+(i?","+i:"")+")"}for(var o=0;o>>0}(a):"")+")"}(e,e.scopedSlots,t)+","),e.model&&(n+="model:{value:"+e.model.value+",callback:"+e.model.callback+",expression:"+e.model.expression+"},"),e.inlineTemplate){var o=function(e,t){var n=e.children[0];if(n&&1===n.type){var r=Pa(n,t.options);return"inlineTemplate:{render:function(){"+r.render+"},staticRenderFns:["+r.staticRenderFns.map(function(e){return"function(){"+e+"}"}).join(",")+"]}"}}(e,t);o&&(n+=o+",")}return n=n.replace(/,$/,"")+"}",e.dynamicAttrs&&(n="_b("+n+',"'+e.tag+'",'+Ga(e.dynamicAttrs)+")"),e.wrapData&&(n=e.wrapData(n)),e.wrapListeners&&(n=e.wrapListeners(n)),n}function Ka(e){return 1===e.type&&("slot"===e.tag||e.children.some(Ka))}function Ja(e,t){var n=e.attrsMap["slot-scope"];if(e.if&&!e.ifProcessed&&!n)return Ua(e,t,Ja,"null");if(e.for&&!e.forProcessed)return za(e,t,Ja);var r=e.slotScope===ca?"":String(e.slotScope),i="function("+r+"){return "+("template"===e.tag?e.if&&n?"("+e.if+")?"+(qa(e,t)||"undefined")+":undefined":qa(e,t)||"undefined":Ra(e,t))+"}",o=r?"":",proxy:true";return"{key:"+(e.slotTarget||'"default"')+",fn:"+i+o+"}"}function qa(e,t,n,r,i){var o=e.children;if(o.length){var a=o[0];if(1===o.length&&a.for&&"template"!==a.tag&&"slot"!==a.tag){var s=n?t.maybeComponent(a)?",1":",0":"";return""+(r||Ra)(a,t)+s}var c=n?function(e,t){for(var n=0,r=0;r':'
',ts.innerHTML.indexOf(" ")>0}var os=!!z&&is(!1),as=!!z&&is(!0),ss=g(function(e){var t=Yn(e);return t&&t.innerHTML}),cs=wn.prototype.$mount;return wn.prototype.$mount=function(e,t){if((e=e&&Yn(e))===document.body||e===document.documentElement)return this;var n=this.$options;if(!n.render){var r=n.template;if(r)if("string"==typeof r)"#"===r.charAt(0)&&(r=ss(r));else{if(!r.nodeType)return this;r=r.innerHTML}else e&&(r=function(e){if(e.outerHTML)return e.outerHTML;var t=document.createElement("div");return t.appendChild(e.cloneNode(!0)),t.innerHTML}(e));if(r){var i=rs(r,{outputSourceRange:!1,shouldDecodeNewlines:os,shouldDecodeNewlinesForHref:as,delimiters:n.delimiters,comments:n.comments},this),o=i.render,a=i.staticRenderFns;n.render=o,n.staticRenderFns=a}}return cs.call(this,e,t)},wn.compile=rs,wn}); ================================================ FILE: api-test-v4/lib/js/vue-json-pretty.js ================================================ !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.VueJsonPretty=t():e.VueJsonPretty=t()}("undefined"!=typeof self?self:this,function(){return function(e){function t(r){if(n[r])return n[r].exports;var o=n[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,t),o.l=!0,o.exports}var n={};return t.m=e,t.c=n,t.d=function(e,n,r){t.o(e,n)||Object.defineProperty(e,n,{configurable:!1,enumerable:!0,get:r})},t.n=function(e){var n=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(n,"a",n),n},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p="",t(t.s=39)}([function(e,t){var n=e.exports={version:"2.6.9"};"number"==typeof __e&&(__e=n)},function(e,t,n){var r=n(25)("wks"),o=n(27),i=n(3).Symbol,s="function"==typeof i;(e.exports=function(e){return r[e]||(r[e]=s&&i[e]||(s?i:o)("Symbol."+e))}).store=r},function(e,t){e.exports=function(e,t,n,r,o,i){var s,a=e=e||{},c=typeof e.default;"object"!==c&&"function"!==c||(s=e,a=e.default);var u="function"==typeof a?a.options:a;t&&(u.render=t.render,u.staticRenderFns=t.staticRenderFns,u._compiled=!0),n&&(u.functional=!0),o&&(u._scopeId=o);var l;if(i?(l=function(e){e=e||this.$vnode&&this.$vnode.ssrContext||this.parent&&this.parent.$vnode&&this.parent.$vnode.ssrContext,e||"undefined"==typeof __VUE_SSR_CONTEXT__||(e=__VUE_SSR_CONTEXT__),r&&r.call(this,e),e&&e._registeredComponents&&e._registeredComponents.add(i)},u._ssrRegister=l):r&&(l=r),l){var f=u.functional,d=f?u.render:u.beforeCreate;f?(u._injectStyles=l,u.render=function(e,t){return l.call(t),d(e,t)}):u.beforeCreate=d?[].concat(d,l):[l]}return{esModule:s,exports:a,options:u}}},function(e,t){var n=e.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=n)},function(e,t,n){e.exports=!n(9)(function(){return 7!=Object.defineProperty({},"a",{get:function(){return 7}}).a})},function(e,t,n){var r=n(3),o=n(0),i=n(19),s=n(6),a=n(10),c=function(e,t,n){var u,l,f,d=e&c.F,p=e&c.G,h=e&c.S,v=e&c.P,b=e&c.B,m=e&c.W,y=p?o:o[t]||(o[t]={}),g=y.prototype,_=p?r:h?r[t]:(r[t]||{}).prototype;p&&(n=t);for(u in n)(l=!d&&_&&void 0!==_[u])&&a(y,u)||(f=l?_[u]:n[u],y[u]=p&&"function"!=typeof _[u]?n[u]:b&&l?i(f,r):m&&_[u]==f?function(e){var t=function(t,n,r){if(this instanceof e){switch(arguments.length){case 0:return new e;case 1:return new e(t);case 2:return new e(t,n)}return new e(t,n,r)}return e.apply(this,arguments)};return t.prototype=e.prototype,t}(f):v&&"function"==typeof f?i(Function.call,f):f,v&&((y.virtual||(y.virtual={}))[u]=f,e&c.R&&g&&!g[u]&&s(g,u,f)))};c.F=1,c.G=2,c.S=4,c.P=8,c.B=16,c.W=32,c.U=64,c.R=128,e.exports=c},function(e,t,n){var r=n(7),o=n(13);e.exports=n(4)?function(e,t,n){return r.f(e,t,o(1,n))}:function(e,t,n){return e[t]=n,e}},function(e,t,n){var r=n(8),o=n(44),i=n(45),s=Object.defineProperty;t.f=n(4)?Object.defineProperty:function(e,t,n){if(r(e),t=i(t,!0),r(n),o)try{return s(e,t,n)}catch(e){}if("get"in n||"set"in n)throw TypeError("Accessors not supported!");return"value"in n&&(e[t]=n.value),e}},function(e,t,n){var r=n(12);e.exports=function(e){if(!r(e))throw TypeError(e+" is not an object!");return e}},function(e,t){e.exports=function(e){try{return!!e()}catch(e){return!0}}},function(e,t){var n={}.hasOwnProperty;e.exports=function(e,t){return n.call(e,t)}},function(e,t,n){var r=n(15);e.exports=function(e){return Object(r(e))}},function(e,t){e.exports=function(e){return"object"==typeof e?null!==e:"function"==typeof e}},function(e,t){e.exports=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}}},function(e,t,n){var r=n(47),o=n(28);e.exports=Object.keys||function(e){return r(e,o)}},function(e,t){e.exports=function(e){if(void 0==e)throw TypeError("Can't call method on "+e);return e}},function(e,t){var n=Math.ceil,r=Math.floor;e.exports=function(e){return isNaN(e=+e)?0:(e>0?r:n)(e)}},function(e,t,n){var r=n(25)("keys"),o=n(27);e.exports=function(e){return r[e]||(r[e]=o(e))}},function(e,t){e.exports={}},function(e,t,n){var r=n(43);e.exports=function(e,t,n){if(r(e),void 0===t)return e;switch(n){case 1:return function(n){return e.call(t,n)};case 2:return function(n,r){return e.call(t,n,r)};case 3:return function(n,r,o){return e.call(t,n,r,o)}}return function(){return e.apply(t,arguments)}}},function(e,t,n){var r=n(12),o=n(3).document,i=r(o)&&r(o.createElement);e.exports=function(e){return i?o.createElement(e):{}}},function(e,t,n){var r=n(22),o=n(15);e.exports=function(e){return r(o(e))}},function(e,t,n){var r=n(23);e.exports=Object("z").propertyIsEnumerable(0)?Object:function(e){return"String"==r(e)?e.split(""):Object(e)}},function(e,t){var n={}.toString;e.exports=function(e){return n.call(e).slice(8,-1)}},function(e,t,n){var r=n(16),o=Math.min;e.exports=function(e){return e>0?o(r(e),9007199254740991):0}},function(e,t,n){var r=n(0),o=n(3),i=o["__core-js_shared__"]||(o["__core-js_shared__"]={});(e.exports=function(e,t){return i[e]||(i[e]=void 0!==t?t:{})})("versions",[]).push({version:r.version,mode:n(26)?"pure":"global",copyright:"© 2019 Denis Pushkarev (zloirock.ru)"})},function(e,t){e.exports=!0},function(e,t){var n=0,r=Math.random();e.exports=function(e){return"Symbol(".concat(void 0===e?"":e,")_",(++n+r).toString(36))}},function(e,t){e.exports="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(",")},function(e,t,n){"use strict";var r=n(53),o=n.n(r),i=n(31),s=n.n(i),a=n(75),c=n(77),u=n(79),l=n(81),f=n(83),d=n(33);t.a={name:"vue-json-pretty",components:{SimpleText:a.a,VueCheckbox:c.a,VueRadio:u.a,BracketsLeft:l.a,BracketsRight:f.a},props:{data:{},deep:{type:Number,default:1/0},showLength:{type:Boolean,default:!1},showDoubleQuotes:{type:Boolean,default:!0},path:{type:String,default:"root"},selectableType:{type:String,default:""},showSelectController:{type:Boolean,default:!1},showLine:{type:Boolean,default:!0},selectOnClickNode:{type:Boolean,default:!0},value:{type:[Array,String],default:function(){return""}},pathSelectable:{type:Function,default:function(){return!0}},highlightMouseoverNode:{type:Boolean,default:!1},highlightSelectedNode:{type:Boolean,default:!0},collapsedOnClickBrackets:{type:Boolean,default:!0},parentData:{},currentDeep:{type:Number,default:1},currentKey:[Number,String]},data:function(){return{visible:this.currentDeep<=this.deep,isMouseover:!1,currentCheckboxVal:!!Array.isArray(this.value)&&this.value.includes(this.path)}},computed:{model:{get:function(){var e="multiple"===this.selectableType?[]:"single"===this.selectableType?"":null;return this.value||e},set:function(e){this.$emit("input",e)}},lastKey:function(){if(Array.isArray(this.parentData))return this.parentData.length-1;if(this.isObject(this.parentData)){var e=s()(this.parentData);return e[e.length-1]}},notLastKey:function(){return this.currentKey!==this.lastKey},selectable:function(){return this.pathSelectable(this.path,this.data)&&(this.isMultiple||this.isSingle)},isMultiple:function(){return"multiple"===this.selectableType},isSingle:function(){return"single"===this.selectableType},isSelected:function(){return this.isMultiple?this.model.includes(this.path):!!this.isSingle&&this.model===this.path},propsError:function(){return!this.selectableType||this.selectOnClickNode||this.showSelectController?"":"When selectableType is not null, selectOnClickNode and showSelectController cannot be false at the same time, because this will cause the selection to fail."}},methods:{handleValueChange:function(e){var t=this;if(!this.isMultiple||"checkbox"!==e&&"tree"!==e){if(this.isSingle&&("radio"===e||"tree"===e)&&this.model!==this.path){var n=this.model,r=this.path;this.model=r,this.$emit("change",r,n)}}else{var i=this.model.findIndex(function(e){return e===t.path}),s=[].concat(o()(this.model));-1!==i?this.model.splice(i,1):this.model.push(this.path),"checkbox"!==e&&(this.currentCheckboxVal=!this.currentCheckboxVal),this.$emit("change",this.model,s)}},handleClick:function(e){e._uid&&e._uid!==this._uid||(e._uid=this._uid,this.$emit("click",this.path,this.data),this.selectable&&this.selectOnClickNode&&this.handleValueChange("tree"))},handleItemClick:function(e,t){this.$emit("click",e,t)},handleItemChange:function(e,t){this.selectable&&this.$emit("change",e,t)},handleMouseover:function(){this.highlightMouseoverNode&&(this.selectable||""===this.selectableType)&&(this.isMouseover=!0)},handleMouseout:function(){this.highlightMouseoverNode&&(this.selectable||""===this.selectableType)&&(this.isMouseover=!1)},isObject:function(e){return"object"===Object(d.a)(e)},keyFormatter:function(e){return this.showDoubleQuotes?'"'+e+'"':e}},errorCaptured:function(){return!1},watch:{deep:function(e){this.visible=this.currentDeep<=e},propsError:{handler:function(e){if(e)throw new Error("[vue-json-pretty] "+e)},immediate:!0}}}},function(e,t,n){var r=n(7).f,o=n(10),i=n(1)("toStringTag");e.exports=function(e,t,n){e&&!o(e=n?e:e.prototype,i)&&r(e,i,{configurable:!0,value:t})}},function(e,t,n){e.exports={default:n(72),__esModule:!0}},function(e,t,n){"use strict";var r=n(33);t.a={props:{showDoubleQuotes:Boolean,parentData:{},data:{},showComma:Boolean,currentKey:[Number,String]},computed:{dataType:function(){return Object(r.a)(this.data)},parentDataType:function(){return Object(r.a)(this.parentData)}},methods:{textFormatter:function(e){var t=e+"";return"string"===this.dataType&&(t='"'+t+'"'),this.showComma&&(t+=","),t}}}},function(e,t,n){"use strict";function r(e){return Object.prototype.toString.call(e).slice(8,-1).toLowerCase()}t.a=r},function(e,t,n){"use strict";t.a={props:{value:{type:Boolean,default:!1}},data:function(){return{focus:!1}},computed:{model:{get:function(){return this.value},set:function(e){this.$emit("input",e)}}}}},function(e,t,n){"use strict";t.a={props:{path:String,value:{type:String,default:""}},data:function(){return{focus:!1}},computed:{currentPath:function(){return this.path},model:{get:function(){return this.value},set:function(e){this.$emit("input",e)}}},methods:{change:function(){this.$emit("change",this.model)}}}},function(e,t,n){"use strict";var r=n(31),o=n.n(r),i=n(37);t.a={mixins:[i.a],props:{showLength:Boolean},methods:{closedBracketsGenerator:function(e){var t=Array.isArray(e)?"[...]":"{...}";return this.bracketsFormatter(t)},lengthGenerator:function(e){return" // "+(Array.isArray(e)?e.length+" items":o()(e).length+" keys")}}}},function(e,t,n){"use strict";t.a={props:{visible:{required:!0,type:Boolean},data:{required:!0},showComma:Boolean,collapsedOnClickBrackets:Boolean},computed:{dataVisible:{get:function(){return this.visible},set:function(e){this.collapsedOnClickBrackets&&this.$emit("update:visible",e)}}},methods:{toggleBrackets:function(){this.dataVisible=!this.dataVisible},bracketsFormatter:function(e){return this.showComma?e+",":e}}}},function(e,t,n){"use strict";var r=n(37);t.a={mixins:[r.a]}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(40),o=n.n(r),i=n(52),s=n(86);n.n(s);t.default=o()({},i.a,{version:"1.6.2"})},function(e,t,n){e.exports={default:n(41),__esModule:!0}},function(e,t,n){n(42),e.exports=n(0).Object.assign},function(e,t,n){var r=n(5);r(r.S+r.F,"Object",{assign:n(46)})},function(e,t){e.exports=function(e){if("function"!=typeof e)throw TypeError(e+" is not a function!");return e}},function(e,t,n){e.exports=!n(4)&&!n(9)(function(){return 7!=Object.defineProperty(n(20)("div"),"a",{get:function(){return 7}}).a})},function(e,t,n){var r=n(12);e.exports=function(e,t){if(!r(e))return e;var n,o;if(t&&"function"==typeof(n=e.toString)&&!r(o=n.call(e)))return o;if("function"==typeof(n=e.valueOf)&&!r(o=n.call(e)))return o;if(!t&&"function"==typeof(n=e.toString)&&!r(o=n.call(e)))return o;throw TypeError("Can't convert object to primitive value")}},function(e,t,n){"use strict";var r=n(4),o=n(14),i=n(50),s=n(51),a=n(11),c=n(22),u=Object.assign;e.exports=!u||n(9)(function(){var e={},t={},n=Symbol(),r="abcdefghijklmnopqrst";return e[n]=7,r.split("").forEach(function(e){t[e]=e}),7!=u({},e)[n]||Object.keys(u({},t)).join("")!=r})?function(e,t){for(var n=a(e),u=arguments.length,l=1,f=i.f,d=s.f;u>l;)for(var p,h=c(arguments[l++]),v=f?o(h).concat(f(h)):o(h),b=v.length,m=0;b>m;)p=v[m++],r&&!d.call(h,p)||(n[p]=h[p]);return n}:u},function(e,t,n){var r=n(10),o=n(21),i=n(48)(!1),s=n(17)("IE_PROTO");e.exports=function(e,t){var n,a=o(e),c=0,u=[];for(n in a)n!=s&&r(a,n)&&u.push(n);for(;t.length>c;)r(a,n=t[c++])&&(~i(u,n)||u.push(n));return u}},function(e,t,n){var r=n(21),o=n(24),i=n(49);e.exports=function(e){return function(t,n,s){var a,c=r(t),u=o(c.length),l=i(s,u);if(e&&n!=n){for(;u>l;)if((a=c[l++])!=a)return!0}else for(;u>l;l++)if((e||l in c)&&c[l]===n)return e||l||0;return!e&&-1}}},function(e,t,n){var r=n(16),o=Math.max,i=Math.min;e.exports=function(e,t){return e=r(e),e<0?o(e+t,0):i(e,t)}},function(e,t){t.f=Object.getOwnPropertySymbols},function(e,t){t.f={}.propertyIsEnumerable},function(e,t,n){"use strict";var r=n(29),o=n(85),i=n(2),s=i(r.a,o.a,!1,null,null,null);t.a=s.exports},function(e,t,n){"use strict";t.__esModule=!0;var r=n(54),o=function(e){return e&&e.__esModule?e:{default:e}}(r);t.default=function(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t=t.length?{value:void 0,done:!0}:(e=r(t,n),this._i+=e.length,{value:e,done:!1})})},function(e,t,n){var r=n(16),o=n(15);e.exports=function(e){return function(t,n){var i,s,a=String(o(t)),c=r(n),u=a.length;return c<0||c>=u?e?"":void 0:(i=a.charCodeAt(c),i<55296||i>56319||c+1===u||(s=a.charCodeAt(c+1))<56320||s>57343?e?a.charAt(c):i:e?a.slice(c,c+2):s-56320+(i-55296<<10)+65536)}}},function(e,t,n){"use strict";var r=n(26),o=n(5),i=n(59),s=n(6),a=n(18),c=n(60),u=n(30),l=n(64),f=n(1)("iterator"),d=!([].keys&&"next"in[].keys()),p=function(){return this};e.exports=function(e,t,n,h,v,b,m){c(n,t,h);var y,g,_,x=function(e){if(!d&&e in C)return C[e];switch(e){case"keys":case"values":return function(){return new n(this,e)}}return function(){return new n(this,e)}},k=t+" Iterator",j="values"==v,w=!1,C=e.prototype,O=C[f]||C["@@iterator"]||v&&C[v],S=O||x(v),A=v?j?x("entries"):S:void 0,M="Array"==t?C.entries||O:O;if(M&&(_=l(M.call(new e)))!==Object.prototype&&_.next&&(u(_,k,!0),r||"function"==typeof _[f]||s(_,f,p)),j&&O&&"values"!==O.name&&(w=!0,S=function(){return O.call(this)}),r&&!m||!d&&!w&&C[f]||s(C,f,S),a[t]=S,a[k]=p,v)if(y={values:j?S:x("values"),keys:b?S:x("keys"),entries:A},m)for(g in y)g in C||i(C,g,y[g]);else o(o.P+o.F*(d||w),t,y);return y}},function(e,t,n){e.exports=n(6)},function(e,t,n){"use strict";var r=n(61),o=n(13),i=n(30),s={};n(6)(s,n(1)("iterator"),function(){return this}),e.exports=function(e,t,n){e.prototype=r(s,{next:o(1,n)}),i(e,t+" Iterator")}},function(e,t,n){var r=n(8),o=n(62),i=n(28),s=n(17)("IE_PROTO"),a=function(){},c=function(){var e,t=n(20)("iframe"),r=i.length;for(t.style.display="none",n(63).appendChild(t),t.src="javascript:",e=t.contentWindow.document,e.open(),e.write("

Web SDK demo 消息接收demo

appkey

token

token2   切换方法使用

targetIds 逗号间隔,至少提供两个

    所有业务方法都必须在 链接成功 之后执行

当前登录用户 id:

链接状态:
发送消息:

接收消息:
历史消息:
会  话:

聊 天 室:
在线状态:
公众服务:

运行结果:

    ================================================ FILE: calllib-v2/README.md ================================================ ### 文档 开通音视频服务,请参考 [音视频开通指南](http://www.rongcloud.cn/docs/call.html#open) CallLib [开发指南](http://www.rongcloud.cn/docs/web_calllib.html#CallLibInit) ### 示例说明 1、HTTPS 站点或 localhost, 端口不限 2、配置 `private.html` 、`group.html` 页面中的用户信息 至少配置 2 个 用户 `private.html`: ```js var config = { // 融云开发者后台创建应用获取 http://developer.rongcloud.cn/ appKey: 'appkey', users: [{ // 用户 Id id: "XDov3Ln7p", /* 用户 Token Server API:http://www.rongcloud.cn/docs/server.html#user_get_token Server SDK:http://rongcloud.github.io/server-sdk-nodejs/docs/v1/user/user.html#register */ token: "48WQuGNh7065SB3WVJYnt6+YsUIoF3ojin3K2sssIg+8Ph5+QmAtoP6tdpZUyLdaH" }, { id: "Qlyvf1BdT", token: "KM7HOjWA2JPghgUJSvFUkcjRgiV1+NBKF4hsSSFA/joNtsdS1YEkeV2IKH+AY1qZPXnLINfK" }] }; ``` `group.html`: ```js var config = { // 融云开发者后台创建应用获取 http://developer.rongcloud.cn/ appKey: 'appkey', groupId: '群组 Id', members: [{ id: "XDov3Ln7p", /* 用户 Token Server API:http://www.rongcloud.cn/docs/server.html#user_get_token Server SDK:http://rongcloud.github.io/server-sdk-nodejs/docs/v1/user/user.html#register */ token: "48WQuGNojin3K277sfOlwuO8bLvftw4xaa/DrZEyJMsLZ9PPIg+8Ph5+QmAtoP6tdpZUyLdaH" }, { id: "Qlyvf1BdT", token: "KM7HOjWA2JPgasdfrUJSvFUkcjRgiV1+NBKF4hsSSFA/joNtsdS1YEkeV2IKH+AY1qZPXnLINfK" }, { id: "OasdgfrU", token: "KM7HfOasdgfrUJSvFUkcjRgiV1+KH+AY1qZPXnLINfK" }] }; ``` 3、访问地址: >一对一视频通话 用户 XDov3Ln7p: `https://域名/private.html?0` 用户 Qlyvf1BdT: `https://域名/private.html?1` >多人视频通话 用户 XDov3Ln7p: `https://域名/private.html?0` 用户 Qlyvf1BdT: `https://域名/private.html?1` 用户 OasdgfrU: `https://域名/private.html?2` ================================================ FILE: calllib-v2/demo.js ================================================ var RongCallLib = RongCallLib.init({ RongIMLib: RongIMLib }); var tools = { //仅支持类选择器和 Id 选择器 getDom: function(selector) { var selectorMap = { class: function(selector) { return document.getElementsByClassName(selector); }, id: function(selector) { return document.getElementById(selector); } }; var isClass = (selector.indexOf('.') == 0); var type = isClass ? 'class' : 'id'; var name = selector.slice(1); return selectorMap[type](name); }, toggleClass: function(node, name) { node.className = name; }, createDom: function(name, attrs) { attrs = attrs || {}; var node = document.createElement(name); for (var key in attrs) { node[key] = attrs[key]; } return node; }, noop: function(){} }; var ClassType = { MAX: 'rong-max-window', MIN: 'rong-min-window' }; var containerNode = tools.getDom('.rong-container')[0]; var clearWindow = function() { containerNode.innerHTML = ''; }; var setMaxWindow = function(minNode) { var maxNode = tools.getDom('.' + ClassType.MAX)[0]; if (maxNode) { tools.toggleClass(maxNode, ClassType.MIN); } tools.toggleClass(minNode, ClassType.MAX); }; var videoItem = { added: function(result) { var node = result.data; var win = tools.createDom('div', { className: ClassType.MIN }); var isLocal = result.isLocal; win.onclick = function(event) { setMaxWindow(event.currentTarget); }; win.appendChild(node); containerNode.appendChild(win); if (isLocal) { setMaxWindow(win); } }, removed: function(result) { var videoId = result.data; var video = tools.getDom('#' + videoId); if (video) { var win = video.parentNode; containerNode.removeChild(win); } }, leave: function() { clearWindow(); } }; // 注册视频节点监听 RongCallLib.videoWatch(function(result) { videoItem[result.type](result); }); var tBarCallVideo = tools.getDom('.rong-callvideo')[0]; var tBarCallAudio = tools.getDom('.rong-callaudio')[0]; var tBarAccept = tools.getDom('.rong-accept')[0]; var tBarHungup = tools.getDom('.rong-hungup')[0]; var tBarMute = tools.getDom('.rong-mute')[0]; var tBarUnMute = tools.getDom('.rong-unmute')[0]; var tBarDisableVideo = tools.getDom('.rong-disable-video')[0]; var tbarDisableAudio = tools.getDom('.rong-disable-audio')[0]; var show = function(node){ node.style.display = 'block'; }; var hide = function(node){ node.style.display = 'none'; }; var Buttons = { showCall: function(){ show(tBarCallVideo); show(tBarCallAudio); }, hideCall: function(){ hide(tBarCallVideo); hide(tBarCallAudio); }, showAccept: function(){ show(tBarAccept); }, hideAccept: function(){ hide(tBarAccept); }, showMute: function(){ show(tBarMute); hide(tBarUnMute); }, showUnmute: function(){ show(tBarUnMute); hide(tBarMute); }, showDisableVideo: function(){ show(tBarDisableVideo); hide(tbarDisableAudio); }, showDisableAudio: function(){ show(tbarDisableAudio); hide(tBarDisableVideo); }, showCaller: function(){ show(tBarHungup); show(tBarMute); show(tBarDisableVideo); }, showCallee: function(){ show(tBarAccept); show(tBarHungup); show(tBarMute); show(tBarDisableVideo); }, hideOperate: function(){ hide(tBarHungup); hide(tBarAccept); hide(tBarMute); hide(tBarUnMute); hide(tBarDisableVideo); hide(tbarDisableAudio); } }; var commandMap = { InviteMessage: function(){ Buttons.showCallee(); Buttons.hideCall(); } }; // 注册命令监听 RongCallLib.commandWatch(function(command) { var cmd = commandMap[command.messageType] || tools.noop; cmd(); console.log(command); }); var CallType = RongIMLib.VoIPMediaType; function callVideo() { var mediaType = CallType.MEDIA_VEDIO; call(mediaType); } function callAudio() { var mediaType = CallType.MEDIA_AUDIO; call(mediaType); } function call(mediaType) { Buttons.hideCall(); Buttons.showCaller(); params.mediaType = mediaType; RongCallLib.call(params, function(error) { console.log(error); }); } function hungup() { Buttons.showCall(); Buttons.hideOperate(); clearWindow(); RongCallLib.hungup(params, function(error, summary) { console.log(summary); }); } function acceptVideo() { Buttons.hideAccept(); params.mediaType = CallType.MEDIA_VEDIO; RongCallLib.accept(params); } function reject() { RongCallLib.reject(params); } function mute() { Buttons.showUnmute(); RongCallLib.mute(); } function unmute() { Buttons.showMute(); RongCallLib.unmute(); } function videoToAudio() { Buttons.showDisableAudio(); RongCallLib.videoToAudio(); } function audioToVideo() { Buttons.showDisableVideo(); RongCallLib.audioToVideo(); } ================================================ FILE: calllib-v2/group.html ================================================ CallLib 获取源码

    公告:此 Demo 即将废弃,后续不再维护,同时会推出新示例

    兼容说明:

    • 操作系统: macOS 10.13.3+ 、Win7+
    • 浏览器: Chrome 57+

    站点要求:

    • HTTPS 站点或 localhost, 端口不限
    ================================================ FILE: calllib-v2/init.js ================================================ "use strict"; ; (function(dependencies) { var global = dependencies.global; var RongIMLib = dependencies.RongIMLib; var RongIMClient = RongIMLib.RongIMClient; function ObserverList() { var checkIndexOutBound = function(index, bound) { return index > -1 && index < bound; }; this.observerList = []; this.add = function(observer, force) { force && (this.observerList.length = 0); this.observerList.push(observer); }; this.get = function(index) { if (checkIndexOutBound(index, this.observerList.length)) { return this.observerList[index]; } }; this.count = function() { return this.observerList.length; }; this.removeAt = function(index) { checkIndexOutBound(index, this.observerList.length) && this.observerList.splice(index, 1); }; this.remove = function(observer) { if (!observer) { this.observerList.length = 0; return; } observer = Object.prototype.toString.call(observer) == '[object Function]' ? [observer] : observer; for (var i = 0, len = this.observerList.length; i < len; i++) { if (this.observerList[i] === observer[i]) { this.removeAt(i); break; } } }; this.notify = function(val) { for (var i = 0, len = this.observerList.length; i < len; i++) { this.observerList[i](val); } }; this.indexOf = function(observer, startIndex) { var i = startIndex || 0, len = this.observerList.length; while (i < len) { if (this.observerList[i] === observer) { return i; } i++; } return -1; }; } var msgObserverList = new ObserverList(); var init = function(params, callbacks) { var appKey = params.appKey; var token = params.token; var navi = params.navi || ""; if (navi !== "") { //私有云 var config = { navi: navi } RongIMLib.RongIMClient.init(appKey, null, config); } else { //公有云 RongIMLib.RongIMClient.init(appKey); } var instance = RongIMClient.getInstance(); // 连接状态监听器 RongIMClient.setConnectionStatusListener({ onChanged: function(status) { switch (status) { case RongIMLib.ConnectionStatus.CONNECTED: callbacks.getInstance && callbacks.getInstance(instance); break; } } }); RongIMClient.setOnReceiveMessageListener({ // 接收到的消息 onReceived: function(message) { // 判断消息类型 msgObserverList.notify(message); } }); //开始链接 RongIMClient.connect(token, { onSuccess: function(userId) { callbacks.getCurrentUser && callbacks.getCurrentUser({ userId: userId }); console.log("链接成功"); }, onTokenIncorrect: function() { //console.log('token无效'); }, onError: function(errorCode) { console.log(errorCode); } }); } var watch = function(watcher) { msgObserverList.add(watcher); }; global.IMLib = { init: init, watch: watch }; })({ global: window, RongIMLib: RongIMLib }); ================================================ FILE: calllib-v2/private.html ================================================ CallLib

    公告:此 Demo 即将废弃,后续不再维护,同时会推出新示例

    兼容说明:

    • 操作系统: macOS 10.13.3+ 、Win7+
    • 浏览器: Chrome 57+

    站点要求:

    • HTTPS 站点或 localhost, 端口不限
    ================================================ FILE: calllib-v2/style/main.css ================================================ html,body{ width: 100%; height: 100%; margin: 0; position: absolute; z-index: -3; } .rong-container{ width: 100%; height: 100%; position: absolute; background-color: #333; z-index: -2; } .rong-max-window{ width: 100%; height: 100%; position: absolute; z-index: -1; } .rong-max-window video{ width: 100%; height: 100%; object-fit: fill; margin: 0 auto; display: block; } .rong-min-window{ float:left; margin-left: 30px; margin-top: 10px; width: 200px; height: 150px; border: 2px solid #FFF; cursor: pointer; } .rong-min-window video{ height: 100%; } .rong-toolbar{ position: absolute; bottom: 50px; left: 40%; } .rong-toolbar button{ border-radius: 47%; padding: 7px; margin-left: 20px; float: left; outline: none; cursor: pointer; background-repeat: no-repeat; border: none; font-family:"iconfont"; font-size:28px; font-style:normal; -webkit-font-smoothing: antialiased; -webkit-text-stroke-width: 0.2px; -moz-osx-font-smoothing: grayscale; display: none; } .rong-toolbar-operation{ display: none; } @font-face { font-family: 'iconfont'; /* project id 698950 */ src: url('//at.alicdn.com/t/font_698950_0qhfkfwxt2xfxbt9.eot'); src: url('//at.alicdn.com/t/font_698950_0qhfkfwxt2xfxbt9.eot?#iefix') format('embedded-opentype'), url('//at.alicdn.com/t/font_698950_0qhfkfwxt2xfxbt9.woff') format('woff'), url('//at.alicdn.com/t/font_698950_0qhfkfwxt2xfxbt9.ttf') format('truetype'), url('//at.alicdn.com/t/font_698950_0qhfkfwxt2xfxbt9.svg#iconfont') format('svg'); } button.rong-callvideo, button.rong-callaudio{ display: block; } .rong-callvideo:before{ content: "\e895"; } .rong-callaudio:before{ content: "\e608"; } button.rong-accept{ padding: 8px 4px 8px 7px; } .rong-accept:before{ content: "\e606"; color: green; } .rong-hungup:before{ content: "\e64e"; color: red; } .rong-mute:before{ content: "\e610"; } .rong-unmute:before{ content: "\e684"; } .rong-disable-video:before{ content: "\e6a1"; color: red; } .rong-disable-audio:before{ content: "\e895"; color: green; } .rong-warns{ width: 400px; height: 200px; position: absolute; right: 0; font-style: italic; border: 2px solid #FFF; color: #FFF; padding-left: 10px; box-sizing: border-box; } .rong-warns li{ list-style: none; line-height: 26px; } .rong-notice{ position: relative; left: 30%; color: #FFF; } ================================================ FILE: calllib-v2/user-media.html ================================================ user media

    ================================================ FILE: calllib-v3/README.md ================================================ # CallLib Demo `注意事项:` 1、需开通 [音视频 3.0 服务](./docs/ready.md) 2、旧版 calllib-v3 demo 请参考: [calllib-v3-old](https://github.com/rongcloud/websdk-demo/tree/11de9a6f7c3dc33d3211c89e39069c684718224e/calllib-v3) `启动流程:` * [前期准备](./docs/ready.md) * [Demo Server](./docs/server.md) * [Demo Web](./docs/web.md) * [演示示例](./docs/show.md) `相关文档:` Web CallLib 开发指南: [https://www.rongcloud.cn/docs/web_calllib.html](https://www.rongcloud.cn/docs/web_calllib.html) Web IM SDK 开发指南: [https://www.rongcloud.cn/docs/web.html](https://www.rongcloud.cn/docs/web.html) 融云知识库: [https://support.rongcloud.cn](https://support.rongcloud.cn) 融云开发者后台: [https://developer.rongcloud.cn](https://developer.rongcloud.cn) ================================================ FILE: calllib-v3/docs/ready.md ================================================ ## 前期准备 SealRTC Web 是基于 [RongCloud Web CallLib](https://www.rongcloud.cn/docs/web_calllib.html) 的音视频示例,通过此示例,可更好的帮助您集成、使用 Web CallLib SDK #### 创建应用 1、移步融云开发者后台: [https://developer.rongcloud.cn](https://developer.rongcloud.cn) 2、输入必要信息注册用户 ![](./images/register.png) 3、首次登录融云开发者后台 ![](./images/first-login.png) 4、创建应用 #### 开通服务 ![](./images/open.png) ================================================ FILE: calllib-v3/docs/server.md ================================================ ## CallLib Demo Server **Demo Server 作用** 1、为 CallLib Web Demo 提供获取 token 的接口 2、自动创建群组, 提供进行群组音视频的能力 : 运行 Web Demo 时, 必须运行 Demo Server, 并且 appKey 配置必须一致 **下载并安装 Node.js** Node.js 最低版本为 [10+](http://nodejs.cn/download/),如果机器已安装 Node ,可使用 [NVM](https://github.com/creationix/nvm) 切换版本 **快速启动** 1、下载 Demo Server 源码 [https://github.com/rongcloud/websdk-demo/tree/master/calllib-v3/server](https://github.com/rongcloud/websdk-demo/tree/master/calllib-v3/server) 2、进入 server 根目录执行 ```bash npm install ``` 3、修改配置文件 `setting.js` ```js module.exports = { appkey: 'appkey', // 融云应用 AppKey,可在融云开发者后台获取 secret: 'secret', // 融云应用 Secret,可在融云开发者后台获取 port: '9929' // 启动服务端口号, 默认 9929, 按需修改 }; ``` 4、启动服务 ``` npm run serve ``` 启动成功后, 控制台输出如下: ![](./images/serve.png) : 此 Server 仅供测试, 生产环境 App Server 需部署 https 协议 ================================================ FILE: calllib-v3/docs/show.md ================================================ ## 演示示例 #### CallLib Demo Web 浏览器兼容性说明 ![](./images/compatible.png) 1、在谷歌浏览器使用两个 Tab 页面分别打开 Web Demo: [http://localhost:3582/src/index.html](http://localhost:3582/src/index.html) ![](./images/login.png) 2、两个页面分别输入不同的用户 id(例如用户为 A、B), 点击登录, 进入通话界面 ![](./images/call.png) 3、用户 A 点击视频或音频按钮, 输入用户 B 的 id ![](./images/call-other.png) 4、用户 B 接收到 A 发送的音视频请求, 点击接听按钮 ![](./images/accept.png) 5、开始音视频通话 ![](./images/finished.png) ================================================ FILE: calllib-v3/docs/web.md ================================================ ## CallLib Demo Web 1、下载 Demo Web 源码 [https://github.com/rongcloud/websdk-demo/tree/master/calllib-v3/web](https://github.com/rongcloud/websdk-demo/tree/master/calllib-v3/web) 2、修改配置文件 `setting.js` ```js { appkey: 'appkey', // 融云应用 AppKey,可在融云开发者后台获取 server: 'http://localhost:9929' // Demo Server 地址 } ``` 3、启动 `index.html` 开始体验 : 浏览器限制协议必须是 `HTTPS` 或 `http://localhost:port` 才可使用摄像头、麦克风 所以需准备本地服务,若无本地服务,推荐: [Nginx](http://nginx.org/en/download.html) 或 [Node.js Puer](https://www.npmjs.com/package/puer) ![](./images/login.png)


    使用 Puer 启动服务器示例: 1、全局安装 puer ```bash npm install puer -g ``` 2、打开命令行 `Web Demo` 根目录 ```bash puer --port 3582 ``` 启动成功后出现如下界面,点击 `index.html` 开始体验 ![](./images/puer.png) ================================================ FILE: calllib-v3/private.html ================================================ 已废弃 CallLib

    抱歉, 为了大家更好的使用体验, 推荐参考最新版 Demo: CallLib Demo v3

    如依然需要使用旧版 Demo, 请访问: CallLib Demo v3 Old

    ================================================ FILE: calllib-v3/server/index.js ================================================ var app = require('express')(), setting = require('./setting'), http = require('http'), bodyParser = require("body-parser"), RongSDK = require('rongcloud-sdk')({ appkey: setting.appkey, secret: setting.secret }), port = setting.port; var Group = RongSDK.Group, User = RongSDK.User; var groupId, userList; // 允许跨域 var allowCors = function (req, res, next) { res.header('Access-Control-Allow-Origin', req.headers.origin); res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS'); res.header('Access-Control-Allow-Headers', 'Content-Type'); res.header('Access-Control-Allow-Credentials', 'true'); next(); }; app.use(allowCors); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.post('/login', function (req, res) { var params = req.params, body = req.body; var userId = body.userId; var user = { id: userId, name: userId, portrait: ' ' }; var token; User.register(user).then(function (result) { console.log('register result', result); token = result.token; var joinGroup, joinParams; if (!groupId) { groupId = +new Date() + ''; joinGroup = Group.create; joinParams = { id: groupId, name: groupId, members: [{ id: userId }] }; console.log('createParams', joinParams); } else { joinGroup = Group.join; joinParams = { id: groupId, member: { id: userId } }; console.log('joinParams', joinParams); } return joinGroup(joinParams); }).then(function (result) { return Group.get({ id: groupId }); }).then(function (result) { result.userId = userId; result.groupId = groupId; result.token = token; console.log('result', result); return res.send(result); }).catch(function (e) { console.error('error', e); }); }); app.post('/getMembers', function (req, res) { var params = req.params, body = req.body; Group.get({ id: body.groupId || groupId }).then(function (result) { return res.send(result); }); }); app.listen(port, function () { console.log( `CallLib Demo Server 启动成功 AppKey: ${setting.appkey} (Web 需一致) Server 地址: http://localhost:${port} 请将此 Server 地址填入 CallLib Demo Web 的 setting.js 文件 `); }); ================================================ FILE: calllib-v3/server/package.json ================================================ { "name": "server", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "serve": "node index.js" }, "author": "", "license": "ISC", "devDependencies": { "express": "^4.16.4", "rongcloud-sdk": "^3.0.1" } } ================================================ FILE: calllib-v3/server/setting.js ================================================ module.exports = { appkey: 'appkey', secret: 'secret', port: '9929' }; ================================================ FILE: calllib-v3/web/css/main.css ================================================ @charset "UTF-8"; /* 超出部分省略 */ .ellipsis, .rong-dialog-box .rong-dialog-user-list-content span { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; } html, body { margin: 0; padding: 0; width: 100%; height: 100%; background-color: #f5f5f5; } .rong-main { width: 100%; height: 100%; } .rong-box { width: 100%; height: 100%; } .rong-login-inner { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } .rong-login-inner p { text-align: center; font-size: 20px; } .rong-login-inner input { width: 280px; height: 44px; border: none; border-radius: 10px; display: block; box-sizing: border-box; margin: 17px; padding: 0 15px; font-size: 14px; outline: none; } .rong-login-inner input[type="text"] { border: 1px solid #ddd; } .rong-login-inner input[type="button"] { background-color: #0888ff; color: white; } .rong-info { position: absolute; top: 10px; left: 30px; text-align: left; color: white; z-index: 20; } .rong-info p { font-size: 15px; } .rong-call-box { background-color: #333; } .rong-call-box .rong-call-btns { position: absolute; bottom: 32px; left: 50%; transform: translateX(-50%); z-index: 32; } .rong-call-box .rong-call-btns button { width: 55px; height: 55px; margin: 0 8px; border-radius: 50%; background-image: url("../img/icons.svg"); border: none; outline: none; background-repeat: no-repeat; background-color: rgba(255, 255, 255, 0.87); transition: background-color 250ms cubic-bezier(0.4, 0, 0.2, 1) 0ms, box-shadow 250ms cubic-bezier(0.4, 0, 0.2, 1) 0ms, border 250ms cubic-bezier(0.4, 0, 0.2, 1) 0ms; box-shadow: 0px 3px 5px -1px rgba(0, 0, 0, 0.2), 0px 6px 10px 0px rgba(0, 0, 0, 0.14), 0px 1px 18px 0px rgba(0, 0, 0, 0.12); cursor: pointer; } .rong-call-box .rong-call-btns button:hover { background-color: rgba(255, 255, 255, 0.7); } .rong-call-box .rong-call-btns .rong-call-hungup { background-position: -66px 15px; background-color: #ef5350; } .rong-call-box .rong-call-btns button.rong-call-hungup:hover { background-color: #EF5360; } .rong-call-box .rong-call-btns .rong-call-accept { background-color: #008700; background-position: 14px 15px; } .rong-call-box .rong-call-btns .rong-call-accept:hover { background-color: #00a000; } .rong-call-box .rong-call-btns .rong-call-mute { background-position: 15px -154px; background-size: 112px; } .rong-call-box .rong-call-btns .rong-call-mute[closed] { background-position: -68px -154px; } .rong-call-box .rong-call-btns .rong-call-video { background-position: 12px -30px; background-size: 102px; } .rong-call-box .rong-call-btns .rong-call-video[closed] { background-position: -61px -30px; background-size: 102px; } .rong-call-box .rong-call-btns .rong-call-audio { background-position: 17px -93px; background-size: 111px; } .rong-call-box .rong-call-btns .rong-call-invite { background-position: 13px -310px; } .rong-type-box { color: white; position: absolute; left: 50%; transform: translateX(-50%); top: 20px; z-index: 30; } .rong-video-box { position: absolute; top: 0; left: 0; width: 100%; height: 100%; } .rong-video-box .rong-video-list { width: calc(100% - 200px); height: 150px; position: absolute; right: 0; z-index: 10; margin-top: 10px; } .rong-video-box .rong-video-list .rong-video-min { display: inline-block; width: 190px; height: 100%; position: relative; margin: 0 15px; border: 1px solid white; } .rong-video-box .rong-video-list video { position: absolute; width: 100%; height: 100%; background-color: black; } .rong-video-box .rong-video-max { width: 100%; height: 100%; position: absolute; } .rong-video-box .rong-video-max video { position: absolute; width: 100%; height: 100%; background-color: black; } .rong-video-box .rong-video-max[talktype="0"], .rong-video-box .rong-video-min[talktype="0"] { background-color: black; } .rong-video-box .rong-video-max[talktype="0"] video, .rong-video-box .rong-video-min[talktype="0"] video { display: none; } .rong-video-box .rong-video-max[talktype="0"]::before, .rong-video-box .rong-video-min[talktype="0"]::before { content: '摄像头已关闭'; color: white; font-size: 18px; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } .rong-video-box .rong-video-min[talktype="0"]::before { font-size: 15px; } .rong-dialog-box { position: fixed; width: 100%; height: 100%; left: 0; top: 0; opacity: 1; z-index: 500; color: #333; } .rong-dialog-box .rong-dialog-user-list { position: fixed; left: 50%; transform: translateX(-50%); top: 45px; background-color: #fefefe; border: 1px solid #e6e6e6; border-radius: 5px; box-shadow: 5px 5px 7px rgba(0, 0, 0, 0.1); padding: 20px 20px 12px 20px; z-index: 12; font-weight: 400; width: 252px; } .rong-dialog-box .rong-dialog-user-list h3 { margin: 0; font-size: 15px; } .rong-dialog-box .rong-dialog-user-list-content { margin: 15px 0; } .rong-dialog-box .rong-dialog-user-list-content .rong-dialog-user { display: inline-block; width: 50%; margin: 4px 0; line-height: 1; } .rong-dialog-box .rong-dialog-user-list-content i { display: inline-block; width: 12px; height: 12px; border: 1px solid #B2B2B2; background-color: white; margin-right: 1px; vertical-align: middle; background-image: url(../img/icons.svg); } .rong-dialog-box .rong-dialog-user-list-content i.rong-user-selected { background-color: transparent; background-position: 0px -115px; background-size: 54px; background-repeat: no-repeat; border: 1px solid black; } .rong-dialog-box .rong-dialog-user-list-content span { font-size: 12px; color: #585858; vertical-align: middle; max-width: 96px; display: inline-block; } .rong-dialog-box .rong-confirm-btns { text-align: right; } .rong-dialog-box .rong-confirm-btns button { padding: 0 8px; height: 23px; border: none; font-size: 12px; border-radius: 5px; margin-left: 3px; outline: none; } .rong-dialog-box .rong-confirm-btns .rong-confirm-ok[disabled] { opacity: 0.6; } .rong-dialog-box .rong-confirm-btns .rong-confirm-ok, .rong-dialog-box .rong-confirm-btns .rong-confirm-cancel { background-color: #f9f9f9; border: 1px solid #979797; } .rong-dialog-toast { position: fixed; text-align: center; top: 30px; left: 50%; transform: translateX(-50%); width: auto; padding: 12px 50px; background-color: #fefefe; border: 1px solid #e6e6e6; border-radius: 5px; box-shadow: 5px 5px 7px rgba(0, 0, 0, 0.1); padding: 7px 35px; z-index: 31; font-weight: 400; } .rong-dialog-toast .rong-dialog-toast-content { display: inline-block; font-size: 14px; vertical-align: middle; } ================================================ FILE: calllib-v3/web/css/main.scss ================================================ /* 超出部分省略 */ .ellipsis { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; } html, body { margin: 0; padding: 0; width: 100%; height: 100%; background-color: #f5f5f5; } .rong-main { width: 100%; height: 100%; } .rong-box { width: 100%; height: 100%; } .rong-login-inner { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); p { text-align: center; font-size: 20px; } input { width: 280px; height: 44px; border: none; border-radius: 10px; display: block; box-sizing: border-box; margin: 17px; padding: 0 15px; font-size: 14px; outline: none; } input[type="text"] { border: 1px solid #ddd; } input[type="button"] { background-color: #0888ff; color: white; } } .rong-info { position: absolute; top: 10px; left: 30px; text-align: left; color: white; z-index: 20; p { font-size: 15px; } } .rong-call-box { background-color: #333; .rong-call-btns { position: absolute; bottom: 32px; left: 50%; transform: translateX(-50%); z-index: 32; button { width: 55px; height: 55px; margin: 0 8px; border-radius: 50%; background-image: url('../img/icons.svg'); border: none; outline: none; background-repeat: no-repeat; background-color: rgba(255, 255, 255, 0.87); transition: background-color 250ms cubic-bezier(0.4, 0, 0.2, 1) 0ms,box-shadow 250ms cubic-bezier(0.4, 0, 0.2, 1) 0ms,border 250ms cubic-bezier(0.4, 0, 0.2, 1) 0ms; box-shadow: 0px 3px 5px -1px rgba(0,0,0,0.2), 0px 6px 10px 0px rgba(0,0,0,0.14), 0px 1px 18px 0px rgba(0,0,0,0.12); cursor: pointer; } button:hover { background-color: rgba(255, 255, 255, 0.7); } .rong-call-hungup { background-position: -66px 15px; background-color: #ef5350; } button.rong-call-hungup:hover { background-color: #EF5360; } .rong-call-accept { background-color: rgb(0, 135, 0); background-position: 14px 15px; } .rong-call-accept:hover { background-color: rgb(0, 160, 0); } .rong-call-mute { background-position: 15px -154px; background-size: 112px; } .rong-call-mute[closed] { background-position: -68px -154px; } .rong-call-video { background-position: 12px -30px; background-size: 102px; } .rong-call-video[closed] { background-position: -61px -30px; background-size: 102px; } .rong-call-audio { background-position: 17px -93px; background-size: 111px; } .rong-call-invite { background-position: 13px -310px; } } } .rong-type-box { color: white; position: absolute; left: 50%; transform: translateX(-50%); top: 20px; z-index: 30; } .rong-video-box { position: absolute; top: 0; left: 0; width: 100%; height: 100%; .rong-video-list { width: calc(100% - 200px); height: 150px; position: absolute; right: 0; z-index: 10; margin-top: 10px; .rong-video-min { display: inline-block; width: 190px; height: 100%; position: relative; margin: 0 15px; border: 1px solid white; } video { position: absolute; width: 100%; height: 100%; background-color: black; } } .rong-video-max { width: 100%; height: 100%; position: absolute; video { position: absolute; width: 100%; height: 100%; background-color: black; } } .rong-video-max[talktype="0"], .rong-video-min[talktype="0"] { background-color: black; video { display: none; } &::before { content: '摄像头已关闭'; color: white; font-size: 18px; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } } .rong-video-min[talktype="0"]::before { font-size: 15px; } } .rong-dialog-box { position: fixed; width: 100%; height: 100%; left: 0; top: 0; opacity: 1; z-index: 500; color: #333; .rong-dialog-user-list { position: fixed; left: 50%; transform: translateX(-50%); top: 45px; background-color: rgb(254, 254, 254); border: 1px solid rgb(230, 230, 230); border-radius: 5px; box-shadow: 5px 5px 7px rgba(0, 0, 0, 0.1); padding: 20px 20px 12px 20px; z-index: 12; font-weight: 400; width: 252px; h3 { margin: 0; font-size: 15px; } } .rong-dialog-user-list-content { margin: 15px 0; .rong-dialog-user { display: inline-block; width: 50%; margin: 4px 0; line-height: 1; } i { display: inline-block; width: 12px; height: 12px; border: 1px solid #B2B2B2; background-color: white; margin-right: 1px; vertical-align: middle; background-image: url(../img/icons.svg); } i.rong-user-selected { background-color: transparent; background-position: 0px -115px; background-size: 54px; background-repeat: no-repeat; border: 1px solid black; } span { font-size: 12px; color: rgb(88, 88, 88); vertical-align: middle; max-width: 96px; display: inline-block; @extend .ellipsis; } } .rong-confirm-btns { text-align: right; button { padding: 0 8px; height: 23px; border: none; font-size: 12px; border-radius: 5px; margin-left: 3px; outline: none; } .rong-confirm-ok[disabled] { opacity: 0.6; } .rong-confirm-ok, .rong-confirm-cancel { background-color: rgb(249, 249, 249); border: 1px solid rgb(151, 151, 151); } } } .rong-dialog-toast { position: fixed; text-align: center; top: 30px;; left: 50%; transform: translateX(-50%); width: auto; // top: 116px; padding: 12px 50px; background-color: rgb(254, 254, 254); border: 1px solid rgb(230, 230, 230); border-radius: 5px; box-shadow: 5px 5px 7px rgba(0, 0, 0, 0.1); padding: 7px 35px; z-index: 31; font-weight: 400; .rong-dialog-toast-content { display: inline-block; font-size: 14px; vertical-align: middle; } } ================================================ FILE: calllib-v3/web/index.html ================================================ Rong CallLib Demo
    ================================================ FILE: calllib-v3/web/js/call.js ================================================ (function (RongCall, dependencies) { /* 通话逻辑 */ var win = dependencies.win, Vue = win.Vue, RongIMLib = win.RongIMLib, RongCallLib = win.RongCallLib, utils = RongCall.utils; var toast = utils.toast, dialog = RongCall.dialog, ConversationType = RongIMLib.ConversationType, MediaType = RongIMLib.VoIPMediaType; // 通话阶段 var CallStep = { READY_TO_CALL: 1, // 准备拨打(最初状态) INVITED_TO_ANSWER: 2, // 被邀请接听, 其他人拨打, 己方选择接听或拒绝 CALLING: 3, // 拨打中 CALLS_ESTABLISH: 4 // 通话建立完成 }; var CallName = {}; CallName[MediaType.MEDIA_AUDIO] = '语音'; CallName[MediaType.MEDIA_VEDIO] = '视频'; // 将消息转化为调用 CallLib 需要参数 function messageToCallInfo(message) { return { conversationType: message.conversationType, targetId: message.targetId, mediaType: message.content.mediaType }; } // 获取挂断原因 function getHungupReason(reason, message) { var reasonPrompt; var senderUserId = message.senderUserId; switch(reason) { case 8: reasonPrompt = '其他设备已处理'; break; case 11: reasonPrompt = `${senderUserId} 已取消`; break; case 12: reasonPrompt = `${senderUserId} 已拒绝`; break; case 13: reasonPrompt = `${senderUserId} 已挂断`; break; case 14: reasonPrompt = `${senderUserId} 忙碌中`; break; case 15: reasonPrompt = `${senderUserId} 未接听`; break; default: reasonPrompt = '未知原因挂断'; } return reasonPrompt; } // 己方挂断后的提示 function getSummaryText(status, message) { var senderUserId = message.senderUserId; var text; switch(status) { case 1: text = '己方已取消'; break; case 2: text = '己方已拒绝'; break; case 3: text = '己方挂断'; break; case 4: text = `收到 ${senderUserId} 的音视频邀请, 但己方忙碌中, 不处理`; break; case 5: text = '己方未接听'; break; default: text = '未知原因'; } return text; } function mediaTypeToTalkType(mediaType) { return mediaType === MediaType.MEDIA_AUDIO ? 0 : 1; } var commandEvents = { // 监听其他人邀请自己 InviteMessage: function (message, context) { var conversationType = message.conversationType === ConversationType.PRIVATE ? '单聊' : '群聊'; toast(`${message.senderUserId} 邀请您进行${CallName[message.content.mediaType]}通话(${conversationType})`); context.callInfo = messageToCallInfo(message); context.callStep = CallStep.INVITED_TO_ANSWER; }, MemberModifyMessage: function (message, context) { if (message.content.inviteUserIds.indexOf(context.selfUserId) !== -1) { var conversationType = message.conversationType === ConversationType.PRIVATE ? '单聊' : '群聊'; toast(`${message.senderUserId} 邀请您进行${CallName[message.content.mediaType]}通话(${conversationType})`); context.callInfo = messageToCallInfo(message); context.callStep = CallStep.INVITED_TO_ANSWER; } }, HungupMessage: function (message) { var reason = getHungupReason(message.content.reason, message); toast(reason); }, MediaModifyMessage: function (message, context) { var senderUserId = message.senderUserId, mediaType = message.content.mediaType; context.userList.forEach(function (user) { if (user.userId === senderUserId) { user.talkType = mediaTypeToTalkType(mediaType); } }); }, SummaryMessage: function (message, context) { var status = message.content.status; var promptText = getSummaryText(status, message); toast(promptText); if (status === 5) { // 自己未接听, 回到初始状态 context.callStep = CallStep.READY_TO_CALL; } } }; var videoChangedEvents = { added: function (detail, context) { context.userList.push(detail); context.callStep = CallStep.CALLS_ESTABLISH; }, removed: function (detail, context) { context.userList = utils.removeArray(detail, context.userList, 'userId'); }, leave: function (detail, context) { context.userList = []; } }; function getMembers(currentUserList, selfUserId) { return utils.getMembers().then(function (members) { members = members.filter(function (user) { var currentUserIds = currentUserList.map(function (user) { return user.id || user.userId; }); return user.id !== selfUserId && currentUserIds.indexOf(user.id) === -1; }); return win.Promise.resolve(members); }); } function call(callParams) { var context = this; RongCallLib.call(callParams, function (error) { // 置为通话中状态 context.callStep = error ? context.callStep : CallStep.CALLING; }); context.callInfo = callParams; } function accept() { var context = this; var callInfo = context.callInfo; // callInfo 在监听到 InviteMessage 时赋值, 格式见 messageToCallInfo 方法 RongCallLib.accept(callInfo, function (error) { // 置为通话中状态 context.callStep = error ? context.callStep : CallStep.CALLING; }); } function invite() { var context = this; var callInfo = context.callInfo, inviteParams = { conversationType: ConversationType.GROUP, targetId: callInfo.targetId, inviteUserIds: [], mediaType: callInfo.mediaType }; getMembers(context.userList, context.selfUserId).then(function (members) { dialog.selectUser({ userList: members, confirmed: function (selectedUserList) { var selectedIds = selectedUserList.map(function (user) { return user.id; }); inviteParams.inviteUserIds = selectedIds; RongCallLib.invite(inviteParams); } }); }).catch(function () { toast('获取群组成员失败'); }); } function reject() { var context = this; var callInfo = context.callInfo; // callInfo 在监听到 InviteMessage 时赋值, 格式见 messageToCallInfo 方法 RongCallLib.reject(callInfo, function (error) { // 置为最初的准备拨打状态 context.callStep = error ? context.callStep : CallStep.READY_TO_CALL; }); } function hungup() { var context = this; var callInfo = context.callInfo; RongCallLib.hungup(callInfo, function (error) { // 置为最初的准备拨打状态 context.callStep = error ? context.callStep : CallStep.READY_TO_CALL; }); } function mute() { var isMuted = this.isMuted; var event = isMuted ? RongCallLib.unmute : RongCallLib.mute; event(); this.isMuted = !isMuted; } function setVideo() { var callInfo = this.callInfo, mediaType = callInfo.mediaType; var event = mediaType === MediaType.MEDIA_AUDIO ? RongCallLib.audioToVideo : RongCallLib.videoToAudio; event(); this.callInfo.mediaType = mediaType === MediaType.MEDIA_AUDIO ? MediaType.MEDIA_VEDIO : MediaType.MEDIA_AUDIO; } RongCall.call = Vue.component('call', { template: '#rong-template-call', data: function () { return { userList: [], callStep: CallStep.READY_TO_CALL, callType: ConversationType.PRIVATE, // 通话类型, 默认为单聊 /** * 通话信息. 给 callInfo 赋值的地方有: * 1. 发送 call 成功后, 存储当前通话信息 * 2. 接收到 InviteMessage 后, 存储通话信息 */ callInfo: {}, isMuted: false }; }, directives: { video: function (el, binding) { var user = binding.value; var video = user.data; el.appendChild(video); video.play(); } }, computed: { CallStep: function () { return CallStep; }, // 大窗口用户 maxUser: function () { var context = this; var maxUser; context.userList.forEach(function (user) { if (user.userId === context.selfUserId) { maxUser = user; } }); if (maxUser) { maxUser.talkType = mediaTypeToTalkType(context.callInfo.mediaType); } return maxUser; }, // 小窗口用户列表 minUserList: function () { var context = this, maxUser = context.maxUser || {}; return context.userList.filter(function (user) { return user.userId !== maxUser.userId; }); }, selfUserId: function () { return this.$route.params.userId; } }, methods: { /** * @param {boolean} isOnlyAudio 是否仅以音频发起 */ startCall: function (isOnlyAudio) { var mediaType = isOnlyAudio ? MediaType.MEDIA_AUDIO : MediaType.MEDIA_VEDIO; if (this.callType == ConversationType.GROUP) { this.startGroupCall(mediaType); } else { this.startPrivateCall(mediaType); } }, startPrivateCall: function (mediaType) { var targetId = win.prompt('请输入接收者 id:'); targetId && this.call({ conversationType: ConversationType.PRIVATE, targetId: targetId, inviteUserIds: [ targetId ], mediaType: mediaType }); }, startGroupCall: function (mediaType) { var context = this; var params = context.$route.params, groupId = params.groupId; var callParams = { conversationType: ConversationType.GROUP, targetId: groupId, inviteUserIds: [], mediaType: mediaType }; getMembers(context.userList, context.selfUserId).then(function (members) { dialog.selectUser({ userList: members, confirmed: function (selectedUserList) { var selectedIds = selectedUserList.map(function (user) { return user.id; }); callParams.inviteUserIds = selectedIds; context.call(callParams); } }); }).catch(function () { toast('获取群组成员失败'); }); }, call: call, accept: accept, invite: invite, reject: reject, hungup: hungup, mute: mute, setVideo: setVideo }, mounted: function () { var context = this; // 初始化 RongCallLib = RongCall.initCallLib(context.selfUserId); // 注册命令(消息)监听 RongCallLib.commandWatch(function (message) { var event = commandEvents[message.messageType]; event && event(message, context); console.log('received message', message); }); // 注册音视频节点监听 RongCallLib.videoWatch(function (result) { var event = videoChangedEvents[result.type]; event && event(result, context); console.log('video changed', result); }); } }); })(window.RongCall, { win: window }); ================================================ FILE: calllib-v3/web/js/common/init.js ================================================ (function (RongCall, dependencies) { var RongIMLib = dependencies.RongIMLib, RongIMClient = RongIMLib.RongIMClient, RongCallLib = dependencies.RongCallLib, RongRTC = dependencies.RongRTC; var RCRTC = dependencies.RCRTC; var RCRTCAdapter = dependencies.RCRTCAdapter; var win = dependencies.win; var imClient; /** * * @param {string} params.appkey 融云 appKey * @param {string} params.token 融云 token * @param {string} params.navi navi 地址, 公有云可不配置 */ var initIM = function (params) { var console = win.console; var appKey = params.appkey, token = params.token, navi = params.navi; if (navi) { // 私有云初始化 RongIMClient.init(appKey, null, { navi: navi // 私有云 navi 地址 }); } else { RongIMClient.init(appKey); } // 设置状态监听器 RongIMClient.setConnectionStatusListener({ onChanged: function (status) { console.log('status changed', status); // 此处若监听到网络错误, 需调用 disconnect 做重连处理 } }); // 设置消息监听器 RongIMClient.setOnReceiveMessageListener({ onReceived: function (message) { console.log('received message', message, 'is offLineMessage :', message.offLineMessage); } }); return new win.Promise(function (resolve, reject) { // 连接融云服务器 RongIMClient.connect(token, { onSuccess: function (userId) { resolve(userId) }, onTokenIncorrect: function () { reject(); }, onError: function (errorCode) { reject(errorCode); } }, ''); }); }; var initCallLib = function (userId) { RongIMClient.getInstance().install(RongCallLib.installer) const rtcClient = RongIMClient.getInstance().install(RCRTC.installer) var config = { RongIMLib: RongIMLib, RongRTC: rtcClient, currentUserId: userId, RongRTCAdapter: RCRTCAdapter }; // 初始化 CallLib RongCallLib = RongCallLib.init(config); return RongCallLib; }; RongCall = RongCall || {}; RongCall.initIM = initIM; RongCall.initCallLib = initCallLib; })(window.RongCall, { win: window, RongIMLib: window.RongIMLib, RongCallLib: window.RongCallLib, RongRTC: window.RongRTC, RCRTC: window.RCRTC, RCRTCAdapter: window.RCRTCAdapter }); ================================================ FILE: calllib-v3/web/js/common/utils.js ================================================ (function (dependencies) { var win = dependencies.win; var noop = function () {}; var Dom = { get: function (name) { var selector = null; try { selector = win.document.querySelector(name); } catch (e) { // console.error(e); } return selector; }, getById: function (id) { return win.document.getElementById(id); }, create: function (innerHTML) { var div = win.document.createElement('div'); div.innerHTML = innerHTML; return div.children[0]; } }; function tplEngine(temp, data, regexp) { var replaceAction = function (object) { return temp.replace(regexp || (/{([^}]+)}/g), function (match, name) { if (match.charAt(0) === '\\') return match.slice(1); return (object[name] !== undefined) ? object[name] : '{' + name + '}'; }); }; if (!(Object.prototype.toString.call(data) === '[object Array]')) data = [data]; var ret = []; for (var i = 0, j = data.length; i < j; i++) { ret.push(replaceAction(data[i])); } return ret.join(''); } /** * http 请求 * @param {object} option * @param {object} option.url 地址 * @param {object} option.queryStrings * @param {object} option.headers * @param {object} option.body * @param {object} option.isSync */ function ajax(option) { var xhr = new win.XMLHttpRequest(); var method = option.method || 'GET'; var url = option.url; var isSync = option.isSync; var queryStrings = option.queryStrings || {}; var tpl = '{key}={value}', strings = []; for (var key in queryStrings) { var value = queryStrings[key]; var str = tplEngine(tpl, { key: key, value: value }); strings.push(str); } queryStrings = strings.join('&'); var urlTpl = '{url}?{queryString}'; url = tplEngine(urlTpl, { url: url, queryString: queryStrings }); xhr.open(method, url, !isSync); var headers = option.headers || {}; for (var name in headers) { var header = headers[name]; xhr.setRequestHeader(name, header); } var isSuccess = function (xhr) { return /^(200|202|10000)$/.test(xhr.status); }; var success = option.success || noop; var fail = option.fail || noop; var onLoad = function () { var result = xhr.responseText; if (isSuccess(xhr)) { success(result); } else { fail(result); } } if ('onload' in xhr) { xhr.onload = onLoad; } else { xhr.onreadystatechange = function () { if (xhr.readyState === 4) { onLoad(); } }; } xhr.onerror = function (result) { fail(result); }; xhr.send(option.body); } /* 监听器(观察者模式) */ var EventEmitter = (function () { var events = {}; var on = function (name, event) { var currentEventList = events[name] || []; currentEventList.push(event); events[name] = currentEventList; }; var off = function (name, event) { if (!event) { delete events[name]; } else { var currentEventList = events[name]; currentEventList && currentEventList.forEach(function (currentEvent) { if (currentEvent === event) { var index = currentEventList.indexOf(currentEvent); currentEventList.splice(index, 1); } }); } }; var emit = function (name, data) { let currentEventList = events[name] || []; currentEventList.forEach(function (event) { event(data); }); }; var clear = function () { events = {}; }; return { on: on, off: off, emit: emit, clear: clear }; })(); function mountDialog(options) { var Dialog = win.Vue.extend(options); var instance = new Dialog({ el: document.createElement('div') }); var wrap = document.getElementsByTagName('body')[0]; wrap.appendChild(instance.$el); return instance; } function removeArray(value, array, removeKey) { var removeKeyList = array.map(function (value) { return value[removeKey]; }); var index = removeKeyList.indexOf(value[removeKey]); if (index !== -1) { array.splice(index, 1); } return array; } function DialogQueue() { this.isRunning = false; this.list = []; } DialogQueue.prototype.add = function (fn) { var context = this; var run = function () { context.isRunning = true; var index = context.list.indexOf(run); context.list.splice(index, 1); var runNext = function () { context.isRunning = false; context.run(); }; fn(runNext); }; context.list.push(run); }; DialogQueue.prototype.run = function () { if (this.list.length && !this.isRunning) { var run = this.list[0]; run && run(); } }; var toastQueue = new DialogQueue(); function toast(content) { var destroyTimeout = 3000; var fn = function (runNext) { win.RongCall.dialog.toast({ content: content, destroyTimeout: destroyTimeout, onDestoryed: runNext }); }; toastQueue.add(fn); toastQueue.run(); } function login(userId) { return new win.Promise(function (resolve, reject) { ajax({ url: win.RongCall.setting.server + '/login', method: 'POST', headers: { 'Content-Type': 'application/json' }, body: win.JSON.stringify({ userId: userId }), success: function (result) { resolve(win.JSON.parse(result)); }, fail: function (err) { reject(err); } }); }); } function getMembers(groupId) { return new win.Promise(function (resolve, reject) { ajax({ url: win.RongCall.setting.server + '/getMembers', method: 'POST', headers: { 'Content-Type': 'application/json' }, body: win.JSON.stringify({ groupId: groupId }), success: function (result) { resolve(win.JSON.parse(result).members); }, fail: function (err) { reject(err); } }); }); } win.RongCall = win.RongCall || {}; win.RongCall.utils = { Dom: Dom, console: win.console, ajax: ajax, EventEmitter: EventEmitter, mountDialog: mountDialog, removeArray: removeArray, toast: toast, login: login, getMembers: getMembers }; })({ win: window }); ================================================ FILE: calllib-v3/web/js/dialog.js ================================================ (function (RongCall) { /* 弹框 */ var utils = RongCall.utils; function removeSelf($el) { var parent = $el.parentElement; parent.removeChild($el); } /* 选择人员弹框 */ var selectUser = function (options) { options = options || {}; var userList = options.userList; userList = userList.map(function (user) { user.isSelected = false; return user; }); return utils.mountDialog({ name: 'rong-select-dialog', template: '#rong-template-dialog-users', data: function () { return { isShow: true, userList: userList }; }, computed: { hasSelectedUser: function () { var selectedUser = this.userList.filter(function (user) { return user.isSelected; }); return selectedUser.length; } }, methods: { selectUser: function (user) { user.isSelected = !user.isSelected; }, cancel: function () { this.isShow = false; options.canceled && options.canceled(); }, confirm: function () { var userList = this.userList; userList = userList.filter(function (user) { return user.isSelected; }); options.confirmed && options.confirmed(userList); this.isShow = false; } }, watch: { isShow: function (isShow) { !isShow && removeSelf(this.$el); } } }); }; /* 提示弹框 */ var toast = function (options) { options = options || {}; return utils.mountDialog({ name: 'rong-toast-dialog', template: '#rong-template-dialog-toast', data: function () { return { isShow: true, content: options.content }; }, watch: { isShow: function (isShow) { !isShow && removeSelf(this.$el); } }, mounted: function () { var context = this; setTimeout(function () { if (context.isShow) { context.isShow = false; options && options.onDestoryed(); } }, options.destroyTimeout || 5000); } }); }; RongCall.dialog = { selectUser: selectUser, toast: toast }; })(window.RongCall, { win: window }); ================================================ FILE: calllib-v3/web/js/login.js ================================================ (function (RongCall, dependencies) { /* 登录逻辑 */ var win = dependencies.win, Vue = win.Vue; var utils = RongCall.utils, setting = RongCall.setting; function toInfoPage(data) { var instance = RongCall.instance; instance.$router.push({ name: 'call', params: data }); } RongCall.login = Vue.component('login', { template: '#rong-template-login', data: function () { return { userId: '' }; }, methods: { login: function () { var userId = this.userId; var loginDetail utils.login(userId).then(function (result) { setting.token = result.token; loginDetail = result; return RongCall.initIM(setting); }).then(function () { RongCall.instance.auth = loginDetail; toInfoPage(loginDetail); }).catch(function () { win.alert('登录失败, 请检查 CallLib Demo Server 是否启动'); }); } } }); })(window.RongCall, { win: window }); ================================================ FILE: calllib-v3/web/js/main.js ================================================ (function (RongCall, dependencies) { 'use strict'; var Vue = dependencies.Vue, VueRouter = dependencies.VueRouter; function getRouter() { var router = new VueRouter({ routes: [ { path: '/login', name: 'login', component: RongCall.login }, { path: '/call', name: 'call', component: RongCall.call }, { path: '*', redirect: '/login' } ] }); router.beforeEach(function (to, from, next) { var ignoreAuthRoutes = ['login']; var toName = to.name; var instance = RongCall.instance || {}; var auth = instance.auth; if (ignoreAuthRoutes.indexOf(toName) === -1 && !auth) { return next({ name: 'login' }); } next(); }); return router; } function init(config) { RongCall.instance = new Vue({ el: config.el, router: getRouter() }); } RongCall.init = init; })(window.RongCall, { win: window, Vue: window.Vue, VueRouter: window.VueRouter }); ================================================ FILE: calllib-v3/web/lib/vue-2.6.7.js ================================================ /*! * Vue.js v2.6.7 * (c) 2014-2019 Evan You * Released under the MIT License. */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global = global || self, global.Vue = factory()); }(this, function () { 'use strict'; /* */ var emptyObject = Object.freeze({}); // These helpers produce better VM code in JS engines due to their // explicitness and function inlining. function isUndef (v) { return v === undefined || v === null } function isDef (v) { return v !== undefined && v !== null } function isTrue (v) { return v === true } function isFalse (v) { return v === false } /** * Check if value is primitive. */ function isPrimitive (value) { return ( typeof value === 'string' || typeof value === 'number' || // $flow-disable-line typeof value === 'symbol' || typeof value === 'boolean' ) } /** * Quick object check - this is primarily used to tell * Objects from primitive values when we know the value * is a JSON-compliant type. */ function isObject (obj) { return obj !== null && typeof obj === 'object' } /** * Get the raw type string of a value, e.g., [object Object]. */ var _toString = Object.prototype.toString; function toRawType (value) { return _toString.call(value).slice(8, -1) } /** * Strict object type check. Only returns true * for plain JavaScript objects. */ function isPlainObject (obj) { return _toString.call(obj) === '[object Object]' } function isRegExp (v) { return _toString.call(v) === '[object RegExp]' } /** * Check if val is a valid array index. */ function isValidArrayIndex (val) { var n = parseFloat(String(val)); return n >= 0 && Math.floor(n) === n && isFinite(val) } function isPromise (val) { return ( isDef(val) && typeof val.then === 'function' && typeof val.catch === 'function' ) } /** * Convert a value to a string that is actually rendered. */ function toString (val) { return val == null ? '' : Array.isArray(val) || (isPlainObject(val) && val.toString === _toString) ? JSON.stringify(val, null, 2) : String(val) } /** * Convert an input value to a number for persistence. * If the conversion fails, return original string. */ function toNumber (val) { var n = parseFloat(val); return isNaN(n) ? val : n } /** * Make a map and return a function for checking if a key * is in that map. */ function makeMap ( str, expectsLowerCase ) { var map = Object.create(null); var list = str.split(','); for (var i = 0; i < list.length; i++) { map[list[i]] = true; } return expectsLowerCase ? function (val) { return map[val.toLowerCase()]; } : function (val) { return map[val]; } } /** * Check if a tag is a built-in tag. */ var isBuiltInTag = makeMap('slot,component', true); /** * Check if an attribute is a reserved attribute. */ var isReservedAttribute = makeMap('key,ref,slot,slot-scope,is'); /** * Remove an item from an array. */ function remove (arr, item) { if (arr.length) { var index = arr.indexOf(item); if (index > -1) { return arr.splice(index, 1) } } } /** * Check whether an object has the property. */ var hasOwnProperty = Object.prototype.hasOwnProperty; function hasOwn (obj, key) { return hasOwnProperty.call(obj, key) } /** * Create a cached version of a pure function. */ function cached (fn) { var cache = Object.create(null); return (function cachedFn (str) { var hit = cache[str]; return hit || (cache[str] = fn(str)) }) } /** * Camelize a hyphen-delimited string. */ var camelizeRE = /-(\w)/g; var camelize = cached(function (str) { return str.replace(camelizeRE, function (_, c) { return c ? c.toUpperCase() : ''; }) }); /** * Capitalize a string. */ var capitalize = cached(function (str) { return str.charAt(0).toUpperCase() + str.slice(1) }); /** * Hyphenate a camelCase string. */ var hyphenateRE = /\B([A-Z])/g; var hyphenate = cached(function (str) { return str.replace(hyphenateRE, '-$1').toLowerCase() }); /** * Simple bind polyfill for environments that do not support it, * e.g., PhantomJS 1.x. Technically, we don't need this anymore * since native bind is now performant enough in most browsers. * But removing it would mean breaking code that was able to run in * PhantomJS 1.x, so this must be kept for backward compatibility. */ /* istanbul ignore next */ function polyfillBind (fn, ctx) { function boundFn (a) { var l = arguments.length; return l ? l > 1 ? fn.apply(ctx, arguments) : fn.call(ctx, a) : fn.call(ctx) } boundFn._length = fn.length; return boundFn } function nativeBind (fn, ctx) { return fn.bind(ctx) } var bind = Function.prototype.bind ? nativeBind : polyfillBind; /** * Convert an Array-like object to a real Array. */ function toArray (list, start) { start = start || 0; var i = list.length - start; var ret = new Array(i); while (i--) { ret[i] = list[i + start]; } return ret } /** * Mix properties into target object. */ function extend (to, _from) { for (var key in _from) { to[key] = _from[key]; } return to } /** * Merge an Array of Objects into a single Object. */ function toObject (arr) { var res = {}; for (var i = 0; i < arr.length; i++) { if (arr[i]) { extend(res, arr[i]); } } return res } /* eslint-disable no-unused-vars */ /** * Perform no operation. * Stubbing args to make Flow happy without leaving useless transpiled code * with ...rest (https://flow.org/blog/2017/05/07/Strict-Function-Call-Arity/). */ function noop (a, b, c) {} /** * Always return false. */ var no = function (a, b, c) { return false; }; /* eslint-enable no-unused-vars */ /** * Return the same value. */ var identity = function (_) { return _; }; /** * Generate a string containing static keys from compiler modules. */ function genStaticKeys (modules) { return modules.reduce(function (keys, m) { return keys.concat(m.staticKeys || []) }, []).join(',') } /** * Check if two values are loosely equal - that is, * if they are plain objects, do they have the same shape? */ function looseEqual (a, b) { if (a === b) { return true } var isObjectA = isObject(a); var isObjectB = isObject(b); if (isObjectA && isObjectB) { try { var isArrayA = Array.isArray(a); var isArrayB = Array.isArray(b); if (isArrayA && isArrayB) { return a.length === b.length && a.every(function (e, i) { return looseEqual(e, b[i]) }) } else if (a instanceof Date && b instanceof Date) { return a.getTime() === b.getTime() } else if (!isArrayA && !isArrayB) { var keysA = Object.keys(a); var keysB = Object.keys(b); return keysA.length === keysB.length && keysA.every(function (key) { return looseEqual(a[key], b[key]) }) } else { /* istanbul ignore next */ return false } } catch (e) { /* istanbul ignore next */ return false } } else if (!isObjectA && !isObjectB) { return String(a) === String(b) } else { return false } } /** * Return the first index at which a loosely equal value can be * found in the array (if value is a plain object, the array must * contain an object of the same shape), or -1 if it is not present. */ function looseIndexOf (arr, val) { for (var i = 0; i < arr.length; i++) { if (looseEqual(arr[i], val)) { return i } } return -1 } /** * Ensure a function is called only once. */ function once (fn) { var called = false; return function () { if (!called) { called = true; fn.apply(this, arguments); } } } var SSR_ATTR = 'data-server-rendered'; var ASSET_TYPES = [ 'component', 'directive', 'filter' ]; var LIFECYCLE_HOOKS = [ 'beforeCreate', 'created', 'beforeMount', 'mounted', 'beforeUpdate', 'updated', 'beforeDestroy', 'destroyed', 'activated', 'deactivated', 'errorCaptured', 'serverPrefetch' ]; /* */ var config = ({ /** * Option merge strategies (used in core/util/options) */ // $flow-disable-line optionMergeStrategies: Object.create(null), /** * Whether to suppress warnings. */ silent: false, /** * Show production mode tip message on boot? */ productionTip: "development" !== 'production', /** * Whether to enable devtools */ devtools: "development" !== 'production', /** * Whether to record perf */ performance: false, /** * Error handler for watcher errors */ errorHandler: null, /** * Warn handler for watcher warns */ warnHandler: null, /** * Ignore certain custom elements */ ignoredElements: [], /** * Custom user key aliases for v-on */ // $flow-disable-line keyCodes: Object.create(null), /** * Check if a tag is reserved so that it cannot be registered as a * component. This is platform-dependent and may be overwritten. */ isReservedTag: no, /** * Check if an attribute is reserved so that it cannot be used as a component * prop. This is platform-dependent and may be overwritten. */ isReservedAttr: no, /** * Check if a tag is an unknown element. * Platform-dependent. */ isUnknownElement: no, /** * Get the namespace of an element */ getTagNamespace: noop, /** * Parse the real tag name for the specific platform. */ parsePlatformTagName: identity, /** * Check if an attribute must be bound using property, e.g. value * Platform-dependent. */ mustUseProp: no, /** * Perform updates asynchronously. Intended to be used by Vue Test Utils * This will significantly reduce performance if set to false. */ async: true, /** * Exposed for legacy reasons */ _lifecycleHooks: LIFECYCLE_HOOKS }); /* */ /** * unicode letters used for parsing html tags, component names and property paths. * using https://www.w3.org/TR/html53/semantics-scripting.html#potentialcustomelementname * skipping \u10000-\uEFFFF due to it freezing up PhantomJS */ var unicodeLetters = 'a-zA-Z\u00B7\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u037D\u037F-\u1FFF\u200C-\u200D\u203F-\u2040\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD'; /** * Check if a string starts with $ or _ */ function isReserved (str) { var c = (str + '').charCodeAt(0); return c === 0x24 || c === 0x5F } /** * Define a property. */ function def (obj, key, val, enumerable) { Object.defineProperty(obj, key, { value: val, enumerable: !!enumerable, writable: true, configurable: true }); } /** * Parse simple path. */ var bailRE = new RegExp(("[^" + unicodeLetters + ".$_\\d]")); function parsePath (path) { if (bailRE.test(path)) { return } var segments = path.split('.'); return function (obj) { for (var i = 0; i < segments.length; i++) { if (!obj) { return } obj = obj[segments[i]]; } return obj } } /* */ // can we use __proto__? var hasProto = '__proto__' in {}; // Browser environment sniffing var inBrowser = typeof window !== 'undefined'; var inWeex = typeof WXEnvironment !== 'undefined' && !!WXEnvironment.platform; var weexPlatform = inWeex && WXEnvironment.platform.toLowerCase(); var UA = inBrowser && window.navigator.userAgent.toLowerCase(); var isIE = UA && /msie|trident/.test(UA); var isIE9 = UA && UA.indexOf('msie 9.0') > 0; var isEdge = UA && UA.indexOf('edge/') > 0; var isAndroid = (UA && UA.indexOf('android') > 0) || (weexPlatform === 'android'); var isIOS = (UA && /iphone|ipad|ipod|ios/.test(UA)) || (weexPlatform === 'ios'); var isChrome = UA && /chrome\/\d+/.test(UA) && !isEdge; var isPhantomJS = UA && /phantomjs/.test(UA); var isFF = UA && UA.match(/firefox\/(\d+)/); // Firefox has a "watch" function on Object.prototype... var nativeWatch = ({}).watch; var supportsPassive = false; if (inBrowser) { try { var opts = {}; Object.defineProperty(opts, 'passive', ({ get: function get () { /* istanbul ignore next */ supportsPassive = true; } })); // https://github.com/facebook/flow/issues/285 window.addEventListener('test-passive', null, opts); } catch (e) {} } // this needs to be lazy-evaled because vue may be required before // vue-server-renderer can set VUE_ENV var _isServer; var isServerRendering = function () { if (_isServer === undefined) { /* istanbul ignore if */ if (!inBrowser && !inWeex && typeof global !== 'undefined') { // detect presence of vue-server-renderer and avoid // Webpack shimming the process _isServer = global['process'] && global['process'].env.VUE_ENV === 'server'; } else { _isServer = false; } } return _isServer }; // detect devtools var devtools = inBrowser && window.__VUE_DEVTOOLS_GLOBAL_HOOK__; /* istanbul ignore next */ function isNative (Ctor) { return typeof Ctor === 'function' && /native code/.test(Ctor.toString()) } var hasSymbol = typeof Symbol !== 'undefined' && isNative(Symbol) && typeof Reflect !== 'undefined' && isNative(Reflect.ownKeys); var _Set; /* istanbul ignore if */ // $flow-disable-line if (typeof Set !== 'undefined' && isNative(Set)) { // use native Set when available. _Set = Set; } else { // a non-standard Set polyfill that only works with primitive keys. _Set = /*@__PURE__*/(function () { function Set () { this.set = Object.create(null); } Set.prototype.has = function has (key) { return this.set[key] === true }; Set.prototype.add = function add (key) { this.set[key] = true; }; Set.prototype.clear = function clear () { this.set = Object.create(null); }; return Set; }()); } /* */ var warn = noop; var tip = noop; var generateComponentTrace = (noop); // work around flow check var formatComponentName = (noop); { var hasConsole = typeof console !== 'undefined'; var classifyRE = /(?:^|[-_])(\w)/g; var classify = function (str) { return str .replace(classifyRE, function (c) { return c.toUpperCase(); }) .replace(/[-_]/g, ''); }; warn = function (msg, vm) { var trace = vm ? generateComponentTrace(vm) : ''; if (config.warnHandler) { config.warnHandler.call(null, msg, vm, trace); } else if (hasConsole && (!config.silent)) { console.error(("[Vue warn]: " + msg + trace)); } }; tip = function (msg, vm) { if (hasConsole && (!config.silent)) { console.warn("[Vue tip]: " + msg + ( vm ? generateComponentTrace(vm) : '' )); } }; formatComponentName = function (vm, includeFile) { if (vm.$root === vm) { return '' } var options = typeof vm === 'function' && vm.cid != null ? vm.options : vm._isVue ? vm.$options || vm.constructor.options : vm; var name = options.name || options._componentTag; var file = options.__file; if (!name && file) { var match = file.match(/([^/\\]+)\.vue$/); name = match && match[1]; } return ( (name ? ("<" + (classify(name)) + ">") : "") + (file && includeFile !== false ? (" at " + file) : '') ) }; var repeat = function (str, n) { var res = ''; while (n) { if (n % 2 === 1) { res += str; } if (n > 1) { str += str; } n >>= 1; } return res }; generateComponentTrace = function (vm) { if (vm._isVue && vm.$parent) { var tree = []; var currentRecursiveSequence = 0; while (vm) { if (tree.length > 0) { var last = tree[tree.length - 1]; if (last.constructor === vm.constructor) { currentRecursiveSequence++; vm = vm.$parent; continue } else if (currentRecursiveSequence > 0) { tree[tree.length - 1] = [last, currentRecursiveSequence]; currentRecursiveSequence = 0; } } tree.push(vm); vm = vm.$parent; } return '\n\nfound in\n\n' + tree .map(function (vm, i) { return ("" + (i === 0 ? '---> ' : repeat(' ', 5 + i * 2)) + (Array.isArray(vm) ? ((formatComponentName(vm[0])) + "... (" + (vm[1]) + " recursive calls)") : formatComponentName(vm))); }) .join('\n') } else { return ("\n\n(found in " + (formatComponentName(vm)) + ")") } }; } /* */ var uid = 0; /** * A dep is an observable that can have multiple * directives subscribing to it. */ var Dep = function Dep () { this.id = uid++; this.subs = []; }; Dep.prototype.addSub = function addSub (sub) { this.subs.push(sub); }; Dep.prototype.removeSub = function removeSub (sub) { remove(this.subs, sub); }; Dep.prototype.depend = function depend () { if (Dep.target) { Dep.target.addDep(this); } }; Dep.prototype.notify = function notify () { // stabilize the subscriber list first var subs = this.subs.slice(); if (!config.async) { // subs aren't sorted in scheduler if not running async // we need to sort them now to make sure they fire in correct // order subs.sort(function (a, b) { return a.id - b.id; }); } for (var i = 0, l = subs.length; i < l; i++) { subs[i].update(); } }; // The current target watcher being evaluated. // This is globally unique because only one watcher // can be evaluated at a time. Dep.target = null; var targetStack = []; function pushTarget (target) { targetStack.push(target); Dep.target = target; } function popTarget () { targetStack.pop(); Dep.target = targetStack[targetStack.length - 1]; } /* */ var VNode = function VNode ( tag, data, children, text, elm, context, componentOptions, asyncFactory ) { this.tag = tag; this.data = data; this.children = children; this.text = text; this.elm = elm; this.ns = undefined; this.context = context; this.fnContext = undefined; this.fnOptions = undefined; this.fnScopeId = undefined; this.key = data && data.key; this.componentOptions = componentOptions; this.componentInstance = undefined; this.parent = undefined; this.raw = false; this.isStatic = false; this.isRootInsert = true; this.isComment = false; this.isCloned = false; this.isOnce = false; this.asyncFactory = asyncFactory; this.asyncMeta = undefined; this.isAsyncPlaceholder = false; }; var prototypeAccessors = { child: { configurable: true } }; // DEPRECATED: alias for componentInstance for backwards compat. /* istanbul ignore next */ prototypeAccessors.child.get = function () { return this.componentInstance }; Object.defineProperties( VNode.prototype, prototypeAccessors ); var createEmptyVNode = function (text) { if ( text === void 0 ) text = ''; var node = new VNode(); node.text = text; node.isComment = true; return node }; function createTextVNode (val) { return new VNode(undefined, undefined, undefined, String(val)) } // optimized shallow clone // used for static nodes and slot nodes because they may be reused across // multiple renders, cloning them avoids errors when DOM manipulations rely // on their elm reference. function cloneVNode (vnode) { var cloned = new VNode( vnode.tag, vnode.data, // #7975 // clone children array to avoid mutating original in case of cloning // a child. vnode.children && vnode.children.slice(), vnode.text, vnode.elm, vnode.context, vnode.componentOptions, vnode.asyncFactory ); cloned.ns = vnode.ns; cloned.isStatic = vnode.isStatic; cloned.key = vnode.key; cloned.isComment = vnode.isComment; cloned.fnContext = vnode.fnContext; cloned.fnOptions = vnode.fnOptions; cloned.fnScopeId = vnode.fnScopeId; cloned.asyncMeta = vnode.asyncMeta; cloned.isCloned = true; return cloned } /* * not type checking this file because flow doesn't play well with * dynamically accessing methods on Array prototype */ var arrayProto = Array.prototype; var arrayMethods = Object.create(arrayProto); var methodsToPatch = [ 'push', 'pop', 'shift', 'unshift', 'splice', 'sort', 'reverse' ]; /** * Intercept mutating methods and emit events */ methodsToPatch.forEach(function (method) { // cache original method var original = arrayProto[method]; def(arrayMethods, method, function mutator () { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; var result = original.apply(this, args); var ob = this.__ob__; var inserted; switch (method) { case 'push': case 'unshift': inserted = args; break case 'splice': inserted = args.slice(2); break } if (inserted) { ob.observeArray(inserted); } // notify change ob.dep.notify(); return result }); }); /* */ var arrayKeys = Object.getOwnPropertyNames(arrayMethods); /** * In some cases we may want to disable observation inside a component's * update computation. */ var shouldObserve = true; function toggleObserving (value) { shouldObserve = value; } /** * Observer class that is attached to each observed * object. Once attached, the observer converts the target * object's property keys into getter/setters that * collect dependencies and dispatch updates. */ var Observer = function Observer (value) { this.value = value; this.dep = new Dep(); this.vmCount = 0; def(value, '__ob__', this); if (Array.isArray(value)) { if (hasProto) { protoAugment(value, arrayMethods); } else { copyAugment(value, arrayMethods, arrayKeys); } this.observeArray(value); } else { this.walk(value); } }; /** * Walk through all properties and convert them into * getter/setters. This method should only be called when * value type is Object. */ Observer.prototype.walk = function walk (obj) { var keys = Object.keys(obj); for (var i = 0; i < keys.length; i++) { defineReactive$$1(obj, keys[i]); } }; /** * Observe a list of Array items. */ Observer.prototype.observeArray = function observeArray (items) { for (var i = 0, l = items.length; i < l; i++) { observe(items[i]); } }; // helpers /** * Augment a target Object or Array by intercepting * the prototype chain using __proto__ */ function protoAugment (target, src) { /* eslint-disable no-proto */ target.__proto__ = src; /* eslint-enable no-proto */ } /** * Augment a target Object or Array by defining * hidden properties. */ /* istanbul ignore next */ function copyAugment (target, src, keys) { for (var i = 0, l = keys.length; i < l; i++) { var key = keys[i]; def(target, key, src[key]); } } /** * Attempt to create an observer instance for a value, * returns the new observer if successfully observed, * or the existing observer if the value already has one. */ function observe (value, asRootData) { if (!isObject(value) || value instanceof VNode) { return } var ob; if (hasOwn(value, '__ob__') && value.__ob__ instanceof Observer) { ob = value.__ob__; } else if ( shouldObserve && !isServerRendering() && (Array.isArray(value) || isPlainObject(value)) && Object.isExtensible(value) && !value._isVue ) { ob = new Observer(value); } if (asRootData && ob) { ob.vmCount++; } return ob } /** * Define a reactive property on an Object. */ function defineReactive$$1 ( obj, key, val, customSetter, shallow ) { var dep = new Dep(); var property = Object.getOwnPropertyDescriptor(obj, key); if (property && property.configurable === false) { return } // cater for pre-defined getter/setters var getter = property && property.get; var setter = property && property.set; if ((!getter || setter) && arguments.length === 2) { val = obj[key]; } var childOb = !shallow && observe(val); Object.defineProperty(obj, key, { enumerable: true, configurable: true, get: function reactiveGetter () { var value = getter ? getter.call(obj) : val; if (Dep.target) { dep.depend(); if (childOb) { childOb.dep.depend(); if (Array.isArray(value)) { dependArray(value); } } } return value }, set: function reactiveSetter (newVal) { var value = getter ? getter.call(obj) : val; /* eslint-disable no-self-compare */ if (newVal === value || (newVal !== newVal && value !== value)) { return } /* eslint-enable no-self-compare */ if (customSetter) { customSetter(); } // #7981: for accessor properties without setter if (getter && !setter) { return } if (setter) { setter.call(obj, newVal); } else { val = newVal; } childOb = !shallow && observe(newVal); dep.notify(); } }); } /** * Set a property on an object. Adds the new property and * triggers change notification if the property doesn't * already exist. */ function set (target, key, val) { if (isUndef(target) || isPrimitive(target) ) { warn(("Cannot set reactive property on undefined, null, or primitive value: " + ((target)))); } if (Array.isArray(target) && isValidArrayIndex(key)) { target.length = Math.max(target.length, key); target.splice(key, 1, val); return val } if (key in target && !(key in Object.prototype)) { target[key] = val; return val } var ob = (target).__ob__; if (target._isVue || (ob && ob.vmCount)) { warn( 'Avoid adding reactive properties to a Vue instance or its root $data ' + 'at runtime - declare it upfront in the data option.' ); return val } if (!ob) { target[key] = val; return val } defineReactive$$1(ob.value, key, val); ob.dep.notify(); return val } /** * Delete a property and trigger change if necessary. */ function del (target, key) { if (isUndef(target) || isPrimitive(target) ) { warn(("Cannot delete reactive property on undefined, null, or primitive value: " + ((target)))); } if (Array.isArray(target) && isValidArrayIndex(key)) { target.splice(key, 1); return } var ob = (target).__ob__; if (target._isVue || (ob && ob.vmCount)) { warn( 'Avoid deleting properties on a Vue instance or its root $data ' + '- just set it to null.' ); return } if (!hasOwn(target, key)) { return } delete target[key]; if (!ob) { return } ob.dep.notify(); } /** * Collect dependencies on array elements when the array is touched, since * we cannot intercept array element access like property getters. */ function dependArray (value) { for (var e = (void 0), i = 0, l = value.length; i < l; i++) { e = value[i]; e && e.__ob__ && e.__ob__.dep.depend(); if (Array.isArray(e)) { dependArray(e); } } } /* */ /** * Option overwriting strategies are functions that handle * how to merge a parent option value and a child option * value into the final value. */ var strats = config.optionMergeStrategies; /** * Options with restrictions */ { strats.el = strats.propsData = function (parent, child, vm, key) { if (!vm) { warn( "option \"" + key + "\" can only be used during instance " + 'creation with the `new` keyword.' ); } return defaultStrat(parent, child) }; } /** * Helper that recursively merges two data objects together. */ function mergeData (to, from) { if (!from) { return to } var key, toVal, fromVal; var keys = hasSymbol ? Reflect.ownKeys(from) : Object.keys(from); for (var i = 0; i < keys.length; i++) { key = keys[i]; // in case the object is already observed... if (key === '__ob__') { continue } toVal = to[key]; fromVal = from[key]; if (!hasOwn(to, key)) { set(to, key, fromVal); } else if ( toVal !== fromVal && isPlainObject(toVal) && isPlainObject(fromVal) ) { mergeData(toVal, fromVal); } } return to } /** * Data */ function mergeDataOrFn ( parentVal, childVal, vm ) { if (!vm) { // in a Vue.extend merge, both should be functions if (!childVal) { return parentVal } if (!parentVal) { return childVal } // when parentVal & childVal are both present, // we need to return a function that returns the // merged result of both functions... no need to // check if parentVal is a function here because // it has to be a function to pass previous merges. return function mergedDataFn () { return mergeData( typeof childVal === 'function' ? childVal.call(this, this) : childVal, typeof parentVal === 'function' ? parentVal.call(this, this) : parentVal ) } } else { return function mergedInstanceDataFn () { // instance merge var instanceData = typeof childVal === 'function' ? childVal.call(vm, vm) : childVal; var defaultData = typeof parentVal === 'function' ? parentVal.call(vm, vm) : parentVal; if (instanceData) { return mergeData(instanceData, defaultData) } else { return defaultData } } } } strats.data = function ( parentVal, childVal, vm ) { if (!vm) { if (childVal && typeof childVal !== 'function') { warn( 'The "data" option should be a function ' + 'that returns a per-instance value in component ' + 'definitions.', vm ); return parentVal } return mergeDataOrFn(parentVal, childVal) } return mergeDataOrFn(parentVal, childVal, vm) }; /** * Hooks and props are merged as arrays. */ function mergeHook ( parentVal, childVal ) { var res = childVal ? parentVal ? parentVal.concat(childVal) : Array.isArray(childVal) ? childVal : [childVal] : parentVal; return res ? dedupeHooks(res) : res } function dedupeHooks (hooks) { var res = []; for (var i = 0; i < hooks.length; i++) { if (res.indexOf(hooks[i]) === -1) { res.push(hooks[i]); } } return res } LIFECYCLE_HOOKS.forEach(function (hook) { strats[hook] = mergeHook; }); /** * Assets * * When a vm is present (instance creation), we need to do * a three-way merge between constructor options, instance * options and parent options. */ function mergeAssets ( parentVal, childVal, vm, key ) { var res = Object.create(parentVal || null); if (childVal) { assertObjectType(key, childVal, vm); return extend(res, childVal) } else { return res } } ASSET_TYPES.forEach(function (type) { strats[type + 's'] = mergeAssets; }); /** * Watchers. * * Watchers hashes should not overwrite one * another, so we merge them as arrays. */ strats.watch = function ( parentVal, childVal, vm, key ) { // work around Firefox's Object.prototype.watch... if (parentVal === nativeWatch) { parentVal = undefined; } if (childVal === nativeWatch) { childVal = undefined; } /* istanbul ignore if */ if (!childVal) { return Object.create(parentVal || null) } { assertObjectType(key, childVal, vm); } if (!parentVal) { return childVal } var ret = {}; extend(ret, parentVal); for (var key$1 in childVal) { var parent = ret[key$1]; var child = childVal[key$1]; if (parent && !Array.isArray(parent)) { parent = [parent]; } ret[key$1] = parent ? parent.concat(child) : Array.isArray(child) ? child : [child]; } return ret }; /** * Other object hashes. */ strats.props = strats.methods = strats.inject = strats.computed = function ( parentVal, childVal, vm, key ) { if (childVal && "development" !== 'production') { assertObjectType(key, childVal, vm); } if (!parentVal) { return childVal } var ret = Object.create(null); extend(ret, parentVal); if (childVal) { extend(ret, childVal); } return ret }; strats.provide = mergeDataOrFn; /** * Default strategy. */ var defaultStrat = function (parentVal, childVal) { return childVal === undefined ? parentVal : childVal }; /** * Validate component names */ function checkComponents (options) { for (var key in options.components) { validateComponentName(key); } } function validateComponentName (name) { if (!new RegExp(("^[a-zA-Z][\\-\\.0-9_" + unicodeLetters + "]*$")).test(name)) { warn( 'Invalid component name: "' + name + '". Component names ' + 'should conform to valid custom element name in html5 specification.' ); } if (isBuiltInTag(name) || config.isReservedTag(name)) { warn( 'Do not use built-in or reserved HTML elements as component ' + 'id: ' + name ); } } /** * Ensure all props option syntax are normalized into the * Object-based format. */ function normalizeProps (options, vm) { var props = options.props; if (!props) { return } var res = {}; var i, val, name; if (Array.isArray(props)) { i = props.length; while (i--) { val = props[i]; if (typeof val === 'string') { name = camelize(val); res[name] = { type: null }; } else { warn('props must be strings when using array syntax.'); } } } else if (isPlainObject(props)) { for (var key in props) { val = props[key]; name = camelize(key); res[name] = isPlainObject(val) ? val : { type: val }; } } else { warn( "Invalid value for option \"props\": expected an Array or an Object, " + "but got " + (toRawType(props)) + ".", vm ); } options.props = res; } /** * Normalize all injections into Object-based format */ function normalizeInject (options, vm) { var inject = options.inject; if (!inject) { return } var normalized = options.inject = {}; if (Array.isArray(inject)) { for (var i = 0; i < inject.length; i++) { normalized[inject[i]] = { from: inject[i] }; } } else if (isPlainObject(inject)) { for (var key in inject) { var val = inject[key]; normalized[key] = isPlainObject(val) ? extend({ from: key }, val) : { from: val }; } } else { warn( "Invalid value for option \"inject\": expected an Array or an Object, " + "but got " + (toRawType(inject)) + ".", vm ); } } /** * Normalize raw function directives into object format. */ function normalizeDirectives (options) { var dirs = options.directives; if (dirs) { for (var key in dirs) { var def$$1 = dirs[key]; if (typeof def$$1 === 'function') { dirs[key] = { bind: def$$1, update: def$$1 }; } } } } function assertObjectType (name, value, vm) { if (!isPlainObject(value)) { warn( "Invalid value for option \"" + name + "\": expected an Object, " + "but got " + (toRawType(value)) + ".", vm ); } } /** * Merge two option objects into a new one. * Core utility used in both instantiation and inheritance. */ function mergeOptions ( parent, child, vm ) { { checkComponents(child); } if (typeof child === 'function') { child = child.options; } normalizeProps(child, vm); normalizeInject(child, vm); normalizeDirectives(child); // Apply extends and mixins on the child options, // but only if it is a raw options object that isn't // the result of another mergeOptions call. // Only merged options has the _base property. if (!child._base) { if (child.extends) { parent = mergeOptions(parent, child.extends, vm); } if (child.mixins) { for (var i = 0, l = child.mixins.length; i < l; i++) { parent = mergeOptions(parent, child.mixins[i], vm); } } } var options = {}; var key; for (key in parent) { mergeField(key); } for (key in child) { if (!hasOwn(parent, key)) { mergeField(key); } } function mergeField (key) { var strat = strats[key] || defaultStrat; options[key] = strat(parent[key], child[key], vm, key); } return options } /** * Resolve an asset. * This function is used because child instances need access * to assets defined in its ancestor chain. */ function resolveAsset ( options, type, id, warnMissing ) { /* istanbul ignore if */ if (typeof id !== 'string') { return } var assets = options[type]; // check local registration variations first if (hasOwn(assets, id)) { return assets[id] } var camelizedId = camelize(id); if (hasOwn(assets, camelizedId)) { return assets[camelizedId] } var PascalCaseId = capitalize(camelizedId); if (hasOwn(assets, PascalCaseId)) { return assets[PascalCaseId] } // fallback to prototype chain var res = assets[id] || assets[camelizedId] || assets[PascalCaseId]; if (warnMissing && !res) { warn( 'Failed to resolve ' + type.slice(0, -1) + ': ' + id, options ); } return res } /* */ function validateProp ( key, propOptions, propsData, vm ) { var prop = propOptions[key]; var absent = !hasOwn(propsData, key); var value = propsData[key]; // boolean casting var booleanIndex = getTypeIndex(Boolean, prop.type); if (booleanIndex > -1) { if (absent && !hasOwn(prop, 'default')) { value = false; } else if (value === '' || value === hyphenate(key)) { // only cast empty string / same name to boolean if // boolean has higher priority var stringIndex = getTypeIndex(String, prop.type); if (stringIndex < 0 || booleanIndex < stringIndex) { value = true; } } } // check default value if (value === undefined) { value = getPropDefaultValue(vm, prop, key); // since the default value is a fresh copy, // make sure to observe it. var prevShouldObserve = shouldObserve; toggleObserving(true); observe(value); toggleObserving(prevShouldObserve); } { assertProp(prop, key, value, vm, absent); } return value } /** * Get the default value of a prop. */ function getPropDefaultValue (vm, prop, key) { // no default, return undefined if (!hasOwn(prop, 'default')) { return undefined } var def = prop.default; // warn against non-factory defaults for Object & Array if (isObject(def)) { warn( 'Invalid default value for prop "' + key + '": ' + 'Props with type Object/Array must use a factory function ' + 'to return the default value.', vm ); } // the raw prop value was also undefined from previous render, // return previous default value to avoid unnecessary watcher trigger if (vm && vm.$options.propsData && vm.$options.propsData[key] === undefined && vm._props[key] !== undefined ) { return vm._props[key] } // call factory function for non-Function types // a value is Function if its prototype is function even across different execution context return typeof def === 'function' && getType(prop.type) !== 'Function' ? def.call(vm) : def } /** * Assert whether a prop is valid. */ function assertProp ( prop, name, value, vm, absent ) { if (prop.required && absent) { warn( 'Missing required prop: "' + name + '"', vm ); return } if (value == null && !prop.required) { return } var type = prop.type; var valid = !type || type === true; var expectedTypes = []; if (type) { if (!Array.isArray(type)) { type = [type]; } for (var i = 0; i < type.length && !valid; i++) { var assertedType = assertType(value, type[i]); expectedTypes.push(assertedType.expectedType || ''); valid = assertedType.valid; } } if (!valid) { warn( getInvalidTypeMessage(name, value, expectedTypes), vm ); return } var validator = prop.validator; if (validator) { if (!validator(value)) { warn( 'Invalid prop: custom validator check failed for prop "' + name + '".', vm ); } } } var simpleCheckRE = /^(String|Number|Boolean|Function|Symbol)$/; function assertType (value, type) { var valid; var expectedType = getType(type); if (simpleCheckRE.test(expectedType)) { var t = typeof value; valid = t === expectedType.toLowerCase(); // for primitive wrapper objects if (!valid && t === 'object') { valid = value instanceof type; } } else if (expectedType === 'Object') { valid = isPlainObject(value); } else if (expectedType === 'Array') { valid = Array.isArray(value); } else { valid = value instanceof type; } return { valid: valid, expectedType: expectedType } } /** * Use function string name to check built-in types, * because a simple equality check will fail when running * across different vms / iframes. */ function getType (fn) { var match = fn && fn.toString().match(/^\s*function (\w+)/); return match ? match[1] : '' } function isSameType (a, b) { return getType(a) === getType(b) } function getTypeIndex (type, expectedTypes) { if (!Array.isArray(expectedTypes)) { return isSameType(expectedTypes, type) ? 0 : -1 } for (var i = 0, len = expectedTypes.length; i < len; i++) { if (isSameType(expectedTypes[i], type)) { return i } } return -1 } function getInvalidTypeMessage (name, value, expectedTypes) { var message = "Invalid prop: type check failed for prop \"" + name + "\"." + " Expected " + (expectedTypes.map(capitalize).join(', ')); var expectedType = expectedTypes[0]; var receivedType = toRawType(value); var expectedValue = styleValue(value, expectedType); var receivedValue = styleValue(value, receivedType); // check if we need to specify expected value if (expectedTypes.length === 1 && isExplicable(expectedType) && !isBoolean(expectedType, receivedType)) { message += " with value " + expectedValue; } message += ", got " + receivedType + " "; // check if we need to specify received value if (isExplicable(receivedType)) { message += "with value " + receivedValue + "."; } return message } function styleValue (value, type) { if (type === 'String') { return ("\"" + value + "\"") } else if (type === 'Number') { return ("" + (Number(value))) } else { return ("" + value) } } function isExplicable (value) { var explicitTypes = ['string', 'number', 'boolean']; return explicitTypes.some(function (elem) { return value.toLowerCase() === elem; }) } function isBoolean () { var args = [], len = arguments.length; while ( len-- ) args[ len ] = arguments[ len ]; return args.some(function (elem) { return elem.toLowerCase() === 'boolean'; }) } /* */ function handleError (err, vm, info) { // Deactivate deps tracking while processing error handler to avoid possible infinite rendering. // See: https://github.com/vuejs/vuex/issues/1505 pushTarget(); try { if (vm) { var cur = vm; while ((cur = cur.$parent)) { var hooks = cur.$options.errorCaptured; if (hooks) { for (var i = 0; i < hooks.length; i++) { try { var capture = hooks[i].call(cur, err, vm, info) === false; if (capture) { return } } catch (e) { globalHandleError(e, cur, 'errorCaptured hook'); } } } } } globalHandleError(err, vm, info); } finally { popTarget(); } } function invokeWithErrorHandling ( handler, context, args, vm, info ) { var res; try { res = args ? handler.apply(context, args) : handler.call(context); if (res && !res._isVue && isPromise(res)) { // issue #9511 // reassign to res to avoid catch triggering multiple times when nested calls res = res.catch(function (e) { return handleError(e, vm, info + " (Promise/async)"); }); } } catch (e) { handleError(e, vm, info); } return res } function globalHandleError (err, vm, info) { if (config.errorHandler) { try { return config.errorHandler.call(null, err, vm, info) } catch (e) { // if the user intentionally throws the original error in the handler, // do not log it twice if (e !== err) { logError(e, null, 'config.errorHandler'); } } } logError(err, vm, info); } function logError (err, vm, info) { { warn(("Error in " + info + ": \"" + (err.toString()) + "\""), vm); } /* istanbul ignore else */ if ((inBrowser || inWeex) && typeof console !== 'undefined') { console.error(err); } else { throw err } } /* */ var isUsingMicroTask = false; var callbacks = []; var pending = false; function flushCallbacks () { pending = false; var copies = callbacks.slice(0); callbacks.length = 0; for (var i = 0; i < copies.length; i++) { copies[i](); } } // Here we have async deferring wrappers using microtasks. // In 2.5 we used (macro) tasks (in combination with microtasks). // However, it has subtle problems when state is changed right before repaint // (e.g. #6813, out-in transitions). // Also, using (macro) tasks in event handler would cause some weird behaviors // that cannot be circumvented (e.g. #7109, #7153, #7546, #7834, #8109). // So we now use microtasks everywhere, again. // A major drawback of this tradeoff is that there are some scenarios // where microtasks have too high a priority and fire in between supposedly // sequential events (e.g. #4521, #6690, which have workarounds) // or even between bubbling of the same event (#6566). var timerFunc; // The nextTick behavior leverages the microtask queue, which can be accessed // via either native Promise.then or MutationObserver. // MutationObserver has wider support, however it is seriously bugged in // UIWebView in iOS >= 9.3.3 when triggered in touch event handlers. It // completely stops working after triggering a few times... so, if native // Promise is available, we will use it: /* istanbul ignore next, $flow-disable-line */ if (typeof Promise !== 'undefined' && isNative(Promise)) { var p = Promise.resolve(); timerFunc = function () { p.then(flushCallbacks); // In problematic UIWebViews, Promise.then doesn't completely break, but // it can get stuck in a weird state where callbacks are pushed into the // microtask queue but the queue isn't being flushed, until the browser // needs to do some other work, e.g. handle a timer. Therefore we can // "force" the microtask queue to be flushed by adding an empty timer. if (isIOS) { setTimeout(noop); } }; isUsingMicroTask = true; } else if (!isIE && typeof MutationObserver !== 'undefined' && ( isNative(MutationObserver) || // PhantomJS and iOS 7.x MutationObserver.toString() === '[object MutationObserverConstructor]' )) { // Use MutationObserver where native Promise is not available, // e.g. PhantomJS, iOS7, Android 4.4 // (#6466 MutationObserver is unreliable in IE11) var counter = 1; var observer = new MutationObserver(flushCallbacks); var textNode = document.createTextNode(String(counter)); observer.observe(textNode, { characterData: true }); timerFunc = function () { counter = (counter + 1) % 2; textNode.data = String(counter); }; isUsingMicroTask = true; } else if (typeof setImmediate !== 'undefined' && isNative(setImmediate)) { // Fallback to setImmediate. // Techinically it leverages the (macro) task queue, // but it is still a better choice than setTimeout. timerFunc = function () { setImmediate(flushCallbacks); }; } else { // Fallback to setTimeout. timerFunc = function () { setTimeout(flushCallbacks, 0); }; } function nextTick (cb, ctx) { var _resolve; callbacks.push(function () { if (cb) { try { cb.call(ctx); } catch (e) { handleError(e, ctx, 'nextTick'); } } else if (_resolve) { _resolve(ctx); } }); if (!pending) { pending = true; timerFunc(); } // $flow-disable-line if (!cb && typeof Promise !== 'undefined') { return new Promise(function (resolve) { _resolve = resolve; }) } } /* */ var mark; var measure; { var perf = inBrowser && window.performance; /* istanbul ignore if */ if ( perf && perf.mark && perf.measure && perf.clearMarks && perf.clearMeasures ) { mark = function (tag) { return perf.mark(tag); }; measure = function (name, startTag, endTag) { perf.measure(name, startTag, endTag); perf.clearMarks(startTag); perf.clearMarks(endTag); // perf.clearMeasures(name) }; } } /* not type checking this file because flow doesn't play well with Proxy */ var initProxy; { var allowedGlobals = makeMap( 'Infinity,undefined,NaN,isFinite,isNaN,' + 'parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,' + 'Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl,' + 'require' // for Webpack/Browserify ); var warnNonPresent = function (target, key) { warn( "Property or method \"" + key + "\" is not defined on the instance but " + 'referenced during render. Make sure that this property is reactive, ' + 'either in the data option, or for class-based components, by ' + 'initializing the property. ' + 'See: https://vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.', target ); }; var warnReservedPrefix = function (target, key) { warn( "Property \"" + key + "\" must be accessed with \"$data." + key + "\" because " + 'properties starting with "$" or "_" are not proxied in the Vue instance to ' + 'prevent conflicts with Vue internals' + 'See: https://vuejs.org/v2/api/#data', target ); }; var hasProxy = typeof Proxy !== 'undefined' && isNative(Proxy); if (hasProxy) { var isBuiltInModifier = makeMap('stop,prevent,self,ctrl,shift,alt,meta,exact'); config.keyCodes = new Proxy(config.keyCodes, { set: function set (target, key, value) { if (isBuiltInModifier(key)) { warn(("Avoid overwriting built-in modifier in config.keyCodes: ." + key)); return false } else { target[key] = value; return true } } }); } var hasHandler = { has: function has (target, key) { var has = key in target; var isAllowed = allowedGlobals(key) || (typeof key === 'string' && key.charAt(0) === '_' && !(key in target.$data)); if (!has && !isAllowed) { if (key in target.$data) { warnReservedPrefix(target, key); } else { warnNonPresent(target, key); } } return has || !isAllowed } }; var getHandler = { get: function get (target, key) { if (typeof key === 'string' && !(key in target)) { if (key in target.$data) { warnReservedPrefix(target, key); } else { warnNonPresent(target, key); } } return target[key] } }; initProxy = function initProxy (vm) { if (hasProxy) { // determine which proxy handler to use var options = vm.$options; var handlers = options.render && options.render._withStripped ? getHandler : hasHandler; vm._renderProxy = new Proxy(vm, handlers); } else { vm._renderProxy = vm; } }; } /* */ var seenObjects = new _Set(); /** * Recursively traverse an object to evoke all converted * getters, so that every nested property inside the object * is collected as a "deep" dependency. */ function traverse (val) { _traverse(val, seenObjects); seenObjects.clear(); } function _traverse (val, seen) { var i, keys; var isA = Array.isArray(val); if ((!isA && !isObject(val)) || Object.isFrozen(val) || val instanceof VNode) { return } if (val.__ob__) { var depId = val.__ob__.dep.id; if (seen.has(depId)) { return } seen.add(depId); } if (isA) { i = val.length; while (i--) { _traverse(val[i], seen); } } else { keys = Object.keys(val); i = keys.length; while (i--) { _traverse(val[keys[i]], seen); } } } /* */ var normalizeEvent = cached(function (name) { var passive = name.charAt(0) === '&'; name = passive ? name.slice(1) : name; var once$$1 = name.charAt(0) === '~'; // Prefixed last, checked first name = once$$1 ? name.slice(1) : name; var capture = name.charAt(0) === '!'; name = capture ? name.slice(1) : name; return { name: name, once: once$$1, capture: capture, passive: passive } }); function createFnInvoker (fns, vm) { function invoker () { var arguments$1 = arguments; var fns = invoker.fns; if (Array.isArray(fns)) { var cloned = fns.slice(); for (var i = 0; i < cloned.length; i++) { invokeWithErrorHandling(cloned[i], null, arguments$1, vm, "v-on handler"); } } else { // return handler return value for single handlers return invokeWithErrorHandling(fns, null, arguments, vm, "v-on handler") } } invoker.fns = fns; return invoker } function updateListeners ( on, oldOn, add, remove$$1, createOnceHandler, vm ) { var name, def$$1, cur, old, event; for (name in on) { def$$1 = cur = on[name]; old = oldOn[name]; event = normalizeEvent(name); if (isUndef(cur)) { warn( "Invalid handler for event \"" + (event.name) + "\": got " + String(cur), vm ); } else if (isUndef(old)) { if (isUndef(cur.fns)) { cur = on[name] = createFnInvoker(cur, vm); } if (isTrue(event.once)) { cur = on[name] = createOnceHandler(event.name, cur, event.capture); } add(event.name, cur, event.capture, event.passive, event.params); } else if (cur !== old) { old.fns = cur; on[name] = old; } } for (name in oldOn) { if (isUndef(on[name])) { event = normalizeEvent(name); remove$$1(event.name, oldOn[name], event.capture); } } } /* */ function mergeVNodeHook (def, hookKey, hook) { if (def instanceof VNode) { def = def.data.hook || (def.data.hook = {}); } var invoker; var oldHook = def[hookKey]; function wrappedHook () { hook.apply(this, arguments); // important: remove merged hook to ensure it's called only once // and prevent memory leak remove(invoker.fns, wrappedHook); } if (isUndef(oldHook)) { // no existing hook invoker = createFnInvoker([wrappedHook]); } else { /* istanbul ignore if */ if (isDef(oldHook.fns) && isTrue(oldHook.merged)) { // already a merged invoker invoker = oldHook; invoker.fns.push(wrappedHook); } else { // existing plain hook invoker = createFnInvoker([oldHook, wrappedHook]); } } invoker.merged = true; def[hookKey] = invoker; } /* */ function extractPropsFromVNodeData ( data, Ctor, tag ) { // we are only extracting raw values here. // validation and default values are handled in the child // component itself. var propOptions = Ctor.options.props; if (isUndef(propOptions)) { return } var res = {}; var attrs = data.attrs; var props = data.props; if (isDef(attrs) || isDef(props)) { for (var key in propOptions) { var altKey = hyphenate(key); { var keyInLowerCase = key.toLowerCase(); if ( key !== keyInLowerCase && attrs && hasOwn(attrs, keyInLowerCase) ) { tip( "Prop \"" + keyInLowerCase + "\" is passed to component " + (formatComponentName(tag || Ctor)) + ", but the declared prop name is" + " \"" + key + "\". " + "Note that HTML attributes are case-insensitive and camelCased " + "props need to use their kebab-case equivalents when using in-DOM " + "templates. You should probably use \"" + altKey + "\" instead of \"" + key + "\"." ); } } checkProp(res, props, key, altKey, true) || checkProp(res, attrs, key, altKey, false); } } return res } function checkProp ( res, hash, key, altKey, preserve ) { if (isDef(hash)) { if (hasOwn(hash, key)) { res[key] = hash[key]; if (!preserve) { delete hash[key]; } return true } else if (hasOwn(hash, altKey)) { res[key] = hash[altKey]; if (!preserve) { delete hash[altKey]; } return true } } return false } /* */ // The template compiler attempts to minimize the need for normalization by // statically analyzing the template at compile time. // // For plain HTML markup, normalization can be completely skipped because the // generated render function is guaranteed to return Array. There are // two cases where extra normalization is needed: // 1. When the children contains components - because a functional component // may return an Array instead of a single root. In this case, just a simple // normalization is needed - if any child is an Array, we flatten the whole // thing with Array.prototype.concat. It is guaranteed to be only 1-level deep // because functional components already normalize their own children. function simpleNormalizeChildren (children) { for (var i = 0; i < children.length; i++) { if (Array.isArray(children[i])) { return Array.prototype.concat.apply([], children) } } return children } // 2. When the children contains constructs that always generated nested Arrays, // e.g.