The code powering m.abunchtell.com https://m.abunchtell.com
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

537 lines
16 KiB

  1. const os = require('os');
  2. const throng = require('throng');
  3. const dotenv = require('dotenv');
  4. const express = require('express');
  5. const http = require('http');
  6. const redis = require('redis');
  7. const pg = require('pg');
  8. const log = require('npmlog');
  9. const url = require('url');
  10. const WebSocket = require('uws');
  11. const uuid = require('uuid');
  12. const env = process.env.NODE_ENV || 'development';
  13. dotenv.config({
  14. path: env === 'production' ? '.env.production' : '.env',
  15. });
  16. log.level = process.env.LOG_LEVEL || 'verbose';
  17. const dbUrlToConfig = (dbUrl) => {
  18. if (!dbUrl) {
  19. return {};
  20. }
  21. const params = url.parse(dbUrl);
  22. const config = {};
  23. if (params.auth) {
  24. [config.user, config.password] = params.auth.split(':');
  25. }
  26. if (params.hostname) {
  27. config.host = params.hostname;
  28. }
  29. if (params.port) {
  30. config.port = params.port;
  31. }
  32. if (params.pathname) {
  33. config.database = params.pathname.split('/')[1];
  34. }
  35. const ssl = params.query && params.query.ssl;
  36. if (ssl) {
  37. config.ssl = ssl === 'true' || ssl === '1';
  38. }
  39. return config;
  40. };
  41. const redisUrlToClient = (defaultConfig, redisUrl) => {
  42. const config = defaultConfig;
  43. if (!redisUrl) {
  44. return redis.createClient(config);
  45. }
  46. if (redisUrl.startsWith('unix://')) {
  47. return redis.createClient(redisUrl.slice(7), config);
  48. }
  49. return redis.createClient(Object.assign(config, {
  50. url: redisUrl,
  51. }));
  52. };
  53. const numWorkers = +process.env.STREAMING_CLUSTER_NUM || (env === 'development' ? 1 : Math.max(os.cpus().length - 1, 1));
  54. const startMaster = () => {
  55. log.info(`Starting streaming API server master with ${numWorkers} workers`);
  56. };
  57. const startWorker = (workerId) => {
  58. log.info(`Starting worker ${workerId}`);
  59. const pgConfigs = {
  60. development: {
  61. user: process.env.DB_USER || pg.defaults.user,
  62. password: process.env.DB_PASS || pg.defaults.password,
  63. database: process.env.DB_NAME || 'mastodon_development',
  64. host: process.env.DB_HOST || pg.defaults.host,
  65. port: process.env.DB_PORT || pg.defaults.port,
  66. max: 10,
  67. },
  68. production: {
  69. user: process.env.DB_USER || 'mastodon',
  70. password: process.env.DB_PASS || '',
  71. database: process.env.DB_NAME || 'mastodon_production',
  72. host: process.env.DB_HOST || 'localhost',
  73. port: process.env.DB_PORT || 5432,
  74. max: 10,
  75. },
  76. };
  77. const app = express();
  78. const pgPool = new pg.Pool(Object.assign(pgConfigs[env], dbUrlToConfig(process.env.DATABASE_URL)));
  79. const server = http.createServer(app);
  80. const redisNamespace = process.env.REDIS_NAMESPACE || null;
  81. const redisParams = {
  82. host: process.env.REDIS_HOST || '127.0.0.1',
  83. port: process.env.REDIS_PORT || 6379,
  84. db: process.env.REDIS_DB || 0,
  85. password: process.env.REDIS_PASSWORD,
  86. };
  87. if (redisNamespace) {
  88. redisParams.namespace = redisNamespace;
  89. }
  90. const redisPrefix = redisNamespace ? `${redisNamespace}:` : '';
  91. const redisSubscribeClient = redisUrlToClient(redisParams, process.env.REDIS_URL);
  92. const redisClient = redisUrlToClient(redisParams, process.env.REDIS_URL);
  93. const subs = {};
  94. redisSubscribeClient.on('message', (channel, message) => {
  95. const callbacks = subs[channel];
  96. log.silly(`New message on channel ${channel}`);
  97. if (!callbacks) {
  98. return;
  99. }
  100. callbacks.forEach(callback => callback(message));
  101. });
  102. const subscriptionHeartbeat = (channel) => {
  103. const interval = 6*60;
  104. const tellSubscribed = () => {
  105. redisClient.set(`${redisPrefix}subscribed:${channel}`, '1', 'EX', interval*3);
  106. };
  107. tellSubscribed();
  108. const heartbeat = setInterval(tellSubscribed, interval*1000);
  109. return () => {
  110. clearInterval(heartbeat);
  111. };
  112. };
  113. const subscribe = (channel, callback) => {
  114. log.silly(`Adding listener for ${channel}`);
  115. subs[channel] = subs[channel] || [];
  116. if (subs[channel].length === 0) {
  117. log.verbose(`Subscribe ${channel}`);
  118. redisSubscribeClient.subscribe(channel);
  119. }
  120. subs[channel].push(callback);
  121. };
  122. const unsubscribe = (channel, callback) => {
  123. log.silly(`Removing listener for ${channel}`);
  124. subs[channel] = subs[channel].filter(item => item !== callback);
  125. if (subs[channel].length === 0) {
  126. log.verbose(`Unsubscribe ${channel}`);
  127. redisSubscribeClient.unsubscribe(channel);
  128. }
  129. };
  130. const allowCrossDomain = (req, res, next) => {
  131. res.header('Access-Control-Allow-Origin', '*');
  132. res.header('Access-Control-Allow-Headers', 'Authorization, Accept, Cache-Control');
  133. res.header('Access-Control-Allow-Methods', 'GET, OPTIONS');
  134. next();
  135. };
  136. const setRequestId = (req, res, next) => {
  137. req.requestId = uuid.v4();
  138. res.header('X-Request-Id', req.requestId);
  139. next();
  140. };
  141. const accountFromToken = (token, req, next) => {
  142. pgPool.connect((err, client, done) => {
  143. if (err) {
  144. next(err);
  145. return;
  146. }
  147. client.query('SELECT oauth_access_tokens.resource_owner_id, users.account_id, users.filtered_languages FROM oauth_access_tokens INNER JOIN users ON oauth_access_tokens.resource_owner_id = users.id WHERE oauth_access_tokens.token = $1 AND oauth_access_tokens.revoked_at IS NULL LIMIT 1', [token], (err, result) => {
  148. done();
  149. if (err) {
  150. next(err);
  151. return;
  152. }
  153. if (result.rows.length === 0) {
  154. err = new Error('Invalid access token');
  155. err.statusCode = 401;
  156. next(err);
  157. return;
  158. }
  159. req.accountId = result.rows[0].account_id;
  160. req.filteredLanguages = result.rows[0].filtered_languages;
  161. next();
  162. });
  163. });
  164. };
  165. const accountFromRequest = (req, next) => {
  166. const authorization = req.headers.authorization;
  167. const location = url.parse(req.url, true);
  168. const accessToken = location.query.access_token;
  169. if (!authorization && !accessToken) {
  170. const err = new Error('Missing access token');
  171. err.statusCode = 401;
  172. next(err);
  173. return;
  174. }
  175. const token = authorization ? authorization.replace(/^Bearer /, '') : accessToken;
  176. accountFromToken(token, req, next);
  177. };
  178. const wsVerifyClient = (info, cb) => {
  179. accountFromRequest(info.req, err => {
  180. if (!err) {
  181. cb(true, undefined, undefined);
  182. } else {
  183. log.error(info.req.requestId, err.toString());
  184. cb(false, 401, 'Unauthorized');
  185. }
  186. });
  187. };
  188. const authenticationMiddleware = (req, res, next) => {
  189. if (req.method === 'OPTIONS') {
  190. next();
  191. return;
  192. }
  193. accountFromRequest(req, next);
  194. };
  195. const errorMiddleware = (err, req, res, {}) => {
  196. log.error(req.requestId, err.toString());
  197. res.writeHead(err.statusCode || 500, { 'Content-Type': 'application/json' });
  198. res.end(JSON.stringify({ error: err.statusCode ? err.toString() : 'An unexpected error occurred' }));
  199. };
  200. const placeholders = (arr, shift = 0) => arr.map((_, i) => `$${i + 1 + shift}`).join(', ');
  201. const authorizeListAccess = (id, req, next) => {
  202. pgPool.connect((err, client, done) => {
  203. if (err) {
  204. next(false);
  205. return;
  206. }
  207. client.query('SELECT id, account_id FROM lists WHERE id = $1 LIMIT 1', [id], (err, result) => {
  208. done();
  209. if (err || result.rows.length === 0 || result.rows[0].account_id !== req.accountId) {
  210. next(false);
  211. return;
  212. }
  213. next(true);
  214. });
  215. });
  216. };
  217. const streamFrom = (id, req, output, attachCloseHandler, needsFiltering = false, notificationOnly = false) => {
  218. const streamType = notificationOnly ? ' (notification)' : '';
  219. log.verbose(req.requestId, `Starting stream from ${id} for ${req.accountId}${streamType}`);
  220. const listener = message => {
  221. const { event, payload, queued_at } = JSON.parse(message);
  222. const transmit = () => {
  223. const now = new Date().getTime();
  224. const delta = now - queued_at;
  225. const encodedPayload = typeof payload === 'object' ? JSON.stringify(payload) : payload;
  226. log.silly(req.requestId, `Transmitting for ${req.accountId}: ${event} ${encodedPayload} Delay: ${delta}ms`);
  227. output(event, encodedPayload);
  228. };
  229. if (notificationOnly && event !== 'notification') {
  230. return;
  231. }
  232. // Only messages that may require filtering are statuses, since notifications
  233. // are already personalized and deletes do not matter
  234. if (needsFiltering && event === 'update') {
  235. pgPool.connect((err, client, done) => {
  236. if (err) {
  237. log.error(err);
  238. return;
  239. }
  240. const unpackedPayload = payload;
  241. const targetAccountIds = [unpackedPayload.account.id].concat(unpackedPayload.mentions.map(item => item.id));
  242. const accountDomain = unpackedPayload.account.acct.split('@')[1];
  243. if (Array.isArray(req.filteredLanguages) && req.filteredLanguages.indexOf(unpackedPayload.language) !== -1) {
  244. log.silly(req.requestId, `Message ${unpackedPayload.id} filtered by language (${unpackedPayload.language})`);
  245. done();
  246. return;
  247. }
  248. const queries = [
  249. client.query(`SELECT 1 FROM blocks WHERE (account_id = $1 AND target_account_id IN (${placeholders(targetAccountIds, 2)})) OR (account_id = $2 AND target_account_id = $1) UNION SELECT 1 FROM mutes WHERE account_id = $1 AND target_account_id IN (${placeholders(targetAccountIds, 2)})`, [req.accountId, unpackedPayload.account.id].concat(targetAccountIds)),
  250. ];
  251. if (accountDomain) {
  252. queries.push(client.query('SELECT 1 FROM account_domain_blocks WHERE account_id = $1 AND domain = $2', [req.accountId, accountDomain]));
  253. }
  254. Promise.all(queries).then(values => {
  255. done();
  256. if (values[0].rows.length > 0 || (values.length > 1 && values[1].rows.length > 0)) {
  257. return;
  258. }
  259. transmit();
  260. }).catch(err => {
  261. done();
  262. log.error(err);
  263. });
  264. });
  265. } else {
  266. transmit();
  267. }
  268. };
  269. subscribe(`${redisPrefix}${id}`, listener);
  270. attachCloseHandler(`${redisPrefix}${id}`, listener);
  271. };
  272. // Setup stream output to HTTP
  273. const streamToHttp = (req, res) => {
  274. res.setHeader('Content-Type', 'text/event-stream');
  275. res.setHeader('Transfer-Encoding', 'chunked');
  276. const heartbeat = setInterval(() => res.write(':thump\n'), 15000);
  277. req.on('close', () => {
  278. log.verbose(req.requestId, `Ending stream for ${req.accountId}`);
  279. clearInterval(heartbeat);
  280. });
  281. return (event, payload) => {
  282. res.write(`event: ${event}\n`);
  283. res.write(`data: ${payload}\n\n`);
  284. };
  285. };
  286. // Setup stream end for HTTP
  287. const streamHttpEnd = (req, closeHandler = false) => (id, listener) => {
  288. req.on('close', () => {
  289. unsubscribe(id, listener);
  290. if (closeHandler) {
  291. closeHandler();
  292. }
  293. });
  294. };
  295. // Setup stream output to WebSockets
  296. const streamToWs = (req, ws) => (event, payload) => {
  297. if (ws.readyState !== ws.OPEN) {
  298. log.error(req.requestId, 'Tried writing to closed socket');
  299. return;
  300. }
  301. ws.send(JSON.stringify({ event, payload }));
  302. };
  303. // Setup stream end for WebSockets
  304. const streamWsEnd = (req, ws, closeHandler = false) => (id, listener) => {
  305. ws.on('close', () => {
  306. log.verbose(req.requestId, `Ending stream for ${req.accountId}`);
  307. unsubscribe(id, listener);
  308. if (closeHandler) {
  309. closeHandler();
  310. }
  311. });
  312. ws.on('error', () => {
  313. log.verbose(req.requestId, `Ending stream for ${req.accountId}`);
  314. unsubscribe(id, listener);
  315. if (closeHandler) {
  316. closeHandler();
  317. }
  318. });
  319. };
  320. app.use(setRequestId);
  321. app.use(allowCrossDomain);
  322. app.use(authenticationMiddleware);
  323. app.use(errorMiddleware);
  324. app.get('/api/v1/streaming/user', (req, res) => {
  325. const channel = `timeline:${req.accountId}`;
  326. streamFrom(channel, req, streamToHttp(req, res), streamHttpEnd(req, subscriptionHeartbeat(channel)));
  327. });
  328. app.get('/api/v1/streaming/user/notification', (req, res) => {
  329. streamFrom(`timeline:${req.accountId}`, req, streamToHttp(req, res), streamHttpEnd(req), false, true);
  330. });
  331. app.get('/api/v1/streaming/public', (req, res) => {
  332. streamFrom('timeline:public', req, streamToHttp(req, res), streamHttpEnd(req), true);
  333. });
  334. app.get('/api/v1/streaming/public/local', (req, res) => {
  335. streamFrom('timeline:public:local', req, streamToHttp(req, res), streamHttpEnd(req), true);
  336. });
  337. app.get('/api/v1/streaming/hashtag', (req, res) => {
  338. streamFrom(`timeline:hashtag:${req.query.tag.toLowerCase()}`, req, streamToHttp(req, res), streamHttpEnd(req), true);
  339. });
  340. app.get('/api/v1/streaming/hashtag/local', (req, res) => {
  341. streamFrom(`timeline:hashtag:${req.query.tag.toLowerCase()}:local`, req, streamToHttp(req, res), streamHttpEnd(req), true);
  342. });
  343. app.get('/api/v1/streaming/list', (req, res) => {
  344. const listId = req.query.list;
  345. authorizeListAccess(listId, req, authorized => {
  346. if (!authorized) {
  347. res.writeHead(404, { 'Content-Type': 'application/json' });
  348. res.end(JSON.stringify({ error: 'Not found' }));
  349. return;
  350. }
  351. const channel = `timeline:list:${listId}`;
  352. streamFrom(channel, req, streamToHttp(req, res), streamHttpEnd(req, subscriptionHeartbeat(channel)));
  353. });
  354. });
  355. const wss = new WebSocket.Server({ server, verifyClient: wsVerifyClient });
  356. wss.on('connection', ws => {
  357. const req = ws.upgradeReq;
  358. const location = url.parse(req.url, true);
  359. req.requestId = uuid.v4();
  360. ws.isAlive = true;
  361. ws.on('pong', () => {
  362. ws.isAlive = true;
  363. });
  364. switch(location.query.stream) {
  365. case 'user':
  366. const channel = `timeline:${req.accountId}`;
  367. streamFrom(channel, req, streamToWs(req, ws), streamWsEnd(req, ws, subscriptionHeartbeat(channel)));
  368. break;
  369. case 'user:notification':
  370. streamFrom(`timeline:${req.accountId}`, req, streamToWs(req, ws), streamWsEnd(req, ws), false, true);
  371. break;
  372. case 'public':
  373. streamFrom('timeline:public', req, streamToWs(req, ws), streamWsEnd(req, ws), true);
  374. break;
  375. case 'public:local':
  376. streamFrom('timeline:public:local', req, streamToWs(req, ws), streamWsEnd(req, ws), true);
  377. break;
  378. case 'hashtag':
  379. streamFrom(`timeline:hashtag:${location.query.tag.toLowerCase()}`, req, streamToWs(req, ws), streamWsEnd(req, ws), true);
  380. break;
  381. case 'hashtag:local':
  382. streamFrom(`timeline:hashtag:${location.query.tag.toLowerCase()}:local`, req, streamToWs(req, ws), streamWsEnd(req, ws), true);
  383. break;
  384. case 'list':
  385. const listId = location.query.list;
  386. authorizeListAccess(listId, req, authorized => {
  387. if (!authorized) {
  388. ws.close();
  389. return;
  390. }
  391. const channel = `timeline:list:${listId}`;
  392. streamFrom(channel, req, streamToWs(req, ws), streamWsEnd(req, ws, subscriptionHeartbeat(channel)));
  393. });
  394. break;
  395. default:
  396. ws.close();
  397. }
  398. });
  399. setInterval(() => {
  400. wss.clients.forEach(ws => {
  401. if (ws.isAlive === false) {
  402. ws.terminate();
  403. return;
  404. }
  405. ws.isAlive = false;
  406. ws.ping('', false, true);
  407. });
  408. }, 30000);
  409. server.listen(process.env.PORT || 4000, () => {
  410. log.info(`Worker ${workerId} now listening on ${server.address().address}:${server.address().port}`);
  411. });
  412. const onExit = () => {
  413. log.info(`Worker ${workerId} exiting, bye bye`);
  414. server.close();
  415. process.exit(0);
  416. };
  417. const onError = (err) => {
  418. log.error(err);
  419. };
  420. process.on('SIGINT', onExit);
  421. process.on('SIGTERM', onExit);
  422. process.on('exit', onExit);
  423. process.on('error', onError);
  424. };
  425. throng({
  426. workers: numWorkers,
  427. lifetime: Infinity,
  428. start: startWorker,
  429. master: startMaster,
  430. });