闭社主体 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.

410 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 cluster from 'cluster';
  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. const dbUrlToConfig = (dbUrl) => {
  17. if (!dbUrl) {
  18. return {};
  19. }
  20. const params = url.parse(dbUrl);
  21. const config = {};
  22. if (params.auth) {
  23. [config.user, config.password] = params.auth.split(':');
  24. }
  25. if (params.hostname) {
  26. config.host = params.hostname;
  27. }
  28. if (params.port) {
  29. config.port = params.port;
  30. }
  31. if (params.pathname) {
  32. config.database = params.pathname.split('/')[1];
  33. }
  34. const ssl = params.query && params.query.ssl;
  35. if (ssl) {
  36. config.ssl = ssl === 'true' || ssl === '1';
  37. }
  38. return config;
  39. };
  40. const redisUrlToClient = (defaultConfig, redisUrl) => {
  41. const config = defaultConfig;
  42. if (!redisUrl) {
  43. return redis.createClient(config);
  44. }
  45. if (redisUrl.startsWith('unix://')) {
  46. return redis.createClient(redisUrl.slice(7), config);
  47. }
  48. return redis.createClient(Object.assign(config, {
  49. url: redisUrl,
  50. }));
  51. };
  52. if (cluster.isMaster) {
  53. // Cluster master
  54. const core = +process.env.STREAMING_CLUSTER_NUM || (env === 'development' ? 1 : Math.max(os.cpus().length - 1, 1));
  55. const fork = () => {
  56. const worker = cluster.fork();
  57. worker.on('exit', (code, signal) => {
  58. log.error(`Worker died with exit code ${code}, signal ${signal} received.`);
  59. setTimeout(() => fork(), 0);
  60. });
  61. };
  62. for (let i = 0; i < core; i++) fork();
  63. log.info(`Starting streaming API server master with ${core} workers`);
  64. } else {
  65. // Cluster worker
  66. const pgConfigs = {
  67. development: {
  68. database: 'mastodon_development',
  69. max: 10,
  70. },
  71. production: {
  72. user: process.env.DB_USER || 'mastodon',
  73. password: process.env.DB_PASS || '',
  74. database: process.env.DB_NAME || 'mastodon_production',
  75. host: process.env.DB_HOST || 'localhost',
  76. port: process.env.DB_PORT || 5432,
  77. max: 10,
  78. },
  79. };
  80. const app = express();
  81. const pgPool = new pg.Pool(Object.assign(pgConfigs[env], dbUrlToConfig(process.env.DATABASE_URL)));
  82. const server = http.createServer(app);
  83. const wss = new WebSocket.Server({ server });
  84. const redisNamespace = process.env.REDIS_NAMESPACE || null;
  85. const redisParams = {
  86. host: process.env.REDIS_HOST || '127.0.0.1',
  87. port: process.env.REDIS_PORT || 6379,
  88. db: process.env.REDIS_DB || 0,
  89. password: process.env.REDIS_PASSWORD,
  90. };
  91. if (redisNamespace) {
  92. redisParams.namespace = redisNamespace;
  93. }
  94. const redisPrefix = redisNamespace ? `${redisNamespace}:` : '';
  95. const redisClient = redisUrlToClient(redisParams, process.env.REDIS_URL);
  96. const subs = {};
  97. redisClient.on('pmessage', (_, channel, message) => {
  98. const callbacks = subs[channel];
  99. log.silly(`New message on channel ${channel}`);
  100. if (!callbacks) {
  101. return;
  102. }
  103. callbacks.forEach(callback => callback(message));
  104. });
  105. redisClient.psubscribe(`${redisPrefix}timeline:*`);
  106. const subscribe = (channel, callback) => {
  107. log.silly(`Adding listener for ${channel}`);
  108. subs[channel] = subs[channel] || [];
  109. subs[channel].push(callback);
  110. };
  111. const unsubscribe = (channel, callback) => {
  112. log.silly(`Removing listener for ${channel}`);
  113. subs[channel] = subs[channel].filter(item => item !== callback);
  114. };
  115. const allowCrossDomain = (req, res, next) => {
  116. res.header('Access-Control-Allow-Origin', '*');
  117. res.header('Access-Control-Allow-Headers', 'Authorization, Accept, Cache-Control');
  118. res.header('Access-Control-Allow-Methods', 'GET, OPTIONS');
  119. next();
  120. };
  121. const setRequestId = (req, res, next) => {
  122. req.requestId = uuid.v4();
  123. res.header('X-Request-Id', req.requestId);
  124. next();
  125. };
  126. const accountFromToken = (token, req, next) => {
  127. pgPool.connect((err, client, done) => {
  128. if (err) {
  129. next(err);
  130. return;
  131. }
  132. client.query('SELECT oauth_access_tokens.resource_owner_id, users.account_id FROM oauth_access_tokens INNER JOIN users ON oauth_access_tokens.resource_owner_id = users.id WHERE oauth_access_tokens.token = $1 LIMIT 1', [token], (err, result) => {
  133. done();
  134. if (err) {
  135. next(err);
  136. return;
  137. }
  138. if (result.rows.length === 0) {
  139. err = new Error('Invalid access token');
  140. err.statusCode = 401;
  141. next(err);
  142. return;
  143. }
  144. req.accountId = result.rows[0].account_id;
  145. next();
  146. });
  147. });
  148. };
  149. const authenticationMiddleware = (req, res, next) => {
  150. if (req.method === 'OPTIONS') {
  151. next();
  152. return;
  153. }
  154. const authorization = req.get('Authorization');
  155. const accessToken = req.query.access_token;
  156. if (!authorization && !accessToken) {
  157. const err = new Error('Missing access token');
  158. err.statusCode = 401;
  159. next(err);
  160. return;
  161. }
  162. const token = authorization ? authorization.replace(/^Bearer /, '') : accessToken;
  163. accountFromToken(token, req, next);
  164. };
  165. const errorMiddleware = (err, req, res, next) => {
  166. log.error(req.requestId, err);
  167. res.writeHead(err.statusCode || 500, { 'Content-Type': 'application/json' });
  168. res.end(JSON.stringify({ error: err.statusCode ? `${err}` : 'An unexpected error occurred' }));
  169. };
  170. const placeholders = (arr, shift = 0) => arr.map((_, i) => `$${i + 1 + shift}`).join(', ');
  171. const streamFrom = (id, req, output, attachCloseHandler, needsFiltering = false) => {
  172. log.verbose(req.requestId, `Starting stream from ${id} for ${req.accountId}`);
  173. const listener = message => {
  174. const { event, payload, queued_at } = JSON.parse(message);
  175. const transmit = () => {
  176. const now = new Date().getTime();
  177. const delta = now - queued_at;
  178. log.silly(req.requestId, `Transmitting for ${req.accountId}: ${event} ${payload} Delay: ${delta}ms`);
  179. output(event, payload);
  180. };
  181. // Only messages that may require filtering are statuses, since notifications
  182. // are already personalized and deletes do not matter
  183. if (needsFiltering && event === 'update') {
  184. pgPool.connect((err, client, done) => {
  185. if (err) {
  186. log.error(err);
  187. return;
  188. }
  189. const unpackedPayload = JSON.parse(payload);
  190. const targetAccountIds = [unpackedPayload.account.id].concat(unpackedPayload.mentions.map(item => item.id)).concat(unpackedPayload.reblog ? [unpackedPayload.reblog.account.id] : []);
  191. const accountDomain = unpackedPayload.account.acct.split('@')[1];
  192. const queries = [
  193. client.query(`SELECT 1 FROM blocks WHERE account_id = $1 AND target_account_id IN (${placeholders(targetAccountIds, 1)}) UNION SELECT 1 FROM mutes WHERE account_id = $1 AND target_account_id IN (${placeholders(targetAccountIds, 1)})`, [req.accountId].concat(targetAccountIds)),
  194. ];
  195. if (accountDomain) {
  196. queries.push(client.query('SELECT 1 FROM account_domain_blocks WHERE account_id = $1 AND domain = $2', [req.accountId, accountDomain]));
  197. }
  198. Promise.all(queries).then(values => {
  199. done();
  200. if (values[0].rows.length > 0 || (values.length > 1 && values[1].rows.length > 0)) {
  201. return;
  202. }
  203. transmit();
  204. }).catch(err => {
  205. log.error(err);
  206. });
  207. });
  208. } else {
  209. transmit();
  210. }
  211. };
  212. subscribe(`${redisPrefix}${id}`, listener);
  213. attachCloseHandler(`${redisPrefix}${id}`, listener);
  214. };
  215. // Setup stream output to HTTP
  216. const streamToHttp = (req, res) => {
  217. res.setHeader('Content-Type', 'text/event-stream');
  218. res.setHeader('Transfer-Encoding', 'chunked');
  219. const heartbeat = setInterval(() => res.write(':thump\n'), 15000);
  220. req.on('close', () => {
  221. log.verbose(req.requestId, `Ending stream for ${req.accountId}`);
  222. clearInterval(heartbeat);
  223. });
  224. return (event, payload) => {
  225. res.write(`event: ${event}\n`);
  226. res.write(`data: ${payload}\n\n`);
  227. };
  228. };
  229. // Setup stream end for HTTP
  230. const streamHttpEnd = req => (id, listener) => {
  231. req.on('close', () => {
  232. unsubscribe(id, listener);
  233. });
  234. };
  235. // Setup stream output to WebSockets
  236. const streamToWs = (req, ws) => {
  237. const heartbeat = setInterval(() => {
  238. // TODO: Can't add multiple listeners, due to the limitation of uws.
  239. if (ws.readyState !== ws.OPEN) {
  240. log.verbose(req.requestId, `Ending stream for ${req.accountId}`);
  241. clearInterval(heartbeat);
  242. return;
  243. }
  244. ws.ping();
  245. }, 15000);
  246. return (event, payload) => {
  247. if (ws.readyState !== ws.OPEN) {
  248. log.error(req.requestId, 'Tried writing to closed socket');
  249. return;
  250. }
  251. ws.send(JSON.stringify({ event, payload }));
  252. };
  253. };
  254. // Setup stream end for WebSockets
  255. const streamWsEnd = ws => (id, listener) => {
  256. ws.on('close', () => {
  257. unsubscribe(id, listener);
  258. });
  259. ws.on('error', e => {
  260. unsubscribe(id, listener);
  261. });
  262. };
  263. app.use(setRequestId);
  264. app.use(allowCrossDomain);
  265. app.use(authenticationMiddleware);
  266. app.use(errorMiddleware);
  267. app.get('/api/v1/streaming/user', (req, res) => {
  268. streamFrom(`timeline:${req.accountId}`, req, streamToHttp(req, res), streamHttpEnd(req));
  269. });
  270. app.get('/api/v1/streaming/public', (req, res) => {
  271. streamFrom('timeline:public', req, streamToHttp(req, res), streamHttpEnd(req), true);
  272. });
  273. app.get('/api/v1/streaming/public/local', (req, res) => {
  274. streamFrom('timeline:public:local', req, streamToHttp(req, res), streamHttpEnd(req), true);
  275. });
  276. app.get('/api/v1/streaming/hashtag', (req, res) => {
  277. streamFrom(`timeline:hashtag:${req.query.tag}`, req, streamToHttp(req, res), streamHttpEnd(req), true);
  278. });
  279. app.get('/api/v1/streaming/hashtag/local', (req, res) => {
  280. streamFrom(`timeline:hashtag:${req.query.tag}:local`, req, streamToHttp(req, res), streamHttpEnd(req), true);
  281. });
  282. wss.on('connection', ws => {
  283. const location = url.parse(ws.upgradeReq.url, true);
  284. const token = location.query.access_token;
  285. const req = { requestId: uuid.v4() };
  286. accountFromToken(token, req, err => {
  287. if (err) {
  288. log.error(req.requestId, err);
  289. ws.close();
  290. return;
  291. }
  292. switch(location.query.stream) {
  293. case 'user':
  294. streamFrom(`timeline:${req.accountId}`, req, streamToWs(req, ws), streamWsEnd(ws));
  295. break;
  296. case 'public':
  297. streamFrom('timeline:public', req, streamToWs(req, ws), streamWsEnd(ws), true);
  298. break;
  299. case 'public:local':
  300. streamFrom('timeline:public:local', req, streamToWs(req, ws), streamWsEnd(ws), true);
  301. break;
  302. case 'hashtag':
  303. streamFrom(`timeline:hashtag:${location.query.tag}`, req, streamToWs(req, ws), streamWsEnd(ws), true);
  304. break;
  305. case 'hashtag:local':
  306. streamFrom(`timeline:hashtag:${location.query.tag}:local`, req, streamToWs(req, ws), streamWsEnd(ws), true);
  307. break;
  308. default:
  309. ws.close();
  310. }
  311. });
  312. });
  313. server.listen(process.env.PORT || 4000, () => {
  314. log.level = process.env.LOG_LEVEL || 'verbose';
  315. log.info(`Starting streaming API server worker on ${server.address().address}:${server.address().port}`);
  316. });
  317. process.on('SIGINT', exit);
  318. process.on('SIGTERM', exit);
  319. process.on('exit', exit);
  320. function exit() {
  321. server.close();
  322. }
  323. }