Files
NodeBB/src/messaging/index.js

307 lines
8.6 KiB
JavaScript
Raw Normal View History

2014-03-08 15:45:42 -05:00
'use strict';
2015-12-15 17:50:30 +02:00
const validator = require('validator');
2016-10-03 20:35:36 +03:00
const db = require('../database');
const user = require('../user');
const privileges = require('../privileges');
const plugins = require('../plugins');
const meta = require('../meta');
const utils = require('../utils');
2013-08-26 13:18:20 -04:00
const Messaging = module.exports;
2017-01-03 20:02:24 +03:00
2018-10-23 15:03:32 -04:00
require('./data')(Messaging);
require('./create')(Messaging);
require('./delete')(Messaging);
require('./edit')(Messaging);
require('./rooms')(Messaging);
require('./unread')(Messaging);
require('./notifications')(Messaging);
2017-01-03 20:02:24 +03:00
2021-12-20 11:30:43 -05:00
Messaging.messageExists = async mid => db.exists(`message:${mid}`);
2017-01-03 20:02:24 +03:00
Messaging.getMessages = async (params) => {
const isNew = params.isNew || false;
const start = params.hasOwnProperty('start') ? params.start : 0;
const stop = parseInt(start, 10) + ((params.count || 50) - 1);
2016-09-20 16:58:50 +03:00
const indices = {};
const ok = await canGet('filter:messaging.canGetMessages', params.callerUid, params.uid);
if (!ok) {
return;
}
2016-10-03 20:35:36 +03:00
2021-02-03 23:59:08 -07:00
const mids = await db.getSortedSetRevRange(`uid:${params.uid}:chat:room:${params.roomId}:mids`, start, stop);
if (!mids.length) {
return [];
}
2021-02-04 00:01:39 -07:00
mids.forEach((mid, index) => {
indices[mid] = start + index;
});
mids.reverse();
2016-10-03 20:35:36 +03:00
const messageData = await Messaging.getMessagesData(mids, params.uid, params.roomId, isNew);
2021-02-04 00:01:39 -07:00
messageData.forEach((messageData) => {
messageData.index = indices[messageData.messageId.toString()];
messageData.isOwner = messageData.fromuid === parseInt(params.uid, 10);
if (messageData.deleted && !messageData.isOwner) {
messageData.content = '[[modules:chat.message-deleted]]';
messageData.cleanedContent = messageData.content;
}
});
return messageData;
2017-01-03 20:02:24 +03:00
};
async function canGet(hook, callerUid, uid) {
const data = await plugins.hooks.fire(hook, {
2017-01-03 20:02:24 +03:00
callerUid: callerUid,
uid: uid,
2017-02-17 19:31:21 -07:00
canGet: parseInt(callerUid, 10) === parseInt(uid, 10),
2017-01-03 20:02:24 +03:00
});
return data ? data.canGet : false;
2017-01-03 20:02:24 +03:00
}
Messaging.parse = async (message, fromuid, uid, roomId, isNew) => {
2021-03-15 17:55:14 -04:00
const parsed = await plugins.hooks.fire('filter:parse.raw', String(message || ''));
let messageData = {
message: message,
parsed: parsed,
fromuid: fromuid,
uid: uid,
roomId: roomId,
isNew: isNew,
parsedMessage: parsed,
};
2013-08-26 13:18:20 -04:00
messageData = await plugins.hooks.fire('filter:messaging.parse', messageData);
return messageData ? messageData.parsedMessage : '';
2017-01-03 20:02:24 +03:00
};
Messaging.isNewSet = async (uid, roomId, timestamp) => {
2021-02-03 23:59:08 -07:00
const setKey = `uid:${uid}:chat:room:${roomId}:mids`;
const messages = await db.getSortedSetRevRangeWithScores(setKey, 0, 0);
if (messages && messages.length) {
return parseInt(timestamp, 10) > parseInt(messages[0].score, 10) + Messaging.newMessageCutoff;
}
return true;
2017-01-03 20:02:24 +03:00
};
Messaging.getRecentChats = async (callerUid, uid, start, stop) => {
const ok = await canGet('filter:messaging.canGetRecentChats', callerUid, uid);
if (!ok) {
return null;
}
2017-01-03 20:02:24 +03:00
2021-02-03 23:59:08 -07:00
const roomIds = await db.getSortedSetRevRange(`uid:${uid}:chat:rooms`, start, stop);
const results = await utils.promiseParallel({
roomData: Messaging.getRoomsData(roomIds),
2021-02-03 23:59:08 -07:00
unread: db.isSortedSetMembers(`uid:${uid}:chat:rooms:unread`, roomIds),
users: Promise.all(roomIds.map(async (roomId) => {
2021-02-03 23:59:08 -07:00
let uids = await db.getSortedSetRevRange(`chat:room:${roomId}:uids`, 0, 9);
uids = uids.filter(_uid => _uid && parseInt(_uid, 10) !== parseInt(uid, 10));
return await user.getUsersFields(uids, ['uid', 'username', 'userslug', 'picture', 'status', 'lastonline']);
})),
teasers: Promise.all(roomIds.map(async roomId => Messaging.getTeaser(uid, roomId))),
});
2021-02-04 00:01:39 -07:00
results.roomData.forEach((room, index) => {
if (room) {
room.users = results.users[index];
room.groupChat = room.hasOwnProperty('groupChat') ? room.groupChat : room.users.length > 2;
room.unread = results.unread[index];
room.teaser = results.teasers[index];
2021-02-04 00:01:39 -07:00
room.users.forEach((userData) => {
if (userData && parseInt(userData.uid, 10)) {
userData.status = user.getStatus(userData);
2017-10-12 17:05:15 -04:00
}
2017-01-03 20:02:24 +03:00
});
2021-02-04 00:01:39 -07:00
room.users = room.users.filter(user => user && parseInt(user.uid, 10));
room.lastUser = room.users[0];
room.usernames = Messaging.generateUsernames(room.users, uid);
}
});
2016-09-30 19:39:08 +03:00
results.roomData = results.roomData.filter(Boolean);
const ref = { rooms: results.roomData, nextStart: stop + 1 };
return await plugins.hooks.fire('filter:messaging.getRecentChats', {
rooms: ref.rooms,
nextStart: ref.nextStart,
uid: uid,
callerUid: callerUid,
});
2017-01-03 20:02:24 +03:00
};
2020-01-23 22:19:15 -05:00
Messaging.generateUsernames = (users, excludeUid) => users.filter(user => user && parseInt(user.uid, 10) !== excludeUid)
.map(user => user.username).join(', ');
2017-01-03 20:02:24 +03:00
Messaging.getTeaser = async (uid, roomId) => {
const mid = await Messaging.getLatestUndeletedMessage(uid, roomId);
if (!mid) {
return null;
}
const teaser = await Messaging.getMessageFields(mid, ['fromuid', 'content', 'timestamp']);
if (!teaser.fromuid) {
return null;
}
const blocked = await user.blocks.is(teaser.fromuid, uid);
if (blocked) {
return null;
}
2015-12-17 12:35:49 +02:00
teaser.user = await user.getUserFields(teaser.fromuid, ['uid', 'username', 'userslug', 'picture', 'status', 'lastonline']);
if (teaser.content) {
teaser.content = utils.stripHTMLTags(utils.decodeHTMLEntities(teaser.content));
teaser.content = validator.escape(String(teaser.content));
}
const payload = await plugins.hooks.fire('filter:messaging.getTeaser', { teaser: teaser });
return payload.teaser;
2017-01-03 20:02:24 +03:00
};
Messaging.getLatestUndeletedMessage = async (uid, roomId) => {
let done = false;
let latestMid = null;
let index = 0;
let mids;
while (!done) {
/* eslint-disable no-await-in-loop */
2021-02-03 23:59:08 -07:00
mids = await db.getSortedSetRevRange(`uid:${uid}:chat:room:${roomId}:mids`, index, index);
if (mids.length) {
const states = await Messaging.getMessageFields(mids[0], ['deleted', 'system']);
done = !states.deleted && !states.system;
if (done) {
latestMid = mids[0];
}
index += 1;
} else {
done = true;
}
}
return latestMid;
};
Messaging.canMessageUser = async (uid, toUid) => {
if (meta.config.disableChat || uid <= 0) {
throw new Error('[[error:chat-disabled]]');
2017-01-03 20:02:24 +03:00
}
2016-10-22 10:22:05 +03:00
2017-01-03 20:02:24 +03:00
if (parseInt(uid, 10) === parseInt(toUid, 10)) {
throw new Error('[[error:cant-chat-with-yourself]]');
2017-01-03 20:02:24 +03:00
}
const [exists, canChat] = await Promise.all([
user.exists(toUid),
privileges.global.can('chat', uid),
checkReputation(uid),
]);
2014-07-19 10:33:27 -04:00
if (!exists) {
throw new Error('[[error:no-user]]');
}
if (!canChat) {
throw new Error('[[error:no-privileges]]');
}
const [settings, isAdmin, isModerator, isFollowing, isBlocked] = await Promise.all([
user.getSettings(toUid),
user.isAdministrator(uid),
user.isModeratorOfAnyCategory(uid),
user.isFollowing(toUid, uid),
user.blocks.is(uid, toUid),
]);
if (isBlocked || (settings.restrictChat && !isAdmin && !isModerator && !isFollowing)) {
throw new Error('[[error:chat-restricted]]');
}
await plugins.hooks.fire('static:messaging.canMessageUser', {
uid: uid,
toUid: toUid,
});
2017-01-03 20:02:24 +03:00
};
2016-02-29 10:36:20 +02:00
Messaging.canMessageRoom = async (uid, roomId) => {
2018-11-17 22:31:39 -05:00
if (meta.config.disableChat || uid <= 0) {
throw new Error('[[error:chat-disabled]]');
2017-01-03 20:02:24 +03:00
}
2016-02-29 10:36:20 +02:00
const [inRoom, canChat] = await Promise.all([
Messaging.isUserInRoom(uid, roomId),
privileges.global.can('chat', uid),
checkReputation(uid),
]);
if (!inRoom) {
throw new Error('[[error:not-in-room]]');
}
2016-02-29 10:36:20 +02:00
if (!canChat) {
throw new Error('[[error:no-privileges]]');
}
2014-10-30 17:50:07 -04:00
await plugins.hooks.fire('static:messaging.canMessageRoom', {
uid: uid,
roomId: roomId,
});
2017-01-03 20:02:24 +03:00
};
2016-01-18 15:35:24 +02:00
async function checkReputation(uid) {
if (meta.config['min:rep:chat'] > 0) {
const reputation = await user.getUserField(uid, 'reputation');
if (meta.config['min:rep:chat'] > reputation) {
throw new Error(`[[error:not-enough-reputation-to-chat, ${meta.config['min:rep:chat']}]]`);
}
}
}
Messaging.hasPrivateChat = async (uid, withUid) => {
2017-01-03 20:02:24 +03:00
if (parseInt(uid, 10) === parseInt(withUid, 10)) {
return 0;
2017-01-03 20:02:24 +03:00
}
2016-01-18 15:35:24 +02:00
const results = await utils.promiseParallel({
2021-02-03 23:59:08 -07:00
myRooms: db.getSortedSetRevRange(`uid:${uid}:chat:rooms`, 0, -1),
theirRooms: db.getSortedSetRevRange(`uid:${withUid}:chat:rooms`, 0, -1),
});
2021-02-04 00:01:39 -07:00
const roomIds = results.myRooms.filter(roomId => roomId && results.theirRooms.includes(roomId));
Squashed commit of the following: Closes #2668 commit 3d4f494ed3257bceda8f6f82057cab83f0f252b3 Author: Julian Lam <julian@designcreateplay.com> Date: Fri Dec 11 12:06:42 2015 -0500 theme minvers for #2668 commit b608ce61854f8195143685bb9753b80d32b26e95 Author: Julian Lam <julian@designcreateplay.com> Date: Fri Dec 11 12:01:03 2015 -0500 Allowing chat modal to edit and delete messages re: #2668 commit 0104db90a4070582f3938b6929dae35f985bac35 Author: Julian Lam <julian@designcreateplay.com> Date: Fri Dec 11 11:51:23 2015 -0500 Fixed issue where newSet calculations were off ... sometimes. Also, rendering of edited messages now parses a template partial, instead of just replacing the content. commit 5cb6ca600425ca9320c599b32306e93dcc5aa4ce Author: Julian Lam <julian@designcreateplay.com> Date: Fri Dec 11 11:07:12 2015 -0500 If edited content matches existing content... ... then edit is aborted. commit 6e7495247b1895589c716db29f919a934087b924 Author: Julian Lam <julian@designcreateplay.com> Date: Fri Dec 11 11:05:08 2015 -0500 some linting and fixed issue where new msgs when deleted would crash server commit db4a9e40d6dff44569c2437378121db8fdf75cf8 Author: Julian Lam <julian@designcreateplay.com> Date: Tue Dec 8 17:25:56 2015 -0500 Message deletion for #2668, and fixed bug Fixed bug where chat modal would spawn even though user was sitting on the /chats page. commit a5aa2498ab4a8bba02a6daa43a9dbed7b3e37976 Author: Julian Lam <julian@designcreateplay.com> Date: Tue Dec 8 14:55:23 2015 -0500 wiring up the edit button, #2668 commit 5f2afdcf6f2b9eae6b5873ca100149e65e3d385d Author: Julian Lam <julian@designcreateplay.com> Date: Tue Dec 8 14:20:39 2015 -0500 added indicator to show if and when a message had been edited commit e8301132d525c1b9fd46c98cdb282ac7ea7a0d7f Author: Julian Lam <julian@designcreateplay.com> Date: Tue Dec 8 14:06:39 2015 -0500 Allowing editing of chat messages commit bfd991be1cb1769599f7d5d2b1638e313c3c2dcb Author: Julian Lam <julian@designcreateplay.com> Date: Tue Dec 8 10:33:49 2015 -0500 Added messageId to messages object return commit 0306ee6657b3288dd4547c66869d7d4ece0b31ad Author: Julian Lam <julian@designcreateplay.com> Date: Tue Dec 8 08:20:17 2015 -0500 WIP #2668
2015-12-11 12:07:02 -05:00
if (!roomIds.length) {
return 0;
}
2021-02-04 00:06:15 -07:00
let index = 0;
let roomId = 0;
while (index < roomIds.length && !roomId) {
/* eslint-disable no-await-in-loop */
const count = await Messaging.getUserCountInRoom(roomIds[index]);
if (count === 2) {
roomId = roomIds[index];
} else {
index += 1;
}
}
return roomId;
2017-01-03 20:02:24 +03:00
};
Messaging.canViewMessage = async (mids, roomId, uid) => {
let single = false;
if (!Array.isArray(mids) && isFinite(mids)) {
mids = [mids];
single = true;
}
const canView = await db.isSortedSetMembers(`uid:${uid}:chat:room:${roomId}:mids`, mids);
return single ? canView.pop() : canView;
};
require('../promisify')(Messaging);