Upgrade common server dependencies
[oweals/peertube.git] / server.ts
1 import { isTestInstance } from './server/helpers/core-utils'
2
3 if (isTestInstance()) {
4   require('source-map-support').install()
5 }
6
7 // ----------- Node modules -----------
8 import * as bodyParser from 'body-parser'
9 import * as express from 'express'
10 // FIXME: cannot import express-validator
11 const expressValidator = require('express-validator')
12 import * as http from 'http'
13 import * as morgan from 'morgan'
14 import * as path from 'path'
15 import * as bittorrentTracker from 'bittorrent-tracker'
16 import * as cors from 'cors'
17 import { Server as WebSocketServer } from 'ws'
18
19 const TrackerServer = bittorrentTracker.Server
20
21 process.title = 'peertube'
22
23 // Create our main app
24 const app = express()
25
26 // ----------- Database -----------
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 // Initialize database and models
31 import { database as db } from './server/initializers/database'
32 db.init(false).then(() => onDatabaseInitDone())
33
34 // ----------- Checker -----------
35 import { checkMissedConfig, checkFFmpeg, checkConfig } from './server/initializers/checker'
36
37 const missed = checkMissedConfig()
38 if (missed.length !== 0) {
39   throw new Error('Miss some configurations keys : ' + missed)
40 }
41 checkFFmpeg()
42
43 const errorMessage = checkConfig()
44 if (errorMessage !== null) {
45   throw new Error(errorMessage)
46 }
47
48 // ----------- PeerTube modules -----------
49 import { migrate, installApplication } from './server/initializers'
50 import { JobScheduler, activateSchedulers, VideosPreviewCache } from './server/lib'
51 import * as customValidators from './server/helpers/custom-validators'
52 import { apiRouter, clientsRouter, staticRouter } from './server/controllers'
53
54 // ----------- Command line -----------
55
56 // ----------- App -----------
57
58 // Enable CORS for develop
59 if (isTestInstance()) {
60   app.use((req, res, next) => {
61     // These routes have already cors
62     if (
63       req.path.indexOf(STATIC_PATHS.TORRENTS) === -1 &&
64       req.path.indexOf(STATIC_PATHS.WEBSEED) === -1
65     ) {
66       return (cors({
67         origin: 'http://localhost:3000',
68         credentials: true
69       }))(req, res, next)
70     }
71
72     return next()
73   })
74 }
75
76 // For the logger
77 app.use(morgan('combined', {
78   stream: { write: logger.info }
79 }))
80 // For body requests
81 app.use(bodyParser.json({ limit: '500kb' }))
82 app.use(bodyParser.urlencoded({ extended: false }))
83 // Validate some params for the API
84 app.use(expressValidator({
85   customValidators: customValidators
86 }))
87
88 // ----------- Views, routes and static files -----------
89
90 // API
91 const apiRoute = '/api/' + API_VERSION
92 app.use(apiRoute, apiRouter)
93
94 // Client files
95 app.use('/', clientsRouter)
96
97 // Static files
98 app.use('/', staticRouter)
99
100 // Always serve index client page (the client is a single page application, let it handle routing)
101 app.use('/*', function (req, res, next) {
102   res.sendFile(path.join(__dirname, '../client/dist/index.html'))
103 })
104
105 // ----------- Tracker -----------
106
107 const trackerServer = new TrackerServer({
108   http: false,
109   udp: false,
110   ws: false,
111   dht: false
112 })
113
114 trackerServer.on('error', function (err) {
115   logger.error(err)
116 })
117
118 trackerServer.on('warning', function (err) {
119   logger.error(err)
120 })
121
122 const server = http.createServer(app)
123 const wss = new WebSocketServer({ server: server, path: '/tracker/socket' })
124 wss.on('connection', function (ws) {
125   trackerServer.onWebSocketConnection(ws)
126 })
127
128 // ----------- Errors -----------
129
130 // Catch 404 and forward to error handler
131 app.use(function (req, res, next) {
132   const err = new Error('Not Found')
133   err['status'] = 404
134   next(err)
135 })
136
137 app.use(function (err, req, res, next) {
138   logger.error(err)
139   res.sendStatus(err.status || 500)
140 })
141
142 // ----------- Run -----------
143
144 function onDatabaseInitDone () {
145   const port = CONFIG.LISTEN.PORT
146     // Run the migration scripts if needed
147   migrate()
148     .then(() => {
149       return installApplication()
150     })
151     .then(() => {
152       // ----------- Make the server listening -----------
153       server.listen(port, function () {
154         // Activate the communication with friends
155         activateSchedulers()
156
157         // Activate job scheduler
158         JobScheduler.Instance.activate()
159
160         VideosPreviewCache.Instance.init(CONFIG.CACHE.PREVIEWS.SIZE)
161
162         logger.info('Server listening on port %d', port)
163         logger.info('Web server: %s', CONFIG.WEBSERVER.URL)
164       })
165     })
166 }