refactor(admin): 重构评论管理界面样式和功能

feat(login): 添加API地址配置功能并支持本地存储

fix(api): 移除CWD_CONFIG_KV相关配置改用数据库存储
fix(cors): 修改跨域配置允许所有来源

perf(email): 添加邮件发送日志记录和调试信息
perf(comments): 优化评论提交和邮件通知逻辑

docs(backend): 更新后端配置文档移除CWD_CONFIG_KV相关说明

chore: 更新端口号和示例配置
This commit is contained in:
anghunk
2026-01-19 16:08:14 +08:00
parent 3d0e3a317a
commit e6e21dff61
17 changed files with 636 additions and 355 deletions

View File

@@ -1,8 +1,19 @@
const API_BASE_URL = import.meta.env.VITE_API_BASE_URL.replace(/\/+$/, ''); const rawEnvApiBaseUrl = (import.meta.env.VITE_API_BASE_URL || '').trim();
function getApiBaseUrl(): string {
const stored = (localStorage.getItem('cwd_admin_api_base_url') || '').trim();
const source = stored || rawEnvApiBaseUrl;
const apiBaseUrl = source.replace(/\/+$/, '');
if (!apiBaseUrl) {
throw new Error('未配置 API 地址,请在登录页填写后重试');
}
return apiBaseUrl;
}
type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE'; type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE';
async function request<T>(method: HttpMethod, path: string, body?: unknown): Promise<T> { async function request<T>(method: HttpMethod, path: string, body?: unknown): Promise<T> {
const apiBaseUrl = getApiBaseUrl();
const token = localStorage.getItem('cwd_admin_token'); const token = localStorage.getItem('cwd_admin_token');
const headers: HeadersInit = {}; const headers: HeadersInit = {};
if (body !== undefined) { if (body !== undefined) {
@@ -11,7 +22,7 @@ async function request<T>(method: HttpMethod, path: string, body?: unknown): Pro
if (token) { if (token) {
headers['Authorization'] = `Bearer ${token}`; headers['Authorization'] = `Bearer ${token}`;
} }
const res = await fetch(`${API_BASE_URL}${path}`, { const res = await fetch(`${apiBaseUrl}${path}`, {
method, method,
headers, headers,
body: body !== undefined ? JSON.stringify(body) : undefined body: body !== undefined ? JSON.stringify(body) : undefined
@@ -44,4 +55,3 @@ export function put<T>(path: string, body?: unknown): Promise<T> {
export function del<T>(path: string): Promise<T> { export function del<T>(path: string): Promise<T> {
return request<T>('DELETE', path); return request<T>('DELETE', path);
} }

View File

@@ -1,254 +1,421 @@
<template> <template>
<div class="page"> <div class="page">
<h2 class="page-title">评论管理</h2> <h2 class="page-title">评论管理</h2>
<div class="toolbar"> <div class="toolbar">
<div class="toolbar-left"> <div class="toolbar-left">
<select v-model="statusFilter" class="toolbar-select"> <select v-model="statusFilter" class="toolbar-select">
<option value="">全部状态</option> <option value="">全部状态</option>
<option value="approved">已通过</option> <option value="approved">已通过</option>
<option value="pending">待审核</option> <option value="pending">待审核</option>
<option value="rejected">已拒绝</option> <option value="rejected">已拒绝</option>
</select> </select>
</div> </div>
<div class="toolbar-right"> <div class="toolbar-right">
<button class="toolbar-button" @click="loadComments">刷新</button> <button class="toolbar-button" @click="loadComments">刷新</button>
</div> </div>
</div> </div>
<div v-if="loading" class="page-hint">加载中...</div> <div v-if="loading" class="page-hint">加载中...</div>
<div v-else-if="error" class="page-error">{{ error }}</div> <div v-else-if="error" class="page-error">{{ error }}</div>
<div v-else> <div v-else>
<table class="table"> <div class="comment-list">
<thead> <div
<tr> v-for="item in filteredComments"
<th>ID</th> :key="item.id"
<th>文章</th> class="comment-card"
<th>作者</th> >
<th>邮箱</th> <div class="comment-card-header">
<th>内容</th> <div class="comment-author">
<th>状态</th> <div class="comment-author-name">
<th>时间</th> {{ item.author }}
<th>操作</th> </div>
</tr> <div class="comment-author-email">
</thead> {{ item.email }}
<tbody> </div>
<tr v-for="item in filteredComments" :key="item.id"> </div>
<td>{{ item.id }}</td> <div class="comment-meta">
<td>{{ item.postSlug }}</td> <span class="comment-path">{{ item.postSlug }}</span>
<td>{{ item.author }}</td> <span class="comment-time">{{ formatDate(item.pubDate) }}</span>
<td>{{ item.email }}</td> </div>
<td class="table-content">{{ item.contentText }}</td> </div>
<td>{{ item.status }}</td> <div class="comment-content">
<td>{{ formatDate(item.pubDate) }}</td> {{ item.contentText }}
<td> </div>
<button class="table-button" @click="changeStatus(item, 'approved')" :disabled="item.status === 'approved'"> <div class="comment-footer">
通过 <div class="comment-info">
</button> <span class="comment-id">#{{ item.id }}</span>
<button class="table-button" @click="changeStatus(item, 'pending')" :disabled="item.status === 'pending'"> <span
待审 class="comment-status"
</button> :class="`comment-status-${item.status}`"
<button class="table-button" @click="changeStatus(item, 'rejected')" :disabled="item.status === 'rejected'"> >
拒绝 {{ formatStatus(item.status) }}
</button> </span>
<button class="table-button table-button-danger" @click="removeComment(item)">删除</button> </div>
</td> <div class="comment-actions">
</tr> <button
<tr v-if="filteredComments.length === 0"> class="comment-action"
<td colspan="8" class="page-hint">暂无数据</td> @click="changeStatus(item, 'approved')"
</tr> :disabled="item.status === 'approved'"
</tbody> >
</table> 通过
<div v-if="pagination.total > 1" class="pagination"> </button>
<button class="pagination-button" :disabled="pagination.page <= 1" @click="goPage(pagination.page - 1)">上一页</button> <button
<span class="pagination-info">{{ pagination.page }} / {{ pagination.total }}</span> class="comment-action"
<button class="pagination-button" :disabled="pagination.page >= pagination.total" @click="goPage(pagination.page + 1)"> @click="changeStatus(item, 'pending')"
下一页 :disabled="item.status === 'pending'"
</button> >
</div> 待审
</div> </button>
</div> <button
class="comment-action"
@click="changeStatus(item, 'rejected')"
:disabled="item.status === 'rejected'"
>
拒绝
</button>
<button
class="comment-action comment-action-danger"
@click="removeComment(item)"
>
删除
</button>
</div>
</div>
</div>
<div
v-if="filteredComments.length === 0"
class="page-hint comment-empty"
>
暂无数据
</div>
</div>
<div v-if="pagination.total > 1" class="pagination">
<button
class="pagination-button"
:disabled="pagination.page <= 1"
@click="goPage(pagination.page - 1)"
>
上一页
</button>
<span class="pagination-info"
>{{ pagination.page }} / {{ pagination.total }}</span
>
<button
class="pagination-button"
:disabled="pagination.page >= pagination.total"
@click="goPage(pagination.page + 1)"
>
下一页
</button>
</div>
</div>
</div>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { onMounted, ref, computed } from 'vue'; import { onMounted, ref, computed } from "vue";
import { CommentItem, CommentListResponse, fetchComments, deleteComment, updateCommentStatus } from '../api/admin'; import {
CommentItem,
CommentListResponse,
fetchComments,
deleteComment,
updateCommentStatus,
} from "../api/admin";
const comments = ref<CommentItem[]>([]); const comments = ref<CommentItem[]>([]);
const pagination = ref<{ page: number; total: number }>({ page: 1, total: 1 }); const pagination = ref<{ page: number; total: number }>({ page: 1, total: 1 });
const loading = ref(false); const loading = ref(false);
const error = ref(''); const error = ref("");
const statusFilter = ref(''); const statusFilter = ref("");
const filteredComments = computed(() => { const filteredComments = computed(() => {
if (!statusFilter.value) { if (!statusFilter.value) {
return comments.value; return comments.value;
} }
return comments.value.filter((item) => item.status === statusFilter.value); return comments.value.filter((item) => item.status === statusFilter.value);
}); });
function formatDate(value: string) { function formatDate(value: string) {
const d = new Date(value); const d = new Date(value);
if (Number.isNaN(d.getTime())) { if (Number.isNaN(d.getTime())) {
return value; return value;
} }
return d.toLocaleString(); return d.toLocaleString();
} }
async function loadComments(page = 1) { function formatStatus(status: string) {
loading.value = true; if (status === "approved") {
error.value = ''; return "已通过";
try { }
const res = await fetchComments(page); if (status === "pending") {
comments.value = res.data; return "待审核";
pagination.value = { page: res.pagination.page, total: res.pagination.total }; }
} catch (e: any) { if (status === "rejected") {
error.value = e.message || '加载失败'; return "已拒绝";
} finally { }
loading.value = false; return status;
} }
async function loadComments(page?: number) {
const targetPage = typeof page === "number" ? page : 1;
loading.value = true;
error.value = "";
try {
const res = await fetchComments(targetPage);
comments.value = res.data;
pagination.value = { page: res.pagination.page, total: res.pagination.total };
} catch (e: any) {
error.value = e.message || "加载失败";
} finally {
loading.value = false;
}
} }
async function goPage(page: number) { async function goPage(page: number) {
if (page < 1 || page > pagination.value.total) { if (page < 1 || page > pagination.value.total) {
return; return;
} }
await loadComments(page); await loadComments(page);
} }
async function changeStatus(item: CommentItem, status: string) { async function changeStatus(item: CommentItem, status: string) {
try { try {
await updateCommentStatus(item.id, status); await updateCommentStatus(item.id, status);
item.status = status; item.status = status;
} catch (e: any) { } catch (e: any) {
error.value = e.message || '更新状态失败'; error.value = e.message || "更新状态失败";
} }
} }
async function removeComment(item: CommentItem) { async function removeComment(item: CommentItem) {
if (!window.confirm(`确认删除评论 ${item.id}`)) { if (!window.confirm(`确认删除评论 ${item.id}`)) {
return; return;
} }
try { try {
await deleteComment(item.id); await deleteComment(item.id);
comments.value = comments.value.filter((c) => c.id !== item.id); comments.value = comments.value.filter((c) => c.id !== item.id);
} catch (e: any) { } catch (e: any) {
error.value = e.message || '删除失败'; error.value = e.message || "删除失败";
} }
} }
onMounted(() => { onMounted(() => {
loadComments(); loadComments();
}); });
</script> </script>
<style scoped> <style scoped>
.page { .page {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
gap: 12px; gap: 12px;
} }
.page-title { .page-title {
margin: 0; margin: 0;
font-size: 18px; font-size: 18px;
color: #24292f; color: #24292f;
} }
.toolbar { .toolbar {
display: flex; display: flex;
justify-content: space-between; justify-content: space-between;
align-items: center; align-items: center;
margin-bottom: 8px; margin-bottom: 8px;
} }
.toolbar-left { .toolbar-left {
display: flex; display: flex;
gap: 8px; gap: 8px;
} }
.toolbar-right { .toolbar-right {
display: flex; display: flex;
gap: 8px; gap: 8px;
} }
.toolbar-select { .toolbar-select {
padding: 4px 8px; padding: 4px 8px;
font-size: 13px; font-size: 13px;
} }
.toolbar-button { .toolbar-button {
padding: 6px 10px; padding: 6px 10px;
border-radius: 4px; border-radius: 4px;
border: 1px solid #d0d7de; border: 1px solid #d0d7de;
background-color: #f6f8fa; background-color: #f6f8fa;
cursor: pointer; cursor: pointer;
font-size: 13px; font-size: 13px;
} }
.page-hint { .page-hint {
font-size: 14px; font-size: 14px;
color: #57606a; color: #57606a;
} }
.page-error { .page-error {
font-size: 14px; font-size: 14px;
color: #d1242f; color: #d1242f;
} }
.table { .comment-list {
width: 100%; display: flex;
border-collapse: collapse; flex-direction: column;
background-color: #ffffff; gap: 12px;
} }
.table th, .comment-card {
.table td { background-color: #ffffff;
border: 1px solid #d0d7de; border-radius: 6px;
padding: 6px 8px; border: 1px solid #d0d7de;
font-size: 13px; padding: 10px 12px;
text-align: left; box-shadow: 0 1px 0 rgba(27, 31, 36, 0.04);
vertical-align: top;
} }
.table-content { .comment-card-header {
max-width: 260px; display: flex;
white-space: nowrap; justify-content: space-between;
overflow: hidden; align-items: flex-start;
text-overflow: ellipsis; gap: 12px;
margin-bottom: 8px;
} }
.table-button { .comment-author {
margin-right: 4px; display: flex;
padding: 4px 6px; flex-direction: column;
border-radius: 4px; gap: 2px;
border: 1px solid #d0d7de;
background-color: #f6f8fa;
font-size: 12px;
cursor: pointer;
} }
.table-button-danger { .comment-author-name {
border-color: #d1242f; font-size: 14px;
color: #d1242f; font-weight: 600;
color: #24292f;
}
.comment-author-email {
font-size: 12px;
color: #57606a;
word-break: break-all;
}
.comment-meta {
display: flex;
flex-direction: column;
align-items: flex-end;
gap: 4px;
font-size: 12px;
color: #57606a;
}
.comment-path {
max-width: 220px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.comment-time {
white-space: nowrap;
}
.comment-content {
font-size: 14px;
line-height: 1.6;
color: #24292f;
margin-bottom: 8px;
white-space: pre-wrap;
word-break: break-word;
}
.comment-footer {
display: flex;
justify-content: space-between;
align-items: center;
gap: 12px;
flex-wrap: wrap;
}
.comment-info {
display: flex;
align-items: center;
gap: 8px;
font-size: 12px;
color: #57606a;
}
.comment-id {
padding: 2px 6px;
border-radius: 999px;
background-color: #f6f8fa;
}
.comment-status {
padding: 2px 8px;
border-radius: 999px;
background-color: #f6f8fa;
}
.comment-status-approved {
color: #1a7f37;
background-color: #e7f5eb;
}
.comment-status-pending {
color: #9a6700;
background-color: #fff8c5;
}
.comment-status-rejected {
color: #d1242f;
background-color: #ffebe9;
}
.comment-actions {
display: flex;
flex-wrap: wrap;
gap: 4px;
}
.comment-action {
padding: 4px 8px;
border-radius: 4px;
border: 1px solid #d0d7de;
background-color: #f6f8fa;
font-size: 12px;
cursor: pointer;
}
.comment-action-danger {
border-color: #d1242f;
color: #d1242f;
}
.comment-action:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.comment-empty {
margin-top: 8px;
text-align: center;
} }
.pagination { .pagination {
margin-top: 8px; margin-top: 8px;
display: flex; display: flex;
align-items: center; align-items: center;
gap: 8px; gap: 8px;
} }
.pagination-button { .pagination-button {
padding: 4px 8px; padding: 4px 8px;
border-radius: 4px; border-radius: 4px;
border: 1px solid #d0d7de; border: 1px solid #d0d7de;
background-color: #f6f8fa; background-color: #f6f8fa;
font-size: 12px; font-size: 12px;
cursor: pointer; cursor: pointer;
} }
.pagination-info { .pagination-info {
font-size: 13px; font-size: 13px;
} }
</style> </style>

View File

@@ -1,127 +1,156 @@
<template> <template>
<div class="login-page"> <div class="login-page">
<div class="login-card"> <div class="login-card">
<h1 class="login-title">CWD 评论后台</h1> <h1 class="login-title">CWD 评论后台</h1>
<form class="login-form" @submit.prevent="handleSubmit"> <form class="login-form" @submit.prevent="handleSubmit">
<div class="form-item"> <div class="form-item">
<label class="form-label">管理员账号</label> <label class="form-label">API 地址</label>
<input v-model="name" class="form-input" type="text" autocomplete="username" /> <input v-model="apiBaseUrl" class="form-input" type="text" />
</div> </div>
<div class="form-item"> <div class="form-item">
<label class="form-label">密码</label> <label class="form-label">管理员账号</label>
<input v-model="password" class="form-input" type="password" autocomplete="current-password" /> <input v-model="name" class="form-input" type="text" autocomplete="username" />
</div> </div>
<div v-if="error" class="form-error">{{ error }}</div> <div class="form-item">
<button class="form-button" type="submit" :disabled="submitting"> <label class="form-label">密码</label>
<span v-if="submitting">登录中...</span> <input
<span v-else>登录</span> v-model="password"
</button> class="form-input"
</form> type="password"
</div> autocomplete="current-password"
</div> />
</div>
<div v-if="error" class="form-error">{{ error }}</div>
<button class="form-button" type="submit" :disabled="submitting">
<span v-if="submitting">登录中...</span>
<span v-else>登录</span>
</button>
</form>
</div>
</div>
</template> </template>
<script setup lang="ts"> <script setup lang="ts">
import { ref } from 'vue'; import { onMounted, ref } from "vue";
import { useRouter } from 'vue-router'; import { useRouter } from "vue-router";
import { loginAdmin } from '../api/admin'; import { loginAdmin } from "../api/admin";
const router = useRouter(); const router = useRouter();
const name = ref(''); const defaultAdminName = (import.meta.env.VITE_ADMIN_NAME || "").trim();
const password = ref(''); const defaultAdminPassword = (import.meta.env.VITE_ADMIN_PASSWORD || "").trim();
const name = ref(defaultAdminName);
const password = ref(defaultAdminPassword);
const submitting = ref(false); const submitting = ref(false);
const error = ref(''); const error = ref("");
const apiBaseUrl = ref("");
const rawEnvApiBaseUrl = (import.meta.env.VITE_API_BASE_URL || "").trim();
const defaultApiBaseUrl = rawEnvApiBaseUrl.replace(/\/+$/, "");
onMounted(() => {
const stored = (localStorage.getItem("cwd_admin_api_base_url") || "").trim();
if (stored) {
apiBaseUrl.value = stored;
return;
}
apiBaseUrl.value = defaultApiBaseUrl;
});
async function handleSubmit() { async function handleSubmit() {
if (!name.value || !password.value) { const normalizedApiBaseUrl = apiBaseUrl.value.trim().replace(/\/+$/, "");
error.value = '请输入账号和密码'; if (!normalizedApiBaseUrl) {
return; error.value = "请输入 API 地址";
} return;
error.value = ''; }
submitting.value = true; if (!name.value || !password.value) {
try { error.value = "请输入账号和密码";
await loginAdmin(name.value, password.value); return;
router.push({ name: 'comments' }); }
} catch (e: any) { error.value = "";
error.value = e.message || '登录失败'; submitting.value = true;
} finally { try {
submitting.value = false; localStorage.setItem("cwd_admin_api_base_url", normalizedApiBaseUrl);
} await loginAdmin(name.value, password.value);
router.push({ name: "comments" });
} catch (e: any) {
error.value = e.message || "登录失败";
} finally {
submitting.value = false;
}
} }
</script> </script>
<style scoped> <style scoped>
.login-page { .login-page {
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
height: 100%; height: 100%;
} }
.login-card { .login-card {
background-color: #ffffff; background-color: #ffffff;
padding: 32px 40px; padding: 32px 40px;
border-radius: 8px; border-radius: 8px;
box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08); box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
width: 360px; width: 360px;
} }
.login-title { .login-title {
margin: 0 0 24px; margin: 0 0 24px;
font-size: 22px; font-size: 22px;
text-align: center; text-align: center;
color: #333333; color: #333333;
} }
.login-form { .login-form {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
gap: 16px; gap: 16px;
} }
.form-item { .form-item {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
gap: 6px; gap: 6px;
} }
.form-label { .form-label {
font-size: 14px; font-size: 14px;
color: #555555; color: #555555;
} }
.form-input { .form-input {
padding: 8px 10px; padding: 8px 10px;
border-radius: 4px; border-radius: 4px;
border: 1px solid #d0d7de; border: 1px solid #d0d7de;
font-size: 14px; font-size: 14px;
outline: none; outline: none;
} }
.form-input:focus { .form-input:focus {
border-color: #0969da; border-color: #0969da;
box-shadow: 0 0 0 1px rgba(9, 105, 218, 0.2); box-shadow: 0 0 0 1px rgba(9, 105, 218, 0.2);
} }
.form-error { .form-error {
font-size: 13px; font-size: 13px;
color: #d1242f; color: #d1242f;
} }
.form-button { .form-button {
margin-top: 8px; margin-top: 8px;
padding: 10px 0; padding: 10px 0;
border-radius: 4px; border-radius: 4px;
border: none; border: none;
background-color: #0969da; background-color: #0969da;
color: #ffffff; color: #ffffff;
font-size: 15px; font-size: 15px;
cursor: pointer; cursor: pointer;
} }
.form-button:disabled { .form-button:disabled {
opacity: 0.7; opacity: 0.7;
cursor: default; cursor: default;
} }
</style> </style>

View File

@@ -4,7 +4,7 @@ import vue from '@vitejs/plugin-vue';
export default defineConfig({ export default defineConfig({
plugins: [vue()], plugins: [vue()],
server: { server: {
port: 5176 port: 1226
} }
}); });

View File

@@ -1,5 +0,0 @@
ALLOW_ORIGIN="http://localhost:4321,https://blog.example.top"
CF_FROM_EMAIL="noreply@yourdomain.com"
EMAIL_ADDRESS="admin@example.top"
ADMIN_NAME="Admin"
ADMIN_PASSWORD="password"

View File

@@ -3,14 +3,14 @@ import { Bindings } from '../../bindings';
export const getAdminEmail = async (c: Context<{ Bindings: Bindings }>) => { export const getAdminEmail = async (c: Context<{ Bindings: Bindings }>) => {
try { try {
let email: string | null = null; await c.env.CWD_DB.prepare(
if (c.env.CWD_CONFIG_KV) { 'CREATE TABLE IF NOT EXISTS Settings (key TEXT PRIMARY KEY, value TEXT NOT NULL)'
email = await c.env.CWD_CONFIG_KV.get('settings:admin_notify_email'); ).run();
} const row = await c.env.CWD_DB.prepare('SELECT value FROM Settings WHERE key = ?')
if (!email) { .bind('admin_notify_email')
email = c.env.EMAIL_ADDRESS || null; .first<{ value: string }>();
} const email = row?.value || c.env.EMAIL_ADDRESS || null;
return c.json({ email }); return c.json({ email: email });
} catch (e: any) { } catch (e: any) {
return c.json({ message: e.message }, 500); return c.json({ message: e.message }, 500);
} }

View File

@@ -11,10 +11,12 @@ export const setAdminEmail = async (c: Context<{ Bindings: Bindings }>) => {
if (!email || !isValidEmail(email)) { if (!email || !isValidEmail(email)) {
return c.json({ message: '邮箱格式不正确' }, 400); return c.json({ message: '邮箱格式不正确' }, 400);
} }
if (!c.env.CWD_CONFIG_KV) { await c.env.CWD_DB.prepare(
return c.json({ message: '未配置 CWD_CONFIG_KV无法保存设置' }, 500); 'CREATE TABLE IF NOT EXISTS Settings (key TEXT PRIMARY KEY, value TEXT NOT NULL)'
} ).run();
await c.env.CWD_CONFIG_KV.put('settings:admin_notify_email', email); await c.env.CWD_DB.prepare('REPLACE INTO Settings (key, value) VALUES (?, ?)')
.bind('admin_notify_email', email)
.run();
return c.json({ message: '保存成功' }); return c.json({ message: '保存成功' });
} catch (e: any) { } catch (e: any) {
return c.json({ message: e.message }, 500); return c.json({ message: e.message }, 500);

View File

@@ -58,6 +58,17 @@ export const postComment = async (c: Context<{ Bindings: Bindings }>) => {
// 3. 准备数据 // 3. 准备数据
const content = checkContent(rawContent); const content = checkContent(rawContent);
const author = checkContent(rawAuthor); const author = checkContent(rawAuthor);
console.log('PostComment:request', {
postSlug: post_slug,
hasParent: !!parent_id,
author,
email,
ip,
hasSendEmailBinding: !!c.env.SEND_EMAIL,
fromEmail: c.env.CF_FROM_EMAIL,
emailAddressEnv: c.env.EMAIL_ADDRESS
});
const uaParser = new UAParser(userAgent); const uaParser = new UAParser(userAgent);
const uaResult = uaParser.getResult(); const uaResult = uaParser.getResult();
@@ -88,12 +99,20 @@ export const postComment = async (c: Context<{ Bindings: Bindings }>) => {
if (!success) throw new Error("Database insert failed"); if (!success) throw new Error("Database insert failed");
console.log('PostComment:inserted', {
postSlug: post_slug,
hasParent: !!parent_id,
ip
});
// 5. 发送邮件通知 (后台异步执行,不阻塞用户响应) // 5. 发送邮件通知 (后台异步执行,不阻塞用户响应)
if (c.env.SEND_EMAIL && c.env.CF_FROM_EMAIL) { if (c.env.SEND_EMAIL && c.env.CF_FROM_EMAIL) {
console.log('PostComment:mailDispatch:start', {
hasParent: !!data.parent_id
});
c.executionCtx.waitUntil((async () => { c.executionCtx.waitUntil((async () => {
try { try {
if (data.parent_id) { if (data.parent_id) {
// 回复逻辑:查询父评论信息
const parentComment = await c.env.CWD_DB.prepare( const parentComment = await c.env.CWD_DB.prepare(
"SELECT author, email, content_text FROM Comment WHERE id = ?" "SELECT author, email, content_text FROM Comment WHERE id = ?"
).bind(data.parent_id).first<{ author: string, email: string, content_text: string }>(); ).bind(data.parent_id).first<{ author: string, email: string, content_text: string }>();
@@ -104,6 +123,10 @@ export const postComment = async (c: Context<{ Bindings: Bindings }>) => {
).bind(parentComment.email).first<{ created_at: string }>(); ).bind(parentComment.email).first<{ created_at: string }>();
const canSendUserMail = !recentUserMail || (Date.now() - new Date(recentUserMail.created_at).getTime() > 60 * 1000); const canSendUserMail = !recentUserMail || (Date.now() - new Date(recentUserMail.created_at).getTime() > 60 * 1000);
if (canSendUserMail) { if (canSendUserMail) {
console.log('PostComment:mailDispatch:userReply:send', {
toEmail: parentComment.email,
toName: parentComment.author
});
await sendCommentReplyNotification(c.env, { await sendCommentReplyNotification(c.env, {
toEmail: parentComment.email, toEmail: parentComment.email,
toName: parentComment.author, toName: parentComment.author,
@@ -116,15 +139,23 @@ export const postComment = async (c: Context<{ Bindings: Bindings }>) => {
await c.env.CWD_DB.prepare( await c.env.CWD_DB.prepare(
"INSERT INTO EmailLog (recipient, type, ip_address, created_at) VALUES (?, ?, ?, ?)" "INSERT INTO EmailLog (recipient, type, ip_address, created_at) VALUES (?, ?, ?, ?)"
).bind(parentComment.email, 'user-reply', ip, new Date().toISOString()).run(); ).bind(parentComment.email, 'user-reply', ip, new Date().toISOString()).run();
console.log('PostComment:mailDispatch:userReply:logInserted', {
toEmail: parentComment.email
});
}
if (!canSendUserMail) {
console.log('PostComment:mailDispatch:userReply:skippedByRateLimit', {
toEmail: parentComment.email
});
} }
} }
} else { } else {
// 新评论通知站长
const adminEmailRow = await c.env.CWD_DB.prepare( const adminEmailRow = await c.env.CWD_DB.prepare(
"SELECT created_at FROM EmailLog WHERE type = 'admin-notify' ORDER BY created_at DESC LIMIT 1" "SELECT created_at FROM EmailLog WHERE type = 'admin-notify' ORDER BY created_at DESC LIMIT 1"
).first<{ created_at: string }>(); ).first<{ created_at: string }>();
const canSendAdminMail = !adminEmailRow || (Date.now() - new Date(adminEmailRow.created_at).getTime() > 15 * 1000); const canSendAdminMail = !adminEmailRow || (Date.now() - new Date(adminEmailRow.created_at).getTime() > 15 * 1000);
if (canSendAdminMail) { if (canSendAdminMail) {
console.log('PostComment:mailDispatch:admin:send');
await sendCommentNotification(c.env, { await sendCommentNotification(c.env, {
postTitle: data.post_title, postTitle: data.post_title,
postUrl: data.post_url, postUrl: data.post_url,
@@ -134,12 +165,21 @@ export const postComment = async (c: Context<{ Bindings: Bindings }>) => {
await c.env.CWD_DB.prepare( await c.env.CWD_DB.prepare(
"INSERT INTO EmailLog (recipient, type, ip_address, created_at) VALUES (?, ?, ?, ?)" "INSERT INTO EmailLog (recipient, type, ip_address, created_at) VALUES (?, ?, ?, ?)"
).bind('admin', 'admin-notify', ip, new Date().toISOString()).run(); ).bind('admin', 'admin-notify', ip, new Date().toISOString()).run();
console.log('PostComment:mailDispatch:admin:logInserted');
}
if (!canSendAdminMail) {
console.log('PostComment:mailDispatch:admin:skippedByRateLimit');
} }
} }
} catch (mailError) { } catch (mailError) {
console.error("Mail Notification Failed:", mailError); console.error("Mail Notification Failed:", mailError);
} }
})()); })());
} else {
console.log('PostComment:mailDispatch:skipNoBinding', {
hasSendEmailBinding: !!c.env.SEND_EMAIL,
fromEmail: c.env.CF_FROM_EMAIL
});
} }
return c.json({ message: "Comment submitted. Awaiting moderation." }); return c.json({ message: "Comment submitted. Awaiting moderation." });

View File

@@ -1,7 +1,6 @@
export type Bindings = { export type Bindings = {
CWD_DB: D1Database CWD_DB: D1Database
CWD_AUTH_KV: KVNamespace; CWD_AUTH_KV: KVNamespace;
CWD_CONFIG_KV?: KVNamespace;
ALLOW_ORIGIN: string ALLOW_ORIGIN: string
CF_FROM_EMAIL?: string CF_FROM_EMAIL?: string
SEND_EMAIL?: { SEND_EMAIL?: {

View File

@@ -14,8 +14,24 @@ import { getAdminEmail } from './api/admin/getAdminEmail';
import { setAdminEmail } from './api/admin/setAdminEmail'; import { setAdminEmail } from './api/admin/setAdminEmail';
const app = new Hono<{ Bindings: Bindings }>(); const app = new Hono<{ Bindings: Bindings }>();
const VERSION = 'v0.0.1';
app.use('*', async (c, next) => {
console.log('Request:start', {
method: c.req.method,
path: c.req.path,
url: c.req.url,
hasDb: !!c.env.CWD_DB,
hasAuthKv: !!c.env.CWD_AUTH_KV
});
const res = await next();
console.log('Request:end', {
method: c.req.method,
path: c.req.path
});
return res;
});
// 跨域
app.use('/api/*', async (c, next) => { app.use('/api/*', async (c, next) => {
const corsMiddleware = customCors(c.env.ALLOW_ORIGIN); const corsMiddleware = customCors(c.env.ALLOW_ORIGIN);
return corsMiddleware(c, next); return corsMiddleware(c, next);
@@ -25,7 +41,12 @@ app.use('/admin/*', async (c, next) => {
return corsMiddleware(c, next); return corsMiddleware(c, next);
}); });
// API app.get('/', (c) => {
return c.html(
`CWD 评论部署成功,当前版本 ${VERSION}<a href="https://github.com/anghunk/cwd-comments" target="_blank" rel="noreferrer">查看文档</a>`
);
});
app.get('/api/comments', getComments); app.get('/api/comments', getComments);
app.post('/api/comments', postComment); app.post('/api/comments', postComment);

View File

@@ -1,23 +1,12 @@
import { cors } from 'hono/cors' import { cors } from 'hono/cors'
export const customCors = (allowOriginStr: string | undefined) => { export const customCors = (_allowOriginStr: string | undefined) => {
// 1. 将环境变量字符串解析为数组
// 如果环境变量不存在,则默认为空数组
const allowedOrigins = allowOriginStr
? allowOriginStr.split(',').map(origin => origin.trim())
: []
return cors({ return cors({
origin: (origin) => { origin: '*',
// 如果请求的 origin 在白名单中,或者是本地文件(null)
if (!origin || allowedOrigins.includes(origin)) {
return origin
}
},
allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
allowHeaders: ['Content-Type', 'Authorization'], allowHeaders: ['Content-Type', 'Authorization'],
exposeHeaders: ['Content-Length'], exposeHeaders: ['Content-Length'],
maxAge: 600, maxAge: 600,
credentials: true, credentials: false,
}) })
} }

View File

@@ -17,6 +17,14 @@ export async function sendCommentReplyNotification(
) { ) {
const { toEmail, toName, postTitle, parentComment, replyAuthor, replyContent, postUrl } = params; const { toEmail, toName, postTitle, parentComment, replyAuthor, replyContent, postUrl } = params;
console.log('EmailReplyNotification:start', {
toEmail,
toName,
postTitle,
fromEmail: env.CF_FROM_EMAIL,
hasSendBinding: !!env.SEND_EMAIL
});
const html = ` const html = `
<div style="font-family: sans-serif; line-height: 1.6; color: #333;"> <div style="font-family: sans-serif; line-height: 1.6; color: #333;">
<p>Hi <b>${toName}</b></p> <p>Hi <b>${toName}</b></p>
@@ -39,6 +47,10 @@ export async function sendCommentReplyNotification(
`; `;
if (!env.SEND_EMAIL || !env.CF_FROM_EMAIL) { if (!env.SEND_EMAIL || !env.CF_FROM_EMAIL) {
console.error('EmailReplyNotification:missingBinding', {
hasSendBinding: !!env.SEND_EMAIL,
fromEmail: env.CF_FROM_EMAIL
});
throw new Error('未配置邮件发送绑定或发件人地址'); throw new Error('未配置邮件发送绑定或发件人地址');
} }
@@ -48,6 +60,10 @@ export async function sendCommentReplyNotification(
subject: `你在 example.com 上的评论有了新回复`, subject: `你在 example.com 上的评论有了新回复`,
html html
}); });
console.log('EmailReplyNotification:sent', {
toEmail
});
} }
/** /**
@@ -65,6 +81,13 @@ export async function sendCommentNotification(
const { postTitle, postUrl, commentAuthor, commentContent } = params; const { postTitle, postUrl, commentAuthor, commentContent } = params;
const toEmail = await getAdminNotifyEmail(env); const toEmail = await getAdminNotifyEmail(env);
console.log('EmailAdminNotification:start', {
toEmail,
postTitle,
fromEmail: env.CF_FROM_EMAIL,
hasSendBinding: !!env.SEND_EMAIL
});
const html = ` const html = `
<div style="font-family: sans-serif;"> <div style="font-family: sans-serif;">
<p><b>${commentAuthor}</b> 在文章《${postTitle}》下发表了评论:</p> <p><b>${commentAuthor}</b> 在文章《${postTitle}》下发表了评论:</p>
@@ -76,6 +99,10 @@ export async function sendCommentNotification(
`; `;
if (!env.SEND_EMAIL || !env.CF_FROM_EMAIL) { if (!env.SEND_EMAIL || !env.CF_FROM_EMAIL) {
console.error('EmailAdminNotification:missingBinding', {
hasSendBinding: !!env.SEND_EMAIL,
fromEmail: env.CF_FROM_EMAIL
});
throw new Error('未配置邮件发送绑定或发件人地址'); throw new Error('未配置邮件发送绑定或发件人地址');
} }
@@ -85,14 +112,31 @@ export async function sendCommentNotification(
subject: `新评论通知:${postTitle}`, subject: `新评论通知:${postTitle}`,
html html
}); });
console.log('EmailAdminNotification:sent', {
toEmail
});
} }
// 读取管理员通知邮箱:优先 KV 设置,其次环境变量
async function getAdminNotifyEmail(env: Bindings): Promise<string> { async function getAdminNotifyEmail(env: Bindings): Promise<string> {
if (env.CWD_CONFIG_KV) { await env.CWD_DB.prepare(
const val = await env.CWD_CONFIG_KV.get('settings:admin_notify_email'); 'CREATE TABLE IF NOT EXISTS Settings (key TEXT PRIMARY KEY, value TEXT NOT NULL)'
if (val) return val; ).run();
const row = await env.CWD_DB.prepare('SELECT value FROM Settings WHERE key = ?')
.bind('admin_notify_email')
.first<{ value: string }>();
if (row?.value) {
console.log('EmailAdminNotification:useDbEmail', {
email: row.value
});
return row.value;
} }
if (env.EMAIL_ADDRESS) return env.EMAIL_ADDRESS; if (env.EMAIL_ADDRESS) {
console.log('EmailAdminNotification:useEnvEmail', {
email: env.EMAIL_ADDRESS
});
return env.EMAIL_ADDRESS;
}
console.error('EmailAdminNotification:noAdminEmail');
throw new Error('未配置管理员通知邮箱'); throw new Error('未配置管理员通知邮箱');
} }

View File

@@ -7,9 +7,6 @@
"name": "cwd-comments", "name": "cwd-comments",
"main": "src/index.ts", "main": "src/index.ts",
"compatibility_date": "2026-01-03", "compatibility_date": "2026-01-03",
"observability": {
"enabled": true
},
"workers_dev": true, "workers_dev": true,
"preview_urls": true "preview_urls": true
} }

View File

@@ -50,11 +50,10 @@ npm install
] ]
``` ```
如果`binding`字段不是`CWD_DB`,请修改为`CWD_DB` 如果`binding`字段不是`CWD_DB`,请修改为`CWD_DB`
* **创建 KV 存储**,如果遇到提示,按回车继续 * **创建 KV 存储**,如果遇到提示,按回车继续
```bash ```bash
npx wrangler kv namespace create CWD_AUTH_KV npx wrangler kv namespace create CWD_AUTH_KV
npx wrangler kv namespace create CWD_CONFIG_KV
``` ```
运行完成后可以确认一下 `wrangler.jsonc` 中是否有如下配置 运行完成后可以确认一下 `wrangler.jsonc` 中是否有如下配置
```jsonc ```jsonc
@@ -62,10 +61,6 @@ npm install
{ {
"binding": "CWD_AUTH_KV", "binding": "CWD_AUTH_KV",
"id": "xxxxxxx" // KV 存储 ID "id": "xxxxxxx" // KV 存储 ID
},
{
"binding": "CWD_CONFIG_KV",
"id": "xxxxxxx" // KV 存储 ID
} }
] ]
``` ```

View File

@@ -159,19 +159,15 @@ export class CommentForm extends Component {
updateErrors(formErrors) { updateErrors(formErrors) {
if (!this.elements.root) return; if (!this.elements.root) return;
// 昵称错误 const authorInput = this.elements.root.querySelector('input[name="author"]');
const authorInput = this.elements.root.querySelector('input[placeholder*="昵称"]');
this.updateFieldError(authorInput, formErrors?.author); this.updateFieldError(authorInput, formErrors?.author);
// 邮箱错误 const emailInput = this.elements.root.querySelector('input[name="email"]');
const emailInput = this.elements.root.querySelector('input[placeholder*="邮箱"]');
this.updateFieldError(emailInput, formErrors?.email); this.updateFieldError(emailInput, formErrors?.email);
// 网址错误 const urlInput = this.elements.root.querySelector('input[name="url"]');
const urlInput = this.elements.root.querySelector('input[placeholder*="网址"]');
this.updateFieldError(urlInput, formErrors?.url); this.updateFieldError(urlInput, formErrors?.url);
// 内容错误
const contentTextarea = this.elements.root.querySelector('textarea'); const contentTextarea = this.elements.root.querySelector('textarea');
this.updateFieldError(contentTextarea, formErrors?.content); this.updateFieldError(contentTextarea, formErrors?.content);
} }
@@ -216,7 +212,8 @@ export class CommentForm extends Component {
className: `cwd-form-input ${error ? 'cwd-input-error' : ''}`, className: `cwd-form-input ${error ? 'cwd-input-error' : ''}`,
attributes: { attributes: {
type, type,
placeholder, name: fieldName,
value: value || '',
disabled: this.props.submitting, disabled: this.props.submitting,
onInput: (e) => this.handleFieldChange(fieldName, e.target.value), onInput: (e) => this.handleFieldChange(fieldName, e.target.value),
}, },
@@ -230,9 +227,9 @@ export class CommentForm extends Component {
* 设置输入框的值 * 设置输入框的值
*/ */
setInputValues(root, form) { setInputValues(root, form) {
const authorInput = root.querySelector('input[placeholder*="昵称"]'); const authorInput = root.querySelector('input[name="author"]');
const emailInput = root.querySelector('input[placeholder*="邮箱"]'); const emailInput = root.querySelector('input[name="email"]');
const urlInput = root.querySelector('input[placeholder*="网址"]'); const urlInput = root.querySelector('input[name="url"]');
const contentTextarea = root.querySelector('textarea'); const contentTextarea = root.querySelector('textarea');
if (authorInput) authorInput.value = form.author || ''; if (authorInput) authorInput.value = form.author || '';

View File

@@ -10,7 +10,7 @@ const STORAGE_KEY = 'cwd-dev-config';
// 默认配置 // 默认配置
const DEFAULT_CONFIG = { const DEFAULT_CONFIG = {
apiBaseUrl: 'http://localhost:8788', apiBaseUrl: 'http://localhost:8788',
postSlug: 'demo-post', postSlug: "https://zishu.me/message",
theme: 'light', theme: 'light',
avatarPrefix: 'https://gravatar.com/avatar', avatarPrefix: 'https://gravatar.com/avatar',
}; };

View File

@@ -3,34 +3,30 @@ import { resolve } from 'path';
import cssInjectedByJsPlugin from 'vite-plugin-css-injected-by-js'; import cssInjectedByJsPlugin from 'vite-plugin-css-injected-by-js';
export default defineConfig({ export default defineConfig({
plugins: [cssInjectedByJsPlugin()], plugins: [cssInjectedByJsPlugin()],
resolve: { resolve: {
alias: { alias: {
'@': resolve(__dirname, 'src') '@': resolve(__dirname, 'src'),
} },
}, },
build: { build: {
lib: { lib: {
name: 'CWDComments', name: 'CWDComments',
entry: resolve(__dirname, 'src/index.js'), entry: resolve(__dirname, 'src/index.js'),
formats: ['umd'], formats: ['umd'],
fileName: (format) => `cwd-comments.js` fileName: (format) => `cwd-comments.js`,
}, },
rollupOptions: { rollupOptions: {
output: { output: {
exports: 'named' exports: 'named',
} },
}, },
sourcemap: false, sourcemap: false,
minify: 'terser', minify: 'terser',
terserOptions: { terserOptions: {
compress: { compress: {
drop_console: false drop_console: false,
} },
} },
}, },
server: {
port: 5173,
open: false
}
}); });