]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server.ts
Handle subtitles in player
[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
19 process.title = 'peertube'
20
21 // Create our main app
22 const app = express()
23
24 // ----------- Core checker -----------
25 import { 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)
28 import { logger } from './server/helpers/logger'
29 import { API_VERSION, CONFIG, STATIC_PATHS } from './server/initializers/constants'
30
31 const missed = checkMissedConfig()
32 if (missed.length !== 0) {
33 logger.error('Your configuration files miss keys: ' + missed)
34 process.exit(-1)
35 }
36
37 checkFFmpeg(CONFIG)
38 .catch(err => {
39 logger.error('Error in ffmpeg check.', { err })
40 process.exit(-1)
41 })
42
43 const errorMessage = checkConfig()
44 if (errorMessage !== null) {
45 throw new Error(errorMessage)
46 }
47
48 // Trust our proxy (IP forwarding...)
49 app.set('trust proxy', CONFIG.TRUST_PROXY)
50
51 // ----------- Database -----------
52
53 // Initialize database and models
54 import { initDatabaseModels } from './server/initializers/database'
55 import { migrate } from './server/initializers/migrator'
56 migrate()
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 -----------
65 import { installApplication } from './server/initializers'
66 import { Emailer } from './server/lib/emailer'
67 import { JobQueue } from './server/lib/job-queue'
68 import { VideosPreviewCache } from './server/lib/cache'
69 import {
70 activityPubRouter,
71 apiRouter,
72 clientsRouter,
73 feedsRouter,
74 staticRouter,
75 servicesRouter,
76 webfingerRouter,
77 trackerRouter,
78 createWebsocketServer
79 } from './server/controllers'
80 import { Redis } from './server/lib/redis'
81 import { BadActorFollowScheduler } from './server/lib/schedulers/bad-actor-follow-scheduler'
82 import { RemoveOldJobsScheduler } from './server/lib/schedulers/remove-old-jobs-scheduler'
83 import { UpdateVideosScheduler } from './server/lib/schedulers/update-videos-scheduler'
84
85 // ----------- Command line -----------
86
87 // ----------- App -----------
88
89 // Enable CORS for develop
90 if (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
110 app.use(morgan('combined', {
111 stream: { write: logger.info.bind(logger) }
112 }))
113 // For body requests
114 app.use(bodyParser.urlencoded({ extended: false }))
115 app.use(bodyParser.json({
116 type: [ 'application/json', 'application/*+json' ],
117 limit: '500kb'
118 }))
119 // Cookies
120 app.use(cookieParser())
121
122 // ----------- Views, routes and static files -----------
123
124 // API
125 const apiRoute = '/api/' + API_VERSION
126 app.use(apiRoute, apiRouter)
127
128 // Services (oembed...)
129 app.use('/services', servicesRouter)
130
131 app.use('/', activityPubRouter)
132 app.use('/', feedsRouter)
133 app.use('/', webfingerRouter)
134 app.use('/', trackerRouter)
135
136 // Static files
137 app.use('/', staticRouter)
138
139 // Client files, last valid routes!
140 app.use('/', clientsRouter)
141
142 // ----------- Errors -----------
143
144 // Catch 404 and forward to error handler
145 app.use(function (req, res, next) {
146 const err = new Error('Not Found')
147 err['status'] = 404
148 next(err)
149 })
150
151 app.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
161 const server = createWebsocketServer(app)
162
163 // ----------- Run -----------
164
165 async 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 }