import { CoolController, BaseController } from '@cool-midway/core'; import { Body, Headers, Inject, Post, Provide } from '@midwayjs/core'; import { InjectEntityModel } from '@midwayjs/typeorm'; import { Repository } from 'typeorm'; import { RuntimeReportEntity, DeviceEntity } from '../../entity/runtime'; import { CenterAuthService, ApiError } from '../../service/auth'; /** * 运行上报 + 设备上报(对齐旧 FastAPI apis/plugins.py /api/runtime/report、/api/device/report) * 注意:现网 devices 表无 client_version 列(以现网 schema 为准),上报仅 upsert 现有列 */ @Provide() @CoolController('/api') export class ApiDeviceController extends BaseController { @Inject() centerAuthService: CenterAuthService; @InjectEntityModel(RuntimeReportEntity) runtimeRepo: Repository; @InjectEntityModel(DeviceEntity) deviceRepo: Repository; /** POST /api/runtime/report */ @Post('/runtime/report') async runtimeReport(@Body() b: any, @Headers('X-API-Token') xApiToken: string = '') { this.centerAuthService.checkApiToken(xApiToken); await this.runtimeRepo.insert({ account: b?.account || '', deviceId: b?.device_id || '', pluginId: b?.plugin_id || '', version: b?.version || '', status: b?.status || '', msg: b?.msg || '', durationSec: Number(b?.duration_sec || 0), at: new Date(), }); return { ok: true }; } /** POST /api/device/report — 执行机心跳/环境上报(按 device_id 幂等 upsert) */ @Post('/device/report') async deviceReport(@Body() b: any, @Headers('X-API-Token') xApiToken: string = '') { this.centerAuthService.checkApiToken(xApiToken); const deviceId = (b?.device_id || '').trim(); if (!deviceId) throw new ApiError(400, 'device_id 不能为空'); await this.deviceRepo.manager.query( `INSERT INTO devices(device_id, account, hostname, os, ip, chrome_installed, chrome_version, chrome_ok, last_seen, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW(), ?) ON DUPLICATE KEY UPDATE account = VALUES(account), hostname = VALUES(hostname), os = VALUES(os), ip = VALUES(ip), chrome_installed = VALUES(chrome_installed), chrome_version = VALUES(chrome_version), chrome_ok = VALUES(chrome_ok), last_seen = VALUES(last_seen), status = VALUES(status)`, [ deviceId, (b?.account || '').trim(), (b?.hostname || '').trim(), (b?.os || '').trim(), (b?.ip || '').trim(), Number(!!b?.chrome_installed), (b?.chrome_version || '').trim(), Number(!!b?.chrome_ok), Number(!!b?.status), ] ); return { ok: true, device_id: deviceId }; } }