Initial commit: organize FPV RID local registry source

This commit is contained in:
zhangshuochi
2026-10-20 11:41:04 +08:00
commit 26afff4926
17 changed files with 3369 additions and 0 deletions
+254
View File
@@ -0,0 +1,254 @@
// Local registration and verification server. No outbound network requests.
const http = require('node:http');
const fs = require('node:fs');
const path = require('node:path');
const { backup } = require('node:sqlite');
const database = require('./database');
const exportFiles = require('./export-files');
const HOST = '127.0.0.1';
const PORT = 8787;
const ROOT = __dirname;
const WEB = path.join(ROOT, 'web');
const ARCHIVE = path.join(ROOT, '..', '档案库');
const ARCHIVE_CARDS = path.join(ARCHIVE, '档案卡');
fs.mkdirSync(ARCHIVE_CARDS, { recursive: true });
fs.writeFileSync(path.join(ARCHIVE, '使用说明.txt'), 'FPV-RID 本地档案库\r\n档案卡目录中的 HTML 文件内含登记照片,可以离线打开。\r\n登记数据库.sqlite 是当前数据库备份;登记数据库.previous.sqlite 是上一次备份。\r\n网站正在使用的数据库位于 registry/data/registry.sqlite。\r\n');
const staticFiles = new Map([
['/', ['index.html', 'text/html; charset=utf-8']],
['/app.css', ['app.css', 'text/css; charset=utf-8']],
['/app.js', ['app.js', 'text/javascript; charset=utf-8']],
['/vendor/qrcode.js', ['vendor/qrcode.js', 'text/javascript; charset=utf-8']],
['/fpv-rid-icon.png', ['fpv-rid-icon.png', 'image/png']],
]);
function reply(res, status, body, type = 'application/json; charset=utf-8', extraHeaders = {}) {
res.writeHead(status, {
'content-type': type,
'cache-control': 'no-store',
'x-content-type-options': 'nosniff',
'access-control-allow-origin': '*',
'access-control-allow-methods': 'GET, POST, DELETE, OPTIONS',
'access-control-allow-headers': 'content-type',
'access-control-allow-private-network': 'true',
'content-security-policy': "default-src 'self'; img-src 'self' data: blob:; style-src 'self'; script-src 'self'; connect-src 'self'; base-uri 'none'; frame-ancestors 'none'",
...extraHeaders,
});
res.end(body);
}
function json(res, status, value) { reply(res, status, JSON.stringify(value)); }
async function readJson(req) {
const parts = [];
let size = 0;
for await (const part of req) {
size += part.length;
if (size > 16 * 1024 * 1024) throw new Error('提交内容过大,单张照片最多 5 MB');
parts.push(part);
}
return JSON.parse(Buffer.concat(parts).toString('utf8'));
}
function publicRecord(record) {
return {
id: record.id,
serialNo: record.serialNo,
uasCode: record.uasCode,
modelName: record.modelName,
ownerName: record.ownerName,
createdAt: record.createdAt,
source: 'local-fpv-registry',
qrUrl: `http://${HOST}:${PORT}/r/${record.id}`,
archiveUrl: `/r/${record.id}`,
downloadArchiveUrl: `/api/records/${record.id}/archive`,
photo1Url: record.photo1 ? `/api/records/${record.id}/photos/1` : null,
photo2Url: record.photo2 ? `/api/records/${record.id}/photos/2` : null,
};
}
function parseLocalQr(input) {
let url;
try { url = new URL(String(input || '')); }
catch { throw new Error('二维码内容不是有效网址'); }
if (url.protocol !== 'http:' || !['127.0.0.1', 'localhost'].includes(url.hostname) || url.port !== String(PORT)) {
throw new Error('二维码不是本机登记站生成的链接');
}
const match = /^\/r\/([0-9a-f]{36})$/.exec(url.pathname);
if (!match) throw new Error('本地登记链接格式无效');
return match[1];
}
function escapeHtml(value) {
return String(value).replace(/[&<>"']/g, char => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[char]);
}
function recordPage(record, standalone = false) {
const r = publicRecord(record);
const photos = [1, 2].map(slot => {
const photo = database.getPhoto(record.id, slot);
if (!photo) return `<figure><div class="no-photo">未上传照片 ${slot}</div><figcaption>照片 ${slot}</figcaption></figure>`;
const src = standalone ? `data:${photo.mimeType};base64,${Buffer.from(photo.image).toString('base64')}` : `/api/records/${record.id}/photos/${slot}`;
return `<figure><img src="${src}" alt="登记照片 ${slot}"><figcaption>登记照片 ${slot}</figcaption></figure>`;
}).join('');
return `<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${escapeHtml(r.serialNo)} · 本地档案卡</title><style>
*{box-sizing:border-box}body{font-family:system-ui,"Microsoft YaHei",sans-serif;background:#edf2f7;color:#173047;margin:0;padding:36px 18px}
main{max-width:760px;margin:auto;background:#fff;border:1px solid #dce6f0;border-radius:20px;padding:36px;box-shadow:0 12px 40px #1a385015}
.tag{display:inline-block;background:#e7f4ec;color:#25734a;border-radius:999px;padding:7px 13px;font-size:12px;font-weight:700}
h1{font-size:26px;margin:22px 0 6px}.code{font-size:19px;color:#1c6595;font-weight:800;letter-spacing:.04em}
.note{color:#7a8c9b;font-size:12px;line-height:1.6;margin:12px 0 24px}
dl{display:grid;grid-template-columns:125px 1fr;gap:15px;border-top:1px solid #e5ebf0;padding-top:22px;margin:0}
dt{color:#63768a}dd{margin:0;font-weight:700;overflow-wrap:anywhere}
h2{font-size:16px;margin:30px 0 14px}.photos{display:grid;grid-template-columns:1fr 1fr;gap:14px}
figure{margin:0;border:1px solid #e1e8ee;border-radius:11px;overflow:hidden}figure img,.no-photo{width:100%;height:245px;object-fit:contain;background:#f4f7fa}
.no-photo{display:grid;place-items:center;color:#9aabb8;font-size:13px}figcaption{padding:10px 12px;font-size:12px;color:#63768a}
footer{border-top:1px solid #e5ebf0;margin-top:26px;padding-top:15px;color:#98a7b3;font-size:11px;overflow-wrap:anywhere}
@media(max-width:540px){main{padding:22px}.photos{grid-template-columns:1fr}dl{grid-template-columns:90px 1fr}}
@media print{body{background:#fff;padding:0}main{box-shadow:none;border:0;max-width:none}}
</style></head><body><main><span class="tag">本地备案档案卡</span><h1>${escapeHtml(r.serialNo)}</h1><div class="code">${escapeHtml(r.uasCode)}</div>
<p class="note">本档案卡由 FPV-RID 本地登记软件保存,可离线打开。</p>
<dl><dt>模块 SN</dt><dd>${escapeHtml(r.serialNo)}</dd><dt>FPV 编号</dt><dd>${escapeHtml(r.uasCode)}</dd><dt>机型</dt><dd>${escapeHtml(r.modelName || '—')}</dd><dt>登记人 / 备注</dt><dd>${escapeHtml(r.ownerName || '—')}</dd><dt>登记时间</dt><dd>${escapeHtml(r.createdAt)}</dd></dl>
<h2>登记照片</h2><div class="photos">${photos}</div><footer>档案 ID:${escapeHtml(r.id)}</footer></main></body></html>`;
}
function atomicWrite(file, content) {
const temporary = `${file}.${process.pid}.tmp`;
fs.writeFileSync(temporary, content);
fs.renameSync(temporary, file);
}
let archiveQueue = Promise.resolve();
function syncArchive(retainPrevious = true) {
const task = archiveQueue.catch(() => {}).then(async () => {
const records = database.listRecords();
const names = new Set();
for (const record of records) {
const name = `${record.id}.html`;
names.add(name);
atomicWrite(path.join(ARCHIVE_CARDS, name), recordPage(record, true));
}
for (const name of fs.readdirSync(ARCHIVE_CARDS)) {
if (/^[0-9a-f]{36}\.html$/.test(name) && !names.has(name)) fs.unlinkSync(path.join(ARCHIVE_CARDS, name));
}
atomicWrite(path.join(ARCHIVE, '记录索引.json'), JSON.stringify(records.map(publicRecord), null, 2));
const temporary = path.join(ARCHIVE, `登记数据库.${process.pid}.tmp.sqlite`);
try {
await backup(database.db, temporary);
const current = path.join(ARCHIVE, '登记数据库.sqlite');
if (retainPrevious && fs.existsSync(current)) fs.copyFileSync(current, path.join(ARCHIVE, '登记数据库.previous.sqlite'));
fs.renameSync(temporary, current);
if (!retainPrevious) fs.rmSync(path.join(ARCHIVE, '登记数据库.previous.sqlite'), { force: true });
} finally {
if (fs.existsSync(temporary)) fs.unlinkSync(temporary);
}
});
archiveQueue = task;
return task;
}
function selectedRecords(body) {
if (!body || !Array.isArray(body.ids) || body.ids.length < 1 || body.ids.length > 5000) throw new Error('请先勾选要导出的档案');
const ids = [...new Set(body.ids)];
if (ids.some(id => typeof id !== 'string' || !/^[0-9a-f]{36}$/.test(id))) throw new Error('档案 ID 无效');
const records = database.getRecords(ids);
if (records.length !== ids.length) throw new Error('选择的档案已不存在,请刷新记录');
return records;
}
function archiveZip(records) {
const entries = [{ name: '档案库/使用说明.txt', data: '每个档案卡 HTML 均包含照片,可离线直接打开。照片原件另存于“照片”目录。records.json 保存登记字段与文件对应关系。\r\n' }];
const manifest = [];
for (const record of records) {
const photoPaths = [];
entries.push({ name: `档案库/档案卡/${record.serialNo}.html`, data: recordPage(record, true) });
for (const slot of [1, 2]) {
const photo = database.getPhoto(record.id, slot);
if (!photo) { photoPaths.push(null); continue; }
const ext = photo.mimeType === 'image/jpeg' ? 'jpg' : photo.mimeType.split('/')[1];
const filename = `档案库/照片/${record.serialNo}-${slot}.${ext}`;
entries.push({ name: filename, data: photo.image });
photoPaths.push(filename);
}
manifest.push({ id: record.id, serialNo: record.serialNo, fpvCode: record.uasCode, modelName: record.modelName, ownerName: record.ownerName, createdAt: record.createdAt, photos: photoPaths });
}
entries.push({ name: '档案库/records.json', data: JSON.stringify(manifest, null, 2) });
return exportFiles.zip(entries);
}
const server = http.createServer(async (req, res) => {
try {
const url = new URL(req.url, `http://${HOST}:${PORT}`);
const origin = req.headers.origin;
if (origin && ![`http://${HOST}:${PORT}`, `http://localhost:${PORT}`].includes(origin) && url.pathname !== '/api/resolve') {
return json(res, 403, { error: '只允许从本地登记站访问' });
}
if (req.method === 'OPTIONS') return reply(res, 204, '');
if (url.pathname === '/api/records' && req.method === 'GET') {
return json(res, 200, { records: database.listRecords(url.searchParams.get('q')).map(publicRecord) });
}
if (url.pathname === '/api/records' && req.method === 'POST') {
const result = database.register(await readJson(req));
await syncArchive();
return json(res, 200, { record: publicRecord(result.record), existing: result.existing });
}
if (url.pathname === '/api/export/archive' && req.method === 'POST') {
const records = selectedRecords(await readJson(req));
return reply(res, 200, archiveZip(records), 'application/zip', {
'content-disposition': 'attachment; filename="FPV-RID-archive.zip"',
});
}
if (url.pathname === '/api/export/excel' && req.method === 'POST') {
const records = selectedRecords(await readJson(req));
return reply(res, 200, exportFiles.excel(records), 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', {
'content-disposition': 'attachment; filename="FPV-RID-records.xlsx"',
});
}
const deleteMatch = /^\/api\/records\/([0-9a-f]{36})$/.exec(url.pathname);
if (req.method === 'DELETE' && deleteMatch) {
if (!database.deleteRecord(deleteMatch[1])) return json(res, 404, { error: '档案不存在' });
await syncArchive(false);
return json(res, 200, { deleted: true });
}
if (url.pathname === '/api/resolve' && req.method === 'GET') {
const id = parseLocalQr(url.searchParams.get('url'));
const record = database.getRecord(id);
return record ? json(res, 200, publicRecord(record)) : json(res, 404, { error: '本地登记记录不存在' });
}
const photoMatch = /^\/api\/records\/([0-9a-f]{36})\/photos\/([12])$/.exec(url.pathname);
if (req.method === 'GET' && photoMatch) {
const photo = database.getPhoto(photoMatch[1], Number(photoMatch[2]));
return photo ? reply(res, 200, photo.image, photo.mimeType) : json(res, 404, { error: '照片不存在' });
}
const archiveMatch = /^\/api\/records\/([0-9a-f]{36})\/archive$/.exec(url.pathname);
if (req.method === 'GET' && archiveMatch) {
const record = database.getRecord(archiveMatch[1]);
if (!record) return json(res, 404, { error: '档案不存在' });
return reply(res, 200, recordPage(record, true), 'text/html; charset=utf-8', {
'content-disposition': `attachment; filename="FPV-RID-${record.serialNo}.html"`,
'content-security-policy': "default-src 'none'; img-src data:; style-src 'unsafe-inline'; base-uri 'none'",
});
}
if (req.method === 'GET' && /^\/r\/[0-9a-f]{36}$/.test(url.pathname)) {
const id = url.pathname.slice(3);
const record = database.getRecord(id);
return record ? reply(res, 200, recordPage(record), 'text/html; charset=utf-8', {
'content-security-policy': "default-src 'none'; img-src 'self'; style-src 'unsafe-inline'; base-uri 'none'",
}) : json(res, 404, { error: '记录不存在' });
}
const file = staticFiles.get(url.pathname);
if (req.method === 'GET' && file) {
return reply(res, 200, fs.readFileSync(path.join(WEB, file[0])), file[1]);
}
json(res, 404, { error: '页面不存在' });
} catch (error) {
const status = error instanceof SyntaxError || /SN|FPV|二维码|链接|登记|提交|照片|内容|档案|导出|选择|搜索/.test(error.message) ? 400 : 500;
json(res, status, { error: error.message });
}
});
server.listen(PORT, HOST, async () => {
console.log(`FPV-RID 本地登记站:http://${HOST}:${PORT}`);
try { await syncArchive(); }
catch (error) { console.error('档案库初始化失败:', error); }
});