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