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