useIM.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  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. // 通过自身userId和企业id获取token和uid
  148. await resetConfig()
  149. // 连接状态监听
  150. WKSDK.shared().connectManager.addConnectStatusListener(connectStatusListener)
  151. // 常规消息监听
  152. WKSDK.shared().chatManager.addMessageListener(messageListen)
  153. // 连接
  154. WKSDK.shared().connectManager.connect()
  155. })
  156. onUnmounted(() => {
  157. WKSDK.shared().connectManager.removeConnectStatusListener(connectStatusListener)
  158. // 常规消息监听移除
  159. WKSDK.shared().chatManager.removeMessageListener(messageListen)
  160. // 连接状态监听移除
  161. WKSDK.shared().connectManager.disconnect()
  162. })
  163. async function messageListen (message) {
  164. // console.log('收到消息', message)
  165. IM.setFromChannel(message.channel.channelID)
  166. setUnreadCount()
  167. }
  168. async function connectStatusListener (status) {
  169. // console.log('连接状态', status === ConnectStatus.Connected)
  170. // 连接成功 获取点击数
  171. const connected = status === ConnectStatus.Connected
  172. IM.setConnected(connected)
  173. if (connected) {
  174. // 必须同步最近会话才能获取未读总数
  175. await syncConversation()
  176. setUnreadCount()
  177. }
  178. }
  179. function setUnreadCount () {
  180. const count = WKSDK.shared().conversationManager.getAllUnreadCount()
  181. key.value++
  182. IM.setNewMsg(key.value)
  183. IM.setUnreadCount(count)
  184. console.log('未读消息总数', count)
  185. }
  186. async function resetConfig () {
  187. const { uid, wssUrl, token } = await getKey()
  188. IM.setUid(uid)
  189. // 单机模式可以直接设置地址
  190. WKSDK.shared().config.addr = 'wss://' + wssUrl// 默认端口为5200 + wsUrl
  191. // 认证信息
  192. WKSDK.shared().config.uid = uid // 用户uid(需要在悟空通讯端注册过)
  193. WKSDK.shared().config.token = token // 用户token (需要在悟空通讯端注册过)
  194. }
  195. return {
  196. resetConfig
  197. }
  198. }
  199. export function initConnect (callback = () => {}, mounted = () => {}) {
  200. useDataSource()
  201. const IM = useIMStore()
  202. const conversationList = ref([])
  203. const messageItems = ref([])
  204. watch(
  205. () => IM.newMsg,
  206. async () => {
  207. // 未读消息变化
  208. updateConversation()
  209. // 拉取最新消息 查看是否是自己的数据
  210. },
  211. {
  212. deep: true,
  213. immediate: true
  214. }
  215. )
  216. onMounted(async () => {
  217. // 消息发送状态监听
  218. WKSDK.shared().chatManager.addMessageStatusListener(statusListen)
  219. // 常规消息监听
  220. // WKSDK.shared().chatManager.addMessageListener(messageListen)
  221. mounted()
  222. })
  223. onUnmounted(() => {
  224. // 消息发送状态监听移除
  225. WKSDK.shared().chatManager.removeMessageStatusListener(statusListen)
  226. // 常规消息监听移除
  227. // WKSDK.shared().chatManager.removeMessageListener(messageListen)
  228. })
  229. // 消息发送状态监听
  230. function statusListen (packet) {
  231. console.log('发送状态', packet)
  232. if (packet.reasonCode === 1) {
  233. // 发送成功
  234. console.log('发送成功')
  235. // 添加一组成功数据
  236. callback(true)
  237. } else {
  238. // 发送失败
  239. console.log('发送失败')
  240. // 添加一组失败数据
  241. callback(false)
  242. }
  243. }
  244. async function updateConversation () {
  245. const res = await syncConversation()
  246. conversationList.value = res
  247. }
  248. function updateUnreadCount () {
  249. const count = WKSDK.shared().conversationManager.getAllUnreadCount()
  250. IM.setUnreadCount(count)
  251. }
  252. async function deleteConversations (channel, enterpriseId) {
  253. const query = {
  254. channel_id: channel.channelID,
  255. channel_type: channel.channelType,
  256. enterpriseId
  257. }
  258. await deleteConversation(query)
  259. }
  260. async function resetUnread (channel, enterpriseId) {
  261. const query = {
  262. channel_id: channel.channelID,
  263. channel_type: channel.channelType,
  264. enterpriseId,
  265. unread: 0
  266. }
  267. const res = await setUnread(query)
  268. return res
  269. }
  270. return {
  271. resetUnread,
  272. deleteConversations,
  273. updateConversation,
  274. updateUnreadCount,
  275. conversationList,
  276. messageItems,
  277. // channel
  278. }
  279. }
  280. // 同步最近会话
  281. async function syncConversation () {
  282. const res = await WKSDK.shared().conversationManager.sync()
  283. return res
  284. }
  285. // 发起聊天
  286. export async function initChart (userId, enterpriseId) {
  287. const channel = ref()
  288. // const list = ref([])
  289. const query = {
  290. userId,
  291. enterpriseId
  292. }
  293. // 创建聊天频道
  294. const { data } = await getChatKey(query)
  295. const { uid } = data
  296. const _channel = new Channel(uid, ChannelTypePerson)
  297. channel.value = _channel
  298. const conversation = WKSDK.shared().conversationManager.findConversation(_channel)
  299. if(!conversation) {
  300. // 如果最近会话不存在,则创建一个空的会话
  301. WKSDK.shared().conversationManager.createEmptyConversation(_channel)
  302. }
  303. const res = await getMoreMessages(1, _channel)
  304. return {
  305. channel,
  306. ...res
  307. }
  308. }
  309. // 翻页
  310. export async function getMoreMessages (pageSize, channel) {
  311. const list = ref([])
  312. Object.assign(HISTORY_QUERY, {
  313. startMessageSeq: (pageSize - 1) * HISTORY_QUERY.limit
  314. })
  315. const { resultMessages, more } = await WKSDK.shared().chatManager.syncMessages(channel)
  316. list.value = resultMessages
  317. return {
  318. list,
  319. more
  320. }
  321. }
  322. /**
  323. *
  324. * @param {*} text
  325. * @param {*} _channel
  326. * @param { Number } type : 101 面试主体
  327. * @returns
  328. */
  329. // 发送职位使用101
  330. export function send (text, _channel, type) {
  331. let _text
  332. if (contentType[type]) {
  333. _text = new contentType[type](text)
  334. WKSDK.shared().chatManager.send(_text, _channel)
  335. return
  336. }
  337. // if (type === 101) {
  338. // _text = new ObjectContent(text)
  339. // WKSDK.shared().chatManager.send(_text, _channel)
  340. // // console.log(_text)
  341. // return
  342. // }
  343. // if (type === 102) {
  344. // _text = new ObjectContent2(text)
  345. // WKSDK.shared().chatManager.send(_text, _channel)
  346. // // console.log(_text)
  347. // return
  348. // }
  349. // // 求职者拒绝面试邀请
  350. // if (type === 103) {
  351. // _text = new ObjectContent3(text)
  352. // WKSDK.shared().chatManager.send(_text, _channel)
  353. // return
  354. // }
  355. // // 求职者接受面试邀请
  356. // if (type === 104) {
  357. // _text = new ObjectContent4(text)
  358. // WKSDK.shared().chatManager.send(_text, _channel)
  359. // return
  360. // }
  361. _text = new MessageText(text)
  362. // console.log(_text)
  363. WKSDK.shared().chatManager.send(_text, _channel)
  364. }
  365. // 对话开场白 用户 to 企业
  366. export async function prologue ({userId, enterpriseId, text}) {
  367. const { channel } = await checkConversation(userId, enterpriseId)
  368. send(text, channel, 102)
  369. return channel
  370. }
  371. // 企业 to 用户
  372. export async function talkToUser ({userId, text}) {
  373. const { channel, isNewTalk } = await checkConversation(userId)
  374. if (!isNewTalk) send(text, channel)
  375. }
  376. // 检测是否存在频道
  377. export async function checkConversation (userId, enterpriseId) {
  378. const query = {
  379. userId,
  380. enterpriseId
  381. }
  382. // 创建聊天频道
  383. const { data } = await getChatKey(query)
  384. const { uid } = data
  385. const _channel = new Channel(uid, ChannelTypePerson)
  386. console.log('生成channel', _channel)
  387. const conversation = WKSDK.shared().conversationManager.findConversation(_channel)
  388. const isNewTalk = ref(false)
  389. if(!conversation) {
  390. // 如果最近会话不存在,则创建一个空的会话
  391. WKSDK.shared().conversationManager.createEmptyConversation(_channel)
  392. isNewTalk.value = true
  393. }
  394. return {
  395. channel: _channel,
  396. isNewTalk: isNewTalk.value
  397. }
  398. }