Commit 5eb4ea7d by liimin

chore(deps): 添加项目依赖包锁定文件

- 初始化项目依赖配置,添加 package-lock.json 文件
- 集成 NestJS 框架核心依赖及模块
- 添加数据库 ORM TypeORM 和 Prisma 依赖
- 配置邮件发送模块 @nestjs-modules/mailer
- 添加定时任务调度模块 nestjs-schedule
- 集成 WebSocket 和 Socket.IO 实时通信支持
- 添加 Redis 缓存和队列处理依赖 bull
- 配置 Winston 日志系统和文件轮转功能
- 添加 Swagger API 文档生成工具
- 集成单元测试和 E2E 测试相关依赖
- 添加代码格式化和静态检查工具链
- 配置环境变量管理模块 nestjs-config
1 parent 480318cc
This diff could not be displayed because it is too large.
...@@ -75,7 +75,8 @@ ...@@ -75,7 +75,8 @@
"swagger-ui-express": "^5.0.1", "swagger-ui-express": "^5.0.1",
"typeorm": "0.2.25", "typeorm": "0.2.25",
"winston": "^3.14.2", "winston": "^3.14.2",
"winston-daily-rotate-file": "^5.0.0" "winston-daily-rotate-file": "^5.0.0",
"ws": "^8.19.0"
}, },
"devDependencies": { "devDependencies": {
"@nestjs/cli": "^10.4.5", "@nestjs/cli": "^10.4.5",
...@@ -89,6 +90,7 @@ ...@@ -89,6 +90,7 @@
"@types/node": "^22.5.5", "@types/node": "^22.5.5",
"@types/socket.io": "^3.0.2", "@types/socket.io": "^3.0.2",
"@types/supertest": "^2.0.8", "@types/supertest": "^2.0.8",
"@types/ws": "^8.18.1",
"@typescript-eslint/eslint-plugin": "5.62.0", "@typescript-eslint/eslint-plugin": "5.62.0",
"@typescript-eslint/parser": "5.62.0", "@typescript-eslint/parser": "5.62.0",
"eslint": "8.42.0", "eslint": "8.42.0",
......
...@@ -9,8 +9,8 @@ datasource db { ...@@ -9,8 +9,8 @@ datasource db {
model device { model device {
id Int @id @unique(map: "id") @default(autoincrement()) id Int @id @unique(map: "id") @default(autoincrement())
sn String @unique @db.VarChar(20) sn String @unique @db.VarChar(50)
created_at DateTime @default(dbgenerated("(now())")) @db.Timestamp(0) created_at DateTime @default(now()) @db.Timestamp(0)
device_info device_info? device_info device_info?
device_status device_status? device_status device_status?
fields field_relation[] fields field_relation[]
......
...@@ -82,10 +82,15 @@ export enum Command { ...@@ -82,10 +82,15 @@ export enum Command {
StopPolling = 'stopPolling', StopPolling = 'stopPolling',
StartPolling = 'startPolling', StartPolling = 'startPolling',
SetPollingInterval = 'setPollingInterval', SetPollingInterval = 'setPollingInterval',
Records='records',
TempRecords='tempRecords', TempRecords='tempRecords',
RemoveTempRecord='removeTempRecord', RemoveTempRecord='removeTempRecord',
AddTempRecord='addTempRecord', AddTempRecord='addTempRecord',
AddRecord='addRecord' AddRecord='addRecord',
LiveLog='liveLog',
FileExplorer='fileExplorer',
ExecuteSql='executeSql',
UploadFile='uploadFile',
} }
export enum LogFieldTypes { export enum LogFieldTypes {
......
import { join,extname } from 'path'; import { join, extname } from 'path'
import { diskStorage } from 'multer'; import { diskStorage } from 'multer'
import * as fs from 'fs'
const normalizeName = (originalname: string) => {
const ext = extname(originalname)
const base = originalname.slice(0, originalname.length - ext.length)
return base.replace(/_\d{10,}$/, '').replace(/@\d+@\d{10,}(?:-\d+)?$/, '')
}
export default { export default {
root: join(__dirname,'..','..',process.env.STATIC_PATH), root: join(__dirname, '..', '..', process.env.STATIC_PATH),
storage: diskStorage({ storage: diskStorage({
destination: join(__dirname,'..','..', `${process.env.STATIC_PATH}/${new Date().toLocaleDateString()}`), destination: (req, file, cb) => {
filename: (req, file, cb) => { const now = new Date()
const deviceId = req.body.deviceId; const year = now.getFullYear()
// const name=file.originalname.split('.'); const month = now.getMonth() + 1
// const filename = `${name[0]}-${new Date().getTime()}.${name.pop()}`//${file.mimetype.split('/')[1]}`; const target = join(__dirname, '..', '..', `${process.env.STATIC_PATH}/${year}/${month}`)
const path = `${file.originalname.split('.').shift()}@${deviceId}@${Date.now()}-${Math.round(Math.random() * 1e10)}${extname(file.originalname)}` fs.mkdirSync(target, { recursive: true })
return cb(null, path); return cb(null, target)
}, },
}), filename: (req, file, cb) => {
}; const deviceId = req.body.deviceId
const name = normalizeName(file.originalname)
const filename = `${name}@${deviceId}${extname(file.originalname)}`
return cb(null, filename)
}
})
}
...@@ -9,7 +9,6 @@ import { SnDto } from 'src/dto/base.dto' ...@@ -9,7 +9,6 @@ import { SnDto } from 'src/dto/base.dto'
@Controller() @Controller()
@ApiTags('权限管理') @ApiTags('权限管理')
@Controller('device')
@UseInterceptors(TransformInterceptor) @UseInterceptors(TransformInterceptor)
@UsePipes(new ValidationPipe()) @UsePipes(new ValidationPipe())
export class AuthController { export class AuthController {
......
...@@ -5,6 +5,8 @@ import { ConfigService } from 'nestjs-config' ...@@ -5,6 +5,8 @@ import { ConfigService } from 'nestjs-config'
import { Command, Events, RESPONSE_CODE, WsMessageType } from '../../common/enums' import { Command, Events, RESPONSE_CODE, WsMessageType } from '../../common/enums'
import { EventEmitter2 } from '@nestjs/event-emitter' import { EventEmitter2 } from '@nestjs/event-emitter'
import { WsGateway } from '../ws/ws.gateway' import { WsGateway } from '../ws/ws.gateway'
import { NativeWsService } from '../ws/native-ws.service'
@Injectable() @Injectable()
export class BroadcastService { export class BroadcastService {
private webHook: string private webHook: string
...@@ -13,28 +15,61 @@ export class BroadcastService { ...@@ -13,28 +15,61 @@ export class BroadcastService {
private readonly config: ConfigService, private readonly config: ConfigService,
@Inject(EventEmitter2) @Inject(EventEmitter2)
private readonly eventEmitter: EventEmitter2, private readonly eventEmitter: EventEmitter2,
private readonly wsGateway: WsGateway private readonly wsGateway: WsGateway,
private readonly nativeWsService: NativeWsService
) { ) {
this.webHook = this.config.get('env').AppWebhook this.webHook = this.config.get('env').AppWebhook
} }
async send(message: WsTypes.MessageBody<Command, WsMessageType>): Promise<CommonTypes.IResData> { async send(message: WsTypes.MessageBody<Command, WsMessageType>): Promise<CommonTypes.IResData> {
// const success = await this.eventEmitter.emitAsync(Events.OnMessageToSendClient, message) const deviceId = message.device_id!
return this.wsGateway.send(message)
// return { code: success ? RESPONSE_CODE.SUCCESS : RESPONSE_CODE.NOSUCCESS, data: { success } } // 定义服务列表(按优先级排序)
const services = [
{
name: 'Native WebSocket',
isOnline: () => this.nativeWsService.isDeviceOnline(deviceId),
send: () => this.nativeWsService.send(message)
},
{
name: 'Socket.IO',
isOnline: () => this.wsGateway.wsService.isDeviceOnline(deviceId),
send: () => this.wsGateway.send(message)
}
] as const
// 查找并发送到第一个在线的服务
for (const service of services) {
if (service.isOnline()) {
await service.send()
return {
code: RESPONSE_CODE.SUCCESS,
message: '发送成功',
data: {
socketIo: service.name === 'Socket.IO',
nativeWs: service.name === 'Native WebSocket',
method: service.name
}
}
}
}
// 都不在线
throw new Error(`Device ${deviceId} is offline`)
} }
// // 广播消息
// 广播消息
async onMessage(param: any): Promise<CommonTypes.IResData> { async onMessage(param: any): Promise<CommonTypes.IResData> {
if (param?.code == RESPONSE_CODE.SUCCESS && param?.data?.command === Command.RemoveLog) { if (param?.code == RESPONSE_CODE.SUCCESS && param?.data?.command === Command.RemoveLog) {
const statusInfo: DeviceStatus.IDeviceStatus = { device_id: param.device_id, last_log_remove_time: new Date() } const statusInfo: DeviceStatus.IDeviceStatus = { device_id: param.device_id, last_log_remove_time: new Date() }
this.eventEmitter.emit(Events.OnLogFileRemoved, statusInfo) this.eventEmitter.emit(Events.OnLogFileRemoved, statusInfo)
} }
//判断param 是否 对象
const content = typeof param == 'string' ? param : JSON.stringify(param)
const res: AxiosResponse<any, any> = await this.httpService const res: AxiosResponse<any, any> = await this.httpService
.post(this.webHook, { .post(this.webHook, {
msgtype: 'text', msgtype: 'text',
text: { text: {
content: JSON.stringify(param) content
} }
}) })
.toPromise() .toPromise()
......
...@@ -86,10 +86,15 @@ export class DeviceController { ...@@ -86,10 +86,15 @@ export class DeviceController {
@OnEvent(Events.OnConnected) @OnEvent(Events.OnConnected)
@ApiOperation({ summary: '更新设备状态' }) @ApiOperation({ summary: '更新设备状态' })
async upsertDeviceStatus(@Body() param: DeviceStatusDto): Promise<void | CommonTypes.IResData> { async upsertDeviceStatus(@Body() param: DeviceStatusDto): Promise<void | CommonTypes.IResData> {
return await this.deviceService.upsertDeviceStatus(param).catch(error => { return await this.deviceService
const out: WsTypes.WsConnError = { message: WsAccess.ConnFailure, device_id: param.device_id } .upsertDeviceStatus(param)
this.eventEmitter.emit(Events.OnConnectError, out) .then(async () => {
}) await this.deviceService.sendDeviceStatusMessage(param)
})
.catch(error => {
const out: WsTypes.WsConnError = { message: WsAccess.ConnFailure, device_id: param.device_id }
this.eventEmitter.emit(Events.OnConnectError, out)
})
} }
@Post('/upsertFileRemovedTime') @Post('/upsertFileRemovedTime')
@OnEvent(Events.OnLogFileRemoved) @OnEvent(Events.OnLogFileRemoved)
......
...@@ -5,17 +5,35 @@ import { Inject, Injectable, HttpException, HttpStatus, OnModuleInit, Logger } f ...@@ -5,17 +5,35 @@ import { Inject, Injectable, HttpException, HttpStatus, OnModuleInit, Logger } f
import { PrismaService } from 'nestjs-prisma' import { PrismaService } from 'nestjs-prisma'
import { Command, Events, RESPONSE_CODE, WsMessageType, WsStatus } from '../../common/enums' import { Command, Events, RESPONSE_CODE, WsMessageType, WsStatus } from '../../common/enums'
import { EventEmitter2 } from '@nestjs/event-emitter' import { EventEmitter2 } from '@nestjs/event-emitter'
import { createClient, RedisClientType } from 'redis'
import { DeviceStatusDto } from '../../dto'
@Injectable() @Injectable()
export class DeviceService implements OnModuleInit { export class DeviceService implements OnModuleInit {
private redisClient: RedisClientType
private readonly MAX_ONLINE_KEY = 'max_online_count'
private readonly MAX_ONLINE_DATE_KEY = 'max_online_date'
constructor( constructor(
@Inject(PrismaService) @Inject(PrismaService)
private readonly prisma: PrismaService, // private connection: Connection, private readonly prisma: PrismaService, // private connection: Connection,
@Inject(EventEmitter2) @Inject(EventEmitter2)
private readonly eventEmitter: EventEmitter2 private readonly eventEmitter: EventEmitter2
) {} ) {}
async onModuleInit() { async onModuleInit() {
this.resetAllDeviceStatus() this.resetAllDeviceStatus()
await this.initRedis()
}
private async initRedis() {
try {
this.redisClient = createClient({ url: `redis://${process.env.REDIS_HOST}` })
await this.redisClient.connect()
Logger.log('Redis client connected successfully')
} catch (error) {
Logger.error('Failed to connect to Redis:', error)
}
} }
async findAll({ user, mobile, sn, skip, take, status }: DeviceTypes.IQueryDevices): Promise<CommonTypes.IResData<DeviceTypes.IDevice[]>> { async findAll({ user, mobile, sn, skip, take, status }: DeviceTypes.IQueryDevices): Promise<CommonTypes.IResData<DeviceTypes.IDevice[]>> {
const where = { const where = {
...@@ -274,4 +292,64 @@ export class DeviceService implements OnModuleInit { ...@@ -274,4 +292,64 @@ export class DeviceService implements OnModuleInit {
} }
return { code: RESPONSE_CODE.SUCCESS, message: '每日日志删除任务完成' } return { code: RESPONSE_CODE.SUCCESS, message: '每日日志删除任务完成' }
} }
async findOnlineCount(): Promise<number> {
const count = await this.prisma.device_status.count({
where: { status: WsStatus.Online }
})
return count
}
async getMaxOnlineCount(): Promise<{ maxCount: number; maxDate: string }> {
if (!this.redisClient) {
return { maxCount: 0, maxDate: '' }
}
const maxCount = await this.redisClient.get(this.MAX_ONLINE_KEY)
const maxDate = await this.redisClient.get(this.MAX_ONLINE_DATE_KEY)
return {
maxCount: parseInt(maxCount || '0', 10),
maxDate: maxDate || ''
}
}
async updateMaxOnlineCount(currentCount: number): Promise<void> {
if (!this.redisClient) {
return
}
const currentMax = await this.redisClient.get(this.MAX_ONLINE_KEY)
const currentMaxNum = parseInt(currentMax || '0', 10)
if (currentCount > currentMaxNum) {
await this.redisClient.set(this.MAX_ONLINE_KEY, currentCount.toString())
const dateStr = `${new Date().toLocaleString('zh')}`
await this.redisClient.set(this.MAX_ONLINE_DATE_KEY, dateStr)
Logger.log(`更新最高在线人数:${currentCount}人,时间:${dateStr}`)
}
}
/**
* 构建设备状态变更通知消息并触发事件
* @param param - 设备状态参数
*/
async sendDeviceStatusMessage(param: DeviceStatusDto): Promise<void> {
const onlineCount = await this.findOnlineCount()
const isOnline = param.status === 1
const statusText = isOnline ? '🟢 设备上线' : '🔴 设备下线'
const { maxCount, maxDate } = await this.getMaxOnlineCount()
// 仅在设备上线时更新最高在线人数
if (isOnline) {
await this.updateMaxOnlineCount(onlineCount)
}
const msg = `${statusText}
设备 ID: ${param.device_id}
当前在线:${onlineCount}人
最高在线:${maxCount}人 (${maxDate})
当前时间:${new Date().toLocaleString('zh')}`
this.eventEmitter.emit(Events.OnMessage, msg)
}
} }
...@@ -5,9 +5,14 @@ import * as fs from 'fs' ...@@ -5,9 +5,14 @@ import * as fs from 'fs'
import * as path from 'path' import * as path from 'path'
import { DocTypes, RESPONSE_CODE } from '../../common/enums' import { DocTypes, RESPONSE_CODE } from '../../common/enums'
import { PrismaService } from 'nestjs-prisma' import { PrismaService } from 'nestjs-prisma'
import { Doc } from 'prettier'
import { join } from 'path' import { join } from 'path'
const normalizeLogName = (name: string) => {
const ext = path.extname(name)
const base = name.slice(0, name.length - ext.length)
return base.replace(/_\d{10,}$/, '').replace(/@\d+@\d{10,}(?:-\d+)?$/, '')
}
@Injectable() @Injectable()
export class FileService { export class FileService {
/** /**
...@@ -53,19 +58,51 @@ export class FileService { ...@@ -53,19 +58,51 @@ export class FileService {
* @returns 一个 Promise,成功时解析为包含操作结果的 CommonTypes.IResData 对象。 * @returns 一个 Promise,成功时解析为包含操作结果的 CommonTypes.IResData 对象。
*/ */
async save(file: FileTypes.FileUpload<DocTypes>): Promise<CommonTypes.IResData> { async save(file: FileTypes.FileUpload<DocTypes>): Promise<CommonTypes.IResData> {
const { filename, path, created_at, destination, size, ...where } = file const { filename, created_at, destination } = file
await this.prisma.$transaction(async prisma => { await this.prisma.$transaction(async prisma => {
const files: Pick<FileTypes.IFile<DocTypes>, 'id' | 'destination' | 'filename'>[] = await prisma.file.findMany({ where, select: { id: true, destination: true, filename: true } }) const where =
file.type === DocTypes.Log
? {
device_id: file.device_id,
type: file.type,
OR: [
{ filename },
{ filename: { startsWith: `${normalizeLogName(file.originalname)}@${file.device_id}@` } },
{ filename: { startsWith: `${normalizeLogName(file.originalname)}@${file.device_id}.` } },
{
AND: [{ filename: { startsWith: `${normalizeLogName(file.originalname)}_` } }, { filename: { contains: `@${file.device_id}@` } }]
}
]
}
: {
device_id: file.device_id,
type: file.type,
originalname: file.originalname
}
const files: Pick<FileTypes.IFile<DocTypes>, 'id' | 'destination' | 'filename'>[] = await prisma.file.findMany({
where,
select: { id: true, destination: true, filename: true },
orderBy: { created_at: 'desc' }
})
const currentPath = join(destination, filename)
if (files?.length) { if (files?.length) {
files.forEach(async ({ id, destination: dest, filename: fname }) => { const [keep, ...stales] = files
for (const { id, destination: dest, filename: fname } of stales) {
const origin_path = join(dest, fname) const origin_path = join(dest, fname)
try { try {
fs.existsSync(origin_path) && fs.unlinkSync(origin_path) fs.existsSync(origin_path) && fs.unlinkSync(origin_path)
} catch (err) { } catch (err) {
Logger.error('删除文件失败', err) Logger.error('删除文件失败', err)
} }
await prisma.file.update({ where: { id }, data: { filename, path, created_at, destination } }) await prisma.file.delete({ where: { id } })
}) }
const keepPath = join(keep.destination, keep.filename)
try {
keepPath !== currentPath && fs.existsSync(keepPath) && fs.unlinkSync(keepPath)
} catch (err) {
Logger.error('删除文件失败', err)
}
await prisma.file.update({ where: { id: keep.id }, data: { ...file } })
} else { } else {
await prisma.file.create({ data: file }) await prisma.file.create({ data: file })
} }
......
import { Controller, Post, Body, Get } from '@nestjs/common';
import { WsNativeService } from './ws-native.service';
import { WsMessageType } from '../../common/enums';
@Controller('ws-native')
export class WsNativeController {
constructor(private readonly wsNativeService: WsNativeService) {}
/**
* 获取在线设备列表
*/
@Get('online-devices')
getOnlineDevices() {
return {
devices: this.wsNativeService.getOnlineDevices(),
count: this.wsNativeService.getOnlineDevices().length,
};
}
/**
* 发送消息给指定设备
*/
@Post('send-to-device')
sendToDevice(@Body() body: { deviceId: string; message: any }) {
const { deviceId, message } = body;
const sent = this.wsNativeService.sendToDevice(deviceId, {
type: WsMessageType.Private,
data: message,
});
return {
success: sent,
message: sent ? 'Message sent' : 'Device not found or offline',
};
}
/**
* 发送指令给客户端 - 请求日志
*/
@Post('request-logs')
requestLogs(@Body() body: { deviceId: string; logType?: string }) {
const result = this.wsNativeService.requestLogs(body.deviceId, body.logType);
return {
...result,
message: result.success ? 'Log request sent' : 'Device not found or offline',
};
}
/**
* 发送指令给客户端 - 请求设备信息
*/
@Post('request-device-info')
requestDeviceInfo(@Body() body: { deviceId: string }) {
const result = this.wsNativeService.requestDeviceInfo(body.deviceId);
return {
...result,
message: result.success ? 'Device info request sent' : 'Device not found or offline',
};
}
/**
* 发送自定义指令给客户端
*/
@Post('send-command')
sendCommand(@Body() body: { deviceId: string; command: string; params?: any }) {
const result = this.wsNativeService.sendCommand(body.deviceId, body.command, body.params);
return {
...result,
message: result.success ? 'Command sent' : 'Device not found or offline',
};
}
/**
* 广播消息给所有在线设备
*/
@Post('broadcast')
broadcast(@Body() body: { message: any }) {
this.wsNativeService.broadcast({
type: WsMessageType.System,
data: body.message,
});
return {
success: true,
message: 'Broadcast sent',
recipients: this.wsNativeService.getOnlineDevices().length,
};
}
}
import {
WebSocketGateway,
WebSocketServer,
OnGatewayConnection,
OnGatewayDisconnect,
OnGatewayInit,
SubscribeMessage,
MessageBody,
ConnectedSocket,
} from '@nestjs/websockets';
import { Logger } from '@nestjs/common';
import { Server } from 'ws';
import { IncomingMessage } from 'http';
import { WsNativeService } from './ws-native.service';
import { AuthService } from '../auth/auth.service';
import { WsAccess, WsAccessCode, WsMessageType, WsStatus } from '../../common/enums';
/**
* 原生 WebSocket 网关(不使用 Socket.IO)
*/
@WebSocketGateway(+process.env.NATIVE_WS_PORT! || 8081, {
transports: ['websocket'], // 只使用 WebSocket 传输
path: '/ws',
})
export class WsNativeGateway implements OnGatewayConnection, OnGatewayDisconnect, OnGatewayInit {
@WebSocketServer()
server: Server;
private readonly logger = new Logger(WsNativeGateway.name);
constructor(
private readonly wsNativeService: WsNativeService,
private readonly authService: AuthService,
) {}
afterInit(server: Server) {
this.logger.warn(`Native WebSocket initialized on port: ${process.env.NATIVE_WS_PORT || 8081}`);
this.wsNativeService.server = server;
}
handleConnection(client: any, request: IncomingMessage) {
this.logger.log(`Client connecting: ${client._socket.remoteAddress}`);
// 从 URL 查询参数中获取 token 和 deviceId
const url = new URL(request.url, `http://${request.headers.host}`);
const token = url.searchParams.get('token');
const deviceId = url.searchParams.get('deviceId') || url.searchParams.get('device_id');
if (!token) {
this.handleInvalidAuth(client, WsAccess.InValidToken, WsAccessCode.InValidToken);
return;
}
if (!deviceId) {
this.handleInvalidAuth(client, WsAccess.InvalidDeviceId, WsAccessCode.InvalidDeviceId);
return;
}
// 验证 token
const verify = this.authService.verifyToken(String(token));
if (!verify.isPass) {
const errorCode = verify.isExpired ? WsAccessCode.TokenExpired : WsAccessCode.InValidToken;
this.handleInvalidAuth(client, WsAccess.TokenExpired, errorCode);
return;
}
// 登录处理
this.wsNativeService.login(client, token, deviceId);
// 监听消息
client.on('message', (data: Buffer) => {
try {
const message = JSON.parse(data.toString());
this.wsNativeService.onMessage(client, message);
} catch (error) {
this.logger.error(`Failed to parse message: ${error.message}`);
}
});
}
handleDisconnect(client: any) {
this.logger.log(`Client disconnected`);
this.wsNativeService.logout(client);
}
private handleInvalidAuth(client: any, errMsg: WsAccess, errorCode: WsAccessCode) {
this.logger.error(`Auth failed: ${errMsg}`);
const response = {
type: WsMessageType.Private,
data: {
isValidate: false,
errMsg,
errorCode,
},
};
client.send(JSON.stringify(response));
client.close();
}
}
import { Module } from '@nestjs/common';
import { WsNativeGateway } from './ws-native.gateway';
import { WsNativeService } from './ws-native.service';
import { WsNativeController } from './ws-native.controller';
import { AuthModule } from '../auth/auth.module';
import { EventEmitterModule } from '@nestjs/event-emitter';
@Module({
imports: [AuthModule, EventEmitterModule.forRoot()],
controllers: [WsNativeController],
providers: [WsNativeGateway, WsNativeService],
exports: [WsNativeGateway, WsNativeService],
})
export class WsNativeModule {}
import { Injectable, Logger } from '@nestjs/common';
import { Server } from 'ws';
import { WsMessageType, WsStatus } from '../../common/enums';
@Injectable()
export class WsNativeService {
private readonly logger = new Logger(WsNativeService.name);
public server: Server;
// 存储客户端连接 deviceId -> client
private clients: Map<string, any> = new Map();
// 存储客户端信息 client -> { deviceId, token }
private clientInfo: WeakMap<any, { deviceId: string; token: string }> = new WeakMap();
/**
* 用户登录
*/
login(client: any, token: string, deviceId: string) {
this.logger.log(`Device ${deviceId} logged in`);
// 如果该设备已经连接,断开旧连接
const existingClient = this.clients.get(deviceId);
if (existingClient && existingClient !== client) {
this.logger.warn(`Device ${deviceId} already connected, closing old connection`);
existingClient.close();
}
// 保存新连接
this.clients.set(deviceId, client);
this.clientInfo.set(client, { deviceId, token });
// 发送连接成功消息
this.sendToClient(client, {
type: WsMessageType.System,
data: {
status: WsStatus.Online,
message: 'Connected successfully',
deviceId,
},
});
return {
status: WsStatus.Online,
message: 'Connected',
device_id: deviceId,
};
}
/**
* 用户登出
*/
logout(client: any) {
const info = this.clientInfo.get(client);
if (info) {
this.logger.log(`Device ${info.deviceId} logged out`);
this.clients.delete(info.deviceId);
this.clientInfo.delete(client);
}
}
/**
* 处理客户端消息
*/
onMessage(client: any, message: any) {
const info = this.clientInfo.get(client);
if (!info) {
this.logger.warn('Received message from unknown client');
return;
}
this.logger.log(`Received message from ${info.deviceId}: ${JSON.stringify(message)}`);
// 根据消息类型处理
const { type, data, requestId } = message;
switch (type) {
case 'response':
// 客户端响应服务端指令
this.handleClientResponse(info.deviceId, data, requestId);
break;
case 'log_upload':
// 客户端上传日志
this.handleLogUpload(info.deviceId, data);
break;
case 'heartbeat':
// 心跳
this.sendToClient(client, {
type: 'heartbeat',
data: { timestamp: Date.now() },
});
break;
default:
this.logger.warn(`Unknown message type: ${type}`);
}
}
/**
* 处理客户端响应
*/
private handleClientResponse(deviceId: string, data: any, requestId: string) {
this.logger.log(`Device ${deviceId} response for request ${requestId}: ${JSON.stringify(data)}`);
// 这里可以触发事件或回调,通知等待响应的服务
}
/**
* 处理日志上传
*/
private handleLogUpload(deviceId: string, data: any) {
this.logger.log(`Device ${deviceId} uploaded logs: ${JSON.stringify(data)}`);
// 这里可以保存日志到数据库或文件系统
}
/**
* 发送消息给指定客户端
*/
sendToClient(client: any, message: any) {
if (client.readyState === 1) { // WebSocket.OPEN
client.send(JSON.stringify(message));
}
}
/**
* 发送消息给指定设备
*/
sendToDevice(deviceId: string, message: any) {
const client = this.clients.get(deviceId);
if (client) {
this.sendToClient(client, message);
return true;
}
return false;
}
/**
* 广播消息给所有连接的客户端
*/
broadcast(message: any) {
const data = JSON.stringify(message);
this.clients.forEach((client) => {
if (client.readyState === 1) {
client.send(data);
}
});
}
/**
* 获取在线设备列表
*/
getOnlineDevices(): string[] {
return Array.from(this.clients.keys());
}
/**
* 重置所有客户端连接
*/
resetClients() {
this.clients.forEach((client) => {
client.close();
});
this.clients.clear();
}
/**
* 发送指令给客户端(带请求ID,用于追踪响应)
*/
sendCommand(deviceId: string, command: string, params?: any): { success: boolean; requestId?: string } {
const client = this.clients.get(deviceId);
if (!client) {
return { success: false };
}
const requestId = `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
this.sendToClient(client, {
type: 'command',
requestId,
data: {
command,
params,
timestamp: Date.now(),
},
});
return { success: true, requestId };
}
/**
* 请求客户端上传日志
*/
requestLogs(deviceId: string, logType?: string) {
return this.sendCommand(deviceId, 'get_logs', { logType: logType || 'all' });
}
/**
* 请求客户端设备信息
*/
requestDeviceInfo(deviceId: string) {
return this.sendCommand(deviceId, 'get_device_info');
}
/**
* 请求客户端执行操作
*/
requestAction(deviceId: string, action: string, params?: any) {
return this.sendCommand(deviceId, action, params);
}
}
import { HttpException, HttpStatus, Injectable, Logger, OnModuleDestroy, OnModuleInit } from '@nestjs/common'
import { EventEmitter2 } from '@nestjs/event-emitter'
import { Inject } from '@nestjs/common'
import { Command, Events, RESPONSE_CODE, WsAccess, WsAccessCode, WsMessageType } from '../../common/enums'
import { AuthService } from '../auth/auth.service'
import * as WebSocket from 'ws'
@Injectable()
export class NativeWsService implements OnModuleInit, OnModuleDestroy {
private server: any
private readonly clients = new Map<number, any>()
private readonly clientMeta = new Map<any, { deviceId: number; token: string }>()
private readonly path = process.env.NATIVE_WS_PATH || '/ws-native'
private readonly port = Number(process.env.NATIVE_WS_PORT || 8081)
constructor(
@Inject(EventEmitter2)
private readonly eventEmitter: EventEmitter2,
private readonly authService: AuthService
) {}
onModuleInit() {
this.server = new WebSocket.Server({ port: this.port, path: this.path })
this.server.on('connection', (socket: any, req: any) => this.handleConnection(socket, req))
this.server.on('listening', () => Logger.warn(`NativeWebSocket init... Port: ${this.port}, Path: ${this.path}`))
this.server.on('error', (error: Error) => Logger.error('NativeWebSocket server error', error))
}
onModuleDestroy() {
this.clients.forEach(client => client.close())
this.clients.clear()
this.clientMeta.clear()
this.server?.close()
}
private parseAuth(req: any) {
const origin = `http://${req.headers?.host || 'localhost'}`
const url = new URL(req.url || '', origin)
const queryToken = url.searchParams.get('token') || ''
const queryDeviceId = url.searchParams.get('deviceId') || url.searchParams.get('device_id') || ''
const token = String(req.headers?.token || queryToken || '').trim()
const deviceId = Number(String(req.headers?.deviceid || req.headers?.device_id || queryDeviceId || '').trim())
return { token, deviceId }
}
private sendPacket(socket: any, event: WsMessageType, data: any) {
socket.send(JSON.stringify({ event, data }))
}
private handleConnection(socket: any, req: any) {
const { token, deviceId } = this.parseAuth(req)
if (!token) {
this.sendPacket(socket, WsMessageType.Private, { isValidate: false, errMsg: WsAccess.InValidToken, errorCode: WsAccessCode.InValidToken })
socket.close()
return
}
if (!deviceId) {
this.sendPacket(socket, WsMessageType.Private, { isValidate: false, errMsg: WsAccess.InvalidDeviceId, errorCode: WsAccessCode.InvalidDeviceId })
socket.close()
return
}
const verify = this.authService.verifyToken(token)
if (!verify.isPass) {
const errorCode = verify.isExpired ? WsAccessCode.TokenExpired : WsAccessCode.InValidToken
this.sendPacket(socket, WsMessageType.Private, { isValidate: false, errMsg: WsAccess.TokenExpired, errorCode })
socket.close()
return
}
const prevClient = this.clients.get(deviceId)
if (prevClient) {
this.sendPacket(prevClient, WsMessageType.Private, `设备-> ${deviceId} 已在别处上线`)
prevClient.close()
}
this.clients.set(deviceId, socket)
this.clientMeta.set(socket, { deviceId, token })
Logger.warn(`Device-> ${deviceId} [native-ws] Has Connected, OnLine Number: ${this.clients.size}`)
this.sendPacket(socket, WsMessageType.Private, { isValidate: true, errMsg: WsAccess.IsOnline, errorCode: WsAccessCode.IsOnline })
this.eventEmitter.emit(Events.OnConnected, { device_id: deviceId, status: 1 })
socket.on('message', (buffer: any) => {
try {
const text = typeof buffer === 'string' ? buffer : buffer.toString()
const message = JSON.parse(text)
if (message.type === 'ping') {
socket.send(
JSON.stringify({
type: 'pong',
timestamp: Date.now()
})
)
// Logger.debug(`Device ${deviceId} heartbeat received, sent pong`)
return
}
if (message?.event === WsMessageType.Private || message?.event === WsMessageType.System) {
this.eventEmitter.emit(Events.OnMessage, message.data)
return
}
this.eventEmitter.emit(Events.OnMessage, message)
} catch (error) {
Logger.error('NativeWebSocket message parse error', error)
}
})
socket.on('close', () => {
const meta = this.clientMeta.get(socket)
if (meta) {
this.clients.delete(meta.deviceId)
this.clientMeta.delete(socket)
Logger.warn(`Device-> ${meta.deviceId} [native-ws] Logout, OnLine Number: ${this.clients.size}`)
this.eventEmitter.emit(Events.OnConnected, { device_id: meta.deviceId, status: 2 })
}
})
socket.on('error', (error: Error) => {
Logger.error(`NativeWebSocket error device_id=${deviceId}`, error)
this.eventEmitter.emit(Events.OnConnectError, { device_id: deviceId, message: error?.message })
})
}
isDeviceOnline(deviceId: number): boolean {
return this.clients.has(deviceId)
}
async send(payload: WsTypes.MessageBody<Command, WsMessageType>): Promise<CommonTypes.IResData> {
if (payload.event === WsMessageType.System) {
this.clients.forEach(client => this.sendPacket(client, WsMessageType.System, payload.data))
return { code: RESPONSE_CODE.SUCCESS, message: '发送成功' }
}
if (!payload.device_id) {
throw new HttpException({ status: HttpStatus.BAD_REQUEST, message: '请求参数device_id 必传', error: 'deviceId is required' }, HttpStatus.BAD_REQUEST)
}
const client = this.clients.get(payload.device_id)
if (!client) {
throw new HttpException({ status: HttpStatus.BAD_REQUEST, message: `发送失败,客户端:(设备号->${payload.device_id}) 不在线`, error: 'send error' }, HttpStatus.BAD_REQUEST)
}
this.sendPacket(client, WsMessageType.Private, payload.data)
return { code: RESPONSE_CODE.SUCCESS, message: '发送成功' }
}
}
import { Module } from '@nestjs/common' import { Module } from '@nestjs/common'
import { WsGateway } from './ws.gateway' import { WsGateway } from './ws.gateway'
import { WsService } from './ws.service' import { WsService } from './ws.service'
import { NativeWsService } from './native-ws.service'
import { AuthModule } from '../auth/auth.module' import { AuthModule } from '../auth/auth.module'
@Module({ @Module({
imports: [AuthModule], imports: [AuthModule],
providers: [WsGateway, WsService], providers: [WsGateway, WsService, NativeWsService],
exports: [WsGateway] exports: [WsGateway, NativeWsService]
}) })
export class WsModule {} export class WsModule {}
...@@ -114,6 +114,13 @@ export class WsService { ...@@ -114,6 +114,13 @@ export class WsService {
} }
/** /**
* 检查设备是否在线
*/
isDeviceOnline(deviceId: number): boolean {
return this.clientIds.has(deviceId)
}
/**
* 发送私人消息(事务消息、个人消息) * 发送私人消息(事务消息、个人消息)
* @param messagePath 发布地址 * @param messagePath 发布地址
* @param response 响应数据 * @param response 响应数据
......
...@@ -7,14 +7,14 @@ ...@@ -7,14 +7,14 @@
# content-type: application/json # content-type: application/json
# { # {
# "sn":"test2002" # "sn":"4DF8801064461802495A2452CCD04EE4"
# } # }
# POST http://localhost:3000/device/addInfo HTTP/1.1 # POST http://localhost:3000/device/addInfo HTTP/1.1
# content-type: application/json # content-type: application/json
# { # {
# "device_id":1000001, # "device_id":1,
# "mobile":"13335327367", # "mobile":"13335327367",
# "user":"郝小美", # "user":"郝小美",
# "merchant_name":"D+陕西榆林华睿通园区店(44211168)" # "merchant_name":"D+陕西榆林华睿通园区店(44211168)"
...@@ -24,38 +24,42 @@ ...@@ -24,38 +24,42 @@
# content-type: application/json # content-type: application/json
# { # {
# "device_id":1000002, # "device_id": 1,
# "mobile":"13335327367", # "device_info": {
# "user":"郝小美", # "mobile": "13335327367",
# "merchant_name":"D+陕西榆林华睿通园区店(44211168)" # "user": "郝小美",
# "merchant_name": "D+陕西榆林华睿通园区店(44211168)"
# }
# } # }
# http://localhost:3000/sse/event # http://localhost:3000/sse/event
POST http://localhost:3000/broadcast/cmd HTTP/1.1 POST http://192.168.1.237:3000/broadcast/cmd HTTP/1.1
content-type: application/json content-type: application/json
{ {
"event":"private", "event":"private",
"device_id":"1000001", "device_id":"1000032",
"data":{ "data":{
# "command":"setPollingInterval", "command":"getLog"
# "command":"getLog", //"filePath":"/storage/emulated/0/Android/data/io.dcloud.HBuilder/apps/HBuilder/doc/uniapp_save/1773140510986_F7E5393B.mp3"
# "command":"stopPolling", // "action":"stop"
# "command":"startPolling", //"path":"_doc/uniapp_save"
# "command":"removeLog", //"sql":"SELECT * FROM records where recordStatus=0"
"command":"getLogList", // "key":"recordList"
"interval":20, }
"beginDate": "2024-11-07",
"endDate": "2024-11-07",
"force":true
}
} }
# POST http://192.168.1.237:3000/login HTTP/1.1
# content-type: application/json
# {
# "sn":"85021F6039BB89866048E0410707025E"
# }
# http://localhost:3000/file/list?device_id=1000000 # http://localhost:3000/file/list?device_id=1000000
# http://localhost:3000/config?device_id=1000000 # http://localhost:3000/config?device_id=1000000
# http://localhost:3000/file/delete?id=50 # http://localhost:3000/file/delete?id=50
# POST http://localhost:3000/config/add HTTP/1.1 # POST http://localhost:3000/config/add HTTP/1.1
# content-type: application/json # content-type: application/json
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!