]>
Commit | Line | Data |
---|---|---|
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 } 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 | app.use(helmet({ | |
63 | frameguard: { | |
64 | action: 'deny' // we only allow it for /videos/embed, see server/controllers/client.ts | |
65 | }, | |
66 | hsts: false | |
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 | } from './server/controllers' | |
108 | import { advertiseDoNotTrack } from './server/middlewares/dnt' | |
109 | import { Redis } from './server/lib/redis' | |
110 | import { ActorFollowScheduler } from './server/lib/schedulers/actor-follow-scheduler' | |
111 | import { RemoveOldViewsScheduler } from './server/lib/schedulers/remove-old-views-scheduler' | |
112 | import { RemoveOldJobsScheduler } from './server/lib/schedulers/remove-old-jobs-scheduler' | |
113 | import { UpdateVideosScheduler } from './server/lib/schedulers/update-videos-scheduler' | |
114 | import { YoutubeDlUpdateScheduler } from './server/lib/schedulers/youtube-dl-update-scheduler' | |
115 | import { VideosRedundancyScheduler } from './server/lib/schedulers/videos-redundancy-scheduler' | |
116 | import { RemoveOldHistoryScheduler } from './server/lib/schedulers/remove-old-history-scheduler' | |
117 | import { AutoFollowIndexInstances } from './server/lib/schedulers/auto-follow-index-instances' | |
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 { Hooks } from './server/lib/plugins/hooks' | |
123 | import { PluginManager } from './server/lib/plugins/plugin-manager' | |
124 | import { LiveManager } from './server/lib/live-manager' | |
125 | import { HttpStatusCode } from './shared/core-utils/miscs/http-error-codes' | |
126 | ||
127 | // ----------- Command line ----------- | |
128 | ||
129 | cli | |
130 | .option('--no-client', 'Start PeerTube without client interface') | |
131 | .option('--no-plugins', 'Start PeerTube without plugins/themes enabled') | |
132 | .parse(process.argv) | |
133 | ||
134 | // ----------- App ----------- | |
135 | ||
136 | // Enable CORS for develop | |
137 | if (isTestInstance()) { | |
138 | app.use(cors({ | |
139 | origin: '*', | |
140 | exposedHeaders: 'Retry-After', | |
141 | credentials: true | |
142 | })) | |
143 | } | |
144 | ||
145 | // For the logger | |
146 | morgan.token('remote-addr', (req: express.Request) => { | |
147 | if (CONFIG.LOG.ANONYMIZE_IP === true || req.get('DNT') === '1') { | |
148 | return anonymize(req.ip, 16, 16) | |
149 | } | |
150 | ||
151 | return req.ip | |
152 | }) | |
153 | morgan.token('user-agent', (req: express.Request) => { | |
154 | if (req.get('DNT') === '1') { | |
155 | return useragent.parse(req.get('user-agent')).family | |
156 | } | |
157 | ||
158 | return req.get('user-agent') | |
159 | }) | |
160 | app.use(morgan('combined', { | |
161 | stream: { write: logger.info.bind(logger) } | |
162 | })) | |
163 | ||
164 | // For body requests | |
165 | app.use(bodyParser.urlencoded({ extended: false })) | |
166 | app.use(bodyParser.json({ | |
167 | type: [ 'application/json', 'application/*+json' ], | |
168 | limit: '500kb', | |
169 | verify: (req: express.Request, _, buf: Buffer) => { | |
170 | const valid = isHTTPSignatureDigestValid(buf, req) | |
171 | if (valid !== true) throw new Error('Invalid digest') | |
172 | } | |
173 | })) | |
174 | ||
175 | // Cookies | |
176 | app.use(cookieParser()) | |
177 | ||
178 | // W3C DNT Tracking Status | |
179 | app.use(advertiseDoNotTrack) | |
180 | ||
181 | // ----------- Views, routes and static files ----------- | |
182 | ||
183 | // API | |
184 | const apiRoute = '/api/' + API_VERSION | |
185 | app.use(apiRoute, apiRouter) | |
186 | ||
187 | // Services (oembed...) | |
188 | app.use('/services', servicesRouter) | |
189 | ||
190 | // Live streaming | |
191 | app.use('/live', liveRouter) | |
192 | ||
193 | // Plugins & themes | |
194 | app.use('/', pluginsRouter) | |
195 | ||
196 | app.use('/', activityPubRouter) | |
197 | app.use('/', feedsRouter) | |
198 | app.use('/', webfingerRouter) | |
199 | app.use('/', trackerRouter) | |
200 | app.use('/', botsRouter) | |
201 | ||
202 | // Static files | |
203 | app.use('/', staticRouter) | |
204 | app.use('/', lazyStaticRouter) | |
205 | ||
206 | // Client files, last valid routes! | |
207 | if (cli.client) app.use('/', clientsRouter) | |
208 | ||
209 | // ----------- Errors ----------- | |
210 | ||
211 | // Catch 404 and forward to error handler | |
212 | app.use(function (req, res, next) { | |
213 | const err = new Error('Not Found') | |
214 | err['status'] = HttpStatusCode.NOT_FOUND_404 | |
215 | next(err) | |
216 | }) | |
217 | ||
218 | app.use(function (err, req, res, next) { | |
219 | let error = 'Unknown error.' | |
220 | if (err) { | |
221 | error = err.stack || err.message || err | |
222 | } | |
223 | ||
224 | // Sequelize error | |
225 | const sql = err.parent ? err.parent.sql : undefined | |
226 | ||
227 | logger.error('Error in controller.', { err: error, sql }) | |
228 | return res.status(err.status || HttpStatusCode.INTERNAL_SERVER_ERROR_500).end() | |
229 | }) | |
230 | ||
231 | const server = createWebsocketTrackerServer(app) | |
232 | ||
233 | // ----------- Run ----------- | |
234 | ||
235 | async function startApplication () { | |
236 | const port = CONFIG.LISTEN.PORT | |
237 | const hostname = CONFIG.LISTEN.HOSTNAME | |
238 | ||
239 | await installApplication() | |
240 | ||
241 | // Check activity pub urls are valid | |
242 | checkActivityPubUrls() | |
243 | .catch(err => { | |
244 | logger.error('Error in ActivityPub URLs checker.', { err }) | |
245 | process.exit(-1) | |
246 | }) | |
247 | ||
248 | // Email initialization | |
249 | Emailer.Instance.init() | |
250 | ||
251 | await Promise.all([ | |
252 | Emailer.Instance.checkConnection(), | |
253 | JobQueue.Instance.init() | |
254 | ]) | |
255 | ||
256 | // Caches initializations | |
257 | VideosPreviewCache.Instance.init(CONFIG.CACHE.PREVIEWS.SIZE, FILES_CACHE.PREVIEWS.MAX_AGE) | |
258 | VideosCaptionCache.Instance.init(CONFIG.CACHE.VIDEO_CAPTIONS.SIZE, FILES_CACHE.VIDEO_CAPTIONS.MAX_AGE) | |
259 | ||
260 | // Enable Schedulers | |
261 | ActorFollowScheduler.Instance.enable() | |
262 | RemoveOldJobsScheduler.Instance.enable() | |
263 | UpdateVideosScheduler.Instance.enable() | |
264 | YoutubeDlUpdateScheduler.Instance.enable() | |
265 | VideosRedundancyScheduler.Instance.enable() | |
266 | RemoveOldHistoryScheduler.Instance.enable() | |
267 | RemoveOldViewsScheduler.Instance.enable() | |
268 | PluginsCheckScheduler.Instance.enable() | |
269 | AutoFollowIndexInstances.Instance.enable() | |
270 | ||
271 | // Redis initialization | |
272 | Redis.Instance.init() | |
273 | ||
274 | PeerTubeSocket.Instance.init(server) | |
275 | ||
276 | updateStreamingPlaylistsInfohashesIfNeeded() | |
277 | .catch(err => logger.error('Cannot update streaming playlist infohashes.', { err })) | |
278 | ||
279 | if (cli.plugins) await PluginManager.Instance.registerPluginsAndThemes() | |
280 | ||
281 | LiveManager.Instance.init() | |
282 | if (CONFIG.LIVE.ENABLED) LiveManager.Instance.run() | |
283 | ||
284 | // Make server listening | |
285 | server.listen(port, hostname, () => { | |
286 | logger.info('Server listening on %s:%d', hostname, port) | |
287 | logger.info('Web server: %s', WEBSERVER.URL) | |
288 | ||
289 | Hooks.runAction('action:application.listening') | |
290 | }) | |
291 | ||
292 | process.on('exit', () => { | |
293 | JobQueue.Instance.terminate() | |
294 | }) | |
295 | ||
296 | process.on('SIGINT', () => process.exit(0)) | |
297 | } |