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