feat(api): 新增素材检索 API 服务(图标/海报检索 + SVG 直链 + Key 鉴权 + 中文语义检索)
This commit is contained in:
@@ -0,0 +1,5 @@
|
||||
# API 运行数据(索引 / Key)——不入库
|
||||
data/
|
||||
config.json
|
||||
*.log
|
||||
node_modules/
|
||||
+339
@@ -0,0 +1,339 @@
|
||||
# 画个标素材 API
|
||||
|
||||
面向公司内部项目的**素材检索服务**:按关键词查图标/海报素材,直接拿到可嵌入的 SVG。
|
||||
|
||||
- 线上地址:`https://drawlogo.zhuig.com/api/v1`
|
||||
- 鉴权:API Key(`X-API-Key` 请求头)
|
||||
- 数据规模:图标 **371,504** 个 / 224 源;海报 **1,582** 个 / 25 源;技能元数据 130 个
|
||||
- 特性:支持**中文语义检索**(搜「学校」命中 school / graduation-cap / book…)、按协议过滤商用可用素材、默认排除 `-off`/`-error` 等负面变体
|
||||
|
||||
> 本服务只提供**素材与技能元数据**,不提供 AI 生成 LOGO(当前 AI 生成质量不足以对外提供)。
|
||||
|
||||
---
|
||||
|
||||
## 一、快速开始
|
||||
|
||||
```bash
|
||||
# 1. 搜索(中文或英文)
|
||||
curl -H "X-API-Key: <你的Key>" \
|
||||
"https://drawlogo.zhuig.com/api/v1/icons/search?q=学校&limit=5"
|
||||
|
||||
# 2. 直接拿 SVG(可直接放进 <img src> 或 fetch)
|
||||
curl -H "X-API-Key: <你的Key>" \
|
||||
"https://drawlogo.zhuig.com/api/v1/icons/lucide/school.svg"
|
||||
|
||||
# 3. 查看有哪些源(免鉴权)
|
||||
curl "https://drawlogo.zhuig.com/api/v1/sources"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 二、鉴权
|
||||
|
||||
请求头二选一:
|
||||
|
||||
```
|
||||
X-API-Key: dl_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
|
||||
Authorization: Bearer dl_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
|
||||
```
|
||||
|
||||
- Key 由管理员用 `node admin.js create --name "调用方"` 生成,**明文只显示一次**
|
||||
- 服务端只存 SHA-256 摘要,无法反查明文
|
||||
- 每个 Key 独立配置:分钟限流、每日配额、启用/禁用
|
||||
|
||||
**免鉴权端点**(仅基础信息):`/health`、`/stats`、`/sources`
|
||||
|
||||
---
|
||||
|
||||
## 三、端点
|
||||
|
||||
所有成功响应:
|
||||
|
||||
```json
|
||||
{ "ok": true, "data": ..., "meta": { "total": 1059, "limit": 5, "offset": 0 } }
|
||||
```
|
||||
|
||||
所有失败响应:
|
||||
|
||||
```json
|
||||
{ "ok": false, "error": { "code": "UNAUTHORIZED", "message": "缺少 API Key" } }
|
||||
```
|
||||
|
||||
### 1. 健康检查
|
||||
|
||||
```
|
||||
GET /api/v1/health # 免鉴权
|
||||
```
|
||||
```json
|
||||
{ "ok": true, "data": { "status": "up", "version": "1.0.0", "builtAt": "...", "uptime": 3600 } }
|
||||
```
|
||||
|
||||
### 2. 运行统计
|
||||
|
||||
```
|
||||
GET /api/v1/stats # 免鉴权
|
||||
```
|
||||
|
||||
### 3. 源清单
|
||||
|
||||
```
|
||||
GET /api/v1/sources?kind=icons|posters # 免鉴权
|
||||
```
|
||||
返回每个源的 `id / name / nameCn / desc / type / license / commercial / count / workspaces`。
|
||||
**接入前建议先读这个**,确认目标源协议是否允许商用。
|
||||
|
||||
### 4. 图标搜索
|
||||
|
||||
```
|
||||
GET /api/v1/icons/search
|
||||
```
|
||||
|
||||
| 参数 | 说明 | 默认 |
|
||||
|---|---|---|
|
||||
| `q` | 关键词(英文名 / 中文分类 / 中文语义) | 空=全部 |
|
||||
| `source` | 限定源 id,如 `lucide` | 全部 |
|
||||
| `type` | `icon`(单色)/ `emoji`(多色)/ `brand`(品牌) | 全部 |
|
||||
| `commercial` | `1`=仅商用可用(排除 BY-NC/BY-SA/BY-ND/GPL) | 不过滤 |
|
||||
| `dedupe` | `1`=按图标名去重(多源同名只留最优一个) | `0` |
|
||||
| `include_negative` | `1`=包含 `-off`/`-error` 等负面变体 | `0` |
|
||||
| `limit` | 1–100 | `20` |
|
||||
| `offset` | 分页偏移 | `0` |
|
||||
|
||||
响应项:
|
||||
|
||||
```json
|
||||
{
|
||||
"id": "school",
|
||||
"name": "school",
|
||||
"categoryCn": "教育学习",
|
||||
"type": "icon",
|
||||
"source": "lucide",
|
||||
"sourceNameCn": "Lucide 图标",
|
||||
"license": "ISC",
|
||||
"commercial": true,
|
||||
"index": 1321
|
||||
}
|
||||
```
|
||||
|
||||
> `index` 是该素材在源内的序号,用于内部定位;外部调用请用 `source` + `name`。
|
||||
|
||||
排序规则:名称精确 > 名称前缀 > 名称包含 > 中文别名精确 > 分类匹配 > 别名包含;同分时主流库(lucide/tabler/heroicons/feather…)优先、短名优先。
|
||||
|
||||
### 5. 图标详情 / SVG 直链
|
||||
|
||||
```
|
||||
GET /api/v1/icons/{source}/{name} # JSON(含 svg 原文)
|
||||
GET /api/v1/icons/{source}/{name}.svg # image/svg+xml
|
||||
```
|
||||
|
||||
SVG 直链返回:
|
||||
|
||||
```html
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor">
|
||||
<path d="..." />
|
||||
</svg>
|
||||
```
|
||||
|
||||
- 单色图标(`type=icon`)带 `fill="currentColor"`,颜色由 CSS 的 `color` 控制
|
||||
- 多色图标(`type=emoji/brand`)保留原色,不加 `fill`
|
||||
- 建议在 `<img>` 中用时手动加 `style="color:#1B4F72"`
|
||||
|
||||
### 6. 随机图标
|
||||
|
||||
```
|
||||
GET /api/v1/icons/random?count=10&source=lucide
|
||||
```
|
||||
适合做占位图、灵感墙、测试数据。
|
||||
|
||||
### 7. 海报素材
|
||||
|
||||
```
|
||||
GET /api/v1/posters/search?q=&type=&source=&limit=
|
||||
GET /api/v1/posters/{source}/{name}
|
||||
```
|
||||
`type` 为 `palette`(配色)/ `font`(字体)/ `bg`(背景)/ `decoration`(装饰)。
|
||||
配色类素材的 `data` 字段内联了色值数组;字体类给出 `file` 路径(相对静态站根目录)。
|
||||
|
||||
### 8. 技能元数据
|
||||
|
||||
```
|
||||
GET /api/v1/skills?workspace=logo&step=3&category=color
|
||||
GET /api/v1/skills/{id}
|
||||
```
|
||||
返回技能的 `id / name / category / scene / summary / params / step / kind / workspaces`。
|
||||
**仅元数据**(可直接当设计知识/评审规则用),不执行 `run`。
|
||||
|
||||
---
|
||||
|
||||
## 四、中文检索说明
|
||||
|
||||
图标名是英文(`graduation-cap`),分类是中文宽类目(`教育学习`)。为了支持「学校」「医院」「餐厅」这类词,服务内置了一张**中文语义别名表**(约 240 个高频词 → 英文词根),构建索引时为每个图标预计算别名。
|
||||
|
||||
- 搜「学校」→ school / graduation-cap / book / backpack…
|
||||
- 搜「医院」→ hospital / ambulance / stethoscope / pill…
|
||||
- 搜「工厂」→ factory / building-factory…
|
||||
- 搜「飞机」→ plane / plane-landing / plane-takeoff…
|
||||
|
||||
词表在 [build-index.js](./build-index.js) 的 `CN_ALIAS`,新增行业词直接加进去并重建索引即可。
|
||||
|
||||
---
|
||||
|
||||
## 五、限流与配额
|
||||
|
||||
| 项 | 默认 | 说明 |
|
||||
|---|---|---|
|
||||
| 分钟限流 | 60 次/分钟/Key | 创建时可调,如 `--rate 120` |
|
||||
| 每日配额 | 20,000 次/天/Key | 创建时可调,如 `--quota 30000` |
|
||||
|
||||
响应头:
|
||||
|
||||
```
|
||||
X-RateLimit-Limit: 120
|
||||
X-RateLimit-Remaining: 118
|
||||
```
|
||||
|
||||
超限返回 `429`,`Retry-After: 60`。
|
||||
|
||||
### 错误码
|
||||
|
||||
| HTTP | code | 含义 |
|
||||
|---|---|---|
|
||||
| 400 | `BAD_REQUEST` | 参数非法 |
|
||||
| 401 | `UNAUTHORIZED` | 未带 Key |
|
||||
| 403 | `INVALID_KEY` | Key 无效或已禁用 |
|
||||
| 404 | `NOT_FOUND` | 素材/源/技能不存在 |
|
||||
| 405 | `METHOD_NOT_ALLOWED` | 仅支持 GET |
|
||||
| 429 | `RATE_LIMITED` | 分钟限流 |
|
||||
| 429 | `DAILY_QUOTA_EXCEEDED` | 日配额用尽 |
|
||||
| 500 | `INTERNAL` | 服务内部错误 |
|
||||
| 503 | `NOT_READY` | 索引未构建 |
|
||||
|
||||
---
|
||||
|
||||
## 六、接入示例
|
||||
|
||||
### JavaScript / 前端
|
||||
|
||||
```js
|
||||
const KEY = '...'; // 注意:放前端会暴露给访客,建议走后端代理
|
||||
const r = await fetch('/api/v1/icons/search?q=学校&limit=8', {
|
||||
headers: { 'X-API-Key': KEY }
|
||||
});
|
||||
const { data } = await r.json();
|
||||
data.forEach(ic => {
|
||||
const img = new Image();
|
||||
img.src = `/api/v1/icons/${ic.source}/${ic.name}.svg`;
|
||||
});
|
||||
```
|
||||
|
||||
### Node / 后端
|
||||
|
||||
```js
|
||||
const res = await fetch('https://drawlogo.zhuig.com/api/v1/icons/search?q=hospital&limit=5', {
|
||||
headers: { 'X-API-Key': process.env.DRAWLOGO_API_KEY }
|
||||
});
|
||||
const { data } = await res.json();
|
||||
```
|
||||
|
||||
### Java(Spring RestTemplate)
|
||||
|
||||
```java
|
||||
HttpHeaders h = new HttpHeaders();
|
||||
h.set("X-API-Key", System.getenv("DRAWLOGO_API_KEY"));
|
||||
String url = "https://drawlogo.zhuig.com/api/v1/icons/search?q=%E5%AD%A6%E6%A0%A1&limit=5";
|
||||
ResponseEntity<String> resp = new RestTemplate().exchange(url, HttpMethod.GET, new HttpEntity<>(h), String.class);
|
||||
```
|
||||
|
||||
### Python
|
||||
|
||||
```python
|
||||
import os, requests
|
||||
r = requests.get(
|
||||
"https://drawlogo.zhuig.com/api/v1/icons/search",
|
||||
params={"q": "学校", "limit": 5},
|
||||
headers={"X-API-Key": os.environ["DRAWLOGO_API_KEY"]},
|
||||
)
|
||||
print(r.json()["data"])
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 七、协议合规(重要)
|
||||
|
||||
- 调用 `/api/v1/sources` 可看到每个源的 `license` 与 `commercial`
|
||||
- 商业项目请加 `commercial=1`,或自行校验 `commercial: true`
|
||||
- 以下协议**不可商用**:`BY-NC`、`BY-SA`、`BY-ND`、`GPL`
|
||||
- 品牌类图标(`type=brand`,如 Instagram / 微信 logo)有商标风险,做 LOGO 时避免直接使用
|
||||
- 建议在产物中标注素材来源与协议(源 `name` + `license`)
|
||||
|
||||
---
|
||||
|
||||
## 八、运维
|
||||
|
||||
### 重建索引(素材库更新后)
|
||||
|
||||
```bash
|
||||
cd /opt/drawlogo-api
|
||||
DRAWLOGO_ROOT=/opt/drawlogo node --max-old-space-size=1536 build-index.js
|
||||
sudo systemctl restart drawlogo-api
|
||||
```
|
||||
|
||||
索引产物在 `data/`(约 530 MB),**不纳入 git**。
|
||||
|
||||
### Key 管理
|
||||
|
||||
```bash
|
||||
cd /opt/drawlogo-api
|
||||
node admin.js create --name "项目A" --rate 120 --quota 30000
|
||||
node admin.js list
|
||||
node admin.js disable <key_id>
|
||||
node admin.js enable <key_id>
|
||||
node admin.js revoke <key_id>
|
||||
```
|
||||
|
||||
Key 文件 `data/apikeys.json` 权限 600,服务每 5 秒热加载,**改 Key 无需重启**。
|
||||
|
||||
### 服务与反向代理
|
||||
|
||||
```bash
|
||||
sudo systemctl status drawlogo-api
|
||||
sudo journalctl -u drawlogo-api -f
|
||||
```
|
||||
|
||||
- systemd 单元:[deploy/drawlogo-api.service](./deploy/drawlogo-api.service)
|
||||
- nginx 片段:[deploy/nginx-location.conf](./deploy/nginx-location.conf)(必须 `location ^~ /api/`)
|
||||
- 幂等写入脚本:`sudo python3 deploy/patch-nginx.py`
|
||||
|
||||
### 更新 API 代码
|
||||
|
||||
```bash
|
||||
# 本地
|
||||
scp api/server.js api/build-index.js api/admin.js ubuntu@119.45.242.239:/opt/drawlogo-api/
|
||||
scp api/deploy/* ubuntu@119.45.242.239:/opt/drawlogo-api/deploy/
|
||||
# 服务器
|
||||
sudo systemctl restart drawlogo-api
|
||||
```
|
||||
|
||||
> 注意:静态站的 Gitea 自动部署只更新 `/opt/drawlogo`,**不会**更新 `/opt/drawlogo-api`,API 代码需按上面的步骤单独发布。
|
||||
|
||||
---
|
||||
|
||||
## 九、架构
|
||||
|
||||
```
|
||||
公司各项目
|
||||
│ HTTPS + X-API-Key
|
||||
▼
|
||||
nginx (drawlogo.zhuig.com)
|
||||
├── / → /opt/drawlogo(静态站)
|
||||
└── ^~ /api/ → 127.0.0.1:7891(drawlogo-api)
|
||||
├── data/*.idx.json 常驻内存(检索索引)
|
||||
├── data/*.jsonl 按字节偏移随机读取(素材正文)
|
||||
├── data/apikeys.json Key(SHA-256)
|
||||
└── data/skills.json 技能元数据
|
||||
```
|
||||
|
||||
- 零第三方依赖(Node 原生 `http`/`fs`)
|
||||
- 索引常驻约 130–170 MB;素材正文按需 seek,单次读几百字节
|
||||
- 服务只监听 `127.0.0.1`,公网仅经 nginx HTTPS 进入
|
||||
- 内存上限 900 MB(systemd `MemoryMax`),避免影响同机其他项目
|
||||
+143
@@ -0,0 +1,143 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* 画个标 · API Key 管理
|
||||
*
|
||||
* 用法:
|
||||
* node admin.js create --name "内部项目A" [--rate 60] [--quota 20000] [--note "备注"]
|
||||
* node admin.js list
|
||||
* node admin.js enable <id>
|
||||
* node admin.js disable <id>
|
||||
* node admin.js revoke <id>
|
||||
*
|
||||
* 说明:明文 Key 只在 create 时输出一次,服务端只保存 SHA-256 摘要。
|
||||
*/
|
||||
'use strict';
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const crypto = require('crypto');
|
||||
|
||||
const ROOT = __dirname;
|
||||
const CONFIG = (() => {
|
||||
const f = path.join(ROOT, 'config.json');
|
||||
const base = { keyFile: './data/apikeys.json' };
|
||||
if (!fs.existsSync(f)) return base;
|
||||
return { ...base, ...JSON.parse(fs.readFileSync(f, 'utf8')) };
|
||||
})();
|
||||
const KEY_FILE = path.resolve(ROOT, CONFIG.keyFile);
|
||||
|
||||
function load() {
|
||||
if (!fs.existsSync(KEY_FILE)) return [];
|
||||
try {
|
||||
const list = JSON.parse(fs.readFileSync(KEY_FILE, 'utf8'));
|
||||
return Array.isArray(list) ? list : [];
|
||||
} catch (e) {
|
||||
console.error('Key 文件解析失败:' + e.message);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
function save(list) {
|
||||
fs.mkdirSync(path.dirname(KEY_FILE), { recursive: true });
|
||||
fs.writeFileSync(KEY_FILE, JSON.stringify(list, null, 2));
|
||||
try { fs.chmodSync(KEY_FILE, 0o600); } catch (e) { /* Windows 忽略 */ }
|
||||
}
|
||||
|
||||
function parseArgs(argv) {
|
||||
const out = { _: [] };
|
||||
for (let i = 0; i < argv.length; i++) {
|
||||
const a = argv[i];
|
||||
if (a.startsWith('--')) {
|
||||
const key = a.slice(2);
|
||||
const next = argv[i + 1];
|
||||
if (next && !next.startsWith('--')) { out[key] = next; i++; }
|
||||
else out[key] = true;
|
||||
} else {
|
||||
out._.push(a);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const args = parseArgs(process.argv.slice(2));
|
||||
const cmd = args._[0];
|
||||
|
||||
function create() {
|
||||
const name = args.name;
|
||||
if (!name || name === true) {
|
||||
console.error('请提供 --name "调用方名称"');
|
||||
process.exit(1);
|
||||
}
|
||||
const list = load();
|
||||
const raw = 'dl_' + crypto.randomBytes(20).toString('hex');
|
||||
const rec = {
|
||||
id: 'key_' + crypto.randomBytes(4).toString('hex'),
|
||||
name,
|
||||
hash: crypto.createHash('sha256').update(raw).digest('hex'),
|
||||
enabled: true,
|
||||
ratePerMin: Number(args.rate || CONFIG.defaultRatePerMin || 60),
|
||||
dailyQuota: Number(args.quota || CONFIG.defaultDailyQuota || 20000),
|
||||
note: args.note && args.note !== true ? String(args.note) : '',
|
||||
createdAt: new Date().toISOString(),
|
||||
lastUsedAt: null
|
||||
};
|
||||
list.push(rec);
|
||||
save(list);
|
||||
|
||||
console.log('\n✅ 已创建 API Key(明文仅显示这一次,请立即保存)\n');
|
||||
console.log(' 名称 : ' + rec.name);
|
||||
console.log(' Key ID : ' + rec.id);
|
||||
console.log(' 限流 : ' + rec.ratePerMin + ' 次/分钟');
|
||||
console.log(' 日配额 : ' + rec.dailyQuota + ' 次/天');
|
||||
console.log('\n API Key: ' + raw + '\n');
|
||||
console.log(' 调用示例:');
|
||||
console.log(' curl -H "X-API-Key: ' + raw + '" \\');
|
||||
console.log(' "https://drawlogo.zhuig.com/api/v1/icons/search?q=school&limit=5"\n');
|
||||
}
|
||||
|
||||
function list() {
|
||||
const all = load();
|
||||
if (!all.length) { console.log('暂无 API Key'); return; }
|
||||
console.log('\nID 状态 限流/分 日配额 名称');
|
||||
console.log('─'.repeat(72));
|
||||
for (const k of all) {
|
||||
console.log(
|
||||
String(k.id).padEnd(15) +
|
||||
(k.enabled === false ? '禁用 ' : '启用 ').padEnd(9) +
|
||||
String(k.ratePerMin || '').padEnd(10) +
|
||||
String(k.dailyQuota || '').padEnd(10) +
|
||||
k.name
|
||||
);
|
||||
}
|
||||
console.log('');
|
||||
}
|
||||
|
||||
function setEnabled(id, enabled) {
|
||||
const all = load();
|
||||
const hit = all.find(k => k.id === id);
|
||||
if (!hit) { console.error('未找到: ' + id); process.exit(1); }
|
||||
hit.enabled = enabled;
|
||||
save(all);
|
||||
console.log(`${enabled ? '已启用' : '已禁用'}: ${id} (${hit.name})`);
|
||||
}
|
||||
|
||||
function revoke(id) {
|
||||
const all = load();
|
||||
const next = all.filter(k => k.id !== id);
|
||||
if (next.length === all.length) { console.error('未找到: ' + id); process.exit(1); }
|
||||
save(next);
|
||||
console.log('已删除: ' + id);
|
||||
}
|
||||
|
||||
switch (cmd) {
|
||||
case 'create': create(); break;
|
||||
case 'list': list(); break;
|
||||
case 'enable': setEnabled(args._[1], true); break;
|
||||
case 'disable': setEnabled(args._[1], false); break;
|
||||
case 'revoke': revoke(args._[1]); break;
|
||||
default:
|
||||
console.log('用法:');
|
||||
console.log(' node admin.js create --name "调用方" [--rate 60] [--quota 20000]');
|
||||
console.log(' node admin.js list');
|
||||
console.log(' node admin.js enable|disable|revoke <id>');
|
||||
}
|
||||
@@ -0,0 +1,571 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* 画个标 · 素材 API 索引构建
|
||||
*
|
||||
* 读取 ../js/data 下的图标/海报源文件,产出两类文件到 api/data/:
|
||||
* {kind}/{source}.jsonl 每行一个素材的完整 JSON(按字节偏移随机读取)
|
||||
* {kind}/{source}.idx.json 检索索引(name/categoryCn/type + 字节偏移)
|
||||
*
|
||||
* 设计要点:
|
||||
* - 不依赖任何第三方库,Node 原生即可跑
|
||||
* - 索引常驻内存,素材正文按需 seek 读取,避免把 99MB 源文件整体加载
|
||||
* - 源文件是严格 JSON 对象字面量(window['HGB_Source_x'] = {...};),可直接 JSON.parse
|
||||
*
|
||||
* 用法:
|
||||
* node build-index.js # 默认读取上一级的 js/data
|
||||
* DRAWLOGO_ROOT=/opt/drawlogo node build-index.js
|
||||
*/
|
||||
'use strict';
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const API_ROOT = __dirname;
|
||||
const SITE_ROOT = process.env.DRAWLOGO_ROOT || path.resolve(API_ROOT, '..');
|
||||
const SITE_DATA = path.join(SITE_ROOT, 'js', 'data');
|
||||
const OUT = path.join(API_ROOT, 'data');
|
||||
const OUT_ICONS = path.join(OUT, 'icons');
|
||||
const OUT_POSTERS = path.join(OUT, 'posters');
|
||||
|
||||
/** 不允许商用的协议特征(与项目规则一致:排除 BY-SA/BY-NC/BY-ND/GPL) */
|
||||
const NON_COMMERCIAL_RE = /BY-NC|BY-SA|BY-ND|\bGPL\b|NonCommercial|非商业|禁止商用/i;
|
||||
|
||||
/**
|
||||
* 中文语义别名表:中文关键词 → 英文词根
|
||||
* 解决的问题:图标 name 是英文、categoryCn 是「教育学习」这类宽分类,
|
||||
* 用户搜「学校/医院/餐厅」时匹配不到。构建期为每个图标预计算中文别名。
|
||||
*/
|
||||
const CN_ALIAS = {
|
||||
'学校': ['school', 'graduation', 'student', 'book', 'academic', 'backpack'],
|
||||
'教育': ['education', 'school', 'graduation', 'book', 'study', 'learn', 'academic', 'pencil'],
|
||||
'医院': ['hospital', 'medical', 'health', 'doctor', 'nurse', 'stethoscope', 'pill', 'ambulance'],
|
||||
'医疗': ['medical', 'health', 'hospital', 'doctor', 'pill', 'stethoscope', 'first-aid'],
|
||||
'餐厅': ['restaurant', 'food', 'dining', 'chef', 'fork', 'knife', 'meal', 'cook', 'utensil'],
|
||||
'餐饮': ['restaurant', 'food', 'chef', 'fork', 'meal', 'cook', 'coffee', 'cup'],
|
||||
'咖啡': ['coffee', 'cup', 'cafe', 'mug', 'tea'],
|
||||
'银行': ['bank', 'wallet', 'credit', 'card', 'money', 'payment', 'currency', 'coin'],
|
||||
'支付': ['payment', 'credit', 'card', 'wallet', 'qr', 'money', 'cash'],
|
||||
'金融': ['finance', 'money', 'bank', 'chart', 'stock', 'coin', 'currency', 'wallet'],
|
||||
'科技': ['tech', 'chip', 'cpu', 'circuit', 'robot', 'code', 'terminal', 'server', 'brain'],
|
||||
'互联网': ['internet', 'web', 'cloud', 'network', 'wifi', 'globe', 'link'],
|
||||
'物流': ['truck', 'shipping', 'delivery', 'package', 'box', 'warehouse', 'cargo', 'container'],
|
||||
'运输': ['truck', 'shipping', 'delivery', 'package', 'cargo', 'bus', 'train'],
|
||||
'房产': ['home', 'house', 'building', 'apartment', 'estate', 'door'],
|
||||
'建筑': ['building', 'architecture', 'construction', 'home', 'house', 'crane'],
|
||||
'法律': ['law', 'legal', 'gavel', 'justice', 'scale', 'court', 'contract'],
|
||||
'旅游': ['travel', 'plane', 'map', 'luggage', 'hotel', 'compass', 'globe', 'beach'],
|
||||
'酒店': ['hotel', 'bed', 'building', 'key', 'door'],
|
||||
'制造': ['factory', 'industry', 'gear', 'machine', 'cog', 'wrench', 'production'],
|
||||
'工业': ['factory', 'industry', 'gear', 'machine', 'cog', 'wrench'],
|
||||
'农业': ['agriculture', 'farm', 'plant', 'leaf', 'seed', 'tractor', 'wheat'],
|
||||
'能源': ['energy', 'battery', 'power', 'solar', 'electric', 'zap', 'fuel', 'plug'],
|
||||
'零售': ['shop', 'store', 'cart', 'bag', 'shopping', 'basket', 'market'],
|
||||
'电商': ['shop', 'cart', 'shopping', 'store', 'bag', 'package'],
|
||||
'娱乐': ['music', 'play', 'game', 'movie', 'film', 'video', 'headphone', 'party'],
|
||||
'媒体': ['media', 'video', 'camera', 'music', 'film', 'play', 'mic'],
|
||||
'体育': ['sport', 'ball', 'fitness', 'run', 'gym', 'bike', 'swim', 'trophy'],
|
||||
'安防': ['security', 'shield', 'lock', 'camera', 'alarm', 'guard', 'safe'],
|
||||
'通信': ['phone', 'message', 'mail', 'signal', 'wifi', 'antenna', 'chat'],
|
||||
'汽车': ['car', 'auto', 'vehicle', 'truck', 'wheel', 'road', 'engine'],
|
||||
'航空': ['plane', 'flight', 'airplane', 'rocket', 'jet'],
|
||||
'政务': ['government', 'building', 'document', 'law', 'badge', 'flag', 'landmark'],
|
||||
'宠物': ['pet', 'dog', 'cat', 'paw', 'animal', 'bone'],
|
||||
'美容': ['beauty', 'scissors', 'cosmetic', 'sparkle', 'flower', 'lipstick'],
|
||||
'服装': ['shirt', 'clothes', 'fashion', 'dress', 'tag', 'hanger'],
|
||||
'食品': ['food', 'apple', 'coffee', 'restaurant', 'meal', 'bottle', 'bread'],
|
||||
'工具': ['tool', 'wrench', 'hammer', 'settings', 'gear', 'screwdriver'],
|
||||
'安全': ['shield', 'lock', 'key', 'security', 'safe', 'protect'],
|
||||
'云': ['cloud', 'server', 'upload', 'download', 'storage'],
|
||||
'数据': ['data', 'chart', 'database', 'analytics', 'graph', 'bar', 'table'],
|
||||
'人工智能': ['ai', 'robot', 'brain', 'chip', 'sparkles', 'neural'],
|
||||
'设计': ['design', 'pen', 'brush', 'palette', 'layout', 'ruler', 'vector'],
|
||||
'音乐': ['music', 'note', 'headphone', 'speaker', 'audio', 'mic'],
|
||||
'摄影': ['camera', 'photo', 'image', 'aperture', 'lens'],
|
||||
'游戏': ['game', 'joystick', 'controller', 'dice', 'trophy', 'arcade'],
|
||||
'地图': ['map', 'location', 'pin', 'navigation', 'compass', 'route'],
|
||||
'时间': ['clock', 'time', 'calendar', 'watch', 'timer', 'alarm'],
|
||||
'天气': ['weather', 'sun', 'cloud', 'rain', 'snow', 'wind', 'thermometer'],
|
||||
'环保': ['leaf', 'recycle', 'nature', 'tree', 'eco', 'plant', 'globe'],
|
||||
'公益': ['heart', 'hand', 'donate', 'help', 'charity', 'volunteer'],
|
||||
'社交': ['user', 'users', 'message', 'chat', 'share', 'heart', 'comment'],
|
||||
'办公': ['briefcase', 'file', 'folder', 'desk', 'paperclip', 'printer'],
|
||||
'购物': ['cart', 'bag', 'shopping', 'store', 'tag', 'credit'],
|
||||
'地图定位': ['map-pin', 'location', 'navigation', 'gps'],
|
||||
'视频': ['video', 'play', 'film', 'camera', 'youtube', 'movie'],
|
||||
'搜索': ['search', 'magnify', 'find', 'zoom'],
|
||||
'设置': ['settings', 'gear', 'cog', 'sliders', 'wrench'],
|
||||
'用户': ['user', 'users', 'person', 'account', 'profile', 'avatar'],
|
||||
'下载': ['download', 'arrow-down', 'save', 'import'],
|
||||
'上传': ['upload', 'arrow-up', 'cloud', 'export'],
|
||||
'通知': ['bell', 'notification', 'alert', 'message'],
|
||||
'邮件': ['mail', 'email', 'envelope', 'inbox', 'send'],
|
||||
'电话': ['phone', 'call', 'telephone', 'headset'],
|
||||
'日历': ['calendar', 'date', 'schedule', 'event'],
|
||||
'锁': ['lock', 'unlock', 'key', 'shield', 'password'],
|
||||
'星星': ['star', 'sparkle', 'favorite', 'rating'],
|
||||
'心': ['heart', 'love', 'favorite', 'like'],
|
||||
'箭头': ['arrow', 'chevron', 'direction', 'right', 'left', 'up', 'down'],
|
||||
'文件': ['file', 'document', 'folder', 'page', 'paper'],
|
||||
'图表': ['chart', 'graph', 'bar', 'pie', 'trend', 'analytics'],
|
||||
'机器人': ['robot', 'bot', 'ai', 'android'],
|
||||
'礼物': ['gift', 'present', 'box', 'ribbon'],
|
||||
'旗帜': ['flag', 'banner', 'country'],
|
||||
'地球': ['globe', 'earth', 'world', 'planet', 'international'],
|
||||
'闪电': ['zap', 'lightning', 'flash', 'bolt', 'power'],
|
||||
'火焰': ['fire', 'flame', 'hot', 'burn'],
|
||||
'水滴': ['droplet', 'water', 'drop', 'rain'],
|
||||
'叶子': ['leaf', 'plant', 'nature', 'eco', 'green'],
|
||||
'太阳': ['sun', 'sunny', 'light', 'day'],
|
||||
'月亮': ['moon', 'night', 'dark', 'sleep'],
|
||||
'相机': ['camera', 'photo', 'lens', 'picture'],
|
||||
'打印机': ['printer', 'print', 'paper'],
|
||||
'键盘': ['keyboard', 'typing', 'input'],
|
||||
'鼠标': ['mouse', 'click', 'pointer', 'cursor'],
|
||||
'电脑': ['computer', 'laptop', 'desktop', 'monitor', 'pc'],
|
||||
'手机': ['phone', 'mobile', 'smartphone', 'device'],
|
||||
'平板': ['tablet', 'ipad', 'device'],
|
||||
'服务器': ['server', 'database', 'rack', 'cloud', 'host'],
|
||||
'数据库': ['database', 'db', 'storage', 'server', 'data'],
|
||||
'网络': ['network', 'wifi', 'signal', 'internet', 'router', 'globe'],
|
||||
'蓝牙': ['bluetooth', 'wireless', 'connect'],
|
||||
'电池': ['battery', 'power', 'charge', 'energy'],
|
||||
'插座': ['plug', 'socket', 'power', 'electric'],
|
||||
'灯泡': ['bulb', 'idea', 'light', 'lamp'],
|
||||
'齿轮': ['gear', 'cog', 'settings', 'machine', 'engine'],
|
||||
'锤子': ['hammer', 'tool', 'build', 'repair'],
|
||||
'扳手': ['wrench', 'tool', 'repair', 'settings'],
|
||||
'螺丝刀': ['screwdriver', 'tool', 'repair'],
|
||||
'刷子': ['brush', 'paint', 'design', 'clean'],
|
||||
'画笔': ['brush', 'pen', 'paint', 'design', 'draw'],
|
||||
'调色板': ['palette', 'color', 'design', 'paint'],
|
||||
'尺子': ['ruler', 'measure', 'design', 'size'],
|
||||
'剪刀': ['scissors', 'cut', 'tool', 'barber'],
|
||||
'针': ['needle', 'pin', 'sew', 'medical'],
|
||||
'药': ['pill', 'medicine', 'drug', 'health', 'pharmacy'],
|
||||
'注射器': ['syringe', 'vaccine', 'medical', 'injection'],
|
||||
'听诊器': ['stethoscope', 'doctor', 'medical', 'health'],
|
||||
'救护车': ['ambulance', 'emergency', 'medical', 'hospital'],
|
||||
'消防': ['fire', 'extinguisher', 'emergency', 'alarm'],
|
||||
'警察': ['police', 'badge', 'security', 'law'],
|
||||
'法庭': ['court', 'gavel', 'law', 'justice', 'judge'],
|
||||
'合同': ['contract', 'document', 'agreement', 'sign', 'file'],
|
||||
'印章': ['stamp', 'seal', 'approve', 'official'],
|
||||
'发票': ['invoice', 'receipt', 'bill', 'document', 'money'],
|
||||
'钱包': ['wallet', 'money', 'payment', 'finance', 'card'],
|
||||
'硬币': ['coin', 'money', 'currency', 'cash', 'finance'],
|
||||
'信用卡': ['credit-card', 'payment', 'bank', 'money', 'card'],
|
||||
'二维码': ['qr', 'code', 'scan', 'payment'],
|
||||
'条形码': ['barcode', 'scan', 'code', 'product'],
|
||||
'包裹': ['package', 'box', 'delivery', 'shipping', 'parcel'],
|
||||
'卡车': ['truck', 'delivery', 'shipping', 'transport', 'logistics'],
|
||||
'飞机': ['plane', 'flight', 'travel', 'airport', 'airplane'],
|
||||
'火车': ['train', 'railway', 'transport', 'travel'],
|
||||
'公交': ['bus', 'transport', 'public', 'travel'],
|
||||
'自行车': ['bike', 'bicycle', 'cycle', 'transport', 'sport'],
|
||||
'船': ['ship', 'boat', 'sail', 'sea', 'transport'],
|
||||
'路': ['road', 'route', 'street', 'map', 'navigation'],
|
||||
'地图标记': ['map-pin', 'location', 'marker', 'gps', 'place'],
|
||||
'导航': ['navigation', 'compass', 'route', 'direction', 'gps'],
|
||||
'指南针': ['compass', 'navigation', 'direction', 'explore'],
|
||||
'行李箱': ['luggage', 'suitcase', 'travel', 'bag'],
|
||||
'护照': ['passport', 'travel', 'document', 'id'],
|
||||
'签证': ['visa', 'passport', 'travel', 'document'],
|
||||
'床': ['bed', 'hotel', 'sleep', 'room', 'furniture'],
|
||||
'房子': ['house', 'home', 'building', 'property', 'real-estate'],
|
||||
'公寓': ['apartment', 'building', 'home', 'property'],
|
||||
'工厂': ['factory', 'industry', 'manufacture', 'plant', 'production'],
|
||||
'仓库': ['warehouse', 'storage', 'logistics', 'inventory'],
|
||||
'小麦': ['wheat', 'grain', 'agriculture', 'farm', 'food'],
|
||||
'拖拉机': ['tractor', 'farm', 'agriculture', 'vehicle'],
|
||||
'种植': ['plant', 'seed', 'grow', 'agriculture', 'farm'],
|
||||
'太阳能': ['solar', 'sun', 'energy', 'panel', 'renewable'],
|
||||
'风力': ['wind', 'turbine', 'energy', 'renewable'],
|
||||
'核能': ['nuclear', 'atom', 'energy', 'power'],
|
||||
'回收': ['recycle', 'eco', 'environment', 'green', 'sustainability'],
|
||||
'树': ['tree', 'nature', 'forest', 'eco', 'plant'],
|
||||
'花': ['flower', 'nature', 'beauty', 'plant', 'bloom'],
|
||||
'动物': ['animal', 'pet', 'wildlife', 'dog', 'cat'],
|
||||
'狗': ['dog', 'pet', 'animal', 'paw'],
|
||||
'猫': ['cat', 'pet', 'animal', 'kitten'],
|
||||
'咖啡杯': ['coffee', 'cup', 'mug', 'cafe', 'drink'],
|
||||
'面包': ['bread', 'food', 'bakery', 'bake'],
|
||||
'蛋糕': ['cake', 'dessert', 'birthday', 'food'],
|
||||
'披萨': ['pizza', 'food', 'restaurant', 'slice'],
|
||||
'汉堡': ['burger', 'food', 'fastfood', 'restaurant'],
|
||||
'饮料': ['drink', 'beverage', 'cup', 'bottle', 'water'],
|
||||
'酒': ['wine', 'beer', 'drink', 'bar', 'alcohol'],
|
||||
'购物车': ['cart', 'shopping', 'store', 'ecommerce', 'buy'],
|
||||
'商店': ['shop', 'store', 'market', 'retail', 'building'],
|
||||
'标签': ['tag', 'label', 'price', 'sale'],
|
||||
'折扣': ['discount', 'sale', 'tag', 'percent', 'price'],
|
||||
'支付成功': ['check', 'success', 'payment', 'done', 'circle-check'],
|
||||
'图表分析': ['chart', 'analytics', 'data', 'report', 'trend', 'graph'],
|
||||
'报表': ['report', 'document', 'chart', 'data', 'file'],
|
||||
'演示': ['presentation', 'screen', 'slides', 'projector', 'chart'],
|
||||
'会议': ['meeting', 'users', 'video', 'calendar', 'presentation'],
|
||||
'团队': ['team', 'users', 'group', 'people', 'collaboration'],
|
||||
'招聘': ['recruit', 'user', 'briefcase', 'hiring', 'person'],
|
||||
'简历': ['resume', 'document', 'briefcase', 'profile', 'cv'],
|
||||
'培训': ['training', 'education', 'learn', 'presentation', 'book'],
|
||||
'证书': ['certificate', 'award', 'badge', 'achievement', 'diploma'],
|
||||
'奖杯': ['trophy', 'award', 'win', 'prize', 'achievement'],
|
||||
'排名': ['ranking', 'trophy', 'chart', 'leaderboard', 'medal'],
|
||||
'目标': ['target', 'goal', 'aim', 'focus', 'bullseye'],
|
||||
'火箭': ['rocket', 'launch', 'startup', 'space', 'growth'],
|
||||
'灯泡创意': ['bulb', 'idea', 'innovation', 'light', 'creative'],
|
||||
'大脑': ['brain', 'ai', 'mind', 'thinking', 'intelligence'],
|
||||
'芯片': ['chip', 'cpu', 'processor', 'hardware', 'tech'],
|
||||
'电路': ['circuit', 'electronics', 'chip', 'board'],
|
||||
'代码': ['code', 'terminal', 'programming', 'developer', 'brackets'],
|
||||
'终端': ['terminal', 'console', 'command', 'shell', 'code'],
|
||||
'bug': ['bug', 'debug', 'error', 'issue', 'insect'],
|
||||
'测试': ['test', 'check', 'verify', 'flask', 'experiment'],
|
||||
'部署': ['deploy', 'rocket', 'server', 'upload', 'cloud'],
|
||||
'备份': ['backup', 'save', 'cloud', 'archive', 'storage'],
|
||||
'恢复': ['restore', 'refresh', 'rotate', 'backup'],
|
||||
'删除': ['trash', 'delete', 'remove', 'bin', 'garbage'],
|
||||
'编辑': ['edit', 'pencil', 'pen', 'write', 'modify'],
|
||||
'保存': ['save', 'disk', 'download', 'check'],
|
||||
'分享': ['share', 'send', 'social', 'link'],
|
||||
'链接': ['link', 'chain', 'url', 'connect'],
|
||||
'二维码扫描': ['qr', 'scan', 'code', 'camera'],
|
||||
'指纹': ['fingerprint', 'security', 'identity', 'biometric'],
|
||||
'人脸': ['face', 'user', 'avatar', 'profile', 'scan'],
|
||||
'盾牌': ['shield', 'security', 'protect', 'safe', 'defense'],
|
||||
'钥匙': ['key', 'lock', 'security', 'access', 'password'],
|
||||
'警报': ['alert', 'warning', 'alarm', 'danger', 'exclamation'],
|
||||
'禁止': ['ban', 'block', 'forbidden', 'stop', 'prohibited'],
|
||||
'检查': ['check', 'tick', 'done', 'success', 'verify'],
|
||||
'关闭': ['close', 'x', 'cancel', 'exit'],
|
||||
'菜单': ['menu', 'hamburger', 'list', 'bars'],
|
||||
'更多': ['more', 'dots', 'ellipsis', 'options'],
|
||||
'刷新': ['refresh', 'reload', 'rotate', 'sync', 'update'],
|
||||
'同步': ['sync', 'refresh', 'rotate', 'update', 'cloud'],
|
||||
'筛选': ['filter', 'funnel', 'sort', 'sliders'],
|
||||
'排序': ['sort', 'arrow', 'list', 'order'],
|
||||
'折叠': ['chevron', 'arrow', 'collapse', 'expand', 'down'],
|
||||
'展开': ['chevron', 'arrow', 'expand', 'down', 'up'],
|
||||
'全屏': ['fullscreen', 'expand', 'maximize', 'screen'],
|
||||
'静音': ['mute', 'volume', 'speaker', 'sound', 'off'],
|
||||
'音量': ['volume', 'speaker', 'sound', 'audio'],
|
||||
'播放': ['play', 'media', 'video', 'music', 'start'],
|
||||
'暂停': ['pause', 'media', 'stop', 'break'],
|
||||
'录音': ['record', 'mic', 'audio', 'voice'],
|
||||
'麦克风': ['mic', 'microphone', 'audio', 'record', 'voice'],
|
||||
'耳机': ['headphone', 'audio', 'music', 'listen'],
|
||||
'喇叭': ['speaker', 'volume', 'sound', 'audio', 'megaphone'],
|
||||
'广播': ['broadcast', 'signal', 'radio', 'live', 'antenna'],
|
||||
'卫星': ['satellite', 'space', 'signal', 'orbit'],
|
||||
'天线': ['antenna', 'signal', 'network', 'wireless'],
|
||||
'无线': ['wireless', 'wifi', 'signal', 'network'],
|
||||
'定位': ['location', 'pin', 'gps', 'map', 'place'],
|
||||
'地震': ['earthquake', 'activity', 'wave', 'pulse', 'seismic'],
|
||||
'温度': ['temperature', 'thermometer', 'weather', 'heat'],
|
||||
'湿度': ['humidity', 'water', 'weather', 'droplet'],
|
||||
'空气质量': ['air', 'wind', 'weather', 'quality'],
|
||||
'时钟': ['clock', 'time', 'watch', 'timer'],
|
||||
'日历事件': ['calendar', 'event', 'date', 'schedule'],
|
||||
'提醒': ['bell', 'reminder', 'notification', 'alarm'],
|
||||
'待办': ['todo', 'check', 'list', 'task', 'checkbox'],
|
||||
'清单': ['list', 'checklist', 'todo', 'tasks'],
|
||||
'看板': ['board', 'kanban', 'columns', 'layout', 'dashboard'],
|
||||
'仪表盘': ['dashboard', 'gauge', 'chart', 'speed', 'analytics'],
|
||||
'大屏': ['dashboard', 'monitor', 'screen', 'chart', 'display'],
|
||||
'报表导出': ['export', 'download', 'file', 'sheet', 'csv']
|
||||
};
|
||||
|
||||
function ensureDir(p) {
|
||||
fs.mkdirSync(p, { recursive: true });
|
||||
}
|
||||
|
||||
/* ---------- 中文别名匹配(词边界,避免 car→card 之类误命中) ---------- */
|
||||
const ROOT_RANK = new Map(); // 单词词根 -> [[中文词, 位次], ...]
|
||||
const MULTI_ROOTS = []; // 含连字符的词根(如 real-estate)
|
||||
|
||||
for (const [cn, roots] of Object.entries(CN_ALIAS)) {
|
||||
roots.forEach((r, rank) => {
|
||||
const k = r.toLowerCase();
|
||||
if (k.includes('-')) {
|
||||
MULTI_ROOTS.push([k, cn, rank]);
|
||||
} else {
|
||||
if (!ROOT_RANK.has(k)) ROOT_RANK.set(k, []);
|
||||
ROOT_RANK.get(k).push([cn, rank]);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 为图标名计算中文别名(按 -/_ 分词后精确匹配,多词词根用包含匹配)
|
||||
* @returns {Array<{cn:string, rank:number}>} rank = 词根在该中文词表中的位次(越小越相关)
|
||||
*/
|
||||
function aliasesFor(name) {
|
||||
const tokens = String(name || '').toLowerCase().split(/[-_\s]+/);
|
||||
const best = new Map(); // cn -> 最小 rank
|
||||
|
||||
const add = (cn, rank) => {
|
||||
const prev = best.get(cn);
|
||||
if (prev === undefined || rank < prev) best.set(cn, rank);
|
||||
};
|
||||
|
||||
for (const t of tokens) {
|
||||
const list = ROOT_RANK.get(t);
|
||||
if (list) for (const [cn, rank] of list) add(cn, rank);
|
||||
}
|
||||
if (MULTI_ROOTS.length) {
|
||||
const lower = String(name || '').toLowerCase();
|
||||
for (const [root, cn, rank] of MULTI_ROOTS) {
|
||||
if (lower.includes(root)) add(cn, rank);
|
||||
}
|
||||
}
|
||||
return [...best.entries()].map(([cn, rank]) => ({ cn, rank }));
|
||||
}
|
||||
|
||||
function readJSON(file) {
|
||||
return JSON.parse(fs.readFileSync(file, 'utf8'));
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析 `window['HGB_Source_x'] = {...};` 形式的源文件
|
||||
* 注意:不能用 eval/vm,大文件(99MB)会撑爆内存;这里直接截取 JSON 文本。
|
||||
*/
|
||||
function parseSourceFile(file) {
|
||||
const text = fs.readFileSync(file, 'utf8');
|
||||
const m = text.match(/window\[['"][^'"]+['"]\]\s*=\s*/);
|
||||
if (!m) throw new Error('无法识别赋值格式: ' + file);
|
||||
let json = text.slice(m.index + m[0].length).trim();
|
||||
if (json.endsWith(';')) json = json.slice(0, -1);
|
||||
return JSON.parse(json);
|
||||
}
|
||||
|
||||
/**
|
||||
* 把一个源的素材数组写成 jsonl + idx.json
|
||||
* @returns {{count:number, bytes:number}}
|
||||
*/
|
||||
function buildIndex(items, outBase) {
|
||||
const jsonlPath = outBase + '.jsonl';
|
||||
const fd = fs.openSync(jsonlPath, 'w');
|
||||
|
||||
const names = [];
|
||||
const catIdx = [];
|
||||
const typeIdx = [];
|
||||
const aliasIdx = [];
|
||||
const aliasRank = [];
|
||||
const offsets = [];
|
||||
const cats = [];
|
||||
const types = [];
|
||||
const aliases = [];
|
||||
const catMap = new Map();
|
||||
const typeMap = new Map();
|
||||
const aliasMap = new Map();
|
||||
|
||||
let offset = 0;
|
||||
for (const it of items) {
|
||||
const line = JSON.stringify(it) + '\n';
|
||||
const buf = Buffer.from(line, 'utf8');
|
||||
fs.writeSync(fd, buf);
|
||||
|
||||
names.push(String(it.name || it.id || '').toLowerCase());
|
||||
const cat = String(it.categoryCn || '');
|
||||
if (!catMap.has(cat)) { catMap.set(cat, cats.length); cats.push(cat); }
|
||||
catIdx.push(catMap.get(cat));
|
||||
const ty = String(it.type || '');
|
||||
if (!typeMap.has(ty)) { typeMap.set(ty, types.length); types.push(ty); }
|
||||
typeIdx.push(typeMap.get(ty));
|
||||
|
||||
// 中文语义别名(词边界匹配,rank 越小越相关)
|
||||
const list = aliasesFor(it.name || it.id);
|
||||
const codes = [];
|
||||
const ranks = [];
|
||||
for (const { cn, rank } of list) {
|
||||
if (!aliasMap.has(cn)) { aliasMap.set(cn, aliases.length); aliases.push(cn); }
|
||||
codes.push(aliasMap.get(cn));
|
||||
ranks.push(rank);
|
||||
}
|
||||
aliasIdx.push(codes);
|
||||
aliasRank.push(ranks);
|
||||
|
||||
offsets.push(offset, buf.length);
|
||||
offset += buf.length;
|
||||
}
|
||||
fs.closeSync(fd);
|
||||
|
||||
const idx = {
|
||||
count: items.length,
|
||||
n: names,
|
||||
c: catIdx,
|
||||
t: typeIdx,
|
||||
k: aliasIdx,
|
||||
r: aliasRank,
|
||||
kws: aliases,
|
||||
cats,
|
||||
types,
|
||||
o: offsets
|
||||
};
|
||||
fs.writeFileSync(outBase + '.idx.json', JSON.stringify(idx));
|
||||
return { count: items.length, bytes: offset };
|
||||
}
|
||||
|
||||
/** 进度输出(构建 224 个源时便于观察) */
|
||||
let done = 0;
|
||||
function tick(label, count, bytes) {
|
||||
done++;
|
||||
if (done % 20 === 0 || count > 20000) {
|
||||
process.stdout.write(` [${String(done).padStart(3)}] ${label} → ${count} 条 / ${(bytes / 1048576).toFixed(1)} MB\n`);
|
||||
}
|
||||
}
|
||||
|
||||
function buildIcons() {
|
||||
console.log('\n[1/3] 图标库');
|
||||
const manifest = readJSON(path.join(SITE_DATA, 'manifest', 'icons.json'));
|
||||
const sources = [];
|
||||
|
||||
for (const s of manifest.sources) {
|
||||
const file = path.join(SITE_DATA, s.file || ('sources/' + s.id + '.js'));
|
||||
if (!fs.existsSync(file)) {
|
||||
console.warn(' 跳过(文件缺失): ' + s.id);
|
||||
continue;
|
||||
}
|
||||
let data;
|
||||
try {
|
||||
data = parseSourceFile(file);
|
||||
} catch (e) {
|
||||
console.warn(' 跳过(解析失败): ' + s.id + ' — ' + e.message);
|
||||
continue;
|
||||
}
|
||||
const items = Array.isArray(data.icons) ? data.icons : [];
|
||||
if (!items.length) continue;
|
||||
|
||||
const r = buildIndex(items, path.join(OUT_ICONS, s.id));
|
||||
const commercial = !NON_COMMERCIAL_RE.test(String(s.license || ''));
|
||||
sources.push({
|
||||
id: s.id,
|
||||
name: s.name,
|
||||
nameCn: s.nameCn,
|
||||
desc: s.desc,
|
||||
style: s.style,
|
||||
type: s.type,
|
||||
license: s.license,
|
||||
licenseNote: s.licenseNote,
|
||||
commercial,
|
||||
home: s.home,
|
||||
github: s.github,
|
||||
npm: s.npm,
|
||||
count: r.count,
|
||||
index: 'icons/' + s.id + '.idx.json',
|
||||
data: 'icons/' + s.id + '.jsonl',
|
||||
workspaces: s.workspaces || []
|
||||
});
|
||||
tick(s.id, r.count, r.bytes);
|
||||
}
|
||||
|
||||
return {
|
||||
kind: 'icons',
|
||||
total: sources.reduce((a, b) => a + b.count, 0),
|
||||
sources
|
||||
};
|
||||
}
|
||||
|
||||
function buildPosters() {
|
||||
console.log('\n[2/3] 海报素材库');
|
||||
const manifest = readJSON(path.join(SITE_DATA, 'manifest', 'posters.json'));
|
||||
const sources = [];
|
||||
|
||||
for (const s of manifest.sources) {
|
||||
const file = path.join(SITE_DATA, s.file || ('posters/' + s.id + '.js'));
|
||||
if (!fs.existsSync(file)) {
|
||||
console.warn(' 跳过(文件缺失): ' + s.id);
|
||||
continue;
|
||||
}
|
||||
let data;
|
||||
try {
|
||||
data = parseSourceFile(file);
|
||||
} catch (e) {
|
||||
console.warn(' 跳过(解析失败): ' + s.id + ' — ' + e.message);
|
||||
continue;
|
||||
}
|
||||
const items = Array.isArray(data.items) ? data.items : [];
|
||||
if (!items.length) continue;
|
||||
|
||||
const r = buildIndex(items, path.join(OUT_POSTERS, s.id));
|
||||
const commercial = !NON_COMMERCIAL_RE.test(String(s.license || ''));
|
||||
sources.push({
|
||||
id: s.id,
|
||||
name: s.name,
|
||||
nameCn: s.nameCn,
|
||||
desc: s.desc,
|
||||
type: s.type,
|
||||
license: s.license,
|
||||
licenseNote: s.licenseNote,
|
||||
commercial,
|
||||
home: s.home,
|
||||
github: s.github,
|
||||
count: r.count,
|
||||
index: 'posters/' + s.id + '.idx.json',
|
||||
data: 'posters/' + s.id + '.jsonl',
|
||||
workspaces: s.workspaces || ['poster']
|
||||
});
|
||||
tick(s.id, r.count, r.bytes);
|
||||
}
|
||||
|
||||
return {
|
||||
kind: 'posters',
|
||||
total: sources.reduce((a, b) => a + b.count, 0),
|
||||
sources
|
||||
};
|
||||
}
|
||||
|
||||
function buildSkills() {
|
||||
console.log('\n[3/3] 技能库(元数据)');
|
||||
const manifest = readJSON(path.join(SITE_DATA, 'manifest', 'skills.json'));
|
||||
const out = {
|
||||
kind: 'skills',
|
||||
shared: { total: (manifest.shared && manifest.shared.total) || 0, skills: (manifest.shared && manifest.shared.skills) || [] },
|
||||
poster: { total: (manifest.poster && manifest.poster.total) || 0, skills: (manifest.poster && manifest.poster.skills) || [] },
|
||||
sticker: { total: (manifest.sticker && manifest.sticker.total) || 0, skills: (manifest.sticker && manifest.sticker.skills) || [] }
|
||||
};
|
||||
fs.writeFileSync(path.join(OUT, 'skills.json'), JSON.stringify(out));
|
||||
console.log(` 共享 ${out.shared.total} / 海报 ${out.poster.total} / 表情 ${out.sticker.total}`);
|
||||
return out;
|
||||
}
|
||||
|
||||
function main() {
|
||||
const t0 = Date.now();
|
||||
ensureDir(OUT);
|
||||
ensureDir(OUT_ICONS);
|
||||
ensureDir(OUT_POSTERS);
|
||||
|
||||
console.log('画个标素材 API · 索引构建');
|
||||
console.log(' 源目录: ' + SITE_DATA);
|
||||
console.log(' 输出至: ' + OUT);
|
||||
|
||||
const icons = buildIcons();
|
||||
const posters = buildPosters();
|
||||
const skills = buildSkills();
|
||||
|
||||
const catalog = {
|
||||
builtAt: new Date().toISOString(),
|
||||
icons: { total: icons.total, sources: icons.sources },
|
||||
posters: { total: posters.total, sources: posters.sources },
|
||||
skills: { shared: skills.shared.total, poster: skills.poster.total, sticker: skills.sticker.total }
|
||||
};
|
||||
fs.writeFileSync(path.join(OUT, 'sources.json'), JSON.stringify(catalog));
|
||||
|
||||
const size = dirSize(OUT);
|
||||
console.log('\n完成:');
|
||||
console.log(` 图标 ${icons.total} 个 / ${icons.sources.length} 源`);
|
||||
console.log(` 海报 ${posters.total} 个 / ${posters.sources.length} 源`);
|
||||
console.log(` 技能 ${skills.shared.total + skills.poster.total + skills.sticker.total} 个`);
|
||||
console.log(` 索引总体积 ${(size / 1048576).toFixed(1)} MB,耗时 ${((Date.now() - t0) / 1000).toFixed(1)}s`);
|
||||
}
|
||||
|
||||
function dirSize(dir) {
|
||||
let total = 0;
|
||||
for (const name of fs.readdirSync(dir, { withFileTypes: true })) {
|
||||
const p = path.join(dir, name.name);
|
||||
if (name.isDirectory()) total += dirSize(p);
|
||||
else total += fs.statSync(p).size;
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
main();
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"port": 7891,
|
||||
"host": "127.0.0.1",
|
||||
"dataDir": "./data",
|
||||
"keyFile": "./data/apikeys.json",
|
||||
"defaultRatePerMin": 60,
|
||||
"defaultDailyQuota": 20000,
|
||||
"maxLimit": 100,
|
||||
"corsOrigin": "*",
|
||||
"trustProxy": true
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
[Unit]
|
||||
Description=画个标素材 API
|
||||
After=network.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=ubuntu
|
||||
Group=ubuntu
|
||||
WorkingDirectory=/opt/drawlogo-api
|
||||
ExecStart=/usr/bin/node --max-old-space-size=384 server.js
|
||||
Restart=always
|
||||
RestartSec=5
|
||||
Environment=NODE_ENV=production
|
||||
# 限制内存,避免索引服务挤占同机其他项目
|
||||
MemoryMax=900M
|
||||
NoNewPrivileges=true
|
||||
PrivateTmp=true
|
||||
ProtectSystem=full
|
||||
ReadWritePaths=/opt/drawlogo-api
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
@@ -0,0 +1,13 @@
|
||||
# 画个标素材 API —— 追加到 /etc/nginx/sites-enabled/drawlogo-zhuig-com.conf 的 443 server 块内
|
||||
# 必须用 ^~:否则 /api/v1/icons/xxx.svg 会被下面的 \.svg$ 正则 location 截走 → 404
|
||||
location ^~ /api/ {
|
||||
proxy_pass http://127.0.0.1:7891;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_connect_timeout 10s;
|
||||
proxy_read_timeout 30s;
|
||||
proxy_send_timeout 15s;
|
||||
client_max_body_size 1m;
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
把 /api/ 反代片段插入 drawlogo 站点的 **443 server 块**(幂等,可重复执行)
|
||||
|
||||
注意:不能用「第一个 location /」做锚点——那是 80 端口块。
|
||||
这里改用 443 块独有的 access_log 行做锚点。
|
||||
"""
|
||||
import re
|
||||
import sys
|
||||
|
||||
CONF = '/etc/nginx/sites-enabled/drawlogo-zhuig-com.conf'
|
||||
SNIP = '/opt/drawlogo-api/deploy/nginx-location.conf'
|
||||
ANCHOR = ' access_log /var/log/nginx/drawlogo_zhuig_access.log;'
|
||||
|
||||
text = open(CONF, encoding='utf-8').read()
|
||||
|
||||
# 1) 清理历史上放错位置的 /api/ 块(兼容 location /api/ 与 location ^~ /api/)
|
||||
API_RE = re.compile(r'location\s+(?:\^~\s+)?/api/\s*\{')
|
||||
|
||||
while True:
|
||||
m = API_RE.search(text)
|
||||
if not m:
|
||||
break
|
||||
i = text.find('{', m.start())
|
||||
depth = 0
|
||||
end = -1
|
||||
for j in range(i, len(text)):
|
||||
if text[j] == '{':
|
||||
depth += 1
|
||||
elif text[j] == '}':
|
||||
depth -= 1
|
||||
if depth == 0:
|
||||
end = j + 1
|
||||
break
|
||||
if end < 0:
|
||||
print('ERROR: /api/ 块大括号不配对')
|
||||
sys.exit(1)
|
||||
text = text[:m.start()] + text[end:]
|
||||
|
||||
# 2) 插入到 443 块(锚点:该块独有的 access_log)
|
||||
if ANCHOR not in text:
|
||||
print('ERROR: 未找到 443 块的 access_log 锚点')
|
||||
sys.exit(1)
|
||||
|
||||
snippet = open(SNIP, encoding='utf-8').read().rstrip() + '\n'
|
||||
text = text.replace(ANCHOR, snippet + '\n' + ANCHOR, 1)
|
||||
|
||||
open(CONF, 'w', encoding='utf-8').write(text)
|
||||
print('patched')
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"name": "drawlogo-api",
|
||||
"version": "1.0.0",
|
||||
"private": true,
|
||||
"description": "画个标素材 API:图标/海报检索与 SVG 直链",
|
||||
"main": "server.js",
|
||||
"scripts": {
|
||||
"build": "node build-index.js",
|
||||
"start": "node server.js",
|
||||
"key:create": "node admin.js create",
|
||||
"key:list": "node admin.js list"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"dependencies": {}
|
||||
}
|
||||
+540
@@ -0,0 +1,540 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* 画个标 · 素材 API 服务
|
||||
*
|
||||
* 纯 Node 原生实现(零第三方依赖),对外提供素材检索 / SVG 直链 / 技能元数据。
|
||||
* 设计:
|
||||
* - 索引常驻内存,素材正文按字节偏移 seek 读取(不整体加载大源文件)
|
||||
* - API Key 鉴权(X-API-Key / Authorization: Bearer),Key 以 SHA-256 存储
|
||||
* - 每 Key 分钟级限流 + 每日配额
|
||||
* - 公网部署时由 nginx 反代,服务本身只监听 127.0.0.1
|
||||
*
|
||||
* 启动:node server.js
|
||||
*/
|
||||
'use strict';
|
||||
|
||||
const http = require('http');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const crypto = require('crypto');
|
||||
|
||||
const ROOT = __dirname;
|
||||
const DEFAULT_CONFIG = {
|
||||
port: 7891,
|
||||
host: '127.0.0.1',
|
||||
dataDir: './data',
|
||||
keyFile: './data/apikeys.json',
|
||||
defaultRatePerMin: 60,
|
||||
defaultDailyQuota: 20000,
|
||||
maxLimit: 100,
|
||||
corsOrigin: '*',
|
||||
trustProxy: true
|
||||
};
|
||||
|
||||
function loadConfig() {
|
||||
const file = path.join(ROOT, 'config.json');
|
||||
if (!fs.existsSync(file)) return { ...DEFAULT_CONFIG };
|
||||
return { ...DEFAULT_CONFIG, ...JSON.parse(fs.readFileSync(file, 'utf8')) };
|
||||
}
|
||||
|
||||
const CONFIG = loadConfig();
|
||||
const DATA_DIR = path.resolve(ROOT, CONFIG.dataDir);
|
||||
const KEY_FILE = path.resolve(ROOT, CONFIG.keyFile);
|
||||
|
||||
/* ============================ 索引加载 ============================ */
|
||||
|
||||
const store = {
|
||||
catalog: null,
|
||||
icons: [],
|
||||
posters: [],
|
||||
skills: null,
|
||||
byId: new Map() // source id -> source record
|
||||
};
|
||||
|
||||
function openIndex(kind, meta) {
|
||||
const idxPath = path.join(DATA_DIR, meta.index);
|
||||
const dataPath = path.join(DATA_DIR, meta.data);
|
||||
if (!fs.existsSync(idxPath) || !fs.existsSync(dataPath)) {
|
||||
throw new Error(`索引缺失: ${kind}/${meta.id}(请先执行 node build-index.js)`);
|
||||
}
|
||||
const idx = JSON.parse(fs.readFileSync(idxPath, 'utf8'));
|
||||
const fd = fs.openSync(dataPath, 'r');
|
||||
return { ...meta, kind, idx, fd };
|
||||
}
|
||||
|
||||
function loadStore() {
|
||||
const catalogPath = path.join(DATA_DIR, 'sources.json');
|
||||
if (!fs.existsSync(catalogPath)) {
|
||||
throw new Error('未找到 data/sources.json,请先执行 node build-index.js');
|
||||
}
|
||||
store.catalog = JSON.parse(fs.readFileSync(catalogPath, 'utf8'));
|
||||
store.icons = store.catalog.icons.sources.map(s => openIndex('icons', s));
|
||||
store.posters = store.catalog.posters.sources.map(s => openIndex('posters', s));
|
||||
for (const s of store.icons) store.byId.set('icons/' + s.id, s);
|
||||
for (const s of store.posters) store.byId.set('posters/' + s.id, s);
|
||||
|
||||
const skillsPath = path.join(DATA_DIR, 'skills.json');
|
||||
store.skills = fs.existsSync(skillsPath) ? JSON.parse(fs.readFileSync(skillsPath, 'utf8')) : null;
|
||||
|
||||
const mem = process.memoryUsage();
|
||||
console.log(`[索引] 图标 ${store.icons.length} 源 / ${store.catalog.icons.total} 个`);
|
||||
console.log(`[索引] 海报 ${store.posters.length} 源 / ${store.catalog.posters.total} 个`);
|
||||
console.log(`[索引] RSS ${(mem.rss / 1048576).toFixed(0)} MB`);
|
||||
}
|
||||
|
||||
/** 按字节偏移读取单条素材 */
|
||||
function readItem(src, i) {
|
||||
const off = src.idx.o[i * 2];
|
||||
const len = src.idx.o[i * 2 + 1];
|
||||
if (typeof off !== 'number' || typeof len !== 'number') return null;
|
||||
const buf = Buffer.allocUnsafe(len);
|
||||
fs.readSync(src.fd, buf, 0, len, off);
|
||||
try { return JSON.parse(buf.toString('utf8')); } catch (e) { return null; }
|
||||
}
|
||||
|
||||
/* ============================ API Key ============================ */
|
||||
|
||||
const keyState = {
|
||||
keys: [],
|
||||
mtime: 0,
|
||||
buckets: new Map() // keyId -> { window, count, day, dayCount }
|
||||
};
|
||||
|
||||
function sha256(s) {
|
||||
return crypto.createHash('sha256').update(String(s)).digest('hex');
|
||||
}
|
||||
|
||||
function safeEqual(a, b) {
|
||||
const ba = Buffer.from(String(a));
|
||||
const bb = Buffer.from(String(b));
|
||||
if (ba.length !== bb.length) return false;
|
||||
return crypto.timingSafeEqual(ba, bb);
|
||||
}
|
||||
|
||||
function loadKeys(force) {
|
||||
if (!fs.existsSync(KEY_FILE)) {
|
||||
if (force) keyState.keys = [];
|
||||
return;
|
||||
}
|
||||
const stat = fs.statSync(KEY_FILE);
|
||||
if (!force && stat.mtimeMs === keyState.mtime) return;
|
||||
try {
|
||||
const list = JSON.parse(fs.readFileSync(KEY_FILE, 'utf8'));
|
||||
keyState.keys = Array.isArray(list) ? list : [];
|
||||
keyState.mtime = stat.mtimeMs;
|
||||
} catch (e) {
|
||||
console.error('[Key] 解析失败:' + e.message);
|
||||
}
|
||||
}
|
||||
|
||||
function today() {
|
||||
const d = new Date();
|
||||
return d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') + '-' + String(d.getDate()).padStart(2, '0');
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验 Key,并做分钟限流 + 日配额
|
||||
* @returns {{ok:true, key:object, remaining:number}|{ok:false, status:number, code:string, message:string}}
|
||||
*/
|
||||
function authenticate(req) {
|
||||
const raw = req.headers['x-api-key'] || String(req.headers.authorization || '').replace(/^Bearer\s+/i, '');
|
||||
if (!raw) {
|
||||
return { ok: false, status: 401, code: 'UNAUTHORIZED', message: '缺少 API Key(请求头 X-API-Key 或 Authorization: Bearer <key>)' };
|
||||
}
|
||||
loadKeys(false);
|
||||
const hash = sha256(raw.trim());
|
||||
const rec = keyState.keys.find(k => k.enabled !== false && k.hash && safeEqual(k.hash, hash));
|
||||
if (!rec) {
|
||||
return { ok: false, status: 403, code: 'INVALID_KEY', message: 'API Key 无效或已禁用' };
|
||||
}
|
||||
|
||||
const now = Date.now();
|
||||
const day = today();
|
||||
let b = keyState.buckets.get(rec.id);
|
||||
if (!b) { b = { window: now, count: 0, day, dayCount: 0 }; keyState.buckets.set(rec.id, b); }
|
||||
if (now - b.window >= 60000) { b.window = now; b.count = 0; }
|
||||
if (b.day !== day) { b.day = day; b.dayCount = 0; }
|
||||
|
||||
const rate = Number(rec.ratePerMin || CONFIG.defaultRatePerMin);
|
||||
const quota = Number(rec.dailyQuota || CONFIG.defaultDailyQuota);
|
||||
|
||||
b.count += 1;
|
||||
b.dayCount += 1;
|
||||
rec.lastUsedAt = new Date().toISOString();
|
||||
|
||||
if (b.dayCount > quota) {
|
||||
return { ok: false, status: 429, code: 'DAILY_QUOTA_EXCEEDED', message: `超出每日配额(${quota} 次)` };
|
||||
}
|
||||
if (b.count > rate) {
|
||||
return { ok: false, status: 429, code: 'RATE_LIMITED', message: `请求过于频繁(${rate} 次/分钟)`, retryAfter: 60 };
|
||||
}
|
||||
return { ok: true, key: rec, remaining: Math.max(0, rate - b.count), limit: rate };
|
||||
}
|
||||
|
||||
/* ============================ 检索 ============================ */
|
||||
|
||||
function parseLimit(v) {
|
||||
const n = parseInt(v, 10);
|
||||
if (!Number.isFinite(n) || n <= 0) return 20;
|
||||
return Math.min(n, CONFIG.maxLimit);
|
||||
}
|
||||
|
||||
function parseOffset(v) {
|
||||
const n = parseInt(v, 10);
|
||||
return Number.isFinite(n) && n > 0 ? n : 0;
|
||||
}
|
||||
|
||||
const SAFE_ID = /^[A-Za-z0-9._-]+$/;
|
||||
|
||||
/** 负面变体(-off / -alert / -error …),搜索默认排除 */
|
||||
const NEGATIVE_RE = /-(off|alert|error|forbidden|ban|block|close|cancel|delete|remove|slash|times|prohibited)$/;
|
||||
|
||||
const MAX_CANDIDATES = 5000;
|
||||
|
||||
/** 主流通用图标库优先(同分时排序用,越小越优先) */
|
||||
const SOURCE_RANK = {
|
||||
lucide: 0, tabler: 1, heroicons: 2, feather: 3, phosphor: 4, remix: 5,
|
||||
'material-symbols': 6, 'material-symbols-light': 7, ionicons: 8, mdi: 9,
|
||||
bootstrap: 10, fontawesome: 11, 'simple-icons': 12, fluent: 13, 'fluent-emoji': 14
|
||||
};
|
||||
function sourceRank(id) {
|
||||
return SOURCE_RANK[id] !== undefined ? SOURCE_RANK[id] : 50;
|
||||
}
|
||||
|
||||
/**
|
||||
* 在指定集合中搜索(支持英文名 / 中文分类 / 中文语义别名)
|
||||
* @param {Array} sources 源记录
|
||||
* @param {object} opts { q, source, type, commercial, limit, offset, dedupe, includeNegative }
|
||||
*/
|
||||
function search(sources, opts) {
|
||||
const q = String(opts.q || '').trim().toLowerCase();
|
||||
const limit = parseLimit(opts.limit);
|
||||
const offset = parseOffset(opts.offset);
|
||||
const dedupe = opts.dedupe === true;
|
||||
const includeNegative = opts.includeNegative === true;
|
||||
|
||||
const hits = [];
|
||||
const seen = new Set();
|
||||
let total = 0;
|
||||
|
||||
for (const src of sources) {
|
||||
if (opts.source && src.id !== opts.source) continue;
|
||||
if (opts.commercial === true && !src.commercial) continue;
|
||||
const { n, c, t, k, kws, cats, types } = src.idx;
|
||||
|
||||
for (let i = 0; i < n.length; i++) {
|
||||
if (opts.type && types[t[i]] !== opts.type) continue;
|
||||
if (!includeNegative && NEGATIVE_RE.test(n[i])) continue;
|
||||
|
||||
let score = 0;
|
||||
let aliasRank = 99;
|
||||
if (q) {
|
||||
const name = n[i];
|
||||
if (name === q) score = 0;
|
||||
else if (name.startsWith(q)) score = 1;
|
||||
else if (name.indexOf(q) !== -1) score = 2;
|
||||
else {
|
||||
// 中文语义别名:精确匹配优先于分类,分类优先于别名包含
|
||||
const codes = k[i] || [];
|
||||
const ranks = (src.idx.r && src.idx.r[i]) || [];
|
||||
let exact = false;
|
||||
let partial = false;
|
||||
for (let j = 0; j < codes.length; j++) {
|
||||
const kw = kws[codes[j]] || '';
|
||||
if (kw === q) {
|
||||
exact = true;
|
||||
aliasRank = Math.min(aliasRank, ranks[j] === undefined ? 99 : ranks[j]);
|
||||
} else if (kw.indexOf(q) !== -1) {
|
||||
partial = true;
|
||||
aliasRank = Math.min(aliasRank, ranks[j] === undefined ? 99 : ranks[j]);
|
||||
}
|
||||
}
|
||||
if (exact) score = 3;
|
||||
else if ((cats[c[i]] || '').toLowerCase().indexOf(q) !== -1) score = 4;
|
||||
else if (partial) score = 5;
|
||||
else continue;
|
||||
}
|
||||
}
|
||||
|
||||
if (dedupe) {
|
||||
if (seen.has(n[i])) continue;
|
||||
seen.add(n[i]);
|
||||
}
|
||||
total++;
|
||||
if (hits.length < MAX_CANDIDATES) {
|
||||
hits.push({
|
||||
_sort: score * 100000 + aliasRank * 500 + sourceRank(src.id) * 10 + Math.min(n[i].length, 60),
|
||||
id: n[i],
|
||||
name: n[i],
|
||||
categoryCn: cats[c[i]] || '',
|
||||
type: types[t[i]] || '',
|
||||
source: src.id,
|
||||
sourceNameCn: src.nameCn || src.name || src.id,
|
||||
license: src.license,
|
||||
commercial: src.commercial,
|
||||
index: i
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
hits.sort((a, b) => a._sort - b._sort);
|
||||
const page = hits.slice(offset, offset + limit).map(({ _sort, ...rest }) => rest);
|
||||
return { total, items: page, limit, offset };
|
||||
}
|
||||
|
||||
function findByName(src, name) {
|
||||
const target = String(name || '').toLowerCase();
|
||||
const n = src.idx.n;
|
||||
for (let i = 0; i < n.length; i++) {
|
||||
if (n[i] === target) return i;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
function pickRandom(sources, opts) {
|
||||
const count = Math.min(parseLimit(opts.count || 10), 50);
|
||||
const pool = sources.filter(s => !opts.source || s.id === opts.source);
|
||||
if (!pool.length) return [];
|
||||
const out = [];
|
||||
for (let k = 0; k < count; k++) {
|
||||
const src = pool[Math.floor(Math.random() * pool.length)];
|
||||
const i = Math.floor(Math.random() * src.idx.count);
|
||||
const item = readItem(src, i);
|
||||
if (item) out.push({ ...item, source: src.id, sourceNameCn: src.nameCn || src.id, license: src.license });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** 构造可直接嵌入的 SVG */
|
||||
function toSvg(item) {
|
||||
const body = String(item.svg || '');
|
||||
if (!body) return null;
|
||||
const multiColor = item.type === 'emoji' || item.type === 'brand';
|
||||
const fill = multiColor ? '' : ' fill="currentColor"';
|
||||
return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"${fill}>${body}</svg>`;
|
||||
}
|
||||
|
||||
/* ============================ HTTP ============================ */
|
||||
|
||||
function send(res, status, body, headers) {
|
||||
const h = {
|
||||
'Content-Type': 'application/json; charset=utf-8',
|
||||
'Access-Control-Allow-Origin': CONFIG.corsOrigin,
|
||||
'Access-Control-Allow-Headers': 'Content-Type, X-API-Key, Authorization',
|
||||
'Access-Control-Allow-Methods': 'GET, OPTIONS',
|
||||
'X-Content-Type-Options': 'nosniff',
|
||||
...(headers || {})
|
||||
};
|
||||
const payload = typeof body === 'string' ? body : JSON.stringify(body);
|
||||
res.writeHead(status, h);
|
||||
res.end(payload);
|
||||
}
|
||||
|
||||
function ok(res, data, meta, extraHeaders) {
|
||||
send(res, 200, { ok: true, data, ...(meta ? { meta } : {}) }, extraHeaders);
|
||||
}
|
||||
|
||||
function fail(res, status, code, message, extraHeaders) {
|
||||
send(res, status, { ok: false, error: { code, message } }, extraHeaders);
|
||||
}
|
||||
|
||||
const PUBLIC_PATHS = new Set(['/api/v1/health', '/api/v1/stats', '/api/v1/sources']);
|
||||
|
||||
function handle(req, res) {
|
||||
const t0 = Date.now();
|
||||
const u = new URL(req.url, 'http://localhost');
|
||||
const pathname = decodeURIComponent(u.pathname);
|
||||
const q = u.searchParams;
|
||||
|
||||
if (req.method === 'OPTIONS') {
|
||||
return send(res, 204, '');
|
||||
}
|
||||
if (req.method !== 'GET') {
|
||||
return fail(res, 405, 'METHOD_NOT_ALLOWED', '仅支持 GET');
|
||||
}
|
||||
|
||||
// 鉴权(公开端点除外)
|
||||
let authInfo = null;
|
||||
if (!PUBLIC_PATHS.has(pathname)) {
|
||||
const a = authenticate(req);
|
||||
if (!a.ok) {
|
||||
const headers = a.retryAfter ? { 'Retry-After': String(a.retryAfter) } : undefined;
|
||||
return fail(res, a.status, a.code, a.message, headers);
|
||||
}
|
||||
authInfo = a;
|
||||
}
|
||||
const rateHeaders = authInfo
|
||||
? { 'X-RateLimit-Limit': String(authInfo.limit), 'X-RateLimit-Remaining': String(authInfo.remaining) }
|
||||
: undefined;
|
||||
|
||||
/* ---------- 基础 ---------- */
|
||||
if (pathname === '/api/v1/health') {
|
||||
return ok(res, { status: 'up', version: '1.0.0', builtAt: store.catalog.builtAt, uptime: Math.round(process.uptime()) });
|
||||
}
|
||||
|
||||
if (pathname === '/api/v1/stats') {
|
||||
const mem = process.memoryUsage();
|
||||
return ok(res, {
|
||||
builtAt: store.catalog.builtAt,
|
||||
icons: { total: store.catalog.icons.total, sources: store.icons.length },
|
||||
posters: { total: store.catalog.posters.total, sources: store.posters.length },
|
||||
skills: store.skills
|
||||
? { shared: store.skills.shared.total, poster: store.skills.poster.total, sticker: store.skills.sticker.total }
|
||||
: null,
|
||||
runtime: { rssMB: Math.round(mem.rss / 1048576), uptime: Math.round(process.uptime()) }
|
||||
});
|
||||
}
|
||||
|
||||
if (pathname === '/api/v1/sources') {
|
||||
const kind = q.get('kind');
|
||||
const pick = s => ({
|
||||
id: s.id, name: s.name, nameCn: s.nameCn, desc: s.desc, style: s.style, type: s.type,
|
||||
license: s.license, licenseNote: s.licenseNote, commercial: s.commercial,
|
||||
count: s.count, workspaces: s.workspaces
|
||||
});
|
||||
const data = {};
|
||||
if (!kind || kind === 'icons') data.icons = store.icons.map(pick);
|
||||
if (!kind || kind === 'posters') data.posters = store.posters.map(pick);
|
||||
return ok(res, data);
|
||||
}
|
||||
|
||||
/* ---------- 图标 ---------- */
|
||||
if (pathname === '/api/v1/icons/search') {
|
||||
const r = search(store.icons, {
|
||||
q: q.get('q'), source: q.get('source'), type: q.get('type'),
|
||||
commercial: q.get('commercial') === '1', limit: q.get('limit'), offset: q.get('offset'),
|
||||
dedupe: q.get('dedupe') === '1', includeNegative: q.get('include_negative') === '1'
|
||||
});
|
||||
return ok(res, r.items, { total: r.total, limit: r.limit, offset: r.offset }, rateHeaders);
|
||||
}
|
||||
|
||||
if (pathname === '/api/v1/icons/random') {
|
||||
const items = pickRandom(store.icons, { count: q.get('count'), source: q.get('source') });
|
||||
return ok(res, items, { count: items.length }, rateHeaders);
|
||||
}
|
||||
|
||||
const iconMatch = pathname.match(/^\/api\/v1\/icons\/([^/]+)\/(.+?)(\.svg|\.json)?$/);
|
||||
if (iconMatch) {
|
||||
const [, sourceId, rawName, ext] = iconMatch;
|
||||
if (!SAFE_ID.test(sourceId)) return fail(res, 400, 'BAD_REQUEST', 'source 参数非法');
|
||||
const src = store.byId.get('icons/' + sourceId);
|
||||
if (!src) return fail(res, 404, 'NOT_FOUND', `图标源不存在: ${sourceId}`);
|
||||
|
||||
const name = rawName.replace(/\.(svg|json)$/i, '');
|
||||
const i = findByName(src, name);
|
||||
if (i < 0) return fail(res, 404, 'NOT_FOUND', `图标不存在: ${sourceId}/${name}`);
|
||||
const item = readItem(src, i);
|
||||
if (!item) return fail(res, 500, 'INTERNAL', '读取素材失败');
|
||||
|
||||
if (ext === '.svg') {
|
||||
const svg = toSvg(item);
|
||||
if (!svg) return fail(res, 404, 'NOT_FOUND', '该素材无 SVG 内容');
|
||||
res.writeHead(200, {
|
||||
'Content-Type': 'image/svg+xml; charset=utf-8',
|
||||
'Cache-Control': 'public, max-age=86400',
|
||||
'Access-Control-Allow-Origin': CONFIG.corsOrigin,
|
||||
'X-Content-Type-Options': 'nosniff'
|
||||
});
|
||||
return res.end(svg);
|
||||
}
|
||||
|
||||
return ok(res, { ...item, source: sourceId, sourceNameCn: src.nameCn || sourceId, license: src.license, commercial: src.commercial }, null, rateHeaders);
|
||||
}
|
||||
|
||||
/* ---------- 海报 ---------- */
|
||||
if (pathname === '/api/v1/posters/search') {
|
||||
const r = search(store.posters, {
|
||||
q: q.get('q'), source: q.get('source'), type: q.get('type'),
|
||||
commercial: q.get('commercial') === '1', limit: q.get('limit'), offset: q.get('offset'),
|
||||
dedupe: q.get('dedupe') === '1', includeNegative: q.get('include_negative') === '1'
|
||||
});
|
||||
return ok(res, r.items, { total: r.total, limit: r.limit, offset: r.offset }, rateHeaders);
|
||||
}
|
||||
|
||||
const posterMatch = pathname.match(/^\/api\/v1\/posters\/([^/]+)\/(.+)$/);
|
||||
if (posterMatch) {
|
||||
const [, sourceId, rawName] = posterMatch;
|
||||
if (!SAFE_ID.test(sourceId)) return fail(res, 400, 'BAD_REQUEST', 'source 参数非法');
|
||||
const src = store.byId.get('posters/' + sourceId);
|
||||
if (!src) return fail(res, 404, 'NOT_FOUND', `海报源不存在: ${sourceId}`);
|
||||
const i = findByName(src, rawName);
|
||||
if (i < 0) return fail(res, 404, 'NOT_FOUND', `素材不存在: ${sourceId}/${rawName}`);
|
||||
const item = readItem(src, i);
|
||||
if (!item) return fail(res, 500, 'INTERNAL', '读取素材失败');
|
||||
return ok(res, { ...item, source: sourceId, sourceNameCn: src.nameCn || sourceId, license: src.license, commercial: src.commercial }, null, rateHeaders);
|
||||
}
|
||||
|
||||
/* ---------- 技能(元数据) ---------- */
|
||||
if (pathname === '/api/v1/skills') {
|
||||
if (!store.skills) return fail(res, 503, 'NOT_READY', '技能索引未构建');
|
||||
const workspace = q.get('workspace');
|
||||
const step = q.get('step');
|
||||
const category = q.get('category');
|
||||
let list = [];
|
||||
for (const [lib, obj] of Object.entries(store.skills)) {
|
||||
if (lib === 'kind') continue;
|
||||
for (const s of (obj.skills || [])) list.push({ ...s, library: lib });
|
||||
}
|
||||
if (workspace) list = list.filter(s => !s.workspaces || s.workspaces.includes(workspace));
|
||||
if (step) list = list.filter(s => String(s.step) === String(step));
|
||||
if (category) list = list.filter(s => s.category === category);
|
||||
const limit = parseLimit(q.get('limit'));
|
||||
const offset = parseOffset(q.get('offset'));
|
||||
return ok(res, list.slice(offset, offset + limit), { total: list.length, limit, offset }, rateHeaders);
|
||||
}
|
||||
|
||||
const skillMatch = pathname.match(/^\/api\/v1\/skills\/([A-Za-z0-9._-]+)$/);
|
||||
if (skillMatch) {
|
||||
if (!store.skills) return fail(res, 503, 'NOT_READY', '技能索引未构建');
|
||||
const id = skillMatch[1];
|
||||
for (const [lib, obj] of Object.entries(store.skills)) {
|
||||
if (lib === 'kind') continue;
|
||||
const hit = (obj.skills || []).find(s => s.id === id);
|
||||
if (hit) return ok(res, { ...hit, library: lib }, null, rateHeaders);
|
||||
}
|
||||
return fail(res, 404, 'NOT_FOUND', `技能不存在: ${id}`);
|
||||
}
|
||||
|
||||
return fail(res, 404, 'NOT_FOUND', `未知端点: ${pathname}`);
|
||||
}
|
||||
|
||||
/* ============================ 启动 ============================ */
|
||||
|
||||
function main() {
|
||||
loadStore();
|
||||
loadKeys(true);
|
||||
// Key 文件热加载(改 Key 无需重启)
|
||||
setInterval(() => loadKeys(false), 5000).unref();
|
||||
|
||||
const server = http.createServer((req, res) => {
|
||||
const t0 = Date.now();
|
||||
try {
|
||||
handle(req, res);
|
||||
} catch (e) {
|
||||
console.error('[ERROR]', e);
|
||||
if (!res.headersSent) fail(res, 500, 'INTERNAL', '服务内部错误');
|
||||
}
|
||||
const cost = Date.now() - t0;
|
||||
if (cost > 300) console.warn(`[SLOW] ${req.method} ${req.url} ${cost}ms`);
|
||||
});
|
||||
|
||||
server.listen(CONFIG.port, CONFIG.host, () => {
|
||||
console.log(`[启动] http://${CONFIG.host}:${CONFIG.port} (Key: ${keyState.keys.length} 把)`);
|
||||
});
|
||||
|
||||
const shutdown = () => {
|
||||
console.log('[退出] 关闭中…');
|
||||
server.close(() => {
|
||||
for (const s of store.icons.concat(store.posters)) {
|
||||
try { fs.closeSync(s.fd); } catch (e) { /* ignore */ }
|
||||
}
|
||||
process.exit(0);
|
||||
});
|
||||
setTimeout(() => process.exit(0), 3000).unref();
|
||||
};
|
||||
process.on('SIGTERM', shutdown);
|
||||
process.on('SIGINT', shutdown);
|
||||
}
|
||||
|
||||
main();
|
||||
@@ -0,0 +1,7 @@
|
||||
#!/bin/bash
|
||||
# 画个标自动部署脚本(由 Gitea webhook 触发或手动执行)
|
||||
set -e
|
||||
cd /opt/drawlogo
|
||||
git fetch origin main && git reset --hard origin/main
|
||||
echo "$(date '+%Y-%m-%d %H:%M:%S') DEPLOY ok $(git log -1 --format='%h %s')" >> /opt/drawlogo/.deploy.log
|
||||
echo "部署完成: $(git log -1 --format='%h %s')"
|
||||
@@ -0,0 +1,13 @@
|
||||
[Unit]
|
||||
Description=画个标 Gitea Webhook 自动部署
|
||||
After=network.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=ubuntu
|
||||
ExecStart=/usr/bin/python3 /opt/drawlogo/deploy/drawlogo-webhook.py
|
||||
Restart=always
|
||||
RestartSec=5
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
@@ -0,0 +1,30 @@
|
||||
#!/usr/bin/env python3
|
||||
"""画个标 Gitea webhook 监听(push main 时自动部署)"""
|
||||
import http.server, subprocess, json, os, datetime
|
||||
|
||||
DEPLOY_SCRIPT = '/opt/drawlogo/deploy/deploy.sh'
|
||||
|
||||
class Handler(http.server.BaseHTTPRequestHandler):
|
||||
def do_POST(self):
|
||||
length = int(self.headers.get('Content-Length', 0))
|
||||
body = self.rfile.read(length)
|
||||
try:
|
||||
data = json.loads(body) if body else {}
|
||||
ref = data.get('ref', '')
|
||||
if ref == 'refs/heads/main':
|
||||
subprocess.Popen(
|
||||
['/bin/bash', DEPLOY_SCRIPT],
|
||||
stdout=open('/opt/drawlogo/.deploy.log', 'a'),
|
||||
stderr=subprocess.STDOUT
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
self.send_response(200)
|
||||
self.end_headers()
|
||||
self.wfile.write(b'ok')
|
||||
|
||||
def log_message(self, format, *args):
|
||||
pass
|
||||
|
||||
if __name__ == '__main__':
|
||||
http.server.HTTPServer(('0.0.0.0', 7890), Handler).serve_forever()
|
||||
@@ -0,0 +1,54 @@
|
||||
# 画个标 - drawlogo.zhuig.com(纯静态站,无后端)
|
||||
server {
|
||||
listen 80;
|
||||
listen [::]:80;
|
||||
server_name drawlogo.zhuig.com;
|
||||
|
||||
# certbot ACME 验证
|
||||
location /.well-known/acme-challenge/ {
|
||||
root /var/www/certbot;
|
||||
}
|
||||
|
||||
location / {
|
||||
return 301 https://$host$request_uri;
|
||||
}
|
||||
}
|
||||
|
||||
server {
|
||||
listen 443 ssl;
|
||||
listen [::]:443 ssl;
|
||||
server_name drawlogo.zhuig.com;
|
||||
|
||||
ssl_certificate /etc/letsencrypt/live/drawlogo.zhuig.com/fullchain.pem;
|
||||
ssl_certificate_key /etc/letsencrypt/live/drawlogo.zhuig.com/privkey.pem;
|
||||
include /etc/letsencrypt/options-ssl-nginx.conf;
|
||||
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;
|
||||
|
||||
# 安全响应头
|
||||
add_header X-Frame-Options "SAMEORIGIN" always;
|
||||
add_header X-Content-Type-Options "nosniff" always;
|
||||
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
|
||||
add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; connect-src 'self' https://api.deepseek.com; img-src 'self' data: blob:;" always;
|
||||
|
||||
root /opt/drawlogo;
|
||||
index index.html;
|
||||
|
||||
# 静态资源长期缓存(带 ?v= 版本号的 JS/CSS)
|
||||
location ~* \.(js|css|woff2|ttf|svg|png|jpg|jpeg|gif|ico)$ {
|
||||
expires 30d;
|
||||
add_header Cache-Control "public, immutable";
|
||||
}
|
||||
|
||||
# HTML 不缓存(保证入口页及时更新)
|
||||
location ~* \.html$ {
|
||||
add_header Cache-Control "no-cache, no-store, must-revalidate";
|
||||
}
|
||||
|
||||
# 默认首页
|
||||
location / {
|
||||
try_files $uri $uri/ $uri/index.html =404;
|
||||
}
|
||||
|
||||
access_log /var/log/nginx/drawlogo_zhuig_access.log;
|
||||
error_log /var/log/nginx/drawlogo_zhuig_error.log;
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
[Unit]
|
||||
Description=画个标 Gitea Webhook 自动部署
|
||||
After=network.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
User=ubuntu
|
||||
ExecStart=/usr/bin/python3 -c "
|
||||
import http.server, subprocess, json
|
||||
class H(http.server.BaseHTTPRequestHandler):
|
||||
def do_POST(self):
|
||||
length = int(self.headers.get('Content-Length', 0))
|
||||
body = self.rfile.read(length)
|
||||
try:
|
||||
data = json.loads(body) if body else {}
|
||||
ref = data.get('ref', '')
|
||||
if ref == 'refs/heads/main':
|
||||
subprocess.Popen(['/bin/bash', '/opt/drawlogo/deploy/deploy.sh'],
|
||||
stdout=open('/opt/drawlogo/.deploy.log', 'a'),
|
||||
stderr=subprocess.STDOUT)
|
||||
except Exception as e:
|
||||
pass
|
||||
self.send_response(200)
|
||||
self.end_headers()
|
||||
self.wfile.write(b'ok')
|
||||
def log_message(self, format, *args):
|
||||
pass
|
||||
http.server.HTTPServer(('127.0.0.1', 7890), H).serve_forever()
|
||||
"
|
||||
Restart=always
|
||||
RestartSec=5
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
Reference in New Issue
Block a user