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';
async function request<T>(method: HttpMethod, path: string, body?: unknown): Promise<T> {
const apiBaseUrl = getApiBaseUrl();
const token = localStorage.getItem('cwd_admin_token');
const headers: HeadersInit = {};
if (body !== undefined) {
@@ -11,7 +22,7 @@ async function request<T>(method: HttpMethod, path: string, body?: unknown): Pro
if (token) {
headers['Authorization'] = `Bearer ${token}`;
}
const res = await fetch(`${API_BASE_URL}${path}`, {
const res = await fetch(`${apiBaseUrl}${path}`, {
method,
headers,
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> {
return request<T>('DELETE', path);
}

View File

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

View File

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

View File

@@ -4,7 +4,7 @@ import vue from '@vitejs/plugin-vue';
export default defineConfig({
plugins: [vue()],
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 }>) => {
try {
let email: string | null = null;
if (c.env.CWD_CONFIG_KV) {
email = await c.env.CWD_CONFIG_KV.get('settings:admin_notify_email');
}
if (!email) {
email = c.env.EMAIL_ADDRESS || null;
}
return c.json({ email });
await c.env.CWD_DB.prepare(
'CREATE TABLE IF NOT EXISTS Settings (key TEXT PRIMARY KEY, value TEXT NOT NULL)'
).run();
const row = await c.env.CWD_DB.prepare('SELECT value FROM Settings WHERE key = ?')
.bind('admin_notify_email')
.first<{ value: string }>();
const email = row?.value || c.env.EMAIL_ADDRESS || null;
return c.json({ email: email });
} catch (e: any) {
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)) {
return c.json({ message: '邮箱格式不正确' }, 400);
}
if (!c.env.CWD_CONFIG_KV) {
return c.json({ message: '未配置 CWD_CONFIG_KV无法保存设置' }, 500);
}
await c.env.CWD_CONFIG_KV.put('settings:admin_notify_email', email);
await c.env.CWD_DB.prepare(
'CREATE TABLE IF NOT EXISTS Settings (key TEXT PRIMARY KEY, value TEXT NOT NULL)'
).run();
await c.env.CWD_DB.prepare('REPLACE INTO Settings (key, value) VALUES (?, ?)')
.bind('admin_notify_email', email)
.run();
return c.json({ message: '保存成功' });
} catch (e: any) {
return c.json({ message: e.message }, 500);

View File

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

View File

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

View File

@@ -14,8 +14,24 @@ import { getAdminEmail } from './api/admin/getAdminEmail';
import { setAdminEmail } from './api/admin/setAdminEmail';
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) => {
const corsMiddleware = customCors(c.env.ALLOW_ORIGIN);
return corsMiddleware(c, next);
@@ -25,7 +41,12 @@ app.use('/admin/*', async (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.post('/api/comments', postComment);

View File

@@ -1,23 +1,12 @@
import { cors } from 'hono/cors'
export const customCors = (allowOriginStr: string | undefined) => {
// 1. 将环境变量字符串解析为数组
// 如果环境变量不存在,则默认为空数组
const allowedOrigins = allowOriginStr
? allowOriginStr.split(',').map(origin => origin.trim())
: []
export const customCors = (_allowOriginStr: string | undefined) => {
return cors({
origin: (origin) => {
// 如果请求的 origin 在白名单中,或者是本地文件(null)
if (!origin || allowedOrigins.includes(origin)) {
return origin
}
},
origin: '*',
allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
allowHeaders: ['Content-Type', 'Authorization'],
exposeHeaders: ['Content-Length'],
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;
console.log('EmailReplyNotification:start', {
toEmail,
toName,
postTitle,
fromEmail: env.CF_FROM_EMAIL,
hasSendBinding: !!env.SEND_EMAIL
});
const html = `
<div style="font-family: sans-serif; line-height: 1.6; color: #333;">
<p>Hi <b>${toName}</b></p>
@@ -39,6 +47,10 @@ export async function sendCommentReplyNotification(
`;
if (!env.SEND_EMAIL || !env.CF_FROM_EMAIL) {
console.error('EmailReplyNotification:missingBinding', {
hasSendBinding: !!env.SEND_EMAIL,
fromEmail: env.CF_FROM_EMAIL
});
throw new Error('未配置邮件发送绑定或发件人地址');
}
@@ -48,6 +60,10 @@ export async function sendCommentReplyNotification(
subject: `你在 example.com 上的评论有了新回复`,
html
});
console.log('EmailReplyNotification:sent', {
toEmail
});
}
/**
@@ -65,6 +81,13 @@ export async function sendCommentNotification(
const { postTitle, postUrl, commentAuthor, commentContent } = params;
const toEmail = await getAdminNotifyEmail(env);
console.log('EmailAdminNotification:start', {
toEmail,
postTitle,
fromEmail: env.CF_FROM_EMAIL,
hasSendBinding: !!env.SEND_EMAIL
});
const html = `
<div style="font-family: sans-serif;">
<p><b>${commentAuthor}</b> 在文章《${postTitle}》下发表了评论:</p>
@@ -76,6 +99,10 @@ export async function sendCommentNotification(
`;
if (!env.SEND_EMAIL || !env.CF_FROM_EMAIL) {
console.error('EmailAdminNotification:missingBinding', {
hasSendBinding: !!env.SEND_EMAIL,
fromEmail: env.CF_FROM_EMAIL
});
throw new Error('未配置邮件发送绑定或发件人地址');
}
@@ -85,14 +112,31 @@ export async function sendCommentNotification(
subject: `新评论通知:${postTitle}`,
html
});
console.log('EmailAdminNotification:sent', {
toEmail
});
}
// 读取管理员通知邮箱:优先 KV 设置,其次环境变量
async function getAdminNotifyEmail(env: Bindings): Promise<string> {
if (env.CWD_CONFIG_KV) {
const val = await env.CWD_CONFIG_KV.get('settings:admin_notify_email');
if (val) return val;
await env.CWD_DB.prepare(
'CREATE TABLE IF NOT EXISTS Settings (key TEXT PRIMARY KEY, value TEXT NOT NULL)'
).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('未配置管理员通知邮箱');
}

View File

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

View File

@@ -50,11 +50,10 @@ npm install
]
```
如果`binding`字段不是`CWD_DB`,请修改为`CWD_DB`
* **创建 KV 存储**,如果遇到提示,按回车继续
```bash
npx wrangler kv namespace create CWD_AUTH_KV
npx wrangler kv namespace create CWD_CONFIG_KV
```
运行完成后可以确认一下 `wrangler.jsonc` 中是否有如下配置
```jsonc
@@ -62,10 +61,6 @@ npm install
{
"binding": "CWD_AUTH_KV",
"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) {
if (!this.elements.root) return;
// 昵称错误
const authorInput = this.elements.root.querySelector('input[placeholder*="昵称"]');
const authorInput = this.elements.root.querySelector('input[name="author"]');
this.updateFieldError(authorInput, formErrors?.author);
// 邮箱错误
const emailInput = this.elements.root.querySelector('input[placeholder*="邮箱"]');
const emailInput = this.elements.root.querySelector('input[name="email"]');
this.updateFieldError(emailInput, formErrors?.email);
// 网址错误
const urlInput = this.elements.root.querySelector('input[placeholder*="网址"]');
const urlInput = this.elements.root.querySelector('input[name="url"]');
this.updateFieldError(urlInput, formErrors?.url);
// 内容错误
const contentTextarea = this.elements.root.querySelector('textarea');
this.updateFieldError(contentTextarea, formErrors?.content);
}
@@ -216,7 +212,8 @@ export class CommentForm extends Component {
className: `cwd-form-input ${error ? 'cwd-input-error' : ''}`,
attributes: {
type,
placeholder,
name: fieldName,
value: value || '',
disabled: this.props.submitting,
onInput: (e) => this.handleFieldChange(fieldName, e.target.value),
},
@@ -230,9 +227,9 @@ export class CommentForm extends Component {
* 设置输入框的值
*/
setInputValues(root, form) {
const authorInput = root.querySelector('input[placeholder*="昵称"]');
const emailInput = root.querySelector('input[placeholder*="邮箱"]');
const urlInput = root.querySelector('input[placeholder*="网址"]');
const authorInput = root.querySelector('input[name="author"]');
const emailInput = root.querySelector('input[name="email"]');
const urlInput = root.querySelector('input[name="url"]');
const contentTextarea = root.querySelector('textarea');
if (authorInput) authorInput.value = form.author || '';

View File

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

View File

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