Optimize actor follow scores modifications
[oweals/peertube.git] / server.ts
1 // FIXME: https://github.com/nodejs/node/pull/16853
2 require('tls').DEFAULT_ECDH_CURVE = 'auto'
3
4 import { isTestInstance } from './server/helpers/core-utils'
5
6 if (isTestInstance()) {
7   require('source-map-support').install()
8 }
9
10 // ----------- Node modules -----------
11 import * as bodyParser from 'body-parser'
12 import * as express from 'express'
13 import * as morgan from 'morgan'
14 import * as cors from 'cors'
15 import * as cookieParser from 'cookie-parser'
16 import * as helmet from 'helmet'
17 import * as useragent from 'useragent'
18 import * as anonymize from 'ip-anonymize'
19 import * as cli from 'commander'
20
21 process.title = 'peertube'
22
23 // Create our main app
24 const app = express()
25
26 // ----------- Core checker -----------
27 import { checkMissedConfig, checkFFmpeg } from './server/initializers/checker-before-init'
28
29 // Do not use barrels because we don't want to load all modules here (we need to initialize database first)
30 import { logger } from './server/helpers/logger'
31 import { API_VERSION, CONFIG, CACHE, HTTP_SIGNATURE } from './server/initializers/constants'
32
33 const missed = checkMissedConfig()
34 if (missed.length !== 0) {
35   logger.error('Your configuration files miss keys: ' + missed)
36   process.exit(-1)
37 }
38
39 checkFFmpeg(CONFIG)
40   .catch(err => {
41     logger.error('Error in ffmpeg check.', { err })
42     process.exit(-1)
43   })
44
45 import { checkConfig, checkActivityPubUrls } from './server/initializers/checker-after-init'
46
47 const errorMessage = checkConfig()
48 if (errorMessage !== null) {
49   throw new Error(errorMessage)
50 }
51
52 // Trust our proxy (IP forwarding...)
53 app.set('trust proxy', CONFIG.TRUST_PROXY)
54
55 // Security middleware
56 import { baseCSP } from './server/middlewares'
57
58 app.use(baseCSP)
59 app.use(helmet({
60   frameguard: {
61     action: 'deny' // we only allow it for /videos/embed, see server/controllers/client.ts
62   },
63   hsts: false
64 }))
65
66 // ----------- Database -----------
67
68 // Initialize database and models
69 import { initDatabaseModels } from './server/initializers/database'
70 import { migrate } from './server/initializers/migrator'
71 migrate()
72   .then(() => initDatabaseModels(false))
73   .then(() => startApplication())
74   .catch(err => {
75     logger.error('Cannot start application.', { err })
76     process.exit(-1)
77   })
78
79 // ----------- PeerTube modules -----------
80 import { installApplication } from './server/initializers'
81 import { Emailer } from './server/lib/emailer'
82 import { JobQueue } from './server/lib/job-queue'
83 import { VideosPreviewCache, VideosCaptionCache } from './server/lib/cache'
84 import {
85   activityPubRouter,
86   apiRouter,
87   clientsRouter,
88   feedsRouter,
89   staticRouter,
90   servicesRouter,
91   webfingerRouter,
92   trackerRouter,
93   createWebsocketServer, botsRouter
94 } from './server/controllers'
95 import { advertiseDoNotTrack } from './server/middlewares/dnt'
96 import { Redis } from './server/lib/redis'
97 import { ActorFollowScheduler } from './server/lib/schedulers/actor-follow-scheduler'
98 import { RemoveOldJobsScheduler } from './server/lib/schedulers/remove-old-jobs-scheduler'
99 import { UpdateVideosScheduler } from './server/lib/schedulers/update-videos-scheduler'
100 import { YoutubeDlUpdateScheduler } from './server/lib/schedulers/youtube-dl-update-scheduler'
101 import { VideosRedundancyScheduler } from './server/lib/schedulers/videos-redundancy-scheduler'
102 import { isHTTPSignatureDigestValid } from './server/helpers/peertube-crypto'
103
104 // ----------- Command line -----------
105
106 cli
107   .option('--no-client', 'Start PeerTube without client interface')
108   .parse(process.argv)
109
110 // ----------- App -----------
111
112 // Enable CORS for develop
113 if (isTestInstance()) {
114   app.use(cors({
115     origin: '*',
116     exposedHeaders: 'Retry-After',
117     credentials: true
118   }))
119 }
120 // For the logger
121 morgan.token('remote-addr', req => {
122   return (req.get('DNT') === '1') ?
123     anonymize(req.ip || (req.connection && req.connection.remoteAddress) || undefined,
124     16, // bitmask for IPv4
125     16  // bitmask for IPv6
126     ) :
127     req.ip
128 })
129 morgan.token('user-agent', req => (req.get('DNT') === '1') ?
130   useragent.parse(req.get('user-agent')).family : req.get('user-agent'))
131 app.use(morgan('combined', {
132   stream: { write: logger.info.bind(logger) }
133 }))
134 // For body requests
135 app.use(bodyParser.urlencoded({ extended: false }))
136 app.use(bodyParser.json({
137   type: [ 'application/json', 'application/*+json' ],
138   limit: '500kb',
139   verify: (req: express.Request, _, buf: Buffer, encoding: string) => {
140     const valid = isHTTPSignatureDigestValid(buf, req)
141     if (valid !== true) throw new Error('Invalid digest')
142   }
143 }))
144 // Cookies
145 app.use(cookieParser())
146 // W3C DNT Tracking Status
147 app.use(advertiseDoNotTrack)
148
149 // ----------- Views, routes and static files -----------
150
151 // API
152 const apiRoute = '/api/' + API_VERSION
153 app.use(apiRoute, apiRouter)
154
155 // Services (oembed...)
156 app.use('/services', servicesRouter)
157
158 app.use('/', activityPubRouter)
159 app.use('/', feedsRouter)
160 app.use('/', webfingerRouter)
161 app.use('/', trackerRouter)
162 app.use('/', botsRouter)
163
164 // Static files
165 app.use('/', staticRouter)
166
167 // Client files, last valid routes!
168 if (cli.client) app.use('/', clientsRouter)
169
170 // ----------- Errors -----------
171
172 // Catch 404 and forward to error handler
173 app.use(function (req, res, next) {
174   const err = new Error('Not Found')
175   err['status'] = 404
176   next(err)
177 })
178
179 app.use(function (err, req, res, next) {
180   let error = 'Unknown error.'
181   if (err) {
182     error = err.stack || err.message || err
183   }
184
185   // Sequelize error
186   const sql = err.parent ? err.parent.sql : undefined
187
188   logger.error('Error in controller.', { err: error, sql })
189   return res.status(err.status || 500).end()
190 })
191
192 const server = createWebsocketServer(app)
193
194 // ----------- Run -----------
195
196 async function startApplication () {
197   const port = CONFIG.LISTEN.PORT
198   const hostname = CONFIG.LISTEN.HOSTNAME
199
200   await installApplication()
201
202   // Check activity pub urls are valid
203   checkActivityPubUrls()
204     .catch(err => {
205       logger.error('Error in ActivityPub URLs checker.', { err })
206       process.exit(-1)
207     })
208
209   // Email initialization
210   Emailer.Instance.init()
211
212   await Promise.all([
213     Emailer.Instance.checkConnectionOrDie(),
214     JobQueue.Instance.init()
215   ])
216
217   // Caches initializations
218   VideosPreviewCache.Instance.init(CONFIG.CACHE.PREVIEWS.SIZE, CACHE.PREVIEWS.MAX_AGE)
219   VideosCaptionCache.Instance.init(CONFIG.CACHE.VIDEO_CAPTIONS.SIZE, CACHE.VIDEO_CAPTIONS.MAX_AGE)
220
221   // Enable Schedulers
222   ActorFollowScheduler.Instance.enable()
223   RemoveOldJobsScheduler.Instance.enable()
224   UpdateVideosScheduler.Instance.enable()
225   YoutubeDlUpdateScheduler.Instance.enable()
226   VideosRedundancyScheduler.Instance.enable()
227
228   // Redis initialization
229   Redis.Instance.init()
230
231   // Make server listening
232   server.listen(port, hostname, () => {
233     logger.info('Server listening on %s:%d', hostname, port)
234     logger.info('Web server: %s', CONFIG.WEBSERVER.URL)
235   })
236
237   process.on('exit', () => {
238     JobQueue.Instance.terminate()
239   })
240
241   process.on('SIGINT', () => process.exit(0))
242 }