Server: use constants to get port configuration
[oweals/peertube.git] / server.js
1 'use strict'
2
3 // ----------- Node modules -----------
4 const bodyParser = require('body-parser')
5 const cors = require('cors')
6 const express = require('express')
7 const expressValidator = require('express-validator')
8 const http = require('http')
9 const morgan = require('morgan')
10 const path = require('path')
11 const TrackerServer = require('bittorrent-tracker').Server
12 const WebSocketServer = require('ws').Server
13
14 process.title = 'peertube'
15
16 // Create our main app
17 const app = express()
18
19 // ----------- Database -----------
20 const config = require('config')
21 const constants = require('./server/initializers/constants')
22 const database = require('./server/initializers/database')
23 const logger = require('./server/helpers/logger')
24
25 database.connect()
26
27 // ----------- Checker -----------
28 const checker = require('./server/initializers/checker')
29
30 const miss = checker.checkConfig()
31 if (miss.length !== 0) {
32   throw new Error('Miss some configurations keys : ' + miss)
33 }
34
35 // ----------- PeerTube modules -----------
36 const customValidators = require('./server/helpers/custom-validators')
37 const installer = require('./server/initializers/installer')
38 const migrator = require('./server/initializers/migrator')
39 const mongoose = require('mongoose')
40 const routes = require('./server/controllers')
41 const Request = mongoose.model('Request')
42
43 // ----------- Command line -----------
44
45 // ----------- App -----------
46
47 // For the logger
48 app.use(morgan('combined', { stream: logger.stream }))
49 // For body requests
50 app.use(bodyParser.json({ limit: '500kb' }))
51 app.use(bodyParser.urlencoded({ extended: false }))
52 // Validate some params for the API
53 app.use(expressValidator({
54   customValidators: Object.assign(
55     {},
56     customValidators.misc,
57     customValidators.pods,
58     customValidators.users,
59     customValidators.videos
60   )
61 }))
62
63 // ----------- Views, routes and static files -----------
64
65 // API routes
66 const apiRoute = '/api/' + constants.API_VERSION
67 app.use(apiRoute, routes.api)
68
69 // Static files
70 app.use('/client', express.static(path.join(__dirname, '/client/dist'), { maxAge: constants.STATIC_MAX_AGE }))
71 // 404 for static files not found
72 app.use('/client/*', function (req, res, next) {
73   res.sendStatus(404)
74 })
75
76 const torrentsPhysicalPath = path.join(__dirname, config.get('storage.torrents'))
77 app.use(constants.STATIC_PATHS.TORRENTS, cors(), express.static(torrentsPhysicalPath, { maxAge: constants.STATIC_MAX_AGE }))
78
79 // Videos path for webseeding
80 const videosPhysicalPath = path.join(__dirname, config.get('storage.videos'))
81 app.use(constants.STATIC_PATHS.WEBSEED, cors(), express.static(videosPhysicalPath, { maxAge: constants.STATIC_MAX_AGE }))
82
83 // Thumbnails path for express
84 const thumbnailsPhysicalPath = path.join(__dirname, config.get('storage.thumbnails'))
85 app.use(constants.STATIC_PATHS.THUMBNAILS, express.static(thumbnailsPhysicalPath, { maxAge: constants.STATIC_MAX_AGE }))
86
87 // Client application
88 app.use('/*', function (req, res, next) {
89   res.sendFile(path.join(__dirname, 'client/dist/index.html'))
90 })
91
92 // ----------- Tracker -----------
93
94 const trackerServer = new TrackerServer({
95   http: false,
96   udp: false,
97   ws: false,
98   dht: false
99 })
100
101 trackerServer.on('error', function (err) {
102   logger.error(err)
103 })
104
105 trackerServer.on('warning', function (err) {
106   logger.error(err)
107 })
108
109 const server = http.createServer(app)
110 const wss = new WebSocketServer({server: server, path: '/tracker/socket'})
111 wss.on('connection', function (ws) {
112   trackerServer.onWebSocketConnection(ws)
113 })
114
115 // ----------- Errors -----------
116
117 // Catch 404 and forward to error handler
118 app.use(function (req, res, next) {
119   const err = new Error('Not Found')
120   err.status = 404
121   next(err)
122 })
123
124 app.use(function (err, req, res, next) {
125   logger.error(err)
126   res.sendStatus(err.status || 500)
127 })
128
129 const port = constants.CONFIG.LISTEN.PORT
130 installer.installApplication(function (err) {
131   if (err) throw err
132
133   // Run the migration scripts if needed
134   migrator.migrate(function (err) {
135     if (err) throw err
136
137     // ----------- Make the server listening -----------
138     server.listen(port, function () {
139       // Activate the pool requests
140       Request.activate()
141
142       logger.info('Server listening on port %d', port)
143       app.emit('ready')
144     })
145   })
146 })
147
148 module.exports = app