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