Type models
[oweals/peertube.git] / server.ts
1 if ([ 'dev', 'test'].indexOf(process.env.NODE_ENV) !== -1) {
2   require('source-map-support').install()
3 }
4
5 // ----------- Node modules -----------
6 import bodyParser = require('body-parser')
7 import express = require('express')
8 const expressValidator = require('express-validator')
9 import http = require('http')
10 import morgan = require('morgan')
11 import path = require('path')
12 import bittorrentTracker = require('bittorrent-tracker')
13 import { Server as WebSocketServer } from 'ws'
14
15 const TrackerServer = bittorrentTracker.Server
16
17 process.title = 'peertube'
18
19 // Create our main app
20 const app = express()
21
22 // ----------- Database -----------
23 // Do not use barels because we don't want to load all modules here (we need to initialize database first)
24 import { logger } from './server/helpers/logger'
25 import { API_VERSION, CONFIG } from './server/initializers/constants'
26 // Initialize database and models
27 import { database as db } from './server/initializers/database'
28 db.init(false, onDatabaseInitDone)
29
30 // ----------- Checker -----------
31 import { checkMissedConfig, checkFFmpeg, checkConfig } from './server/initializers/checker'
32
33 const missed = checkMissedConfig()
34 if (missed.length !== 0) {
35   throw new Error('Miss some configurations keys : ' + missed)
36 }
37 checkFFmpeg(function (err) {
38   if (err) {
39     throw err
40   }
41 })
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 } 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 // For the logger
59 app.use(morgan('combined', {
60   stream: { write: logger.info }
61 }))
62 // For body requests
63 app.use(bodyParser.json({ limit: '500kb' }))
64 app.use(bodyParser.urlencoded({ extended: false }))
65 // Validate some params for the API
66 app.use(expressValidator({
67   customValidators: customValidators
68 }))
69
70 // ----------- Views, routes and static files -----------
71
72 // API
73 const apiRoute = '/api/' + API_VERSION
74 app.use(apiRoute, apiRouter)
75
76 // Client files
77 app.use('/', clientsRouter)
78
79 // Static files
80 app.use('/', staticRouter)
81
82 // Always serve index client page (the client is a single page application, let it handle routing)
83 app.use('/*', function (req, res, next) {
84   res.sendFile(path.join(__dirname, '../client/dist/index.html'))
85 })
86
87 // ----------- Tracker -----------
88
89 const trackerServer = new TrackerServer({
90   http: false,
91   udp: false,
92   ws: false,
93   dht: false
94 })
95
96 trackerServer.on('error', function (err) {
97   logger.error(err)
98 })
99
100 trackerServer.on('warning', function (err) {
101   logger.error(err)
102 })
103
104 const server = http.createServer(app)
105 const wss = new WebSocketServer({ server: server, path: '/tracker/socket' })
106 wss.on('connection', function (ws) {
107   trackerServer.onWebSocketConnection(ws)
108 })
109
110 // ----------- Errors -----------
111
112 // Catch 404 and forward to error handler
113 app.use(function (req, res, next) {
114   const err = new Error('Not Found')
115   err['status'] = 404
116   next(err)
117 })
118
119 app.use(function (err, req, res, next) {
120   logger.error(err)
121   res.sendStatus(err.status || 500)
122 })
123
124 // ----------- Run -----------
125
126 function onDatabaseInitDone () {
127   const port = CONFIG.LISTEN.PORT
128     // Run the migration scripts if needed
129   migrate(function (err) {
130     if (err) throw err
131
132     installApplication(function (err) {
133       if (err) throw err
134
135       // ----------- Make the server listening -----------
136       server.listen(port, function () {
137         // Activate the communication with friends
138         activateSchedulers()
139
140         // Activate job scheduler
141         JobScheduler.Instance.activate()
142
143         logger.info('Server listening on port %d', port)
144         logger.info('Webserver: %s', CONFIG.WEBSERVER.URL)
145       })
146     })
147   })
148 }