useIM.js 11 KB

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