]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame_incremental - server.ts
Remove "function" in favor of () => {}
[github/Chocobozzz/PeerTube.git] / server.ts
... / ...
CommitLineData
1import { isTestInstance } from './server/helpers/core-utils'
2
3if (isTestInstance()) {
4 require('source-map-support').install()
5}
6
7// ----------- Node modules -----------
8import * as bodyParser from 'body-parser'
9import * as express from 'express'
10// FIXME: cannot import express-validator
11const expressValidator = require('express-validator')
12import * as http from 'http'
13import * as morgan from 'morgan'
14import * as path from 'path'
15import * as bittorrentTracker from 'bittorrent-tracker'
16import * as cors from 'cors'
17import { Server as WebSocketServer } from 'ws'
18
19const TrackerServer = bittorrentTracker.Server
20
21process.title = 'peertube'
22
23// Create our main app
24const 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)
28import { logger } from './server/helpers/logger'
29import { API_VERSION, CONFIG } from './server/initializers/constants'
30// Initialize database and models
31import { database as db } from './server/initializers/database'
32db.init(false).then(() => onDatabaseInitDone())
33
34// ----------- Checker -----------
35import { checkMissedConfig, checkFFmpeg, checkConfig } from './server/initializers/checker'
36
37const missed = checkMissedConfig()
38if (missed.length !== 0) {
39 throw new Error('Miss some configurations keys : ' + missed)
40}
41checkFFmpeg()
42
43const errorMessage = checkConfig()
44if (errorMessage !== null) {
45 throw new Error(errorMessage)
46}
47
48// ----------- PeerTube modules -----------
49import { migrate, installApplication } from './server/initializers'
50import { JobScheduler, activateSchedulers } from './server/lib'
51import * as customValidators from './server/helpers/custom-validators'
52import { apiRouter, clientsRouter, staticRouter } from './server/controllers'
53
54// ----------- Command line -----------
55
56// ----------- App -----------
57
58// Enable cors for develop
59if (isTestInstance()) {
60 app.use(cors({
61 origin: 'http://localhost:3000',
62 credentials: true
63 }))
64}
65
66// For the logger
67app.use(morgan('combined', {
68 stream: { write: logger.info }
69}))
70// For body requests
71app.use(bodyParser.json({ limit: '500kb' }))
72app.use(bodyParser.urlencoded({ extended: false }))
73// Validate some params for the API
74app.use(expressValidator({
75 customValidators: customValidators
76}))
77
78// ----------- Views, routes and static files -----------
79
80// API
81const apiRoute = '/api/' + API_VERSION
82app.use(apiRoute, apiRouter)
83
84// Client files
85app.use('/', clientsRouter)
86
87// Static files
88app.use('/', staticRouter)
89
90// Always serve index client page (the client is a single page application, let it handle routing)
91app.use('/*', function (req, res, next) {
92 res.sendFile(path.join(__dirname, '../client/dist/index.html'))
93})
94
95// ----------- Tracker -----------
96
97const trackerServer = new TrackerServer({
98 http: false,
99 udp: false,
100 ws: false,
101 dht: false
102})
103
104trackerServer.on('error', function (err) {
105 logger.error(err)
106})
107
108trackerServer.on('warning', function (err) {
109 logger.error(err)
110})
111
112const server = http.createServer(app)
113const wss = new WebSocketServer({ server: server, path: '/tracker/socket' })
114wss.on('connection', function (ws) {
115 trackerServer.onWebSocketConnection(ws)
116})
117
118// ----------- Errors -----------
119
120// Catch 404 and forward to error handler
121app.use(function (req, res, next) {
122 const err = new Error('Not Found')
123 err['status'] = 404
124 next(err)
125})
126
127app.use(function (err, req, res, next) {
128 logger.error(err)
129 res.sendStatus(err.status || 500)
130})
131
132// ----------- Run -----------
133
134function 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 logger.info('Server listening on port %d', port)
151 logger.info('Webserver: %s', CONFIG.WEBSERVER.URL)
152 })
153 })
154}