]>
Commit | Line | Data |
---|---|---|
1 | // ----------- Node modules ----------- | |
2 | import express from 'express' | |
3 | import morgan, { token } from 'morgan' | |
4 | import cors from 'cors' | |
5 | import cookieParser from 'cookie-parser' | |
6 | import { frameguard } from 'helmet' | |
7 | import { parse } from 'useragent' | |
8 | import anonymize from 'ip-anonymize' | |
9 | import { program as cli } from 'commander' | |
10 | ||
11 | process.title = 'peertube' | |
12 | ||
13 | // Create our main app | |
14 | const app = express().disable('x-powered-by') | |
15 | ||
16 | // ----------- Core checker ----------- | |
17 | import { checkMissedConfig, checkFFmpeg, checkNodeVersion } from './server/initializers/checker-before-init' | |
18 | ||
19 | // Do not use barrels because we don't want to load all modules here (we need to initialize database first) | |
20 | import { CONFIG } from './server/initializers/config' | |
21 | import { API_VERSION, FILES_CACHE, WEBSERVER, loadLanguages } from './server/initializers/constants' | |
22 | import { logger } from './server/helpers/logger' | |
23 | ||
24 | const missed = checkMissedConfig() | |
25 | if (missed.length !== 0) { | |
26 | logger.error('Your configuration files miss keys: ' + missed) | |
27 | process.exit(-1) | |
28 | } | |
29 | ||
30 | checkFFmpeg(CONFIG) | |
31 | .catch(err => { | |
32 | logger.error('Error in ffmpeg check.', { err }) | |
33 | process.exit(-1) | |
34 | }) | |
35 | ||
36 | try { | |
37 | checkNodeVersion() | |
38 | } catch (err) { | |
39 | logger.error('Error in NodeJS check.', { err }) | |
40 | process.exit(-1) | |
41 | } | |
42 | ||
43 | import { checkConfig, checkActivityPubUrls, checkFFmpegVersion } from './server/initializers/checker-after-init' | |
44 | ||
45 | const errorMessage = checkConfig() | |
46 | if (errorMessage !== null) { | |
47 | throw new Error(errorMessage) | |
48 | } | |
49 | ||
50 | // Trust our proxy (IP forwarding...) | |
51 | app.set('trust proxy', CONFIG.TRUST_PROXY) | |
52 | ||
53 | // Security middleware | |
54 | import { baseCSP } from './server/middlewares/csp' | |
55 | ||
56 | if (CONFIG.CSP.ENABLED) { | |
57 | app.use(baseCSP) | |
58 | } | |
59 | ||
60 | if (CONFIG.SECURITY.FRAMEGUARD.ENABLED) { | |
61 | app.use(frameguard({ | |
62 | action: 'deny' // we only allow it for /videos/embed, see server/controllers/client.ts | |
63 | })) | |
64 | } | |
65 | ||
66 | // ----------- Database ----------- | |
67 | ||
68 | // Initialize database and models | |
69 | import { initDatabaseModels, checkDatabaseConnectionOrDie } from './server/initializers/database' | |
70 | checkDatabaseConnectionOrDie() | |
71 | ||
72 | import { migrate } from './server/initializers/migrator' | |
73 | migrate() | |
74 | .then(() => initDatabaseModels(false)) | |
75 | .then(() => startApplication()) | |
76 | .catch(err => { | |
77 | logger.error('Cannot start application.', { err }) | |
78 | process.exit(-1) | |
79 | }) | |
80 | ||
81 | // ----------- Initialize ----------- | |
82 | loadLanguages() | |
83 | ||
84 | // ----------- PeerTube modules ----------- | |
85 | import { installApplication } from './server/initializers/installer' | |
86 | import { Emailer } from './server/lib/emailer' | |
87 | import { JobQueue } from './server/lib/job-queue' | |
88 | import { VideosPreviewCache, VideosCaptionCache } from './server/lib/files-cache' | |
89 | import { | |
90 | activityPubRouter, | |
91 | apiRouter, | |
92 | clientsRouter, | |
93 | feedsRouter, | |
94 | staticRouter, | |
95 | lazyStaticRouter, | |
96 | servicesRouter, | |
97 | liveRouter, | |
98 | pluginsRouter, | |
99 | webfingerRouter, | |
100 | trackerRouter, | |
101 | createWebsocketTrackerServer, | |
102 | botsRouter, | |
103 | downloadRouter | |
104 | } from './server/controllers' | |
105 | import { advertiseDoNotTrack } from './server/middlewares/dnt' | |
106 | import { apiFailMiddleware } from './server/middlewares/error' | |
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 { AutoFollowIndexInstances } from './server/lib/schedulers/auto-follow-index-instances' | |
116 | import { RemoveDanglingResumableUploadsScheduler } from './server/lib/schedulers/remove-dangling-resumable-uploads-scheduler' | |
117 | import { VideoViewsBufferScheduler } from './server/lib/schedulers/video-views-buffer-scheduler' | |
118 | import { isHTTPSignatureDigestValid } from './server/helpers/peertube-crypto' | |
119 | import { PeerTubeSocket } from './server/lib/peertube-socket' | |
120 | import { updateStreamingPlaylistsInfohashesIfNeeded } from './server/lib/hls' | |
121 | import { PluginsCheckScheduler } from './server/lib/schedulers/plugins-check-scheduler' | |
122 | import { PeerTubeVersionCheckScheduler } from './server/lib/schedulers/peertube-version-check-scheduler' | |
123 | import { Hooks } from './server/lib/plugins/hooks' | |
124 | import { PluginManager } from './server/lib/plugins/plugin-manager' | |
125 | import { LiveManager } from './server/lib/live' | |
126 | import { HttpStatusCode } from './shared/models/http/http-error-codes' | |
127 | import { VideosTorrentCache } from '@server/lib/files-cache/videos-torrent-cache' | |
128 | import { ServerConfigManager } from '@server/lib/server-config-manager' | |
129 | import { VideoViews } from '@server/lib/video-views' | |
130 | import { isTestInstance } from './server/helpers/core-utils' | |
131 | ||
132 | // ----------- Command line ----------- | |
133 | ||
134 | cli | |
135 | .option('--no-client', 'Start PeerTube without client interface') | |
136 | .option('--no-plugins', 'Start PeerTube without plugins/themes enabled') | |
137 | .option('--benchmark-startup', 'Automatically stop server when initialized') | |
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 | 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 | token('user-agent', (req: express.Request) => { | |
160 | if (req.get('DNT') === '1') { | |
161 | return 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.trim(), { tags: [ 'http' ] }) | |
169 | }, | |
170 | skip: req => CONFIG.LOG.LOG_PING_REQUESTS === false && req.originalUrl === '/api/v1/ping' | |
171 | })) | |
172 | ||
173 | // Add .fail() helper to response | |
174 | app.use(apiFailMiddleware) | |
175 | ||
176 | // For body requests | |
177 | app.use(express.urlencoded({ extended: false })) | |
178 | app.use(express.json({ | |
179 | type: [ 'application/json', 'application/*+json' ], | |
180 | limit: '500kb', | |
181 | verify: (req: express.Request, res: express.Response, buf: Buffer) => { | |
182 | const valid = isHTTPSignatureDigestValid(buf, req) | |
183 | ||
184 | if (valid !== true) { | |
185 | res.fail({ | |
186 | status: HttpStatusCode.FORBIDDEN_403, | |
187 | message: 'Invalid digest' | |
188 | }) | |
189 | } | |
190 | } | |
191 | })) | |
192 | ||
193 | // Cookies | |
194 | app.use(cookieParser()) | |
195 | ||
196 | // W3C DNT Tracking Status | |
197 | app.use(advertiseDoNotTrack) | |
198 | ||
199 | // ----------- Views, routes and static files ----------- | |
200 | ||
201 | // API | |
202 | const apiRoute = '/api/' + API_VERSION | |
203 | app.use(apiRoute, apiRouter) | |
204 | ||
205 | // Services (oembed...) | |
206 | app.use('/services', servicesRouter) | |
207 | ||
208 | // Live streaming | |
209 | app.use('/live', liveRouter) | |
210 | ||
211 | // Plugins & themes | |
212 | app.use('/', pluginsRouter) | |
213 | ||
214 | app.use('/', activityPubRouter) | |
215 | app.use('/', feedsRouter) | |
216 | app.use('/', webfingerRouter) | |
217 | app.use('/', trackerRouter) | |
218 | app.use('/', botsRouter) | |
219 | ||
220 | // Static files | |
221 | app.use('/', staticRouter) | |
222 | app.use('/', downloadRouter) | |
223 | app.use('/', lazyStaticRouter) | |
224 | ||
225 | // Client files, last valid routes! | |
226 | const cliOptions = cli.opts() | |
227 | if (cliOptions.client) app.use('/', clientsRouter) | |
228 | ||
229 | // ----------- Errors ----------- | |
230 | ||
231 | // Catch unmatched routes | |
232 | app.use((req, res: express.Response) => { | |
233 | res.status(HttpStatusCode.NOT_FOUND_404).end() | |
234 | }) | |
235 | ||
236 | // Catch thrown errors | |
237 | app.use((err, req, res: express.Response, next) => { | |
238 | // Format error to be logged | |
239 | let error = 'Unknown error.' | |
240 | if (err) { | |
241 | error = err.stack || err.message || err | |
242 | } | |
243 | // Handling Sequelize error traces | |
244 | const sql = err.parent ? err.parent.sql : undefined | |
245 | logger.error('Error in controller.', { err: error, sql }) | |
246 | ||
247 | return res.fail({ | |
248 | status: err.status || HttpStatusCode.INTERNAL_SERVER_ERROR_500, | |
249 | message: err.message, | |
250 | type: err.name | |
251 | }) | |
252 | }) | |
253 | ||
254 | const server = createWebsocketTrackerServer(app) | |
255 | ||
256 | // ----------- Run ----------- | |
257 | ||
258 | async function startApplication () { | |
259 | const port = CONFIG.LISTEN.PORT | |
260 | const hostname = CONFIG.LISTEN.HOSTNAME | |
261 | ||
262 | await installApplication() | |
263 | ||
264 | // Check activity pub urls are valid | |
265 | checkActivityPubUrls() | |
266 | .catch(err => { | |
267 | logger.error('Error in ActivityPub URLs checker.', { err }) | |
268 | process.exit(-1) | |
269 | }) | |
270 | ||
271 | checkFFmpegVersion() | |
272 | .catch(err => logger.error('Cannot check ffmpeg version', { err })) | |
273 | ||
274 | // Email initialization | |
275 | Emailer.Instance.init() | |
276 | ||
277 | await Promise.all([ | |
278 | Emailer.Instance.checkConnection(), | |
279 | JobQueue.Instance.init(), | |
280 | ServerConfigManager.Instance.init() | |
281 | ]) | |
282 | ||
283 | // Caches initializations | |
284 | VideosPreviewCache.Instance.init(CONFIG.CACHE.PREVIEWS.SIZE, FILES_CACHE.PREVIEWS.MAX_AGE) | |
285 | VideosCaptionCache.Instance.init(CONFIG.CACHE.VIDEO_CAPTIONS.SIZE, FILES_CACHE.VIDEO_CAPTIONS.MAX_AGE) | |
286 | VideosTorrentCache.Instance.init(CONFIG.CACHE.TORRENTS.SIZE, FILES_CACHE.TORRENTS.MAX_AGE) | |
287 | ||
288 | // Enable Schedulers | |
289 | ActorFollowScheduler.Instance.enable() | |
290 | RemoveOldJobsScheduler.Instance.enable() | |
291 | UpdateVideosScheduler.Instance.enable() | |
292 | YoutubeDlUpdateScheduler.Instance.enable() | |
293 | VideosRedundancyScheduler.Instance.enable() | |
294 | RemoveOldHistoryScheduler.Instance.enable() | |
295 | RemoveOldViewsScheduler.Instance.enable() | |
296 | PluginsCheckScheduler.Instance.enable() | |
297 | PeerTubeVersionCheckScheduler.Instance.enable() | |
298 | AutoFollowIndexInstances.Instance.enable() | |
299 | RemoveDanglingResumableUploadsScheduler.Instance.enable() | |
300 | VideoViewsBufferScheduler.Instance.enable() | |
301 | ||
302 | Redis.Instance.init() | |
303 | PeerTubeSocket.Instance.init(server) | |
304 | VideoViews.Instance.init() | |
305 | ||
306 | updateStreamingPlaylistsInfohashesIfNeeded() | |
307 | .catch(err => logger.error('Cannot update streaming playlist infohashes.', { err })) | |
308 | ||
309 | LiveManager.Instance.init() | |
310 | if (CONFIG.LIVE.ENABLED) await LiveManager.Instance.run() | |
311 | ||
312 | // Make server listening | |
313 | server.listen(port, hostname, async () => { | |
314 | if (cliOptions.plugins) { | |
315 | try { | |
316 | await PluginManager.Instance.registerPluginsAndThemes() | |
317 | } catch (err) { | |
318 | logger.error('Cannot register plugins and themes.', { err }) | |
319 | } | |
320 | } | |
321 | ||
322 | logger.info('HTTP server listening on %s:%d', hostname, port) | |
323 | logger.info('Web server: %s', WEBSERVER.URL) | |
324 | ||
325 | Hooks.runAction('action:application.listening') | |
326 | ||
327 | if (cliOptions['benchmarkStartup']) process.exit(0) | |
328 | }) | |
329 | ||
330 | process.on('exit', () => { | |
331 | JobQueue.Instance.terminate() | |
332 | }) | |
333 | ||
334 | process.on('SIGINT', () => process.exit(0)) | |
335 | } |