Skip to content

Node.js based forum software built for the modern web

Add `message` flag type with admin-only moderation (#14678)

Julian Lam86551026ea5f
diff --git a/public/language/en-GB/admin/settings/reputation.json b/public/language/en-GB/admin/settings/reputation.json
index a4fde0d0af..5c8f62293f 100644
--- a/public/language/en-GB/admin/settings/reputation.json
+++ b/public/language/en-GB/admin/settings/reputation.json
@@ -33,6 +33,8 @@
"flags.limit-post-flags-per-day-help": "Set to 0 to disable, (default: 10)",
"flags.limit-user-flags-per-day": "Maximum number of times a user can flag users in a day",
"flags.limit-user-flags-per-day-help": "Set to 0 to disable, (default: 10)",
+ "flags.limit-message-flags-per-day": "Maximum number of times a user can flag chat messages in a day",
+ "flags.limit-message-flags-per-day-help": "Set to 0 to disable, (default: 10)",
"flags.auto-flag-on-downvote-threshold": "Number of downvotes to auto flag posts",
"flags.auto-flag-on-downvote-threshold-help": "Set to 0 to disable, (default: 0)",
"flags.auto-resolve-on-ban": "Automatically resolve all of a user's tickets when they are banned",
diff --git a/public/language/en-GB/error.json b/public/language/en-GB/error.json
index f71e365e6f..887d9d96f4 100644
--- a/public/language/en-GB/error.json
+++ b/public/language/en-GB/error.json
@@ -231,10 +231,13 @@
"invalid-custom-user-field": "Invalid custom user field, \"%1\" is already used by NodeBB",
"post-already-flagged": "You have already flagged this post",
"user-already-flagged": "You have already flagged this user",
+ "message-already-flagged": "You have already flagged this chat message",
"post-flagged-too-many-times": "This post has been flagged by others already",
"user-flagged-too-many-times": "This user has been flagged by others already",
+ "message-flagged-too-many-times": "This chat message has been flagged by others already",
"too-many-post-flags-per-day": "You can only flag %1 post(s) per day",
"too-many-user-flags-per-day": "You can only flag %1 user(s) per day",
+ "too-many-message-flags-per-day": "You can only flag %1 chat message(s) per day",
"cant-flag-privileged": "You are not allowed to flag the profiles or content of privileged users (moderators/global moderators/admins)",
"cant-locate-flag-report": "Cannot locate flag report",
"self-vote": "You cannot vote on your own post",
diff --git a/public/language/en-GB/flags.json b/public/language/en-GB/flags.json
index 7985a69f33..01beb9d224 100644
--- a/public/language/en-GB/flags.json
+++ b/public/language/en-GB/flags.json
@@ -25,6 +25,7 @@
"filter-type-all": "All Content",
"filter-type-post": "Post",
"filter-type-user": "User",
+ "filter-type-message": "Chat Message",
"filter-state": "State",
"filter-assignee": "Assignee",
"filter-cid": "Category",
@@ -43,6 +44,7 @@
"delete-post": "Delete Post",
"purge-post": "Purge Post",
"restore-post": "Restore Post",
+ "delete-message": "Delete Message",
"delete": "Delete Flag",
"user-view": "View Profile",
@@ -54,6 +56,8 @@
"no-notes": "No shared notes.",
"delete-note-confirm": "Are you sure you want to delete this flag note?",
"delete-flag-confirm": "Are you sure you want to delete this flag?",
+ "delete-message-confirm": "Are you sure you want to delete this chat message?",
+ "message-deleted": "Chat Message Deleted",
"note-added": "Note Added",
"note-deleted": "Note Deleted",
"flag-deleted": "Flag Deleted",
diff --git a/public/language/en-GB/notifications.json b/public/language/en-GB/notifications.json
index c0cc9b3d47..53576f60c5 100644
--- a/public/language/en-GB/notifications.json
+++ b/public/language/en-GB/notifications.json
@@ -50,6 +50,7 @@
"user-flagged-user-dual": "<strong>%1</strong> and <strong>%2</strong> flagged a user profile (%3)",
"user-flagged-user-triple": "<strong>%1</strong>, <strong>%2</strong> and <strong>%3</strong> flagged a user profile (%4)",
"user-flagged-user-multiple": "<strong>%1</strong>, <strong>%2</strong> and %3 others flagged a user profile (%4)",
+ "user-flagged-message": "<strong>%1</strong> flagged a chat message in <strong>%2</strong>",
"user-posted-to" : "<strong>%1</strong> posted a reply in <strong>%2</strong>",
"user-posted-to-dual" : "<strong>%1</strong> and <strong>%2</strong> replied in <strong>%3</strong>",
"user-posted-to-triple" : "<strong>%1</strong>, <strong>%2</strong> and <strong>%3</strong> replied in <strong>%4</strong>",
@@ -109,6 +110,7 @@
"notificationType-post-queue": "When a new post is queued",
"notificationType-new-post-flag": "When a post is flagged",
"notificationType-new-user-flag": "When a user is flagged",
+ "notificationType-new-message-flag": "When a chat message is flagged",
"notificationType-new-reward": "When you earn a new reward",
"activitypub.announce": "<strong>%1</strong> shared your post in <strong>%2</strong> to their followers.",
diff --git a/public/openapi/write.yaml b/public/openapi/write.yaml
index a948fac6b7..a7b47e3437 100644
--- a/public/openapi/write.yaml
+++ b/public/openapi/write.yaml
@@ -264,6 +264,8 @@ paths:
$ref: 'write/chats/roomId/messages/mid/raw.yaml'
/chats/{roomId}/messages/{mid}/ip:
$ref: 'write/chats/roomId/messages/mid/ip.yaml'
+ /chats/{roomId}/messages/{mid}/state:
+ $ref: 'write/chats/roomId/messages/mid/state.yaml'
/flags/:
$ref: 'write/flags.yaml'
/flags/{flagId}:
diff --git a/public/openapi/write/chats/roomId/messages/mid.yaml b/public/openapi/write/chats/roomId/messages/mid.yaml
index c899627802..c3862383ac 100644
--- a/public/openapi/write/chats/roomId/messages/mid.yaml
+++ b/public/openapi/write/chats/roomId/messages/mid.yaml
@@ -76,8 +76,8 @@ put:
delete:
tags:
- chats
- summary: delete a chat message
- description: This operation deletes a chat message
+ summary: purge a chat message
+ description: This operation purges a chat message, removing it from the database entirely
parameters:
- in: path
name: roomId
@@ -95,7 +95,7 @@ delete:
example: 2
responses:
'200':
- description: Message successfully deleted
+ description: Message successfully purged
content:
application/json:
schema:
diff --git a/public/openapi/write/chats/roomId/messages/mid/ip.yaml b/public/openapi/write/chats/roomId/messages/mid/ip.yaml
index 2c2af8fb1b..fa16cf9a25 100644
--- a/public/openapi/write/chats/roomId/messages/mid/ip.yaml
+++ b/public/openapi/write/chats/roomId/messages/mid/ip.yaml
@@ -32,4 +32,5 @@ get:
type: object
properties:
ip:
- type: string
\ No newline at end of file
+ type: ['string', 'null']
+ description: message IP address, or null if not available
\ No newline at end of file
diff --git a/public/openapi/write/chats/roomId/messages/mid/state.yaml b/public/openapi/write/chats/roomId/messages/mid/state.yaml
new file mode 100644
index 0000000000..1f1bdb7697
--- /dev/null
+++ b/public/openapi/write/chats/roomId/messages/mid/state.yaml
@@ -0,0 +1,66 @@
+put:
+ tags:
+ - chats
+ summary: restore a chat message
+ description: This operation restores a deleted chat message (clears the deleted flag)
+ parameters:
+ - in: path
+ name: roomId
+ schema:
+ type: number
+ required: true
+ description: a valid chat room id
+ example: 1
+ - in: path
+ name: mid
+ schema:
+ type: number
+ required: true
+ description: a valid message id
+ example: 2
+ responses:
+ '200':
+ description: Message successfully restored
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ status:
+ $ref: ../../../../../components/schemas/Status.yaml#/Status
+ response:
+ type: object
+ properties: {}
+delete:
+ tags:
+ - chats
+ summary: delete a chat message
+ description: This operation soft-deletes a chat message (sets the deleted flag)
+ parameters:
+ - in: path
+ name: roomId
+ schema:
+ type: number
+ required: true
+ description: a valid chat room id
+ example: 1
+ - in: path
+ name: mid
+ schema:
+ type: number
+ required: true
+ description: a valid message id
+ example: 2
+ responses:
+ '200':
+ description: Message successfully deleted
+ content:
+ application/json:
+ schema:
+ type: object
+ properties:
+ status:
+ $ref: ../../../../../components/schemas/Status.yaml#/Status
+ response:
+ type: object
+ properties: {}
diff --git a/public/src/client/chats.js b/public/src/client/chats.js
index 234336173f..4a175f5075 100644
--- a/public/src/client/chats.js
+++ b/public/src/client/chats.js
@@ -21,11 +21,12 @@ define('forum/chats', [
'chat',
'api',
'uploadHelpers',
+ 'modules/flags',
], function (
components, mousetrap, recentChats, create,
manage, messages, userList, messageSearch, pinnedMessages,
events, search, autocomplete, hooks, modals, benchpress, alerts,
- chatModule, api, uploadHelpers
+ chatModule, api, uploadHelpers, flags
) {
const Chats = {
activeAutocomplete: new WeakMap(),
@@ -436,10 +437,21 @@ define('forum/chats', [
case 'unpin':
pinnedMessages.unpin(messageId, roomId);
break;
+ case 'flag':
+ Chats.flagMessage(msgEl.attr('data-mid'), roomId);
+ break;
}
});
};
+ Chats.flagMessage = function (messageId, roomId) {
+ flags.showFlagModal({
+ type: 'message',
+ id: messageId,
+ roomId: roomId,
+ });
+ };
+
Chats.addHotkeys = function () {
mousetrap.bind('ctrl+up', function () {
const activeContact = ('.chats-list .active');
diff --git a/public/src/client/flags/detail.js b/public/src/client/flags/detail.js
index 2479b676f7..33f2fcf8f8 100644
--- a/public/src/client/flags/detail.js
+++ b/public/src/client/flags/detail.js
@@ -138,6 +138,16 @@ define('forum/flags/detail', [
postAction('restore', api.put, `/posts/${ajaxify.data.target.pid}/state`);
break;
+ case 'delete-message': {
+ modals.confirm('[[flags:delete-message-confirm]]', function (confirm) {
+ if (!confirm) {
+ return;
+ }
+ api.del(`/chats/${ajaxify.data.target.roomId}/messages/${ajaxify.data.target.mid}`, {}).then(ajaxify.refresh).catch(alerts.error);
+ });
+ break;
+ }
+
case 'delete-flag': {
modals.confirm('[[flags:delete-flag-confirm]]', function (ok) {
if (ok) {
diff --git a/public/src/modules/flags.js b/public/src/modules/flags.js
index 5eae76d9bb..8eadd36b73 100644
--- a/public/src/modules/flags.js
+++ b/public/src/modules/flags.js
@@ -6,9 +6,11 @@ define('flags', ['hooks', 'components', 'api', 'alerts'], function (hooks, compo
let flagModal;
let flagCommit;
let flagReason;
+ let currentData = {};
Flag.showFlagModal = function (data) {
- data.remote = URL.canParse(data.id) ? new URL(data.id).hostname : false;
+ currentData = data;
+ data.remote = data.id && URL.canParse(data.id) ? new URL(data.id).hostname : false;
app.parseAndTranslate('modals/flag', data, function (html) {
flagModal = html;
@@ -38,7 +40,7 @@ define('flags', ['hooks', 'components', 'api', 'alerts'], function (hooks, compo
reason = flagReason.val();
}
const notifyRemote = $('input[name="flag-notify-remote"]').is(':checked');
- createFlag(data.type, data.id, reason, notifyRemote);
+ createFlag(currentData.type, currentData.id, reason, notifyRemote);
});
flagModal.on('click', '#flag-reason-other', function () {
@@ -86,7 +88,7 @@ define('flags', ['hooks', 'components', 'api', 'alerts'], function (hooks, compo
if (!type || !id || !reason) {
return;
}
- const data = { type: type, id: id, reason: reason, notifyRemote: notifyRemote };
+ const data = { type: type, id: id, reason: reason, notifyRemote: notifyRemote, roomId: currentData.roomId };
api.post('/flags', data, function (err, flagId) {
if (err) {
return alerts.error(err);
@@ -98,6 +100,11 @@ define('flags', ['hooks', 'components', 'api', 'alerts'], function (hooks, compo
const postEl = components.get('post', 'pid', id);
postEl.find('[component="post/flag"]').addClass('hidden').parent().attr('hidden', '');
postEl.find('[component="post/already-flagged"]').removeClass('hidden').parent().attr('hidden', null);
+ } else if (type === 'message') {
+ const msgEl = components.get('chat/message', id);
+ if (msgEl.length) {
+ msgEl.find('[data-action="flag"]').closest('li').addClass('hidden');
+ }
}
hooks.fire('action:flag.create', { flagId: flagId, data: data });
});
diff --git a/src/api/chats.js b/src/api/chats.js
index ff9e8ca3d6..c9883df15e 100644
--- a/src/api/chats.js
+++ b/src/api/chats.js
@@ -447,6 +447,11 @@ chatsAPI.restoreMessage = async (caller, { mid }) => {
await messaging.restoreMessage(mid, caller.uid);
};
+chatsAPI.purgeMessage = async (caller, { mid }) => {
+ await messaging.canDelete(mid, caller.uid);
+ await messaging.purgeMessage(mid);
+};
+
chatsAPI.pinMessage = async (caller, { roomId, mid }) => {
await messaging.canPin(roomId, caller.uid);
await messaging.pinMessage(mid, roomId);
diff --git a/src/api/flags.js b/src/api/flags.js
index ff30978982..9280cad415 100644
--- a/src/api/flags.js
+++ b/src/api/flags.js
@@ -11,12 +11,13 @@ flagsApi.create = async (caller, data) => {
throw new Error('[[error:invalid-data]]');
}
- const { type, id, reason, notifyRemote } = data;
+ const { type, id, reason, notifyRemote, roomId } = data;
await flags.validate({
uid: caller.uid,
type: type,
id: id,
+ roomId: roomId,
});
const flagObj = await flags.create(type, id, caller.uid, reason, undefined, undefined, notifyRemote);
diff --git a/src/controllers/accounts/settings.js b/src/controllers/accounts/settings.js
index 331fad7508..dff1e62f8f 100644
--- a/src/controllers/accounts/settings.js
+++ b/src/controllers/accounts/settings.js
@@ -180,6 +180,9 @@ async function getNotificationSettings(userData) {
if (privileges.isAdmin || privileges.isGlobalMod) {
privilegedTypes.push('notificationType_new-user-flag');
}
+ if (privileges.isAdmin) {
+ privilegedTypes.push('notificationType_new-message-flag');
+ }
const results = await plugins.hooks.fire('filter:user.notificationTypes', {
types: notifications.baseTypes.slice(),
privilegedTypes: privilegedTypes,
diff --git a/src/controllers/mods.js b/src/controllers/mods.js
index 433f1d7474..28b3e8bc8f 100644
--- a/src/controllers/mods.js
+++ b/src/controllers/mods.js
@@ -33,7 +33,7 @@ modsController.flags.list = async function (req, res) {
quick: ['mine'],
sort: ['newest', 'oldest', 'reports', 'upvotes', 'downvotes', 'replies'],
state: ['open', 'wip', 'resolved', 'rejected'],
- type: ['post', 'user'],
+ type: ['post', 'user', 'message'],
};
const [isAdminOrGlobalMod, moderatedCids, { filters: allFilters }, { sorts: allSorts }] = await Promise.all([
@@ -126,6 +126,7 @@ modsController.flags.list = async function (req, res) {
modsController.flags.detail = async function (req, res, next) {
const results = await utils.promiseParallel({
+ isAdmin: user.isAdministrator(req.uid),
isAdminOrGlobalMod: user.isAdminOrGlobalMod(req.uid),
moderatedCids: user.getModeratedCids(req.uid),
flagData: flags.get(req.params.flagId),
@@ -136,6 +137,11 @@ modsController.flags.detail = async function (req, res, next) {
return next(); // 404
}
+ // message flags require admin access regardless of global mod status
+ if (results.flagData.type === 'message' && !results.isAdmin) {
+ return next();
+ }
+
// extra checks for plain moderators
if (!results.isAdminOrGlobalMod) {
if (results.flagData.type === 'user') {
@@ -169,6 +175,8 @@ modsController.flags.detail = async function (req, res, next) {
const modUids = (await privileges.categories.getUidsWithPrivilege([cid], 'moderate'))[0];
uids = _.uniq(uids.concat(modUids));
}
+ } else if (flagData.type === 'message') {
+ uids = admins;
}
const userData = await user.getUsersData(uids);
return await user.hidePrivateData(userData.filter(u => u && u.userslug), uid);
@@ -181,11 +189,13 @@ modsController.flags.detail = async function (req, res, next) {
results.flagData.type_path = 'uid';
} else if (results.flagData.type === 'post') {
results.flagData.type_path = 'post';
+ } else if (results.flagData.type === 'message') {
+ results.flagData.type_path = 'message';
}
res.render('flags/detail', Object.assign(results.flagData, {
assignees: assignees,
- type_bool: ['post', 'user', 'empty'].reduce((memo, cur) => {
+ type_bool: ['post', 'user', 'message', 'empty'].reduce((memo, cur) => {
if (cur !== 'empty') {
memo[cur] = results.flagData.type === cur && (
!results.flagData.target ||
diff --git a/src/controllers/write/chats.js b/src/controllers/write/chats.js
index 2f00cb586c..a52183575c 100644
--- a/src/controllers/write/chats.js
+++ b/src/controllers/write/chats.js
@@ -207,6 +207,13 @@ Chats.messages.delete = async (req, res) => {
helpers.formatApiResponse(200, res);
};
+Chats.messages.purge = async (req, res) => {
+ const { mid } = req.params;
+ await api.chats.purgeMessage(req, { mid });
+
+ helpers.formatApiResponse(200, res);
+};
+
Chats.messages.restore = async (req, res) => {
const { mid } = req.params;
await api.chats.restoreMessage(req, { mid });
diff --git a/src/controllers/write/flags.js b/src/controllers/write/flags.js
index 786159ea62..1636e02c9a 100644
--- a/src/controllers/write/flags.js
+++ b/src/controllers/write/flags.js
@@ -7,8 +7,8 @@ const helpers = require('../helpers');
const Flags = module.exports;
Flags.create = async (req, res) => {
- const { type, id, reason, notifyRemote } = req.body;
- const flagObj = await api.flags.create(req, { type, id, reason, notifyRemote });
+ const { type, id, reason, notifyRemote, roomId } = req.body;
+ const flagObj = await api.flags.create(req, { type, id, reason, notifyRemote, roomId });
helpers.formatApiResponse(200, res, await user.isPrivileged(req.uid) ? flagObj : undefined);
};
diff --git a/src/flags.js b/src/flags.js
index 5013097373..80a7586c0b 100644
--- a/src/flags.js
+++ b/src/flags.js
@@ -18,6 +18,7 @@ const plugins = require('./plugins');
const utils = require('./utils');
const batch = require('./batch');
const translator = require('./translator');
+const messaging = require('./messaging');
const Flags = module.exports;
@@ -111,12 +112,13 @@ Flags.get = async function (flagId) {
if (!base) {
throw new Error('[[error:no-flag]]');
}
+ const readableType = base.type === 'message' ? 'Chat message' : base.type.charAt(0).toUpperCase() + base.type.slice(1);
const flagObj = {
state: 'open',
assignee: null,
...base,
datetimeISO: utils.toISOString(base.datetime),
- target_readable: `${base.type.charAt(0).toUpperCase() + base.type.slice(1)} ${base.targetId}`,
+ target_readable: `${readableType} ${base.targetId}`,
target: await Flags.getTarget(base.type, base.targetId, 0),
notes,
reports,
@@ -220,8 +222,9 @@ Flags.list = async function (data) {
}
});
+ const readableType = flagObj.type === 'message' ? 'Chat message' : flagObj.type.charAt(0).toUpperCase() + flagObj.type.slice(1);
return Object.assign(flagObj, {
- target_readable: `${flagObj.type.charAt(0).toUpperCase() + flagObj.type.slice(1)} ${flagObj.targetId}`,
+ target_readable: `${readableType} ${flagObj.targetId}`,
datetimeISO: utils.toISOString(flagObj.datetime),
});
}));
@@ -321,6 +324,11 @@ Flags.validate = async function (payload) {
if (!editable && !meta.config['reputation:disabled'] && reporter.reputation < meta.config['min:rep:flag']) {
throw new Error(`[[error:not-enough-reputation-to-flag, ${meta.config['min:rep:flag']}]]`);
}
+ } else if (payload.type === 'message') {
+ const canView = await messaging.canViewMessage([parseInt(payload.id, 10)], payload.roomId, payload.uid);
+ if (!canView[0]) {
+ throw new Error('[[error:no-privileges]]');
+ }
} else {
throw new Error('[[error:invalid-data]]');
}
@@ -630,27 +638,6 @@ Flags.exists = async function (type, id, uid) {
return await db.isSortedSetMember('flags:hash', [type, id, uid].join(':'));
};
-Flags.canView = async (flagId, uid) => {
- const exists = await db.isSortedSetMember('flags:datetime', flagId);
- if (!exists) {
- return false;
- }
-
- const [{ type, targetId }, isAdminOrGlobalMod] = await Promise.all([
- db.getObject(`flag:${flagId}`),
- user.isAdminOrGlobalMod(uid),
- ]);
-
- if (type === 'post') {
- const cid = await Flags.getTargetCid(type, targetId);
- const isModerator = await user.isModerator(uid, cid);
-
- return isAdminOrGlobalMod || isModerator;
- }
-
- return isAdminOrGlobalMod;
-};
-
Flags.canFlag = async function (type, id, uid, skipLimitCheck = false) {
const limit = meta.config['flags:limitPerTarget'];
if (!skipLimitCheck && limit > 0) {
@@ -685,11 +672,39 @@ Flags.canFlag = async function (type, id, uid, skipLimitCheck = false) {
}
break;
+ case 'message':
+ return true;
+
default:
throw new Error('[[error:invalid-data]]');
}
};
+Flags.canView = async (flagId, uid) => {
+ const exists = await db.isSortedSetMember('flags:datetime', flagId);
+ if (!exists) {
+ return false;
+ }
+
+ const [{ type, targetId }, isAdminOrGlobalMod] = await Promise.all([
+ db.getObject(`flag:${flagId}`),
+ user.isAdminOrGlobalMod(uid),
+ ]);
+
+ if (type === 'message') {
+ return user.isAdministrator(uid);
+ }
+
+ if (type === 'post') {
+ const cid = await Flags.getTargetCid(type, targetId);
+ const isModerator = await user.isModerator(uid, cid);
+
+ return isAdminOrGlobalMod || isModerator;
+ }
+
+ return isAdminOrGlobalMod;
+};
+
Flags.getTarget = async function (type, id, uid) {
if (type === 'user') {
const userData = await user.getUserData(id);
@@ -704,6 +719,10 @@ Flags.getTarget = async function (type, id, uid) {
postData = await topics.addPostData([postData], uid);
return postData[0];
}
+ if (type === 'message') {
+ const message = await messaging.getMessageData(parseInt(id, 10), uid, await messaging.getRoomIdByMid(id));
+ return message && message[0] ? message[0] : {};
+ }
throw new Error('[[error:invalid-data]]');
};
@@ -720,6 +739,8 @@ Flags.targetExists = async function (type, id) {
}
}
return await user.exists(id);
+ } else if (type === 'message') {
+ return await messaging.messageExists(id);
}
throw new Error('[[error:invalid-data]]');
};
@@ -732,6 +753,14 @@ Flags.getTargetUid = async function (type, id) {
if (type === 'post') {
return await posts.getPostField(id, 'uid');
}
+ if (type === 'message') {
+ const roomId = await messaging.getRoomIdByMid(id);
+ if (!roomId) {
+ return 0;
+ }
+ const uid = await messaging.getMessageField(id, 'fromuid');
+ return uid ? parseInt(uid, 10) : 0;
+ }
return id;
};
@@ -960,6 +989,23 @@ Flags.notify = async function (flagObj, uid, notifySelf = false) {
from: uid,
mergeId: `notifications:user-flagged-user|${flagObj.targetId}`,
});
+ } else if (flagObj.type === 'message') {
+ const roomId = await messaging.getRoomIdByMid(flagObj.targetId);
+ const roomData = roomId ? await messaging.getRoomData(roomId) : null;
+ const targetDisplayname = await user.getNotificationDisplayname(flagObj.targetUid);
+ let bodyLong = String(flagObj.target?.content || '');
+ if (bodyLong && bodyLong.length > 500) {
+ bodyLong = bodyLong.substring(0, 497) + '...';
+ }
+ notifObj = await notifications.create({
+ type: 'new-message-flag',
+ bodyShort: translator.compile('notifications:user-flagged-message', displayname, roomData?.roomName || targetDisplayname),
+ bodyLong: bodyLong,
+ path: `/flags/${flagObj.flagId}`,
+ nid: `flag:message:${flagObj.targetId}:${uid}`,
+ from: uid,
+ mergeId: `notifications:user-flagged-message|${flagObj.targetId}`,
+ });
} else {
throw new Error('[[error:invalid-data]]');
}
diff --git a/src/messaging/data.js b/src/messaging/data.js
index 40d0b2aca6..c1a360520c 100644
--- a/src/messaging/data.js
+++ b/src/messaging/data.js
@@ -45,6 +45,20 @@ module.exports = function (Messaging) {
await db.setObject(`message:${mid}`, data);
};
+ Messaging.getRoomIdByMid = async (mid) => {
+ const roomId = await Messaging.getMessageField(mid, 'roomId');
+ return roomId ? parseInt(roomId, 10) : null;
+ };
+
+ Messaging.getMessageData = async (mid, uid, roomId) => {
+ roomId = roomId || await Messaging.getRoomIdByMid(mid);
+ if (!roomId) {
+ return [];
+ }
+ const message = await Messaging.getMessagesData([mid], uid, roomId, false);
+ return message;
+ };
+
Messaging.getMessagesData = async (mids, uid, roomId, isNew) => {
let messages = await Messaging.getMessagesFields(mids, []);
messages = messages
diff --git a/src/messaging/delete.js b/src/messaging/delete.js
index ef3f7a3fd8..9f5f9ca678 100644
--- a/src/messaging/delete.js
+++ b/src/messaging/delete.js
@@ -1,5 +1,6 @@
'use strict';
+const db = require('../database');
const sockets = require('../socket.io');
const plugins = require('../plugins');
const activitypub = require('../activitypub');
@@ -7,6 +8,18 @@ const activitypub = require('../activitypub');
module.exports = function (Messaging) {
Messaging.deleteMessage = async (mid, uid) => await doDeleteRestore(mid, 1, uid);
Messaging.restoreMessage = async (mid, uid) => await doDeleteRestore(mid, 0, uid);
+ Messaging.purgeMessage = async (mid) => {
+ const msgData = await Messaging.getMessageFields(mid, [
+ 'mid', 'fromuid', 'roomId', 'deleted', 'system',
+ ]);
+ if (!msgData) {
+ return;
+ }
+ await db.delete(`message:${mid}`);
+ await db.sortedSetRemove(`chat:room:${msgData.roomId}:mids`, mid);
+
+ plugins.hooks.fire('action:messaging.delete', { message: msgData });
+ };
async function doDeleteRestore(mid, state, uid) {
const field = state ? 'deleted' : 'restored';
diff --git a/src/messaging/index.js b/src/messaging/index.js
index 212db2df52..310064633f 100644
--- a/src/messaging/index.js
+++ b/src/messaging/index.js
@@ -547,6 +547,14 @@ Messaging.canViewMessage = async (mids, roomId, uid) => {
mids = [mids];
single = true;
}
+
+ // Admins get blanket permission to read messages (for flagging/moderation purposes)
+ if (await user.isAdministrator(uid)) {
+ const midList = Array.isArray(mids) ? mids : [mids];
+ const canView = midList.map(() => true);
+ return single ? canView.pop() : canView;
+ }
+
const isPublic = parseInt(await db.getObjectField(`chat:room:${roomId}`, 'public'), 10) === 1;
const [midTimestamps, userTimestamp] = await Promise.all([
db.sortedSetScores(`chat:room:${roomId}:mids`, mids),
diff --git a/src/middleware/assert.js b/src/middleware/assert.js
index db896fda15..f43724a7e8 100644
--- a/src/middleware/assert.js
+++ b/src/middleware/assert.js
@@ -144,7 +144,7 @@ Assert.room = helpers.try(async (req, res, next) => {
return controllerHelpers.formatApiResponse(404, res, new Error('[[error:chat-room-does-not-exist]]'));
}
- if (!inRoom) {
+ if (!inRoom && !await user.isAdministrator(req.uid)) {
return controllerHelpers.formatApiResponse(403, res, new Error('[[error:no-privileges]]'));
}
diff --git a/src/notifications.js b/src/notifications.js
index 342c28c84e..59d39be82e 100644
--- a/src/notifications.js
+++ b/src/notifications.js
@@ -60,6 +60,7 @@ Notifications.privilegedTypes = [
'notificationType_post-queue',
'notificationType_new-post-flag',
'notificationType_new-user-flag',
+ 'notificationType_new-message-flag',
];
const notificationPruneCutoff = 2592000000; // one month
diff --git a/src/routes/write/chats.js b/src/routes/write/chats.js
index ea52de5bd3..147da6b7e6 100644
--- a/src/routes/write/chats.js
+++ b/src/routes/write/chats.js
@@ -44,7 +44,9 @@ module.exports = function () {
setupApiRoute(router, 'get', '/:roomId/messages/:mid', [...middlewares, middleware.assert.room, middleware.assert.message], controllers.write.chats.messages.get);
setupApiRoute(router, 'put', '/:roomId/messages/:mid', [...middlewares, middleware.assert.room, middleware.assert.message], controllers.write.chats.messages.edit);
setupApiRoute(router, 'post', '/:roomId/messages/:mid', [...middlewares, middleware.assert.room, middleware.assert.message], controllers.write.chats.messages.restore);
- setupApiRoute(router, 'delete', '/:roomId/messages/:mid', [...middlewares, middleware.assert.room, middleware.assert.message], controllers.write.chats.messages.delete);
+ setupApiRoute(router, 'put', '/:roomId/messages/:mid/state', [...middlewares, middleware.assert.room, middleware.assert.message], controllers.write.chats.messages.restore);
+ setupApiRoute(router, 'delete', '/:roomId/messages/:mid', [...middlewares, middleware.assert.room, middleware.assert.message], controllers.write.chats.messages.purge);
+ setupApiRoute(router, 'delete', '/:roomId/messages/:mid/state', [...middlewares, middleware.assert.room, middleware.assert.message], controllers.write.chats.messages.delete);
setupApiRoute(router, 'get', '/:roomId/messages/:mid/raw', [...middlewares, middleware.assert.room], controllers.write.chats.messages.getRaw);
setupApiRoute(router, 'get', '/:roomId/messages/:mid/ip', [...middlewares, middleware.assert.room], controllers.write.chats.messages.getIpAddress);
diff --git a/src/views/admin/settings/reputation.tpl b/src/views/admin/settings/reputation.tpl
index c4e093eb50..1195c7c717 100644
--- a/src/views/admin/settings/reputation.tpl
+++ b/src/views/admin/settings/reputation.tpl
@@ -119,6 +119,14 @@
</p>
</div>
+ <div class="mb-3">
+ <label class="form-label" for="flags:messageFlagsPerDay">{{tx("admin/settings/reputation:flags.limit-message-flags-per-day")}}</label>
+ <input type="number" min="0" class="form-control" data-field="flags:messageFlagsPerDay" id="flags:messageFlagsPerDay">
+ <p class="form-text">
+ {{tx("admin/settings/reputation:flags.limit-message-flags-per-day-help")}}
+ </p>
+ </div>
+
<div class="mb-3">
<label class="form-label" for="flags:autoFlagOnDownvoteThreshold">{{tx("admin/settings/reputation:flags.auto-flag-on-downvote-threshold")}}</label>
diff --git a/src/views/flags/detail.tpl b/src/views/flags/detail.tpl
index e5a5375d19..480b5a34b0 100644
--- a/src/views/flags/detail.tpl
+++ b/src/views/flags/detail.tpl
@@ -3,10 +3,12 @@
<div class="d-flex flex-column flex-md-row">
<div class="flex-shrink-0 d-flex flex-column gap-3 border-end-md text-sm mb-3 pe-4" style="flex-basis: 240px !important;">
<div class="d-grid gap-1">
+ {{{ if !type_bool.message }}}
<a class="btn btn-ghost btn-sm ff-secondary border d-flex gap-2 align-items-center" href="{config.relative_path}/{type_path}/{targetId}">
<i class="fa fa-fw fa-external-link text-primary"></i>
{{tx("flags:go-to-target")}}
</a>
+ {{{ end }}}
{{{ if target.uid }}}
<div class="dropdown dropend" data-uid="{target.uid}">
@@ -51,6 +53,10 @@
<a class="d-flex gap-2 align-items-center btn btn-sm btn-outline-success border border-secondary-subtle text-start" href="#" data-action="restore-post"><i class="fa fa-fw fa-reply"></i><i class="fa fa-fw fa-trash"></i> {{tx("flags:restore-post")}}</a>
{{{ end }}}
{{{ end }}}
+
+ {{{ if type_bool.message }}}
+ <a class="d-flex gap-2 align-items-center btn btn-sm btn-outline-danger border border-secondary-subtle text-start" href="#" data-action="delete-message"><i class="fa fa-fw fa-trash"></i> {{tx("flags:delete-message")}}</a>
+ {{{ end }}}
</div>
<form class="d-flex flex-column gap-3" id="attributes">
@@ -130,6 +136,15 @@
<blockquote>{{{ if target.aboutme }}}{target.aboutme}{{{ else }}}<em>{{tx("flags:target-aboutme-empty")}}</em>{{{ end }}}</blockquote>
{{{ end }}}
+ {{{ if type_bool.message }}}
+ <div class="d-flex gap-2 align-items-center">
+ <a class="d-flex text-decoration-none" href="{config.relative_path}/user/{target.user.userslug}">{{buildAvatar(target.user, "16px", true)}}</a>
+ <a href="{config.relative_path}/user/{target.user.userslug}">{target.user.username}</a>
+ <span class="timeago text-muted" title="{target.timestampISO}"></span>
+ </div>
+ <blockquote>{{{ if target.txContent }}}{{tx(target.content)}}{{{ else }}}{target.content}{{{ end }}}</blockquote>
+ {{{ end }}}
+
{{{ if type_bool.empty }}}
<div class="alert alert-warning" role="alert">{{tx("flags:target-purged")}}</div>
{{{ end }}}
diff --git a/src/views/partials/chats/message.tpl b/src/views/partials/chats/message.tpl
index f125837ce2..216c7b5878 100644
--- a/src/views/partials/chats/message.tpl
+++ b/src/views/partials/chats/message.tpl
@@ -52,6 +52,11 @@
<li class="dropdown-divider"></li>
{{{ end }}}
+ {{{ if !./isOwner }}}
+ <li>
+ <a href="#" class="dropdown-item rounded-1" data-action="flag" data-mid="{messages.mid}" role="menuitem"><span class="d-inline-flex align-items-center gap-2"><i class="fa fa-fw fa-flag text-muted"></i> {{tx("flags:report")}}</span></a>
+ </li>
+ {{{ end }}}
{{{ if isAdminOrGlobalMod }}}
<li>
<a href="#" class="dropdown-item rounded-1 chat-ip-button" role="menuitem">
diff --git a/src/views/partials/flags/filters.tpl b/src/views/partials/flags/filters.tpl
index 20462ee394..7fdcd49086 100644
--- a/src/views/partials/flags/filters.tpl
+++ b/src/views/partials/flags/filters.tpl
@@ -80,6 +80,7 @@
<li class="dropdown-item rounded-1" data-name="type" data-value="all" role="menuitem">{{tx("flags:filter-type-all")}}</li>
<li class="dropdown-item rounded-1" data-name="type" data-value="post" role="menuitem">{{tx("flags:filter-type-post")}}</li>
<li class="dropdown-item rounded-1" data-name="type" data-value="user" role="menuitem">{{tx("flags:filter-type-user")}}</li>
+ <li class="dropdown-item rounded-1" data-name="type" data-value="message" role="menuitem">{{tx("flags:filter-type-message")}}</li>
</ul>
</div>
diff --git a/test/api/schema.js b/test/api/schema.js
index cbd45856f0..b2cae773fb 100644
--- a/test/api/schema.js
+++ b/test/api/schema.js
@@ -298,13 +298,63 @@ async function setupData() {
await flags.appendNote(flagId, 1, 'test note', 1626446956652);
await flags.create('post', 2, unprivUid, 'sample reasons', Date.now()); // for testing flag notes (since flag 1 deleted)
- // Create a new chat room & send a message
- const roomId = await messaging.newRoom(adminUid, { uids: [unprivUid] });
+ // Create a chat room & multiple messages for chat deletion/restoration tests
+ const chatRoomId = await messaging.newRoom(adminUid, { uids: [unprivUid] });
await messaging.sendMessage({
- roomId,
+ roomId: chatRoomId,
uid: adminUid,
content: 'this is a chat message',
});
+ // Create a second message for permanent delete test
+ const secondMsg = await messaging.sendMessage({
+ roomId: chatRoomId,
+ uid: adminUid,
+ content: 'this is another chat message',
+ });
+ // Create a third message for POST /mid restore test (soft-delete it)
+ const restorePostMsg = await messaging.sendMessage({
+ roomId: chatRoomId,
+ uid: adminUid,
+ content: 'this is a message for POST restore testing',
+ });
+ await messaging.deleteMessage(restorePostMsg.mid, adminUid);
+ // Create a fourth message for PUT /mid/state restore test (soft-delete it)
+ const restoreStateMsg = await messaging.sendMessage({
+ roomId: chatRoomId,
+ uid: adminUid,
+ content: 'this is a message for PUT state restore testing',
+ });
+ await messaging.deleteMessage(restoreStateMsg.mid, adminUid);
+
+ // Get the mid of the first message for test mock data
+ const [firstMsg] = await messaging.getMessages({ callerUid: adminUid, uid: adminUid, roomId: chatRoomId });
+ // Get the mid of the second message (for permanent delete test)
+ const [secondMsgData] = await messaging.getMessagesData([secondMsg.mid], adminUid, chatRoomId);
+ // Get the mid of the POST restore message
+ const [restorePostMsgData] = await messaging.getMessagesData([restorePostMsg.mid], adminUid, chatRoomId);
+ // Get the mid of the PUT state restore message
+ const [restoreStateMsgData] = await messaging.getMessagesData([restoreStateMsg.mid], adminUid, chatRoomId);
+
+ mocks.put['/chats/{roomId}/messages/{mid}/state'] = [
+ { in: 'path', name: 'roomId', example: chatRoomId },
+ { in: 'path', name: 'mid', example: restoreStateMsgData.mid },
+ ];
+ mocks.delete['/chats/{roomId}/messages/{mid}/state'] = [
+ { in: 'path', name: 'roomId', example: chatRoomId },
+ { in: 'path', name: 'mid', example: firstMsg.mid },
+ ];
+ mocks.delete['/chats/{roomId}/messages/{mid}'] = [
+ { in: 'path', name: 'roomId', example: chatRoomId },
+ { in: 'path', name: 'mid', example: secondMsgData.mid },
+ ];
+ mocks.post['/chats/{roomId}/messages/{mid}'] = [
+ { in: 'path', name: 'roomId', example: chatRoomId },
+ { in: 'path', name: 'mid', example: restorePostMsgData.mid },
+ ];
+ mocks.get['/chats/{roomId}/messages/{mid}/ip'] = [
+ { in: 'path', name: 'roomId', example: chatRoomId },
+ { in: 'path', name: 'mid', example: firstMsg.mid },
+ ];
// Create an empty file to test DELETE /files and thumb deletion
fs.closeSync(fs.openSync(path.resolve(nconf.get('upload_path'), 'files/test.txt'), 'w'));
diff --git a/test/messaging.js b/test/messaging.js
index b2810c80c7..370c666c7f 100644
--- a/test/messaging.js
+++ b/test/messaging.js
@@ -856,13 +856,13 @@ describe('Messaging Library', () => {
});
it('should fail to delete message if not owner', async () => {
- const { response, body } = await callv3API('delete', `/chats/${roomId}/messages/${mid}`, {}, 'herp');
+ const { response, body } = await callv3API('delete', `/chats/${roomId}/messages/${mid}/state`, {}, 'herp');
assert.strictEqual(response.statusCode, 400);
assert.strictEqual(body.status.message, 'You are not allowed to delete this message');
});
it('should mark the message as deleted', async () => {
- await callv3API('delete', `/chats/${roomId}/messages/${mid}`, {}, 'foo');
+ await callv3API('delete', `/chats/${roomId}/messages/${mid}/state`, {}, 'foo');
const value = await db.getObjectField(`message:${mid}`, 'deleted');
assert.strictEqual(1, parseInt(value, 10));
});
@@ -896,7 +896,7 @@ describe('Messaging Library', () => {
});
it('should error out if a message is deleted again', async () => {
- const { response, body } = await callv3API('delete', `/chats/${roomId}/messages/${mid}`, {}, 'foo');
+ const { response, body } = await callv3API('delete', `/chats/${roomId}/messages/${mid}/state`, {}, 'foo');
assert.strictEqual(response.statusCode, 400);
assert.strictEqual(body.status.message, 'This chat message has already been deleted.');
});
@@ -923,20 +923,20 @@ describe('Messaging Library', () => {
});
it('should error out for regular users', async () => {
- const { response, body } = await callv3API('delete', `/chats/${roomId}/messages/${mid2}`, {}, 'baz');
+ const { response, body } = await callv3API('delete', `/chats/${roomId}/messages/${mid2}/state`, {}, 'baz');
assert.strictEqual(response.statusCode, 400);
assert.strictEqual(body.status.message, 'Chat messaging editing is disabled.');
});
it('should succeed for administrators', async () => {
- await callv3API('delete', `/chats/${roomId}/messages/${mid2}`, {}, 'foo');
+ await callv3API('delete', `/chats/${roomId}/messages/${mid2}/state`, {}, 'foo');
await callv3API('post', `/chats/${roomId}/messages/${mid2}`, {}, 'foo');
});
it('should succeed for global moderators', async () => {
await Groups.join(['Global Moderators'], mocks.users.baz.uid);
- await callv3API('delete', `/chats/${roomId}/messages/${mid2}`, {}, 'baz');
+ await callv3API('delete', `/chats/${roomId}/messages/${mid2}/state`, {}, 'baz');
await callv3API('post', `/chats/${roomId}/messages/${mid2}`, {}, 'baz');
await Groups.leave(['Global Moderators'], mocks.users.baz.uid);