broadcast.service.ts
2.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import { HttpService } from '@nestjs/axios'
import { Inject, Injectable } from '@nestjs/common'
import { AxiosResponse } from 'axios'
import { ConfigService } from 'nestjs-config'
import { Command, Events, RESPONSE_CODE, WsMessageType } from '../../common/enums'
import { EventEmitter2 } from '@nestjs/event-emitter'
import { WsGateway } from '../ws/ws.gateway'
import { NativeWsService } from '../ws/native-ws.service'
@Injectable()
export class BroadcastService {
private webHook: string
constructor(
private readonly httpService: HttpService,
private readonly config: ConfigService,
@Inject(EventEmitter2)
private readonly eventEmitter: EventEmitter2,
private readonly wsGateway: WsGateway,
private readonly nativeWsService: NativeWsService
) {
this.webHook = this.config.get('env').AppWebhook
}
async send(message: WsTypes.MessageBody<Command, WsMessageType>): Promise<CommonTypes.IResData> {
const deviceId = message.device_id!
// 定义服务列表(按优先级排序)
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> {
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() }
this.eventEmitter.emit(Events.OnLogFileRemoved, statusInfo)
}
//判断param 是否 对象
const content = typeof param == 'string' ? param : JSON.stringify(param)
const res: AxiosResponse<any, any> = await this.httpService
.post(this.webHook, {
msgtype: 'text',
text: {
content
}
})
.toPromise()
return { code: res.status, message: '发送企微消息成功' }
}
}