闭社主体 forked from https://github.com/tootsuite/mastodon
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.

440 lines
12 KiB

Account domain blocks (#2381) * Add <ostatus:conversation /> tag to Atom input/output Only uses ref attribute (not href) because href would be the alternate link that's always included also. Creates new conversation for every non-reply status. Carries over conversation for every reply. Keeps remote URIs verbatim, generates local URIs on the fly like the rest of them. * Conversation muting - prevents notifications that reference a conversation (including replies, favourites, reblogs) from being created. API endpoints /api/v1/statuses/:id/mute and /api/v1/statuses/:id/unmute Currently no way to tell when a status/conversation is muted, so the web UI only has a "disable notifications" button, doesn't work as a toggle * Display "Dismiss notifications" on all statuses in notifications column, not just own * Add "muted" as a boolean attribute on statuses JSON For now always false on contained reblogs, since it's only relevant for statuses returned from the notifications endpoint, which are not nested Remove "Disable notifications" from detailed status view, since it's only relevant in the notifications column * Up max class length * Remove pending test for conversation mute * Add tests, clean up * Rename to "mute conversation" and "unmute conversation" * Raise validation error when trying to mute/unmute status without conversation * Adding account domain blocks that filter notifications and public timelines * Add tests for domain blocks in notifications, public timelines Filter reblogs of blocked domains from home * Add API for listing and creating account domain blocks * API for creating/deleting domain blocks, tests for Status#ancestors and Status#descendants, filter domain blocks from them * Filter domains in streaming API * Update account_domain_block_spec.rb
7 years ago
Account domain blocks (#2381) * Add <ostatus:conversation /> tag to Atom input/output Only uses ref attribute (not href) because href would be the alternate link that's always included also. Creates new conversation for every non-reply status. Carries over conversation for every reply. Keeps remote URIs verbatim, generates local URIs on the fly like the rest of them. * Conversation muting - prevents notifications that reference a conversation (including replies, favourites, reblogs) from being created. API endpoints /api/v1/statuses/:id/mute and /api/v1/statuses/:id/unmute Currently no way to tell when a status/conversation is muted, so the web UI only has a "disable notifications" button, doesn't work as a toggle * Display "Dismiss notifications" on all statuses in notifications column, not just own * Add "muted" as a boolean attribute on statuses JSON For now always false on contained reblogs, since it's only relevant for statuses returned from the notifications endpoint, which are not nested Remove "Disable notifications" from detailed status view, since it's only relevant in the notifications column * Up max class length * Remove pending test for conversation mute * Add tests, clean up * Rename to "mute conversation" and "unmute conversation" * Raise validation error when trying to mute/unmute status without conversation * Adding account domain blocks that filter notifications and public timelines * Add tests for domain blocks in notifications, public timelines Filter reblogs of blocked domains from home * Add API for listing and creating account domain blocks * API for creating/deleting domain blocks, tests for Status#ancestors and Status#descendants, filter domain blocks from them * Filter domains in streaming API * Update account_domain_block_spec.rb
7 years ago
Account domain blocks (#2381) * Add <ostatus:conversation /> tag to Atom input/output Only uses ref attribute (not href) because href would be the alternate link that's always included also. Creates new conversation for every non-reply status. Carries over conversation for every reply. Keeps remote URIs verbatim, generates local URIs on the fly like the rest of them. * Conversation muting - prevents notifications that reference a conversation (including replies, favourites, reblogs) from being created. API endpoints /api/v1/statuses/:id/mute and /api/v1/statuses/:id/unmute Currently no way to tell when a status/conversation is muted, so the web UI only has a "disable notifications" button, doesn't work as a toggle * Display "Dismiss notifications" on all statuses in notifications column, not just own * Add "muted" as a boolean attribute on statuses JSON For now always false on contained reblogs, since it's only relevant for statuses returned from the notifications endpoint, which are not nested Remove "Disable notifications" from detailed status view, since it's only relevant in the notifications column * Up max class length * Remove pending test for conversation mute * Add tests, clean up * Rename to "mute conversation" and "unmute conversation" * Raise validation error when trying to mute/unmute status without conversation * Adding account domain blocks that filter notifications and public timelines * Add tests for domain blocks in notifications, public timelines Filter reblogs of blocked domains from home * Add API for listing and creating account domain blocks * API for creating/deleting domain blocks, tests for Status#ancestors and Status#descendants, filter domain blocks from them * Filter domains in streaming API * Update account_domain_block_spec.rb
7 years ago
Account domain blocks (#2381) * Add <ostatus:conversation /> tag to Atom input/output Only uses ref attribute (not href) because href would be the alternate link that's always included also. Creates new conversation for every non-reply status. Carries over conversation for every reply. Keeps remote URIs verbatim, generates local URIs on the fly like the rest of them. * Conversation muting - prevents notifications that reference a conversation (including replies, favourites, reblogs) from being created. API endpoints /api/v1/statuses/:id/mute and /api/v1/statuses/:id/unmute Currently no way to tell when a status/conversation is muted, so the web UI only has a "disable notifications" button, doesn't work as a toggle * Display "Dismiss notifications" on all statuses in notifications column, not just own * Add "muted" as a boolean attribute on statuses JSON For now always false on contained reblogs, since it's only relevant for statuses returned from the notifications endpoint, which are not nested Remove "Disable notifications" from detailed status view, since it's only relevant in the notifications column * Up max class length * Remove pending test for conversation mute * Add tests, clean up * Rename to "mute conversation" and "unmute conversation" * Raise validation error when trying to mute/unmute status without conversation * Adding account domain blocks that filter notifications and public timelines * Add tests for domain blocks in notifications, public timelines Filter reblogs of blocked domains from home * Add API for listing and creating account domain blocks * API for creating/deleting domain blocks, tests for Status#ancestors and Status#descendants, filter domain blocks from them * Filter domains in streaming API * Update account_domain_block_spec.rb
7 years ago
Account domain blocks (#2381) * Add <ostatus:conversation /> tag to Atom input/output Only uses ref attribute (not href) because href would be the alternate link that's always included also. Creates new conversation for every non-reply status. Carries over conversation for every reply. Keeps remote URIs verbatim, generates local URIs on the fly like the rest of them. * Conversation muting - prevents notifications that reference a conversation (including replies, favourites, reblogs) from being created. API endpoints /api/v1/statuses/:id/mute and /api/v1/statuses/:id/unmute Currently no way to tell when a status/conversation is muted, so the web UI only has a "disable notifications" button, doesn't work as a toggle * Display "Dismiss notifications" on all statuses in notifications column, not just own * Add "muted" as a boolean attribute on statuses JSON For now always false on contained reblogs, since it's only relevant for statuses returned from the notifications endpoint, which are not nested Remove "Disable notifications" from detailed status view, since it's only relevant in the notifications column * Up max class length * Remove pending test for conversation mute * Add tests, clean up * Rename to "mute conversation" and "unmute conversation" * Raise validation error when trying to mute/unmute status without conversation * Adding account domain blocks that filter notifications and public timelines * Add tests for domain blocks in notifications, public timelines Filter reblogs of blocked domains from home * Add API for listing and creating account domain blocks * API for creating/deleting domain blocks, tests for Status#ancestors and Status#descendants, filter domain blocks from them * Filter domains in streaming API * Update account_domain_block_spec.rb
7 years ago
Account domain blocks (#2381) * Add <ostatus:conversation /> tag to Atom input/output Only uses ref attribute (not href) because href would be the alternate link that's always included also. Creates new conversation for every non-reply status. Carries over conversation for every reply. Keeps remote URIs verbatim, generates local URIs on the fly like the rest of them. * Conversation muting - prevents notifications that reference a conversation (including replies, favourites, reblogs) from being created. API endpoints /api/v1/statuses/:id/mute and /api/v1/statuses/:id/unmute Currently no way to tell when a status/conversation is muted, so the web UI only has a "disable notifications" button, doesn't work as a toggle * Display "Dismiss notifications" on all statuses in notifications column, not just own * Add "muted" as a boolean attribute on statuses JSON For now always false on contained reblogs, since it's only relevant for statuses returned from the notifications endpoint, which are not nested Remove "Disable notifications" from detailed status view, since it's only relevant in the notifications column * Up max class length * Remove pending test for conversation mute * Add tests, clean up * Rename to "mute conversation" and "unmute conversation" * Raise validation error when trying to mute/unmute status without conversation * Adding account domain blocks that filter notifications and public timelines * Add tests for domain blocks in notifications, public timelines Filter reblogs of blocked domains from home * Add API for listing and creating account domain blocks * API for creating/deleting domain blocks, tests for Status#ancestors and Status#descendants, filter domain blocks from them * Filter domains in streaming API * Update account_domain_block_spec.rb
7 years ago
  1. import os from 'os';
  2. import throng from 'throng';
  3. import dotenv from 'dotenv';
  4. import express from 'express';
  5. import http from 'http';
  6. import redis from 'redis';
  7. import pg from 'pg';
  8. import log from 'npmlog';
  9. import url from 'url';
  10. import WebSocket from 'uws';
  11. import uuid from '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. database: 'mastodon_development',
  62. max: 10,
  63. },
  64. production: {
  65. user: process.env.DB_USER || 'mastodon',
  66. password: process.env.DB_PASS || '',
  67. database: process.env.DB_NAME || 'mastodon_production',
  68. host: process.env.DB_HOST || 'localhost',
  69. port: process.env.DB_PORT || 5432,
  70. max: 10,
  71. },
  72. };
  73. const app = express();
  74. const pgPool = new pg.Pool(Object.assign(pgConfigs[env], dbUrlToConfig(process.env.DATABASE_URL)));
  75. const server = http.createServer(app);
  76. const redisNamespace = process.env.REDIS_NAMESPACE || null;
  77. const redisParams = {
  78. host: process.env.REDIS_HOST || '127.0.0.1',
  79. port: process.env.REDIS_PORT || 6379,
  80. db: process.env.REDIS_DB || 0,
  81. password: process.env.REDIS_PASSWORD,
  82. };
  83. if (redisNamespace) {
  84. redisParams.namespace = redisNamespace;
  85. }
  86. const redisPrefix = redisNamespace ? `${redisNamespace}:` : '';
  87. const redisClient = redisUrlToClient(redisParams, process.env.REDIS_URL);
  88. const subs = {};
  89. redisClient.on('pmessage', (_, channel, message) => {
  90. const callbacks = subs[channel];
  91. log.silly(`New message on channel ${channel}`);
  92. if (!callbacks) {
  93. return;
  94. }
  95. callbacks.forEach(callback => callback(message));
  96. });
  97. redisClient.psubscribe(`${redisPrefix}timeline:*`);
  98. const subscribe = (channel, callback) => {
  99. log.silly(`Adding listener for ${channel}`);
  100. subs[channel] = subs[channel] || [];
  101. subs[channel].push(callback);
  102. };
  103. const unsubscribe = (channel, callback) => {
  104. log.silly(`Removing listener for ${channel}`);
  105. subs[channel] = subs[channel].filter(item => item !== callback);
  106. };
  107. const allowCrossDomain = (req, res, next) => {
  108. res.header('Access-Control-Allow-Origin', '*');
  109. res.header('Access-Control-Allow-Headers', 'Authorization, Accept, Cache-Control');
  110. res.header('Access-Control-Allow-Methods', 'GET, OPTIONS');
  111. next();
  112. };
  113. const setRequestId = (req, res, next) => {
  114. req.requestId = uuid.v4();
  115. res.header('X-Request-Id', req.requestId);
  116. next();
  117. };
  118. const accountFromToken = (token, req, next) => {
  119. pgPool.connect((err, client, done) => {
  120. if (err) {
  121. next(err);
  122. return;
  123. }
  124. 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) => {
  125. done();
  126. if (err) {
  127. next(err);
  128. return;
  129. }
  130. if (result.rows.length === 0) {
  131. err = new Error('Invalid access token');
  132. err.statusCode = 401;
  133. next(err);
  134. return;
  135. }
  136. req.accountId = result.rows[0].account_id;
  137. req.filteredLanguages = result.rows[0].filtered_languages;
  138. next();
  139. });
  140. });
  141. };
  142. const accountFromRequest = (req, next) => {
  143. const authorization = req.headers.authorization;
  144. const location = url.parse(req.url, true);
  145. const accessToken = location.query.access_token;
  146. if (!authorization && !accessToken) {
  147. const err = new Error('Missing access token');
  148. err.statusCode = 401;
  149. next(err);
  150. return;
  151. }
  152. const token = authorization ? authorization.replace(/^Bearer /, '') : accessToken;
  153. accountFromToken(token, req, next);
  154. };
  155. const wsVerifyClient = (info, cb) => {
  156. accountFromRequest(info.req, err => {
  157. if (!err) {
  158. cb(true, undefined, undefined);
  159. } else {
  160. log.error(info.req.requestId, err.toString());
  161. cb(false, 401, 'Unauthorized');
  162. }
  163. });
  164. };
  165. const authenticationMiddleware = (req, res, next) => {
  166. if (req.method === 'OPTIONS') {
  167. next();
  168. return;
  169. }
  170. accountFromRequest(req, next);
  171. };
  172. const errorMiddleware = (err, req, res, next) => {
  173. log.error(req.requestId, err.toString());
  174. res.writeHead(err.statusCode || 500, { 'Content-Type': 'application/json' });
  175. res.end(JSON.stringify({ error: err.statusCode ? err.toString() : 'An unexpected error occurred' }));
  176. };
  177. const placeholders = (arr, shift = 0) => arr.map((_, i) => `$${i + 1 + shift}`).join(', ');
  178. const streamFrom = (id, req, output, attachCloseHandler, needsFiltering = false) => {
  179. log.verbose(req.requestId, `Starting stream from ${id} for ${req.accountId}`);
  180. const listener = message => {
  181. const { event, payload, queued_at } = JSON.parse(message);
  182. const transmit = () => {
  183. const now = new Date().getTime();
  184. const delta = now - queued_at;
  185. log.silly(req.requestId, `Transmitting for ${req.accountId}: ${event} ${payload} Delay: ${delta}ms`);
  186. output(event, payload);
  187. };
  188. // Only messages that may require filtering are statuses, since notifications
  189. // are already personalized and deletes do not matter
  190. if (needsFiltering && event === 'update') {
  191. pgPool.connect((err, client, done) => {
  192. if (err) {
  193. log.error(err);
  194. return;
  195. }
  196. const unpackedPayload = JSON.parse(payload);
  197. const targetAccountIds = [unpackedPayload.account.id].concat(unpackedPayload.mentions.map(item => item.id));
  198. const accountDomain = unpackedPayload.account.acct.split('@')[1];
  199. if (Array.isArray(req.filteredLanguages) && req.filteredLanguages.includes(unpackedPayload.language)) {
  200. log.silly(req.requestId, `Message ${unpackedPayload.id} filtered by language (${unpackedPayload.language})`);
  201. done();
  202. return;
  203. }
  204. const queries = [
  205. 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)),
  206. ];
  207. if (accountDomain) {
  208. queries.push(client.query('SELECT 1 FROM account_domain_blocks WHERE account_id = $1 AND domain = $2', [req.accountId, accountDomain]));
  209. }
  210. Promise.all(queries).then(values => {
  211. done();
  212. if (values[0].rows.length > 0 || (values.length > 1 && values[1].rows.length > 0)) {
  213. return;
  214. }
  215. transmit();
  216. }).catch(err => {
  217. done();
  218. log.error(err);
  219. });
  220. });
  221. } else {
  222. transmit();
  223. }
  224. };
  225. subscribe(`${redisPrefix}${id}`, listener);
  226. attachCloseHandler(`${redisPrefix}${id}`, listener);
  227. };
  228. // Setup stream output to HTTP
  229. const streamToHttp = (req, res) => {
  230. res.setHeader('Content-Type', 'text/event-stream');
  231. res.setHeader('Transfer-Encoding', 'chunked');
  232. const heartbeat = setInterval(() => res.write(':thump\n'), 15000);
  233. req.on('close', () => {
  234. log.verbose(req.requestId, `Ending stream for ${req.accountId}`);
  235. clearInterval(heartbeat);
  236. });
  237. return (event, payload) => {
  238. res.write(`event: ${event}\n`);
  239. res.write(`data: ${payload}\n\n`);
  240. };
  241. };
  242. // Setup stream end for HTTP
  243. const streamHttpEnd = req => (id, listener) => {
  244. req.on('close', () => {
  245. unsubscribe(id, listener);
  246. });
  247. };
  248. // Setup stream output to WebSockets
  249. const streamToWs = (req, ws) => (event, payload) => {
  250. if (ws.readyState !== ws.OPEN) {
  251. log.error(req.requestId, 'Tried writing to closed socket');
  252. return;
  253. }
  254. ws.send(JSON.stringify({ event, payload }));
  255. };
  256. // Setup stream end for WebSockets
  257. const streamWsEnd = (req, ws) => (id, listener) => {
  258. ws.on('close', () => {
  259. log.verbose(req.requestId, `Ending stream for ${req.accountId}`);
  260. unsubscribe(id, listener);
  261. });
  262. ws.on('error', e => {
  263. log.verbose(req.requestId, `Ending stream for ${req.accountId}`);
  264. unsubscribe(id, listener);
  265. });
  266. };
  267. app.use(setRequestId);
  268. app.use(allowCrossDomain);
  269. app.use(authenticationMiddleware);
  270. app.use(errorMiddleware);
  271. app.get('/api/v1/streaming/user', (req, res) => {
  272. streamFrom(`timeline:${req.accountId}`, req, streamToHttp(req, res), streamHttpEnd(req));
  273. });
  274. app.get('/api/v1/streaming/public', (req, res) => {
  275. streamFrom('timeline:public', req, streamToHttp(req, res), streamHttpEnd(req), true);
  276. });
  277. app.get('/api/v1/streaming/public/local', (req, res) => {
  278. streamFrom('timeline:public:local', req, streamToHttp(req, res), streamHttpEnd(req), true);
  279. });
  280. app.get('/api/v1/streaming/hashtag', (req, res) => {
  281. streamFrom(`timeline:hashtag:${req.query.tag}`, req, streamToHttp(req, res), streamHttpEnd(req), true);
  282. });
  283. app.get('/api/v1/streaming/hashtag/local', (req, res) => {
  284. streamFrom(`timeline:hashtag:${req.query.tag}:local`, req, streamToHttp(req, res), streamHttpEnd(req), true);
  285. });
  286. const wss = new WebSocket.Server({ server, verifyClient: wsVerifyClient });
  287. wss.on('connection', ws => {
  288. const req = ws.upgradeReq;
  289. const location = url.parse(req.url, true);
  290. req.requestId = uuid.v4();
  291. ws.isAlive = true;
  292. ws.on('pong', () => {
  293. ws.isAlive = true;
  294. });
  295. switch(location.query.stream) {
  296. case 'user':
  297. streamFrom(`timeline:${req.accountId}`, req, streamToWs(req, ws), streamWsEnd(req, ws));
  298. break;
  299. case 'public':
  300. streamFrom('timeline:public', req, streamToWs(req, ws), streamWsEnd(req, ws), true);
  301. break;
  302. case 'public:local':
  303. streamFrom('timeline:public:local', req, streamToWs(req, ws), streamWsEnd(req, ws), true);
  304. break;
  305. case 'hashtag':
  306. streamFrom(`timeline:hashtag:${location.query.tag}`, req, streamToWs(req, ws), streamWsEnd(req, ws), true);
  307. break;
  308. case 'hashtag:local':
  309. streamFrom(`timeline:hashtag:${location.query.tag}:local`, req, streamToWs(req, ws), streamWsEnd(req, ws), true);
  310. break;
  311. default:
  312. ws.close();
  313. }
  314. });
  315. const wsInterval = setInterval(() => {
  316. wss.clients.forEach(ws => {
  317. if (ws.isAlive === false) {
  318. ws.terminate();
  319. return;
  320. }
  321. ws.isAlive = false;
  322. ws.ping('', false, true);
  323. });
  324. }, 30000);
  325. server.listen(process.env.PORT || 4000, () => {
  326. log.info(`Worker ${workerId} now listening on ${server.address().address}:${server.address().port}`);
  327. });
  328. const onExit = () => {
  329. log.info(`Worker ${workerId} exiting, bye bye`);
  330. server.close();
  331. };
  332. const onError = (err) => {
  333. log.error(err);
  334. };
  335. process.on('SIGINT', onExit);
  336. process.on('SIGTERM', onExit);
  337. process.on('exit', onExit);
  338. process.on('error', onError);
  339. };
  340. throng({
  341. workers: numWorkers,
  342. lifetime: Infinity,
  343. start: startWorker,
  344. master: startMaster,
  345. });