]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blob - server.ts
Refactor video views
[github/Chocobozzz/PeerTube.git] / server.ts
1 import { registerTSPaths } from './server/helpers/register-ts-paths'
2 registerTSPaths()
3
4 import { isTestInstance } from './server/helpers/core-utils'
5 if (isTestInstance()) {
6 require('source-map-support').install()
7 }
8
9 // ----------- Node modules -----------
10 import express from 'express'
11 import morgan, { token } from 'morgan'
12 import cors from 'cors'
13 import cookieParser from 'cookie-parser'
14 import { frameguard } from 'helmet'
15 import { parse } from 'useragent'
16 import anonymize from 'ip-anonymize'
17 import { program as cli } from 'commander'
18
19 process.title = 'peertube'
20
21 // Create our main app
22 const app = express().disable("x-powered-by")
23
24 // ----------- Core checker -----------
25 import { checkMissedConfig, checkFFmpeg, checkNodeVersion } from './server/initializers/checker-before-init'
26
27 // Do not use barrels because we don't want to load all modules here (we need to initialize database first)
28 import { CONFIG } from './server/initializers/config'
29 import { API_VERSION, FILES_CACHE, WEBSERVER, loadLanguages } from './server/initializers/constants'
30 import { logger } from './server/helpers/logger'
31
32 const missed = checkMissedConfig()
33 if (missed.length !== 0) {
34 logger.error('Your configuration files miss keys: ' + missed)
35 process.exit(-1)
36 }
37
38 checkFFmpeg(CONFIG)
39 .catch(err => {
40 logger.error('Error in ffmpeg check.', { err })
41 process.exit(-1)
42 })
43
44 checkNodeVersion()
45
46 import { checkConfig, checkActivityPubUrls, checkFFmpegVersion } from './server/initializers/checker-after-init'
47
48 const errorMessage = checkConfig()
49 if (errorMessage !== null) {
50 throw new Error(errorMessage)
51 }
52
53 // Trust our proxy (IP forwarding...)
54 app.set('trust proxy', CONFIG.TRUST_PROXY)
55
56 // Security middleware
57 import { baseCSP } from './server/middlewares/csp'
58
59 if (CONFIG.CSP.ENABLED) {
60 app.use(baseCSP)
61 }
62
63 if (CONFIG.SECURITY.FRAMEGUARD.ENABLED) {
64 app.use(frameguard({
65 action: 'deny' // we only allow it for /videos/embed, see server/controllers/client.ts
66 }))
67 }
68
69 // ----------- Database -----------
70
71 // Initialize database and models
72 import { initDatabaseModels, checkDatabaseConnectionOrDie } from './server/initializers/database'
73 checkDatabaseConnectionOrDie()
74
75 import { migrate } from './server/initializers/migrator'
76 migrate()
77 .then(() => initDatabaseModels(false))
78 .then(() => startApplication())
79 .catch(err => {
80 logger.error('Cannot start application.', { err })
81 process.exit(-1)
82 })
83
84 // ----------- Initialize -----------
85 loadLanguages()
86
87 // ----------- PeerTube modules -----------
88 import { installApplication } from './server/initializers/installer'
89 import { Emailer } from './server/lib/emailer'
90 import { JobQueue } from './server/lib/job-queue'
91 import { VideosPreviewCache, VideosCaptionCache } from './server/lib/files-cache'
92 import {
93 activityPubRouter,
94 apiRouter,
95 clientsRouter,
96 feedsRouter,
97 staticRouter,
98 lazyStaticRouter,
99 servicesRouter,
100 liveRouter,
101 pluginsRouter,
102 webfingerRouter,
103 trackerRouter,
104 createWebsocketTrackerServer,
105 botsRouter,
106 downloadRouter
107 } from './server/controllers'
108 import { advertiseDoNotTrack } from './server/middlewares/dnt'
109 import { apiFailMiddleware } from './server/middlewares/error'
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 { AutoFollowIndexInstances } from './server/lib/schedulers/auto-follow-index-instances'
119 import { RemoveDanglingResumableUploadsScheduler } from './server/lib/schedulers/remove-dangling-resumable-uploads-scheduler'
120 import { VideoViewsBufferScheduler } from './server/lib/schedulers/video-views-buffer-scheduler'
121 import { isHTTPSignatureDigestValid } from './server/helpers/peertube-crypto'
122 import { PeerTubeSocket } from './server/lib/peertube-socket'
123 import { updateStreamingPlaylistsInfohashesIfNeeded } from './server/lib/hls'
124 import { PluginsCheckScheduler } from './server/lib/schedulers/plugins-check-scheduler'
125 import { PeerTubeVersionCheckScheduler } from './server/lib/schedulers/peertube-version-check-scheduler'
126 import { Hooks } from './server/lib/plugins/hooks'
127 import { PluginManager } from './server/lib/plugins/plugin-manager'
128 import { LiveManager } from './server/lib/live'
129 import { HttpStatusCode } from './shared/models/http/http-error-codes'
130 import { VideosTorrentCache } from '@server/lib/files-cache/videos-torrent-cache'
131 import { ServerConfigManager } from '@server/lib/server-config-manager'
132 import { VideoViews } from '@server/lib/video-views'
133
134 // ----------- Command line -----------
135
136 cli
137 .option('--no-client', 'Start PeerTube without client interface')
138 .option('--no-plugins', 'Start PeerTube without plugins/themes enabled')
139 .parse(process.argv)
140
141 // ----------- App -----------
142
143 // Enable CORS for develop
144 if (isTestInstance()) {
145 app.use(cors({
146 origin: '*',
147 exposedHeaders: 'Retry-After',
148 credentials: true
149 }))
150 }
151
152 // For the logger
153 token('remote-addr', (req: express.Request) => {
154 if (CONFIG.LOG.ANONYMIZE_IP === true || req.get('DNT') === '1') {
155 return anonymize(req.ip, 16, 16)
156 }
157
158 return req.ip
159 })
160 token('user-agent', (req: express.Request) => {
161 if (req.get('DNT') === '1') {
162 return parse(req.get('user-agent')).family
163 }
164
165 return req.get('user-agent')
166 })
167 app.use(morgan('combined', {
168 stream: {
169 write: (str: string) => logger.info(str.trim(), { tags: [ 'http' ] })
170 },
171 skip: req => CONFIG.LOG.LOG_PING_REQUESTS === false && req.originalUrl === '/api/v1/ping'
172 }))
173
174 // Add .fail() helper to response
175 app.use(apiFailMiddleware)
176
177 // For body requests
178 app.use(express.urlencoded({ extended: false }))
179 app.use(express.json({
180 type: [ 'application/json', 'application/*+json' ],
181 limit: '500kb',
182 verify: (req: express.Request, res: express.Response, buf: Buffer) => {
183 const valid = isHTTPSignatureDigestValid(buf, req)
184
185 if (valid !== true) {
186 res.fail({
187 status: HttpStatusCode.FORBIDDEN_403,
188 message: 'Invalid digest'
189 })
190 }
191 }
192 }))
193
194 // Cookies
195 app.use(cookieParser())
196
197 // W3C DNT Tracking Status
198 app.use(advertiseDoNotTrack)
199
200 // ----------- Views, routes and static files -----------
201
202 // API
203 const apiRoute = '/api/' + API_VERSION
204 app.use(apiRoute, apiRouter)
205
206 // Services (oembed...)
207 app.use('/services', servicesRouter)
208
209 // Live streaming
210 app.use('/live', liveRouter)
211
212 // Plugins & themes
213 app.use('/', pluginsRouter)
214
215 app.use('/', activityPubRouter)
216 app.use('/', feedsRouter)
217 app.use('/', webfingerRouter)
218 app.use('/', trackerRouter)
219 app.use('/', botsRouter)
220
221 // Static files
222 app.use('/', staticRouter)
223 app.use('/', downloadRouter)
224 app.use('/', lazyStaticRouter)
225
226 // Client files, last valid routes!
227 const cliOptions = cli.opts()
228 if (cliOptions.client) app.use('/', clientsRouter)
229
230 // ----------- Errors -----------
231
232 // Catch unmatched routes
233 app.use((req, res: express.Response) => {
234 res.status(HttpStatusCode.NOT_FOUND_404).end()
235 })
236
237 // Catch thrown errors
238 app.use((err, req, res: express.Response, next) => {
239 // Format error to be logged
240 let error = 'Unknown error.'
241 if (err) {
242 error = err.stack || err.message || err
243 }
244 // Handling Sequelize error traces
245 const sql = err.parent ? err.parent.sql : undefined
246 logger.error('Error in controller.', { err: error, sql })
247
248 return res.fail({
249 status: err.status || HttpStatusCode.INTERNAL_SERVER_ERROR_500,
250 message: err.message,
251 type: err.name
252 })
253 })
254
255 const server = createWebsocketTrackerServer(app)
256
257 // ----------- Run -----------
258
259 async function startApplication () {
260 const port = CONFIG.LISTEN.PORT
261 const hostname = CONFIG.LISTEN.HOSTNAME
262
263 await installApplication()
264
265 // Check activity pub urls are valid
266 checkActivityPubUrls()
267 .catch(err => {
268 logger.error('Error in ActivityPub URLs checker.', { err })
269 process.exit(-1)
270 })
271
272 checkFFmpegVersion()
273 .catch(err => logger.error('Cannot check ffmpeg version', { err }))
274
275 // Email initialization
276 Emailer.Instance.init()
277
278 await Promise.all([
279 Emailer.Instance.checkConnection(),
280 JobQueue.Instance.init(),
281 ServerConfigManager.Instance.init()
282 ])
283
284 // Caches initializations
285 VideosPreviewCache.Instance.init(CONFIG.CACHE.PREVIEWS.SIZE, FILES_CACHE.PREVIEWS.MAX_AGE)
286 VideosCaptionCache.Instance.init(CONFIG.CACHE.VIDEO_CAPTIONS.SIZE, FILES_CACHE.VIDEO_CAPTIONS.MAX_AGE)
287 VideosTorrentCache.Instance.init(CONFIG.CACHE.TORRENTS.SIZE, FILES_CACHE.TORRENTS.MAX_AGE)
288
289 // Enable Schedulers
290 ActorFollowScheduler.Instance.enable()
291 RemoveOldJobsScheduler.Instance.enable()
292 UpdateVideosScheduler.Instance.enable()
293 YoutubeDlUpdateScheduler.Instance.enable()
294 VideosRedundancyScheduler.Instance.enable()
295 RemoveOldHistoryScheduler.Instance.enable()
296 RemoveOldViewsScheduler.Instance.enable()
297 PluginsCheckScheduler.Instance.enable()
298 PeerTubeVersionCheckScheduler.Instance.enable()
299 AutoFollowIndexInstances.Instance.enable()
300 RemoveDanglingResumableUploadsScheduler.Instance.enable()
301 VideoViewsBufferScheduler.Instance.enable()
302
303 Redis.Instance.init()
304 PeerTubeSocket.Instance.init(server)
305 VideoViews.Instance.init()
306
307 updateStreamingPlaylistsInfohashesIfNeeded()
308 .catch(err => logger.error('Cannot update streaming playlist infohashes.', { err }))
309
310 LiveManager.Instance.init()
311 if (CONFIG.LIVE.ENABLED) await LiveManager.Instance.run()
312
313 // Make server listening
314 server.listen(port, hostname, async () => {
315 if (cliOptions.plugins) {
316 try {
317 await PluginManager.Instance.registerPluginsAndThemes()
318 } catch (err) {
319 logger.error('Cannot register plugins and themes.', { err })
320 }
321 }
322
323 logger.info('HTTP server listening on %s:%d', hostname, port)
324 logger.info('Web server: %s', WEBSERVER.URL)
325
326 Hooks.runAction('action:application.listening')
327 })
328
329 process.on('exit', () => {
330 JobQueue.Instance.terminate()
331 })
332
333 process.on('SIGINT', () => process.exit(0))
334 }