source: Klonkt/src/routes/comments.js@ c9c6a2d

main
Last change on this file since c9c6a2d was c9c6a2d, checked in by roboburr <roboburr@…>, 3 months ago

feat(meldingen): notifications — reply on comment, comment on post, like on post

For every logged-in user (Google visitors/fans and admin). Bell icon in the
header with unread counter + notifications page /notifications (via user menu
desktop + profile sheet mobile; badge also on the mobile Profile tab). Opening =
read. Triggers in comments (reply→comment author, top-level→post author) and
like (→post author); notify() skips notifying yourself. Table notifications
+ NotificationService. NL/EN/DE.

Co-Authored-By: Claude <noreply@…>

  • Property mode set to 100644
File size: 5.3 KB
Line 
1/**
2 * Comments — phase G v1.
3 *
4 * POST /comments -> create a comment on a post (auth required)
5 * POST /comments/:id/delete -> delete (own, or god/site-admin)
6 *
7 * Threading: 1 level deep (top-level + replies). Replies-of-replies fold up
8 * into the same parent (UI keeps it shallow).
9 *
10 * Status: auto-approved for logged-in users (trust mode). The schema's
11 * `status` column stays so we can switch to moderation later without changing
12 * shape. Anonymous comments (require_login_to_comment = 0 + no user) come
13 * later — for now we always require login.
14 */
15
16import express from 'express';
17import { v4 as uuid } from 'uuid';
18import db from '../config/database.js';
19import { requireAuth } from '../middleware/auth.js';
20import PermissionsService from '../services/PermissionsService.js';
21import { notify } from '../services/NotificationService.js';
22
23const router = express.Router();
24
25// Limits
26const MAX_LEN = 4000;
27const MIN_LEN = 1;
28
29router.post('/', requireAuth, (req, res) => {
30 const site = res.locals.site;
31 if (!site) return res.status(404).send('Site required');
32
33 const postSlug = (req.body.post_slug || '').trim();
34 const rawContent = (req.body.content || '').trim();
35 const parentId = (req.body.parent_comment_id || '').trim() || null;
36
37 if (!postSlug) return res.status(400).send('post_slug required');
38 if (rawContent.length < MIN_LEN) return res.status(400).send('Comment cannot be empty');
39 if (rawContent.length > MAX_LEN) return res.status(413).send(`Comment too long (max ${MAX_LEN} chars)`);
40
41 const post = db.prepare(
42 'SELECT id, slug, title, author_id FROM posts WHERE site_id = ? AND slug = ? AND status = ?'
43 ).get(site.id, postSlug, 'published');
44 if (!post) return res.status(404).send('Post not found');
45
46 if (!PermissionsService.canComment(req.session.user, site, post)) {
47 return res.status(403).send('Comments not allowed');
48 }
49
50 // Validate parent (must belong to this post; collapses replies-of-replies
51 // up to the top-level parent so we never go deeper than 1)
52 let resolvedParent = null;
53 let parentAuthorId = null;
54 if (parentId) {
55 const parent = db.prepare(
56 'SELECT id, parent_comment_id, author_id FROM comments WHERE id = ? AND post_id = ?'
57 ).get(parentId, post.id);
58 if (!parent) return res.status(400).send('Invalid parent comment');
59 resolvedParent = parent.parent_comment_id || parent.id;
60 parentAuthorId = parent.author_id; // ontvanger van de "antwoord"-melding
61 }
62
63 // Status depends on the site's moderation mode.
64 // 'trust' = auto-approve immediately (default).
65 // 'moderate' = pending until an admin reviews in /admin/comments.
66 // Author is the post author or god → always trusted (no point gatekeeping yourself).
67 const isTrustedAuthor = req.session.user.role === 'god'
68 || req.session.user.id === post.author_id;
69 const status = (site.comments_moderation_mode === 'moderate' && !isTrustedAuthor)
70 ? 'pending'
71 : 'approved';
72
73 const commentId = uuid();
74 db.prepare(`
75 INSERT INTO comments (id, post_id, author_id, parent_comment_id, content, status)
76 VALUES (?, ?, ?, ?, ?, ?)
77 `).run(commentId, post.id, req.session.user.id, resolvedParent, rawContent, status);
78
79 // Melding (alleen bij een zichtbare reactie): antwoord → de auteur van de reactie
80 // waarop gereageerd is; top-level reactie → de auteur van de post. notify() slaat
81 // jezelf-notificeren over.
82 if (status === 'approved') {
83 const url = `${res.locals.siteUrlBase || ''}/${post.slug}#comment-${commentId}`;
84 const actorId = req.session.user.id;
85 const actorName = req.session.user.username;
86 if (parentId) {
87 notify({ userId: parentAuthorId, actorId, actorName, type: 'reply', postSlug: post.slug, postTitle: post.title, url });
88 } else {
89 notify({ userId: post.author_id, actorId, actorName, type: 'comment', postSlug: post.slug, postTitle: post.title, url });
90 }
91 }
92
93 // Where to land after submit:
94 // approved → scroll to the new comment
95 // pending → comments anchor + ?pending=1 query so post page can flash a notice
96 const target = status === 'approved'
97 ? `${res.locals.siteUrlBase || ''}/${post.slug}#comment-${commentId}`
98 : `${res.locals.siteUrlBase || ''}/${post.slug}?pending=1#comments`;
99 if (req.headers['hx-request']) {
100 res.setHeader('HX-Redirect', target);
101 return res.send('OK');
102 }
103 res.redirect(target);
104});
105
106router.post('/:id/delete', requireAuth, (req, res) => {
107 const site = res.locals.site;
108 if (!site) return res.status(404).send('Site required');
109
110 const comment = db.prepare(`
111 SELECT c.id, c.author_id, c.post_id, p.slug AS post_slug
112 FROM comments c JOIN posts p ON p.id = c.post_id
113 WHERE c.id = ? AND p.site_id = ?
114 `).get(req.params.id, site.id);
115
116 if (!comment) return res.status(404).send('Not found');
117 if (!PermissionsService.canDeleteComment(req.session.user, comment, site)) {
118 return res.status(403).send('No permission');
119 }
120
121 // Delete the comment plus any replies that hung off it
122 db.prepare('DELETE FROM comments WHERE id = ? OR parent_comment_id = ?')
123 .run(req.params.id, req.params.id);
124
125 if (req.headers['hx-request']) {
126 res.setHeader('HX-Redirect', `${res.locals.siteUrlBase || ''}/${comment.post_slug}#comments`);
127 return res.send('OK');
128 }
129 res.redirect(`${res.locals.siteUrlBase || ''}/${comment.post_slug}#comments`);
130});
131
132export default router;
Note: See TracBrowser for help on using the repository browser.