diff options
author | Vitaly Takmazov | 2022-10-29 23:35:20 +0300 |
---|---|---|
committer | Vitaly Takmazov | 2023-01-13 10:37:58 +0300 |
commit | 47218df561e877265c739ffab59b760318ea3143 (patch) | |
tree | 166dd029133aca8d0d60af50535bb579bd6b8096 /vnext/server/middleware/event.js | |
parent | 3a403e4023ce3b7074a7922e7b504263ddc7a3d1 (diff) |
Merge server routes from Next version
Diffstat (limited to 'vnext/server/middleware/event.js')
-rw-r--r-- | vnext/server/middleware/event.js | 76 |
1 files changed, 76 insertions, 0 deletions
diff --git a/vnext/server/middleware/event.js b/vnext/server/middleware/event.js new file mode 100644 index 00000000..29bede76 --- /dev/null +++ b/vnext/server/middleware/event.js @@ -0,0 +1,76 @@ +import { simpleParser } from 'mailparser'; +import { isPM, isReply, isService } from '../common/MessageUtils'; +import { subscribers } from '../http'; +import { sendNotification, buildNotification } from '../sender'; +var debug = require('debug')('event'); + +/** @type {number[]} */ +const allSandboxIds = []; + +/** + * handle message event + * + * @param {import('../../client').Message} msg message + */ +function processMessageEvent(msg) { + let params = {}; + params.uid = isPM(msg) ? msg.to.uid : msg.user.uid; + if (isReply(msg)) { + params.mid = msg.mid; + params.rid = msg.rid; + } else if (!isPM(msg) && !isService(msg)) { + params.mid = msg.mid; + } + subscribers(new URLSearchParams(JSON.parse(JSON.stringify(params)))).then(users => { + users.forEach(user => { + debug(`${user.uname}: ${user.unreadCount}`); + let [sandboxTokens, productionTokens] = (user.tokens || []) + .filter(t => ['mpns', 'apns', 'gcm'].includes(t.type)) + .map(t => t.token) + .reduce((result, element, i) => { + allSandboxIds.includes(user.uid) + ? result[0].push(element) + : result[1].push(element); + return result; + }, [[], []]); + sendNotification(productionTokens, sandboxTokens, buildNotification(user, msg)); + }); + }).catch(console.error); +} + +/** + * Handle new events + * + * @param {import("next").NextApiRequest} req + * @param {import("next").NextApiResponse} res + */ +export default function handleMessage(req, res) { + return simpleParser(req.body, {}) + .then(parsed => { + const new_version = parsed.headers.get('x-event-version') == '1.0'; + debug(`New event: ${parsed.text}, new version: ${new_version}`); + if (new_version) { + /** @type {import('../../client').SystemEvent} */ + const event = JSON.parse(parsed.text || ''); + if (event.type === 'message' && event.message) { + if (event.message.service) { + // TODO: remove + let msg = { ...event.message }; + if (event.from) { + msg.user = event.from; + } + processMessageEvent(msg); + } else { + processMessageEvent(event.message); + } + + } + } else { + /** @type {import('../../client').Message} */ + const msg = JSON.parse(parsed.text || ''); + processMessageEvent(msg); + } + res.end(); + }) + .catch(err => { console.error(err); res.status(400).send('Invalid request'); }); +} |