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