Fix upgrade script \n
[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 } 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(cors({
61     origin: 'http://localhost:3000',
62     credentials: true
63   }))
64 }
65
66 // For the logger
67 app.use(morgan('combined', {
68   stream: { write: logger.info }
69 }))
70 // For body requests
71 app.use(bodyParser.json({ limit: '500kb' }))
72 app.use(bodyParser.urlencoded({ extended: false }))
73 // Validate some params for the API
74 app.use(expressValidator({
75   customValidators: customValidators
76 }))
77
78 // ----------- Views, routes and static files -----------
79
80 // API
81 const apiRoute = '/api/' + API_VERSION
82 app.use(apiRoute, apiRouter)
83
84 // Client files
85 app.use('/', clientsRouter)
86
87 // Static files
88 app.use('/', staticRouter)
89
90 // Always serve index client page (the client is a single page application, let it handle routing)
91 app.use('/*', function (req, res, next) {
92   res.sendFile(path.join(__dirname, '../client/dist/index.html'))
93 })
94
95 // ----------- Tracker -----------
96
97 const trackerServer = new TrackerServer({
98   http: false,
99   udp: false,
100   ws: false,
101   dht: false
102 })
103
104 trackerServer.on('error', function (err) {
105   logger.error(err)
106 })
107
108 trackerServer.on('warning', function (err) {
109   logger.error(err)
110 })
111
112 const server = http.createServer(app)
113 const wss = new WebSocketServer({ server: server, path: '/tracker/socket' })
114 wss.on('connection', function (ws) {
115   trackerServer.onWebSocketConnection(ws)
116 })
117
118 // ----------- Errors -----------
119
120 // Catch 404 and forward to error handler
121 app.use(function (req, res, next) {
122   const err = new Error('Not Found')
123   err['status'] = 404
124   next(err)
125 })
126
127 app.use(function (err, req, res, next) {
128   logger.error(err)
129   res.sendStatus(err.status || 500)
130 })
131
132 // ----------- Run -----------
133
134 function onDatabaseInitDone () {
135   const port = CONFIG.LISTEN.PORT
136     // Run the migration scripts if needed
137   migrate()
138     .then(() => {
139       return installApplication()
140     })
141     .then(() => {
142       // ----------- Make the server listening -----------
143       server.listen(port, function () {
144         // Activate the communication with friends
145         activateSchedulers()
146
147         // Activate job scheduler
148         JobScheduler.Instance.activate()
149
150         VideosPreviewCache.Instance.init(CONFIG.CACHE.PREVIEWS.SIZE)
151
152         logger.info('Server listening on port %d', port)
153         logger.info('Webserver: %s', CONFIG.WEBSERVER.URL)
154       })
155     })
156 }