feat: 帖子编辑功能(用户限制)
- 发布后24小时内可编辑 - 最多修改5次 - 编辑按钮仅作者可见 - 显示编辑次数和剩余次数 - 数据库新增 edit_count 和 last_edit_at 字段
This commit is contained in:
@@ -697,10 +697,44 @@ def api_post_detail(post_id):
|
||||
'likes': len(post['likes']),
|
||||
'views': post['views'],
|
||||
'replies': reply_list,
|
||||
'edit_count': post.get('edit_count', 0) or 0,
|
||||
'last_edit_at': post.get('last_edit_at'),
|
||||
'created_at': post['created_at'],
|
||||
'updated_at': post.get('updated_at', post['created_at'])
|
||||
})
|
||||
|
||||
@app.route('/api/posts/<post_id>/edit', methods=['POST'])
|
||||
def api_edit_post(post_id):
|
||||
"""用户编辑自己的帖子"""
|
||||
user = get_current_user()
|
||||
if not user:
|
||||
return jsonify({'error': '请先登录'}), 401
|
||||
|
||||
data = request.json
|
||||
title = data.get('title', '').strip()
|
||||
content = data.get('content', '').strip()
|
||||
tags = data.get('tags')
|
||||
|
||||
if not title or len(title) < 5:
|
||||
return jsonify({'error': '标题至少5个字符'}), 400
|
||||
if not content or len(content) < 10:
|
||||
return jsonify({'error': '内容至少10个字符'}), 400
|
||||
|
||||
# 检查是否可以编辑
|
||||
can_edit, error = post_model.can_edit(post_id, user['id'])
|
||||
if not can_edit:
|
||||
return jsonify({'error': error}), 400
|
||||
|
||||
# 执行编辑
|
||||
success, error = post_model.update_by_user(post_id, user['id'], title, content, tags)
|
||||
if not success:
|
||||
return jsonify({'error': error}), 400
|
||||
|
||||
return jsonify({
|
||||
'success': True,
|
||||
'message': '编辑成功'
|
||||
})
|
||||
|
||||
@app.route('/api/posts/<post_id>/reply', methods=['POST'])
|
||||
def api_reply_post(post_id):
|
||||
user = get_current_user()
|
||||
|
||||
@@ -56,9 +56,47 @@
|
||||
<div id="repliesList" class="mt-6 space-y-4"></div>
|
||||
</main>
|
||||
|
||||
<!-- 编辑弹窗 -->
|
||||
<div id="editModal" class="fixed inset-0 bg-black/50 z-50 hidden items-center justify-center p-4">
|
||||
<div class="bg-white rounded-xl w-full max-w-2xl max-h-[90vh] overflow-hidden flex flex-col">
|
||||
<div class="p-4 border-b flex justify-between items-center">
|
||||
<h3 class="font-bold text-lg">编辑帖子</h3>
|
||||
<button onclick="closeEditModal()" class="text-gray-400 hover:text-gray-600">
|
||||
<i class="ri-close-line text-xl"></i>
|
||||
</button>
|
||||
</div>
|
||||
<div class="p-6 flex-1 overflow-auto">
|
||||
<div id="editWarning" class="mb-4 p-3 bg-yellow-50 text-yellow-700 rounded-lg text-sm hidden"></div>
|
||||
<div class="space-y-4">
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-gray-700 mb-1">标题</label>
|
||||
<input type="text" id="editTitle" class="w-full px-3 py-2 border border-gray-200 rounded-lg focus:ring-2 focus:ring-blue-500">
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-gray-700 mb-1">内容</label>
|
||||
<textarea id="editContent" rows="10" class="w-full px-3 py-2 border border-gray-200 rounded-lg focus:ring-2 focus:ring-blue-500 resize-none"></textarea>
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-gray-700 mb-1">标签(逗号分隔)</label>
|
||||
<input type="text" id="editTags" class="w-full px-3 py-2 border border-gray-200 rounded-lg focus:ring-2 focus:ring-blue-500" placeholder="如: Python, 后端, API">
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="p-4 border-t flex gap-3 justify-end">
|
||||
<button onclick="closeEditModal()" class="px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50">
|
||||
取消
|
||||
</button>
|
||||
<button onclick="saveEdit()" class="px-4 py-2 gradient-bg text-white rounded-lg hover:opacity-90">
|
||||
保存修改
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
let currentUser = null;
|
||||
let currentPostId = null;
|
||||
let currentPost = null;
|
||||
let postLiked = false;
|
||||
|
||||
// 获取帖子ID
|
||||
@@ -82,17 +120,49 @@
|
||||
}
|
||||
|
||||
async function loadPost() {
|
||||
const res = await fetch(`/api/posts/${currentPostId}`);
|
||||
const res = await fetch('/api/posts/' + currentPostId);
|
||||
const post = await res.json();
|
||||
|
||||
if (post.error) {
|
||||
document.getElementById('postContent').innerHTML = `
|
||||
<div class="p-6 text-center text-gray-500">${post.error}</div>
|
||||
`;
|
||||
document.getElementById('postContent').innerHTML = '<div class="p-6 text-center text-gray-500">' + post.error + '</div>';
|
||||
return;
|
||||
}
|
||||
|
||||
currentPost = post;
|
||||
document.title = post.title + ' - 技术论坛';
|
||||
|
||||
// 检查是否可编辑
|
||||
let canEdit = false;
|
||||
let editInfo = '';
|
||||
if (currentUser && post.author.id === currentUser.id) {
|
||||
const createdTime = new Date(post.created_at);
|
||||
const now = new Date();
|
||||
const hoursPassed = (now - createdTime) / (1000 * 60 * 60);
|
||||
const editCount = post.edit_count || 0;
|
||||
|
||||
if (hoursPassed > 24) {
|
||||
editInfo = '发布超过24小时,无法编辑';
|
||||
} else if (editCount >= 5) {
|
||||
editInfo = '已达到最大修改次数(5次)';
|
||||
} else {
|
||||
canEdit = true;
|
||||
editInfo = '剩余修改次数: ' + (5 - editCount) + ' 次,时限: ' + Math.ceil(24 - hoursPassed) + ' 小时';
|
||||
}
|
||||
}
|
||||
|
||||
// 渲染帖子
|
||||
let editBtnHtml = '';
|
||||
if (canEdit) {
|
||||
editBtnHtml = '<button onclick="openEditModal()" class="px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50 flex items-center gap-1"><i class="ri-edit-line"></i> 编辑</button>';
|
||||
} else if (currentUser && post.author.id === currentUser.id && editInfo) {
|
||||
editBtnHtml = '<span class="text-sm text-gray-400">' + editInfo + '</span>';
|
||||
}
|
||||
|
||||
let editCountHtml = '';
|
||||
if (post.edit_count > 0) {
|
||||
editCountHtml = '<span class="text-xs text-gray-400 ml-2">已编辑 ' + post.edit_count + ' 次' + (post.last_edit_at ? ',最后编辑: ' + new Date(post.last_edit_at).toLocaleString() : '') + '</span>';
|
||||
}
|
||||
|
||||
document.getElementById('postContent').innerHTML = `
|
||||
<div class="p-6">
|
||||
<!-- 类型标签 -->
|
||||
@@ -100,6 +170,7 @@
|
||||
<span class="px-2 py-1 rounded text-xs ${post.type === 'discussion' ? 'bg-blue-100 text-blue-600' : 'bg-purple-100 text-purple-600'}">
|
||||
${post.type === 'discussion' ? '技术交流' : '工具分享'}
|
||||
</span>
|
||||
${editCountHtml}
|
||||
</div>
|
||||
|
||||
<!-- 标题 -->
|
||||
@@ -118,11 +189,9 @@
|
||||
<div class="prose text-gray-700 leading-relaxed mb-6 whitespace-pre-wrap">${post.content}</div>
|
||||
|
||||
<!-- 标签 -->
|
||||
${post.tags.length > 0 ? `
|
||||
${post.tags && post.tags.length > 0 ? `
|
||||
<div class="flex flex-wrap gap-2 mb-6">
|
||||
${post.tags.map(tag => `
|
||||
<span class="px-3 py-1 bg-gray-100 text-gray-600 rounded-full text-sm">${tag}</span>
|
||||
`).join('')}
|
||||
${post.tags.map(tag => '<span class="px-3 py-1 bg-gray-100 text-gray-600 rounded-full text-sm">' + tag + '</span>').join('')}
|
||||
</div>
|
||||
` : ''}
|
||||
|
||||
@@ -132,7 +201,8 @@
|
||||
<span><i class="ri-eye-line mr-1"></i> ${post.views} 浏览</span>
|
||||
<span id="likesCount"><i class="ri-heart-line mr-1"></i> ${post.likes} 赞</span>
|
||||
</div>
|
||||
<div class="flex gap-3">
|
||||
<div class="flex gap-3 items-center">
|
||||
${editBtnHtml}
|
||||
<button onclick="likePost()" id="likeBtn" class="px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50 flex items-center gap-1">
|
||||
<i class="ri-heart-line"></i> 赞
|
||||
</button>
|
||||
@@ -170,7 +240,7 @@
|
||||
<button onclick="likeReply('${reply.id}')" class="hover:text-blue-500">
|
||||
<i class="ri-heart-line"></i> ${reply.likes}
|
||||
</button>
|
||||
<button onclick="replyTo('${reply.id}')" class="hover:text-blue-500">
|
||||
<button onclick="replyTo('${reply.author.username}')" class="hover:text-blue-500">
|
||||
<i class="ri-reply-line"></i> 回复
|
||||
</button>
|
||||
</div>
|
||||
@@ -180,6 +250,68 @@
|
||||
`).join('');
|
||||
}
|
||||
|
||||
function openEditModal() {
|
||||
document.getElementById('editTitle').value = currentPost.title;
|
||||
document.getElementById('editContent').value = currentPost.content;
|
||||
document.getElementById('editTags').value = currentPost.tags ? currentPost.tags.join(', ') : '';
|
||||
|
||||
// 显示编辑限制提示
|
||||
const createdTime = new Date(currentPost.created_at);
|
||||
const now = new Date();
|
||||
const hoursPassed = (now - createdTime) / (1000 * 60 * 60);
|
||||
const editCount = currentPost.edit_count || 0;
|
||||
|
||||
document.getElementById('editWarning').innerHTML = '剩余修改次数: ' + (5 - editCount) + ' 次,时限: ' + Math.ceil(24 - hoursPassed) + ' 小时';
|
||||
document.getElementById('editWarning').classList.remove('hidden');
|
||||
|
||||
document.getElementById('editModal').classList.remove('hidden');
|
||||
document.getElementById('editModal').classList.add('flex');
|
||||
}
|
||||
|
||||
function closeEditModal() {
|
||||
document.getElementById('editModal').classList.add('hidden');
|
||||
document.getElementById('editModal').classList.remove('flex');
|
||||
}
|
||||
|
||||
async function saveEdit() {
|
||||
const title = document.getElementById('editTitle').value.trim();
|
||||
const content = document.getElementById('editContent').value.trim();
|
||||
const tagsStr = document.getElementById('editTags').value.trim();
|
||||
const tags = tagsStr ? tagsStr.split(',').map(t => t.trim()).filter(t => t) : [];
|
||||
|
||||
if (!title || title.length < 5) {
|
||||
alert('标题至少5个字符');
|
||||
return;
|
||||
}
|
||||
if (!content || content.length < 10) {
|
||||
alert('内容至少10个字符');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await fetch('/api/posts/' + currentPostId + '/edit', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Authorization': 'Bearer ' + localStorage.getItem('token'),
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({ title, content, tags })
|
||||
});
|
||||
|
||||
const data = await res.json();
|
||||
|
||||
if (data.success) {
|
||||
closeEditModal();
|
||||
loadPost();
|
||||
alert('编辑成功!');
|
||||
} else {
|
||||
alert(data.error || '编辑失败');
|
||||
}
|
||||
} catch (err) {
|
||||
alert('网络错误');
|
||||
}
|
||||
}
|
||||
|
||||
async function submitReply() {
|
||||
if (!currentUser) {
|
||||
alert('请先登录');
|
||||
@@ -193,10 +325,10 @@
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await fetch(`/api/posts/${currentPostId}/reply`, {
|
||||
const res = await fetch('/api/posts/' + currentPostId + '/reply', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Authorization': `Bearer ${localStorage.getItem('token')}`,
|
||||
'Authorization': 'Bearer ' + localStorage.getItem('token'),
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({ content })
|
||||
@@ -221,10 +353,10 @@
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await fetch(`/api/posts/${currentPostId}/like`, {
|
||||
const res = await fetch('/api/posts/' + currentPostId + '/like', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Authorization': `Bearer ${localStorage.getItem('token')}`
|
||||
'Authorization': 'Bearer ' + localStorage.getItem('token')
|
||||
}
|
||||
});
|
||||
const data = await res.json();
|
||||
@@ -241,7 +373,7 @@
|
||||
btn.classList.remove('border-red-300', 'text-red-500');
|
||||
}
|
||||
|
||||
countEl.innerHTML = `<i class="ri-heart-line mr-1"></i> ${data.likes_count} 赞`;
|
||||
countEl.innerHTML = '<i class="ri-heart-line mr-1"></i> ' + data.likes_count + ' 赞';
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(err);
|
||||
@@ -255,13 +387,12 @@
|
||||
});
|
||||
}
|
||||
|
||||
function replyTo(replyId) {
|
||||
function replyTo(username) {
|
||||
document.getElementById('replyContent').value = '@' + username + ' ';
|
||||
document.getElementById('replyContent').focus();
|
||||
document.getElementById('replyContent').placeholder = '回复中...';
|
||||
}
|
||||
|
||||
function likeReply(replyId) {
|
||||
// TODO: 实现回复点赞
|
||||
alert('功能开发中');
|
||||
}
|
||||
</script>
|
||||
|
||||
66
models.py
66
models.py
@@ -55,6 +55,8 @@ class Database:
|
||||
views INTEGER DEFAULT 0,
|
||||
is_pinned INTEGER DEFAULT 0,
|
||||
is_hidden INTEGER DEFAULT 0,
|
||||
edit_count INTEGER DEFAULT 0,
|
||||
last_edit_at TEXT,
|
||||
created_at TEXT,
|
||||
updated_at TEXT,
|
||||
FOREIGN KEY (author_id) REFERENCES users(id)
|
||||
@@ -281,6 +283,70 @@ class PostModel:
|
||||
conn.commit()
|
||||
return new_pin
|
||||
|
||||
def can_edit(self, post_id, user_id):
|
||||
"""检查用户是否可以编辑帖子"""
|
||||
post = self.get_by_id(post_id)
|
||||
if not post:
|
||||
return False, '帖子不存在'
|
||||
|
||||
# 检查是否是作者
|
||||
if post['author_id'] != user_id:
|
||||
return False, '只能编辑自己的帖子'
|
||||
|
||||
# 检查时间限制(24小时内)
|
||||
created_time = datetime.datetime.fromisoformat(post['created_at'])
|
||||
now = datetime.datetime.now()
|
||||
hours_passed = (now - created_time).total_seconds() / 3600
|
||||
|
||||
if hours_passed > 24:
|
||||
return False, '超过24小时,无法编辑'
|
||||
|
||||
# 检查修改次数限制(最多5次)
|
||||
edit_count = post.get('edit_count', 0) or 0
|
||||
if edit_count >= 5:
|
||||
return False, '已达到最大修改次数(5次)'
|
||||
|
||||
return True, None
|
||||
|
||||
def update_by_user(self, post_id, user_id, title=None, content=None, tags=None):
|
||||
"""用户编辑帖子(带限制检查)"""
|
||||
can_edit, error = self.can_edit(post_id, user_id)
|
||||
if not can_edit:
|
||||
return False, error
|
||||
|
||||
now = datetime.datetime.now().isoformat()
|
||||
|
||||
with self.db.get_conn() as conn:
|
||||
# 获取当前修改次数
|
||||
row = conn.execute('SELECT edit_count FROM posts WHERE id = ?', (post_id,)).fetchone()
|
||||
edit_count = (row['edit_count'] or 0) + 1
|
||||
|
||||
update_fields = []
|
||||
values = []
|
||||
|
||||
if title:
|
||||
update_fields.append('title = ?')
|
||||
values.append(title)
|
||||
if content:
|
||||
update_fields.append('content = ?')
|
||||
values.append(content)
|
||||
if tags:
|
||||
update_fields.append('tags = ?')
|
||||
values.append(json.dumps(tags))
|
||||
|
||||
update_fields.append('edit_count = ?')
|
||||
values.append(edit_count)
|
||||
update_fields.append('last_edit_at = ?')
|
||||
values.append(now)
|
||||
update_fields.append('updated_at = ?')
|
||||
values.append(now)
|
||||
values.append(post_id)
|
||||
|
||||
conn.execute(f"UPDATE posts SET {', '.join(update_fields)} WHERE id = ?", values)
|
||||
conn.commit()
|
||||
|
||||
return True, None
|
||||
|
||||
def get_tags_stats(self):
|
||||
with self.db.get_conn() as conn:
|
||||
rows = conn.execute('SELECT tags FROM posts').fetchall()
|
||||
|
||||
Reference in New Issue
Block a user