add cli option to run without client
[oweals/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 import * as cookieParser from 'cookie-parser'
16 import * as helmet from 'helmet'
17 import * as useragent from 'useragent'
18 import * as anonymize from 'ip-anonymize'
19 import * as cli from 'commander'
20
21 process.title = 'peertube'
22
23 // Create our main app
24 const app = express()
25
26 // ----------- Core checker -----------
27 import { checkMissedConfig, checkFFmpeg } from './server/initializers/checker-before-init'
28
29 // Do not use barrels because we don't want to load all modules here (we need to initialize database first)
30 import { logger } from './server/helpers/logger'
31 import { API_VERSION, CONFIG, CACHE } from './server/initializers/constants'
32
33 const missed = checkMissedConfig()
34 if (missed.length !== 0) {
35   logger.error('Your configuration files miss keys: ' + missed)
36   process.exit(-1)
37 }
38
39 checkFFmpeg(CONFIG)
40   .catch(err => {
41     logger.error('Error in ffmpeg check.', { err })
42     process.exit(-1)
43   })
44
45 import { checkConfig, checkActivityPubUrls } from './server/initializers/checker-after-init'
46
47 const errorMessage = checkConfig()
48 if (errorMessage !== null) {
49   throw new Error(errorMessage)
50 }
51
52 // Trust our proxy (IP forwarding...)
53 app.set('trust proxy', CONFIG.TRUST_PROXY)
54
55 // Security middleware
56 app.use(helmet({
57   frameguard: {
58     action: 'deny' // we only allow it for /videos/embed, see server/controllers/client.ts
59   },
60   hsts: false
61 }))
62
63 // ----------- Database -----------
64
65 // Initialize database and models
66 import { initDatabaseModels } from './server/initializers/database'
67 import { migrate } from './server/initializers/migrator'
68 migrate()
69   .then(() => initDatabaseModels(false))
70   .then(() => startApplication())
71   .catch(err => {
72     logger.error('Cannot start application.', { err })
73     process.exit(-1)
74   })
75
76 // ----------- PeerTube modules -----------
77 import { installApplication } from './server/initializers'
78 import { Emailer } from './server/lib/emailer'
79 import { JobQueue } from './server/lib/job-queue'
80 import { VideosPreviewCache, VideosCaptionCache } from './server/lib/cache'
81 import {
82   activityPubRouter,
83   apiRouter,
84   clientsRouter,
85   feedsRouter,
86   staticRouter,
87   servicesRouter,
88   webfingerRouter,
89   trackerRouter,
90   createWebsocketServer
91 } from './server/controllers'
92 import { advertiseDoNotTrack } from './server/middlewares/dnt'
93 import { Redis } from './server/lib/redis'
94 import { BadActorFollowScheduler } from './server/lib/schedulers/bad-actor-follow-scheduler'
95 import { RemoveOldJobsScheduler } from './server/lib/schedulers/remove-old-jobs-scheduler'
96 import { UpdateVideosScheduler } from './server/lib/schedulers/update-videos-scheduler'
97 import { YoutubeDlUpdateScheduler } from './server/lib/schedulers/youtube-dl-update-scheduler'
98 import { VideosRedundancyScheduler } from './server/lib/schedulers/videos-redundancy-scheduler'
99
100 // ----------- Command line -----------
101
102 cli
103   .option('--no-client', 'Start PeerTube without client interface')
104   .parse(process.argv)
105
106 // ----------- App -----------
107
108 // Enable CORS for develop
109 if (isTestInstance()) {
110   app.use(cors({
111     origin: '*',
112     exposedHeaders: 'Retry-After',
113     credentials: true
114   }))
115 }
116 // For the logger
117 morgan.token('remote-addr', req => {
118   return (req.get('DNT') === '1') ?
119     anonymize(req.ip || (req.connection && req.connection.remoteAddress) || undefined,
120     16, // bitmask for IPv4
121     16  // bitmask for IPv6
122     ) :
123     req.ip
124 })
125 morgan.token('user-agent', req => (req.get('DNT') === '1') ?
126   useragent.parse(req.get('user-agent')).family : req.get('user-agent'))
127 app.use(morgan('combined', {
128   stream: { write: logger.info.bind(logger) }
129 }))
130 // For body requests
131 app.use(bodyParser.urlencoded({ extended: false }))
132 app.use(bodyParser.json({
133   type: [ 'application/json', 'application/*+json' ],
134   limit: '500kb'
135 }))
136 // Cookies
137 app.use(cookieParser())
138 // W3C DNT Tracking Status
139 app.use(advertiseDoNotTrack)
140
141 // ----------- Views, routes and static files -----------
142
143 // API
144 const apiRoute = '/api/' + API_VERSION
145 app.use(apiRoute, apiRouter)
146
147 // Services (oembed...)
148 app.use('/services', servicesRouter)
149
150 app.use('/', activityPubRouter)
151 app.use('/', feedsRouter)
152 app.use('/', webfingerRouter)
153 app.use('/', trackerRouter)
154
155 // Static files
156 app.use('/', staticRouter)
157
158 // Client files, last valid routes!
159 if (cli.client) app.use('/', clientsRouter)
160
161 // ----------- Errors -----------
162
163 // Catch 404 and forward to error handler
164 app.use(function (req, res, next) {
165   const err = new Error('Not Found')
166   err['status'] = 404
167   next(err)
168 })
169
170 app.use(function (err, req, res, next) {
171   let error = 'Unknown error.'
172   if (err) {
173     error = err.stack || err.message || err
174   }
175
176   // Sequelize error
177   const sql = err.parent ? err.parent.sql : undefined
178
179   logger.error('Error in controller.', { err: error, sql })
180   return res.status(err.status || 500).end()
181 })
182
183 const server = createWebsocketServer(app)
184
185 // ----------- Run -----------
186
187 async function startApplication () {
188   const port = CONFIG.LISTEN.PORT
189   const hostname = CONFIG.LISTEN.HOSTNAME
190
191   await installApplication()
192
193   // Check activity pub urls are valid
194   checkActivityPubUrls()
195     .catch(err => {
196       logger.error('Error in ActivityPub URLs checker.', { err })
197       process.exit(-1)
198     })
199
200   // Email initialization
201   Emailer.Instance.init()
202   await Emailer.Instance.checkConnectionOrDie()
203
204   await JobQueue.Instance.init()
205
206   // Caches initializations
207   VideosPreviewCache.Instance.init(CONFIG.CACHE.PREVIEWS.SIZE, CACHE.PREVIEWS.MAX_AGE)
208   VideosCaptionCache.Instance.init(CONFIG.CACHE.VIDEO_CAPTIONS.SIZE, CACHE.VIDEO_CAPTIONS.MAX_AGE)
209
210   // Enable Schedulers
211   BadActorFollowScheduler.Instance.enable()
212   RemoveOldJobsScheduler.Instance.enable()
213   UpdateVideosScheduler.Instance.enable()
214   YoutubeDlUpdateScheduler.Instance.enable()
215   VideosRedundancyScheduler.Instance.enable()
216
217   // Redis initialization
218   Redis.Instance.init()
219
220   // Make server listening
221   server.listen(port, hostname, () => {
222     logger.info('Server listening on %s:%d', hostname, port)
223     logger.info('Web server: %s', CONFIG.WEBSERVER.URL)
224   })
225
226   process.on('exit', () => {
227     JobQueue.Instance.terminate()
228   })
229
230   process.on('SIGINT', () => process.exit(0))
231 }