```
chore(node): 移除已废弃的 Node.js 回退代码并同步更新文档 删除 package.json、registry/database.js、registry/export-files.js 和 registry/legacy-web/app.css,服务运行不再依赖 Node.js。 更新文档以反映纯 Rust 架构: - README: 明确 Node.js 24 及 Playwright 仅用于开发验收 - 使用说明: "迁移与回退"改为"迁移与备份恢复" - 接口清单: 补充分页、编辑、照片删除及同步接口 - 架构说明: 补充 registry_meta 元数据表 - 验收记录: 新增 2026-10-21 复查记录 ```
This commit is contained in:
@@ -1,138 +0,0 @@
|
||||
// SQLite is bundled with the supplied Node.js runtime. All data stays here.
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const crypto = require('node:crypto');
|
||||
const { DatabaseSync } = require('node:sqlite');
|
||||
|
||||
const dataDir = path.join(__dirname, 'data');
|
||||
fs.mkdirSync(dataDir, { recursive: true });
|
||||
const db = new DatabaseSync(path.join(dataDir, 'registry.sqlite'));
|
||||
db.exec(`
|
||||
PRAGMA foreign_keys = ON;
|
||||
CREATE TABLE IF NOT EXISTS records (
|
||||
id TEXT PRIMARY KEY,
|
||||
serial_no TEXT NOT NULL UNIQUE,
|
||||
uas_code TEXT NOT NULL UNIQUE,
|
||||
model_name TEXT NOT NULL DEFAULT '',
|
||||
owner_name TEXT NOT NULL DEFAULT '',
|
||||
created_at TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS photos (
|
||||
record_id TEXT NOT NULL REFERENCES records(id) ON DELETE CASCADE,
|
||||
slot INTEGER NOT NULL CHECK (slot IN (1, 2)),
|
||||
mime_type TEXT NOT NULL,
|
||||
image BLOB NOT NULL,
|
||||
PRIMARY KEY (record_id, slot)
|
||||
);
|
||||
`);
|
||||
|
||||
// Import the previous JSON database once, leaving the old file as a backup.
|
||||
const oldPath = path.join(dataDir, 'records.json');
|
||||
if (fs.existsSync(oldPath) && db.prepare('SELECT COUNT(*) AS total FROM records').get().total === 0) {
|
||||
const old = JSON.parse(fs.readFileSync(oldPath, 'utf8'));
|
||||
if (!Array.isArray(old)) throw new Error('旧登记文件格式无效');
|
||||
db.exec('BEGIN IMMEDIATE');
|
||||
try {
|
||||
const insert = db.prepare('INSERT OR IGNORE INTO records (id, serial_no, uas_code, model_name, owner_name, created_at) VALUES (?, ?, ?, ?, ?, ?)');
|
||||
for (const r of old) insert.run(r.id, r.serialNo, r.uasCode, r.modelName || '', r.ownerName || '', r.createdAt);
|
||||
db.exec('COMMIT');
|
||||
} catch (error) {
|
||||
db.exec('ROLLBACK');
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
const selectColumns = `
|
||||
SELECT r.id, r.serial_no AS serialNo, r.uas_code AS uasCode,
|
||||
r.model_name AS modelName, r.owner_name AS ownerName,
|
||||
r.created_at AS createdAt,
|
||||
EXISTS(SELECT 1 FROM photos p WHERE p.record_id = r.id AND p.slot = 1) AS photo1,
|
||||
EXISTS(SELECT 1 FROM photos p WHERE p.record_id = r.id AND p.slot = 2) AS photo2
|
||||
FROM records r
|
||||
`;
|
||||
const listStmt = db.prepare(selectColumns + ' ORDER BY r.created_at DESC');
|
||||
const searchStmt = db.prepare(selectColumns + ` WHERE
|
||||
instr(lower(r.serial_no), lower(?)) > 0 OR
|
||||
instr(lower(r.uas_code), lower(?)) > 0 OR
|
||||
instr(lower(r.model_name), lower(?)) > 0 OR
|
||||
instr(lower(r.owner_name), lower(?)) > 0 OR
|
||||
instr(lower(r.created_at), lower(?)) > 0
|
||||
ORDER BY r.created_at DESC`);
|
||||
const getStmt = db.prepare(selectColumns + ' WHERE r.id = ?');
|
||||
const bySnStmt = db.prepare('SELECT id, uas_code AS uasCode FROM records WHERE serial_no = ?');
|
||||
const byUasStmt = db.prepare('SELECT id FROM records WHERE uas_code = ?');
|
||||
const photoStmt = db.prepare('SELECT mime_type AS mimeType, image FROM photos WHERE record_id = ? AND slot = ?');
|
||||
const upsertPhotoStmt = db.prepare('INSERT INTO photos (record_id, slot, mime_type, image) VALUES (?, ?, ?, ?) ON CONFLICT(record_id, slot) DO UPDATE SET mime_type = excluded.mime_type, image = excluded.image');
|
||||
|
||||
function decodePhoto(value, slot) {
|
||||
if (value == null || value === '') return null;
|
||||
if (typeof value !== 'string') throw new Error(`照片 ${slot} 格式无效`);
|
||||
const match = /^data:image\/(jpeg|png|webp);base64,([A-Za-z0-9+/]+={0,2})$/.exec(value);
|
||||
if (!match) throw new Error(`照片 ${slot} 仅支持 JPG、PNG 或 WebP`);
|
||||
const image = Buffer.from(match[2], 'base64');
|
||||
if (!image.length || image.length > 5 * 1024 * 1024) throw new Error(`照片 ${slot} 须小于 5 MB`);
|
||||
const mimeType = `image/${match[1]}`;
|
||||
const valid = (mimeType === 'image/jpeg' && image.subarray(0, 3).equals(Buffer.from([0xff, 0xd8, 0xff])))
|
||||
|| (mimeType === 'image/png' && image.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])))
|
||||
|| (mimeType === 'image/webp' && image.toString('ascii', 0, 4) === 'RIFF' && image.toString('ascii', 8, 12) === 'WEBP');
|
||||
if (!valid) throw new Error(`照片 ${slot} 内容与格式不符`);
|
||||
return { mimeType, image };
|
||||
}
|
||||
|
||||
function listRecords(keyword = '') {
|
||||
const query = String(keyword ?? '').trim();
|
||||
if (query.length > 60) throw new Error('搜索关键词不能超过 60 字');
|
||||
return query ? searchStmt.all(query, query, query, query, query) : listStmt.all();
|
||||
}
|
||||
function getRecord(id) { return getStmt.get(id); }
|
||||
function getPhoto(id, slot) { return photoStmt.get(id, slot); }
|
||||
function getRecords(ids) {
|
||||
const wanted = new Set(ids);
|
||||
return listRecords().filter(record => wanted.has(record.id));
|
||||
}
|
||||
function deleteRecord(id) {
|
||||
const result = db.prepare('DELETE FROM records WHERE id = ?').run(id);
|
||||
return result.changes > 0;
|
||||
}
|
||||
|
||||
function register(input) {
|
||||
if (!input || typeof input !== 'object' || Array.isArray(input)) throw new Error('登记内容格式无效');
|
||||
const serialNo = String(input.serialNo || '').trim();
|
||||
const modelName = String(input.modelName || '').trim();
|
||||
const ownerName = String(input.ownerName || '').trim();
|
||||
const requested = String(input.uasCode || '').trim().toUpperCase();
|
||||
if (!/^[A-Za-z0-9-]{6,40}$/.test(serialNo)) throw new Error('SN 须为 6–40 位字母、数字或连字符');
|
||||
if (ownerName.length > 40) throw new Error('登记人不能超过 40 字符');
|
||||
if (modelName.length > 60) throw new Error('机型不能超过 60 字符');
|
||||
if (requested && !/^FPV\d{8}$/.test(requested)) throw new Error('FPV 编号须为 FPV 加 8 位数字');
|
||||
const photo1 = decodePhoto(input.photo1, 1);
|
||||
const photo2 = decodePhoto(input.photo2, 2);
|
||||
const existing = bySnStmt.get(serialNo);
|
||||
if (existing && requested && requested !== existing.uasCode) throw new Error('该 SN 已登记其他 FPV 编号');
|
||||
if (!existing && requested && byUasStmt.get(requested)) throw new Error('该 FPV 编号已登记其他 SN');
|
||||
let uasCode = existing?.uasCode || requested;
|
||||
if (!uasCode) {
|
||||
do { uasCode = `FPV${String(crypto.randomInt(100000000)).padStart(8, '0')}`; }
|
||||
while (byUasStmt.get(uasCode));
|
||||
}
|
||||
const id = existing?.id || crypto.randomBytes(18).toString('hex');
|
||||
db.exec('BEGIN IMMEDIATE');
|
||||
try {
|
||||
if (!existing) {
|
||||
db.prepare('INSERT INTO records (id, serial_no, uas_code, model_name, owner_name, created_at) VALUES (?, ?, ?, ?, ?, ?)')
|
||||
.run(id, serialNo, uasCode, modelName, ownerName, new Date().toISOString());
|
||||
} else if (modelName || ownerName) {
|
||||
db.prepare('UPDATE records SET model_name = CASE WHEN ? = \'\' THEN model_name ELSE ? END, owner_name = CASE WHEN ? = \'\' THEN owner_name ELSE ? END WHERE id = ?')
|
||||
.run(modelName, modelName, ownerName, ownerName, id);
|
||||
}
|
||||
if (photo1) upsertPhotoStmt.run(id, 1, photo1.mimeType, photo1.image);
|
||||
if (photo2) upsertPhotoStmt.run(id, 2, photo2.mimeType, photo2.image);
|
||||
db.exec('COMMIT');
|
||||
} catch (error) {
|
||||
db.exec('ROLLBACK');
|
||||
throw error;
|
||||
}
|
||||
return { record: getRecord(id), existing: !!existing };
|
||||
}
|
||||
|
||||
module.exports = { db, listRecords, getRecord, getRecords, getPhoto, register, deleteRecord };
|
||||
@@ -1,95 +0,0 @@
|
||||
// Self-contained ZIP and XLSX generation for offline exports.
|
||||
const zlib = require('node:zlib');
|
||||
|
||||
const crcTable = Array.from({ length: 256 }, (_, start) => {
|
||||
let value = start;
|
||||
for (let bit = 0; bit < 8; bit++) value = value & 1 ? (value >>> 1) ^ 0xedb88320 : value >>> 1;
|
||||
return value >>> 0;
|
||||
});
|
||||
|
||||
function crc32(data) {
|
||||
let value = 0xffffffff;
|
||||
for (const byte of data) value = crcTable[(value ^ byte) & 0xff] ^ (value >>> 8);
|
||||
return (value ^ 0xffffffff) >>> 0;
|
||||
}
|
||||
|
||||
function zip(entries) {
|
||||
const localParts = [];
|
||||
const centralParts = [];
|
||||
let offset = 0;
|
||||
const now = new Date();
|
||||
const dosTime = (now.getHours() << 11) | (now.getMinutes() << 5) | (now.getSeconds() >> 1);
|
||||
const dosDate = (Math.max(1980, now.getFullYear()) - 1980) << 9 | ((now.getMonth() + 1) << 5) | now.getDate();
|
||||
for (const entry of entries) {
|
||||
const name = Buffer.from(entry.name.replaceAll('\\', '/'), 'utf8');
|
||||
if (!name.length || name.length > 65535 || entry.name.includes('..')) throw new Error('导出文件名无效');
|
||||
const data = Buffer.isBuffer(entry.data) ? entry.data : Buffer.from(entry.data, 'utf8');
|
||||
const deflated = zlib.deflateRawSync(data);
|
||||
const compressed = deflated.length < data.length ? deflated : data;
|
||||
const method = compressed === data ? 0 : 8;
|
||||
const checksum = crc32(data);
|
||||
const local = Buffer.alloc(30);
|
||||
local.writeUInt32LE(0x04034b50, 0);
|
||||
local.writeUInt16LE(20, 4);
|
||||
local.writeUInt16LE(0x0800, 6); // UTF-8 filenames
|
||||
local.writeUInt16LE(method, 8);
|
||||
local.writeUInt16LE(dosTime, 10);
|
||||
local.writeUInt16LE(dosDate, 12);
|
||||
local.writeUInt32LE(checksum, 14);
|
||||
local.writeUInt32LE(compressed.length, 18);
|
||||
local.writeUInt32LE(data.length, 22);
|
||||
local.writeUInt16LE(name.length, 26);
|
||||
localParts.push(local, name, compressed);
|
||||
|
||||
const central = Buffer.alloc(46);
|
||||
central.writeUInt32LE(0x02014b50, 0);
|
||||
central.writeUInt16LE(20, 4);
|
||||
central.writeUInt16LE(20, 6);
|
||||
central.writeUInt16LE(0x0800, 8);
|
||||
central.writeUInt16LE(method, 10);
|
||||
central.writeUInt16LE(dosTime, 12);
|
||||
central.writeUInt16LE(dosDate, 14);
|
||||
central.writeUInt32LE(checksum, 16);
|
||||
central.writeUInt32LE(compressed.length, 20);
|
||||
central.writeUInt32LE(data.length, 24);
|
||||
central.writeUInt16LE(name.length, 28);
|
||||
central.writeUInt32LE(offset, 42);
|
||||
centralParts.push(central, name);
|
||||
offset += local.length + name.length + compressed.length;
|
||||
}
|
||||
if (entries.length > 65535) throw new Error('单次导出记录过多');
|
||||
const centralLength = centralParts.reduce((sum, part) => sum + part.length, 0);
|
||||
const end = Buffer.alloc(22);
|
||||
end.writeUInt32LE(0x06054b50, 0);
|
||||
end.writeUInt16LE(entries.length, 8);
|
||||
end.writeUInt16LE(entries.length, 10);
|
||||
end.writeUInt32LE(centralLength, 12);
|
||||
end.writeUInt32LE(offset, 16);
|
||||
return Buffer.concat([...localParts, ...centralParts, end]);
|
||||
}
|
||||
|
||||
const xml = value => String(value ?? '').replace(/[&<>"']/g, char => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[char]);
|
||||
|
||||
function excel(records) {
|
||||
const headings = ['模块 SN', 'FPV 编号', '机型', '登记人 / 备注', '登记时间', '照片 1', '照片 2', '档案 ID'];
|
||||
const rows = [headings, ...records.map(record => [
|
||||
record.serialNo, record.uasCode, record.modelName, record.ownerName,
|
||||
record.createdAt, record.photo1 ? '有' : '无', record.photo2 ? '有' : '无', record.id,
|
||||
])];
|
||||
const rowXml = rows.map((row, rowIndex) => `<row r="${rowIndex + 1}">${row.map((value, columnIndex) => {
|
||||
const cell = `${String.fromCharCode(65 + columnIndex)}${rowIndex + 1}`;
|
||||
return `<c r="${cell}" t="inlineStr"${rowIndex === 0 ? ' s="1"' : ''}><is><t xml:space="preserve">${xml(value)}</t></is></c>`;
|
||||
}).join('')}</row>`).join('');
|
||||
const lastRow = rows.length;
|
||||
const worksheet = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?><worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><sheetViews><sheetView workbookViewId="0"><pane ySplit="1" topLeftCell="A2" activePane="bottomLeft" state="frozen"/></sheetView></sheetViews><cols>${[25, 19, 20, 24, 25, 10, 10, 40].map((width, i) => `<col min="${i + 1}" max="${i + 1}" width="${width}" customWidth="1"/>`).join('')}</cols><sheetData>${rowXml}</sheetData><autoFilter ref="A1:H${lastRow}"/></worksheet>`;
|
||||
return zip([
|
||||
{ name: '[Content_Types].xml', data: '<?xml version="1.0" encoding="UTF-8"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Override PartName="/xl/workbook.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml"/><Override PartName="/xl/worksheets/sheet1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml"/><Override PartName="/xl/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml"/></Types>' },
|
||||
{ name: '_rels/.rels', data: '<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="xl/workbook.xml"/></Relationships>' },
|
||||
{ name: 'xl/workbook.xml', data: '<?xml version="1.0" encoding="UTF-8"?><workbook xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"><sheets><sheet name="FPV-RID 登记记录" sheetId="1" r:id="rId1"/></sheets></workbook>' },
|
||||
{ name: 'xl/_rels/workbook.xml.rels', data: '<?xml version="1.0" encoding="UTF-8"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/worksheet" Target="worksheets/sheet1.xml"/><Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/></Relationships>' },
|
||||
{ name: 'xl/styles.xml', data: '<?xml version="1.0" encoding="UTF-8"?><styleSheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><fonts count="2"><font><sz val="11"/><name val="Microsoft YaHei"/></font><font><b/><sz val="11"/><color rgb="FFFFFFFF"/><name val="Microsoft YaHei"/></font></fonts><fills count="3"><fill><patternFill patternType="none"/></fill><fill><patternFill patternType="gray125"/></fill><fill><patternFill patternType="solid"><fgColor rgb="FF206D9F"/><bgColor indexed="64"/></patternFill></fill></fills><borders count="1"><border><left/><right/><top/><bottom/><diagonal/></border></borders><cellStyleXfs count="1"><xf numFmtId="0" fontId="0" fillId="0" borderId="0"/></cellStyleXfs><cellXfs count="2"><xf numFmtId="0" fontId="0" fillId="0" borderId="0" xfId="0"/><xf numFmtId="0" fontId="1" fillId="2" borderId="0" xfId="0" applyFont="1" applyFill="1"/></cellXfs></styleSheet>' },
|
||||
{ name: 'xl/worksheets/sheet1.xml', data: worksheet },
|
||||
]);
|
||||
}
|
||||
|
||||
module.exports = { zip, excel };
|
||||
File diff suppressed because one or more lines are too long
@@ -1,274 +0,0 @@
|
||||
const $ = id => document.getElementById(id);
|
||||
let activeRecord = null;
|
||||
let listedRecords = [];
|
||||
const selectedIds = new Set();
|
||||
let listRequestId = 0;
|
||||
let searchTimer;
|
||||
|
||||
function setMessage(message, error = false) {
|
||||
$('form-message').textContent = message;
|
||||
$('form-message').classList.toggle('error', error);
|
||||
}
|
||||
|
||||
function setHistoryMessage(message, error = false) {
|
||||
$('history-message').textContent = message;
|
||||
$('history-message').classList.toggle('error', error);
|
||||
}
|
||||
|
||||
function updateSelectionControls() {
|
||||
const count = selectedIds.size;
|
||||
$('selected-count').textContent = `(${count})`;
|
||||
$('select-all').checked = listedRecords.length > 0 && count === listedRecords.length;
|
||||
$('select-all').indeterminate = count > 0 && count < listedRecords.length;
|
||||
$('export-archive').disabled = count === 0;
|
||||
$('export-excel').disabled = count === 0;
|
||||
}
|
||||
|
||||
function formatTime(iso) {
|
||||
try { return new Date(iso).toLocaleString('zh-CN', { hour12: false }); }
|
||||
catch { return iso; }
|
||||
}
|
||||
|
||||
async function readPhoto(input, slot) {
|
||||
const file = input.files?.[0];
|
||||
if (!file) return null;
|
||||
if (!['image/jpeg', 'image/png', 'image/webp'].includes(file.type)) throw new Error(`照片 ${slot} 仅支持 JPG、PNG 或 WebP`);
|
||||
if (file.size > 5 * 1024 * 1024) throw new Error(`照片 ${slot} 不能超过 5 MB`);
|
||||
return await new Promise((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
reader.onload = () => resolve(reader.result);
|
||||
reader.onerror = () => reject(new Error(`照片 ${slot} 读取失败`));
|
||||
reader.readAsDataURL(file);
|
||||
});
|
||||
}
|
||||
|
||||
function drawRecord(record) {
|
||||
activeRecord = record;
|
||||
$('empty-result').hidden = true;
|
||||
$('record-result').hidden = false;
|
||||
$('display-uas').textContent = record.uasCode;
|
||||
$('display-sn').textContent = record.serialNo;
|
||||
$('display-model').textContent = record.modelName || '—';
|
||||
$('display-owner').textContent = record.ownerName || '—';
|
||||
$('display-url').textContent = record.qrUrl;
|
||||
$('open-card').href = record.archiveUrl;
|
||||
$('download-card').href = record.downloadArchiveUrl;
|
||||
$('saved-photos').hidden = !record.photo1Url && !record.photo2Url;
|
||||
for (const [slot, url] of [[1, record.photo1Url], [2, record.photo2Url]]) {
|
||||
const link = $(`photo-${slot}-link`);
|
||||
link.hidden = !url;
|
||||
if (url) {
|
||||
link.href = url;
|
||||
$(`photo-${slot}-preview`).src = `${url}?v=${Date.now()}`;
|
||||
}
|
||||
}
|
||||
const qr = qrcode(0, 'M');
|
||||
qr.addData(record.qrUrl);
|
||||
qr.make();
|
||||
$('qr-stage').innerHTML = qr.createSvgTag({ cellSize: 6, margin: 4 });
|
||||
}
|
||||
|
||||
async function loadRecords() {
|
||||
const requestId = ++listRequestId;
|
||||
const query = $('history-query').value.trim();
|
||||
const response = await fetch(`/api/records?q=${encodeURIComponent(query)}`);
|
||||
const payload = await response.json();
|
||||
if (!response.ok) throw new Error(payload.error || '读取记录失败');
|
||||
if (requestId !== listRequestId) return;
|
||||
const body = $('history-cards');
|
||||
body.replaceChildren();
|
||||
listedRecords = payload.records;
|
||||
$('search-count').textContent = query ? `${listedRecords.length} 条` : '';
|
||||
const currentIds = new Set(listedRecords.map(record => record.id));
|
||||
for (const id of selectedIds) if (!currentIds.has(id)) selectedIds.delete(id);
|
||||
$('history-empty').hidden = listedRecords.length > 0;
|
||||
$('history-empty').textContent = query ? '没有找到匹配的档案。' : '暂无登记记录。';
|
||||
for (const record of listedRecords) {
|
||||
const card = document.createElement('article');
|
||||
card.className = 'archive-card';
|
||||
card.classList.toggle('selected', selectedIds.has(record.id));
|
||||
const select = document.createElement('label');
|
||||
select.className = 'archive-select';
|
||||
const checkbox = document.createElement('input');
|
||||
checkbox.type = 'checkbox';
|
||||
checkbox.checked = selectedIds.has(record.id);
|
||||
checkbox.setAttribute('aria-label', `选择档案 ${record.serialNo}`);
|
||||
checkbox.addEventListener('change', () => {
|
||||
if (checkbox.checked) selectedIds.add(record.id); else selectedIds.delete(record.id);
|
||||
card.classList.toggle('selected', checkbox.checked);
|
||||
updateSelectionControls();
|
||||
});
|
||||
select.append(checkbox, document.createTextNode('导出'));
|
||||
const title = document.createElement('h3');
|
||||
title.textContent = record.serialNo;
|
||||
const code = document.createElement('strong');
|
||||
code.textContent = record.uasCode;
|
||||
const detail = document.createElement('p');
|
||||
detail.textContent = `${record.modelName || '未填机型'} · ${record.ownerName || '未填登记人'} · ${formatTime(record.createdAt)}`;
|
||||
const images = document.createElement('div');
|
||||
images.className = 'archive-thumbs';
|
||||
for (const [slot, url] of [[1, record.photo1Url], [2, record.photo2Url]]) {
|
||||
const thumb = document.createElement('div');
|
||||
if (url) {
|
||||
const image = document.createElement('img');
|
||||
image.src = url;
|
||||
image.alt = `登记照片 ${slot}`;
|
||||
image.loading = 'lazy';
|
||||
thumb.append(image);
|
||||
} else {
|
||||
thumb.textContent = `照片 ${slot} 未上传`;
|
||||
}
|
||||
images.append(thumb);
|
||||
}
|
||||
const actions = document.createElement('div');
|
||||
actions.className = 'archive-actions';
|
||||
const open = document.createElement('a');
|
||||
open.href = record.archiveUrl;
|
||||
open.target = '_blank';
|
||||
open.rel = 'noopener';
|
||||
open.textContent = '打开档案卡';
|
||||
const download = document.createElement('a');
|
||||
download.href = record.downloadArchiveUrl;
|
||||
download.textContent = '下载离线档案卡';
|
||||
const showQr = document.createElement('button');
|
||||
showQr.type = 'button';
|
||||
showQr.textContent = '查看二维码';
|
||||
showQr.addEventListener('click', () => { drawRecord(record); $('result-title').scrollIntoView({ behavior: 'smooth' }); });
|
||||
const remove = document.createElement('button');
|
||||
remove.type = 'button';
|
||||
remove.className = 'delete-record';
|
||||
remove.textContent = '删除档案';
|
||||
remove.addEventListener('click', async () => {
|
||||
if (!confirm(`确定删除 ${record.serialNo} 的登记档案和照片吗?`)) return;
|
||||
remove.disabled = true;
|
||||
try {
|
||||
const response = await fetch(`/api/records/${record.id}`, { method: 'DELETE' });
|
||||
const payload = await response.json();
|
||||
if (!response.ok) throw new Error(payload.error || '删除失败');
|
||||
selectedIds.delete(record.id);
|
||||
if (activeRecord?.id === record.id) {
|
||||
activeRecord = null;
|
||||
$('record-result').hidden = true;
|
||||
$('empty-result').hidden = false;
|
||||
}
|
||||
await loadRecords();
|
||||
setHistoryMessage(`已删除 ${record.serialNo} 的档案。`);
|
||||
} catch (error) { setHistoryMessage(error.message, true); remove.disabled = false; }
|
||||
});
|
||||
actions.append(open, download, showQr, remove);
|
||||
card.append(select, title, code, detail, images, actions);
|
||||
body.append(card);
|
||||
}
|
||||
updateSelectionControls();
|
||||
}
|
||||
|
||||
$('register-form').addEventListener('submit', async event => {
|
||||
event.preventDefault();
|
||||
const button = $('register-button');
|
||||
button.disabled = true;
|
||||
setMessage('正在保存本地记录…');
|
||||
const uasDigits = $('uas-code').value.trim();
|
||||
try {
|
||||
const [photo1, photo2] = await Promise.all([
|
||||
readPhoto($('photo-1'), 1),
|
||||
readPhoto($('photo-2'), 2),
|
||||
]);
|
||||
const response = await fetch('/api/records', {
|
||||
method: 'POST', headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
serialNo: $('serial-no').value.trim(),
|
||||
modelName: $('model-name').value.trim(),
|
||||
ownerName: $('owner-name').value.trim(),
|
||||
uasCode: uasDigits ? `FPV${uasDigits}` : '',
|
||||
photo1, photo2,
|
||||
}),
|
||||
});
|
||||
const payload = await response.json();
|
||||
if (!response.ok) throw new Error(payload.error || '保存失败');
|
||||
drawRecord(payload.record);
|
||||
setMessage(payload.existing ? '该 SN 已登记,照片和填写的信息已保存。' : '登记成功,二维码已生成。');
|
||||
await loadRecords();
|
||||
} catch (error) { setMessage(error.message, true); }
|
||||
finally { button.disabled = false; }
|
||||
});
|
||||
|
||||
$('refresh-list').addEventListener('click', () => loadRecords().catch(error => setMessage(error.message, true)));
|
||||
$('history-query').addEventListener('input', () => {
|
||||
clearTimeout(searchTimer);
|
||||
listRequestId++;
|
||||
selectedIds.clear();
|
||||
document.querySelectorAll('.archive-card').forEach(card => {
|
||||
card.classList.remove('selected');
|
||||
card.querySelector('.archive-select input').checked = false;
|
||||
});
|
||||
updateSelectionControls();
|
||||
searchTimer = setTimeout(() => loadRecords().catch(error => setHistoryMessage(error.message, true)), 180);
|
||||
});
|
||||
$('select-all').addEventListener('change', event => {
|
||||
selectedIds.clear();
|
||||
if (event.target.checked) for (const record of listedRecords) selectedIds.add(record.id);
|
||||
document.querySelectorAll('.archive-card').forEach((card, index) => {
|
||||
const checked = selectedIds.has(listedRecords[index].id);
|
||||
card.querySelector('.archive-select input').checked = checked;
|
||||
card.classList.toggle('selected', checked);
|
||||
});
|
||||
updateSelectionControls();
|
||||
});
|
||||
|
||||
async function exportSelected(kind) {
|
||||
const ids = [...selectedIds];
|
||||
if (!ids.length) return;
|
||||
const button = $(kind === 'archive' ? 'export-archive' : 'export-excel');
|
||||
button.disabled = true;
|
||||
setHistoryMessage(`正在导出 ${ids.length} 条档案…`);
|
||||
try {
|
||||
const response = await fetch(`/api/export/${kind}`, {
|
||||
method: 'POST', headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ ids }),
|
||||
});
|
||||
if (!response.ok) {
|
||||
const payload = await response.json();
|
||||
throw new Error(payload.error || '导出失败');
|
||||
}
|
||||
const link = document.createElement('a');
|
||||
const url = URL.createObjectURL(await response.blob());
|
||||
link.href = url;
|
||||
link.download = kind === 'archive' ? 'FPV-RID-档案库.zip' : 'FPV-RID-登记记录.xlsx';
|
||||
document.body.append(link);
|
||||
link.click();
|
||||
link.remove();
|
||||
setTimeout(() => URL.revokeObjectURL(url), 30000);
|
||||
setHistoryMessage(`已导出 ${ids.length} 条档案。`);
|
||||
} catch (error) { setHistoryMessage(error.message, true); }
|
||||
finally { updateSelectionControls(); }
|
||||
}
|
||||
$('export-archive').addEventListener('click', () => exportSelected('archive'));
|
||||
$('export-excel').addEventListener('click', () => exportSelected('excel'));
|
||||
$('copy-url').addEventListener('click', async () => {
|
||||
if (!activeRecord) return;
|
||||
try { await navigator.clipboard.writeText(activeRecord.qrUrl); setMessage('本地二维码链接已复制。'); }
|
||||
catch { setMessage('复制失败,可从“二维码内容”手动复制。', true); }
|
||||
});
|
||||
$('download-qr').addEventListener('click', async () => {
|
||||
if (!activeRecord) return;
|
||||
const svg = $('qr-stage').querySelector('svg');
|
||||
if (!svg) return;
|
||||
const blob = new Blob([new XMLSerializer().serializeToString(svg)], { type: 'image/svg+xml' });
|
||||
const url = URL.createObjectURL(blob);
|
||||
try {
|
||||
const image = new Image();
|
||||
await new Promise((resolve, reject) => { image.onload = resolve; image.onerror = reject; image.src = url; });
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = 640; canvas.height = 640;
|
||||
const context = canvas.getContext('2d');
|
||||
context.fillStyle = '#fff'; context.fillRect(0, 0, 640, 640);
|
||||
context.drawImage(image, 0, 0, 640, 640);
|
||||
const link = document.createElement('a');
|
||||
link.href = canvas.toDataURL('image/png');
|
||||
link.download = `${activeRecord.serialNo}-${activeRecord.uasCode}-LOCAL.png`;
|
||||
link.click();
|
||||
} catch { setMessage('二维码图片下载失败。', true); }
|
||||
finally { URL.revokeObjectURL(url); }
|
||||
});
|
||||
|
||||
loadRecords().catch(error => setMessage(error.message, true));
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 34 KiB |
@@ -1,88 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="color-scheme" content="light">
|
||||
<title>FPV-RID · 本地登记与核验</title>
|
||||
<link rel="icon" type="image/png" href="/fpv-rid-icon.png">
|
||||
<link rel="stylesheet" href="/app.css">
|
||||
<script defer src="/vendor/qrcode.js"></script>
|
||||
<script defer src="/app.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div class="shell">
|
||||
<header class="topbar">
|
||||
<img class="brand-mark" src="/fpv-rid-icon.png" alt="FPV-RID 图标">
|
||||
<div class="brand-copy"><strong>FPV-RID</strong><small>本地登记工作台</small></div>
|
||||
<div class="top-status"><i></i> 仅在本机运行</div>
|
||||
</header>
|
||||
|
||||
<main>
|
||||
<section class="hero">
|
||||
<div>
|
||||
<h1>登记设备,生成本地二维码</h1>
|
||||
<p>为模块 SN 建立本机记录。二维码交给配套的本地版上位机扫描,校验 SN 后再由上位机完成设备操作。</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<div class="columns">
|
||||
<section class="panel form-panel" aria-labelledby="register-title">
|
||||
<div class="panel-head"><div><span class="step">01</span><h2 id="register-title">新建设备登记</h2></div><span class="subtle">同一 SN 只保留一条记录</span></div>
|
||||
<form id="register-form">
|
||||
<label for="serial-no">模块 SN <em>必填</em></label>
|
||||
<input id="serial-no" name="serialNo" required maxlength="40" autocomplete="off" placeholder="例如 ZEX0RID1202605011000" pattern="[A-Za-z0-9-]{6,40}">
|
||||
<p class="hint">请与上位机“RID 模块状态信息”里的 SN 完全一致。</p>
|
||||
|
||||
<div class="field-grid">
|
||||
<div><label for="model-name">机型</label><input id="model-name" name="modelName" maxlength="60" placeholder="例如 5 寸穿越机"></div>
|
||||
<div><label for="owner-name">登记人 / 备注</label><input id="owner-name" name="ownerName" maxlength="40" placeholder="可选"></div>
|
||||
</div>
|
||||
|
||||
<label for="uas-code">FPV 编号 <span class="optional">可选</span></label>
|
||||
<div class="input-prefix"><span>FPV</span><input id="uas-code" name="uasDigits" maxlength="8" inputmode="numeric" pattern="[0-9]{8}" placeholder="留空则自动生成 8 位数字"></div>
|
||||
<p class="hint">已有 FPV 编号可输入后 8 位数字;留空则自动生成。</p>
|
||||
|
||||
<div class="field-grid photo-fields">
|
||||
<div><label for="photo-1">登记照片 1 <span class="optional">可选</span></label><input id="photo-1" type="file" accept="image/jpeg,image/png,image/webp"></div>
|
||||
<div><label for="photo-2">登记照片 2 <span class="optional">可选</span></label><input id="photo-2" type="file" accept="image/jpeg,image/png,image/webp"></div>
|
||||
</div>
|
||||
<p class="hint">每张最多 5 MB,支持 JPG、PNG 和 WebP。照片保存在本机数据库;同一 SN 再次保存可补充或替换照片。</p>
|
||||
|
||||
<button class="primary" id="register-button" type="submit">保存登记并生成二维码 <span aria-hidden="true">→</span></button>
|
||||
<p class="form-message" id="form-message" role="status"></p>
|
||||
</form>
|
||||
</section>
|
||||
|
||||
<section class="panel result-panel" aria-labelledby="result-title">
|
||||
<div class="panel-head"><div><span class="step muted">02</span><h2 id="result-title">二维码与核验</h2></div><span class="subtle">同机使用</span></div>
|
||||
<div id="empty-result" class="empty-state"><div class="empty-glyph">▦</div><b>等待登记</b><span>保存后在这里生成二维码,供本地版上位机读取。</span></div>
|
||||
<div id="record-result" class="record-result" hidden>
|
||||
<div class="qr-stage" id="qr-stage" aria-label="本地登记二维码"></div>
|
||||
<div class="record-kicker">本地记录已保存</div>
|
||||
<div class="uas-display" id="display-uas"></div>
|
||||
<dl class="result-fields"><div><dt>Serial No.</dt><dd id="display-sn"></dd></div><div><dt>机型</dt><dd id="display-model"></dd></div><div><dt>登记人</dt><dd id="display-owner"></dd></div></dl>
|
||||
<div class="saved-photos" id="saved-photos" hidden>
|
||||
<a id="photo-1-link" target="_blank" rel="noopener" hidden><img id="photo-1-preview" alt="登记照片 1"><span>照片 1</span></a>
|
||||
<a id="photo-2-link" target="_blank" rel="noopener" hidden><img id="photo-2-preview" alt="登记照片 2"><span>照片 2</span></a>
|
||||
</div>
|
||||
<div class="url-box"><span>二维码内容</span><code id="display-url"></code></div>
|
||||
<div class="result-actions"><button id="download-qr" class="secondary" type="button">下载二维码 PNG</button><button id="copy-url" class="ghost" type="button">复制链接</button></div>
|
||||
<div class="result-actions"><a id="open-card" class="secondary action-link" target="_blank" rel="noopener">打开档案卡</a><a id="download-card" class="ghost action-link">下载离线档案卡</a></div>
|
||||
<p class="result-tip">在本机同时启动登记站和本地版上位机,上传此二维码。上位机会从本地记录读取字段并比对模块 SN。</p>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<section class="panel history-panel" aria-labelledby="history-title">
|
||||
<div class="panel-head history-head"><div><span class="step muted">03</span><h2 id="history-title">本地登记记录</h2></div><div class="history-controls"><div class="history-search"><input id="history-query" type="search" maxlength="60" autocomplete="off" aria-label="搜索登记档案" placeholder="搜索 SN、FPV 编号、机型、登记人"><span id="search-count" aria-live="polite"></span></div><label class="select-all"><input id="select-all" type="checkbox">全选 <span id="selected-count">(0)</span></label><button id="export-archive" class="export-button" type="button" disabled>导出档案包</button><button id="export-excel" class="export-button" type="button" disabled>导出 Excel</button><button id="refresh-list" class="text-button" type="button">刷新记录</button></div></div>
|
||||
<p class="history-message" id="history-message" role="status">导出档案包包含离线档案卡、照片和登记信息;Excel 导出为登记表。</p>
|
||||
<div id="history-empty" class="history-empty">暂无登记记录。</div>
|
||||
<div id="history-cards" class="history-cards"></div>
|
||||
</section>
|
||||
</main>
|
||||
|
||||
<footer><span>127.0.0.1:8787 · 数据保存在本机</span></footer>
|
||||
</div>
|
||||
</body>
|
||||
</html>
|
||||
-21
@@ -1,21 +0,0 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2009 Kazuhiko Arase
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
Vendored
-2297
File diff suppressed because it is too large
Load Diff
@@ -1,254 +0,0 @@
|
||||
// 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, 'legacy-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 => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[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); }
|
||||
});
|
||||
Reference in New Issue
Block a user