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