]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server.ts
Add auto follow back support for instances
[github/Chocobozzz/PeerTube.git] / server.ts
1 require('module-alias/register')
2
3 // FIXME: https://github.com/nodejs/node/pull/16853
4 import { PluginManager } from './server/lib/plugins/plugin-manager'
5
6 require('tls').DEFAULT_ECDH_CURVE = 'auto'
7
8 import { isTestInstance } from './server/helpers/core-utils'
9
10 if (isTestInstance()) {
11 require('source-map-support').install()
12 }
13
14 // ----------- Node modules -----------
15 import * as bodyParser from 'body-parser'
16 import * as express from 'express'
17 import * as morgan from 'morgan'
18 import * as cors from 'cors'
19 import * as cookieParser from 'cookie-parser'
20 import * as helmet from 'helmet'
21 import * as useragent from 'useragent'
22 import * as anonymize from 'ip-anonymize'
23 import * as cli from 'commander'
24
25 process.title = 'peertube'
26
27 // Create our main app
28 const app = express()
29
30 // ----------- Core checker -----------
31 import { checkMissedConfig, checkFFmpeg, checkNodeVersion } from './server/initializers/checker-before-init'
32
33 // Do not use barrels because we don't want to load all modules here (we need to initialize database first)
34 import { CONFIG } from './server/initializers/config'
35 import { API_VERSION, FILES_CACHE, WEBSERVER, loadLanguages } from './server/initializers/constants'
36 import { logger } from './server/helpers/logger'
37
38 const missed = checkMissedConfig()
39 if (missed.length !== 0) {
40 logger.error('Your configuration files miss keys: ' + missed)
41 process.exit(-1)
42 }
43
44 checkFFmpeg(CONFIG)
45 .catch(err => {
46 logger.error('Error in ffmpeg check.', { err })
47 process.exit(-1)
48 })
49
50 checkNodeVersion()
51
52 import { checkConfig, checkActivityPubUrls } from './server/initializers/checker-after-init'
53
54 const errorMessage = checkConfig()
55 if (errorMessage !== null) {
56 throw new Error(errorMessage)
57 }
58
59 // Trust our proxy (IP forwarding...)
60 app.set('trust proxy', CONFIG.TRUST_PROXY)
61
62 // Security middleware
63 import { baseCSP } from './server/middlewares/csp'
64
65 if (CONFIG.CSP.ENABLED) {
66 app.use(baseCSP)
67 app.use(helmet({
68 frameguard: {
69 action: 'deny' // we only allow it for /videos/embed, see server/controllers/client.ts
70 },
71 hsts: false
72 }))
73 }
74
75 // ----------- Database -----------
76
77 // Initialize database and models
78 import { initDatabaseModels } from './server/initializers/database'
79 import { migrate } from './server/initializers/migrator'
80 migrate()
81 .then(() => initDatabaseModels(false))
82 .then(() => startApplication())
83 .catch(err => {
84 logger.error('Cannot start application.', { err })
85 process.exit(-1)
86 })
87
88 // ----------- Initialize -----------
89 loadLanguages()
90
91 // ----------- PeerTube modules -----------
92 import { installApplication } from './server/initializers'
93 import { Emailer } from './server/lib/emailer'
94 import { JobQueue } from './server/lib/job-queue'
95 import { VideosPreviewCache, VideosCaptionCache } from './server/lib/files-cache'
96 import {
97 activityPubRouter,
98 apiRouter,
99 clientsRouter,
100 feedsRouter,
101 staticRouter,
102 lazyStaticRouter,
103 servicesRouter,
104 pluginsRouter,
105 webfingerRouter,
106 trackerRouter,
107 createWebsocketTrackerServer, botsRouter
108 } from './server/controllers'
109 import { advertiseDoNotTrack } from './server/middlewares/dnt'
110 import { Redis } from './server/lib/redis'
111 import { ActorFollowScheduler } from './server/lib/schedulers/actor-follow-scheduler'
112 import { RemoveOldViewsScheduler } from './server/lib/schedulers/remove-old-views-scheduler'
113 import { RemoveOldJobsScheduler } from './server/lib/schedulers/remove-old-jobs-scheduler'
114 import { UpdateVideosScheduler } from './server/lib/schedulers/update-videos-scheduler'
115 import { YoutubeDlUpdateScheduler } from './server/lib/schedulers/youtube-dl-update-scheduler'
116 import { VideosRedundancyScheduler } from './server/lib/schedulers/videos-redundancy-scheduler'
117 import { RemoveOldHistoryScheduler } from './server/lib/schedulers/remove-old-history-scheduler'
118 import { isHTTPSignatureDigestValid } from './server/helpers/peertube-crypto'
119 import { PeerTubeSocket } from './server/lib/peertube-socket'
120 import { updateStreamingPlaylistsInfohashesIfNeeded } from './server/lib/hls'
121 import { PluginsCheckScheduler } from './server/lib/schedulers/plugins-check-scheduler'
122 import { Hooks } from './server/lib/plugins/hooks'
123
124 // ----------- Command line -----------
125
126 cli
127 .option('--no-client', 'Start PeerTube without client interface')
128 .option('--no-plugins', 'Start PeerTube without plugins/themes enabled')
129 .parse(process.argv)
130
131 // ----------- App -----------
132
133 // Enable CORS for develop
134 if (isTestInstance()) {
135 app.use(cors({
136 origin: '*',
137 exposedHeaders: 'Retry-After',
138 credentials: true
139 }))
140 }
141
142 // For the logger
143 morgan.token('remote-addr', req => {
144 if (req.get('DNT') === '1') {
145 return anonymize(req.ip, 16, 16)
146 }
147
148 return req.ip
149 })
150 morgan.token('user-agent', req => {
151 if (req.get('DNT') === '1') {
152 return useragent.parse(req.get('user-agent')).family
153 }
154
155 return req.get('user-agent')
156 })
157 app.use(morgan('combined', {
158 stream: { write: logger.info.bind(logger) }
159 }))
160
161 // For body requests
162 app.use(bodyParser.urlencoded({ extended: false }))
163 app.use(bodyParser.json({
164 type: [ 'application/json', 'application/*+json' ],
165 limit: '500kb',
166 verify: (req: express.Request, _, buf: Buffer) => {
167 const valid = isHTTPSignatureDigestValid(buf, req)
168 if (valid !== true) throw new Error('Invalid digest')
169 }
170 }))
171
172 // Cookies
173 app.use(cookieParser())
174
175 // W3C DNT Tracking Status
176 app.use(advertiseDoNotTrack)
177
178 // ----------- Views, routes and static files -----------
179
180 // API
181 const apiRoute = '/api/' + API_VERSION
182 app.use(apiRoute, apiRouter)
183
184 // Services (oembed...)
185 app.use('/services', servicesRouter)
186
187 // Plugins & themes
188 app.use('/', pluginsRouter)
189
190 app.use('/', activityPubRouter)
191 app.use('/', feedsRouter)
192 app.use('/', webfingerRouter)
193 app.use('/', trackerRouter)
194 app.use('/', botsRouter)
195
196 // Static files
197 app.use('/', staticRouter)
198 app.use('/', lazyStaticRouter)
199
200 // Client files, last valid routes!
201 if (cli.client) app.use('/', clientsRouter)
202
203 // ----------- Errors -----------
204
205 // Catch 404 and forward to error handler
206 app.use(function (req, res, next) {
207 const err = new Error('Not Found')
208 err['status'] = 404
209 next(err)
210 })
211
212 app.use(function (err, req, res, next) {
213 let error = 'Unknown error.'
214 if (err) {
215 error = err.stack || err.message || err
216 }
217
218 // Sequelize error
219 const sql = err.parent ? err.parent.sql : undefined
220
221 logger.error('Error in controller.', { err: error, sql })
222 return res.status(err.status || 500).end()
223 })
224
225 const server = createWebsocketTrackerServer(app)
226
227 // ----------- Run -----------
228
229 async function startApplication () {
230 const port = CONFIG.LISTEN.PORT
231 const hostname = CONFIG.LISTEN.HOSTNAME
232
233 await installApplication()
234
235 // Check activity pub urls are valid
236 checkActivityPubUrls()
237 .catch(err => {
238 logger.error('Error in ActivityPub URLs checker.', { err })
239 process.exit(-1)
240 })
241
242 // Email initialization
243 Emailer.Instance.init()
244
245 await Promise.all([
246 Emailer.Instance.checkConnectionOrDie(),
247 JobQueue.Instance.init()
248 ])
249
250 // Caches initializations
251 VideosPreviewCache.Instance.init(CONFIG.CACHE.PREVIEWS.SIZE, FILES_CACHE.PREVIEWS.MAX_AGE)
252 VideosCaptionCache.Instance.init(CONFIG.CACHE.VIDEO_CAPTIONS.SIZE, FILES_CACHE.VIDEO_CAPTIONS.MAX_AGE)
253
254 // Enable Schedulers
255 ActorFollowScheduler.Instance.enable()
256 RemoveOldJobsScheduler.Instance.enable()
257 UpdateVideosScheduler.Instance.enable()
258 YoutubeDlUpdateScheduler.Instance.enable()
259 VideosRedundancyScheduler.Instance.enable()
260 RemoveOldHistoryScheduler.Instance.enable()
261 RemoveOldViewsScheduler.Instance.enable()
262 PluginsCheckScheduler.Instance.enable()
263
264 // Redis initialization
265 Redis.Instance.init()
266
267 PeerTubeSocket.Instance.init(server)
268
269 updateStreamingPlaylistsInfohashesIfNeeded()
270 .catch(err => logger.error('Cannot update streaming playlist infohashes.', { err }))
271
272 if (cli.plugins) await PluginManager.Instance.registerPluginsAndThemes()
273
274 // Make server listening
275 server.listen(port, hostname, () => {
276 logger.info('Server listening on %s:%d', hostname, port)
277 logger.info('Web server: %s', WEBSERVER.URL)
278
279 Hooks.runAction('action:application.listening')
280 })
281
282 process.on('exit', () => {
283 JobQueue.Instance.terminate()
284 })
285
286 process.on('SIGINT', () => process.exit(0))
287 }