liufumingren 993c7acd30 跨公司下载:云端中转成片(分片上传 + Range 下载)
A(查询机)和 B(仓库)不同网络、B 无公网 IP。B 出站领任务后把成片传回云端中转,
A 再从云端取回本地 —— 全程不需要任何一方有公网入口。

云端
- POST /api/web/edge/download      建任务(按主体选在线设备 → 下发 download)
- GET  /api/web/edge/download/:id  查进度(queued/uploading/done/failed)
- GET  /api/web/edge/download/:id/file  取成片,支持 Range(浏览器播放要拖动进度条)
- POST /api/scanner/tasks/:id/upload  设备分片上传(原始字节流,不是 base64)
- bodyParser 对该上传路由禁用:否则原始请求体会被解析掉
- 成片落 run/edge-files(run/ 属部署保留目录,不会被发布覆盖)
- 每次建任务顺手清理过期文件;元数据按主体校验,越权一律 404

桌面端
- AgentHost 新增 download 任务执行:worker 拉流合并 → 分片上传 → 传完删本地临时文件
- 失败时把 uploadTaskId 带回云端,立刻落 failed,查询机不用干等到超时
- ApiClient 新增建任务 / 查状态 / 取文件 / 分片上传
- PlaybackDownloadService 改为三级选路:
  LAN 设备管理服务 → 云端中转 → 本机直连

实测(真实 NVR)
  建任务 → 设备拉流 1.9MB → 上传 → 下载:7.5 秒,字节数一致,ftypisom
  Range: bytes=0-99 → HTTP 206 + Content-Range 正确

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-10-22 00:30:09 +08:00

168 lines
5.2 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 { Controller } = require('egg');
const fs = require('fs');
const path = require('path');
/**
* web 用户端:边缘能力(`/api/web/edge/*`)
*
* 查询机先在本机局域网找"设备管理服务"(UDP 询问),找不到才来这里问云端。
* 云端把问题转给打包仓库那台扫码服务(它出站领任务、真拉一段录像确认)。
*
* 这样查询机得到的结论和"本机自己校验"是同一套语义,不会各说一套。
*/
class WebEdgeController extends Controller {
/**
* POST /api/web/edge/check { code }
*
* 返回 `data.state`:
* - `ok` 设备确认过:`hasVideo` 为准
* - `no-plan` 这个运单在本主体下算不出回放计划(没绑工作台/摄像头)
* - `no-device` 同主体没有在线的扫码服务,或它们都连不上该 NVR
* - `no-credential` 录像机没有保存密码
*
* `hasVideo` 三态:true / false / null(未知,调用方自己决定怎么展示)
*/
async check() {
const { ctx } = this;
const body = ctx.request.body || {};
const code = String(body.code || ctx.query.code || '').trim();
if (!code) ctx.throw(422, '缺少运单号');
const data = await ctx.service.edgeTask.checkVideo({
subjectId: ctx.state.subjectId,
code,
});
ctx.body = { ok: true, data };
}
/**
* POST /api/web/edge/download { code }
*
* 跨网下载:云端让能访问 NVR 的扫码服务去拉流合并,传回云端中转,
* 查询机拿到 `taskId` 后再取文件(不会占住这个请求)。
*/
async download() {
const { ctx } = this;
const body = ctx.request.body || {};
const code = String(body.code || ctx.query.code || '').trim();
if (!code) ctx.throw(422, '缺少运单号');
const data = await ctx.service.edgeTask.createDownloadTask({
subjectId: ctx.state.subjectId,
code,
});
ctx.logger.info('[edge] 主体 %s 跨网下载 %s → %s', ctx.state.subjectId, code, data.state);
ctx.body = { ok: true, data };
}
/**
* GET /api/web/edge/download/:taskId —— 查进度
*
* 只能查自己主体创建的任务(元数据里记了 subjectId)。
*/
async downloadStatus() {
const { ctx } = this;
const meta = await this.requireOwnTask(ctx.params.taskId);
ctx.body = {
ok: true,
data: {
state: meta.state,
size: meta.size || 0,
error: meta.error || null,
scannerSn: meta.scannerSn || null,
},
};
}
/**
* GET /api/web/edge/download/:taskId/file —— 取成片
*
* 支持 `Range`(浏览器 `<video>` 拖动进度条要用),鉴权同样按主体。
*/
async downloadFile() {
const { ctx } = this;
const meta = await this.requireOwnTask(ctx.params.taskId);
if (meta.state !== 'done') {
ctx.status = 409;
ctx.body = { ok: false, message: meta.state === 'failed' ? (meta.error || '下载失败') : '文件还没准备好' };
return;
}
const file = ctx.service.edgeTask.filePath(ctx.params.taskId);
let stat;
try {
stat = await fs.promises.stat(file);
} catch (err) {
ctx.status = 404;
ctx.body = { ok: false, message: '文件已过期或被清理' };
return;
}
const total = stat.size;
const range = parseRange(ctx.headers.range, total);
ctx.type = 'video/mp4';
ctx.set('Accept-Ranges', 'bytes');
ctx.set('Content-Disposition',
`attachment; filename="${encodeURIComponent(meta.code || 'video')}.mp4"`);
if (!range) {
ctx.set('Content-Length', String(total));
ctx.body = fs.createReadStream(file);
return;
}
ctx.status = 206;
ctx.set('Content-Range', `bytes ${range.start}-${range.end}/${total}`);
ctx.set('Content-Length', String(range.end - range.start + 1));
ctx.body = fs.createReadStream(file, { start: range.start, end: range.end });
}
/** 取任务元数据并校验主体;不存在/越权一律 404(不泄露"存在但不是你的") */
async requireOwnTask(taskIdRaw) {
const { ctx } = this;
const taskId = String(taskIdRaw || '').trim();
if (!taskId) ctx.throw(400, '缺少任务 id');
const meta = await ctx.service.edgeTask.readMeta(taskId);
if (!meta || Number(meta.subjectId) !== Number(ctx.state.subjectId)) {
ctx.throw(404, '任务不存在或已过期');
}
return meta;
}
}
/**
* 解析 `Range: bytes=start-end`
* @return {{start:number,end:number}|null} 非法或不支持时返回 null(走整文件)
*/
function parseRange(header, total) {
const text = String(header || '').trim();
const match = /^bytes=(\d*)-(\d*)$/.exec(text);
if (!match) return null;
let start = match[1] === '' ? null : Number(match[1]);
let end = match[2] === '' ? null : Number(match[2]);
if (start === null && end === null) return null;
if (start === null) {
// bytes=-N:最后 N 字节
start = Math.max(total - end, 0);
end = total - 1;
} else if (end === null || end >= total) {
end = total - 1;
}
if (!Number.isFinite(start) || !Number.isFinite(end) || start > end || start >= total) return null;
return { start, end };
}
module.exports = WebEdgeController;