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