aboutsummaryrefslogtreecommitdiff
path: root/vnext/server/middleware
diff options
context:
space:
mode:
authorGravatar Vitaly Takmazov2022-10-29 23:35:20 +0300
committerGravatar Vitaly Takmazov2023-01-13 10:37:58 +0300
commit47218df561e877265c739ffab59b760318ea3143 (patch)
tree166dd029133aca8d0d60af50535bb579bd6b8096 /vnext/server/middleware
parent3a403e4023ce3b7074a7922e7b504263ddc7a3d1 (diff)
Merge server routes from Next version
Diffstat (limited to 'vnext/server/middleware')
-rw-r--r--vnext/server/middleware/event.js76
-rw-r--r--vnext/server/middleware/oembed.js48
-rw-r--r--vnext/server/middleware/urlexpand.js14
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);
+ });
+}