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