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