useIM.js 11 KB

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