打包chat-im

This commit is contained in:
zdg 2024-08-19 14:21:42 +08:00
parent 4fd47d2f2f
commit 49c4c7245a
12 changed files with 557 additions and 126 deletions

View File

@ -13,6 +13,11 @@ asarUnpack:
win: win:
executableName: AIx executableName: AIx
icon: resources/logo2.ico icon: resources/logo2.ico
extraFiles:
- from: ./node_modules/im_electron_sdk/lib/
- to: ./resources
- filter:
- '**/*'
nsis: nsis:
oneClick: false oneClick: false
allowToChangeInstallationDirectory: true allowToChangeInstallationDirectory: true

View File

@ -3,7 +3,7 @@
*/ */
// import { ipcMain } from 'electron' // import { ipcMain } from 'electron'
// const TimMain = require('im_electron_sdk/dist/main') // const TimMain = require('im_electron_sdk/dist/main')
// import TimMain from 'im_electron_sdk/dist/main' import TimMain from 'im_electron_sdk/dist/main'
// import {TIMErrCode} from 'im_electron_sdk/dist/enumbers' // import {TIMErrCode} from 'im_electron_sdk/dist/enumbers'
const sdkappidDef = 1600034736 // 可以去腾讯云即时通信IM控制台申请 const sdkappidDef = 1600034736 // 可以去腾讯云即时通信IM控制台申请

View File

@ -3,7 +3,7 @@ import { join } from 'path'
import { electronApp, optimizer, is } from '@electron-toolkit/utils' import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import icon from '../../resources/icon.png?asset' import icon from '../../resources/icon.png?asset'
import File from './file' import File from './file'
// import chat from './chat' // chat封装 import chat from './chat' // chat封装
// 代理 electron/remote // 代理 electron/remote
// 第一步引入remote // 第一步引入remote
import remote from '@electron/remote/main' import remote from '@electron/remote/main'
@ -230,14 +230,14 @@ app.on('window-all-closed', () => {
// 监听全局事件 // 监听全局事件
function handleAll() { function handleAll() {
// const chatInstance = chat.initialize() // im-chat 实例 const chatInstance = chat.initialize() // im-chat 实例
// 新窗口创建-监听 // 新窗口创建-监听
ipcMain.on('new-window', (e, data) => { ipcMain.on('new-window', (e, data) => {
const { id, type } = data const { id, type } = data
const win = BrowserWindow.fromId(id) const win = BrowserWindow.fromId(id)
win.type = type // 绑定独立标识 win.type = type // 绑定独立标识
remote.enable(win.webContents) // 开启远程服务 remote.enable(win.webContents) // 开启远程服务
// chatInstance.enable(win.webContents) // 开启im-chat chatInstance.enable(win.webContents) // 开启im-chat
}) })
// 用于监听-状态管理变化-同步所有窗口 // 用于监听-状态管理变化-同步所有窗口
ipcMain.handle('pinia-state-change', (e, storeName, jsonStr) => { ipcMain.handle('pinia-state-change', (e, storeName, jsonStr) => {

View File

@ -1,10 +1,10 @@
import { contextBridge } from 'electron' import { contextBridge } from 'electron'
import { electronAPI } from '@electron-toolkit/preload' import { electronAPI } from '@electron-toolkit/preload'
// import TimRender from 'im_electron_sdk/dist/renderer' // im渲染部分实例 import TimRender from 'im_electron_sdk/dist/renderer' // im渲染部分实例
// Custom APIs for renderer // Custom APIs for renderer
const api = { const api = {
preloadPath: __dirname, // 当前preload地址 preloadPath: __dirname, // 当前preload地址
// getTimRender: () => new TimRender(), // im渲染部分实例 getTimRender: () => new TimRender(), // im渲染部分实例
} }
// Use `contextBridge` APIs to expose Electron APIs to // Use `contextBridge` APIs to expose Electron APIs to
// renderer only if context isolation is enabled, otherwise // renderer only if context isolation is enabled, otherwise

View File

@ -0,0 +1,420 @@
/**
* @description im 事件监听
* @author zdg
* @date 2023-07-07
*/
// @ts-ignore
const API = window?.api || {}
const timRenderInstance = API.getTimRender()
// im 事件监听
export class IMListeners {
// 初始化监听
static initListeners(callback) {
/**
* 注销消息监听事件
*/
timRenderInstance.TIMRemoveRecvNewMsgCallback()
/**
* @brief 增加接收新消息回调
* @param cb 新消息回调函数请参考[TIMRecvNewMsgCallback](TIMCloudCallback.h)
* @param user_data 用户自定义数据ImSDK只负责传回给回调函数cb不做任何处理
*
* @note
* 如果用户是登录状态ImSDK收到新消息会通过此接口设置的回调抛出另外需要注意抛出的消息不一定是未读的消息
* 只是本地曾经没有过的消息例如在另外一个终端已读拉取最近联系人消息时可以获取会话最后一条消息如果本地没有会通过此方法抛出
* 在用户登录之后ImSDK会拉取离线消息为了不漏掉消息通知需要在登录之前注册新消息通知
*/
timRenderInstance.TIMAddRecvNewMsgCallback({
callback:(args)=>{
callback({
type: 'TIMAddRecvNewMsgCallback',
data: JSON.parse(args[0])
})
},
user_data: "test"
})
/**
* @brief 1.3 设置消息已读回执回调
* @param cb 消息已读回执回调请参考[TIMMsgReadedReceiptCallback](TIMCloudCallback.h)
* @param user_data 用户自定义数据ImSDK只负责传回给回调函数cb不做任何处理
*
* @note
* 发送方发送消息接收方调用接口[TIMMsgReportReaded]()上报该消息已读发送方ImSDK会通过此接口设置的回调抛出
*/
timRenderInstance.TIMSetMsgReadedReceiptCallback({
callback:(args)=>{
callback({
type: 'TIMSetMsgReadedReceiptCallback',
data: JSON.parse(args[0])
})
},
user_data: "test"
})
/**
* @brief 1.4 设置接收的消息被撤回回调
* @param cb 消息撤回通知回调,请参考[TIMMsgRevokeCallback](TIMCloudCallback.h)
* @param user_data 用户自定义数据ImSDK只负责传回给回调函数cb不做任何处理
*
* @note
* 发送方发送消息接收方收到消息此时发送方调用接口[TIMMsgRevoke]()撤回该消息接收方的ImSDK会通过此接口设置的回调抛出
*/
timRenderInstance.TIMSetMsgRevokeCallback({
callback:(args)=>{
callback({
type: 'TIMSetMsgRevokeCallback',
data: JSON.parse(args[0])
});
},
user_data: "test"
})
/**
* @brief 1.5 设置消息内元素相关文件上传进度回调
* @param cb 文件上传进度回调请参考[TIMMsgElemUploadProgressCallback](TIMCloudCallback.h)
* @param user_data 用户自定义数据ImSDK只负责传回给回调函数cb不做任何处理
*
* @note
* 设置消息元素上传进度回调当消息内包含图片声音文件视频元素时ImSDK会上传这些文件并触发此接口设置的回调用户可以根据回调感知上传的进度
*/
timRenderInstance.TIMSetMsgElemUploadProgressCallback({
callback:(args)=>{
try{
const [message, index, cur_size, total_size, user_data] = JSON.parse(args)
callback({
type: 'TIMSetMsgElemUploadProgressCallback',
data: {
message: JSON.parse(message),
index,
cur_size,
total_size,
user_data
}
})
}catch(err){
throw err;
}
},
user_data: "test"
})
/**
* @brief 1.6 设置群组系统消息回调
* @param cb 群消息回调请参考[TIMGroupTipsEventCallback](TIMCloudCallback.h)
* @param user_data 用户自定义数据ImSDK只负责传回给回调函数cb不做任何处理
*
* @note
* 群组系统消息事件包括 加入群退出群踢出群设置管理员取消管理员群资料变更群成员资料变更此消息是针对所有群组成员下发的
*/
timRenderInstance.TIMSetGroupTipsEventCallback({
callback:(args)=>{
callback({
type: 'TIMSetGroupTipsEventCallback',
data: JSON.parse(args[0])
})
},
})
/**
* @brief 1.7 设置群组属性变更回调
* @param cb 群组属性变更回调请参考[TIMGroupAttributeChangedCallback](TIMCloudCallback.h)
* @param user_data 用户自定义数据ImSDK只负责传回给回调函数cb不做任何处理
*
* @note
* 某个已加入的群的属性被修改了会返回所在群组的所有属性该群所有的成员都能收到
*/
timRenderInstance.TIMSetGroupAttributeChangedCallback({
callback: (...args) => {callback({ type: 'TIMSetGroupAttributeChangedCallback', data: args })},
userData: ""
})
/**
* @brief 1.8 设置会话事件回调
* @param cb 会话事件回调请参考[TIMConvEventCallback](TIMCloudCallback.h)
* @param user_data 用户自定义数据ImSDK只负责传回给回调函数cb不做任何处理
*
* @note
* > 会话事件包括
* >> 会话新增
* >> 会话删除
* >> 会话更新
* >> 会话开始
* >> 会话结束
* > 任何产生一个新会话的操作都会触发会话新增事件例如调用接口[TIMConvCreate]()创建会话接收到未知会话的第一条消息等
* 任何已有会话变化的操作都会触发会话更新事件例如收到会话新消息消息撤回已读上报等
* 调用接口[TIMConvDelete]()删除会话成功时会触发会话删除事件
*/
timRenderInstance.TIMSetConvEventCallback({
callback:(args)=>{
callback({
type: 'TIMSetConvEventCallback',
data: {
type:args[0],
data:args[1]!=="" ? JSON.parse(args[1]) : []
}
})
},
user_data:"TIMSetConvEventCallback"
})
/**
* @brief 1.9 设置会话未读消息总数变更的回调
* @param cb 会话未读消息总数变更的回调请参考[TIMConvTotalUnreadMessageCountChangedCallback](TIMCloudCallback.h)
* @param user_data 用户自定义数据ImSDK只负责传回给回调函数cb不做任何处理
*
*/
timRenderInstance.TIMSetConvTotalUnreadMessageCountChangedCallback({
callback:(args)=>{
callback({
type: 'TIMSetConvTotalUnreadMessageCountChangedCallback',
data: args[0]
})
}
})
/**
* @brief 1.10 设置网络连接状态监听回调
* @param cb 连接事件回调请参考[TIMNetworkStatusListenerCallback](TIMCloudCallback.h)
* @param user_data 用户自定义数据ImSDK只负责传回给回调函数cb不做任何处理
*
* @note
* > 当调用接口 [TIMInit]() ImSDK会去连接云后台此接口设置的回调用于监听网络连接的状态
* > 网络连接状态包含四个正在连接连接失败连接成功已连接这里的网络事件不表示用户本地网络状态仅指明ImSDK是否与即时通信IM云Server连接状态
* > 可选设置如果要用户感知是否已经连接服务器需要设置此回调用于通知调用者跟通讯后台链接的连接和断开事件另外如果断开网络等网络恢复后会自动重连自动拉取消息通知用户用户无需关心网络状态仅作通知之用
* > 只要用户处于登录状态ImSDK内部会进行断网重连用户无需关心
*/
timRenderInstance.TIMSetNetworkStatusListenerCallback({
callback: (...args) => {callback({ type: 'TIMSetNetworkStatusListenerCallback', data: args })},
userData: ""
})
/**
* @brief 1.11 设置被踢下线通知回调
* @param cb 踢下线回调请参考[TIMKickedOfflineCallback](TIMCloudCallback.h)
* @param user_data 用户自定义数据ImSDK只负责传回给回调函数cb不做任何处理
*
* @note
* > 用户如果在其他终端登录会被踢下线这时会收到用户被踢下线的通知出现这种情况常规的做法是提示用户进行操作退出或者再次把对方踢下线
* > 用户如果在离线状态下被踢下次登录将会失败可以给用户一个非常强的提醒登录错误码ERR_IMSDK_KICKED_BY_OTHERS6208开发者也可以选择忽略这次错误再次登录即可
* > 用户在线情况下的互踢情况
* + 用户在设备1登录保持在线状态下该用户又在设备2登录这时用户会在设备1上强制下线收到 TIMKickedOfflineCallback 回调
* 用户在设备1上收到回调后提示用户可继续调用login上线强制设备2下线这里是在线情况下互踢过程
* > 用户离线状态互踢:
* + 用户在设备1登录没有进行logout情况下进程退出该用户在设备2登录此时由于用户不在线无法感知此事件
* 为了显式提醒用户避免无感知的互踢用户在设备1重新登录时会返回ERR_IMSDK_KICKED_BY_OTHERS6208错误码表明之前被踢是否需要把对方踢下线
* 如果需要则再次调用login强制上线设备2的登录的实例将会收到 TIMKickedOfflineCallback 回调
*/
timRenderInstance.TIMSetKickedOfflineCallback({
callback: (...args) => {
callback({
type: 'TIMSetKickedOfflineCallback',
data: args
});
},
userData: ""
})
/**
* @brief 1.12 设置票据过期回调
* @param cb 票据过期回调请参考[TIMUserSigExpiredCallback](TIMCloudCallback.h)
* @param user_data 用户自定义数据ImSDK只负责传回给回调函数cb不做任何处理
*
* @note
* 用户票据可能会存在过期的情况如果用户票据过期此接口设置的回调会调用
* [TIMLogin]()也将会返回70001错误码开发者可根据错误码或者票据过期回调进行票据更换
*/
timRenderInstance.TIMSetUserSigExpiredCallback({
callback: (...args) => {callback({ type: 'TIMSetUserSigExpiredCallback', data: args })},
userData: ""
})
/**
* @brief 1.13 设置添加好友的回调
* @param cb 添加好友回调请参考[TIMOnAddFriendCallback](TIMCloudCallback.h)
* @param user_data 用户自定义数据ImSDK只负责传回给回调函数cb不做任何处理
*
* @note
* 此回调为了多终端同步例如A设备B设备都登录了同一帐号的ImSDKA设备添加了好友B设备ImSDK会收到添加好友的推送ImSDK通过此回调告知开发者
*/
timRenderInstance.TIMSetOnAddFriendCallback({
callback: (...args) => {
console.log('=====添加好友=====', args)
callback({ type: 'TIMSetOnAddFriendCallback', data: args })
},
userData: ""
})
/**
* @brief 1.14 设置删除好友的回调
* @param cb 删除好友回调请参考[TIMOnDeleteFriendCallback](TIMCloudCallback.h)
* @param user_data 用户自定义数据ImSDK只负责传回给回调函数cb不做任何处理
*
* @note
* 此回调为了多终端同步例如A设备B设备都登录了同一帐号的ImSDKA设备删除了好友B设备ImSDK会收到删除好友的推送ImSDK通过此回调告知开发者
*/
timRenderInstance.TIMSetOnDeleteFriendCallback({
callback: (...args) => {callback({ type: 'TIMSetOnDeleteFriendCallback', data: args })},
userData: ""
})
/**
* @brief 1.15 设置更新好友资料的回调
* @param cb 更新好友资料回调请参考[TIMUpdateFriendProfileCallback](TIMCloudCallback.h)
* @param user_data 用户自定义数据ImSDK只负责传回给回调函数cb不做任何处理
*
* @note
* 此回调为了多终端同步例如A设备B设备都登录了同一帐号的ImSDKA设备更新了好友资料B设备ImSDK会收到更新好友资料的推送ImSDK通过此回调告知开发者
*/
timRenderInstance.TIMSetUpdateFriendProfileCallback({
callback: (...args) => {callback({ type: 'TIMSetUpdateFriendProfileCallback', data: args })},
userData: ""
})
/**
* @brief 1.16 设置好友添加请求的回调
* @param cb 好友添加请求回调请参考[TIMFriendAddRequestCallback](TIMCloudCallback.h)
* @param user_data 用户自定义数据ImSDK只负责传回给回调函数cb不做任何处理
*
* @note
* 当前登入用户设置添加好友需要确认时如果有用户请求加当前登入用户为好友会收到好友添加请求的回调ImSDK通过此回调告知开发者如果多终端登入同一帐号每个终端都会收到这个回调
*/
timRenderInstance.TIMSetFriendAddRequestCallback({
callback: (...args) => {
console.log('=====添加好友请求=====', JSON.parse(args[0][0]));
callback({
type: 'TIMSetFriendAddRequestCallback',
data: JSON.parse(args[0][0])
})
},
userData: ""
})
/**
* @brief 1.17 设置好友申请删除的回调
* @param cb 好友申请删除回调请参考[TIMFriendApplicationListDeletedCallback](TIMCloudCallback.h)
* @param user_data 用户自定义数据ImSDK只负责传回给回调函数cb不做任何处理
*
* @note
* 1. 主动删除好友申请
* 2. 拒绝好友申请
* 3. 同意好友申请
* 4. 申请加别人好友被拒绝
*/
timRenderInstance.TIMSetFriendApplicationListDeletedCallback({
callback: (...args) => {callback({ type: 'TIMSetFriendApplicationListDeletedCallback', data: args })},
userData: ""
})
/**
* @brief 1.18 设置好友申请已读的回调
* @param cb 好友申请已读回调请参考[TIMFriendApplicationListReadCallback](TIMCloudCallback.h)
* @param user_data 用户自定义数据ImSDK只负责传回给回调函数cb不做任何处理
*
* @note
* 如果调用 setFriendApplicationRead 设置好友申请列表已读会收到这个回调主要用于多端同步
*/
timRenderInstance.TIMSetFriendApplicationListReadCallback({
callback: (...args) => {callback({ type: 'TIMSetFriendApplicationListReadCallback', data: args })},
userData: ""
})
/**
* @brief 1.19 设置黑名单新增的回调
* @param cb 黑名单新增的回调请参考[TIMFriendBlackListAddedCallback](TIMCloudCallback.h)
* @param user_data 用户自定义数据ImSDK只负责传回给回调函数cb不做任何处理
*
*/
timRenderInstance.TIMSetFriendBlackListAddedCallback({
callback: (...args) => {callback({ type: 'TIMSetFriendBlackListAddedCallback', data: args })},
userData: ""
})
/**
* @brief 1.20 设置黑名单删除的回调
* @param cb 黑名单删除的回调请参考[TIMFriendBlackListDeletedCallback](TIMCloudCallback.h)
* @param user_data 用户自定义数据ImSDK只负责传回给回调函数cb不做任何处理
*
*/
timRenderInstance.TIMSetFriendBlackListDeletedCallback({
callback: (...args) => {callback({ type: 'TIMSetFriendBlackListDeletedCallback', data: args })},
userData: ""
})
/**
* @brief 1.22 设置消息在云端被修改后回传回来的消息更新通知回调
* @param cb 消息更新回调请参考[TIMMsgUpdateCallback](TIMCloudCallback.h)
* @param user_data 用户自定义数据ImSDK只负责传回给回调函数cb不做任何处理
*
* @note
* > 当您发送的消息在服务端被修改后ImSDK会通过该回调通知给您
* > 您可以在您自己的服务器上拦截所有即时通信IM消息 [发单聊消息之前回调](https://cloud.tencent.com/document/product/269/1632)
* > 设置成功之后即时通信IM服务器会将您的用户发送的每条消息都同步地通知给您的业务服务器
* > 您的业务服务器可以对该条消息进行修改例如过滤敏感词如果您的服务器对消息进行了修改ImSDK就会通过此回调通知您
*/
timRenderInstance.TIMSetMsgUpdateCallback({
callback: (...args) => {callback({ type: 'TIMSetMsgUpdateCallback', data: args })},
userData: ""
})
timRenderInstance.TIMOnInvited({
callback:(data)=>{
callback({
type: 'TIMOnInvited',
data: data
})
}
})
timRenderInstance.TIMOnRejected({
callback:(data)=>{
callback({
type: 'TIMOnRejected',
data: data
})
}
})
timRenderInstance.TIMOnAccepted({
callback:(data)=>{
callback({
type: 'TIMOnAccepted',
data: data
})
}
})
timRenderInstance.TIMOnCancelled({
callback:(data)=>{
callback({
type: 'TIMOnCancelled',
data: data
})
}
})
timRenderInstance.TIMOnTimeout({
callback:(data)=>{
callback({
type: 'TIMOnTimeout',
data: data
})
}
})
}
}
export default { timRenderInstance, initListeners: IMListeners.initListeners }

View File

@ -8,6 +8,7 @@
// const TimRender = require('im_electron_sdk/dist/render') // const TimRender = require('im_electron_sdk/dist/render')
import * as TYPES from './enumbers' // sdk相关枚举 import * as TYPES from './enumbers' // sdk相关枚举
import MsgEnum from './msgEnum' // 消息相关枚举(自定义) import MsgEnum from './msgEnum' // 消息相关枚举(自定义)
import IMListeners from './imLiseners' // im消息-监听器
const API = window.api const API = window.api
// TIM生成签名 // TIM生成签名
// import * as GenerateUserSig from './userSig' // 引入签名生成器 // import * as GenerateUserSig from './userSig' // 引入签名生成器
@ -73,14 +74,18 @@ export class ImChat {
return new Promise(async(resolve, reject) => { return new Promise(async(resolve, reject) => {
try { try {
if(!API) reject('preload api获取失败, 初始化-未完成') if(!API) reject('preload api获取失败, 初始化-未完成')
this.timChat = await API.getTimRender() // this.timChat = await API.getTimRender()
await this.timChat.TIMInit({ this.timChat = IMListeners.timRenderInstance
// electron_log:true, const code = await this.timChat.TIMInit()
}) if (code == 0) { // 初始化成功
console.log('[im-chat]:初始化成功') this.setConsole('%cim-chat: init', '初始化成功')
this.status.isConnect = true this.status.isConnect = true
this.setConfig() // 设置日志级别 this.setConfig() // 设置日志级别
resolve(this) resolve(this)
} else { // 失败具体请看code
console.error('[im-chat]:初始化失败', code)
reject(code)
}
} catch (error) {reject(error)} } catch (error) {reject(error)}
}) })
} }
@ -96,21 +101,27 @@ export class ImChat {
} }
// 监听 // 监听
watch(callback) { watch(callback) {
// 先移除监听 // // 先移除监听
this.timChat.TIMRemoveRecvNewMsgCallback() // this.timChat.TIMRemoveRecvNewMsgCallback()
// 消息监听 // // 消息监听
this.timChat.TIMAddRecvNewMsgCallback({ // this.timChat.TIMAddRecvNewMsgCallback({
callback, user_data: this.toStr('msg') // callback, user_data: this.toStr('msg')
}) // })
// 群消息监听 // // 群消息监听
// 群组系统消息事件包括 加入群、退出群、踢出群、设置管理员、取消管理员、群资料变更、群成员资料变更。此消息是针对所有群组成员下发的 // // 群组系统消息事件包括 加入群、退出群、踢出群、设置管理员、取消管理员、群资料变更、群成员资料变更。此消息是针对所有群组成员下发的
this.timChat.TIMSetGroupTipsEventCallback({ // this.timChat.TIMSetGroupTipsEventCallback({
// callback, user_data: this.toStr('msg-group') // // callback, user_data: this.toStr('msg-group')
callback: (data) => { // callback: (data) => {
// console.log('群消息', group_tips_event) // // console.log('群消息', group_tips_event)
this.setConsole('%c群消息', data) // this.setConsole('%c群消息', data)
}, // },
}) // })
if (this.timChat && this.status.isConnect) { // 连接成功允许监听
this.setConsole('%cim-chat: watch', '监听成功')
IMListeners.initListeners(callback)
} else {
this.setConsole('%cim-chat: watch', '监听失败, 未连接')
}
} }
// 登录 // 登录
login() { login() {
@ -127,18 +138,19 @@ export class ImChat {
const res = await this.timChat.TIMLogin(option) const res = await this.timChat.TIMLogin(option)
if (res && res.code == 0) { if (res && res.code == 0) {
// console.log('登录成功', res) // console.log('登录成功', res)
this.setConsole('%cim-chat: login', '登录成功')
this.status.isLogin = true this.status.isLogin = true
resolve({status:0, msg:'登录成功', data:res}) resolve({status:0, msg:'登录成功', data:res})
} else reject(res) } else reject(res)
} else { } else {
if (status == 1) { // 已登录 if (status == 1) { // 已登录
console.log('已登录') this.setConsole('%cim-chat: login', '已登录')
resolve({status, msg:'已登录'}) resolve({status, msg:'已登录'})
} else if (status == 2) { // 登录中 } else if (status == 2) { // 登录中
console.log('登录中') this.setConsole('%cim-chat: login', '登录中')
resolve({status, msg:'登录中'}) resolve({status, msg:'登录中'})
} else if (status == 4) { // 登出中 } else if (status == 4) { // 登出中
console.log('登出中') this.setConsole('%cim-chat: login', '登出中')
resolve({status, msg:'登出中'}) resolve({status, msg:'登出中'})
} }
} }
@ -189,9 +201,10 @@ export class ImChat {
// @TGS#3XVNI6ZOG // @TGS#3XVNI6ZOG
return this.timChat.TIMGroupCreate(option).then(res => { return this.timChat.TIMGroupCreate(option).then(res => {
if (res && res.code == 0) { if (res && res.code == 0) {
this.setConsole('%c创建群组成功', res)
const timGroupId = res?.json_param?.create_group_result_groupid const timGroupId = res?.json_param?.create_group_result_groupid
if (!!timGroupId && timGroupId != 'undefined'){ if (!!timGroupId && timGroupId != 'undefined'){
this.setConsole('%c创建群组成功', timGroupId) // this.setConsole('%c创建群组成功', timGroupId)
this.timGroupId = timGroupId this.timGroupId = timGroupId
// this.setGroupMsgReceive() // this.setGroupMsgReceive()
} }

File diff suppressed because one or more lines are too long

View File

@ -1,44 +0,0 @@
/**
* @description: 生成签名|客户端计算 UserSig
* @author: zdg
* @date 2021-07-05 14:07:01
*/
// TIM生成签名
import LibGenerateTestUserSig from './lib-generate-test-usersig-es.min.js';
/**
* Signature expiration time, which should not be too short
* Time unit: second
* Default time: 7 * 24 * 60 * 60 = 604800 = 7days
*/
const EXPIRETIME = 604800;
/**
* Module: GenerateTestUserSig
*
* Description: Generates UserSig for testing. UserSig is a security signature designed by Tencent Cloud for its cloud services.
* It is calculated based on `SDKAppID`, `UserID`, and `EXPIRETIME` using the HMAC-SHA256 encryption algorithm.
*
* Attention: For the following reasons, do not use the code below in your commercial application.
*
* The code may be able to calculate UserSig correctly, but it is only for quick testing of the SDKs basic features, not for commercial applications.
* `SECRETKEY` in client code can be easily decompiled and reversed, especially on web.
* Once your key is disclosed, attackers will be able to steal your Tencent Cloud traffic.
*
* The correct method is to deploy the `UserSig` calculation code and encryption key on your project server so that your application can request from your server a `UserSig` that is calculated whenever one is needed.
* Given that it is more difficult to hack a server than a client application, server-end calculation can better protect your key.
*
* Reference: https://cloud.tencent.com/document/product/647/17275#Server
*/
function genTestUserSig(options) {
const { SDKAppID, secretKey, userID } = options;
const generator = new LibGenerateTestUserSig(SDKAppID, secretKey, EXPIRETIME);
const userSig = generator.genTestUserSig(userID);
return {
SDKAppID,
userSig,
};
}
export { genTestUserSig, EXPIRETIME };

View File

@ -12,7 +12,7 @@ export function shareStorePlugin({store}) {
// console.log('store.$subscribe', mutation) // console.log('store.$subscribe', mutation)
// 在存储变化的时候执行 // 在存储变化的时候执行
// const storeName = store.$id // const storeName = store.$id
// const storeName = mutation.storeId const storeName = mutation.storeId
// 用于多窗口共享(需要共享的状态名称) // 用于多窗口共享(需要共享的状态名称)
const names = ['tool'] const names = ['tool']
if (names.includes(storeName)) { if (names.includes(storeName)) {
@ -36,11 +36,15 @@ export function shareStorePlugin({store}) {
// 同步数据-发送给主线程-单独 // 同步数据-发送给主线程-单独
function stateSync(storeName, key, value) { function stateSync(storeName, key, value) {
// console.log('state-change', storeName, key, value) // console.log('state-change', storeName, key, value)
let jsonStr = '' try {
if (typeof key === 'string') jsonStr = JSON.stringify({[key]:value}) let jsonStr = ''
else if (typeof value === 'object') jsonStr = JSON.stringify(key) if (typeof key === 'string') jsonStr = JSON.stringify({[key]:value})
// 通知主线程更新 else if (typeof value === 'object') jsonStr = JSON.stringify(key)
ipcRenderer?.invoke('pinia-state-change', storeName, jsonStr) // 通知主线程更新
ipcRenderer?.invoke('pinia-state-change', storeName, jsonStr)
} catch (error) {
console.log('state-change-error', error)
}
} }
// 同步数据-发送给主线程-全量更新 // 同步数据-发送给主线程-全量更新

View File

@ -190,7 +190,11 @@ export function toolWindow({url, isConsole, isWeb=true, option={}}) {
// 内部监听器-是否打印 // 内部监听器-是否打印
if (!!isConsole) { if (!!isConsole) {
win.webContents.on('console-message', (e,leve,m,lin,s) => { win.webContents.on('console-message', (e,leve,m,lin,s) => {
console.log(`[${win.type}]`,m) console.log(m)
if(m.startsWith('%c')){ // 特殊打印
const arr = m.match(/(%c[^ ]+)(?:\s+(.*;))(.*)/)
console.log(arr[1],arr[2],arr[3])
} else console.log(`[${win.type}]`,m)
}) })
} }
}) })
@ -248,12 +252,12 @@ const eventHandles = (type, win) => {
} }
} }
const taskHandles = () => { // const taskHandles = () => {
// // 设置任务栏上下文菜单 // // 设置任务栏上下文菜单
// const contextMenu = new Remote.Menu() // const contextMenu = new Remote.Menu()
// contextMenu.append(new Remote.MenuItem({ // contextMenu.append(new Remote.MenuItem({
// label: '关闭', // label: '关闭',
// click: () => {Remote.app.quit()} // click: () => {Remote.app.quit()}
// })) // }))
} // }

View File

@ -13,10 +13,10 @@ const props = defineProps({
const imChatObj = reactive({imChat:null}) const imChatObj = reactive({imChat:null})
onMounted(() => { onMounted(() => {
// console.log(imChatObj) // console.log(imChatObj)
initImChat() // initImChat()
}) })
// im-chat // im-chat
const initImChat = async () => { const initImChat = async (timGroupId) => {
// console.log('im-chat', userStore.user.timuserid) // console.log('im-chat', userStore.user.timuserid)
try { try {
const { timuserid, deptId, userId } = userStore.user const { timuserid, deptId, userId } = userStore.user
@ -35,25 +35,55 @@ const initImChat = async () => {
await imChatObj.imChat.login() await imChatObj.imChat.login()
// im-chat // im-chat
imChatObj.imChat.watch((res) => { imChatObj.imChat.watch((res) => {
const [msg] = res[0]?JSON.parse(res[0]):[] imChatObj.imChat.setConsole('%cchat-msg', res)
imChatObj.imChat.setConsole('%cchat-msg', msg) msgHandle(res) //
//
if(msg.message_sender == '@TIM#SYSTEM'){
emits('change', 'msg-system', null, msg)
} else { // -
(msg?.message_elem_array||[]).forEach(o => {
const msgData = !!o.text_elem_content ? JSON.parse(o.text_elem_content)||'' : ''
emits('change', 'msg', msgData, msg)
})
}
}) })
// //
if (props.isGroup) await createGroup(groupName) if (!timGroupId||props.isGroup) { //
await createGroup(groupName)
} else { // -id
imChatObj.imChat.timGroupId = timGroupId
}
return imChatObj.imChat
} }
} catch (error) { } catch (error) {
console.log('im-error: ', error) console.log('im-error: ', error)
} }
} }
//
const msgHandle = (msg) => {
const { type, data } = msg
switch(type) {
case 'TIMAddRecvNewMsgCallback': // data=[]
{
(data||[]).forEach(o => {
const msgArr = o?.message_elem_array||[]
msgArr.forEach(info => {
const msgType = info?.elem_type // TIMElemType
const msgData = !!info.text_elem_content ? JSON.parse(info.text_elem_content)||'' : ''
emits('change', 'msg', msgData, o, type, msgType)
})
})
}
break
case 'TIMSetConvEventCallback': // data = {data,type}
{
const convArr = data.data || []
convArr.forEach(o => {
const msgArr = o?.conv_last_msg?.message_elem_array||[]
msgArr.forEach(info => {
const msgType = info?.elem_type // TIMElemType
const msgData = !!info.text_elem_content ? JSON.parse(info.text_elem_content)||'' : ''
emits('change', 'msg', msgData, o?.conv_last_msg, type, msgType)
})
})
}
emits('change', 'msg-conv', msg)
break
}
//
emits('change', 'msgDef', msg)
}
// //
const createGroup = async (groupName) => { const createGroup = async (groupName) => {
if (!imChatObj.imChat) return if (!imChatObj.imChat) return
@ -65,7 +95,7 @@ const logout = () => imChatObj.imChat?.logout()
// //
const deleteGroup = () => imChatObj.imChat?.deleteGroup() const deleteGroup = () => imChatObj.imChat?.deleteGroup()
defineExpose({ logout, deleteGroup, imChatObj }) defineExpose({ initImChat, logout, deleteGroup, imChatObj })
</script> </script>
<template> <template>

View File

@ -10,7 +10,7 @@
<upvote-vue ref="upvoteRef"></upvote-vue> <upvote-vue ref="upvoteRef"></upvote-vue>
<!-- im-chat 聊天组件 --> <!-- im-chat 聊天组件 -->
<!-- <im-chat ref="imChatRef" @change="chatChange" /> --> <im-chat ref="imChatRef" @change="chatChange" />
<!-- 底部工具栏 --> <!-- 底部工具栏 -->
<div class="tool-bottom-all" @mouseenter="mouseChange(0)" @mouseleave="mouseChange(1)"> <div class="tool-bottom-all" @mouseenter="mouseChange(0)" @mouseleave="mouseChange(1)">
@ -66,6 +66,7 @@ const classObj = reactive({ // 课程相关
id: route.query.reservId, // id id: route.query.reservId, // id
data: {} // data: {} //
}) })
const msgIds = [] // id
const btnList = [ // const btnList = [ //
{ label: '选择', value: 'select', icon: 'icon-mouse' }, { label: '选择', value: 'select', icon: 'icon-mouse' },
{ label: '画笔', value: 'brush', icon: 'icon-huabi' }, { label: '画笔', value: 'brush', icon: 'icon-huabi' },
@ -77,9 +78,9 @@ const btnList = [ // 工具栏按钮列表
] ]
// === === // === ===
onMounted(async() => { onMounted(async() => {
getClassInfo() // ex3
setTimeout(() => { setTimeout(() => {
classManageApi.startClass(classObj.id) // - // classManageApi.startClass(classObj.id) // -
// getClassInfo() // ex3
resetStatus() // - resetStatus() // -
}, 200); }, 200);
}) })
@ -89,16 +90,12 @@ onMounted(async() => {
const getClassInfo = async () => { const getClassInfo = async () => {
const { data } = await classManageApi.getClassInfo(classObj.id) const { data } = await classManageApi.getClassInfo(classObj.id)
classObj.data = data classObj.data = data
// console.log('classObj:', classObj) // id
if(!data.ex3 || data.ex3 == 'undefined') { // let timGroupId = data?.ex3 && data?.ex3 != 'undefined' ? data.ex3: ''
await imChatRef.value.imChatObj.imChat.createGroup(data.className) console.log('timGroupId:', timGroupId)
const timGroupId = imChatRef.value.imChatObj.imChat.timGroupId const chat = await imChatRef.value?.initImChat(timGroupId) // im-chat
classManageApi.startClass(classObj.id, timGroupId) // if (!timGroupId) timGroupId = chat.timGroupId
} else { // classManageApi.startClass(classObj.id, timGroupId) //
console.log('已创建群: ', data.ex3)
imChatRef.value.imChatObj.imChat.timGroupId = data.ex3
// imChatRef.value.imChatObj.imChat.setGroupMsgReceive(data.ex3)
}
} }
// tab-change // tab-change
const tabChange = (val) => { const tabChange = (val) => {
@ -121,17 +118,21 @@ const mouseChange = (bool) => {
setIgnore(resBool) setIgnore(resBool)
} }
// im-chat: {type, data} // im-chat: {type, data}
const chatChange = (type, data) => { const chatChange = (type, data, ...args) => {
if (type == 'createGroup') { // - if (type == 'createGroup') { // -
console.log('创建群:', data) console.log('创建群:', data)
!!data && classManageApi.startClass(classObj.id, data) !!data && classManageApi.startClass(classObj.id, data)
} else if (type == 'msg') { // im-chat } else if (type == 'msg') { // im-chat
if (!data) return // msg if (!data) return // msg message_msg_id
const msgId = (args||[])[0].message_msg_id
const { msgKey:head, msgcontent:msg, senduserid:sendId, msgType } = data const { msgKey:head, msgcontent:msg, senduserid:sendId, msgType } = data
switch(head) { switch(head) {
case MsgEnum.HEADS.MSG_0001: case MsgEnum.HEADS.MSG_0001:
// console.log(':', data) // console.log(':', data)
if(msgIds.includes(msgId)) return
upvoteRef.value.trigger() upvoteRef.value.trigger()
if (msgIds.length >= 100) msgIds.shift() //
msgIds.push(msgId) //
break break
default: default:
console.log('未知消息:', data) console.log('未知消息:', data)
@ -188,11 +189,11 @@ const sideChange = async o => {
setTimeout(async() => { setTimeout(async() => {
// elMsg.close() // elMsg.close()
toolStore.isToolWin = false toolStore.isToolWin = false
await classManageApi.endClass(route.query.reservId)
await imChatRef.value?.deleteGroup() // await imChatRef.value?.deleteGroup() //
await imChatRef.value?.logout() // 退im await imChatRef.value?.logout() // 退im
await classManageApi.endClass(route.query.reservId)
ipcMsgSend('tool-sphere:close') // ipcMsgSend('tool-sphere:close') //
}, 200); }, 500);
// isOver.value = false // isOver.value = false
// setIgnore(true) // -穿 // setIgnore(true) // -穿