feat: 管理后台可配置首页推荐 — reco.json存储+公开/reco接口+admin增删改排序启停, 首页近期新功能动态拉取(失败回退静态清单)

This commit is contained in:
personal82555 committed 2026-10-13 11:34:59 +08:00
1 parent f0ac658887
commit 17c71d4259
3 files changed
+269 -4

No files matched your search

+69
View File
@@ -394,6 +394,44 @@ def _save_sites(sites: list) -> None:
os.replace(tmp, path)
def _reco_file() -> str:
return os.path.join(DATA_DIR, "reco.json")
# 首页推荐种子:新工具上线时的默认展示(管理后台可增删改)
DEFAULT_RECO = [
{"path": "/ai-image-lab", "icon": "🪄", "name": "AI 图片实验室", "desc": "智能抠图去背景、AI 无损放大变清晰、一键证件照", "enabled": True},
{"path": "/ai-chat", "icon": "🤖", "name": "AI 问答", "desc": "报错解读、文案写作、代码问题随口问,支持多轮对话", "enabled": True},
{"path": "/copywriting", "icon": "✍️", "name": "文案工具箱", "desc": "一键改写、降 AIGC 率、爆款标题、小红书/朋友圈文案", "enabled": True},
{"path": "/video-tools", "icon": "🎥", "name": "视频工具箱", "desc": "转码/压缩/水印/去水印/GIF + AI 字幕一条龙", "enabled": True},
{"path": "/seal-maker", "icon": "🔴", "name": "印章生成器", "desc": "公章一键生成,盖章到图片/PDF,三栏专业编辑器", "enabled": True},
{"path": "/signature-pad", "icon": "✍️", "name": "手写签名", "desc": "真实笔触模拟,透明 PNG,签合同一步到位", "enabled": True},
{"path": "/zh-convert", "icon": "🈶", "name": "简繁体转换", "desc": "OpenCC 词典,词组级准确互转", "enabled": True},
{"path": "/pinyin-converter", "icon": "🀄", "name": "汉字转拼音", "desc": "多音字智能转换,全读音标注", "enabled": True},
{"path": "/user-center", "icon": "👤", "name": "用户中心", "desc": "收藏/记录云端同步,换电脑登录即恢复", "enabled": True},
]
def _load_reco() -> list:
try:
with open(_reco_file(), "r", encoding="utf-8") as fh:
data = json.load(fh)
if isinstance(data, list) and data:
return data
except Exception: # noqa: BLE001
pass
return [dict(x) for x in DEFAULT_RECO]
def _save_reco(items: list) -> None:
path = _reco_file()
os.makedirs(os.path.dirname(path), exist_ok=True)
tmp = path + ".tmp"
with open(tmp, "w", encoding="utf-8") as fh:
json.dump(items, fh, ensure_ascii=False, indent=2)
os.replace(tmp, path)
def sites_api(method: str, path: str, payload: dict) -> tuple[int, dict]:
"""Shared bookmarks CRUD. path is after /sites."""
if method == "GET" and path == "":
@@ -1082,6 +1120,27 @@ def admin_api(method: str, sub: str, payload: dict, handler):
shutil.rmtree(udir, ignore_errors=True)
return 200, {"code": 200, "message": "ok"}
if method == "GET" and sub == "/reco":
return 200, {"code": 200, "message": "ok", "data": _load_reco()}
if method == "POST" and sub == "/reco":
items = payload.get("items")
if not isinstance(items, list):
return 400, {"code": 400, "message": "items 必须是数组"}
clean = []
for it in items[:200]:
if not isinstance(it, dict):
continue
clean.append({
"path": str(it.get("path") or "").strip(),
"icon": str(it.get("icon") or "📌")[:8],
"name": str(it.get("name") or "").strip()[:40],
"desc": str(it.get("desc") or "").strip()[:120],
"enabled": bool(it.get("enabled", True)),
})
_save_reco(clean)
return 200, {"code": 200, "message": "ok"}
if method == "GET" and sub == "/storage":
total = _dir_size(USERS_ROOT) if os.path.isdir(USERS_ROOT) else 0
for extra in ("users.db", "usage.db", "trials.json"):
@@ -1422,6 +1481,16 @@ class Handler(BaseHTTPRequestHandler):
self._reply(200, json.dumps(body, ensure_ascii=False).encode("utf-8"), "application/json")
return
if parsed.path == "/reco":
items = [x for x in _load_reco() if x.get("enabled")][:24]
body = json.dumps({"code": 200, "message": "ok", "data": items}, ensure_ascii=False).encode("utf-8")
self.send_response(200)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Access-Control-Allow-Origin", "*")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
return
if parsed.path == "/sites":
status, body = sites_api("GET", "", {})
self._reply(status, json.dumps(body, ensure_ascii=False).encode("utf-8"), "application/json")
+185 -2
View File
@@ -306,13 +306,53 @@ function fmtTime(t: number) {
}
// ============ tabs ============
const tab = ref<'overview' | 'files' | 'usage' | 'storage'>('overview');
// ============ 首页推荐 ============
const reco = ref<any[]>([]);
const recoBusy = ref(false);
function switchTab(id: 'overview' | 'files' | 'usage' | 'storage') {
async function loadReco() {
const b = await api('/admin/reco');
reco.value = (b.data ?? []).map((x: any) => ({ ...x }));
}
async function saveReco() {
recoBusy.value = true;
try {
const b = await api('/admin/reco', { method: 'POST', body: JSON.stringify({ items: reco.value }) });
setMsg(b.code === 200 ? '首页推荐已保存,首页立即生效' : (b.message || '保存失败'));
}
finally {
recoBusy.value = false;
}
}
function recoAdd() {
reco.value.unshift({ path: '/', icon: '📌', name: '', desc: '', enabled: true });
}
function recoDel(i: number) {
reco.value.splice(i, 1);
}
function recoMove(i: number, d: -1 | 1) {
const j = i + d;
if (j < 0 || j >= reco.value.length) {
return;
}
const [it] = reco.value.splice(i, 1);
reco.value.splice(j, 0, it);
}
const tab = ref<'overview' | 'files' | 'usage' | 'storage' | 'reco'>('overview');
function switchTab(id: 'overview' | 'files' | 'usage' | 'storage' | 'reco') {
tab.value = id;
if (id === 'overview') {
loadOverview();
}
if (id === 'reco') {
loadReco();
}
if (id === 'usage') {
loadUsage();
}
@@ -349,6 +389,7 @@ function switchTab(id: 'overview' | 'files' | 'usage' | 'storage') {
<div class="adm-nav-item" :class="{ active: tab === 'files' }" @click="switchTab('files')">📁 文件管理</div>
<div class="adm-nav-item" :class="{ active: tab === 'usage' }" @click="switchTab('usage')">📈 使用统计</div>
<div class="adm-nav-item" :class="{ active: tab === 'storage' }" @click="switchTab('storage')">💾 存储设置</div>
<div class="adm-nav-item" :class="{ active: tab === 'reco' }" @click="switchTab('reco')">🏠 首页推荐</div>
</div>
<a href="javascript:;" class="adm-logout" @click="authed = false; localStorage.removeItem(TOKEN_KEY)">退出</a>
</div>
@@ -485,6 +526,36 @@ function switchTab(id: 'overview' | 'files' | 'usage' | 'storage') {
</div>
</template>
<!-- reco -->
<template v-if="tab === 'reco'">
<div class="adm-toolbar">
<h3 class="adm-h3" style="margin:0">🏠 首页推荐管理 <span class="adm-sub">配置首页「近期新功能」展示的工具,按顺序排列,可启停</span></h3>
<button class="adm-btn adm-btn-sm" @click="recoAdd">+ 添加推荐</button>
<button class="adm-btn adm-btn-sm adm-btn-primary" :disabled="recoBusy" @click="saveReco">{{ recoBusy ? '保存中…' : '💾 保存并发布' }}</button>
<span v-if="adminMsg" class="adm-ok">{{ adminMsg }}</span>
</div>
<div class="adm-reco-list">
<div v-for="(it, i) in reco" :key="i" class="adm-reco-row">
<span class="adm-reco-ord">{{ i + 1 }}</span>
<input v-model="it.icon" class="adm-reco-icon" maxlength="4" title="图标(emoji)">
<input v-model="it.path" class="adm-reco-path" placeholder="/tool-path">
<input v-model="it.name" class="adm-reco-name" placeholder="名称">
<input v-model="it.desc" class="adm-reco-desc" placeholder="一句话描述">
<label class="adm-reco-on"><input v-model="it.enabled" type="checkbox"> 显示</label>
<span class="adm-reco-ops">
<button class="adm-mini" :disabled="i === 0" @click="recoMove(i, -1)" title="上移">↑</button>
<button class="adm-mini" :disabled="i === reco.length - 1" @click="recoMove(i, 1)" title="下移">↓</button>
<button class="adm-mini adm-mini-del" @click="recoDel(i)" title="删除">✕</button>
</span>
</div>
<div v-if="!reco.length" class="adm-empty">暂无推荐项,点右上「添加推荐」新增</div>
</div>
<div class="adm-storage-note" style="margin-top:10px">
💡 点「保存并发布」后首页「近期新功能」立即生效,所有访客可见。<code>path</code> 填工具路由(如 /seal-maker),未启用的项不显示。
</div>
</template>
<!-- usage -->
<template v-if="tab === 'usage'">
<div class="adm-toolbar">
@@ -588,6 +659,118 @@ function switchTab(id: 'overview' | 'files' | 'usage' | 'storage') {
}
}
.adm-btn-primary {
background: #2563eb;
}
.adm-mini {
border: 1px solid rgba(128, 128, 128, 0.3);
background: #fff;
border-radius: 6px;
padding: 2px 9px;
font-size: 12.5px;
cursor: pointer;
line-height: 1.5;
&:disabled {
opacity: 0.35;
cursor: not-allowed;
}
&:hover:not(:disabled) {
border-color: #18a058;
color: #18a058;
}
&.adm-mini-del:hover:not(:disabled) {
border-color: #d03050;
color: #d03050;
}
}
.adm-empty {
text-align: center;
opacity: 0.45;
font-size: 13px;
padding: 26px 0;
}
.adm-reco-list {
display: flex;
flex-direction: column;
gap: 7px;
}
.adm-reco-row {
display: flex;
align-items: center;
gap: 7px;
border: 1px solid rgba(128, 128, 128, 0.2);
border-radius: 9px;
padding: 7px 10px;
background: rgba(128, 128, 128, 0.03);
.adm-reco-ord {
width: 22px;
height: 22px;
border-radius: 50%;
background: rgba(24, 160, 88, 0.15);
color: #18a058;
font-size: 12px;
font-weight: 700;
display: flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
}
input {
border: 1px solid rgba(128, 128, 128, 0.32);
border-radius: 7px;
padding: 5px 8px;
font-size: 12.5px;
outline: none;
background: #fff;
&:focus {
border-color: #18a058;
}
}
.adm-reco-icon {
width: 46px;
text-align: center;
}
.adm-reco-path {
width: 150px;
}
.adm-reco-name {
width: 120px;
}
.adm-reco-desc {
flex: 1;
min-width: 120px;
}
.adm-reco-on {
display: flex;
align-items: center;
gap: 4px;
font-size: 12px;
flex-shrink: 0;
cursor: pointer;
}
.adm-reco-ops {
display: flex;
gap: 4px;
flex-shrink: 0;
}
}
.adm-error {
color: #d03050;
font-size: 12.5px;
+15 -2
View File
@@ -1,7 +1,7 @@
<script setup lang="ts">
import { IconDragDrop, IconHeart } from '@tabler/icons-vue';
import { useHead } from '@vueuse/head';
import { computed } from 'vue';
import { computed, onMounted, ref } from 'vue';
import Draggable from 'vuedraggable';
import ColoredCard from '../components/ColoredCard.vue';
import ToolCard from '../components/ToolCard.vue';
@@ -27,6 +27,19 @@ import { config } from '@/config';
const toolStore = useToolStore();
const { recentTools } = useRecentTools();
// 首页推荐:优先读管理后台配置(/relay/reco),失败/为空则回退静态清单
const newFeatures = ref<any[]>(NEW_FEATURES);
onMounted(async () => {
try {
const res = await fetch('/relay/reco');
const j = await res.json();
if (j.code === 200 && Array.isArray(j.data) && j.data.length) {
newFeatures.value = j.data.filter((x: any) => x.path && x.name);
}
}
catch { /* 保持静态清单 */ }
});
// map recent paths to tool objects (newest first, cap 8)
const recentToolList = computed(() => {
const byPath = new Map(toolStore.tools.map(t => [t.path, t]));
@@ -63,7 +76,7 @@ function onUpdateFavoriteTools() {
<span class="nf-sub">持续更新中,登录后数据云端同步、授权跟随账号</span>
</div>
<div class="nf-grid">
<RouterLink v-for="f in NEW_FEATURES" :key="f.path" :to="f.path" class="nf-card">
<RouterLink v-for="f in newFeatures" :key="f.path" :to="f.path" class="nf-card">
<span class="nf-icon">{{ f.icon }}</span>
<span class="nf-body">
<span class="nf-name">{{ f.name }} <em class="nf-badge">新</em></span>