Update webpack stack
[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 barels 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 } from './server/initializers/constants'
30 // Initialize database and models
31 import { database as db } from './server/initializers/database'
32 db.init(false, 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(function (err) {
42   if (err) {
43     throw err
44   }
45 })
46
47 const errorMessage = checkConfig()
48 if (errorMessage !== null) {
49   throw new Error(errorMessage)
50 }
51
52 // ----------- PeerTube modules -----------
53 import { migrate, installApplication } from './server/initializers'
54 import { JobScheduler, activateSchedulers } from './server/lib'
55 import * as customValidators from './server/helpers/custom-validators'
56 import { apiRouter, clientsRouter, staticRouter } from './server/controllers'
57
58 // ----------- Command line -----------
59
60 // ----------- App -----------
61
62 // Enable cors for develop
63 if (isTestInstance()) {
64   app.use(cors({
65     origin: 'http://localhost:3000',
66     credentials: true
67   }))
68 }
69
70 // For the logger
71 app.use(morgan('combined', {
72   stream: { write: logger.info }
73 }))
74 // For body requests
75 app.use(bodyParser.json({ limit: '500kb' }))
76 app.use(bodyParser.urlencoded({ extended: false }))
77 // Validate some params for the API
78 app.use(expressValidator({
79   customValidators: customValidators
80 }))
81
82 // ----------- Views, routes and static files -----------
83
84 // API
85 const apiRoute = '/api/' + API_VERSION
86 app.use(apiRoute, apiRouter)
87
88 // Client files
89 app.use('/', clientsRouter)
90
91 // Static files
92 app.use('/', staticRouter)
93
94 // Always serve index client page (the client is a single page application, let it handle routing)
95 app.use('/*', function (req, res, next) {
96   res.sendFile(path.join(__dirname, '../client/dist/index.html'))
97 })
98
99 // ----------- Tracker -----------
100
101 const trackerServer = new TrackerServer({
102   http: false,
103   udp: false,
104   ws: false,
105   dht: false
106 })
107
108 trackerServer.on('error', function (err) {
109   logger.error(err)
110 })
111
112 trackerServer.on('warning', function (err) {
113   logger.error(err)
114 })
115
116 const server = http.createServer(app)
117 const wss = new WebSocketServer({ server: server, path: '/tracker/socket' })
118 wss.on('connection', function (ws) {
119   trackerServer.onWebSocketConnection(ws)
120 })
121
122 // ----------- Errors -----------
123
124 // Catch 404 and forward to error handler
125 app.use(function (req, res, next) {
126   const err = new Error('Not Found')
127   err['status'] = 404
128   next(err)
129 })
130
131 app.use(function (err, req, res, next) {
132   logger.error(err)
133   res.sendStatus(err.status || 500)
134 })
135
136 // ----------- Run -----------
137
138 function onDatabaseInitDone () {
139   const port = CONFIG.LISTEN.PORT
140     // Run the migration scripts if needed
141   migrate(function (err) {
142     if (err) throw err
143
144     installApplication(function (err) {
145       if (err) throw err
146
147       // ----------- Make the server listening -----------
148       server.listen(port, function () {
149         // Activate the communication with friends
150         activateSchedulers()
151
152         // Activate job scheduler
153         JobScheduler.Instance.activate()
154
155         logger.info('Server listening on port %d', port)
156         logger.info('Webserver: %s', CONFIG.WEBSERVER.URL)
157       })
158     })
159   })
160 }