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

313 lines
8.5 KiB

  1. import dotenv from 'dotenv'
  2. import express from 'express'
  3. import http from 'http'
  4. import redis from 'redis'
  5. import pg from 'pg'
  6. import log from 'npmlog'
  7. import url from 'url'
  8. import WebSocket from 'ws'
  9. import uuid from 'uuid'
  10. const env = process.env.NODE_ENV || 'development'
  11. dotenv.config({
  12. path: env === 'production' ? '.env.production' : '.env'
  13. })
  14. const pgConfigs = {
  15. development: {
  16. database: 'mastodon_development',
  17. host: '/var/run/postgresql',
  18. max: 10
  19. },
  20. production: {
  21. user: process.env.DB_USER || 'mastodon',
  22. password: process.env.DB_PASS || '',
  23. database: process.env.DB_NAME || 'mastodon_production',
  24. host: process.env.DB_HOST || 'localhost',
  25. port: process.env.DB_PORT || 5432,
  26. max: 10
  27. }
  28. }
  29. const app = express()
  30. const pgPool = new pg.Pool(pgConfigs[env])
  31. const server = http.createServer(app)
  32. const wss = new WebSocket.Server({ server })
  33. const redisClient = redis.createClient({
  34. host: process.env.REDIS_HOST || '127.0.0.1',
  35. port: process.env.REDIS_PORT || 6379,
  36. password: process.env.REDIS_PASSWORD
  37. })
  38. const subs = {}
  39. redisClient.on('pmessage', (_, channel, message) => {
  40. const callbacks = subs[channel]
  41. log.silly(`New message on channel ${channel}`)
  42. if (!callbacks) {
  43. return
  44. }
  45. callbacks.forEach(callback => callback(message))
  46. })
  47. redisClient.psubscribe('timeline:*')
  48. const subscribe = (channel, callback) => {
  49. log.silly(`Adding listener for ${channel}`)
  50. subs[channel] = subs[channel] || []
  51. subs[channel].push(callback)
  52. }
  53. const unsubscribe = (channel, callback) => {
  54. log.silly(`Removing listener for ${channel}`)
  55. subs[channel] = subs[channel].filter(item => item !== callback)
  56. }
  57. const allowCrossDomain = (req, res, next) => {
  58. res.header('Access-Control-Allow-Origin', '*')
  59. res.header('Access-Control-Allow-Headers', 'Authorization, Accept, Cache-Control')
  60. res.header('Access-Control-Allow-Methods', 'GET, OPTIONS')
  61. next()
  62. }
  63. const setRequestId = (req, res, next) => {
  64. req.requestId = uuid.v4()
  65. res.header('X-Request-Id', req.requestId)
  66. next()
  67. }
  68. const accountFromToken = (token, req, next) => {
  69. pgPool.connect((err, client, done) => {
  70. if (err) {
  71. next(err)
  72. return
  73. }
  74. 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) => {
  75. done()
  76. if (err) {
  77. next(err)
  78. return
  79. }
  80. if (result.rows.length === 0) {
  81. err = new Error('Invalid access token')
  82. err.statusCode = 401
  83. next(err)
  84. return
  85. }
  86. req.accountId = result.rows[0].account_id
  87. next()
  88. })
  89. })
  90. }
  91. const authenticationMiddleware = (req, res, next) => {
  92. if (req.method === 'OPTIONS') {
  93. next()
  94. return
  95. }
  96. const authorization = req.get('Authorization')
  97. if (!authorization) {
  98. const err = new Error('Missing access token')
  99. err.statusCode = 401
  100. next(err)
  101. return
  102. }
  103. const token = authorization.replace(/^Bearer /, '')
  104. accountFromToken(token, req, next)
  105. }
  106. const errorMiddleware = (err, req, res, next) => {
  107. log.error(req.requestId, err)
  108. res.writeHead(err.statusCode || 500, { 'Content-Type': 'application/json' })
  109. res.end(JSON.stringify({ error: err.statusCode ? `${err}` : 'An unexpected error occurred' }))
  110. }
  111. const placeholders = (arr, shift = 0) => arr.map((_, i) => `$${i + 1 + shift}`).join(', ');
  112. const streamFrom = (id, req, output, attachCloseHandler, needsFiltering = false) => {
  113. log.verbose(req.requestId, `Starting stream from ${id} for ${req.accountId}`)
  114. const listener = message => {
  115. const { event, payload, queued_at } = JSON.parse(message)
  116. const transmit = () => {
  117. const now = new Date().getTime()
  118. const delta = now - queued_at;
  119. log.silly(req.requestId, `Transmitting for ${req.accountId}: ${event} ${payload} Delay: ${delta}ms`)
  120. output(event, payload)
  121. }
  122. // Only messages that may require filtering are statuses, since notifications
  123. // are already personalized and deletes do not matter
  124. if (needsFiltering && event === 'update') {
  125. pgPool.connect((err, client, done) => {
  126. if (err) {
  127. log.error(err)
  128. return
  129. }
  130. const unpackedPayload = JSON.parse(payload)
  131. const targetAccountIds = [unpackedPayload.account.id].concat(unpackedPayload.mentions.map(item => item.id)).concat(unpackedPayload.reblog ? [unpackedPayload.reblog.account.id] : [])
  132. client.query(`SELECT target_account_id FROM blocks WHERE account_id = $1 AND target_account_id IN (${placeholders(targetAccountIds, 1)}) UNION SELECT target_account_id FROM mutes WHERE account_id = $1 AND target_account_id IN (${placeholders(targetAccountIds, 1)})`, [req.accountId].concat(targetAccountIds), (err, result) => {
  133. done()
  134. if (err) {
  135. log.error(err)
  136. return
  137. }
  138. if (result.rows.length > 0) {
  139. return
  140. }
  141. transmit()
  142. })
  143. })
  144. } else {
  145. transmit()
  146. }
  147. }
  148. subscribe(id, listener)
  149. attachCloseHandler(id, listener)
  150. }
  151. // Setup stream output to HTTP
  152. const streamToHttp = (req, res) => {
  153. res.setHeader('Content-Type', 'text/event-stream')
  154. res.setHeader('Transfer-Encoding', 'chunked')
  155. const heartbeat = setInterval(() => res.write(':thump\n'), 15000)
  156. req.on('close', () => {
  157. log.verbose(req.requestId, `Ending stream for ${req.accountId}`)
  158. clearInterval(heartbeat)
  159. })
  160. return (event, payload) => {
  161. res.write(`event: ${event}\n`)
  162. res.write(`data: ${payload}\n\n`)
  163. }
  164. }
  165. // Setup stream end for HTTP
  166. const streamHttpEnd = req => (id, listener) => {
  167. req.on('close', () => {
  168. unsubscribe(id, listener)
  169. })
  170. }
  171. // Setup stream output to WebSockets
  172. const streamToWs = (req, ws) => {
  173. const heartbeat = setInterval(() => ws.ping(), 15000)
  174. ws.on('close', () => {
  175. log.verbose(req.requestId, `Ending stream for ${req.accountId}`)
  176. clearInterval(heartbeat)
  177. })
  178. return (event, payload) => {
  179. if (ws.readyState !== ws.OPEN) {
  180. log.error(req.requestId, 'Tried writing to closed socket')
  181. return
  182. }
  183. ws.send(JSON.stringify({ event, payload }))
  184. }
  185. }
  186. // Setup stream end for WebSockets
  187. const streamWsEnd = ws => (id, listener) => {
  188. ws.on('close', () => {
  189. unsubscribe(id, listener)
  190. })
  191. ws.on('error', e => {
  192. unsubscribe(id, listener)
  193. })
  194. }
  195. app.use(setRequestId)
  196. app.use(allowCrossDomain)
  197. app.use(authenticationMiddleware)
  198. app.use(errorMiddleware)
  199. app.get('/api/v1/streaming/user', (req, res) => {
  200. streamFrom(`timeline:${req.accountId}`, req, streamToHttp(req, res), streamHttpEnd(req))
  201. })
  202. app.get('/api/v1/streaming/public', (req, res) => {
  203. streamFrom('timeline:public', req, streamToHttp(req, res), streamHttpEnd(req), true)
  204. })
  205. app.get('/api/v1/streaming/public/local', (req, res) => {
  206. streamFrom('timeline:public:local', req, streamToHttp(req, res), streamHttpEnd(req), true)
  207. })
  208. app.get('/api/v1/streaming/hashtag', (req, res) => {
  209. streamFrom(`timeline:hashtag:${req.params.tag}`, req, streamToHttp(req, res), streamHttpEnd(req), true)
  210. })
  211. app.get('/api/v1/streaming/hashtag/local', (req, res) => {
  212. streamFrom(`timeline:hashtag:${req.params.tag}:local`, req, streamToHttp(req, res), streamHttpEnd(req), true)
  213. })
  214. wss.on('connection', ws => {
  215. const location = url.parse(ws.upgradeReq.url, true)
  216. const token = location.query.access_token
  217. const req = { requestId: uuid.v4() }
  218. accountFromToken(token, req, err => {
  219. if (err) {
  220. log.error(req.requestId, err)
  221. ws.close()
  222. return
  223. }
  224. switch(location.query.stream) {
  225. case 'user':
  226. streamFrom(`timeline:${req.accountId}`, req, streamToWs(req, ws), streamWsEnd(ws))
  227. break;
  228. case 'public':
  229. streamFrom('timeline:public', req, streamToWs(req, ws), streamWsEnd(ws), true)
  230. break;
  231. case 'public:local':
  232. streamFrom('timeline:public:local', req, streamToWs(req, ws), streamWsEnd(ws), true)
  233. break;
  234. case 'hashtag':
  235. streamFrom(`timeline:hashtag:${location.query.tag}`, req, streamToWs(req, ws), streamWsEnd(ws), true)
  236. break;
  237. case 'hashtag:local':
  238. streamFrom(`timeline:hashtag:${location.query.tag}:local`, req, streamToWs(req, ws), streamWsEnd(ws), true)
  239. break;
  240. default:
  241. ws.close()
  242. }
  243. })
  244. })
  245. server.listen(process.env.PORT || 4000, () => {
  246. log.level = process.env.LOG_LEVEL || 'verbose'
  247. log.info(`Starting streaming API server on port ${server.address().port}`)
  248. })