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