useIM.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452
  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. // 企业默认招呼语
  17. // export const defaultTextEnt = '您好,我们正在寻找充满激情、勇于挑战的您,快来和我聊一聊吧~'
  18. const { ObjectContent } = initRegister(101)
  19. const { ObjectContent: ObjectContent2 } = initRegister(102)
  20. const { ObjectContent: ObjectContent3 } = initRegister(103)
  21. const { ObjectContent: ObjectContent4 } = initRegister(104)
  22. const { ObjectContent: ObjectContent5 } = initRegister(105) // 发送简历
  23. const contentType = {
  24. 101: ObjectContent,
  25. 102: ObjectContent2,
  26. 103: ObjectContent3,
  27. 104: ObjectContent4,
  28. 105: ObjectContent5, // 发送简历
  29. }
  30. // 注册消息体
  31. function initRegister (type) {
  32. class ObjectContent extends MessageContent {
  33. constructor(text) {
  34. super();
  35. this.content = text
  36. }
  37. get conversationDigest() {
  38. // 这里需要实现具体的逻辑
  39. return this.content
  40. }
  41. get contentType() {
  42. // 这里需要实现具体的逻辑
  43. return type; // 示例实现
  44. }
  45. decodeJSON(content) {
  46. this.content = content.text;
  47. }
  48. encodeJSON() {
  49. return {
  50. content: this.content
  51. };
  52. }
  53. }
  54. // 注册101类型为面试
  55. WKSDK.shared().register(type, () => new ObjectContent(''))
  56. return {
  57. ObjectContent
  58. }
  59. }
  60. const HISTORY_QUERY = {
  61. limit: 20,
  62. startMessageSeq: 0,
  63. endMessageSeq: 0,
  64. pullMode: 1
  65. }
  66. const ConnectStatus = {
  67. Disconnect: 0, // 断开连接
  68. Connected: 1, // 连接成功
  69. Connecting: 2, // 连接中
  70. ConnectFail: 3, // 连接错误
  71. ConnectKick: 4, // 连接被踢,服务器要求客户端断开(一般是账号在其他地方登录,被踢)
  72. }
  73. // api 接入
  74. export function useDataSource () {
  75. // 最近会话数据源
  76. WKSDK.shared().config.provider.syncConversationsCallback = async () => {
  77. const query = {
  78. msg_count: 1
  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. start_message_seq,
  106. end_message_seq,
  107. limit,
  108. pull_mode,
  109. }
  110. const { data } = await getMessageSync(query)
  111. const resp = data
  112. const messageList = resp && resp["messages"]
  113. if (messageList) {
  114. messageList.forEach((msg) => {
  115. // const message = Convert.toMessage(msg);
  116. // msg.channel = new Channel(msg.channel_id, msg.channel_type)
  117. msg.payload = JSON.parse(Base64.decode(msg.payload))
  118. if (contentType[msg.payload.type]) {
  119. msg.payload.content = JSON.parse(msg.payload.content ?? '{}')
  120. }
  121. resultMessages.push(msg)
  122. })
  123. }
  124. // console.log(resultMessages)
  125. const more = resp.more === 1
  126. return {
  127. more,
  128. resultMessages
  129. }
  130. }
  131. }
  132. async function getKey () {
  133. const useUserStore = userStore()
  134. const keyQuery = {
  135. userId: useUserStore.accountInfo?.userId
  136. }
  137. const { data } = await getChatKey(keyQuery)
  138. return {
  139. ...data
  140. }
  141. }
  142. export const useIM = () => {
  143. useDataSource()
  144. const key = ref(0)
  145. const IM = useIMStore()
  146. onMounted( async () => {
  147. try {
  148. // 通过自身userId和企业id获取token和uid
  149. await resetConfig()
  150. // 连接状态监听
  151. WKSDK.shared().connectManager.addConnectStatusListener(connectStatusListener)
  152. // 常规消息监听
  153. WKSDK.shared().chatManager.addMessageListener(messageListen)
  154. // 连接
  155. WKSDK.shared().connectManager.connect()
  156. } catch (error) {
  157. console.log(error)
  158. }
  159. })
  160. onUnmounted(() => {
  161. WKSDK.shared().connectManager.removeConnectStatusListener(connectStatusListener)
  162. // 常规消息监听移除
  163. WKSDK.shared().chatManager.removeMessageListener(messageListen)
  164. // 连接状态监听移除
  165. WKSDK.shared().connectManager.disconnect()
  166. })
  167. async function messageListen (message) {
  168. // console.log('收到消息', message)
  169. IM.setFromChannel(message.channel.channelID)
  170. setUnreadCount()
  171. }
  172. async function connectStatusListener (status) {
  173. // console.log('连接状态', status === ConnectStatus.Connected)
  174. // 连接成功 获取点击数
  175. const connected = status === ConnectStatus.Connected
  176. IM.setConnected(connected)
  177. if (connected) {
  178. // 必须同步最近会话才能获取未读总数
  179. await syncConversation()
  180. setUnreadCount()
  181. }
  182. }
  183. function setUnreadCount () {
  184. const count = WKSDK.shared().conversationManager.getAllUnreadCount()
  185. key.value++
  186. IM.setNewMsg(key.value)
  187. IM.setUnreadCount(count)
  188. console.log('未读消息总数', count)
  189. }
  190. async function resetConfig () {
  191. try {
  192. const { uid, wssUrl, token } = await getKey()
  193. if (!wssUrl) {
  194. return
  195. }
  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. const channel = ref()
  299. // const list = ref([])
  300. const query = {
  301. userId,
  302. enterpriseId
  303. }
  304. // 创建聊天频道
  305. const { data } = await getChatKey(query)
  306. const { uid } = data
  307. const _channel = new Channel(uid, ChannelTypePerson)
  308. channel.value = _channel
  309. const conversation = WKSDK.shared().conversationManager.findConversation(_channel)
  310. if(!conversation) {
  311. // 如果最近会话不存在,则创建一个空的会话
  312. WKSDK.shared().conversationManager.createEmptyConversation(_channel)
  313. }
  314. const res = await getMoreMessages(1, _channel)
  315. return {
  316. channel,
  317. ...res
  318. }
  319. }
  320. // 翻页
  321. export async function getMoreMessages (pageSize, channel) {
  322. const list = ref([])
  323. Object.assign(HISTORY_QUERY, {
  324. startMessageSeq: (pageSize - 1) * HISTORY_QUERY.limit
  325. })
  326. const { resultMessages, more } = await WKSDK.shared().chatManager.syncMessages(channel)
  327. list.value = resultMessages
  328. return {
  329. list,
  330. more
  331. }
  332. }
  333. /**
  334. *
  335. * @param {*} text
  336. * @param {*} _channel
  337. * @param { Number } type : 101 面试主体
  338. * @returns
  339. */
  340. // 发送职位使用101
  341. export function send (text, _channel, type) {
  342. let _text
  343. if (contentType[type]) {
  344. _text = new contentType[type](text)
  345. WKSDK.shared().chatManager.send(_text, _channel)
  346. return
  347. }
  348. // if (type === 101) {
  349. // _text = new ObjectContent(text)
  350. // WKSDK.shared().chatManager.send(_text, _channel)
  351. // // console.log(_text)
  352. // return
  353. // }
  354. // if (type === 102) {
  355. // _text = new ObjectContent2(text)
  356. // WKSDK.shared().chatManager.send(_text, _channel)
  357. // // console.log(_text)
  358. // return
  359. // }
  360. // // 求职者拒绝面试邀请
  361. // if (type === 103) {
  362. // _text = new ObjectContent3(text)
  363. // WKSDK.shared().chatManager.send(_text, _channel)
  364. // return
  365. // }
  366. // // 求职者接受面试邀请
  367. // if (type === 104) {
  368. // _text = new ObjectContent4(text)
  369. // WKSDK.shared().chatManager.send(_text, _channel)
  370. // return
  371. // }
  372. _text = new MessageText(text)
  373. // console.log(_text)
  374. WKSDK.shared().chatManager.send(_text, _channel)
  375. }
  376. // 对话开场白 用户 to 企业
  377. export async function prologue ({userId, enterpriseId, text}) {
  378. const { channel } = await checkConversation(userId, enterpriseId)
  379. send(text, channel, 102)
  380. return channel
  381. }
  382. // 企业 to 用户
  383. export async function talkToUser ({userId, text}) {
  384. const { channel, isNewTalk } = await checkConversation(userId)
  385. if (!isNewTalk) send(text, channel)
  386. }
  387. // 检测是否存在频道
  388. export async function checkConversation (userId, enterpriseId) {
  389. const query = {
  390. userId,
  391. enterpriseId
  392. }
  393. // 创建聊天频道
  394. const { data } = await getChatKey(query)
  395. const { uid } = data
  396. const _channel = new Channel(uid, ChannelTypePerson)
  397. console.log('生成channel', _channel)
  398. const conversation = WKSDK.shared().conversationManager.findConversation(_channel)
  399. const isNewTalk = ref(false)
  400. if(!conversation) {
  401. // 如果最近会话不存在,则创建一个空的会话
  402. WKSDK.shared().conversationManager.createEmptyConversation(_channel)
  403. isNewTalk.value = true
  404. }
  405. return {
  406. channel: _channel,
  407. isNewTalk: isNewTalk.value
  408. }
  409. }