chat.js 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. import {
  2. YeIMUniSDK,
  3. YeIMUniSDKDefines
  4. } from '@/uni_modules/wzJun1-YeIM-Uni-SDK/js_sdk/yeim-uni-sdk.min.js'
  5. import {
  6. login,
  7. sendSystem
  8. } from '@/request/api/chat.js'
  9. import md5 from '@/js_sdk/js-md5/build/md5.min.js';
  10. import config from "@/config";
  11. let userIds, isListenerChatList = false;
  12. const connect = success => {
  13. if (!userIds) return;
  14. let code = YeIMUniSDK.getInstance().readyState();
  15. if (code !== 3) {
  16. if (success) success();
  17. return;
  18. }
  19. YeIMUniSDK.getInstance().connect({
  20. userId: userIds,
  21. token: uni.getStorageSync('chatToken'),
  22. success: (response) => {
  23. if (response.code === 200) {
  24. $chat.listenerList();
  25. if (success) success();
  26. }
  27. },
  28. fail: (err) => {
  29. logins();
  30. }
  31. });
  32. }
  33. const logins = () => {
  34. let timestamp = (new Date()).getTime() + 86400 * 1000; //1000天后过期
  35. let sign = md5(String(userIds) + timestamp + "50abd47112ebe8c5a73f4694c96a49ce");
  36. login({
  37. userId: userIds,
  38. timestamp: timestamp,
  39. sign: sign
  40. }).then(res => {
  41. if (res.code === 200) {
  42. uni.setStorageSync('chatToken', res.data.token);
  43. connect();
  44. }
  45. })
  46. }
  47. const $chat = {
  48. init() {
  49. //初始化YeIMUniSDK
  50. uni.$YeIMUniSDKDefines = YeIMUniSDKDefines;
  51. uni.$YeIM = YeIMUniSDK.init({
  52. baseURL: config.baseUrl + '/im', // YeIMServer http url (如无特殊需求,服务端启动后仅需修改ip或者域名即可)
  53. socketURL: config.socketURL, // YeIMServer socket url(如无特殊需求,服务端启动后仅需修改ip或者域名即可)
  54. /**
  55. * 日志等级
  56. * 0 普通日志,日志量较多,接入时建议使用
  57. * 1 关键性日志,日志量较少,生产环境时建议使用
  58. * 2 无日志级别,SDK 将不打印任何日志
  59. */
  60. logLevel: 2, // 日志等级,
  61. reConnectInterval: 3000, // 重连时间间隔
  62. reConnectTotal: 99, // 最大重连次数,0不限制一直重连
  63. heartInterval: 35000, //心跳时间间隔(默认30s)
  64. });
  65. },
  66. connect(userId) {
  67. userIds = userId;
  68. if (!userId) return;
  69. if (!uni.getStorageSync('chatToken')) {
  70. logins()
  71. } else {
  72. connect();
  73. }
  74. },
  75. getConversationList(success) {
  76. connect(() => {
  77. YeIMUniSDK.getInstance().getConversationList({
  78. page: 1, //页码
  79. limit: 100, //每页数量
  80. success: success,
  81. fail: (err) => {
  82. console.log('error');
  83. }
  84. });
  85. });
  86. },
  87. getHistoryMessageList(nextMessageId, userId, success, fail) {
  88. connect(() => {
  89. YeIMUniSDK.getInstance().getHistoryMessageList({
  90. nextMessageId: nextMessageId,
  91. conversationId: userId,
  92. success: success,
  93. fail: fail
  94. });
  95. });
  96. },
  97. sendImage(userId, success) {
  98. connect(() => {
  99. uni.chooseImage({
  100. count: 1, //图片数量
  101. sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有
  102. sourceType: ['album'], //从相册选择
  103. success: res => {
  104. uni.getImageInfo({
  105. src: res.tempFilePaths[0],
  106. success: image => {
  107. //创建图片消息
  108. let message = YeIMUniSDK.getInstance()
  109. .createImageMessage({
  110. toId: userId, //接收者用户ID字符串
  111. conversationType: YeIMUniSDKDefines
  112. .CONVERSATION_TYPE
  113. .PRIVATE, //会话类型:私聊
  114. body: {
  115. file: {
  116. tempFilePath: res.tempFilePaths[
  117. 0], //本地图片临时路径
  118. width: image.width, //图片宽度
  119. height: image.height //图片高度
  120. }
  121. },
  122. extra: "",
  123. onProgress: (progress) => {
  124. // console.log(progress);
  125. }
  126. });
  127. //发送消息
  128. uni.showLoading();
  129. YeIMUniSDK.getInstance().sendMessage({
  130. message: message,
  131. success: success,
  132. fail: (err) => {
  133. uni.hideLoading();
  134. uni.showToast({
  135. title: '发送失败',
  136. icon: "none"
  137. });
  138. }
  139. });
  140. }
  141. });
  142. }
  143. });
  144. });
  145. },
  146. sendText(userId, content, success) {
  147. connect(() => {
  148. //创建文字消息
  149. let message = YeIMUniSDK.getInstance().createTextMessage({
  150. toId: userId, //接收者用户ID字符串
  151. conversationType: YeIMUniSDKDefines.CONVERSATION_TYPE.PRIVATE, //会话类型:私聊
  152. body: {
  153. text: content //文本消息内容字符串
  154. },
  155. extra: ""
  156. });
  157. //发送消息
  158. YeIMUniSDK.getInstance().sendMessage({
  159. message: message,
  160. success: success,
  161. fail: (err) => {
  162. uni.hideLoading();
  163. uni.showToast({
  164. title: '发送失败',
  165. icon: "none"
  166. });
  167. }
  168. });
  169. });
  170. },
  171. disConnect() {
  172. YeIMUniSDK.getInstance().disConnect();
  173. },
  174. listenerLogin() {
  175. //监听登陆互踢,当同一用户重复登录时触发
  176. YeIMUniSDK.getInstance().addEventListener(YeIMUniSDKDefines.EVENT.KICKED_OUT, () => {
  177. // uni.removeStorageSync('token');
  178. // uni.removeStorageSync('chatToken');
  179. // uni.showToast({
  180. // title: '该用户已在其他设备登录',
  181. // icon: 'none'
  182. // })
  183. // uni.switchTab({
  184. // url: '/pages/highseas/highseas'
  185. // });
  186. });
  187. },
  188. listenerList() {
  189. if (isListenerChatList) return;
  190. connect(() => {
  191. isListenerChatList = true;
  192. //监听会话列表更新
  193. YeIMUniSDK.getInstance().addEventListener(YeIMUniSDKDefines.EVENT.CONVERSATION_LIST_CHANGED, (
  194. list) => {
  195. uni.$emit('changeChatList', list);
  196. });
  197. })
  198. },
  199. clearConversationUnread(conversationId) {
  200. //清除指定会话未读数,并给对方发送已读回执
  201. YeIMUniSDK.getInstance().clearConversationUnread(conversationId);
  202. },
  203. sendSystemMessage() {
  204. let timestamp = (new Date()).getTime() + 86400 * 1000; //1000天后过期
  205. let sign = md5('system' + timestamp + "50abd47112ebe8c5a73f4694c96a49ce");
  206. login({
  207. userId: 'system',
  208. timestamp: timestamp,
  209. sign: sign
  210. }).then(res => {
  211. if (res.code === 200) {
  212. uni.setStorageSync('systemChatToken', res.data.token);
  213. sendSystem({
  214. body: {
  215. text: "2"
  216. },
  217. conversationId: "4",
  218. conversationType: "private",
  219. extra: "",
  220. from: 'system',
  221. fromUserInfo: {},
  222. isDeleted: 0,
  223. isRead: 0,
  224. isRevoke: 0,
  225. status: "unSend",
  226. time: new Date().getTime(),
  227. to: 1,
  228. type: "text",
  229. })
  230. }
  231. })
  232. }
  233. }
  234. export default $chat;