useIM.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. import { ref, onMounted, onUnmounted, watch } from 'vue';
  2. import { getConversationSync, getMessageSync, getChatKey, setUnread, deleteConversation } from '@/api/common'
  3. import { Base64 } from 'js-base64'
  4. import { userStore } from '@/store/user'
  5. import { useIMStore } from '@/store/im'
  6. // 配置悟空IM
  7. import {
  8. MessageText,
  9. Channel,
  10. WKSDK,
  11. ChannelTypePerson,
  12. MessageContent,
  13. } from "wukongimjssdk"
  14. // 默认招呼语
  15. export const defaultText = '您好,我们正在寻找充满激情、勇于挑战的您,快来和我聊一聊吧~'
  16. const { ObjectContent } = initRegister(101)
  17. const { ObjectContent: ObjectContent2 } = initRegister(102)
  18. const { ObjectContent: ObjectContent3 } = initRegister(103)
  19. const { ObjectContent: ObjectContent4 } = initRegister(104)
  20. const { ObjectContent: ObjectContent5 } = initRegister(105) // 发送简历
  21. const contentType = {
  22. 101: ObjectContent,
  23. 102: ObjectContent2,
  24. 103: ObjectContent3,
  25. 104: ObjectContent4,
  26. 105: ObjectContent5, // 发送简历
  27. }
  28. // 注册消息体
  29. function initRegister (type) {
  30. class ObjectContent extends MessageContent {
  31. constructor(text) {
  32. super();
  33. this.content = text
  34. }
  35. get conversationDigest() {
  36. // 这里需要实现具体的逻辑
  37. return this.content
  38. }
  39. get contentType() {
  40. // 这里需要实现具体的逻辑
  41. return type; // 示例实现
  42. }
  43. decodeJSON(content) {
  44. this.content = content.text;
  45. }
  46. encodeJSON() {
  47. return {
  48. content: this.content
  49. };
  50. }
  51. }
  52. // 注册101类型为面试
  53. WKSDK.shared().register(type, () => new ObjectContent(''))
  54. return {
  55. ObjectContent
  56. }
  57. }
  58. const HISTORY_QUERY = {
  59. limit: 20,
  60. startMessageSeq: 0,
  61. endMessageSeq: 0,
  62. pullMode: 1
  63. }
  64. const ConnectStatus = {
  65. Disconnect: 0, // 断开连接
  66. Connected: 1, // 连接成功
  67. Connecting: 2, // 连接中
  68. ConnectFail: 3, // 连接错误
  69. ConnectKick: 4, // 连接被踢,服务器要求客户端断开(一般是账号在其他地方登录,被踢)
  70. }
  71. // api 接入
  72. export function useDataSource () {
  73. const useUserStore = userStore()
  74. // 最近会话数据源
  75. WKSDK.shared().config.provider.syncConversationsCallback = async () => {
  76. const query = {
  77. msg_count: 1,
  78. enterpriseId: useUserStore?.userInfo?.enterpriseId
  79. }
  80. const resultConversations = []
  81. const resp = await getConversationSync(query)
  82. const { data:conversationList } = resp
  83. if (conversationList) {
  84. conversationList.forEach(conversation => {
  85. conversation.channel = new Channel(conversation.channel_id, conversation.channel_type)
  86. conversation.unread = +(conversation.unread || 0)
  87. resultConversations.push(conversation)
  88. })
  89. }
  90. return resultConversations
  91. }
  92. // 同步频道消息数据源
  93. WKSDK.shared().config.provider.syncMessagesCallback = async function(channel) {
  94. // 后端提供的获取频道消息列表的接口数据 然后构建成 Message对象数组返回
  95. let resultMessages = new Array()
  96. const {
  97. startMessageSeq: start_message_seq,
  98. endMessageSeq: end_message_seq,
  99. limit,
  100. pullMode: pull_mode
  101. } = HISTORY_QUERY
  102. const query = {
  103. channel_id: channel.channelID,
  104. channel_type: channel.channelType,
  105. enterpriseId: useUserStore?.userInfo?.enterpriseId,
  106. start_message_seq,
  107. end_message_seq,
  108. limit,
  109. pull_mode,
  110. }
  111. const { data } = await getMessageSync(query)
  112. const resp = data
  113. const messageList = resp && resp["messages"]
  114. if (messageList) {
  115. messageList.forEach((msg) => {
  116. // const message = Convert.toMessage(msg);
  117. // msg.channel = new Channel(msg.channel_id, msg.channel_type)
  118. msg.payload = JSON.parse(Base64.decode(msg.payload))
  119. if (contentType[msg.payload.type]) {
  120. msg.payload.content = JSON.parse(msg.payload.content ?? '{}')
  121. }
  122. resultMessages.push(msg)
  123. })
  124. }
  125. // console.log(resultMessages)
  126. const more = resp.more === 1
  127. return {
  128. more,
  129. resultMessages
  130. }
  131. }
  132. }
  133. export function toChannel (channelID, channelType) {
  134. return new Channel(channelID, channelType)
  135. }
  136. async function getKey () {
  137. const useUserStore = userStore()
  138. if (!useUserStore.accountInfo?.userId) {
  139. return {}
  140. }
  141. const keyQuery = {
  142. userId: useUserStore.accountInfo?.userId,
  143. enterpriseId: useUserStore?.userInfo?.enterpriseId
  144. }
  145. const { data } = await getChatKey(keyQuery)
  146. return {
  147. ...data
  148. }
  149. }
  150. export const useIM = () => {
  151. useDataSource()
  152. const key = ref(0)
  153. const IM = useIMStore()
  154. onMounted( async () => {
  155. await resetConfig()
  156. // 连接状态监听
  157. WKSDK.shared().connectManager.addConnectStatusListener(connectStatusListener)
  158. // 常规消息监听
  159. WKSDK.shared().chatManager.addMessageListener(messageListen)
  160. // 连接
  161. WKSDK.shared().connectManager.connect()
  162. })
  163. onUnmounted(() => {
  164. WKSDK.shared().connectManager.removeConnectStatusListener(connectStatusListener)
  165. // 常规消息监听移除
  166. WKSDK.shared().chatManager.removeMessageListener(messageListen)
  167. // 连接状态监听移除
  168. WKSDK.shared().connectManager.disconnect()
  169. })
  170. async function messageListen (message) {
  171. // console.log('收到消息', message)
  172. IM.setFromChannel(message.channel.channelID)
  173. setUnreadCount()
  174. }
  175. async function connectStatusListener (status) {
  176. // console.log('连接状态', status === ConnectStatus.Connected)
  177. // 连接成功 获取点击数
  178. const connected = status === ConnectStatus.Connected
  179. IM.setConnected(connected)
  180. if (connected) {
  181. // 必须同步最近会话才能获取未读总数
  182. await syncConversation()
  183. setUnreadCount()
  184. }
  185. }
  186. function setUnreadCount () {
  187. const count = WKSDK.shared().conversationManager.getAllUnreadCount()
  188. key.value++
  189. IM.setNewMsg(key.value)
  190. IM.setUnreadCount(count)
  191. console.log('未读消息总数', count)
  192. }
  193. async function resetConfig () {
  194. try {
  195. const { uid, wssUrl, token } = await getKey()
  196. IM.setUid(uid)
  197. // 单机模式可以直接设置地址
  198. WKSDK.shared().config.addr = 'wss://' + wssUrl// 默认端口为5200 + wsUrl
  199. // 认证信息
  200. WKSDK.shared().config.uid = uid // 用户uid(需要在悟空通讯端注册过)
  201. WKSDK.shared().config.token = token // 用户token (需要在悟空通讯端注册过)
  202. } catch (error) {
  203. console.log(error)
  204. }
  205. }
  206. return {
  207. resetConfig
  208. }
  209. }
  210. export function initConnect (callback = () => {}, mounted = () => {}) {
  211. useDataSource()
  212. const IM = useIMStore()
  213. const conversationList = ref([])
  214. const messageItems = ref([])
  215. watch(
  216. () => IM.newMsg,
  217. async () => {
  218. // 未读消息变化
  219. updateConversation()
  220. // 拉取最新消息 查看是否是自己的数据
  221. },
  222. {
  223. deep: true,
  224. immediate: true
  225. }
  226. )
  227. onMounted(async () => {
  228. // 消息发送状态监听
  229. WKSDK.shared().chatManager.addMessageStatusListener(statusListen)
  230. // 常规消息监听
  231. // WKSDK.shared().chatManager.addMessageListener(messageListen)
  232. mounted()
  233. })
  234. onUnmounted(() => {
  235. // 消息发送状态监听移除
  236. WKSDK.shared().chatManager.removeMessageStatusListener(statusListen)
  237. // 常规消息监听移除
  238. // WKSDK.shared().chatManager.removeMessageListener(messageListen)
  239. })
  240. // 消息发送状态监听
  241. function statusListen (packet) {
  242. console.log('发送状态', packet)
  243. if (packet.reasonCode === 1) {
  244. // 发送成功
  245. console.log('发送成功')
  246. // 添加一组成功数据
  247. callback(true)
  248. } else {
  249. // 发送失败
  250. console.log('发送失败')
  251. // 添加一组失败数据
  252. callback(false)
  253. }
  254. }
  255. async function updateConversation () {
  256. const res = await syncConversation()
  257. conversationList.value = res
  258. }
  259. function updateUnreadCount () {
  260. const count = WKSDK.shared().conversationManager.getAllUnreadCount()
  261. IM.setUnreadCount(count)
  262. }
  263. async function deleteConversations (channel, enterpriseId) {
  264. const query = {
  265. channel_id: channel.channelID,
  266. channel_type: channel.channelType,
  267. enterpriseId
  268. }
  269. await deleteConversation(query)
  270. }
  271. async function resetUnread (channel, enterpriseId) {
  272. const query = {
  273. channel_id: channel.channelID,
  274. channel_type: channel.channelType,
  275. enterpriseId,
  276. unread: 0
  277. }
  278. const res = await setUnread(query)
  279. return res
  280. }
  281. return {
  282. resetUnread,
  283. deleteConversations,
  284. updateConversation,
  285. updateUnreadCount,
  286. conversationList,
  287. messageItems,
  288. // channel
  289. }
  290. }
  291. // 同步最近会话
  292. async function syncConversation () {
  293. const res = await WKSDK.shared().conversationManager.sync()
  294. return res
  295. }
  296. // 发起聊天
  297. export async function initChart (userId, enterpriseId) {
  298. try {
  299. const channel = ref()
  300. // const list = ref([])
  301. const query = {
  302. userId,
  303. enterpriseId
  304. }
  305. // 创建聊天频道
  306. const { data } = await getChatKey(query)
  307. // console.log(data, 'data')
  308. const { uid } = data
  309. const _channel = new Channel(uid, ChannelTypePerson)
  310. channel.value = _channel
  311. const conversation = WKSDK.shared().conversationManager.findConversation(_channel)
  312. if(!conversation) {
  313. // 如果最近会话不存在,则创建一个空的会话
  314. WKSDK.shared().conversationManager.createEmptyConversation(_channel)
  315. }
  316. const res = await getMoreMessages(1, _channel)
  317. return {
  318. channel,
  319. ...res
  320. }
  321. } catch (error) {
  322. console.log(error)
  323. }
  324. }
  325. // 翻页
  326. export async function getMoreMessages (pageSize, channel) {
  327. const list = ref([])
  328. Object.assign(HISTORY_QUERY, {
  329. startMessageSeq: (pageSize - 1) * HISTORY_QUERY.limit
  330. })
  331. const { resultMessages, more } = await WKSDK.shared().chatManager.syncMessages(channel)
  332. list.value = resultMessages
  333. return {
  334. list,
  335. more
  336. }
  337. }
  338. /**
  339. *
  340. * @param {*} text
  341. * @param {*} _channel
  342. * @param { Number } type : 101 面试主体
  343. * @returns
  344. */
  345. // 发送职位使用101
  346. export function send (text, _channel, type) {
  347. let _text
  348. if (contentType[type]) {
  349. _text = new contentType[type](text)
  350. WKSDK.shared().chatManager.send(_text, _channel)
  351. return
  352. }
  353. _text = new MessageText(text)
  354. console.log(WKSDK.shared().chatManager, 111111)
  355. WKSDK.shared().chatManager.send(_text, _channel)
  356. }
  357. // 对话开场白 用户 to 企业
  358. export async function prologue ({userId, enterpriseId, text}) {
  359. const { channel } = await checkConversation(userId, enterpriseId)
  360. send(text, channel, 102)
  361. return channel
  362. }
  363. // 企业 to 用户
  364. export async function talkToUser ({userId, text}) {
  365. const { channel, isNewTalk } = await checkConversation(userId)
  366. // if (!isNewTalk) send(text, channel)
  367. send(text, channel)
  368. return channel
  369. }
  370. // 检测是否存在频道
  371. export async function checkConversation (userId, enterpriseId) {
  372. const query = {
  373. userId,
  374. enterpriseId
  375. }
  376. // 创建聊天频道
  377. const { data } = await getChatKey(query)
  378. const { uid } = data
  379. const _channel = new Channel(uid, ChannelTypePerson)
  380. console.log('生成channel', _channel)
  381. const conversation = WKSDK.shared().conversationManager.findConversation(_channel)
  382. const isNewTalk = ref(false)
  383. if(!conversation) {
  384. // 如果最近会话不存在,则创建一个空的会话
  385. WKSDK.shared().conversationManager.createEmptyConversation(_channel)
  386. isNewTalk.value = true
  387. }
  388. return {
  389. channel: _channel,
  390. isNewTalk: isNewTalk.value
  391. }
  392. }