From d3ce6868a36153b528b60f6abed10839a34136bb Mon Sep 17 00:00:00 2001 From: cha0s Date: Mon, 20 Jul 2020 23:47:03 -0500 Subject: [PATCH] feat: private messaging --- src/server/entry.js | 7 ++++++- src/server/sockets.js | 25 ++++++++++++++++++------- 2 files changed, 24 insertions(+), 8 deletions(-) diff --git a/src/server/entry.js b/src/server/entry.js index 08b0ea2..4a97eae 100644 --- a/src/server/entry.js +++ b/src/server/entry.js @@ -32,7 +32,11 @@ export const channelUsers = async (req, channel) => ( ); export const channelState = async (req, channel) => { - const messageKeys = await keys(redisClient, `${channel}:messages:*`); + const {name, type} = parseChannel(`/chat${channel}`); + const serverChannel = 'r' === type + ? channel + : `/u/${[name, req.user.redditUsername].sort().join('$')}`; + const messageKeys = await keys(redisClient, `${serverChannel}:messages:*`); const messages = 0 === messageKeys.length ? [] : (await mget(messageKeys)) @@ -104,6 +108,7 @@ export const appChatState = async (req) => { if (0 === toHydrate.length) { return null; } + console.log({toHydrate}) const entries = await Promise.all( toHydrate.map((favorite) => channelState(req, joinChannel(favorite))), ); diff --git a/src/server/sockets.js b/src/server/sockets.js index 634c51a..1616622 100644 --- a/src/server/sockets.js +++ b/src/server/sockets.js @@ -187,16 +187,27 @@ export function createSocketServer(httpServer) { } if (packet instanceof Message) { const {channel, message} = packet.data; + const {name, type} = parseChannel(`/chat${channel}`); + const other = await User.findOne({where: {redditUsername: name}}); const owner = '/r/anonymous' === channel ? 0 : req.userId; + const serverChannel = 'r' === type + ? channel + : `/u/${[name, req.user.redditUsername].sort().join('$')}`; const timestamp = Date.now(); + const username = '/r/anonymous' === channel ? 'anonymous' : req.user.redditUsername; const uuid = uuidv4(); - const key = `${channel}:messages:${uuid}`; - socket.to(channel, new Message({ - ...packet.data, - owner, - timestamp, - uuid, - })); + const key = `${serverChannel}:messages:${uuid}`; + ('u' === type ? [`/user/${other.id}`, `/user/${req.userId}`] : [channel]).forEach((room) => ( + socket.to(room, new Message({ + ...packet.data, + channel: 'r' === type + ? channel + : `/u/${username === room.substr(3) ? name : username}`, + owner, + timestamp, + uuid, + })) + )); pubClient .multi() .set(key, JSON.stringify({