useIM.js 12 KB

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