]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server.ts
26750802c7f162c6946bbf98475567b04a47796f
[github/Chocobozzz/PeerTube.git] / server.ts
1 // FIXME: https://github.com/nodejs/node/pull/16853
2 import { VideosCaptionCache } from './server/lib/cache/videos-caption-cache'
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
20 process.title = 'peertube'
21
22 // Create our main app
23 const app = express()
24
25 // ----------- Core checker -----------
26 import { checkMissedConfig, checkFFmpeg, checkConfig, checkActivityPubUrls } from './server/initializers/checker'
27
28 // Do not use barrels because we don't want to load all modules here (we need to initialize database first)
29 import { logger } from './server/helpers/logger'
30 import { API_VERSION, CONFIG, STATIC_PATHS, CACHE } from './server/initializers/constants'
31
32 const missed = checkMissedConfig()
33 if (missed.length !== 0) {
34 logger.error('Your configuration files miss keys: ' + missed)
35 process.exit(-1)
36 }
37
38 checkFFmpeg(CONFIG)
39 .catch(err => {
40 logger.error('Error in ffmpeg check.', { err })
41 process.exit(-1)
42 })
43
44 const errorMessage = checkConfig()
45 if (errorMessage !== null) {
46 throw new Error(errorMessage)
47 }
48
49 // Trust our proxy (IP forwarding...)
50 app.set('trust proxy', CONFIG.TRUST_PROXY)
51
52 // Security middlewares
53 app.use(helmet({
54 frameguard: {
55 action: 'deny'
56 }
57 }))
58
59 // ----------- Database -----------
60
61 // Initialize database and models
62 import { initDatabaseModels } from './server/initializers/database'
63 import { migrate } from './server/initializers/migrator'
64 migrate()
65 .then(() => initDatabaseModels(false))
66 .then(() => startApplication())
67 .catch(err => {
68 logger.error('Cannot start application.', { err })
69 process.exit(-1)
70 })
71
72 // ----------- PeerTube modules -----------
73 import { installApplication } from './server/initializers'
74 import { Emailer } from './server/lib/emailer'
75 import { JobQueue } from './server/lib/job-queue'
76 import { VideosPreviewCache } from './server/lib/cache'
77 import {
78 activityPubRouter,
79 apiRouter,
80 clientsRouter,
81 feedsRouter,
82 staticRouter,
83 servicesRouter,
84 webfingerRouter,
85 trackerRouter,
86 createWebsocketServer
87 } from './server/controllers'
88 import { Redis } from './server/lib/redis'
89 import { BadActorFollowScheduler } from './server/lib/schedulers/bad-actor-follow-scheduler'
90 import { RemoveOldJobsScheduler } from './server/lib/schedulers/remove-old-jobs-scheduler'
91 import { UpdateVideosScheduler } from './server/lib/schedulers/update-videos-scheduler'
92
93 // ----------- Command line -----------
94
95 // ----------- App -----------
96
97 // Enable CORS for develop
98 if (isTestInstance()) {
99 app.use((req, res, next) => {
100 // These routes have already cors
101 if (
102 req.path.indexOf(STATIC_PATHS.TORRENTS) === -1 &&
103 req.path.indexOf(STATIC_PATHS.WEBSEED) === -1 &&
104 req.path.startsWith('/api/') === false
105 ) {
106 return (cors({
107 origin: '*',
108 exposedHeaders: 'Retry-After',
109 credentials: true
110 }))(req, res, next)
111 }
112
113 return next()
114 })
115 }
116
117 // For the logger
118 app.use(morgan('combined', {
119 stream: { write: logger.info.bind(logger) }
120 }))
121 // For body requests
122 app.use(bodyParser.urlencoded({ extended: false }))
123 app.use(bodyParser.json({
124 type: [ 'application/json', 'application/*+json' ],
125 limit: '500kb'
126 }))
127 // Cookies
128 app.use(cookieParser())
129
130 // ----------- Views, routes and static files -----------
131
132 // API
133 const apiRoute = '/api/' + API_VERSION
134 app.use(apiRoute, apiRouter)
135
136 // Services (oembed...)
137 app.use('/services', servicesRouter)
138
139 app.use('/', activityPubRouter)
140 app.use('/', feedsRouter)
141 app.use('/', webfingerRouter)
142 app.use('/', trackerRouter)
143
144 // Static files
145 app.use('/', staticRouter)
146
147 // Client files, last valid routes!
148 app.use('/', clientsRouter)
149
150 // ----------- Errors -----------
151
152 // Catch 404 and forward to error handler
153 app.use(function (req, res, next) {
154 const err = new Error('Not Found')
155 err['status'] = 404
156 next(err)
157 })
158
159 app.use(function (err, req, res, next) {
160 let error = 'Unknown error.'
161 if (err) {
162 error = err.stack || err.message || err
163 }
164
165 logger.error('Error in controller.', { error })
166 return res.status(err.status || 500).end()
167 })
168
169 const server = createWebsocketServer(app)
170
171 // ----------- Run -----------
172
173 async function startApplication () {
174 const port = CONFIG.LISTEN.PORT
175 const hostname = CONFIG.LISTEN.HOSTNAME
176
177 await installApplication()
178
179 // Check activity pub urls are valid
180 checkActivityPubUrls()
181 .catch(err => {
182 logger.error('Error in ActivityPub URLs checker.', { err })
183 process.exit(-1)
184 })
185
186 // Email initialization
187 Emailer.Instance.init()
188 await Emailer.Instance.checkConnectionOrDie()
189
190 await JobQueue.Instance.init()
191
192 // Caches initializations
193 VideosPreviewCache.Instance.init(CONFIG.CACHE.PREVIEWS.SIZE, CACHE.PREVIEWS.MAX_AGE)
194 VideosCaptionCache.Instance.init(CONFIG.CACHE.VIDEO_CAPTIONS.SIZE, CACHE.VIDEO_CAPTIONS.MAX_AGE)
195
196 // Enable Schedulers
197 BadActorFollowScheduler.Instance.enable()
198 RemoveOldJobsScheduler.Instance.enable()
199 UpdateVideosScheduler.Instance.enable()
200
201 // Redis initialization
202 Redis.Instance.init()
203
204 // Make server listening
205 server.listen(port, hostname, () => {
206 logger.info('Server listening on %s:%d', hostname, port)
207 logger.info('Web server: %s', CONFIG.WEBSERVER.URL)
208 })
209 }