283 lines
10 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'use strict';
const { Service } = require('egg');
const { Op } = require('sequelize');
/**
* 摄像头(NVR 通道)service
*
* 关键点:
* - 归属看**主体 `subject_id`**(跟随所属 NVR),别的主体的摄像头一律 404
* - 唯一键 `(nvr_id, channel_no)`:同一通道重复添加走「更新 / 复活」,不产生重复行
* - 批量添加用事务,最后回填 NVR 的通道数与同步时间
*/
const NVR_ATTRIBUTES = [ 'id', 'name', 'host', 'port', 'serialNumber', 'subjectId', 'userId' ];
class CameraService extends Service {
get Camera() {
return this.app.model.Camera;
}
get Nvr() {
return this.app.model.Nvr;
}
/** 分页列表:可按 NVR、状态过滤,keyword 匹配名称 / IP / 通道号 */
async list({ page = 1, pageSize = 20, keyword, nvrId, status, subjectId } = {}) {
const size = Math.min(Number(pageSize) || 20, 100);
const current = Math.max(Number(page) || 1, 1);
// 只查属于当前主体的 NVR 下的摄像头
const nvrWhere = { subjectId: Number(subjectId) };
if (nvrId) nvrWhere.id = Number(nvrId);
const where = {};
if (status !== undefined && status !== '' && status !== null) where.status = Number(status);
if (keyword) {
where[Op.or] = [
{ name: { [Op.like]: `%${keyword}%` } },
{ ip: { [Op.like]: `%${keyword}%` } },
];
const asNumber = Number(keyword);
if (Number.isInteger(asNumber)) where[Op.or].push({ channelNo: asNumber });
}
const { rows, count } = await this.Camera.findAndCountAll({
where,
include: [{
model: this.Nvr,
as: 'nvr',
required: true,
where: nvrWhere,
attributes: NVR_ATTRIBUTES,
}],
limit: size,
offset: (current - 1) * size,
order: [[ 'nvr_id', 'ASC' ], [ 'channel_no', 'ASC' ]],
});
return {
list: rows.map(row => row.toJSON()),
total: count,
page: current,
pageSize: size,
};
}
/** 某台 NVR 下的全部摄像头(不分页,绑定时用) */
async listByNvr(nvrId, subjectId) {
const nvr = await this.ctx.service.nvr.findOwned(nvrId, subjectId);
const rows = await this.Camera.findAll({
where: { nvrId: nvr.id },
order: [[ 'channel_no', 'ASC' ]],
});
return rows.map(row => row.toJSON());
}
/** 取单个摄像头(含所属 NVR),归属校验失败 → 404 */
async findOwned(id, subjectId) {
const camera = await this.Camera.findByPk(id, {
include: [{ model: this.Nvr, as: 'nvr', required: true, attributes: NVR_ATTRIBUTES }],
});
if (!camera || Number(camera.subjectId) !== Number(subjectId)) {
this.ctx.throw(404, '摄像头不存在或不属于当前主体');
}
return camera;
}
/**
* 批量添加摄像头(前端从本机软件拉到通道后,勾选提交)
*
* @param {object} params
* @param {number} params.subjectId 当前主体
* @param {number} params.nvrId 所属 NVR
* @param {Array} params.channels [{ channel|channelNo, type?, name?, ip?, port?, enabled? }]
* @returns {Promise<object>} { created, updated, list, nvr }
*/
async batchCreate({ subjectId, nvrId, channels = [] } = {}) {
if (!Array.isArray(channels) || channels.length === 0) this.ctx.throw(422, 'channels 不能为空');
const nvr = await this.ctx.service.nvr.findOwned(nvrId, subjectId);
const normalized = [];
const seen = new Set();
for (const raw of channels) {
const channelNo = Number(raw && (raw.channel !== undefined ? raw.channel : raw.channelNo));
if (!Number.isInteger(channelNo) || channelNo <= 0) this.ctx.throw(422, '通道号必须是正整数');
if (seen.has(channelNo)) continue;
seen.add(channelNo);
normalized.push({
channelNo,
name: String(raw.name || '').trim() || `${nvr.name || 'NVR'}-${channelNo}`,
// 设备原始通道名单独存一份,业务名改了也不丢
channelName: String(raw.name || '').trim() || null,
type: raw.type === 'analog' ? 'analog' : 'digital',
ip: raw.ip ? String(raw.ip).slice(0, 45) : null,
port: raw.port ? Number(raw.port) : null,
enabled: raw.enabled === false || raw.enabled === 0 ? 0 : 1,
});
}
let created = 0;
let updated = 0;
const transaction = await this.app.model.transaction();
try {
for (const item of normalized) {
const existing = await this.Camera.findOne({
where: { nvrId: nvr.id, channelNo: item.channelNo },
paranoid: false,
transaction,
});
if (existing) {
if (existing.deletedAt) await existing.restore({ transaction });
// 名称保护:用户改过名的不要被「重新拉取通道」覆盖,只更新设备侧字段
const defaultName = `${nvr.name || 'NVR'}-${item.channelNo}`;
const keepName = existing.name && existing.name !== defaultName;
const patch = Object.assign({}, item, { nvrId: nvr.id, subjectId: Number(subjectId) });
if (keepName) delete patch.name;
await existing.update(patch, { transaction });
updated += 1;
} else {
await this.Camera.create(Object.assign({}, item, { nvrId: nvr.id, subjectId: Number(subjectId) }), { transaction });
created += 1;
}
}
await nvr.update({
channelCount: await this.Camera.count({ where: { nvrId: nvr.id }, transaction }),
lastSyncAt: new Date(),
lastError: null,
}, { transaction });
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
this.ctx.logger.info('[camera] 主体 %s 从 NVR %s 导入通道:新增 %d,更新 %d',
subjectId, nvr.id, created, updated);
const list = await this.listByNvr(nvr.id, subjectId);
return { created, updated, list, nvr: await this.ctx.service.nvr.findOwned(nvr.id, subjectId) };
}
/** 更新摄像头(名称 / 状态 / 备注 / 是否带云台) */
async update(id, subjectId, patch = {}) {
const camera = await this.findOwned(id, subjectId);
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.hasPtz !== undefined) fields.hasPtz = Boolean(Number(patch.hasPtz));
await camera.update(fields);
return this.findOwned(id, subjectId);
}
/** 删除摄像头(软删除 + 解除工作台绑定) */
async remove(id, subjectId) {
const camera = await this.findOwned(id, subjectId);
await this.app.model.WorkstationCamera.destroy({ where: { cameraId: camera.id } });
await camera.destroy();
await this.syncNvrChannelCount(camera.nvrId);
this.ctx.logger.info('[camera] 主体 %s 删除摄像头 %s', subjectId, camera.id);
return { id: camera.id };
}
/**
* 批量删除(只删除属于当前主体的)
*
* @param {number[]} ids 摄像头 id
* @returns {Promise<{ removed: number, skipped: number }>} skipped = 不属于当前主体/不存在的数量
*/
async batchRemove({ subjectId, ids = [] } = {}) {
const list = Array.isArray(ids) ? [ ...new Set(ids.map(Number).filter(item => Number.isInteger(item) && item > 0)) ] : [];
if (!list.length) this.ctx.throw(422, 'ids 不能为空');
const nvrs = await this.Nvr.findAll({ attributes: [ 'id' ], where: { subjectId: Number(subjectId) }, raw: true });
const nvrIds = nvrs.map(item => item.id);
const owned = nvrIds.length
? await this.Camera.findAll({ attributes: [ 'id' ], where: { id: { [Op.in]: list }, nvrId: { [Op.in]: nvrIds } }, raw: true })
: [];
const ownedIds = owned.map(item => item.id);
if (!ownedIds.length) return { removed: 0, skipped: list.length };
// 先记下涉及的 NVR,删完回填计数
const rows = await this.Camera.findAll({ attributes: [ 'nvrId' ], where: { id: { [Op.in]: ownedIds } }, raw: true });
const affectedNvrIds = [ ...new Set(rows.map(item => Number(item.nvrId))) ];
await this.app.model.WorkstationCamera.destroy({ where: { cameraId: { [Op.in]: ownedIds } } });
const removed = await this.Camera.destroy({ where: { id: { [Op.in]: ownedIds } } });
await Promise.all(affectedNvrIds.map(nvrId => this.syncNvrChannelCount(nvrId)));
this.ctx.logger.info('[camera] 主体 %s 批量删除摄像头 %s', subjectId, ownedIds.join(','));
return { removed, skipped: list.length - ownedIds.length };
}
/** 回填 NVR 的「已导入通道数」(增删摄像头后保持一致) */
async syncNvrChannelCount(nvrId) {
if (!nvrId) return;
const count = await this.Camera.count({ where: { nvrId } });
await this.Nvr.update({ channelCount: count }, { where: { id: nvrId } });
}
/** 某主体可用的全部摄像头(工作台绑定选择器用) */
/**
* 工作台选择器用:当前主体的摄像头 + 「已被哪个工作台绑定」(null = 还可以绑)
*/
async optionsOfUser(subjectId) {
const list = await this.listOfUser(subjectId);
if (!list.length) return [];
const cameraIds = list.map(item => Number(item.id));
const links = await this.app.model.WorkstationCamera.findAll({
where: { cameraId: { [Op.in]: cameraIds } },
include: [{
model: this.app.model.Workstation,
as: 'workstation',
required: false,
attributes: [ 'id', 'code', 'name' ],
}],
});
const boundBy = new Map();
for (const link of links) {
boundBy.set(Number(link.cameraId), link.workstation ? link.workstation.toJSON() : null);
}
return list.map(item => ({
...item,
boundWorkstation: boundBy.get(Number(item.id)) || null,
}));
}
async listOfUser(subjectId) {
const nvrs = await this.Nvr.findAll({ attributes: [ 'id' ], where: { subjectId: Number(subjectId) }, raw: true });
if (!nvrs.length) return [];
const rows = await this.Camera.findAll({
where: { nvrId: { [Op.in]: nvrs.map(item => item.id) }, status: 1 },
include: [{ model: this.Nvr, as: 'nvr', attributes: NVR_ATTRIBUTES }],
order: [[ 'nvr_id', 'ASC' ], [ 'channel_no', 'ASC' ]],
});
return rows.map(row => row.toJSON());
}
}
module.exports = CameraService;