]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server.ts
refactor API errors to standard error format
[github/Chocobozzz/PeerTube.git] / server.ts
1 import { registerTSPaths } from './server/helpers/register-ts-paths'
2 registerTSPaths()
3
4 import { isTestInstance } from './server/helpers/core-utils'
5 if (isTestInstance()) {
6 require('source-map-support').install()
7 }
8
9 // ----------- Node modules -----------
10 import * as bodyParser from 'body-parser'
11 import * as express from 'express'
12 import * as morgan from 'morgan'
13 import * as cors from 'cors'
14 import * as cookieParser from 'cookie-parser'
15 import * as helmet from 'helmet'
16 import * as useragent from 'useragent'
17 import * as anonymize from 'ip-anonymize'
18 import * as cli from 'commander'
19
20 process.title = 'peertube'
21
22 // Create our main app
23 const app = express().disable("x-powered-by")
24
25 // ----------- Core checker -----------
26 import { checkMissedConfig, checkFFmpeg, checkNodeVersion } 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 { CONFIG } from './server/initializers/config'
30 import { API_VERSION, FILES_CACHE, WEBSERVER, loadLanguages } from './server/initializers/constants'
31 import { logger } from './server/helpers/logger'
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 checkNodeVersion()
46
47 import { checkConfig, checkActivityPubUrls, checkFFmpegVersion } from './server/initializers/checker-after-init'
48
49 const errorMessage = checkConfig()
50 if (errorMessage !== null) {
51 throw new Error(errorMessage)
52 }
53
54 // Trust our proxy (IP forwarding...)
55 app.set('trust proxy', CONFIG.TRUST_PROXY)
56
57 // Security middleware
58 import { baseCSP } from './server/middlewares/csp'
59
60 if (CONFIG.CSP.ENABLED) {
61 app.use(baseCSP)
62 }
63
64 if (CONFIG.SECURITY.FRAMEGUARD.ENABLED) {
65 app.use(helmet.frameguard({
66 action: 'deny' // we only allow it for /videos/embed, see server/controllers/client.ts
67 }))
68 }
69
70 // ----------- Database -----------
71
72 // Initialize database and models
73 import { initDatabaseModels, checkDatabaseConnectionOrDie } from './server/initializers/database'
74 checkDatabaseConnectionOrDie()
75
76 import { migrate } from './server/initializers/migrator'
77 migrate()
78 .then(() => initDatabaseModels(false))
79 .then(() => startApplication())
80 .catch(err => {
81 logger.error('Cannot start application.', { err })
82 process.exit(-1)
83 })
84
85 // ----------- Initialize -----------
86 loadLanguages()
87
88 // ----------- PeerTube modules -----------
89 import { installApplication } from './server/initializers/installer'
90 import { Emailer } from './server/lib/emailer'
91 import { JobQueue } from './server/lib/job-queue'
92 import { VideosPreviewCache, VideosCaptionCache } from './server/lib/files-cache'
93 import {
94 activityPubRouter,
95 apiRouter,
96 clientsRouter,
97 feedsRouter,
98 staticRouter,
99 lazyStaticRouter,
100 servicesRouter,
101 liveRouter,
102 pluginsRouter,
103 webfingerRouter,
104 trackerRouter,
105 createWebsocketTrackerServer,
106 botsRouter,
107 downloadRouter
108 } from './server/controllers'
109 import { advertiseDoNotTrack } from './server/middlewares/dnt'
110 import { Redis } from './server/lib/redis'
111 import { ActorFollowScheduler } from './server/lib/schedulers/actor-follow-scheduler'
112 import { RemoveOldViewsScheduler } from './server/lib/schedulers/remove-old-views-scheduler'
113 import { RemoveOldJobsScheduler } from './server/lib/schedulers/remove-old-jobs-scheduler'
114 import { UpdateVideosScheduler } from './server/lib/schedulers/update-videos-scheduler'
115 import { YoutubeDlUpdateScheduler } from './server/lib/schedulers/youtube-dl-update-scheduler'
116 import { VideosRedundancyScheduler } from './server/lib/schedulers/videos-redundancy-scheduler'
117 import { RemoveOldHistoryScheduler } from './server/lib/schedulers/remove-old-history-scheduler'
118 import { AutoFollowIndexInstances } from './server/lib/schedulers/auto-follow-index-instances'
119 import { RemoveDanglingResumableUploadsScheduler } from './server/lib/schedulers/remove-dangling-resumable-uploads-scheduler'
120 import { isHTTPSignatureDigestValid } from './server/helpers/peertube-crypto'
121 import { PeerTubeSocket } from './server/lib/peertube-socket'
122 import { updateStreamingPlaylistsInfohashesIfNeeded } from './server/lib/hls'
123 import { PluginsCheckScheduler } from './server/lib/schedulers/plugins-check-scheduler'
124 import { PeerTubeVersionCheckScheduler } from './server/lib/schedulers/peertube-version-check-scheduler'
125 import { Hooks } from './server/lib/plugins/hooks'
126 import { PluginManager } from './server/lib/plugins/plugin-manager'
127 import { LiveManager } from './server/lib/live-manager'
128 import { HttpStatusCode } from './shared/core-utils/miscs/http-error-codes'
129 import { VideosTorrentCache } from '@server/lib/files-cache/videos-torrent-cache'
130 import { ServerConfigManager } from '@server/lib/server-config-manager'
131 import { apiResponseHelpers } from '@server/helpers/express-utils'
132
133 // ----------- Command line -----------
134
135 cli
136 .option('--no-client', 'Start PeerTube without client interface')
137 .option('--no-plugins', 'Start PeerTube without plugins/themes enabled')
138 .parse(process.argv)
139
140 // ----------- App -----------
141
142 // Enable CORS for develop
143 if (isTestInstance()) {
144 app.use(cors({
145 origin: '*',
146 exposedHeaders: 'Retry-After',
147 credentials: true
148 }))
149 }
150
151 // For the logger
152 morgan.token('remote-addr', (req: express.Request) => {
153 if (CONFIG.LOG.ANONYMIZE_IP === true || req.get('DNT') === '1') {
154 return anonymize(req.ip, 16, 16)
155 }
156
157 return req.ip
158 })
159 morgan.token('user-agent', (req: express.Request) => {
160 if (req.get('DNT') === '1') {
161 return useragent.parse(req.get('user-agent')).family
162 }
163
164 return req.get('user-agent')
165 })
166 app.use(morgan('combined', {
167 stream: {
168 write: (str: string) => logger.info(str, { tags: [ 'http' ] })
169 },
170 skip: req => CONFIG.LOG.LOG_PING_REQUESTS === false && req.originalUrl === '/api/v1/ping'
171 }))
172
173 // For body requests
174 app.use(bodyParser.urlencoded({ extended: false }))
175 app.use(bodyParser.json({
176 type: [ 'application/json', 'application/*+json' ],
177 limit: '500kb',
178 verify: (req: express.Request, _, buf: Buffer) => {
179 const valid = isHTTPSignatureDigestValid(buf, req)
180 if (valid !== true) throw new Error('Invalid digest')
181 }
182 }))
183
184 // Cookies
185 app.use(cookieParser())
186
187 // W3C DNT Tracking Status
188 app.use(advertiseDoNotTrack)
189
190 // Response helpers used in developement
191 app.use(apiResponseHelpers)
192
193 // ----------- Views, routes and static files -----------
194
195 // API
196 const apiRoute = '/api/' + API_VERSION
197 app.use(apiRoute, apiRouter)
198
199 // Services (oembed...)
200 app.use('/services', servicesRouter)
201
202 // Live streaming
203 app.use('/live', liveRouter)
204
205 // Plugins & themes
206 app.use('/', pluginsRouter)
207
208 app.use('/', activityPubRouter)
209 app.use('/', feedsRouter)
210 app.use('/', webfingerRouter)
211 app.use('/', trackerRouter)
212 app.use('/', botsRouter)
213
214 // Static files
215 app.use('/', staticRouter)
216 app.use('/', downloadRouter)
217 app.use('/', lazyStaticRouter)
218
219 // Client files, last valid routes!
220 const cliOptions = cli.opts()
221 if (cliOptions.client) app.use('/', clientsRouter)
222
223 // ----------- Errors -----------
224
225 // Catch 404 and forward to error handler
226 app.use(function (req, res, next) {
227 const err = new Error('Not Found')
228 err['status'] = HttpStatusCode.NOT_FOUND_404
229 next(err)
230 })
231
232 app.use(function (err, req, res, next) {
233 let error = 'Unknown error.'
234 if (err) {
235 error = err.stack || err.message || err
236 }
237
238 // Sequelize error
239 const sql = err.parent ? err.parent.sql : undefined
240
241 logger.error('Error in controller.', { err: error, sql })
242 return res.fail({
243 status: err.status || HttpStatusCode.INTERNAL_SERVER_ERROR_500,
244 message: err.message,
245 type: err.name
246 })
247 })
248
249 const server = createWebsocketTrackerServer(app)
250
251 // ----------- Run -----------
252
253 async function startApplication () {
254 const port = CONFIG.LISTEN.PORT
255 const hostname = CONFIG.LISTEN.HOSTNAME
256
257 await installApplication()
258
259 // Check activity pub urls are valid
260 checkActivityPubUrls()
261 .catch(err => {
262 logger.error('Error in ActivityPub URLs checker.', { err })
263 process.exit(-1)
264 })
265
266 checkFFmpegVersion()
267 .catch(err => logger.error('Cannot check ffmpeg version', { err }))
268
269 // Email initialization
270 Emailer.Instance.init()
271
272 await Promise.all([
273 Emailer.Instance.checkConnection(),
274 JobQueue.Instance.init(),
275 ServerConfigManager.Instance.init()
276 ])
277
278 // Caches initializations
279 VideosPreviewCache.Instance.init(CONFIG.CACHE.PREVIEWS.SIZE, FILES_CACHE.PREVIEWS.MAX_AGE)
280 VideosCaptionCache.Instance.init(CONFIG.CACHE.VIDEO_CAPTIONS.SIZE, FILES_CACHE.VIDEO_CAPTIONS.MAX_AGE)
281 VideosTorrentCache.Instance.init(CONFIG.CACHE.TORRENTS.SIZE, FILES_CACHE.TORRENTS.MAX_AGE)
282
283 // Enable Schedulers
284 ActorFollowScheduler.Instance.enable()
285 RemoveOldJobsScheduler.Instance.enable()
286 UpdateVideosScheduler.Instance.enable()
287 YoutubeDlUpdateScheduler.Instance.enable()
288 VideosRedundancyScheduler.Instance.enable()
289 RemoveOldHistoryScheduler.Instance.enable()
290 RemoveOldViewsScheduler.Instance.enable()
291 PluginsCheckScheduler.Instance.enable()
292 PeerTubeVersionCheckScheduler.Instance.enable()
293 AutoFollowIndexInstances.Instance.enable()
294 RemoveDanglingResumableUploadsScheduler.Instance.enable()
295
296 // Redis initialization
297 Redis.Instance.init()
298
299 PeerTubeSocket.Instance.init(server)
300
301 updateStreamingPlaylistsInfohashesIfNeeded()
302 .catch(err => logger.error('Cannot update streaming playlist infohashes.', { err }))
303
304 if (cliOptions.plugins) await PluginManager.Instance.registerPluginsAndThemes()
305
306 LiveManager.Instance.init()
307 if (CONFIG.LIVE.ENABLED) LiveManager.Instance.run()
308
309 // Make server listening
310 server.listen(port, hostname, () => {
311 logger.info('HTTP server listening on %s:%d', hostname, port)
312 logger.info('Web server: %s', WEBSERVER.URL)
313
314 Hooks.runAction('action:application.listening')
315 })
316
317 process.on('exit', () => {
318 JobQueue.Instance.terminate()
319 })
320
321 process.on('SIGINT', () => process.exit(0))
322 }