]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server.ts
Upgrade common server dependencies
[github/Chocobozzz/PeerTube.git] / server.ts
CommitLineData
1840c2f7
C
1import { isTestInstance } from './server/helpers/core-utils'
2
3if (isTestInstance()) {
e02643f3
C
4 require('source-map-support').install()
5}
6
a030a9b2 7// ----------- Node modules -----------
4d4e5cd4
C
8import * as bodyParser from 'body-parser'
9import * as express from 'express'
10// FIXME: cannot import express-validator
13ce1d01 11const expressValidator = require('express-validator')
4d4e5cd4
C
12import * as http from 'http'
13import * as morgan from 'morgan'
14import * as path from 'path'
15import * as bittorrentTracker from 'bittorrent-tracker'
1840c2f7 16import * as cors from 'cors'
65fcc311
C
17import { Server as WebSocketServer } from 'ws'
18
19const TrackerServer = bittorrentTracker.Server
a030a9b2 20
9f540774
C
21process.title = 'peertube'
22
a030a9b2 23// Create our main app
13ce1d01 24const app = express()
a030a9b2 25
00057e85 26// ----------- Database -----------
407c4473 27// Do not use barrels because we don't want to load all modules here (we need to initialize database first)
65fcc311 28import { logger } from './server/helpers/logger'
93e1258c 29import { API_VERSION, CONFIG, STATIC_PATHS } from './server/initializers/constants'
feb4bdfd 30// Initialize database and models
e02643f3 31import { database as db } from './server/initializers/database'
6fcd19ba 32db.init(false).then(() => onDatabaseInitDone())
00057e85 33
69b0a27c 34// ----------- Checker -----------
65fcc311 35import { checkMissedConfig, checkFFmpeg, checkConfig } from './server/initializers/checker'
69b0a27c 36
65fcc311 37const missed = checkMissedConfig()
b65c27aa
C
38if (missed.length !== 0) {
39 throw new Error('Miss some configurations keys : ' + missed)
40}
6fcd19ba 41checkFFmpeg()
b65c27aa 42
65fcc311 43const errorMessage = checkConfig()
b65c27aa
C
44if (errorMessage !== null) {
45 throw new Error(errorMessage)
69b0a27c
C
46}
47
00057e85 48// ----------- PeerTube modules -----------
65fcc311 49import { migrate, installApplication } from './server/initializers'
f981dae8 50import { JobScheduler, activateSchedulers, VideosPreviewCache } from './server/lib'
65fcc311
C
51import * as customValidators from './server/helpers/custom-validators'
52import { apiRouter, clientsRouter, staticRouter } from './server/controllers'
a030a9b2 53
a030a9b2
C
54// ----------- Command line -----------
55
56// ----------- App -----------
57
407c4473 58// Enable CORS for develop
1840c2f7 59if (isTestInstance()) {
93e1258c
C
60 app.use((req, res, next) => {
61 // These routes have already cors
62 if (
63 req.path.indexOf(STATIC_PATHS.TORRENTS) === -1 &&
64 req.path.indexOf(STATIC_PATHS.WEBSEED) === -1
65 ) {
66 return (cors({
67 origin: 'http://localhost:3000',
68 credentials: true
69 }))(req, res, next)
70 }
71
72 return next()
73 })
1840c2f7
C
74}
75
a030a9b2 76// For the logger
e02643f3
C
77app.use(morgan('combined', {
78 stream: { write: logger.info }
79}))
a030a9b2 80// For body requests
def16d33 81app.use(bodyParser.json({ limit: '500kb' }))
a030a9b2
C
82app.use(bodyParser.urlencoded({ extended: false }))
83// Validate some params for the API
84app.use(expressValidator({
65fcc311 85 customValidators: customValidators
a030a9b2
C
86}))
87
88// ----------- Views, routes and static files -----------
89
79530164 90// API
65fcc311
C
91const apiRoute = '/api/' + API_VERSION
92app.use(apiRoute, apiRouter)
052937db 93
79530164 94// Client files
65fcc311 95app.use('/', clientsRouter)
cbe2f7c3 96
79530164 97// Static files
65fcc311 98app.use('/', staticRouter)
6a94a109 99
79530164 100// Always serve index client page (the client is a single page application, let it handle routing)
6f4e2522 101app.use('/*', function (req, res, next) {
e02643f3 102 res.sendFile(path.join(__dirname, '../client/dist/index.html'))
6f4e2522 103})
a030a9b2
C
104
105// ----------- Tracker -----------
106
13ce1d01 107const trackerServer = new TrackerServer({
a030a9b2
C
108 http: false,
109 udp: false,
110 ws: false,
111 dht: false
112})
113
114trackerServer.on('error', function (err) {
115 logger.error(err)
116})
117
118trackerServer.on('warning', function (err) {
119 logger.error(err)
120})
121
13ce1d01 122const server = http.createServer(app)
65fcc311 123const wss = new WebSocketServer({ server: server, path: '/tracker/socket' })
a030a9b2
C
124wss.on('connection', function (ws) {
125 trackerServer.onWebSocketConnection(ws)
126})
127
128// ----------- Errors -----------
129
130// Catch 404 and forward to error handler
131app.use(function (req, res, next) {
13ce1d01 132 const err = new Error('Not Found')
65fcc311 133 err['status'] = 404
a030a9b2
C
134 next(err)
135})
136
6f4e2522
C
137app.use(function (err, req, res, next) {
138 logger.error(err)
139 res.sendStatus(err.status || 500)
140})
a030a9b2 141
79530164
C
142// ----------- Run -----------
143
5804c0db 144function onDatabaseInitDone () {
65fcc311 145 const port = CONFIG.LISTEN.PORT
5804c0db 146 // Run the migration scripts if needed
6fcd19ba
C
147 migrate()
148 .then(() => {
149 return installApplication()
150 })
151 .then(() => {
5804c0db
C
152 // ----------- Make the server listening -----------
153 server.listen(port, function () {
154 // Activate the communication with friends
65fcc311 155 activateSchedulers()
052937db 156
227d02fe 157 // Activate job scheduler
65fcc311 158 JobScheduler.Instance.activate()
227d02fe 159
f981dae8
C
160 VideosPreviewCache.Instance.init(CONFIG.CACHE.PREVIEWS.SIZE)
161
5804c0db 162 logger.info('Server listening on port %d', port)
556ddc31 163 logger.info('Web server: %s', CONFIG.WEBSERVER.URL)
5804c0db 164 })
8c308c2b 165 })
5804c0db 166}