diff options
Diffstat (limited to 'vnext/server/middleware')
-rw-r--r-- | vnext/server/middleware/event.js | 76 | ||||
-rw-r--r-- | vnext/server/middleware/oembed.js | 48 | ||||
-rw-r--r-- | vnext/server/middleware/urlexpand.js | 14 |
3 files changed, 138 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'); }); +} diff --git a/vnext/server/middleware/oembed.js b/vnext/server/middleware/oembed.js new file mode 100644 index 00000000..ad23d9e2 --- /dev/null +++ b/vnext/server/middleware/oembed.js @@ -0,0 +1,48 @@ +import { embeddedTweet } from '../../src/api'; +import Cors from 'cors'; + +// Initializing the cors middleware +// You can read more about the available options here: https://github.com/expressjs/cors#configuration-options +const cors = Cors({ + methods: ['POST', 'GET', 'HEAD'], +}); + +/** + * Helper method to wait for a middleware to execute before continuing + * And to throw an error when an error happens in a middleware + * + * @param {import("next").NextApiRequest} req + * @param {import("next").NextApiResponse} res + * @param { Function } fn + */ +function runMiddleware(req, res, fn) { + return new Promise((resolve, reject) => { + fn(req, res, (result) => { + if (result instanceof Error) { + return reject(result); + } + return resolve(result); + }); + }); +} +/** + * Return content for embedding. + * + * @param {import("next").NextApiRequest} req + * @param {import("next").NextApiResponse} res + */ +const oembed = async (req, res) => { + let url = (req.query.url || '').toString(); + await runMiddleware(req, res, cors); + return embeddedTweet(url).then(result => { + res.send(result); + res.end(); + }).catch(err => { + console.log(`Err: ${err.response.status}`); + res.status(err.response.status); + res.send({}); + res.end(); + }); +}; + +export default oembed; diff --git a/vnext/server/middleware/urlexpand.js b/vnext/server/middleware/urlexpand.js new file mode 100644 index 00000000..730e2e8f --- /dev/null +++ b/vnext/server/middleware/urlexpand.js @@ -0,0 +1,14 @@ +import { expandShortenedLink } from '../../src/api'; + +/** + * Expand URLs + * + * @param {import("next").NextApiRequest} req + * @param {import("next").NextApiResponse} res + */ +export default function urlExpand(req, res) { + let url = (req.query.url || '').toString(); + return expandShortenedLink(url).then(result => { + res.json(result); + }); +} |