qq-official-bot
Version:
201 lines (200 loc) • 7.24 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SessionManager = exports.MAX_RETRY = void 0;
const events_1 = require("events");
const constants_1 = require("./constants");
// 导入重构后的管理器
const connection_manager_1 = require("./connection/connection-manager");
const auth_manager_1 = require("./auth/auth-manager");
// 向后兼容的导入
const webhook_1 = require("./receivers/webhook");
const WebSocketReceiver_1 = require("./receivers/WebSocketReceiver"); // 使用新的工厂函数
exports.MAX_RETRY = 10;
/**
* 重构后的会话管理器
* 现在作为连接管理、认证管理和接收器管理的协调者
*/
class SessionManager extends events_1.EventEmitter {
// 保持向后兼容的公共属性
get access_token() {
return this.authManager.getCurrentTokenInfo()?.access_token || "";
}
get wsUrl() {
return this._wsUrl || "";
}
get retry() {
return this.connectionManager.getConnectionState().retry;
}
get alive() {
return this.connectionManager.isAlive();
}
get sessionRecord() {
const state = this.connectionManager.getConnectionState();
return {
sessionID: state.sessionID,
seq: state.seq
};
}
get heartbeatParam() {
return this._heartbeatParam;
}
// 公共方法访问 bot 实例(用于 receiver)
getBot() {
return this.bot;
}
constructor(bot) {
super();
this._wsUrl = "";
this._heartbeatParam = {
op: 1, // OpCode.HEARTBEAT
d: null
};
// 废弃属性
this.heartbeatInterval = 30000;
this.isReconnect = false;
this.userClose = false;
this.bot = bot;
// 初始化认证管理器
this.authManager = new auth_manager_1.AuthManager(bot, {
appid: bot.config.appid,
secret: bot.config.secret,
maxRetries: 3,
tokenRefreshBuffer: 60
});
// 初始化连接管理器
this.connectionManager = new connection_manager_1.ConnectionManager(bot, {
maxRetry: bot.config.maxRetry || exports.MAX_RETRY,
heartbeatInterval: 30000,
reconnectDelay: 5000
});
// 创建接收器
this.receiver = this.createReceiver();
// 设置事件处理
this.setupEventHandlers();
}
/**
* 创建对应模式的接收器
*/
createReceiver() {
switch (this.bot.config.mode) {
case 'middleware':
const middlewareConfig = this.bot.config;
// 为向后兼容,仍使用工厂函数,但可以考虑后续迁移到新的类结构
return (0, webhook_1.createMiddlewareReceiver)(middlewareConfig.application);
case 'webhook':
const webhookConfig = this.bot.config;
// 为向后兼容,仍使用工厂函数,但可以考虑后续迁移到新的类结构
return (0, webhook_1.createWebhookReceiver)(webhookConfig.port, webhookConfig.path);
case 'websocket':
// 使用新的WebSocket接收器类,同时保持向后兼容的接口
return (0, WebSocketReceiver_1.createWebsocketReceiver)();
default:
throw new Error(`未知的接收器模式: ${this.bot.config.mode}`);
}
}
/**
* 设置事件处理器
*/
setupEventHandlers() {
// 接收器事件处理
this.receiver.on("packet", (packet) => {
this.bot.dispatchEvent(packet.t, packet);
});
// 连接管理器事件转发
this.connectionManager.on(constants_1.SessionEvents.EVENT_WS, (data) => {
this.emit(constants_1.SessionEvents.EVENT_WS, data);
});
this.connectionManager.on(constants_1.SessionEvents.ERROR, (code, message) => {
this.emit(constants_1.SessionEvents.ERROR, code, message);
});
this.connectionManager.on(constants_1.SessionEvents.DEAD, (data) => {
this.emit(constants_1.SessionEvents.DEAD, data);
});
// 连接事件处理
this.connectionManager.on('connecting', () => {
this.bot.logger.debug("[SESSION] 开始连接");
});
this.connectionManager.on('connect', async () => {
try {
// 获取网关地址
this._wsUrl = await this.authManager.getGatewayUrl();
// 启动接收器
this.receiver.emit('start', this);
}
catch (error) {
this.bot.logger.error("[SESSION] 连接准备失败:", error);
this.connectionManager.emit(constants_1.SessionEvents.ERROR, -1, `连接准备失败: ${error}`);
}
});
this.connectionManager.on('disconnect', () => {
this.receiver.emit('stop', this);
});
this.connectionManager.on('heartbeat', (heartbeatData) => {
this._heartbeatParam = heartbeatData;
});
// 接收器事件处理
this.receiver.on('ready', () => {
this.connectionManager.emit(constants_1.SessionEvents.EVENT_WS, {
eventType: constants_1.SessionEvents.READY
});
});
this.receiver.on('error', (error) => {
this.connectionManager.emit(constants_1.SessionEvents.ERROR, -1, error.message || error);
});
this.receiver.on('close', (code, reason) => {
this.connectionManager.emit(constants_1.SessionEvents.EVENT_WS, {
eventType: constants_1.SessionEvents.DISCONNECT,
code,
eventMsg: this.sessionRecord
});
});
}
/**
* 获取访问令牌
*/
async getAccessToken() {
const tokenInfo = await this.authManager.refreshAccessToken();
return {
access_token: tokenInfo.access_token,
expires_in: tokenInfo.expires_in,
};
}
/**
* 获取WebSocket连接地址
*/
async getWsUrl() {
this._wsUrl = await this.authManager.getGatewayUrl();
return this._wsUrl;
}
/**
* 获取有效的意图值
*/
getValidIntends() {
return (this.bot.config.intents || []).reduce((result, item) => {
const value = constants_1.Intends[item];
if (value === undefined) {
this.bot.logger.warn(`无效的意图(${item}),已跳过...`);
return result;
}
return value | result;
}, 0);
}
async start() {
return new Promise(async (resolve) => {
await this.getAccessToken();
this.receiver.emit('start', this);
this.receiver.on('ready', resolve);
});
}
async stop() {
this.userClose = true;
this.receiver.emit('stop', this);
}
/**
* 更新会话记录(用于WebSocket接收器)
*/
updateSessionRecord(record) {
this.connectionManager.updateSessionRecord(record);
}
}
exports.SessionManager = SessionManager;