commit 26afff492636cbe473a8d558c45090b0057e8455 Author: zhangshuochi <1774240792@qq.com> Date: Tue Oct 20 11:41:04 2026 +0800 Initial commit: organize FPV RID local registry source diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..19e5e93 --- /dev/null +++ b/.gitignore @@ -0,0 +1,11 @@ +# 运行时生成的真实备案与照片;不要提交到源码仓库 +registry/data/ +档案库/ + +# 从原版自行复制的运行程序、上位机程序 +runtime/ +host/ + +# 临时文件 +*.tmp +*.log diff --git a/README.md b/README.md new file mode 100644 index 0000000..140bb57 --- /dev/null +++ b/README.md @@ -0,0 +1,45 @@ +# Rid_Drone_Receivev + +FPV-RID 本地备案源码(新版2整理版)。对应 GitHub 仓库:`zhangshuochi/Rid_Drone_Receivev`。 + +这份工程从你指定的 **`FPV-RID_本地登记验证_新版2`** 提取。业务源码保持原版内容,新增了启动入口和开发说明,方便后续维护和与 RID 监管平台联动。原桌面目录未改动。 + +## 一句话看懂 + +在本机网页填写 RID 模块 SN、机型、登记人和照片 → SQLite 保存备案 → 生成本地二维码及离线档案卡。配套上位机读取该记录、核对 SN,并负责向模块写入 FPV 编号。 + +## 目录 + +| 位置 | 用途 | +| --- | --- | +| `registry/server.js` | 本地 HTTP 服务、接口、离线档案卡和档案备份 | +| `registry/database.js` | SQLite 表、登记、搜索、删除、照片保存 | +| `registry/export-files.js` | ZIP 档案包和 Excel 导出 | +| `registry/web/` | 登记网页、样式、二维码脚本和图标 | +| `docs/原版使用说明.md` | 新版2附带的原始说明 | +| `docs/架构与RID联动.md` | 数据流、字段和对接方式 | +| `docs/接口清单.md` | 本地 HTTP 接口说明 | +| `启动源码版.cmd` | Windows 启动入口 | + +## 启动 + +1. 使用 **Node.js 24**。原版自带的是 **24.19.0**;本包不重复附带 `node.exe`。可以安装 Node.js,或从你原版目录把 `runtime/node.exe` 复制到本包的 `runtime/node.exe`。 +2. 双击 `启动源码版.cmd`,保持命令窗口打开。 +3. 在同一台电脑的浏览器打开 `http://127.0.0.1:8787/`。 + +项目没有 npm 第三方依赖,二维码脚本已随源码保存。如果原版登记站正在运行,先关闭原版;两个实例都使用 8787 端口。 + +## 已有备案数据怎么迁移 + +**本包不包含实际备案信息。** 正在使用的数据库可能被锁定,直接复制可能拿到不完整文件。迁移时先关闭原版登记站,再将原版的 `registry/data/registry.sqlite` 复制到本包相同位置,然后启动本包。`档案库/` 会按数据库重新生成档案卡和备份;如需保留原有备份历史,也先单独备份原版整个 `档案库/`。 + +不要把空数据库覆盖到原版。原版的 `host/FPV-RID-本地FPV版.exe` 是单独的上位机程序,当前提供的目录里只有可执行文件,没有其源码。本源码包只整理登记站;上位机仍可按原版说明单独使用。 + +## 后续开发先看哪里 + +- 改登记表单和页面:`registry/web/index.html`、`app.js`、`app.css`。 +- 改校验规则或查询:`registry/database.js`。 +- 改本地接口和档案卡:`registry/server.js`。 +- 接入无人机监管平台:先看 `docs/架构与RID联动.md`。备案记录可用于判断“已备案 / 未匹配”,RID 实时坐标仍由基站上报。 + +当前服务仅监听 `127.0.0.1`,没有登录认证。要让局域网内的其他电脑读取档案,应由 RID 平台后端做受控同步接口,不能直接把这个本地服务改成对全网开放。 diff --git a/SOURCE_MANIFEST.sha256 b/SOURCE_MANIFEST.sha256 new file mode 100644 index 0000000..8b93aaf --- /dev/null +++ b/SOURCE_MANIFEST.sha256 @@ -0,0 +1,9 @@ +71932C28FC2DB6F009BA2EFEA5D1A78BA1429FE16CE205C17AACBE9708473AF5 registry\database.js +E349E2DD600F2998D9EDAD52AFA276076D1FCBB99B152C368C8BF504C0DFF8CF registry\export-files.js +D68399ADF71A28B971C722FFAA4EDB380CB474B29893793EDF94DFA652E36C53 registry\server.js +52F9458B7DE7AA8668A18001A94D33F3F7F737872B4B24084AA49606C8CA699F registry\web\app.css +4F5C9EC61F7B1AF7ACBA4C4AE1F7F224A6276011BA28BDA35BA43215389FCFF1 registry\web\app.js +C08BBBE6447917EF8C316FCB03113334C94025477AE17934AE4FBBA0D904D906 registry\web\index.html +73D51105CBE3790D0967D20A32359D193CD31461D754E4CDA802C94757226A7C registry\web\fpv-rid-icon.png +79EC86F82856005B1C887905CFCCFCFBEC3821CA61C7FD5A952FAA5F778F791C registry\web\vendor\qrcode.js +3A850FA5F08101DB6F40676C2786E10BD2CD5FFF7B12FFDF1E0C434D4E49D90C registry\web\vendor\LICENSE.txt diff --git a/docs/原版使用说明.md b/docs/原版使用说明.md new file mode 100644 index 0000000..aba4dc6 --- /dev/null +++ b/docs/原版使用说明.md @@ -0,0 +1,21 @@ +# FPV-RID 本地登记与验证 + +## 打开 + +双击 `启动本地登记站.cmd`,在同一台电脑打开 `http://127.0.0.1:8787/`。双击 `打开FPV-RID上位机.cmd` 可启动新版上位机(程序位于 `host/FPV-RID-本地FPV版.exe`)。两个程序须在同一台电脑运行。 + +## 登记与绑定 + +输入模块 SN,可填写机型、登记人、两张照片和 FPV 编号的后 8 位数字。留空时自动生成 `FPV` 加 8 位数字。二维码指向本机档案卡;上位机从本地网站读取记录、比对模块 SN,然后通过 `$WRITE_UOM:FPVxxxxxxxx` 将完整 FPV 编号写入模块。已有 UOM 绑定的模块可能拒绝再次写入,此时需按设备原有流程处理绑定状态。 + +## 档案与导出 + +- 网站数据库:`registry/data/registry.sqlite`。 +- 自动档案库:`档案库/`。每条登记都有内含照片的离线 HTML 档案卡,另有 `记录索引.json` 和数据库最新、上一次备份。 +- 勾选单条或使用“全选”,可导出 ZIP 档案包(离线档案卡、照片原件、JSON 索引)或 Excel `.xlsx` 登记表。Excel 登记表列出照片有无;照片原件在 ZIP 档案包中。 +- 记录区可按模块 SN、FPV 编号、机型或登记人搜索;“全选”只选中当前搜索结果。 +- 每张档案卡有“删除档案”。删除后记录及照片从网站数据库和自动档案库移除。导出到电脑其他位置的文件不会自动删除。 + +本地生成的编号与二维码用于本机登记和模块操作;官方登记状态需以官方系统为准。 + +更新程序时请保留现有的 `registry/data/registry.sqlite` 和 `档案库/`,不要用新压缩包里的空数据库覆盖已有档案。 diff --git a/docs/接口清单.md b/docs/接口清单.md new file mode 100644 index 0000000..61224a6 --- /dev/null +++ b/docs/接口清单.md @@ -0,0 +1,36 @@ +# 本地接口清单(基于新版2源码) + +服务地址:`http://127.0.0.1:8787`。以下是现有功能,均由 `registry/server.js` 提供。 + +| 方法和路径 | 用途 | +| --- | --- | +| `GET /api/records?q=关键词` | 列出/搜索备案;结果为 `{ "records": [...] }` | +| `POST /api/records` | 新增或更新登记及照片 | +| `DELETE /api/records/:id` | 删除记录和照片,并同步档案库 | +| `GET /api/records/:id/photos/1` | 第一张照片;`2` 是第二张 | +| `GET /api/records/:id/archive` | 下载单条离线 HTML 档案卡 | +| `POST /api/export/archive` | 按 `ids` 数组导出 ZIP | +| `POST /api/export/excel` | 按 `ids` 数组导出 Excel | +| `GET /api/resolve?url=二维码内容` | 解析本机生成的登记二维码 | +| `GET /r/:id` | 查看档案卡网页 | + +一条记录的主要返回字段: + +```json +{ + "id": "示意:36位十六进制档案ID", + "serialNo": "示意模块SN", + "uasCode": "FPV12345678", + "modelName": "示意机型", + "ownerName": "示意登记人", + "createdAt": "ISO时间", + "source": "local-fpv-registry", + "qrUrl": "http://127.0.0.1:8787/r/档案ID", + "archiveUrl": "/r/档案ID", + "downloadArchiveUrl": "/api/records/档案ID/archive", + "photo1Url": null, + "photo2Url": null +} +``` + +以上为字段示意,不是实际备案数据。接口无账号认证,只监听本机;局域网共享前需要单独设计身份验证与授权。`GET /api/records` 包含登记人字段,因此平台同步时应限制调用端和前端展示范围。 diff --git a/docs/架构与RID联动.md b/docs/架构与RID联动.md new file mode 100644 index 0000000..ee9586d --- /dev/null +++ b/docs/架构与RID联动.md @@ -0,0 +1,46 @@ +# 源码结构与 RID 平台联动 + +## 现有数据怎么走 + +```mermaid +flowchart LR + A[用户在本机网页登记] --> B[server.js] + B --> C[database.js / SQLite] + C --> D[档案库 / 离线档案卡和备份] + B --> E[网页二维码] + E --> F[本地版上位机] + F --> G[核对模块 SN 并写入 FPV 编号] +``` + +这份源码只负责**备案**。地图上的无人机位置、飞手位置、航线和基站状态,仍来自你规划的 RID 基站采集链路,不来自备案库。 + +## 数据表(现有代码) + +`registry/data/registry.sqlite` 中有两张表: + +| 表 | 主要字段 | 白话解释 | +| --- | --- | --- | +| `records` | `id`, `serial_no`, `uas_code`, `model_name`, `owner_name`, `created_at` | 一台模块对应一条备案;SN 和 FPV 编号都不能重复 | +| `photos` | `record_id`, `slot`, `mime_type`, `image` | 每条备案最多两张照片,照片二进制保存在数据库中 | + +网页接口把字段转换成驼峰命名,例如 `serial_no` 变为 `serialNo`,`uas_code` 变为 `uasCode`。`ownerName` 目前兼作“登记人 / 备注”,以后若要区分真实飞手和备注,应新增独立字段,不要直接推断两者相同。 + +## 与 RID 实时报文怎么比对 + +RID 报文示例中的 `serial` 可作为候选匹配字段;备案库用 `serialNo` 保存模块 SN。**只有确认基站报送的 `serial` 与备案时填的模块 SN 是同一编号**,才可直接按完全相等匹配。若设备上报的是其他序列号,应建立编号映射表。`uasCode` 是本地 FPV 编号,亦可作为经过核实的辅助匹配键。 + +建议平台显示三种结果: + +- **已匹配备案**:同一编号找到一条本地备案,可显示机型、FPV 编号、登记人。 +- **未匹配备案**:当前库里找不到对应编号;这只说明没有匹配到,不能直接认定违规。 +- **编号待核实**:RID 上报编号与模块 SN 的对应关系尚未确认,避免误关联。 + +同一架无人机可能被多个基站同时接收。平台先对基站报文去重、融合,再拿目标编号查询备案;备案库本身无需处理多基站合并。 + +## 最容易落地的对接方式 + +**登记站与 RID 平台后端在同一台电脑时:** 平台后端读取 `http://127.0.0.1:8787/api/records`,按 `serialNo` 建立备案索引;或读取自动生成的 `档案库/记录索引.json`。只同步文字字段即可,地图不需要原始照片。 + +**分开电脑时:** 在登记站电脑定期导出或同步上述索引,由 RID 平台后端接收。不要把二维码里的 `127.0.0.1` 当作跨电脑地址;它始终指向打开链接的那台电脑。 + +平台后端保存一份备案索引缓存后,前端只显示业务结论和必要字段。涉及 `ownerName`、照片等个人信息时,应按账号权限控制可见范围。 diff --git a/package.json b/package.json new file mode 100644 index 0000000..c92bec6 --- /dev/null +++ b/package.json @@ -0,0 +1,12 @@ +{ + "name": "rid-drone-receivev", + "version": "2.0.0-source", + "private": true, + "description": "FPV-RID 本地登记站新版2源码整理包", + "scripts": { + "start": "node registry/server.js" + }, + "engines": { + "node": ">=24" + } +} diff --git a/registry/database.js b/registry/database.js new file mode 100644 index 0000000..47ab6a4 --- /dev/null +++ b/registry/database.js @@ -0,0 +1,138 @@ +// 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 }; diff --git a/registry/export-files.js b/registry/export-files.js new file mode 100644 index 0000000..c44d4ed --- /dev/null +++ b/registry/export-files.js @@ -0,0 +1,95 @@ +// 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.map((value, columnIndex) => { + const cell = `${String.fromCharCode(65 + columnIndex)}${rowIndex + 1}`; + return `${xml(value)}`; + }).join('')}`).join(''); + const lastRow = rows.length; + const worksheet = `${[25, 19, 20, 24, 25, 10, 10, 40].map((width, i) => ``).join('')}${rowXml}`; + return zip([ + { name: '[Content_Types].xml', data: '' }, + { name: '_rels/.rels', data: '' }, + { name: 'xl/workbook.xml', data: '' }, + { name: 'xl/_rels/workbook.xml.rels', data: '' }, + { name: 'xl/styles.xml', data: '' }, + { name: 'xl/worksheets/sheet1.xml', data: worksheet }, + ]); +} + +module.exports = { zip, excel }; diff --git a/registry/server.js b/registry/server.js new file mode 100644 index 0000000..6cfd229 --- /dev/null +++ b/registry/server.js @@ -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 => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[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 `
未上传照片 ${slot}
照片 ${slot}
`; + const src = standalone ? `data:${photo.mimeType};base64,${Buffer.from(photo.image).toString('base64')}` : `/api/records/${record.id}/photos/${slot}`; + return `
登记照片 ${slot}
登记照片 ${slot}
`; + }).join(''); + return `${escapeHtml(r.serialNo)} · 本地档案卡
本地备案档案卡

${escapeHtml(r.serialNo)}

${escapeHtml(r.uasCode)}
+

本档案卡由 FPV-RID 本地登记软件保存,可离线打开。

+
模块 SN
${escapeHtml(r.serialNo)}
FPV 编号
${escapeHtml(r.uasCode)}
机型
${escapeHtml(r.modelName || '—')}
登记人 / 备注
${escapeHtml(r.ownerName || '—')}
登记时间
${escapeHtml(r.createdAt)}
+

登记照片

${photos}
档案 ID:${escapeHtml(r.id)}
`; +} + +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); } +}); diff --git a/registry/web/app.css b/registry/web/app.css new file mode 100644 index 0000000..1193264 --- /dev/null +++ b/registry/web/app.css @@ -0,0 +1,5 @@ +:root{font-family:Inter,"Segoe UI","Microsoft YaHei",sans-serif;color:#172b40;background:#eef2f6;font-synthesis:none}*{box-sizing:border-box}body{margin:0}button,input{font:inherit}button{cursor:pointer}.shell{max-width:1320px;margin:0 auto;min-height:100vh;background:#f8fafc;box-shadow:0 0 60px #1d3d5912}.topbar{height:76px;background:#fff;border-bottom:1px solid #e4eaf0;display:flex;align-items:center;padding:0 48px;gap:14px}.brand-mark{width:38px;height:38px;background:#144e83;color:white;display:grid;place-items:center;border-radius:10px;font-size:21px;font-weight:900;letter-spacing:-5px;padding-right:6px}.brand-mark span{color:#7fd5f3;font-size:18px;margin-left:-2px}.brand-copy{display:flex;flex-direction:column;line-height:1.15;gap:4px}.brand-copy strong{font-size:17px;letter-spacing:.04em}.brand-copy small{color:#8192a2;font-size:12px}.top-status{margin-left:auto;border:1px solid #cce8d9;background:#f3fbf6;border-radius:999px;color:#187348;font-size:12px;font-weight:700;padding:8px 13px}.top-status i{display:inline-block;width:7px;height:7px;border-radius:50%;background:#2eae6c;margin-right:5px}main{padding:38px 48px 54px}.hero{display:flex;justify-content:space-between;align-items:center;gap:26px;margin-bottom:22px}.eyebrow{color:#4a779b;font-size:11px;font-weight:800;letter-spacing:.2em}.hero h1{font-size:32px;letter-spacing:-.025em;margin:12px 0 10px}.hero p{color:#617488;font-size:14px;line-height:1.7;max-width:720px;margin:0}.hero-aside{display:flex;flex-direction:column;align-items:flex-end;gap:4px;min-width:125px;color:#3a627f;font-size:13px}.hero-aside small{color:#91a0af}.hero-dot{width:40px;height:40px;border-radius:12px;background:linear-gradient(135deg,#dff8ee,#a9e0c7);margin-bottom:2px;position:relative}.hero-dot:after{content:"✓";position:absolute;inset:0;display:grid;place-items:center;color:#13815a;font-size:21px;font-weight:800}.notice{display:flex;align-items:center;gap:14px;background:#fff8e9;border:1px solid #f0ddb0;border-radius:12px;padding:13px 17px;color:#755b28;font-size:13px;margin-bottom:24px}.notice b{white-space:nowrap;color:#7b5314}.columns{display:grid;grid-template-columns:minmax(0,1.03fr) minmax(0,.97fr);gap:22px}.panel{background:#fff;border:1px solid #e2e8ef;border-radius:17px;box-shadow:0 8px 25px #173b5b0a}.form-panel,.result-panel{min-height:570px;padding:26px 28px}.panel-head{display:flex;align-items:center;justify-content:space-between;gap:15px;padding-bottom:24px}.panel-head>div{display:flex;align-items:center;gap:11px}.panel-head h2{font-size:18px;margin:0}.step{width:29px;height:29px;border-radius:8px;background:#dcecf9;color:#1a5d8e;font-weight:800;font-size:12px;display:grid;place-items:center}.step.muted{background:#eef2f6;color:#73879b}.subtle{color:#9aa9b5;font-size:12px}label{font-size:13px;font-weight:700;display:block;margin:0 0 9px}label em{color:#d76254;font-size:11px;font-style:normal;margin-left:6px}label .optional{color:#a2b0bd;font-size:11px;font-weight:500}input{height:45px;width:100%;border:1px solid #d6e0e9;border-radius:9px;background:#fbfcfe;padding:0 13px;color:#1f3448;outline:none;transition:border-color .15s,box-shadow .15s}input:focus{border-color:#3a91cd;box-shadow:0 0 0 3px #3a91cd20}input::placeholder{color:#a7b3be}.hint{margin:7px 0 24px;color:#93a0ae;font-size:11px;line-height:1.5}.field-grid{display:grid;grid-template-columns:1fr 1fr;gap:15px}.field-grid+label{margin-top:3px}.input-prefix{height:45px;display:flex;border:1px solid #d6e0e9;border-radius:9px;overflow:hidden;background:#fbfcfe}.input-prefix span{display:grid;place-items:center;width:58px;background:#edf4f9;color:#2e6d9c;font-weight:800;font-size:13px;border-right:1px solid #d6e0e9}.input-prefix input{border:0;border-radius:0;background:transparent;height:43px}.input-prefix:focus-within{border-color:#3a91cd;box-shadow:0 0 0 3px #3a91cd20}.primary{height:47px;width:100%;border:0;border-radius:9px;background:#206d9f;color:#fff;font-weight:750;display:flex;align-items:center;justify-content:center;gap:12px;box-shadow:0 8px 16px #206d9f26}.primary:hover{background:#155d8d}.primary:disabled{opacity:.55;cursor:wait}.form-message{min-height:18px;margin:12px 0 0;font-size:12px;color:#23724b}.form-message.error{color:#bd4c3b}.empty-state{height:415px;border:1px dashed #d6e1eb;border-radius:12px;background:#fbfcfe;display:flex;align-items:center;justify-content:center;flex-direction:column;color:#9aaab8;gap:9px;text-align:center;padding:20px}.empty-state b{font-size:15px;color:#526b7f}.empty-state span{font-size:12px;max-width:230px;line-height:1.6}.empty-glyph{height:64px;width:64px;border-radius:17px;background:#ecf3f8;color:#93afc2;display:grid;place-items:center;font-size:38px;margin-bottom:6px}.record-result{display:flex;align-items:center;flex-direction:column}.record-result[hidden],.empty-state[hidden],#history-table[hidden],#history-empty[hidden]{display:none}.qr-stage{width:200px;height:200px;display:grid;place-items:center;background:white;border:1px solid #e5ecf2;border-radius:12px;padding:9px;box-shadow:0 8px 22px #183a5a10}.qr-stage svg{max-width:100%;max-height:100%}.record-kicker{font-size:11px;color:#26915f;font-weight:800;margin-top:16px;letter-spacing:.05em}.uas-display{font-size:27px;font-weight:850;letter-spacing:.04em;margin:3px 0 17px;color:#174d78}.result-fields{width:100%;margin:0;border-top:1px solid #edf1f5;border-bottom:1px solid #edf1f5}.result-fields div{display:flex;justify-content:space-between;gap:10px;padding:8px 0;font-size:12px}.result-fields dt{color:#8a9bae}.result-fields dd{margin:0;font-weight:700;text-align:right;overflow-wrap:anywhere}.url-box{align-self:stretch;background:#f4f7fa;border-radius:8px;margin-top:16px;padding:10px 12px;font-size:11px}.url-box span{display:block;color:#92a2b0;margin-bottom:3px}.url-box code{overflow-wrap:anywhere;color:#366987}.result-actions{display:flex;width:100%;gap:10px;margin-top:15px}.secondary,.ghost{height:39px;border-radius:8px;font-size:12px;font-weight:700}.secondary{flex:1;background:#e9f3fa;color:#1a6b9b;border:1px solid #cce2f1}.ghost{flex:1;background:#fff;color:#52718a;border:1px solid #d9e3eb}.result-tip{font-size:11px;color:#95a5b2;line-height:1.55;align-self:stretch;margin:12px 0 0}.history-panel{margin-top:22px;padding:24px 28px}.history-panel .panel-head{padding-bottom:14px}.text-button{border:0;background:none;color:#2879ab;font-size:12px;font-weight:700}.history-empty{color:#9eacb7;font-size:13px;padding:25px 0}.table-scroll{overflow-x:auto}table{width:100%;border-collapse:collapse;text-align:left;font-size:12px}th{background:#f5f8fb;color:#7a8c9d;font-weight:700;padding:11px 13px}td{padding:13px;border-bottom:1px solid #edf1f4;color:#334b60}td code{color:#286e9c;font-weight:700}.show-record{border:0;color:#2677a8;background:none;font-size:12px;font-weight:700}footer{border-top:1px solid #e8edf2;padding:17px 48px 22px;color:#a0acb8;font-size:11px;display:flex;justify-content:space-between}@media(max-width:850px){.topbar{padding:0 22px}main{padding:28px 20px}.columns{grid-template-columns:1fr}.form-panel,.result-panel{min-height:auto}.hero-aside{display:none}footer{padding:18px 22px}}@media(max-width:530px){.hero h1{font-size:25px}.field-grid{grid-template-columns:1fr}.notice{align-items:flex-start;flex-direction:column;gap:5px}.panel-head{align-items:flex-start}.subtle{display:none}.result-actions{flex-direction:column}footer{gap:5px;flex-direction:column}} +.photo-fields{margin-top:4px}.photo-fields input[type=file]{padding:10px;height:auto;min-height:45px;font-size:11px}.photo-fields+.hint{margin-bottom:22px}.saved-photos{align-self:stretch;display:flex;gap:10px;margin-top:12px}.saved-photos[hidden],.saved-photos a[hidden]{display:none}.saved-photos a{width:50%;border:1px solid #e5ecf2;border-radius:8px;overflow:hidden;text-align:center;color:#4a708c;text-decoration:none;font-size:11px;padding:5px}.saved-photos img{width:100%;height:90px;object-fit:contain;background:#f5f8fb;display:block}.saved-photos span{display:block;margin-top:4px} +.action-link{display:grid;place-items:center;text-decoration:none}.history-cards{display:grid;grid-template-columns:repeat(auto-fill,minmax(280px,1fr));gap:14px}.archive-card{border:1px solid #dfe8f0;border-radius:12px;padding:16px;background:#fbfdff}.archive-card h3{font-size:15px;margin:0 0 5px;overflow-wrap:anywhere}.archive-card strong{color:#236d9b;font-size:13px}.archive-card p{color:#8193a3;font-size:11px;line-height:1.5;margin:9px 0 12px}.archive-thumbs{display:grid;grid-template-columns:1fr 1fr;gap:8px}.archive-thumbs>div{height:105px;border:1px solid #e2e9ef;border-radius:7px;background:#f3f7fa;display:grid;place-items:center;color:#a4b1bc;font-size:11px;overflow:hidden}.archive-thumbs img{height:100%;width:100%;object-fit:contain}.archive-actions{display:flex;flex-wrap:wrap;gap:8px;margin-top:13px}.archive-actions a,.archive-actions button{background:#eaf3f9;color:#236f9d;border:1px solid #d0e2ef;border-radius:7px;padding:7px 9px;font-size:11px;font-weight:700;text-decoration:none;cursor:pointer} +.topbar .brand-mark{width:42px;height:42px;object-fit:contain;border-radius:10px;padding:0;letter-spacing:normal;background:#fff}.hero h1{margin-top:0}.history-head{align-items:center}.history-controls{display:flex;align-items:center;justify-content:flex-end;flex-wrap:wrap;gap:10px}.select-all{display:inline-flex;align-items:center;gap:5px;margin:0;color:#49657a;white-space:nowrap;font-size:12px}.select-all input,.archive-select input{width:16px;height:16px;accent-color:#206d9f;cursor:pointer}.export-button{height:34px;padding:0 11px;border:1px solid #c8ddeb;border-radius:7px;background:#e9f3fa;color:#1d6c9c;font-size:12px;font-weight:700}.export-button:disabled{opacity:.48;cursor:not-allowed}.history-message{font-size:11px;line-height:1.55;color:#8a9dad;margin:0 0 14px}.history-message.error{color:#b84036}.archive-card{position:relative}.archive-card.selected{border-color:#4b9bc8;box-shadow:0 0 0 2px #4b9bc820}.archive-select{display:flex;align-items:center;gap:5px;float:right;margin:0 0 8px 10px;color:#59788f;font-size:11px;font-weight:600}.archive-actions .delete-record{background:#fff1ef;color:#b34039;border-color:#f2c9c5}.archive-actions .delete-record:hover{background:#ffe7e3}footer{justify-content:flex-end}@media(max-width:850px){.history-head{align-items:flex-start;flex-direction:column}.history-controls{justify-content:flex-start}}@media(max-width:530px){.history-controls{gap:8px}.export-button{flex:1}} +.history-search{position:relative;width:260px;flex:0 1 260px}.history-search input{height:36px;padding:0 66px 0 12px;font-size:12px;background:#fff}.history-search input::placeholder{color:#8fa1af}.history-search #search-count{position:absolute;right:10px;top:50%;transform:translateY(-50%);color:#6b8294;font-size:11px;white-space:nowrap;pointer-events:none}.history-search #search-count:empty{display:none}@media(max-width:850px){.history-controls{width:100%}.history-search{flex:1 1 260px}}@media(max-width:530px){.history-search{flex-basis:100%;width:100%}} diff --git a/registry/web/app.js b/registry/web/app.js new file mode 100644 index 0000000..e581ded --- /dev/null +++ b/registry/web/app.js @@ -0,0 +1,274 @@ +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)); diff --git a/registry/web/fpv-rid-icon.png b/registry/web/fpv-rid-icon.png new file mode 100644 index 0000000..7309c5d Binary files /dev/null and b/registry/web/fpv-rid-icon.png differ diff --git a/registry/web/index.html b/registry/web/index.html new file mode 100644 index 0000000..8db40e5 --- /dev/null +++ b/registry/web/index.html @@ -0,0 +1,88 @@ + + + + + + + FPV-RID · 本地登记与核验 + + + + + + +
+
+ FPV-RID 图标 +
FPV-RID本地登记工作台
+
仅在本机运行
+
+ +
+
+
+

登记设备,生成本地二维码

+

为模块 SN 建立本机记录。二维码交给配套的本地版上位机扫描,校验 SN 后再由上位机完成设备操作。

+
+
+ +
+
+
01

新建设备登记

同一 SN 只保留一条记录
+
+ + +

请与上位机“RID 模块状态信息”里的 SN 完全一致。

+ +
+
+
+
+ + +
FPV
+

已有 FPV 编号可输入后 8 位数字;留空则自动生成。

+ +
+
+
+
+

每张最多 5 MB,支持 JPG、PNG 和 WebP。照片保存在本机数据库;同一 SN 再次保存可补充或替换照片。

+ + +

+
+
+ +
+
02

二维码与核验

同机使用
+
▦
等待登记保存后在这里生成二维码,供本地版上位机读取。
+ +
+
+ +
+
03

本地登记记录

+

导出档案包包含离线档案卡、照片和登记信息;Excel 导出为登记表。

+
暂无登记记录。
+
+
+
+ +
127.0.0.1:8787 · 数据保存在本机
+
+ + diff --git a/registry/web/vendor/LICENSE.txt b/registry/web/vendor/LICENSE.txt new file mode 100644 index 0000000..150770c --- /dev/null +++ b/registry/web/vendor/LICENSE.txt @@ -0,0 +1,21 @@ +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. diff --git a/registry/web/vendor/qrcode.js b/registry/web/vendor/qrcode.js new file mode 100644 index 0000000..df13f82 --- /dev/null +++ b/registry/web/vendor/qrcode.js @@ -0,0 +1,2297 @@ +//--------------------------------------------------------------------- +// +// QR Code Generator for JavaScript +// +// Copyright (c) 2009 Kazuhiko Arase +// +// URL: http://www.d-project.com/ +// +// Licensed under the MIT license: +// http://www.opensource.org/licenses/mit-license.php +// +// The word 'QR Code' is registered trademark of +// DENSO WAVE INCORPORATED +// http://www.denso-wave.com/qrcode/faqpatent-e.html +// +//--------------------------------------------------------------------- + +var qrcode = function() { + + //--------------------------------------------------------------------- + // qrcode + //--------------------------------------------------------------------- + + /** + * qrcode + * @param typeNumber 1 to 40 + * @param errorCorrectionLevel 'L','M','Q','H' + */ + var qrcode = function(typeNumber, errorCorrectionLevel) { + + var PAD0 = 0xEC; + var PAD1 = 0x11; + + var _typeNumber = typeNumber; + var _errorCorrectionLevel = QRErrorCorrectionLevel[errorCorrectionLevel]; + var _modules = null; + var _moduleCount = 0; + var _dataCache = null; + var _dataList = []; + + var _this = {}; + + var makeImpl = function(test, maskPattern) { + + _moduleCount = _typeNumber * 4 + 17; + _modules = function(moduleCount) { + var modules = new Array(moduleCount); + for (var row = 0; row < moduleCount; row += 1) { + modules[row] = new Array(moduleCount); + for (var col = 0; col < moduleCount; col += 1) { + modules[row][col] = null; + } + } + return modules; + }(_moduleCount); + + setupPositionProbePattern(0, 0); + setupPositionProbePattern(_moduleCount - 7, 0); + setupPositionProbePattern(0, _moduleCount - 7); + setupPositionAdjustPattern(); + setupTimingPattern(); + setupTypeInfo(test, maskPattern); + + if (_typeNumber >= 7) { + setupTypeNumber(test); + } + + if (_dataCache == null) { + _dataCache = createData(_typeNumber, _errorCorrectionLevel, _dataList); + } + + mapData(_dataCache, maskPattern); + }; + + var setupPositionProbePattern = function(row, col) { + + for (var r = -1; r <= 7; r += 1) { + + if (row + r <= -1 || _moduleCount <= row + r) continue; + + for (var c = -1; c <= 7; c += 1) { + + if (col + c <= -1 || _moduleCount <= col + c) continue; + + if ( (0 <= r && r <= 6 && (c == 0 || c == 6) ) + || (0 <= c && c <= 6 && (r == 0 || r == 6) ) + || (2 <= r && r <= 4 && 2 <= c && c <= 4) ) { + _modules[row + r][col + c] = true; + } else { + _modules[row + r][col + c] = false; + } + } + } + }; + + var getBestMaskPattern = function() { + + var minLostPoint = 0; + var pattern = 0; + + for (var i = 0; i < 8; i += 1) { + + makeImpl(true, i); + + var lostPoint = QRUtil.getLostPoint(_this); + + if (i == 0 || minLostPoint > lostPoint) { + minLostPoint = lostPoint; + pattern = i; + } + } + + return pattern; + }; + + var setupTimingPattern = function() { + + for (var r = 8; r < _moduleCount - 8; r += 1) { + if (_modules[r][6] != null) { + continue; + } + _modules[r][6] = (r % 2 == 0); + } + + for (var c = 8; c < _moduleCount - 8; c += 1) { + if (_modules[6][c] != null) { + continue; + } + _modules[6][c] = (c % 2 == 0); + } + }; + + var setupPositionAdjustPattern = function() { + + var pos = QRUtil.getPatternPosition(_typeNumber); + + for (var i = 0; i < pos.length; i += 1) { + + for (var j = 0; j < pos.length; j += 1) { + + var row = pos[i]; + var col = pos[j]; + + if (_modules[row][col] != null) { + continue; + } + + for (var r = -2; r <= 2; r += 1) { + + for (var c = -2; c <= 2; c += 1) { + + if (r == -2 || r == 2 || c == -2 || c == 2 + || (r == 0 && c == 0) ) { + _modules[row + r][col + c] = true; + } else { + _modules[row + r][col + c] = false; + } + } + } + } + } + }; + + var setupTypeNumber = function(test) { + + var bits = QRUtil.getBCHTypeNumber(_typeNumber); + + for (var i = 0; i < 18; i += 1) { + var mod = (!test && ( (bits >> i) & 1) == 1); + _modules[Math.floor(i / 3)][i % 3 + _moduleCount - 8 - 3] = mod; + } + + for (var i = 0; i < 18; i += 1) { + var mod = (!test && ( (bits >> i) & 1) == 1); + _modules[i % 3 + _moduleCount - 8 - 3][Math.floor(i / 3)] = mod; + } + }; + + var setupTypeInfo = function(test, maskPattern) { + + var data = (_errorCorrectionLevel << 3) | maskPattern; + var bits = QRUtil.getBCHTypeInfo(data); + + // vertical + for (var i = 0; i < 15; i += 1) { + + var mod = (!test && ( (bits >> i) & 1) == 1); + + if (i < 6) { + _modules[i][8] = mod; + } else if (i < 8) { + _modules[i + 1][8] = mod; + } else { + _modules[_moduleCount - 15 + i][8] = mod; + } + } + + // horizontal + for (var i = 0; i < 15; i += 1) { + + var mod = (!test && ( (bits >> i) & 1) == 1); + + if (i < 8) { + _modules[8][_moduleCount - i - 1] = mod; + } else if (i < 9) { + _modules[8][15 - i - 1 + 1] = mod; + } else { + _modules[8][15 - i - 1] = mod; + } + } + + // fixed module + _modules[_moduleCount - 8][8] = (!test); + }; + + var mapData = function(data, maskPattern) { + + var inc = -1; + var row = _moduleCount - 1; + var bitIndex = 7; + var byteIndex = 0; + var maskFunc = QRUtil.getMaskFunction(maskPattern); + + for (var col = _moduleCount - 1; col > 0; col -= 2) { + + if (col == 6) col -= 1; + + while (true) { + + for (var c = 0; c < 2; c += 1) { + + if (_modules[row][col - c] == null) { + + var dark = false; + + if (byteIndex < data.length) { + dark = ( ( (data[byteIndex] >>> bitIndex) & 1) == 1); + } + + var mask = maskFunc(row, col - c); + + if (mask) { + dark = !dark; + } + + _modules[row][col - c] = dark; + bitIndex -= 1; + + if (bitIndex == -1) { + byteIndex += 1; + bitIndex = 7; + } + } + } + + row += inc; + + if (row < 0 || _moduleCount <= row) { + row -= inc; + inc = -inc; + break; + } + } + } + }; + + var createBytes = function(buffer, rsBlocks) { + + var offset = 0; + + var maxDcCount = 0; + var maxEcCount = 0; + + var dcdata = new Array(rsBlocks.length); + var ecdata = new Array(rsBlocks.length); + + for (var r = 0; r < rsBlocks.length; r += 1) { + + var dcCount = rsBlocks[r].dataCount; + var ecCount = rsBlocks[r].totalCount - dcCount; + + maxDcCount = Math.max(maxDcCount, dcCount); + maxEcCount = Math.max(maxEcCount, ecCount); + + dcdata[r] = new Array(dcCount); + + for (var i = 0; i < dcdata[r].length; i += 1) { + dcdata[r][i] = 0xff & buffer.getBuffer()[i + offset]; + } + offset += dcCount; + + var rsPoly = QRUtil.getErrorCorrectPolynomial(ecCount); + var rawPoly = qrPolynomial(dcdata[r], rsPoly.getLength() - 1); + + var modPoly = rawPoly.mod(rsPoly); + ecdata[r] = new Array(rsPoly.getLength() - 1); + for (var i = 0; i < ecdata[r].length; i += 1) { + var modIndex = i + modPoly.getLength() - ecdata[r].length; + ecdata[r][i] = (modIndex >= 0)? modPoly.getAt(modIndex) : 0; + } + } + + var totalCodeCount = 0; + for (var i = 0; i < rsBlocks.length; i += 1) { + totalCodeCount += rsBlocks[i].totalCount; + } + + var data = new Array(totalCodeCount); + var index = 0; + + for (var i = 0; i < maxDcCount; i += 1) { + for (var r = 0; r < rsBlocks.length; r += 1) { + if (i < dcdata[r].length) { + data[index] = dcdata[r][i]; + index += 1; + } + } + } + + for (var i = 0; i < maxEcCount; i += 1) { + for (var r = 0; r < rsBlocks.length; r += 1) { + if (i < ecdata[r].length) { + data[index] = ecdata[r][i]; + index += 1; + } + } + } + + return data; + }; + + var createData = function(typeNumber, errorCorrectionLevel, dataList) { + + var rsBlocks = QRRSBlock.getRSBlocks(typeNumber, errorCorrectionLevel); + + var buffer = qrBitBuffer(); + + for (var i = 0; i < dataList.length; i += 1) { + var data = dataList[i]; + buffer.put(data.getMode(), 4); + buffer.put(data.getLength(), QRUtil.getLengthInBits(data.getMode(), typeNumber) ); + data.write(buffer); + } + + // calc num max data. + var totalDataCount = 0; + for (var i = 0; i < rsBlocks.length; i += 1) { + totalDataCount += rsBlocks[i].dataCount; + } + + if (buffer.getLengthInBits() > totalDataCount * 8) { + throw 'code length overflow. (' + + buffer.getLengthInBits() + + '>' + + totalDataCount * 8 + + ')'; + } + + // end code + if (buffer.getLengthInBits() + 4 <= totalDataCount * 8) { + buffer.put(0, 4); + } + + // padding + while (buffer.getLengthInBits() % 8 != 0) { + buffer.putBit(false); + } + + // padding + while (true) { + + if (buffer.getLengthInBits() >= totalDataCount * 8) { + break; + } + buffer.put(PAD0, 8); + + if (buffer.getLengthInBits() >= totalDataCount * 8) { + break; + } + buffer.put(PAD1, 8); + } + + return createBytes(buffer, rsBlocks); + }; + + _this.addData = function(data, mode) { + + mode = mode || 'Byte'; + + var newData = null; + + switch(mode) { + case 'Numeric' : + newData = qrNumber(data); + break; + case 'Alphanumeric' : + newData = qrAlphaNum(data); + break; + case 'Byte' : + newData = qr8BitByte(data); + break; + case 'Kanji' : + newData = qrKanji(data); + break; + default : + throw 'mode:' + mode; + } + + _dataList.push(newData); + _dataCache = null; + }; + + _this.isDark = function(row, col) { + if (row < 0 || _moduleCount <= row || col < 0 || _moduleCount <= col) { + throw row + ',' + col; + } + return _modules[row][col]; + }; + + _this.getModuleCount = function() { + return _moduleCount; + }; + + _this.make = function() { + if (_typeNumber < 1) { + var typeNumber = 1; + + for (; typeNumber < 40; typeNumber++) { + var rsBlocks = QRRSBlock.getRSBlocks(typeNumber, _errorCorrectionLevel); + var buffer = qrBitBuffer(); + + for (var i = 0; i < _dataList.length; i++) { + var data = _dataList[i]; + buffer.put(data.getMode(), 4); + buffer.put(data.getLength(), QRUtil.getLengthInBits(data.getMode(), typeNumber) ); + data.write(buffer); + } + + var totalDataCount = 0; + for (var i = 0; i < rsBlocks.length; i++) { + totalDataCount += rsBlocks[i].dataCount; + } + + if (buffer.getLengthInBits() <= totalDataCount * 8) { + break; + } + } + + _typeNumber = typeNumber; + } + + makeImpl(false, getBestMaskPattern() ); + }; + + _this.createTableTag = function(cellSize, margin) { + + cellSize = cellSize || 2; + margin = (typeof margin == 'undefined')? cellSize * 4 : margin; + + var qrHtml = ''; + + qrHtml += ''; + qrHtml += ''; + + for (var r = 0; r < _this.getModuleCount(); r += 1) { + + qrHtml += ''; + + for (var c = 0; c < _this.getModuleCount(); c += 1) { + qrHtml += ''; + } + + qrHtml += ''; + qrHtml += '
'; + } + + qrHtml += '
'; + + return qrHtml; + }; + + _this.createSvgTag = function(cellSize, margin, alt, title) { + + var opts = {}; + if (typeof arguments[0] == 'object') { + // Called by options. + opts = arguments[0]; + // overwrite cellSize and margin. + cellSize = opts.cellSize; + margin = opts.margin; + alt = opts.alt; + title = opts.title; + } + + cellSize = cellSize || 2; + margin = (typeof margin == 'undefined')? cellSize * 4 : margin; + + // Compose alt property surrogate + alt = (typeof alt === 'string') ? {text: alt} : alt || {}; + alt.text = alt.text || null; + alt.id = (alt.text) ? alt.id || 'qrcode-description' : null; + + // Compose title property surrogate + title = (typeof title === 'string') ? {text: title} : title || {}; + title.text = title.text || null; + title.id = (title.text) ? title.id || 'qrcode-title' : null; + + var size = _this.getModuleCount() * cellSize + margin * 2; + var c, mc, r, mr, qrSvg='', rect; + + rect = 'l' + cellSize + ',0 0,' + cellSize + + ' -' + cellSize + ',0 0,-' + cellSize + 'z '; + + qrSvg += '' + + escapeXml(title.text) + '' : ''; + qrSvg += (alt.text) ? '' + + escapeXml(alt.text) + '' : ''; + qrSvg += ''; + qrSvg += ''; + qrSvg += ''; + + return qrSvg; + }; + + _this.createDataURL = function(cellSize, margin) { + + cellSize = cellSize || 2; + margin = (typeof margin == 'undefined')? cellSize * 4 : margin; + + var size = _this.getModuleCount() * cellSize + margin * 2; + var min = margin; + var max = size - margin; + + return createDataURL(size, size, function(x, y) { + if (min <= x && x < max && min <= y && y < max) { + var c = Math.floor( (x - min) / cellSize); + var r = Math.floor( (y - min) / cellSize); + return _this.isDark(r, c)? 0 : 1; + } else { + return 1; + } + } ); + }; + + _this.createImgTag = function(cellSize, margin, alt) { + + cellSize = cellSize || 2; + margin = (typeof margin == 'undefined')? cellSize * 4 : margin; + + var size = _this.getModuleCount() * cellSize + margin * 2; + + var img = ''; + img += '': escaped += '>'; break; + case '&': escaped += '&'; break; + case '"': escaped += '"'; break; + default : escaped += c; break; + } + } + return escaped; + }; + + var _createHalfASCII = function(margin) { + var cellSize = 1; + margin = (typeof margin == 'undefined')? cellSize * 2 : margin; + + var size = _this.getModuleCount() * cellSize + margin * 2; + var min = margin; + var max = size - margin; + + var y, x, r1, r2, p; + + var blocks = { + '██': '█', + '█ ': '▀', + ' █': '▄', + ' ': ' ' + }; + + var blocksLastLineNoMargin = { + '██': '▀', + '█ ': '▀', + ' █': ' ', + ' ': ' ' + }; + + var ascii = ''; + for (y = 0; y < size; y += 2) { + r1 = Math.floor((y - min) / cellSize); + r2 = Math.floor((y + 1 - min) / cellSize); + for (x = 0; x < size; x += 1) { + p = '█'; + + if (min <= x && x < max && min <= y && y < max && _this.isDark(r1, Math.floor((x - min) / cellSize))) { + p = ' '; + } + + if (min <= x && x < max && min <= y+1 && y+1 < max && _this.isDark(r2, Math.floor((x - min) / cellSize))) { + p += ' '; + } + else { + p += '█'; + } + + // Output 2 characters per pixel, to create full square. 1 character per pixels gives only half width of square. + ascii += (margin < 1 && y+1 >= max) ? blocksLastLineNoMargin[p] : blocks[p]; + } + + ascii += '\n'; + } + + if (size % 2 && margin > 0) { + return ascii.substring(0, ascii.length - size - 1) + Array(size+1).join('▀'); + } + + return ascii.substring(0, ascii.length-1); + }; + + _this.createASCII = function(cellSize, margin) { + cellSize = cellSize || 1; + + if (cellSize < 2) { + return _createHalfASCII(margin); + } + + cellSize -= 1; + margin = (typeof margin == 'undefined')? cellSize * 2 : margin; + + var size = _this.getModuleCount() * cellSize + margin * 2; + var min = margin; + var max = size - margin; + + var y, x, r, p; + + var white = Array(cellSize+1).join('██'); + var black = Array(cellSize+1).join(' '); + + var ascii = ''; + var line = ''; + for (y = 0; y < size; y += 1) { + r = Math.floor( (y - min) / cellSize); + line = ''; + for (x = 0; x < size; x += 1) { + p = 1; + + if (min <= x && x < max && min <= y && y < max && _this.isDark(r, Math.floor((x - min) / cellSize))) { + p = 0; + } + + // Output 2 characters per pixel, to create full square. 1 character per pixels gives only half width of square. + line += p ? white : black; + } + + for (r = 0; r < cellSize; r += 1) { + ascii += line + '\n'; + } + } + + return ascii.substring(0, ascii.length-1); + }; + + _this.renderTo2dContext = function(context, cellSize) { + cellSize = cellSize || 2; + var length = _this.getModuleCount(); + for (var row = 0; row < length; row++) { + for (var col = 0; col < length; col++) { + context.fillStyle = _this.isDark(row, col) ? 'black' : 'white'; + context.fillRect(col * cellSize, row * cellSize, cellSize, cellSize); + } + } + } + + return _this; + }; + + //--------------------------------------------------------------------- + // qrcode.stringToBytes + //--------------------------------------------------------------------- + + qrcode.stringToBytesFuncs = { + 'default' : function(s) { + var bytes = []; + for (var i = 0; i < s.length; i += 1) { + var c = s.charCodeAt(i); + bytes.push(c & 0xff); + } + return bytes; + } + }; + + qrcode.stringToBytes = qrcode.stringToBytesFuncs['default']; + + //--------------------------------------------------------------------- + // qrcode.createStringToBytes + //--------------------------------------------------------------------- + + /** + * @param unicodeData base64 string of byte array. + * [16bit Unicode],[16bit Bytes], ... + * @param numChars + */ + qrcode.createStringToBytes = function(unicodeData, numChars) { + + // create conversion map. + + var unicodeMap = function() { + + var bin = base64DecodeInputStream(unicodeData); + var read = function() { + var b = bin.read(); + if (b == -1) throw 'eof'; + return b; + }; + + var count = 0; + var unicodeMap = {}; + while (true) { + var b0 = bin.read(); + if (b0 == -1) break; + var b1 = read(); + var b2 = read(); + var b3 = read(); + var k = String.fromCharCode( (b0 << 8) | b1); + var v = (b2 << 8) | b3; + unicodeMap[k] = v; + count += 1; + } + if (count != numChars) { + throw count + ' != ' + numChars; + } + + return unicodeMap; + }(); + + var unknownChar = '?'.charCodeAt(0); + + return function(s) { + var bytes = []; + for (var i = 0; i < s.length; i += 1) { + var c = s.charCodeAt(i); + if (c < 128) { + bytes.push(c); + } else { + var b = unicodeMap[s.charAt(i)]; + if (typeof b == 'number') { + if ( (b & 0xff) == b) { + // 1byte + bytes.push(b); + } else { + // 2bytes + bytes.push(b >>> 8); + bytes.push(b & 0xff); + } + } else { + bytes.push(unknownChar); + } + } + } + return bytes; + }; + }; + + //--------------------------------------------------------------------- + // QRMode + //--------------------------------------------------------------------- + + var QRMode = { + MODE_NUMBER : 1 << 0, + MODE_ALPHA_NUM : 1 << 1, + MODE_8BIT_BYTE : 1 << 2, + MODE_KANJI : 1 << 3 + }; + + //--------------------------------------------------------------------- + // QRErrorCorrectionLevel + //--------------------------------------------------------------------- + + var QRErrorCorrectionLevel = { + L : 1, + M : 0, + Q : 3, + H : 2 + }; + + //--------------------------------------------------------------------- + // QRMaskPattern + //--------------------------------------------------------------------- + + var QRMaskPattern = { + PATTERN000 : 0, + PATTERN001 : 1, + PATTERN010 : 2, + PATTERN011 : 3, + PATTERN100 : 4, + PATTERN101 : 5, + PATTERN110 : 6, + PATTERN111 : 7 + }; + + //--------------------------------------------------------------------- + // QRUtil + //--------------------------------------------------------------------- + + var QRUtil = function() { + + var PATTERN_POSITION_TABLE = [ + [], + [6, 18], + [6, 22], + [6, 26], + [6, 30], + [6, 34], + [6, 22, 38], + [6, 24, 42], + [6, 26, 46], + [6, 28, 50], + [6, 30, 54], + [6, 32, 58], + [6, 34, 62], + [6, 26, 46, 66], + [6, 26, 48, 70], + [6, 26, 50, 74], + [6, 30, 54, 78], + [6, 30, 56, 82], + [6, 30, 58, 86], + [6, 34, 62, 90], + [6, 28, 50, 72, 94], + [6, 26, 50, 74, 98], + [6, 30, 54, 78, 102], + [6, 28, 54, 80, 106], + [6, 32, 58, 84, 110], + [6, 30, 58, 86, 114], + [6, 34, 62, 90, 118], + [6, 26, 50, 74, 98, 122], + [6, 30, 54, 78, 102, 126], + [6, 26, 52, 78, 104, 130], + [6, 30, 56, 82, 108, 134], + [6, 34, 60, 86, 112, 138], + [6, 30, 58, 86, 114, 142], + [6, 34, 62, 90, 118, 146], + [6, 30, 54, 78, 102, 126, 150], + [6, 24, 50, 76, 102, 128, 154], + [6, 28, 54, 80, 106, 132, 158], + [6, 32, 58, 84, 110, 136, 162], + [6, 26, 54, 82, 110, 138, 166], + [6, 30, 58, 86, 114, 142, 170] + ]; + var G15 = (1 << 10) | (1 << 8) | (1 << 5) | (1 << 4) | (1 << 2) | (1 << 1) | (1 << 0); + var G18 = (1 << 12) | (1 << 11) | (1 << 10) | (1 << 9) | (1 << 8) | (1 << 5) | (1 << 2) | (1 << 0); + var G15_MASK = (1 << 14) | (1 << 12) | (1 << 10) | (1 << 4) | (1 << 1); + + var _this = {}; + + var getBCHDigit = function(data) { + var digit = 0; + while (data != 0) { + digit += 1; + data >>>= 1; + } + return digit; + }; + + _this.getBCHTypeInfo = function(data) { + var d = data << 10; + while (getBCHDigit(d) - getBCHDigit(G15) >= 0) { + d ^= (G15 << (getBCHDigit(d) - getBCHDigit(G15) ) ); + } + return ( (data << 10) | d) ^ G15_MASK; + }; + + _this.getBCHTypeNumber = function(data) { + var d = data << 12; + while (getBCHDigit(d) - getBCHDigit(G18) >= 0) { + d ^= (G18 << (getBCHDigit(d) - getBCHDigit(G18) ) ); + } + return (data << 12) | d; + }; + + _this.getPatternPosition = function(typeNumber) { + return PATTERN_POSITION_TABLE[typeNumber - 1]; + }; + + _this.getMaskFunction = function(maskPattern) { + + switch (maskPattern) { + + case QRMaskPattern.PATTERN000 : + return function(i, j) { return (i + j) % 2 == 0; }; + case QRMaskPattern.PATTERN001 : + return function(i, j) { return i % 2 == 0; }; + case QRMaskPattern.PATTERN010 : + return function(i, j) { return j % 3 == 0; }; + case QRMaskPattern.PATTERN011 : + return function(i, j) { return (i + j) % 3 == 0; }; + case QRMaskPattern.PATTERN100 : + return function(i, j) { return (Math.floor(i / 2) + Math.floor(j / 3) ) % 2 == 0; }; + case QRMaskPattern.PATTERN101 : + return function(i, j) { return (i * j) % 2 + (i * j) % 3 == 0; }; + case QRMaskPattern.PATTERN110 : + return function(i, j) { return ( (i * j) % 2 + (i * j) % 3) % 2 == 0; }; + case QRMaskPattern.PATTERN111 : + return function(i, j) { return ( (i * j) % 3 + (i + j) % 2) % 2 == 0; }; + + default : + throw 'bad maskPattern:' + maskPattern; + } + }; + + _this.getErrorCorrectPolynomial = function(errorCorrectLength) { + var a = qrPolynomial([1], 0); + for (var i = 0; i < errorCorrectLength; i += 1) { + a = a.multiply(qrPolynomial([1, QRMath.gexp(i)], 0) ); + } + return a; + }; + + _this.getLengthInBits = function(mode, type) { + + if (1 <= type && type < 10) { + + // 1 - 9 + + switch(mode) { + case QRMode.MODE_NUMBER : return 10; + case QRMode.MODE_ALPHA_NUM : return 9; + case QRMode.MODE_8BIT_BYTE : return 8; + case QRMode.MODE_KANJI : return 8; + default : + throw 'mode:' + mode; + } + + } else if (type < 27) { + + // 10 - 26 + + switch(mode) { + case QRMode.MODE_NUMBER : return 12; + case QRMode.MODE_ALPHA_NUM : return 11; + case QRMode.MODE_8BIT_BYTE : return 16; + case QRMode.MODE_KANJI : return 10; + default : + throw 'mode:' + mode; + } + + } else if (type < 41) { + + // 27 - 40 + + switch(mode) { + case QRMode.MODE_NUMBER : return 14; + case QRMode.MODE_ALPHA_NUM : return 13; + case QRMode.MODE_8BIT_BYTE : return 16; + case QRMode.MODE_KANJI : return 12; + default : + throw 'mode:' + mode; + } + + } else { + throw 'type:' + type; + } + }; + + _this.getLostPoint = function(qrcode) { + + var moduleCount = qrcode.getModuleCount(); + + var lostPoint = 0; + + // LEVEL1 + + for (var row = 0; row < moduleCount; row += 1) { + for (var col = 0; col < moduleCount; col += 1) { + + var sameCount = 0; + var dark = qrcode.isDark(row, col); + + for (var r = -1; r <= 1; r += 1) { + + if (row + r < 0 || moduleCount <= row + r) { + continue; + } + + for (var c = -1; c <= 1; c += 1) { + + if (col + c < 0 || moduleCount <= col + c) { + continue; + } + + if (r == 0 && c == 0) { + continue; + } + + if (dark == qrcode.isDark(row + r, col + c) ) { + sameCount += 1; + } + } + } + + if (sameCount > 5) { + lostPoint += (3 + sameCount - 5); + } + } + }; + + // LEVEL2 + + for (var row = 0; row < moduleCount - 1; row += 1) { + for (var col = 0; col < moduleCount - 1; col += 1) { + var count = 0; + if (qrcode.isDark(row, col) ) count += 1; + if (qrcode.isDark(row + 1, col) ) count += 1; + if (qrcode.isDark(row, col + 1) ) count += 1; + if (qrcode.isDark(row + 1, col + 1) ) count += 1; + if (count == 0 || count == 4) { + lostPoint += 3; + } + } + } + + // LEVEL3 + + for (var row = 0; row < moduleCount; row += 1) { + for (var col = 0; col < moduleCount - 6; col += 1) { + if (qrcode.isDark(row, col) + && !qrcode.isDark(row, col + 1) + && qrcode.isDark(row, col + 2) + && qrcode.isDark(row, col + 3) + && qrcode.isDark(row, col + 4) + && !qrcode.isDark(row, col + 5) + && qrcode.isDark(row, col + 6) ) { + lostPoint += 40; + } + } + } + + for (var col = 0; col < moduleCount; col += 1) { + for (var row = 0; row < moduleCount - 6; row += 1) { + if (qrcode.isDark(row, col) + && !qrcode.isDark(row + 1, col) + && qrcode.isDark(row + 2, col) + && qrcode.isDark(row + 3, col) + && qrcode.isDark(row + 4, col) + && !qrcode.isDark(row + 5, col) + && qrcode.isDark(row + 6, col) ) { + lostPoint += 40; + } + } + } + + // LEVEL4 + + var darkCount = 0; + + for (var col = 0; col < moduleCount; col += 1) { + for (var row = 0; row < moduleCount; row += 1) { + if (qrcode.isDark(row, col) ) { + darkCount += 1; + } + } + } + + var ratio = Math.abs(100 * darkCount / moduleCount / moduleCount - 50) / 5; + lostPoint += ratio * 10; + + return lostPoint; + }; + + return _this; + }(); + + //--------------------------------------------------------------------- + // QRMath + //--------------------------------------------------------------------- + + var QRMath = function() { + + var EXP_TABLE = new Array(256); + var LOG_TABLE = new Array(256); + + // initialize tables + for (var i = 0; i < 8; i += 1) { + EXP_TABLE[i] = 1 << i; + } + for (var i = 8; i < 256; i += 1) { + EXP_TABLE[i] = EXP_TABLE[i - 4] + ^ EXP_TABLE[i - 5] + ^ EXP_TABLE[i - 6] + ^ EXP_TABLE[i - 8]; + } + for (var i = 0; i < 255; i += 1) { + LOG_TABLE[EXP_TABLE[i] ] = i; + } + + var _this = {}; + + _this.glog = function(n) { + + if (n < 1) { + throw 'glog(' + n + ')'; + } + + return LOG_TABLE[n]; + }; + + _this.gexp = function(n) { + + while (n < 0) { + n += 255; + } + + while (n >= 256) { + n -= 255; + } + + return EXP_TABLE[n]; + }; + + return _this; + }(); + + //--------------------------------------------------------------------- + // qrPolynomial + //--------------------------------------------------------------------- + + function qrPolynomial(num, shift) { + + if (typeof num.length == 'undefined') { + throw num.length + '/' + shift; + } + + var _num = function() { + var offset = 0; + while (offset < num.length && num[offset] == 0) { + offset += 1; + } + var _num = new Array(num.length - offset + shift); + for (var i = 0; i < num.length - offset; i += 1) { + _num[i] = num[i + offset]; + } + return _num; + }(); + + var _this = {}; + + _this.getAt = function(index) { + return _num[index]; + }; + + _this.getLength = function() { + return _num.length; + }; + + _this.multiply = function(e) { + + var num = new Array(_this.getLength() + e.getLength() - 1); + + for (var i = 0; i < _this.getLength(); i += 1) { + for (var j = 0; j < e.getLength(); j += 1) { + num[i + j] ^= QRMath.gexp(QRMath.glog(_this.getAt(i) ) + QRMath.glog(e.getAt(j) ) ); + } + } + + return qrPolynomial(num, 0); + }; + + _this.mod = function(e) { + + if (_this.getLength() - e.getLength() < 0) { + return _this; + } + + var ratio = QRMath.glog(_this.getAt(0) ) - QRMath.glog(e.getAt(0) ); + + var num = new Array(_this.getLength() ); + for (var i = 0; i < _this.getLength(); i += 1) { + num[i] = _this.getAt(i); + } + + for (var i = 0; i < e.getLength(); i += 1) { + num[i] ^= QRMath.gexp(QRMath.glog(e.getAt(i) ) + ratio); + } + + // recursive call + return qrPolynomial(num, 0).mod(e); + }; + + return _this; + }; + + //--------------------------------------------------------------------- + // QRRSBlock + //--------------------------------------------------------------------- + + var QRRSBlock = function() { + + var RS_BLOCK_TABLE = [ + + // L + // M + // Q + // H + + // 1 + [1, 26, 19], + [1, 26, 16], + [1, 26, 13], + [1, 26, 9], + + // 2 + [1, 44, 34], + [1, 44, 28], + [1, 44, 22], + [1, 44, 16], + + // 3 + [1, 70, 55], + [1, 70, 44], + [2, 35, 17], + [2, 35, 13], + + // 4 + [1, 100, 80], + [2, 50, 32], + [2, 50, 24], + [4, 25, 9], + + // 5 + [1, 134, 108], + [2, 67, 43], + [2, 33, 15, 2, 34, 16], + [2, 33, 11, 2, 34, 12], + + // 6 + [2, 86, 68], + [4, 43, 27], + [4, 43, 19], + [4, 43, 15], + + // 7 + [2, 98, 78], + [4, 49, 31], + [2, 32, 14, 4, 33, 15], + [4, 39, 13, 1, 40, 14], + + // 8 + [2, 121, 97], + [2, 60, 38, 2, 61, 39], + [4, 40, 18, 2, 41, 19], + [4, 40, 14, 2, 41, 15], + + // 9 + [2, 146, 116], + [3, 58, 36, 2, 59, 37], + [4, 36, 16, 4, 37, 17], + [4, 36, 12, 4, 37, 13], + + // 10 + [2, 86, 68, 2, 87, 69], + [4, 69, 43, 1, 70, 44], + [6, 43, 19, 2, 44, 20], + [6, 43, 15, 2, 44, 16], + + // 11 + [4, 101, 81], + [1, 80, 50, 4, 81, 51], + [4, 50, 22, 4, 51, 23], + [3, 36, 12, 8, 37, 13], + + // 12 + [2, 116, 92, 2, 117, 93], + [6, 58, 36, 2, 59, 37], + [4, 46, 20, 6, 47, 21], + [7, 42, 14, 4, 43, 15], + + // 13 + [4, 133, 107], + [8, 59, 37, 1, 60, 38], + [8, 44, 20, 4, 45, 21], + [12, 33, 11, 4, 34, 12], + + // 14 + [3, 145, 115, 1, 146, 116], + [4, 64, 40, 5, 65, 41], + [11, 36, 16, 5, 37, 17], + [11, 36, 12, 5, 37, 13], + + // 15 + [5, 109, 87, 1, 110, 88], + [5, 65, 41, 5, 66, 42], + [5, 54, 24, 7, 55, 25], + [11, 36, 12, 7, 37, 13], + + // 16 + [5, 122, 98, 1, 123, 99], + [7, 73, 45, 3, 74, 46], + [15, 43, 19, 2, 44, 20], + [3, 45, 15, 13, 46, 16], + + // 17 + [1, 135, 107, 5, 136, 108], + [10, 74, 46, 1, 75, 47], + [1, 50, 22, 15, 51, 23], + [2, 42, 14, 17, 43, 15], + + // 18 + [5, 150, 120, 1, 151, 121], + [9, 69, 43, 4, 70, 44], + [17, 50, 22, 1, 51, 23], + [2, 42, 14, 19, 43, 15], + + // 19 + [3, 141, 113, 4, 142, 114], + [3, 70, 44, 11, 71, 45], + [17, 47, 21, 4, 48, 22], + [9, 39, 13, 16, 40, 14], + + // 20 + [3, 135, 107, 5, 136, 108], + [3, 67, 41, 13, 68, 42], + [15, 54, 24, 5, 55, 25], + [15, 43, 15, 10, 44, 16], + + // 21 + [4, 144, 116, 4, 145, 117], + [17, 68, 42], + [17, 50, 22, 6, 51, 23], + [19, 46, 16, 6, 47, 17], + + // 22 + [2, 139, 111, 7, 140, 112], + [17, 74, 46], + [7, 54, 24, 16, 55, 25], + [34, 37, 13], + + // 23 + [4, 151, 121, 5, 152, 122], + [4, 75, 47, 14, 76, 48], + [11, 54, 24, 14, 55, 25], + [16, 45, 15, 14, 46, 16], + + // 24 + [6, 147, 117, 4, 148, 118], + [6, 73, 45, 14, 74, 46], + [11, 54, 24, 16, 55, 25], + [30, 46, 16, 2, 47, 17], + + // 25 + [8, 132, 106, 4, 133, 107], + [8, 75, 47, 13, 76, 48], + [7, 54, 24, 22, 55, 25], + [22, 45, 15, 13, 46, 16], + + // 26 + [10, 142, 114, 2, 143, 115], + [19, 74, 46, 4, 75, 47], + [28, 50, 22, 6, 51, 23], + [33, 46, 16, 4, 47, 17], + + // 27 + [8, 152, 122, 4, 153, 123], + [22, 73, 45, 3, 74, 46], + [8, 53, 23, 26, 54, 24], + [12, 45, 15, 28, 46, 16], + + // 28 + [3, 147, 117, 10, 148, 118], + [3, 73, 45, 23, 74, 46], + [4, 54, 24, 31, 55, 25], + [11, 45, 15, 31, 46, 16], + + // 29 + [7, 146, 116, 7, 147, 117], + [21, 73, 45, 7, 74, 46], + [1, 53, 23, 37, 54, 24], + [19, 45, 15, 26, 46, 16], + + // 30 + [5, 145, 115, 10, 146, 116], + [19, 75, 47, 10, 76, 48], + [15, 54, 24, 25, 55, 25], + [23, 45, 15, 25, 46, 16], + + // 31 + [13, 145, 115, 3, 146, 116], + [2, 74, 46, 29, 75, 47], + [42, 54, 24, 1, 55, 25], + [23, 45, 15, 28, 46, 16], + + // 32 + [17, 145, 115], + [10, 74, 46, 23, 75, 47], + [10, 54, 24, 35, 55, 25], + [19, 45, 15, 35, 46, 16], + + // 33 + [17, 145, 115, 1, 146, 116], + [14, 74, 46, 21, 75, 47], + [29, 54, 24, 19, 55, 25], + [11, 45, 15, 46, 46, 16], + + // 34 + [13, 145, 115, 6, 146, 116], + [14, 74, 46, 23, 75, 47], + [44, 54, 24, 7, 55, 25], + [59, 46, 16, 1, 47, 17], + + // 35 + [12, 151, 121, 7, 152, 122], + [12, 75, 47, 26, 76, 48], + [39, 54, 24, 14, 55, 25], + [22, 45, 15, 41, 46, 16], + + // 36 + [6, 151, 121, 14, 152, 122], + [6, 75, 47, 34, 76, 48], + [46, 54, 24, 10, 55, 25], + [2, 45, 15, 64, 46, 16], + + // 37 + [17, 152, 122, 4, 153, 123], + [29, 74, 46, 14, 75, 47], + [49, 54, 24, 10, 55, 25], + [24, 45, 15, 46, 46, 16], + + // 38 + [4, 152, 122, 18, 153, 123], + [13, 74, 46, 32, 75, 47], + [48, 54, 24, 14, 55, 25], + [42, 45, 15, 32, 46, 16], + + // 39 + [20, 147, 117, 4, 148, 118], + [40, 75, 47, 7, 76, 48], + [43, 54, 24, 22, 55, 25], + [10, 45, 15, 67, 46, 16], + + // 40 + [19, 148, 118, 6, 149, 119], + [18, 75, 47, 31, 76, 48], + [34, 54, 24, 34, 55, 25], + [20, 45, 15, 61, 46, 16] + ]; + + var qrRSBlock = function(totalCount, dataCount) { + var _this = {}; + _this.totalCount = totalCount; + _this.dataCount = dataCount; + return _this; + }; + + var _this = {}; + + var getRsBlockTable = function(typeNumber, errorCorrectionLevel) { + + switch(errorCorrectionLevel) { + case QRErrorCorrectionLevel.L : + return RS_BLOCK_TABLE[(typeNumber - 1) * 4 + 0]; + case QRErrorCorrectionLevel.M : + return RS_BLOCK_TABLE[(typeNumber - 1) * 4 + 1]; + case QRErrorCorrectionLevel.Q : + return RS_BLOCK_TABLE[(typeNumber - 1) * 4 + 2]; + case QRErrorCorrectionLevel.H : + return RS_BLOCK_TABLE[(typeNumber - 1) * 4 + 3]; + default : + return undefined; + } + }; + + _this.getRSBlocks = function(typeNumber, errorCorrectionLevel) { + + var rsBlock = getRsBlockTable(typeNumber, errorCorrectionLevel); + + if (typeof rsBlock == 'undefined') { + throw 'bad rs block @ typeNumber:' + typeNumber + + '/errorCorrectionLevel:' + errorCorrectionLevel; + } + + var length = rsBlock.length / 3; + + var list = []; + + for (var i = 0; i < length; i += 1) { + + var count = rsBlock[i * 3 + 0]; + var totalCount = rsBlock[i * 3 + 1]; + var dataCount = rsBlock[i * 3 + 2]; + + for (var j = 0; j < count; j += 1) { + list.push(qrRSBlock(totalCount, dataCount) ); + } + } + + return list; + }; + + return _this; + }(); + + //--------------------------------------------------------------------- + // qrBitBuffer + //--------------------------------------------------------------------- + + var qrBitBuffer = function() { + + var _buffer = []; + var _length = 0; + + var _this = {}; + + _this.getBuffer = function() { + return _buffer; + }; + + _this.getAt = function(index) { + var bufIndex = Math.floor(index / 8); + return ( (_buffer[bufIndex] >>> (7 - index % 8) ) & 1) == 1; + }; + + _this.put = function(num, length) { + for (var i = 0; i < length; i += 1) { + _this.putBit( ( (num >>> (length - i - 1) ) & 1) == 1); + } + }; + + _this.getLengthInBits = function() { + return _length; + }; + + _this.putBit = function(bit) { + + var bufIndex = Math.floor(_length / 8); + if (_buffer.length <= bufIndex) { + _buffer.push(0); + } + + if (bit) { + _buffer[bufIndex] |= (0x80 >>> (_length % 8) ); + } + + _length += 1; + }; + + return _this; + }; + + //--------------------------------------------------------------------- + // qrNumber + //--------------------------------------------------------------------- + + var qrNumber = function(data) { + + var _mode = QRMode.MODE_NUMBER; + var _data = data; + + var _this = {}; + + _this.getMode = function() { + return _mode; + }; + + _this.getLength = function(buffer) { + return _data.length; + }; + + _this.write = function(buffer) { + + var data = _data; + + var i = 0; + + while (i + 2 < data.length) { + buffer.put(strToNum(data.substring(i, i + 3) ), 10); + i += 3; + } + + if (i < data.length) { + if (data.length - i == 1) { + buffer.put(strToNum(data.substring(i, i + 1) ), 4); + } else if (data.length - i == 2) { + buffer.put(strToNum(data.substring(i, i + 2) ), 7); + } + } + }; + + var strToNum = function(s) { + var num = 0; + for (var i = 0; i < s.length; i += 1) { + num = num * 10 + chatToNum(s.charAt(i) ); + } + return num; + }; + + var chatToNum = function(c) { + if ('0' <= c && c <= '9') { + return c.charCodeAt(0) - '0'.charCodeAt(0); + } + throw 'illegal char :' + c; + }; + + return _this; + }; + + //--------------------------------------------------------------------- + // qrAlphaNum + //--------------------------------------------------------------------- + + var qrAlphaNum = function(data) { + + var _mode = QRMode.MODE_ALPHA_NUM; + var _data = data; + + var _this = {}; + + _this.getMode = function() { + return _mode; + }; + + _this.getLength = function(buffer) { + return _data.length; + }; + + _this.write = function(buffer) { + + var s = _data; + + var i = 0; + + while (i + 1 < s.length) { + buffer.put( + getCode(s.charAt(i) ) * 45 + + getCode(s.charAt(i + 1) ), 11); + i += 2; + } + + if (i < s.length) { + buffer.put(getCode(s.charAt(i) ), 6); + } + }; + + var getCode = function(c) { + + if ('0' <= c && c <= '9') { + return c.charCodeAt(0) - '0'.charCodeAt(0); + } else if ('A' <= c && c <= 'Z') { + return c.charCodeAt(0) - 'A'.charCodeAt(0) + 10; + } else { + switch (c) { + case ' ' : return 36; + case '$' : return 37; + case '%' : return 38; + case '*' : return 39; + case '+' : return 40; + case '-' : return 41; + case '.' : return 42; + case '/' : return 43; + case ':' : return 44; + default : + throw 'illegal char :' + c; + } + } + }; + + return _this; + }; + + //--------------------------------------------------------------------- + // qr8BitByte + //--------------------------------------------------------------------- + + var qr8BitByte = function(data) { + + var _mode = QRMode.MODE_8BIT_BYTE; + var _data = data; + var _bytes = qrcode.stringToBytes(data); + + var _this = {}; + + _this.getMode = function() { + return _mode; + }; + + _this.getLength = function(buffer) { + return _bytes.length; + }; + + _this.write = function(buffer) { + for (var i = 0; i < _bytes.length; i += 1) { + buffer.put(_bytes[i], 8); + } + }; + + return _this; + }; + + //--------------------------------------------------------------------- + // qrKanji + //--------------------------------------------------------------------- + + var qrKanji = function(data) { + + var _mode = QRMode.MODE_KANJI; + var _data = data; + + var stringToBytes = qrcode.stringToBytesFuncs['SJIS']; + if (!stringToBytes) { + throw 'sjis not supported.'; + } + !function(c, code) { + // self test for sjis support. + var test = stringToBytes(c); + if (test.length != 2 || ( (test[0] << 8) | test[1]) != code) { + throw 'sjis not supported.'; + } + }('\u53cb', 0x9746); + + var _bytes = stringToBytes(data); + + var _this = {}; + + _this.getMode = function() { + return _mode; + }; + + _this.getLength = function(buffer) { + return ~~(_bytes.length / 2); + }; + + _this.write = function(buffer) { + + var data = _bytes; + + var i = 0; + + while (i + 1 < data.length) { + + var c = ( (0xff & data[i]) << 8) | (0xff & data[i + 1]); + + if (0x8140 <= c && c <= 0x9FFC) { + c -= 0x8140; + } else if (0xE040 <= c && c <= 0xEBBF) { + c -= 0xC140; + } else { + throw 'illegal char at ' + (i + 1) + '/' + c; + } + + c = ( (c >>> 8) & 0xff) * 0xC0 + (c & 0xff); + + buffer.put(c, 13); + + i += 2; + } + + if (i < data.length) { + throw 'illegal char at ' + (i + 1); + } + }; + + return _this; + }; + + //===================================================================== + // GIF Support etc. + // + + //--------------------------------------------------------------------- + // byteArrayOutputStream + //--------------------------------------------------------------------- + + var byteArrayOutputStream = function() { + + var _bytes = []; + + var _this = {}; + + _this.writeByte = function(b) { + _bytes.push(b & 0xff); + }; + + _this.writeShort = function(i) { + _this.writeByte(i); + _this.writeByte(i >>> 8); + }; + + _this.writeBytes = function(b, off, len) { + off = off || 0; + len = len || b.length; + for (var i = 0; i < len; i += 1) { + _this.writeByte(b[i + off]); + } + }; + + _this.writeString = function(s) { + for (var i = 0; i < s.length; i += 1) { + _this.writeByte(s.charCodeAt(i) ); + } + }; + + _this.toByteArray = function() { + return _bytes; + }; + + _this.toString = function() { + var s = ''; + s += '['; + for (var i = 0; i < _bytes.length; i += 1) { + if (i > 0) { + s += ','; + } + s += _bytes[i]; + } + s += ']'; + return s; + }; + + return _this; + }; + + //--------------------------------------------------------------------- + // base64EncodeOutputStream + //--------------------------------------------------------------------- + + var base64EncodeOutputStream = function() { + + var _buffer = 0; + var _buflen = 0; + var _length = 0; + var _base64 = ''; + + var _this = {}; + + var writeEncoded = function(b) { + _base64 += String.fromCharCode(encode(b & 0x3f) ); + }; + + var encode = function(n) { + if (n < 0) { + // error. + } else if (n < 26) { + return 0x41 + n; + } else if (n < 52) { + return 0x61 + (n - 26); + } else if (n < 62) { + return 0x30 + (n - 52); + } else if (n == 62) { + return 0x2b; + } else if (n == 63) { + return 0x2f; + } + throw 'n:' + n; + }; + + _this.writeByte = function(n) { + + _buffer = (_buffer << 8) | (n & 0xff); + _buflen += 8; + _length += 1; + + while (_buflen >= 6) { + writeEncoded(_buffer >>> (_buflen - 6) ); + _buflen -= 6; + } + }; + + _this.flush = function() { + + if (_buflen > 0) { + writeEncoded(_buffer << (6 - _buflen) ); + _buffer = 0; + _buflen = 0; + } + + if (_length % 3 != 0) { + // padding + var padlen = 3 - _length % 3; + for (var i = 0; i < padlen; i += 1) { + _base64 += '='; + } + } + }; + + _this.toString = function() { + return _base64; + }; + + return _this; + }; + + //--------------------------------------------------------------------- + // base64DecodeInputStream + //--------------------------------------------------------------------- + + var base64DecodeInputStream = function(str) { + + var _str = str; + var _pos = 0; + var _buffer = 0; + var _buflen = 0; + + var _this = {}; + + _this.read = function() { + + while (_buflen < 8) { + + if (_pos >= _str.length) { + if (_buflen == 0) { + return -1; + } + throw 'unexpected end of file./' + _buflen; + } + + var c = _str.charAt(_pos); + _pos += 1; + + if (c == '=') { + _buflen = 0; + return -1; + } else if (c.match(/^\s$/) ) { + // ignore if whitespace. + continue; + } + + _buffer = (_buffer << 6) | decode(c.charCodeAt(0) ); + _buflen += 6; + } + + var n = (_buffer >>> (_buflen - 8) ) & 0xff; + _buflen -= 8; + return n; + }; + + var decode = function(c) { + if (0x41 <= c && c <= 0x5a) { + return c - 0x41; + } else if (0x61 <= c && c <= 0x7a) { + return c - 0x61 + 26; + } else if (0x30 <= c && c <= 0x39) { + return c - 0x30 + 52; + } else if (c == 0x2b) { + return 62; + } else if (c == 0x2f) { + return 63; + } else { + throw 'c:' + c; + } + }; + + return _this; + }; + + //--------------------------------------------------------------------- + // gifImage (B/W) + //--------------------------------------------------------------------- + + var gifImage = function(width, height) { + + var _width = width; + var _height = height; + var _data = new Array(width * height); + + var _this = {}; + + _this.setPixel = function(x, y, pixel) { + _data[y * _width + x] = pixel; + }; + + _this.write = function(out) { + + //--------------------------------- + // GIF Signature + + out.writeString('GIF87a'); + + //--------------------------------- + // Screen Descriptor + + out.writeShort(_width); + out.writeShort(_height); + + out.writeByte(0x80); // 2bit + out.writeByte(0); + out.writeByte(0); + + //--------------------------------- + // Global Color Map + + // black + out.writeByte(0x00); + out.writeByte(0x00); + out.writeByte(0x00); + + // white + out.writeByte(0xff); + out.writeByte(0xff); + out.writeByte(0xff); + + //--------------------------------- + // Image Descriptor + + out.writeString(','); + out.writeShort(0); + out.writeShort(0); + out.writeShort(_width); + out.writeShort(_height); + out.writeByte(0); + + //--------------------------------- + // Local Color Map + + //--------------------------------- + // Raster Data + + var lzwMinCodeSize = 2; + var raster = getLZWRaster(lzwMinCodeSize); + + out.writeByte(lzwMinCodeSize); + + var offset = 0; + + while (raster.length - offset > 255) { + out.writeByte(255); + out.writeBytes(raster, offset, 255); + offset += 255; + } + + out.writeByte(raster.length - offset); + out.writeBytes(raster, offset, raster.length - offset); + out.writeByte(0x00); + + //--------------------------------- + // GIF Terminator + out.writeString(';'); + }; + + var bitOutputStream = function(out) { + + var _out = out; + var _bitLength = 0; + var _bitBuffer = 0; + + var _this = {}; + + _this.write = function(data, length) { + + if ( (data >>> length) != 0) { + throw 'length over'; + } + + while (_bitLength + length >= 8) { + _out.writeByte(0xff & ( (data << _bitLength) | _bitBuffer) ); + length -= (8 - _bitLength); + data >>>= (8 - _bitLength); + _bitBuffer = 0; + _bitLength = 0; + } + + _bitBuffer = (data << _bitLength) | _bitBuffer; + _bitLength = _bitLength + length; + }; + + _this.flush = function() { + if (_bitLength > 0) { + _out.writeByte(_bitBuffer); + } + }; + + return _this; + }; + + var getLZWRaster = function(lzwMinCodeSize) { + + var clearCode = 1 << lzwMinCodeSize; + var endCode = (1 << lzwMinCodeSize) + 1; + var bitLength = lzwMinCodeSize + 1; + + // Setup LZWTable + var table = lzwTable(); + + for (var i = 0; i < clearCode; i += 1) { + table.add(String.fromCharCode(i) ); + } + table.add(String.fromCharCode(clearCode) ); + table.add(String.fromCharCode(endCode) ); + + var byteOut = byteArrayOutputStream(); + var bitOut = bitOutputStream(byteOut); + + // clear code + bitOut.write(clearCode, bitLength); + + var dataIndex = 0; + + var s = String.fromCharCode(_data[dataIndex]); + dataIndex += 1; + + while (dataIndex < _data.length) { + + var c = String.fromCharCode(_data[dataIndex]); + dataIndex += 1; + + if (table.contains(s + c) ) { + + s = s + c; + + } else { + + bitOut.write(table.indexOf(s), bitLength); + + if (table.size() < 0xfff) { + + if (table.size() == (1 << bitLength) ) { + bitLength += 1; + } + + table.add(s + c); + } + + s = c; + } + } + + bitOut.write(table.indexOf(s), bitLength); + + // end code + bitOut.write(endCode, bitLength); + + bitOut.flush(); + + return byteOut.toByteArray(); + }; + + var lzwTable = function() { + + var _map = {}; + var _size = 0; + + var _this = {}; + + _this.add = function(key) { + if (_this.contains(key) ) { + throw 'dup key:' + key; + } + _map[key] = _size; + _size += 1; + }; + + _this.size = function() { + return _size; + }; + + _this.indexOf = function(key) { + return _map[key]; + }; + + _this.contains = function(key) { + return typeof _map[key] != 'undefined'; + }; + + return _this; + }; + + return _this; + }; + + var createDataURL = function(width, height, getPixel) { + var gif = gifImage(width, height); + for (var y = 0; y < height; y += 1) { + for (var x = 0; x < width; x += 1) { + gif.setPixel(x, y, getPixel(x, y) ); + } + } + + var b = byteArrayOutputStream(); + gif.write(b); + + var base64 = base64EncodeOutputStream(); + var bytes = b.toByteArray(); + for (var i = 0; i < bytes.length; i += 1) { + base64.writeByte(bytes[i]); + } + base64.flush(); + + return 'data:image/gif;base64,' + base64; + }; + + //--------------------------------------------------------------------- + // returns qrcode function. + + return qrcode; +}(); + +// multibyte support +!function() { + + qrcode.stringToBytesFuncs['UTF-8'] = function(s) { + // http://stackoverflow.com/questions/18729405/how-to-convert-utf8-string-to-byte-array + function toUTF8Array(str) { + var utf8 = []; + for (var i=0; i < str.length; i++) { + var charcode = str.charCodeAt(i); + if (charcode < 0x80) utf8.push(charcode); + else if (charcode < 0x800) { + utf8.push(0xc0 | (charcode >> 6), + 0x80 | (charcode & 0x3f)); + } + else if (charcode < 0xd800 || charcode >= 0xe000) { + utf8.push(0xe0 | (charcode >> 12), + 0x80 | ((charcode>>6) & 0x3f), + 0x80 | (charcode & 0x3f)); + } + // surrogate pair + else { + i++; + // UTF-16 encodes 0x10000-0x10FFFF by + // subtracting 0x10000 and splitting the + // 20 bits of 0x0-0xFFFFF into two halves + charcode = 0x10000 + (((charcode & 0x3ff)<<10) + | (str.charCodeAt(i) & 0x3ff)); + utf8.push(0xf0 | (charcode >>18), + 0x80 | ((charcode>>12) & 0x3f), + 0x80 | ((charcode>>6) & 0x3f), + 0x80 | (charcode & 0x3f)); + } + } + return utf8; + } + return toUTF8Array(s); + }; + +}(); + +(function (factory) { + if (typeof define === 'function' && define.amd) { + define([], factory); + } else if (typeof exports === 'object') { + module.exports = factory(); + } +}(function () { + return qrcode; +})); diff --git a/启动源码版.cmd b/启动源码版.cmd new file mode 100644 index 0000000..d348bf2 --- /dev/null +++ b/启动源码版.cmd @@ -0,0 +1,17 @@ +@echo off +cd /d "%~dp0" +if exist "%~dp0runtime\node.exe" ( + "%~dp0runtime\node.exe" "%~dp0registry\server.js" +) else ( + where node >nul 2>&1 + if errorlevel 1 ( + echo Node.js 24 was not found. + echo Install Node.js 24 or copy the original runtime\node.exe into this folder. + pause + exit /b 1 + ) + node "%~dp0registry\server.js" +) +echo. +echo FPV-RID registration server has stopped. +pause