]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server.ts
5cfa09445537215fd3f9c772955d45a02ddd1b9a
[github/Chocobozzz/PeerTube.git] / server.ts
1 require('module-alias/register')
2
3 // FIXME: https://github.com/nodejs/node/pull/16853
4 import { PluginManager } from './server/lib/plugins/plugin-manager'
5
6 require('tls').DEFAULT_ECDH_CURVE = 'auto'
7
8 import { isTestInstance } from './server/helpers/core-utils'
9
10 if (isTestInstance()) {
11 require('source-map-support').install()
12 }
13
14 // ----------- Node modules -----------
15 import * as bodyParser from 'body-parser'
16 import * as express from 'express'
17 import * as morgan from 'morgan'
18 import * as cors from 'cors'
19 import * as cookieParser from 'cookie-parser'
20 import * as helmet from 'helmet'
21 import * as useragent from 'useragent'
22 import * as anonymize from 'ip-anonymize'
23 import * as cli from 'commander'
24
25 process.title = 'peertube'
26
27 // Create our main app
28 const app = express()
29
30 // ----------- Core checker -----------
31 import { checkMissedConfig, checkFFmpeg, checkNodeVersion } from './server/initializers/checker-before-init'
32
33 // Do not use barrels because we don't want to load all modules here (we need to initialize database first)
34 import { CONFIG } from './server/initializers/config'
35 import { API_VERSION, FILES_CACHE, WEBSERVER, loadLanguages } from './server/initializers/constants'
36 import { logger } from './server/helpers/logger'
37
38 const missed = checkMissedConfig()
39 if (missed.length !== 0) {
40 logger.error('Your configuration files miss keys: ' + missed)
41 process.exit(-1)
42 }
43
44 checkFFmpeg(CONFIG)
45 .catch(err => {
46 logger.error('Error in ffmpeg check.', { err })
47 process.exit(-1)
48 })
49
50 checkNodeVersion()
51
52 import { checkConfig, checkActivityPubUrls } from './server/initializers/checker-after-init'
53
54 const errorMessage = checkConfig()
55 if (errorMessage !== null) {
56 throw new Error(errorMessage)
57 }
58
59 // Trust our proxy (IP forwarding...)
60 app.set('trust proxy', CONFIG.TRUST_PROXY)
61
62 // Security middleware
63 import { baseCSP } from './server/middlewares/csp'
64
65 if (CONFIG.CSP.ENABLED) {
66 app.use(baseCSP)
67 app.use(helmet({
68 frameguard: {
69 action: 'deny' // we only allow it for /videos/embed, see server/controllers/client.ts
70 },
71 hsts: false
72 }))
73 }
74
75 // ----------- Database -----------
76
77 // Initialize database and models
78 import { initDatabaseModels } from './server/initializers/database'
79 import { migrate } from './server/initializers/migrator'
80 migrate()
81 .then(() => initDatabaseModels(false))
82 .then(() => startApplication())
83 .catch(err => {
84 logger.error('Cannot start application.', { err })
85 process.exit(-1)
86 })
87
88 // ----------- Initialize -----------
89 loadLanguages()
90
91 // ----------- PeerTube modules -----------
92 import { installApplication } from './server/initializers'
93 import { Emailer } from './server/lib/emailer'
94 import { JobQueue } from './server/lib/job-queue'
95 import { VideosPreviewCache, VideosCaptionCache } from './server/lib/files-cache'
96 import {
97 activityPubRouter,
98 apiRouter,
99 clientsRouter,
100 feedsRouter,
101 staticRouter,
102 lazyStaticRouter,
103 servicesRouter,
104 pluginsRouter,
105 webfingerRouter,
106 trackerRouter,
107 createWebsocketTrackerServer, botsRouter
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 { isHTTPSignatureDigestValid } from './server/helpers/peertube-crypto'
120 import { PeerTubeSocket } from './server/lib/peertube-socket'
121 import { updateStreamingPlaylistsInfohashesIfNeeded } from './server/lib/hls'
122 import { PluginsCheckScheduler } from './server/lib/schedulers/plugins-check-scheduler'
123 import { Hooks } from './server/lib/plugins/hooks'
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 }