diff options
Diffstat (limited to 'vnext/server/middleware')
-rw-r--r-- | vnext/server/middleware/event.js | 74 | ||||
-rw-r--r-- | vnext/server/middleware/oembed.js | 20 | ||||
-rw-r--r-- | vnext/server/middleware/renderer.js | 84 | ||||
-rw-r--r-- | vnext/server/middleware/urlexpand.js | 8 |
4 files changed, 93 insertions, 93 deletions
diff --git a/vnext/server/middleware/event.js b/vnext/server/middleware/event.js index 5681eb59..59f36950 100644 --- a/vnext/server/middleware/event.js +++ b/vnext/server/middleware/event.js @@ -1,54 +1,54 @@ -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'); +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 = []; +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; + let params = {} + params.uid = isPM(msg) ? msg.to.uid : msg.user.uid if (isReply(msg)) { - params.mid = msg.mid; - params.rid = msg.rid; + params.mid = msg.mid + params.rid = msg.rid } else if (!isPM(msg) && !isService(msg)) { - params.mid = msg.mid; + params.mid = msg.mid } subscribers(new URLSearchParams(JSON.parse(JSON.stringify(params)))).then(users => { users.forEach(user => { - log(`${user.uname}: ${user.unreadCount}`); + 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, i) => { allSandboxIds.includes(user.uid) ? result[0].push(element) - : result[1].push(element); - return result; - }, [[], []]); - sendNotification(productionTokens, sandboxTokens, buildNotification(user, msg)); + : 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); + .map(t => t.token) + sendTelegramNotification(msg, durovIds) let hmsIds = (user.tokens || []) .filter(t => t.type === 'hcm') - .map(t => t.token); - log(`${user.uname}: ${hmsIds}`); + .map(t => t.token) + log(`${user.uname}: ${hmsIds}`) send(msg, hmsIds).then(() => { // TODO: handle results - }).catch(log); - }); - }).catch(log); + }).catch(log) + }) + }).catch(log) } /** @@ -58,30 +58,30 @@ function processMessageEvent(msg) { 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}`); + 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 || ''); + const event = JSON.parse(parsed.text || '') if (event.type === 'message' && event.message) { if (event.message.service) { // TODO: remove - let msg = { ...event.message }; + let msg = { ...event.message } if (event.from) { - msg.user = event.from; + msg.user = event.from } - processMessageEvent(msg); + processMessageEvent(msg) } else { - processMessageEvent(event.message); + processMessageEvent(event.message) } } } else { /** @type {import('../../client').Message} */ - const msg = JSON.parse(parsed.text || ''); - processMessageEvent(msg); + const msg = JSON.parse(parsed.text || '') + processMessageEvent(msg) } - res.end(); + res.end() }) - .catch(err => { log(err); res.status(400).send('Invalid request'); }); + .catch(err => { log(err); res.status(400).send('Invalid request') }) } diff --git a/vnext/server/middleware/oembed.js b/vnext/server/middleware/oembed.js index 8b1ed61d..5d062228 100644 --- a/vnext/server/middleware/oembed.js +++ b/vnext/server/middleware/oembed.js @@ -1,19 +1,19 @@ -import { embeddedTweet } from '../../src/api'; +import { embeddedTweet } from '../../src/api' /** * Return content for embedding * @type {import('express').RequestParamHandler} */ const oembed = async (req, res) => { - let url = (req.query.url || '').toString(); + let url = (req.query.url || '').toString() return embeddedTweet(url).then(result => { - res.send(result); - res.end(); + res.send(result) + res.end() }).catch(err => { - console.log(`HTTP ${err.response ? err.response.status : err.code}: ${url}`); - res.sendStatus(err.response ? err.response.status : 500); - res.end(); - }); -}; + console.log(`HTTP ${err.response ? err.response.status : err.code}: ${url}`) + res.sendStatus(err.response ? err.response.status : 500) + res.end() + }) +} -export default oembed; +export default oembed diff --git a/vnext/server/middleware/renderer.js b/vnext/server/middleware/renderer.js index debba758..e7e0324e 100644 --- a/vnext/server/middleware/renderer.js +++ b/vnext/server/middleware/renderer.js @@ -1,54 +1,54 @@ -import * as ReactDOMServer from 'react-dom/server'; -import cookie from 'cookie'; -import config from 'config'; +import * as ReactDOMServer from 'react-dom/server' +import cookie from 'cookie' +import config from 'config' // import our main App component -import App from '../../src/App'; +import App from '../../src/App' -import { getLinks } from '../sape'; -import { StaticRouter } from 'react-router-dom/server'; -import { VisitorProvider } from '../../src/ui/VisitorContext'; +import { getLinks } from '../sape' +import { StaticRouter } from 'react-router-dom/server' +import { VisitorProvider } from '../../src/ui/VisitorContext' -import path from 'path'; -import fs from 'fs'; +import path from 'path' +import fs from 'fs' // convert a Unicode string to a string in which // each 16-bit unit occupies only one byte function toBinary(string) { - const codeUnits = new Uint16Array(string.length); + const codeUnits = new Uint16Array(string.length) for (let i = 0; i < codeUnits.length; i++) { - codeUnits[i] = string.charCodeAt(i); + codeUnits[i] = string.charCodeAt(i) } - return Buffer.from(String.fromCharCode(...new Uint8Array(codeUnits.buffer))).toString('base64'); + return Buffer.from(String.fromCharCode(...new Uint8Array(codeUnits.buffer))).toString('base64') } -const STATIC_ROOT = config.get('service.static_root') || path.resolve(__dirname, 'public'); +const STATIC_ROOT = config.get('service.static_root') || path.resolve(__dirname, 'public') const serverRenderer = async (req, res) => { // point to the html file created by CRA's build tool - const filePath = path.resolve(STATIC_ROOT, 'index.html'); + const filePath = path.resolve(STATIC_ROOT, 'index.html') // links - const cookies = cookie.parse(req.headers.cookie || ''); + const cookies = cookie.parse(req.headers.cookie || '') - const links = await getLinks(req.originalUrl, cookies['sape_cookie']); + const links = await getLinks(req.originalUrl, cookies['sape_cookie']) fs.readFile(filePath, 'utf8', (err, htmlData) => { if (err) { - console.error('err', err); - return res.status(404).end(); + console.error('err', err) + return res.status(404).end() } - const routerContext = {}; + const routerContext = {} const props = { footer: links.join(' ') - }; + } - const marker = '<div id="app">'; - const data = htmlData.split(marker); - const propsData = `<script>window.__PROPS__="${toBinary(JSON.stringify(props))}";</script>${marker}`; - let didError = false; + const marker = '<div id="app">' + const data = htmlData.split(marker) + const propsData = `<script>window.__PROPS__="${toBinary(JSON.stringify(props))}";</script>${marker}` + let didError = false const { pipe } = ReactDOMServer.renderToPipeableStream( <VisitorProvider> <StaticRouter location={req.baseUrl} context={routerContext}> @@ -57,33 +57,33 @@ const serverRenderer = async (req, res) => { </VisitorProvider> , { onShellReady() { - res.statusCode = didError ? 500 : 200; - res.setHeader('Content-type', 'text/html'); - res.write(data[0]); - res.write(propsData); - pipe(res, { end: false }); + res.statusCode = didError ? 500 : 200 + res.setHeader('Content-type', 'text/html') + res.write(data[0]) + res.write(propsData) + pipe(res, { end: false }) }, onShellError() { - didError = true; - res.statusCode = 500; - res.setHeader('Content-type', 'text/html'); + didError = true + res.statusCode = 500 + res.setHeader('Content-type', 'text/html') res.send( '<h1>Something went wrong :(</h1>' - ); - res.end(); + ) + res.end() }, onAllReady() { if (!didError) { - res.write(data[1]); + res.write(data[1]) } - res.end(); + res.end() }, onError(err) { - didError = true; - console.log(err); + didError = true + console.log(err) } - }); - }); -}; + }) + }) +} -export default serverRenderer; +export default serverRenderer diff --git a/vnext/server/middleware/urlexpand.js b/vnext/server/middleware/urlexpand.js index f78d1cc0..a99f80a7 100644 --- a/vnext/server/middleware/urlexpand.js +++ b/vnext/server/middleware/urlexpand.js @@ -1,4 +1,4 @@ -import { expandShortenedLink } from '../../src/api'; +import { expandShortenedLink } from '../../src/api' /** * Expand URLs @@ -6,8 +6,8 @@ import { expandShortenedLink } from '../../src/api'; * @param {import("next").NextApiResponse} res */ export default function urlExpand(req, res) { - let url = (req.query.url || '').toString(); + let url = (req.query.url || '').toString() return expandShortenedLink(url).then(result => { - res.json(result); - }); + res.json(result) + }) } |