import { simpleParser } from 'mailparser' import { isPM, isReply, isService } from '../common/MessageUtils' import { sendTelegramNotification } from '../durov' import { subscribers } from '../http' import { sendNotification, buildNotification } from '../sender' import debug from 'debug' import { send } from '../hms' var log = 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 => { return users.map(user => { log(`${user.uname}: ${user.unreadCount}`) let [sandboxTokens, productionTokens] = (user.tokens || []) .filter(t => ['mpns', 'apns', 'fcm', 'web'].includes(t.type)) .map(t => t.type === 'web' ? JSON.parse(t.token) : t.token) .reduce((result, element) => { allSandboxIds.includes(user.uid) ? result[0].push(element) : result[1].push(element) return result }, [[], []]) sendNotification(productionTokens, sandboxTokens, buildNotification(user, msg)) let durovIds = (user.tokens || []) .filter(t => ['durov'].includes(t.type)) .map(t => t.token) sendTelegramNotification(msg, durovIds) let hmsIds = (user.tokens || []) .filter(t => t.type === 'hcm') .map(t => t.token) log(`${user.uname}: ${hmsIds}`) return hmsIds }) }).then(userHmsIds => { userHmsIds.forEach(hmsIds => { send(msg, hmsIds) }) }).then(() => { // TODO: handle results }).catch(log) } /** * Handle new events * @type {import('express').RequestParamHandler} */ export default function handleMessage(req, res) { return simpleParser(req.body, {}) .then(parsed => { const new_version = parsed.headers.get('x-event-version') == '1.0' log(`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 => { log(err); res.status(400).send('Invalid request') }) }