273 lines
9.9 KiB
JavaScript
273 lines
9.9 KiB
JavaScript
'use strict';
|
||
|
||
const { Service } = require('egg');
|
||
const { Op } = require('sequelize');
|
||
const crypto = require('crypto');
|
||
|
||
/**
|
||
* NVR 录像机 service
|
||
*
|
||
* 职责:
|
||
* - NVR 的增删改查(**按主体 `subject_id` 隔离**,别的主体的一律 404)
|
||
* - 登录密码的**加解密**:库里只存密文(AES-256-GCM),接口永不返回
|
||
* - 拉取通道后回填序列号 / 通道数 / 最近同步时间
|
||
*
|
||
* 密钥来源:`NVR_SECRET` 环境变量 > `config.keys`(同一部署内稳定即可;
|
||
* 换密钥会导致已存的密文解不开,表现为「密码需要重新填写」)。
|
||
*/
|
||
|
||
/** 列表/详情默认不返回密码密文 */
|
||
const SAFE_ATTRIBUTES = { exclude: [ 'passwordEnc' ] };
|
||
|
||
const CIPHER_PREFIX = 'v1';
|
||
|
||
function deriveKey(secret) {
|
||
return crypto.createHash('sha256').update(`nvr-credential:${secret}`).digest();
|
||
}
|
||
|
||
function encryptPassword(plain, secret) {
|
||
if (!plain) return null;
|
||
const iv = crypto.randomBytes(12);
|
||
const cipher = crypto.createCipheriv('aes-256-gcm', deriveKey(secret), iv);
|
||
const encrypted = Buffer.concat([ cipher.update(String(plain), 'utf8'), cipher.final() ]);
|
||
const tag = cipher.getAuthTag();
|
||
return [ CIPHER_PREFIX, iv.toString('base64'), tag.toString('base64'), encrypted.toString('base64') ].join(':');
|
||
}
|
||
|
||
function decryptPassword(payload, secret) {
|
||
if (!payload) return '';
|
||
const parts = String(payload).split(':');
|
||
if (parts.length !== 4 || parts[0] !== CIPHER_PREFIX) return '';
|
||
|
||
try {
|
||
const iv = Buffer.from(parts[1], 'base64');
|
||
const tag = Buffer.from(parts[2], 'base64');
|
||
const data = Buffer.from(parts[3], 'base64');
|
||
const decipher = crypto.createDecipheriv('aes-256-gcm', deriveKey(secret), iv);
|
||
decipher.setAuthTag(tag);
|
||
return Buffer.concat([ decipher.update(data), decipher.final() ]).toString('utf8');
|
||
} catch (err) {
|
||
return '';
|
||
}
|
||
}
|
||
|
||
class NvrService extends Service {
|
||
get Nvr() {
|
||
return this.app.model.Nvr;
|
||
}
|
||
|
||
get secret() {
|
||
return process.env.NVR_SECRET || this.app.config.keys;
|
||
}
|
||
|
||
/** 密码加密(供 create/update 用) */
|
||
encrypt(plain) {
|
||
return encryptPassword(plain, this.secret);
|
||
}
|
||
|
||
/** 解密设备密码(内部使用,绝不直接返回给前端) */
|
||
passwordOf(nvr) {
|
||
return decryptPassword(nvr && nvr.passwordEnc, this.secret);
|
||
}
|
||
|
||
/**
|
||
* 取「拉取通道」所需的登录凭据(含**明文**密码)
|
||
*
|
||
* 仅限 NVR 所有者调用;返回给前端后会立即随请求传给本机软件,
|
||
* 服务端不做任何缓存。列表/详情接口依然**不返回**密码。
|
||
*/
|
||
async credentialOf(id, subjectId) {
|
||
const nvr = await this.Nvr.findByPk(id, { attributes: { include: [ 'passwordEnc' ] } });
|
||
if (!nvr || Number(nvr.subjectId) !== Number(subjectId)) {
|
||
this.ctx.throw(404, 'NVR 不存在或不属于当前主体');
|
||
}
|
||
return {
|
||
id: nvr.id,
|
||
name: nvr.name,
|
||
host: nvr.host,
|
||
port: nvr.port,
|
||
username: nvr.username,
|
||
password: this.passwordOf(nvr),
|
||
hasPassword: Boolean(nvr.passwordEnc),
|
||
};
|
||
}
|
||
|
||
/** 取「当前主体」的 NVR;不存在或不属于当前主体 → 404 */
|
||
async findOwned(id, subjectId) {
|
||
const nvr = await this.Nvr.findByPk(id, { attributes: SAFE_ATTRIBUTES });
|
||
if (!nvr || Number(nvr.subjectId) !== Number(subjectId)) {
|
||
this.ctx.throw(404, 'NVR 不存在或不属于当前主体');
|
||
}
|
||
return nvr;
|
||
}
|
||
|
||
/** 分页列表:keyword 模糊匹配名称 / 地址 / 序列号 */
|
||
async list({ page = 1, pageSize = 20, keyword, status, subjectId } = {}) {
|
||
const size = Math.min(Number(pageSize) || 20, 100);
|
||
const current = Math.max(Number(page) || 1, 1);
|
||
|
||
const where = {};
|
||
if (subjectId) where.subjectId = Number(subjectId);
|
||
if (status !== undefined && status !== '' && status !== null) where.status = Number(status);
|
||
if (keyword) {
|
||
where[Op.or] = [
|
||
{ name: { [Op.like]: `%${keyword}%` } },
|
||
{ host: { [Op.like]: `%${keyword}%` } },
|
||
{ serialNumber: { [Op.like]: `%${keyword}%` } },
|
||
];
|
||
}
|
||
|
||
const { rows, count } = await this.Nvr.findAndCountAll({
|
||
where,
|
||
attributes: SAFE_ATTRIBUTES,
|
||
limit: size,
|
||
offset: (current - 1) * size,
|
||
order: [[ 'id', 'DESC' ]],
|
||
});
|
||
|
||
return {
|
||
list: rows.map(row => row.toJSON()),
|
||
total: count,
|
||
page: current,
|
||
pageSize: size,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 新增 NVR
|
||
*
|
||
* 同一 `host + port + username` 全局唯一(唯一索引):重复添加时
|
||
* - 已被其他主体占用 → 409
|
||
* - 自己之前删过 → 复活并更新
|
||
* - 当前主体已存在 → 更新(覆盖密码等信息)
|
||
*
|
||
* @param {object} params { subjectId 当前主体, userId 创建人, name, host, port, username, password, serialNumber?, deviceModel?, remark? }
|
||
*/
|
||
async create({ subjectId, userId, name, host, port = 8000, username = 'admin', password, serialNumber, deviceModel, remark } = {}) {
|
||
if (!subjectId) this.ctx.throw(400, '缺少主体');
|
||
const finalHost = String(host || '').trim();
|
||
if (!finalHost) this.ctx.throw(422, 'host 不能为空');
|
||
const finalPort = Number(port) || 8000;
|
||
if (finalPort < 1 || finalPort > 65535) this.ctx.throw(422, 'port 必须在 1~65535 之间');
|
||
const finalUser = String(username || '').trim() || 'admin';
|
||
if (!password) this.ctx.throw(422, 'password 不能为空');
|
||
|
||
// 带已删除的一起查:软删的行仍占着唯一键
|
||
const existing = await this.Nvr.findOne({
|
||
where: { host: finalHost, port: finalPort, username: finalUser },
|
||
attributes: { include: [ 'passwordEnc' ] },
|
||
paranoid: false,
|
||
});
|
||
|
||
if (existing) {
|
||
if (existing.subjectId && Number(existing.subjectId) !== Number(subjectId)) {
|
||
this.ctx.throw(409, `NVR ${finalHost}:${finalPort} 已被其他主体添加`);
|
||
}
|
||
if (existing.deletedAt) await existing.restore();
|
||
|
||
await existing.update({
|
||
subjectId: Number(subjectId),
|
||
userId: Number(userId),
|
||
name: name === undefined ? existing.name : String(name || '').trim(),
|
||
passwordEnc: this.encrypt(password),
|
||
serialNumber: serialNumber || existing.serialNumber,
|
||
deviceModel: deviceModel || existing.deviceModel,
|
||
remark: remark === undefined ? existing.remark : remark,
|
||
status: 1,
|
||
lastError: null,
|
||
});
|
||
return this.findOwned(existing.id, subjectId);
|
||
}
|
||
|
||
const created = await this.Nvr.create({
|
||
subjectId: Number(subjectId),
|
||
userId: Number(userId),
|
||
name: String(name || '').trim(),
|
||
host: finalHost,
|
||
port: finalPort,
|
||
username: finalUser,
|
||
passwordEnc: this.encrypt(password),
|
||
serialNumber: serialNumber || null,
|
||
deviceModel: deviceModel || null,
|
||
remark: remark || null,
|
||
status: 1,
|
||
});
|
||
|
||
this.ctx.logger.info('[nvr] 主体 %s 新增 NVR %s(%s:%s)', subjectId, created.name, finalHost, finalPort);
|
||
return this.findOwned(created.id, subjectId);
|
||
}
|
||
|
||
/**
|
||
* 更新 NVR(`password` 不传 = 保持原密码)
|
||
* @param {object} patch { name?, host?, port?, username?, password?, remark?, status? }
|
||
*/
|
||
async update(id, subjectId, patch = {}) {
|
||
const nvr = await this.Nvr.findByPk(id, { attributes: { include: [ 'passwordEnc' ] } });
|
||
if (!nvr || Number(nvr.subjectId) !== Number(subjectId)) this.ctx.throw(404, 'NVR 不存在或不属于当前主体');
|
||
|
||
const fields = {};
|
||
if (patch.name !== undefined) fields.name = String(patch.name || '').trim();
|
||
if (patch.remark !== undefined) fields.remark = patch.remark;
|
||
if (patch.status !== undefined) fields.status = Number(patch.status) === 0 ? 0 : 1;
|
||
if (patch.host !== undefined) fields.host = String(patch.host || '').trim() || nvr.host;
|
||
if (patch.port !== undefined) {
|
||
const nextPort = Number(patch.port);
|
||
if (!nextPort || nextPort < 1 || nextPort > 65535) this.ctx.throw(422, 'port 必须在 1~65535 之间');
|
||
fields.port = nextPort;
|
||
}
|
||
if (patch.username !== undefined) fields.username = String(patch.username || '').trim() || nvr.username;
|
||
if (patch.password) fields.passwordEnc = this.encrypt(patch.password);
|
||
|
||
try {
|
||
await nvr.update(fields);
|
||
} catch (err) {
|
||
if (err && err.name === 'SequelizeUniqueConstraintError') {
|
||
this.ctx.throw(409, '该地址 + 账号的 NVR 已存在');
|
||
}
|
||
throw err;
|
||
}
|
||
|
||
return this.findOwned(id, subjectId);
|
||
}
|
||
|
||
/**
|
||
* 删除 NVR(软删除)
|
||
*
|
||
* 级联处理:该 NVR 下的摄像头一并软删除,并解除它们与工作台的绑定,
|
||
* 避免工作台里残留「指向已删除 NVR 的摄像头」。
|
||
*/
|
||
async remove(id, subjectId) {
|
||
const nvr = await this.findOwned(id, subjectId);
|
||
const { Camera, WorkstationCamera } = this.app.model;
|
||
|
||
const cameras = await Camera.findAll({ attributes: [ 'id' ], where: { nvrId: nvr.id }, raw: true });
|
||
const cameraIds = cameras.map(item => item.id);
|
||
|
||
if (cameraIds.length) {
|
||
await WorkstationCamera.destroy({ where: { cameraId: { [Op.in]: cameraIds } } });
|
||
await Camera.destroy({ where: { id: { [Op.in]: cameraIds } } });
|
||
}
|
||
|
||
await nvr.destroy();
|
||
this.ctx.logger.info('[nvr] 主体 %s 删除 NVR %s(连带 %d 个摄像头)', subjectId, nvr.id, cameraIds.length);
|
||
|
||
return { id: nvr.id, removedCameras: cameraIds.length };
|
||
}
|
||
|
||
/** 前端拉取成功/失败后回填同步结果 */
|
||
async saveSyncResult(id, subjectId, { serialNumber, deviceModel, channelCount, error } = {}) {
|
||
const nvr = await this.findOwned(id, subjectId);
|
||
const fields = { lastSyncAt: new Date() };
|
||
|
||
if (serialNumber !== undefined) fields.serialNumber = serialNumber || nvr.serialNumber;
|
||
if (deviceModel !== undefined) fields.deviceModel = deviceModel || nvr.deviceModel;
|
||
if (channelCount !== undefined) fields.channelCount = Number(channelCount) || 0;
|
||
fields.lastError = error ? String(error).slice(0, 255) : null;
|
||
|
||
await nvr.update(fields);
|
||
return this.findOwned(id, subjectId);
|
||
}
|
||
}
|
||
|
||
module.exports = NvrService;
|