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.

134 lines
3.7 KiB

  1. import dotenv from 'dotenv'
  2. import express from 'express'
  3. import redis from 'redis'
  4. import pg from 'pg'
  5. import log from 'npmlog'
  6. dotenv.config()
  7. const pgConfigs = {
  8. development: {
  9. database: 'mastodon_development',
  10. host: '/var/run/postgresql',
  11. max: 10
  12. },
  13. production: {
  14. user: process.env.DB_USER || 'mastodon',
  15. password: process.env.DB_PASS || '',
  16. database: process.env.DB_NAME || 'mastodon_production',
  17. host: process.env.DB_HOST || 'localhost',
  18. port: process.env.DB_PORT || 5432,
  19. max: 10
  20. }
  21. }
  22. const app = express()
  23. const env = process.env.NODE_ENV || 'development'
  24. const pgPool = new pg.Pool(pgConfigs[env])
  25. const authenticationMiddleware = (req, res, next) => {
  26. const authorization = req.get('Authorization')
  27. if (!authorization) {
  28. err = new Error('Missing access token')
  29. err.statusCode = 401
  30. return next(err)
  31. }
  32. const token = authorization.replace(/^Bearer /, '')
  33. pgPool.connect((err, client, done) => {
  34. if (err) {
  35. log.error(err)
  36. return next(err)
  37. }
  38. 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 token = $1 LIMIT 1', [token], (err, result) => {
  39. done()
  40. if (err) {
  41. log.error(err)
  42. return next(err)
  43. }
  44. if (result.rows.length === 0) {
  45. err = new Error('Invalid access token')
  46. err.statusCode = 401
  47. return next(err)
  48. }
  49. req.accountId = result.rows[0].account_id
  50. next()
  51. })
  52. })
  53. }
  54. const errorMiddleware = (err, req, res, next) => {
  55. res.writeHead(err.statusCode || 500, { 'Content-Type': 'application/json' })
  56. res.end(JSON.stringify({ error: err.statusCode ? `${err}` : 'An unexpected error occured' }))
  57. }
  58. const streamFrom = (id, req, res, needsFiltering = false) => {
  59. log.verbose(`Starting stream from ${id} for ${req.accountId}`)
  60. res.setHeader('Content-Type', 'text/event-stream')
  61. res.setHeader('Transfer-Encoding', 'chunked')
  62. const redisClient = redis.createClient()
  63. redisClient.on('message', (channel, message) => {
  64. const { event, payload } = JSON.parse(message)
  65. if (needsFiltering) {
  66. pgPool.connect((err, client, done) => {
  67. if (err) {
  68. log.error(err)
  69. return
  70. }
  71. const unpackedPayload = JSON.parse(payload)
  72. const targetAccountIds = [unpackedPayload.account.id] + unpackedPayload.mentions.map(item => item.id) + (unpackedPayload.reblog ? unpackedPayload.reblog.account.id : [])
  73. client.query('SELECT target_account_id FROM blocks WHERE account_id = $1 AND target_account_id IN ($2)', [req.accountId, targetAccountIds], (err, result) => {
  74. done()
  75. if (err) {
  76. log.error(err)
  77. return
  78. }
  79. if (result.rows.length > 0) {
  80. return
  81. }
  82. res.write(`event: ${event}\n`)
  83. res.write(`data: ${payload}\n\n`)
  84. })
  85. })
  86. } else {
  87. res.write(`event: ${event}\n`)
  88. res.write(`data: ${payload}\n\n`)
  89. }
  90. })
  91. // Heartbeat to keep connection alive
  92. setInterval(() => res.write(':thump\n'), 15000)
  93. redisClient.subscribe(id)
  94. }
  95. app.use(authenticationMiddleware)
  96. app.use(errorMiddleware)
  97. app.get('/api/v1/streaming/user', (req, res) => streamFrom(`timeline:${req.accountId}`, req, res))
  98. app.get('/api/v1/streaming/public', (req, res) => streamFrom('timeline:public', req, res, true))
  99. app.get('/api/v1/streaming/hashtag', (req, res) => streamFrom(`timeline:hashtag:${req.params.tag}`, req, res, true))
  100. log.level = 'verbose'
  101. log.info(`Starting HTTP server on port ${process.env.PORT || 4000}`)
  102. app.listen(process.env.PORT || 4000)