broadcast.service.ts 2.6 KB
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: '发送企微消息成功' }
  }
}