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