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